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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
49f1a252884e9f7cd9899ab1e2c72434a738518b | e0f9ba56b7fedc16ef8697f6caeef5898b435143 | /src/topology/algebra/infinite_sum.lean | 64bb20c078f52259f14156809bf6ad04c6093d97 | [
"Apache-2.0"
] | permissive | anrddh/mathlib | 6a374da53c7e3a35cb0298b0cd67824efef362b4 | a4266a01d2dcb10de19369307c986d038c7bb6a6 | refs/heads/master | 1,656,710,827,909 | 1,589,560,456,000 | 1,589,560,456,000 | 264,271,800 | 0 | 0 | Apache-2.0 | 1,589,568,062,000 | 1,589,568,061,000 | null | UTF-8 | Lean | false | false | 35,445 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
Infinite sum over a topological monoid
This sum is known as unconditionally convergent, as it sums to the same value under all possible
permutations. For Euclidean spaces (finite dimensional Banach spaces) this is equivalent to absolute
convergence.
Note: There are summable sequences which are not unconditionally convergent! The other way holds
generally, see `has_sum.tendsto_sum_nat`.
Reference:
* Bourbaki: General Topology (1995), Chapter 3 §5 (Infinite sums in commutative groups)
-/
import topology.instances.real
noncomputable theory
open finset filter function classical
open_locale topological_space classical big_operators
variables {α : Type*} {β : Type*} {γ : Type*}
section has_sum
variables [add_comm_monoid α] [topological_space α]
/-- Infinite sum on a topological monoid
The `at_top` filter on `finset α` is the limit of all finite sets towards the entire type. So we sum
up bigger and bigger sets. This sum operation is still invariant under reordering, and a absolute
sum operator.
This is based on Mario Carneiro's infinite sum in Metamath.
For the definition or many statements, α does not need to be a topological monoid. We only add
this assumption later, for the lemmas where it is relevant.
-/
def has_sum (f : β → α) (a : α) : Prop := tendsto (λs:finset β, s.sum f) at_top (𝓝 a)
/-- `summable f` means that `f` has some (infinite) sum. Use `tsum` to get the value. -/
def summable (f : β → α) : Prop := ∃a, has_sum f a
/-- `tsum f` is the sum of `f` it exists, or 0 otherwise -/
def tsum (f : β → α) := if h : summable f then classical.some h else 0
notation `∑'` binders `, ` r:(scoped f, tsum f) := r
variables {f g : β → α} {a b : α} {s : finset β}
lemma summable.has_sum (ha : summable f) : has_sum f (∑'b, f b) :=
by simp [ha, tsum]; exact some_spec ha
lemma has_sum.summable (h : has_sum f a) : summable f := ⟨a, h⟩
/-- Constant zero function has sum `0` -/
lemma has_sum_zero : has_sum (λb, 0 : β → α) 0 :=
by simp [has_sum, tendsto_const_nhds]
lemma summable_zero : summable (λb, 0 : β → α) := has_sum_zero.summable
lemma tsum_eq_zero_of_not_summable (h : ¬ summable f) : (∑'b, f b) = 0 :=
by simp [tsum, h]
/-- If a function `f` vanishes outside of a finite set `s`, then it `has_sum` `s.sum f`. -/
lemma has_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : has_sum f (s.sum f) :=
tendsto_infi' s $ tendsto.congr'
(assume t (ht : s ⊆ t), show s.sum f = t.sum f, from sum_subset ht $ assume x _, hf _)
tendsto_const_nhds
lemma has_sum_fintype [fintype β] (f : β → α) : has_sum f (finset.univ.sum f) :=
has_sum_sum_of_ne_finset_zero $ λ a h, h.elim (mem_univ _)
lemma summable_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : summable f :=
(has_sum_sum_of_ne_finset_zero hf).summable
lemma has_sum_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) :
has_sum f (f b) :=
suffices has_sum f (({b} : finset β).sum f),
by simpa using this,
has_sum_sum_of_ne_finset_zero $ by simpa [hf]
lemma has_sum_ite_eq (b : β) (a : α) : has_sum (λb', if b' = b then a else 0) a :=
begin
convert has_sum_single b _,
{ exact (if_pos rfl).symm },
assume b' hb',
exact if_neg hb'
end
lemma has_sum_of_iso {j : γ → β} {i : β → γ}
(hf : has_sum f a) (h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) : has_sum (f ∘ j) a :=
have ∀x y, j x = j y → x = y,
from assume x y h,
have i (j x) = i (j y), by rw [h],
by rwa [h₁, h₁] at this,
have (λs:finset γ, s.sum (f ∘ j)) = (λs:finset β, s.sum f) ∘ (λs:finset γ, s.image j),
from funext $ assume s, (sum_image $ assume x _ y _, this x y).symm,
show tendsto (λs:finset γ, s.sum (f ∘ j)) at_top (𝓝 a),
by rw [this]; apply hf.comp (tendsto_finset_image_at_top_at_top h₂)
lemma has_sum_iff_has_sum_of_iso {j : γ → β} (i : β → γ)
(h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) :
has_sum (f ∘ j) a ↔ has_sum f a :=
iff.intro
(assume hfj,
have has_sum ((f ∘ j) ∘ i) a, from has_sum_of_iso hfj h₂ h₁,
by simp [(∘), h₂] at this; assumption)
(assume hf, has_sum_of_iso hf h₁ h₂)
lemma equiv.has_sum_iff (e : γ ≃ β) :
has_sum (f ∘ e) a ↔ has_sum f a :=
has_sum_iff_has_sum_of_iso e.symm e.left_inv e.right_inv
lemma equiv.summable_iff (e : γ ≃ β) :
summable (f ∘ e) ↔ summable f :=
⟨λ H, (e.has_sum_iff.1 H.has_sum).summable, λ H, (e.has_sum_iff.2 H.has_sum).summable⟩
lemma has_sum_hom (g : α → γ) [add_comm_monoid γ] [topological_space γ]
[is_add_monoid_hom g] (h₃ : continuous g) (hf : has_sum f a) :
has_sum (g ∘ f) (g a) :=
have (λs:finset β, s.sum (g ∘ f)) = g ∘ (λs:finset β, s.sum f),
from funext $ assume s, s.sum_hom g,
show tendsto (λs:finset β, s.sum (g ∘ f)) at_top (𝓝 (g a)),
by rw [this]; exact tendsto.comp (continuous_iff_continuous_at.mp h₃ a) hf
/-- If `f : ℕ → α` has sum `a`, then the partial sums `∑_{i=0}^{n-1} f i` converge to `a`. -/
lemma has_sum.tendsto_sum_nat {f : ℕ → α} (h : has_sum f a) :
tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) :=
@tendsto.comp _ _ _ finset.range (λ s : finset ℕ, s.sum f) _ _ _ h tendsto_finset_range
lemma has_sum_unique {a₁ a₂ : α} [t2_space α] : has_sum f a₁ → has_sum f a₂ → a₁ = a₂ :=
tendsto_nhds_unique at_top_ne_bot
lemma has_sum_iff_tendsto_nat_of_summable [t2_space α] {f : ℕ → α} {a : α} (hf : summable f) :
has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) :=
begin
refine ⟨λ h, h.tendsto_sum_nat, λ h, _⟩,
rw tendsto_nhds_unique at_top_ne_bot h hf.has_sum.tendsto_sum_nat,
exact hf.has_sum
end
variable [topological_add_monoid α]
lemma has_sum.add (hf : has_sum f a) (hg : has_sum g b) : has_sum (λb, f b + g b) (a + b) :=
by simp [has_sum, sum_add_distrib]; exact hf.add hg
lemma summable.add (hf : summable f) (hg : summable g) : summable (λb, f b + g b) :=
(hf.has_sum.add hg.has_sum).summable
lemma has_sum_sum {f : γ → β → α} {a : γ → α} {s : finset γ} :
(∀i∈s, has_sum (f i) (a i)) → has_sum (λb, s.sum $ λi, f i b) (s.sum a) :=
finset.induction_on s (by simp [has_sum_zero]) (by simp [has_sum.add] {contextual := tt})
lemma summable_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) :
summable (λb, s.sum $ λi, f i b) :=
(has_sum_sum $ assume i hi, (hf i hi).has_sum).summable
lemma has_sum.sigma [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α}
(ha : has_sum f a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) : has_sum g a :=
assume s' hs',
let
⟨s, hs, hss', hsc⟩ := nhds_is_closed hs',
⟨u, hu⟩ := mem_at_top_sets.mp $ ha hs,
fsts := u.image sigma.fst,
snds := λb, u.bind (λp, (if h : p.1 = b then {cast (congr_arg γ h) p.2} else ∅ : finset (γ b)))
in
have u_subset : u ⊆ fsts.sigma snds,
from subset_iff.mpr $ assume ⟨b, c⟩ hu,
have hb : b ∈ fsts, from finset.mem_image.mpr ⟨_, hu, rfl⟩,
have hc : c ∈ snds b, from mem_bind.mpr ⟨_, hu, by simp; refl⟩,
by simp [mem_sigma, hb, hc] ,
mem_at_top_sets.mpr $ exists.intro fsts $ assume bs (hbs : fsts ⊆ bs),
have h : ∀cs : Π b ∈ bs, finset (γ b),
((⋂b (hb : b ∈ bs), (λp:Πb, finset (γ b), p b) ⁻¹' {cs' | cs b hb ⊆ cs' }) ∩
(λp, bs.sum (λb, (p b).sum (λc, f ⟨b, c⟩))) ⁻¹' s).nonempty,
from assume cs,
let cs' := λb, (if h : b ∈ bs then cs b h else ∅) ∪ snds b in
have sum_eq : bs.sum (λb, (cs' b).sum (λc, f ⟨b, c⟩)) = (bs.sigma cs').sum f,
from sum_sigma.symm,
have (bs.sigma cs').sum f ∈ s,
from hu _ $ finset.subset.trans u_subset $ sigma_mono hbs $
assume b, @finset.subset_union_right (γ b) _ _ _,
exists.intro cs' $
by simp [sum_eq, this]; { intros b hb, simp [cs', hb, finset.subset_union_left] },
have tendsto (λp:(Πb:β, finset (γ b)), bs.sum (λb, (p b).sum (λc, f ⟨b, c⟩)))
(⨅b (h : b ∈ bs), at_top.comap (λp, p b)) (𝓝 (bs.sum g)),
from tendsto_finset_sum bs $
assume c hc, tendsto_infi' c $ tendsto_infi' hc $ by apply tendsto.comp (hf c) tendsto_comap,
have bs.sum g ∈ s,
from mem_of_closed_of_tendsto' this hsc $ forall_sets_nonempty_iff_ne_bot.mp $
begin
simp only [mem_inf_sets, exists_imp_distrib, forall_and_distrib, and_imp,
filter.mem_infi_sets_finset, mem_comap_sets, mem_at_top_sets, and_comm,
mem_principal_sets, set.preimage_subset_iff, exists_prop, skolem],
intros s₁ s₂ s₃ hs₁ hs₃ p hs₂ p' hp cs hp',
have : (⋂b (h : b ∈ bs), (λp:(Πb, finset (γ b)), p b) ⁻¹' {cs' | cs b h ⊆ cs' }) ≤ (⨅b∈bs, p b),
from (infi_le_infi $ assume b, infi_le_infi $ assume hb,
le_trans (set.preimage_mono $ hp' b hb) (hp b hb)),
exact (h _).mono (set.subset.trans (set.inter_subset_inter (le_trans this hs₂) hs₃) hs₁)
end,
hss' this
lemma summable.sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α}
(ha : summable f) (hf : ∀b, summable (λc, f ⟨b, c⟩)) : summable (λb, ∑'c, f ⟨b, c⟩) :=
(ha.has_sum.sigma (assume b, (hf b).has_sum)).summable
lemma has_sum.sigma_of_has_sum [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α}
(ha : has_sum g a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) (hf' : summable f) : has_sum f a :=
by simpa [has_sum_unique (hf'.has_sum.sigma hf) ha] using hf'.has_sum
end has_sum
section has_sum_iff_has_sum_of_iso_ne_zero
variables [add_comm_monoid α] [topological_space α]
variables {f : β → α} {g : γ → α} {a : α}
lemma has_sum.has_sum_of_sum_eq
(h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ u'.sum g = v'.sum f)
(hf : has_sum g a) : has_sum f a :=
suffices at_top.map (λs:finset β, s.sum f) ≤ at_top.map (λs:finset γ, s.sum g),
from le_trans this hf,
by rw [map_at_top_eq, map_at_top_eq];
from (le_infi $ assume b, let ⟨v, hv⟩ := h_eq b in infi_le_of_le v $
by simp [set.image_subset_iff]; exact hv)
lemma has_sum_iff_has_sum
(h₁ : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ u'.sum g = v'.sum f)
(h₂ : ∀v:finset β, ∃u:finset γ, ∀u', u ⊆ u' → ∃v', v ⊆ v' ∧ v'.sum f = u'.sum g) :
has_sum f a ↔ has_sum g a :=
⟨has_sum.has_sum_of_sum_eq h₂, has_sum.has_sum_of_sum_eq h₁⟩
variables
(i : Π⦃c⦄, g c ≠ 0 → β) (hi : ∀⦃c⦄ (h : g c ≠ 0), f (i h) ≠ 0)
(j : Π⦃b⦄, f b ≠ 0 → γ) (hj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) ≠ 0)
(hji : ∀⦃c⦄ (h : g c ≠ 0), j (hi h) = c)
(hij : ∀⦃b⦄ (h : f b ≠ 0), i (hj h) = b)
(hgj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) = f b)
include hi hj hji hij hgj
-- FIXME this causes a deterministic timeout with `-T50000`
lemma has_sum.has_sum_ne_zero : has_sum g a → has_sum f a :=
have j_inj : ∀x y (hx : f x ≠ 0) (hy : f y ≠ 0), (j hx = j hy ↔ x = y),
from assume x y hx hy,
⟨assume h,
have i (hj hx) = i (hj hy), by simp [h],
by rwa [hij, hij] at this; assumption,
by simp {contextual := tt}⟩,
let ii : finset γ → finset β := λu, u.bind $ λc, if h : g c = 0 then ∅ else {i h} in
let jj : finset β → finset γ := λv, v.bind $ λb, if h : f b = 0 then ∅ else {j h} in
has_sum.has_sum_of_sum_eq $ assume u, exists.intro (ii u) $
assume v hv, exists.intro (u ∪ jj v) $ and.intro (subset_union_left _ _) $
have ∀c:γ, c ∈ u ∪ jj v → c ∉ jj v → g c = 0,
from assume c hc hnc, classical.by_contradiction $ assume h : g c ≠ 0,
have c ∈ u,
from (finset.mem_union.1 hc).resolve_right hnc,
have i h ∈ v,
from hv $ by simp [mem_bind]; existsi c; simp [h, this],
have j (hi h) ∈ jj v,
by simp [mem_bind]; existsi i h; simp [h, hi, this],
by rw [hji h] at this; exact hnc this,
calc (u ∪ jj v).sum g = (jj v).sum g : (sum_subset (subset_union_right _ _) this).symm
... = v.sum _ : sum_bind $ by intros x _ y _ _; by_cases f x = 0; by_cases f y = 0; simp [*]; cc
... = v.sum f : sum_congr rfl $ by intros x hx; by_cases f x = 0; simp [*]
lemma has_sum_iff_has_sum_of_ne_zero : has_sum f a ↔ has_sum g a :=
iff.intro
(has_sum.has_sum_ne_zero j hj i hi hij hji $ assume b hb, by rw [←hgj (hi _), hji])
(has_sum.has_sum_ne_zero i hi j hj hji hij hgj)
lemma summable_iff_summable_ne_zero : summable g ↔ summable f :=
exists_congr $
assume a, has_sum_iff_has_sum_of_ne_zero j hj i hi hij hji $
assume b hb, by rw [←hgj (hi _), hji]
end has_sum_iff_has_sum_of_iso_ne_zero
section has_sum_iff_has_sum_of_bij_ne_zero
variables [add_comm_monoid α] [topological_space α]
variables {f : β → α} {g : γ → α} {a : α}
(i : Π⦃c⦄, g c ≠ 0 → β)
(h₁ : ∀⦃c₁ c₂⦄ (h₁ : g c₁ ≠ 0) (h₂ : g c₂ ≠ 0), i h₁ = i h₂ → c₁ = c₂)
(h₂ : ∀⦃b⦄, f b ≠ 0 → ∃c (h : g c ≠ 0), i h = b)
(h₃ : ∀⦃c⦄ (h : g c ≠ 0), f (i h) = g c)
include i h₁ h₂ h₃
lemma has_sum_iff_has_sum_of_ne_zero_bij : has_sum f a ↔ has_sum g a :=
have hi : ∀⦃c⦄ (h : g c ≠ 0), f (i h) ≠ 0,
from assume c h, by simp [h₃, h],
let j : Π⦃b⦄, f b ≠ 0 → γ := λb h, some $ h₂ h in
have hj : ∀⦃b⦄ (h : f b ≠ 0), ∃(h : g (j h) ≠ 0), i h = b,
from assume b h, some_spec $ h₂ h,
have hj₁ : ∀⦃b⦄ (h : f b ≠ 0), g (j h) ≠ 0,
from assume b h, let ⟨h₁, _⟩ := hj h in h₁,
have hj₂ : ∀⦃b⦄ (h : f b ≠ 0), i (hj₁ h) = b,
from assume b h, let ⟨h₁, h₂⟩ := hj h in h₂,
has_sum_iff_has_sum_of_ne_zero i hi j hj₁
(assume c h, h₁ (hj₁ _) h $ hj₂ _) hj₂ (assume b h, by rw [←h₃ (hj₁ _), hj₂])
lemma summable_iff_summable_ne_zero_bij : summable f ↔ summable g :=
exists_congr $
assume a, has_sum_iff_has_sum_of_ne_zero_bij @i h₁ h₂ h₃
end has_sum_iff_has_sum_of_bij_ne_zero
section subtype
variables [add_comm_monoid α] [topological_space α] {s : finset β} {f : β → α} {a : α}
lemma has_sum_subtype_iff_of_eq_zero (h : ∀ x ∈ s, f x = 0) :
has_sum (λ b : {b // b ∉ s}, f b) a ↔ has_sum f a :=
begin
symmetry,
apply has_sum_iff_has_sum_of_ne_zero_bij (λ (b : {b // b ∉ s}) hb, (b : β)),
{ exact λ c₁ c₂ h₁ h₂ H, subtype.eq H },
{ assume b hb,
have : b ∉ s := λ H, hb (h b H),
exact ⟨⟨b, this⟩, hb, rfl⟩ },
{ dsimp, simp }
end
end subtype
section tsum
variables [add_comm_monoid α] [topological_space α] [t2_space α]
variables {f g : β → α} {a a₁ a₂ : α}
lemma tsum_eq_has_sum (ha : has_sum f a) : (∑'b, f b) = a :=
has_sum_unique (summable.has_sum ⟨a, ha⟩) ha
lemma summable.has_sum_iff (h : summable f) : has_sum f a ↔ (∑'b, f b) = a :=
iff.intro tsum_eq_has_sum (assume eq, eq ▸ h.has_sum)
@[simp] lemma tsum_zero : (∑'b:β, 0:α) = 0 := tsum_eq_has_sum has_sum_zero
lemma tsum_eq_sum {f : β → α} {s : finset β} (hf : ∀b∉s, f b = 0) :
(∑'b, f b) = s.sum f :=
tsum_eq_has_sum $ has_sum_sum_of_ne_finset_zero hf
lemma tsum_fintype [fintype β] (f : β → α) : (∑'b, f b) = finset.univ.sum f :=
tsum_eq_has_sum $ has_sum_fintype f
lemma tsum_eq_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) :
(∑'b, f b) = f b :=
tsum_eq_has_sum $ has_sum_single b hf
@[simp] lemma tsum_ite_eq (b : β) (a : α) : (∑'b', if b' = b then a else 0) = a :=
tsum_eq_has_sum (has_sum_ite_eq b a)
lemma tsum_eq_tsum_of_has_sum_iff_has_sum {f : β → α} {g : γ → α}
(h : ∀{a}, has_sum f a ↔ has_sum g a) : (∑'b, f b) = (∑'c, g c) :=
by_cases
(assume : ∃a, has_sum f a,
let ⟨a, hfa⟩ := this in
have hga : has_sum g a, from h.mp hfa,
by rw [tsum_eq_has_sum hfa, tsum_eq_has_sum hga])
(assume hf : ¬ summable f,
have hg : ¬ summable g, from assume ⟨a, hga⟩, hf ⟨a, h.mpr hga⟩,
by simp [tsum, hf, hg])
lemma tsum_eq_tsum_of_ne_zero {f : β → α} {g : γ → α}
(i : Π⦃c⦄, g c ≠ 0 → β) (hi : ∀⦃c⦄ (h : g c ≠ 0), f (i h) ≠ 0)
(j : Π⦃b⦄, f b ≠ 0 → γ) (hj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) ≠ 0)
(hji : ∀⦃c⦄ (h : g c ≠ 0), j (hi h) = c)
(hij : ∀⦃b⦄ (h : f b ≠ 0), i (hj h) = b)
(hgj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) = f b) :
(∑'i, f i) = (∑'j, g j) :=
tsum_eq_tsum_of_has_sum_iff_has_sum $ assume a, has_sum_iff_has_sum_of_ne_zero i hi j hj hji hij hgj
lemma tsum_eq_tsum_of_ne_zero_bij {f : β → α} {g : γ → α}
(i : Π⦃c⦄, g c ≠ 0 → β)
(h₁ : ∀⦃c₁ c₂⦄ (h₁ : g c₁ ≠ 0) (h₂ : g c₂ ≠ 0), i h₁ = i h₂ → c₁ = c₂)
(h₂ : ∀⦃b⦄, f b ≠ 0 → ∃c (h : g c ≠ 0), i h = b)
(h₃ : ∀⦃c⦄ (h : g c ≠ 0), f (i h) = g c) :
(∑'i, f i) = (∑'j, g j) :=
tsum_eq_tsum_of_has_sum_iff_has_sum $ assume a, has_sum_iff_has_sum_of_ne_zero_bij i h₁ h₂ h₃
lemma tsum_eq_tsum_of_iso (j : γ → β) (i : β → γ)
(h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) :
(∑'c, f (j c)) = (∑'b, f b) :=
tsum_eq_tsum_of_has_sum_iff_has_sum $ assume a, has_sum_iff_has_sum_of_iso i h₁ h₂
lemma tsum_equiv (j : γ ≃ β) : (∑'c, f (j c)) = (∑'b, f b) :=
tsum_eq_tsum_of_iso j j.symm (by simp) (by simp)
variable [topological_add_monoid α]
lemma tsum_add (hf : summable f) (hg : summable g) : (∑'b, f b + g b) = (∑'b, f b) + (∑'b, g b) :=
tsum_eq_has_sum $ hf.has_sum.add hg.has_sum
lemma tsum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) :
(∑'b, s.sum (λi, f i b)) = s.sum (λi, ∑'b, f i b) :=
tsum_eq_has_sum $ has_sum_sum $ assume i hi, (hf i hi).has_sum
lemma tsum_sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α}
(h₁ : ∀b, summable (λc, f ⟨b, c⟩)) (h₂ : summable f) : (∑'p, f p) = (∑'b c, f ⟨b, c⟩) :=
(tsum_eq_has_sum $ h₂.has_sum.sigma (assume b, (h₁ b).has_sum)).symm
end tsum
section topological_group
variables [add_comm_group α] [topological_space α] [topological_add_group α]
variables {f g : β → α} {a a₁ a₂ : α}
lemma has_sum.neg : has_sum f a → has_sum (λb, - f b) (- a) :=
has_sum_hom has_neg.neg continuous_neg
lemma summable.neg (hf : summable f) : summable (λb, - f b) :=
hf.has_sum.neg.summable
lemma has_sum.sub (hf : has_sum f a₁) (hg : has_sum g a₂) : has_sum (λb, f b - g b) (a₁ - a₂) :=
by { simp [sub_eq_add_neg], exact hf.add hg.neg }
lemma summable.sub (hf : summable f) (hg : summable g) : summable (λb, f b - g b) :=
(hf.has_sum.sub hg.has_sum).summable
section tsum
variables [t2_space α]
lemma tsum_neg (hf : summable f) : (∑'b, - f b) = - (∑'b, f b) :=
tsum_eq_has_sum $ hf.has_sum.neg
lemma tsum_sub (hf : summable f) (hg : summable g) : (∑'b, f b - g b) = (∑'b, f b) - (∑'b, g b) :=
tsum_eq_has_sum $ hf.has_sum.sub hg.has_sum
lemma tsum_eq_zero_add {f : ℕ → α} (hf : summable f) : (∑'b, f b) = f 0 + (∑'b, f (b + 1)) :=
begin
let f₁ : ℕ → α := λ n, nat.rec (f 0) (λ _ _, 0) n,
let f₂ : ℕ → α := λ n, nat.rec 0 (λ k _, f (k+1)) n,
have : f = λ n, f₁ n + f₂ n, { ext n, symmetry, cases n, apply add_zero, apply zero_add },
have hf₁ : summable f₁,
{ fapply summable_sum_of_ne_finset_zero,
{ exact finset.singleton 0 },
{ rintros (_ | n) hn,
{ exfalso,
apply hn,
apply finset.mem_singleton_self },
{ refl } } },
have hf₂ : summable f₂,
{ have : f₂ = λ n, f n - f₁ n, ext, rw [eq_sub_iff_add_eq', this],
rw [this], apply hf.sub hf₁ },
conv_lhs { rw [this] },
rw [tsum_add hf₁ hf₂, tsum_eq_single 0],
{ congr' 1,
fapply tsum_eq_tsum_of_ne_zero_bij (λ n _, n + 1),
{ intros _ _ _ _, exact nat.succ_inj },
{ rintros (_ | n) h,
{ contradiction },
{ exact ⟨n, h, rfl⟩ } },
{ intros, refl },
{ apply_instance } },
{ rintros (_ | n) hn,
{ contradiction },
{ refl } },
{ apply_instance }
end
end tsum
/-!
### Sums on subtypes
If `s` is a finset of `α`, we show that the summability of `f` in the whole space and on the subtype
`univ - s` are equivalent, and relate their sums. For a function defined on `ℕ`, we deduce the
formula `(∑ i in range k, f i) + (∑' i, f (i + k)) = (∑' i, f i)`, in `sum_add_tsum_nat_add`.
-/
section subtype
variables {s : finset β}
lemma has_sum_subtype_iff :
has_sum (λ b : {b // b ∉ s}, f b) a ↔ has_sum f (a + ∑ b in s, f b) :=
begin
let gs := λ b, if b ∈ s then f b else 0,
let g := λ b, if b ∉ s then f b else 0,
have f_sum_iff : has_sum f (a + ∑ b in s, f b) = has_sum (λ b, g b + gs b) (a + ∑ b in s, f b),
{ congr,
ext i,
simp [gs, g],
split_ifs;
simp },
have g_zero : ∀ b ∈ s, g b = 0,
{ assume b hb,
dsimp [g],
split_ifs,
refl },
have gs_sum : has_sum gs (∑ b in s, f b),
{ have : (∑ b in s, f b) = (∑ b in s, gs b),
{ apply sum_congr rfl (λ b hb, _),
dsimp [gs],
split_ifs,
{ refl },
{ exact false.elim (h hb) } },
rw this,
apply has_sum_sum_of_ne_finset_zero (λ b hb, _),
dsimp [gs],
split_ifs,
{ exact false.elim (hb h) },
{ refl } },
have : (λ b : {b // b ∉ s}, f b) = (λ b : {b // b ∉ s}, g b),
{ ext i,
simp [g],
split_ifs,
{ exact false.elim (i.2 h) },
{ refl } },
rw [this, has_sum_subtype_iff_of_eq_zero g_zero, f_sum_iff],
exact ⟨λ H, H.add gs_sum, λ H, by simpa using H.sub gs_sum⟩,
end
lemma has_sum_subtype_iff' :
has_sum (λ b : {b // b ∉ s}, f b) (a - ∑ b in s, f b) ↔ has_sum f a :=
by simp [has_sum_subtype_iff]
lemma summable_subtype_iff (s : finset β):
summable (λ b : {b // b ∉ s}, f b) ↔ summable f :=
⟨λ H, (has_sum_subtype_iff.1 H.has_sum).summable, λ H, (has_sum_subtype_iff'.2 H.has_sum).summable⟩
lemma sum_add_tsum_subtype [t2_space α] (s : finset β) (h : summable f) :
(∑ b in s, f b) + (∑' (b : {b // b ∉ s}), f b) = (∑' b, f b) :=
by simpa [add_comm] using
has_sum_unique (has_sum_subtype_iff.1 ((summable_subtype_iff s).2 h).has_sum) h.has_sum
lemma summable_nat_add_iff {f : ℕ → α} (k : ℕ) : summable (λ n, f (n + k)) ↔ summable f :=
begin
refine iff.trans _ (summable_subtype_iff (range k)),
rw [← (not_mem_range_equiv k).symm.summable_iff],
refl
end
lemma has_sum_nat_add_iff {f : ℕ → α} (k : ℕ) {a : α} :
has_sum (λ n, f (n + k)) a ↔ has_sum f (a + ∑ i in range k, f i) :=
begin
refine iff.trans _ has_sum_subtype_iff,
rw [← (not_mem_range_equiv k).symm.has_sum_iff],
refl
end
lemma has_sum_nat_add_iff' {f : ℕ → α} (k : ℕ) {a : α} :
has_sum (λ n, f (n + k)) (a - ∑ i in range k, f i) ↔ has_sum f a :=
by simp [has_sum_nat_add_iff]
lemma sum_add_tsum_nat_add [t2_space α] {f : ℕ → α} (k : ℕ) (h : summable f) :
(∑ i in range k, f i) + (∑' i, f (i + k)) = (∑' i, f i) :=
by simpa [add_comm] using
has_sum_unique ((has_sum_nat_add_iff k).1 ((summable_nat_add_iff k).2 h).has_sum) h.has_sum
end subtype
end topological_group
section topological_semiring
variables [semiring α] [topological_space α] [topological_semiring α]
variables {f g : β → α} {a a₁ a₂ : α}
lemma has_sum.mul_left (a₂) : has_sum f a₁ → has_sum (λb, a₂ * f b) (a₂ * a₁) :=
has_sum_hom _ (continuous_const.mul continuous_id)
lemma has_sum.mul_right (a₂) (hf : has_sum f a₁) : has_sum (λb, f b * a₂) (a₁ * a₂) :=
@has_sum_hom _ _ _ _ _ f a₁ (λa, a * a₂) _ _ _
(continuous_id.mul continuous_const) hf
lemma summable.mul_left (a) (hf : summable f) : summable (λb, a * f b) :=
(hf.has_sum.mul_left _).summable
lemma summable.mul_right (a) (hf : summable f) : summable (λb, f b * a) :=
(hf.has_sum.mul_right _).summable
section tsum
variables [t2_space α]
lemma tsum_mul_left (a) (hf : summable f) : (∑'b, a * f b) = a * (∑'b, f b) :=
tsum_eq_has_sum $ hf.has_sum.mul_left _
lemma tsum_mul_right (a) (hf : summable f) : (∑'b, f b * a) = (∑'b, f b) * a :=
tsum_eq_has_sum $ hf.has_sum.mul_right _
end tsum
end topological_semiring
section field
variables [field α] [topological_space α] [topological_semiring α]
{f g : β → α} {a a₁ a₂ : α}
lemma has_sum_mul_left_iff (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (λb, a₂ * f b) (a₂ * a₁) :=
⟨has_sum.mul_left _, λ H, by simpa [← mul_assoc, inv_mul_cancel h] using H.mul_left a₂⁻¹⟩
lemma has_sum_mul_right_iff (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (λb, f b * a₂) (a₁ * a₂) :=
by { simp only [mul_comm _ a₂], exact has_sum_mul_left_iff h }
lemma summable_mul_left_iff (h : a ≠ 0) : summable f ↔ summable (λb, a * f b) :=
⟨λ H, H.mul_left _, λ H, by simpa [← mul_assoc, inv_mul_cancel h] using H.mul_left a⁻¹⟩
lemma summable_mul_right_iff (h : a ≠ 0) : summable f ↔ summable (λb, f b * a) :=
by { simp only [mul_comm _ a], exact summable_mul_left_iff h }
end field
section order_topology
variables [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α]
variables {f g : β → α} {a a₁ a₂ : α}
lemma has_sum_le (h : ∀b, f b ≤ g b) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ :=
le_of_tendsto_of_tendsto' at_top_ne_bot hf hg $ assume s, sum_le_sum $ assume b _, h b
lemma has_sum_le_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c)
(h : ∀b, f b ≤ g (i b)) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ :=
have has_sum (λc, (partial_inv i c).cases_on' 0 f) a₁,
begin
refine (has_sum_iff_has_sum_of_ne_zero_bij (λb _, i b) _ _ _).2 hf,
{ assume c₁ c₂ h₁ h₂ eq, exact hi eq },
{ assume c hc,
cases eq : partial_inv i c with b; rw eq at hc,
{ contradiction },
{ rw [partial_inv_of_injective hi] at eq,
exact ⟨b, hc, eq⟩ } },
{ assume c hc, rw [partial_inv_left hi, option.cases_on'] }
end,
begin
refine has_sum_le (assume c, _) this hg,
by_cases c ∈ set.range i,
{ rcases h with ⟨b, rfl⟩,
rw [partial_inv_left hi, option.cases_on'],
exact h _ },
{ have : partial_inv i c = none := dif_neg h,
rw [this, option.cases_on'],
exact hs _ h }
end
lemma tsum_le_tsum_of_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c)
(h : ∀b, f b ≤ g (i b)) (hf : summable f) (hg : summable g) : tsum f ≤ tsum g :=
has_sum_le_inj i hi hs h hf.has_sum hg.has_sum
lemma sum_le_has_sum {f : β → α} (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : has_sum f a) :
s.sum f ≤ a :=
ge_of_tendsto at_top_ne_bot hf (eventually_at_top.2 ⟨s, λ t hst,
sum_le_sum_of_subset_of_nonneg hst $ λ b hbt hbs, hs b hbs⟩)
lemma sum_le_tsum {f : β → α} (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : summable f) :
s.sum f ≤ tsum f :=
sum_le_has_sum s hs hf.has_sum
lemma tsum_le_tsum (h : ∀b, f b ≤ g b) (hf : summable f) (hg : summable g) : (∑'b, f b) ≤ (∑'b, g b) :=
has_sum_le h hf.has_sum hg.has_sum
lemma tsum_nonneg (h : ∀ b, 0 ≤ g b) : 0 ≤ (∑'b, g b) :=
begin
by_cases hg : summable g,
{ simpa using tsum_le_tsum h summable_zero hg },
{ simp [tsum_eq_zero_of_not_summable hg] }
end
lemma tsum_nonpos (h : ∀ b, f b ≤ 0) : (∑'b, f b) ≤ 0 :=
begin
by_cases hf : summable f,
{ simpa using tsum_le_tsum h hf summable_zero},
{ simp [tsum_eq_zero_of_not_summable hf] }
end
end order_topology
section uniform_group
variables [add_comm_group α] [uniform_space α]
variables {f g : β → α} {a a₁ a₂ : α}
lemma summable_iff_cauchy_seq_finset [complete_space α] :
summable f ↔ cauchy_seq (λ (s : finset β), s.sum f) :=
(cauchy_map_iff_exists_tendsto at_top_ne_bot).symm
variable [uniform_add_group α]
lemma cauchy_seq_finset_iff_vanishing :
cauchy_seq (λ (s : finset β), s.sum f)
↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → t.sum f ∈ e) :=
begin
simp only [cauchy_seq, cauchy_map_iff, and_iff_right at_top_ne_bot,
prod_at_top_at_top_eq, uniformity_eq_comap_nhds_zero α, tendsto_comap_iff, (∘)],
rw [tendsto_at_top' (_ : finset β × finset β → α)],
split,
{ assume h e he,
rcases h e he with ⟨⟨s₁, s₂⟩, h⟩,
use [s₁ ∪ s₂],
assume t ht,
specialize h (s₁ ∪ s₂, (s₁ ∪ s₂) ∪ t) ⟨le_sup_left, le_sup_left_of_le le_sup_right⟩,
simpa only [finset.sum_union ht.symm, add_sub_cancel'] using h },
{ assume h e he,
rcases exists_nhds_half_neg he with ⟨d, hd, hde⟩,
rcases h d hd with ⟨s, h⟩,
use [(s, s)],
rintros ⟨t₁, t₂⟩ ⟨ht₁, ht₂⟩,
have : t₂.sum f - t₁.sum f = (t₂ \ s).sum f - (t₁ \ s).sum f,
{ simp only [(finset.sum_sdiff ht₁).symm, (finset.sum_sdiff ht₂).symm,
add_sub_add_right_eq_sub] },
simp only [this],
exact hde _ _ (h _ finset.sdiff_disjoint) (h _ finset.sdiff_disjoint) }
end
variable [complete_space α]
lemma summable_iff_vanishing :
summable f ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → t.sum f ∈ e) :=
by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing]
/- TODO: generalize to monoid with a uniform continuous subtraction operator: `(a + b) - b = a` -/
lemma summable.summable_of_eq_zero_or_self (hf : summable f) (h : ∀b, g b = 0 ∨ g b = f b) : summable g :=
summable_iff_vanishing.2 $
assume e he,
let ⟨s, hs⟩ := summable_iff_vanishing.1 hf e he in
⟨s, assume t ht,
have eq : (t.filter (λb, g b = f b)).sum f = t.sum g :=
calc (t.filter (λb, g b = f b)).sum f = (t.filter (λb, g b = f b)).sum g :
finset.sum_congr rfl (assume b hb, (finset.mem_filter.1 hb).2.symm)
... = t.sum g :
begin
refine finset.sum_subset (finset.filter_subset _) _,
assume b hbt hb,
simp only [(∉), finset.mem_filter, and_iff_right hbt] at hb,
exact (h b).resolve_right hb
end,
eq ▸ hs _ $ finset.disjoint_of_subset_left (finset.filter_subset _) ht⟩
lemma summable.summable_comp_of_injective {i : γ → β} (hf : summable f) (hi : injective i) :
summable (f ∘ i) :=
suffices summable (λb, if b ∈ set.range i then f b else 0),
begin
refine (summable_iff_summable_ne_zero_bij (λc _, i c) _ _ _).1 this,
{ assume c₁ c₂ hc₁ hc₂ eq, exact hi eq },
{ assume b hb,
split_ifs at hb,
{ rcases h with ⟨c, rfl⟩,
exact ⟨c, hb, rfl⟩ },
{ contradiction } },
{ assume c hc, exact if_pos (set.mem_range_self _) }
end,
hf.summable_of_eq_zero_or_self $ assume b, by by_cases b ∈ set.range i; simp [h]
lemma summable.sigma_factor {γ : β → Type*} {f : (Σb:β, γ b) → α}
(ha : summable f) (b : β) : summable (λc, f ⟨b, c⟩) :=
ha.summable_comp_of_injective (λ x y hxy, by simpa using hxy)
lemma summable.sigma' [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α}
(ha : summable f) : summable (λb, ∑'c, f ⟨b, c⟩) :=
ha.sigma (λ b, ha.sigma_factor b)
lemma tsum_sigma' [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α}
(ha : summable f) : (∑'p, f p) = (∑'b c, f ⟨b, c⟩) :=
tsum_sigma (λ b, ha.sigma_factor b) ha
end uniform_group
section cauchy_seq
open finset.Ico filter
/-- If the extended distance between consequent points of a sequence is estimated
by a summable series of `nnreal`s, then the original sequence is a Cauchy sequence. -/
lemma cauchy_seq_of_edist_le_of_summable [emetric_space α] {f : ℕ → α} (d : ℕ → nnreal)
(hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f :=
begin
refine emetric.cauchy_seq_iff_nnreal.2 (λ ε εpos, _),
-- Actually we need partial sums of `d` to be a Cauchy sequence
replace hd : cauchy_seq (λ (n : ℕ), (range n).sum d) :=
let ⟨_, H⟩ := hd in cauchy_seq_of_tendsto_nhds _ H.tendsto_sum_nat,
-- Now we take the same `N` as in one of the definitions of a Cauchy sequence
refine (metric.cauchy_seq_iff'.1 hd ε (nnreal.coe_pos.2 εpos)).imp (λ N hN n hn, _),
have hsum := hN n hn,
-- We simplify the known inequality
rw [dist_nndist, nnreal.nndist_eq, ← sum_range_add_sum_Ico _ hn, nnreal.add_sub_cancel'] at hsum,
norm_cast at hsum,
replace hsum := lt_of_le_of_lt (le_max_left _ _) hsum,
rw edist_comm,
-- Then use `hf` to simplify the goal to the same form
apply lt_of_le_of_lt (edist_le_Ico_sum_of_edist_le hn (λ k _ _, hf k)),
assumption_mod_cast
end
/-- If the distance between consequent points of a sequence is estimated by a summable series,
then the original sequence is a Cauchy sequence. -/
lemma cauchy_seq_of_dist_le_of_summable [metric_space α] {f : ℕ → α} (d : ℕ → ℝ)
(hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f :=
begin
refine metric.cauchy_seq_iff'.2 (λε εpos, _),
replace hd : cauchy_seq (λ (n : ℕ), (range n).sum d) :=
let ⟨_, H⟩ := hd in cauchy_seq_of_tendsto_nhds _ H.tendsto_sum_nat,
refine (metric.cauchy_seq_iff'.1 hd ε εpos).imp (λ N hN n hn, _),
have hsum := hN n hn,
rw [real.dist_eq, ← sum_Ico_eq_sub _ hn] at hsum,
calc dist (f n) (f N) = dist (f N) (f n) : dist_comm _ _
... ≤ (Ico N n).sum d : dist_le_Ico_sum_of_dist_le hn (λ k _ _, hf k)
... ≤ abs ((Ico N n).sum d) : le_abs_self _
... < ε : hsum
end
lemma cauchy_seq_of_summable_dist [metric_space α] {f : ℕ → α}
(h : summable (λn, dist (f n) (f n.succ))) : cauchy_seq f :=
cauchy_seq_of_dist_le_of_summable _ (λ _, le_refl _) h
lemma dist_le_tsum_of_dist_le_of_tendsto [metric_space α] {f : ℕ → α} (d : ℕ → ℝ)
(hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a))
(n : ℕ) :
dist (f n) a ≤ ∑' m, d (n + m) :=
begin
refine le_of_tendsto at_top_ne_bot (tendsto_const_nhds.dist ha)
(eventually_at_top.2 ⟨n, λ m hnm, _⟩),
refine le_trans (dist_le_Ico_sum_of_dist_le hnm (λ k _ _, hf k)) _,
rw [sum_Ico_eq_sum_range],
refine sum_le_tsum (range _) (λ _ _, le_trans dist_nonneg (hf _)) _,
exact hd.summable_comp_of_injective (add_right_injective n)
end
lemma dist_le_tsum_of_dist_le_of_tendsto₀ [metric_space α] {f : ℕ → α} (d : ℕ → ℝ)
(hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a)) :
dist (f 0) a ≤ tsum d :=
by simpa only [zero_add] using dist_le_tsum_of_dist_le_of_tendsto d hf hd ha 0
lemma dist_le_tsum_dist_of_tendsto [metric_space α] {f : ℕ → α}
(h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) (n) :
dist (f n) a ≤ ∑' m, dist (f (n+m)) (f (n+m).succ) :=
show dist (f n) a ≤ ∑' m, (λx, dist (f x) (f x.succ)) (n + m), from
dist_le_tsum_of_dist_le_of_tendsto (λ n, dist (f n) (f n.succ)) (λ _, le_refl _) h ha n
lemma dist_le_tsum_dist_of_tendsto₀ [metric_space α] {f : ℕ → α}
(h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) :
dist (f 0) a ≤ ∑' n, dist (f n) (f n.succ) :=
by simpa only [zero_add] using dist_le_tsum_dist_of_tendsto h ha 0
end cauchy_seq
|
066367606ecdfa4d0d13034aa575ef45bc604152 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/linear_algebra/special_linear_group.lean | 7ddc9aa1a2761cf55fe72a98da821f4ed9761d66 | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 5,696 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Anne Baanen.
The Special Linear group $SL(n, R)$
-/
import linear_algebra.matrix
import linear_algebra.nonsingular_inverse
/-!
# The Special Linear group $SL(n, R)$
This file defines the elements of the Special Linear group `special_linear_group n R`,
also written `SL(n, R)` or `SLₙ(R)`, consisting of all `n` by `n` `R`-matrices with
determinant `1`. In addition, we define the group structure on `special_linear_group n R`
and the embedding into the general linear group `general_linear_group R (n → R)`
(i.e. `GL(n, R)` or `GLₙ(R)`).
## Main definitions
* `matrix.special_linear_group` is the type of matrices with determinant 1
* `matrix.special_linear_group.group` gives the group structure (under multiplication)
* `matrix.special_linear_group.embedding_GL` is the embedding `SLₙ(R) → GLₙ(R)`
## Implementation notes
The inverse operation in the `special_linear_group` is defined to be the adjugate
matrix, so that `special_linear_group n R` has a group structure for all `comm_ring R`.
We define the elements of `special_linear_group` to be matrices, since we need to
compute their determinant. This is in contrast with `general_linear_group R M`,
which consists of invertible `R`-linear maps on `M`.
## References
* https://en.wikipedia.org/wiki/Special_linear_group
## Tags
matrix group, group, matrix inverse
-/
namespace matrix
universes u v
open_locale matrix
open linear_map
section
variables (n : Type u) [fintype n] [decidable_eq n] (R : Type v) [comm_ring R]
/-- `special_linear_group n R` is the group of `n` by `n` `R`-matrices with determinant equal to 1. -/
def special_linear_group := { A : matrix n n R // A.det = 1 }
end
namespace special_linear_group
variables {n : Type u} [fintype n] [decidable_eq n] {R : Type v} [comm_ring R]
instance coe_matrix : has_coe (special_linear_group n R) (matrix n n R) :=
⟨λ A, A.val⟩
instance coe_fun : has_coe_to_fun (special_linear_group n R) :=
{ F := λ _, n → n → R,
coe := λ A, A.val }
/--
`to_lin A` is matrix multiplication of vectors by `A`, as a linear map.
After the group structure on `special_linear_group n R` is defined,
we show in `to_linear_equiv` that this gives a linear equivalence.
-/
def to_lin (A : special_linear_group n R) := matrix.to_lin A
lemma ext_iff (A B : special_linear_group n R) : A = B ↔ (∀ i j, A i j = B i j) :=
iff.trans subtype.ext_iff_val ⟨(λ h i j, congr_fun (congr_fun h i) j), matrix.ext⟩
@[ext] lemma ext (A B : special_linear_group n R) : (∀ i j, A i j = B i j) → A = B :=
(special_linear_group.ext_iff A B).mpr
instance has_inv : has_inv (special_linear_group n R) :=
⟨λ A, ⟨adjugate A, det_adjugate_eq_one A.2⟩⟩
instance has_mul : has_mul (special_linear_group n R) :=
⟨λ A B, ⟨A.1 ⬝ B.1, by erw [det_mul, A.2, B.2, one_mul]⟩⟩
instance has_one : has_one (special_linear_group n R) :=
⟨⟨1, det_one⟩⟩
instance : inhabited (special_linear_group n R) := ⟨1⟩
section coe_lemmas
variables (A B : special_linear_group n R)
@[simp] lemma inv_val : ↑(A⁻¹) = adjugate A := rfl
@[simp] lemma inv_apply : ⇑(A⁻¹) = adjugate A := rfl
@[simp] lemma mul_val : ↑(A * B) = A ⬝ B := rfl
@[simp] lemma mul_apply : ⇑(A * B) = (A ⬝ B) := rfl
@[simp] lemma one_val : ↑(1 : special_linear_group n R) = (1 : matrix n n R) := rfl
@[simp] lemma one_apply : ⇑(1 : special_linear_group n R) = (1 : matrix n n R) := rfl
@[simp] lemma det_coe_matrix : det A = 1 := A.2
lemma det_coe_fun : det ⇑A = 1 := A.2
@[simp] lemma to_lin_mul : to_lin (A * B) = (to_lin A).comp (to_lin B) := matrix.mul_to_lin A B
@[simp] lemma to_lin_one : to_lin (1 : special_linear_group n R) = linear_map.id := matrix.to_lin_one
end coe_lemmas
instance group : group (special_linear_group n R) :=
{ mul_assoc := λ A B C, by { ext, simp [matrix.mul_assoc] },
one_mul := λ A, by { ext, simp },
mul_one := λ A, by { ext, simp },
mul_left_inv := λ A, by { ext, simp [adjugate_mul] },
..special_linear_group.has_mul,
..special_linear_group.has_one,
..special_linear_group.has_inv }
/-- `to_linear_equiv A` is matrix multiplication of vectors by `A`, as a linear equivalence. -/
def to_linear_equiv (A : special_linear_group n R) : (n → R) ≃ₗ[R] (n → R) :=
{ inv_fun := A⁻¹.to_lin,
left_inv := λ x, calc
A⁻¹.to_lin.comp A.to_lin x
= (A⁻¹ * A).to_lin x : by rw [←to_lin_mul]
... = x : by rw [mul_left_inv, to_lin_one, id_apply],
right_inv := λ x, calc
A.to_lin.comp A⁻¹.to_lin x
= (A * A⁻¹).to_lin x : by rw [←to_lin_mul]
... = x : by rw [mul_right_inv, to_lin_one, id_apply],
..matrix.to_lin A }
/-- `to_GL` is the map from the special linear group to the general linear group -/
def to_GL (A : special_linear_group n R) : general_linear_group R (n → R) :=
general_linear_group.of_linear_equiv (to_linear_equiv A)
lemma coe_to_GL (A : special_linear_group n R) :
(@coe (units _) _ _ (to_GL A)) = A.to_lin :=
rfl
@[simp]
lemma to_GL_one : to_GL (1 : special_linear_group n R) = 1 :=
by { ext v i, rw [coe_to_GL, to_lin_one], refl }
@[simp]
lemma to_GL_mul (A B : special_linear_group n R) :
to_GL (A * B) = to_GL A * to_GL B :=
by { ext v i, rw [coe_to_GL, to_lin_mul], refl }
/-- `special_linear_group.embedding_GL` is the embedding from `special_linear_group n R`
to `general_linear_group n R`. -/
def embedding_GL : (special_linear_group n R) →* (general_linear_group R (n → R)) :=
⟨λ A, to_GL A, by simp, by simp⟩
end special_linear_group
end matrix
|
9603debef283c6ed1f9e6c6a4405baf009fb1fdb | 77c5b91fae1b966ddd1db969ba37b6f0e4901e88 | /src/algebra/order/sub.lean | da3fa7b8a813cebf20d7b7347a3df349eb459eb4 | [
"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 | 27,618 | lean | /-
Copyright (c) 2021 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import algebra.order.monoid
/-!
# Ordered Subtraction
This file proves lemmas relating (truncated) subtraction with an order. We provide a class
`has_ordered_sub` stating that `a - b ≤ c ↔ a ≤ c + b`.
The subtraction discussed here could both be normal subtraction in an additive group or truncated
subtraction on a canonically ordered monoid (`ℕ`, `multiset`, `enat`, `ennreal`, ...)
## Implementation details
`has_ordered_sub` is a mixin type-class, so that we can use the results in this file even in cases
where we don't have a `canonically_ordered_add_monoid` instance
(even though that is our main focus). Conversely, this means we can use
`canonically_ordered_add_monoid` without necessarily having to define a subtraction.
The results in this file are ordered by the type-class assumption needed to prove it.
This means that similar results might not be close to each other. Furthermore, we don't prove
implications if a bi-implication can be proven under the same assumptions.
Many results about this subtraction are primed, to not conflict with similar lemmas about ordered
groups.
We provide a second version of most results that require `[contravariant_class α α (+) (≤)]`. In the
second version we replace this type-class assumption by explicit `add_le_cancellable` assumptions.
TODO: maybe we should make a multiplicative version of this, so that we can replace some identical
lemmas about subtraction/division in `ordered_[add_]comm_group` with these.
-/
variables {α β : Type*}
/-- `has_ordered_sub α` means that `α` has a subtraction characterized by `a - b ≤ c ↔ a ≤ c + b`.
In other words, `a - b` is the least `c` such that `a ≤ b + c`.
This is satisfied both by the subtraction in additive ordered groups and by truncated subtraction
in canonically ordered monoids on many specific types.
-/
class has_ordered_sub (α : Type*) [preorder α] [has_add α] [has_sub α] :=
(sub_le_iff_right : ∀ a b c : α, a - b ≤ c ↔ a ≤ c + b)
section has_add
variables [preorder α] [has_add α] [has_sub α] [has_ordered_sub α] {a b c d : α}
@[simp] lemma sub_le_iff_right : a - b ≤ c ↔ a ≤ c + b :=
has_ordered_sub.sub_le_iff_right a b c
/-- See `add_sub_cancel_right` for the equality if `contravariant_class α α (+) (≤)`. -/
lemma add_sub_le_right : a + b - b ≤ a :=
sub_le_iff_right.mpr le_rfl
lemma le_sub_add : b ≤ (b - a) + a :=
sub_le_iff_right.mp le_rfl
lemma add_hom.le_map_sub [preorder β] [has_add β] [has_sub β] [has_ordered_sub β]
(f : add_hom α β) (hf : monotone f) (a b : α) :
f a - f b ≤ f (a - b) :=
by { rw [sub_le_iff_right, ← f.map_add], exact hf le_sub_add }
lemma le_mul_sub {R : Type*} [distrib R] [preorder R] [has_sub R] [has_ordered_sub R]
[covariant_class R R (*) (≤)] (a b c : R) :
a * b - a * c ≤ a * (b - c) :=
(add_hom.mul_left a).le_map_sub (monotone_id.const_mul' a) _ _
lemma le_sub_mul {R : Type*} [comm_semiring R] [preorder R] [has_sub R] [has_ordered_sub R]
[covariant_class R R (*) (≤)] (a b c : R) :
a * c - b * c ≤ (a - b) * c :=
by simpa only [mul_comm c] using le_mul_sub c a b
end has_add
/-- An order isomorphism between types with ordered subtraction preserves subtraction provided that
it preserves addition. -/
lemma order_iso.map_sub {M N : Type*} [preorder M] [has_add M] [has_sub M] [has_ordered_sub M]
[partial_order N] [has_add N] [has_sub N] [has_ordered_sub N] (e : M ≃o N)
(h_add : ∀ a b, e (a + b) = e a + e b) (a b : M) :
e (a - b) = e a - e b :=
begin
set e_add : M ≃+ N := { map_add' := h_add, .. e },
refine le_antisymm _ (e_add.to_add_hom.le_map_sub e.monotone a b),
suffices : e (e.symm (e a) - e.symm (e b)) ≤ e (e.symm (e a - e b)), by simpa,
exact e.monotone (e_add.symm.to_add_hom.le_map_sub e.symm.monotone _ _)
end
section ordered_add_comm_monoid
section preorder
variables [preorder α] [add_comm_monoid α] [has_sub α] [has_ordered_sub α] {a b c d : α}
lemma sub_le_iff_left : a - b ≤ c ↔ a ≤ b + c :=
by rw [sub_le_iff_right, add_comm]
lemma le_add_sub : a ≤ b + (a - b) :=
sub_le_iff_left.mp le_rfl
/-- See `add_sub_cancel_left` for the equality if `contravariant_class α α (+) (≤)`. -/
lemma add_sub_le_left : a + b - a ≤ b :=
sub_le_iff_left.mpr le_rfl
lemma sub_le_sub_right' (h : a ≤ b) (c : α) : a - c ≤ b - c :=
sub_le_iff_left.mpr $ h.trans le_add_sub
lemma sub_le_iff_sub_le : a - b ≤ c ↔ a - c ≤ b :=
by rw [sub_le_iff_left, sub_le_iff_right]
/-- See `sub_sub_cancel_of_le` for the equality. -/
lemma sub_sub_le : b - (b - a) ≤ a :=
sub_le_iff_right.mpr le_add_sub
lemma add_monoid_hom.le_map_sub [preorder β] [add_comm_monoid β] [has_sub β]
[has_ordered_sub β] (f : α →+ β) (hf : monotone f) (a b : α) :
f a - f b ≤ f (a - b) :=
f.to_add_hom.le_map_sub hf a b
end preorder
variables [partial_order α] [add_comm_monoid α] [has_sub α] [has_ordered_sub α] {a b c d : α}
lemma sub_sub' (b a c : α) : b - a - c = b - (a + c) :=
begin
apply le_antisymm,
{ rw [sub_le_iff_left, sub_le_iff_left, ← add_assoc, ← sub_le_iff_left] },
{ rw [sub_le_iff_left, add_assoc, ← sub_le_iff_left, ← sub_le_iff_left] }
end
section cov
variable [covariant_class α α (+) (≤)]
lemma sub_le_sub_left' (h : a ≤ b) (c : α) : c - b ≤ c - a :=
sub_le_iff_left.mpr $ le_add_sub.trans $ add_le_add_right h _
lemma sub_le_sub' (hab : a ≤ b) (hcd : c ≤ d) : a - d ≤ b - c :=
(sub_le_sub_right' hab _).trans $ sub_le_sub_left' hcd _
lemma sub_add_eq_sub_sub' : a - (b + c) = a - b - c :=
begin
refine le_antisymm (sub_le_iff_left.mpr _)
(sub_le_iff_left.mpr $ sub_le_iff_left.mpr _),
{ rw [add_assoc], refine le_trans le_add_sub (add_le_add_left le_add_sub _) },
{ rw [← add_assoc], apply le_add_sub }
end
lemma sub_add_eq_sub_sub_swap' : a - (b + c) = a - c - b :=
by { rw [add_comm], exact sub_add_eq_sub_sub' }
lemma add_le_add_add_sub : a + b ≤ (a + c) + (b - c) :=
by { rw [add_assoc], exact add_le_add_left le_add_sub a }
lemma sub_right_comm' : a - b - c = a - c - b :=
by simp_rw [← sub_add_eq_sub_sub', add_comm]
/-- See `add_sub_assoc_of_le` for the equality. -/
lemma add_sub_le_assoc : a + b - c ≤ a + (b - c) :=
by { rw [sub_le_iff_left, add_left_comm], exact add_le_add_left le_add_sub a }
lemma le_sub_add_add : a + b ≤ (a - c) + (b + c) :=
by { rw [add_comm a, add_comm (a - c)], exact add_le_add_add_sub }
lemma sub_le_sub_add_sub : a - c ≤ (a - b) + (b - c) :=
begin
rw [sub_le_iff_left, ← add_assoc, add_right_comm],
refine le_add_sub.trans (add_le_add_right le_add_sub _),
end
lemma sub_sub_sub_le_sub : (c - a) - (c - b) ≤ b - a :=
begin
rw [sub_le_iff_left, sub_le_iff_left, add_left_comm],
refine le_sub_add.trans (add_le_add_left le_add_sub _),
end
end cov
/-! ### Lemmas that assume that an element is `add_le_cancellable`. -/
namespace add_le_cancellable
protected lemma le_add_sub_swap (hb : add_le_cancellable b) : a ≤ b + a - b :=
hb le_add_sub
protected lemma le_add_sub (hb : add_le_cancellable b) : a ≤ a + b - b :=
by { rw [add_comm], exact hb.le_add_sub_swap }
protected lemma sub_eq_of_eq_add (hb : add_le_cancellable b) (h : a = c + b) : a - b = c :=
le_antisymm (sub_le_iff_right.mpr h.le) $
by { rw h, exact hb.le_add_sub }
protected lemma eq_sub_of_add_eq (hc : add_le_cancellable c) (h : a + c = b) : a = b - c :=
(hc.sub_eq_of_eq_add h.symm).symm
@[simp]
protected lemma add_sub_cancel_right (hb : add_le_cancellable b) : a + b - b = a :=
hb.sub_eq_of_eq_add $ by rw [add_comm]
@[simp]
protected lemma add_sub_cancel_left (ha : add_le_cancellable a) : a + b - a = b :=
ha.sub_eq_of_eq_add $ add_comm a b
protected lemma le_sub_of_add_le_left (ha : add_le_cancellable a) (h : a + b ≤ c) : b ≤ c - a :=
ha $ h.trans le_add_sub
protected lemma le_sub_of_add_le_right (hb : add_le_cancellable b) (h : a + b ≤ c) : a ≤ c - b :=
hb.le_sub_of_add_le_left $ by rwa [add_comm]
protected lemma lt_add_of_sub_lt_left (hb : add_le_cancellable b) (h : a - b < c) : a < b + c :=
begin
rw [lt_iff_le_and_ne, ← sub_le_iff_left],
refine ⟨h.le, _⟩,
rintro rfl,
simpa [hb] using h,
end
protected lemma lt_add_of_sub_lt_right (hc : add_le_cancellable c) (h : a - c < b) : a < b + c :=
begin
rw [lt_iff_le_and_ne, ← sub_le_iff_right],
refine ⟨h.le, _⟩,
rintro rfl,
simpa [hc] using h,
end
end add_le_cancellable
/-! ### Lemmas where addition is order-reflecting. -/
section contra
variable [contravariant_class α α (+) (≤)]
lemma le_add_sub_swap : a ≤ b + a - b :=
contravariant.add_le_cancellable.le_add_sub_swap
lemma le_add_sub' : a ≤ a + b - b :=
contravariant.add_le_cancellable.le_add_sub
lemma sub_eq_of_eq_add'' (h : a = c + b) : a - b = c :=
contravariant.add_le_cancellable.sub_eq_of_eq_add h
lemma eq_sub_of_add_eq'' (h : a + c = b) : a = b - c :=
contravariant.add_le_cancellable.eq_sub_of_add_eq h
@[simp]
lemma add_sub_cancel_right : a + b - b = a :=
contravariant.add_le_cancellable.add_sub_cancel_right
@[simp]
lemma add_sub_cancel_left : a + b - a = b :=
contravariant.add_le_cancellable.add_sub_cancel_left
lemma le_sub_of_add_le_left' (h : a + b ≤ c) : b ≤ c - a :=
contravariant.add_le_cancellable.le_sub_of_add_le_left h
lemma le_sub_of_add_le_right' (h : a + b ≤ c) : a ≤ c - b :=
contravariant.add_le_cancellable.le_sub_of_add_le_right h
lemma lt_add_of_sub_lt_left' (h : a - b < c) : a < b + c :=
contravariant.add_le_cancellable.lt_add_of_sub_lt_left h
lemma lt_add_of_sub_lt_right' (h : a - c < b) : a < b + c :=
contravariant.add_le_cancellable.lt_add_of_sub_lt_right h
end contra
section both
variables [covariant_class α α (+) (≤)] [contravariant_class α α (+) (≤)]
lemma add_sub_add_right_eq_sub' : (a + c) - (b + c) = a - b :=
begin
apply le_antisymm,
{ rw [sub_le_iff_left, add_right_comm], exact add_le_add_right le_add_sub c },
{ rw [sub_le_iff_left, add_comm b],
apply le_of_add_le_add_right,
rw [add_assoc],
exact le_sub_add }
end
lemma add_sub_add_eq_sub_left' (a b c : α) : (a + b) - (a + c) = b - c :=
by rw [add_comm a b, add_comm a c, add_sub_add_right_eq_sub']
end both
end ordered_add_comm_monoid
/-! ### Lemmas in a linearly ordered monoid. -/
section linear_order
variables {a b c d : α} [linear_order α] [add_comm_monoid α] [has_sub α] [has_ordered_sub α]
/-- See `lt_of_sub_lt_sub_right_of_le` for a weaker statement in a partial order. -/
lemma lt_of_sub_lt_sub_right (h : a - c < b - c) : a < b :=
lt_imp_lt_of_le_imp_le (λ h, sub_le_sub_right' h c) h
section cov
variable [covariant_class α α (+) (≤)]
/-- See `lt_of_sub_lt_sub_left_of_le` for a weaker statement in a partial order. -/
lemma lt_of_sub_lt_sub_left (h : a - b < a - c) : c < b :=
lt_imp_lt_of_le_imp_le (λ h, sub_le_sub_left' h a) h
end cov
end linear_order
/-! ### Lemmas in a canonically ordered monoid. -/
section canonically_ordered_add_monoid
variables [canonically_ordered_add_monoid α] [has_sub α] [has_ordered_sub α] {a b c d : α}
lemma add_sub_cancel_of_le (h : a ≤ b) : a + (b - a) = b :=
begin
refine le_antisymm _ le_add_sub,
obtain ⟨c, rfl⟩ := le_iff_exists_add.1 h,
exact add_le_add_left add_sub_le_left a,
end
lemma sub_add_cancel_of_le (h : a ≤ b) : b - a + a = b :=
by { rw [add_comm], exact add_sub_cancel_of_le h }
lemma add_sub_cancel_iff_le : a + (b - a) = b ↔ a ≤ b :=
⟨λ h, le_iff_exists_add.mpr ⟨b - a, h.symm⟩, add_sub_cancel_of_le⟩
lemma sub_add_cancel_iff_le : b - a + a = b ↔ a ≤ b :=
by { rw [add_comm], exact add_sub_cancel_iff_le }
lemma add_le_of_le_sub_right_of_le (h : b ≤ c) (h2 : a ≤ c - b) : a + b ≤ c :=
(add_le_add_right h2 b).trans_eq $ sub_add_cancel_of_le h
lemma add_le_of_le_sub_left_of_le (h : a ≤ c) (h2 : b ≤ c - a) : a + b ≤ c :=
(add_le_add_left h2 a).trans_eq $ add_sub_cancel_of_le h
lemma sub_le_sub_iff_right' (h : c ≤ b) : a - c ≤ b - c ↔ a ≤ b :=
by rw [sub_le_iff_right, sub_add_cancel_of_le h]
lemma sub_left_inj' (h1 : c ≤ a) (h2 : c ≤ b) : a - c = b - c ↔ a = b :=
by simp_rw [le_antisymm_iff, sub_le_sub_iff_right' h1, sub_le_sub_iff_right' h2]
/-- See `lt_of_sub_lt_sub_right` for a stronger statement in a linear order. -/
lemma lt_of_sub_lt_sub_right_of_le (h : c ≤ b) (h2 : a - c < b - c) : a < b :=
by { refine ((sub_le_sub_iff_right' h).mp h2.le).lt_of_ne _, rintro rfl, exact h2.false }
lemma sub_eq_zero_iff_le : a - b = 0 ↔ a ≤ b :=
by rw [← nonpos_iff_eq_zero, sub_le_iff_left, add_zero]
@[simp] lemma sub_self' : a - a = 0 :=
sub_eq_zero_iff_le.mpr le_rfl
@[simp] lemma sub_le_self' : a - b ≤ a :=
sub_le_iff_left.mpr $ le_add_left le_rfl
@[simp] lemma sub_zero' : a - 0 = a :=
le_antisymm sub_le_self' $ le_add_sub.trans_eq $ zero_add _
@[simp] lemma zero_sub' : 0 - a = 0 :=
sub_eq_zero_iff_le.mpr $ zero_le a
lemma sub_self_add (a b : α) : a - (a + b) = 0 :=
by { rw [sub_eq_zero_iff_le], apply self_le_add_right }
lemma sub_inj_left (h₁ : a ≤ b) (h₂ : a ≤ c) (h₃ : b - a = c - a) : b = c :=
by rw [← sub_add_cancel_of_le h₁, ← sub_add_cancel_of_le h₂, h₃]
lemma sub_pos_iff_not_le : 0 < a - b ↔ ¬ a ≤ b :=
by rw [pos_iff_ne_zero, ne.def, sub_eq_zero_iff_le]
lemma sub_pos_of_lt' (h : a < b) : 0 < b - a :=
sub_pos_iff_not_le.mpr h.not_le
lemma sub_add_sub_cancel'' (hab : b ≤ a) (hbc : c ≤ b) : (a - b) + (b - c) = a - c :=
begin
convert sub_add_cancel_of_le (sub_le_sub_right' hab c) using 2,
rw [sub_sub', add_sub_cancel_of_le hbc],
end
lemma sub_sub_sub_cancel_right' (h : c ≤ b) : (a - c) - (b - c) = a - b :=
by rw [sub_sub', add_sub_cancel_of_le h]
/-! ### Lemmas that assume that an element is `add_le_cancellable`. -/
namespace add_le_cancellable
protected lemma eq_sub_iff_add_eq_of_le (hc : add_le_cancellable c) (h : c ≤ b) :
a = b - c ↔ a + c = b :=
begin
split,
{ rintro rfl, exact sub_add_cancel_of_le h },
{ rintro rfl, exact (hc.add_sub_cancel_right).symm }
end
protected lemma sub_eq_iff_eq_add_of_le (hb : add_le_cancellable b) (h : b ≤ a) :
a - b = c ↔ a = c + b :=
by rw [eq_comm, hb.eq_sub_iff_add_eq_of_le h, eq_comm]
protected lemma add_sub_assoc_of_le (hc : add_le_cancellable c) (h : c ≤ b) (a : α) :
a + b - c = a + (b - c) :=
by conv_lhs { rw [← add_sub_cancel_of_le h, add_comm c, ← add_assoc,
hc.add_sub_cancel_right] }
protected lemma sub_add_eq_add_sub (hb : add_le_cancellable b) (h : b ≤ a) :
a - b + c = a + c - b :=
by rw [add_comm a, hb.add_sub_assoc_of_le h, add_comm]
protected lemma sub_sub_assoc (hbc : add_le_cancellable (b - c)) (h₁ : b ≤ a) (h₂ : c ≤ b) :
a - (b - c) = a - b + c :=
by rw [hbc.sub_eq_iff_eq_add_of_le (sub_le_self'.trans h₁), add_assoc,
add_sub_cancel_of_le h₂, sub_add_cancel_of_le h₁]
protected lemma le_sub_iff_left (ha : add_le_cancellable a) (h : a ≤ c) : b ≤ c - a ↔ a + b ≤ c :=
⟨add_le_of_le_sub_left_of_le h, ha.le_sub_of_add_le_left⟩
protected lemma le_sub_iff_right (ha : add_le_cancellable a) (h : a ≤ c) : b ≤ c - a ↔ b + a ≤ c :=
by { rw [add_comm], exact ha.le_sub_iff_left h }
protected lemma sub_lt_iff_left (hb : add_le_cancellable b) (hba : b ≤ a) :
a - b < c ↔ a < b + c :=
begin
refine ⟨hb.lt_add_of_sub_lt_left, _⟩,
intro h, refine (sub_le_iff_left.mpr h.le).lt_of_ne _,
rintro rfl, exact h.ne' (add_sub_cancel_of_le hba)
end
protected lemma sub_lt_iff_right (hb : add_le_cancellable b) (hba : b ≤ a) :
a - b < c ↔ a < c + b :=
by { rw [add_comm], exact hb.sub_lt_iff_left hba }
protected lemma lt_sub_of_add_lt_right (hc : add_le_cancellable c) (h : a + c < b) : a < b - c :=
begin
apply lt_of_le_of_ne,
{ rw [← add_sub_cancel_of_le h.le, add_right_comm, add_assoc],
rw [hc.add_sub_assoc_of_le], refine le_self_add, refine le_add_self },
{ rintro rfl, apply h.not_le, exact le_sub_add }
end
protected lemma lt_sub_of_add_lt_left (ha : add_le_cancellable a) (h : a + c < b) : c < b - a :=
by { apply ha.lt_sub_of_add_lt_right, rwa add_comm }
protected lemma sub_lt_iff_sub_lt (hb : add_le_cancellable b) (hc : add_le_cancellable c)
(h₁ : b ≤ a) (h₂ : c ≤ a) : a - b < c ↔ a - c < b :=
by rw [hb.sub_lt_iff_left h₁, hc.sub_lt_iff_right h₂]
protected lemma le_sub_iff_le_sub (ha : add_le_cancellable a) (hc : add_le_cancellable c)
(h₁ : a ≤ b) (h₂ : c ≤ b) : a ≤ b - c ↔ c ≤ b - a :=
by rw [ha.le_sub_iff_left h₁, hc.le_sub_iff_right h₂]
protected lemma lt_sub_iff_right_of_le (hc : add_le_cancellable c) (h : c ≤ b) :
a < b - c ↔ a + c < b :=
begin
refine ⟨_, hc.lt_sub_of_add_lt_right⟩,
intro h2,
refine (add_le_of_le_sub_right_of_le h h2.le).lt_of_ne _,
rintro rfl,
apply h2.not_le,
rw [hc.add_sub_cancel_right]
end
protected lemma lt_sub_iff_left_of_le (hc : add_le_cancellable c) (h : c ≤ b) :
a < b - c ↔ c + a < b :=
by { rw [add_comm], exact hc.lt_sub_iff_right_of_le h }
protected lemma lt_of_sub_lt_sub_left_of_le [contravariant_class α α (+) (<)]
(hb : add_le_cancellable b) (hca : c ≤ a) (h : a - b < a - c) : c < b :=
begin
conv_lhs at h { rw [← sub_add_cancel_of_le hca] },
exact lt_of_add_lt_add_left (hb.lt_add_of_sub_lt_right h),
end
protected lemma sub_le_sub_iff_left (ha : add_le_cancellable a) (hc : add_le_cancellable c)
(h : c ≤ a) : a - b ≤ a - c ↔ c ≤ b :=
begin
refine ⟨_, λ h, sub_le_sub_left' h a⟩,
rw [sub_le_iff_left, ← hc.add_sub_assoc_of_le h,
hc.le_sub_iff_right (h.trans le_add_self), add_comm b],
apply ha,
end
protected lemma sub_right_inj (ha : add_le_cancellable a) (hb : add_le_cancellable b)
(hc : add_le_cancellable c) (hba : b ≤ a) (hca : c ≤ a) : a - b = a - c ↔ b = c :=
by simp_rw [le_antisymm_iff, ha.sub_le_sub_iff_left hb hba, ha.sub_le_sub_iff_left hc hca, and_comm]
protected lemma sub_lt_sub_right_of_le (hc : add_le_cancellable c) (h : c ≤ a) (h2 : a < b) :
a - c < b - c :=
by { apply hc.lt_sub_of_add_lt_left, rwa [add_sub_cancel_of_le h] }
protected lemma sub_inj_right (hab : add_le_cancellable (a - b)) (h₁ : b ≤ a) (h₂ : c ≤ a)
(h₃ : a - b = a - c) : b = c :=
by { rw ← hab.inj, rw [sub_add_cancel_of_le h₁, h₃, sub_add_cancel_of_le h₂] }
protected lemma sub_lt_sub_iff_left_of_le_of_le [contravariant_class α α (+) (<)]
(hb : add_le_cancellable b) (hab : add_le_cancellable (a - b)) (h₁ : b ≤ a) (h₂ : c ≤ a) :
a - b < a - c ↔ c < b :=
begin
refine ⟨hb.lt_of_sub_lt_sub_left_of_le h₂, _⟩,
intro h, refine (sub_le_sub_left' h.le _).lt_of_ne _,
rintro h2, exact h.ne' (hab.sub_inj_right h₁ h₂ h2)
end
@[simp] protected lemma add_sub_sub_cancel (hac : add_le_cancellable (a - c)) (h : c ≤ a) :
(a + b) - (a - c) = b + c :=
(hac.sub_eq_iff_eq_add_of_le $ sub_le_self'.trans le_self_add).mpr $
by rw [add_assoc, add_sub_cancel_of_le h, add_comm]
protected lemma sub_sub_cancel_of_le (hba : add_le_cancellable (b - a)) (h : a ≤ b) :
b - (b - a) = a :=
by rw [hba.sub_eq_iff_eq_add_of_le sub_le_self', add_sub_cancel_of_le h]
end add_le_cancellable
section contra
/-! ### Lemmas where addition is order-reflecting. -/
variable [contravariant_class α α (+) (≤)]
lemma eq_sub_iff_add_eq_of_le (h : c ≤ b) : a = b - c ↔ a + c = b :=
contravariant.add_le_cancellable.eq_sub_iff_add_eq_of_le h
lemma sub_eq_iff_eq_add_of_le (h : b ≤ a) : a - b = c ↔ a = c + b :=
contravariant.add_le_cancellable.sub_eq_iff_eq_add_of_le h
/-- See `add_sub_le_assoc` for an inequality. -/
lemma add_sub_assoc_of_le (h : c ≤ b) (a : α) : a + b - c = a + (b - c) :=
contravariant.add_le_cancellable.add_sub_assoc_of_le h a
lemma sub_add_eq_add_sub' (h : b ≤ a) : a - b + c = a + c - b :=
contravariant.add_le_cancellable.sub_add_eq_add_sub h
lemma sub_sub_assoc (h₁ : b ≤ a) (h₂ : c ≤ b) : a - (b - c) = a - b + c :=
contravariant.add_le_cancellable.sub_sub_assoc h₁ h₂
lemma le_sub_iff_left (h : a ≤ c) : b ≤ c - a ↔ a + b ≤ c :=
contravariant.add_le_cancellable.le_sub_iff_left h
lemma le_sub_iff_right (h : a ≤ c) : b ≤ c - a ↔ b + a ≤ c :=
contravariant.add_le_cancellable.le_sub_iff_right h
lemma sub_lt_iff_left (hbc : b ≤ a) : a - b < c ↔ a < b + c :=
contravariant.add_le_cancellable.sub_lt_iff_left hbc
lemma sub_lt_iff_right (hbc : b ≤ a) : a - b < c ↔ a < c + b :=
contravariant.add_le_cancellable.sub_lt_iff_right hbc
/-- This lemma (and some of its corollaries also holds for `ennreal`,
but this proof doesn't work for it.
Maybe we should add this lemma as field to `has_ordered_sub`? -/
lemma lt_sub_of_add_lt_right (h : a + c < b) : a < b - c :=
contravariant.add_le_cancellable.lt_sub_of_add_lt_right h
lemma lt_sub_of_add_lt_left (h : a + c < b) : c < b - a :=
contravariant.add_le_cancellable.lt_sub_of_add_lt_left h
lemma sub_lt_iff_sub_lt (h₁ : b ≤ a) (h₂ : c ≤ a) : a - b < c ↔ a - c < b :=
contravariant.add_le_cancellable.sub_lt_iff_sub_lt contravariant.add_le_cancellable h₁ h₂
lemma le_sub_iff_le_sub (h₁ : a ≤ b) (h₂ : c ≤ b) : a ≤ b - c ↔ c ≤ b - a :=
contravariant.add_le_cancellable.le_sub_iff_le_sub contravariant.add_le_cancellable h₁ h₂
/-- See `lt_sub_iff_right` for a stronger statement in a linear order. -/
lemma lt_sub_iff_right_of_le (h : c ≤ b) : a < b - c ↔ a + c < b :=
contravariant.add_le_cancellable.lt_sub_iff_right_of_le h
/-- See `lt_sub_iff_left` for a stronger statement in a linear order. -/
lemma lt_sub_iff_left_of_le (h : c ≤ b) : a < b - c ↔ c + a < b :=
contravariant.add_le_cancellable.lt_sub_iff_left_of_le h
/-- See `lt_of_sub_lt_sub_left` for a stronger statement in a linear order. -/
lemma lt_of_sub_lt_sub_left_of_le [contravariant_class α α (+) (<)]
(hca : c ≤ a) (h : a - b < a - c) : c < b :=
contravariant.add_le_cancellable.lt_of_sub_lt_sub_left_of_le hca h
lemma sub_le_sub_iff_left' (h : c ≤ a) : a - b ≤ a - c ↔ c ≤ b :=
contravariant.add_le_cancellable.sub_le_sub_iff_left contravariant.add_le_cancellable h
lemma sub_right_inj' (hba : b ≤ a) (hca : c ≤ a) : a - b = a - c ↔ b = c :=
contravariant.add_le_cancellable.sub_right_inj contravariant.add_le_cancellable
contravariant.add_le_cancellable hba hca
lemma sub_lt_sub_right_of_le (h : c ≤ a) (h2 : a < b) : a - c < b - c :=
contravariant.add_le_cancellable.sub_lt_sub_right_of_le h h2
lemma sub_inj_right (h₁ : b ≤ a) (h₂ : c ≤ a) (h₃ : a - b = a - c) : b = c :=
contravariant.add_le_cancellable.sub_inj_right h₁ h₂ h₃
/-- See `sub_lt_sub_iff_left_of_le` for a stronger statement in a linear order. -/
lemma sub_lt_sub_iff_left_of_le_of_le [contravariant_class α α (+) (<)]
(h₁ : b ≤ a) (h₂ : c ≤ a) : a - b < a - c ↔ c < b :=
contravariant.add_le_cancellable.sub_lt_sub_iff_left_of_le_of_le
contravariant.add_le_cancellable h₁ h₂
@[simp] lemma add_sub_sub_cancel' (h : c ≤ a) : (a + b) - (a - c) = b + c :=
contravariant.add_le_cancellable.add_sub_sub_cancel h
/-- See `sub_sub_le` for an inequality. -/
lemma sub_sub_cancel_of_le (h : a ≤ b) : b - (b - a) = a :=
contravariant.add_le_cancellable.sub_sub_cancel_of_le h
end contra
end canonically_ordered_add_monoid
/-! ### Lemmas in a linearly canonically ordered monoid. -/
section canonically_linear_ordered_add_monoid
variables [canonically_linear_ordered_add_monoid α] [has_sub α] [has_ordered_sub α] {a b c d : α}
lemma sub_pos_iff_lt : 0 < a - b ↔ b < a :=
by rw [sub_pos_iff_not_le, not_le]
lemma sub_eq_sub_min (a b : α) : a - b = a - min a b :=
begin
cases le_total a b with h h,
{ rw [min_eq_left h, sub_self', sub_eq_zero_iff_le.mpr h] },
{ rw [min_eq_right h] },
end
namespace add_le_cancellable
protected lemma lt_sub_iff_right (hc : add_le_cancellable c) : a < b - c ↔ a + c < b :=
⟨lt_imp_lt_of_le_imp_le sub_le_iff_right.mpr, hc.lt_sub_of_add_lt_right⟩
protected lemma lt_sub_iff_left (hc : add_le_cancellable c) : a < b - c ↔ c + a < b :=
⟨lt_imp_lt_of_le_imp_le sub_le_iff_left.mpr, hc.lt_sub_of_add_lt_left⟩
protected lemma sub_lt_sub_iff_right (hc : add_le_cancellable c) (h : c ≤ a) :
a - c < b - c ↔ a < b :=
by rw [hc.lt_sub_iff_left, add_sub_cancel_of_le h]
protected lemma lt_sub_iff_lt_sub (ha : add_le_cancellable a) (hc : add_le_cancellable c) :
a < b - c ↔ c < b - a :=
by rw [hc.lt_sub_iff_left, ha.lt_sub_iff_right]
protected lemma sub_lt_self (ha : add_le_cancellable a) (hb : add_le_cancellable b)
(h₁ : 0 < a) (h₂ : 0 < b) : a - b < a :=
begin
refine sub_le_self'.lt_of_ne _,
intro h,
rw [← h, sub_pos_iff_lt] at h₁,
have := h.ge,
rw [hb.le_sub_iff_left h₁.le, ha.add_le_iff_nonpos_left] at this,
exact h₂.not_le this,
end
protected lemma sub_lt_self_iff (ha : add_le_cancellable a) (hb : add_le_cancellable b) :
a - b < a ↔ 0 < a ∧ 0 < b :=
begin
refine ⟨_, λ h, ha.sub_lt_self hb h.1 h.2⟩,
intro h,
refine ⟨(zero_le _).trans_lt h, (zero_le b).lt_of_ne _⟩,
rintro rfl,
rw [sub_zero'] at h,
exact h.false
end
/-- See `lt_sub_iff_left_of_le_of_le` for a weaker statement in a partial order. -/
protected lemma sub_lt_sub_iff_left_of_le (ha : add_le_cancellable a) (hb : add_le_cancellable b)
(h : b ≤ a) : a - b < a - c ↔ c < b :=
lt_iff_lt_of_le_iff_le $ ha.sub_le_sub_iff_left hb h
end add_le_cancellable
section contra
variable [contravariant_class α α (+) (≤)]
/-- See `lt_sub_iff_right_of_le` for a weaker statement in a partial order.
This lemma also holds for `ennreal`, but we need a different proof for that. -/
lemma lt_sub_iff_right : a < b - c ↔ a + c < b :=
contravariant.add_le_cancellable.lt_sub_iff_right
/-- See `lt_sub_iff_left_of_le` for a weaker statement in a partial order.
This lemma also holds for `ennreal`, but we need a different proof for that. -/
lemma lt_sub_iff_left : a < b - c ↔ c + a < b :=
contravariant.add_le_cancellable.lt_sub_iff_left
/-- This lemma also holds for `ennreal`, but we need a different proof for that. -/
lemma sub_lt_sub_iff_right' (h : c ≤ a) : a - c < b - c ↔ a < b :=
contravariant.add_le_cancellable.sub_lt_sub_iff_right h
lemma lt_sub_iff_lt_sub : a < b - c ↔ c < b - a :=
contravariant.add_le_cancellable.lt_sub_iff_lt_sub contravariant.add_le_cancellable
lemma sub_lt_self' (h₁ : 0 < a) (h₂ : 0 < b) : a - b < a :=
contravariant.add_le_cancellable.sub_lt_self contravariant.add_le_cancellable h₁ h₂
lemma sub_lt_self_iff' : a - b < a ↔ 0 < a ∧ 0 < b :=
contravariant.add_le_cancellable.sub_lt_self_iff contravariant.add_le_cancellable
/-- See `lt_sub_iff_left_of_le_of_le` for a weaker statement in a partial order. -/
lemma sub_lt_sub_iff_left_of_le (h : b ≤ a) : a - b < a - c ↔ c < b :=
contravariant.add_le_cancellable.sub_lt_sub_iff_left_of_le contravariant.add_le_cancellable h
end contra
/-! ### Lemmas about `max` and `min`. -/
lemma sub_add_eq_max : a - b + b = max a b :=
begin
cases le_total a b with h h,
{ rw [max_eq_right h, sub_eq_zero_iff_le.mpr h, zero_add] },
{ rw [max_eq_left h, sub_add_cancel_of_le h] }
end
lemma add_sub_eq_max : a + (b - a) = max a b :=
by rw [add_comm, max_comm, sub_add_eq_max]
lemma sub_min : a - min a b = a - b :=
begin
cases le_total a b with h h,
{ rw [min_eq_left h, sub_self', sub_eq_zero_iff_le.mpr h] },
{ rw [min_eq_right h] }
end
lemma sub_add_min : a - b + min a b = a :=
by { rw [← sub_min, sub_add_cancel_of_le], apply min_le_left }
end canonically_linear_ordered_add_monoid
|
27a38995ab87ef0605ca63af6e01f33095fa6c08 | 1a61aba1b67cddccce19532a9596efe44be4285f | /library/init/tactic.lean | 1f16ab20aebd90674999cadc282dc0a797da5a13 | [
"Apache-2.0"
] | permissive | eigengrau/lean | 07986a0f2548688c13ba36231f6cdbee82abf4c6 | f8a773be1112015e2d232661ce616d23f12874d0 | refs/heads/master | 1,610,939,198,566 | 1,441,352,386,000 | 1,441,352,494,000 | 41,903,576 | 0 | 0 | null | 1,441,352,210,000 | 1,441,352,210,000 | null | UTF-8 | Lean | false | false | 6,821 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
This is just a trick to embed the 'tactic language' as a Lean
expression. We should view 'tactic' as automation that when execute
produces a term. tactic.builtin is just a "dummy" for creating the
definitions that are actually implemented in C++
-/
prelude
import init.datatypes init.reserved_notation init.num
inductive tactic :
Type := builtin : tactic
namespace tactic
-- Remark the following names are not arbitrary, the tactic module
-- uses them when converting Lean expressions into actual tactic objects.
-- The bultin 'by' construct triggers the process of converting a
-- a term of type 'tactic' into a tactic that sythesizes a term
definition and_then (t1 t2 : tactic) : tactic := builtin
definition or_else (t1 t2 : tactic) : tactic := builtin
definition append (t1 t2 : tactic) : tactic := builtin
definition interleave (t1 t2 : tactic) : tactic := builtin
definition par (t1 t2 : tactic) : tactic := builtin
definition fixpoint (f : tactic → tactic) : tactic := builtin
definition repeat (t : tactic) : tactic := builtin
definition at_most (t : tactic) (k : num) : tactic := builtin
definition discard (t : tactic) (k : num) : tactic := builtin
definition focus_at (t : tactic) (i : num) : tactic := builtin
definition try_for (t : tactic) (ms : num) : tactic := builtin
definition all_goals (t : tactic) : tactic := builtin
definition now : tactic := builtin
definition assumption : tactic := builtin
definition eassumption : tactic := builtin
definition state : tactic := builtin
definition fail : tactic := builtin
definition id : tactic := builtin
definition beta : tactic := builtin
definition info : tactic := builtin
definition whnf : tactic := builtin
definition contradiction : tactic := builtin
definition exfalso : tactic := builtin
definition congruence : tactic := builtin
definition rotate_left (k : num) := builtin
definition rotate_right (k : num) := builtin
definition rotate (k : num) := rotate_left k
-- This is just a trick to embed expressions into tactics.
-- The nested expressions are "raw". They tactic should
-- elaborate them when it is executed.
inductive expr : Type :=
builtin : expr
inductive expr_list : Type :=
| nil : expr_list
| cons : expr → expr_list → expr_list
-- auxiliary type used to mark optional list of arguments
definition opt_expr_list := expr_list
-- auxiliary types used to mark that the expression is suppose to be an identifier, optional, or a list.
definition identifier := expr
definition identifier_list := expr_list
definition opt_identifier_list := expr_list
-- Marker for instructing the parser to parse it as '?(using <expr>)'
definition using_expr := expr
-- Constant used to denote the case were no expression was provided
definition none_expr : expr := expr.builtin
definition apply (e : expr) : tactic := builtin
definition eapply (e : expr) : tactic := builtin
definition fapply (e : expr) : tactic := builtin
definition rename (a b : identifier) : tactic := builtin
definition intro (e : identifier_list) : tactic := builtin
definition generalize_tac (e : expr) (id : identifier) : tactic := builtin
definition clear (e : identifier_list) : tactic := builtin
definition revert (e : identifier_list) : tactic := builtin
definition refine (e : expr) : tactic := builtin
definition exact (e : expr) : tactic := builtin
-- Relaxed version of exact that does not enforce goal type
definition rexact (e : expr) : tactic := builtin
definition check_expr (e : expr) : tactic := builtin
definition trace (s : string) : tactic := builtin
-- rewrite_tac is just a marker for the builtin 'rewrite' notation
-- used to create instances of this tactic.
definition rewrite_tac (e : expr_list) : tactic := builtin
definition xrewrite_tac (e : expr_list) : tactic := builtin
definition krewrite_tac (e : expr_list) : tactic := builtin
-- simp_tac is just a marker for the builtin 'simp' notation
-- used to create instances of this tactic.
-- Arguments:
-- - e : additional rewrites to be considered
-- - n : add rewrites from the give namespaces
-- - x : exclude the give global rewrites
-- - t : tactic for discharging conditions
-- - l : location
definition simp_tac (e : expr_list) (n : identifier_list) (x : identifier_list) (t : option tactic) (l : expr) : tactic := builtin
-- with_options_tac is just a marker for the builtin 'with_options' notation
definition with_options_tac (o : expr) (t : tactic) : tactic := builtin
definition cases (h : expr) (ids : opt_identifier_list) : tactic := builtin
definition induction (h : expr) (rec : using_expr) (ids : opt_identifier_list) : tactic := builtin
definition intros (ids : opt_identifier_list) : tactic := builtin
definition generalizes (es : expr_list) : tactic := builtin
definition clears (ids : identifier_list) : tactic := builtin
definition reverts (ids : identifier_list) : tactic := builtin
definition change (e : expr) : tactic := builtin
definition assert_hypothesis (id : identifier) (e : expr) : tactic := builtin
definition lettac (id : identifier) (e : expr) : tactic := builtin
definition constructor (k : option num) : tactic := builtin
definition fconstructor (k : option num) : tactic := builtin
definition existsi (e : expr) : tactic := builtin
definition split : tactic := builtin
definition left : tactic := builtin
definition right : tactic := builtin
definition injection (e : expr) (ids : opt_identifier_list) : tactic := builtin
definition subst (ids : identifier_list) : tactic := builtin
definition substvars : tactic := builtin
definition reflexivity : tactic := builtin
definition symmetry : tactic := builtin
definition transitivity (e : expr) : tactic := builtin
definition try (t : tactic) : tactic := or_else t id
definition repeat1 (t : tactic) : tactic := and_then t (repeat t)
definition focus (t : tactic) : tactic := focus_at t 0
definition determ (t : tactic) : tactic := at_most t 1
definition trivial : tactic := or_else (or_else (apply eq.refl) (apply true.intro)) assumption
definition do (n : num) (t : tactic) : tactic :=
nat.rec id (λn t', and_then t t') (nat.of_num n)
end tactic
tactic_infixl `;`:15 := tactic.and_then
tactic_notation T1 `:`:15 T2 := tactic.focus (tactic.and_then T1 (tactic.all_goals T2))
tactic_notation `(` h `|` r:(foldl `|` (e r, tactic.or_else r e) h) `)` := r
|
fae63d8bcd760c46549a73423594b60f531f2b97 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /tests/bench/rbmap500k.lean | e1ef3f43d70b13102f65f998b5c5f90a9cbd92b0 | [
"Apache-2.0"
] | permissive | mhuisi/lean4 | 28d35a4febc2e251c7f05492e13f3b05d6f9b7af | dda44bc47f3e5d024508060dac2bcb59fd12e4c0 | refs/heads/master | 1,621,225,489,283 | 1,585,142,689,000 | 1,585,142,689,000 | 250,590,438 | 0 | 2 | Apache-2.0 | 1,602,443,220,000 | 1,585,327,814,000 | C | UTF-8 | Lean | false | false | 2,838 | 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
-/
prelude
import init.coe init.data.option.basic init.system.io
universes u v w w'
inductive color
| Red | Black
inductive Tree
| Leaf {} : Tree
| Node (color : color) (lchild : Tree) (key : Nat) (val : Bool) (rchild : Tree) : Tree
variables {σ : Type w}
open color Nat Tree
def fold (f : Nat → Bool → σ → σ) : Tree → σ → σ
| Leaf, b => b
| Node _ l k v r, b => fold r (f k v (fold l b))
@[inline]
def balance1 : Nat → Bool → Tree → Tree → Tree
| kv, vv, t, Node _ (Node Red l kx vx r₁) ky vy r₂ => Node Red (Node Black l kx vx r₁) ky vy (Node Black r₂ kv vv t)
| kv, vv, t, Node _ l₁ ky vy (Node Red l₂ kx vx r) => Node Red (Node Black l₁ ky vy l₂) kx vx (Node Black r kv vv t)
| kv, vv, t, Node _ l ky vy r => Node Black (Node Red l ky vy r) kv vv t
| _, _, _, _ => Leaf
@[inline]
def balance2 : Tree → Nat → Bool → Tree → Tree
| t, kv, vv, Node _ (Node Red l kx₁ vx₁ r₁) ky vy r₂ => Node Red (Node Black t kv vv l) kx₁ vx₁ (Node Black r₁ ky vy r₂)
| t, kv, vv, Node _ l₁ ky vy (Node Red l₂ kx₂ vx₂ r₂) => Node Red (Node Black t kv vv l₁) ky vy (Node Black l₂ kx₂ vx₂ r₂)
| t, kv, vv, Node _ l ky vy r => Node Black t kv vv (Node Red l ky vy r)
| _, _, _, _ => Leaf
def isRed : Tree → Bool
| Node Red _ _ _ _ => true
| _ => false
def ins : Tree → Nat → Bool → Tree
| Leaf, kx, vx => Node Red Leaf kx vx Leaf
| Node Red a ky vy b, kx, vx =>
(if kx < ky then Node Red (ins a kx vx) ky vy b
else if kx = ky then Node Red a kx vx b
else Node Red a ky vy (ins b kx vx))
| Node Black a ky vy b, kx, vx =>
if kx < ky then
(if isRed a then balance1 ky vy b (ins a kx vx)
else Node Black (ins a kx vx) ky vy b)
else if kx = ky then Node Black a kx vx b
else if isRed b then balance2 a ky vy (ins b kx vx)
else Node Black a ky vy (ins b kx vx)
def setBlack : Tree → Tree
| Node _ l k v r => Node Black l k v r
| e => e
def insert (t : Tree) (k : Nat) (v : Bool) : Tree :=
if isRed t then setBlack (ins t k v)
else ins t k v
def mkMapAux : Nat → Tree → Tree
| 0, m => m
| n+1, m => mkMapAux n (insert m n (n % 10 = 0))
def mkMap (n : Nat) :=
mkMapAux n Leaf
def main (xs : List String) : IO UInt32 :=
let m := mkMap 500000;
let v := fold (fun (k : Nat) (v : Bool) (r : Nat) => if v then r + 1 else r) m 0;
IO.println (toString v) *>
pure 0
|
9d861dee5a561c9c5a5ed4e90468927ab453f9db | ba4794a0deca1d2aaa68914cd285d77880907b5c | /src/game/world8/level4.lean | 6700729952b38f934d02006d3cef71e869373b26 | [
"Apache-2.0"
] | permissive | ChrisHughes24/natural_number_game | c7c00aa1f6a95004286fd456ed13cf6e113159ce | 9d09925424da9f6275e6cfe427c8bcf12bb0944f | refs/heads/master | 1,600,715,773,528 | 1,573,910,462,000 | 1,573,910,462,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,013 | lean | import mynat.definition -- hide
import mynat.add -- hide
import game.world8.level3 -- hide
namespace mynat -- hide
/-
# Advanced Addition World
## Level 4: `eq_iff_succ_eq_succ`
Here is an `iff` goal. You can split it into two goals (the implications in both
directions) using the `split` tactic, which is how you're going to have to start.
`split,`
Now you have two goals. The first is exactly `succ_inj` so you can close
it with
`exact succ_inj,`
and the second one you could solve by looking up the name of the theorem
you proved in the last level and doing `exact <that name>`, or alternatively
you could get some more `intro` practice and seeing if you can prove it
using `intro`, `rw` and `refl`.
-/
/- Theorem
Two natural numbers are equal if and only if their successors are equal.
-/
theorem succ_eq_succ_iff (a b : mynat) : succ a = succ b ↔ a = b :=
begin [less_leaky]
split,
{ exact succ_inj},
-- exact succ_eq_succ_of_eq,
{ intro H,
rw H,
refl,
}
end
end mynat -- hide
|
1190f603fb29a016c611d6085bb6a01fa73dfc6f | 853df553b1d6ca524e3f0a79aedd32dde5d27ec3 | /src/ring_theory/ideals.lean | 98d3a6be84a18b6c7a534d0c1b6da36059d1919b | [
"Apache-2.0"
] | permissive | DanielFabian/mathlib | efc3a50b5dde303c59eeb6353ef4c35a345d7112 | f520d07eba0c852e96fe26da71d85bf6d40fcc2a | refs/heads/master | 1,668,739,922,971 | 1,595,201,756,000 | 1,595,201,756,000 | 279,469,476 | 0 | 0 | null | 1,594,696,604,000 | 1,594,696,604,000 | null | UTF-8 | Lean | false | false | 20,092 | 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 algebra.associated
import algebra.pointwise
import linear_algebra.basic
import order.zorn
universes u v
variables {α : Type u} {β : Type v} {a b : α}
open set function
open_locale classical big_operators
namespace ideal
variables [comm_ring α] (I : ideal α)
@[ext] lemma ext {I J : ideal α} (h : ∀ x, x ∈ I ↔ x ∈ J) : I = J :=
submodule.ext h
theorem eq_top_of_unit_mem
(x y : α) (hx : x ∈ I) (h : y * x = 1) : I = ⊤ :=
eq_top_iff.2 $ λ z _, calc
z = z * (y * x) : by simp [h]
... = (z * y) * x : eq.symm $ mul_assoc z y x
... ∈ I : I.mul_mem_left hx
theorem eq_top_of_is_unit_mem {x} (hx : x ∈ I) (h : is_unit x) : I = ⊤ :=
let ⟨y, hy⟩ := is_unit_iff_exists_inv'.1 h in eq_top_of_unit_mem I x y hx hy
theorem eq_top_iff_one : I = ⊤ ↔ (1:α) ∈ I :=
⟨by rintro rfl; trivial,
λ h, eq_top_of_unit_mem _ _ 1 h (by simp)⟩
theorem ne_top_iff_one : I ≠ ⊤ ↔ (1:α) ∉ I :=
not_congr I.eq_top_iff_one
/-- The ideal generated by a subset of a ring -/
def span (s : set α) : ideal α := submodule.span α s
lemma subset_span {s : set α} : s ⊆ span s := submodule.subset_span
lemma span_le {s : set α} {I} : span s ≤ I ↔ s ⊆ I := submodule.span_le
lemma span_mono {s t : set α} : s ⊆ t → span s ≤ span t := submodule.span_mono
@[simp] lemma span_eq : span (I : set α) = I := submodule.span_eq _
@[simp] lemma span_singleton_one : span (1 : set α) = ⊤ :=
(eq_top_iff_one _).2 $ subset_span $ mem_singleton _
lemma mem_span_insert {s : set α} {x y} :
x ∈ span (insert y s) ↔ ∃ a (z ∈ span s), x = a * y + z := submodule.mem_span_insert
lemma mem_span_insert' {s : set α} {x y} :
x ∈ span (insert y s) ↔ ∃a, x + a * y ∈ span s := submodule.mem_span_insert'
lemma mem_span_singleton' {x y : α} :
x ∈ span ({y} : set α) ↔ ∃ a, a * y = x := submodule.mem_span_singleton
lemma mem_span_singleton {x y : α} :
x ∈ span ({y} : set α) ↔ y ∣ x :=
mem_span_singleton'.trans $ exists_congr $ λ _, by rw [eq_comm, mul_comm]
lemma span_singleton_le_span_singleton {x y : α} :
span ({x} : set α) ≤ span ({y} : set α) ↔ y ∣ x :=
span_le.trans $ singleton_subset_iff.trans mem_span_singleton
lemma span_eq_bot {s : set α} : span s = ⊥ ↔ ∀ x ∈ s, (x:α) = 0 := submodule.span_eq_bot
lemma span_singleton_eq_bot {x} : span ({x} : set α) = ⊥ ↔ x = 0 := submodule.span_singleton_eq_bot
lemma span_singleton_eq_top {x} : span ({x} : set α) = ⊤ ↔ is_unit x :=
by rw [is_unit_iff_dvd_one, ← span_singleton_le_span_singleton, singleton_one, span_singleton_one,
eq_top_iff]
/-- An ideal `P` of a ring `R` is prime if `P ≠ R` and `xy ∈ P → x ∈ P ∨ y ∈ P` -/
@[class] def is_prime (I : ideal α) : Prop :=
I ≠ ⊤ ∧ ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I
theorem is_prime.mem_or_mem {I : ideal α} (hI : I.is_prime) :
∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I := hI.2
theorem is_prime.mem_or_mem_of_mul_eq_zero {I : ideal α} (hI : I.is_prime)
{x y : α} (h : x * y = 0) : x ∈ I ∨ y ∈ I :=
hI.2 (h.symm ▸ I.zero_mem)
theorem is_prime.mem_of_pow_mem {I : ideal α} (hI : I.is_prime)
{r : α} (n : ℕ) (H : r^n ∈ I) : r ∈ I :=
begin
induction n with n ih,
{ exact (mt (eq_top_iff_one _).2 hI.1).elim H },
exact or.cases_on (hI.mem_or_mem H) id ih
end
theorem zero_ne_one_of_proper {I : ideal α} (h : I ≠ ⊤) : (0:α) ≠ 1 :=
λ hz, I.ne_top_iff_one.1 h $ hz ▸ I.zero_mem
theorem span_singleton_prime {p : α} (hp : p ≠ 0) :
is_prime (span ({p} : set α)) ↔ prime p :=
by simp [is_prime, prime, span_singleton_eq_top, hp, mem_span_singleton]
/-- An ideal is maximal if it is maximal in the collection of proper ideals. -/
@[class] def is_maximal (I : ideal α) : Prop :=
I ≠ ⊤ ∧ ∀ J, I < J → J = ⊤
theorem is_maximal_iff {I : ideal α} : I.is_maximal ↔
(1:α) ∉ I ∧ ∀ (J : ideal α) x, I ≤ J → x ∉ I → x ∈ J → (1:α) ∈ J :=
and_congr I.ne_top_iff_one $ forall_congr $ λ J,
by rw [lt_iff_le_not_le]; exact
⟨λ H x h hx₁ hx₂, J.eq_top_iff_one.1 $
H ⟨h, not_subset.2 ⟨_, hx₂, hx₁⟩⟩,
λ H ⟨h₁, h₂⟩, let ⟨x, xJ, xI⟩ := not_subset.1 h₂ in
J.eq_top_iff_one.2 $ H x h₁ xI xJ⟩
theorem is_maximal.eq_of_le {I J : ideal α}
(hI : I.is_maximal) (hJ : J ≠ ⊤) (IJ : I ≤ J) : I = J :=
eq_iff_le_not_lt.2 ⟨IJ, λ h, hJ (hI.2 _ h)⟩
theorem is_maximal.exists_inv {I : ideal α}
(hI : I.is_maximal) {x} (hx : x ∉ I) : ∃ y, y * x - 1 ∈ I :=
begin
cases is_maximal_iff.1 hI with H₁ H₂,
rcases mem_span_insert'.1 (H₂ (span (insert x I)) x
(set.subset.trans (subset_insert _ _) subset_span)
hx (subset_span (mem_insert _ _))) with ⟨y, hy⟩,
rw [span_eq, ← neg_mem_iff, add_comm, neg_add', neg_mul_eq_neg_mul] at hy,
exact ⟨-y, hy⟩
end
theorem is_maximal.is_prime {I : ideal α} (H : I.is_maximal) : I.is_prime :=
⟨H.1, λ x y hxy, or_iff_not_imp_left.2 $ λ hx, begin
cases H.exists_inv hx with z hz,
have := I.mul_mem_left hz,
rw [mul_sub, mul_one, mul_comm, mul_assoc] at this,
exact I.neg_mem_iff.1 ((I.add_mem_iff_right $ I.mul_mem_left hxy).1 this)
end⟩
@[priority 100] -- see Note [lower instance priority]
instance is_maximal.is_prime' (I : ideal α) : ∀ [H : I.is_maximal], I.is_prime := is_maximal.is_prime
theorem exists_le_maximal (I : ideal α) (hI : I ≠ ⊤) :
∃ M : ideal α, M.is_maximal ∧ I ≤ M :=
begin
rcases zorn.zorn_partial_order₀ { J : ideal α | J ≠ ⊤ } _ I hI with ⟨M, M0, IM, h⟩,
{ refine ⟨M, ⟨M0, λ J hJ, by_contradiction $ λ J0, _⟩, IM⟩,
cases h J J0 (le_of_lt hJ), exact lt_irrefl _ hJ },
{ intros S SC cC I IS,
refine ⟨Sup S, λ H, _, λ _, le_Sup⟩,
obtain ⟨J, JS, J0⟩ : ∃ J ∈ S, (1 : α) ∈ J,
from (submodule.mem_Sup_of_directed ⟨I, IS⟩ cC.directed_on).1 ((eq_top_iff_one _).1 H),
exact SC JS ((eq_top_iff_one _).2 J0) }
end
theorem mem_span_pair {x y z : α} :
z ∈ span ({x, y} : set α) ↔ ∃ a b, a * x + b * y = z :=
by simp [mem_span_insert, mem_span_singleton', @eq_comm _ _ z]
lemma span_singleton_lt_span_singleton [integral_domain β] {x y : β} :
span ({x} : set β) < span ({y} : set β) ↔ y ≠ 0 ∧ ∃ d : β, ¬ is_unit d ∧ x = y * d :=
by rw [lt_iff_le_not_le, span_singleton_le_span_singleton, span_singleton_le_span_singleton,
dvd_and_not_dvd_iff]
lemma factors_decreasing [integral_domain β] (b₁ b₂ : β) (h₁ : b₁ ≠ 0) (h₂ : ¬ is_unit b₂) :
span ({b₁ * b₂} : set β) < span {b₁} :=
lt_of_le_not_le (ideal.span_le.2 $ singleton_subset_iff.2 $
ideal.mem_span_singleton.2 ⟨b₂, rfl⟩) $ λ h,
h₂ $ is_unit_of_dvd_one _ $ (mul_dvd_mul_iff_left h₁).1 $
by rwa [mul_one, ← ideal.span_singleton_le_span_singleton]
/-- The quotient `R/I` of a ring `R` by an ideal `I`. -/
def quotient (I : ideal α) := I.quotient
namespace quotient
variables {I} {x y : α}
/-- The map from a ring `R` to a quotient ring `R/I`. -/
def mk (I : ideal α) (a : α) : I.quotient := submodule.quotient.mk a
instance : inhabited (quotient I) := ⟨mk I 37⟩
protected theorem eq : mk I x = mk I y ↔ x - y ∈ I := submodule.quotient.eq I
instance (I : ideal α) : has_one I.quotient := ⟨mk I 1⟩
@[simp] lemma mk_one (I : ideal α) : mk I 1 = 1 := rfl
instance (I : ideal α) : has_mul I.quotient :=
⟨λ a b, quotient.lift_on₂' a b (λ a b, mk I (a * b)) $
λ a₁ a₂ b₁ b₂ h₁ h₂, quot.sound $ begin
refine calc a₁ * a₂ - b₁ * b₂ = a₂ * (a₁ - b₁) + (a₂ - b₂) * b₁ : _
... ∈ I : I.add_mem (I.mul_mem_left h₁) (I.mul_mem_right h₂),
rw [mul_sub, sub_mul, sub_add_sub_cancel, mul_comm, mul_comm b₁]
end⟩
@[simp] theorem mk_mul : mk I (x * y) = mk I x * mk I y := rfl
instance (I : ideal α) : comm_ring I.quotient :=
{ mul := (*),
one := 1,
mul_assoc := λ a b c, quotient.induction_on₃' a b c $
λ a b c, congr_arg (mk _) (mul_assoc a b c),
mul_comm := λ a b, quotient.induction_on₂' a b $
λ a b, congr_arg (mk _) (mul_comm a b),
one_mul := λ a, quotient.induction_on' a $
λ a, congr_arg (mk _) (one_mul a),
mul_one := λ a, quotient.induction_on' a $
λ a, congr_arg (mk _) (mul_one a),
left_distrib := λ a b c, quotient.induction_on₃' a b c $
λ a b c, congr_arg (mk _) (left_distrib a b c),
right_distrib := λ a b c, quotient.induction_on₃' a b c $
λ a b c, congr_arg (mk _) (right_distrib a b c),
..submodule.quotient.add_comm_group I }
/-- `ideal.quotient.mk` as a `ring_hom` -/
def mk_hom (I : ideal α) : α →+* I.quotient := ⟨mk I, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩
lemma mk_eq_mk_hom (I : ideal α) (x : α) : ideal.quotient.mk I x = ideal.quotient.mk_hom I x := rfl
/-- The image of an ideal J under the quotient map `R → R/I`. -/
def map_mk (I J : ideal α) : ideal I.quotient :=
{ carrier := mk I '' J,
zero_mem' := ⟨0, J.zero_mem, rfl⟩,
add_mem' := by rintro _ _ ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩;
exact ⟨x + y, J.add_mem hx hy, rfl⟩,
smul_mem' := by rintro ⟨c⟩ _ ⟨x, hx, rfl⟩;
exact ⟨c * x, J.mul_mem_left hx, rfl⟩ }
@[simp] lemma mk_zero (I : ideal α) : mk I 0 = 0 := rfl
@[simp] lemma mk_add (I : ideal α) (a b : α) : mk I (a + b) = mk I a + mk I b := rfl
@[simp] lemma mk_neg (I : ideal α) (a : α) : mk I (-a : α) = -mk I a := rfl
@[simp] lemma mk_sub (I : ideal α) (a b : α) : mk I (a - b : α) = mk I a - mk I b := rfl
@[simp] lemma mk_pow (I : ideal α) (a : α) (n : ℕ) : mk I (a ^ n : α) = mk I a ^ n :=
(mk_hom I).map_pow a n
lemma mk_prod {ι} (I : ideal α) (s : finset ι) (f : ι → α) :
mk I (∏ i in s, f i) = ∏ i in s, mk I (f i) :=
(mk_hom I).map_prod f s
lemma mk_sum {ι} (I : ideal α) (s : finset ι) (f : ι → α) :
mk I (∑ i in s, f i) = ∑ i in s, mk I (f i) :=
(mk_hom I).map_sum f s
lemma eq_zero_iff_mem {I : ideal α} : mk I a = 0 ↔ a ∈ I :=
by conv {to_rhs, rw ← sub_zero a }; exact quotient.eq'
theorem zero_eq_one_iff {I : ideal α} : (0 : I.quotient) = 1 ↔ I = ⊤ :=
eq_comm.trans $ eq_zero_iff_mem.trans (eq_top_iff_one _).symm
theorem zero_ne_one_iff {I : ideal α} : (0 : I.quotient) ≠ 1 ↔ I ≠ ⊤ :=
not_congr zero_eq_one_iff
protected theorem nontrivial {I : ideal α} (hI : I ≠ ⊤) : nontrivial I.quotient :=
⟨⟨0, 1, zero_ne_one_iff.2 hI⟩⟩
instance (I : ideal α) [hI : I.is_prime] : integral_domain I.quotient :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ a b,
quotient.induction_on₂' a b $ λ a b hab,
(hI.mem_or_mem (eq_zero_iff_mem.1 hab)).elim
(or.inl ∘ eq_zero_iff_mem.2)
(or.inr ∘ eq_zero_iff_mem.2),
.. quotient.comm_ring I,
.. quotient.nontrivial hI.1 }
lemma exists_inv {I : ideal α} [hI : I.is_maximal] :
∀ {a : I.quotient}, a ≠ 0 → ∃ b : I.quotient, a * b = 1 :=
begin
rintro ⟨a⟩ h,
cases hI.exists_inv (mt eq_zero_iff_mem.2 h) with b hb,
rw [mul_comm] at hb,
exact ⟨mk _ b, quot.sound hb⟩
end
/-- quotient by maximal ideal is a field. def rather than instance, since users will have
computable inverses in some applications -/
protected noncomputable def field (I : ideal α) [hI : I.is_maximal] : field I.quotient :=
{ inv := λ a, if ha : a = 0 then 0 else classical.some (exists_inv ha),
mul_inv_cancel := λ a (ha : a ≠ 0), show a * dite _ _ _ = _,
by rw dif_neg ha;
exact classical.some_spec (exists_inv ha),
inv_zero := dif_pos rfl,
..quotient.integral_domain I }
variable [comm_ring β]
/-- Given a ring homomorphism `f : α →+* β` sending all elements of an ideal to zero,
lift it to the quotient by this ideal. -/
def lift (S : ideal α) (f : α →+* β) (H : ∀ (a : α), a ∈ S → f a = 0) :
quotient S →+* β :=
{ to_fun := λ x, quotient.lift_on' x f $ λ (a b) (h : _ ∈ _),
eq_of_sub_eq_zero $ by rw [← f.map_sub, H _ h],
map_one' := f.map_one,
map_zero' := f.map_zero,
map_add' := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ f.map_add,
map_mul' := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ f.map_mul }
@[simp] lemma lift_mk (S : ideal α) (f : α →+* β) (H : ∀ (a : α), a ∈ S → f a = 0) :
lift S f H (mk S a) = f a := rfl
end quotient
section lattice
variables {R : Type u} [comm_ring R]
theorem mem_Inf {s : set (ideal R)} {x : R} :
x ∈ Inf s ↔ ∀ ⦃I⦄, I ∈ s → x ∈ I :=
⟨λ hx I his, hx I ⟨I, infi_pos his⟩, λ H I ⟨J, hij⟩, hij ▸ λ S ⟨hj, hS⟩, hS ▸ H hj⟩
end lattice
/-- All ideals in a field are trivial. -/
lemma eq_bot_or_top {K : Type u} [field K] (I : ideal K) :
I = ⊥ ∨ I = ⊤ :=
begin
rw classical.or_iff_not_imp_right,
change _ ≠ _ → _,
rw ideal.ne_top_iff_one,
intro h1,
rw eq_bot_iff,
intros r hr,
by_cases H : r = 0, {simpa},
simpa [H, h1] using submodule.smul_mem I r⁻¹ hr,
end
lemma eq_bot_of_prime {K : Type u} [field K] (I : ideal K) [h : I.is_prime] :
I = ⊥ :=
classical.or_iff_not_imp_right.mp I.eq_bot_or_top h.1
end ideal
/-- The set of non-invertible elements of a monoid. -/
def nonunits (α : Type u) [monoid α] : set α := { a | ¬is_unit a }
@[simp] theorem mem_nonunits_iff [comm_monoid α] : a ∈ nonunits α ↔ ¬ is_unit a := iff.rfl
theorem mul_mem_nonunits_right [comm_monoid α] :
b ∈ nonunits α → a * b ∈ nonunits α :=
mt is_unit_of_mul_is_unit_right
theorem mul_mem_nonunits_left [comm_monoid α] :
a ∈ nonunits α → a * b ∈ nonunits α :=
mt is_unit_of_mul_is_unit_left
theorem zero_mem_nonunits [semiring α] : 0 ∈ nonunits α ↔ (0:α) ≠ 1 :=
not_congr is_unit_zero_iff
@[simp] theorem one_not_mem_nonunits [monoid α] : (1:α) ∉ nonunits α :=
not_not_intro is_unit_one
theorem coe_subset_nonunits [comm_ring α] {I : ideal α} (h : I ≠ ⊤) :
(I : set α) ⊆ nonunits α :=
λ x hx hu, h $ I.eq_top_of_is_unit_mem hx hu
lemma exists_max_ideal_of_mem_nonunits [comm_ring α] (h : a ∈ nonunits α) :
∃ I : ideal α, I.is_maximal ∧ a ∈ I :=
begin
have : ideal.span ({a} : set α) ≠ ⊤,
{ intro H, rw ideal.span_singleton_eq_top at H, contradiction },
rcases ideal.exists_le_maximal _ this with ⟨I, Imax, H⟩,
use [I, Imax], apply H, apply ideal.subset_span, exact set.mem_singleton a
end
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A commutative ring is local if it has a unique maximal ideal. Note that
`local_ring` is a predicate. -/
class local_ring (α : Type u) [comm_ring α] extends nontrivial α : Prop :=
(is_local : ∀ (a : α), (is_unit a) ∨ (is_unit (1 - a)))
end prio
namespace local_ring
variables [comm_ring α] [local_ring α]
lemma is_unit_or_is_unit_one_sub_self (a : α) :
(is_unit a) ∨ (is_unit (1 - a)) :=
is_local a
lemma is_unit_of_mem_nonunits_one_sub_self (a : α) (h : (1 - a) ∈ nonunits α) :
is_unit a :=
or_iff_not_imp_right.1 (is_local a) h
lemma is_unit_one_sub_self_of_mem_nonunits (a : α) (h : a ∈ nonunits α) :
is_unit (1 - a) :=
or_iff_not_imp_left.1 (is_local a) h
lemma nonunits_add {x y} (hx : x ∈ nonunits α) (hy : y ∈ nonunits α) :
x + y ∈ nonunits α :=
begin
rintros ⟨u, hu⟩,
apply hy,
suffices : is_unit ((↑u⁻¹ : α) * y),
{ rcases this with ⟨s, hs⟩,
use u * s,
convert congr_arg (λ z, (u : α) * 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⁻¹ : α) * 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 (α)
/-- The ideal of elements that are not units. -/
def maximal_ideal : ideal α :=
{ carrier := nonunits α,
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 α).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.smul_mem ↑u⁻¹ H }
end
lemma max_ideal_unique :
∃! I : ideal α, I.is_maximal :=
⟨maximal_ideal α, maximal_ideal.is_maximal α,
λ I hI, hI.eq_of_le (maximal_ideal.is_maximal α).1 $
λ x hx, hI.1 ∘ I.eq_top_of_is_unit_mem hx⟩
variable {α}
@[simp] lemma mem_maximal_ideal (x) :
x ∈ maximal_ideal α ↔ x ∈ nonunits α := iff.rfl
end local_ring
lemma local_of_nonunits_ideal [comm_ring α] (hnze : (0:α) ≠ 1)
(h : ∀ x y ∈ nonunits α, x + y ∈ nonunits α) : local_ring α :=
{ 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 α] (h : ∃! I : ideal α, I.is_maximal) :
local_ring α :=
local_of_nonunits_ideal
(let ⟨I, Imax, _⟩ := h in (λ (H : 0 = 1), Imax.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 $ I.eq_top_of_is_unit_mem (I.add_mem xmemI ymemI) H
section prio
set_option default_priority 100 -- see Note [default priority]
/-- 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 α] [semiring β] (f : α →+* β) : Prop :=
(map_nonunit : ∀ a, is_unit (f a) → is_unit a)
end prio
@[simp] lemma is_unit_of_map_unit [semiring α] [semiring β] (f : α →+* β) [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 α] [semiring β] (f : α →+* β) [h : is_local_ring_hom f] {x : α}
(hfx : irreducible (f x)) : irreducible x :=
⟨λ h, hfx.1 $ is_unit.map f.to_monoid_hom h, λ p q hx, let ⟨H⟩ := h in
or.imp (H p) (H q) $ hfx.2 _ _ $ f.map_mul p q ▸ congr_arg f hx⟩
section
open local_ring
variables [comm_ring α] [local_ring α] [comm_ring β] [local_ring β]
variables (f : α →+* β) [is_local_ring_hom f]
lemma map_nonunit (a) (h : a ∈ maximal_ideal α) : f a ∈ maximal_ideal β :=
λ H, h $ is_unit_of_map_unit f a H
end
namespace local_ring
variables [comm_ring α] [local_ring α] [comm_ring β] [local_ring β]
variable (α)
/-- The residue field of a local ring is the quotient of the ring by its maximal ideal. -/
def residue_field := (maximal_ideal α).quotient
noncomputable instance residue_field.field : field (residue_field α) :=
ideal.quotient.field (maximal_ideal α)
noncomputable instance : inhabited (residue_field α) := ⟨37⟩
/-- The quotient map from a local ring to its residue field. -/
def residue : α →+* (residue_field α) :=
ideal.quotient.mk_hom _
namespace residue_field
variables {α β}
/-- The map on residue fields induced by a local homomorphism between local rings -/
noncomputable def map (f : α →+* β) [is_local_ring_hom f] :
residue_field α →+* residue_field β :=
ideal.quotient.lift (maximal_ideal α) ((ideal.quotient.mk_hom _).comp f) $
λ a ha,
begin
erw ideal.quotient.eq_zero_iff_mem,
exact map_nonunit f a ha
end
end residue_field
end local_ring
namespace field
variables [field α]
@[priority 100] -- see Note [lower instance priority]
instance : local_ring α :=
{ is_local := λ a,
if h : a = 0
then or.inr (by rw [h, sub_zero]; exact is_unit_one)
else or.inl $ is_unit_of_mul_eq_one a a⁻¹ $ div_self h }
end field
|
9694589225352465241d6098b5d58c52ad683563 | eeee7bfb5e0033ce2c5099a3cf5c87a3c71b1f62 | /src/adic_space.lean | 8fa53e9dce6b4734426b77438344b463973cfe4e | [
"Apache-2.0"
] | permissive | jesse-michael-han/lean-perfectoid-spaces | f0c652bc1a0de64de90bb8c98f26d9579b226a9c | 45b42a5302dca28910ae9c6e3847c025e5ba4180 | refs/heads/master | 1,584,646,248,214 | 1,528,569,065,000 | 1,528,569,065,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,797 | lean | import for_mathlib.prime
import for_mathlib.is_cover
import analysis.topology.topological_structures
import data.nat.prime
import algebra.group_power
import for_mathlib.presheaves
import for_mathlib.topology
open nat function
variables (R : Type) [comm_ring R] [topological_space R] [topological_ring R]
-- Scholze : "Recall that a topological ring R is Tate if it contains an
-- open and bounded subring R0 ⊂ R and a topologically nilpotent unit pi ∈ R; such elements are
-- called pseudo-uniformizers.""
-- we need definitions of bounded subsete and topologically nilpotent -- and do we have unit? Probably.
class Tate_ring (R : Type) extends comm_ring R, topological_space R, topological_ring R :=
(unfinished : sorry)
-- f-adic rings are called Huber rings by Scholze.
-- Topological ring A contains on open subring A0 such that the subspace topology on A0 is
-- I-adic, where I is a finitely generated ideal of A0 .
class Huber_ring (R : Type) extends comm_ring R, topological_space R, topological_ring R :=
(unfinished2 : sorry)
-- TODO should have an instance going from Tate to Huber
-- peredicates we need for topological rings
definition is_complete (R : Type) [topological_space R] [comm_ring R] [topological_ring R] : Prop := sorry
definition is_uniform (R : Type) : Prop := sorry
definition is_bounded {R : Type} [topological_space R] [comm_ring R] [topological_ring R]
(U : set R) : Prop := sorry
definition is_power_bounded {R : Type} (r : R) : Prop := sorry
definition power_bounded_subring (R : Type) := {r : R // is_power_bounded r}
instance subring_to_ring (R : Type) : has_coe (power_bounded_subring R) R := ⟨subtype.val⟩
instance power_bounded_subring_is_ring (R : Type) : comm_ring (power_bounded_subring R) := sorry
theorem p_is_power_bounded (R : Type) [p : Prime] : is_power_bounded (p : power_bounded_subring R) := sorry
definition is_pseudo_uniformizer {R : Type} : R → Prop := sorry
definition is_subring {R : Type} [comm_ring R] : set R → Prop := sorry
definition is_integrally_closed {R : Type} [comm_ring R] : set R → Prop := sorry
-- Wedhorn Def 7.14
structure is_ring_of_integral_elements {R : Type} [Huber_ring R] (Rplus : set R) : Prop :=
[is_subring : is_subring Rplus]
(is_open : is_open Rplus)
(is_int_closed : is_integrally_closed Rplus)
(is_power_bounded : Rplus ⊆ { r : R | is_power_bounded r})
-- a Huber Ring is an f-adic ring.
-- a Huber Pair is what Huber called an Affinoid Ring.
structure Huber_pair :=
(R : Type)
[RHuber : Huber_ring R]
(Rplus : set R)
[intel : is_ring_of_integral_elements Rplus]
instance : has_coe_to_sort Huber_pair :=
{ S := Type, coe := Huber_pair.R}
postfix `⁺` : 66 := λ R : Huber_pair _, R.Rplus
definition Spa (A : Huber_pair) : Type := sorry
instance Spa_topology (A : Huber_pair) : topological_space (Spa A) := sorry
--definition 𝓞_X (A : Huber_pair) : presheaf_of_rings (Spa A) := sorry
-- it's a presheaf of complete topological rings on all opens (defined on rational opens
-- first and then extended to all via proj limits) -- Huber p75
-- most of that would not be in the adic_space file.
--structure 𝓥pre :=
--(X : sorry)
--(𝓞X : sorry)
--(v : sorry)
/-
We denote by 𝓥pre the category of tuples X = (X, O X , (v x ) x∈X ), where
(a) X is a topological space,
(b) 𝓞_X is a presheaf of complete topological rings on X such that the stalk 𝓞_X,x of
𝓞_X (considered as a presheaf of rings) is a local ring,
(c) v_x is an equivalence class of valuations on the stalk 𝓞_X,x such that supp(v_x) is the
maximal ideal of 𝓞_X,x .
Wedhorn p76 shows how Spa(A) gives an object of this for A a Huber pair
-/
--definition affinoid_adic_space (A : Huber_pair) : 𝓥pre := sorry
-- unwritten -- it's a full subcat of 𝓥pre
class preadic_space (X : Type) extends topological_space X
-- not logically necessary but should be easy
instance (A : Huber_pair) : preadic_space (Spa A) := sorry
-- attribute [class] _root_.is_open
instance preadic_space_restriction {X : Type} [preadic_space X] {U : opens X} :
preadic_space U := sorry
-- unwritten
class adic_space (X : Type) extends preadic_space X
-- a preadic_space_equiv is just an isom in 𝓥pre, or an isomorphism of preadic spaces.
-- is homeo in Lean yet?
-- unwritten
structure preadic_space_equiv (X Y : Type) [AX : preadic_space X] [AY : preadic_space Y] extends equiv X Y
definition is_preadic_space_equiv (X Y : Type) [AX : preadic_space X] [AY : preadic_space Y] :=
nonempty (preadic_space_equiv X Y)
definition preadic_space_pullback {X : Type} [preadic_space X] (U : set X) := {x : X // x ∈ U}
instance pullback_is_preadic_space {X : Type} [preadic_space X] (U : set X) : preadic_space (preadic_space_pullback U) := sorry
-- notation `is_open` := _root_.is_open
|
3ef4ea8b9142ddc661c7dcef1e68a25356a4e8d2 | 31f556cdeb9239ffc2fad8f905e33987ff4feab9 | /tests/lean/run/frontend_meeting_2022_09_13.lean | b8074fcb50a3ef5ff933e42cef70664593920015 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | tobiasgrosser/lean4 | ce0fd9cca0feba1100656679bf41f0bffdbabb71 | ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f | refs/heads/master | 1,673,103,412,948 | 1,664,930,501,000 | 1,664,930,501,000 | 186,870,185 | 0 | 0 | Apache-2.0 | 1,665,129,237,000 | 1,557,939,901,000 | Lean | UTF-8 | Lean | false | false | 3,158 | lean | import Lean
/-
(1) How are the source information, comments etc stored in the Syntax tree? In particular, how can one recreate the original source?
-/
elab "#reprint" e:term : command => do
let some val := e.raw.reprint | throwError "failed to reprint"
IO.println val
#reprint
let x : Nat := 3 -- My comment 1
x + 2 /- another comment here -/
elab "#repr" e:term : command => do
IO.println (repr e)
#check Lean.SourceInfo
#repr
let x : Nat := 3 -- My comment 1
x + 2 /- another comment here -/
/-
(2) I am comfortable with the usual token level parsers but could not understand the code for `commentBody` and such parsers. How does one parse at character level?
-/
section
open Lean Parser
partial def commandCommentBodyFn (c : ParserContext) (s : ParserState) : ParserState :=
go s
where
go (s : ParserState) : ParserState := Id.run do
let input := c.input
let i := s.pos
if input.atEnd i then return s.mkUnexpectedError "unterminated command comment"
let curr := input.get i
let i := input.next i
if curr != '-' then return go (s.setPos i)
let curr := input.get i
let i := input.next i
if curr != '/' then return go (s.setPos i)
let curr := input.get i
let i := input.next i
if curr != '/' then return go (s.setPos i)
-- Found '-//'
return s.setPos i
def commandCommentBody : Parser :=
{ fn := rawFn commandCommentBodyFn (trailingWs := true) }
@[combinatorParenthesizer commandCommentBody] def commandCommentBody.parenthesizer := PrettyPrinter.Parenthesizer.visitToken
@[combinatorFormatter commandCommentBody] def commandCommentBody.formatter := PrettyPrinter.Formatter.visitAtom Name.anonymous
@[commandParser] def commandComment := leading_parser "//-" >> commandCommentBody >> ppLine
end
open Lean Elab Command in
@[commandElab commandComment] def elabCommandComment : CommandElab := fun stx => do
let .atom _ val := stx[1] | return ()
let str := val.extract 0 (val.endPos - ⟨3⟩)
IO.println s!"str := {repr str}"
//- My command comment hello world -//
/-
(3) How does one split a `tacticSeq` into individual tactics, with the goal of running them one by one logging state along the way?
-/
section
open Lean Parser Elab Tactic
def getTactics (s : TSyntax ``tacticSeq) : Array (TSyntax `tactic) :=
match s with
| `(tacticSeq| { $[$t]* }) => t
| `(tacticSeq| $[$t]*) => t
| _ => #[]
elab "seq" s:tacticSeq : tactic => do
-- IO.println s
let tacs := getTactics s
for tac in tacs do
let gs ← getUnsolvedGoals
withRef tac <| Meta.withPPForTacticGoal <| addRawTrace (goalsToMessageData gs)
evalTactic tac
example (h : x = y) : 0 + x = y := by
seq rw [h]; rw [Nat.zero_add]
done
example (h : x = y) : 0 + x = y := by
seq rw [h]
rw [Nat.zero_add]
done
example (h : x = y) : 0 + x = y := by
seq { rw [h]; rw [Nat.zero_add] }
done
end
/-
(4) Related to the above, how does one parse and run all the commands in a file updating the environment, with modifications to the running in some cases (specifically when running a `tacticSeq` log state at each step)?
-/
#check Lean.Elab.runFrontend
|
7a9c9ca7953adfbd856db034d3730390e90d995b | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/pi.lean | 97564dfd147a7d340c6a0760596565c5d212f1b1 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,239 | lean | /-
Copyright (c) 2020 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Patrick Massot, Eric Wieser
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.split_ifs
import Mathlib.tactic.simpa
import Mathlib.algebra.group.to_additive
import Mathlib.PostPort
universes u v u_1
namespace Mathlib
/-!
# Instances and theorems on pi types
This file provides basic definitions and notation instances for Pi types.
Instances of more sophisticated classes are defined in `pi.lean` files elsewhere.
-/
namespace pi
/-! `1`, `0`, `+`, `*`, `-`, `⁻¹`, and `/` are defined pointwise. -/
protected instance has_zero {I : Type u} {f : I → Type v} [(i : I) → HasZero (f i)] : HasZero ((i : I) → f i) :=
{ zero := fun (_x : I) => 0 }
@[simp] theorem one_apply {I : Type u} {f : I → Type v} (i : I) [(i : I) → HasOne (f i)] : HasOne.one i = 1 :=
rfl
theorem one_def {I : Type u} {f : I → Type v} [(i : I) → HasOne (f i)] : 1 = fun (i : I) => 1 :=
rfl
protected instance has_mul {I : Type u} {f : I → Type v} [(i : I) → Mul (f i)] : Mul ((i : I) → f i) :=
{ mul := fun (f_1 g : (i : I) → f i) (i : I) => f_1 i * g i }
@[simp] theorem mul_apply {I : Type u} {f : I → Type v} (x : (i : I) → f i) (y : (i : I) → f i) (i : I) [(i : I) → Mul (f i)] : Mul.mul x y i = x i * y i :=
rfl
protected instance has_inv {I : Type u} {f : I → Type v} [(i : I) → has_inv (f i)] : has_inv ((i : I) → f i) :=
has_inv.mk fun (f_1 : (i : I) → f i) (i : I) => f_1 i⁻¹
@[simp] theorem neg_apply {I : Type u} {f : I → Type v} (x : (i : I) → f i) (i : I) [(i : I) → Neg (f i)] : Neg.neg x i = -x i :=
rfl
protected instance has_sub {I : Type u} {f : I → Type v} [(i : I) → Sub (f i)] : Sub ((i : I) → f i) :=
{ sub := fun (f_1 g : (i : I) → f i) (i : I) => f_1 i - g i }
@[simp] theorem sub_apply {I : Type u} {f : I → Type v} (x : (i : I) → f i) (y : (i : I) → f i) (i : I) [(i : I) → Sub (f i)] : Sub.sub x y i = x i - y i :=
rfl
theorem div_def {I : Type u} {f : I → Type v} (x : (i : I) → f i) (y : (i : I) → f i) [(i : I) → Div (f i)] : x / y = fun (i : I) => x i / y i :=
rfl
/-- The function supported at `i`, with value `x` there. -/
def single {I : Type u} {f : I → Type v} [DecidableEq I] [(i : I) → HasZero (f i)] (i : I) (x : f i) : (i : I) → f i :=
function.update 0 i x
@[simp] theorem single_eq_same {I : Type u} {f : I → Type v} [DecidableEq I] [(i : I) → HasZero (f i)] (i : I) (x : f i) : single i x i = x :=
function.update_same i x 0
@[simp] theorem single_eq_of_ne {I : Type u} {f : I → Type v} [DecidableEq I] [(i : I) → HasZero (f i)] {i : I} {i' : I} (h : i' ≠ i) (x : f i) : single i x i' = 0 :=
function.update_noteq h x 0
theorem single_injective {I : Type u} (f : I → Type v) [DecidableEq I] [(i : I) → HasZero (f i)] (i : I) : function.injective (single i) :=
function.update_injective (fun (a : I) => HasZero.zero a) i
end pi
theorem subsingleton.pi_single_eq {I : Type u} {α : Type u_1} [DecidableEq I] [subsingleton I] [HasZero α] (i : I) (x : α) : pi.single i x = fun (_x : I) => x := sorry
|
a86ee7a21ebdd4a90f53062f3e460b3313e6878b | 94e33a31faa76775069b071adea97e86e218a8ee | /src/algebra/category/FinVect.lean | f78a110c0bf5d86ce41ce1f439ec4986396dd768 | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 5,267 | lean | /-
Copyright (c) 2021 Jakob von Raumer. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jakob von Raumer
-/
import category_theory.monoidal.rigid.basic
import category_theory.monoidal.subcategory
import linear_algebra.tensor_product_basis
import linear_algebra.coevaluation
import algebra.category.Module.monoidal
/-!
# The category of finite dimensional vector spaces
This introduces `FinVect K`, the category of finite dimensional vector spaces over a field `K`.
It is implemented as a full subcategory on a subtype of `Module K`, which inherits monoidal and
symmetric structure as `finite_dimensional K` is a monoidal predicate.
We also provide a right rigid monoidal category instance.
-/
noncomputable theory
open category_theory Module.monoidal_category
open_locale classical big_operators
universes u
variables (K : Type u) [field K]
instance monoidal_predicate_finite_dimensional :
monoidal_category.monoidal_predicate (λ V : Module.{u} K, finite_dimensional K V) :=
{ prop_id' := finite_dimensional.finite_dimensional_self K,
prop_tensor' := λ X Y hX hY, by exactI module.finite.tensor_product K X Y }
/-- Define `FinVect` as the subtype of `Module.{u} K` of finite dimensional vector spaces. -/
@[derive [large_category, λ α, has_coe_to_sort α (Sort*), concrete_category, monoidal_category,
symmetric_category]]
def FinVect := { V : Module.{u} K // finite_dimensional K V }
namespace FinVect
instance finite_dimensional (V : FinVect K) : finite_dimensional K V := V.prop
instance : inhabited (FinVect K) := ⟨⟨Module.of K K, finite_dimensional.finite_dimensional_self K⟩⟩
instance : has_coe (FinVect.{u} K) (Module.{u} K) := { coe := λ V, V.1, }
protected lemma coe_comp {U V W : FinVect K} (f : U ⟶ V) (g : V ⟶ W) :
((f ≫ g) : U → W) = (g : V → W) ∘ (f : U → V) := rfl
/-- Lift an unbundled vector space to `FinVect K`. -/
def of (V : Type u) [add_comm_group V] [module K V] [finite_dimensional K V] : FinVect K :=
⟨Module.of K V, by { change finite_dimensional K V, apply_instance }⟩
instance : has_forget₂ (FinVect.{u} K) (Module.{u} K) :=
by { dsimp [FinVect], apply_instance, }
instance : full (forget₂ (FinVect K) (Module.{u} K)) :=
{ preimage := λ X Y f, f, }
variables (V : FinVect K)
/-- The dual module is the dual in the rigid monoidal category `FinVect K`. -/
def FinVect_dual : FinVect K :=
⟨Module.of K (module.dual K V), subspace.module.dual.finite_dimensional⟩
instance : has_coe_to_fun (FinVect_dual K V) (λ _, V → K) :=
{ coe := λ v, by { change V →ₗ[K] K at v, exact v, } }
open category_theory.monoidal_category
/-- The coevaluation map is defined in `linear_algebra.coevaluation`. -/
def FinVect_coevaluation : 𝟙_ (FinVect K) ⟶ V ⊗ (FinVect_dual K V) :=
by apply coevaluation K V
lemma FinVect_coevaluation_apply_one : FinVect_coevaluation K V (1 : K) =
∑ (i : basis.of_vector_space_index K V),
(basis.of_vector_space K V) i ⊗ₜ[K] (basis.of_vector_space K V).coord i :=
by apply coevaluation_apply_one K V
/-- The evaluation morphism is given by the contraction map. -/
def FinVect_evaluation : (FinVect_dual K V) ⊗ V ⟶ 𝟙_ (FinVect K) :=
by apply contract_left K V
@[simp]
lemma FinVect_evaluation_apply (f : (FinVect_dual K V)) (x : V) :
(FinVect_evaluation K V) (f ⊗ₜ x) = f x :=
by apply contract_left_apply f x
private theorem coevaluation_evaluation :
let V' : FinVect K := FinVect_dual K V in
(𝟙 V' ⊗ (FinVect_coevaluation K V)) ≫ (α_ V' V V').inv ≫ (FinVect_evaluation K V ⊗ 𝟙 V')
= (ρ_ V').hom ≫ (λ_ V').inv :=
by apply contract_left_assoc_coevaluation K V
private theorem evaluation_coevaluation :
(FinVect_coevaluation K V ⊗ 𝟙 V)
≫ (α_ V (FinVect_dual K V) V).hom ≫ (𝟙 V ⊗ FinVect_evaluation K V)
= (λ_ V).hom ≫ (ρ_ V).inv :=
by apply contract_left_assoc_coevaluation' K V
instance exact_pairing : exact_pairing V (FinVect_dual K V) :=
{ coevaluation := FinVect_coevaluation K V,
evaluation := FinVect_evaluation K V,
coevaluation_evaluation' := coevaluation_evaluation K V,
evaluation_coevaluation' := evaluation_coevaluation K V }
instance right_dual : has_right_dual V := ⟨FinVect_dual K V⟩
instance right_rigid_category : right_rigid_category (FinVect K) := { }
variables {K V} (W : FinVect K)
/-- Converts and isomorphism in the category `FinVect` to a `linear_equiv` between the underlying
vector spaces. -/
def iso_to_linear_equiv {V W : FinVect K} (i : V ≅ W) : V ≃ₗ[K] W :=
((forget₂ (FinVect.{u} K) (Module.{u} K)).map_iso i).to_linear_equiv
lemma iso.conj_eq_conj {V W : FinVect K} (i : V ≅ W) (f : End V) :
iso.conj i f = linear_equiv.conj (iso_to_linear_equiv i) f := rfl
end FinVect
variables {K}
/-- Converts a `linear_equiv` to an isomorphism in the category `FinVect`. -/
@[simps] def linear_equiv.to_FinVect_iso
{V W : Type u} [add_comm_group V] [module K V] [finite_dimensional K V]
[add_comm_group W] [module K W] [finite_dimensional K W]
(e : V ≃ₗ[K] W) :
FinVect.of K V ≅ FinVect.of K W :=
{ hom := e.to_linear_map,
inv := e.symm.to_linear_map,
hom_inv_id' := by {ext, exact e.left_inv x},
inv_hom_id' := by {ext, exact e.right_inv x} }
|
f9959e0b74e0b47106f1d5b0d02281f8432b7f95 | 82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7 | /src/Init/System/IO.lean | 5d66eada39ae76fc75d710011ba69e3d8a9c1d27 | [
"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 | 18,532 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Luke Nelson, Jared Roesch, Leonardo de Moura, Sebastian Ullrich
-/
prelude
import Init.Control.EState
import Init.Control.Reader
import Init.Data.String
import Init.Data.ByteArray
import Init.System.IOError
import Init.System.FilePath
import Init.System.ST
/-- Like https://hackage.haskell.org/package/ghc-Prim-0.5.2.0/docs/GHC-Prim.html#t:RealWorld.
Makes sure we never reorder `IO` operations.
TODO: mark opaque -/
def IO.RealWorld : Type := Unit
/- TODO(Leo): mark it as an opaque definition. Reason: prevent
functions defined in other modules from accessing `IO.RealWorld`.
We don't want action such as
```
def getWorld : IO (IO.RealWorld) := get
```
-/
def EIO (ε : Type) : Type → Type := EStateM ε IO.RealWorld
@[inline] def EIO.catchExceptions {α ε} (x : EIO ε α) (h : ε → EIO Empty α) : EIO Empty α :=
fun s => match x s with
| EStateM.Result.ok a s => EStateM.Result.ok a s
| EStateM.Result.error ex s => h ex s
instance (ε : Type) : Monad (EIO ε) := inferInstanceAs (Monad (EStateM ε IO.RealWorld))
instance (ε : Type) : MonadFinally (EIO ε) := inferInstanceAs (MonadFinally (EStateM ε IO.RealWorld))
instance (ε : Type) : MonadExceptOf ε (EIO ε) := inferInstanceAs (MonadExceptOf ε (EStateM ε IO.RealWorld))
instance (α ε : Type) : OrElse (EIO ε α) := ⟨MonadExcept.orelse⟩
instance {ε : Type} {α : Type} [Inhabited ε] : Inhabited (EIO ε α) := inferInstanceAs (Inhabited (EStateM ε IO.RealWorld α))
open IO (Error) in
abbrev IO : Type → Type := EIO Error
@[inline] def EIO.toIO {α ε} (f : ε → IO.Error) (x : EIO ε α) : IO α :=
x.adaptExcept f
@[inline] def EIO.toIO' {α ε} (x : EIO ε α) : IO (Except ε α) :=
EIO.toIO (fun _ => unreachable!) (observing x)
@[inline] def IO.toEIO {α ε} (f : IO.Error → ε) (x : IO α) : EIO ε α :=
x.adaptExcept f
/- After we inline `EState.run'`, the closed term `((), ())` is generated, where the second `()`
represents the "initial world". We don't want to cache this closed term. So, we disable
the "extract closed terms" optimization. -/
set_option compiler.extract_closed false in
@[inline] unsafe def unsafeEIO {ε α : Type} (fn : EIO ε α) : Except ε α :=
match fn.run () with
| EStateM.Result.ok a _ => Except.ok a
| EStateM.Result.error e _ => Except.error e
@[inline] unsafe def unsafeIO {α : Type} (fn : IO α) : Except IO.Error α :=
unsafeEIO fn
@[extern "lean_io_timeit"] constant timeit {α : Type} (msg : @& String) (fn : IO α) : IO α
@[extern "lean_io_allocprof"] constant allocprof {α : Type} (msg : @& String) (fn : IO α) : IO α
/- Programs can execute IO actions during initialization that occurs before
the `main` function is executed. The attribute `[init <action>]` specifies
which IO action is executed to set the value of an opaque constant.
The action `initializing` returns `true` iff it is invoked during initialization. -/
@[extern "lean_io_initializing"] constant IO.initializing : IO Bool
class MonadIO (m : Type → Type) :=
{ liftIO {α} : IO α → m α }
export MonadIO (liftIO)
instance (m n) [MonadIO m] [MonadLift m n] : MonadIO n :=
{ liftIO := fun x => liftM (liftIO x : m _) }
instance : MonadIO IO :=
{ liftIO := id }
namespace IO
def ofExcept {ε α : Type} [ToString ε] (e : Except ε α) : IO α :=
match e with
| Except.ok a => pure a
| Except.error e => throw (IO.userError (toString e))
def lazyPure {α : Type} (fn : Unit → α) : IO α :=
pure (fn ())
/--
Run `act` in a separate `Task`. This is similar to Haskell's [`unsafeInterleaveIO`](http://hackage.haskell.org/package/base-4.14.0.0/docs/System-IO-Unsafe.html#v:unsafeInterleaveIO),
except that the `Task` is started eagerly as usual. Thus pure accesses to the `Task` do not influence the impure `act`
computation.
Unlike with pure tasks created by `Task.mk`, tasks created by this function will be run even if the last reference
to the task is dropped. `act` should manually check for cancellation via `IO.checkInterrupt` if it wants to react
to that. -/
@[extern "lean_io_as_task"]
constant asTask {α : Type} (act : IO α) (prio := Task.Priority.default) : IO (Task (Except IO.Error α))
/-- See `IO.asTask`. -/
@[extern "lean_io_map_task"]
constant mapTask {α β : Type} (f : α → IO β) (t : Task α) (prio := Task.Priority.default) : IO (Task (Except IO.Error β))
/-- See `IO.asTask`. -/
@[extern "lean_io_bind_task"]
constant bindTask {α β : Type} (t : Task α) (f : α → IO (Task (Except IO.Error β))) (prio := Task.Priority.default) : IO (Task (Except IO.Error β))
/-- Check if the task's cancellation flag has been set by calling `IO.cancel` or dropping the last reference to the task. -/
@[extern "lean_io_check_canceled"] constant checkCanceled : IO Bool
/-- Request cooperative cancellation of the task. The task must explicitly call `IO.checkCanceled` to react to the cancellation. -/
@[extern "lean_io_cancel"] constant cancel {α : Type} : @& Task α → IO Unit
/-- Check if the task has finished execution, at which point calling `Task.get` will return immediately. -/
@[extern "lean_io_has_finished"] constant hasFinished {α : Type} : @& Task α → IO Unit
/-- Wait for the task to finish, then return its result. -/
@[extern "lean_io_wait"] constant wait {α : Type} : Task α → IO α
/-- Wait until any of the tasks in the given list has finished, then return its result. -/
@[extern "lean_io_wait_any"] constant waitAny {α : Type} : @& List (Task α) → IO α
inductive FS.Mode
| read | write | readWrite | append
constant FS.Handle : Type := Unit
/--
A pure-Lean abstraction of POSIX streams. We use `Stream`s for the standard streams stdin/stdout/stderr so we can
capture output of `#eval` commands into memory. -/
structure FS.Stream :=
(isEof : IO Bool)
(flush : IO Unit)
(read : forall (bytes : USize), IO ByteArray)
(write : ByteArray → IO Unit)
(getLine : IO String)
(putStr : String → IO Unit)
namespace Prim
open FS
@[extern "lean_get_stdin"] constant getStdin : IO FS.Stream
@[extern "lean_get_stdout"] constant getStdout : IO FS.Stream
@[extern "lean_get_stderr"] constant getStderr : IO FS.Stream
@[extern "lean_get_set_stdin"] constant setStdin : FS.Stream → IO FS.Stream
@[extern "lean_get_set_stdout"] constant setStdout : FS.Stream → IO FS.Stream
@[extern "lean_get_set_stderr"] constant setStderr : FS.Stream → IO FS.Stream
@[specialize] partial def iterate {α β : Type} (a : α) (f : α → IO (Sum α β)) : IO β := do
let v ← f a
match v with
| Sum.inl a => iterate a f
| Sum.inr b => pure b
-- @[export lean_fopen_flags]
def fopenFlags (m : FS.Mode) (b : Bool) : String :=
let mode :=
match m with
| FS.Mode.read => "r"
| FS.Mode.write => "w"
| FS.Mode.readWrite => "r+"
| FS.Mode.append => "a" ;
let bin := if b then "b" else "t"
mode ++ bin
@[extern "lean_io_prim_handle_mk"] constant Handle.mk (s : @& String) (mode : @& String) : IO Handle
@[extern "lean_io_prim_handle_is_eof"] constant Handle.isEof (h : @& Handle) : IO Bool
@[extern "lean_io_prim_handle_flush"] constant Handle.flush (h : @& Handle) : IO Unit
@[extern "lean_io_prim_handle_read"] constant Handle.read (h : @& Handle) (bytes : USize) : IO ByteArray
@[extern "lean_io_prim_handle_write"] constant Handle.write (h : @& Handle) (buffer : @& ByteArray) : IO Unit
@[extern "lean_io_prim_handle_get_line"] constant Handle.getLine (h : @& Handle) : IO String
@[extern "lean_io_prim_handle_put_str"] constant Handle.putStr (h : @& Handle) (s : @& String) : IO Unit
@[extern "lean_io_getenv"] constant getEnv (var : @& String) : IO (Option String)
@[extern "lean_io_realpath"] constant realPath (fname : String) : IO String
@[extern "lean_io_is_dir"] constant isDir (fname : @& String) : IO Bool
@[extern "lean_io_file_exists"] constant fileExists (fname : @& String) : IO Bool
@[extern "lean_io_app_dir"] constant appPath : IO String
@[extern "lean_io_current_dir"] constant currentDir : IO String
end Prim
namespace FS
variables {m : Type → Type} [Monad m] [MonadIO m]
def Handle.mk (s : String) (Mode : Mode) (bin : Bool := true) : m Handle :=
liftIO (Prim.Handle.mk s (Prim.fopenFlags Mode bin))
@[inline]
def withFile {α} (fn : String) (mode : Mode) (f : Handle → m α) : m α :=
Handle.mk fn mode >>= f
/-- returns whether the end of the file has been reached while reading a file.
`h.isEof` returns true /after/ the first attempt at reading past the end of `h`.
Once `h.isEof` is true, the reading `h` raises `IO.Error.eof`.
-/
def Handle.isEof : Handle → m Bool := liftIO ∘ Prim.Handle.isEof
def Handle.flush : Handle → m Unit := liftIO ∘ Prim.Handle.flush
def Handle.read (h : Handle) (bytes : Nat) : m ByteArray := liftIO (Prim.Handle.read h (USize.ofNat bytes))
def Handle.write (h : Handle) (s : ByteArray) : m Unit := liftIO (Prim.Handle.write h s)
def Handle.getLine : Handle → m String := liftIO ∘ Prim.Handle.getLine
def Handle.putStr (h : Handle) (s : String) : m Unit :=
liftIO $ Prim.Handle.putStr h s
def Handle.putStrLn (h : Handle) (s : String) : m Unit :=
h.putStr (s.push '\n')
-- TODO: support for binary files
partial def Handle.readToEnd (h : Handle) : m String :=
let rec read (s : String) := do
let line ← h.getLine
if line.length == 0 then pure s else read (s ++ line)
read ""
-- TODO: support for binary files
def readFile (fname : String) : m String := do
let h ← Handle.mk fname Mode.read false
h.readToEnd
partial def lines (fname : String) : m (Array String) := do
let h ← Handle.mk fname Mode.read false
let rec read (lines : Array String) := do
let line ← h.getLine
if line.length == 0 then
pure lines
else if line.back == '\n' then
let line := line.dropRight 1
let line := if System.Platform.isWindows && line.back == '\x0d' then line.dropRight 1 else line
read $ lines.push line
else
pure $ lines.push line
read #[]
namespace Stream
def putStrLn (strm : FS.Stream) (s : String) : m Unit :=
liftIO (strm.putStr (s.push '\n'))
end Stream
end FS
section
variables {m : Type → Type} [Monad m] [MonadIO m]
def getStdin : m FS.Stream := liftIO Prim.getStdin
def getStdout : m FS.Stream := liftIO Prim.getStdout
def getStderr : m FS.Stream := liftIO Prim.getStderr
/-- Replaces the stdin stream of the current thread and returns its previous value. -/
def setStdin : FS.Stream → m FS.Stream := liftIO ∘ Prim.setStdin
/-- Replaces the stdout stream of the current thread and returns its previous value. -/
def setStdout : FS.Stream → m FS.Stream := liftIO ∘ Prim.setStdout
/-- Replaces the stderr stream of the current thread and returns its previous value. -/
def setStderr : FS.Stream → m FS.Stream := liftIO ∘ Prim.setStderr
def withStdin [MonadFinally m] {α} (h : FS.Stream) (x : m α) : m α := do
let prev ← setStdin h
try x finally discard $ setStdin prev
def withStdout [MonadFinally m] {α} (h : FS.Stream) (x : m α) : m α := do
let prev ← setStdout h
try x finally discard $ setStdout prev
def withStderr [MonadFinally m] {α} (h : FS.Stream) (x : m α) : m α := do
let prev ← setStderr h
try x finally discard $ setStderr prev
def print {α} [ToString α] (s : α) : m Unit := do
let out ← getStdout
liftIO $ out.putStr $ toString s
def println {α} [ToString α] (s : α) : m Unit := print ((toString s).push '\n')
def eprint {α} [ToString α] (s : α) : m Unit := do
let out ← getStderr
liftIO $ out.putStr $ toString s
def eprintln {α} [ToString α] (s : α) : m Unit := eprint ((toString s).push '\n')
@[export lean_io_eprintln]
private def eprintlnAux (s : String) : IO Unit := eprintln s
def getEnv : String → m (Option String) := liftIO ∘ Prim.getEnv
def realPath : String → m String := liftIO ∘ Prim.realPath
def isDir : String → m Bool := liftIO ∘ Prim.isDir
def fileExists : String → m Bool := liftIO ∘ Prim.fileExists
def appPath : m String := liftIO Prim.appPath
def appDir : m String := do
let p ← appPath
realPath (System.FilePath.dirName p)
def currentDir : m String := liftIO Prim.currentDir
end
namespace Process
inductive Stdio
| piped
| inherit
| null
def Stdio.toHandleType : Stdio → Type
| Stdio.piped => FS.Handle
| Stdio.inherit => Unit
| Stdio.null => Unit
structure StdioConfig :=
/- Configuration for the process' stdin handle. -/
(stdin := Stdio.inherit)
/- Configuration for the process' stdout handle. -/
(stdout := Stdio.inherit)
/- Configuration for the process' stderr handle. -/
(stderr := Stdio.inherit)
structure SpawnArgs extends StdioConfig :=
/- Command name. -/
(cmd : String)
/- Arguments for the process -/
(args : Array String := #[])
/- Working directory for the process. Inherit from current process if `none`. -/
(cwd : Option String := none)
/- Add or remove environment variables for the process. -/
(env : Array (String × Option String) := #[])
-- TODO(Sebastian): constructor must be private
structure Child (cfg : StdioConfig) :=
(stdin : cfg.stdin.toHandleType)
(stdout : cfg.stdout.toHandleType)
(stderr : cfg.stderr.toHandleType)
@[extern "lean_io_process_spawn"] constant spawn (args : SpawnArgs) : IO (Child args.toStdioConfig)
@[extern "lean_io_process_child_wait"] constant Child.wait {cfg : @& StdioConfig} : @& Child cfg → IO UInt32
structure Output :=
(exitCode : UInt32)
(stdout : String)
(stderr : String)
/-- Run process to completion and capture output. -/
def output (args : SpawnArgs) : IO Output := do
let child ← spawn { args with stdout := Stdio.piped, stderr := Stdio.piped }
let stdout ← IO.asTask child.stdout.readToEnd Task.Priority.dedicated
let stderr ← child.stderr.readToEnd
let exitCode ← child.wait
let stdout ← IO.ofExcept stdout.get
pure { exitCode := exitCode, stdout := stdout, stderr := stderr }
/-- Run process to completion and return stdout on success. -/
def run (args : SpawnArgs) : IO String := do
let out ← output args
if out.exitCode != 0 then
throw $ IO.userError $ "process '" ++ args.cmd ++ "' exited with code " ++ toString out.exitCode;
pure out.stdout
end Process
structure AccessRight :=
(read write execution : Bool := false)
def AccessRight.flags (acc : AccessRight) : UInt32 :=
let r : UInt32 := if acc.read then 0x4 else 0
let w : UInt32 := if acc.write then 0x2 else 0
let x : UInt32 := if acc.execution then 0x1 else 0
r.lor $ w.lor x
structure FileRight :=
(user group other : AccessRight := { })
def FileRight.flags (acc : FileRight) : UInt32 :=
let u : UInt32 := acc.user.flags.shiftLeft 6
let g : UInt32 := acc.group.flags.shiftLeft 3
let o : UInt32 := acc.other.flags
u.lor $ g.lor o
@[extern "lean_chmod"] constant Prim.setAccessRights (filename : @& String) (mode : UInt32) : IO Unit
def setAccessRights (filename : String) (mode : FileRight) : IO Unit :=
Prim.setAccessRights filename mode.flags
/- References -/
abbrev Ref (α : Type) := ST.Ref IO.RealWorld α
instance {ε} : MonadLift (ST IO.RealWorld) (EIO ε) := ⟨fun x s =>
match x s with
| EStateM.Result.ok a s => EStateM.Result.ok a s
| EStateM.Result.error ex _ => nomatch ex⟩
def mkRef {α : Type} {m : Type → Type} [Monad m] [MonadLiftT (ST IO.RealWorld) m] (a : α) : m (IO.Ref α) :=
ST.mkRef a
namespace FS
namespace Stream
@[export lean_stream_of_handle]
def ofHandle (h : Handle) : Stream := {
isEof := Prim.Handle.isEof h,
flush := Prim.Handle.flush h,
read := Prim.Handle.read h,
write := Prim.Handle.write h,
getLine := Prim.Handle.getLine h,
putStr := Prim.Handle.putStr h,
}
structure Buffer :=
(data : ByteArray := ByteArray.empty)
(pos : Nat := 0)
def ofBuffer (r : Ref Buffer) : Stream := {
isEof := do let b ← r.get; pure $ b.pos >= b.data.size,
flush := pure (),
read := fun n => r.modifyGet fun b =>
let data := b.data.extract b.pos (b.pos + n.toNat)
(data, { b with pos := b.pos + data.size }),
write := fun data => r.modify fun b =>
-- set `exact` to `false` so that repeatedly writing to the stream does not impose quadratic run time
{ b with data := data.copySlice 0 b.data b.pos data.size false, pos := b.pos + data.size },
getLine := r.modifyGet fun b =>
let pos := match b.data.findIdx? (start := b.pos) fun u => u == 0 || u = '\n'.toNat.toUInt8 with
-- include '\n', but not '\0'
| some pos => if b.data.get! pos == 0 then pos else pos + 1
| none => b.data.size
(String.fromUTF8Unchecked $ b.data.extract b.pos pos, { b with pos := pos }),
putStr := fun s => r.modify fun b =>
let data := s.toUTF8
{ b with data := data.copySlice 0 b.data b.pos data.size false, pos := b.pos + data.size },
}
end Stream
/-- Run action with `stdin` emptied and `stdout+stderr` captured into a `String`. -/
def withIsolatedStreams {α : Type} (x : IO α) : IO (String × Except IO.Error α) := do
let bIn ← mkRef { : Stream.Buffer }
let bOut ← mkRef { : Stream.Buffer }
let r ← withStdin (Stream.ofBuffer bIn) $
withStdout (Stream.ofBuffer bOut) $
withStderr (Stream.ofBuffer bOut) $
observing x
let bOut ← bOut.get
let out := String.fromUTF8Unchecked bOut.data
pure (out, r)
end FS
end IO
universe u
namespace Lean
/-- Typeclass used for presenting the output of an `#eval` command. -/
class Eval (α : Type u) :=
-- We default `hideUnit` to `true`, but set it to `false` in the direct call from `#eval`
-- so that `()` output is hidden in chained instances such as for some `m Unit`.
-- We take `Unit → α` instead of `α` because ‵α` may contain effectful debugging primitives (e.g., `dbgTrace!`)
(eval : (Unit → α) → forall (hideUnit : optParam Bool true), IO Unit)
instance {α : Type u} [Repr α] : Eval α :=
⟨fun a _ => IO.println (repr (a ()))⟩
instance : Eval Unit :=
⟨fun u hideUnit => if hideUnit then pure () else IO.println (repr (u ()))⟩
instance {α : Type} [Eval α] : Eval (IO α) :=
⟨fun x _ => do let a ← x (); Eval.eval (fun _ => a)⟩
@[noinline, nospecialize] def runEval {α : Type u} [Eval α] (a : Unit → α) : IO (String × Except IO.Error Unit) :=
IO.FS.withIsolatedStreams (Eval.eval a false)
end Lean
|
1b3b2812df8dec97ebba44858a0d137e60030978 | e9078bde91465351e1b354b353c9f9d8b8a9c8c2 | /two_quotient_and_ap.hlean | 31c384d5a6afd54953451680631d2c67eb714c6b | [
"Apache-2.0"
] | permissive | EgbertRijke/leansnippets | 09fb7a9813477471532fbdd50c99be8d8fe3e6c4 | 1d9a7059784c92c0281fcc7ce66ac7b3619c8661 | refs/heads/master | 1,610,743,957,626 | 1,442,532,603,000 | 1,442,532,603,000 | 41,563,379 | 0 | 0 | null | 1,440,787,514,000 | 1,440,787,514,000 | null | UTF-8 | Lean | false | false | 1,520 | hlean | import hit.two_quotient hit.interval
open two_quotient sum unit interval e_closure eq function
namespace test
definition A := interval + unit
inductive R : A → A → Type :=
| Rmk0 : R (inl zero) (inr star)
| Rmk1 : R (inl one) (inr star)
open R
-- definition torus_R (x y : unit) := bool
-- local infix `⬝r`:75 := @e_closure.trans unit torus_R star star star
-- local postfix `⁻¹ʳ`:(max+10) := @e_closure.symm unit torus_R star star
-- local notation `[`:max a `]`:0 := @e_closure.of_rel unit torus_R star star a
inductive Q : Π⦃x y : A⦄, e_closure R x y → e_closure R x y → Type :=
| Qmk : Q (ap inl seg ▸ [Rmk0]) [Rmk1]
open Q
definition triangle := two_quotient R Q
definition x0 : triangle := incl0 R Q (inl zero)
definition x1 : triangle := incl0 R Q (inl one)
definition x2 : triangle := incl0 R Q (inr star)
definition p01 : x0 = x1 := ap (incl0 R Q) (ap inl seg)
definition p02 : x0 = x2 := incl1 R Q Rmk0
definition p12 : x1 = x2 := incl1 R Q Rmk1
open relation
definition fill : p01⁻¹ ⬝ p02 = p12 :=
!e_closure.transport_left⁻¹ ⬝ incl2 R Q Qmk
definition elim (P : Type) (P0 : A → P) (P10 : P0 (inl zero) = P0 (inr star))
(P11 : P0 (inl one) = P0 (inr star)) (P2 : (ap P0 (ap inl seg))⁻¹ ⬝ P10 = P11)
(y : triangle) : P :=
begin
induction y,
{ exact P0 a},
{ induction s,
{ exact P10},
{ exact P11}},
{ induction q, esimp, exact !e_closure.transport_left ⬝ P2}
end
end test
|
e3847fe7a000989656f700eba33d06fbdc537de1 | c45b34bfd44d8607a2e8762c926e3cfaa7436201 | /uexp/src/uexp/rules/relationalAlgebra.lean | abdf5b0698e4b44fd8643a3030b2276af175247c | [
"BSD-2-Clause"
] | permissive | Shamrock-Frost/Cosette | b477c442c07e45082348a145f19ebb35a7f29392 | 24cbc4adebf627f13f5eac878f04ffa20d1209af | refs/heads/master | 1,619,721,304,969 | 1,526,082,841,000 | 1,526,082,841,000 | 121,695,605 | 1 | 0 | null | 1,518,737,210,000 | 1,518,737,210,000 | null | UTF-8 | Lean | false | false | 2,877 | lean | import ..u_semiring
import ..sql
import ..tactics
import ..ucongr
import ..TDP
set_option profiler true
open Expr
open Proj
open Pred
open SQL
lemma commutativeSelect:
forall Γ s a slct0 slct1,
denoteSQL ((SELECT * FROM1 (SELECT * FROM1 a WHERE slct1) WHERE slct0): SQL Γ s) =
denoteSQL ((SELECT * FROM1 (SELECT * FROM1 a WHERE slct0) WHERE slct1): SQL Γ s) :=
begin
intros,
unfold_all_denotations,
funext,
-- simp should work here, but it seems require ac refl now
ac_refl,
end
lemma pushdownSelect:
forall Γ s1 s2 (r: SQL Γ s1) (s: SQL Γ s2) slct,
denoteSQL
((SELECT * FROM1 (SQL.product r (SELECT * FROM1 s WHERE slct))) : SQL Γ _) =
denoteSQL
(SELECT *
FROM1 (SQL.product r s)
WHERE (Pred.castPred (Proj.combine left (right⋅right)) slct): SQL Γ _) :=
begin
intros,
unfold_all_denotations,
funext,
unfold pair,
simp,
ac_refl
end
lemma disjointSelect:
forall Γ s (a: SQL Γ s) slct0 slct1,
denoteSQL ((DISTINCT SELECT * FROM1 a WHERE (slct0 OR slct1)): SQL Γ _) =
denoteSQL ((DISTINCT ((SELECT * FROM1 a WHERE slct0) UNION ALL (SELECT * FROM1 a WHERE slct1))) : SQL Γ _) :=
begin
intros,
unfold denoteSQL,
funext,
unfold denotePred,
rewrite squash_time_squash,
simp,
end
lemma idempotentSelect:
forall Γ s (a: SQL Γ s) slct,
denoteSQL ((SELECT * FROM1 (SELECT * FROM1 a WHERE slct) WHERE slct): SQL Γ _) =
denoteSQL ((SELECT * FROM1 a WHERE slct): SQL Γ _) :=
begin
intros,
unfold_all_denotations,
funext,
ucongr,
end
lemma projectionDistributesOverUnion:
forall Γ s (a0 a1: SQL Γ s) slct,
denoteSQL ((SELECT * FROM1 (a0 UNION ALL a1) WHERE slct) : SQL Γ _ ) =
denoteSQL (((SELECT * FROM1 a0 WHERE slct) UNION ALL (SELECT * FROM1 a1 WHERE slct)) : SQL Γ _ ) :=
begin
intros,
unfold_all_denotations,
funext,
simp,
end
lemma productDistributesOverUnion:
forall Γ s (a a0 a1: SQL Γ s),
denoteSQL (SELECT * FROM1 (product a (a0 UNION ALL a1)) : SQL Γ _ ) =
denoteSQL (((SELECT * FROM2 a, a0) UNION ALL (SELECT * FROM2 a, a1)) : SQL Γ _ ) :=
begin
intros,
unfold_all_denotations,
funext,
simp,
end
lemma joinCommute:
forall Γ s1 s2 (a:SQL Γ s1) (b:SQL Γ s2),
denoteSQL ((project (combine (right⋅right⋅star) (right⋅left⋅star)) (product b a) ) : SQL Γ _ ) =
denoteSQL (SELECT * FROM1 (product a b) : SQL Γ _ ) :=
begin
intros,
unfold_all_denotations,
funext,
unfold pair,
simp,
TDP,
end
lemma conjunctSelect:
forall Γ s a slct0 slct1,
denoteSQL ((SELECT * FROM1 a WHERE (and slct0 slct1)) : SQL Γ s ) =
denoteSQL ((SELECT * FROM1 (SELECT * FROM1 a WHERE slct0) WHERE slct1) : SQL Γ s) :=
begin
intros,
unfold_all_denotations,
funext,
unfold pair,
TDP,
end |
0a3c06d0b0edc5dc3ef0302e5983c79991ec18f9 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/data/set/lattice.lean | 3f784fc371977b191b16d2ad7905bcc47d1ab462 | [
"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 | 48,594 | 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, Johannes Hölzl, Mario Carneiro
-- QUESTION: can make the first argument in ∀ x ∈ a, ... implicit?
-/
import order.complete_boolean_algebra
import data.sigma.basic
import order.galois_connection
import order.directed
open function tactic set auto
universes u v w x y
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {ι' : Sort y}
namespace set
instance lattice_set : complete_lattice (set α) :=
{ Sup := λs, {a | ∃ t ∈ s, a ∈ t },
Inf := λs, {a | ∀ t ∈ s, a ∈ t },
le_Sup := assume s t t_in a a_in, ⟨t, ⟨t_in, a_in⟩⟩,
Sup_le := assume s t h a ⟨t', ⟨t'_in, a_in⟩⟩, h t' t'_in a_in,
le_Inf := assume s t h a a_in t' t'_in, h t' t'_in a_in,
Inf_le := assume s t t_in a h, h _ t_in,
.. set.boolean_algebra,
.. (infer_instance : complete_lattice (α → Prop)) }
/-- Image is monotone. See `set.image_image` for the statement in terms of `⊆`. -/
lemma monotone_image {f : α → β} : monotone (image f) :=
assume s t, assume h : s ⊆ t, image_subset _ h
theorem monotone_inter [preorder β] {f g : β → set α}
(hf : monotone f) (hg : monotone g) : monotone (λx, f x ∩ g x) :=
assume b₁ b₂ h, inter_subset_inter (hf h) (hg h)
theorem monotone_union [preorder β] {f g : β → set α}
(hf : monotone f) (hg : monotone g) : monotone (λx, f x ∪ g x) :=
assume b₁ b₂ h, union_subset_union (hf h) (hg h)
theorem monotone_set_of [preorder α] {p : α → β → Prop}
(hp : ∀b, monotone (λa, p a b)) : monotone (λa, {b | p a b}) :=
assume a a' h b, hp b h
section galois_connection
variables {f : α → β}
protected lemma image_preimage : galois_connection (image f) (preimage f) :=
assume a b, image_subset_iff
/-- `kern_image f s` is the set of `y` such that `f ⁻¹ y ⊆ s` -/
def kern_image (f : α → β) (s : set α) : set β := {y | ∀ ⦃x⦄, f x = y → x ∈ s}
protected lemma preimage_kern_image : galois_connection (preimage f) (kern_image f) :=
assume a b,
⟨ assume h x hx y hy, have f y ∈ a, from hy.symm ▸ hx, h this,
assume h x (hx : f x ∈ a), h hx rfl⟩
end galois_connection
/- union and intersection over a family of sets indexed by a type -/
/-- Indexed union of a family of sets -/
@[reducible] def Union (s : ι → set β) : set β := supr s
/-- Indexed intersection of a family of sets -/
@[reducible] def Inter (s : ι → set β) : set β := infi s
notation `⋃` binders `, ` r:(scoped f, Union f) := r
notation `⋂` binders `, ` r:(scoped f, Inter f) := r
@[simp] theorem mem_Union {x : β} {s : ι → set β} : x ∈ Union s ↔ ∃ i, x ∈ s i :=
⟨assume ⟨t, ⟨⟨a, (t_eq : s a = t)⟩, (h : x ∈ t)⟩⟩, ⟨a, t_eq.symm ▸ h⟩,
assume ⟨a, h⟩, ⟨s a, ⟨⟨a, rfl⟩, h⟩⟩⟩
/- alternative proof: dsimp [Union, supr, Sup]; simp -/
-- TODO: more rewrite rules wrt forall / existentials and logical connectives
-- TODO: also eliminate ∃i, ... ∧ i = t ∧ ...
theorem set_of_exists (p : ι → β → Prop) : {x | ∃ i, p i x} = ⋃ i, {x | p i x} :=
ext $ λ i, mem_Union.symm
@[simp] theorem mem_Inter {x : β} {s : ι → set β} : x ∈ Inter s ↔ ∀ i, x ∈ s i :=
⟨assume (h : ∀a ∈ {a : set β | ∃i, s i = a}, x ∈ a) a, h (s a) ⟨a, rfl⟩,
assume h t ⟨a, (eq : s a = t)⟩, eq ▸ h a⟩
theorem set_of_forall (p : ι → β → Prop) : {x | ∀ i, p i x} = ⋂ i, {x | p i x} :=
ext $ λ i, mem_Inter.symm
theorem Union_subset {s : ι → set β} {t : set β} (h : ∀ i, s i ⊆ t) : (⋃ i, s i) ⊆ t :=
-- TODO: should be simpler when sets' order is based on lattices
@supr_le (set β) _ set.lattice_set _ _ h
theorem Union_subset_iff {s : ι → set β} {t : set β} : (⋃ i, s i) ⊆ t ↔ (∀ i, s i ⊆ t) :=
⟨assume h i, subset.trans (le_supr s _) h, Union_subset⟩
theorem mem_Inter_of_mem {x : β} {s : ι → set β} : (∀ i, x ∈ s i) → (x ∈ ⋂ i, s i) :=
mem_Inter.2
theorem subset_Inter {t : set β} {s : ι → set β} (h : ∀ i, t ⊆ s i) : t ⊆ ⋂ i, s i :=
-- TODO: should be simpler when sets' order is based on lattices
@le_infi (set β) _ set.lattice_set _ _ h
theorem subset_Inter_iff {t : set β} {s : ι → set β} : t ⊆ (⋂ i, s i) ↔ ∀ i, t ⊆ s i :=
@le_infi_iff (set β) _ set.lattice_set _ _
theorem subset_Union : ∀ (s : ι → set β) (i : ι), s i ⊆ (⋃ i, s i) := le_supr
-- This rather trivial consequence is convenient with `apply`,
-- and has `i` explicit for this use case.
theorem subset_subset_Union
{A : set β} {s : ι → set β} (i : ι) (h : A ⊆ s i) : A ⊆ ⋃ (i : ι), s i :=
subset.trans h (subset_Union s i)
theorem Inter_subset : ∀ (s : ι → set β) (i : ι), (⋂ i, s i) ⊆ s i := infi_le
lemma Inter_subset_of_subset {s : ι → set α} {t : set α} (i : ι)
(h : s i ⊆ t) : (⋂ i, s i) ⊆ t :=
set.subset.trans (set.Inter_subset s i) h
lemma Inter_subset_Inter {s t : ι → set α} (h : ∀ i, s i ⊆ t i) :
(⋂ i, s i) ⊆ (⋂ i, t i) :=
set.subset_Inter $ λ i, set.Inter_subset_of_subset i (h i)
lemma Inter_subset_Inter2 {s : ι → set α} {t : ι' → set α} (h : ∀ j, ∃ i, s i ⊆ t j) :
(⋂ i, s i) ⊆ (⋂ j, t j) :=
set.subset_Inter $ λ j, let ⟨i, hi⟩ := h j in Inter_subset_of_subset i hi
lemma Inter_set_of (P : ι → α → Prop) : (⋂ i, {x : α | P i x }) = {x : α | ∀ i, P i x} :=
by { ext, simp }
theorem Union_const [nonempty ι] (s : set β) : (⋃ i:ι, s) = s :=
ext $ by simp
theorem Inter_const [nonempty ι] (s : set β) : (⋂ i:ι, s) = s :=
ext $ by simp
@[simp] -- complete_boolean_algebra
theorem compl_Union (s : ι → set β) : (⋃ i, s i)ᶜ = (⋂ i, (s i)ᶜ) :=
ext (by simp)
-- classical -- complete_boolean_algebra
theorem compl_Inter (s : ι → set β) : (⋂ i, s i)ᶜ = (⋃ i, (s i)ᶜ) :=
ext (λ x, by simp [not_forall])
-- classical -- complete_boolean_algebra
theorem Union_eq_comp_Inter_comp (s : ι → set β) : (⋃ i, s i) = (⋂ i, (s i)ᶜ)ᶜ :=
by simp [compl_Inter, compl_compl]
-- classical -- complete_boolean_algebra
theorem Inter_eq_comp_Union_comp (s : ι → set β) : (⋂ i, s i) = (⋃ i, (s i)ᶜ)ᶜ :=
by simp [compl_compl]
theorem inter_Union (s : set β) (t : ι → set β) :
s ∩ (⋃ i, t i) = ⋃ i, s ∩ t i :=
ext $ by simp
theorem Union_inter (s : set β) (t : ι → set β) :
(⋃ i, t i) ∩ s = ⋃ i, t i ∩ s :=
ext $ by simp
theorem Union_union_distrib (s : ι → set β) (t : ι → set β) :
(⋃ i, s i ∪ t i) = (⋃ i, s i) ∪ (⋃ i, t i) :=
ext $ by simp [exists_or_distrib]
theorem Inter_inter_distrib (s : ι → set β) (t : ι → set β) :
(⋂ i, s i ∩ t i) = (⋂ i, s i) ∩ (⋂ i, t i) :=
ext $ by simp [forall_and_distrib]
theorem union_Union [nonempty ι] (s : set β) (t : ι → set β) :
s ∪ (⋃ i, t i) = ⋃ i, s ∪ t i :=
by rw [Union_union_distrib, Union_const]
theorem Union_union [nonempty ι] (s : set β) (t : ι → set β) :
(⋃ i, t i) ∪ s = ⋃ i, t i ∪ s :=
by rw [Union_union_distrib, Union_const]
theorem inter_Inter [nonempty ι] (s : set β) (t : ι → set β) :
s ∩ (⋂ i, t i) = ⋂ i, s ∩ t i :=
by rw [Inter_inter_distrib, Inter_const]
theorem Inter_inter [nonempty ι] (s : set β) (t : ι → set β) :
(⋂ i, t i) ∩ s = ⋂ i, t i ∩ s :=
by rw [Inter_inter_distrib, Inter_const]
-- classical
theorem union_Inter (s : set β) (t : ι → set β) :
s ∪ (⋂ i, t i) = ⋂ i, s ∪ t i :=
ext $ assume x, by simp [forall_or_distrib_left]
theorem Union_diff (s : set β) (t : ι → set β) :
(⋃ i, t i) \ s = ⋃ i, t i \ s :=
Union_inter _ _
theorem diff_Union [nonempty ι] (s : set β) (t : ι → set β) :
s \ (⋃ i, t i) = ⋂ i, s \ t i :=
by rw [diff_eq, compl_Union, inter_Inter]; refl
theorem diff_Inter (s : set β) (t : ι → set β) :
s \ (⋂ i, t i) = ⋃ i, s \ t i :=
by rw [diff_eq, compl_Inter, inter_Union]; refl
lemma directed_on_Union {r} {ι : Sort v} {f : ι → set α} (hd : directed (⊆) f)
(h : ∀x, directed_on r (f x)) : directed_on r (⋃x, f x) :=
by simp only [directed_on, exists_prop, mem_Union, exists_imp_distrib]; exact
assume a₁ b₁ fb₁ a₂ b₂ fb₂,
let ⟨z, zb₁, zb₂⟩ := hd b₁ b₂,
⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂) in
⟨x, ⟨z, xf⟩, xa₁, xa₂⟩
lemma Union_inter_subset {ι α} {s t : ι → set α} : (⋃ i, s i ∩ t i) ⊆ (⋃ i, s i) ∩ (⋃ i, t i) :=
by { rintro x ⟨_, ⟨i, rfl⟩, ⟨xs, xt⟩⟩, exact ⟨⟨_, ⟨i, rfl⟩, xs⟩, ⟨_, ⟨i, rfl⟩, xt⟩⟩ }
lemma Union_inter_of_monotone {ι α} [semilattice_sup ι] {s t : ι → set α}
(hs : monotone s) (ht : monotone t) : (⋃ i, s i ∩ t i) = (⋃ i, s i) ∩ (⋃ i, t i) :=
begin
ext x, refine ⟨λ hx, Union_inter_subset hx, _⟩,
rintro ⟨⟨_, ⟨i, rfl⟩, xs⟩, ⟨_, ⟨j, rfl⟩, xt⟩⟩,
exact ⟨_, ⟨i ⊔ j, rfl⟩, ⟨hs le_sup_left xs, ht le_sup_right xt⟩⟩
end
/-- An equality version of this lemma is `Union_Inter_of_monotone` in `data.set.finite`. -/
lemma Union_Inter_subset {ι ι' α} {s : ι → ι' → set α} : (⋃ j, ⋂ i, s i j) ⊆ ⋂ i, ⋃ j, s i j :=
by { rintro x ⟨_, ⟨i, rfl⟩, hx⟩ _ ⟨j, rfl⟩, exact ⟨_, ⟨i, rfl⟩, hx _ ⟨j, rfl⟩⟩ }
/- bounded unions and intersections -/
theorem mem_bUnion_iff {s : set α} {t : α → set β} {y : β} :
y ∈ (⋃ x ∈ s, t x) ↔ ∃ x ∈ s, y ∈ t x := by simp
theorem mem_bInter_iff {s : set α} {t : α → set β} {y : β} :
y ∈ (⋂ x ∈ s, t x) ↔ ∀ x ∈ s, y ∈ t x := by simp
theorem mem_bUnion {s : set α} {t : α → set β} {x : α} {y : β} (xs : x ∈ s) (ytx : y ∈ t x) :
y ∈ ⋃ x ∈ s, t x :=
by simp; exact ⟨x, ⟨xs, ytx⟩⟩
theorem mem_bInter {s : set α} {t : α → set β} {y : β} (h : ∀ x ∈ s, y ∈ t x) :
y ∈ ⋂ x ∈ s, t x :=
by simp; assumption
theorem bUnion_subset {s : set α} {t : set β} {u : α → set β} (h : ∀ x ∈ s, u x ⊆ t) :
(⋃ x ∈ s, u x) ⊆ t :=
show (⨆ x ∈ s, u x) ≤ t, -- TODO: should not be necessary when sets' order is based on lattices
from supr_le $ assume x, supr_le (h x)
theorem subset_bInter {s : set α} {t : set β} {u : α → set β} (h : ∀ x ∈ s, t ⊆ u x) :
t ⊆ (⋂ x ∈ s, u x) :=
subset_Inter $ assume x, subset_Inter $ h x
theorem subset_bUnion_of_mem {s : set α} {u : α → set β} {x : α} (xs : x ∈ s) :
u x ⊆ (⋃ x ∈ s, u x) :=
show u x ≤ (⨆ x ∈ s, u x),
from le_supr_of_le x $ le_supr _ xs
theorem bInter_subset_of_mem {s : set α} {t : α → set β} {x : α} (xs : x ∈ s) :
(⋂ x ∈ s, t x) ⊆ t x :=
show (⨅x ∈ s, t x) ≤ t x,
from infi_le_of_le x $ infi_le _ xs
theorem bUnion_subset_bUnion_left {s s' : set α} {t : α → set β}
(h : s ⊆ s') : (⋃ x ∈ s, t x) ⊆ (⋃ x ∈ s', t x) :=
bUnion_subset (λ x xs, subset_bUnion_of_mem (h xs))
theorem bInter_subset_bInter_left {s s' : set α} {t : α → set β}
(h : s' ⊆ s) : (⋂ x ∈ s, t x) ⊆ (⋂ x ∈ s', t x) :=
subset_bInter (λ x xs, bInter_subset_of_mem (h xs))
theorem bUnion_subset_bUnion_right {s : set α} {t1 t2 : α → set β}
(h : ∀ x ∈ s, t1 x ⊆ t2 x) : (⋃ x ∈ s, t1 x) ⊆ (⋃ x ∈ s, t2 x) :=
bUnion_subset (λ x xs, subset.trans (h x xs) (subset_bUnion_of_mem xs))
theorem bInter_subset_bInter_right {s : set α} {t1 t2 : α → set β}
(h : ∀ x ∈ s, t1 x ⊆ t2 x) : (⋂ x ∈ s, t1 x) ⊆ (⋂ x ∈ s, t2 x) :=
subset_bInter (λ x xs, subset.trans (bInter_subset_of_mem xs) (h x xs))
theorem bUnion_subset_bUnion {γ : Type*} {s : set α} {t : α → set β} {s' : set γ} {t' : γ → set β}
(h : ∀ x ∈ s, ∃ y ∈ s', t x ⊆ t' y) :
(⋃ x ∈ s, t x) ⊆ (⋃ y ∈ s', t' y) :=
begin
intros x,
simp only [mem_Union],
rintros ⟨a, a_in, ha⟩,
rcases h a a_in with ⟨c, c_in, hc⟩,
exact ⟨c, c_in, hc ha⟩
end
theorem bInter_mono' {s s' : set α} {t t' : α → set β} (hs : s ⊆ s') (h : ∀ x ∈ s, t x ⊆ t' x) :
(⋂ x ∈ s', t x) ⊆ (⋂ x ∈ s, t' x) :=
begin
intros x x_in,
simp only [mem_Inter] at *,
exact λ a a_in, h a a_in $ x_in _ (hs a_in)
end
theorem bInter_mono {s : set α} {t t' : α → set β} (h : ∀ x ∈ s, t x ⊆ t' x) :
(⋂ x ∈ s, t x) ⊆ (⋂ x ∈ s, t' x) :=
bInter_mono' (subset.refl s) h
theorem bUnion_mono {s : set α} {t t' : α → set β} (h : ∀ x ∈ s, t x ⊆ t' x) :
(⋃ x ∈ s, t x) ⊆ (⋃ x ∈ s, t' x) :=
bUnion_subset_bUnion (λ x x_in, ⟨x, x_in, h x x_in⟩)
theorem bUnion_eq_Union (s : set α) (t : Π x ∈ s, set β) :
(⋃ x ∈ s, t x ‹_›) = (⋃ x : s, t x x.2) :=
supr_subtype'
theorem bInter_eq_Inter (s : set α) (t : Π x ∈ s, set β) :
(⋂ x ∈ s, t x ‹_›) = (⋂ x : s, t x x.2) :=
infi_subtype'
theorem bInter_empty (u : α → set β) : (⋂ x ∈ (∅ : set α), u x) = univ :=
show (⨅x ∈ (∅ : set α), u x) = ⊤, -- simplifier should be able to rewrite x ∈ ∅ to false.
from infi_emptyset
theorem bInter_univ (u : α → set β) : (⋂ x ∈ @univ α, u x) = ⋂ x, u x :=
infi_univ
-- TODO(Jeremy): here is an artifact of the the encoding of bounded intersection:
-- without dsimp, the next theorem fails to type check, because there is a lambda
-- in a type that needs to be contracted. Using simp [eq_of_mem_singleton xa] also works.
@[simp] theorem bInter_singleton (a : α) (s : α → set β) : (⋂ x ∈ ({a} : set α), s x) = s a :=
show (⨅ x ∈ ({a} : set α), s x) = s a, by simp
theorem bInter_union (s t : set α) (u : α → set β) :
(⋂ x ∈ s ∪ t, u x) = (⋂ x ∈ s, u x) ∩ (⋂ x ∈ t, u x) :=
show (⨅ x ∈ s ∪ t, u x) = (⨅ x ∈ s, u x) ⊓ (⨅ x ∈ t, u x),
from infi_union
-- TODO(Jeremy): simp [insert_eq, bInter_union] doesn't work
@[simp] theorem bInter_insert (a : α) (s : set α) (t : α → set β) :
(⋂ x ∈ insert a s, t x) = t a ∩ (⋂ x ∈ s, t x) :=
begin rw insert_eq, simp [bInter_union] end
-- TODO(Jeremy): another example of where an annotation is needed
theorem bInter_pair (a b : α) (s : α → set β) :
(⋂ x ∈ ({a, b} : set α), s x) = s a ∩ s b :=
by simp [inter_comm]
theorem bUnion_empty (s : α → set β) : (⋃ x ∈ (∅ : set α), s x) = ∅ :=
supr_emptyset
theorem bUnion_univ (s : α → set β) : (⋃ x ∈ @univ α, s x) = ⋃ x, s x :=
supr_univ
@[simp] theorem bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : set α), s x) = s a :=
supr_singleton
@[simp] theorem bUnion_of_singleton (s : set α) : (⋃ x ∈ s, {x}) = s :=
ext $ by simp
theorem bUnion_union (s t : set α) (u : α → set β) :
(⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) :=
supr_union
-- TODO(Jeremy): once again, simp doesn't do it alone.
@[simp] theorem bUnion_insert (a : α) (s : set α) (t : α → set β) :
(⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) :=
begin rw [insert_eq], simp [bUnion_union] end
theorem bUnion_pair (a b : α) (s : α → set β) :
(⋃ x ∈ ({a, b} : set α), s x) = s a ∪ s b :=
by simp [union_comm]
@[simp] -- complete_boolean_algebra
theorem compl_bUnion (s : set α) (t : α → set β) : (⋃ i ∈ s, t i)ᶜ = (⋂ i ∈ s, (t i)ᶜ) :=
ext (λ x, by simp)
-- classical -- complete_boolean_algebra
theorem compl_bInter (s : set α) (t : α → set β) : (⋂ i ∈ s, t i)ᶜ = (⋃ i ∈ s, (t i)ᶜ) :=
ext (λ x, by simp [not_forall])
theorem inter_bUnion (s : set α) (t : α → set β) (u : set β) :
u ∩ (⋃ i ∈ s, t i) = ⋃ i ∈ s, u ∩ t i :=
begin
ext x,
simp only [exists_prop, mem_Union, mem_inter_eq],
exact ⟨λ ⟨hx, ⟨i, is, xi⟩⟩, ⟨i, is, hx, xi⟩, λ ⟨i, is, hx, xi⟩, ⟨hx, ⟨i, is, xi⟩⟩⟩
end
theorem bUnion_inter (s : set α) (t : α → set β) (u : set β) :
(⋃ i ∈ s, t i) ∩ u = (⋃ i ∈ s, t i ∩ u) :=
by simp [@inter_comm _ _ u, inter_bUnion]
/-- Intersection of a set of sets. -/
@[reducible] def sInter (S : set (set α)) : set α := Inf S
prefix `⋂₀`:110 := sInter
theorem mem_sUnion_of_mem {x : α} {t : set α} {S : set (set α)} (hx : x ∈ t) (ht : t ∈ S) :
x ∈ ⋃₀ S :=
⟨t, ⟨ht, hx⟩⟩
theorem mem_sUnion {x : α} {S : set (set α)} : x ∈ ⋃₀ S ↔ ∃t ∈ S, x ∈ t := iff.rfl
-- is this theorem really necessary?
theorem not_mem_of_not_mem_sUnion {x : α} {t : set α} {S : set (set α)}
(hx : x ∉ ⋃₀ S) (ht : t ∈ S) : x ∉ t :=
λ h, hx ⟨t, ht, h⟩
@[simp] theorem mem_sInter {x : α} {S : set (set α)} : x ∈ ⋂₀ S ↔ ∀ t ∈ S, x ∈ t := iff.rfl
theorem sInter_subset_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : ⋂₀ S ⊆ t :=
Inf_le tS
theorem subset_sUnion_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : t ⊆ ⋃₀ S :=
le_Sup tS
lemma subset_sUnion_of_subset {s : set α} (t : set (set α)) (u : set α) (h₁ : s ⊆ u)
(h₂ : u ∈ t) : s ⊆ ⋃₀ t :=
subset.trans h₁ (subset_sUnion_of_mem h₂)
theorem sUnion_subset {S : set (set α)} {t : set α} (h : ∀t' ∈ S, t' ⊆ t) : (⋃₀ S) ⊆ t :=
Sup_le h
theorem sUnion_subset_iff {s : set (set α)} {t : set α} : ⋃₀ s ⊆ t ↔ ∀t' ∈ s, t' ⊆ t :=
⟨assume h t' ht', subset.trans (subset_sUnion_of_mem ht') h, sUnion_subset⟩
theorem subset_sInter {S : set (set α)} {t : set α} (h : ∀t' ∈ S, t ⊆ t') : t ⊆ (⋂₀ S) :=
le_Inf h
theorem sUnion_subset_sUnion {S T : set (set α)} (h : S ⊆ T) : ⋃₀ S ⊆ ⋃₀ T :=
sUnion_subset $ λ s hs, subset_sUnion_of_mem (h hs)
theorem sInter_subset_sInter {S T : set (set α)} (h : S ⊆ T) : ⋂₀ T ⊆ ⋂₀ S :=
subset_sInter $ λ s hs, sInter_subset_of_mem (h hs)
@[simp] theorem sUnion_empty : ⋃₀ ∅ = (∅ : set α) := Sup_empty
@[simp] theorem sInter_empty : ⋂₀ ∅ = (univ : set α) := Inf_empty
@[simp] theorem sUnion_singleton (s : set α) : ⋃₀ {s} = s := Sup_singleton
@[simp] theorem sInter_singleton (s : set α) : ⋂₀ {s} = s := Inf_singleton
theorem sUnion_union (S T : set (set α)) : ⋃₀ (S ∪ T) = ⋃₀ S ∪ ⋃₀ T := Sup_union
theorem sInter_union (S T : set (set α)) : ⋂₀ (S ∪ T) = ⋂₀ S ∩ ⋂₀ T := Inf_union
theorem sInter_Union (s : ι → set (set α)) : ⋂₀ (⋃ i, s i) = ⋂ i, ⋂₀ s i :=
begin
ext x,
simp only [mem_Union, mem_Inter, mem_sInter, exists_imp_distrib],
split ; tauto
end
@[simp] theorem sUnion_insert (s : set α) (T : set (set α)) : ⋃₀ (insert s T) = s ∪ ⋃₀ T := Sup_insert
@[simp] theorem sInter_insert (s : set α) (T : set (set α)) : ⋂₀ (insert s T) = s ∩ ⋂₀ T := Inf_insert
theorem sUnion_pair (s t : set α) : ⋃₀ {s, t} = s ∪ t :=
Sup_pair
theorem sInter_pair (s t : set α) : ⋂₀ {s, t} = s ∩ t :=
Inf_pair
@[simp] theorem sUnion_image (f : α → set β) (s : set α) : ⋃₀ (f '' s) = ⋃ x ∈ s, f x := Sup_image
@[simp] theorem sInter_image (f : α → set β) (s : set α) : ⋂₀ (f '' s) = ⋂ x ∈ s, f x := Inf_image
@[simp] theorem sUnion_range (f : ι → set β) : ⋃₀ (range f) = ⋃ x, f x := rfl
@[simp] theorem sInter_range (f : ι → set β) : ⋂₀ (range f) = ⋂ x, f x := rfl
lemma sUnion_eq_univ_iff {c : set (set α)} :
⋃₀ c = @set.univ α ↔ ∀ a, ∃ b ∈ c, a ∈ b :=
⟨λ H a, let ⟨b, hm, hb⟩ := mem_sUnion.1 $ by rw H; exact mem_univ a in ⟨b, hm, hb⟩,
λ H, set.univ_subset_iff.1 $ λ x hx, let ⟨b, hm, hb⟩ := H x in set.mem_sUnion_of_mem hb hm⟩
theorem compl_sUnion (S : set (set α)) :
(⋃₀ S)ᶜ = ⋂₀ (compl '' S) :=
set.ext $ assume x,
⟨assume : ¬ (∃s∈S, x ∈ s), assume s h,
match s, h with
._, ⟨t, hs, rfl⟩ := assume h, this ⟨t, hs, h⟩
end,
assume : ∀s, s ∈ compl '' S → x ∈ s,
assume ⟨t, tS, xt⟩, this (compl t) (mem_image_of_mem _ tS) xt⟩
-- classical
theorem sUnion_eq_compl_sInter_compl (S : set (set α)) :
⋃₀ S = (⋂₀ (compl '' S))ᶜ :=
by rw [←compl_compl (⋃₀ S), compl_sUnion]
-- classical
theorem compl_sInter (S : set (set α)) :
(⋂₀ S)ᶜ = ⋃₀ (compl '' S) :=
by rw [sUnion_eq_compl_sInter_compl, compl_compl_image]
-- classical
theorem sInter_eq_comp_sUnion_compl (S : set (set α)) :
⋂₀ S = (⋃₀ (compl '' S))ᶜ :=
by rw [←compl_compl (⋂₀ S), compl_sInter]
theorem inter_empty_of_inter_sUnion_empty {s t : set α} {S : set (set α)} (hs : t ∈ S)
(h : s ∩ ⋃₀ S = ∅) :
s ∩ t = ∅ :=
eq_empty_of_subset_empty $ by rw ← h; exact
inter_subset_inter_right _ (subset_sUnion_of_mem hs)
theorem range_sigma_eq_Union_range {γ : α → Type*} (f : sigma γ → β) :
range f = ⋃ a, range (λ b, f ⟨a, b⟩) :=
set.ext $ by simp
theorem Union_eq_range_sigma (s : α → set β) : (⋃ i, s i) = range (λ a : Σ i, s i, a.2) :=
by simp [set.ext_iff]
theorem Union_image_preimage_sigma_mk_eq_self {ι : Type*} {σ : ι → Type*} (s : set (sigma σ)) :
(⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s)) = s :=
begin
ext x,
simp only [mem_Union, mem_image, mem_preimage],
split,
{ rintros ⟨i, a, h, rfl⟩, exact h },
{ intro h, cases x with i a, exact ⟨i, a, h, rfl⟩ }
end
lemma sUnion_mono {s t : set (set α)} (h : s ⊆ t) : (⋃₀ s) ⊆ (⋃₀ t) :=
sUnion_subset $ assume t' ht', subset_sUnion_of_mem $ h ht'
lemma Union_subset_Union {s t : ι → set α} (h : ∀i, s i ⊆ t i) : (⋃i, s i) ⊆ (⋃i, t i) :=
@supr_le_supr (set α) ι _ s t h
lemma Union_subset_Union2 {ι₂ : Sort*} {s : ι → set α} {t : ι₂ → set α} (h : ∀i, ∃j, s i ⊆ t j) :
(⋃i, s i) ⊆ (⋃i, t i) :=
@supr_le_supr2 (set α) ι ι₂ _ s t h
lemma Union_subset_Union_const {ι₂ : Sort x} {s : set α} (h : ι → ι₂) : (⋃ i:ι, s) ⊆ (⋃ j:ι₂, s) :=
@supr_le_supr_const (set α) ι ι₂ _ s h
@[simp] lemma Union_of_singleton (α : Type u) : (⋃(x : α), {x}) = @set.univ α :=
ext $ λ x, ⟨λ h, ⟨⟩, λ h, ⟨{x}, ⟨⟨x, rfl⟩, mem_singleton x⟩⟩⟩
theorem bUnion_subset_Union (s : set α) (t : α → set β) :
(⋃ x ∈ s, t x) ⊆ (⋃ x, t x) :=
Union_subset_Union $ λ i, Union_subset $ λ h, by refl
lemma sUnion_eq_bUnion {s : set (set α)} : (⋃₀ s) = (⋃ (i : set α) (h : i ∈ s), i) :=
by rw [← sUnion_image, image_id']
lemma sInter_eq_bInter {s : set (set α)} : (⋂₀ s) = (⋂ (i : set α) (h : i ∈ s), i) :=
by rw [← sInter_image, image_id']
lemma sUnion_eq_Union {s : set (set α)} : (⋃₀ s) = (⋃ (i : s), i) :=
by simp only [←sUnion_range, subtype.range_coe]
lemma sInter_eq_Inter {s : set (set α)} : (⋂₀ s) = (⋂ (i : s), i) :=
by simp only [←sInter_range, subtype.range_coe]
lemma union_eq_Union {s₁ s₂ : set α} : s₁ ∪ s₂ = ⋃ b : bool, cond b s₁ s₂ :=
set.ext $ λ x, by simp [bool.exists_bool, or_comm]
lemma inter_eq_Inter {s₁ s₂ : set α} : s₁ ∩ s₂ = ⋂ b : bool, cond b s₁ s₂ :=
set.ext $ λ x, by simp [bool.forall_bool, and_comm]
instance : complete_boolean_algebra (set α) :=
{ compl := compl,
sdiff := (\),
infi_sup_le_sup_Inf := assume s t x, show x ∈ (⋂ b ∈ t, s ∪ b) → x ∈ s ∪ (⋂₀ t),
by simp; exact assume h,
or.imp_right
(assume hn : x ∉ s, assume i hi, or.resolve_left (h i hi) hn)
(classical.em $ x ∈ s),
inf_Sup_le_supr_inf := assume s t x, show x ∈ s ∩ (⋃₀ t) → x ∈ (⋃ b ∈ t, s ∩ b),
by simp [-and_imp, and.left_comm],
.. set.boolean_algebra, .. set.lattice_set }
lemma sInter_union_sInter {S T : set (set α)} :
(⋂₀S) ∪ (⋂₀T) = (⋂p ∈ S.prod T, (p : (set α) × (set α)).1 ∪ p.2) :=
Inf_sup_Inf
lemma sUnion_inter_sUnion {s t : set (set α)} :
(⋃₀s) ∩ (⋃₀t) = (⋃p ∈ s.prod t, (p : (set α) × (set α )).1 ∩ p.2) :=
Sup_inf_Sup
/-- If `S` is a set of sets, and each `s ∈ S` can be represented as an intersection
of sets `T s hs`, then `⋂₀ S` is the intersection of the union of all `T s hs`. -/
lemma sInter_bUnion {S : set (set α)} {T : Π s ∈ S, set (set α)} (hT : ∀s∈S, s = ⋂₀ T s ‹s ∈ S›) :
⋂₀ (⋃s∈S, T s ‹_›) = ⋂₀ S :=
begin
ext,
simp only [and_imp, exists_prop, set.mem_sInter, set.mem_Union, exists_imp_distrib],
split,
{ assume H s sS,
rw [hT s sS, mem_sInter],
assume t tTs,
exact H t s sS tTs },
{ assume H t s sS tTs,
suffices : s ⊆ t, exact this (H s sS),
rw [hT s sS, sInter_eq_bInter],
exact bInter_subset_of_mem tTs }
end
/-- If `S` is a set of sets, and each `s ∈ S` can be represented as an union
of sets `T s hs`, then `⋃₀ S` is the union of the union of all `T s hs`. -/
lemma sUnion_bUnion {S : set (set α)} {T : Π s ∈ S, set (set α)} (hT : ∀s∈S, s = ⋃₀ T s ‹_›) :
⋃₀ (⋃s∈S, T s ‹_›) = ⋃₀ S :=
begin
ext,
simp only [exists_prop, set.mem_Union, set.mem_set_of_eq],
split,
{ rintros ⟨t, ⟨⟨s, ⟨sS, tTs⟩⟩, xt⟩⟩,
refine ⟨s, ⟨sS, _⟩⟩,
rw hT s sS,
exact subset_sUnion_of_mem tTs xt },
{ rintros ⟨s, ⟨sS, xs⟩⟩,
rw hT s sS at xs,
rcases mem_sUnion.1 xs with ⟨t, tTs, xt⟩,
exact ⟨t, ⟨⟨s, ⟨sS, tTs⟩⟩, xt⟩⟩ }
end
lemma Union_range_eq_sUnion {α β : Type*} (C : set (set α))
{f : ∀(s : C), β → s} (hf : ∀(s : C), surjective (f s)) :
(⋃(y : β), range (λ(s : C), (f s y).val)) = ⋃₀ C :=
begin
ext x, split,
{ rintro ⟨s, ⟨y, rfl⟩, ⟨⟨s, hs⟩, rfl⟩⟩, refine ⟨_, hs, _⟩, exact (f ⟨s, hs⟩ y).2 },
{ rintro ⟨s, hs, hx⟩, cases hf ⟨s, hs⟩ ⟨x, hx⟩ with y hy, refine ⟨_, ⟨y, rfl⟩, ⟨⟨s, hs⟩, _⟩⟩,
exact congr_arg subtype.val hy }
end
lemma Union_range_eq_Union {ι α β : Type*} (C : ι → set α)
{f : ∀(x : ι), β → C x} (hf : ∀(x : ι), surjective (f x)) :
(⋃(y : β), range (λ(x : ι), (f x y).val)) = ⋃x, C x :=
begin
ext x, rw [mem_Union, mem_Union], split,
{ rintro ⟨y, ⟨i, rfl⟩⟩, exact ⟨i, (f i y).2⟩ },
{ rintro ⟨i, hx⟩, cases hf i ⟨x, hx⟩ with y hy, refine ⟨y, ⟨i, congr_arg subtype.val hy⟩⟩ }
end
lemma union_distrib_Inter_right {ι : Type*} (s : ι → set α) (t : set α) :
(⋂ i, s i) ∪ t = (⋂ i, s i ∪ t) :=
begin
ext x,
rw [mem_union_eq, mem_Inter],
split ; finish
end
lemma union_distrib_Inter_left {ι : Type*} (s : ι → set α) (t : set α) :
t ∪ (⋂ i, s i) = (⋂ i, t ∪ s i) :=
begin
rw [union_comm, union_distrib_Inter_right],
simp [union_comm]
end
section function
/-!
### `maps_to`
-/
lemma maps_to_sUnion {S : set (set α)} {t : set β} {f : α → β} (H : ∀ s ∈ S, maps_to f s t) :
maps_to f (⋃₀ S) t :=
λ x ⟨s, hs, hx⟩, H s hs hx
lemma maps_to_Union {s : ι → set α} {t : set β} {f : α → β} (H : ∀ i, maps_to f (s i) t) :
maps_to f (⋃ i, s i) t :=
maps_to_sUnion $ forall_range_iff.2 H
lemma maps_to_bUnion {p : ι → Prop} {s : Π (i : ι) (hi : p i), set α} {t : set β} {f : α → β}
(H : ∀ i hi, maps_to f (s i hi) t) :
maps_to f (⋃ i hi, s i hi) t :=
maps_to_Union $ λ i, maps_to_Union (H i)
lemma maps_to_Union_Union {s : ι → set α} {t : ι → set β} {f : α → β}
(H : ∀ i, maps_to f (s i) (t i)) :
maps_to f (⋃ i, s i) (⋃ i, t i) :=
maps_to_Union $ λ i, (H i).mono (subset.refl _) (subset_Union t i)
lemma maps_to_bUnion_bUnion {p : ι → Prop} {s : Π i (hi : p i), set α} {t : Π i (hi : p i), set β}
{f : α → β} (H : ∀ i hi, maps_to f (s i hi) (t i hi)) :
maps_to f (⋃ i hi, s i hi) (⋃ i hi, t i hi) :=
maps_to_Union_Union $ λ i, maps_to_Union_Union (H i)
lemma maps_to_sInter {s : set α} {T : set (set β)} {f : α → β} (H : ∀ t ∈ T, maps_to f s t) :
maps_to f s (⋂₀ T) :=
λ x hx t ht, H t ht hx
lemma maps_to_Inter {s : set α} {t : ι → set β} {f : α → β} (H : ∀ i, maps_to f s (t i)) :
maps_to f s (⋂ i, t i) :=
λ x hx, mem_Inter.2 $ λ i, H i hx
lemma maps_to_bInter {p : ι → Prop} {s : set α} {t : Π i (hi : p i), set β} {f : α → β}
(H : ∀ i hi, maps_to f s (t i hi)) :
maps_to f s (⋂ i hi, t i hi) :=
maps_to_Inter $ λ i, maps_to_Inter (H i)
lemma maps_to_Inter_Inter {s : ι → set α} {t : ι → set β} {f : α → β}
(H : ∀ i, maps_to f (s i) (t i)) :
maps_to f (⋂ i, s i) (⋂ i, t i) :=
maps_to_Inter $ λ i, (H i).mono (Inter_subset s i) (subset.refl _)
lemma maps_to_bInter_bInter {p : ι → Prop} {s : Π i (hi : p i), set α}
{t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, maps_to f (s i hi) (t i hi)) :
maps_to f (⋂ i hi, s i hi) (⋂ i hi, t i hi) :=
maps_to_Inter_Inter $ λ i, maps_to_Inter_Inter (H i)
lemma image_Inter_subset (s : ι → set α) (f : α → β) :
f '' (⋂ i, s i) ⊆ ⋂ i, f '' (s i) :=
(maps_to_Inter_Inter $ λ i, maps_to_image f (s i)).image_subset
lemma image_bInter_subset {p : ι → Prop} (s : Π i (hi : p i), set α) (f : α → β) :
f '' (⋂ i hi, s i hi) ⊆ ⋂ i hi, f '' (s i hi) :=
(maps_to_bInter_bInter $ λ i hi, maps_to_image f (s i hi)).image_subset
lemma image_sInter_subset (S : set (set α)) (f : α → β) :
f '' (⋂₀ S) ⊆ ⋂ s ∈ S, f '' s :=
by { rw sInter_eq_bInter, apply image_bInter_subset }
/-!
### `inj_on`
-/
lemma inj_on.image_Inter_eq [nonempty ι] {s : ι → set α} {f : α → β} (h : inj_on f (⋃ i, s i)) :
f '' (⋂ i, s i) = ⋂ i, f '' (s i) :=
begin
inhabit ι,
refine subset.antisymm (image_Inter_subset s f) (λ y hy, _),
simp only [mem_Inter, mem_image_iff_bex] at hy,
choose x hx hy using hy,
refine ⟨x (default ι), mem_Inter.2 $ λ i, _, hy _⟩,
suffices : x (default ι) = x i,
{ rw this, apply hx },
replace hx : ∀ i, x i ∈ ⋃ j, s j := λ i, (subset_Union _ _) (hx i),
apply h (hx _) (hx _),
simp only [hy]
end
lemma inj_on.image_bInter_eq {p : ι → Prop} {s : Π i (hi : p i), set α} (hp : ∃ i, p i) {f : α → β}
(h : inj_on f (⋃ i hi, s i hi)) :
f '' (⋂ i hi, s i hi) = ⋂ i hi, f '' (s i hi) :=
begin
simp only [Inter, infi_subtype'],
haveI : nonempty {i // p i} := nonempty_subtype.2 hp,
apply inj_on.image_Inter_eq,
simpa only [Union, supr_subtype'] using h
end
lemma inj_on_Union_of_directed {s : ι → set α} (hs : directed (⊆) s)
{f : α → β} (hf : ∀ i, inj_on f (s i)) :
inj_on f (⋃ i, s i) :=
begin
intros x hx y hy hxy,
rcases mem_Union.1 hx with ⟨i, hx⟩,
rcases mem_Union.1 hy with ⟨j, hy⟩,
rcases hs i j with ⟨k, hi, hj⟩,
exact hf k (hi hx) (hj hy) hxy
end
/-!
### `surj_on`
-/
lemma surj_on_sUnion {s : set α} {T : set (set β)} {f : α → β} (H : ∀ t ∈ T, surj_on f s t) :
surj_on f s (⋃₀ T) :=
λ x ⟨t, ht, hx⟩, H t ht hx
lemma surj_on_Union {s : set α} {t : ι → set β} {f : α → β} (H : ∀ i, surj_on f s (t i)) :
surj_on f s (⋃ i, t i) :=
surj_on_sUnion $ forall_range_iff.2 H
lemma surj_on_Union_Union {s : ι → set α} {t : ι → set β} {f : α → β}
(H : ∀ i, surj_on f (s i) (t i)) :
surj_on f (⋃ i, s i) (⋃ i, t i) :=
surj_on_Union $ λ i, (H i).mono (subset_Union _ _) (subset.refl _)
lemma surj_on_bUnion {p : ι → Prop} {s : set α} {t : Π i (hi : p i), set β} {f : α → β}
(H : ∀ i hi, surj_on f s (t i hi)) :
surj_on f s (⋃ i hi, t i hi) :=
surj_on_Union $ λ i, surj_on_Union (H i)
lemma surj_on_bUnion_bUnion {p : ι → Prop} {s : Π i (hi : p i), set α} {t : Π i (hi : p i), set β}
{f : α → β} (H : ∀ i hi, surj_on f (s i hi) (t i hi)) :
surj_on f (⋃ i hi, s i hi) (⋃ i hi, t i hi) :=
surj_on_Union_Union $ λ i, surj_on_Union_Union (H i)
lemma surj_on_Inter [hi : nonempty ι] {s : ι → set α} {t : set β} {f : α → β}
(H : ∀ i, surj_on f (s i) t) (Hinj : inj_on f (⋃ i, s i)) :
surj_on f (⋂ i, s i) t :=
begin
intros y hy,
rw [Hinj.image_Inter_eq, mem_Inter],
exact λ i, H i hy
end
lemma surj_on_Inter_Inter [hi : nonempty ι] {s : ι → set α} {t : ι → set β} {f : α → β}
(H : ∀ i, surj_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) :
surj_on f (⋂ i, s i) (⋂ i, t i) :=
surj_on_Inter (λ i, (H i).mono (subset.refl _) (Inter_subset _ _)) Hinj
/-!
### `bij_on`
-/
lemma bij_on_Union {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i))
(Hinj : inj_on f (⋃ i, s i)) :
bij_on f (⋃ i, s i) (⋃ i, t i) :=
⟨maps_to_Union_Union $ λ i, (H i).maps_to, Hinj, surj_on_Union_Union $ λ i, (H i).surj_on⟩
lemma bij_on_Inter [hi :nonempty ι] {s : ι → set α} {t : ι → set β} {f : α → β}
(H : ∀ i, bij_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) :
bij_on f (⋂ i, s i) (⋂ i, t i) :=
⟨maps_to_Inter_Inter $ λ i, (H i).maps_to, hi.elim $ λ i, (H i).inj_on.mono (Inter_subset _ _),
surj_on_Inter_Inter (λ i, (H i).surj_on) Hinj⟩
lemma bij_on_Union_of_directed {s : ι → set α} (hs : directed (⊆) s) {t : ι → set β} {f : α → β}
(H : ∀ i, bij_on f (s i) (t i)) :
bij_on f (⋃ i, s i) (⋃ i, t i) :=
bij_on_Union H $ inj_on_Union_of_directed hs (λ i, (H i).inj_on)
lemma bij_on_Inter_of_directed [nonempty ι] {s : ι → set α} (hs : directed (⊆) s) {t : ι → set β}
{f : α → β} (H : ∀ i, bij_on f (s i) (t i)) :
bij_on f (⋂ i, s i) (⋂ i, t i) :=
bij_on_Inter H $ inj_on_Union_of_directed hs (λ i, (H i).inj_on)
end function
section
variables {p : Prop} {μ : p → set α}
@[simp] lemma Inter_pos (hp : p) : (⋂h:p, μ h) = μ hp := infi_pos hp
@[simp] lemma Inter_neg (hp : ¬ p) : (⋂h:p, μ h) = univ := infi_neg hp
@[simp] lemma Union_pos (hp : p) : (⋃h:p, μ h) = μ hp := supr_pos hp
@[simp] lemma Union_neg (hp : ¬ p) : (⋃h:p, μ h) = ∅ := supr_neg hp
@[simp] lemma Union_empty {ι : Sort*} : (⋃i:ι, ∅:set α) = ∅ := supr_bot
@[simp] lemma Inter_univ {ι : Sort*} : (⋂i:ι, univ:set α) = univ := infi_top
end
section image
lemma image_Union {f : α → β} {s : ι → set α} : f '' (⋃ i, s i) = (⋃i, f '' s i) :=
begin
apply set.ext, intro x,
simp [image, exists_and_distrib_right.symm, -exists_and_distrib_right],
exact exists_swap
end
lemma univ_subtype {p : α → Prop} : (univ : set (subtype p)) = (⋃x (h : p x), {⟨x, h⟩}) :=
set.ext $ assume ⟨x, h⟩, by simp [h]
lemma range_eq_Union {ι} (f : ι → α) : range f = (⋃i, {f i}) :=
set.ext $ assume a, by simp [@eq_comm α a]
lemma image_eq_Union (f : α → β) (s : set α) : f '' s = (⋃i∈s, {f i}) :=
set.ext $ assume b, by simp [@eq_comm β b]
@[simp] lemma bUnion_range {f : ι → α} {g : α → set β} : (⋃x ∈ range f, g x) = (⋃y, g (f y)) :=
supr_range
@[simp] lemma bInter_range {f : ι → α} {g : α → set β} : (⋂x ∈ range f, g x) = (⋂y, g (f y)) :=
infi_range
variables {s : set γ} {f : γ → α} {g : α → set β}
@[simp] lemma bUnion_image : (⋃x∈ (f '' s), g x) = (⋃y ∈ s, g (f y)) :=
supr_image
@[simp] lemma bInter_image : (⋂x∈ (f '' s), g x) = (⋂y ∈ s, g (f y)) :=
infi_image
end image
section image2
variables (f : α → β → γ) {s : set α} {t : set β}
lemma Union_image_left : (⋃ a ∈ s, f a '' t) = image2 f s t :=
by { ext y, split; simp only [mem_Union]; rintros ⟨a, ha, x, hx, ax⟩; exact ⟨a, x, ha, hx, ax⟩ }
lemma Union_image_right : (⋃ b ∈ t, (λ a, f a b) '' s) = image2 f s t :=
by { ext y, split; simp only [mem_Union]; rintros ⟨a, b, c, d, e⟩, exact ⟨c, a, d, b, e⟩,
exact ⟨b, d, a, c, e⟩ }
end image2
section preimage
theorem monotone_preimage {f : α → β} : monotone (preimage f) := assume a b h, preimage_mono h
@[simp] theorem preimage_Union {ι : Sort w} {f : α → β} {s : ι → set β} :
preimage f (⋃i, s i) = (⋃i, preimage f (s i)) :=
set.ext $ by simp [preimage]
theorem preimage_bUnion {ι} {f : α → β} {s : set ι} {t : ι → set β} :
f ⁻¹' (⋃i ∈ s, t i) = (⋃i ∈ s, f ⁻¹' (t i)) :=
by simp
@[simp] theorem preimage_sUnion {f : α → β} {s : set (set β)} :
f ⁻¹' (⋃₀ s) = (⋃t ∈ s, f ⁻¹' t) :=
set.ext $ by simp [preimage]
lemma preimage_Inter {ι : Sort*} {s : ι → set β} {f : α → β} :
f ⁻¹' (⋂ i, s i) = (⋂ i, f ⁻¹' s i) :=
by ext; simp
lemma preimage_bInter {s : γ → set β} {t : set γ} {f : α → β} :
f ⁻¹' (⋂ i∈t, s i) = (⋂ i∈t, f ⁻¹' s i) :=
by ext; simp
@[simp] lemma bUnion_preimage_singleton (f : α → β) (s : set β) : (⋃ y ∈ s, f ⁻¹' {y}) = f ⁻¹' s :=
by rw [← preimage_bUnion, bUnion_of_singleton]
lemma bUnion_range_preimage_singleton (f : α → β) : (⋃ y ∈ range f, f ⁻¹' {y}) = univ :=
by simp
end preimage
section prod
theorem monotone_prod [preorder α] {f : α → set β} {g : α → set γ}
(hf : monotone f) (hg : monotone g) : monotone (λx, (f x).prod (g x)) :=
assume a b h, prod_mono (hf h) (hg h)
alias monotone_prod ← monotone.set_prod
lemma prod_Union {ι} {s : set α} {t : ι → set β} : s.prod (⋃ i, t i) = ⋃ i, s.prod (t i) :=
by { ext, simp }
lemma prod_bUnion {ι} {u : set ι} {s : set α} {t : ι → set β} :
s.prod (⋃ i ∈ u, t i) = ⋃ i ∈ u, s.prod (t i) :=
by simp_rw [prod_Union]
lemma prod_sUnion {s : set α} {C : set (set β)} : s.prod (⋃₀ C) = ⋃₀ ((λ t, s.prod t) '' C) :=
by { simp only [sUnion_eq_bUnion, prod_bUnion, bUnion_image] }
lemma Union_prod {ι} {s : ι → set α} {t : set β} : (⋃ i, s i).prod t = ⋃ i, (s i).prod t :=
by { ext, simp }
lemma bUnion_prod {ι} {u : set ι} {s : ι → set α} {t : set β} :
(⋃ i ∈ u, s i).prod t = ⋃ i ∈ u, (s i).prod t :=
by simp_rw [Union_prod]
lemma sUnion_prod {C : set (set α)} {t : set β} :
(⋃₀ C).prod t = ⋃₀ ((λ s : set α, s.prod t) '' C) :=
by { simp only [sUnion_eq_bUnion, bUnion_prod, bUnion_image] }
lemma Union_prod_of_monotone [semilattice_sup α] {s : α → set β} {t : α → set γ}
(hs : monotone s) (ht : monotone t) : (⋃ x, (s x).prod (t x)) = (⋃ x, (s x)).prod (⋃ x, (t x)) :=
begin
ext ⟨z, w⟩, simp only [mem_prod, mem_Union, exists_imp_distrib, and_imp, iff_def], split,
{ intros x hz hw, exact ⟨⟨x, hz⟩, ⟨x, hw⟩⟩ },
{ intros x hz x' hw, exact ⟨x ⊔ x', hs le_sup_left hz, ht le_sup_right hw⟩ }
end
end prod
section seq
/-- Given a set `s` of functions `α → β` and `t : set α`, `seq s t` is the union of `f '' t` over
all `f ∈ s`. -/
def seq (s : set (α → β)) (t : set α) : set β := {b | ∃f∈s, ∃a∈t, (f : α → β) a = b}
lemma seq_def {s : set (α → β)} {t : set α} : seq s t = ⋃f∈s, f '' t :=
set.ext $ by simp [seq]
@[simp] lemma mem_seq_iff {s : set (α → β)} {t : set α} {b : β} :
b ∈ seq s t ↔ ∃ (f ∈ s) (a ∈ t), (f : α → β) a = b :=
iff.rfl
lemma seq_subset {s : set (α → β)} {t : set α} {u : set β} :
seq s t ⊆ u ↔ (∀f∈s, ∀a∈t, (f : α → β) a ∈ u) :=
iff.intro
(assume h f hf a ha, h ⟨f, hf, a, ha, rfl⟩)
(assume h b ⟨f, hf, a, ha, eq⟩, eq ▸ h f hf a ha)
lemma seq_mono {s₀ s₁ : set (α → β)} {t₀ t₁ : set α} (hs : s₀ ⊆ s₁) (ht : t₀ ⊆ t₁) :
seq s₀ t₀ ⊆ seq s₁ t₁ :=
assume b ⟨f, hf, a, ha, eq⟩, ⟨f, hs hf, a, ht ha, eq⟩
lemma singleton_seq {f : α → β} {t : set α} : set.seq {f} t = f '' t :=
set.ext $ by simp
lemma seq_singleton {s : set (α → β)} {a : α} : set.seq s {a} = (λf:α→β, f a) '' s :=
set.ext $ by simp
lemma seq_seq {s : set (β → γ)} {t : set (α → β)} {u : set α} :
seq s (seq t u) = seq (seq ((∘) '' s) t) u :=
begin
refine set.ext (assume c, iff.intro _ _),
{ rintros ⟨f, hfs, b, ⟨g, hg, a, hau, rfl⟩, rfl⟩,
exact ⟨f ∘ g, ⟨(∘) f, mem_image_of_mem _ hfs, g, hg, rfl⟩, a, hau, rfl⟩ },
{ rintros ⟨fg, ⟨fc, ⟨f, hfs, rfl⟩, g, hgt, rfl⟩, a, ha, rfl⟩,
exact ⟨f, hfs, g a, ⟨g, hgt, a, ha, rfl⟩, rfl⟩ }
end
lemma image_seq {f : β → γ} {s : set (α → β)} {t : set α} :
f '' seq s t = seq ((∘) f '' s) t :=
by rw [← singleton_seq, ← singleton_seq, seq_seq, image_singleton]
lemma prod_eq_seq {s : set α} {t : set β} : s.prod t = (prod.mk '' s).seq t :=
begin
ext ⟨a, b⟩,
split,
{ rintros ⟨ha, hb⟩, exact ⟨prod.mk a, ⟨a, ha, rfl⟩, b, hb, rfl⟩ },
{ rintros ⟨f, ⟨x, hx, rfl⟩, y, hy, eq⟩, rw ← eq, exact ⟨hx, hy⟩ }
end
lemma prod_image_seq_comm (s : set α) (t : set β) :
(prod.mk '' s).seq t = seq ((λb a, (a, b)) '' t) s :=
by rw [← prod_eq_seq, ← image_swap_prod, prod_eq_seq, image_seq, ← image_comp, prod.swap]
lemma image2_eq_seq (f : α → β → γ) (s : set α) (t : set β) : image2 f s t = seq (f '' s) t :=
by { ext, simp }
end seq
instance : monad set :=
{ pure := λ(α : Type u) a, {a},
bind := λ(α β : Type u) s f, ⋃i∈s, f i,
seq := λ(α β : Type u), set.seq,
map := λ(α β : Type u), set.image }
section monad
variables {α' β' : Type u} {s : set α'} {f : α' → set β'} {g : set (α' → β')}
@[simp] lemma bind_def : s >>= f = ⋃i∈s, f i := rfl
@[simp] lemma fmap_eq_image (f : α' → β') : f <$> s = f '' s := rfl
@[simp] lemma seq_eq_set_seq {α β : Type*} (s : set (α → β)) (t : set α) : s <*> t = s.seq t := rfl
@[simp] lemma pure_def (a : α) : (pure a : set α) = {a} := rfl
end monad
instance : is_lawful_monad set :=
{ pure_bind := assume α β x f, by simp,
bind_assoc := assume α β γ s f g, set.ext $ assume a,
by simp [exists_and_distrib_right.symm, -exists_and_distrib_right,
exists_and_distrib_left.symm, -exists_and_distrib_left, and_assoc];
exact exists_swap,
id_map := assume α, id_map,
bind_pure_comp_eq_map := assume α β f s, set.ext $ by simp [set.image, eq_comm],
bind_map_eq_seq := assume α β s t, by simp [seq_def] }
instance : is_comm_applicative (set : Type u → Type u) :=
⟨ assume α β s t, prod_image_seq_comm s t ⟩
section pi
lemma pi_def {α : Type*} {π : α → Type*} (i : set α) (s : Πa, set (π a)) :
pi i s = (⋂ a∈i, ((λf:(Πa, π a), f a) ⁻¹' (s a))) :=
by ext; simp [pi]
end pi
end set
/- disjoint sets -/
section disjoint
variables {s t u : set α}
namespace disjoint
/-! We define some lemmas in the `disjoint` namespace to be able to use projection notation. -/
theorem union_left (hs : disjoint s u) (ht : disjoint t u) : disjoint (s ∪ t) u :=
hs.sup_left ht
theorem union_right (ht : disjoint s t) (hu : disjoint s u) : disjoint s (t ∪ u) :=
ht.sup_right hu
lemma preimage {α β} (f : α → β) {s t : set β} (h : disjoint s t) : disjoint (f ⁻¹' s) (f ⁻¹' t) :=
λ x hx, h hx
end disjoint
namespace set
protected theorem disjoint_iff : disjoint s t ↔ s ∩ t ⊆ ∅ := iff.rfl
theorem disjoint_iff_inter_eq_empty : disjoint s t ↔ s ∩ t = ∅ :=
disjoint_iff
lemma not_disjoint_iff : ¬disjoint s t ↔ ∃x, x ∈ s ∧ x ∈ t :=
not_forall.trans $ exists_congr $ λ x, not_not
lemma disjoint_left : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t :=
show (∀ x, ¬(x ∈ s ∩ t)) ↔ _, from ⟨λ h a, not_and.1 $ h a, λ h a, not_and.2 $ h a⟩
theorem disjoint_right : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s :=
by rw [disjoint.comm, disjoint_left]
theorem disjoint_of_subset_left (h : s ⊆ u) (d : disjoint u t) : disjoint s t :=
d.mono_left h
theorem disjoint_of_subset_right (h : t ⊆ u) (d : disjoint s u) : disjoint s t :=
d.mono_right h
theorem disjoint_of_subset {s t u v : set α} (h1 : s ⊆ u) (h2 : t ⊆ v) (d : disjoint u v) :
disjoint s t :=
d.mono h1 h2
@[simp] theorem disjoint_union_left :
disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u :=
disjoint_sup_left
@[simp] theorem disjoint_union_right :
disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u :=
disjoint_sup_right
theorem disjoint_diff {a b : set α} : disjoint a (b \ a) :=
disjoint_iff.2 (inter_diff_self _ _)
theorem disjoint_compl_left (s : set α) : disjoint sᶜ s := assume a ⟨h₁, h₂⟩, h₁ h₂
theorem disjoint_compl_right (s : set α) : disjoint s sᶜ := assume a ⟨h₁, h₂⟩, h₂ h₁
@[simp] lemma univ_disjoint {s : set α}: disjoint univ s ↔ s = ∅ :=
by simp [set.disjoint_iff_inter_eq_empty]
@[simp] lemma disjoint_univ {s : set α} : disjoint s univ ↔ s = ∅ :=
by simp [set.disjoint_iff_inter_eq_empty]
@[simp] theorem disjoint_singleton_left {a : α} {s : set α} : disjoint {a} s ↔ a ∉ s :=
by simp [set.disjoint_iff, subset_def]; exact iff.rfl
@[simp] theorem disjoint_singleton_right {a : α} {s : set α} : disjoint s {a} ↔ a ∉ s :=
by rw [disjoint.comm]; exact disjoint_singleton_left
theorem disjoint_image_image {f : β → α} {g : γ → α} {s : set β} {t : set γ}
(h : ∀b∈s, ∀c∈t, f b ≠ g c) : disjoint (f '' s) (g '' t) :=
by rintros a ⟨⟨b, hb, eq⟩, ⟨c, hc, rfl⟩⟩; exact h b hb c hc eq
theorem pairwise_on_disjoint_fiber (f : α → β) (s : set β) :
pairwise_on s (disjoint on (λ y, f ⁻¹' {y})) :=
λ y₁ _ y₂ _ hy x ⟨hx₁, hx₂⟩, hy (eq.trans (eq.symm hx₁) hx₂)
lemma preimage_eq_empty {f : α → β} {s : set β} (h : disjoint s (range f)) :
f ⁻¹' s = ∅ :=
by simpa using h.preimage f
lemma preimage_eq_empty_iff {f : α → β} {s : set β} : disjoint s (range f) ↔ f ⁻¹' s = ∅ :=
⟨preimage_eq_empty,
λ h, by { simp [eq_empty_iff_forall_not_mem, set.disjoint_iff_inter_eq_empty] at h ⊢, finish }⟩
end set
end disjoint
namespace set
/-- A collection of sets is `pairwise_disjoint`, if any two different sets in this collection
are disjoint. -/
def pairwise_disjoint (s : set (set α)) : Prop :=
pairwise_on s disjoint
lemma pairwise_disjoint.subset {s t : set (set α)} (h : s ⊆ t)
(ht : pairwise_disjoint t) : pairwise_disjoint s :=
pairwise_on.mono h ht
lemma pairwise_disjoint.range {s : set (set α)} (f : s → set α) (hf : ∀(x : s), f x ⊆ x.1)
(ht : pairwise_disjoint s) : pairwise_disjoint (range f) :=
begin
rintro _ ⟨x, rfl⟩ _ ⟨y, rfl⟩ hxy, refine (ht _ x.2 _ y.2 _).mono (hf x) (hf y),
intro h, apply hxy, apply congr_arg f, exact subtype.eq h
end
/- classical -/
lemma pairwise_disjoint.elim {s : set (set α)} (h : pairwise_disjoint s) {x y : set α}
(hx : x ∈ s) (hy : y ∈ s) (z : α) (hzx : z ∈ x) (hzy : z ∈ y) : x = y :=
not_not.1 $ λ h', h x hx y hy h' ⟨hzx, hzy⟩
end set
namespace set
variables (t : α → set β)
lemma subset_diff {s t u : set α} : s ⊆ t \ u ↔ s ⊆ t ∧ disjoint s u :=
⟨λ h, ⟨λ x hxs, (h hxs).1, λ x ⟨hxs, hxu⟩, (h hxs).2 hxu⟩,
λ ⟨h1, h2⟩ x hxs, ⟨h1 hxs, λ hxu, h2 ⟨hxs, hxu⟩⟩⟩
/-- If `t` is an indexed family of sets, then there is a natural map from `Σ i, t i` to `⋃ i, t i`
sending `⟨i, x⟩` to `x`. -/
def sigma_to_Union (x : Σi, t i) : (⋃i, t i) := ⟨x.2, mem_Union.2 ⟨x.1, x.2.2⟩⟩
lemma sigma_to_Union_surjective : surjective (sigma_to_Union t)
| ⟨b, hb⟩ := have ∃a, b ∈ t a, by simpa using hb, let ⟨a, hb⟩ := this in ⟨⟨a, ⟨b, hb⟩⟩, rfl⟩
lemma sigma_to_Union_injective (h : ∀i j, i ≠ j → disjoint (t i) (t j)) :
injective (sigma_to_Union t)
| ⟨a₁, ⟨b₁, h₁⟩⟩ ⟨a₂, ⟨b₂, h₂⟩⟩ eq :=
have b_eq : b₁ = b₂, from congr_arg subtype.val eq,
have a_eq : a₁ = a₂, from classical.by_contradiction $ assume ne,
have b₁ ∈ t a₁ ∩ t a₂, from ⟨h₁, b_eq.symm ▸ h₂⟩,
h _ _ ne this,
sigma.eq a_eq $ subtype.eq $ by subst b_eq; subst a_eq
lemma sigma_to_Union_bijective (h : ∀i j, i ≠ j → disjoint (t i) (t j)) :
bijective (sigma_to_Union t) :=
⟨sigma_to_Union_injective t h, sigma_to_Union_surjective t⟩
/-- Equivalence between a disjoint union and a dependent sum. -/
noncomputable def Union_eq_sigma_of_disjoint {t : α → set β}
(h : ∀i j, i ≠ j → disjoint (t i) (t j)) : (⋃i, t i) ≃ (Σi, t i) :=
(equiv.of_bijective _ $ sigma_to_Union_bijective t h).symm
/-- Equivalence between a disjoint bounded union and a dependent sum. -/
noncomputable def bUnion_eq_sigma_of_disjoint {s : set α} {t : α → set β}
(h : pairwise_on s (disjoint on t)) : (⋃i∈s, t i) ≃ (Σi:s, t i.val) :=
equiv.trans (equiv.set_congr (bUnion_eq_Union _ _)) $ Union_eq_sigma_of_disjoint $
assume ⟨i, hi⟩ ⟨j, hj⟩ ne, h _ hi _ hj $ assume eq, ne $ subtype.eq eq
end set
|
45c1bf290ff26fcc5b2cc458ba6ba1ec2f92045d | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/ring_theory/polynomial/vieta.lean | d98adcd5c1f08420da5c1c15831d284bf2838864 | [
"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 | 4,426 | lean | /-
Copyright (c) 2020 Hanting Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Hanting Zhang
-/
import ring_theory.polynomial.symmetric
/-!
# Vieta's Formula
The main result is `vieta.prod_X_add_C_eq_sum_esymm`, which shows that the product of linear terms
`λ + X i` is equal to a linear combination of the symmetric polynomials `esymm σ R j`.
## Implementation Notes:
We first take the viewpoint where the "roots" `X i` are variables. This means we work over
`polynomial (mv_polynomial σ R)`, which enables us to talk about linear combinations of
`esymm σ R j`. We then derive Vieta's formula in `polynomial R` by giving a
valuation from each `X i` to `r i`.
-/
universes u
open_locale big_operators
open finset polynomial fintype
namespace mv_polynomial
variables {R : Type u} [comm_semiring R]
variables (σ : Type u) [fintype σ]
/-- A sum version of Vieta's formula. Viewing `X i` as variables,
the product of linear terms `λ + X i` is equal to a linear combination of
the symmetric polynomials `esymm σ R j`. -/
lemma prod_X_add_C_eq_sum_esymm :
(∏ i : σ, (polynomial.C (X i) + polynomial.X) : polynomial (mv_polynomial σ R) )=
∑ j in range (card σ + 1),
(polynomial.C (esymm σ R j) * polynomial.X ^ (card σ - j)) :=
begin
classical,
rw [prod_add, sum_powerset],
refine sum_congr begin congr end (λ j hj, _),
rw [esymm, polynomial.C.map_sum, sum_mul],
refine sum_congr rfl (λ t ht, _),
have h : (univ \ t).card = card σ - j :=
by { rw card_sdiff (mem_powerset_len.mp ht).1, congr, exact (mem_powerset_len.mp ht).2 },
rw [(polynomial.C : mv_polynomial σ R →+* polynomial _).map_prod, prod_const, ← h],
congr,
end
/-- A fully expanded sum version of Vieta's formula, evaluated at the roots.
The product of linear terms `X + r i` is equal to `∑ j in range (n + 1), e_j * X ^ (n - j)`,
where `e_j` is the `j`th symmetric polynomial of the constant terms `r i`. -/
lemma prod_X_add_C_eval (r : σ → R) : ∏ i : σ, (polynomial.C (r i) + polynomial.X) =
∑ i in range (card σ + 1), (∑ t in powerset_len i (univ : finset σ),
∏ i in t, polynomial.C (r i)) * polynomial.X ^ (card σ - i) :=
begin
classical,
have h := @prod_X_add_C_eq_sum_esymm _ _ σ _,
apply_fun (polynomial.map (eval r)) at h,
rw [map_prod, map_sum] at h,
convert h,
simp only [eval_X, map_add, polynomial.map_C, polynomial.map_X, eq_self_iff_true],
funext,
simp only [function.funext_iff, esymm, polynomial.map_C, map_sum, polynomial.C.map_sum,
polynomial.map_C, map_pow, polynomial.map_X, map_mul],
congr,
funext,
simp only [eval_prod, eval_X, (polynomial.C : R →+* polynomial R).map_prod],
end
lemma esymm_to_sum (r : σ → R) (j : ℕ) : polynomial.C (eval r (esymm σ R j)) =
∑ t in powerset_len j (univ : finset σ), ∏ i in t, polynomial.C (r i) :=
by simp only [esymm, eval_sum, eval_prod, eval_X, polynomial.C.map_sum,
(polynomial.C : R →+* polynomial _).map_prod]
/-- Vieta's formula for the coefficients of the product of linear terms `X + r i`,
The `k`th coefficient is `∑ t in powerset_len (card σ - k) (univ : finset σ), ∏ i in t, r i`,
i.e. the symmetric polynomial `esymm σ R (card σ - k)` of the constant terms `r i`. -/
lemma prod_X_add_C_coeff (r : σ → R) (k : ℕ) (h : k ≤ card σ):
polynomial.coeff (∏ i : σ, (polynomial.C (r i) + polynomial.X)) k =
∑ t in powerset_len (card σ - k) (univ : finset σ), ∏ i in t, r i :=
begin
have hk : filter (λ (x : ℕ), k = card σ - x) (range (card σ + 1)) = {card σ - k} :=
begin
refine finset.ext (λ a, ⟨λ ha, _, λ ha, _ ⟩),
rw mem_singleton,
have hσ := (nat.sub_eq_iff_eq_add (mem_range_succ_iff.mp
(mem_filter.mp ha).1)).mp ((mem_filter.mp ha).2).symm,
symmetry,
rwa [(nat.sub_eq_iff_eq_add h), add_comm],
rw mem_filter,
have haσ : a ∈ range (card σ + 1) :=
by { rw mem_singleton.mp ha, exact mem_range_succ_iff.mpr (@sub_le_self' _ _ _ _ _ k) },
refine ⟨haσ, eq.symm _⟩,
rw nat.sub_eq_iff_eq_add (mem_range_succ_iff.mp haσ),
have hσ := (nat.sub_eq_iff_eq_add h).mp (mem_singleton.mp ha).symm,
rwa add_comm,
end,
simp only [prod_X_add_C_eval, ← esymm_to_sum, finset_sum_coeff, coeff_C_mul_X, sum_ite, hk,
sum_singleton, esymm, eval_sum, eval_prod, eval_X, add_zero, sum_const_zero],
end
end mv_polynomial
|
df0652b336c9314442990cf758b77e4811791c7b | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/finset/basic.lean | b5a9474b392566ff28c01b488a61a94b7b6257bf | [] | 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 | 115,318 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.multiset.finset_ops
import Mathlib.tactic.monotonicity.default
import Mathlib.tactic.apply
import Mathlib.tactic.nth_rewrite.default
import Mathlib.PostPort
universes u_4 l u_1 u u_2 u_3
namespace Mathlib
/-!
# Finite sets
mathlib has several different models for finite sets,
and it can be confusing when you're first getting used to them!
This file builds the basic theory of `finset α`,
modelled as a `multiset α` without duplicates.
It's "constructive" in the since that there is an underlying list of elements,
although this is wrapped in a quotient by permutations,
so anytime you actually use this list you're obligated to show you didn't depend on the ordering.
There's also the typeclass `fintype α`
(which asserts that there is some `finset α` containing every term of type `α`)
as well as the predicate `finite` on `s : set α` (which asserts `nonempty (fintype s)`).
-/
/-- `finset α` is the type of finite sets of elements of `α`. It is implemented
as a multiset (a list up to permutation) which has no duplicate elements. -/
structure finset (α : Type u_4)
where
val : multiset α
nodup : multiset.nodup val
namespace finset
theorem eq_of_veq {α : Type u_1} {s : finset α} {t : finset α} : val s = val t → s = t := sorry
@[simp] theorem val_inj {α : Type u_1} {s : finset α} {t : finset α} : val s = val t ↔ s = t :=
{ mp := eq_of_veq, mpr := congr_arg fun {s : finset α} => val s }
@[simp] theorem erase_dup_eq_self {α : Type u_1} [DecidableEq α] (s : finset α) : multiset.erase_dup (val s) = val s :=
iff.mpr multiset.erase_dup_eq_self (nodup s)
protected instance has_decidable_eq {α : Type u_1} [DecidableEq α] : DecidableEq (finset α) :=
sorry
/-! ### membership -/
protected instance has_mem {α : Type u_1} : has_mem α (finset α) :=
has_mem.mk fun (a : α) (s : finset α) => a ∈ val s
theorem mem_def {α : Type u_1} {a : α} {s : finset α} : a ∈ s ↔ a ∈ val s :=
iff.rfl
@[simp] theorem mem_mk {α : Type u_1} {a : α} {s : multiset α} {nd : multiset.nodup s} : a ∈ mk s nd ↔ a ∈ s :=
iff.rfl
protected instance decidable_mem {α : Type u_1} [h : DecidableEq α] (a : α) (s : finset α) : Decidable (a ∈ s) :=
multiset.decidable_mem a (val s)
/-! ### set coercion -/
/-- Convert a finset to a set in the natural way. -/
protected instance set.has_coe_t {α : Type u_1} : has_coe_t (finset α) (set α) :=
has_coe_t.mk fun (s : finset α) => set_of fun (x : α) => x ∈ s
@[simp] theorem mem_coe {α : Type u_1} {a : α} {s : finset α} : a ∈ ↑s ↔ a ∈ s :=
iff.rfl
@[simp] theorem set_of_mem {α : Type u_1} {s : finset α} : (set_of fun (a : α) => a ∈ s) = ↑s :=
rfl
@[simp] theorem coe_mem {α : Type u_1} {s : finset α} (x : ↥↑s) : ↑x ∈ s :=
subtype.property x
@[simp] theorem mk_coe {α : Type u_1} {s : finset α} (x : ↥↑s) {h : ↑x ∈ ↑s} : { val := ↑x, property := h } = x :=
subtype.coe_eta x h
protected instance decidable_mem' {α : Type u_1} [DecidableEq α] (a : α) (s : finset α) : Decidable (a ∈ ↑s) :=
finset.decidable_mem a s
/-! ### extensionality -/
theorem ext_iff {α : Type u_1} {s₁ : finset α} {s₂ : finset α} : s₁ = s₂ ↔ ∀ (a : α), a ∈ s₁ ↔ a ∈ s₂ :=
iff.trans (iff.symm val_inj) (multiset.nodup_ext (nodup s₁) (nodup s₂))
theorem ext {α : Type u_1} {s₁ : finset α} {s₂ : finset α} : (∀ (a : α), a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ :=
iff.mpr ext_iff
@[simp] theorem coe_inj {α : Type u_1} {s₁ : finset α} {s₂ : finset α} : ↑s₁ = ↑s₂ ↔ s₁ = s₂ :=
iff.trans set.ext_iff (iff.symm ext_iff)
theorem coe_injective {α : Type u_1} : function.injective coe :=
fun (s t : finset α) => iff.mp coe_inj
/-! ### subset -/
protected instance has_subset {α : Type u_1} : has_subset (finset α) :=
has_subset.mk fun (s₁ s₂ : finset α) => ∀ {a : α}, a ∈ s₁ → a ∈ s₂
theorem subset_def {α : Type u_1} {s₁ : finset α} {s₂ : finset α} : s₁ ⊆ s₂ ↔ val s₁ ⊆ val s₂ :=
iff.rfl
@[simp] theorem subset.refl {α : Type u_1} (s : finset α) : s ⊆ s :=
multiset.subset.refl (val s)
theorem subset_of_eq {α : Type u_1} {s : finset α} {t : finset α} (h : s = t) : s ⊆ t :=
h ▸ subset.refl s
theorem subset.trans {α : Type u_1} {s₁ : finset α} {s₂ : finset α} {s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ :=
multiset.subset.trans
theorem superset.trans {α : Type u_1} {s₁ : finset α} {s₂ : finset α} {s₃ : finset α} : s₁ ⊇ s₂ → s₂ ⊇ s₃ → s₁ ⊇ s₃ :=
fun (h' : s₁ ⊇ s₂) (h : s₂ ⊇ s₃) => subset.trans h h'
-- TODO: these should be global attributes, but this will require fixing other files
theorem mem_of_subset {α : Type u_1} {s₁ : finset α} {s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ :=
multiset.mem_of_subset
theorem subset.antisymm {α : Type u_1} {s₁ : finset α} {s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ :=
ext fun (a : α) => { mp := H₁, mpr := H₂ }
theorem subset_iff {α : Type u_1} {s₁ : finset α} {s₂ : finset α} : s₁ ⊆ s₂ ↔ ∀ {x : α}, x ∈ s₁ → x ∈ s₂ :=
iff.rfl
@[simp] theorem coe_subset {α : Type u_1} {s₁ : finset α} {s₂ : finset α} : ↑s₁ ⊆ ↑s₂ ↔ s₁ ⊆ s₂ :=
iff.rfl
@[simp] theorem val_le_iff {α : Type u_1} {s₁ : finset α} {s₂ : finset α} : val s₁ ≤ val s₂ ↔ s₁ ⊆ s₂ :=
multiset.le_iff_subset (nodup s₁)
protected instance has_ssubset {α : Type u_1} : has_ssubset (finset α) :=
has_ssubset.mk fun (a b : finset α) => a ⊆ b ∧ ¬b ⊆ a
protected instance partial_order {α : Type u_1} : partial_order (finset α) :=
partial_order.mk has_subset.subset has_ssubset.ssubset subset.refl subset.trans subset.antisymm
theorem subset.antisymm_iff {α : Type u_1} {s₁ : finset α} {s₂ : finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ :=
le_antisymm_iff
@[simp] theorem le_iff_subset {α : Type u_1} {s₁ : finset α} {s₂ : finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ :=
iff.rfl
@[simp] theorem lt_iff_ssubset {α : Type u_1} {s₁ : finset α} {s₂ : finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ :=
iff.rfl
@[simp] theorem coe_ssubset {α : Type u_1} {s₁ : finset α} {s₂ : finset α} : ↑s₁ ⊂ ↑s₂ ↔ s₁ ⊂ s₂ := sorry
@[simp] theorem val_lt_iff {α : Type u_1} {s₁ : finset α} {s₂ : finset α} : val s₁ < val s₂ ↔ s₁ ⊂ s₂ :=
and_congr val_le_iff (not_congr val_le_iff)
theorem ssubset_iff_of_subset {α : Type u_1} {s₁ : finset α} {s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ⊂ s₂ ↔ ∃ (x : α), ∃ (H : x ∈ s₂), ¬x ∈ s₁ :=
set.ssubset_iff_of_subset h
/-! ### Nonempty -/
/-- The property `s.nonempty` expresses the fact that the finset `s` is not empty. It should be used
in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks
to the dot notation. -/
protected def nonempty {α : Type u_1} (s : finset α) :=
∃ (x : α), x ∈ s
@[simp] theorem coe_nonempty {α : Type u_1} {s : finset α} : set.nonempty ↑s ↔ finset.nonempty s :=
iff.rfl
theorem nonempty.bex {α : Type u_1} {s : finset α} (h : finset.nonempty s) : ∃ (x : α), x ∈ s :=
h
theorem nonempty.mono {α : Type u_1} {s : finset α} {t : finset α} (hst : s ⊆ t) (hs : finset.nonempty s) : finset.nonempty t :=
set.nonempty.mono hst hs
theorem nonempty.forall_const {α : Type u_1} {s : finset α} (h : finset.nonempty s) {p : Prop} : (∀ (x : α), x ∈ s → p) ↔ p := sorry
/-! ### empty -/
/-- The empty finset -/
protected def empty {α : Type u_1} : finset α :=
mk 0 multiset.nodup_zero
protected instance has_emptyc {α : Type u_1} : has_emptyc (finset α) :=
has_emptyc.mk finset.empty
protected instance inhabited {α : Type u_1} : Inhabited (finset α) :=
{ default := ∅ }
@[simp] theorem empty_val {α : Type u_1} : val ∅ = 0 :=
rfl
@[simp] theorem not_mem_empty {α : Type u_1} (a : α) : ¬a ∈ ∅ :=
id
@[simp] theorem not_nonempty_empty {α : Type u_1} : ¬finset.nonempty ∅ :=
fun (_x : finset.nonempty ∅) =>
(fun (_a : finset.nonempty ∅) => Exists.dcases_on _a fun (w : α) (h : w ∈ ∅) => idRhs False (not_mem_empty w h)) _x
@[simp] theorem mk_zero {α : Type u_1} : mk 0 multiset.nodup_zero = ∅ :=
rfl
theorem ne_empty_of_mem {α : Type u_1} {a : α} {s : finset α} (h : a ∈ s) : s ≠ ∅ :=
fun (e : s = ∅) => not_mem_empty a (e ▸ h)
theorem nonempty.ne_empty {α : Type u_1} {s : finset α} (h : finset.nonempty s) : s ≠ ∅ :=
exists.elim h fun (a : α) => ne_empty_of_mem
@[simp] theorem empty_subset {α : Type u_1} (s : finset α) : ∅ ⊆ s :=
multiset.zero_subset (val s)
theorem eq_empty_of_forall_not_mem {α : Type u_1} {s : finset α} (H : ∀ (x : α), ¬x ∈ s) : s = ∅ :=
eq_of_veq (multiset.eq_zero_of_forall_not_mem H)
theorem eq_empty_iff_forall_not_mem {α : Type u_1} {s : finset α} : s = ∅ ↔ ∀ (x : α), ¬x ∈ s :=
{ mp := fun (ᾰ : s = ∅) (x : α) => Eq._oldrec id (Eq.symm ᾰ),
mpr := fun (h : ∀ (x : α), ¬x ∈ s) => eq_empty_of_forall_not_mem h }
@[simp] theorem val_eq_zero {α : Type u_1} {s : finset α} : val s = 0 ↔ s = ∅ :=
val_inj
theorem subset_empty {α : Type u_1} {s : finset α} : s ⊆ ∅ ↔ s = ∅ :=
iff.trans multiset.subset_zero val_eq_zero
theorem nonempty_of_ne_empty {α : Type u_1} {s : finset α} (h : s ≠ ∅) : finset.nonempty s :=
multiset.exists_mem_of_ne_zero (mt (iff.mp val_eq_zero) h)
theorem nonempty_iff_ne_empty {α : Type u_1} {s : finset α} : finset.nonempty s ↔ s ≠ ∅ :=
{ mp := nonempty.ne_empty, mpr := nonempty_of_ne_empty }
@[simp] theorem not_nonempty_iff_eq_empty {α : Type u_1} {s : finset α} : ¬finset.nonempty s ↔ s = ∅ :=
eq.mpr (id (Eq._oldrec (Eq.refl (¬finset.nonempty s ↔ s = ∅)) (propext nonempty_iff_ne_empty))) not_not
theorem eq_empty_or_nonempty {α : Type u_1} (s : finset α) : s = ∅ ∨ finset.nonempty s :=
classical.by_cases Or.inl fun (h : ¬s = ∅) => Or.inr (nonempty_of_ne_empty h)
@[simp] theorem coe_empty {α : Type u_1} : ↑∅ = ∅ :=
rfl
/-- A `finset` for an empty type is empty. -/
theorem eq_empty_of_not_nonempty {α : Type u_1} (h : ¬Nonempty α) (s : finset α) : s = ∅ :=
eq_empty_of_forall_not_mem fun (x : α) => false.elim (iff.mp not_nonempty_iff_imp_false h x)
/-! ### singleton -/
/--
`{a} : finset a` is the set `{a}` containing `a` and nothing else.
This differs from `insert a ∅` in that it does not require a `decidable_eq` instance for `α`.
-/
protected instance has_singleton {α : Type u_1} : has_singleton α (finset α) :=
has_singleton.mk fun (a : α) => mk (singleton a) (multiset.nodup_singleton a)
@[simp] theorem singleton_val {α : Type u_1} (a : α) : val (singleton a) = a ::ₘ 0 :=
rfl
@[simp] theorem mem_singleton {α : Type u_1} {a : α} {b : α} : b ∈ singleton a ↔ b = a :=
multiset.mem_singleton
theorem not_mem_singleton {α : Type u_1} {a : α} {b : α} : ¬a ∈ singleton b ↔ a ≠ b :=
not_congr mem_singleton
theorem mem_singleton_self {α : Type u_1} (a : α) : a ∈ singleton a :=
Or.inl rfl
theorem singleton_inj {α : Type u_1} {a : α} {b : α} : singleton a = singleton b ↔ a = b :=
{ mp := fun (h : singleton a = singleton b) => iff.mp mem_singleton (h ▸ mem_singleton_self a),
mpr := congr_arg fun {a : α} => singleton a }
@[simp] theorem singleton_nonempty {α : Type u_1} (a : α) : finset.nonempty (singleton a) :=
Exists.intro a (mem_singleton_self a)
@[simp] theorem singleton_ne_empty {α : Type u_1} (a : α) : singleton a ≠ ∅ :=
nonempty.ne_empty (singleton_nonempty a)
@[simp] theorem coe_singleton {α : Type u_1} (a : α) : ↑(singleton a) = singleton a := sorry
theorem eq_singleton_iff_unique_mem {α : Type u_1} {s : finset α} {a : α} : s = singleton a ↔ a ∈ s ∧ ∀ (x : α), x ∈ s → x = a := sorry
theorem eq_singleton_iff_nonempty_unique_mem {α : Type u_1} {s : finset α} {a : α} : s = singleton a ↔ finset.nonempty s ∧ ∀ (x : α), x ∈ s → x = a := sorry
theorem singleton_iff_unique_mem {α : Type u_1} (s : finset α) : (∃ (a : α), s = singleton a) ↔ exists_unique fun (a : α) => a ∈ s := sorry
theorem singleton_subset_set_iff {α : Type u_1} {s : set α} {a : α} : ↑(singleton a) ⊆ s ↔ a ∈ s :=
eq.mpr (id (Eq._oldrec (Eq.refl (↑(singleton a) ⊆ s ↔ a ∈ s)) (coe_singleton a)))
(eq.mpr (id (Eq._oldrec (Eq.refl (singleton a ⊆ s ↔ a ∈ s)) (propext set.singleton_subset_iff))) (iff.refl (a ∈ s)))
@[simp] theorem singleton_subset_iff {α : Type u_1} {s : finset α} {a : α} : singleton a ⊆ s ↔ a ∈ s :=
singleton_subset_set_iff
/-! ### cons -/
/-- `cons a s h` is the set `{a} ∪ s` containing `a` and the elements of `s`. It is the same as
`insert a s` when it is defined, but unlike `insert a s` it does not require `decidable_eq α`,
and the union is guaranteed to be disjoint. -/
def cons {α : Type u_1} (a : α) (s : finset α) (h : ¬a ∈ s) : finset α :=
mk (a ::ₘ val s) sorry
@[simp] theorem mem_cons {α : Type u_1} {a : α} {s : finset α} {h : ¬a ∈ s} {b : α} : b ∈ cons a s h ↔ b = a ∨ b ∈ s := sorry
@[simp] theorem cons_val {α : Type u_1} {a : α} {s : finset α} (h : ¬a ∈ s) : val (cons a s h) = a ::ₘ val s :=
rfl
@[simp] theorem mk_cons {α : Type u_1} {a : α} {s : multiset α} (h : multiset.nodup (a ::ₘ s)) : mk (a ::ₘ s) h = cons a (mk s (and.right (iff.mp multiset.nodup_cons h))) (and.left (iff.mp multiset.nodup_cons h)) :=
rfl
@[simp] theorem nonempty_cons {α : Type u_1} {a : α} {s : finset α} (h : ¬a ∈ s) : finset.nonempty (cons a s h) :=
Exists.intro a (iff.mpr mem_cons (Or.inl rfl))
@[simp] theorem nonempty_mk_coe {α : Type u_1} {l : List α} {hl : multiset.nodup ↑l} : finset.nonempty (mk (↑l) hl) ↔ l ≠ [] := sorry
/-! ### disjoint union -/
/-- `disj_union s t h` is the set such that `a ∈ disj_union s t h` iff `a ∈ s` or `a ∈ t`.
It is the same as `s ∪ t`, but it does not require decidable equality on the type. The hypothesis
ensures that the sets are disjoint. -/
def disj_union {α : Type u_1} (s : finset α) (t : finset α) (h : ∀ (a : α), a ∈ s → ¬a ∈ t) : finset α :=
mk (val s + val t) sorry
@[simp] theorem mem_disj_union {α : Type u_1} {s : finset α} {t : finset α} {h : ∀ (a : α), a ∈ s → ¬a ∈ t} {a : α} : a ∈ disj_union s t h ↔ a ∈ s ∨ a ∈ t := sorry
/-! ### insert -/
/-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/
protected instance has_insert {α : Type u_1} [DecidableEq α] : has_insert α (finset α) :=
has_insert.mk fun (a : α) (s : finset α) => mk (multiset.ndinsert a (val s)) sorry
theorem insert_def {α : Type u_1} [DecidableEq α] (a : α) (s : finset α) : insert a s = mk (multiset.ndinsert a (val s)) (multiset.nodup_ndinsert a (nodup s)) :=
rfl
@[simp] theorem insert_val {α : Type u_1} [DecidableEq α] (a : α) (s : finset α) : val (insert a s) = multiset.ndinsert a (val s) :=
rfl
theorem insert_val' {α : Type u_1} [DecidableEq α] (a : α) (s : finset α) : val (insert a s) = multiset.erase_dup (a ::ₘ val s) := sorry
theorem insert_val_of_not_mem {α : Type u_1} [DecidableEq α] {a : α} {s : finset α} (h : ¬a ∈ s) : val (insert a s) = a ::ₘ val s :=
eq.mpr (id (Eq._oldrec (Eq.refl (val (insert a s) = a ::ₘ val s)) (insert_val a s)))
(eq.mpr (id (Eq._oldrec (Eq.refl (multiset.ndinsert a (val s) = a ::ₘ val s)) (multiset.ndinsert_of_not_mem h)))
(Eq.refl (a ::ₘ val s)))
@[simp] theorem mem_insert {α : Type u_1} [DecidableEq α] {a : α} {b : α} {s : finset α} : a ∈ insert b s ↔ a = b ∨ a ∈ s :=
multiset.mem_ndinsert
theorem mem_insert_self {α : Type u_1} [DecidableEq α] (a : α) (s : finset α) : a ∈ insert a s :=
multiset.mem_ndinsert_self a (val s)
theorem mem_insert_of_mem {α : Type u_1} [DecidableEq α] {a : α} {b : α} {s : finset α} (h : a ∈ s) : a ∈ insert b s :=
multiset.mem_ndinsert_of_mem h
theorem mem_of_mem_insert_of_ne {α : Type u_1} [DecidableEq α] {a : α} {b : α} {s : finset α} (h : b ∈ insert a s) : b ≠ a → b ∈ s :=
or.resolve_left (iff.mp mem_insert h)
@[simp] theorem cons_eq_insert {α : Type u_1} [DecidableEq α] (a : α) (s : finset α) (h : ¬a ∈ s) : cons a s h = insert a s := sorry
@[simp] theorem coe_insert {α : Type u_1} [DecidableEq α] (a : α) (s : finset α) : ↑(insert a s) = insert a ↑s := sorry
theorem mem_insert_coe {α : Type u_1} [DecidableEq α] {s : finset α} {x : α} {y : α} : x ∈ insert y s ↔ x ∈ insert y ↑s := sorry
protected instance is_lawful_singleton {α : Type u_1} [DecidableEq α] : is_lawful_singleton α (finset α) :=
is_lawful_singleton.mk
fun (a : α) =>
ext
fun (a_1 : α) =>
eq.mpr
(id
(Eq.trans
((fun (a a_2 : Prop) (e_1 : a = a_2) (b b_1 : Prop) (e_2 : b = b_1) => congr (congr_arg Iff e_1) e_2)
(a_1 ∈ insert a ∅) (a_1 = a)
(Eq.trans
(Eq.trans (propext mem_insert)
((fun (a a_2 : Prop) (e_1 : a = a_2) (b b_1 : Prop) (e_2 : b = b_1) => congr (congr_arg Or e_1) e_2)
(a_1 = a) (a_1 = a) (Eq.refl (a_1 = a)) (a_1 ∈ ∅) False
(propext ((fun {α : Type u_1} (a : α) => iff_false_intro (not_mem_empty a)) a_1))))
(propext (or_false (a_1 = a))))
(a_1 ∈ singleton a) (a_1 = a) (propext mem_singleton))
(propext (iff_self (a_1 = a)))))
trivial
@[simp] theorem insert_eq_of_mem {α : Type u_1} [DecidableEq α] {a : α} {s : finset α} (h : a ∈ s) : insert a s = s :=
eq_of_veq (multiset.ndinsert_of_mem h)
@[simp] theorem insert_singleton_self_eq {α : Type u_1} [DecidableEq α] (a : α) : insert a (singleton a) = singleton a :=
insert_eq_of_mem (mem_singleton_self a)
theorem insert.comm {α : Type u_1} [DecidableEq α] (a : α) (b : α) (s : finset α) : insert a (insert b s) = insert b (insert a s) := sorry
theorem insert_singleton_comm {α : Type u_1} [DecidableEq α] (a : α) (b : α) : insert a (singleton b) = insert b (singleton a) := sorry
@[simp] theorem insert_idem {α : Type u_1} [DecidableEq α] (a : α) (s : finset α) : insert a (insert a s) = insert a s := sorry
@[simp] theorem insert_nonempty {α : Type u_1} [DecidableEq α] (a : α) (s : finset α) : finset.nonempty (insert a s) :=
Exists.intro a (mem_insert_self a s)
@[simp] theorem insert_ne_empty {α : Type u_1} [DecidableEq α] (a : α) (s : finset α) : insert a s ≠ ∅ :=
nonempty.ne_empty (insert_nonempty a s)
/-!
The universe annotation is required for the following instance, possibly this is a bug in Lean. See
leanprover.zulipchat.com/#narrow/stream/113488-general/topic/strange.20error.20(universe.20issue.3F)
-/
protected instance has_insert.insert.nonempty {α : Type u} [DecidableEq α] (i : α) (s : finset α) : Nonempty ↥↑(insert i s) :=
set.nonempty.to_subtype (iff.mpr coe_nonempty (insert_nonempty i s))
theorem ne_insert_of_not_mem {α : Type u_1} [DecidableEq α] (s : finset α) (t : finset α) {a : α} (h : ¬a ∈ s) : s ≠ insert a t := sorry
theorem insert_subset {α : Type u_1} [DecidableEq α] {a : α} {s : finset α} {t : finset α} : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t := sorry
theorem subset_insert {α : Type u_1} [DecidableEq α] (a : α) (s : finset α) : s ⊆ insert a s :=
fun (b : α) => mem_insert_of_mem
theorem insert_subset_insert {α : Type u_1} [DecidableEq α] (a : α) {s : finset α} {t : finset α} (h : s ⊆ t) : insert a s ⊆ insert a t :=
iff.mpr insert_subset { left := mem_insert_self a t, right := subset.trans h (subset_insert a t) }
theorem ssubset_iff {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} : s ⊂ t ↔ ∃ (a : α), ∃ (H : ¬a ∈ s), insert a s ⊆ t := sorry
theorem ssubset_insert {α : Type u_1} [DecidableEq α] {s : finset α} {a : α} (h : ¬a ∈ s) : s ⊂ insert a s :=
iff.mpr ssubset_iff (Exists.intro a (Exists.intro h (subset.refl (insert a s))))
protected theorem induction {α : Type u_1} {p : finset α → Prop} [DecidableEq α] (h₁ : p ∅) (h₂ : ∀ {a : α} {s : finset α}, ¬a ∈ s → p s → p (insert a s)) (s : finset α) : p s := sorry
/--
To prove a proposition about an arbitrary `finset α`,
it suffices to prove it for the empty `finset`,
and to show that if it holds for some `finset α`,
then it holds for the `finset` obtained by inserting a new element.
-/
protected theorem induction_on {α : Type u_1} {p : finset α → Prop} [DecidableEq α] (s : finset α) (h₁ : p ∅) (h₂ : ∀ {a : α} {s : finset α}, ¬a ∈ s → p s → p (insert a s)) : p s :=
finset.induction h₁ h₂ s
/--
To prove a proposition about `S : finset α`,
it suffices to prove it for the empty `finset`,
and to show that if it holds for some `finset α ⊆ S`,
then it holds for the `finset` obtained by inserting a new element of `S`.
-/
theorem induction_on' {α : Type u_1} {p : finset α → Prop} [DecidableEq α] (S : finset α) (h₁ : p ∅) (h₂ : ∀ {a : α} {s : finset α}, a ∈ S → s ⊆ S → ¬a ∈ s → p s → p (insert a s)) : p S := sorry
/-- Inserting an element to a finite set is equivalent to the option type. -/
def subtype_insert_equiv_option {α : Type u_1} [DecidableEq α] {t : finset α} {x : α} (h : ¬x ∈ t) : (Subtype fun (i : α) => i ∈ insert x t) ≃ Option (Subtype fun (i : α) => i ∈ t) :=
equiv.mk
(fun (y : Subtype fun (i : α) => i ∈ insert x t) =>
dite (↑y = x) (fun (h : ↑y = x) => none) fun (h : ¬↑y = x) => some { val := ↑y, property := sorry })
(fun (y : Option (Subtype fun (i : α) => i ∈ t)) =>
option.elim y { val := x, property := sorry }
fun (z : Subtype fun (i : α) => i ∈ t) => { val := ↑z, property := sorry })
sorry sorry
/-! ### union -/
/-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/
protected instance has_union {α : Type u_1} [DecidableEq α] : has_union (finset α) :=
has_union.mk fun (s₁ s₂ : finset α) => mk (multiset.ndunion (val s₁) (val s₂)) sorry
theorem union_val_nd {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) : val (s₁ ∪ s₂) = multiset.ndunion (val s₁) (val s₂) :=
rfl
@[simp] theorem union_val {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) : val (s₁ ∪ s₂) = val s₁ ∪ val s₂ :=
multiset.ndunion_eq_union (nodup s₁)
@[simp] theorem mem_union {α : Type u_1} [DecidableEq α] {a : α} {s₁ : finset α} {s₂ : finset α} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ :=
multiset.mem_ndunion
@[simp] theorem disj_union_eq_union {α : Type u_1} [DecidableEq α] (s : finset α) (t : finset α) (h : ∀ (a : α), a ∈ s → ¬a ∈ t) : disj_union s t h = s ∪ t := sorry
theorem mem_union_left {α : Type u_1} [DecidableEq α] {a : α} {s₁ : finset α} (s₂ : finset α) (h : a ∈ s₁) : a ∈ s₁ ∪ s₂ :=
iff.mpr mem_union (Or.inl h)
theorem mem_union_right {α : Type u_1} [DecidableEq α] {a : α} {s₂ : finset α} (s₁ : finset α) (h : a ∈ s₂) : a ∈ s₁ ∪ s₂ :=
iff.mpr mem_union (Or.inr h)
theorem forall_mem_union {α : Type u_1} [DecidableEq α] {s₁ : finset α} {s₂ : finset α} {p : α → Prop} : (∀ (ab : α), ab ∈ s₁ ∪ s₂ → p ab) ↔ (∀ (a : α), a ∈ s₁ → p a) ∧ ∀ (b : α), b ∈ s₂ → p b := sorry
theorem not_mem_union {α : Type u_1} [DecidableEq α] {a : α} {s₁ : finset α} {s₂ : finset α} : ¬a ∈ s₁ ∪ s₂ ↔ ¬a ∈ s₁ ∧ ¬a ∈ s₂ :=
eq.mpr (id (Eq._oldrec (Eq.refl (¬a ∈ s₁ ∪ s₂ ↔ ¬a ∈ s₁ ∧ ¬a ∈ s₂)) (propext mem_union)))
(eq.mpr (id (Eq._oldrec (Eq.refl (¬(a ∈ s₁ ∨ a ∈ s₂) ↔ ¬a ∈ s₁ ∧ ¬a ∈ s₂)) (propext not_or_distrib)))
(iff.refl (¬a ∈ s₁ ∧ ¬a ∈ s₂)))
@[simp] theorem coe_union {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) : ↑(s₁ ∪ s₂) = ↑s₁ ∪ ↑s₂ :=
set.ext fun (x : α) => mem_union
theorem union_subset {α : Type u_1} [DecidableEq α] {s₁ : finset α} {s₂ : finset α} {s₃ : finset α} (h₁ : s₁ ⊆ s₃) (h₂ : s₂ ⊆ s₃) : s₁ ∪ s₂ ⊆ s₃ :=
iff.mp val_le_iff (iff.mpr multiset.ndunion_le { left := h₁, right := iff.mpr val_le_iff h₂ })
theorem subset_union_left {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) : s₁ ⊆ s₁ ∪ s₂ :=
fun (x : α) => mem_union_left s₂
theorem subset_union_right {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) : s₂ ⊆ s₁ ∪ s₂ :=
fun (x : α) => mem_union_right s₁
theorem union_subset_union {α : Type u_1} [DecidableEq α] {s1 : finset α} {t1 : finset α} {s2 : finset α} {t2 : finset α} (h1 : s1 ⊆ t1) (h2 : s2 ⊆ t2) : s1 ∪ s2 ⊆ t1 ∪ t2 := sorry
theorem union_comm {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ := sorry
protected instance has_union.union.is_commutative {α : Type u_1} [DecidableEq α] : is_commutative (finset α) has_union.union :=
is_commutative.mk union_comm
@[simp] theorem union_assoc {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) (s₃ : finset α) : s₁ ∪ s₂ ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := sorry
protected instance has_union.union.is_associative {α : Type u_1} [DecidableEq α] : is_associative (finset α) has_union.union :=
is_associative.mk union_assoc
@[simp] theorem union_idempotent {α : Type u_1} [DecidableEq α] (s : finset α) : s ∪ s = s :=
ext fun (_x : α) => iff.trans mem_union (or_self (_x ∈ s))
protected instance has_union.union.is_idempotent {α : Type u_1} [DecidableEq α] : is_idempotent (finset α) has_union.union :=
is_idempotent.mk union_idempotent
theorem union_left_comm {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) (s₃ : finset α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := sorry
theorem union_right_comm {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) (s₃ : finset α) : s₁ ∪ s₂ ∪ s₃ = s₁ ∪ s₃ ∪ s₂ := sorry
theorem union_self {α : Type u_1} [DecidableEq α] (s : finset α) : s ∪ s = s :=
union_idempotent s
@[simp] theorem union_empty {α : Type u_1} [DecidableEq α] (s : finset α) : s ∪ ∅ = s :=
ext fun (x : α) => iff.trans mem_union (or_false (x ∈ s))
@[simp] theorem empty_union {α : Type u_1} [DecidableEq α] (s : finset α) : ∅ ∪ s = s :=
ext fun (x : α) => iff.trans mem_union (false_or (x ∈ s))
theorem insert_eq {α : Type u_1} [DecidableEq α] (a : α) (s : finset α) : insert a s = singleton a ∪ s :=
rfl
@[simp] theorem insert_union {α : Type u_1} [DecidableEq α] (a : α) (s : finset α) (t : finset α) : insert a s ∪ t = insert a (s ∪ t) := sorry
@[simp] theorem union_insert {α : Type u_1} [DecidableEq α] (a : α) (s : finset α) (t : finset α) : s ∪ insert a t = insert a (s ∪ t) := sorry
theorem insert_union_distrib {α : Type u_1} [DecidableEq α] (a : α) (s : finset α) (t : finset α) : insert a (s ∪ t) = insert a s ∪ insert a t := sorry
@[simp] theorem union_eq_left_iff_subset {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} : s ∪ t = s ↔ t ⊆ s :=
{ mp := fun (h : s ∪ t = s) => eq.mp (Eq._oldrec (Eq.refl (t ⊆ s ∪ t)) h) (subset_union_right s t),
mpr := fun (h : t ⊆ s) => subset.antisymm (union_subset (subset.refl s) h) (subset_union_left s t) }
@[simp] theorem left_eq_union_iff_subset {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} : s = s ∪ t ↔ t ⊆ s :=
eq.mpr (id (Eq._oldrec (Eq.refl (s = s ∪ t ↔ t ⊆ s)) (Eq.symm (propext union_eq_left_iff_subset))))
(eq.mpr (id (Eq._oldrec (Eq.refl (s = s ∪ t ↔ s ∪ t = s)) (propext eq_comm))) (iff.refl (s ∪ t = s)))
@[simp] theorem union_eq_right_iff_subset {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} : t ∪ s = s ↔ t ⊆ s :=
eq.mpr (id (Eq._oldrec (Eq.refl (t ∪ s = s ↔ t ⊆ s)) (union_comm t s)))
(eq.mpr (id (Eq._oldrec (Eq.refl (s ∪ t = s ↔ t ⊆ s)) (propext union_eq_left_iff_subset))) (iff.refl (t ⊆ s)))
@[simp] theorem right_eq_union_iff_subset {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} : s = t ∪ s ↔ t ⊆ s :=
eq.mpr (id (Eq._oldrec (Eq.refl (s = t ∪ s ↔ t ⊆ s)) (Eq.symm (propext union_eq_right_iff_subset))))
(eq.mpr (id (Eq._oldrec (Eq.refl (s = t ∪ s ↔ t ∪ s = s)) (propext eq_comm))) (iff.refl (t ∪ s = s)))
/--
To prove a relation on pairs of `finset X`, it suffices to show that it is
* symmetric,
* it holds when one of the `finset`s is empty,
* it holds for pairs of singletons,
* if it holds for `[a, c]` and for `[b, c]`, then it holds for `[a ∪ b, c]`.
-/
theorem induction_on_union {α : Type u_1} [DecidableEq α] (P : finset α → finset α → Prop) (symm : ∀ {a b : finset α}, P a b → P b a) (empty_right : ∀ {a : finset α}, P a ∅) (singletons : ∀ {a b : α}, P (singleton a) (singleton b)) (union_of : ∀ {a b c : finset α}, P a c → P b c → P (a ∪ b) c) (a : finset α) (b : finset α) : P a b := sorry
/-! ### inter -/
/-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/
protected instance has_inter {α : Type u_1} [DecidableEq α] : has_inter (finset α) :=
has_inter.mk fun (s₁ s₂ : finset α) => mk (multiset.ndinter (val s₁) (val s₂)) sorry
theorem inter_val_nd {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) : val (s₁ ∩ s₂) = multiset.ndinter (val s₁) (val s₂) :=
rfl
@[simp] theorem inter_val {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) : val (s₁ ∩ s₂) = val s₁ ∩ val s₂ :=
multiset.ndinter_eq_inter (nodup s₁)
@[simp] theorem mem_inter {α : Type u_1} [DecidableEq α] {a : α} {s₁ : finset α} {s₂ : finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ :=
multiset.mem_ndinter
theorem mem_of_mem_inter_left {α : Type u_1} [DecidableEq α] {a : α} {s₁ : finset α} {s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₁ :=
and.left (iff.mp mem_inter h)
theorem mem_of_mem_inter_right {α : Type u_1} [DecidableEq α] {a : α} {s₁ : finset α} {s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₂ :=
and.right (iff.mp mem_inter h)
theorem mem_inter_of_mem {α : Type u_1} [DecidableEq α] {a : α} {s₁ : finset α} {s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ :=
iff.mp and_imp (iff.mpr mem_inter)
theorem inter_subset_left {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) : s₁ ∩ s₂ ⊆ s₁ :=
fun (a : α) => mem_of_mem_inter_left
theorem inter_subset_right {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) : s₁ ∩ s₂ ⊆ s₂ :=
fun (a : α) => mem_of_mem_inter_right
theorem subset_inter {α : Type u_1} [DecidableEq α] {s₁ : finset α} {s₂ : finset α} {s₃ : finset α} : s₁ ⊆ s₂ → s₁ ⊆ s₃ → s₁ ⊆ s₂ ∩ s₃ := sorry
@[simp] theorem coe_inter {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) : ↑(s₁ ∩ s₂) = ↑s₁ ∩ ↑s₂ :=
set.ext fun (_x : α) => mem_inter
@[simp] theorem union_inter_cancel_left {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} : (s ∪ t) ∩ s = s := sorry
@[simp] theorem union_inter_cancel_right {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} : (s ∪ t) ∩ t = t := sorry
theorem inter_comm {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ := sorry
@[simp] theorem inter_assoc {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) (s₃ : finset α) : s₁ ∩ s₂ ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := sorry
theorem inter_left_comm {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) (s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := sorry
theorem inter_right_comm {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) (s₃ : finset α) : s₁ ∩ s₂ ∩ s₃ = s₁ ∩ s₃ ∩ s₂ := sorry
@[simp] theorem inter_self {α : Type u_1} [DecidableEq α] (s : finset α) : s ∩ s = s :=
ext fun (_x : α) => iff.trans mem_inter (and_self (_x ∈ s))
@[simp] theorem inter_empty {α : Type u_1} [DecidableEq α] (s : finset α) : s ∩ ∅ = ∅ :=
ext fun (_x : α) => iff.trans mem_inter (and_false (_x ∈ s))
@[simp] theorem empty_inter {α : Type u_1} [DecidableEq α] (s : finset α) : ∅ ∩ s = ∅ :=
ext fun (_x : α) => iff.trans mem_inter (false_and (_x ∈ s))
@[simp] theorem inter_union_self {α : Type u_1} [DecidableEq α] (s : finset α) (t : finset α) : s ∩ (t ∪ s) = s :=
eq.mpr (id (Eq._oldrec (Eq.refl (s ∩ (t ∪ s) = s)) (inter_comm s (t ∪ s))))
(eq.mpr (id (Eq._oldrec (Eq.refl ((t ∪ s) ∩ s = s)) union_inter_cancel_right)) (Eq.refl s))
@[simp] theorem insert_inter_of_mem {α : Type u_1} [DecidableEq α] {s₁ : finset α} {s₂ : finset α} {a : α} (h : a ∈ s₂) : insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) := sorry
@[simp] theorem inter_insert_of_mem {α : Type u_1} [DecidableEq α] {s₁ : finset α} {s₂ : finset α} {a : α} (h : a ∈ s₁) : s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) := sorry
@[simp] theorem insert_inter_of_not_mem {α : Type u_1} [DecidableEq α] {s₁ : finset α} {s₂ : finset α} {a : α} (h : ¬a ∈ s₂) : insert a s₁ ∩ s₂ = s₁ ∩ s₂ := sorry
@[simp] theorem inter_insert_of_not_mem {α : Type u_1} [DecidableEq α] {s₁ : finset α} {s₂ : finset α} {a : α} (h : ¬a ∈ s₁) : s₁ ∩ insert a s₂ = s₁ ∩ s₂ :=
eq.mpr (id (Eq._oldrec (Eq.refl (s₁ ∩ insert a s₂ = s₁ ∩ s₂)) (inter_comm s₁ (insert a s₂))))
(eq.mpr (id (Eq._oldrec (Eq.refl (insert a s₂ ∩ s₁ = s₁ ∩ s₂)) (insert_inter_of_not_mem h)))
(eq.mpr (id (Eq._oldrec (Eq.refl (s₂ ∩ s₁ = s₁ ∩ s₂)) (inter_comm s₂ s₁))) (Eq.refl (s₁ ∩ s₂))))
@[simp] theorem singleton_inter_of_mem {α : Type u_1} [DecidableEq α] {a : α} {s : finset α} (H : a ∈ s) : singleton a ∩ s = singleton a :=
(fun (this : insert a ∅ ∩ s = insert a ∅) => this)
(eq.mpr (id (Eq._oldrec (Eq.refl (insert a ∅ ∩ s = insert a ∅)) (insert_inter_of_mem H)))
(eq.mpr (id (Eq._oldrec (Eq.refl (insert a (∅ ∩ s) = insert a ∅)) (empty_inter s))) (Eq.refl (insert a ∅))))
@[simp] theorem singleton_inter_of_not_mem {α : Type u_1} [DecidableEq α] {a : α} {s : finset α} (H : ¬a ∈ s) : singleton a ∩ s = ∅ := sorry
@[simp] theorem inter_singleton_of_mem {α : Type u_1} [DecidableEq α] {a : α} {s : finset α} (h : a ∈ s) : s ∩ singleton a = singleton a :=
eq.mpr (id (Eq._oldrec (Eq.refl (s ∩ singleton a = singleton a)) (inter_comm s (singleton a))))
(eq.mpr (id (Eq._oldrec (Eq.refl (singleton a ∩ s = singleton a)) (singleton_inter_of_mem h)))
(Eq.refl (singleton a)))
@[simp] theorem inter_singleton_of_not_mem {α : Type u_1} [DecidableEq α] {a : α} {s : finset α} (h : ¬a ∈ s) : s ∩ singleton a = ∅ :=
eq.mpr (id (Eq._oldrec (Eq.refl (s ∩ singleton a = ∅)) (inter_comm s (singleton a))))
(eq.mpr (id (Eq._oldrec (Eq.refl (singleton a ∩ s = ∅)) (singleton_inter_of_not_mem h))) (Eq.refl ∅))
theorem inter_subset_inter {α : Type u_1} [DecidableEq α] {x : finset α} {y : finset α} {s : finset α} {t : finset α} (h : x ⊆ y) (h' : s ⊆ t) : x ∩ s ⊆ y ∩ t := sorry
theorem inter_subset_inter_right {α : Type u_1} [DecidableEq α] {x : finset α} {y : finset α} {s : finset α} (h : x ⊆ y) : x ∩ s ⊆ y ∩ s :=
inter_subset_inter h (subset.refl s)
theorem inter_subset_inter_left {α : Type u_1} [DecidableEq α] {x : finset α} {y : finset α} {s : finset α} (h : x ⊆ y) : s ∩ x ⊆ s ∩ y :=
inter_subset_inter (subset.refl s) h
/-! ### lattice laws -/
protected instance lattice {α : Type u_1} [DecidableEq α] : lattice (finset α) :=
lattice.mk has_union.union partial_order.le partial_order.lt sorry sorry sorry sorry sorry sorry has_inter.inter sorry
sorry sorry
@[simp] theorem sup_eq_union {α : Type u_1} [DecidableEq α] (s : finset α) (t : finset α) : s ⊔ t = s ∪ t :=
rfl
@[simp] theorem inf_eq_inter {α : Type u_1} [DecidableEq α] (s : finset α) (t : finset α) : s ⊓ t = s ∩ t :=
rfl
protected instance semilattice_inf_bot {α : Type u_1} [DecidableEq α] : semilattice_inf_bot (finset α) :=
semilattice_inf_bot.mk ∅ lattice.le lattice.lt sorry sorry sorry empty_subset lattice.inf sorry sorry sorry
protected instance semilattice_sup_bot {α : Type u_1} [DecidableEq α] : semilattice_sup_bot (finset α) :=
semilattice_sup_bot.mk semilattice_inf_bot.bot semilattice_inf_bot.le semilattice_inf_bot.lt sorry sorry sorry sorry
lattice.sup sorry sorry sorry
protected instance distrib_lattice {α : Type u_1} [DecidableEq α] : distrib_lattice (finset α) :=
distrib_lattice.mk lattice.sup lattice.le lattice.lt sorry sorry sorry sorry sorry sorry lattice.inf sorry sorry sorry
sorry
theorem inter_distrib_left {α : Type u_1} [DecidableEq α] (s : finset α) (t : finset α) (u : finset α) : s ∩ (t ∪ u) = s ∩ t ∪ s ∩ u :=
inf_sup_left
theorem inter_distrib_right {α : Type u_1} [DecidableEq α] (s : finset α) (t : finset α) (u : finset α) : (s ∪ t) ∩ u = s ∩ u ∪ t ∩ u :=
inf_sup_right
theorem union_distrib_left {α : Type u_1} [DecidableEq α] (s : finset α) (t : finset α) (u : finset α) : s ∪ t ∩ u = (s ∪ t) ∩ (s ∪ u) :=
sup_inf_left
theorem union_distrib_right {α : Type u_1} [DecidableEq α] (s : finset α) (t : finset α) (u : finset α) : s ∩ t ∪ u = (s ∪ u) ∩ (t ∪ u) :=
sup_inf_right
theorem union_eq_empty_iff {α : Type u_1} [DecidableEq α] (A : finset α) (B : finset α) : A ∪ B = ∅ ↔ A = ∅ ∧ B = ∅ :=
sup_eq_bot_iff
/-! ### erase -/
/-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are
not equal to `a`. -/
def erase {α : Type u_1} [DecidableEq α] (s : finset α) (a : α) : finset α :=
mk (multiset.erase (val s) a) sorry
@[simp] theorem erase_val {α : Type u_1} [DecidableEq α] (s : finset α) (a : α) : val (erase s a) = multiset.erase (val s) a :=
rfl
@[simp] theorem mem_erase {α : Type u_1} [DecidableEq α] {a : α} {b : α} {s : finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s :=
multiset.mem_erase_iff_of_nodup (nodup s)
theorem not_mem_erase {α : Type u_1} [DecidableEq α] (a : α) (s : finset α) : ¬a ∈ erase s a :=
multiset.mem_erase_of_nodup (nodup s)
@[simp] theorem erase_empty {α : Type u_1} [DecidableEq α] (a : α) : erase ∅ a = ∅ :=
rfl
theorem ne_of_mem_erase {α : Type u_1} [DecidableEq α] {a : α} {b : α} {s : finset α} : b ∈ erase s a → b ≠ a :=
eq.mpr (id (imp_congr_eq (propext mem_erase) (Eq.refl (b ≠ a)))) and.left
theorem mem_of_mem_erase {α : Type u_1} [DecidableEq α] {a : α} {b : α} {s : finset α} : b ∈ erase s a → b ∈ s :=
multiset.mem_of_mem_erase
theorem mem_erase_of_ne_of_mem {α : Type u_1} [DecidableEq α] {a : α} {b : α} {s : finset α} : a ≠ b → a ∈ s → a ∈ erase s b :=
eq.mpr (id (imp_congr_eq (Eq.refl (a ≠ b)) (imp_congr_eq (Eq.refl (a ∈ s)) (propext mem_erase)))) And.intro
/-- An element of `s` that is not an element of `erase s a` must be
`a`. -/
theorem eq_of_mem_of_not_mem_erase {α : Type u_1} [DecidableEq α] {a : α} {b : α} {s : finset α} (hs : b ∈ s) (hsa : ¬b ∈ erase s a) : b = a := sorry
theorem erase_insert {α : Type u_1} [DecidableEq α] {a : α} {s : finset α} (h : ¬a ∈ s) : erase (insert a s) a = s := sorry
theorem insert_erase {α : Type u_1} [DecidableEq α] {a : α} {s : finset α} (h : a ∈ s) : insert a (erase s a) = s := sorry
theorem erase_subset_erase {α : Type u_1} [DecidableEq α] (a : α) {s : finset α} {t : finset α} (h : s ⊆ t) : erase s a ⊆ erase t a :=
iff.mp val_le_iff (multiset.erase_le_erase a (iff.mpr val_le_iff h))
theorem erase_subset {α : Type u_1} [DecidableEq α] (a : α) (s : finset α) : erase s a ⊆ s :=
multiset.erase_subset a (val s)
@[simp] theorem coe_erase {α : Type u_1} [DecidableEq α] (a : α) (s : finset α) : ↑(erase s a) = ↑s \ singleton a := sorry
theorem erase_ssubset {α : Type u_1} [DecidableEq α] {a : α} {s : finset α} (h : a ∈ s) : erase s a ⊂ s :=
trans_rel_left has_ssubset.ssubset (ssubset_insert (not_mem_erase a s)) (insert_erase h)
theorem erase_eq_of_not_mem {α : Type u_1} [DecidableEq α] {a : α} {s : finset α} (h : ¬a ∈ s) : erase s a = s :=
eq_of_veq (multiset.erase_of_not_mem h)
theorem subset_insert_iff {α : Type u_1} [DecidableEq α] {a : α} {s : finset α} {t : finset α} : s ⊆ insert a t ↔ erase s a ⊆ t := sorry
theorem erase_insert_subset {α : Type u_1} [DecidableEq α] (a : α) (s : finset α) : erase (insert a s) a ⊆ s :=
iff.mp subset_insert_iff (subset.refl (insert a s))
theorem insert_erase_subset {α : Type u_1} [DecidableEq α] (a : α) (s : finset α) : s ⊆ insert a (erase s a) :=
iff.mpr subset_insert_iff (subset.refl (erase s a))
/-! ### sdiff -/
/-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/
protected instance has_sdiff {α : Type u_1} [DecidableEq α] : has_sdiff (finset α) :=
has_sdiff.mk fun (s₁ s₂ : finset α) => mk (val s₁ - val s₂) sorry
@[simp] theorem mem_sdiff {α : Type u_1} [DecidableEq α] {a : α} {s₁ : finset α} {s₂ : finset α} : a ∈ s₁ \ s₂ ↔ a ∈ s₁ ∧ ¬a ∈ s₂ :=
multiset.mem_sub_of_nodup (nodup s₁)
theorem not_mem_sdiff_of_mem_right {α : Type u_1} [DecidableEq α] {a : α} {s : finset α} {t : finset α} (h : a ∈ t) : ¬a ∈ s \ t := sorry
theorem sdiff_union_of_subset {α : Type u_1} [DecidableEq α] {s₁ : finset α} {s₂ : finset α} (h : s₁ ⊆ s₂) : s₂ \ s₁ ∪ s₁ = s₂ := sorry
theorem union_sdiff_of_subset {α : Type u_1} [DecidableEq α] {s₁ : finset α} {s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ∪ s₂ \ s₁ = s₂ :=
Eq.trans (union_comm s₁ (s₂ \ s₁)) (sdiff_union_of_subset h)
theorem inter_sdiff {α : Type u_1} [DecidableEq α] (s : finset α) (t : finset α) (u : finset α) : s ∩ (t \ u) = s ∩ t \ u := sorry
@[simp] theorem inter_sdiff_self {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) : s₁ ∩ (s₂ \ s₁) = ∅ := sorry
@[simp] theorem sdiff_inter_self {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) : s₂ \ s₁ ∩ s₁ = ∅ :=
Eq.trans (inter_comm (s₂ \ s₁) s₁) (inter_sdiff_self s₁ s₂)
@[simp] theorem sdiff_self {α : Type u_1} [DecidableEq α] (s₁ : finset α) : s₁ \ s₁ = ∅ := sorry
theorem sdiff_inter_distrib_right {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) (s₃ : finset α) : s₁ \ (s₂ ∩ s₃) = s₁ \ s₂ ∪ s₁ \ s₃ := sorry
@[simp] theorem sdiff_inter_self_left {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) : s₁ \ (s₁ ∩ s₂) = s₁ \ s₂ := sorry
@[simp] theorem sdiff_inter_self_right {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) : s₁ \ (s₂ ∩ s₁) = s₁ \ s₂ := sorry
@[simp] theorem sdiff_empty {α : Type u_1} [DecidableEq α] {s₁ : finset α} : s₁ \ ∅ = s₁ := sorry
theorem sdiff_subset_sdiff {α : Type u_1} [DecidableEq α] {s₁ : finset α} {s₂ : finset α} {t₁ : finset α} {t₂ : finset α} (h₁ : t₁ ⊆ t₂) (h₂ : s₂ ⊆ s₁) : t₁ \ s₁ ⊆ t₂ \ s₂ := sorry
theorem sdiff_subset_self {α : Type u_1} [DecidableEq α] {s₁ : finset α} {s₂ : finset α} : s₁ \ s₂ ⊆ s₁ := sorry
@[simp] theorem coe_sdiff {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) : ↑(s₁ \ s₂) = ↑s₁ \ ↑s₂ :=
set.ext fun (_x : α) => mem_sdiff
@[simp] theorem union_sdiff_self_eq_union {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} : s ∪ t \ s = s ∪ t := sorry
@[simp] theorem sdiff_union_self_eq_union {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} : s \ t ∪ t = s ∪ t :=
eq.mpr (id (Eq._oldrec (Eq.refl (s \ t ∪ t = s ∪ t)) (union_comm (s \ t) t)))
(eq.mpr (id (Eq._oldrec (Eq.refl (t ∪ s \ t = s ∪ t)) union_sdiff_self_eq_union))
(eq.mpr (id (Eq._oldrec (Eq.refl (t ∪ s = s ∪ t)) (union_comm t s))) (Eq.refl (s ∪ t))))
theorem union_sdiff_symm {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} : s ∪ t \ s = t ∪ s \ t :=
eq.mpr (id (Eq._oldrec (Eq.refl (s ∪ t \ s = t ∪ s \ t)) union_sdiff_self_eq_union))
(eq.mpr (id (Eq._oldrec (Eq.refl (s ∪ t = t ∪ s \ t)) union_sdiff_self_eq_union))
(eq.mpr (id (Eq._oldrec (Eq.refl (s ∪ t = t ∪ s)) (union_comm s t))) (Eq.refl (t ∪ s))))
theorem sdiff_union_inter {α : Type u_1} [DecidableEq α] (s : finset α) (t : finset α) : s \ t ∪ s ∩ t = s := sorry
@[simp] theorem sdiff_idem {α : Type u_1} [DecidableEq α] (s : finset α) (t : finset α) : s \ t \ t = s \ t := sorry
theorem sdiff_eq_empty_iff_subset {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} : s \ t = ∅ ↔ s ⊆ t := sorry
@[simp] theorem empty_sdiff {α : Type u_1} [DecidableEq α] (s : finset α) : ∅ \ s = ∅ :=
eq.mpr (id (Eq._oldrec (Eq.refl (∅ \ s = ∅)) (propext sdiff_eq_empty_iff_subset))) (empty_subset s)
theorem insert_sdiff_of_not_mem {α : Type u_1} [DecidableEq α] (s : finset α) {t : finset α} {x : α} (h : ¬x ∈ t) : insert x s \ t = insert x (s \ t) := sorry
theorem insert_sdiff_of_mem {α : Type u_1} [DecidableEq α] (s : finset α) {t : finset α} {x : α} (h : x ∈ t) : insert x s \ t = s \ t := sorry
@[simp] theorem insert_sdiff_insert {α : Type u_1} [DecidableEq α] (s : finset α) (t : finset α) (x : α) : insert x s \ insert x t = s \ insert x t :=
insert_sdiff_of_mem s (mem_insert_self x t)
theorem sdiff_insert_of_not_mem {α : Type u_1} [DecidableEq α] {s : finset α} {x : α} (h : ¬x ∈ s) (t : finset α) : s \ insert x t = s \ t := sorry
@[simp] theorem sdiff_subset {α : Type u_1} [DecidableEq α] (s : finset α) (t : finset α) : s \ t ⊆ s := sorry
theorem union_sdiff_distrib {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) (t : finset α) : (s₁ ∪ s₂) \ t = s₁ \ t ∪ s₂ \ t := sorry
theorem sdiff_union_distrib {α : Type u_1} [DecidableEq α] (s : finset α) (t₁ : finset α) (t₂ : finset α) : s \ (t₁ ∪ t₂) = s \ t₁ ∩ (s \ t₂) := sorry
theorem union_sdiff_self {α : Type u_1} [DecidableEq α] (s : finset α) (t : finset α) : (s ∪ t) \ t = s \ t :=
eq.mpr (id (Eq._oldrec (Eq.refl ((s ∪ t) \ t = s \ t)) (union_sdiff_distrib s t t)))
(eq.mpr (id (Eq._oldrec (Eq.refl (s \ t ∪ t \ t = s \ t)) (sdiff_self t)))
(eq.mpr (id (Eq._oldrec (Eq.refl (s \ t ∪ ∅ = s \ t)) (union_empty (s \ t)))) (Eq.refl (s \ t))))
theorem sdiff_singleton_eq_erase {α : Type u_1} [DecidableEq α] (a : α) (s : finset α) : s \ singleton a = erase s a := sorry
theorem sdiff_sdiff_self_left {α : Type u_1} [DecidableEq α] (s : finset α) (t : finset α) : s \ (s \ t) = s ∩ t := sorry
theorem inter_eq_inter_of_sdiff_eq_sdiff {α : Type u_1} [DecidableEq α] {s : finset α} {t₁ : finset α} {t₂ : finset α} : s \ t₁ = s \ t₂ → s ∩ t₁ = s ∩ t₂ := sorry
/-! ### attach -/
/-- `attach s` takes the elements of `s` and forms a new set of elements of the
subtype `{x // x ∈ s}`. -/
def attach {α : Type u_1} (s : finset α) : finset (Subtype fun (x : α) => x ∈ s) :=
mk (multiset.attach (val s)) sorry
theorem sizeof_lt_sizeof_of_mem {α : Type u_1} [SizeOf α] {x : α} {s : finset α} (hx : x ∈ s) : sizeof x < sizeof s := sorry
@[simp] theorem attach_val {α : Type u_1} (s : finset α) : val (attach s) = multiset.attach (val s) :=
rfl
@[simp] theorem mem_attach {α : Type u_1} (s : finset α) (x : Subtype fun (x : α) => x ∈ s) : x ∈ attach s :=
multiset.mem_attach (val s)
@[simp] theorem attach_empty {α : Type u_1} : attach ∅ = ∅ :=
rfl
/-! ### piecewise -/
/-- `s.piecewise f g` is the function equal to `f` on the finset `s`, and to `g` on its
complement. -/
def piecewise {α : Type u_1} {δ : α → Sort u_2} (s : finset α) (f : (i : α) → δ i) (g : (i : α) → δ i) [(j : α) → Decidable (j ∈ s)] (i : α) : δ i :=
ite (i ∈ s) (f i) (g i)
@[simp] theorem piecewise_insert_self {α : Type u_1} {δ : α → Sort u_4} (s : finset α) (f : (i : α) → δ i) (g : (i : α) → δ i) [DecidableEq α] {j : α} [(i : α) → Decidable (i ∈ insert j s)] : piecewise (insert j s) f g j = f j := sorry
@[simp] theorem piecewise_empty {α : Type u_1} {δ : α → Sort u_4} (f : (i : α) → δ i) (g : (i : α) → δ i) [(i : α) → Decidable (i ∈ ∅)] : piecewise ∅ f g = g := sorry
theorem piecewise_coe {α : Type u_1} {δ : α → Sort u_4} (s : finset α) (f : (i : α) → δ i) (g : (i : α) → δ i) [(j : α) → Decidable (j ∈ s)] [(j : α) → Decidable (j ∈ ↑s)] : set.piecewise (↑s) f g = piecewise s f g := sorry
@[simp] theorem piecewise_eq_of_mem {α : Type u_1} {δ : α → Sort u_4} (s : finset α) (f : (i : α) → δ i) (g : (i : α) → δ i) [(j : α) → Decidable (j ∈ s)] {i : α} (hi : i ∈ s) : piecewise s f g i = f i := sorry
@[simp] theorem piecewise_eq_of_not_mem {α : Type u_1} {δ : α → Sort u_4} (s : finset α) (f : (i : α) → δ i) (g : (i : α) → δ i) [(j : α) → Decidable (j ∈ s)] {i : α} (hi : ¬i ∈ s) : piecewise s f g i = g i := sorry
theorem piecewise_congr {α : Type u_1} {δ : α → Sort u_4} (s : finset α) [(j : α) → Decidable (j ∈ s)] {f : (i : α) → δ i} {f' : (i : α) → δ i} {g : (i : α) → δ i} {g' : (i : α) → δ i} (hf : ∀ (i : α), i ∈ s → f i = f' i) (hg : ∀ (i : α), ¬i ∈ s → g i = g' i) : piecewise s f g = piecewise s f' g' :=
funext fun (i : α) => if_ctx_congr iff.rfl (hf i) (hg i)
@[simp] theorem piecewise_insert_of_ne {α : Type u_1} {δ : α → Sort u_4} (s : finset α) (f : (i : α) → δ i) (g : (i : α) → δ i) [(j : α) → Decidable (j ∈ s)] [DecidableEq α] {i : α} {j : α} [(i : α) → Decidable (i ∈ insert j s)] (h : i ≠ j) : piecewise (insert j s) f g i = piecewise s f g i := sorry
theorem piecewise_insert {α : Type u_1} {δ : α → Sort u_4} (s : finset α) (f : (i : α) → δ i) (g : (i : α) → δ i) [(j : α) → Decidable (j ∈ s)] [DecidableEq α] (j : α) [(i : α) → Decidable (i ∈ insert j s)] : piecewise (insert j s) f g = function.update (piecewise s f g) j (f j) := sorry
theorem piecewise_cases {α : Type u_1} {δ : α → Sort u_4} (s : finset α) (f : (i : α) → δ i) (g : (i : α) → δ i) [(j : α) → Decidable (j ∈ s)] {i : α} (p : δ i → Prop) (hf : p (f i)) (hg : p (g i)) : p (piecewise s f g i) := sorry
theorem piecewise_mem_set_pi {α : Type u_1} (s : finset α) [(j : α) → Decidable (j ∈ s)] {δ : α → Type u_2} {t : set α} {t' : (i : α) → set (δ i)} {f : (i : α) → δ i} {g : (i : α) → δ i} (hf : f ∈ set.pi t t') (hg : g ∈ set.pi t t') : piecewise s f g ∈ set.pi t t' :=
eq.mpr (id (Eq._oldrec (Eq.refl (piecewise s f g ∈ set.pi t t')) (Eq.symm (piecewise_coe s f g))))
(set.piecewise_mem_pi (↑s) hf hg)
theorem piecewise_singleton {α : Type u_1} {δ : α → Sort u_4} (f : (i : α) → δ i) (g : (i : α) → δ i) [DecidableEq α] (i : α) : piecewise (singleton i) f g = function.update g i (f i) := sorry
theorem piecewise_piecewise_of_subset_left {α : Type u_1} {δ : α → Sort u_4} {s : finset α} {t : finset α} [(i : α) → Decidable (i ∈ s)] [(i : α) → Decidable (i ∈ t)] (h : s ⊆ t) (f₁ : (a : α) → δ a) (f₂ : (a : α) → δ a) (g : (a : α) → δ a) : piecewise s (piecewise t f₁ f₂) g = piecewise s f₁ g :=
piecewise_congr s (fun (i : α) (hi : i ∈ s) => piecewise_eq_of_mem t f₁ f₂ (h hi)) fun (_x : α) (_x_1 : ¬_x ∈ s) => rfl
@[simp] theorem piecewise_idem_left {α : Type u_1} {δ : α → Sort u_4} (s : finset α) [(j : α) → Decidable (j ∈ s)] (f₁ : (a : α) → δ a) (f₂ : (a : α) → δ a) (g : (a : α) → δ a) : piecewise s (piecewise s f₁ f₂) g = piecewise s f₁ g :=
piecewise_piecewise_of_subset_left (subset.refl s) f₁ f₂ g
theorem piecewise_piecewise_of_subset_right {α : Type u_1} {δ : α → Sort u_4} {s : finset α} {t : finset α} [(i : α) → Decidable (i ∈ s)] [(i : α) → Decidable (i ∈ t)] (h : t ⊆ s) (f : (a : α) → δ a) (g₁ : (a : α) → δ a) (g₂ : (a : α) → δ a) : piecewise s f (piecewise t g₁ g₂) = piecewise s f g₂ :=
piecewise_congr s (fun (_x : α) (_x_1 : _x ∈ s) => rfl)
fun (i : α) (hi : ¬i ∈ s) => piecewise_eq_of_not_mem t g₁ g₂ (mt h hi)
@[simp] theorem piecewise_idem_right {α : Type u_1} {δ : α → Sort u_4} (s : finset α) [(j : α) → Decidable (j ∈ s)] (f : (a : α) → δ a) (g₁ : (a : α) → δ a) (g₂ : (a : α) → δ a) : piecewise s f (piecewise s g₁ g₂) = piecewise s f g₂ :=
piecewise_piecewise_of_subset_right (subset.refl s) f g₁ g₂
theorem update_eq_piecewise {α : Type u_1} {β : Type u_2} [DecidableEq α] (f : α → β) (i : α) (v : β) : function.update f i v = piecewise (singleton i) (fun (j : α) => v) f :=
Eq.symm (piecewise_singleton (fun (i : α) => v) f i)
theorem update_piecewise {α : Type u_1} {δ : α → Sort u_4} (s : finset α) (f : (i : α) → δ i) (g : (i : α) → δ i) [(j : α) → Decidable (j ∈ s)] [DecidableEq α] (i : α) (v : δ i) : function.update (piecewise s f g) i v = piecewise s (function.update f i v) (function.update g i v) := sorry
theorem update_piecewise_of_mem {α : Type u_1} {δ : α → Sort u_4} (s : finset α) (f : (i : α) → δ i) (g : (i : α) → δ i) [(j : α) → Decidable (j ∈ s)] [DecidableEq α] {i : α} (hi : i ∈ s) (v : δ i) : function.update (piecewise s f g) i v = piecewise s (function.update f i v) g := sorry
theorem update_piecewise_of_not_mem {α : Type u_1} {δ : α → Sort u_4} (s : finset α) (f : (i : α) → δ i) (g : (i : α) → δ i) [(j : α) → Decidable (j ∈ s)] [DecidableEq α] {i : α} (hi : ¬i ∈ s) (v : δ i) : function.update (piecewise s f g) i v = piecewise s f (function.update g i v) := sorry
theorem piecewise_le_of_le_of_le {α : Type u_1} (s : finset α) [(j : α) → Decidable (j ∈ s)] {δ : α → Type u_2} [(i : α) → preorder (δ i)] {f : (i : α) → δ i} {g : (i : α) → δ i} {h : (i : α) → δ i} (Hf : f ≤ h) (Hg : g ≤ h) : piecewise s f g ≤ h :=
fun (x : α) => piecewise_cases s f g (fun (_x : δ x) => _x ≤ h x) (Hf x) (Hg x)
theorem le_piecewise_of_le_of_le {α : Type u_1} (s : finset α) [(j : α) → Decidable (j ∈ s)] {δ : α → Type u_2} [(i : α) → preorder (δ i)] {f : (i : α) → δ i} {g : (i : α) → δ i} {h : (i : α) → δ i} (Hf : h ≤ f) (Hg : h ≤ g) : h ≤ piecewise s f g :=
fun (x : α) => piecewise_cases s f g (fun (y : δ x) => h x ≤ y) (Hf x) (Hg x)
theorem piecewise_le_piecewise' {α : Type u_1} (s : finset α) [(j : α) → Decidable (j ∈ s)] {δ : α → Type u_2} [(i : α) → preorder (δ i)] {f : (i : α) → δ i} {g : (i : α) → δ i} {f' : (i : α) → δ i} {g' : (i : α) → δ i} (Hf : ∀ (x : α), x ∈ s → f x ≤ f' x) (Hg : ∀ (x : α), ¬x ∈ s → g x ≤ g' x) : piecewise s f g ≤ piecewise s f' g' := sorry
theorem piecewise_le_piecewise {α : Type u_1} (s : finset α) [(j : α) → Decidable (j ∈ s)] {δ : α → Type u_2} [(i : α) → preorder (δ i)] {f : (i : α) → δ i} {g : (i : α) → δ i} {f' : (i : α) → δ i} {g' : (i : α) → δ i} (Hf : f ≤ f') (Hg : g ≤ g') : piecewise s f g ≤ piecewise s f' g' :=
piecewise_le_piecewise' s (fun (x : α) (_x : x ∈ s) => Hf x) fun (x : α) (_x : ¬x ∈ s) => Hg x
theorem piecewise_mem_Icc_of_mem_of_mem {α : Type u_1} (s : finset α) [(j : α) → Decidable (j ∈ s)] {δ : α → Type u_2} [(i : α) → preorder (δ i)] {f : (i : α) → δ i} {f₁ : (i : α) → δ i} {g : (i : α) → δ i} {g₁ : (i : α) → δ i} (hf : f ∈ set.Icc f₁ g₁) (hg : g ∈ set.Icc f₁ g₁) : piecewise s f g ∈ set.Icc f₁ g₁ :=
{ left := le_piecewise_of_le_of_le s (and.left hf) (and.left hg),
right := piecewise_le_of_le_of_le s (and.right hf) (and.right hg) }
theorem piecewise_mem_Icc {α : Type u_1} (s : finset α) [(j : α) → Decidable (j ∈ s)] {δ : α → Type u_2} [(i : α) → preorder (δ i)] {f : (i : α) → δ i} {g : (i : α) → δ i} (h : f ≤ g) : piecewise s f g ∈ set.Icc f g :=
piecewise_mem_Icc_of_mem_of_mem s (iff.mpr set.left_mem_Icc h) (iff.mpr set.right_mem_Icc h)
theorem piecewise_mem_Icc' {α : Type u_1} (s : finset α) [(j : α) → Decidable (j ∈ s)] {δ : α → Type u_2} [(i : α) → preorder (δ i)] {f : (i : α) → δ i} {g : (i : α) → δ i} (h : g ≤ f) : piecewise s f g ∈ set.Icc g f :=
piecewise_mem_Icc_of_mem_of_mem s (iff.mpr set.right_mem_Icc h) (iff.mpr set.left_mem_Icc h)
protected instance decidable_dforall_finset {α : Type u_1} {s : finset α} {p : (a : α) → a ∈ s → Prop} [hp : (a : α) → (h : a ∈ s) → Decidable (p a h)] : Decidable (∀ (a : α) (h : a ∈ s), p a h) :=
multiset.decidable_dforall_multiset
/-- decidable equality for functions whose domain is bounded by finsets -/
protected instance decidable_eq_pi_finset {α : Type u_1} {s : finset α} {β : α → Type u_2} [h : (a : α) → DecidableEq (β a)] : DecidableEq ((a : α) → a ∈ s → β a) :=
multiset.decidable_eq_pi_multiset
protected instance decidable_dexists_finset {α : Type u_1} {s : finset α} {p : (a : α) → a ∈ s → Prop} [hp : (a : α) → (h : a ∈ s) → Decidable (p a h)] : Decidable (∃ (a : α), ∃ (h : a ∈ s), p a h) :=
multiset.decidable_dexists_multiset
/-! ### filter -/
/-- `filter p s` is the set of elements of `s` that satisfy `p`. -/
def filter {α : Type u_1} (p : α → Prop) [decidable_pred p] (s : finset α) : finset α :=
mk (multiset.filter p (val s)) sorry
@[simp] theorem filter_val {α : Type u_1} (p : α → Prop) [decidable_pred p] (s : finset α) : val (filter p s) = multiset.filter p (val s) :=
rfl
@[simp] theorem filter_subset {α : Type u_1} (p : α → Prop) [decidable_pred p] (s : finset α) : filter p s ⊆ s :=
multiset.filter_subset p (val s)
@[simp] theorem mem_filter {α : Type u_1} {p : α → Prop} [decidable_pred p] {s : finset α} {a : α} : a ∈ filter p s ↔ a ∈ s ∧ p a :=
multiset.mem_filter
theorem filter_ssubset {α : Type u_1} {p : α → Prop} [decidable_pred p] {s : finset α} : filter p s ⊂ s ↔ ∃ (x : α), ∃ (H : x ∈ s), ¬p x := sorry
theorem filter_filter {α : Type u_1} (p : α → Prop) (q : α → Prop) [decidable_pred p] [decidable_pred q] (s : finset α) : filter q (filter p s) = filter (fun (a : α) => p a ∧ q a) s := sorry
theorem filter_true {α : Type u_1} {s : finset α} [h : decidable_pred fun (_x : α) => True] : filter (fun (_x : α) => True) s = s := sorry
@[simp] theorem filter_false {α : Type u_1} {h : decidable_pred fun (a : α) => False} (s : finset α) : filter (fun (a : α) => False) s = ∅ := sorry
/-- If all elements of a `finset` satisfy the predicate `p`, `s.filter p` is `s`. -/
@[simp] theorem filter_true_of_mem {α : Type u_1} {p : α → Prop} [decidable_pred p] {s : finset α} (h : ∀ (x : α), x ∈ s → p x) : filter p s = s := sorry
/-- If all elements of a `finset` fail to satisfy the predicate `p`, `s.filter p` is `∅`. -/
theorem filter_false_of_mem {α : Type u_1} {p : α → Prop} [decidable_pred p] {s : finset α} (h : ∀ (x : α), x ∈ s → ¬p x) : filter p s = ∅ := sorry
theorem filter_congr {α : Type u_1} {p : α → Prop} {q : α → Prop} [decidable_pred p] [decidable_pred q] {s : finset α} (H : ∀ (x : α), x ∈ s → (p x ↔ q x)) : filter p s = filter q s :=
eq_of_veq (multiset.filter_congr H)
theorem filter_empty {α : Type u_1} (p : α → Prop) [decidable_pred p] : filter p ∅ = ∅ :=
iff.mp subset_empty (filter_subset p ∅)
theorem filter_subset_filter {α : Type u_1} (p : α → Prop) [decidable_pred p] {s : finset α} {t : finset α} (h : s ⊆ t) : filter p s ⊆ filter p t :=
fun (a : α) (ha : a ∈ filter p s) =>
iff.mpr mem_filter { left := h (and.left (iff.mp mem_filter ha)), right := and.right (iff.mp mem_filter ha) }
@[simp] theorem coe_filter {α : Type u_1} (p : α → Prop) [decidable_pred p] (s : finset α) : ↑(filter p s) = has_sep.sep (fun (x : α) => p x) ↑s :=
set.ext fun (_x : α) => mem_filter
theorem filter_singleton {α : Type u_1} (p : α → Prop) [decidable_pred p] (a : α) : filter p (singleton a) = ite (p a) (singleton a) ∅ := sorry
theorem filter_union {α : Type u_1} (p : α → Prop) [decidable_pred p] [DecidableEq α] (s₁ : finset α) (s₂ : finset α) : filter p (s₁ ∪ s₂) = filter p s₁ ∪ filter p s₂ := sorry
theorem filter_union_right {α : Type u_1} (p : α → Prop) (q : α → Prop) [decidable_pred p] [decidable_pred q] [DecidableEq α] (s : finset α) : filter p s ∪ filter q s = filter (fun (x : α) => p x ∨ q x) s := sorry
theorem filter_mem_eq_inter {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} [(i : α) → Decidable (i ∈ t)] : filter (fun (i : α) => i ∈ t) s = s ∩ t := sorry
theorem filter_inter {α : Type u_1} (p : α → Prop) [decidable_pred p] [DecidableEq α] (s : finset α) (t : finset α) : filter p s ∩ t = filter p (s ∩ t) := sorry
theorem inter_filter {α : Type u_1} (p : α → Prop) [decidable_pred p] [DecidableEq α] (s : finset α) (t : finset α) : s ∩ filter p t = filter p (s ∩ t) := sorry
theorem filter_insert {α : Type u_1} (p : α → Prop) [decidable_pred p] [DecidableEq α] (a : α) (s : finset α) : filter p (insert a s) = ite (p a) (insert a (filter p s)) (filter p s) := sorry
theorem filter_or {α : Type u_1} (p : α → Prop) (q : α → Prop) [decidable_pred p] [decidable_pred q] [DecidableEq α] [decidable_pred fun (a : α) => p a ∨ q a] (s : finset α) : filter (fun (a : α) => p a ∨ q a) s = filter p s ∪ filter q s := sorry
theorem filter_and {α : Type u_1} (p : α → Prop) (q : α → Prop) [decidable_pred p] [decidable_pred q] [DecidableEq α] [decidable_pred fun (a : α) => p a ∧ q a] (s : finset α) : filter (fun (a : α) => p a ∧ q a) s = filter p s ∩ filter q s := sorry
theorem filter_not {α : Type u_1} (p : α → Prop) [decidable_pred p] [DecidableEq α] [decidable_pred fun (a : α) => ¬p a] (s : finset α) : filter (fun (a : α) => ¬p a) s = s \ filter p s := sorry
theorem sdiff_eq_filter {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) : s₁ \ s₂ = filter (fun (_x : α) => ¬_x ∈ s₂) s₁ := sorry
theorem sdiff_eq_self {α : Type u_1} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) : s₁ \ s₂ = s₁ ↔ s₁ ∩ s₂ ⊆ ∅ := sorry
theorem filter_union_filter_neg_eq {α : Type u_1} (p : α → Prop) [decidable_pred p] [DecidableEq α] [decidable_pred fun (a : α) => ¬p a] (s : finset α) : filter p s ∪ filter (fun (a : α) => ¬p a) s = s := sorry
theorem filter_inter_filter_neg_eq {α : Type u_1} (p : α → Prop) [decidable_pred p] [DecidableEq α] (s : finset α) : filter p s ∩ filter (fun (a : α) => ¬p a) s = ∅ := sorry
theorem subset_union_elim {α : Type u_1} [DecidableEq α] {s : finset α} {t₁ : set α} {t₂ : set α} (h : ↑s ⊆ t₁ ∪ t₂) : ∃ (s₁ : finset α), ∃ (s₂ : finset α), s₁ ∪ s₂ = s ∧ ↑s₁ ⊆ t₁ ∧ ↑s₂ ⊆ t₂ \ t₁ := sorry
/- We can simplify an application of filter where the decidability is inferred in "the wrong way" -/
@[simp] theorem filter_congr_decidable {α : Type u_1} (s : finset α) (p : α → Prop) (h : decidable_pred p) [decidable_pred p] : filter p s = filter p s := sorry
/-- The following instance allows us to write `{ x ∈ s | p x }` for `finset.filter s p`.
Since the former notation requires us to define this for all propositions `p`, and `finset.filter`
only works for decidable propositions, the notation `{ x ∈ s | p x }` is only compatible with
classical logic because it uses `classical.prop_decidable`.
We don't want to redo all lemmas of `finset.filter` for `has_sep.sep`, so we make sure that `simp`
unfolds the notation `{ x ∈ s | p x }` to `finset.filter s p`. If `p` happens to be decidable, the
simp-lemma `filter_congr_decidable` will make sure that `finset.filter` uses the right instance
for decidability.
-/
protected instance has_sep {α : Type u_1} : has_sep α (finset α) :=
has_sep.mk fun (p : α → Prop) (x : finset α) => filter p x
@[simp] theorem sep_def {α : Type u_1} (s : finset α) (p : α → Prop) : has_sep.sep (fun (x : α) => p x) s = filter p s :=
rfl
/--
After filtering out everything that does not equal a given value, at most that value remains.
This is equivalent to `filter_eq'` with the equality the other way.
-/
-- This is not a good simp lemma, as it would prevent `finset.mem_filter` from firing
-- on, e.g. `x ∈ s.filter(eq b)`.
theorem filter_eq {β : Type u_2} [DecidableEq β] (s : finset β) (b : β) : filter (Eq b) s = ite (b ∈ s) (singleton b) ∅ := sorry
/--
After filtering out everything that does not equal a given value, at most that value remains.
This is equivalent to `filter_eq` with the equality the other way.
-/
theorem filter_eq' {β : Type u_2} [DecidableEq β] (s : finset β) (b : β) : filter (fun (a : β) => a = b) s = ite (b ∈ s) (singleton b) ∅ :=
trans (filter_congr fun (_x : β) (_x_1 : _x ∈ s) => { mp := Eq.symm, mpr := Eq.symm }) (filter_eq s b)
theorem filter_ne {β : Type u_2} [DecidableEq β] (s : finset β) (b : β) : filter (fun (a : β) => b ≠ a) s = erase s b := sorry
theorem filter_ne' {β : Type u_2} [DecidableEq β] (s : finset β) (b : β) : filter (fun (a : β) => a ≠ b) s = erase s b :=
trans (filter_congr fun (_x : β) (_x_1 : _x ∈ s) => { mp := ne.symm, mpr := ne.symm }) (filter_ne s b)
/-! ### range -/
/-- `range n` is the set of natural numbers less than `n`. -/
def range (n : ℕ) : finset ℕ :=
mk (multiset.range n) (multiset.nodup_range n)
@[simp] theorem range_coe (n : ℕ) : val (range n) = multiset.range n :=
rfl
@[simp] theorem mem_range {n : ℕ} {m : ℕ} : m ∈ range n ↔ m < n :=
multiset.mem_range
@[simp] theorem range_zero : range 0 = ∅ :=
rfl
@[simp] theorem range_one : range 1 = singleton 0 :=
rfl
theorem range_succ {n : ℕ} : range (Nat.succ n) = insert n (range n) :=
eq_of_veq (Eq.trans (multiset.range_succ n) (Eq.symm (multiset.ndinsert_of_not_mem multiset.not_mem_range_self)))
theorem range_add_one {n : ℕ} : range (n + 1) = insert n (range n) :=
range_succ
@[simp] theorem not_mem_range_self {n : ℕ} : ¬n ∈ range n :=
multiset.not_mem_range_self
@[simp] theorem self_mem_range_succ (n : ℕ) : n ∈ range (n + 1) :=
multiset.self_mem_range_succ n
@[simp] theorem range_subset {n : ℕ} {m : ℕ} : range n ⊆ range m ↔ n ≤ m :=
multiset.range_subset
theorem range_mono : monotone range :=
fun (_x _x_1 : ℕ) => iff.mpr range_subset
theorem mem_range_succ_iff {a : ℕ} {b : ℕ} : a ∈ range (Nat.succ b) ↔ a ≤ b :=
iff.trans mem_range nat.lt_succ_iff
/- useful rules for calculations with quantifiers -/
theorem exists_mem_empty_iff {α : Type u_1} (p : α → Prop) : (∃ (x : α), x ∈ ∅ ∧ p x) ↔ False := sorry
theorem exists_mem_insert {α : Type u_1} [d : DecidableEq α] (a : α) (s : finset α) (p : α → Prop) : (∃ (x : α), x ∈ insert a s ∧ p x) ↔ p a ∨ ∃ (x : α), x ∈ s ∧ p x := sorry
theorem forall_mem_empty_iff {α : Type u_1} (p : α → Prop) : (∀ (x : α), x ∈ ∅ → p x) ↔ True :=
iff_true_intro fun (_x : α) => false.elim
theorem forall_mem_insert {α : Type u_1} [d : DecidableEq α] (a : α) (s : finset α) (p : α → Prop) : (∀ (x : α), x ∈ insert a s → p x) ↔ p a ∧ ∀ (x : α), x ∈ s → p x := sorry
end finset
/-- Equivalence between the set of natural numbers which are `≥ k` and `ℕ`, given by `n → n - k`. -/
def not_mem_range_equiv (k : ℕ) : (Subtype fun (n : ℕ) => ¬n ∈ multiset.range k) ≃ ℕ :=
equiv.mk (fun (i : Subtype fun (n : ℕ) => ¬n ∈ multiset.range k) => subtype.val i - k)
(fun (j : ℕ) => { val := j + k, property := sorry }) sorry sorry
@[simp] theorem coe_not_mem_range_equiv (k : ℕ) : ⇑(not_mem_range_equiv k) = fun (i : Subtype fun (n : ℕ) => ¬n ∈ multiset.range k) => ↑i - k :=
rfl
@[simp] theorem coe_not_mem_range_equiv_symm (k : ℕ) : ⇑(equiv.symm (not_mem_range_equiv k)) =
fun (j : ℕ) =>
{ val := j + k,
property :=
eq.mpr
(id
(Eq.trans
(Eq.trans
((fun (a a_1 : Prop) (e_1 : a = a_1) => congr_arg Not e_1) (j + k ∈ multiset.range k) (j < 0)
(Eq.trans (propext multiset.mem_range) (propext add_lt_iff_neg_right)))
(propext not_lt))
(propext ((fun {α : Type} (a : α) => iff_true_intro (zero_le a)) j))))
trivial } :=
rfl
namespace option
/-- Construct an empty or singleton finset from an `option` -/
def to_finset {α : Type u_1} (o : Option α) : finset α :=
sorry
@[simp] theorem to_finset_none {α : Type u_1} : to_finset none = ∅ :=
rfl
@[simp] theorem to_finset_some {α : Type u_1} {a : α} : to_finset (some a) = singleton a :=
rfl
@[simp] theorem mem_to_finset {α : Type u_1} {a : α} {o : Option α} : a ∈ to_finset o ↔ a ∈ o := sorry
end option
/-! ### erase_dup on list and multiset -/
namespace multiset
/-- `to_finset s` removes duplicates from the multiset `s` to produce a finset. -/
def to_finset {α : Type u_1} [DecidableEq α] (s : multiset α) : finset α :=
finset.mk (erase_dup s) sorry
@[simp] theorem to_finset_val {α : Type u_1} [DecidableEq α] (s : multiset α) : finset.val (to_finset s) = erase_dup s :=
rfl
theorem to_finset_eq {α : Type u_1} [DecidableEq α] {s : multiset α} (n : nodup s) : finset.mk s n = to_finset s :=
iff.mp finset.val_inj (Eq.symm (iff.mpr erase_dup_eq_self n))
@[simp] theorem mem_to_finset {α : Type u_1} [DecidableEq α] {a : α} {s : multiset α} : a ∈ to_finset s ↔ a ∈ s :=
mem_erase_dup
@[simp] theorem to_finset_zero {α : Type u_1} [DecidableEq α] : to_finset 0 = ∅ :=
rfl
@[simp] theorem to_finset_cons {α : Type u_1} [DecidableEq α] (a : α) (s : multiset α) : to_finset (a ::ₘ s) = insert a (to_finset s) :=
finset.eq_of_veq erase_dup_cons
@[simp] theorem to_finset_add {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) : to_finset (s + t) = to_finset s ∪ to_finset t := sorry
@[simp] theorem to_finset_nsmul {α : Type u_1} [DecidableEq α] (s : multiset α) (n : ℕ) (hn : n ≠ 0) : to_finset (n •ℕ s) = to_finset s := sorry
@[simp] theorem to_finset_inter {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) : to_finset (s ∩ t) = to_finset s ∩ to_finset t := sorry
@[simp] theorem to_finset_union {α : Type u_1} [DecidableEq α] (s : multiset α) (t : multiset α) : to_finset (s ∪ t) = to_finset s ∪ to_finset t := sorry
theorem to_finset_eq_empty {α : Type u_1} [DecidableEq α] {m : multiset α} : to_finset m = ∅ ↔ m = 0 :=
iff.trans (iff.symm finset.val_inj) erase_dup_eq_zero
@[simp] theorem to_finset_subset {α : Type u_1} [DecidableEq α] (m1 : multiset α) (m2 : multiset α) : to_finset m1 ⊆ to_finset m2 ↔ m1 ⊆ m2 := sorry
end multiset
namespace finset
@[simp] theorem val_to_finset {α : Type u_1} [DecidableEq α] (s : finset α) : multiset.to_finset (val s) = s := sorry
end finset
namespace list
/-- `to_finset l` removes duplicates from the list `l` to produce a finset. -/
def to_finset {α : Type u_1} [DecidableEq α] (l : List α) : finset α :=
multiset.to_finset ↑l
@[simp] theorem to_finset_val {α : Type u_1} [DecidableEq α] (l : List α) : finset.val (to_finset l) = ↑(erase_dup l) :=
rfl
theorem to_finset_eq {α : Type u_1} [DecidableEq α] {l : List α} (n : nodup l) : finset.mk (↑l) n = to_finset l :=
multiset.to_finset_eq n
@[simp] theorem mem_to_finset {α : Type u_1} [DecidableEq α] {a : α} {l : List α} : a ∈ to_finset l ↔ a ∈ l :=
mem_erase_dup
@[simp] theorem to_finset_nil {α : Type u_1} [DecidableEq α] : to_finset [] = ∅ :=
rfl
@[simp] theorem to_finset_cons {α : Type u_1} [DecidableEq α] {a : α} {l : List α} : to_finset (a :: l) = insert a (to_finset l) := sorry
theorem to_finset_surj_on {α : Type u_1} [DecidableEq α] : set.surj_on to_finset (set_of fun (l : List α) => nodup l) set.univ := sorry
theorem to_finset_surjective {α : Type u_1} [DecidableEq α] : function.surjective to_finset := sorry
end list
namespace finset
/-! ### map -/
/-- When `f` is an embedding of `α` in `β` and `s` is a finset in `α`, then `s.map f` is the image
finset in `β`. The embedding condition guarantees that there are no duplicates in the image. -/
def map {α : Type u_1} {β : Type u_2} (f : α ↪ β) (s : finset α) : finset β :=
mk (multiset.map (⇑f) (val s)) sorry
@[simp] theorem map_val {α : Type u_1} {β : Type u_2} (f : α ↪ β) (s : finset α) : val (map f s) = multiset.map (⇑f) (val s) :=
rfl
@[simp] theorem map_empty {α : Type u_1} {β : Type u_2} (f : α ↪ β) : map f ∅ = ∅ :=
rfl
@[simp] theorem mem_map {α : Type u_1} {β : Type u_2} {f : α ↪ β} {s : finset α} {b : β} : b ∈ map f s ↔ ∃ (a : α), ∃ (H : a ∈ s), coe_fn f a = b := sorry
theorem mem_map' {α : Type u_1} {β : Type u_2} (f : α ↪ β) {a : α} {s : finset α} : coe_fn f a ∈ map f s ↔ a ∈ s :=
multiset.mem_map_of_injective (function.embedding.inj' f)
theorem mem_map_of_mem {α : Type u_1} {β : Type u_2} (f : α ↪ β) {a : α} {s : finset α} : a ∈ s → coe_fn f a ∈ map f s :=
iff.mpr (mem_map' f)
@[simp] theorem coe_map {α : Type u_1} {β : Type u_2} (f : α ↪ β) (s : finset α) : ↑(map f s) = ⇑f '' ↑s :=
set.ext fun (x : β) => iff.trans mem_map (iff.symm set.mem_image_iff_bex)
theorem coe_map_subset_range {α : Type u_1} {β : Type u_2} (f : α ↪ β) (s : finset α) : ↑(map f s) ⊆ set.range ⇑f :=
trans_rel_right has_subset.subset (coe_map f s) (set.image_subset_range ⇑f ↑s)
theorem map_to_finset {α : Type u_1} {β : Type u_2} {f : α ↪ β} [DecidableEq α] [DecidableEq β] {s : multiset α} : map f (multiset.to_finset s) = multiset.to_finset (multiset.map (⇑f) s) := sorry
@[simp] theorem map_refl {α : Type u_1} {s : finset α} : map (function.embedding.refl α) s = s := sorry
theorem map_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {f : α ↪ β} {s : finset α} {g : β ↪ γ} : map g (map f s) = map (function.embedding.trans f g) s := sorry
theorem map_subset_map {α : Type u_1} {β : Type u_2} {f : α ↪ β} {s₁ : finset α} {s₂ : finset α} : map f s₁ ⊆ map f s₂ ↔ s₁ ⊆ s₂ := sorry
theorem map_inj {α : Type u_1} {β : Type u_2} {f : α ↪ β} {s₁ : finset α} {s₂ : finset α} : map f s₁ = map f s₂ ↔ s₁ = s₂ := sorry
/-- Associate to an embedding `f` from `α` to `β` the embedding that maps a finset to its image
under `f`. -/
def map_embedding {α : Type u_1} {β : Type u_2} (f : α ↪ β) : finset α ↪ finset β :=
function.embedding.mk (map f) sorry
@[simp] theorem map_embedding_apply {α : Type u_1} {β : Type u_2} {f : α ↪ β} {s : finset α} : coe_fn (map_embedding f) s = map f s :=
rfl
theorem map_filter {α : Type u_1} {β : Type u_2} {f : α ↪ β} {s : finset α} {p : β → Prop} [decidable_pred p] : filter p (map f s) = map f (filter (p ∘ ⇑f) s) := sorry
theorem map_union {α : Type u_1} {β : Type u_2} [DecidableEq α] [DecidableEq β] {f : α ↪ β} (s₁ : finset α) (s₂ : finset α) : map f (s₁ ∪ s₂) = map f s₁ ∪ map f s₂ := sorry
theorem map_inter {α : Type u_1} {β : Type u_2} [DecidableEq α] [DecidableEq β] {f : α ↪ β} (s₁ : finset α) (s₂ : finset α) : map f (s₁ ∩ s₂) = map f s₁ ∩ map f s₂ := sorry
@[simp] theorem map_singleton {α : Type u_1} {β : Type u_2} (f : α ↪ β) (a : α) : map f (singleton a) = singleton (coe_fn f a) := sorry
@[simp] theorem map_insert {α : Type u_1} {β : Type u_2} [DecidableEq α] [DecidableEq β] (f : α ↪ β) (a : α) (s : finset α) : map f (insert a s) = insert (coe_fn f a) (map f s) := sorry
@[simp] theorem map_eq_empty {α : Type u_1} {β : Type u_2} {f : α ↪ β} {s : finset α} : map f s = ∅ ↔ s = ∅ := sorry
theorem attach_map_val {α : Type u_1} {s : finset α} : map (function.embedding.subtype fun (x : α) => x ∈ s) (attach s) = s := sorry
theorem nonempty.map {α : Type u_1} {β : Type u_2} {s : finset α} (h : finset.nonempty s) (f : α ↪ β) : finset.nonempty (map f s) := sorry
theorem range_add_one' (n : ℕ) : range (n + 1) = insert 0 (map (function.embedding.mk (fun (i : ℕ) => i + 1) fun (i j : ℕ) => nat.succ.inj) (range n)) := sorry
/-! ### image -/
/-- `image f s` is the forward image of `s` under `f`. -/
def image {α : Type u_1} {β : Type u_2} [DecidableEq β] (f : α → β) (s : finset α) : finset β :=
multiset.to_finset (multiset.map f (val s))
@[simp] theorem image_val {α : Type u_1} {β : Type u_2} [DecidableEq β] (f : α → β) (s : finset α) : val (image f s) = multiset.erase_dup (multiset.map f (val s)) :=
rfl
@[simp] theorem image_empty {α : Type u_1} {β : Type u_2} [DecidableEq β] (f : α → β) : image f ∅ = ∅ :=
rfl
@[simp] theorem mem_image {α : Type u_1} {β : Type u_2} [DecidableEq β] {f : α → β} {s : finset α} {b : β} : b ∈ image f s ↔ ∃ (a : α), ∃ (H : a ∈ s), f a = b := sorry
theorem mem_image_of_mem {α : Type u_1} {β : Type u_2} [DecidableEq β] (f : α → β) {a : α} {s : finset α} (h : a ∈ s) : f a ∈ image f s :=
iff.mpr mem_image (Exists.intro a (Exists.intro h rfl))
theorem filter_mem_image_eq_image {α : Type u_1} {β : Type u_2} [DecidableEq β] (f : α → β) (s : finset α) (t : finset β) (h : ∀ (x : α), x ∈ s → f x ∈ t) : filter (fun (y : β) => y ∈ image f s) t = image f s := sorry
theorem fiber_nonempty_iff_mem_image {α : Type u_1} {β : Type u_2} [DecidableEq β] (f : α → β) (s : finset α) (y : β) : finset.nonempty (filter (fun (x : α) => f x = y) s) ↔ y ∈ image f s := sorry
@[simp] theorem coe_image {α : Type u_1} {β : Type u_2} [DecidableEq β] {s : finset α} {f : α → β} : ↑(image f s) = f '' ↑s :=
set.ext fun (_x : β) => iff.trans mem_image (iff.symm set.mem_image_iff_bex)
theorem nonempty.image {α : Type u_1} {β : Type u_2} [DecidableEq β] {s : finset α} (h : finset.nonempty s) (f : α → β) : finset.nonempty (image f s) := sorry
theorem image_to_finset {α : Type u_1} {β : Type u_2} [DecidableEq β] {f : α → β} [DecidableEq α] {s : multiset α} : image f (multiset.to_finset s) = multiset.to_finset (multiset.map f s) := sorry
theorem image_val_of_inj_on {α : Type u_1} {β : Type u_2} [DecidableEq β] {f : α → β} {s : finset α} (H : ∀ (x : α), x ∈ s → ∀ (y : α), y ∈ s → f x = f y → x = y) : val (image f s) = multiset.map f (val s) :=
iff.mpr multiset.erase_dup_eq_self (multiset.nodup_map_on H (nodup s))
@[simp] theorem image_id {α : Type u_1} {s : finset α} [DecidableEq α] : image id s = s := sorry
theorem image_image {α : Type u_1} {β : Type u_2} {γ : Type u_3} [DecidableEq β] {f : α → β} {s : finset α} [DecidableEq γ] {g : β → γ} : image g (image f s) = image (g ∘ f) s := sorry
theorem image_subset_image {α : Type u_1} {β : Type u_2} [DecidableEq β] {f : α → β} {s₁ : finset α} {s₂ : finset α} (h : s₁ ⊆ s₂) : image f s₁ ⊆ image f s₂ := sorry
theorem image_subset_iff {α : Type u_1} {β : Type u_2} [DecidableEq β] {s : finset α} {t : finset β} {f : α → β} : image f s ⊆ t ↔ ∀ (x : α), x ∈ s → f x ∈ t := sorry
theorem image_mono {α : Type u_1} {β : Type u_2} [DecidableEq β] (f : α → β) : monotone (image f) :=
fun (_x _x_1 : finset α) => image_subset_image
theorem coe_image_subset_range {α : Type u_1} {β : Type u_2} [DecidableEq β] {f : α → β} {s : finset α} : ↑(image f s) ⊆ set.range f :=
trans_rel_right has_subset.subset coe_image (set.image_subset_range f ↑s)
theorem image_filter {α : Type u_1} {β : Type u_2} [DecidableEq β] {f : α → β} {s : finset α} {p : β → Prop} [decidable_pred p] : filter p (image f s) = image f (filter (p ∘ f) s) := sorry
theorem image_union {α : Type u_1} {β : Type u_2} [DecidableEq β] [DecidableEq α] {f : α → β} (s₁ : finset α) (s₂ : finset α) : image f (s₁ ∪ s₂) = image f s₁ ∪ image f s₂ := sorry
theorem image_inter {α : Type u_1} {β : Type u_2} [DecidableEq β] {f : α → β} [DecidableEq α] (s₁ : finset α) (s₂ : finset α) (hf : ∀ (x y : α), f x = f y → x = y) : image f (s₁ ∩ s₂) = image f s₁ ∩ image f s₂ := sorry
@[simp] theorem image_singleton {α : Type u_1} {β : Type u_2} [DecidableEq β] (f : α → β) (a : α) : image f (singleton a) = singleton (f a) := sorry
@[simp] theorem image_insert {α : Type u_1} {β : Type u_2} [DecidableEq β] [DecidableEq α] (f : α → β) (a : α) (s : finset α) : image f (insert a s) = insert (f a) (image f s) := sorry
@[simp] theorem image_eq_empty {α : Type u_1} {β : Type u_2} [DecidableEq β] {f : α → β} {s : finset α} : image f s = ∅ ↔ s = ∅ := sorry
theorem attach_image_val {α : Type u_1} [DecidableEq α] {s : finset α} : image subtype.val (attach s) = s := sorry
@[simp] theorem attach_insert {α : Type u_1} [DecidableEq α] {a : α} {s : finset α} : attach (insert a s) =
insert { val := a, property := mem_insert_self a s }
(image
(fun (x : Subtype fun (x : α) => x ∈ s) =>
{ val := subtype.val x, property := mem_insert_of_mem (subtype.property x) })
(attach s)) := sorry
theorem map_eq_image {α : Type u_1} {β : Type u_2} [DecidableEq β] (f : α ↪ β) (s : finset α) : map f s = image (⇑f) s :=
eq_of_veq (Eq.symm (iff.mpr multiset.erase_dup_eq_self (nodup (map f s))))
theorem image_const {α : Type u_1} {β : Type u_2} [DecidableEq β] {s : finset α} (h : finset.nonempty s) (b : β) : image (fun (a : α) => b) s = singleton b := sorry
/--
Because `finset.image` requires a `decidable_eq` instances for the target type,
we can only construct a `functor finset` when working classically.
-/
protected instance functor [(P : Prop) → Decidable P] : Functor finset :=
{ map := fun (α β : Type u_1) (f : α → β) (s : finset α) => image f s,
mapConst := fun (α β : Type u_1) => (fun (f : β → α) (s : finset β) => image f s) ∘ function.const β }
protected instance is_lawful_functor [(P : Prop) → Decidable P] : is_lawful_functor finset :=
is_lawful_functor.mk (fun (α : Type u_1) (x : finset α) => image_id)
fun (α β γ : Type u_1) (f : α → β) (g : β → γ) (s : finset α) => Eq.symm image_image
/-- Given a finset `s` and a predicate `p`, `s.subtype p` is the finset of `subtype p` whose
elements belong to `s`. -/
protected def subtype {α : Type u_1} (p : α → Prop) [decidable_pred p] (s : finset α) : finset (Subtype p) :=
map
(function.embedding.mk
(fun (x : Subtype fun (x : α) => x ∈ filter p s) => { val := subtype.val x, property := sorry }) sorry)
(attach (filter p s))
@[simp] theorem mem_subtype {α : Type u_1} {p : α → Prop} [decidable_pred p] {s : finset α} {a : Subtype p} : a ∈ finset.subtype p s ↔ ↑a ∈ s := sorry
theorem subtype_eq_empty {α : Type u_1} {p : α → Prop} [decidable_pred p] {s : finset α} : finset.subtype p s = ∅ ↔ ∀ (x : α), p x → ¬x ∈ s := sorry
/-- `s.subtype p` converts back to `s.filter p` with
`embedding.subtype`. -/
@[simp] theorem subtype_map {α : Type u_1} {s : finset α} (p : α → Prop) [decidable_pred p] : map (function.embedding.subtype p) (finset.subtype p s) = filter p s := sorry
/-- If all elements of a `finset` satisfy the predicate `p`,
`s.subtype p` converts back to `s` with `embedding.subtype`. -/
theorem subtype_map_of_mem {α : Type u_1} {s : finset α} {p : α → Prop} [decidable_pred p] (h : ∀ (x : α), x ∈ s → p x) : map (function.embedding.subtype p) (finset.subtype p s) = s :=
eq.mpr (id (Eq._oldrec (Eq.refl (map (function.embedding.subtype p) (finset.subtype p s) = s)) (subtype_map p)))
(eq.mpr (id (Eq._oldrec (Eq.refl (filter p s = s)) (filter_true_of_mem h))) (Eq.refl s))
/-- If a `finset` of a subtype is converted to the main type with
`embedding.subtype`, all elements of the result have the property of
the subtype. -/
theorem property_of_mem_map_subtype {α : Type u_1} {p : α → Prop} (s : finset (Subtype fun (x : α) => p x)) {a : α} (h : a ∈ map (function.embedding.subtype fun (x : α) => p x) s) : p a := sorry
/-- If a `finset` of a subtype is converted to the main type with
`embedding.subtype`, the result does not contain any value that does
not satisfy the property of the subtype. -/
theorem not_mem_map_subtype_of_not_property {α : Type u_1} {p : α → Prop} (s : finset (Subtype fun (x : α) => p x)) {a : α} (h : ¬p a) : ¬a ∈ map (function.embedding.subtype fun (x : α) => p x) s :=
mt (property_of_mem_map_subtype s) h
/-- If a `finset` of a subtype is converted to the main type with
`embedding.subtype`, the result is a subset of the set giving the
subtype. -/
theorem map_subtype_subset {α : Type u_1} {t : set α} (s : finset ↥t) : ↑(map (function.embedding.subtype fun (x : α) => x ∈ t) s) ⊆ t := sorry
theorem subset_image_iff {α : Type u_1} {β : Type u_2} [DecidableEq β] {f : α → β} {s : finset β} {t : set α} : ↑s ⊆ f '' t ↔ ∃ (s' : finset α), ↑s' ⊆ t ∧ image f s' = s := sorry
end finset
theorem multiset.to_finset_map {α : Type u_1} {β : Type u_2} [DecidableEq α] [DecidableEq β] (f : α → β) (m : multiset α) : multiset.to_finset (multiset.map f m) = finset.image f (multiset.to_finset m) :=
iff.mp finset.val_inj (Eq.symm (multiset.erase_dup_map_erase_dup_eq f m))
namespace finset
/-! ### card -/
/-- `card s` is the cardinality (number of elements) of `s`. -/
def card {α : Type u_1} (s : finset α) : ℕ :=
coe_fn multiset.card (val s)
theorem card_def {α : Type u_1} (s : finset α) : card s = coe_fn multiset.card (val s) :=
rfl
@[simp] theorem card_mk {α : Type u_1} {m : multiset α} {nodup : multiset.nodup m} : card (mk m nodup) = coe_fn multiset.card m :=
rfl
@[simp] theorem card_empty {α : Type u_1} : card ∅ = 0 :=
rfl
@[simp] theorem card_eq_zero {α : Type u_1} {s : finset α} : card s = 0 ↔ s = ∅ :=
iff.trans multiset.card_eq_zero val_eq_zero
theorem card_pos {α : Type u_1} {s : finset α} : 0 < card s ↔ finset.nonempty s :=
iff.trans pos_iff_ne_zero (iff.trans (not_congr card_eq_zero) (iff.symm nonempty_iff_ne_empty))
theorem card_ne_zero_of_mem {α : Type u_1} {s : finset α} {a : α} (h : a ∈ s) : card s ≠ 0 :=
iff.mpr (not_congr card_eq_zero) (ne_empty_of_mem h)
theorem card_eq_one {α : Type u_1} {s : finset α} : card s = 1 ↔ ∃ (a : α), s = singleton a := sorry
@[simp] theorem card_insert_of_not_mem {α : Type u_1} [DecidableEq α] {a : α} {s : finset α} (h : ¬a ∈ s) : card (insert a s) = card s + 1 := sorry
theorem card_insert_of_mem {α : Type u_1} [DecidableEq α] {a : α} {s : finset α} (h : a ∈ s) : card (insert a s) = card s :=
eq.mpr (id (Eq._oldrec (Eq.refl (card (insert a s) = card s)) (insert_eq_of_mem h))) (Eq.refl (card s))
theorem card_insert_le {α : Type u_1} [DecidableEq α] (a : α) (s : finset α) : card (insert a s) ≤ card s + 1 := sorry
@[simp] theorem card_singleton {α : Type u_1} (a : α) : card (singleton a) = 1 :=
multiset.card_singleton a
theorem card_singleton_inter {α : Type u_1} [DecidableEq α] {x : α} {s : finset α} : card (singleton x ∩ s) ≤ 1 := sorry
theorem card_erase_of_mem {α : Type u_1} [DecidableEq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) = Nat.pred (card s) :=
multiset.card_erase_of_mem
theorem card_erase_lt_of_mem {α : Type u_1} [DecidableEq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) < card s :=
multiset.card_erase_lt_of_mem
theorem card_erase_le {α : Type u_1} [DecidableEq α] {a : α} {s : finset α} : card (erase s a) ≤ card s :=
multiset.card_erase_le
theorem pred_card_le_card_erase {α : Type u_1} [DecidableEq α] {a : α} {s : finset α} : card s - 1 ≤ card (erase s a) := sorry
@[simp] theorem card_range (n : ℕ) : card (range n) = n :=
multiset.card_range n
@[simp] theorem card_attach {α : Type u_1} {s : finset α} : card (attach s) = card s :=
multiset.card_attach
end finset
theorem multiset.to_finset_card_le {α : Type u_1} [DecidableEq α] (m : multiset α) : finset.card (multiset.to_finset m) ≤ coe_fn multiset.card m :=
multiset.card_le_of_le (multiset.erase_dup_le m)
theorem list.to_finset_card_le {α : Type u_1} [DecidableEq α] (l : List α) : finset.card (list.to_finset l) ≤ list.length l :=
multiset.to_finset_card_le (quotient.mk l)
namespace finset
theorem card_image_le {α : Type u_1} {β : Type u_2} [DecidableEq β] {f : α → β} {s : finset α} : card (image f s) ≤ card s := sorry
theorem card_image_of_inj_on {α : Type u_1} {β : Type u_2} [DecidableEq β] {f : α → β} {s : finset α} (H : ∀ (x : α), x ∈ s → ∀ (y : α), y ∈ s → f x = f y → x = y) : card (image f s) = card s := sorry
theorem card_image_of_injective {α : Type u_1} {β : Type u_2} [DecidableEq β] {f : α → β} (s : finset α) (H : function.injective f) : card (image f s) = card s :=
card_image_of_inj_on fun (x : α) (_x : x ∈ s) (y : α) (_x : y ∈ s) (h : f x = f y) => H h
theorem fiber_card_ne_zero_iff_mem_image {α : Type u_1} {β : Type u_2} (s : finset α) (f : α → β) [DecidableEq β] (y : β) : card (filter (fun (x : α) => f x = y) s) ≠ 0 ↔ y ∈ image f s := sorry
@[simp] theorem card_map {α : Type u_1} {β : Type u_2} (f : α ↪ β) {s : finset α} : card (map f s) = card s :=
multiset.card_map (⇑f) (val s)
@[simp] theorem card_subtype {α : Type u_1} (p : α → Prop) [decidable_pred p] (s : finset α) : card (finset.subtype p s) = card (filter p s) := sorry
theorem card_eq_of_bijective {α : Type u_1} {s : finset α} {n : ℕ} (f : (i : ℕ) → i < n → α) (hf : ∀ (a : α), a ∈ s → ∃ (i : ℕ), ∃ (h : i < n), f i h = a) (hf' : ∀ (i : ℕ) (h : i < n), f i h ∈ s) (f_inj : ∀ (i j : ℕ) (hi : i < n) (hj : j < n), f i hi = f j hj → i = j) : card s = n := sorry
theorem card_eq_succ {α : Type u_1} [DecidableEq α] {s : finset α} {n : ℕ} : card s = n + 1 ↔ ∃ (a : α), ∃ (t : finset α), ¬a ∈ t ∧ insert a t = s ∧ card t = n := sorry
theorem card_le_of_subset {α : Type u_1} {s : finset α} {t : finset α} : s ⊆ t → card s ≤ card t :=
multiset.card_le_of_le ∘ iff.mpr val_le_iff
theorem eq_of_subset_of_card_le {α : Type u_1} {s : finset α} {t : finset α} (h : s ⊆ t) (h₂ : card t ≤ card s) : s = t :=
eq_of_veq (multiset.eq_of_le_of_card_le (iff.mpr val_le_iff h) h₂)
theorem card_lt_card {α : Type u_1} {s : finset α} {t : finset α} (h : s ⊂ t) : card s < card t :=
multiset.card_lt_of_lt (iff.mpr val_lt_iff h)
theorem card_le_card_of_inj_on {α : Type u_1} {β : Type u_2} {s : finset α} {t : finset β} (f : α → β) (hf : ∀ (a : α), a ∈ s → f a ∈ t) (f_inj : ∀ (a₁ : α), a₁ ∈ s → ∀ (a₂ : α), a₂ ∈ s → f a₁ = f a₂ → a₁ = a₂) : card s ≤ card t := sorry
/--
If there are more pigeons than pigeonholes, then there are two pigeons
in the same pigeonhole.
-/
theorem exists_ne_map_eq_of_card_lt_of_maps_to {α : Type u_1} {β : Type u_2} {s : finset α} {t : finset β} (hc : card t < card s) {f : α → β} (hf : ∀ (a : α), a ∈ s → f a ∈ t) : ∃ (x : α), ∃ (H : x ∈ s), ∃ (y : α), ∃ (H : y ∈ s), x ≠ y ∧ f x = f y := sorry
theorem card_le_of_inj_on {α : Type u_1} {n : ℕ} {s : finset α} (f : ℕ → α) (hf : ∀ (i : ℕ), i < n → f i ∈ s) (f_inj : ∀ (i j : ℕ), i < n → j < n → f i = f j → i = j) : n ≤ card s := sorry
/-- Suppose that, given objects defined on all strict subsets of any finset `s`, one knows how to
define an object on `s`. Then one can inductively define an object on all finsets, starting from
the empty set and iterating. This can be used either to define data, or to prove properties. -/
def strong_induction_on {α : Type u_1} {p : finset α → Sort u_2} (s : finset α) : ((s : finset α) → ((t : finset α) → t ⊂ s → p t) → p s) → p s :=
sorry
theorem case_strong_induction_on {α : Type u_1} [DecidableEq α] {p : finset α → Prop} (s : finset α) (h₀ : p ∅) (h₁ : ∀ (a : α) (s : finset α), ¬a ∈ s → (∀ (t : finset α), t ⊆ s → p t) → p (insert a s)) : p s := sorry
theorem card_congr {α : Type u_1} {β : Type u_2} {s : finset α} {t : finset β} (f : (a : α) → a ∈ s → β) (h₁ : ∀ (a : α) (ha : a ∈ s), f a ha ∈ t) (h₂ : ∀ (a b : α) (ha : a ∈ s) (hb : b ∈ s), f a ha = f b hb → a = b) (h₃ : ∀ (b : β), b ∈ t → ∃ (a : α), ∃ (ha : a ∈ s), f a ha = b) : card s = card t := sorry
theorem card_union_add_card_inter {α : Type u_1} [DecidableEq α] (s : finset α) (t : finset α) : card (s ∪ t) + card (s ∩ t) = card s + card t := sorry
theorem card_union_le {α : Type u_1} [DecidableEq α] (s : finset α) (t : finset α) : card (s ∪ t) ≤ card s + card t :=
card_union_add_card_inter s t ▸ nat.le_add_right (card (s ∪ t)) (card (s ∩ t))
theorem card_union_eq {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} (h : disjoint s t) : card (s ∪ t) = card s + card t := sorry
theorem surj_on_of_inj_on_of_card_le {α : Type u_1} {β : Type u_2} {s : finset α} {t : finset β} (f : (a : α) → a ∈ s → β) (hf : ∀ (a : α) (ha : a ∈ s), f a ha ∈ t) (hinj : ∀ (a₁ a₂ : α) (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s), f a₁ ha₁ = f a₂ ha₂ → a₁ = a₂) (hst : card t ≤ card s) (b : β) (H : b ∈ t) : ∃ (a : α), ∃ (ha : a ∈ s), b = f a ha := sorry
theorem inj_on_of_surj_on_of_card_le {α : Type u_1} {β : Type u_2} {s : finset α} {t : finset β} (f : (a : α) → a ∈ s → β) (hf : ∀ (a : α) (ha : a ∈ s), f a ha ∈ t) (hsurj : ∀ (b : β), b ∈ t → ∃ (a : α), ∃ (ha : a ∈ s), b = f a ha) (hst : card s ≤ card t) {a₁ : α} {a₂ : α} (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s) (ha₁a₂ : f a₁ ha₁ = f a₂ ha₂) : a₁ = a₂ := sorry
/-!
### bUnion
This section is about the bounded union of an indexed family `t : α → finset β` of finite sets
over a finite set `s : finset α`.
-/
/-- `bUnion s t` is the union of `t x` over `x ∈ s`.
(This was formerly `bind` due to the monad structure on types with `decidable_eq`.) -/
protected def bUnion {α : Type u_1} {β : Type u_2} [DecidableEq β] (s : finset α) (t : α → finset β) : finset β :=
multiset.to_finset (multiset.bind (val s) fun (a : α) => val (t a))
@[simp] theorem bUnion_val {α : Type u_1} {β : Type u_2} [DecidableEq β] (s : finset α) (t : α → finset β) : val (finset.bUnion s t) = multiset.erase_dup (multiset.bind (val s) fun (a : α) => val (t a)) :=
rfl
@[simp] theorem bUnion_empty {α : Type u_1} {β : Type u_2} [DecidableEq β] {t : α → finset β} : finset.bUnion ∅ t = ∅ :=
rfl
@[simp] theorem mem_bUnion {α : Type u_1} {β : Type u_2} [DecidableEq β] {s : finset α} {t : α → finset β} {b : β} : b ∈ finset.bUnion s t ↔ ∃ (a : α), ∃ (H : a ∈ s), b ∈ t a := sorry
@[simp] theorem bUnion_insert {α : Type u_1} {β : Type u_2} [DecidableEq β] {s : finset α} {t : α → finset β} [DecidableEq α] {a : α} : finset.bUnion (insert a s) t = t a ∪ finset.bUnion s t := sorry
-- ext $ λ x, by simp [or_and_distrib_right, exists_or_distrib]
@[simp] theorem singleton_bUnion {α : Type u_1} {β : Type u_2} [DecidableEq β] {t : α → finset β} {a : α} : finset.bUnion (singleton a) t = t a := sorry
theorem bUnion_inter {α : Type u_1} {β : Type u_2} [DecidableEq β] (s : finset α) (f : α → finset β) (t : finset β) : finset.bUnion s f ∩ t = finset.bUnion s fun (x : α) => f x ∩ t := sorry
theorem inter_bUnion {α : Type u_1} {β : Type u_2} [DecidableEq β] (t : finset β) (s : finset α) (f : α → finset β) : t ∩ finset.bUnion s f = finset.bUnion s fun (x : α) => t ∩ f x := sorry
theorem image_bUnion {α : Type u_1} {β : Type u_2} {γ : Type u_3} [DecidableEq β] [DecidableEq γ] {f : α → β} {s : finset α} {t : β → finset γ} : finset.bUnion (image f s) t = finset.bUnion s fun (a : α) => t (f a) := sorry
theorem bUnion_image {α : Type u_1} {β : Type u_2} {γ : Type u_3} [DecidableEq β] [DecidableEq γ] {s : finset α} {t : α → finset β} {f : β → γ} : image f (finset.bUnion s t) = finset.bUnion s fun (a : α) => image f (t a) := sorry
theorem bind_to_finset {α : Type u_1} {β : Type u_2} [DecidableEq β] [DecidableEq α] (s : multiset α) (t : α → multiset β) : multiset.to_finset (multiset.bind s t) = finset.bUnion (multiset.to_finset s) fun (a : α) => multiset.to_finset (t a) := sorry
theorem bUnion_mono {α : Type u_1} {β : Type u_2} [DecidableEq β] {s : finset α} {t₁ : α → finset β} {t₂ : α → finset β} (h : ∀ (a : α), a ∈ s → t₁ a ⊆ t₂ a) : finset.bUnion s t₁ ⊆ finset.bUnion s t₂ := sorry
theorem bUnion_subset_bUnion_of_subset_left {β : Type u_2} [DecidableEq β] {α : Type u_1} {s₁ : finset α} {s₂ : finset α} (t : α → finset β) (h : s₁ ⊆ s₂) : finset.bUnion s₁ t ⊆ finset.bUnion s₂ t := sorry
theorem bUnion_singleton {α : Type u_1} {β : Type u_2} [DecidableEq β] {s : finset α} {f : α → β} : (finset.bUnion s fun (a : α) => singleton (f a)) = image f s := sorry
@[simp] theorem bUnion_singleton_eq_self {α : Type u_1} {s : finset α} [DecidableEq α] : finset.bUnion s singleton = s :=
eq.mpr (id (Eq._oldrec (Eq.refl (finset.bUnion s singleton = s)) bUnion_singleton)) image_id
theorem bUnion_filter_eq_of_maps_to {α : Type u_1} {β : Type u_2} [DecidableEq β] [DecidableEq α] {s : finset α} {t : finset β} {f : α → β} (h : ∀ (x : α), x ∈ s → f x ∈ t) : (finset.bUnion t fun (a : β) => filter (fun (c : α) => f c = a) s) = s := sorry
theorem image_bUnion_filter_eq {α : Type u_1} {β : Type u_2} [DecidableEq β] [DecidableEq α] (s : finset β) (g : β → α) : (finset.bUnion (image g s) fun (a : α) => filter (fun (c : β) => g c = a) s) = s :=
bUnion_filter_eq_of_maps_to fun (x : β) => mem_image_of_mem g
/-! ### prod -/
/-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/
protected def product {α : Type u_1} {β : Type u_2} (s : finset α) (t : finset β) : finset (α × β) :=
mk (multiset.product (val s) (val t)) sorry
@[simp] theorem product_val {α : Type u_1} {β : Type u_2} {s : finset α} {t : finset β} : val (finset.product s t) = multiset.product (val s) (val t) :=
rfl
@[simp] theorem mem_product {α : Type u_1} {β : Type u_2} {s : finset α} {t : finset β} {p : α × β} : p ∈ finset.product s t ↔ prod.fst p ∈ s ∧ prod.snd p ∈ t :=
multiset.mem_product
theorem subset_product {α : Type u_1} {β : Type u_2} [DecidableEq α] [DecidableEq β] {s : finset (α × β)} : s ⊆ finset.product (image prod.fst s) (image prod.snd s) :=
fun (p : α × β) (hp : p ∈ s) =>
iff.mpr mem_product { left := mem_image_of_mem prod.fst hp, right := mem_image_of_mem prod.snd hp }
theorem product_eq_bUnion {α : Type u_1} {β : Type u_2} [DecidableEq α] [DecidableEq β] (s : finset α) (t : finset β) : finset.product s t = finset.bUnion s fun (a : α) => image (fun (b : β) => (a, b)) t := sorry
@[simp] theorem card_product {α : Type u_1} {β : Type u_2} (s : finset α) (t : finset β) : card (finset.product s t) = card s * card t :=
multiset.card_product (val s) (val t)
theorem filter_product {α : Type u_1} {β : Type u_2} {s : finset α} {t : finset β} (p : α → Prop) (q : β → Prop) [decidable_pred p] [decidable_pred q] : filter (fun (x : α × β) => p (prod.fst x) ∧ q (prod.snd x)) (finset.product s t) =
finset.product (filter p s) (filter q t) := sorry
theorem filter_product_card {α : Type u_1} {β : Type u_2} (s : finset α) (t : finset β) (p : α → Prop) (q : β → Prop) [decidable_pred p] [decidable_pred q] : card (filter (fun (x : α × β) => p (prod.fst x) ↔ q (prod.snd x)) (finset.product s t)) =
card (filter p s) * card (filter q t) + card (filter (Not ∘ p) s) * card (filter (Not ∘ q) t) := sorry
/-! ### sigma -/
/-- `sigma s t` is the set of dependent pairs `⟨a, b⟩` such that `a ∈ s` and `b ∈ t a`. -/
protected def sigma {α : Type u_1} {σ : α → Type u_4} (s : finset α) (t : (a : α) → finset (σ a)) : finset (sigma fun (a : α) => σ a) :=
mk (multiset.sigma (val s) fun (a : α) => val (t a)) sorry
@[simp] theorem mem_sigma {α : Type u_1} {σ : α → Type u_4} {s : finset α} {t : (a : α) → finset (σ a)} {p : sigma σ} : p ∈ finset.sigma s t ↔ sigma.fst p ∈ s ∧ sigma.snd p ∈ t (sigma.fst p) :=
multiset.mem_sigma
theorem sigma_mono {α : Type u_1} {σ : α → Type u_4} {s₁ : finset α} {s₂ : finset α} {t₁ : (a : α) → finset (σ a)} {t₂ : (a : α) → finset (σ a)} (H1 : s₁ ⊆ s₂) (H2 : ∀ (a : α), t₁ a ⊆ t₂ a) : finset.sigma s₁ t₁ ⊆ finset.sigma s₂ t₂ := sorry
theorem sigma_eq_bUnion {α : Type u_1} {σ : α → Type u_4} [DecidableEq (sigma fun (a : α) => σ a)] (s : finset α) (t : (a : α) → finset (σ a)) : finset.sigma s t = finset.bUnion s fun (a : α) => map (function.embedding.sigma_mk a) (t a) := sorry
/-! ### disjoint -/
theorem disjoint_left {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} : disjoint s t ↔ ∀ {a : α}, a ∈ s → ¬a ∈ t := sorry
theorem disjoint_val {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} : disjoint s t ↔ multiset.disjoint (val s) (val t) :=
disjoint_left
theorem disjoint_iff_inter_eq_empty {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} : disjoint s t ↔ s ∩ t = ∅ :=
disjoint_iff
protected instance decidable_disjoint {α : Type u_1} [DecidableEq α] (U : finset α) (V : finset α) : Decidable (disjoint U V) :=
decidable_of_decidable_of_iff (finset.has_decidable_eq (U ⊓ V) ⊥) sorry
theorem disjoint_right {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} : disjoint s t ↔ ∀ {a : α}, a ∈ t → ¬a ∈ s :=
eq.mpr (id (Eq._oldrec (Eq.refl (disjoint s t ↔ ∀ {a : α}, a ∈ t → ¬a ∈ s)) (propext disjoint.comm)))
(eq.mpr (id (Eq._oldrec (Eq.refl (disjoint t s ↔ ∀ {a : α}, a ∈ t → ¬a ∈ s)) (propext disjoint_left)))
(iff.refl (∀ {a : α}, a ∈ t → ¬a ∈ s)))
theorem disjoint_iff_ne {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} : disjoint s t ↔ ∀ (a : α), a ∈ s → ∀ (b : α), b ∈ t → a ≠ b := sorry
theorem disjoint_of_subset_left {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} {u : finset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t :=
iff.mpr disjoint_left fun (x : α) (m₁ : x ∈ s) => iff.mp disjoint_left d x (h m₁)
theorem disjoint_of_subset_right {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} {u : finset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t :=
iff.mpr disjoint_right fun (x : α) (m₁ : x ∈ t) => iff.mp disjoint_right d x (h m₁)
@[simp] theorem disjoint_empty_left {α : Type u_1} [DecidableEq α] (s : finset α) : disjoint ∅ s :=
disjoint_bot_left
@[simp] theorem disjoint_empty_right {α : Type u_1} [DecidableEq α] (s : finset α) : disjoint s ∅ :=
disjoint_bot_right
@[simp] theorem singleton_disjoint {α : Type u_1} [DecidableEq α] {s : finset α} {a : α} : disjoint (singleton a) s ↔ ¬a ∈ s := sorry
@[simp] theorem disjoint_singleton {α : Type u_1} [DecidableEq α] {s : finset α} {a : α} : disjoint s (singleton a) ↔ ¬a ∈ s :=
iff.trans disjoint.comm singleton_disjoint
@[simp] theorem disjoint_insert_left {α : Type u_1} [DecidableEq α] {a : α} {s : finset α} {t : finset α} : disjoint (insert a s) t ↔ ¬a ∈ t ∧ disjoint s t := sorry
@[simp] theorem disjoint_insert_right {α : Type u_1} [DecidableEq α] {a : α} {s : finset α} {t : finset α} : disjoint s (insert a t) ↔ ¬a ∈ s ∧ disjoint s t := sorry
@[simp] theorem disjoint_union_left {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} {u : finset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := sorry
@[simp] theorem disjoint_union_right {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} {u : finset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := sorry
theorem sdiff_disjoint {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} : disjoint (t \ s) s :=
iff.mpr disjoint_left fun (a : α) (ha : a ∈ t \ s) => and.right (iff.mp mem_sdiff ha)
theorem disjoint_sdiff {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} : disjoint s (t \ s) :=
disjoint.symm sdiff_disjoint
theorem disjoint_sdiff_inter {α : Type u_1} [DecidableEq α] (s : finset α) (t : finset α) : disjoint (s \ t) (s ∩ t) :=
disjoint_of_subset_right (inter_subset_right s t) sdiff_disjoint
theorem sdiff_eq_self_iff_disjoint {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} : s \ t = s ↔ disjoint s t := sorry
theorem sdiff_eq_self_of_disjoint {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} (h : disjoint s t) : s \ t = s :=
iff.mpr sdiff_eq_self_iff_disjoint h
theorem disjoint_self_iff_empty {α : Type u_1} [DecidableEq α] (s : finset α) : disjoint s s ↔ s = ∅ :=
disjoint_self
theorem disjoint_bUnion_left {α : Type u_1} [DecidableEq α] {ι : Type u_2} (s : finset ι) (f : ι → finset α) (t : finset α) : disjoint (finset.bUnion s f) t ↔ ∀ (i : ι), i ∈ s → disjoint (f i) t := sorry
theorem disjoint_bUnion_right {α : Type u_1} [DecidableEq α] {ι : Type u_2} (s : finset α) (t : finset ι) (f : ι → finset α) : disjoint s (finset.bUnion t f) ↔ ∀ (i : ι), i ∈ t → disjoint s (f i) := sorry
@[simp] theorem card_disjoint_union {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} (h : disjoint s t) : card (s ∪ t) = card s + card t := sorry
theorem card_sdiff {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} (h : s ⊆ t) : card (t \ s) = card t - card s := sorry
theorem disjoint_filter {α : Type u_1} [DecidableEq α] {s : finset α} {p : α → Prop} {q : α → Prop} [decidable_pred p] [decidable_pred q] : disjoint (filter p s) (filter q s) ↔ ∀ (x : α), x ∈ s → p x → ¬q x := sorry
theorem disjoint_filter_filter {α : Type u_1} [DecidableEq α] {s : finset α} {t : finset α} {p : α → Prop} {q : α → Prop} [decidable_pred p] [decidable_pred q] : disjoint s t → disjoint (filter p s) (filter q t) :=
disjoint.mono (filter_subset p s) (filter_subset q t)
theorem disjoint_iff_disjoint_coe {α : Type u_1} {a : finset α} {b : finset α} [DecidableEq α] : disjoint a b ↔ disjoint ↑a ↑b :=
eq.mpr (id (Eq._oldrec (Eq.refl (disjoint a b ↔ disjoint ↑a ↑b)) (propext disjoint_left)))
(eq.mpr (id (Eq._oldrec (Eq.refl ((∀ {a_1 : α}, a_1 ∈ a → ¬a_1 ∈ b) ↔ disjoint ↑a ↑b)) (propext set.disjoint_left)))
(iff.refl (∀ {a_1 : α}, a_1 ∈ a → ¬a_1 ∈ b)))
theorem filter_card_add_filter_neg_card_eq_card {α : Type u_1} {s : finset α} (p : α → Prop) [decidable_pred p] : card (filter p s) + card (filter (Not ∘ p) s) = card s := sorry
/-- Given a finite set `s`, the diagonal, `s.diag` is the set of pairs of the form `(a, a)` for
`a ∈ s`. -/
def diag {α : Type u_1} (s : finset α) [DecidableEq α] : finset (α × α) :=
filter (fun (a : α × α) => prod.fst a = prod.snd a) (finset.product s s)
/-- Given a finite set `s`, the off-diagonal, `s.off_diag` is the set of pairs `(a, b)` with `a ≠ b`
for `a, b ∈ s`. -/
def off_diag {α : Type u_1} (s : finset α) [DecidableEq α] : finset (α × α) :=
filter (fun (a : α × α) => prod.fst a ≠ prod.snd a) (finset.product s s)
@[simp] theorem mem_diag {α : Type u_1} (s : finset α) [DecidableEq α] (x : α × α) : x ∈ diag s ↔ prod.fst x ∈ s ∧ prod.fst x = prod.snd x := sorry
@[simp] theorem mem_off_diag {α : Type u_1} (s : finset α) [DecidableEq α] (x : α × α) : x ∈ off_diag s ↔ prod.fst x ∈ s ∧ prod.snd x ∈ s ∧ prod.fst x ≠ prod.snd x := sorry
@[simp] theorem diag_card {α : Type u_1} (s : finset α) [DecidableEq α] : card (diag s) = card s := sorry
@[simp] theorem off_diag_card {α : Type u_1} (s : finset α) [DecidableEq α] : card (off_diag s) = card s * card s - card s := sorry
/--
Given a set A and a set B inside it, we can shrink A to any appropriate size, and keep B
inside it.
-/
theorem exists_intermediate_set {α : Type u_1} {A : finset α} {B : finset α} (i : ℕ) (h₁ : i + card B ≤ card A) (h₂ : B ⊆ A) : ∃ (C : finset α), B ⊆ C ∧ C ⊆ A ∧ card C = i + card B := sorry
/-- We can shrink A to any smaller size. -/
theorem exists_smaller_set {α : Type u_1} (A : finset α) (i : ℕ) (h₁ : i ≤ card A) : ∃ (B : finset α), B ⊆ A ∧ card B = i := sorry
/-- `finset.fin_range k` is the finset `{0, 1, ..., k-1}`, as a `finset (fin k)`. -/
def fin_range (k : ℕ) : finset (fin k) :=
mk (↑(list.fin_range k)) (list.nodup_fin_range k)
@[simp] theorem fin_range_card {k : ℕ} : card (fin_range k) = k := sorry
@[simp] theorem mem_fin_range {k : ℕ} (m : fin k) : m ∈ fin_range k :=
list.mem_fin_range m
@[simp] theorem coe_fin_range (k : ℕ) : ↑(fin_range k) = set.univ :=
set.eq_univ_of_forall mem_fin_range
/-- Given a finset `s` of `ℕ` contained in `{0,..., n-1}`, the corresponding finset in `fin n`
is `s.attach_fin h` where `h` is a proof that all elements of `s` are less than `n`. -/
def attach_fin (s : finset ℕ) {n : ℕ} (h : ∀ (m : ℕ), m ∈ s → m < n) : finset (fin n) :=
mk (multiset.pmap (fun (a : ℕ) (ha : a < n) => { val := a, property := ha }) (val s) h) sorry
@[simp] theorem mem_attach_fin {n : ℕ} {s : finset ℕ} (h : ∀ (m : ℕ), m ∈ s → m < n) {a : fin n} : a ∈ attach_fin s h ↔ ↑a ∈ s := sorry
@[simp] theorem card_attach_fin {n : ℕ} (s : finset ℕ) (h : ∀ (m : ℕ), m ∈ s → m < n) : card (attach_fin s h) = card s :=
multiset.card_pmap (fun (a : ℕ) (ha : a < n) => { val := a, property := ha }) (val s) h
/-! ### choose -/
/-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of
`l` satisfying `p` this unique element, as an element of the corresponding subtype. -/
def choose_x {α : Type u_1} (p : α → Prop) [decidable_pred p] (l : finset α) (hp : exists_unique fun (a : α) => a ∈ l ∧ p a) : Subtype fun (a : α) => a ∈ l ∧ p a :=
multiset.choose_x p (val l) hp
/-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of
`l` satisfying `p` this unique element, as an element of the ambient type. -/
def choose {α : Type u_1} (p : α → Prop) [decidable_pred p] (l : finset α) (hp : exists_unique fun (a : α) => a ∈ l ∧ p a) : α :=
↑(choose_x p l hp)
theorem choose_spec {α : Type u_1} (p : α → Prop) [decidable_pred p] (l : finset α) (hp : exists_unique fun (a : α) => a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) :=
subtype.property (choose_x p l hp)
theorem choose_mem {α : Type u_1} (p : α → Prop) [decidable_pred p] (l : finset α) (hp : exists_unique fun (a : α) => a ∈ l ∧ p a) : choose p l hp ∈ l :=
and.left (choose_spec p l hp)
theorem choose_property {α : Type u_1} (p : α → Prop) [decidable_pred p] (l : finset α) (hp : exists_unique fun (a : α) => a ∈ l ∧ p a) : p (choose p l hp) :=
and.right (choose_spec p l hp)
theorem lt_wf {α : Type u_1} : well_founded Less :=
(fun (H : subrelation Less (inv_image Less card)) => subrelation.wf H (inv_image.wf card nat.lt_wf))
fun (x y : finset α) (hxy : x < y) => card_lt_card hxy
end finset
namespace equiv
/-- Given an equivalence `α` to `β`, produce an equivalence between `finset α` and `finset β`. -/
protected def finset_congr {α : Type u_1} {β : Type u_2} (e : α ≃ β) : finset α ≃ finset β :=
mk (fun (s : finset α) => finset.map (equiv.to_embedding e) s)
(fun (s : finset β) => finset.map (equiv.to_embedding (equiv.symm e)) s) sorry sorry
@[simp] theorem finset_congr_apply {α : Type u_1} {β : Type u_2} (e : α ≃ β) (s : finset α) : coe_fn (equiv.finset_congr e) s = finset.map (equiv.to_embedding e) s :=
rfl
@[simp] theorem finset_congr_symm_apply {α : Type u_1} {β : Type u_2} (e : α ≃ β) (s : finset β) : coe_fn (equiv.symm (equiv.finset_congr e)) s = finset.map (equiv.to_embedding (equiv.symm e)) s :=
rfl
end equiv
namespace list
theorem to_finset_card_of_nodup {α : Type u_1} [DecidableEq α] {l : List α} (h : nodup l) : finset.card (to_finset l) = length l :=
congr_arg (⇑multiset.card) (iff.mpr multiset.erase_dup_eq_self h)
end list
namespace multiset
theorem to_finset_card_of_nodup {α : Type u_1} [DecidableEq α] {l : multiset α} (h : nodup l) : finset.card (to_finset l) = coe_fn card l :=
congr_arg (⇑card) (iff.mpr erase_dup_eq_self h)
theorem disjoint_to_finset {α : Type u_1} [DecidableEq α] (m1 : multiset α) (m2 : multiset α) : disjoint (to_finset m1) (to_finset m2) ↔ disjoint m1 m2 := sorry
|
4410efb7841aa9360783a753fa3a862e872a9925 | 77c5b91fae1b966ddd1db969ba37b6f0e4901e88 | /src/data/equiv/fin.lean | 989c861556f852697dac2ba2304db0191d2ac73c | [
"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 | 13,799 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import data.fin
import data.equiv.basic
import tactic.norm_num
/-!
# Equivalences for `fin n`
-/
universe variables u
variables {m n : ℕ}
/-- Equivalence between `fin 0` and `empty`. -/
def fin_zero_equiv : fin 0 ≃ empty :=
equiv.equiv_empty _
/-- Equivalence between `fin 0` and `pempty`. -/
def fin_zero_equiv' : fin 0 ≃ pempty.{u} :=
equiv.equiv_pempty _
/-- Equivalence between `fin 1` and `unit`. -/
def fin_one_equiv : fin 1 ≃ unit :=
equiv_punit_of_unique
/-- Equivalence between `fin 2` and `bool`. -/
def fin_two_equiv : fin 2 ≃ bool :=
⟨@fin.cases 1 (λ_, bool) ff (λ_, tt),
λb, cond b 1 0,
begin
refine fin.cases _ _, by norm_num,
refine fin.cases _ _, by norm_num,
exact λi, fin_zero_elim i
end,
begin
rintro ⟨_|_⟩,
{ refl },
{ rw ← fin.succ_zero_eq_one, refl }
end⟩
/-- `Π i : fin 2, α i` is equivalent to `α 0 × α 1`. See also `fin_two_arrow_equiv` for a
non-dependent version and `prod_equiv_pi_fin_two` for a version with inputs `α β : Type u`. -/
@[simps {fully_applied := ff}] def pi_fin_two_equiv (α : fin 2 → Type u) : (Π i, α i) ≃ α 0 × α 1 :=
{ to_fun := λ f, (f 0, f 1),
inv_fun := λ p, fin.cons p.1 $ fin.cons p.2 fin_zero_elim,
left_inv := λ f, funext $ fin.forall_fin_two.2 ⟨rfl, rfl⟩,
right_inv := λ ⟨x, y⟩, rfl }
/-- A product space `α × β` is equivalent to the space `Π i : fin 2, γ i`, where
`γ = fin.cons α (fin.cons β fin_zero_elim)`. See also `pi_fin_two_equiv` and
`fin_two_arrow_equiv`. -/
@[simps {fully_applied := ff }] def prod_equiv_pi_fin_two (α β : Type u) :
α × β ≃ Π i : fin 2, @fin.cons _ (λ _, Type u) α (fin.cons β fin_zero_elim) i :=
(pi_fin_two_equiv (fin.cons α (fin.cons β fin_zero_elim))).symm
/-- The space of functions `fin 2 → α` is equivalent to `α × α`. See also `pi_fin_two_equiv` and
`prod_equiv_pi_fin_two`. -/
@[simps {fully_applied := ff}] def fin_two_arrow_equiv (α : Type*) : (fin 2 → α) ≃ α × α :=
pi_fin_two_equiv (λ _, α)
/-- `Π i : fin 2, α i` is order equivalent to `α 0 × α 1`. See also `order_iso.fin_two_arrow_equiv`
for a non-dependent version. -/
def order_iso.pi_fin_two_iso (α : fin 2 → Type u) [Π i, preorder (α i)] :
(Π i, α i) ≃o α 0 × α 1 :=
{ to_equiv := pi_fin_two_equiv α,
map_rel_iff' := λ f g, iff.symm fin.forall_fin_two }
/-- The space of functions `fin 2 → α` is order equivalent to `α × α`. See also
`order_iso.pi_fin_two_iso`. -/
def order_iso.fin_two_arrow_iso (α : Type*) [preorder α] : (fin 2 → α) ≃o α × α :=
order_iso.pi_fin_two_iso (λ _, α)
/-- The 'identity' equivalence between `fin n` and `fin m` when `n = m`. -/
def fin_congr {n m : ℕ} (h : n = m) : fin n ≃ fin m :=
(fin.cast h).to_equiv
@[simp] lemma fin_congr_apply_mk {n m : ℕ} (h : n = m) (k : ℕ) (w : k < n) :
fin_congr h ⟨k, w⟩ = ⟨k, by { subst h, exact w }⟩ :=
rfl
@[simp] lemma fin_congr_symm {n m : ℕ} (h : n = m) :
(fin_congr h).symm = fin_congr h.symm := rfl
@[simp] lemma fin_congr_apply_coe {n m : ℕ} (h : n = m) (k : fin n) :
(fin_congr h k : ℕ) = k :=
by { cases k, refl, }
lemma fin_congr_symm_apply_coe {n m : ℕ} (h : n = m) (k : fin m) :
((fin_congr h).symm k : ℕ) = k :=
by { cases k, refl, }
/-- An equivalence that removes `i` and maps it to `none`.
This is a version of `fin.pred_above` that produces `option (fin n)` instead of
mapping both `i.cast_succ` and `i.succ` to `i`. -/
def fin_succ_equiv' {n : ℕ} (i : fin (n + 1)) :
fin (n + 1) ≃ option (fin n) :=
{ to_fun := i.insert_nth none some,
inv_fun := λ x, x.cases_on' i (fin.succ_above i),
left_inv := λ x, fin.succ_above_cases i (by simp) (λ j, by simp) x,
right_inv := λ x, by cases x; dsimp; simp }
@[simp] lemma fin_succ_equiv'_at {n : ℕ} (i : fin (n + 1)) :
(fin_succ_equiv' i) i = none := by simp [fin_succ_equiv']
@[simp] lemma fin_succ_equiv'_succ_above {n : ℕ} (i : fin (n + 1)) (j : fin n) :
fin_succ_equiv' i (i.succ_above j) = some j :=
@fin.insert_nth_apply_succ_above n (λ _, option (fin n)) i _ _ _
lemma fin_succ_equiv'_below {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : m.cast_succ < i) :
(fin_succ_equiv' i) m.cast_succ = some m :=
by rw [← fin.succ_above_below _ _ h, fin_succ_equiv'_succ_above]
lemma fin_succ_equiv'_above {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : i ≤ m.cast_succ) :
(fin_succ_equiv' i) m.succ = some m :=
by rw [← fin.succ_above_above _ _ h, fin_succ_equiv'_succ_above]
@[simp] lemma fin_succ_equiv'_symm_none {n : ℕ} (i : fin (n + 1)) :
(fin_succ_equiv' i).symm none = i := rfl
@[simp] lemma fin_succ_equiv'_symm_some {n : ℕ} (i : fin (n + 1)) (j : fin n) :
(fin_succ_equiv' i).symm (some j) = i.succ_above j :=
rfl
lemma fin_succ_equiv'_symm_some_below {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : m.cast_succ < i) :
(fin_succ_equiv' i).symm (some m) = m.cast_succ :=
fin.succ_above_below i m h
lemma fin_succ_equiv'_symm_some_above {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : i ≤ m.cast_succ) :
(fin_succ_equiv' i).symm (some m) = m.succ :=
fin.succ_above_above i m h
lemma fin_succ_equiv'_symm_coe_below {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : m.cast_succ < i) :
(fin_succ_equiv' i).symm m = m.cast_succ :=
fin_succ_equiv'_symm_some_below h
lemma fin_succ_equiv'_symm_coe_above {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : i ≤ m.cast_succ) :
(fin_succ_equiv' i).symm m = m.succ :=
fin_succ_equiv'_symm_some_above h
/-- Equivalence between `fin (n + 1)` and `option (fin n)`.
This is a version of `fin.pred` that produces `option (fin n)` instead of
requiring a proof that the input is not `0`. -/
def fin_succ_equiv (n : ℕ) : fin (n + 1) ≃ option (fin n) :=
fin_succ_equiv' 0
@[simp] lemma fin_succ_equiv_zero {n : ℕ} :
(fin_succ_equiv n) 0 = none :=
by cases n; refl
@[simp] lemma fin_succ_equiv_succ {n : ℕ} (m : fin n):
(fin_succ_equiv n) m.succ = some m :=
fin_succ_equiv'_above (fin.zero_le _)
@[simp] lemma fin_succ_equiv_symm_none {n : ℕ} :
(fin_succ_equiv n).symm none = 0 :=
fin_succ_equiv'_symm_none _
@[simp] lemma fin_succ_equiv_symm_some {n : ℕ} (m : fin n) :
(fin_succ_equiv n).symm (some m) = m.succ :=
congr_fun fin.succ_above_zero m
@[simp] lemma fin_succ_equiv_symm_coe {n : ℕ} (m : fin n) :
(fin_succ_equiv n).symm m = m.succ :=
fin_succ_equiv_symm_some m
/-- The equiv version of `fin.pred_above_zero`. -/
lemma fin_succ_equiv'_zero {n : ℕ} :
fin_succ_equiv' (0 : fin (n + 1)) = fin_succ_equiv n := rfl
/-- `equiv` between `fin (n + 1)` and `option (fin n)` sending `fin.last n` to `none` -/
def fin_succ_equiv_last {n : ℕ} : fin (n + 1) ≃ option (fin n) :=
fin_succ_equiv' (fin.last n)
@[simp] lemma fin_succ_equiv_last_cast_succ {n : ℕ} (i : fin n) :
fin_succ_equiv_last i.cast_succ = some i :=
fin_succ_equiv'_below i.2
@[simp] lemma fin_succ_equiv_last_last {n : ℕ} :
fin_succ_equiv_last (fin.last n) = none :=
by simp [fin_succ_equiv_last]
@[simp] lemma fin_succ_equiv_last_symm_some {n : ℕ} (i : fin n) :
fin_succ_equiv_last.symm (some i) = i.cast_succ :=
fin_succ_equiv'_symm_some_below i.2
@[simp] lemma fin_succ_equiv_last_symm_coe {n : ℕ} (i : fin n) :
fin_succ_equiv_last.symm ↑i = i.cast_succ :=
fin_succ_equiv'_symm_some_below i.2
@[simp] lemma fin_succ_equiv_last_symm_none {n : ℕ} :
fin_succ_equiv_last.symm none = fin.last n :=
fin_succ_equiv'_symm_none _
/-- Equivalence between `fin m ⊕ fin n` and `fin (m + n)` -/
def fin_sum_fin_equiv : fin m ⊕ fin n ≃ fin (m + n) :=
{ to_fun := sum.elim (fin.cast_add n) (fin.nat_add m),
inv_fun := λ i, @fin.add_cases m n (λ _, fin m ⊕ fin n) sum.inl sum.inr i,
left_inv := λ x, by { cases x with y y; dsimp; simp },
right_inv := λ x, by refine fin.add_cases (λ i, _) (λ i, _) x; simp }
@[simp] lemma fin_sum_fin_equiv_apply_left (i : fin m) :
(fin_sum_fin_equiv (sum.inl i) : fin (m + n)) = fin.cast_add n i := rfl
@[simp] lemma fin_sum_fin_equiv_apply_right (i : fin n) :
(fin_sum_fin_equiv (sum.inr i) : fin (m + n)) = fin.nat_add m i := rfl
@[simp] lemma fin_sum_fin_equiv_symm_apply_cast_add (x : fin m) :
fin_sum_fin_equiv.symm (fin.cast_add n x) = sum.inl x :=
fin_sum_fin_equiv.symm_apply_apply (sum.inl x)
@[simp] lemma fin_sum_fin_equiv_symm_apply_nat_add (x : fin n) :
fin_sum_fin_equiv.symm (fin.nat_add m x) = sum.inr x :=
fin_sum_fin_equiv.symm_apply_apply (sum.inr x)
/-- The equivalence between `fin (m + n)` and `fin (n + m)` which rotates by `n`. -/
def fin_add_flip : fin (m + n) ≃ fin (n + m) :=
(fin_sum_fin_equiv.symm.trans (equiv.sum_comm _ _)).trans fin_sum_fin_equiv
@[simp] lemma fin_add_flip_apply_cast_add (k : fin m) (n : ℕ) :
fin_add_flip (fin.cast_add n k) = fin.nat_add n k :=
by simp [fin_add_flip]
@[simp] lemma fin_add_flip_apply_nat_add (k : fin n) (m : ℕ) :
fin_add_flip (fin.nat_add m k) = fin.cast_add m k :=
by simp [fin_add_flip]
@[simp] lemma fin_add_flip_apply_mk_left {k : ℕ} (h : k < m)
(hk : k < m + n := nat.lt_add_right k m n h)
(hnk : n + k < n + m := add_lt_add_left h n) :
fin_add_flip (⟨k, hk⟩ : fin (m + n)) = ⟨n + k, hnk⟩ :=
by convert fin_add_flip_apply_cast_add ⟨k, h⟩ n
@[simp] lemma fin_add_flip_apply_mk_right {k : ℕ} (h₁ : m ≤ k) (h₂ : k < m + n) :
fin_add_flip (⟨k, h₂⟩ : fin (m + n)) = ⟨k - m, sub_le_self'.trans_lt $ add_comm m n ▸ h₂⟩ :=
begin
convert fin_add_flip_apply_nat_add ⟨k - m, (sub_lt_iff_right h₁).2 _⟩ m,
{ simp [nat.add_sub_cancel' h₁] },
{ rwa add_comm }
end
/-- Rotate `fin n` one step to the right. -/
def fin_rotate : Π n, equiv.perm (fin n)
| 0 := equiv.refl _
| (n+1) := fin_add_flip.trans (fin_congr (add_comm _ _))
lemma fin_rotate_of_lt {k : ℕ} (h : k < n) :
fin_rotate (n+1) ⟨k, lt_of_lt_of_le h (nat.le_succ _)⟩ = ⟨k + 1, nat.succ_lt_succ h⟩ :=
begin
dsimp [fin_rotate],
simp [h, add_comm],
end
lemma fin_rotate_last' : fin_rotate (n+1) ⟨n, lt_add_one _⟩ = ⟨0, nat.zero_lt_succ _⟩ :=
begin
dsimp [fin_rotate],
rw fin_add_flip_apply_mk_right,
simp,
end
lemma fin_rotate_last : fin_rotate (n+1) (fin.last _) = 0 :=
fin_rotate_last'
lemma fin.snoc_eq_cons_rotate {α : Type*} (v : fin n → α) (a : α) :
@fin.snoc _ (λ _, α) v a = (λ i, @fin.cons _ (λ _, α) a v (fin_rotate _ i)) :=
begin
ext ⟨i, h⟩,
by_cases h' : i < n,
{ rw [fin_rotate_of_lt h', fin.snoc, fin.cons, dif_pos h'],
refl, },
{ have h'' : n = i,
{ simp only [not_lt] at h', exact (nat.eq_of_le_of_lt_succ h' h).symm, },
subst h'',
rw [fin_rotate_last', fin.snoc, fin.cons, dif_neg (lt_irrefl _)],
refl, }
end
@[simp] lemma fin_rotate_zero : fin_rotate 0 = equiv.refl _ := rfl
@[simp] lemma fin_rotate_one : fin_rotate 1 = equiv.refl _ :=
subsingleton.elim _ _
@[simp] lemma fin_rotate_succ_apply {n : ℕ} (i : fin n.succ) :
fin_rotate n.succ i = i + 1 :=
begin
cases n,
{ simp },
rcases i.le_last.eq_or_lt with rfl|h,
{ simp [fin_rotate_last] },
{ cases i,
simp only [fin.lt_iff_coe_lt_coe, fin.coe_last, fin.coe_mk] at h,
simp [fin_rotate_of_lt h, fin.eq_iff_veq, fin.add_def, nat.mod_eq_of_lt (nat.succ_lt_succ h)] },
end
@[simp] lemma fin_rotate_apply_zero {n : ℕ} : fin_rotate n.succ 0 = 1 :=
by rw [fin_rotate_succ_apply, zero_add]
lemma coe_fin_rotate_of_ne_last {n : ℕ} {i : fin n.succ} (h : i ≠ fin.last n) :
(fin_rotate n.succ i : ℕ) = i + 1 :=
begin
rw fin_rotate_succ_apply,
have : (i : ℕ) < n := lt_of_le_of_ne (nat.succ_le_succ_iff.mp i.2) (fin.coe_injective.ne h),
exact fin.coe_add_one_of_lt this
end
lemma coe_fin_rotate {n : ℕ} (i : fin n.succ) :
(fin_rotate n.succ i : ℕ) = if i = fin.last n then 0 else i + 1 :=
by rw [fin_rotate_succ_apply, fin.coe_add_one i]
/-- Equivalence between `fin m × fin n` and `fin (m * n)` -/
def fin_prod_fin_equiv : fin m × fin n ≃ fin (m * n) :=
{ to_fun := λ x, ⟨x.2.1 + n * x.1.1,
calc x.2.1 + n * x.1.1 + 1
= x.1.1 * n + x.2.1 + 1 : by ac_refl
... ≤ x.1.1 * n + n : nat.add_le_add_left x.2.2 _
... = (x.1.1 + 1) * n : eq.symm $ nat.succ_mul _ _
... ≤ m * n : nat.mul_le_mul_right _ x.1.2⟩,
inv_fun := λ x,
have H : 0 < n, from nat.pos_of_ne_zero $ λ H, nat.not_lt_zero x.1 $ by subst H; from x.2,
(⟨x.1 / n, (nat.div_lt_iff_lt_mul _ _ H).2 x.2⟩,
⟨x.1 % n, nat.mod_lt _ H⟩),
left_inv := λ ⟨x, y⟩,
have H : 0 < n, from nat.pos_of_ne_zero $ λ H, nat.not_lt_zero y.1 $ H ▸ y.2,
prod.ext
(fin.eq_of_veq $ calc
(y.1 + n * x.1) / n
= y.1 / n + x.1 : nat.add_mul_div_left _ _ H
... = 0 + x.1 : by rw nat.div_eq_of_lt y.2
... = x.1 : nat.zero_add x.1)
(fin.eq_of_veq $ calc
(y.1 + n * x.1) % n
= y.1 % n : nat.add_mul_mod_self_left _ _ _
... = y.1 : nat.mod_eq_of_lt y.2),
right_inv := λ x, fin.eq_of_veq $ nat.mod_add_div _ _ }
/-- Promote a `fin n` into a larger `fin m`, as a subtype where the underlying
values are retained. This is the `order_iso` version of `fin.cast_le`. -/
@[simps apply symm_apply]
def fin.cast_le_order_iso {n m : ℕ} (h : n ≤ m) : fin n ≃o {i : fin m // (i : ℕ) < n} :=
{ to_fun := λ i, ⟨fin.cast_le h i, by simpa using i.is_lt⟩,
inv_fun := λ i, ⟨i, i.prop⟩,
left_inv := λ _, by simp,
right_inv := λ _, by simp,
map_rel_iff' := λ _ _, by simp }
/-- `fin 0` is a subsingleton. -/
instance subsingleton_fin_zero : subsingleton (fin 0) :=
fin_zero_equiv.subsingleton
/-- `fin 1` is a subsingleton. -/
instance subsingleton_fin_one : subsingleton (fin 1) :=
fin_one_equiv.subsingleton
|
6715c8f8e215d967e02c44b306bfa8ffdde68e9a | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/hom/equiv/type_tags.lean | 9f40a2cd08224bcf185eea80cef01b4e94d2c1f7 | [
"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 | 3,235 | lean | /-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Callum Sutton, Yury Kudryashov
-/
import algebra.hom.equiv.basic
import algebra.group.type_tags
/-!
# Additive and multiplicative equivalences associated to `multiplicative` and `additive`.
-/
variables {G H : Type*}
/-- Reinterpret `G ≃+ H` as `multiplicative G ≃* multiplicative H`. -/
def add_equiv.to_multiplicative [add_zero_class G] [add_zero_class H] :
(G ≃+ H) ≃ (multiplicative G ≃* multiplicative H) :=
{ to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative,
f.symm.to_add_monoid_hom.to_multiplicative, f.3, f.4, f.5⟩,
inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩,
left_inv := λ x, by { ext, refl, },
right_inv := λ x, by { ext, refl, }, }
/-- Reinterpret `G ≃* H` as `additive G ≃+ additive H`. -/
def mul_equiv.to_additive [mul_one_class G] [mul_one_class H] :
(G ≃* H) ≃ (additive G ≃+ additive H) :=
{ to_fun := λ f, ⟨f.to_monoid_hom.to_additive, f.symm.to_monoid_hom.to_additive, f.3, f.4, f.5⟩,
inv_fun := λ f, ⟨f.to_add_monoid_hom, f.symm.to_add_monoid_hom, f.3, f.4, f.5⟩,
left_inv := λ x, by { ext, refl, },
right_inv := λ x, by { ext, refl, }, }
/-- Reinterpret `additive G ≃+ H` as `G ≃* multiplicative H`. -/
def add_equiv.to_multiplicative' [mul_one_class G] [add_zero_class H] :
(additive G ≃+ H) ≃ (G ≃* multiplicative H) :=
{ to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative',
f.symm.to_add_monoid_hom.to_multiplicative'', f.3, f.4, f.5⟩,
inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩,
left_inv := λ x, by { ext, refl, },
right_inv := λ x, by { ext, refl, }, }
/-- Reinterpret `G ≃* multiplicative H` as `additive G ≃+ H` as. -/
def mul_equiv.to_additive' [mul_one_class G] [add_zero_class H] :
(G ≃* multiplicative H) ≃ (additive G ≃+ H) :=
add_equiv.to_multiplicative'.symm
/-- Reinterpret `G ≃+ additive H` as `multiplicative G ≃* H`. -/
def add_equiv.to_multiplicative'' [add_zero_class G] [mul_one_class H] :
(G ≃+ additive H) ≃ (multiplicative G ≃* H) :=
{ to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative'',
f.symm.to_add_monoid_hom.to_multiplicative', f.3, f.4, f.5⟩,
inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩,
left_inv := λ x, by { ext, refl, },
right_inv := λ x, by { ext, refl, }, }
/-- Reinterpret `multiplicative G ≃* H` as `G ≃+ additive H` as. -/
def mul_equiv.to_additive'' [add_zero_class G] [mul_one_class H] :
(multiplicative G ≃* H) ≃ (G ≃+ additive H) :=
add_equiv.to_multiplicative''.symm
section
variables (G) (H)
/-- `additive (multiplicative G)` is just `G`. -/
def add_equiv.additive_multiplicative [add_zero_class G] : additive (multiplicative G) ≃+ G :=
mul_equiv.to_additive'' (mul_equiv.refl (multiplicative G))
/-- `multiplicative (additive H)` is just `H`. -/
def mul_equiv.multiplicative_additive [mul_one_class H] : multiplicative (additive H) ≃* H :=
add_equiv.to_multiplicative'' (add_equiv.refl (additive H))
end
|
557aa9aab4b1da37fe3bfd9cbe7e2f88617c9d94 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Elab/Deriving/SizeOf.lean | 0d904db525f4e312369c334c1a80f085564c7442 | [
"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 | 807 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.SizeOf
import Lean.Elab.Deriving.Basic
/-!
Remark: `SizeOf` instances are automatically generated. We add support for `deriving instance` for `SizeOf`
just to be able to use them to define instances for types defined at `Prelude.lean`
-/
namespace Lean.Elab.Deriving.SizeOf
open Command
def mkSizeOfHandler (declNames : Array Name) : CommandElabM Bool := do
if (← declNames.allM isInductive) && declNames.size > 0 then
liftTermElabM <| Meta.mkSizeOfInstances declNames[0]!
return true
else
return false
builtin_initialize
registerDerivingHandler `SizeOf mkSizeOfHandler
end Lean.Elab.Deriving.SizeOf
|
8d174e1f3883a28c62e8c9b8bedade0aa0a38cec | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/calculus/fderiv/basic.lean | ca62479ba25cc811a223a704973c0aed857040de | [
"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 | 47,357 | 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, Yury Kudryashov
-/
import analysis.asymptotics.asymptotic_equivalent
import analysis.calculus.tangent_cone
import analysis.normed_space.bounded_linear_maps
/-!
# The Fréchet derivative
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Let `E` and `F` be normed spaces, `f : E → F`, and `f' : E →L[𝕜] F` a
continuous 𝕜-linear map, where `𝕜` is a non-discrete normed field. Then
`has_fderiv_within_at f f' s x`
says that `f` has derivative `f'` at `x`, where the domain of interest
is restricted to `s`. We also have
`has_fderiv_at f f' x := has_fderiv_within_at f f' x univ`
Finally,
`has_strict_fderiv_at f f' x`
means that `f : E → F` has derivative `f' : E →L[𝕜] F` in the sense of strict differentiability,
i.e., `f y - f z - f'(y - z) = o(y - z)` as `y, z → x`. This notion is used in the inverse
function theorem, and is defined here only to avoid proving theorems like
`is_bounded_bilinear_map.has_fderiv_at` twice: first for `has_fderiv_at`, then for
`has_strict_fderiv_at`.
## Main results
In addition to the definition and basic properties of the derivative,
the folder `analysis/calculus/fderiv/` contains the usual formulas
(and existence assertions) for the derivative of
* constants
* the identity
* bounded linear maps (`linear.lean`)
* bounded bilinear maps (`bilinear.lean`)
* sum of two functions (`add.lean`)
* sum of finitely many functions (`add.lean`)
* multiplication of a function by a scalar constant (`add.lean`)
* negative of a function (`add.lean`)
* subtraction of two functions (`add.lean`)
* multiplication of a function by a scalar function (`mul.lean`)
* multiplication of two scalar functions (`mul.lean`)
* composition of functions (the chain rule) (`comp.lean`)
* inverse function (`mul.lean`)
(assuming that it exists; the inverse function theorem is in `../inverse.lean`)
For most binary operations we also define `const_op` and `op_const` theorems for the cases when
the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier,
and they more frequently lead to the desired result.
One can also interpret the derivative of a function `f : 𝕜 → E` as an element of `E` (by identifying
a linear function from `𝕜` to `E` with its value at `1`). Results on the Fréchet derivative are
translated to this more elementary point of view on the derivative in the file `deriv.lean`. The
derivative of polynomials is handled there, as it is naturally one-dimensional.
The simplifier is set up to prove automatically that some functions are differentiable, or
differentiable at a point (but not differentiable on a set or within a set at a point, as checking
automatically that the good domains are mapped one to the other when using composition is not
something the simplifier can easily do). This means that one can write
`example (x : ℝ) : differentiable ℝ (λ x, sin (exp (3 + x^2)) - 5 * cos x) := by simp`.
If there are divisions, one needs to supply to the simplifier proofs that the denominators do
not vanish, as in
```lean
example (x : ℝ) (h : 1 + sin x ≠ 0) : differentiable_at ℝ (λ x, exp x / (1 + sin x)) x :=
by simp [h]
```
Of course, these examples only work once `exp`, `cos` and `sin` have been shown to be
differentiable, in `analysis.special_functions.trigonometric`.
The simplifier is not set up to compute the Fréchet derivative of maps (as these are in general
complicated multidimensional linear maps), but it will compute one-dimensional derivatives,
see `deriv.lean`.
## Implementation details
The derivative is defined in terms of the `is_o` relation, but also
characterized in terms of the `tendsto` relation.
We also introduce predicates `differentiable_within_at 𝕜 f s x` (where `𝕜` is the base field,
`f` the function to be differentiated, `x` the point at which the derivative is asserted to exist,
and `s` the set along which the derivative is defined), as well as `differentiable_at 𝕜 f x`,
`differentiable_on 𝕜 f s` and `differentiable 𝕜 f` to express the existence of a derivative.
To be able to compute with derivatives, we write `fderiv_within 𝕜 f s x` and `fderiv 𝕜 f x`
for some choice of a derivative if it exists, and the zero function otherwise. This choice only
behaves well along sets for which the derivative is unique, i.e., those for which the tangent
directions span a dense subset of the whole space. The predicates `unique_diff_within_at s x` and
`unique_diff_on s`, defined in `tangent_cone.lean` express this property. We prove that indeed
they imply the uniqueness of the derivative. This is satisfied for open subsets, and in particular
for `univ`. This uniqueness only holds when the field is non-discrete, which we request at the very
beginning: otherwise, a derivative can be defined, but it has no interesting properties whatsoever.
To make sure that the simplifier can prove automatically that functions are differentiable, we tag
many lemmas with the `simp` attribute, for instance those saying that the sum of differentiable
functions is differentiable, as well as their product, their cartesian product, and so on. A notable
exception is the chain rule: we do not mark as a simp lemma the fact that, if `f` and `g` are
differentiable, then their composition also is: `simp` would always be able to match this lemma,
by taking `f` or `g` to be the identity. Instead, for every reasonable function (say, `exp`),
we add a lemma that if `f` is differentiable then so is `(λ x, exp (f x))`. This means adding
some boilerplate lemmas, but these can also be useful in their own right.
Tests for this ability of the simplifier (with more examples) are provided in
`tests/differentiable.lean`.
## Tags
derivative, differentiable, Fréchet, calculus
-/
open filter asymptotics continuous_linear_map set metric
open_locale topology classical nnreal filter asymptotics ennreal
noncomputable theory
section
variables {𝕜 : Type*} [nontrivially_normed_field 𝕜]
variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E]
variables {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F]
variables {G : Type*} [normed_add_comm_group G] [normed_space 𝕜 G]
variables {G' : Type*} [normed_add_comm_group G'] [normed_space 𝕜 G']
/-- A function `f` has the continuous linear map `f'` as derivative along the filter `L` if
`f x' = f x + f' (x' - x) + o (x' - x)` when `x'` converges along the filter `L`. This definition
is designed to be specialized for `L = 𝓝 x` (in `has_fderiv_at`), giving rise to the usual notion
of Fréchet derivative, and for `L = 𝓝[s] x` (in `has_fderiv_within_at`), giving rise to
the notion of Fréchet derivative along the set `s`. -/
def has_fderiv_at_filter (f : E → F) (f' : E →L[𝕜] F) (x : E) (L : filter E) :=
(λ x', f x' - f x - f' (x' - x)) =o[L] (λ x', x' - x)
/-- A function `f` has the continuous linear map `f'` as derivative at `x` within a set `s` if
`f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x` inside `s`. -/
def has_fderiv_within_at (f : E → F) (f' : E →L[𝕜] F) (s : set E) (x : E) :=
has_fderiv_at_filter f f' x (𝓝[s] x)
/-- A function `f` has the continuous linear map `f'` as derivative at `x` if
`f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x`. -/
def has_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) :=
has_fderiv_at_filter f f' x (𝓝 x)
/-- A function `f` has derivative `f'` at `a` in the sense of *strict differentiability*
if `f x - f y - f' (x - y) = o(x - y)` as `x, y → a`. This form of differentiability is required,
e.g., by the inverse function theorem. Any `C^1` function on a vector space over `ℝ` is strictly
differentiable but this definition works, e.g., for vector spaces over `p`-adic numbers. -/
def has_strict_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) :=
(λ p : E × E, f p.1 - f p.2 - f' (p.1 - p.2)) =o[𝓝 (x, x)] (λ p : E × E, p.1 - p.2)
variables (𝕜)
/-- A function `f` is differentiable at a point `x` within a set `s` if it admits a derivative
there (possibly non-unique). -/
def differentiable_within_at (f : E → F) (s : set E) (x : E) :=
∃f' : E →L[𝕜] F, has_fderiv_within_at f f' s x
/-- A function `f` is differentiable at a point `x` if it admits a derivative there (possibly
non-unique). -/
def differentiable_at (f : E → F) (x : E) :=
∃f' : E →L[𝕜] F, has_fderiv_at f f' x
/-- If `f` has a derivative at `x` within `s`, then `fderiv_within 𝕜 f s x` is such a derivative.
Otherwise, it is set to `0`. -/
def fderiv_within (f : E → F) (s : set E) (x : E) : E →L[𝕜] F :=
if h : ∃f', has_fderiv_within_at f f' s x then classical.some h else 0
/-- If `f` has a derivative at `x`, then `fderiv 𝕜 f x` is such a derivative. Otherwise, it is
set to `0`. -/
def fderiv (f : E → F) (x : E) : E →L[𝕜] F :=
if h : ∃f', has_fderiv_at f f' x then classical.some h else 0
/-- `differentiable_on 𝕜 f s` means that `f` is differentiable within `s` at any point of `s`. -/
def differentiable_on (f : E → F) (s : set E) :=
∀x ∈ s, differentiable_within_at 𝕜 f s x
/-- `differentiable 𝕜 f` means that `f` is differentiable at any point. -/
def differentiable (f : E → F) :=
∀x, differentiable_at 𝕜 f x
variables {𝕜}
variables {f f₀ f₁ g : E → F}
variables {f' f₀' f₁' g' : E →L[𝕜] F}
variables (e : E →L[𝕜] F)
variables {x : E}
variables {s t : set E}
variables {L L₁ L₂ : filter E}
lemma fderiv_within_zero_of_not_differentiable_within_at
(h : ¬ differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 f s x = 0 :=
have ¬ ∃ f', has_fderiv_within_at f f' s x, from h,
by simp [fderiv_within, this]
lemma fderiv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : fderiv 𝕜 f x = 0 :=
have ¬ ∃ f', has_fderiv_at f f' x, from h,
by simp [fderiv, this]
section derivative_uniqueness
/- In this section, we discuss the uniqueness of the derivative.
We prove that the definitions `unique_diff_within_at` and `unique_diff_on` indeed imply the
uniqueness of the derivative. -/
/-- If a function f has a derivative f' at x, a rescaled version of f around x converges to f',
i.e., `n (f (x + (1/n) v) - f x)` converges to `f' v`. More generally, if `c n` tends to infinity
and `c n * d n` tends to `v`, then `c n * (f (x + d n) - f x)` tends to `f' v`. This lemma expresses
this fact, for functions having a derivative within a set. Its specific formulation is useful for
tangent cone related discussions. -/
theorem has_fderiv_within_at.lim (h : has_fderiv_within_at f f' s x) {α : Type*} (l : filter α)
{c : α → 𝕜} {d : α → E} {v : E} (dtop : ∀ᶠ n in l, x + d n ∈ s)
(clim : tendsto (λ n, ‖c n‖) l at_top)
(cdlim : tendsto (λ n, c n • d n) l (𝓝 v)) :
tendsto (λn, c n • (f (x + d n) - f x)) l (𝓝 (f' v)) :=
begin
have tendsto_arg : tendsto (λ n, x + d n) l (𝓝[s] x),
{ conv in (𝓝[s] x) { rw ← add_zero x },
rw [nhds_within, tendsto_inf],
split,
{ apply tendsto_const_nhds.add (tangent_cone_at.lim_zero l clim cdlim) },
{ rwa tendsto_principal } },
have : (λ y, f y - f x - f' (y - x)) =o[𝓝[s] x] (λ y, y - x) := h,
have : (λ n, f (x + d n) - f x - f' ((x + d n) - x)) =o[l] (λ n, (x + d n) - x) :=
this.comp_tendsto tendsto_arg,
have : (λ n, f (x + d n) - f x - f' (d n)) =o[l] d := by simpa only [add_sub_cancel'],
have : (λ n, c n • (f (x + d n) - f x - f' (d n))) =o[l] (λ n, c n • d n) :=
(is_O_refl c l).smul_is_o this,
have : (λ n, c n • (f (x + d n) - f x - f' (d n))) =o[l] (λ n, (1:ℝ)) :=
this.trans_is_O (cdlim.is_O_one ℝ),
have L1 : tendsto (λn, c n • (f (x + d n) - f x - f' (d n))) l (𝓝 0) :=
(is_o_one_iff ℝ).1 this,
have L2 : tendsto (λn, f' (c n • d n)) l (𝓝 (f' v)) :=
tendsto.comp f'.cont.continuous_at cdlim,
have L3 : tendsto (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n)))
l (𝓝 (0 + f' v)) :=
L1.add L2,
have : (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n)))
= (λn, c n • (f (x + d n) - f x)),
by { ext n, simp [smul_add, smul_sub] },
rwa [this, zero_add] at L3
end
/-- If `f'` and `f₁'` are two derivatives of `f` within `s` at `x`, then they are equal on the
tangent cone to `s` at `x` -/
theorem has_fderiv_within_at.unique_on (hf : has_fderiv_within_at f f' s x)
(hg : has_fderiv_within_at f f₁' s x) :
eq_on f' f₁' (tangent_cone_at 𝕜 s x) :=
λ y ⟨c, d, dtop, clim, cdlim⟩,
tendsto_nhds_unique (hf.lim at_top dtop clim cdlim) (hg.lim at_top dtop clim cdlim)
/-- `unique_diff_within_at` achieves its goal: it implies the uniqueness of the derivative. -/
theorem unique_diff_within_at.eq (H : unique_diff_within_at 𝕜 s x)
(hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at f f₁' s x) : f' = f₁' :=
continuous_linear_map.ext_on H.1 (hf.unique_on hg)
theorem unique_diff_on.eq (H : unique_diff_on 𝕜 s) (hx : x ∈ s)
(h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' :=
(H x hx).eq h h₁
end derivative_uniqueness
section fderiv_properties
/-! ### Basic properties of the derivative -/
theorem has_fderiv_at_filter_iff_tendsto :
has_fderiv_at_filter f f' x L ↔
tendsto (λ x', ‖x' - x‖⁻¹ * ‖f x' - f x - f' (x' - x)‖) L (𝓝 0) :=
have h : ∀ x', ‖x' - x‖ = 0 → ‖f x' - f x - f' (x' - x)‖ = 0, from λ x' hx',
by { rw [sub_eq_zero.1 (norm_eq_zero.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 (λ _, 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)‖) (𝓝[s] x) (𝓝 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_fderiv_at_iff_tendsto : has_fderiv_at f f' x ↔
tendsto (λ x', ‖x' - x‖⁻¹ * ‖f x' - f x - f' (x' - x)‖) (𝓝 x) (𝓝 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_fderiv_at_iff_is_o_nhds_zero : has_fderiv_at f f' x ↔
(λ h : E, f (x + h) - f x - f' h) =o[𝓝 0] (λh, h) :=
begin
rw [has_fderiv_at, has_fderiv_at_filter, ← map_add_left_nhds_zero x, is_o_map],
simp [(∘)]
end
/-- Converse to the mean value inequality: if `f` is differentiable at `x₀` and `C`-lipschitz
on a neighborhood of `x₀` then it its derivative at `x₀` has norm bounded by `C`. This version
only assumes that `‖f x - f x₀‖ ≤ C * ‖x - x₀‖` in a neighborhood of `x`. -/
lemma has_fderiv_at.le_of_lip' {f : E → F} {f' : E →L[𝕜] F} {x₀ : E} (hf : has_fderiv_at f f' x₀)
{C : ℝ} (hC₀ : 0 ≤ C) (hlip : ∀ᶠ x in 𝓝 x₀, ‖f x - f x₀‖ ≤ C * ‖x - x₀‖) : ‖f'‖ ≤ C :=
begin
refine le_of_forall_pos_le_add (λ ε ε0, op_norm_le_of_nhds_zero _ _),
exact add_nonneg hC₀ ε0.le,
rw [← map_add_left_nhds_zero x₀, eventually_map] at hlip,
filter_upwards [is_o_iff.1 (has_fderiv_at_iff_is_o_nhds_zero.1 hf) ε0, hlip] with y hy hyC,
rw add_sub_cancel' at hyC,
calc ‖f' y‖ ≤ ‖f (x₀ + y) - f x₀‖ + ‖f (x₀ + y) - f x₀ - f' y‖ : norm_le_insert _ _
... ≤ C * ‖y‖ + ε * ‖y‖ : add_le_add hyC hy
... = (C + ε) * ‖y‖ : (add_mul _ _ _).symm
end
/-- Converse to the mean value inequality: if `f` is differentiable at `x₀` and `C`-lipschitz
on a neighborhood of `x₀` then it its derivative at `x₀` has norm bounded by `C`. -/
lemma has_fderiv_at.le_of_lip {f : E → F} {f' : E →L[𝕜] F} {x₀ : E} (hf : has_fderiv_at f f' x₀)
{s : set E} (hs : s ∈ 𝓝 x₀) {C : ℝ≥0} (hlip : lipschitz_on_with C f s) : ‖f'‖ ≤ C :=
begin
refine hf.le_of_lip' C.coe_nonneg _,
filter_upwards [hs] with x hx using hlip.norm_sub_le hx (mem_of_mem_nhds hs),
end
theorem has_fderiv_at_filter.mono (h : has_fderiv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) :
has_fderiv_at_filter f f' x L₁ :=
h.mono hst
theorem has_fderiv_within_at.mono_of_mem (h : has_fderiv_within_at f f' t x) (hst : t ∈ 𝓝[s] x) :
has_fderiv_within_at f f' s x :=
h.mono $ nhds_within_le_iff.mpr hst
theorem has_fderiv_within_at.mono (h : has_fderiv_within_at f f' t x) (hst : s ⊆ t) :
has_fderiv_within_at f f' s x :=
h.mono $ nhds_within_mono _ hst
theorem has_fderiv_at.has_fderiv_at_filter (h : has_fderiv_at f f' x) (hL : L ≤ 𝓝 x) :
has_fderiv_at_filter f f' x L :=
h.mono hL
theorem has_fderiv_at.has_fderiv_within_at
(h : has_fderiv_at f f' x) : has_fderiv_within_at f f' s x :=
h.has_fderiv_at_filter inf_le_left
lemma has_fderiv_within_at.differentiable_within_at (h : has_fderiv_within_at f f' s x) :
differentiable_within_at 𝕜 f s x :=
⟨f', h⟩
lemma has_fderiv_at.differentiable_at (h : has_fderiv_at f f' x) : differentiable_at 𝕜 f x :=
⟨f', h⟩
@[simp] lemma has_fderiv_within_at_univ :
has_fderiv_within_at f f' univ x ↔ has_fderiv_at f f' x :=
by { simp only [has_fderiv_within_at, nhds_within_univ], refl }
alias has_fderiv_within_at_univ ↔ has_fderiv_within_at.has_fderiv_at_of_univ _
lemma has_fderiv_within_at_insert {y : E} :
has_fderiv_within_at f f' (insert y s) x ↔ has_fderiv_within_at f f' s x :=
begin
rcases eq_or_ne x y with rfl|h,
{ simp_rw [has_fderiv_within_at, has_fderiv_at_filter],
apply asymptotics.is_o_insert,
simp only [sub_self, map_zero] },
refine ⟨λ h, h.mono $ subset_insert y s, λ hf, hf.mono_of_mem _⟩,
simp_rw [nhds_within_insert_of_ne h, self_mem_nhds_within]
end
alias has_fderiv_within_at_insert ↔ has_fderiv_within_at.of_insert has_fderiv_within_at.insert'
lemma has_fderiv_within_at.insert (h : has_fderiv_within_at f f' s x) :
has_fderiv_within_at f f' (insert x s) x :=
h.insert'
lemma has_fderiv_within_at_diff_singleton (y : E) :
has_fderiv_within_at f f' (s \ {y}) x ↔ has_fderiv_within_at f f' s x :=
by rw [← has_fderiv_within_at_insert, insert_diff_singleton, has_fderiv_within_at_insert]
lemma has_strict_fderiv_at.is_O_sub (hf : has_strict_fderiv_at f f' x) :
(λ p : E × E, f p.1 - f p.2) =O[𝓝 (x, x)] (λ p : E × E, p.1 - p.2) :=
hf.is_O.congr_of_sub.2 (f'.is_O_comp _ _)
lemma has_fderiv_at_filter.is_O_sub (h : has_fderiv_at_filter f f' x L) :
(λ x', f x' - f x) =O[L] (λ x', x' - x) :=
h.is_O.congr_of_sub.2 (f'.is_O_sub _ _)
protected lemma has_strict_fderiv_at.has_fderiv_at (hf : has_strict_fderiv_at f f' x) :
has_fderiv_at f f' x :=
begin
rw [has_fderiv_at, has_fderiv_at_filter, is_o_iff],
exact (λ c hc, tendsto_id.prod_mk_nhds tendsto_const_nhds (is_o_iff.1 hf hc))
end
protected lemma has_strict_fderiv_at.differentiable_at (hf : has_strict_fderiv_at f f' x) :
differentiable_at 𝕜 f x :=
hf.has_fderiv_at.differentiable_at
/-- If `f` is strictly differentiable at `x` with derivative `f'` and `K > ‖f'‖₊`, then `f` is
`K`-Lipschitz in a neighborhood of `x`. -/
lemma has_strict_fderiv_at.exists_lipschitz_on_with_of_nnnorm_lt (hf : has_strict_fderiv_at f f' x)
(K : ℝ≥0) (hK : ‖f'‖₊ < K) : ∃ s ∈ 𝓝 x, lipschitz_on_with K f s :=
begin
have := hf.add_is_O_with (f'.is_O_with_comp _ _) hK,
simp only [sub_add_cancel, is_O_with] at this,
rcases exists_nhds_square this with ⟨U, Uo, xU, hU⟩,
exact ⟨U, Uo.mem_nhds xU, lipschitz_on_with_iff_norm_sub_le.2 $
λ x hx y hy, hU (mk_mem_prod hx hy)⟩
end
/-- If `f` is strictly differentiable at `x` with derivative `f'`, then `f` is Lipschitz in a
neighborhood of `x`. See also `has_strict_fderiv_at.exists_lipschitz_on_with_of_nnnorm_lt` for a
more precise statement. -/
lemma has_strict_fderiv_at.exists_lipschitz_on_with (hf : has_strict_fderiv_at f f' x) :
∃ K (s ∈ 𝓝 x), lipschitz_on_with K f s :=
(exists_gt _).imp hf.exists_lipschitz_on_with_of_nnnorm_lt
/-- Directional derivative agrees with `has_fderiv`. -/
lemma has_fderiv_at.lim (hf : has_fderiv_at f f' x) (v : E) {α : Type*} {c : α → 𝕜}
{l : filter α} (hc : tendsto (λ n, ‖c n‖) l at_top) :
tendsto (λ n, (c n) • (f (x + (c n)⁻¹ • v) - f x)) l (𝓝 (f' v)) :=
begin
refine (has_fderiv_within_at_univ.2 hf).lim _ univ_mem hc _,
assume U hU,
refine (eventually_ne_of_tendsto_norm_at_top hc (0:𝕜)).mono (λ y hy, _),
convert mem_of_mem_nhds hU,
dsimp only,
rw [← mul_smul, mul_inv_cancel hy, one_smul]
end
theorem has_fderiv_at.unique
(h₀ : has_fderiv_at f f₀' x) (h₁ : has_fderiv_at f f₁' x) : f₀' = f₁' :=
begin
rw ← has_fderiv_within_at_univ at h₀ h₁,
exact unique_diff_within_at_univ.eq h₀ h₁
end
lemma has_fderiv_within_at_inter' (h : t ∈ 𝓝[s] x) :
has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x :=
by simp [has_fderiv_within_at, nhds_within_restrict'' s h]
lemma has_fderiv_within_at_inter (h : t ∈ 𝓝 x) :
has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x :=
by simp [has_fderiv_within_at, nhds_within_restrict' s h]
lemma has_fderiv_within_at.union (hs : has_fderiv_within_at f f' s x)
(ht : has_fderiv_within_at f f' t x) :
has_fderiv_within_at f f' (s ∪ t) x :=
begin
simp only [has_fderiv_within_at, nhds_within_union],
exact hs.sup ht,
end
lemma has_fderiv_within_at.nhds_within (h : has_fderiv_within_at f f' s x)
(ht : s ∈ 𝓝[t] x) : has_fderiv_within_at f f' t x :=
(has_fderiv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _))
lemma has_fderiv_within_at.has_fderiv_at (h : has_fderiv_within_at f f' s x) (hs : s ∈ 𝓝 x) :
has_fderiv_at f f' x :=
by rwa [← univ_inter s, has_fderiv_within_at_inter hs, has_fderiv_within_at_univ] at h
lemma differentiable_within_at.differentiable_at
(h : differentiable_within_at 𝕜 f s x) (hs : s ∈ 𝓝 x) : differentiable_at 𝕜 f x :=
h.imp (λ f' hf', hf'.has_fderiv_at hs)
lemma differentiable_within_at.has_fderiv_within_at (h : differentiable_within_at 𝕜 f s x) :
has_fderiv_within_at f (fderiv_within 𝕜 f s x) s x :=
begin
dunfold fderiv_within,
dunfold differentiable_within_at at h,
rw dif_pos h,
exact classical.some_spec h
end
lemma differentiable_at.has_fderiv_at (h : differentiable_at 𝕜 f x) :
has_fderiv_at f (fderiv 𝕜 f x) x :=
begin
dunfold fderiv,
dunfold differentiable_at at h,
rw dif_pos h,
exact classical.some_spec h
end
lemma differentiable_on.has_fderiv_at (h : differentiable_on 𝕜 f s) (hs : s ∈ 𝓝 x) :
has_fderiv_at f (fderiv 𝕜 f x) x :=
((h x (mem_of_mem_nhds hs)).differentiable_at hs).has_fderiv_at
lemma differentiable_on.differentiable_at (h : differentiable_on 𝕜 f s) (hs : s ∈ 𝓝 x) :
differentiable_at 𝕜 f x :=
(h.has_fderiv_at hs).differentiable_at
lemma differentiable_on.eventually_differentiable_at (h : differentiable_on 𝕜 f s) (hs : s ∈ 𝓝 x) :
∀ᶠ y in 𝓝 x, differentiable_at 𝕜 f y :=
(eventually_eventually_nhds.2 hs).mono $ λ y, h.differentiable_at
lemma has_fderiv_at.fderiv (h : has_fderiv_at f f' x) : fderiv 𝕜 f x = f' :=
by { ext, rw h.unique h.differentiable_at.has_fderiv_at }
lemma fderiv_eq {f' : E → E →L[𝕜] F} (h : ∀ x, has_fderiv_at f (f' x) x) : fderiv 𝕜 f = f' :=
funext $ λ x, (h x).fderiv
/-- Converse to the mean value inequality: if `f` is differentiable at `x₀` and `C`-lipschitz
on a neighborhood of `x₀` then it its derivative at `x₀` has norm bounded by `C`.
Version using `fderiv`. -/
lemma fderiv_at.le_of_lip {f : E → F} {x₀ : E} (hf : differentiable_at 𝕜 f x₀)
{s : set E} (hs : s ∈ 𝓝 x₀) {C : ℝ≥0} (hlip : lipschitz_on_with C f s) : ‖fderiv 𝕜 f x₀‖ ≤ C :=
hf.has_fderiv_at.le_of_lip hs hlip
lemma has_fderiv_within_at.fderiv_within
(h : has_fderiv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 f s x = f' :=
(hxs.eq h h.differentiable_within_at.has_fderiv_within_at).symm
/-- If `x` is not in the closure of `s`, then `f` has any derivative at `x` within `s`,
as this statement is empty. -/
lemma has_fderiv_within_at_of_not_mem_closure (h : x ∉ closure s) :
has_fderiv_within_at f f' s x :=
begin
simp only [mem_closure_iff_nhds_within_ne_bot, ne_bot_iff, ne.def, not_not] at h,
simp [has_fderiv_within_at, has_fderiv_at_filter, h, is_o, is_O_with],
end
lemma differentiable_within_at.mono (h : differentiable_within_at 𝕜 f t x) (st : s ⊆ t) :
differentiable_within_at 𝕜 f s x :=
begin
rcases h with ⟨f', hf'⟩,
exact ⟨f', hf'.mono st⟩
end
lemma differentiable_within_at.mono_of_mem (h : differentiable_within_at 𝕜 f s x) {t : set E}
(hst : s ∈ 𝓝[t] x) :
differentiable_within_at 𝕜 f t x :=
(h.has_fderiv_within_at.mono_of_mem hst).differentiable_within_at
lemma differentiable_within_at_univ :
differentiable_within_at 𝕜 f univ x ↔ differentiable_at 𝕜 f x :=
by simp only [differentiable_within_at, has_fderiv_within_at_univ, differentiable_at]
lemma differentiable_within_at_inter (ht : t ∈ 𝓝 x) :
differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x :=
by simp only [differentiable_within_at, has_fderiv_within_at_inter ht]
lemma differentiable_within_at_inter' (ht : t ∈ 𝓝[s] x) :
differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x :=
by simp only [differentiable_within_at, has_fderiv_within_at_inter' ht]
lemma differentiable_at.differentiable_within_at
(h : differentiable_at 𝕜 f x) : differentiable_within_at 𝕜 f s x :=
(differentiable_within_at_univ.2 h).mono (subset_univ _)
lemma differentiable.differentiable_at (h : differentiable 𝕜 f) :
differentiable_at 𝕜 f x :=
h x
lemma differentiable_at.fderiv_within
(h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 f s x = fderiv 𝕜 f x :=
h.has_fderiv_at.has_fderiv_within_at.fderiv_within hxs
lemma differentiable_on.mono (h : differentiable_on 𝕜 f t) (st : s ⊆ t) :
differentiable_on 𝕜 f s :=
λ x hx, (h x (st hx)).mono st
lemma differentiable_on_univ :
differentiable_on 𝕜 f univ ↔ differentiable 𝕜 f :=
by simp only [differentiable_on, differentiable, differentiable_within_at_univ, mem_univ,
forall_true_left]
lemma differentiable.differentiable_on (h : differentiable 𝕜 f) : differentiable_on 𝕜 f s :=
(differentiable_on_univ.2 h).mono (subset_univ _)
lemma differentiable_on_of_locally_differentiable_on
(h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ differentiable_on 𝕜 f (s ∩ u)) : differentiable_on 𝕜 f s :=
begin
assume x xs,
rcases h x xs with ⟨t, t_open, xt, ht⟩,
exact (differentiable_within_at_inter (is_open.mem_nhds t_open xt)).1 (ht x ⟨xs, xt⟩)
end
lemma fderiv_within_of_mem (st : t ∈ 𝓝[s] x) (ht : unique_diff_within_at 𝕜 s x)
(h : differentiable_within_at 𝕜 f t x) :
fderiv_within 𝕜 f s x = fderiv_within 𝕜 f t x :=
((differentiable_within_at.has_fderiv_within_at h).mono_of_mem st).fderiv_within ht
lemma fderiv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x)
(h : differentiable_within_at 𝕜 f t x) :
fderiv_within 𝕜 f s x = fderiv_within 𝕜 f t x :=
fderiv_within_of_mem (nhds_within_mono _ st self_mem_nhds_within) ht h
lemma fderiv_within_inter (ht : t ∈ 𝓝 x) :
fderiv_within 𝕜 f (s ∩ t) x = fderiv_within 𝕜 f s x :=
by simp only [fderiv_within, has_fderiv_within_at_inter ht]
lemma fderiv_within_of_mem_nhds (h : s ∈ 𝓝 x) :
fderiv_within 𝕜 f s x = fderiv 𝕜 f x :=
by simp only [fderiv, fderiv_within, has_fderiv_at, has_fderiv_within_at, nhds_within_eq_nhds.2 h]
@[simp] lemma fderiv_within_univ : fderiv_within 𝕜 f univ = fderiv 𝕜 f :=
funext $ λ _, fderiv_within_of_mem_nhds univ_mem
lemma fderiv_within_of_open (hs : is_open s) (hx : x ∈ s) :
fderiv_within 𝕜 f s x = fderiv 𝕜 f x :=
fderiv_within_of_mem_nhds (hs.mem_nhds hx)
lemma fderiv_within_eq_fderiv (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_at 𝕜 f x) :
fderiv_within 𝕜 f s x = fderiv 𝕜 f x :=
begin
rw ← fderiv_within_univ,
exact fderiv_within_subset (subset_univ _) hs h.differentiable_within_at
end
lemma fderiv_mem_iff {f : E → F} {s : set (E →L[𝕜] F)} {x : E} :
fderiv 𝕜 f x ∈ s ↔ (differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ s) ∨
(¬differentiable_at 𝕜 f x ∧ (0 : E →L[𝕜] F) ∈ s) :=
by by_cases hx : differentiable_at 𝕜 f x; simp [fderiv_zero_of_not_differentiable_at, *]
lemma fderiv_within_mem_iff {f : E → F} {t : set E} {s : set (E →L[𝕜] F)} {x : E} :
fderiv_within 𝕜 f t x ∈ s ↔ (differentiable_within_at 𝕜 f t x ∧ fderiv_within 𝕜 f t x ∈ s) ∨
(¬differentiable_within_at 𝕜 f t x ∧ (0 : E →L[𝕜] F) ∈ s) :=
by by_cases hx : differentiable_within_at 𝕜 f t x;
simp [fderiv_within_zero_of_not_differentiable_within_at, *]
lemma asymptotics.is_O.has_fderiv_within_at {s : set E} {x₀ : E} {n : ℕ}
(h : f =O[𝓝[s] x₀] λ x, ‖x - x₀‖^n) (hx₀ : x₀ ∈ s) (hn : 1 < n) :
has_fderiv_within_at f (0 : E →L[𝕜] F) s x₀ :=
by simp_rw [has_fderiv_within_at, has_fderiv_at_filter,
h.eq_zero_of_norm_pow_within hx₀ $ zero_lt_one.trans hn, zero_apply, sub_zero,
h.trans_is_o ((is_o_pow_sub_sub x₀ hn).mono nhds_within_le_nhds)]
lemma asymptotics.is_O.has_fderiv_at {x₀ : E} {n : ℕ}
(h : f =O[𝓝 x₀] λ x, ‖x - x₀‖^n) (hn : 1 < n) :
has_fderiv_at f (0 : E →L[𝕜] F) x₀ :=
begin
rw [← nhds_within_univ] at h,
exact (h.has_fderiv_within_at (mem_univ _) hn).has_fderiv_at_of_univ
end
lemma has_fderiv_within_at.is_O {f : E → F} {s : set E} {x₀ : E} {f' : E →L[𝕜] F}
(h : has_fderiv_within_at f f' s x₀) :
(λ x, f x - f x₀) =O[𝓝[s] x₀] λ x, x - x₀ :=
by simpa only [sub_add_cancel] using h.is_O.add (is_O_sub f' (𝓝[s] x₀) x₀)
lemma has_fderiv_at.is_O {f : E → F} {x₀ : E} {f' : E →L[𝕜] F} (h : has_fderiv_at f f' x₀) :
(λ x, f x - f x₀) =O[𝓝 x₀] λ x, x - x₀ :=
by simpa only [sub_add_cancel] using h.is_O.add (is_O_sub f' (𝓝 x₀) x₀)
end fderiv_properties
section continuous
/-! ### Deducing continuity from differentiability -/
theorem has_fderiv_at_filter.tendsto_nhds
(hL : L ≤ 𝓝 x) (h : has_fderiv_at_filter f f' x L) :
tendsto f L (𝓝 (f x)) :=
begin
have : tendsto (λ x', f x' - f x) L (𝓝 0),
{ refine h.is_O_sub.trans_tendsto (tendsto.mono_left _ hL),
rw ← sub_self x, exact tendsto_id.sub tendsto_const_nhds },
have := tendsto.add this tendsto_const_nhds,
rw zero_add (f x) at this,
exact this.congr (by simp only [sub_add_cancel, eq_self_iff_true, forall_const])
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 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_rfl h
lemma differentiable_within_at.continuous_within_at (h : differentiable_within_at 𝕜 f s x) :
continuous_within_at f s x :=
let ⟨f', hf'⟩ := h in hf'.continuous_within_at
lemma differentiable_at.continuous_at (h : differentiable_at 𝕜 f x) : continuous_at f x :=
let ⟨f', hf'⟩ := h in hf'.continuous_at
lemma differentiable_on.continuous_on (h : differentiable_on 𝕜 f s) : continuous_on f s :=
λx hx, (h x hx).continuous_within_at
lemma differentiable.continuous (h : differentiable 𝕜 f) : continuous f :=
continuous_iff_continuous_at.2 $ λx, (h x).continuous_at
protected lemma has_strict_fderiv_at.continuous_at (hf : has_strict_fderiv_at f f' x) :
continuous_at f x :=
hf.has_fderiv_at.continuous_at
lemma has_strict_fderiv_at.is_O_sub_rev {f' : E ≃L[𝕜] F}
(hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) x) :
(λ p : E × E, p.1 - p.2) =O[𝓝 (x, x)](λ p : E × E, f p.1 - f p.2) :=
((f'.is_O_comp_rev _ _).trans (hf.trans_is_O (f'.is_O_comp_rev _ _)).right_is_O_add).congr
(λ _, rfl) (λ _, sub_add_cancel _ _)
lemma has_fderiv_at_filter.is_O_sub_rev (hf : has_fderiv_at_filter f f' x L) {C}
(hf' : antilipschitz_with C f') :
(λ x', x' - x) =O[L] (λ x', f x' - f x) :=
have (λ x', x' - x) =O[L] (λ x', f' (x' - x)),
from is_O_iff.2 ⟨C, eventually_of_forall $ λ x',
zero_hom_class.bound_of_antilipschitz f' hf' _⟩,
(this.trans (hf.trans_is_O this).right_is_O_add).congr (λ _, rfl) (λ _, sub_add_cancel _ _)
end continuous
section congr
/-! ### congr properties of the derivative -/
lemma has_fderiv_within_at_congr_set' (y : E) (h : s =ᶠ[𝓝[{y}ᶜ] x] t) :
has_fderiv_within_at f f' s x ↔ has_fderiv_within_at f f' t x :=
calc has_fderiv_within_at f f' s x ↔ has_fderiv_within_at f f' (s \ {y}) x :
(has_fderiv_within_at_diff_singleton _).symm
... ↔ has_fderiv_within_at f f' (t \ {y}) x :
suffices 𝓝[s \ {y}] x = 𝓝[t \ {y}] x, by simp only [has_fderiv_within_at, this],
by simpa only [set_eventually_eq_iff_inf_principal, ← nhds_within_inter', diff_eq, inter_comm]
using h
... ↔ has_fderiv_within_at f f' t x : has_fderiv_within_at_diff_singleton _
lemma has_fderiv_within_at_congr_set (h : s =ᶠ[𝓝 x] t) :
has_fderiv_within_at f f' s x ↔ has_fderiv_within_at f f' t x :=
has_fderiv_within_at_congr_set' x $ h.filter_mono inf_le_left
lemma differentiable_within_at_congr_set' (y : E) (h : s =ᶠ[𝓝[{y}ᶜ] x] t) :
differentiable_within_at 𝕜 f s x ↔ differentiable_within_at 𝕜 f t x :=
exists_congr $ λ _, has_fderiv_within_at_congr_set' _ h
lemma differentiable_within_at_congr_set (h : s =ᶠ[𝓝 x] t) :
differentiable_within_at 𝕜 f s x ↔ differentiable_within_at 𝕜 f t x :=
exists_congr $ λ _, has_fderiv_within_at_congr_set h
lemma fderiv_within_congr_set' (y : E) (h : s =ᶠ[𝓝[{y}ᶜ] x] t) :
fderiv_within 𝕜 f s x = fderiv_within 𝕜 f t x :=
by simp only [fderiv_within, has_fderiv_within_at_congr_set' y h]
lemma fderiv_within_congr_set (h : s =ᶠ[𝓝 x] t) :
fderiv_within 𝕜 f s x = fderiv_within 𝕜 f t x :=
fderiv_within_congr_set' x $ h.filter_mono inf_le_left
lemma fderiv_within_eventually_congr_set' (y : E) (h : s =ᶠ[𝓝[{y}ᶜ] x] t) :
fderiv_within 𝕜 f s =ᶠ[𝓝 x] fderiv_within 𝕜 f t :=
(eventually_nhds_nhds_within.2 h).mono $ λ _, fderiv_within_congr_set' y
lemma fderiv_within_eventually_congr_set (h : s =ᶠ[𝓝 x] t) :
fderiv_within 𝕜 f s =ᶠ[𝓝 x] fderiv_within 𝕜 f t :=
fderiv_within_eventually_congr_set' x $ h.filter_mono inf_le_left
theorem filter.eventually_eq.has_strict_fderiv_at_iff
(h : f₀ =ᶠ[𝓝 x] f₁) (h' : ∀ y, f₀' y = f₁' y) :
has_strict_fderiv_at f₀ f₀' x ↔ has_strict_fderiv_at f₁ f₁' x :=
begin
refine is_o_congr ((h.prod_mk_nhds h).mono _) (eventually_of_forall $ λ _, rfl),
rintros p ⟨hp₁, hp₂⟩,
simp only [*]
end
theorem has_strict_fderiv_at.congr_of_eventually_eq (h : has_strict_fderiv_at f f' x)
(h₁ : f =ᶠ[𝓝 x] f₁) : has_strict_fderiv_at f₁ f' x :=
(h₁.has_strict_fderiv_at_iff (λ _, rfl)).1 h
theorem filter.eventually_eq.has_fderiv_at_filter_iff
(h₀ : f₀ =ᶠ[L] f₁) (hx : 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 :=
is_o_congr (h₀.mono $ λ y hy, by simp only [hy, h₁, hx]) (eventually_of_forall $ λ _, rfl)
lemma has_fderiv_at_filter.congr_of_eventually_eq (h : has_fderiv_at_filter f f' x L)
(hL : f₁ =ᶠ[L] f) (hx : f₁ x = f x) : has_fderiv_at_filter f₁ f' x L :=
(hL.has_fderiv_at_filter_iff hx $ λ _, rfl).2 h
theorem filter.eventually_eq.has_fderiv_at_iff (h : f₀ =ᶠ[𝓝 x] f₁) :
has_fderiv_at f₀ f' x ↔ has_fderiv_at f₁ f' x :=
h.has_fderiv_at_filter_iff h.eq_of_nhds (λ _, rfl)
theorem filter.eventually_eq.differentiable_at_iff (h : f₀ =ᶠ[𝓝 x] f₁) :
differentiable_at 𝕜 f₀ x ↔ differentiable_at 𝕜 f₁ x :=
exists_congr $ λ f', h.has_fderiv_at_iff
theorem filter.eventually_eq.has_fderiv_within_at_iff (h : f₀ =ᶠ[𝓝[s] x] f₁) (hx : f₀ x = f₁ x) :
has_fderiv_within_at f₀ f' s x ↔ has_fderiv_within_at f₁ f' s x :=
h.has_fderiv_at_filter_iff hx (λ _, rfl)
theorem filter.eventually_eq.has_fderiv_within_at_iff_of_mem (h : f₀ =ᶠ[𝓝[s] x] f₁) (hx : x ∈ s) :
has_fderiv_within_at f₀ f' s x ↔ has_fderiv_within_at f₁ f' s x :=
h.has_fderiv_within_at_iff (h.eq_of_nhds_within hx)
theorem filter.eventually_eq.differentiable_within_at_iff (h : f₀ =ᶠ[𝓝[s] x] f₁)
(hx : f₀ x = f₁ x) :
differentiable_within_at 𝕜 f₀ s x ↔ differentiable_within_at 𝕜 f₁ s x :=
exists_congr $ λ f', h.has_fderiv_within_at_iff hx
theorem filter.eventually_eq.differentiable_within_at_iff_of_mem (h : f₀ =ᶠ[𝓝[s] x] f₁)
(hx : x ∈ s) :
differentiable_within_at 𝕜 f₀ s x ↔ differentiable_within_at 𝕜 f₁ s x :=
h.differentiable_within_at_iff (h.eq_of_nhds_within hx)
lemma has_fderiv_within_at.congr_mono (h : has_fderiv_within_at f f' s x) (ht : eq_on f₁ f t)
(hx : f₁ x = f x) (h₁ : t ⊆ s) : has_fderiv_within_at f₁ f' t x :=
has_fderiv_at_filter.congr_of_eventually_eq (h.mono h₁) (filter.mem_inf_of_right ht) hx
lemma has_fderiv_within_at.congr (h : has_fderiv_within_at f f' s x) (hs : eq_on f₁ f s)
(hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x :=
h.congr_mono hs hx (subset.refl _)
lemma has_fderiv_within_at.congr' (h : has_fderiv_within_at f f' s x) (hs : eq_on f₁ f s)
(hx : x ∈ s) : has_fderiv_within_at f₁ f' s x :=
h.congr hs (hs hx)
lemma has_fderiv_within_at.congr_of_eventually_eq (h : has_fderiv_within_at f f' s x)
(h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x :=
has_fderiv_at_filter.congr_of_eventually_eq h h₁ hx
lemma has_fderiv_at.congr_of_eventually_eq (h : has_fderiv_at f f' x)
(h₁ : f₁ =ᶠ[𝓝 x] f) : has_fderiv_at f₁ f' x :=
has_fderiv_at_filter.congr_of_eventually_eq h h₁ (mem_of_mem_nhds h₁ : _)
lemma differentiable_within_at.congr_mono (h : differentiable_within_at 𝕜 f s x)
(ht : eq_on f₁ f t) (hx : f₁ x = f x) (h₁ : t ⊆ s) : differentiable_within_at 𝕜 f₁ t x :=
(h.has_fderiv_within_at.congr_mono ht hx h₁).differentiable_within_at
lemma differentiable_within_at.congr (h : differentiable_within_at 𝕜 f s x)
(ht : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x :=
differentiable_within_at.congr_mono h ht hx (subset.refl _)
lemma differentiable_within_at.congr_of_eventually_eq
(h : differentiable_within_at 𝕜 f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f)
(hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x :=
(h.has_fderiv_within_at.congr_of_eventually_eq h₁ hx).differentiable_within_at
lemma differentiable_on.congr_mono (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ t, f₁ x = f x)
(h₁ : t ⊆ s) : differentiable_on 𝕜 f₁ t :=
λ x hx, (h x (h₁ hx)).congr_mono h' (h' x hx) h₁
lemma differentiable_on.congr (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ s, f₁ x = f x) :
differentiable_on 𝕜 f₁ s :=
λ x hx, (h x hx).congr h' (h' x hx)
lemma differentiable_on_congr (h' : ∀x ∈ s, f₁ x = f x) :
differentiable_on 𝕜 f₁ s ↔ differentiable_on 𝕜 f s :=
⟨λ h, differentiable_on.congr h (λy hy, (h' y hy).symm),
λ h, differentiable_on.congr h h'⟩
lemma differentiable_at.congr_of_eventually_eq (h : differentiable_at 𝕜 f x) (hL : f₁ =ᶠ[𝓝 x] f) :
differentiable_at 𝕜 f₁ x :=
hL.differentiable_at_iff.2 h
lemma differentiable_within_at.fderiv_within_congr_mono (h : differentiable_within_at 𝕜 f s x)
(hs : eq_on f₁ f t) (hx : f₁ x = f x) (hxt : unique_diff_within_at 𝕜 t x) (h₁ : t ⊆ s) :
fderiv_within 𝕜 f₁ t x = fderiv_within 𝕜 f s x :=
(has_fderiv_within_at.congr_mono h.has_fderiv_within_at hs hx h₁).fderiv_within hxt
lemma filter.eventually_eq.fderiv_within_eq (hs : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) :
fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x :=
by simp only [fderiv_within, hs.has_fderiv_within_at_iff hx]
lemma filter.eventually_eq.fderiv_within' (hs : f₁ =ᶠ[𝓝[s] x] f) (ht : t ⊆ s) :
fderiv_within 𝕜 f₁ t =ᶠ[𝓝[s] x] fderiv_within 𝕜 f t :=
(eventually_nhds_within_nhds_within.2 hs).mp $ eventually_mem_nhds_within.mono $ λ y hys hs,
filter.eventually_eq.fderiv_within_eq (hs.filter_mono $ nhds_within_mono _ ht)
(hs.self_of_nhds_within hys)
protected lemma filter.eventually_eq.fderiv_within (hs : f₁ =ᶠ[𝓝[s] x] f) :
fderiv_within 𝕜 f₁ s =ᶠ[𝓝[s] x] fderiv_within 𝕜 f s :=
hs.fderiv_within' subset.rfl
lemma filter.eventually_eq.fderiv_within_eq_nhds (h : f₁ =ᶠ[𝓝 x] f) :
fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x :=
(h.filter_mono nhds_within_le_nhds).fderiv_within_eq h.self_of_nhds
lemma fderiv_within_congr (hs : eq_on f₁ f s) (hx : f₁ x = f x) :
fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x :=
(hs.eventually_eq.filter_mono inf_le_right).fderiv_within_eq hx
lemma fderiv_within_congr' (hs : eq_on f₁ f s) (hx : x ∈ s) :
fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x :=
fderiv_within_congr hs (hs hx)
lemma filter.eventually_eq.fderiv_eq (h : f₁ =ᶠ[𝓝 x] f) :
fderiv 𝕜 f₁ x = fderiv 𝕜 f x :=
by rw [← fderiv_within_univ, ← fderiv_within_univ, h.fderiv_within_eq_nhds]
protected lemma filter.eventually_eq.fderiv (h : f₁ =ᶠ[𝓝 x] f) :
fderiv 𝕜 f₁ =ᶠ[𝓝 x] fderiv 𝕜 f :=
h.eventually_eq_nhds.mono $ λ x h, h.fderiv_eq
end congr
section id
/-! ### Derivative of the identity -/
theorem has_strict_fderiv_at_id (x : E) :
has_strict_fderiv_at id (id 𝕜 E) x :=
(is_o_zero _ _).congr_left $ by simp
theorem has_fderiv_at_filter_id (x : E) (L : filter E) :
has_fderiv_at_filter id (id 𝕜 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) s x :=
has_fderiv_at_filter_id _ _
theorem has_fderiv_at_id (x : E) : has_fderiv_at id (id 𝕜 E) x :=
has_fderiv_at_filter_id _ _
@[simp] lemma differentiable_at_id : differentiable_at 𝕜 id x :=
(has_fderiv_at_id x).differentiable_at
@[simp] lemma differentiable_at_id' : differentiable_at 𝕜 (λ x, x) x :=
(has_fderiv_at_id x).differentiable_at
lemma differentiable_within_at_id : differentiable_within_at 𝕜 id s x :=
differentiable_at_id.differentiable_within_at
@[simp] lemma differentiable_id : differentiable 𝕜 (id : E → E) :=
λx, differentiable_at_id
@[simp] lemma differentiable_id' : differentiable 𝕜 (λ (x : E), x) :=
λx, differentiable_at_id
lemma differentiable_on_id : differentiable_on 𝕜 id s :=
differentiable_id.differentiable_on
lemma fderiv_id : fderiv 𝕜 id x = id 𝕜 E :=
has_fderiv_at.fderiv (has_fderiv_at_id x)
@[simp] lemma fderiv_id' : fderiv 𝕜 (λ (x : E), x) x = continuous_linear_map.id 𝕜 E :=
fderiv_id
lemma fderiv_within_id (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 id s x = id 𝕜 E :=
begin
rw differentiable_at.fderiv_within (differentiable_at_id) hxs,
exact fderiv_id
end
lemma fderiv_within_id' (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λ (x : E), x) s x = continuous_linear_map.id 𝕜 E :=
fderiv_within_id hxs
end id
section const
/-! ### derivative of a constant function -/
theorem has_strict_fderiv_at_const (c : F) (x : E) :
has_strict_fderiv_at (λ _, c) (0 : E →L[𝕜] F) x :=
(is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self]
theorem has_fderiv_at_filter_const (c : F) (x : E) (L : filter E) :
has_fderiv_at_filter (λ x, c) (0 : E →L[𝕜] F) x L :=
(is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self]
theorem has_fderiv_within_at_const (c : F) (x : E) (s : set E) :
has_fderiv_within_at (λ x, c) (0 : E →L[𝕜] F) s x :=
has_fderiv_at_filter_const _ _ _
theorem has_fderiv_at_const (c : F) (x : E) :
has_fderiv_at (λ x, c) (0 : E →L[𝕜] F) x :=
has_fderiv_at_filter_const _ _ _
@[simp] lemma differentiable_at_const (c : F) : differentiable_at 𝕜 (λx, c) x :=
⟨0, has_fderiv_at_const c x⟩
lemma differentiable_within_at_const (c : F) : differentiable_within_at 𝕜 (λx, c) s x :=
differentiable_at.differentiable_within_at (differentiable_at_const _)
lemma fderiv_const_apply (c : F) : fderiv 𝕜 (λy, c) x = 0 :=
has_fderiv_at.fderiv (has_fderiv_at_const c x)
@[simp] lemma fderiv_const (c : F) : fderiv 𝕜 (λ (y : E), c) = 0 :=
by { ext m, rw fderiv_const_apply, refl }
lemma fderiv_within_const_apply (c : F) (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λy, c) s x = 0 :=
begin
rw differentiable_at.fderiv_within (differentiable_at_const _) hxs,
exact fderiv_const_apply _
end
@[simp] lemma differentiable_const (c : F) : differentiable 𝕜 (λx : E, c) :=
λx, differentiable_at_const _
lemma differentiable_on_const (c : F) : differentiable_on 𝕜 (λx, c) s :=
(differentiable_const _).differentiable_on
lemma has_fderiv_within_at_singleton (f : E → F) (x : E) :
has_fderiv_within_at f (0 : E →L[𝕜] F) {x} x :=
by simp only [has_fderiv_within_at, nhds_within_singleton, has_fderiv_at_filter, is_o_pure,
continuous_linear_map.zero_apply, sub_self]
lemma has_fderiv_at_of_subsingleton [h : subsingleton E] (f : E → F) (x : E) :
has_fderiv_at f (0 : E →L[𝕜] F) x :=
begin
rw [← has_fderiv_within_at_univ, subsingleton_univ.eq_singleton_of_mem (mem_univ x)],
exact has_fderiv_within_at_singleton f x
end
lemma differentiable_on_empty : differentiable_on 𝕜 f ∅ := λ x, false.elim
lemma differentiable_on_singleton : differentiable_on 𝕜 f {x} :=
forall_eq.2 (has_fderiv_within_at_singleton f x).differentiable_within_at
lemma set.subsingleton.differentiable_on (hs : s.subsingleton) : differentiable_on 𝕜 f s :=
hs.induction_on differentiable_on_empty (λ x, differentiable_on_singleton)
lemma has_fderiv_at_zero_of_eventually_const
(c : F) (hf : f =ᶠ[𝓝 x] (λ y, c)) :
has_fderiv_at f (0 : E →L[𝕜] F) x :=
(has_fderiv_at_const _ _).congr_of_eventually_eq hf
end const
end
/-! ### Support of derivatives -/
section support
open function
variables (𝕜 : Type*) {E F : Type*} [nontrivially_normed_field 𝕜] [normed_add_comm_group E]
[normed_space 𝕜 E] [normed_add_comm_group F] [normed_space 𝕜 F] {f : E → F}
lemma support_fderiv_subset : support (fderiv 𝕜 f) ⊆ tsupport f :=
begin
intros x,
rw [← not_imp_not, not_mem_tsupport_iff_eventually_eq, nmem_support],
exact λ hx, (hx.fderiv_eq.trans $ fderiv_const_apply 0),
end
lemma tsupport_fderiv_subset : tsupport (fderiv 𝕜 f) ⊆ tsupport f :=
closure_minimal (support_fderiv_subset 𝕜) is_closed_closure
lemma has_compact_support.fderiv (hf : has_compact_support f) : has_compact_support (fderiv 𝕜 f) :=
hf.mono' $ support_fderiv_subset 𝕜
end support
|
e4c96df29396b11ccdc8072526742bf526747270 | 367134ba5a65885e863bdc4507601606690974c1 | /src/algebra/lie/matrix.lean | f99c9bae24bf09fb7b2587ee22c3b33a4d184c42 | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 3,354 | lean | /-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import algebra.lie.of_associative
import linear_algebra.matrix
/-!
# Lie algebras of matrices
An important class of Lie algebras are those arising from the associative algebra structure on
square matrices over a commutative ring. This file provides some very basic definitions whose
primary value stems from their utility when constructing the classical Lie algebras using matrices.
## Main definitions
* `lie_equiv_matrix'`
* `matrix.lie_conj`
* `matrix.reindex_lie_equiv`
## Tags
lie algebra, matrix
-/
universes u v w w₁ w₂
section matrices
open_locale matrix
variables {R : Type u} [comm_ring R]
variables {n : Type w} [decidable_eq n] [fintype n]
/-- The natural equivalence between linear endomorphisms of finite free modules and square matrices
is compatible with the Lie algebra structures. -/
def lie_equiv_matrix' : module.End R (n → R) ≃ₗ⁅R⁆ matrix n n R :=
{ map_lie' := λ T S,
begin
let f := @linear_map.to_matrix' R _ n n _ _ _,
change f (T.comp S - S.comp T) = (f T) * (f S) - (f S) * (f T),
have h : ∀ (T S : module.End R _), f (T.comp S) = (f T) ⬝ (f S) := linear_map.to_matrix'_comp,
rw [linear_equiv.map_sub, h, h, matrix.mul_eq_mul, matrix.mul_eq_mul],
end,
..linear_map.to_matrix' }
@[simp] lemma lie_equiv_matrix'_apply (f : module.End R (n → R)) :
lie_equiv_matrix' f = f.to_matrix' := rfl
@[simp] lemma lie_equiv_matrix'_symm_apply (A : matrix n n R) :
(@lie_equiv_matrix' R _ n _ _).symm A = A.to_lin' := rfl
/-- An invertible matrix induces a Lie algebra equivalence from the space of matrices to itself. -/
noncomputable def matrix.lie_conj (P : matrix n n R) (h : is_unit P) :
matrix n n R ≃ₗ⁅R⁆ matrix n n R :=
((@lie_equiv_matrix' R _ n _ _).symm.trans (P.to_linear_equiv h).lie_conj).trans lie_equiv_matrix'
@[simp] lemma matrix.lie_conj_apply (P A : matrix n n R) (h : is_unit P) :
P.lie_conj h A = P ⬝ A ⬝ P⁻¹ :=
by simp [linear_equiv.conj_apply, matrix.lie_conj, linear_map.to_matrix'_comp,
linear_map.to_matrix'_to_lin']
@[simp] lemma matrix.lie_conj_symm_apply (P A : matrix n n R) (h : is_unit P) :
(P.lie_conj h).symm A = P⁻¹ ⬝ A ⬝ P :=
by simp [linear_equiv.symm_conj_apply, matrix.lie_conj, linear_map.to_matrix'_comp,
linear_map.to_matrix'_to_lin']
/-- For square matrices, the natural map that reindexes a matrix's rows and columns with equivalent
types is an equivalence of Lie algebras. -/
def matrix.reindex_lie_equiv {m : Type w₁} [decidable_eq m] [fintype m]
(e : n ≃ m) : matrix n n R ≃ₗ⁅R⁆ matrix m m R :=
{ map_lie' := λ M N, by simp only [lie_ring.of_associative_ring_bracket, matrix.reindex_mul,
matrix.mul_eq_mul, linear_equiv.map_sub, linear_equiv.to_fun_eq_coe],
..(matrix.reindex_linear_equiv e e) }
@[simp] lemma matrix.reindex_lie_equiv_apply {m : Type w₁} [decidable_eq m] [fintype m]
(e : n ≃ m) (M : matrix n n R) :
matrix.reindex_lie_equiv e M = λ i j, M (e.symm i) (e.symm j) :=
rfl
@[simp] lemma matrix.reindex_lie_equiv_symm_apply {m : Type w₁} [decidable_eq m] [fintype m]
(e : n ≃ m) (M : matrix m m R) :
(matrix.reindex_lie_equiv e).symm M = λ i j, M (e i) (e j) :=
rfl
end matrices
|
15419ee07f558d1e087ab51a5ae704205477bc4e | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /hott/types/prod.hlean | c2db35d3e7ab9235c1d1f2c95bb19457e745e29e | [
"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 | 8,707 | hlean | /-
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, Jakob von Raumer
Ported from Coq HoTT
Theorems about products
-/
open eq equiv is_equiv is_trunc prod prod.ops unit
variables {A A' B B' C D : Type} {P Q : A → Type}
{a a' a'' : A} {b b₁ b₂ b' b'' : B} {u v w : A × B}
namespace prod
/- Paths in a product space -/
protected definition eta [unfold 3] (u : A × B) : (pr₁ u, pr₂ u) = u :=
by cases u; apply idp
definition pair_eq [unfold 7 8] (pa : a = a') (pb : b = b') : (a, b) = (a', b') :=
by cases pa; cases pb; apply idp
definition prod_eq [unfold 3 4 5 6] (H₁ : u.1 = v.1) (H₂ : u.2 = v.2) : u = v :=
by cases u; cases v; exact pair_eq H₁ H₂
definition eq_pr1 [unfold 5] (p : u = v) : u.1 = v.1 :=
ap pr1 p
definition eq_pr2 [unfold 5] (p : u = v) : u.2 = v.2 :=
ap pr2 p
namespace ops
postfix `..1`:(max+1) := eq_pr1
postfix `..2`:(max+1) := eq_pr2
end ops
open ops
protected definition ap_pr1 (p : u = v) : ap pr1 p = p..1 := idp
protected definition ap_pr2 (p : u = v) : ap pr2 p = p..2 := idp
definition pair_prod_eq (p : u.1 = v.1) (q : u.2 = v.2)
: ((prod_eq p q)..1, (prod_eq p q)..2) = (p, q) :=
by induction u; induction v; esimp at *; induction p; induction q; reflexivity
definition prod_eq_pr1 (p : u.1 = v.1) (q : u.2 = v.2) : (prod_eq p q)..1 = p :=
(pair_prod_eq p q)..1
definition prod_eq_pr2 (p : u.1 = v.1) (q : u.2 = v.2) : (prod_eq p q)..2 = q :=
(pair_prod_eq p q)..2
definition prod_eq_eta (p : u = v) : prod_eq (p..1) (p..2) = p :=
by induction p; induction u; reflexivity
-- the uncurried version of prod_eq. We will prove that this is an equivalence
definition prod_eq_unc (H : u.1 = v.1 × u.2 = v.2) : u = v :=
by cases H with H₁ H₂;exact prod_eq H₁ H₂
definition pair_prod_eq_unc : Π(pq : u.1 = v.1 × u.2 = v.2),
((prod_eq_unc pq)..1, (prod_eq_unc pq)..2) = pq
| pair_prod_eq_unc (pq₁, pq₂) := pair_prod_eq pq₁ pq₂
definition prod_eq_unc_pr1 (pq : u.1 = v.1 × u.2 = v.2) : (prod_eq_unc pq)..1 = pq.1 :=
(pair_prod_eq_unc pq)..1
definition prod_eq_unc_pr2 (pq : u.1 = v.1 × u.2 = v.2) : (prod_eq_unc pq)..2 = pq.2 :=
(pair_prod_eq_unc pq)..2
definition prod_eq_unc_eta (p : u = v) : prod_eq_unc (p..1, p..2) = p :=
prod_eq_eta p
definition is_equiv_prod_eq [instance] [constructor] (u v : A × B)
: is_equiv (prod_eq_unc : u.1 = v.1 × u.2 = v.2 → u = v) :=
adjointify prod_eq_unc
(λp, (p..1, p..2))
prod_eq_unc_eta
pair_prod_eq_unc
definition prod_eq_equiv [constructor] (u v : A × B) : (u = v) ≃ (u.1 = v.1 × u.2 = v.2) :=
(equiv.mk prod_eq_unc _)⁻¹ᵉ
/- Groupoid structure -/
definition prod_eq_inv (p : a = a') (q : b = b') : (prod_eq p q)⁻¹ = prod_eq p⁻¹ q⁻¹ :=
by cases p; cases q; reflexivity
definition prod_eq_concat (p : a = a') (p' : a' = a'') (q : b = b') (q' : b' = b'')
: prod_eq p q ⬝ prod_eq p' q' = prod_eq (p ⬝ p') (q ⬝ q') :=
by cases p; cases q; cases p'; cases q'; reflexivity
/- Transport -/
definition prod_transport (p : a = a') (u : P a × Q a)
: p ▸ u = (p ▸ u.1, p ▸ u.2) :=
by induction p; induction u; reflexivity
definition prod_eq_transport (p : a = a') (q : b = b') {R : A × B → Type} (r : R (a, b))
: (prod_eq p q) ▸ r = p ▸ q ▸ r :=
by induction p; induction q; reflexivity
/- Pathovers -/
definition etao (p : a = a') (bc : P a × Q a) : bc =[p] (p ▸ bc.1, p ▸ bc.2) :=
by induction p; induction bc; apply idpo
definition prod_pathover (p : a = a') (u : P a × Q a) (v : P a' × Q a')
(r : u.1 =[p] v.1) (s : u.2 =[p] v.2) : u =[p] v :=
begin
induction u, induction v, esimp at *, induction r,
induction s using idp_rec_on,
apply idpo
end
/-
TODO:
* define the projections from the type u =[p] v
* show that the uncurried version of prod_pathover is an equivalence
-/
/- Functorial action -/
variables (f : A → A') (g : B → B')
definition prod_functor [unfold 7] (u : A × B) : A' × B' :=
(f u.1, g u.2)
definition ap_prod_functor (p : u.1 = v.1) (q : u.2 = v.2)
: ap (prod_functor f g) (prod_eq p q) = prod_eq (ap f p) (ap g q) :=
by induction u; induction v; esimp at *; induction p; induction q; reflexivity
/- Equivalences -/
definition is_equiv_prod_functor [instance] [constructor] [H : is_equiv f] [H : is_equiv g]
: is_equiv (prod_functor f g) :=
begin
apply adjointify _ (prod_functor f⁻¹ g⁻¹),
intro u, induction u, rewrite [▸*,right_inv f,right_inv g],
intro u, induction u, rewrite [▸*,left_inv f,left_inv g],
end
definition prod_equiv_prod_of_is_equiv [constructor] [H : is_equiv f] [H : is_equiv g]
: A × B ≃ A' × B' :=
equiv.mk (prod_functor f g) _
definition prod_equiv_prod [constructor] (f : A ≃ A') (g : B ≃ B') : A × B ≃ A' × B' :=
equiv.mk (prod_functor f g) _
definition prod_equiv_prod_left [constructor] (g : B ≃ B') : A × B ≃ A × B' :=
prod_equiv_prod equiv.refl g
definition prod_equiv_prod_right [constructor] (f : A ≃ A') : A × B ≃ A' × B :=
prod_equiv_prod f equiv.refl
/- Symmetry -/
definition is_equiv_flip [instance] [constructor] (A B : Type)
: is_equiv (flip : A × B → B × A) :=
adjointify flip
flip
(λu, destruct u (λb a, idp))
(λu, destruct u (λa b, idp))
definition prod_comm_equiv [constructor] (A B : Type) : A × B ≃ B × A :=
equiv.mk flip _
/- Associativity -/
definition prod_assoc_equiv [constructor] (A B C : Type) : A × (B × C) ≃ (A × B) × C :=
begin
fapply equiv.MK,
{ intro z, induction z with a z, induction z with b c, exact (a, b, c)},
{ intro z, induction z with z c, induction z with a b, exact (a, (b, c))},
{ intro z, induction z with z c, induction z with a b, reflexivity},
{ intro z, induction z with a z, induction z with b c, reflexivity},
end
definition prod_contr_equiv [constructor] (A B : Type) [H : is_contr B] : A × B ≃ A :=
equiv.MK pr1
(λx, (x, !center))
(λx, idp)
(λx, by cases x with a b; exact pair_eq idp !center_eq)
definition prod_unit_equiv [constructor] (A : Type) : A × unit ≃ A :=
!prod_contr_equiv
definition prod_empty_equiv (A : Type) : A × empty ≃ empty :=
begin
fapply equiv.MK,
{ intro x, cases x with a e, cases e },
{ intro e, cases e },
{ intro e, cases e },
{ intro x, cases x with a e, cases e }
end
/- Universal mapping properties -/
definition is_equiv_prod_rec [instance] [constructor] (P : A × B → Type)
: is_equiv (prod.rec : (Πa b, P (a, b)) → Πu, P u) :=
adjointify _
(λg a b, g (a, b))
(λg, eq_of_homotopy (λu, by induction u;reflexivity))
(λf, idp)
definition equiv_prod_rec [constructor] (P : A × B → Type) : (Πa b, P (a, b)) ≃ (Πu, P u) :=
equiv.mk prod.rec _
definition imp_imp_equiv_prod_imp (A B C : Type) : (A → B → C) ≃ (A × B → C) :=
!equiv_prod_rec
definition prod_corec_unc [unfold 4] {P Q : A → Type} (u : (Πa, P a) × (Πa, Q a)) (a : A)
: P a × Q a :=
(u.1 a, u.2 a)
definition is_equiv_prod_corec [constructor] (P Q : A → Type)
: is_equiv (prod_corec_unc : (Πa, P a) × (Πa, Q a) → Πa, P a × Q a) :=
adjointify _
(λg, (λa, (g a).1, λa, (g a).2))
(by intro g; apply eq_of_homotopy; intro a; esimp; induction (g a); reflexivity)
(by intro h; induction h with f g; reflexivity)
definition equiv_prod_corec [constructor] (P Q : A → Type)
: ((Πa, P a) × (Πa, Q a)) ≃ (Πa, P a × Q a) :=
equiv.mk _ !is_equiv_prod_corec
definition imp_prod_imp_equiv_imp_prod [constructor] (A B C : Type)
: (A → B) × (A → C) ≃ (A → (B × C)) :=
!equiv_prod_corec
theorem is_trunc_prod (A B : Type) (n : trunc_index) [HA : is_trunc n A] [HB : is_trunc n B]
: is_trunc n (A × B) :=
begin
revert A B HA HB, induction n with n IH, all_goals intro A B HA HB,
{ fapply is_contr.mk,
exact (!center, !center),
intro u, apply prod_eq, all_goals apply center_eq},
{ apply is_trunc_succ_intro, intro u v,
apply is_trunc_equiv_closed_rev, apply prod_eq_equiv,
exact IH _ _ _ _}
end
end prod
attribute prod.is_trunc_prod [instance] [priority 1510]
definition tprod [constructor] {n : trunc_index} (A B : n-Type) : n-Type :=
trunctype.mk (A × B) _
infixr `×t`:30 := tprod
|
1535d6715be292bd77fe5aafcd2cb4208909c986 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebra/continued_fractions/basic_auto.lean | 5c680985c70a4851759057da74c98bad517e27db | [] | 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 | 14,823 | lean | /-
Copyright (c) 2019 Kevin Kappelmann. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Kappelmann
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.seq.seq
import Mathlib.algebra.field
import Mathlib.PostPort
universes u_1 l u_2
namespace Mathlib
/-!
# Basic Definitions/Theorems for Continued Fractions
## Summary
We define generalised, simple, and regular continued fractions and functions to evaluate their
convergents. We follow the naming conventions from Wikipedia and [wall2018analytic], Chapter 1.
## Main definitions
1. Generalised continued fractions (gcfs)
2. Simple continued fractions (scfs)
3. (Regular) continued fractions ((r)cfs)
4. Computation of convergents using the recurrence relation in `convergents`.
5. Computation of convergents by directly evaluating the fraction described by the gcf in
`convergents'`.
## Implementation notes
1. The most commonly used kind of continued fractions in the literature are regular continued
fractions. We hence just call them `continued_fractions` in the library.
2. We use sequences from `data.seq` to encode potentially infinite sequences.
## References
- <https://en.wikipedia.org/wiki/Generalized_continued_fraction>
- [Wall, H.S., *Analytic Theory of Continued Fractions*][wall2018analytic]
## Tags
numerics, number theory, approximations, fractions
-/
-- Fix a carrier `α`.
/-- We collect a partial numerator `aᵢ` and partial denominator `bᵢ` in a pair `⟨aᵢ,bᵢ⟩`. -/
structure generalized_continued_fraction.pair (α : Type u_1) where
a : α
b : α
/- Interlude: define some expected coercions and instances. -/
namespace generalized_continued_fraction.pair
/-- Make a `gcf.pair` printable. -/
protected instance has_repr {α : Type u_1} [has_repr α] : has_repr (pair α) := sorry
/-- Maps a function `f` on both components of a given pair. -/
def map {α : Type u_1} {β : Type u_2} (f : α → β) (gp : pair α) : pair β := mk (f (a gp)) (f (b gp))
/-! Interlude: define some expected coercions. -/
/- Fix another type `β` which we will convert to. -/
/-- Coerce a pair by elementwise coercion. -/
protected instance has_coe_to_generalized_continued_fraction_pair {α : Type u_1} {β : Type u_2}
[has_coe α β] : has_coe (pair α) (pair β) :=
has_coe.mk (map coe)
@[simp] theorem coe_to_generalized_continued_fraction_pair {α : Type u_1} {β : Type u_2}
[has_coe α β] {a : α} {b : α} : ↑(mk a b) = mk ↑a ↑b :=
rfl
end generalized_continued_fraction.pair
/--
A *generalised continued fraction* (gcf) is a potentially infinite expression of the form
a₀
h + ---------------------------
a₁
b₀ + --------------------
a₂
b₁ + --------------
a₃
b₂ + --------
b₃ + ...
where `h` is called the *head term* or *integer part*, the `aᵢ` are called the
*partial numerators* and the `bᵢ` the *partial denominators* of the gcf.
We store the sequence of partial numerators and denominators in a sequence of
generalized_continued_fraction.pairs `s`.
For convenience, one often writes `[h; (a₀, b₀), (a₁, b₁), (a₂, b₂),...]`.
-/
structure generalized_continued_fraction (α : Type u_1) where
h : α
s : seq (generalized_continued_fraction.pair α)
namespace generalized_continued_fraction
/-- Constructs a generalized continued fraction without fractional part. -/
def of_integer {α : Type u_1} (a : α) : generalized_continued_fraction α := mk a seq.nil
protected instance inhabited {α : Type u_1} [Inhabited α] :
Inhabited (generalized_continued_fraction α) :=
{ default := of_integer Inhabited.default }
/-- Returns the sequence of partial numerators `aᵢ` of `g`. -/
/-- Returns the sequence of partial denominators `bᵢ` of `g`. -/
def partial_numerators {α : Type u_1} (g : generalized_continued_fraction α) : seq α :=
seq.map pair.a (s g)
def partial_denominators {α : Type u_1} (g : generalized_continued_fraction α) : seq α :=
seq.map pair.b (s g)
/-- A gcf terminated at position `n` if its sequence terminates at position `n`. -/
def terminated_at {α : Type u_1} (g : generalized_continued_fraction α) (n : ℕ) :=
seq.terminated_at (s g) n
/-- It is decidable whether a gcf terminated at a given position. -/
protected instance terminated_at_decidable {α : Type u_1} (g : generalized_continued_fraction α)
(n : ℕ) : Decidable (terminated_at g n) :=
eq.mpr sorry (seq.terminated_at_decidable (s g) n)
/-- A gcf terminates if its sequence terminates. -/
def terminates {α : Type u_1} (g : generalized_continued_fraction α) := seq.terminates (s g)
/-! Interlude: define some expected coercions. -/
/- Fix another type `β` which we will convert to. -/
/-- Coerce a gcf by elementwise coercion. -/
protected instance has_coe_to_generalized_continued_fraction {α : Type u_1} {β : Type u_2}
[has_coe α β] : has_coe (generalized_continued_fraction α) (generalized_continued_fraction β) :=
has_coe.mk fun (g : generalized_continued_fraction α) => mk (↑(h g)) (seq.map coe (s g))
@[simp] theorem coe_to_generalized_continued_fraction {α : Type u_1} {β : Type u_2} [has_coe α β]
{g : generalized_continued_fraction α} : ↑g = mk (↑(h g)) (seq.map coe (s g)) :=
rfl
end generalized_continued_fraction
/--
A generalized continued fraction is a *simple continued fraction* if all partial numerators are
equal to one.
1
h + ---------------------------
1
b₀ + --------------------
1
b₁ + --------------
1
b₂ + --------
b₃ + ...
-/
def generalized_continued_fraction.is_simple_continued_fraction {α : Type u_1}
(g : generalized_continued_fraction α) [HasOne α] :=
∀ (n : ℕ) (aₙ : α),
seq.nth (generalized_continued_fraction.partial_numerators g) n = some aₙ → aₙ = 1
/--
A *simple continued fraction* (scf) is a generalized continued fraction (gcf) whose partial
numerators are equal to one.
1
h + ---------------------------
1
b₀ + --------------------
1
b₁ + --------------
1
b₂ + --------
b₃ + ...
For convenience, one often writes `[h; b₀, b₁, b₂,...]`.
It is encoded as the subtype of gcfs that satisfy
`generalized_continued_fraction.is_simple_continued_fraction`.
-/
def simple_continued_fraction (α : Type u_1) [HasOne α] :=
Subtype
fun (g : generalized_continued_fraction α) =>
generalized_continued_fraction.is_simple_continued_fraction g
/- Interlude: define some expected coercions. -/
namespace simple_continued_fraction
/-- Constructs a simple continued fraction without fractional part. -/
def of_integer {α : Type u_1} [HasOne α] (a : α) : simple_continued_fraction α :=
{ val := generalized_continued_fraction.of_integer a, property := sorry }
protected instance inhabited {α : Type u_1} [HasOne α] : Inhabited (simple_continued_fraction α) :=
{ default := of_integer 1 }
/-- Lift a scf to a gcf using the inclusion map. -/
protected instance has_coe_to_generalized_continued_fraction {α : Type u_1} [HasOne α] :
has_coe (simple_continued_fraction α) (generalized_continued_fraction α) :=
eq.mpr sorry Mathlib.coe_subtype
theorem coe_to_generalized_continued_fraction {α : Type u_1} [HasOne α]
{s : simple_continued_fraction α} : ↑s = subtype.val s :=
rfl
end simple_continued_fraction
/--
A simple continued fraction is a *(regular) continued fraction* ((r)cf) if all partial denominators
`bᵢ` are positive, i.e. `0 < bᵢ`.
-/
def simple_continued_fraction.is_regular_continued_fraction {α : Type u_1} [HasOne α] [HasZero α]
[HasLess α] (s : simple_continued_fraction α) :=
∀ (n : ℕ) (bₙ : α),
seq.nth (generalized_continued_fraction.partial_denominators ↑s) n = some bₙ → 0 < bₙ
/--
A *(regular) continued fraction* ((r)cf) is a simple continued fraction (scf) whose partial
denominators are all positive. It is the subtype of scfs that satisfy
`simple_continued_fraction.is_regular_continued_fraction`.
-/
def continued_fraction (α : Type u_1) [HasOne α] [HasZero α] [HasLess α] :=
Subtype
fun (s : simple_continued_fraction α) =>
simple_continued_fraction.is_regular_continued_fraction s
/- Interlude: define some expected coercions. -/
namespace continued_fraction
/-- Constructs a continued fraction without fractional part. -/
def of_integer {α : Type u_1} [HasOne α] [HasZero α] [HasLess α] (a : α) : continued_fraction α :=
{ val := simple_continued_fraction.of_integer a, property := sorry }
protected instance inhabited {α : Type u_1} [HasOne α] [HasZero α] [HasLess α] :
Inhabited (continued_fraction α) :=
{ default := of_integer 0 }
/-- Lift a cf to a scf using the inclusion map. -/
protected instance has_coe_to_simple_continued_fraction {α : Type u_1} [HasOne α] [HasZero α]
[HasLess α] : has_coe (continued_fraction α) (simple_continued_fraction α) :=
eq.mpr sorry Mathlib.coe_subtype
theorem coe_to_simple_continued_fraction {α : Type u_1} [HasOne α] [HasZero α] [HasLess α]
{c : continued_fraction α} : ↑c = subtype.val c :=
rfl
/-- Lift a cf to a scf using the inclusion map. -/
protected instance has_coe_to_generalized_continued_fraction {α : Type u_1} [HasOne α] [HasZero α]
[HasLess α] : has_coe (continued_fraction α) (generalized_continued_fraction α) :=
has_coe.mk fun (c : continued_fraction α) => ↑↑c
theorem coe_to_generalized_continued_fraction {α : Type u_1} [HasOne α] [HasZero α] [HasLess α]
{c : continued_fraction α} : ↑c = ↑(subtype.val c) :=
rfl
end continued_fraction
/-
We now define how to compute the convergents of a gcf. There are two standard ways to do this:
directly evaluating the (infinite) fraction described by the gcf or using a recurrence relation.
For (r)cfs, these computations are equivalent as shown in
`algebra.continued_fractions.convergents_equiv`.
-/
namespace generalized_continued_fraction
-- Fix a division ring for the computations.
/-
We start with the definition of the recurrence relation. Given a gcf `g`, for all `n ≥ 1`, we define
- `A₋₁ = 1, A₀ = h, Aₙ = bₙ₋₁ * Aₙ₋₁ + aₙ₋₁ * Aₙ₋₂`, and
- `B₋₁ = 0, B₀ = 1, Bₙ = bₙ₋₁ * Bₙ₋₁ + aₙ₋₁ * Bₙ₋₂`.
`Aₙ, `Bₙ` are called the *nth continuants*, Aₙ the *nth numerator*, and `Bₙ` the
*nth denominator* of `g`. The *nth convergent* of `g` is given by `Aₙ / Bₙ`.
-/
/--
Returns the next numerator `Aₙ = bₙ₋₁ * Aₙ₋₁ + aₙ₋₁ * Aₙ₋₂`, where `predA` is `Aₙ₋₁`,
`ppredA` is `Aₙ₋₂`, `a` is `aₙ₋₁`, and `b` is `bₙ₋₁`.
-/
def next_numerator {K : Type u_2} [division_ring K] (a : K) (b : K) (ppredA : K) (predA : K) : K :=
b * predA + a * ppredA
/--
Returns the next denominator `Bₙ = bₙ₋₁ * Bₙ₋₁ + aₙ₋₁ * Bₙ₋₂``, where `predB` is `Bₙ₋₁` and
`ppredB` is `Bₙ₋₂`, `a` is `aₙ₋₁`, and `b` is `bₙ₋₁`.
-/
def next_denominator {K : Type u_2} [division_ring K] (aₙ : K) (bₙ : K) (ppredB : K) (predB : K) :
K :=
bₙ * predB + aₙ * ppredB
/--
Returns the next continuants `⟨Aₙ, Bₙ⟩` using `next_numerator` and `next_denominator`, where `pred`
is `⟨Aₙ₋₁, Bₙ₋₁⟩`, `ppred` is `⟨Aₙ₋₂, Bₙ₋₂⟩`, `a` is `aₙ₋₁`, and `b` is `bₙ₋₁`.
-/
def next_continuants {K : Type u_2} [division_ring K] (a : K) (b : K) (ppred : pair K)
(pred : pair K) : pair K :=
pair.mk (next_numerator a b (pair.a ppred) (pair.a pred))
(next_denominator a b (pair.b ppred) (pair.b pred))
/-- Returns the continuants `⟨Aₙ₋₁, Bₙ₋₁⟩` of `g`. -/
def continuants_aux {K : Type u_2} [division_ring K] (g : generalized_continued_fraction K) :
stream (pair K) :=
sorry
/-- Returns the continuants `⟨Aₙ, Bₙ⟩` of `g`. -/
def continuants {K : Type u_2} [division_ring K] (g : generalized_continued_fraction K) :
stream (pair K) :=
stream.tail (continuants_aux g)
/-- Returns the numerators `Aₙ` of `g`. -/
def numerators {K : Type u_2} [division_ring K] (g : generalized_continued_fraction K) : stream K :=
stream.map pair.a (continuants g)
/-- Returns the denominators `Bₙ` of `g`. -/
def denominators {K : Type u_2} [division_ring K] (g : generalized_continued_fraction K) :
stream K :=
stream.map pair.b (continuants g)
/-- Returns the convergents `Aₙ / Bₙ` of `g`, where `Aₙ, Bₙ` are the nth continuants of `g`. -/
def convergents {K : Type u_2} [division_ring K] (g : generalized_continued_fraction K) :
stream K :=
fun (n : ℕ) => numerators g n / denominators g n
/--
Returns the approximation of the fraction described by the given sequence up to a given position n.
For example, `convergents'_aux [(1, 2), (3, 4), (5, 6)] 2 = 1 / (2 + 3 / 4)` and
`convergents'_aux [(1, 2), (3, 4), (5, 6)] 0 = 0`.
-/
def convergents'_aux {K : Type u_2} [division_ring K] : seq (pair K) → ℕ → K := sorry
/--
Returns the convergents of `g` by evaluating the fraction described by `g` up to a given
position `n`. For example, `convergents' [9; (1, 2), (3, 4), (5, 6)] 2 = 9 + 1 / (2 + 3 / 4)` and
`convergents' [9; (1, 2), (3, 4), (5, 6)] 0 = 9`
-/
def convergents' {K : Type u_2} [division_ring K] (g : generalized_continued_fraction K) (n : ℕ) :
K :=
h g + convergents'_aux (s g) n
end generalized_continued_fraction
-- Now, some basic, general theorems
namespace generalized_continued_fraction
/-- Two gcfs `g` and `g'` are equal if and only if their components are equal. -/
protected theorem ext_iff {α : Type u_1} {g : generalized_continued_fraction α}
{g' : generalized_continued_fraction α} : g = g' ↔ h g = h g' ∧ s g = s g' :=
sorry
protected theorem ext {α : Type u_1} {g : generalized_continued_fraction α}
{g' : generalized_continued_fraction α} (hyp : h g = h g' ∧ s g = s g') : g = g' :=
iff.elim_right generalized_continued_fraction.ext_iff hyp
end Mathlib |
ea9dc24b24c2d58f67a2149ba688e239d9263dd2 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/ring_theory/perfection.lean | dbae95179f92c3c7ec195488db7ab245602c90b4 | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 25,374 | lean | /-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import algebra.char_p
import algebra.ring.pi
import analysis.special_functions.pow
import field_theory.perfect_closure
import ring_theory.localization
import ring_theory.subring
import ring_theory.valuation.integers
/-!
# Ring Perfection and Tilt
In this file we define the perfection of a ring of characteristic p, and the tilt of a field
given a valuation to `ℝ≥0`.
## TODO
Define the valuation on the tilt, and define a characteristic predicate for the tilt.
-/
universes u₁ u₂ u₃ u₄
open_locale nnreal
/-- The perfection of a monoid `M`, defined to be the projective limit of `M`
using the `p`-th power maps `M → M` indexed by the natural numbers, implemented as
`{ f : ℕ → M | ∀ n, f (n + 1) ^ p = f n }`. -/
def monoid.perfection (M : Type u₁) [comm_monoid M] (p : ℕ) : submonoid (ℕ → M) :=
{ carrier := { f | ∀ n, f (n + 1) ^ p = f n },
one_mem' := λ n, one_pow _,
mul_mem' := λ f g hf hg n, (mul_pow _ _ _).trans $ congr_arg2 _ (hf n) (hg n) }
/-- The perfection of a ring `R` with characteristic `p`, as a subsemiring,
defined to be the projective limit of `R` using the Frobenius maps `R → R`
indexed by the natural numbers, implemented as `{ f : ℕ → R | ∀ n, f (n + 1) ^ p = f n }`. -/
def ring.perfection_subsemiring (R : Type u₁) [comm_semiring R]
(p : ℕ) [hp : fact p.prime] [char_p R p] :
subsemiring (ℕ → R) :=
{ zero_mem' := λ n, zero_pow $ hp.1.pos,
add_mem' := λ f g hf hg n, (frobenius_add R p _ _).trans $ congr_arg2 _ (hf n) (hg n),
.. monoid.perfection R p }
/-- The perfection of a ring `R` with characteristic `p`, as a subring,
defined to be the projective limit of `R` using the Frobenius maps `R → R`
indexed by the natural numbers, implemented as `{ f : ℕ → R | ∀ n, f (n + 1) ^ p = f n }`. -/
def ring.perfection_subring (R : Type u₁) [comm_ring R]
(p : ℕ) [hp : fact p.prime] [char_p R p] :
subring (ℕ → R) :=
(ring.perfection_subsemiring R p).to_subring $ λ n, by simp_rw [← frobenius_def, pi.neg_apply,
pi.one_apply, ring_hom.map_neg, ring_hom.map_one]
/-- The perfection of a ring `R` with characteristic `p`,
defined to be the projective limit of `R` using the Frobenius maps `R → R`
indexed by the natural numbers, implemented as `{f : ℕ → R // ∀ n, f (n + 1) ^ p = f n}`. -/
def ring.perfection (R : Type u₁) [comm_semiring R] (p : ℕ) : Type u₁ :=
{f // ∀ (n : ℕ), (f : ℕ → R) (n + 1) ^ p = f n}
namespace perfection
variables (R : Type u₁) [comm_semiring R] (p : ℕ) [hp : fact p.prime] [char_p R p]
include hp
instance : comm_semiring (ring.perfection R p) :=
(ring.perfection_subsemiring R p).to_comm_semiring
instance : char_p (ring.perfection R p) p :=
char_p.subsemiring (ℕ → R) p (ring.perfection_subsemiring R p)
instance ring (R : Type u₁) [comm_ring R] [char_p R p] : ring (ring.perfection R p) :=
(ring.perfection_subring R p).to_ring
instance comm_ring (R : Type u₁) [comm_ring R] [char_p R p] : comm_ring (ring.perfection R p) :=
(ring.perfection_subring R p).to_comm_ring
instance : inhabited (ring.perfection R p) := ⟨0⟩
/-- The `n`-th coefficient of an element of the perfection. -/
def coeff (n : ℕ) : ring.perfection R p →+* R :=
{ to_fun := λ f, f.1 n,
map_one' := rfl,
map_mul' := λ f g, rfl,
map_zero' := rfl,
map_add' := λ f g, rfl }
variables {R p}
@[ext] lemma ext {f g : ring.perfection R p} (h : ∀ n, coeff R p n f = coeff R p n g) : f = g :=
subtype.eq $ funext h
variables (R p)
/-- The `p`-th root of an element of the perfection. -/
def pth_root : ring.perfection R p →+* ring.perfection R p :=
{ to_fun := λ f, ⟨λ n, coeff R p (n + 1) f, λ n, f.2 _⟩,
map_one' := rfl,
map_mul' := λ f g, rfl,
map_zero' := rfl,
map_add' := λ f g, rfl }
variables {R p}
@[simp] lemma coeff_mk (f : ℕ → R) (hf) (n : ℕ) : coeff R p n ⟨f, hf⟩ = f n := rfl
lemma coeff_pth_root (f : ring.perfection R p) (n : ℕ) :
coeff R p n (pth_root R p f) = coeff R p (n + 1) f :=
rfl
lemma coeff_pow_p (f : ring.perfection R p) (n : ℕ) :
coeff R p (n + 1) (f ^ p) = coeff R p n f :=
by { rw ring_hom.map_pow, exact f.2 n }
lemma coeff_pow_p' (f : ring.perfection R p) (n : ℕ) :
coeff R p (n + 1) f ^ p = coeff R p n f :=
f.2 n
lemma coeff_frobenius (f : ring.perfection R p) (n : ℕ) :
coeff R p (n + 1) (frobenius _ p f) = coeff R p n f :=
by apply coeff_pow_p f n -- `coeff_pow_p f n` also works but is slow!
lemma coeff_iterate_frobenius (f : ring.perfection R p) (n m : ℕ) :
coeff R p (n + m) (frobenius _ p ^[m] f) = coeff R p n f :=
nat.rec_on m rfl $ λ m ih, by erw [function.iterate_succ_apply', coeff_frobenius, ih]
lemma coeff_iterate_frobenius' (f : ring.perfection R p) (n m : ℕ) (hmn : m ≤ n) :
coeff R p n (frobenius _ p ^[m] f) = coeff R p (n - m) f :=
eq.symm $ (coeff_iterate_frobenius _ _ m).symm.trans $ (nat.sub_add_cancel hmn).symm ▸ rfl
lemma pth_root_frobenius : (pth_root R p).comp (frobenius _ p) = ring_hom.id _ :=
ring_hom.ext $ λ x, ext $ λ n,
by rw [ring_hom.comp_apply, ring_hom.id_apply, coeff_pth_root, coeff_frobenius]
lemma frobenius_pth_root : (frobenius _ p).comp (pth_root R p) = ring_hom.id _ :=
ring_hom.ext $ λ x, ext $ λ n,
by rw [ring_hom.comp_apply, ring_hom.id_apply, ring_hom.map_frobenius, coeff_pth_root,
← ring_hom.map_frobenius, coeff_frobenius]
lemma coeff_add_ne_zero {f : ring.perfection R p} {n : ℕ} (hfn : coeff R p n f ≠ 0) (k : ℕ) :
coeff R p (n + k) f ≠ 0 :=
nat.rec_on k hfn $ λ k ih h, ih $ by erw [← coeff_pow_p, ring_hom.map_pow, h, zero_pow hp.1.pos]
lemma coeff_ne_zero_of_le {f : ring.perfection R p} {m n : ℕ} (hfm : coeff R p m f ≠ 0)
(hmn : m ≤ n) : coeff R p n f ≠ 0 :=
let ⟨k, hk⟩ := nat.exists_eq_add_of_le hmn in hk.symm ▸ coeff_add_ne_zero hfm k
variables (R p)
instance perfect_ring : perfect_ring (ring.perfection R p) p :=
{ pth_root' := pth_root R p,
frobenius_pth_root' := congr_fun $ congr_arg ring_hom.to_fun $ @frobenius_pth_root R _ p _ _,
pth_root_frobenius' := congr_fun $ congr_arg ring_hom.to_fun $ @pth_root_frobenius R _ p _ _ }
/-- Given rings `R` and `S` of characteristic `p`, with `R` being perfect,
any homomorphism `R →+* S` can be lifted to a homomorphism `R →+* perfection S p`. -/
@[simps] def lift (R : Type u₁) [comm_semiring R] [char_p R p] [perfect_ring R p]
(S : Type u₂) [comm_semiring S] [char_p S p] :
(R →+* S) ≃ (R →+* ring.perfection S p) :=
{ to_fun := λ f,
{ to_fun := λ r, ⟨λ n, f $ _root_.pth_root R p ^[n] r,
λ n, by rw [← f.map_pow, function.iterate_succ_apply', pth_root_pow_p]⟩,
map_one' := ext $ λ n, (congr_arg f $ ring_hom.iterate_map_one _ _).trans f.map_one,
map_mul' := λ x y, ext $ λ n, (congr_arg f $ ring_hom.iterate_map_mul _ _ _ _).trans $
f.map_mul _ _,
map_zero' := ext $ λ n, (congr_arg f $ ring_hom.iterate_map_zero _ _).trans f.map_zero,
map_add' := λ x y, ext $ λ n, (congr_arg f $ ring_hom.iterate_map_add _ _ _ _).trans $
f.map_add _ _ },
inv_fun := ring_hom.comp $ coeff S p 0,
left_inv := λ f, ring_hom.ext $ λ r, rfl,
right_inv := λ f, ring_hom.ext $ λ r, ext $ λ n,
show coeff S p 0 (f (_root_.pth_root R p ^[n] r)) = coeff S p n (f r),
by rw [← coeff_iterate_frobenius _ 0 n, zero_add, ← ring_hom.map_iterate_frobenius,
right_inverse_pth_root_frobenius.iterate] }
lemma hom_ext {R : Type u₁} [comm_semiring R] [char_p R p] [perfect_ring R p]
{S : Type u₂} [comm_semiring S] [char_p S p] {f g : R →+* ring.perfection S p}
(hfg : ∀ x, coeff S p 0 (f x) = coeff S p 0 (g x)) : f = g :=
(lift p R S).symm.injective $ ring_hom.ext hfg
variables {R} {S : Type u₂} [comm_semiring S] [char_p S p]
/-- A ring homomorphism `R →+* S` induces `perfection R p →+* perfection S p` -/
@[simps] def map (φ : R →+* S) : ring.perfection R p →+* ring.perfection S p :=
{ to_fun := λ f, ⟨λ n, φ (coeff R p n f), λ n, by rw [← φ.map_pow, coeff_pow_p']⟩,
map_one' := subtype.eq $ funext $ λ n, φ.map_one,
map_mul' := λ f g, subtype.eq $ funext $ λ n, φ.map_mul _ _,
map_zero' := subtype.eq $ funext $ λ n, φ.map_zero,
map_add' := λ f g, subtype.eq $ funext $ λ n, φ.map_add _ _ }
lemma coeff_map (φ : R →+* S) (f : ring.perfection R p) (n : ℕ) :
coeff S p n (map p φ f) = φ (coeff R p n f) :=
rfl
end perfection
/-- A perfection map to a ring of characteristic `p` is a map that is isomorphic
to its perfection. -/
@[nolint has_inhabited_instance] structure perfection_map (p : ℕ) [fact p.prime]
{R : Type u₁} [comm_semiring R] [char_p R p]
{P : Type u₂} [comm_semiring P] [char_p P p] [perfect_ring P p] (π : P →+* R) : Prop :=
(injective : ∀ ⦃x y : P⦄, (∀ n, π (pth_root P p ^[n] x) = π (pth_root P p ^[n] y)) → x = y)
(surjective : ∀ f : ℕ → R, (∀ n, f (n + 1) ^ p = f n) →
∃ x : P, ∀ n, π (pth_root P p ^[n] x) = f n)
namespace perfection_map
variables {p : ℕ} [fact p.prime]
variables {R : Type u₁} [comm_semiring R] [char_p R p]
variables {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p]
/-- Create a `perfection_map` from an isomorphism to the perfection. -/
@[simps] lemma mk' {f : P →+* R} (g : P ≃+* ring.perfection R p)
(hfg : perfection.lift p P R f = g) :
perfection_map p f :=
{ injective := λ x y hxy, g.injective $ (ring_hom.ext_iff.1 hfg x).symm.trans $
eq.symm $ (ring_hom.ext_iff.1 hfg y).symm.trans $ perfection.ext $ λ n, (hxy n).symm,
surjective := λ y hy, let ⟨x, hx⟩ := g.surjective ⟨y, hy⟩ in
⟨x, λ n, show perfection.coeff R p n (perfection.lift p P R f x) =
perfection.coeff R p n ⟨y, hy⟩,
by rw [hfg, ← coe_fn_coe_base, hx]⟩ }
variables (p R P)
/-- The canonical perfection map from the perfection of a ring. -/
lemma of : perfection_map p (perfection.coeff R p 0) :=
mk' (ring_equiv.refl _) $ (equiv.apply_eq_iff_eq_symm_apply _).2 rfl
/-- For a perfect ring, it itself is the perfection. -/
lemma id [perfect_ring R p] : perfection_map p (ring_hom.id R) :=
{ injective := λ x y hxy, hxy 0,
surjective := λ f hf, ⟨f 0, λ n, show pth_root R p ^[n] (f 0) = f n,
from nat.rec_on n rfl $ λ n ih, injective_pow_p p $
by rw [function.iterate_succ_apply', pth_root_pow_p _, ih, hf]⟩ }
variables {p R P}
/-- A perfection map induces an isomorphism to the prefection. -/
noncomputable def equiv {π : P →+* R} (m : perfection_map p π) : P ≃+* ring.perfection R p :=
ring_equiv.of_bijective (perfection.lift p P R π)
⟨λ x y hxy, m.injective $ λ n, (congr_arg (perfection.coeff R p n) hxy : _),
λ f, let ⟨x, hx⟩ := m.surjective f.1 f.2 in ⟨x, perfection.ext $ hx⟩⟩
lemma equiv_apply {π : P →+* R} (m : perfection_map p π) (x : P) :
m.equiv x = perfection.lift p P R π x :=
rfl
lemma comp_equiv {π : P →+* R} (m : perfection_map p π) (x : P) :
perfection.coeff R p 0 (m.equiv x) = π x :=
rfl
lemma comp_equiv' {π : P →+* R} (m : perfection_map p π) :
(perfection.coeff R p 0).comp ↑m.equiv = π :=
ring_hom.ext $ λ x, rfl
lemma comp_symm_equiv {π : P →+* R} (m : perfection_map p π) (f : ring.perfection R p) :
π (m.equiv.symm f) = perfection.coeff R p 0 f :=
(m.comp_equiv _).symm.trans $ congr_arg _ $ m.equiv.apply_symm_apply f
lemma comp_symm_equiv' {π : P →+* R} (m : perfection_map p π) :
π.comp ↑m.equiv.symm = perfection.coeff R p 0 :=
ring_hom.ext m.comp_symm_equiv
variables (p R P)
/-- Given rings `R` and `S` of characteristic `p`, with `R` being perfect,
any homomorphism `R →+* S` can be lifted to a homomorphism `R →+* P`,
where `P` is any perfection of `S`. -/
@[simps] noncomputable def lift [perfect_ring R p] (S : Type u₂) [comm_semiring S] [char_p S p]
(P : Type u₃) [comm_semiring P] [char_p P p] [perfect_ring P p]
(π : P →+* S) (m : perfection_map p π) :
(R →+* S) ≃ (R →+* P) :=
{ to_fun := λ f, ring_hom.comp ↑m.equiv.symm $ perfection.lift p R S f,
inv_fun := λ f, π.comp f,
left_inv := λ f, by { simp_rw [← ring_hom.comp_assoc, comp_symm_equiv'],
exact (perfection.lift p R S).symm_apply_apply f },
right_inv := λ f, ring_hom.ext $ λ x, m.equiv.injective $ (m.equiv.apply_symm_apply _).trans $
show perfection.lift p R S (π.comp f) x = ring_hom.comp ↑m.equiv f x,
from ring_hom.ext_iff.1 ((perfection.lift p R S).apply_eq_iff_eq_symm_apply.2 rfl) _ }
variables {R p}
lemma hom_ext [perfect_ring R p] {S : Type u₂} [comm_semiring S] [char_p S p]
{P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p]
(π : P →+* S) (m : perfection_map p π) {f g : R →+* P}
(hfg : ∀ x, π (f x) = π (g x)) : f = g :=
(lift p R S P π m).symm.injective $ ring_hom.ext hfg
variables {R P} (p) {S : Type u₂} [comm_semiring S] [char_p S p]
variables {Q : Type u₄} [comm_semiring Q] [char_p Q p] [perfect_ring Q p]
/-- A ring homomorphism `R →+* S` induces `P →+* Q`, a map of the respective perfections. -/
@[nolint unused_arguments]
noncomputable def map {π : P →+* R} (m : perfection_map p π) {σ : Q →+* S} (n : perfection_map p σ)
(φ : R →+* S) : P →+* Q :=
lift p P S Q σ n $ φ.comp π
lemma comp_map {π : P →+* R} (m : perfection_map p π) {σ : Q →+* S} (n : perfection_map p σ)
(φ : R →+* S) : σ.comp (map p m n φ) = φ.comp π :=
(lift p P S Q σ n).symm_apply_apply _
lemma map_map {π : P →+* R} (m : perfection_map p π) {σ : Q →+* S} (n : perfection_map p σ)
(φ : R →+* S) (x : P) : σ (map p m n φ x) = φ (π x) :=
ring_hom.ext_iff.1 (comp_map p m n φ) x
-- Why is this slow?
lemma map_eq_map (φ : R →+* S) :
@map p _ R _ _ _ _ _ _ S _ _ _ _ _ _ _ (of p R) _ (of p S) φ = perfection.map p φ :=
hom_ext _ (of p S) $ λ f, by rw [map_map, perfection.coeff_map]
end perfection_map
section perfectoid
variables (K : Type u₁) [field K] (v : valuation K ℝ≥0)
variables (O : Type u₂) [comm_ring O] [algebra O K] (hv : v.integers O)
variables (p : ℕ)
include hv
/-- `O/(p)` for `O`, ring of integers of `K`. -/
@[nolint unused_arguments has_inhabited_instance] def mod_p :=
(ideal.span {p} : ideal O).quotient
variables [hp : fact p.prime] [hvp : fact (v p ≠ 1)]
namespace mod_p
instance : comm_ring (mod_p K v O hv p) :=
ideal.quotient.comm_ring _
include hp hvp
instance : char_p (mod_p K v O hv p) p :=
char_p.quotient O p $ mt hv.one_of_is_unit $ ((algebra_map O K).map_nat_cast p).symm ▸ hvp.1
instance : nontrivial (mod_p K v O hv p) :=
char_p.nontrivial_of_char_ne_one hp.1.ne_one
section classical
local attribute [instance] classical.dec
omit hp hvp
/-- For a field `K` with valuation `v : K → ℝ≥0` and ring of integers `O`,
a function `O/(p) → ℝ≥0` that sends `0` to `0` and `x + (p)` to `v(x)` as long as `x ∉ (p)`. -/
noncomputable def pre_val (x : mod_p K v O hv p) : ℝ≥0 :=
if x = 0 then 0 else v (algebra_map O K x.out')
variables {K v O hv p}
lemma pre_val_mk {x : O} (hx : (ideal.quotient.mk _ x : mod_p K v O hv p) ≠ 0) :
pre_val K v O hv p (ideal.quotient.mk _ x) = v (algebra_map O K x) :=
begin
obtain ⟨r, hr⟩ := ideal.mem_span_singleton'.1 (ideal.quotient.eq.1 $ quotient.sound' $
@quotient.mk_out' O (ideal.span {p} : ideal O).quotient_rel x),
refine (if_neg hx).trans (v.map_eq_of_sub_lt $ lt_of_not_ge' _),
erw [← ring_hom.map_sub, ← hr, hv.le_iff_dvd],
exact λ hprx, hx (ideal.quotient.eq_zero_iff_mem.2 $ ideal.mem_span_singleton.2 $
dvd_of_mul_left_dvd hprx),
end
lemma pre_val_zero : pre_val K v O hv p 0 = 0 :=
if_pos rfl
lemma pre_val_mul {x y : mod_p K v O hv p} (hxy0 : x * y ≠ 0) :
pre_val K v O hv p (x * y) = pre_val K v O hv p x * pre_val K v O hv p y :=
begin
have hx0 : x ≠ 0 := mt (by { rintro rfl, rw zero_mul }) hxy0,
have hy0 : y ≠ 0 := mt (by { rintro rfl, rw mul_zero }) hxy0,
obtain ⟨r, rfl⟩ := ideal.quotient.mk_surjective x,
obtain ⟨s, rfl⟩ := ideal.quotient.mk_surjective y,
rw ← ring_hom.map_mul at hxy0 ⊢,
rw [pre_val_mk hx0, pre_val_mk hy0, pre_val_mk hxy0, ring_hom.map_mul, v.map_mul]
end
lemma pre_val_add (x y : mod_p K v O hv p) :
pre_val K v O hv p (x + y) ≤ max (pre_val K v O hv p x) (pre_val K v O hv p y) :=
begin
by_cases hx0 : x = 0, { rw [hx0, zero_add], exact le_max_right _ _ },
by_cases hy0 : y = 0, { rw [hy0, add_zero], exact le_max_left _ _ },
by_cases hxy0 : x + y = 0, { rw [hxy0, pre_val_zero], exact zero_le _ },
obtain ⟨r, rfl⟩ := ideal.quotient.mk_surjective x,
obtain ⟨s, rfl⟩ := ideal.quotient.mk_surjective y,
rw ← ring_hom.map_add at hxy0 ⊢,
rw [pre_val_mk hx0, pre_val_mk hy0, pre_val_mk hxy0, ring_hom.map_add], exact v.map_add _ _
end
lemma v_p_lt_pre_val {x : mod_p K v O hv p} : v p < pre_val K v O hv p x ↔ x ≠ 0 :=
begin
refine ⟨λ h hx, by { rw [hx, pre_val_zero] at h, exact not_lt_zero' h },
λ h, lt_of_not_ge' $ λ hp, h _⟩,
obtain ⟨r, rfl⟩ := ideal.quotient.mk_surjective x,
rw [pre_val_mk h, ← (algebra_map O K).map_nat_cast p, hv.le_iff_dvd] at hp,
rw [ideal.quotient.eq_zero_iff_mem, ideal.mem_span_singleton], exact hp
end
lemma pre_val_eq_zero {x : mod_p K v O hv p} : pre_val K v O hv p x = 0 ↔ x = 0 :=
⟨λ hvx, classical.by_contradiction $ λ hx0 : x ≠ 0,
by { rw [← v_p_lt_pre_val, hvx] at hx0, exact not_lt_zero' hx0 },
λ hx, hx.symm ▸ pre_val_zero⟩
variables (hv hvp)
lemma v_p_lt_val {x : O} :
v p < v (algebra_map O K x) ↔ (ideal.quotient.mk _ x : mod_p K v O hv p) ≠ 0 :=
by rw [lt_iff_not_ge', not_iff_not, ← (algebra_map O K).map_nat_cast p, hv.le_iff_dvd,
ideal.quotient.eq_zero_iff_mem, ideal.mem_span_singleton]
open nnreal
variables {hv} [hvp]
include hp
lemma mul_ne_zero_of_pow_p_ne_zero {x y : mod_p K v O hv p} (hx : x ^ p ≠ 0) (hy : y ^ p ≠ 0) :
x * y ≠ 0 :=
begin
obtain ⟨r, rfl⟩ := ideal.quotient.mk_surjective x,
obtain ⟨s, rfl⟩ := ideal.quotient.mk_surjective y,
have h1p : (0 : ℝ) < 1 / p := one_div_pos.2 (nat.cast_pos.2 hp.1.pos),
rw ← ring_hom.map_mul, rw ← ring_hom.map_pow at hx hy,
rw ← v_p_lt_val hv at hx hy ⊢,
rw [ring_hom.map_pow, v.map_pow, ← rpow_lt_rpow_iff h1p, ← rpow_nat_cast, ← rpow_mul,
mul_one_div_cancel (nat.cast_ne_zero.2 hp.1.ne_zero : (p : ℝ) ≠ 0), rpow_one] at hx hy,
rw [ring_hom.map_mul, v.map_mul], refine lt_of_le_of_lt _ (mul_lt_mul'''' hx hy),
by_cases hvp : v p = 0, { rw hvp, exact zero_le _ }, replace hvp := zero_lt_iff.2 hvp,
conv_lhs { rw ← rpow_one (v p) }, rw ← rpow_add (ne_of_gt hvp),
refine rpow_le_rpow_of_exponent_ge hvp ((algebra_map O K).map_nat_cast p ▸ hv.2 _) _,
rw [← add_div, div_le_one (nat.cast_pos.2 hp.1.pos : 0 < (p : ℝ))], exact_mod_cast hp.1.two_le
end
end classical
end mod_p
/-- Perfection of `O/(p)` where `O` is the ring of integers of `K`. -/
@[nolint has_inhabited_instance] def pre_tilt :=
ring.perfection (mod_p K v O hv p) p
include hp hvp
namespace pre_tilt
instance : comm_ring (pre_tilt K v O hv p) :=
perfection.comm_ring p _
instance : char_p (pre_tilt K v O hv p) p :=
perfection.char_p (mod_p K v O hv p) p
section classical
open_locale classical
open perfection
/-- The valuation `Perfection(O/(p)) → ℝ≥0` as a function.
Given `f ∈ Perfection(O/(p))`, if `f = 0` then output `0`;
otherwise output `pre_val(f(n))^(p^n)` for any `n` such that `f(n) ≠ 0`. -/
noncomputable def val_aux (f : pre_tilt K v O hv p) : ℝ≥0 :=
if h : ∃ n, coeff _ _ n f ≠ 0
then mod_p.pre_val K v O hv p (coeff _ _ (nat.find h) f) ^ (p ^ nat.find h)
else 0
variables {K v O hv p}
lemma coeff_nat_find_add_ne_zero {f : pre_tilt K v O hv p} {h : ∃ n, coeff _ _ n f ≠ 0} (k : ℕ) :
coeff _ _ (nat.find h + k) f ≠ 0 :=
coeff_add_ne_zero (nat.find_spec h) k
lemma val_aux_eq {f : pre_tilt K v O hv p} {n : ℕ} (hfn : coeff _ _ n f ≠ 0) :
val_aux K v O hv p f = mod_p.pre_val K v O hv p (coeff _ _ n f) ^ (p ^ n) :=
begin
have h : ∃ n, coeff _ _ n f ≠ 0 := ⟨n, hfn⟩,
rw [val_aux, dif_pos h],
obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le (nat.find_min' h hfn),
induction k with k ih, { refl },
obtain ⟨x, hx⟩ := ideal.quotient.mk_surjective (coeff _ _ (nat.find h + k + 1) f),
have h1 : (ideal.quotient.mk _ x : mod_p K v O hv p) ≠ 0 := hx.symm ▸ hfn,
have h2 : (ideal.quotient.mk _ (x ^ p) : mod_p K v O hv p) ≠ 0,
by { erw [ring_hom.map_pow, hx, ← ring_hom.map_pow, coeff_pow_p],
exact coeff_nat_find_add_ne_zero k },
erw [ih (coeff_nat_find_add_ne_zero k), ← hx, ← coeff_pow_p, ring_hom.map_pow, ← hx,
← ring_hom.map_pow, mod_p.pre_val_mk h1, mod_p.pre_val_mk h2,
ring_hom.map_pow, v.map_pow, ← pow_mul, pow_succ], refl
end
lemma val_aux_zero : val_aux K v O hv p 0 = 0 :=
dif_neg $ λ ⟨n, hn⟩, hn rfl
lemma val_aux_one : val_aux K v O hv p 1 = 1 :=
(val_aux_eq $ show coeff (mod_p K v O hv p) p 0 1 ≠ 0, from one_ne_zero).trans $
by { rw [pow_zero, pow_one, ring_hom.map_one, ← (ideal.quotient.mk _).map_one, mod_p.pre_val_mk,
ring_hom.map_one, v.map_one], exact @one_ne_zero (mod_p K v O hv p) _ _ }
lemma val_aux_mul (f g : pre_tilt K v O hv p) :
val_aux K v O hv p (f * g) = val_aux K v O hv p f * val_aux K v O hv p g :=
begin
by_cases hf : f = 0, { rw [hf, zero_mul, val_aux_zero, zero_mul] },
by_cases hg : g = 0, { rw [hg, mul_zero, val_aux_zero, mul_zero] },
replace hf : ∃ n, coeff _ _ n f ≠ 0 := not_forall.1 (λ h, hf $ perfection.ext h),
replace hg : ∃ n, coeff _ _ n g ≠ 0 := not_forall.1 (λ h, hg $ perfection.ext h),
obtain ⟨m, hm⟩ := hf, obtain ⟨n, hn⟩ := hg,
replace hm := coeff_ne_zero_of_le hm (le_max_left m n),
replace hn := coeff_ne_zero_of_le hn (le_max_right m n),
have hfg : coeff _ _ (max m n + 1) (f * g) ≠ 0,
{ rw ring_hom.map_mul, refine mod_p.mul_ne_zero_of_pow_p_ne_zero _ _;
rw [← ring_hom.map_pow, coeff_pow_p]; assumption },
rw [val_aux_eq (coeff_add_ne_zero hm 1), val_aux_eq (coeff_add_ne_zero hn 1), val_aux_eq hfg],
rw ring_hom.map_mul at hfg ⊢, rw [mod_p.pre_val_mul hfg, mul_pow]
end
lemma val_aux_add (f g : pre_tilt K v O hv p) :
val_aux K v O hv p (f + g) ≤ max (val_aux K v O hv p f) (val_aux K v O hv p g) :=
begin
by_cases hf : f = 0, { rw [hf, zero_add, val_aux_zero, max_eq_right], exact zero_le _ },
by_cases hg : g = 0, { rw [hg, add_zero, val_aux_zero, max_eq_left], exact zero_le _ },
by_cases hfg : f + g = 0, { rw [hfg, val_aux_zero], exact zero_le _ },
replace hf : ∃ n, coeff _ _ n f ≠ 0 := not_forall.1 (λ h, hf $ perfection.ext h),
replace hg : ∃ n, coeff _ _ n g ≠ 0 := not_forall.1 (λ h, hg $ perfection.ext h),
replace hfg : ∃ n, coeff _ _ n (f + g) ≠ 0 := not_forall.1 (λ h, hfg $ perfection.ext h),
obtain ⟨m, hm⟩ := hf, obtain ⟨n, hn⟩ := hg, obtain ⟨k, hk⟩ := hfg,
replace hm := coeff_ne_zero_of_le hm (le_trans (le_max_left m n) (le_max_left _ k)),
replace hn := coeff_ne_zero_of_le hn (le_trans (le_max_right m n) (le_max_left _ k)),
replace hk := coeff_ne_zero_of_le hk (le_max_right (max m n) k),
rw [val_aux_eq hm, val_aux_eq hn, val_aux_eq hk, ring_hom.map_add],
cases le_max_iff.1
(mod_p.pre_val_add (coeff _ _ (max (max m n) k) f) (coeff _ _ (max (max m n) k) g)) with h h,
{ exact le_max_of_le_left (canonically_ordered_comm_semiring.pow_le_pow_of_le_left h _) },
{ exact le_max_of_le_right (canonically_ordered_comm_semiring.pow_le_pow_of_le_left h _) }
end
variables (K v O hv p)
/-- The valuation `Perfection(O/(p)) → ℝ≥0`.
Given `f ∈ Perfection(O/(p))`, if `f = 0` then output `0`;
otherwise output `pre_val(f(n))^(p^n)` for any `n` such that `f(n) ≠ 0`. -/
noncomputable def val : valuation (pre_tilt K v O hv p) ℝ≥0 :=
{ to_fun := val_aux K v O hv p,
map_one' := val_aux_one,
map_mul' := val_aux_mul,
map_zero' := val_aux_zero,
map_add' := val_aux_add }
variables {K v O hv p}
lemma map_eq_zero {f : pre_tilt K v O hv p} : val K v O hv p f = 0 ↔ f = 0 :=
begin
by_cases hf0 : f = 0, { rw hf0, exact iff_of_true (valuation.map_zero _) rfl },
obtain ⟨n, hn⟩ : ∃ n, coeff _ _ n f ≠ 0 := not_forall.1 (λ h, hf0 $ perfection.ext h),
show val_aux K v O hv p f = 0 ↔ f = 0, refine iff_of_false (λ hvf, hn _) hf0,
rw val_aux_eq hn at hvf, replace hvf := pow_eq_zero hvf, rwa mod_p.pre_val_eq_zero at hvf
end
end classical
instance : integral_domain (pre_tilt K v O hv p) :=
{ exists_pair_ne := (char_p.nontrivial_of_char_ne_one hp.1.ne_one).1,
eq_zero_or_eq_zero_of_mul_eq_zero := λ f g hfg,
by { simp_rw ← map_eq_zero at hfg ⊢, contrapose! hfg, rw valuation.map_mul,
exact mul_ne_zero hfg.1 hfg.2 },
.. (infer_instance : comm_ring (pre_tilt K v O hv p)) }
end pre_tilt
/-- The tilt of a field, as defined in Perfectoid Spaces by Peter Scholze, as in
[scholze2011perfectoid]. Given a field `K` with valuation `K → ℝ≥0` and ring of integers `O`,
this is implemented as the fraction field of the perfection of `O/(p)`. -/
@[nolint has_inhabited_instance] def tilt :=
fraction_ring (pre_tilt K v O hv p)
namespace tilt
noncomputable instance : field (tilt K v O hv p) :=
fraction_ring.field
end tilt
end perfectoid
|
dba1da24c2678ec5e6d9c08e762dd14f8220cfe1 | 453dcd7c0d1ef170b0843a81d7d8caedc9741dce | /algebra/order_functions.lean | 416181a29a9cfec7dc76eb28fd87e05193defa39 | [
"Apache-2.0"
] | permissive | amswerdlow/mathlib | 9af77a1f08486d8fa059448ae2d97795bd12ec0c | 27f96e30b9c9bf518341705c99d641c38638dfd0 | refs/heads/master | 1,585,200,953,598 | 1,534,275,532,000 | 1,534,275,532,000 | 144,564,700 | 0 | 0 | null | 1,534,156,197,000 | 1,534,156,197,000 | null | UTF-8 | Lean | false | false | 6,676 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import algebra.ordered_group order.lattice
open lattice
universes u v
variables {α : Type u} {β : Type v}
section
variables [decidable_linear_order α] [decidable_linear_order β] {f : α → β} {a b c d : α}
-- translate from lattices to linear orders (sup → max, inf → min)
lemma le_min_iff : c ≤ min a b ↔ c ≤ a ∧ c ≤ b := le_inf_iff
lemma max_le_iff : max a b ≤ c ↔ a ≤ c ∧ b ≤ c := sup_le_iff
lemma max_le_max : a ≤ c → b ≤ d → max a b ≤ max c d := sup_le_sup
lemma min_le_min : a ≤ c → b ≤ d → min a b ≤ min c d := inf_le_inf
lemma le_max_left_of_le : a ≤ b → a ≤ max b c := le_sup_left_of_le
lemma le_max_right_of_le : a ≤ c → a ≤ max b c := le_sup_right_of_le
lemma min_le_left_of_le : a ≤ c → min a b ≤ c := inf_le_left_of_le
lemma min_le_right_of_le : b ≤ c → min a b ≤ c := inf_le_right_of_le
lemma max_min_distrib_left : max a (min b c) = min (max a b) (max a c) := sup_inf_left
lemma max_min_distrib_right : max (min a b) c = min (max a c) (max b c) := sup_inf_right
lemma min_max_distrib_left : min a (max b c) = max (min a b) (min a c) := inf_sup_left
lemma min_max_distrib_right : min (max a b) c = max (min a c) (min b c) := inf_sup_right
instance max_idem : is_idempotent α max := by apply_instance
instance min_idem : is_idempotent α min := by apply_instance
lemma min_le_iff : min a b ≤ c ↔ a ≤ c ∨ b ≤ c :=
have a ≤ b → (a ≤ c ∨ b ≤ c ↔ a ≤ c),
from assume h, or_iff_left_of_imp $ le_trans h,
have b ≤ a → (a ≤ c ∨ b ≤ c ↔ b ≤ c),
from assume h, or_iff_right_of_imp $ le_trans h,
by cases le_total a b; simp [*, min_eq_left, min_eq_right]
lemma le_max_iff : a ≤ max b c ↔ a ≤ b ∨ a ≤ c :=
have b ≤ c → (a ≤ b ∨ a ≤ c ↔ a ≤ c),
from assume h, or_iff_right_of_imp $ assume h', le_trans h' h,
have c ≤ b → (a ≤ b ∨ a ≤ c ↔ a ≤ b),
from assume h, or_iff_left_of_imp $ assume h', le_trans h' h,
by cases le_total b c; simp [*, max_eq_left, max_eq_right]
lemma max_lt_iff : max a b < c ↔ (a < c ∧ b < c) :=
by rw [lt_iff_not_ge]; simp [(≥), le_max_iff, not_or_distrib]
lemma lt_min_iff : a < min b c ↔ (a < b ∧ a < c) :=
by rw [lt_iff_not_ge]; simp [(≥), min_le_iff, not_or_distrib]
lemma lt_max_iff : a < max b c ↔ a < b ∨ a < c :=
by rw [lt_iff_not_ge]; simp [(≥), max_le_iff, not_and_distrib]
lemma min_lt_iff : min a b < c ↔ a < c ∨ b < c :=
by rw [lt_iff_not_ge]; simp [(≥), le_min_iff, not_and_distrib]
theorem min_right_comm (a b c : α) : min (min a b) c = min (min a c) b :=
right_comm min min_comm min_assoc a b c
theorem max.left_comm (a b c : α) : max a (max b c) = max b (max a c) :=
left_comm max max_comm max_assoc a b c
theorem max.right_comm (a b c : α) : max (max a b) c = max (max a c) b :=
right_comm max max_comm max_assoc a b c
lemma max_distrib_of_monotone (hf : monotone f) : f (max a b) = max (f a) (f b) :=
by cases le_total a b; simp [max_eq_right, max_eq_left, h, hf h]
lemma min_distrib_of_monotone (hf : monotone f) : f (min a b) = min (f a) (f b) :=
by cases le_total a b; simp [min_eq_right, min_eq_left, h, hf h]
theorem min_choice (a b : α) : min a b = a ∨ min a b = b :=
by by_cases h : a ≤ b; simp [min, h]
theorem max_choice (a b : α) : max a b = a ∨ max a b = b :=
by by_cases h : a ≤ b; simp [max, h]
end
section decidable_linear_ordered_comm_group
variables [decidable_linear_ordered_comm_group α] {a b c : α}
attribute [simp] abs_zero abs_neg
def abs_add := @abs_add_le_abs_add_abs
theorem abs_le : abs a ≤ b ↔ - b ≤ a ∧ a ≤ b :=
⟨assume h, ⟨neg_le_of_neg_le $ le_trans (neg_le_abs_self _) h, le_trans (le_abs_self _) h⟩,
assume ⟨h₁, h₂⟩, abs_le_of_le_of_neg_le h₂ $ neg_le_of_neg_le h₁⟩
lemma abs_lt : abs a < b ↔ - b < a ∧ a < b :=
⟨assume h, ⟨neg_lt_of_neg_lt $ lt_of_le_of_lt (neg_le_abs_self _) h, lt_of_le_of_lt (le_abs_self _) h⟩,
assume ⟨h₁, h₂⟩, abs_lt_of_lt_of_neg_lt h₂ $ neg_lt_of_neg_lt h₁⟩
lemma abs_sub_le_iff : abs (a - b) ≤ c ↔ a - b ≤ c ∧ b - a ≤ c :=
by rw [abs_le, neg_le_sub_iff_le_add, @sub_le_iff_le_add' _ _ b, and_comm]
lemma abs_sub_lt_iff : abs (a - b) < c ↔ a - b < c ∧ b - a < c :=
by rw [abs_lt, neg_lt_sub_iff_lt_add, @sub_lt_iff_lt_add' _ _ b, and_comm]
def sub_abs_le_abs_sub := @abs_sub_abs_le_abs_sub
lemma abs_abs_sub_le_abs_sub (a b : α) : abs (abs a - abs b) ≤ abs (a - b) :=
abs_sub_le_iff.2 ⟨sub_abs_le_abs_sub _ _, by rw abs_sub; apply sub_abs_le_abs_sub⟩
lemma abs_eq (hb : b ≥ 0) : abs a = b ↔ a = b ∨ a = -b :=
iff.intro
begin
cases le_total a 0 with a_nonpos a_nonneg,
{ rw [abs_of_nonpos a_nonpos, neg_eq_iff_neg_eq, eq_comm], exact or.inr },
{ rw [abs_of_nonneg a_nonneg, eq_comm], exact or.inl }
end
(by intro h; cases h; subst h; try { rw abs_neg }; exact abs_of_nonneg hb)
@[simp] lemma abs_eq_zero : abs a = 0 ↔ a = 0 :=
⟨eq_zero_of_abs_eq_zero, λ e, e.symm ▸ abs_zero⟩
lemma abs_pos_iff {a : α} : 0 < abs a ↔ a ≠ 0 :=
⟨λ h, mt abs_eq_zero.2 (ne_of_gt h), abs_pos_of_ne_zero⟩
lemma abs_le_max_abs_abs (hab : a ≤ b) (hbc : b ≤ c) : abs b ≤ max (abs a) (abs c) :=
abs_le_of_le_of_neg_le
(by simp [le_max_iff, le_trans hbc (le_abs_self c)])
(by simp [le_max_iff, le_trans (neg_le_neg hab) (neg_le_abs_self a)])
end decidable_linear_ordered_comm_group
section decidable_linear_ordered_comm_ring
variables [decidable_linear_ordered_comm_ring α] {a b c d : α}
@[simp] lemma abs_one : abs (1 : α) = 1 := abs_of_pos zero_lt_one
lemma monotone_mul_of_nonneg (ha : 0 ≤ a) : monotone (λ x, a*x) :=
assume b c b_le_c, mul_le_mul_of_nonneg_left b_le_c ha
lemma mul_max_of_nonneg (b c : α) (ha : 0 ≤ a) : a * max b c = max (a * b) (a * c) :=
max_distrib_of_monotone (monotone_mul_of_nonneg ha)
lemma mul_min_of_nonneg (b c : α) (ha : 0 ≤ a) : a * min b c = min (a * b) (a * c) :=
min_distrib_of_monotone (monotone_mul_of_nonneg ha)
lemma max_mul_mul_le_max_mul_max (b c : α) (ha : 0 ≤ a) (hd: 0 ≤ d) :
max (a * b) (d * c) ≤ max a c * max d b :=
have ba : b * a ≤ max d b * max c a,
from mul_le_mul (le_max_right d b) (le_max_right c a) ha (le_trans hd (le_max_left d b)),
have cd : c * d ≤ max a c * max b d,
from mul_le_mul (le_max_right a c) (le_max_right b d) hd (le_trans ha (le_max_left a c)),
max_le
(by simpa [mul_comm, max_comm] using ba)
(by simpa [mul_comm, max_comm] using cd)
end decidable_linear_ordered_comm_ring
|
bfee8cdd662474299a3290eb0d9e67bf61313f66 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/non_exhaustive_error.lean | 6a0622b7866c56092a73d82e38d61d6a7f26b2c3 | [
"Apache-2.0"
] | permissive | leanprover-community/lean | 12b87f69d92e614daea8bcc9d4de9a9ace089d0e | cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0 | refs/heads/master | 1,687,508,156,644 | 1,684,951,104,000 | 1,684,951,104,000 | 169,960,991 | 457 | 107 | Apache-2.0 | 1,686,744,372,000 | 1,549,790,268,000 | C++ | UTF-8 | Lean | false | false | 658 | lean | --
def g : ℕ × ℕ → ℕ
| (0, n) := n
| (m+2, 0) := m
definition f : string → nat → bool
| "hello world" 1 := tt
| "bye" _ := tt
def foo (y : ℕ) : ℕ → ℕ → ℕ
| 0 a := a
| (x+1) 0 := 3 + foo x 10
| (x+1) (n+2) := 42
namespace other
mutual def f, g
with f : nat → nat → nat
| 0 0 := 1
with g : nat → nat → nat
| 0 0 := 1
end other
inductive term | mk : ℕ → list term → term
def const_name : term → ℕ
| (term.mk n []) := n
namespace other2
def f : nat → nat
| 1000 := 1
def g : string → nat
| "hello" := 0
meta def h : name → nat
| `eq := 0
def r : int → nat
| -1000 := 0
end other2
|
bc04f6302cab36e3410d502e894d463fec21f116 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/analysis/complex/isometry.lean | f28b06bd52e84bc68e7ecdf871d7cb6d997b3005 | [
"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 | 6,462 | lean | /-
Copyright (c) 2021 François Sunatori. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: François Sunatori
-/
import analysis.complex.circle
import linear_algebra.determinant
import linear_algebra.general_linear_group
/-!
# Isometries of the Complex Plane
The lemma `linear_isometry_complex` states the classification of isometries in the complex plane.
Specifically, isometries with rotations but without translation.
The proof involves:
1. creating a linear isometry `g` with two fixed points, `g(0) = 0`, `g(1) = 1`
2. applying `linear_isometry_complex_aux` to `g`
The proof of `linear_isometry_complex_aux` is separated in the following parts:
1. show that the real parts match up: `linear_isometry.re_apply_eq_re`
2. show that I maps to either I or -I
3. every z is a linear combination of a + b * I
## References
* [Isometries of the Complex Plane](http://helmut.knaust.info/mediawiki/images/b/b5/Iso.pdf)
-/
noncomputable theory
open complex
open_locale complex_conjugate
local notation `|` x `|` := complex.abs x
/-- An element of the unit circle defines a `linear_isometry_equiv` from `ℂ` to itself, by
rotation. -/
def rotation : circle →* (ℂ ≃ₗᵢ[ℝ] ℂ) :=
{ to_fun := λ a,
{ norm_map' := λ x, show |a * x| = |x|, by rw [complex.abs_mul, abs_coe_circle, one_mul],
..distrib_mul_action.to_linear_equiv ℝ ℂ a },
map_one' := linear_isometry_equiv.ext $ one_smul _,
map_mul' := λ _ _, linear_isometry_equiv.ext $ mul_smul _ _ }
@[simp] lemma rotation_apply (a : circle) (z : ℂ) : rotation a z = a * z := rfl
lemma rotation_ne_conj_lie (a : circle) : rotation a ≠ conj_lie :=
begin
intro h,
have h1 : rotation a 1 = conj 1 := linear_isometry_equiv.congr_fun h 1,
have hI : rotation a I = conj I := linear_isometry_equiv.congr_fun h I,
rw [rotation_apply, ring_hom.map_one, mul_one] at h1,
rw [rotation_apply, conj_I, ← neg_one_mul, mul_left_inj' I_ne_zero, h1, eq_neg_self_iff] at hI,
exact one_ne_zero hI,
end
/-- Takes an element of `ℂ ≃ₗᵢ[ℝ] ℂ` and checks if it is a rotation, returns an element of the
unit circle. -/
@[simps]
def rotation_of (e : ℂ ≃ₗᵢ[ℝ] ℂ) : circle :=
⟨(e 1) / complex.abs (e 1), by simp⟩
@[simp]
lemma rotation_of_rotation (a : circle) : rotation_of (rotation a) = a :=
subtype.ext $ by simp
lemma rotation_injective : function.injective rotation :=
function.left_inverse.injective rotation_of_rotation
lemma linear_isometry.re_apply_eq_re_of_add_conj_eq (f : ℂ →ₗᵢ[ℝ] ℂ)
(h₃ : ∀ z, z + conj z = f z + conj (f z)) (z : ℂ) : (f z).re = z.re :=
by simpa [ext_iff, add_re, add_im, conj_re, conj_im, ←two_mul,
(show (2 : ℝ) ≠ 0, by simp [two_ne_zero'])] using (h₃ z).symm
lemma linear_isometry.im_apply_eq_im_or_neg_of_re_apply_eq_re {f : ℂ →ₗᵢ[ℝ] ℂ}
(h₂ : ∀ z, (f z).re = z.re) (z : ℂ) :
(f z).im = z.im ∨ (f z).im = -z.im :=
begin
have h₁ := f.norm_map z,
simp only [complex.abs, norm_eq_abs] at h₁,
rwa [real.sqrt_inj (norm_sq_nonneg _) (norm_sq_nonneg _), norm_sq_apply (f z), norm_sq_apply z,
h₂, add_left_cancel_iff, mul_self_eq_mul_self_iff] at h₁,
end
lemma linear_isometry.im_apply_eq_im {f : ℂ →ₗᵢ[ℝ] ℂ} (h : f 1 = 1) (z : ℂ) :
z + conj z = f z + conj (f z) :=
begin
have : ∥f z - 1∥ = ∥z - 1∥ := by rw [← f.norm_map (z - 1), f.map_sub, h],
apply_fun λ x, x ^ 2 at this,
simp only [norm_eq_abs, ←norm_sq_eq_abs] at this,
rw [←of_real_inj, ←mul_conj, ←mul_conj] at this,
rw [ring_hom.map_sub, ring_hom.map_sub] at this,
simp only [sub_mul, mul_sub, one_mul, mul_one] at this,
rw [mul_conj, norm_sq_eq_abs, ←norm_eq_abs, linear_isometry.norm_map] at this,
rw [mul_conj, norm_sq_eq_abs, ←norm_eq_abs] at this,
simp only [sub_sub, sub_right_inj, mul_one, of_real_pow, ring_hom.map_one, norm_eq_abs] at this,
simp only [add_sub, sub_left_inj] at this,
rw [add_comm, ←this, add_comm],
end
lemma linear_isometry.re_apply_eq_re {f : ℂ →ₗᵢ[ℝ] ℂ} (h : f 1 = 1) (z : ℂ) : (f z).re = z.re :=
begin
apply linear_isometry.re_apply_eq_re_of_add_conj_eq,
intro z,
apply linear_isometry.im_apply_eq_im h,
end
lemma linear_isometry_complex_aux {f : ℂ ≃ₗᵢ[ℝ] ℂ} (h : f 1 = 1) :
f = linear_isometry_equiv.refl ℝ ℂ ∨ f = conj_lie :=
begin
have h0 : f I = I ∨ f I = -I,
{ have : |f I| = 1 := by simpa using f.norm_map complex.I,
simp only [ext_iff, ←and_or_distrib_left, neg_re, I_re, neg_im, neg_zero],
split,
{ rw ←I_re,
exact @linear_isometry.re_apply_eq_re f.to_linear_isometry h I, },
{ apply @linear_isometry.im_apply_eq_im_or_neg_of_re_apply_eq_re f.to_linear_isometry,
intro z, rw @linear_isometry.re_apply_eq_re f.to_linear_isometry h } },
refine h0.imp (λ h' : f I = I, _) (λ h' : f I = -I, _);
{ apply linear_isometry_equiv.to_linear_equiv_injective,
apply complex.basis_one_I.ext',
intros i,
fin_cases i; simp [h, h'] }
end
lemma linear_isometry_complex (f : ℂ ≃ₗᵢ[ℝ] ℂ) :
∃ a : circle, f = rotation a ∨ f = conj_lie.trans (rotation a) :=
begin
let a : circle := ⟨f 1, by simpa using f.norm_map 1⟩,
use a,
have : (f.trans (rotation a).symm) 1 = 1,
{ simpa using rotation_apply a⁻¹ (f 1) },
refine (linear_isometry_complex_aux this).imp (λ h₁, _) (λ h₂, _),
{ simpa using eq_mul_of_inv_mul_eq h₁ },
{ exact eq_mul_of_inv_mul_eq h₂ }
end
/-- The matrix representation of `rotation a` is equal to the conformal matrix
`![![re a, -im a], ![im a, re a]]`. -/
lemma to_matrix_rotation (a : circle) :
linear_map.to_matrix basis_one_I basis_one_I (rotation a).to_linear_equiv =
matrix.plane_conformal_matrix (re a) (im a) (by simp [pow_two, ←norm_sq_apply]) :=
begin
ext i j,
simp [linear_map.to_matrix_apply],
fin_cases i; fin_cases j; simp
end
/-- The determinant of `rotation` (as a linear map) is equal to `1`. -/
@[simp] lemma det_rotation (a : circle) : ((rotation a).to_linear_equiv : ℂ →ₗ[ℝ] ℂ).det = 1 :=
begin
rw [←linear_map.det_to_matrix basis_one_I, to_matrix_rotation, matrix.det_fin_two],
simp [←norm_sq_apply]
end
/-- The determinant of `rotation` (as a linear equiv) is equal to `1`. -/
@[simp] lemma linear_equiv_det_rotation (a : circle) : (rotation a).to_linear_equiv.det = 1 :=
by rw [←units.eq_iff, linear_equiv.coe_det, det_rotation, units.coe_one]
|
cd44efc02f333f49e1259a92c623a432e026cfbb | 205f0fc16279a69ea36e9fd158e3a97b06834ce2 | /EXAMS/exam1-practice.lean | 2654d120baf4a0886ea414f8683215e4ffb17c63 | [] | 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 | 7,852 | lean | /-***************-/
/- ** BASICS ** --/
/-***************-/
/-
#
Write a defintion of x as a value of
type nat having the specific value 0.
Be sure it type-checks.
-/
def x : nat := 0
def x' := 0
/-
#
Write a definition of f as a function
of type ℕ → ℕ that returns the square of
the value to which it is applied (i.e.,
that it is given as an argument)
-/
def square' (n : nat) : nat := n^2
#check square'
def square : ℕ → ℕ := λ n : nat, n^2
/-
#
Write a definition of a function, nt, that
takes any proposition, P, and that returns
the proposition, P → false.
-/
def nt (P : Prop) : Prop := P → false
#check nt
def isZero (n : nat) : Prop := 0 = n
#reduce isZero 3
/-
#
What is the type of this function? Hint:
Use #check to check it.
-/
/-****************************************-/
/- ** PROOFS OF EQUALITY PROPOSITIONS ** --/
/-****************************************-/
/-
#1
Write a function, teqt, that takes any type,
T : Type, and any value, t : T, and that
returns a proof of t = t.
-/
def teqt (T : Type) (t: T) := eq.refl t
def teqt' : ∀ (T : Type), ∀ (t : T), (t = t) :=
λ X x, eq.refl x
def teqt'' (T : Type) := λ t : T, t = t
#check teqt''
#check teqt
/-
#2a
Write a function that takes any type, T; three values,
a, b, and c, of type T; a proof of a = b; and a proof
of b = c; and that returns a proof of c = a. We give
you most of the answer. Replace the sorry with your
answer.
-/
def aBbCCa : ∀ (T : Type), ∀ (a b c: T),
(a = b) -> (b = c) → (c = a) :=
λ X a b c ab bc,
eq.symm (eq.trans ab bc)
-- This is equivalent
def aBbCCa''
{ T : Type }
(a b c : T)
(ab : a = b)
(bc: b = c) :
(c = a)
:=
begin
have ac := eq.trans ab bc,
show c = a,
from eq.symm ac
end
/-
#2b.
Define aBbCCa' to be the same function, but specify
its type using ∀ and → connectives, and then provide
the function value using a lambda expression (λ). So
you will start with "def", then the name, then a :,
then the proposition, starting with ∀ and ending with
→ (c = a), followed by :=, and finally follwed by a
lambda expression.
-/
def aBbCCa' :
∀ T : Type, ∀ a b c : T, (a = b) → (b = c) → (c = a) :=
λ T a b c ab bc,
eq.symm (eq.trans ab bc)
/-*******************************-/
/- ** PROOFS OF CONJUNCTIONS ** --/
/-*******************************-/
/-
We assume P Q and R are propositions using the
following "variables" declaration. That means that
we can use P, Q, R, and S in the following theorems
without having to use ∀ P Q R S : Prop to introduce
them again for each individual proposition.
-/
variables P Q R S : Prop
/-
Prove the following propositions by completing
the definitions (replace sorrys with your answers).
-/
theorem t1 : P → Q → R → P :=
λ p q r, p
#check t1
theorem t2 : Q → (Q ∧ Q) :=
λ (q : Q), and.intro q q
theorem t3 : (P ∧ Q) ∧ (Q ∧ R) → (P ∧ R) :=
begin
assume pqqr : (P ∧ Q) ∧ (Q ∧ R),
have pq : P ∧ Q := pqqr.left,
have qr := pqqr.right,
have p := pq.left,
have r := qr.right,
apply and.intro p r
end
/- This is a shorter version!
λ pqqr : ((P ∧ Q) ∧ (Q ∧ R)),
and.intro (pqqr.left.left) pqqr.right.right
-/
/-*******************************-/
/- ** PROOFS OF IMPLICATIONS ** --/
/-*******************************-/
/-
Prove the following theorem. It claims that
implication is transitive (which it is).
-/
theorem t4 : ((P → Q) ∧ P) → Q :=
λ pqp, pqp.left pqp.right
theorem t5 :
(P → Q) → (Q → R) → (R → S) → (P → S) :=
λ pq qr rs,
λ p, rs (qr (pq p))
/-******************-/
/- ** Functions ** --/
/-******************-/
/-
Complete the following definition
with a value that makes the definition
type-check. You can answer with a
lambda expression. You can also
use a tactic script if you prefer.
-/
def n2n : ℕ → ℕ :=
λ n, 0
/-
Define a function called double
that takes any natural number, n,
and returns two times n.
-/
def double : ℕ → ℕ := λ n, 2 * n
/-
Write a test case for double
in the form of a theorem called
d15is30, that asserts that the
double of 15 is 30, and prove it.
-/
theorem d15is30 : double 15 = 30 := rfl
/-
Write a function, sum3, that takes three
natural numbers, a, b, c, and that returns
the sum of a, b, and c. Use a λ expression
to express the function.
-/
def sum' :=
λ (a b c : nat), a + b + c
-- Your answer here
/-*****************-/
/- ** NEGATION ** --/
/-*****************-/
/-
You already know that double
negation elimination requires
classical reasoning (using the
law of the excluded middle).
Give a proof of the following
proposition, which asserts that
it's valid to introduce double
negatations. Note: You do not
need the law of the excluded
middle to prove it.
-/
def t6 : P → ¬ ¬ P :=
λ p np, np p
/-
You've learned a few important
proof strategies. Explain in a
few words when might a proof
by negation be attempted, and
how one proceeds to use it.
Know the answer to the same
question about a proof by
contradiction.
-/
/-
Explain precisely why using a
proof by contradiction relies
on classical reasoning using
the law of the excluded middle.
-/
/-
EXTRA CREDIT: Write a function
that takes a function, f, of type
ℕ → ℕ, and that returns a function
that, for any value, n, returns
one more that what f returns.
-/
/-
That's the end of the practice test.
Here's a partial inventory of inference
rules we've covered. and related concepts.
This is not enough material for a complete
review. Reread all the notes and work any
problems that you're not yet sure you know
how to solve.
-/
/-
Partial inventory of inference rules.
* Equality
-- eq.refl : given a type T and a value t : T, derives a proof of t = t
-- eq.symm : given a type T, values a b : T, and a proof of a = b, derives a proof of b = a
-- eq.trans : given a type T, values a b c : T, and proofs of a = b and b = c, derives a proof of a = c
* Conjunction
-- and.intro : given propositions, P Q : Prop, a proof P : P, and a proof q : Q, derives a proof of P ∧ Q
-- and.elim_right : given propositions, P Q : Prop and a proof pq : P ∧ Q, derives a proof of P
-- and.elim_right : given propositions, P Q : Prop and a proof pq : P ∧ Q, derives a proof of Q
* Implication
-- → introduction: given P Q : Prop and a derivation of a proof Q from a proof of P, conclude P → Q
-- note : a derivation of a proof of Q from a proof of P is given as a function of type P → Q
-- → elimination: given propositions, P and Q, a proof of P → Q, and a proof of P, derive a proof of Q
-- note that → elimination is both a formal version of Aristotle's modus ponens rule and function application
* Negation
-- introduction : given a proposition P and a proof of P → false, conclude ¬ P
-- elimination
---- in constructive logic, showing that a proposition, ¬ P, is false proves only ¬ ¬ P, not that P is true
---- try to derive a proof of P from the assumption of a proof for ¬ ¬ P and you will see the problem
---- you can read ¬ ¬ P as "there's no proof of ¬ P," or as "¬ P is false,"
---- classical logic adds the axiom of the excluded middle (AEM), stating that ∀ P : Prop, P ∨ ¬ P
---- if you accept this axiom and you know that ¬ P is false, then P must be true
---- the AEM enables ¬ elimination
---- given a proposition P and a proof of ¬ P → false (of ¬ ¬ P), derive a proof of P
* Forall
-- introduction : to prove ∀ p : P, Q, where P is a type and Q is a proposition that can involve be written in terms of p, show that Q holds for an any arbitrarily assumed value, p, of type P
-- elimination : given a proof of ∀ p : P, Q, and a specific value x : P, conclude Q
-/ |
cd0ca06cf6207aa29d48e41b3c541acc538bd0e7 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/linear_algebra/finsupp.lean | 93d32abc4829870c45fdd8f098fa8a8572e172ea | [
"Apache-2.0"
] | permissive | gebner/mathlib | eab0150cc4f79ec45d2016a8c21750244a2e7ff0 | cc6a6edc397c55118df62831e23bfbd6e6c6b4ab | refs/heads/master | 1,625,574,853,976 | 1,586,712,827,000 | 1,586,712,827,000 | 99,101,412 | 1 | 0 | Apache-2.0 | 1,586,716,389,000 | 1,501,667,958,000 | Lean | UTF-8 | Lean | false | false | 17,126 | 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 finite support `α →₀ M`.
-/
import data.monoid_algebra linear_algebra.basic
noncomputable theory
open set linear_map submodule
open_locale classical
namespace finsupp
variables {α : Type*} {M : Type*} {R : Type*}
variables [ring R] [add_comm_group M] [module R M]
def lsingle (a : α) : M →ₗ[R] (α →₀ M) :=
⟨single a, assume a b, single_add, assume c b, (smul_single _ _ _).symm⟩
def lapply (a : α) : (α →₀ M) →ₗ[R] M := ⟨λg, g a, assume a b, rfl, assume a b, rfl⟩
section lsubtype_domain
variables (s : set α)
def lsubtype_domain : (α →₀ M) →ₗ[R] (s →₀ M) :=
⟨subtype_domain (λx, x ∈ s), assume a b, subtype_domain_add, assume c a, ext $ assume a, rfl⟩
lemma lsubtype_domain_apply (f : α →₀ M) :
(lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)) f = subtype_domain (λx, x ∈ s) f := rfl
end lsubtype_domain
@[simp] lemma lsingle_apply (a : α) (b : M) : (lsingle a : M →ₗ[R] (α →₀ M)) b = single a b :=
rfl
@[simp] lemma lapply_apply (a : α) (f : α →₀ M) : (lapply a : (α →₀ M) →ₗ[R] M) f = f a :=
rfl
@[simp] lemma ker_lsingle (a : α) : (lsingle a : M →ₗ[R] (α →₀ M)).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 : M →ₗ[R] (α →₀ M)).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 : (α →₀ M) →ₗ[R] M)) ≤ ⊥ :=
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 : M →ₗ[R] (α →₀ M)).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 : M →ₗ[R] (α →₀ M)).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 M) (a : α) :
submodule.span R (single a '' s) = (submodule.span R s).map (lsingle a) :=
by rw ← span_image; refl
variables (M R)
def supported (s : set α) : submodule R (α →₀ M) :=
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
variables {M}
lemma mem_supported {s : set α} (p : α →₀ M) : p ∈ (supported M R s) ↔ ↑p.support ⊆ s :=
iff.rfl
lemma mem_supported' {s : set α} (p : α →₀ M) :
p ∈ supported M R s ↔ ∀ x ∉ s, p x = 0 :=
by haveI := classical.dec_pred (λ (x : α), x ∈ s);
simp [mem_supported, set.subset_def, not_imp_comm]
lemma single_mem_supported {s : set α} {a : α} (b : M) (h : a ∈ s) :
single a b ∈ supported M R s :=
set.subset.trans support_single_subset (set.singleton_subset_iff.2 h)
lemma supported_eq_span_single (s : set α) :
supported R R s = span R ((λ i, single i 1) '' s) :=
begin
refine (span_eq_of_le _ _ (le_def'.2 $ λ l hl, _)).symm,
{ rintro _ ⟨_, hp, rfl ⟩ , exact single_mem_supported R 1 hp },
{ rw ← l.sum_single,
refine sum_mem _ (λ i il, _),
convert @smul_mem R (α →₀ R) _ _ _ _ (single i 1) (l i) _,
{ simp },
apply subset_span,
apply set.mem_image_of_mem _ (hl il) }
end
variables (M R)
def restrict_dom (s : set α) : (α →₀ M) →ₗ supported M R s :=
linear_map.cod_restrict _
{ to_fun := filter (∈ s),
add := λ l₁ l₂, filter_add,
smul := λ a l, filter_smul }
(λ l, (mem_supported' _ _).2 $ λ x, filter_apply_neg (∈ s) l)
variables {M R}
section
set_option class.instance_max_depth 50
@[simp] theorem restrict_dom_apply (s : set α) (l : α →₀ M) :
((restrict_dom M R s : (α →₀ M) →ₗ supported M R s) l : α →₀ M) = finsupp.filter (∈ s) l := rfl
end
theorem restrict_dom_comp_subtype (s : set α) :
(restrict_dom M R s).comp (submodule.subtype _) = linear_map.id :=
begin
ext l,
apply subtype.coe_ext.2,
simp,
ext a,
by_cases a ∈ s,
{ simp [h] },
{ rw [filter_apply_neg (λ x, x ∈ s) _ h],
exact ((mem_supported' R l.1).1 l.2 a h).symm }
end
theorem range_restrict_dom (s : set α) :
(restrict_dom M R s).range = ⊤ :=
begin
have := linear_map.range_comp (submodule.subtype _) (restrict_dom M R s),
rw [restrict_dom_comp_subtype, linear_map.range_id] at this,
exact eq_top_mono (submodule.map_mono le_top) this.symm
end
theorem supported_mono {s t : set α} (st : s ⊆ t) :
supported M R s ≤ supported M R t :=
λ l h, set.subset.trans h st
@[simp] theorem supported_empty : supported M R (∅ : set α) = ⊥ :=
eq_bot_iff.2 $ λ l h, (submodule.mem_bot R).2 $
by ext; simp [*, mem_supported'] at *
@[simp] theorem supported_univ : supported M R (set.univ : set α) = ⊤ :=
eq_top_iff.2 $ λ l _, set.subset_univ _
theorem supported_Union {δ : Type*} (s : δ → set α) :
supported M R (⋃ i, s i) = ⨆ i, supported M R (s i) :=
begin
refine le_antisymm _ (supr_le $ λ i, supported_mono $ set.subset_Union _ _),
haveI := classical.dec_pred (λ x, x ∈ (⋃ i, s i)),
suffices : ((submodule.subtype _).comp (restrict_dom M R (⋃ i, s i))).range ≤ ⨆ i, supported M R (s i),
{ rwa [linear_map.range_comp, range_restrict_dom, map_top, range_subtype] at this },
rw [range_le_iff_comap, eq_top_iff],
rintro l ⟨⟩, rw mem_coe,
apply finsupp.induction l, {exact zero_mem _},
refine λ x a l hl a0, add_mem _ _,
haveI := classical.dec_pred (λ x, ∃ i, x ∈ s i),
by_cases (∃ i, x ∈ s i); simp [h],
{ cases h with i hi,
exact le_supr (λ i, supported M R (s i)) i (single_mem_supported R _ hi) },
{ rw filter_single_of_neg,
{ simp },
{ exact h } }
end
theorem supported_union (s t : set α) :
supported M R (s ∪ t) = supported M R s ⊔ supported M R t :=
by erw [set.union_eq_Union, supported_Union, supr_bool_eq]; refl
theorem supported_Inter {ι : Type*} (s : ι → set α) :
supported M R (⋂ i, s i) = ⨅ i, supported M R (s i) :=
begin
refine le_antisymm (le_infi $ λ i, supported_mono $ set.Inter_subset _ _) _,
simp [le_def, infi_coe, set.subset_def],
exact λ l, set.subset_Inter
end
section
set_option class.instance_max_depth 37
def supported_equiv_finsupp (s : set α) :
(supported M R s) ≃ₗ[R] (s →₀ M) :=
(restrict_support_equiv s).to_linear_equiv
begin
show is_linear_map R ((lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)).comp
(submodule.subtype (supported M R s))),
exact linear_map.is_linear _
end
end
def lsum (f : α → R →ₗ[R] M) : (α →₀ R) →ₗ[R] M :=
⟨λ d, d.sum (λ i, f i),
assume d₁ d₂, by simp [sum_add_index],
assume a d, by simp [sum_smul_index, smul_sum, -smul_eq_mul, smul_eq_mul.symm]⟩
@[simp] theorem lsum_apply (f : α → R →ₗ[R] M) (l : α →₀ R) :
(finsupp.lsum f : (α →₀ R) →ₗ M) l = l.sum (λ b, f b) := rfl
section lmap_domain
variables {α' : Type*} {α'' : Type*} (M R)
def lmap_domain (f : α → α') : (α →₀ M) →ₗ[R] (α' →₀ M) :=
⟨map_domain f, assume a b, map_domain_add, map_domain_smul⟩
@[simp] theorem lmap_domain_apply (f : α → α') (l : α →₀ M) :
(lmap_domain M R f : (α →₀ M) →ₗ[R] (α' →₀ M)) l = map_domain f l := rfl
@[simp] theorem lmap_domain_id : (lmap_domain M R id : (α →₀ M) →ₗ[R] α →₀ M) = linear_map.id :=
linear_map.ext $ λ l, map_domain_id
theorem lmap_domain_comp (f : α → α') (g : α' → α'') :
lmap_domain M R (g ∘ f) = (lmap_domain M R g).comp (lmap_domain M R f) :=
linear_map.ext $ λ l, map_domain_comp
theorem supported_comap_lmap_domain (f : α → α') (s : set α') :
supported M R (f ⁻¹' s) ≤ (supported M R s).comap (lmap_domain M R f) :=
λ l (hl : ↑l.support ⊆ f ⁻¹' s),
show ↑(map_domain f l).support ⊆ s, begin
rw [← set.image_subset_iff, ← finset.coe_image] at hl,
exact set.subset.trans map_domain_support hl
end
theorem lmap_domain_supported [nonempty α] (f : α → α') (s : set α) :
(supported M R s).map (lmap_domain M R f) = supported M R (f '' s) :=
begin
inhabit α,
refine le_antisymm (map_le_iff_le_comap.2 $
le_trans (supported_mono $ set.subset_preimage_image _ _)
(supported_comap_lmap_domain _ _ _ _)) _,
intros l hl,
refine ⟨(lmap_domain M R (function.inv_fun_on f s) : (α' →₀ M) →ₗ α →₀ M) l, λ x hx, _, _⟩,
{ rcases finset.mem_image.1 (map_domain_support hx) with ⟨c, hc, rfl⟩,
exact function.inv_fun_on_mem (by simpa using hl hc) },
{ rw [← linear_map.comp_apply, ← lmap_domain_comp],
refine (map_domain_congr $ λ c hc, _).trans map_domain_id,
exact function.inv_fun_on_eq (by simpa using hl hc) }
end
theorem lmap_domain_disjoint_ker (f : α → α') {s : set α}
(H : ∀ a b ∈ s, f a = f b → a = b) :
disjoint (supported M R s) (lmap_domain M R f).ker :=
begin
rintro l ⟨h₁, h₂⟩,
rw [mem_coe, mem_ker, lmap_domain_apply, map_domain] at h₂,
simp, ext x,
haveI := classical.dec_pred (λ x, x ∈ s),
by_cases xs : x ∈ s,
{ have : finsupp.sum l (λ a, finsupp.single (f a)) (f x) = 0, {rw h₂, refl},
rw [finsupp.sum_apply, finsupp.sum, finset.sum_eq_single x] at this,
{ simpa [finsupp.single_apply] },
{ intros y hy xy, simp [mt (H _ _ (h₁ hy) xs) xy] },
{ simp {contextual := tt} } },
{ by_contra h, exact xs (h₁ $ finsupp.mem_support_iff.2 h) }
end
end lmap_domain
section total
variables (α) {α' : Type*} (M) {M' : Type*} (R)
[add_comm_group M'] [module R M']
(v : α → M) {v' : α' → M'}
/-- Interprets (l : α →₀ R) as linear combination of the elements in the family (v : α → M) and
evaluates this linear combination. -/
protected def total : (α →₀ R) →ₗ M := finsupp.lsum (λ i, linear_map.id.smul_right (v i))
variables {α M v}
theorem total_apply (l : α →₀ R) :
finsupp.total α M R v l = l.sum (λ i a, a • v i) := rfl
@[simp] theorem total_single (c : R) (a : α) :
finsupp.total α M R v (single a c) = c • (v a) :=
by simp [total_apply, sum_single_index]
theorem total_range (h : function.surjective v) : (finsupp.total α M R v).range = ⊤ :=
begin
apply range_eq_top.2,
intros x,
apply exists.elim (h x),
exact λ i hi, ⟨single i 1, by simp [hi]⟩
end
lemma range_total : (finsupp.total α M R v).range = span R (range v) :=
begin
ext x,
split,
{ intros hx,
rw [linear_map.mem_range] at hx,
rcases hx with ⟨l, hl⟩,
rw ← hl,
rw finsupp.total_apply,
unfold finsupp.sum,
apply sum_mem (span R (range v)),
exact λ i hi, submodule.smul _ _ (subset_span (mem_range_self i)) },
{ apply span_le.2,
intros x hx,
rcases hx with ⟨i, hi⟩,
rw [mem_coe, linear_map.mem_range],
use finsupp.single i 1,
simp [hi] }
end
theorem lmap_domain_total (f : α → α') (g : M →ₗ[R] M') (h : ∀ i, g (v i) = v' (f i)) :
(finsupp.total α' M' R v').comp (lmap_domain R R f) = g.comp (finsupp.total α M R v) :=
by ext l; simp [total_apply, finsupp.sum_map_domain_index, add_smul, h]
theorem total_emb_domain (f : α ↪ α') (l : α →₀ R) :
(finsupp.total α' M' R v') (emb_domain f l) = (finsupp.total α M' R (v' ∘ f)) l :=
by simp [total_apply, finsupp.sum, support_emb_domain, emb_domain_apply]
theorem total_map_domain (f : α → α') (hf : function.injective f) (l : α →₀ R) :
(finsupp.total α' M' R v') (map_domain f l) = (finsupp.total α M' R (v' ∘ f)) l :=
begin
have : map_domain f l = emb_domain ⟨f, hf⟩ l,
{ rw emb_domain_eq_map_domain ⟨f, hf⟩,
refl },
rw this,
apply total_emb_domain R ⟨f, hf⟩ l
end
theorem span_eq_map_total (s : set α):
span R (v '' s) = submodule.map (finsupp.total α M R v) (supported R R s) :=
begin
apply span_eq_of_le,
{ intros x hx,
rw set.mem_image at hx,
apply exists.elim hx,
intros i hi,
exact ⟨_, finsupp.single_mem_supported R 1 hi.1, by simp [hi.2]⟩ },
{ refine map_le_iff_le_comap.2 (λ z hz, _),
have : ∀i, z i • v i ∈ span R (v '' s),
{ intro c,
haveI := classical.dec_pred (λ x, x ∈ s),
by_cases c ∈ s,
{ exact smul_mem _ _ (subset_span (set.mem_image_of_mem _ h)) },
{ simp [(finsupp.mem_supported' R _).1 hz _ h] } },
refine sum_mem _ _, simp [this] }
end
theorem mem_span_iff_total {s : set α} {x : M} :
x ∈ span R (v '' s) ↔ ∃ l ∈ supported R R s, finsupp.total α M R v l = x :=
by rw span_eq_map_total; simp
variables (α) (M) (v)
protected def total_on (s : set α) : supported R R s →ₗ[R] span R (v '' s) :=
linear_map.cod_restrict _ ((finsupp.total _ _ _ v).comp (submodule.subtype (supported R R s))) $
λ ⟨l, hl⟩, (mem_span_iff_total _).2 ⟨l, hl, rfl⟩
variables {α} {M} {v}
theorem total_on_range (s : set α) : (finsupp.total_on α M R v s).range = ⊤ :=
by rw [finsupp.total_on, linear_map.range, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap,
range_subtype, map_top, linear_map.range_comp, range_subtype]; exact le_of_eq (span_eq_map_total _ _)
theorem total_comp (f : α' → α) :
(finsupp.total α' M R (v ∘ f)) = (finsupp.total α M R v).comp (lmap_domain R R f) :=
begin
ext l,
simp [total_apply],
rw sum_map_domain_index; simp [add_smul],
end
lemma total_comap_domain
(f : α → α') (l : α' →₀ R) (hf : set.inj_on f (f ⁻¹' l.support.to_set)) :
finsupp.total α M R v (finsupp.comap_domain f l hf) = (l.support.preimage hf).sum (λ i, (l (f i)) • (v i)) :=
by rw finsupp.total_apply; refl
end total
protected def dom_lcongr
{α₁ : Type*} {α₂ : Type*} (e : α₁ ≃ α₂) :
(α₁ →₀ M) ≃ₗ[R] (α₂ →₀ M) :=
(finsupp.dom_congr e).to_linear_equiv
begin
change is_linear_map R (lmap_domain M R e : (α₁ →₀ M) →ₗ[R] (α₂ →₀ M)),
exact linear_map.is_linear _
end
noncomputable def congr {α' : Type*} (s : set α) (t : set α') (e : s ≃ t) :
supported M R s ≃ₗ[R] supported M R t :=
begin
haveI := classical.dec_pred (λ x, x ∈ s),
haveI := classical.dec_pred (λ x, x ∈ t),
refine linear_equiv.trans (finsupp.supported_equiv_finsupp s)
(linear_equiv.trans _ (finsupp.supported_equiv_finsupp t).symm),
exact finsupp.dom_lcongr e
end
end finsupp
variables {R : Type*} {M : Type*} {N : Type*}
variables [ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N]
lemma linear_map.map_finsupp_total
(f : M →ₗ[R] N) {ι : Type*} {g : ι → M} (l : ι →₀ R) :
f (finsupp.total ι M R g l) = finsupp.total ι N R (f ∘ g) l :=
by simp only [finsupp.total_apply, finsupp.total_apply, finsupp.sum, f.map_sum, f.map_smul]
lemma submodule.exists_finset_of_mem_supr
{ι : Sort*} (p : ι → submodule R M) {m : M} (hm : m ∈ ⨆ i, p i) :
∃ s : finset ι, m ∈ ⨆ i ∈ s, p i :=
begin
obtain ⟨f, hf, rfl⟩ : ∃ f ∈ finsupp.supported R R (⋃ i, ↑(p i)), finsupp.total M M R id f = m,
{ have aux : (id : M → M) '' (⋃ (i : ι), ↑(p i)) = (⋃ (i : ι), ↑(p i)) := set.image_id _,
rwa [supr_eq_span, ← aux, finsupp.mem_span_iff_total R] at hm },
let t : finset M := f.support,
have ht : ∀ x : {x // x ∈ t}, ∃ i, ↑x ∈ p i,
{ intros x,
rw finsupp.mem_supported at hf,
specialize hf x.2,
rwa set.mem_Union at hf },
choose g hg using ht,
let s : finset ι := finset.univ.image g,
use s,
simp only [mem_supr, supr_le_iff],
assume N hN,
rw [finsupp.total_apply, finsupp.sum, ← submodule.mem_coe],
apply is_add_submonoid.finset_sum_mem,
assume x hx,
apply submodule.smul_mem,
let i : ι := g ⟨x, hx⟩,
have hi : i ∈ s, { rw finset.mem_image, exact ⟨⟨x, hx⟩, finset.mem_univ _, rfl⟩ },
exact hN i hi (hg _),
end
|
f051d575723a004bb815bbb0578e4df84df82b59 | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/ring_theory/adjoin_root.lean | 46c99fa0da797ea84462cdedf3a09006715d4a3f | [
"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 | 3,418 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Chris Hughes
Adjoining roots of polynomials
-/
import data.polynomial ring_theory.principal_ideal_domain
noncomputable theory
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
open polynomial ideal
def adjoin_root [comm_ring α] (f : polynomial α) : Type u :=
ideal.quotient (span {f} : ideal (polynomial α))
namespace adjoin_root
section comm_ring
variables [comm_ring α] (f : polynomial α)
instance : comm_ring (adjoin_root f) := ideal.quotient.comm_ring _
instance : decidable_eq (adjoin_root f) := classical.dec_eq _
variable {f}
def mk : polynomial α → adjoin_root f := ideal.quotient.mk _
def root : adjoin_root f := mk X
def of (x : α) : adjoin_root f := mk (C x)
instance adjoin_root.has_coe_t : has_coe_t α (adjoin_root f) := ⟨of⟩
instance mk.is_ring_hom : is_ring_hom (mk : polynomial α → adjoin_root f) :=
ideal.quotient.is_ring_hom_mk _
@[simp] lemma mk_self : (mk f : adjoin_root f) = 0 :=
quotient.sound' (mem_span_singleton.2 $ by simp)
instance : is_ring_hom (coe : α → adjoin_root f) :=
@is_ring_hom.comp _ _ _ _ C _ _ _ mk mk.is_ring_hom
lemma eval₂_root (f : polynomial α) : f.eval₂ coe (root : adjoin_root f) = 0 :=
quotient.induction_on' (root : adjoin_root f)
(λ (g : polynomial α) (hg : mk g = mk X),
show finsupp.sum f (λ (e : ℕ) (a : α), mk (C a) * mk g ^ e) = 0,
by simp only [hg, (is_semiring_hom.map_pow (mk : polynomial α → adjoin_root f) _ _).symm,
(is_ring_hom.map_mul (mk : polynomial α → adjoin_root f)).symm];
rw [finsupp.sum, finset.sum_hom (mk : polynomial α → adjoin_root f),
show finset.sum _ _ = _, from sum_C_mul_X_eq _, mk_self])
(show (root : adjoin_root f) = mk X, from rfl)
lemma is_root_root (f : polynomial α) : is_root (f.map coe) (root : adjoin_root f) :=
by rw [is_root, eval_map, eval₂_root]
variables [comm_ring β]
def lift (i : α → β) [is_ring_hom i] (x : β) (h : f.eval₂ i x = 0) : (adjoin_root f) → β :=
ideal.quotient.lift _ (eval₂ i x) $ λ g H,
begin
simp [mem_span_singleton] at H,
cases H with y H,
rw [H, eval₂_mul],
simp [h]
end
variables {i : α → β} [is_ring_hom i] {a : β} {h : f.eval₂ i a = 0}
@[simp] lemma lift_mk {g : polynomial α} : lift i a h (mk g) = g.eval₂ i a :=
ideal.quotient.lift_mk
@[simp] lemma lift_root : lift i a h root = a := by simp [root, h]
@[simp] lemma lift_of {x : α} : lift i a h x = i x :=
by show lift i a h (ideal.quotient.mk _ (C x)) = i x;
convert ideal.quotient.lift_mk; simp
instance is_ring_hom_lift : is_ring_hom (lift i a h) :=
by unfold lift; apply_instance
end comm_ring
variables [discrete_field α] {f : polynomial α} [irreducible f]
instance is_maximal_span : is_maximal (span {f} : ideal (polynomial α)) :=
principal_ideal_domain.is_maximal_of_irreducible ‹irreducible f›
noncomputable instance field : discrete_field (adjoin_root f) :=
ideal.quotient.field (span {f} : ideal (polynomial α))
lemma coe_injective : function.injective (coe : α → adjoin_root f) :=
is_ring_hom.injective _
lemma mul_div_root_cancel (f : polynomial α) [irreducible f] :
(X - C (root : adjoin_root f)) * (f.map coe / (X - C root)) = f.map coe :=
mul_div_eq_iff_is_root.2 $ is_root_root _
end adjoin_root
|
b672624eee9e364987b71a26701ba42832f42e24 | 77c5b91fae1b966ddd1db969ba37b6f0e4901e88 | /src/algebra/lie/submodule.lean | 981f2fa1dd92424b47289d8ddad4b8fefd8827fa | [
"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 | 33,387 | lean | /-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import algebra.lie.subalgebra
import ring_theory.noetherian
/-!
# Lie submodules of a Lie algebra
In this file we define Lie submodules and Lie ideals, we construct the lattice structure on Lie
submodules and we use it to define various important operations, notably the Lie span of a subset
of a Lie module.
## Main definitions
* `lie_submodule`
* `lie_submodule.well_founded_of_noetherian`
* `lie_submodule.lie_span`
* `lie_submodule.map`
* `lie_submodule.comap`
* `lie_ideal`
* `lie_ideal.map`
* `lie_ideal.comap`
## Tags
lie algebra, lie submodule, lie ideal, lattice structure
-/
universes u v w w₁ w₂
section lie_submodule
variables (R : Type u) (L : Type v) (M : Type w)
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M]
variables [lie_ring_module L M] [lie_module R L M]
set_option old_structure_cmd true
/-- A Lie submodule of a Lie module is a submodule that is closed under the Lie bracket.
This is a sufficient condition for the subset itself to form a Lie module. -/
structure lie_submodule extends submodule R M :=
(lie_mem : ∀ {x : L} {m : M}, m ∈ carrier → ⁅x, m⁆ ∈ carrier)
attribute [nolint doc_blame] lie_submodule.to_submodule
namespace lie_submodule
variables {R L M} (N N' : lie_submodule R L M)
/-- The zero module is a Lie submodule of any Lie module. -/
instance : has_zero (lie_submodule R L M) :=
⟨{ lie_mem := λ x m h, by { rw ((submodule.mem_bot R).1 h), apply lie_zero, },
..(0 : submodule R M)}⟩
instance : inhabited (lie_submodule R L M) := ⟨0⟩
instance coe_submodule : has_coe (lie_submodule R L M) (submodule R M) := ⟨to_submodule⟩
@[norm_cast]
lemma coe_to_submodule : ((N : submodule R M) : set M) = N := rfl
instance has_mem : has_mem M (lie_submodule R L M) := ⟨λ x N, x ∈ (N : set M)⟩
@[simp] lemma mem_carrier {x : M} : x ∈ N.carrier ↔ x ∈ (N : set M) :=
iff.rfl
@[simp] lemma mem_mk_iff (S : set M) (h₁ h₂ h₃ h₄) {x : M} :
x ∈ (⟨S, h₁, h₂, h₃, h₄⟩ : lie_submodule R L M) ↔ x ∈ S :=
iff.rfl
@[simp] lemma mem_coe_submodule {x : M} : x ∈ (N : submodule R M) ↔ x ∈ N := iff.rfl
lemma mem_coe {x : M} : x ∈ (N : set M) ↔ x ∈ N := iff.rfl
@[simp] lemma zero_mem : (0 : M) ∈ N := (N : submodule R M).zero_mem
@[simp] lemma coe_to_set_mk (S : set M) (h₁ h₂ h₃ h₄) :
((⟨S, h₁, h₂, h₃, h₄⟩ : lie_submodule R L M) : set M) = S := rfl
@[simp] lemma coe_to_submodule_mk (p : submodule R M) (h) :
(({lie_mem := h, ..p} : lie_submodule R L M) : submodule R M) = p :=
by { cases p, refl, }
@[ext] lemma ext (h : ∀ m, m ∈ N ↔ m ∈ N') : N = N' :=
by { cases N, cases N', simp only [], ext m, exact h m, }
@[simp] lemma coe_to_submodule_eq_iff : (N : submodule R M) = (N' : submodule R M) ↔ N = N' :=
begin
split; intros h,
{ ext, rw [← mem_coe_submodule, h], simp, },
{ rw h, },
end
/-- Copy of a lie_submodule with a new `carrier` equal to the old one. Useful to fix definitional
equalities. -/
protected def copy (s : set M) (hs : s = ↑N) : lie_submodule R L M :=
{ carrier := s,
zero_mem' := hs.symm ▸ N.zero_mem',
add_mem' := hs.symm ▸ N.add_mem',
smul_mem' := hs.symm ▸ N.smul_mem',
lie_mem := hs.symm ▸ N.lie_mem, }
instance : lie_ring_module L N :=
{ bracket := λ (x : L) (m : N), ⟨⁅x, m.val⁆, N.lie_mem m.property⟩,
add_lie := by { intros x y m, apply set_coe.ext, apply add_lie, },
lie_add := by { intros x m n, apply set_coe.ext, apply lie_add, },
leibniz_lie := by { intros x y m, apply set_coe.ext, apply leibniz_lie, }, }
instance : lie_module R L N :=
{ lie_smul := by { intros t x y, apply set_coe.ext, apply lie_smul, },
smul_lie := by { intros t x y, apply set_coe.ext, apply smul_lie, }, }
@[simp, norm_cast] lemma coe_zero : ((0 : N) : M) = (0 : M) := rfl
@[simp, norm_cast] lemma coe_add (m m' : N) : (↑(m + m') : M) = (m : M) + (m' : M) := rfl
@[simp, norm_cast] lemma coe_neg (m : N) : (↑(-m) : M) = -(m : M) := rfl
@[simp, norm_cast] lemma coe_sub (m m' : N) : (↑(m - m') : M) = (m : M) - (m' : M) := rfl
@[simp, norm_cast] lemma coe_smul (t : R) (m : N) : (↑(t • m) : M) = t • (m : M) := rfl
@[simp, norm_cast] lemma coe_bracket (x : L) (m : N) : (↑⁅x, m⁆ : M) = ⁅x, ↑m⁆ := rfl
end lie_submodule
section lie_ideal
variables (L)
/-- An ideal of a Lie algebra is a Lie submodule of the Lie algebra as a Lie module over itself. -/
abbreviation lie_ideal := lie_submodule R L L
lemma lie_mem_right (I : lie_ideal R L) (x y : L) (h : y ∈ I) : ⁅x, y⁆ ∈ I := I.lie_mem h
lemma lie_mem_left (I : lie_ideal R L) (x y : L) (h : x ∈ I) : ⁅x, y⁆ ∈ I :=
by { rw [←lie_skew, ←neg_lie], apply lie_mem_right, assumption, }
/-- An ideal of a Lie algebra is a Lie subalgebra. -/
def lie_ideal_subalgebra (I : lie_ideal R L) : lie_subalgebra R L :=
{ lie_mem' := by { intros x y hx hy, apply lie_mem_right, exact hy, },
..I.to_submodule, }
instance : has_coe (lie_ideal R L) (lie_subalgebra R L) := ⟨λ I, lie_ideal_subalgebra R L I⟩
@[norm_cast] lemma lie_ideal.coe_to_subalgebra (I : lie_ideal R L) :
((I : lie_subalgebra R L) : set L) = I := rfl
@[norm_cast] lemma lie_ideal.coe_to_lie_subalgebra_to_submodule (I : lie_ideal R L) :
((I : lie_subalgebra R L) : submodule R L) = I := rfl
end lie_ideal
variables {R M}
lemma submodule.exists_lie_submodule_coe_eq_iff (p : submodule R M) :
(∃ (N : lie_submodule R L M), ↑N = p) ↔ ∀ (x : L) (m : M), m ∈ p → ⁅x, m⁆ ∈ p :=
begin
split,
{ rintros ⟨N, rfl⟩, exact N.lie_mem, },
{ intros h, use { lie_mem := h, ..p }, exact lie_submodule.coe_to_submodule_mk p _, },
end
namespace lie_subalgebra
variables {L}
/-- Given a Lie subalgebra `K ⊆ L`, if we view `L` as a `K`-module by restriction, it contains
a distinguished Lie submodule for the action of `K`, namely `K` itself. -/
def to_lie_submodule (K : lie_subalgebra R L) : lie_submodule R K L :=
{ lie_mem := λ x y hy, K.lie_mem x.property hy,
.. (K : submodule R L) }
@[simp] lemma coe_to_lie_submodule (K : lie_subalgebra R L) :
(K.to_lie_submodule : submodule R L) = K :=
rfl
@[simp] lemma mem_to_lie_submodule {K : lie_subalgebra R L} (x : L) :
x ∈ K.to_lie_submodule ↔ x ∈ K :=
iff.rfl
lemma exists_lie_ideal_coe_eq_iff (K : lie_subalgebra R L) :
(∃ (I : lie_ideal R L), ↑I = K) ↔ ∀ (x y : L), y ∈ K → ⁅x, y⁆ ∈ K :=
begin
simp only [← coe_to_submodule_eq_iff, lie_ideal.coe_to_lie_subalgebra_to_submodule,
submodule.exists_lie_submodule_coe_eq_iff L],
exact iff.rfl,
end
lemma exists_nested_lie_ideal_coe_eq_iff {K K' : lie_subalgebra R L} (h : K ≤ K') :
(∃ (I : lie_ideal R K'), ↑I = of_le h) ↔ ∀ (x y : L), x ∈ K' → y ∈ K → ⁅x, y⁆ ∈ K :=
begin
simp only [exists_lie_ideal_coe_eq_iff, coe_bracket, mem_of_le],
split,
{ intros h' x y hx hy, exact h' ⟨x, hx⟩ ⟨y, h hy⟩ hy, },
{ rintros h' ⟨x, hx⟩ ⟨y, hy⟩ hy', exact h' x y hx hy', },
end
end lie_subalgebra
end lie_submodule
namespace lie_submodule
variables {R : Type u} {L : Type v} {M : Type w}
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M]
variables [lie_ring_module L M] [lie_module R L M]
variables (N N' : lie_submodule R L M) (I J : lie_ideal R L)
section lattice_structure
open set
lemma coe_injective : function.injective (coe : lie_submodule R L M → set M) :=
λ N N' h, by { cases N, cases N', simp only, exact h, }
lemma coe_submodule_injective : function.injective (coe : lie_submodule R L M → submodule R M) :=
λ N N' h, by { ext, rw [← mem_coe_submodule, h], refl, }
instance : partial_order (lie_submodule R L M) :=
{ le := λ N N', ∀ ⦃x⦄, x ∈ N → x ∈ N', -- Overriding `le` like this gives a better defeq.
..partial_order.lift (coe : lie_submodule R L M → set M) coe_injective }
lemma le_def : N ≤ N' ↔ (N : set M) ⊆ N' := iff.rfl
@[simp, norm_cast] lemma coe_submodule_le_coe_submodule : (N : submodule R M) ≤ N' ↔ N ≤ N' :=
iff.rfl
instance : has_bot (lie_submodule R L M) := ⟨0⟩
@[simp] lemma bot_coe : ((⊥ : lie_submodule R L M) : set M) = {0} := rfl
@[simp] lemma bot_coe_submodule : ((⊥ : lie_submodule R L M) : submodule R M) = ⊥ := rfl
@[simp] lemma mem_bot (x : M) : x ∈ (⊥ : lie_submodule R L M) ↔ x = 0 := mem_singleton_iff
instance : has_top (lie_submodule R L M) :=
⟨{ lie_mem := λ x m h, mem_univ ⁅x, m⁆,
..(⊤ : submodule R M) }⟩
@[simp] lemma top_coe : ((⊤ : lie_submodule R L M) : set M) = univ := rfl
@[simp] lemma top_coe_submodule : ((⊤ : lie_submodule R L M) : submodule R M) = ⊤ := rfl
@[simp] lemma mem_top (x : M) : x ∈ (⊤ : lie_submodule R L M) := mem_univ x
instance : has_inf (lie_submodule R L M) :=
⟨λ N N', { lie_mem := λ x m h, mem_inter (N.lie_mem h.1) (N'.lie_mem h.2),
..(N ⊓ N' : submodule R M) }⟩
instance : has_Inf (lie_submodule R L M) :=
⟨λ S, { lie_mem := λ x m h, by
{ simp only [submodule.mem_carrier, mem_Inter, submodule.Inf_coe, mem_set_of_eq,
forall_apply_eq_imp_iff₂, exists_imp_distrib] at *,
intros N hN, apply N.lie_mem (h N hN), },
..Inf {(s : submodule R M) | s ∈ S} }⟩
@[simp] theorem inf_coe : (↑(N ⊓ N') : set M) = N ∩ N' := rfl
@[simp] lemma Inf_coe_to_submodule (S : set (lie_submodule R L M)) :
(↑(Inf S) : submodule R M) = Inf {(s : submodule R M) | s ∈ S} := rfl
@[simp] lemma Inf_coe (S : set (lie_submodule R L M)) : (↑(Inf S) : set M) = ⋂ s ∈ S, (s : set M) :=
begin
rw [← lie_submodule.coe_to_submodule, Inf_coe_to_submodule, submodule.Inf_coe],
ext m,
simpa only [mem_Inter, mem_set_of_eq, forall_apply_eq_imp_iff₂, exists_imp_distrib],
end
lemma Inf_glb (S : set (lie_submodule R L M)) : is_glb S (Inf S) :=
begin
have h : ∀ (N N' : lie_submodule R L M), (N : set M) ≤ N' ↔ N ≤ N', { intros, refl },
apply is_glb.of_image h,
simp only [Inf_coe],
exact is_glb_binfi
end
/-- The set of Lie submodules of a Lie module form a complete lattice.
We provide explicit values for the fields `bot`, `top`, `inf` to get more convenient definitions
than we would otherwise obtain from `complete_lattice_of_Inf`. -/
instance : complete_lattice (lie_submodule R L M) :=
{ bot := ⊥,
bot_le := λ N _ h, by { rw mem_bot at h, rw h, exact N.zero_mem', },
top := ⊤,
le_top := λ _ _ _, trivial,
inf := (⊓),
le_inf := λ N₁ N₂ N₃ h₁₂ h₁₃ m hm, ⟨h₁₂ hm, h₁₃ hm⟩,
inf_le_left := λ _ _ _, and.left,
inf_le_right := λ _ _ _, and.right,
..complete_lattice_of_Inf _ Inf_glb }
instance : add_comm_monoid (lie_submodule R L M) :=
{ add := (⊔),
add_assoc := λ _ _ _, sup_assoc,
zero := ⊥,
zero_add := λ _, bot_sup_eq,
add_zero := λ _, sup_bot_eq,
add_comm := λ _ _, sup_comm, }
@[simp] lemma add_eq_sup : N + N' = N ⊔ N' := rfl
@[norm_cast, simp] lemma sup_coe_to_submodule :
(↑(N ⊔ N') : submodule R M) = (N : submodule R M) ⊔ (N' : submodule R M) :=
begin
have aux : ∀ (x : L) m, m ∈ (N ⊔ N' : submodule R M) → ⁅x,m⁆ ∈ (N ⊔ N' : submodule R M),
{ simp only [submodule.mem_sup],
rintro x m ⟨y, hy, z, hz, rfl⟩,
refine ⟨⁅x, y⁆, N.lie_mem hy, ⁅x, z⁆, N'.lie_mem hz, (lie_add _ _ _).symm⟩ },
refine le_antisymm (Inf_le ⟨{ lie_mem := aux, ..(N ⊔ N' : submodule R M) }, _⟩) _,
{ simp only [exists_prop, and_true, mem_set_of_eq, eq_self_iff_true, coe_to_submodule_mk,
← coe_submodule_le_coe_submodule, and_self, le_sup_left, le_sup_right] },
{ simp, },
end
@[norm_cast, simp] lemma inf_coe_to_submodule :
(↑(N ⊓ N') : submodule R M) = (N : submodule R M) ⊓ (N' : submodule R M) := rfl
@[simp] lemma mem_inf (x : M) : x ∈ N ⊓ N' ↔ x ∈ N ∧ x ∈ N' :=
by rw [← mem_coe_submodule, ← mem_coe_submodule, ← mem_coe_submodule, inf_coe_to_submodule,
submodule.mem_inf]
lemma mem_sup (x : M) : x ∈ N ⊔ N' ↔ ∃ (y ∈ N) (z ∈ N'), y + z = x :=
by { rw [← mem_coe_submodule, sup_coe_to_submodule, submodule.mem_sup], exact iff.rfl, }
lemma eq_bot_iff : N = ⊥ ↔ ∀ (m : M), m ∈ N → m = 0 :=
by { rw eq_bot_iff, exact iff.rfl, }
-- TODO[gh-6025]: make this an instance once safe to do so
lemma subsingleton_of_bot : subsingleton (lie_submodule R L ↥(⊥ : lie_submodule R L M)) :=
begin
apply subsingleton_of_bot_eq_top,
ext ⟨x, hx⟩, change x ∈ ⊥ at hx, rw submodule.mem_bot at hx, subst hx,
simp only [true_iff, eq_self_iff_true, submodule.mk_eq_zero, lie_submodule.mem_bot],
end
instance : is_modular_lattice (lie_submodule R L M) :=
{ sup_inf_le_assoc_of_le := λ N₁ N₂ N₃,
by { simp only [← coe_submodule_le_coe_submodule, sup_coe_to_submodule, inf_coe_to_submodule],
exact is_modular_lattice.sup_inf_le_assoc_of_le ↑N₂, }, }
variables (R L M)
lemma well_founded_of_noetherian [is_noetherian R M] :
well_founded ((>) : lie_submodule R L M → lie_submodule R L M → Prop) :=
begin
let f : ((>) : lie_submodule R L M → lie_submodule R L M → Prop) →r
((>) : submodule R M → submodule R M → Prop) :=
{ to_fun := coe,
map_rel' := λ N N' h, h, },
apply f.well_founded, rw ← is_noetherian_iff_well_founded, apply_instance,
end
@[simp] lemma subsingleton_iff : subsingleton (lie_submodule R L M) ↔ subsingleton M :=
have h : subsingleton (lie_submodule R L M) ↔ subsingleton (submodule R M),
{ rw [← subsingleton_iff_bot_eq_top, ← subsingleton_iff_bot_eq_top, ← coe_to_submodule_eq_iff,
top_coe_submodule, bot_coe_submodule], },
h.trans $ submodule.subsingleton_iff R
@[simp] lemma nontrivial_iff : nontrivial (lie_submodule R L M) ↔ nontrivial M :=
not_iff_not.mp (
(not_nontrivial_iff_subsingleton.trans $ subsingleton_iff R L M).trans
not_nontrivial_iff_subsingleton.symm)
instance [nontrivial M] : nontrivial (lie_submodule R L M) := (nontrivial_iff R L M).mpr ‹_›
variables {R L M}
section inclusion_maps
/-- The inclusion of a Lie submodule into its ambient space is a morphism of Lie modules. -/
def incl : N →ₗ⁅R,L⁆ M :=
{ map_lie' := λ x m, rfl,
..submodule.subtype (N : submodule R M) }
@[simp] lemma incl_apply (m : N) : N.incl m = m := rfl
lemma incl_eq_val : (N.incl : N → M) = subtype.val := rfl
variables {N N'} (h : N ≤ N')
/-- Given two nested Lie submodules `N ⊆ N'`, the inclusion `N ↪ N'` is a morphism of Lie modules.-/
def hom_of_le : N →ₗ⁅R,L⁆ N' :=
{ map_lie' := λ x m, rfl,
..submodule.of_le h }
@[simp] lemma coe_hom_of_le (m : N) : (hom_of_le h m : M) = m := rfl
lemma hom_of_le_apply (m : N) : hom_of_le h m = ⟨m.1, h m.2⟩ := rfl
lemma hom_of_le_injective : function.injective (hom_of_le h) :=
λ x y, by simp only [hom_of_le_apply, imp_self, subtype.mk_eq_mk, set_like.coe_eq_coe,
subtype.val_eq_coe]
end inclusion_maps
section lie_span
variables (R L) (s : set M)
/-- The `lie_span` of a set `s ⊆ M` is the smallest Lie submodule of `M` that contains `s`. -/
def lie_span : lie_submodule R L M := Inf {N | s ⊆ N}
variables {R L s}
lemma mem_lie_span {x : M} : x ∈ lie_span R L s ↔ ∀ N : lie_submodule R L M, s ⊆ N → x ∈ N :=
by { change x ∈ (lie_span R L s : set M) ↔ _, erw Inf_coe, exact mem_bInter_iff, }
lemma subset_lie_span : s ⊆ lie_span R L s :=
by { intros m hm, erw mem_lie_span, intros N hN, exact hN hm, }
lemma submodule_span_le_lie_span : submodule.span R s ≤ lie_span R L s :=
by { rw submodule.span_le, apply subset_lie_span, }
lemma lie_span_le {N} : lie_span R L s ≤ N ↔ s ⊆ N :=
begin
split,
{ exact subset.trans subset_lie_span, },
{ intros hs m hm, rw mem_lie_span at hm, exact hm _ hs, },
end
lemma lie_span_mono {t : set M} (h : s ⊆ t) : lie_span R L s ≤ lie_span R L t :=
by { rw lie_span_le, exact subset.trans h subset_lie_span, }
lemma lie_span_eq : lie_span R L (N : set M) = N :=
le_antisymm (lie_span_le.mpr rfl.subset) subset_lie_span
lemma coe_lie_span_submodule_eq_iff {p : submodule R M} :
(lie_span R L (p : set M) : submodule R M) = p ↔ ∃ (N : lie_submodule R L M), ↑N = p :=
begin
rw p.exists_lie_submodule_coe_eq_iff L, split; intros h,
{ intros x m hm, rw [← h, mem_coe_submodule], exact lie_mem _ (subset_lie_span hm), },
{ rw [← coe_to_submodule_mk p h, coe_to_submodule, coe_to_submodule_eq_iff, lie_span_eq], },
end
variables (R L M)
/-- `lie_span` forms a Galois insertion with the coercion from `lie_submodule` to `set`. -/
protected def gi : galois_insertion (lie_span R L : set M → lie_submodule R L M) coe :=
{ choice := λ s _, lie_span R L s,
gc := λ s t, lie_span_le,
le_l_u := λ s, subset_lie_span,
choice_eq := λ s h, rfl }
@[simp] lemma span_empty : lie_span R L (∅ : set M) = ⊥ :=
(lie_submodule.gi R L M).gc.l_bot
@[simp] lemma span_univ : lie_span R L (set.univ : set M) = ⊤ :=
eq_top_iff.2 $ set_like.le_def.2 $ subset_lie_span
variables {M}
lemma span_union (s t : set M) : lie_span R L (s ∪ t) = lie_span R L s ⊔ lie_span R L t :=
(lie_submodule.gi R L M).gc.l_sup
lemma span_Union {ι} (s : ι → set M) : lie_span R L (⋃ i, s i) = ⨆ i, lie_span R L (s i) :=
(lie_submodule.gi R L M).gc.l_supr
end lie_span
end lattice_structure
end lie_submodule
section lie_submodule_map_and_comap
variables {R : Type u} {L : Type v} {L' : Type w₂} {M : Type w} {M' : Type w₁}
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L']
variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M]
variables [add_comm_group M'] [module R M'] [lie_ring_module L M'] [lie_module R L M']
namespace lie_submodule
variables (f : M →ₗ⁅R,L⁆ M') (N N₂ : lie_submodule R L M) (N' : lie_submodule R L M')
/-- A morphism of Lie modules `f : M → M'` pushes forward Lie submodules of `M` to Lie submodules
of `M'`. -/
def map : lie_submodule R L M' :=
{ lie_mem := λ x m' h, by
{ rcases h with ⟨m, hm, hfm⟩, use ⁅x, m⁆, split,
{ apply N.lie_mem hm, },
{ norm_cast at hfm, simp [hfm], }, },
..(N : submodule R M).map (f : M →ₗ[R] M') }
/-- A morphism of Lie modules `f : M → M'` pulls back Lie submodules of `M'` to Lie submodules of
`M`. -/
def comap : lie_submodule R L M :=
{ lie_mem := λ x m h, by { suffices : ⁅x, f m⁆ ∈ N', { simp [this], }, apply N'.lie_mem h, },
..(N' : submodule R M').comap (f : M →ₗ[R] M') }
variables {f N N₂ N'}
lemma map_le_iff_le_comap : map f N ≤ N' ↔ N ≤ comap f N' :=
set.image_subset_iff
variables (f)
lemma gc_map_comap : galois_connection (map f) (comap f) :=
λ N N', map_le_iff_le_comap
variables {f}
@[simp] lemma map_sup : (N ⊔ N₂).map f = N.map f ⊔ N₂.map f :=
(gc_map_comap f).l_sup
lemma mem_map (m' : M') : m' ∈ N.map f ↔ ∃ m, m ∈ N ∧ f m = m' :=
submodule.mem_map
@[simp] lemma mem_comap {m : M} : m ∈ comap f N' ↔ f m ∈ N' := iff.rfl
end lie_submodule
namespace lie_ideal
variables (f : L →ₗ⁅R⁆ L') (I I₂ : lie_ideal R L) (J : lie_ideal R L')
@[simp] lemma top_coe_lie_subalgebra : ((⊤ : lie_ideal R L) : lie_subalgebra R L) = ⊤ := rfl
/-- A morphism of Lie algebras `f : L → L'` pushes forward Lie ideals of `L` to Lie ideals of `L'`.
Note that unlike `lie_submodule.map`, we must take the `lie_span` of the image. Mathematically
this is because although `f` makes `L'` into a Lie module over `L`, in general the `L` submodules of
`L'` are not the same as the ideals of `L'`. -/
def map : lie_ideal R L' := lie_submodule.lie_span R L' $ (I : submodule R L).map (f : L →ₗ[R] L')
/-- A morphism of Lie algebras `f : L → L'` pulls back Lie ideals of `L'` to Lie ideals of `L`.
Note that `f` makes `L'` into a Lie module over `L` (turning `f` into a morphism of Lie modules)
and so this is a special case of `lie_submodule.comap` but we do not exploit this fact. -/
def comap : lie_ideal R L :=
{ lie_mem := λ x y h, by { suffices : ⁅f x, f y⁆ ∈ J, { simp [this], }, apply J.lie_mem h, },
..(J : submodule R L').comap (f : L →ₗ[R] L') }
@[simp] lemma map_coe_submodule (h : ↑(map f I) = f '' I) :
(map f I : submodule R L') = (I : submodule R L).map (f : L →ₗ[R] L') :=
by { rw [set_like.ext'_iff, lie_submodule.coe_to_submodule, h, submodule.map_coe], refl, }
@[simp] lemma comap_coe_submodule :
(comap f J : submodule R L) = (J : submodule R L').comap (f : L →ₗ[R] L') := rfl
lemma map_le : map f I ≤ J ↔ f '' I ⊆ J := lie_submodule.lie_span_le
variables {f I I₂ J}
lemma mem_map {x : L} (hx : x ∈ I) : f x ∈ map f I :=
by { apply lie_submodule.subset_lie_span, use x, exact ⟨hx, rfl⟩, }
@[simp] lemma mem_comap {x : L} : x ∈ comap f J ↔ f x ∈ J := iff.rfl
lemma map_le_iff_le_comap : map f I ≤ J ↔ I ≤ comap f J :=
by { rw map_le, exact set.image_subset_iff, }
variables (f)
lemma gc_map_comap : galois_connection (map f) (comap f) :=
λ I I', map_le_iff_le_comap
variables {f}
@[simp] lemma map_sup : (I ⊔ I₂).map f = I.map f ⊔ I₂.map f :=
(gc_map_comap f).l_sup
lemma map_comap_le : map f (comap f J) ≤ J :=
by { rw map_le_iff_le_comap, apply le_refl _, }
/-- See also `lie_ideal.map_comap_eq`. -/
lemma comap_map_le : I ≤ comap f (map f I) :=
by { rw ← map_le_iff_le_comap, apply le_refl _, }
@[mono] lemma map_mono : monotone (map f) :=
λ I₁ I₂ h,
by { rw lie_submodule.le_def at h, apply lie_submodule.lie_span_mono (set.image_subset ⇑f h), }
@[mono] lemma comap_mono : monotone (comap f) :=
λ J₁ J₂ h, by { rw lie_submodule.le_def at h ⊢, exact set.preimage_mono h, }
lemma map_of_image (h : f '' I = J) : I.map f = J :=
begin
apply le_antisymm,
{ erw [lie_submodule.lie_span_le, submodule.map_coe, h], },
{ rw [lie_submodule.le_def, ← h], exact lie_submodule.subset_lie_span, },
end
/-- Note that this is not a special case of `lie_submodule.subsingleton_of_bot`. Indeed, given
`I : lie_ideal R L`, in general the two lattices `lie_ideal R I` and `lie_submodule R L I` are
different (though the latter does naturally inject into the former).
In other words, in general, ideals of `I`, regarded as a Lie algebra in its own right, are not the
same as ideals of `L` contained in `I`. -/
-- TODO[gh-6025]: make this an instance once safe to do so
lemma subsingleton_of_bot : subsingleton (lie_ideal R ↥(⊥ : lie_ideal R L)) :=
begin
apply subsingleton_of_bot_eq_top,
ext ⟨x, hx⟩, change x ∈ ⊥ at hx, rw submodule.mem_bot at hx, subst hx,
simp only [true_iff, eq_self_iff_true, submodule.mk_eq_zero, lie_submodule.mem_bot],
end
end lie_ideal
namespace lie_hom
variables (f : L →ₗ⁅R⁆ L') (I : lie_ideal R L) (J : lie_ideal R L')
/-- The kernel of a morphism of Lie algebras, as an ideal in the domain. -/
def ker : lie_ideal R L := lie_ideal.comap f ⊥
/-- The range of a morphism of Lie algebras as an ideal in the codomain. -/
def ideal_range : lie_ideal R L' := lie_submodule.lie_span R L' f.range
lemma ideal_range_eq_lie_span_range :
f.ideal_range = lie_submodule.lie_span R L' f.range := rfl
lemma ideal_range_eq_map :
f.ideal_range = lie_ideal.map f ⊤ :=
by { ext, simp only [ideal_range, range_eq_map], refl }
/-- The condition that the image of a morphism of Lie algebras is an ideal. -/
def is_ideal_morphism : Prop := (f.ideal_range : lie_subalgebra R L') = f.range
@[simp] lemma is_ideal_morphism_def :
f.is_ideal_morphism ↔ (f.ideal_range : lie_subalgebra R L') = f.range := iff.rfl
lemma is_ideal_morphism_iff :
f.is_ideal_morphism ↔ ∀ (x : L') (y : L), ∃ (z : L), ⁅x, f y⁆ = f z :=
begin
simp only [is_ideal_morphism_def, ideal_range_eq_lie_span_range,
← lie_subalgebra.coe_to_submodule_eq_iff, ← f.range.coe_to_submodule,
lie_ideal.coe_to_lie_subalgebra_to_submodule, lie_submodule.coe_lie_span_submodule_eq_iff,
lie_subalgebra.mem_coe_submodule, mem_range, exists_imp_distrib,
submodule.exists_lie_submodule_coe_eq_iff],
split,
{ intros h x y, obtain ⟨z, hz⟩ := h x (f y) y rfl, use z, exact hz.symm, },
{ intros h x y z hz, obtain ⟨w, hw⟩ := h x z, use w, rw [← hw, hz], },
end
lemma range_subset_ideal_range : (f.range : set L') ⊆ f.ideal_range := lie_submodule.subset_lie_span
lemma map_le_ideal_range : I.map f ≤ f.ideal_range :=
begin
rw f.ideal_range_eq_map,
exact lie_ideal.map_mono le_top,
end
lemma ker_le_comap : f.ker ≤ J.comap f := lie_ideal.comap_mono bot_le
@[simp] lemma ker_coe_submodule : (ker f : submodule R L) = (f : L →ₗ[R] L').ker := rfl
@[simp] lemma mem_ker {x : L} : x ∈ ker f ↔ f x = 0 :=
show x ∈ (f.ker : submodule R L) ↔ _,
by simp only [ker_coe_submodule, linear_map.mem_ker, coe_to_linear_map]
lemma mem_ideal_range {x : L} : f x ∈ ideal_range f :=
begin
rw ideal_range_eq_map,
exact lie_ideal.mem_map (lie_submodule.mem_top x)
end
@[simp] lemma mem_ideal_range_iff (h : is_ideal_morphism f) {y : L'} :
y ∈ ideal_range f ↔ ∃ (x : L), f x = y :=
begin
rw f.is_ideal_morphism_def at h,
rw [← lie_submodule.mem_coe, ← lie_ideal.coe_to_subalgebra, h, f.range_coe, set.mem_range],
end
lemma le_ker_iff : I ≤ f.ker ↔ ∀ x, x ∈ I → f x = 0 :=
begin
split; intros h x hx,
{ specialize h hx, rw mem_ker at h, exact h, },
{ rw mem_ker, apply h x hx, },
end
lemma ker_eq_bot : f.ker = ⊥ ↔ function.injective f :=
by rw [← lie_submodule.coe_to_submodule_eq_iff, ker_coe_submodule, lie_submodule.bot_coe_submodule,
linear_map.ker_eq_bot, coe_to_linear_map]
@[simp] lemma range_coe_submodule : (f.range : submodule R L') = (f : L →ₗ[R] L').range := rfl
lemma range_eq_top : f.range = ⊤ ↔ function.surjective f :=
begin
rw [← lie_subalgebra.coe_to_submodule_eq_iff, range_coe_submodule,
lie_subalgebra.top_coe_submodule],
exact linear_map.range_eq_top,
end
@[simp] lemma ideal_range_eq_top_of_surjective (h : function.surjective f) : f.ideal_range = ⊤ :=
begin
rw ← f.range_eq_top at h,
rw [ideal_range_eq_lie_span_range, h, ← lie_subalgebra.coe_to_submodule,
← lie_submodule.coe_to_submodule_eq_iff, lie_submodule.top_coe_submodule,
lie_subalgebra.top_coe_submodule, lie_submodule.coe_lie_span_submodule_eq_iff],
use ⊤,
exact lie_submodule.top_coe_submodule,
end
lemma is_ideal_morphism_of_surjective (h : function.surjective f) : f.is_ideal_morphism :=
by rw [is_ideal_morphism_def, f.ideal_range_eq_top_of_surjective h, f.range_eq_top.mpr h,
lie_ideal.top_coe_lie_subalgebra]
end lie_hom
namespace lie_ideal
variables {f : L →ₗ⁅R⁆ L'} {I : lie_ideal R L} {J : lie_ideal R L'}
@[simp] lemma map_eq_bot_iff : I.map f = ⊥ ↔ I ≤ f.ker :=
by { rw ← le_bot_iff, exact lie_ideal.map_le_iff_le_comap }
lemma coe_map_of_surjective (h : function.surjective f) :
(I.map f : submodule R L') = (I : submodule R L).map (f : L →ₗ[R] L') :=
begin
let J : lie_ideal R L' :=
{ lie_mem := λ x y hy,
begin
have hy' : ∃ (x : L), x ∈ I ∧ f x = y, { simpa [hy], },
obtain ⟨z₂, hz₂, rfl⟩ := hy',
obtain ⟨z₁, rfl⟩ := h x,
simp only [lie_hom.coe_to_linear_map, set_like.mem_coe, set.mem_image,
lie_submodule.mem_coe_submodule, submodule.mem_carrier, submodule.map_coe],
use ⁅z₁, z₂⁆,
exact ⟨I.lie_mem hz₂, f.map_lie z₁ z₂⟩,
end,
..(I : submodule R L).map (f : L →ₗ[R] L'), },
erw lie_submodule.coe_lie_span_submodule_eq_iff,
use J,
apply lie_submodule.coe_to_submodule_mk,
end
lemma mem_map_of_surjective {y : L'} (h₁ : function.surjective f) (h₂ : y ∈ I.map f) :
∃ (x : I), f x = y :=
begin
rw [← lie_submodule.mem_coe_submodule, coe_map_of_surjective h₁, submodule.mem_map] at h₂,
obtain ⟨x, hx, rfl⟩ := h₂,
use ⟨x, hx⟩,
refl,
end
lemma bot_of_map_eq_bot {I : lie_ideal R L} (h₁ : function.injective f) (h₂ : I.map f = ⊥) :
I = ⊥ :=
begin
rw ← f.ker_eq_bot at h₁, change comap f ⊥ = ⊥ at h₁,
rw [eq_bot_iff, map_le_iff_le_comap, h₁] at h₂,
rw eq_bot_iff, exact h₂,
end
/-- Given two nested Lie ideals `I₁ ⊆ I₂`, the inclusion `I₁ ↪ I₂` is a morphism of Lie algebras. -/
def hom_of_le {I₁ I₂ : lie_ideal R L} (h : I₁ ≤ I₂) : I₁ →ₗ⁅R⁆ I₂ :=
{ map_lie' := λ x y, rfl,
..submodule.of_le h, }
@[simp] lemma coe_hom_of_le {I₁ I₂ : lie_ideal R L} (h : I₁ ≤ I₂) (x : I₁) :
(hom_of_le h x : L) = x := rfl
lemma hom_of_le_apply {I₁ I₂ : lie_ideal R L} (h : I₁ ≤ I₂) (x : I₁) :
hom_of_le h x = ⟨x.1, h x.2⟩ := rfl
lemma hom_of_le_injective {I₁ I₂ : lie_ideal R L} (h : I₁ ≤ I₂) :
function.injective (hom_of_le h) :=
λ x y, by simp only [hom_of_le_apply, imp_self, subtype.mk_eq_mk, set_like.coe_eq_coe,
subtype.val_eq_coe]
@[simp] lemma map_sup_ker_eq_map : lie_ideal.map f (I ⊔ f.ker) = lie_ideal.map f I :=
begin
suffices : lie_ideal.map f (I ⊔ f.ker) ≤ lie_ideal.map f I,
{ exact le_antisymm this (lie_ideal.map_mono le_sup_left), },
apply lie_submodule.lie_span_mono,
rintros x ⟨y, hy₁, hy₂⟩, rw ← hy₂,
erw lie_submodule.mem_sup at hy₁, obtain ⟨z₁, hz₁, z₂, hz₂, hy⟩ := hy₁, rw ← hy,
rw [f.coe_to_linear_map, f.map_add, f.mem_ker.mp hz₂, add_zero], exact ⟨z₁, hz₁, rfl⟩,
end
@[simp] lemma map_comap_eq (h : f.is_ideal_morphism) : map f (comap f J) = f.ideal_range ⊓ J :=
begin
apply le_antisymm,
{ rw le_inf_iff, exact ⟨f.map_le_ideal_range _, map_comap_le⟩, },
{ rw f.is_ideal_morphism_def at h,
rw [lie_submodule.le_def, lie_submodule.inf_coe, ← coe_to_subalgebra, h],
rintros y ⟨⟨x, h₁⟩, h₂⟩, rw ← h₁ at h₂ ⊢, exact mem_map h₂, },
end
@[simp] lemma comap_map_eq (h : ↑(map f I) = f '' I) : comap f (map f I) = I ⊔ f.ker :=
by rw [← lie_submodule.coe_to_submodule_eq_iff, comap_coe_submodule, I.map_coe_submodule f h,
lie_submodule.sup_coe_to_submodule, f.ker_coe_submodule, submodule.comap_map_eq]
variables (f I J)
/-- Regarding an ideal `I` as a subalgebra, the inclusion map into its ambient space is a morphism
of Lie algebras. -/
def incl : I →ₗ⁅R⁆ L := (I : lie_subalgebra R L).incl
@[simp] lemma incl_range : I.incl.range = I := (I : lie_subalgebra R L).incl_range
@[simp] lemma incl_apply (x : I) : I.incl x = x := rfl
@[simp] lemma incl_coe : (I.incl : I →ₗ[R] L) = (I : submodule R L).subtype := rfl
@[simp] lemma comap_incl_self : comap I.incl I = ⊤ :=
by { rw ← lie_submodule.coe_to_submodule_eq_iff, exact submodule.comap_subtype_self _, }
@[simp] lemma ker_incl : I.incl.ker = ⊥ :=
by rw [← lie_submodule.coe_to_submodule_eq_iff, I.incl.ker_coe_submodule,
lie_submodule.bot_coe_submodule, incl_coe, submodule.ker_subtype]
@[simp] lemma incl_ideal_range : I.incl.ideal_range = I :=
begin
rw [lie_hom.ideal_range_eq_lie_span_range, ← lie_subalgebra.coe_to_submodule,
← lie_submodule.coe_to_submodule_eq_iff, incl_range, coe_to_lie_subalgebra_to_submodule,
lie_submodule.coe_lie_span_submodule_eq_iff],
use I,
end
lemma incl_is_ideal_morphism : I.incl.is_ideal_morphism :=
begin
rw [I.incl.is_ideal_morphism_def, incl_ideal_range],
exact (I : lie_subalgebra R L).incl_range.symm,
end
end lie_ideal
end lie_submodule_map_and_comap
namespace lie_module_hom
variables {R : Type u} {L : Type v} {M : Type w} {N : Type w₁}
variables [comm_ring R] [lie_ring L] [lie_algebra R L]
variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M]
variables [add_comm_group N] [module R N] [lie_ring_module L N] [lie_module R L N]
variables (f : M →ₗ⁅R,L⁆ N)
/-- The range of a morphism of Lie modules `f : M → N` is a Lie submodule of `N`.
See Note [range copy pattern]. -/
def range : lie_submodule R L N :=
(lie_submodule.map f ⊤).copy (set.range f) set.image_univ.symm
@[simp] lemma coe_range : (f.range : set N) = set.range f := rfl
@[simp] lemma coe_submodule_range : (f.range : submodule R N) = (f : M →ₗ[R] N).range := rfl
@[simp] lemma mem_range (n : N) : n ∈ f.range ↔ ∃ m, f m = n :=
iff.rfl
lemma map_top : lie_submodule.map f ⊤ = f.range :=
by { ext, simp [lie_submodule.mem_map], }
end lie_module_hom
section top_equiv_self
variables {R : Type u} {L : Type v}
variables [comm_ring R] [lie_ring L] [lie_algebra R L]
/-- The natural equivalence between the 'top' Lie subalgebra and the enclosing Lie algebra. -/
def lie_subalgebra.top_equiv_self : (⊤ : lie_subalgebra R L) ≃ₗ⁅R⁆ L :=
{ inv_fun := λ x, ⟨x, set.mem_univ x⟩,
left_inv := λ x, by { ext, refl, },
right_inv := λ x, rfl,
..(⊤ : lie_subalgebra R L).incl, }
@[simp] lemma lie_subalgebra.top_equiv_self_apply (x : (⊤ : lie_subalgebra R L)) :
lie_subalgebra.top_equiv_self x = x := rfl
/-- The natural equivalence between the 'top' Lie ideal and the enclosing Lie algebra. -/
def lie_ideal.top_equiv_self : (⊤ : lie_ideal R L) ≃ₗ⁅R⁆ L :=
lie_subalgebra.top_equiv_self
@[simp] lemma lie_ideal.top_equiv_self_apply (x : (⊤ : lie_ideal R L)) :
lie_ideal.top_equiv_self x = x := rfl
end top_equiv_self
|
4c7bc1ab7d83b23ae6ab71f1d33dc7ac84805dc2 | 7b9ff28673cd3dd7dd3dcfe2ab8449f9244fe05a | /src/jesse/exercises-day-one.lean | a74ecc86ad00b712a554f199979ddef85e07056c | [] | no_license | jesse-michael-han/hanoi-lean-2019 | ea2f0e04f81093373c48447065765a964ee82262 | a5a9f368e394d563bfcc13e3773863924505b1ce | refs/heads/master | 1,591,320,223,247 | 1,561,022,886,000 | 1,561,022,886,000 | 192,264,820 | 1 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 4,847 | lean | open classical
/- Fill in the `sorry`s below -/
local attribute [instance, priority 0] prop_decidable
example (p : Prop) : p ∨ ¬ p :=
begin
by_cases p,
{ sorry },
{ sorry }
end
example (p : Prop) : p ∨ ¬ p :=
begin
by_cases h' : p,
{ sorry },
{ sorry }
end
/-
Give a calculational proof of the theorem log_mul below. You can use the
rewrite tactic `rw` (and `calc` if you want), but not `simp`.
These objects are actually defined in mathlib, but for now, we'll
just declare them.
-/
constant real : Type
@[instance] constant orreal : ordered_ring real
constants (log exp : real → real)
constant log_exp_eq : ∀ x, log (exp x) = x
constant exp_log_eq : ∀ {x}, x > 0 → exp (log x) = x
constant exp_pos : ∀ x, exp x > 0
constant exp_add : ∀ x y, exp (x + y) = exp x * exp y
example (x y z : real) :
exp (x + y + z) = exp x * exp y * exp z :=
sorry
example (y : real) (h : y > 0) : exp (log y) = y :=
sorry
theorem log_mul' {x y : real} (hx : x > 0) (hy : y > 0) :
log (x * y) = log x + log y :=
sorry
section
variables {p q r : Prop}
example : (p → q) → (¬q → ¬p) :=
sorry
example : (p → (q → r)) → (p ∧ q → r) :=
sorry
example : p ∧ ¬q → ¬(p → q) :=
sorry
example : (¬p ∨ q) → (p → q) :=
sorry
example : (p ∨ q → r) → (p → r) ∧ (q → r) :=
sorry
example : (p → q) → (¬p ∨ q) :=
sorry
end
section
variables {α β : Type} (p q : α → Prop) (r : α → β → Prop)
example : (∀ x, p x) ∧ (∀ x, q x) → ∀ x, p x ∧ q x :=
sorry
example : (∀ x, p x) ∨ (∀ x, q x) → ∀ x, p x ∨ q x :=
sorry
example : (∃ x, ∀ y, r x y) → ∀ y, ∃ x, r x y :=
sorry
theorem e1 : (¬ ∃ x, p x) → ∀ x, ¬ p x :=
sorry
example : (¬ ∀ x, ¬ p x) → ∃ x, p x :=
sorry
example : (¬ ∀ x, ¬ p x) → ∃ x, p x :=
sorry
end
section
/-
There is a man in the town who is the barber. The barber shaves all men who do not shave themselves.
Does the barber shave himself?
-/
variables (man : Type) (barber : man)
variable (shaves : man → man → Prop)
example (H : ∀ x : man, shaves barber x ↔ ¬ shaves x x) : false :=
sorry
end
section
variables {α : Type} (p : α → Prop) (r : Prop) (a : α)
include a
example : (r → ∃ x, p x) → ∃ x, (r → p x) :=
sorry
end
/-
Prove the theorem below, using only the ring properties of ℤ enumerated
in Section 4.2 and the theorem sub_self. You should probably work out
a pen-and-paper proof first.
-/
example (x : ℤ) : x * 0 = 0 :=
sorry
section
open list
variable {α : Type*}
variables s t : list α
variable a : α
example : length (s ++ t) = length s + length t :=
sorry
end
/-
Define an inductive data type consisting of terms built up from the
following constructors:
`const n`, a constant denoting the natural number n
`var n`, a variable, numbered n
`plus s t`, denoting the sum of s and t
`times s t`, denoting the product of s and t
-/
inductive nat_term
| const : ℕ → nat_term
| var : ℕ → nat_term
| plus : nat_term → nat_term → nat_term
| times : nat_term → nat_term → nat_term
open nat_term
/-
Recursively define a function that evaluates any such term with respect to
an assignment `val : ℕ → ℕ` of values to the variables.
For example, if `val 4 = 3
-/
def eval (val : ℕ → ℕ) : nat_term → ℕ
| (const k) := k
| (var k) := val k
| (plus s t) := (eval s) + (eval t)
| (times s t) := (eval s) * (eval t)
/-
Test it out by using #eval on some terms. You can use the following `val` function. In that case, for example, we would expect to have
eval val (plus (const 2) (var 1)) = 5
-/
def val : ℕ → ℕ
| 0 := 4
| 1 := 3
| 2 := 8
| _ := 0
example : eval val (plus (const 2) (var 1)) = 5 := rfl
#eval eval val (plus (const 2) (var 1))
/-
Below, we define a function `rev` that reverses a list. It uses an auxiliary function
`append1`.
If you can, prove that the length of the list is preserved, and that
`rev (rev l) = l` for every `l`. The theorem below is given as an example, and should
be helpful.
Note that when you use the equation compiler to define a function foo, `rw [foo]` uses
one of the defining equations if it can. For example, `rw [append1, ...]` in the theorem
uses the second equation in the definition of `append1`
-/
section
open list
variable {α : Type*}
def append1 (a : α) : list α → list α
| nil := [a]
| (b :: l) := b :: (append1 l)
def rev : list α → list α
| nil := nil
| (a :: l) := append1 a (rev l)
theorem length_append1 (a : α) (l : list α): length (append1 a l) = length l + 1 :=
sorry
theorem length_rev (l : list α) : length (rev l) = length l :=
sorry
lemma hd_rev (a : α) (l : list α) :
a :: rev l = rev (append1 a l) :=
sorry
theorem rev_rev (l : list α) : rev (rev l) = l :=
sorry
end
|
0dd5369afc68e641d70e81d0095ec493ce449f3c | 80162757f50b09d3cad5564907e4c9b00742e045 | /list.lean | 2ef38b836aa778b602fd4fdcb03bb5d6d6455b73 | [] | no_license | EdAyers/edlib | cc30d0a54fed347a85b6df6045f68e6b48bc71a3 | 78b8c5d91f023f939c102837d748868e2f3ed27d | refs/heads/master | 1,586,459,758,216 | 1,571,322,179,000 | 1,571,322,179,000 | 160,538,917 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,288 | lean |
namespace list
universes u
variables {α : Type u} {l l₁ l₂: list α} {a : α}
@[simp] lemma rev_nil : @list.reverse α [] = [] := begin unfold reverse, unfold reverse_core end
@[simp] lemma rev_core_nil : reverse_core [] l = l := rfl
@[simp] lemma rev_core_cons : reverse_core (a::l₁) l = reverse_core l₁ (a::l) := rfl
@[simp] lemma rev_core_length : (list.length $ list.reverse_core l₁ l₂) = (list.length l₁) + (list.length l₂) :=
@well_founded.recursion
(list α)
_
(measure_wf (length))
(λ l₁, ∀ l₂, (list.length $ list.reverse_core (l₁) l₂) = (list.length (l₁)) + (list.length l₂))
(l₁)
(λ l₃,
list.rec_on l₃ (by simp) (λ h l₃ i p l₂,
begin
simp,
have p₂ : length (reverse_core l₃ (h::l₂)) = length l₃ + length (h::l₂),
apply p, focus {simp [measure, inv_image], rw add_comm, apply nat.lt_succ_self },
rw p₂, simp
end
)
)
l₂
@[simp] lemma l_rev {t : list α} : list.length (list.reverse t) = list.length t := by simp [reverse]
end list |
937c271e3f0d24addab467d28f877638c6efd690 | 53618200bef52920c1e974173f78cd378d268f3e | /hott/hit/pushout.hlean | aed77ccebbb7eea76e55534115d168e7f1f13ce8 | [
"Apache-2.0"
] | permissive | sayantangkhan/lean2 | cc41e61102e0fcc8b65e8501186dcca40b19b22e | 0fc0378969678eec25ea425a426bb48a184a6db0 | refs/heads/master | 1,590,323,112,724 | 1,489,425,932,000 | 1,489,425,932,000 | 84,854,525 | 0 | 0 | null | 1,489,425,509,000 | 1,489,425,509,000 | null | UTF-8 | Lean | false | false | 13,947 | hlean | /-
Copyright (c) 2015-16 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Ulrik Buchholtz, Jakob von Raumer
Declaration and properties of the pushout
-/
import .quotient types.sigma types.arrow_2
open quotient eq sum equiv is_trunc pointed
namespace pushout
section
parameters {TL BL TR : Type} (f : TL → BL) (g : TL → TR)
local abbreviation A := BL + TR
inductive pushout_rel : A → A → Type :=
| Rmk : Π(x : TL), pushout_rel (inl (f x)) (inr (g x))
open pushout_rel
local abbreviation R := pushout_rel
definition pushout : Type := quotient R -- TODO: define this in root namespace
parameters {f g}
definition inl (x : BL) : pushout :=
class_of R (inl x)
definition inr (x : TR) : pushout :=
class_of R (inr x)
definition glue (x : TL) : inl (f x) = inr (g x) :=
eq_of_rel pushout_rel (Rmk f g x)
protected definition rec {P : pushout → Type} (Pinl : Π(x : BL), P (inl x))
(Pinr : Π(x : TR), P (inr x)) (Pglue : Π(x : TL), Pinl (f x) =[glue x] Pinr (g x))
(y : pushout) : P y :=
begin
induction y,
{ cases a,
apply Pinl,
apply Pinr},
{ cases H, apply Pglue}
end
protected definition rec_on [reducible] {P : pushout → Type} (y : pushout)
(Pinl : Π(x : BL), P (inl x)) (Pinr : Π(x : TR), P (inr x))
(Pglue : Π(x : TL), Pinl (f x) =[glue x] Pinr (g x)) : P y :=
rec Pinl Pinr Pglue y
theorem rec_glue {P : pushout → Type} (Pinl : Π(x : BL), P (inl x))
(Pinr : Π(x : TR), P (inr x)) (Pglue : Π(x : TL), Pinl (f x) =[glue x] Pinr (g x))
(x : TL) : apd (rec Pinl Pinr Pglue) (glue x) = Pglue x :=
!rec_eq_of_rel
protected definition elim {P : Type} (Pinl : BL → P) (Pinr : TR → P)
(Pglue : Π(x : TL), Pinl (f x) = Pinr (g x)) (y : pushout) : P :=
rec Pinl Pinr (λx, pathover_of_eq _ (Pglue x)) y
protected definition elim_on [reducible] {P : Type} (y : pushout) (Pinl : BL → P)
(Pinr : TR → P) (Pglue : Π(x : TL), Pinl (f x) = Pinr (g x)) : P :=
elim Pinl Pinr Pglue y
theorem elim_glue {P : Type} (Pinl : BL → P) (Pinr : TR → P)
(Pglue : Π(x : TL), Pinl (f x) = Pinr (g x)) (x : TL)
: ap (elim Pinl Pinr Pglue) (glue x) = Pglue x :=
begin
apply eq_of_fn_eq_fn_inv !(pathover_constant (glue x)),
rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑pushout.elim,rec_glue],
end
protected definition elim_type (Pinl : BL → Type) (Pinr : TR → Type)
(Pglue : Π(x : TL), Pinl (f x) ≃ Pinr (g x)) : pushout → Type :=
quotient.elim_type (sum.rec Pinl Pinr)
begin intro v v' r, induction r, apply Pglue end
protected definition elim_type_on [reducible] (y : pushout) (Pinl : BL → Type)
(Pinr : TR → Type) (Pglue : Π(x : TL), Pinl (f x) ≃ Pinr (g x)) : Type :=
elim_type Pinl Pinr Pglue y
theorem elim_type_glue (Pinl : BL → Type) (Pinr : TR → Type)
(Pglue : Π(x : TL), Pinl (f x) ≃ Pinr (g x)) (x : TL)
: transport (elim_type Pinl Pinr Pglue) (glue x) = Pglue x :=
!elim_type_eq_of_rel_fn
theorem elim_type_glue_inv (Pinl : BL → Type) (Pinr : TR → Type)
(Pglue : Π(x : TL), Pinl (f x) ≃ Pinr (g x)) (x : TL)
: transport (elim_type Pinl Pinr Pglue) (glue x)⁻¹ = to_inv (Pglue x) :=
!elim_type_eq_of_rel_inv
protected definition rec_prop {P : pushout → Type} [H : Πx, is_prop (P x)]
(Pinl : Π(x : BL), P (inl x)) (Pinr : Π(x : TR), P (inr x)) (y : pushout) :=
rec Pinl Pinr (λx, !is_prop.elimo) y
protected definition elim_prop {P : Type} [H : is_prop P] (Pinl : BL → P) (Pinr : TR → P)
(y : pushout) : P :=
elim Pinl Pinr (λa, !is_prop.elim) y
end
end pushout
attribute pushout.inl pushout.inr [constructor]
attribute pushout.rec pushout.elim [unfold 10] [recursor 10]
attribute pushout.elim_type [unfold 9]
attribute pushout.rec_on pushout.elim_on [unfold 7]
attribute pushout.elim_type_on [unfold 6]
open sigma
namespace pushout
variables {TL BL TR : Type} (f : TL → BL) (g : TL → TR)
/- The non-dependent universal property -/
definition pushout_arrow_equiv (C : Type)
: (pushout f g → C) ≃ (Σ(i : BL → C) (j : TR → C), Πc, i (f c) = j (g c)) :=
begin
fapply equiv.MK,
{ intro f, exact ⟨λx, f (inl x), λx, f (inr x), λx, ap f (glue x)⟩},
{ intro v x, induction v with i w, induction w with j p, induction x,
exact (i a), exact (j a), exact (p x)},
{ intro v, induction v with i w, induction w with j p, esimp,
apply ap (λp, ⟨i, j, p⟩), apply eq_of_homotopy, intro x, apply elim_glue},
{ intro f, apply eq_of_homotopy, intro x, induction x: esimp,
apply eq_pathover, apply hdeg_square, esimp, apply elim_glue},
end
/- glue squares -/
protected definition glue_square {x x' : TL} (p : x = x')
: square (glue x) (glue x') (ap inl (ap f p)) (ap inr (ap g p)) :=
by cases p; apply vrefl
end pushout
open function sigma.ops
namespace pushout
/- The flattening lemma -/
section
universe variable u
parameters {TL BL TR : Type} (f : TL → BL) (g : TL → TR)
(Pinl : BL → Type.{u}) (Pinr : TR → Type.{u})
(Pglue : Π(x : TL), Pinl (f x) ≃ Pinr (g x))
include Pglue
local abbreviation A := BL + TR
local abbreviation R : A → A → Type := pushout_rel f g
local abbreviation P [unfold 5] := pushout.elim_type Pinl Pinr Pglue
local abbreviation F : sigma (Pinl ∘ f) → sigma Pinl :=
λz, ⟨ f z.1 , z.2 ⟩
local abbreviation G : sigma (Pinl ∘ f) → sigma Pinr :=
λz, ⟨ g z.1 , Pglue z.1 z.2 ⟩
protected definition flattening : sigma P ≃ pushout F G :=
begin
apply equiv.trans !quotient.flattening.flattening_lemma,
fapply equiv.MK,
{ intro q, induction q with z z z' fr,
{ induction z with a p, induction a with x x,
{ exact inl ⟨x, p⟩ },
{ exact inr ⟨x, p⟩ } },
{ induction fr with a a' r p, induction r with x,
exact glue ⟨x, p⟩ } },
{ intro q, induction q with xp xp xp,
{ exact class_of _ ⟨sum.inl xp.1, xp.2⟩ },
{ exact class_of _ ⟨sum.inr xp.1, xp.2⟩ },
{ apply eq_of_rel, constructor } },
{ intro q, induction q with xp xp xp: induction xp with x p,
{ apply ap inl, reflexivity },
{ apply ap inr, reflexivity },
{ unfold F, unfold G, apply eq_pathover,
rewrite [ap_id,ap_compose' (quotient.elim _ _)],
krewrite elim_glue, krewrite elim_eq_of_rel, apply hrefl } },
{ intro q, induction q with z z z' fr,
{ induction z with a p, induction a with x x,
{ reflexivity },
{ reflexivity } },
{ induction fr with a a' r p, induction r with x,
esimp, apply eq_pathover,
rewrite [ap_id,ap_compose' (pushout.elim _ _ _)],
krewrite elim_eq_of_rel, krewrite elim_glue, apply hrefl } }
end
end
-- Commutativity of pushouts
section
variables {TL BL TR : Type} (f : TL → BL) (g : TL → TR)
protected definition transpose [unfold 6] : pushout f g → pushout g f :=
begin
intro x, induction x, apply inr a, apply inl a, apply !glue⁻¹
end
--TODO prove without krewrite?
protected definition transpose_involutive (x : pushout f g) :
pushout.transpose g f (pushout.transpose f g x) = x :=
begin
induction x, apply idp, apply idp,
apply eq_pathover, refine _ ⬝hp !ap_id⁻¹,
refine !(ap_compose (pushout.transpose _ _)) ⬝ph _, esimp[pushout.transpose],
krewrite [elim_glue, ap_inv, elim_glue, inv_inv], apply hrfl
end
protected definition symm : pushout f g ≃ pushout g f :=
begin
fapply equiv.MK, do 2 exact !pushout.transpose,
do 2 (intro x; apply pushout.transpose_involutive),
end
end
-- Functoriality of pushouts
section
section lemmas
variables {X : Type} {x₀ x₁ x₂ x₃ : X}
(p : x₀ = x₁) (q : x₁ = x₂) (r : x₂ = x₃)
private definition is_equiv_functor_lemma₁
: (r ⬝ ((p ⬝ q ⬝ r)⁻¹ ⬝ p)) = q⁻¹ :=
by cases p; cases r; cases q; reflexivity
private definition is_equiv_functor_lemma₂
: (p ⬝ q ⬝ r)⁻¹ ⬝ (p ⬝ q) = r⁻¹ :=
by cases p; cases r; cases q; reflexivity
end lemmas
variables {TL BL TR : Type} {f : TL → BL} {g : TL → TR}
{TL' BL' TR' : Type} {f' : TL' → BL'} {g' : TL' → TR'}
(tl : TL → TL') (bl : BL → BL') (tr : TR → TR')
(fh : bl ∘ f ~ f' ∘ tl) (gh : tr ∘ g ~ g' ∘ tl)
include fh gh
protected definition functor [reducible] : pushout f g → pushout f' g' :=
begin
intro x, induction x with a b z,
{ exact inl (bl a) },
{ exact inr (tr b) },
{ exact (ap inl (fh z)) ⬝ glue (tl z) ⬝ (ap inr (gh z)⁻¹) }
end
protected definition ap_functor_inl [unfold 18] {x x' : BL} (p : x = x')
: ap (pushout.functor tl bl tr fh gh) (ap inl p) = ap inl (ap bl p) :=
by cases p; reflexivity
protected definition ap_functor_inr [unfold 18] {x x' : TR} (p : x = x')
: ap (pushout.functor tl bl tr fh gh) (ap inr p) = ap inr (ap tr p) :=
by cases p; reflexivity
variables [ietl : is_equiv tl] [iebl : is_equiv bl] [ietr : is_equiv tr]
include ietl iebl ietr
open equiv is_equiv arrow
protected definition is_equiv_functor [instance]
: is_equiv (pushout.functor tl bl tr fh gh) :=
adjointify
(pushout.functor tl bl tr fh gh)
(pushout.functor tl⁻¹ bl⁻¹ tr⁻¹
(inv_commute_of_commute tl bl f f' fh)
(inv_commute_of_commute tl tr g g' gh))
abstract begin
intro x', induction x' with a' b' z',
{ apply ap inl, apply right_inv },
{ apply ap inr, apply right_inv },
{ apply eq_pathover,
rewrite [ap_id,ap_compose' (pushout.functor tl bl tr fh gh)],
krewrite elim_glue,
rewrite [ap_inv,ap_con,ap_inv],
krewrite [pushout.ap_functor_inr], rewrite ap_con,
krewrite [pushout.ap_functor_inl,elim_glue],
apply transpose,
apply move_top_of_right, apply move_top_of_left',
krewrite [-(ap_inv inl),-ap_con,-(ap_inv inr),-ap_con],
apply move_top_of_right, apply move_top_of_left',
krewrite [-ap_con,-(ap_inv inl),-ap_con],
rewrite ap_bot_inv_commute_of_commute,
apply eq_hconcat (ap02 inl
(is_equiv_functor_lemma₁
(right_inv bl (f' z'))
(ap f' (right_inv tl z')⁻¹)
(fh (tl⁻¹ z'))⁻¹)),
rewrite [ap_inv f',inv_inv],
rewrite ap_bot_inv_commute_of_commute,
refine hconcat_eq _ (ap02 inr
(is_equiv_functor_lemma₁
(right_inv tr (g' z'))
(ap g' (right_inv tl z')⁻¹)
(gh (tl⁻¹ z'))⁻¹))⁻¹,
rewrite [ap_inv g',inv_inv],
apply pushout.glue_square }
end end
abstract begin
intro x, induction x with a b z,
{ apply ap inl, apply left_inv },
{ apply ap inr, apply left_inv },
{ apply eq_pathover,
rewrite [ap_id,ap_compose'
(pushout.functor tl⁻¹ bl⁻¹ tr⁻¹ _ _)
(pushout.functor tl bl tr _ _)],
krewrite elim_glue,
rewrite [ap_inv,ap_con,ap_inv],
krewrite [pushout.ap_functor_inr], rewrite ap_con,
krewrite [pushout.ap_functor_inl,elim_glue],
apply transpose,
apply move_top_of_right, apply move_top_of_left',
krewrite [-(ap_inv inl),-ap_con,-(ap_inv inr),-ap_con],
apply move_top_of_right, apply move_top_of_left',
krewrite [-ap_con,-(ap_inv inl),-ap_con],
rewrite inv_commute_of_commute_top,
apply eq_hconcat (ap02 inl
(is_equiv_functor_lemma₂
(ap bl⁻¹ (fh z))⁻¹
(left_inv bl (f z))
(ap f (left_inv tl z)⁻¹))),
rewrite [ap_inv f,inv_inv],
rewrite inv_commute_of_commute_top,
refine hconcat_eq _ (ap02 inr
(is_equiv_functor_lemma₂
(ap tr⁻¹ (gh z))⁻¹
(left_inv tr (g z))
(ap g (left_inv tl z)⁻¹)))⁻¹,
rewrite [ap_inv g,inv_inv],
apply pushout.glue_square }
end end
end
/- version giving the equivalence -/
section
variables {TL BL TR : Type} (f : TL → BL) (g : TL → TR)
{TL' BL' TR' : Type} (f' : TL' → BL') (g' : TL' → TR')
(tl : TL ≃ TL') (bl : BL ≃ BL') (tr : TR ≃ TR')
(fh : bl ∘ f ~ f' ∘ tl) (gh : tr ∘ g ~ g' ∘ tl)
include fh gh
protected definition equiv : pushout f g ≃ pushout f' g' :=
equiv.mk (pushout.functor tl bl tr fh gh) _
end
definition pointed_pushout [instance] [constructor] {TL BL TR : Type} [HTL : pointed TL]
[HBL : pointed BL] [HTR : pointed TR] (f : TL → BL) (g : TL → TR) : pointed (pushout f g) :=
pointed.mk (inl (point _))
end pushout open pushout
definition ppushout [constructor] {TL BL TR : Type*} (f : TL →* BL) (g : TL →* TR) : Type* :=
pointed.mk' (pushout f g)
namespace pushout
section
parameters {TL BL TR : Type*} (f : TL →* BL) (g : TL →* TR)
parameters {f g}
definition pinl [constructor] : BL →* ppushout f g :=
pmap.mk inl idp
definition pinr [constructor] : TR →* ppushout f g :=
pmap.mk inr ((ap inr (respect_pt g))⁻¹ ⬝ !glue⁻¹ ⬝ (ap inl (respect_pt f)))
definition pglue (x : TL) : pinl (f x) = pinr (g x) := -- TODO do we need this?
!glue
end
section
variables {TL BL TR : Type*} (f : TL →* BL) (g : TL →* TR)
protected definition psymm [constructor] : ppushout f g ≃* ppushout g f :=
begin
fapply pequiv_of_equiv,
{ apply pushout.symm },
{ exact ap inr (respect_pt f)⁻¹ ⬝ !glue⁻¹ ⬝ ap inl (respect_pt g) }
end
end
end pushout
|
69bbac9b1d8772c37c0846f204434bf4d6ee9de6 | 592ee40978ac7604005a4e0d35bbc4b467389241 | /Library/generated/mathscheme-lean/Band.lean | 12782a70b0858234d1ea73a13b790c2948b7f63c | [] | no_license | ysharoda/Deriving-Definitions | 3e149e6641fae440badd35ac110a0bd705a49ad2 | dfecb27572022de3d4aa702cae8db19957523a59 | refs/heads/master | 1,679,127,857,700 | 1,615,939,007,000 | 1,615,939,007,000 | 229,785,731 | 4 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,511 | lean | import init.data.nat.basic
import init.data.fin.basic
import data.vector
import .Prelude
open Staged
open nat
open fin
open vector
section Band
structure Band (A : Type) : Type :=
(op : (A → (A → A)))
(associative_op : (∀ {x y z : A} , (op (op x y) z) = (op x (op y z))))
(idempotent_op : (∀ {x : A} , (op x x) = x))
open Band
structure Sig (AS : Type) : Type :=
(opS : (AS → (AS → AS)))
structure Product (A : Type) : Type :=
(opP : ((Prod A A) → ((Prod A A) → (Prod A A))))
(associative_opP : (∀ {xP yP zP : (Prod A A)} , (opP (opP xP yP) zP) = (opP xP (opP yP zP))))
(idempotent_opP : (∀ {xP : (Prod A A)} , (opP xP xP) = xP))
structure Hom {A1 : Type} {A2 : Type} (Ba1 : (Band A1)) (Ba2 : (Band A2)) : Type :=
(hom : (A1 → A2))
(pres_op : (∀ {x1 x2 : A1} , (hom ((op Ba1) x1 x2)) = ((op Ba2) (hom x1) (hom x2))))
structure RelInterp {A1 : Type} {A2 : Type} (Ba1 : (Band A1)) (Ba2 : (Band A2)) : Type 1 :=
(interp : (A1 → (A2 → Type)))
(interp_op : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((op Ba1) x1 x2) ((op Ba2) y1 y2))))))
inductive BandTerm : Type
| opL : (BandTerm → (BandTerm → BandTerm))
open BandTerm
inductive ClBandTerm (A : Type) : Type
| sing : (A → ClBandTerm)
| opCl : (ClBandTerm → (ClBandTerm → ClBandTerm))
open ClBandTerm
inductive OpBandTerm (n : ℕ) : Type
| v : ((fin n) → OpBandTerm)
| opOL : (OpBandTerm → (OpBandTerm → OpBandTerm))
open OpBandTerm
inductive OpBandTerm2 (n : ℕ) (A : Type) : Type
| v2 : ((fin n) → OpBandTerm2)
| sing2 : (A → OpBandTerm2)
| opOL2 : (OpBandTerm2 → (OpBandTerm2 → OpBandTerm2))
open OpBandTerm2
def simplifyCl {A : Type} : ((ClBandTerm A) → (ClBandTerm A))
| (opCl x1 x2) := (opCl (simplifyCl x1) (simplifyCl x2))
| (sing x1) := (sing x1)
def simplifyOpB {n : ℕ} : ((OpBandTerm n) → (OpBandTerm n))
| (opOL x1 x2) := (opOL (simplifyOpB x1) (simplifyOpB x2))
| (v x1) := (v x1)
def simplifyOp {n : ℕ} {A : Type} : ((OpBandTerm2 n A) → (OpBandTerm2 n A))
| (opOL2 x1 x2) := (opOL2 (simplifyOp x1) (simplifyOp x2))
| (v2 x1) := (v2 x1)
| (sing2 x1) := (sing2 x1)
def evalB {A : Type} : ((Band A) → (BandTerm → A))
| Ba (opL x1 x2) := ((op Ba) (evalB Ba x1) (evalB Ba x2))
def evalCl {A : Type} : ((Band A) → ((ClBandTerm A) → A))
| Ba (sing x1) := x1
| Ba (opCl x1 x2) := ((op Ba) (evalCl Ba x1) (evalCl Ba x2))
def evalOpB {A : Type} {n : ℕ} : ((Band A) → ((vector A n) → ((OpBandTerm n) → A)))
| Ba vars (v x1) := (nth vars x1)
| Ba vars (opOL x1 x2) := ((op Ba) (evalOpB Ba vars x1) (evalOpB Ba vars x2))
def evalOp {A : Type} {n : ℕ} : ((Band A) → ((vector A n) → ((OpBandTerm2 n A) → A)))
| Ba vars (v2 x1) := (nth vars x1)
| Ba vars (sing2 x1) := x1
| Ba vars (opOL2 x1 x2) := ((op Ba) (evalOp Ba vars x1) (evalOp Ba vars x2))
def inductionB {P : (BandTerm → Type)} : ((∀ (x1 x2 : BandTerm) , ((P x1) → ((P x2) → (P (opL x1 x2))))) → (∀ (x : BandTerm) , (P x)))
| popl (opL x1 x2) := (popl _ _ (inductionB popl x1) (inductionB popl x2))
def inductionCl {A : Type} {P : ((ClBandTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClBandTerm A)) , ((P x1) → ((P x2) → (P (opCl x1 x2))))) → (∀ (x : (ClBandTerm A)) , (P x))))
| psing popcl (sing x1) := (psing x1)
| psing popcl (opCl x1 x2) := (popcl _ _ (inductionCl psing popcl x1) (inductionCl psing popcl x2))
def inductionOpB {n : ℕ} {P : ((OpBandTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpBandTerm n)) , ((P x1) → ((P x2) → (P (opOL x1 x2))))) → (∀ (x : (OpBandTerm n)) , (P x))))
| pv popol (v x1) := (pv x1)
| pv popol (opOL x1 x2) := (popol _ _ (inductionOpB pv popol x1) (inductionOpB pv popol x2))
def inductionOp {n : ℕ} {A : Type} {P : ((OpBandTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpBandTerm2 n A)) , ((P x1) → ((P x2) → (P (opOL2 x1 x2))))) → (∀ (x : (OpBandTerm2 n A)) , (P x)))))
| pv2 psing2 popol2 (v2 x1) := (pv2 x1)
| pv2 psing2 popol2 (sing2 x1) := (psing2 x1)
| pv2 psing2 popol2 (opOL2 x1 x2) := (popol2 _ _ (inductionOp pv2 psing2 popol2 x1) (inductionOp pv2 psing2 popol2 x2))
def stageB : (BandTerm → (Staged BandTerm))
| (opL x1 x2) := (stage2 opL (codeLift2 opL) (stageB x1) (stageB x2))
def stageCl {A : Type} : ((ClBandTerm A) → (Staged (ClBandTerm A)))
| (sing x1) := (Now (sing x1))
| (opCl x1 x2) := (stage2 opCl (codeLift2 opCl) (stageCl x1) (stageCl x2))
def stageOpB {n : ℕ} : ((OpBandTerm n) → (Staged (OpBandTerm n)))
| (v x1) := (const (code (v x1)))
| (opOL x1 x2) := (stage2 opOL (codeLift2 opOL) (stageOpB x1) (stageOpB x2))
def stageOp {n : ℕ} {A : Type} : ((OpBandTerm2 n A) → (Staged (OpBandTerm2 n A)))
| (sing2 x1) := (Now (sing2 x1))
| (v2 x1) := (const (code (v2 x1)))
| (opOL2 x1 x2) := (stage2 opOL2 (codeLift2 opOL2) (stageOp x1) (stageOp x2))
structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type :=
(opT : ((Repr A) → ((Repr A) → (Repr A))))
end Band |
c6229415d20647fd5df3751f7691a2629ec37372 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /src/Lean/Meta/Match/Match.lean | 2e5e3892324db34a92ecb096f026b1d39c549244 | [
"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 | 44,085 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Util.CollectLevelParams
import Lean.Util.CollectFVars
import Lean.Util.Recognizers
import Lean.Compiler.ExternAttr
import Lean.Meta.Check
import Lean.Meta.Closure
import Lean.Meta.Tactic.Cases
import Lean.Meta.Tactic.Contradiction
import Lean.Meta.GeneralizeTelescope
import Lean.Meta.Match.Basic
import Lean.Meta.Match.MVarRenaming
import Lean.Meta.Match.CaseValues
namespace Lean.Meta.Match
/-- The number of patterns in each AltLHS must be equal to the number of discriminants. -/
private def checkNumPatterns (numDiscrs : Nat) (lhss : List AltLHS) : MetaM Unit := do
if lhss.any fun lhs => lhs.patterns.length != numDiscrs then
throwError "incorrect number of patterns"
/--
Execute `k hs` where `hs` contains new equalities `h : lhs[i] = rhs[i]` for each `discrInfos[i] = some h`.
Assume `lhs.size == rhs.size == discrInfos.size`
-/
private partial def withEqs (lhs rhs : Array Expr) (discrInfos : Array DiscrInfo) (k : Array Expr → MetaM α) : MetaM α := do
go 0 #[]
where
go (i : Nat) (hs : Array Expr) : MetaM α := do
if i < lhs.size then
if let some hName := discrInfos[i]!.hName? then
withLocalDeclD hName (← mkEqHEq lhs[i]! rhs[i]!) fun h =>
go (i+1) (hs.push h)
else
go (i+1) hs
else
k hs
/-- Given a list of `AltLHS`, create a minor premise for each one, convert them into `Alt`, and then execute `k` -/
private def withAlts {α} (motive : Expr) (discrs : Array Expr) (discrInfos : Array DiscrInfo) (lhss : List AltLHS) (k : List Alt → Array (Expr × Nat) → MetaM α) : MetaM α :=
loop lhss [] #[]
where
mkMinorType (xs : Array Expr) (lhs : AltLHS) : MetaM Expr :=
withExistingLocalDecls lhs.fvarDecls do
let args ← lhs.patterns.toArray.mapM (Pattern.toExpr · (annotate := true))
let minorType := mkAppN motive args
withEqs discrs args discrInfos fun eqs => do
mkForallFVars (xs ++ eqs) minorType
loop (lhss : List AltLHS) (alts : List Alt) (minors : Array (Expr × Nat)) : MetaM α := do
match lhss with
| [] => k alts.reverse minors
| lhs::lhss =>
let xs := lhs.fvarDecls.toArray.map LocalDecl.toExpr
let minorType ← mkMinorType xs lhs
let hasParams := !xs.isEmpty || discrInfos.any fun info => info.hName?.isSome
let (minorType, minorNumParams) := if hasParams then (minorType, xs.size) else (mkSimpleThunkType minorType, 1)
let idx := alts.length
let minorName := (`h).appendIndexAfter (idx+1)
trace[Meta.Match.debug] "minor premise {minorName} : {minorType}"
withLocalDeclD minorName minorType fun minor => do
let rhs := if hasParams then mkAppN minor xs else mkApp minor (mkConst `Unit.unit)
let minors := minors.push (minor, minorNumParams)
let fvarDecls ← lhs.fvarDecls.mapM instantiateLocalDeclMVars
let alts := { ref := lhs.ref, idx := idx, rhs := rhs, fvarDecls := fvarDecls, patterns := lhs.patterns, cnstrs := [] } :: alts
loop lhss alts minors
structure State where
used : Std.HashSet Nat := {} -- used alternatives
counterExamples : List (List Example) := []
/-- Return true if the given (sub-)problem has been solved. -/
private def isDone (p : Problem) : Bool :=
p.vars.isEmpty
/-- Return true if the next element on the `p.vars` list is a variable. -/
private def isNextVar (p : Problem) : Bool :=
match p.vars with
| .fvar _ :: _ => true
| _ => false
private def hasAsPattern (p : Problem) : Bool :=
p.alts.any fun alt => match alt.patterns with
| .as .. :: _ => true
| _ => false
private def hasCtorPattern (p : Problem) : Bool :=
p.alts.any fun alt => match alt.patterns with
| .ctor .. :: _ => true
| _ => false
private def hasValPattern (p : Problem) : Bool :=
p.alts.any fun alt => match alt.patterns with
| .val _ :: _ => true
| _ => false
private def hasNatValPattern (p : Problem) : Bool :=
p.alts.any fun alt => match alt.patterns with
| .val v :: _ => v.isNatLit
| _ => false
private def hasVarPattern (p : Problem) : Bool :=
p.alts.any fun alt => match alt.patterns with
| .var _ :: _ => true
| _ => false
private def hasArrayLitPattern (p : Problem) : Bool :=
p.alts.any fun alt => match alt.patterns with
| .arrayLit .. :: _ => true
| _ => false
private def isVariableTransition (p : Problem) : Bool :=
p.alts.all fun alt => match alt.patterns with
| .inaccessible _ :: _ => true
| .var _ :: _ => true
| _ => false
private def isConstructorTransition (p : Problem) : Bool :=
(hasCtorPattern p || p.alts.isEmpty)
&& p.alts.all fun alt => match alt.patterns with
| .ctor .. :: _ => true
| .var _ :: _ => true
| .inaccessible _ :: _ => true
| _ => false
private def isValueTransition (p : Problem) : Bool :=
hasVarPattern p && hasValPattern p
&& p.alts.all fun alt => match alt.patterns with
| .val _ :: _ => true
| .var _ :: _ => true
| _ => false
private def isArrayLitTransition (p : Problem) : Bool :=
hasArrayLitPattern p && hasVarPattern p
&& p.alts.all fun alt => match alt.patterns with
| .arrayLit .. :: _ => true
| .var _ :: _ => true
| _ => false
private def isNatValueTransition (p : Problem) : Bool :=
hasNatValPattern p
&& (!isNextVar p ||
p.alts.any fun alt => match alt.patterns with
| .ctor .. :: _ => true
| .inaccessible _ :: _ => true
| _ => false)
private def processSkipInaccessible (p : Problem) : Problem := Id.run do
let x :: xs := p.vars | unreachable!
let alts := p.alts.map fun alt => Id.run do
let .inaccessible e :: ps := alt.patterns | unreachable!
{ alt with patterns := ps, cnstrs := (x, e) :: alt.cnstrs }
{ p with alts := alts, vars := xs }
/--
If contraint is of the form `e ≋ x` where `x` is a free variable, reorient it
as `x ≋ e` If
- `x` is an `alt`-local declaration
- `e` is not a free variable.
-/
private def reorientCnstrs (alt : Alt) : Alt :=
let cnstrs := alt.cnstrs.map fun (lhs, rhs) =>
if rhs.isFVar && alt.isLocalDecl rhs.fvarId! then
(rhs, lhs)
else if !lhs.isFVar && rhs.isFVar then
(rhs, lhs)
else
(lhs, rhs)
{ alt with cnstrs }
/--
Remove constraints of the form `lhs ≋ rhs` where `lhs` and `rhs` are definitionally equal,
or `lhs` is a free variable.
-/
private def filterTrivialCnstrs (alt : Alt) : MetaM Alt := do
let cnstrs ← withExistingLocalDecls alt.fvarDecls do
alt.cnstrs.filterM fun (lhs, rhs) => do
if (← isDefEqGuarded lhs rhs) then
return false
else if lhs.isFVar then
return false
else
return true
return { alt with cnstrs }
/--
Find an alternative constraint of the form `x ≋ e` where `x` is an alternative
local declarations, and `x` and `e` have definitionally equal types.
Then, replace `x` with `e` in the alternative, and return it.
Return `none` if the alternative does not contain a constraint of this form.
-/
private def solveSomeLocalFVarIdCnstr? (alt : Alt) : MetaM (Option Alt) :=
withExistingLocalDecls alt.fvarDecls do
let (some (fvarId, val), cnstrs) ← go alt.cnstrs | return none
trace[Meta.Match.match] "found cnstr to solve {mkFVar fvarId} ↦ {val}"
return some <| { alt with cnstrs }.replaceFVarId fvarId val
where
go (cnstrs : List (Expr × Expr)) := do
match cnstrs with
| [] => return (none, [])
| (lhs, rhs) :: cnstrs =>
if lhs.isFVar && alt.isLocalDecl lhs.fvarId! then
if !(← dependsOn rhs lhs.fvarId!) && (← isDefEqGuarded (← inferType lhs) (← inferType rhs)) then
return (some (lhs.fvarId!, rhs), cnstrs)
let (p, cnstrs) ← go cnstrs
return (p, (lhs, rhs) :: cnstrs)
/--
Solve pending alternative constraints. If all constraints can be solved perform assignment
`mvarId := alt.rhs`, and return true.
-/
private partial def solveCnstrs (mvarId : MVarId) (alt : Alt) : StateRefT State MetaM Bool := do
go (reorientCnstrs alt)
where
go (alt : Alt) : StateRefT State MetaM Bool := do
match (← solveSomeLocalFVarIdCnstr? alt) with
| some alt => go alt
| none =>
let alt ← filterTrivialCnstrs alt
if alt.cnstrs.isEmpty then
let eType ← inferType alt.rhs
let targetType ← mvarId.getType
unless (← isDefEqGuarded targetType eType) do
trace[Meta.Match.match] "assignGoalOf failed {eType} =?= {targetType}"
throwError "dependent elimination failed, type mismatch when solving alternative with type{indentExpr eType}\nbut expected{indentExpr targetType}"
mvarId.assign alt.rhs
modify fun s => { s with used := s.used.insert alt.idx }
return true
else
trace[Meta.Match.match] "alt has unsolved cnstrs:\n{← alt.toMessageData}"
return false
/--
Try to solve the problem by using the first alternative whose pending constraints can be resolved.
-/
private def processLeaf (p : Problem) : StateRefT State MetaM Unit :=
p.mvarId.withContext do
withPPForTacticGoal do trace[Meta.Match.match] "local context at processLeaf:\n{(← mkFreshTypeMVar).mvarId!}"
go p.alts
where
go (alts : List Alt) : StateRefT State MetaM Unit := do
match alts with
| [] =>
/- TODO: allow users to configure which tactic is used to close leaves. -/
unless (← p.mvarId.contradictionCore {}) do
trace[Meta.Match.match] "missing alternative"
p.mvarId.admit
modify fun s => { s with counterExamples := p.examples :: s.counterExamples }
| alt :: alts =>
unless (← solveCnstrs p.mvarId alt) do
go alts
private def processAsPattern (p : Problem) : MetaM Problem := withGoalOf p do
let x :: _ := p.vars | unreachable!
let alts ← p.alts.mapM fun alt => do
match alt.patterns with
| .as fvarId p h :: ps =>
/- We used to use `checkAndReplaceFVarId` here, but `x` and `fvarId` may have different types
when dependent types are beind used. Let's consider the repro for issue #471
```
inductive vec : Nat → Type
| nil : vec 0
| cons : Int → vec n → vec n.succ
def vec_len : vec n → Nat
| vec.nil => 0
| x@(vec.cons h t) => vec_len t + 1
```
we reach the state
```
[Meta.Match.match] remaining variables: [x✝:(vec n✝)]
alternatives:
[n:(Nat), x:(vec (Nat.succ n)), h:(Int), t:(vec n)] |- [x@(vec.cons n h t)] => h_1 n x h t
[x✝:(vec n✝)] |- [x✝] => h_2 n✝ x✝
```
The variables `x✝:(vec n✝)` and `x:(vec (Nat.succ n))` have different types, but we perform the substitution anyway,
because we claim the "discrepancy" will be corrected after we process the pattern `(vec.cons n h t)`.
The right-hand-side is temporarily type incorrect, but we claim this is fine because it will be type correct again after
we the pattern `(vec.cons n h t)`. TODO: try to find a cleaner solution.
-/
let r ← mkEqRefl x
return { alt with patterns := p :: ps }.replaceFVarId fvarId x |>.replaceFVarId h r
| _ => return alt
return { p with alts := alts }
private def processVariable (p : Problem) : MetaM Problem := withGoalOf p do
let x :: xs := p.vars | unreachable!
let alts ← p.alts.mapM fun alt => do
match alt.patterns with
| .inaccessible e :: ps => return { alt with patterns := ps, cnstrs := (x, e) :: alt.cnstrs }
| .var fvarId :: ps =>
withExistingLocalDecls alt.fvarDecls do
if (← isDefEqGuarded (← fvarId.getType) (← inferType x)) then
return { alt with patterns := ps }.replaceFVarId fvarId x
else
return { alt with patterns := ps, cnstrs := (mkFVar fvarId, x) :: alt.cnstrs }
| _ => unreachable!
return { p with alts := alts, vars := xs }
/-!
Note that we decided to store pending constraints to address issues exposed by #1279 and #1361.
Here is a simplified version of the example on this issue (see test: `1279_simplified.lean`)
```lean
inductive Arrow : Type → Type → Type 1
| id : Arrow a a
| unit : Arrow Unit Unit
| comp : Arrow β γ → Arrow α β → Arrow α γ
deriving Repr
def Arrow.compose (f : Arrow β γ) (g : Arrow α β) : Arrow α γ :=
match f, g with
| id, g => g
| f, id => f
| f, g => comp f g
```
The initial state for the `match`-expression above is
```lean
[Meta.Match.match] remaining variables: [β✝:(Type), γ✝:(Type), f✝:(Arrow β✝ γ✝), g✝:(Arrow α β✝)]
alternatives:
[β:(Type), g:(Arrow α β)] |- [β, .(β), (Arrow.id .(β)), g] => h_1 β g
[γ:(Type), f:(Arrow α γ)] |- [.(α), γ, f, (Arrow.id .(α))] => h_2 γ f
[β:(Type), γ:(Type), f:(Arrow β γ), g:(Arrow α β)] |- [β, γ, f, g] => h_3 β γ f g
```
The first step is a variable-transition which replaces `β` with `β✝` in the first and third alternatives.
The constraint `β✝ ≋ α` in the second alternative used to be discarded. We now store it at the
alternative `cnstrs` field.
-/
private def inLocalDecls (localDecls : List LocalDecl) (fvarId : FVarId) : Bool :=
localDecls.any fun d => d.fvarId == fvarId
private def expandVarIntoCtor? (alt : Alt) (fvarId : FVarId) (ctorName : Name) : MetaM (Option Alt) :=
withExistingLocalDecls alt.fvarDecls do
trace[Meta.Match.unify] "expandVarIntoCtor? fvarId: {mkFVar fvarId}, ctorName: {ctorName}, alt:\n{← alt.toMessageData}"
let expectedType ← inferType (mkFVar fvarId)
let expectedType ← whnfD expectedType
let (ctorLevels, ctorParams) ← getInductiveUniverseAndParams expectedType
let ctor := mkAppN (mkConst ctorName ctorLevels) ctorParams
let ctorType ← inferType ctor
forallTelescopeReducing ctorType fun ctorFields resultType => do
let ctor := mkAppN ctor ctorFields
let alt := alt.replaceFVarId fvarId ctor
let ctorFieldDecls ← ctorFields.mapM fun ctorField => ctorField.fvarId!.getDecl
let newAltDecls := ctorFieldDecls.toList ++ alt.fvarDecls
let mut cnstrs := alt.cnstrs
unless (← isDefEqGuarded resultType expectedType) do
cnstrs := (resultType, expectedType) :: cnstrs
trace[Meta.Match.unify] "expandVarIntoCtor? {mkFVar fvarId} : {expectedType}, ctor: {ctor}"
let ctorFieldPatterns := ctorFieldDecls.toList.map fun decl => Pattern.var decl.fvarId
return some { alt with fvarDecls := newAltDecls, patterns := ctorFieldPatterns ++ alt.patterns, cnstrs }
private def getInductiveVal? (x : Expr) : MetaM (Option InductiveVal) := do
let xType ← inferType x
let xType ← whnfD xType
match xType.getAppFn with
| Expr.const constName _ =>
let cinfo ← getConstInfo constName
match cinfo with
| ConstantInfo.inductInfo val => return some val
| _ => return none
| _ => return none
private def hasRecursiveType (x : Expr) : MetaM Bool := do
match (← getInductiveVal? x) with
| some val => return val.isRec
| _ => return false
/-- Given `alt` s.t. the next pattern is an inaccessible pattern `e`,
try to normalize `e` into a constructor application.
If it is not a constructor, throw an error.
Otherwise, if it is a constructor application of `ctorName`,
update the next patterns with the fields of the constructor.
Otherwise, return none. -/
def processInaccessibleAsCtor (alt : Alt) (ctorName : Name) : MetaM (Option Alt) := do
let env ← getEnv
match alt.patterns with
| p@(.inaccessible e) :: ps =>
trace[Meta.Match.match] "inaccessible in ctor step {e}"
withExistingLocalDecls alt.fvarDecls do
-- Try to push inaccessible annotations.
let e ← whnfD e
match e.constructorApp? env with
| some (ctorVal, ctorArgs) =>
if ctorVal.name == ctorName then
let fields := ctorArgs.extract ctorVal.numParams ctorArgs.size
let fields := fields.toList.map .inaccessible
return some { alt with patterns := fields ++ ps }
else
return none
| _ => throwErrorAt alt.ref "dependent match elimination failed, inaccessible pattern found{indentD p.toMessageData}\nconstructor expected"
| _ => unreachable!
private def hasNonTrivialExample (p : Problem) : Bool :=
p.examples.any fun | Example.underscore => false | _ => true
private def throwCasesException (p : Problem) (ex : Exception) : MetaM α := do
match ex with
| .error ref msg =>
let exampleMsg :=
if hasNonTrivialExample p then m!" after processing{indentD <| examplesToMessageData p.examples}" else ""
throw <| Exception.error ref <| m!"{msg}{exampleMsg}\n" ++
"the dependent pattern matcher can solve the following kinds of equations\n" ++
"- <var> = <term> and <term> = <var>\n" ++
"- <term> = <term> where the terms are definitionally equal\n" ++
"- <constructor> = <constructor>, examples: List.cons x xs = List.cons y ys, and List.cons x xs = List.nil"
| _ => throw ex
private def processConstructor (p : Problem) : MetaM (Array Problem) := do
trace[Meta.Match.match] "constructor step"
let x :: xs := p.vars | unreachable!
let subgoals? ← commitWhenSome? do
let subgoals ←
try
p.mvarId.cases x.fvarId!
catch ex =>
if p.alts.isEmpty then
/- If we have no alternatives and dependent pattern matching fails, then a "missing cases" error is bettern than a "stuck" error message. -/
return none
else
throwCasesException p ex
if subgoals.isEmpty then
/- Easy case: we have solved problem `p` since there are no subgoals -/
return some #[]
else if !p.alts.isEmpty then
return some subgoals
else do
let isRec ← withGoalOf p <| hasRecursiveType x
/- If there are no alternatives and the type of the current variable is recursive, we do NOT consider
a constructor-transition to avoid nontermination.
TODO: implement a more general approach if this is not sufficient in practice -/
if isRec then
return none
else
return some subgoals
let some subgoals := subgoals? | return #[{ p with vars := xs }]
subgoals.mapM fun subgoal => subgoal.mvarId.withContext do
let subst := subgoal.subst
let fields := subgoal.fields.toList
let newVars := fields ++ xs
let newVars := newVars.map fun x => x.applyFVarSubst subst
let subex := Example.ctor subgoal.ctorName <| fields.map fun field => match field with
| .fvar fvarId => Example.var fvarId
| _ => Example.underscore -- This case can happen due to dependent elimination
let examples := p.examples.map <| Example.replaceFVarId x.fvarId! subex
let examples := examples.map <| Example.applyFVarSubst subst
let newAlts := p.alts.filter fun alt => match alt.patterns with
| .ctor n .. :: _ => n == subgoal.ctorName
| .var _ :: _ => true
| .inaccessible _ :: _ => true
| _ => false
let newAlts := newAlts.map fun alt => alt.applyFVarSubst subst
let newAlts ← newAlts.filterMapM fun alt => do
match alt.patterns with
| .ctor _ _ _ fields :: ps => return some { alt with patterns := fields ++ ps }
| .var fvarId :: ps => expandVarIntoCtor? { alt with patterns := ps } fvarId subgoal.ctorName
| .inaccessible _ :: _ => processInaccessibleAsCtor alt subgoal.ctorName
| _ => unreachable!
return { mvarId := subgoal.mvarId, vars := newVars, alts := newAlts, examples := examples }
private def altsAreCtorLike (p : Problem) : MetaM Bool := withGoalOf p do
p.alts.allM fun alt => do match alt.patterns with
| .ctor .. :: _ => return true
| .inaccessible e :: _ => return (← whnfD e).isConstructorApp (← getEnv)
| _ => return false
private def processNonVariable (p : Problem) : MetaM Problem := withGoalOf p do
let x :: xs := p.vars | unreachable!
if let some (ctorVal, xArgs) := (← whnfD x).constructorApp? (← getEnv) then
if (← altsAreCtorLike p) then
let alts ← p.alts.filterMapM fun alt => do
match alt.patterns with
| .ctor ctorName _ _ fields :: ps =>
if ctorName != ctorVal.name then
return none
else
return some { alt with patterns := fields ++ ps }
| .inaccessible _ :: _ => processInaccessibleAsCtor alt ctorVal.name
| _ => unreachable!
let xFields := xArgs.extract ctorVal.numParams xArgs.size
return { p with alts := alts, vars := xFields.toList ++ xs }
let alts ← p.alts.mapM fun alt => do
match alt.patterns with
| p :: ps => return { alt with patterns := ps, cnstrs := (x, ← p.toExpr) :: alt.cnstrs }
| _ => unreachable!
return { p with alts := alts, vars := xs }
private def collectValues (p : Problem) : Array Expr :=
p.alts.foldl (init := #[]) fun values alt =>
match alt.patterns with
| .val v :: _ => if values.contains v then values else values.push v
| _ => values
private def isFirstPatternVar (alt : Alt) : Bool :=
match alt.patterns with
| .var _ :: _ => true
| _ => false
private def processValue (p : Problem) : MetaM (Array Problem) := do
trace[Meta.Match.match] "value step"
let x :: xs := p.vars | unreachable!
let values := collectValues p
let subgoals ← caseValues p.mvarId x.fvarId! values (substNewEqs := true)
subgoals.mapIdxM fun i subgoal => do
trace[Meta.Match.match] "processValue subgoal\n{MessageData.ofGoal subgoal.mvarId}"
if h : i.val < values.size then
let value := values.get ⟨i, h⟩
-- (x = value) branch
let subst := subgoal.subst
trace[Meta.Match.match] "processValue subst: {subst.map.toList.map fun p => mkFVar p.1}, {subst.map.toList.map fun p => p.2}"
let examples := p.examples.map <| Example.replaceFVarId x.fvarId! (Example.val value)
let examples := examples.map <| Example.applyFVarSubst subst
let newAlts := p.alts.filter fun alt => match alt.patterns with
| .val v :: _ => v == value
| .var _ :: _ => true
| _ => false
let newAlts := newAlts.map fun alt => alt.applyFVarSubst subst
let newAlts := newAlts.map fun alt => match alt.patterns with
| .val _ :: ps => { alt with patterns := ps }
| .var fvarId :: ps =>
let alt := { alt with patterns := ps }
alt.replaceFVarId fvarId value
| _ => unreachable!
let newVars := xs.map fun x => x.applyFVarSubst subst
return { mvarId := subgoal.mvarId, vars := newVars, alts := newAlts, examples := examples }
else
-- else branch for value
let newAlts := p.alts.filter isFirstPatternVar
return { p with mvarId := subgoal.mvarId, alts := newAlts, vars := x::xs }
private def collectArraySizes (p : Problem) : Array Nat :=
p.alts.foldl (init := #[]) fun sizes alt =>
match alt.patterns with
| .arrayLit _ ps :: _ => let sz := ps.length; if sizes.contains sz then sizes else sizes.push sz
| _ => sizes
private def expandVarIntoArrayLit (alt : Alt) (fvarId : FVarId) (arrayElemType : Expr) (arraySize : Nat) : MetaM Alt :=
withExistingLocalDecls alt.fvarDecls do
let fvarDecl ← fvarId.getDecl
let varNamePrefix := fvarDecl.userName
let rec loop (n : Nat) (newVars : Array Expr) := do
match n with
| n+1 =>
withLocalDeclD (varNamePrefix.appendIndexAfter (n+1)) arrayElemType fun x =>
loop n (newVars.push x)
| 0 =>
let arrayLit ← mkArrayLit arrayElemType newVars.toList
let alt := alt.replaceFVarId fvarId arrayLit
let newDecls ← newVars.toList.mapM fun newVar => newVar.fvarId!.getDecl
let newPatterns := newVars.toList.map fun newVar => .var newVar.fvarId!
return { alt with fvarDecls := newDecls ++ alt.fvarDecls, patterns := newPatterns ++ alt.patterns }
loop arraySize #[]
private def processArrayLit (p : Problem) : MetaM (Array Problem) := do
trace[Meta.Match.match] "array literal step"
let x :: xs := p.vars | unreachable!
let sizes := collectArraySizes p
let subgoals ← caseArraySizes p.mvarId x.fvarId! sizes
subgoals.mapIdxM fun i subgoal => do
if i.val < sizes.size then
let size := sizes.get! i
let subst := subgoal.subst
let elems := subgoal.elems.toList
let newVars := elems.map mkFVar ++ xs
let newVars := newVars.map fun x => x.applyFVarSubst subst
let subex := Example.arrayLit <| elems.map Example.var
let examples := p.examples.map <| Example.replaceFVarId x.fvarId! subex
let examples := examples.map <| Example.applyFVarSubst subst
let newAlts := p.alts.filter fun alt => match alt.patterns with
| .arrayLit _ ps :: _ => ps.length == size
| .var _ :: _ => true
| _ => false
let newAlts := newAlts.map fun alt => alt.applyFVarSubst subst
let newAlts ← newAlts.mapM fun alt => do
match alt.patterns with
| .arrayLit _ pats :: ps => return { alt with patterns := pats ++ ps }
| .var fvarId :: ps =>
let α ← getArrayArgType <| subst.apply x
expandVarIntoArrayLit { alt with patterns := ps } fvarId α size
| _ => unreachable!
return { mvarId := subgoal.mvarId, vars := newVars, alts := newAlts, examples := examples }
else
-- else branch
let newAlts := p.alts.filter isFirstPatternVar
return { p with mvarId := subgoal.mvarId, alts := newAlts, vars := x::xs }
private def expandNatValuePattern (p : Problem) : Problem :=
let alts := p.alts.map fun alt => match alt.patterns with
| .val (.lit (.natVal 0)) :: ps => { alt with patterns := .ctor ``Nat.zero [] [] [] :: ps }
| .val (.lit (.natVal (n+1))) :: ps => { alt with patterns := .ctor ``Nat.succ [] [] [.val (mkRawNatLit n)] :: ps }
| _ => alt
{ p with alts := alts }
private def traceStep (msg : String) : StateRefT State MetaM Unit := do
trace[Meta.Match.match] "{msg} step"
private def traceState (p : Problem) : MetaM Unit :=
withGoalOf p (traceM `Meta.Match.match p.toMessageData)
private def throwNonSupported (p : Problem) : MetaM Unit :=
withGoalOf p do
let msg ← p.toMessageData
throwError "failed to compile pattern matching, stuck at{indentD msg}"
def isCurrVarInductive (p : Problem) : MetaM Bool := do
match p.vars with
| [] => return false
| x::_ => withGoalOf p do
let val? ← getInductiveVal? x
return val?.isSome
private def checkNextPatternTypes (p : Problem) : MetaM Unit := do
match p.vars with
| [] => return ()
| x::_ => withGoalOf p do
for alt in p.alts do
withRef alt.ref do
match alt.patterns with
| [] => return ()
| p::_ =>
let e ← p.toExpr
let xType ← inferType x
let eType ← inferType e
unless (← isDefEq xType eType) do
throwError "pattern{indentExpr e}\n{← mkHasTypeButIsExpectedMsg eType xType}"
private partial def process (p : Problem) : StateRefT State MetaM Unit := do
traceState p
let isInductive ← isCurrVarInductive p
if isDone p then
traceStep ("leaf")
processLeaf p
else if hasAsPattern p then
traceStep ("as-pattern")
let p ← processAsPattern p
process p
else if isNatValueTransition p then
traceStep ("nat value to constructor")
process (expandNatValuePattern p)
else if !isNextVar p then
traceStep ("non variable")
let p ← processNonVariable p
process p
else if isInductive && isConstructorTransition p then
let ps ← processConstructor p
ps.forM process
else if isVariableTransition p then
traceStep ("variable")
let p ← processVariable p
process p
else if isValueTransition p then
let ps ← processValue p
ps.forM process
else if isArrayLitTransition p then
let ps ← processArrayLit p
ps.forM process
else if hasNatValPattern p then
-- This branch is reachable when `p`, for example, is just values without an else-alternative.
-- We added it just to get better error messages.
traceStep ("nat value to constructor")
process (expandNatValuePattern p)
else
checkNextPatternTypes p
throwNonSupported p
private def getUElimPos? (matcherLevels : List Level) (uElim : Level) : MetaM (Option Nat) :=
if uElim == levelZero then
return none
else match matcherLevels.toArray.indexOf? uElim with
| none => throwError "dependent match elimination failed, universe level not found"
| some pos => return some pos.val
/- See comment at `mkMatcher` before `mkAuxDefinition` -/
register_builtin_option bootstrap.genMatcherCode : Bool := {
defValue := true
group := "bootstrap"
descr := "disable code generation for auxiliary matcher function"
}
builtin_initialize matcherExt : EnvExtension (Std.PHashMap (Expr × Bool) Name) ← registerEnvExtension (pure {})
/-- Similar to `mkAuxDefinition`, but uses the cache `matcherExt`.
It also returns an Boolean that indicates whether a new matcher function was added to the environment or not. -/
def mkMatcherAuxDefinition (name : Name) (type : Expr) (value : Expr) : MetaM (Expr × Option (MatcherInfo → MetaM Unit)) := do
trace[Meta.Match.debug] "{name} : {type} := {value}"
let compile := bootstrap.genMatcherCode.get (← getOptions)
let result ← Closure.mkValueTypeClosure type value (zeta := false)
let env ← getEnv
let mkMatcherConst name :=
mkAppN (mkConst name result.levelArgs.toList) result.exprArgs
match (matcherExt.getState env).find? (result.value, compile) with
| some nameNew => return (mkMatcherConst nameNew, none)
| none =>
let decl := Declaration.defnDecl {
name
levelParams := result.levelParams.toList
type := result.type
value := result.value
hints := ReducibilityHints.abbrev
safety := if env.hasUnsafe result.type || env.hasUnsafe result.value then DefinitionSafety.unsafe else DefinitionSafety.safe
}
trace[Meta.Match.debug] "{name} : {result.type} := {result.value}"
let addMatcher : MatcherInfo → MetaM Unit := fun mi => do
addDecl decl
modifyEnv fun env => matcherExt.modifyState env fun s => s.insert (result.value, compile) name
addMatcherInfo name mi
setInlineAttribute name
if compile then
compileDecl decl
return (mkMatcherConst name, some addMatcher)
structure MkMatcherInput where
matcherName : Name
matchType : Expr
discrInfos : Array DiscrInfo
lhss : List AltLHS
def MkMatcherInput.numDiscrs (m : MkMatcherInput) :=
m.discrInfos.size
def MkMatcherInput.collectFVars (m : MkMatcherInput) : StateRefT CollectFVars.State MetaM Unit := do
m.matchType.collectFVars
m.lhss.forM fun alt => alt.collectFVars
def MkMatcherInput.collectDependencies (m : MkMatcherInput) : MetaM FVarIdSet := do
let (_, s) ← m.collectFVars |>.run {}
let s ← s.addDependencies
return s.fvarSet
/--
Auxiliary method used at `mkMatcher`. It executes `k` in a local context that contains only
the local declarations `m` depends on. This is important because otherwise dependent elimination
may "refine" the types of unnecessary declarations and accidentally introduce unnecessary dependencies
in the auto-generated auxiliary declaration. Note that this is not just an optimization because the
unnecessary dependencies may prevent the termination checker from succeeding. For an example,
see issue #1237.
-/
def withCleanLCtxFor (m : MkMatcherInput) (k : MetaM α) : MetaM α := do
let s ← m.collectDependencies
let lctx ← getLCtx
let lctx := lctx.foldr (init := lctx) fun localDecl lctx =>
if s.contains localDecl.fvarId then lctx else lctx.erase localDecl.fvarId
let localInstances := (← getLocalInstances).filter fun localInst => s.contains localInst.fvar.fvarId!
withLCtx lctx localInstances k
/--
Create a dependent matcher for `matchType` where `matchType` is of the form
`(a_1 : A_1) -> (a_2 : A_2[a_1]) -> ... -> (a_n : A_n[a_1, a_2, ... a_{n-1}]) -> B[a_1, ..., a_n]`
where `n = numDiscrs`, and the `lhss` are the left-hand-sides of the `match`-expression alternatives.
Each `AltLHS` has a list of local declarations and a list of patterns.
The number of patterns must be the same in each `AltLHS`.
The generated matcher has the structure described at `MatcherInfo`. The motive argument is of the form
`(motive : (a_1 : A_1) -> (a_2 : A_2[a_1]) -> ... -> (a_n : A_n[a_1, a_2, ... a_{n-1}]) -> Sort v)`
where `v` is a universe parameter or 0 if `B[a_1, ..., a_n]` is a proposition. -/
def mkMatcher (input : MkMatcherInput) : MetaM MatcherResult := withCleanLCtxFor input do
let ⟨matcherName, matchType, discrInfos, lhss⟩ := input
let numDiscrs := discrInfos.size
let numEqs := getNumEqsFromDiscrInfos discrInfos
checkNumPatterns numDiscrs lhss
forallBoundedTelescope matchType numDiscrs fun discrs matchTypeBody => do
/- We generate an matcher that can eliminate using different motives with different universe levels.
`uElim` is the universe level the caller wants to eliminate to.
If it is not levelZero, we create a matcher that can eliminate in any universe level.
This is useful for implementing `MatcherApp.addArg` because it may have to change the universe level. -/
let uElim ← getLevel matchTypeBody
let uElimGen ← if uElim == levelZero then pure levelZero else mkFreshLevelMVar
let mkMatcher (type val : Expr) (minors : Array (Expr × Nat)) (s : State) : MetaM MatcherResult := do
trace[Meta.Match.debug] "matcher value: {val}\ntype: {type}"
trace[Meta.Match.debug] "minors num params: {minors.map (·.2)}"
/- The option `bootstrap.gen_matcher_code` is a helper hack. It is useful, for example,
for compiling `src/Init/Data/Int`. It is needed because the compiler uses `Int.decLt`
for generating code for `Int.casesOn` applications, but `Int.casesOn` is used to
give the reference implementation for
```
@[extern "lean_int_neg"] def neg (n : @& Int) : Int :=
match n with
| ofNat n => negOfNat n
| negSucc n => succ n
```
which is defined **before** `Int.decLt` -/
let (matcher, addMatcher) ← mkMatcherAuxDefinition matcherName type val
trace[Meta.Match.debug] "matcher levels: {matcher.getAppFn.constLevels!}, uElim: {uElimGen}"
let uElimPos? ← getUElimPos? matcher.getAppFn.constLevels! uElimGen
discard <| isLevelDefEq uElimGen uElim
let addMatcher :=
match addMatcher with
| some addMatcher => addMatcher <|
{ numParams := matcher.getAppNumArgs
altNumParams := minors.map fun minor => minor.2 + numEqs
discrInfos
numDiscrs
uElimPos?
}
| none => pure ()
trace[Meta.Match.debug] "matcher: {matcher}"
let unusedAltIdxs := lhss.length.fold (init := []) fun i r =>
if s.used.contains i then r else i::r
return {
matcher,
counterExamples := s.counterExamples,
unusedAltIdxs := unusedAltIdxs.reverse,
addMatcher
}
let motiveType ← mkForallFVars discrs (mkSort uElimGen)
trace[Meta.Match.debug] "motiveType: {motiveType}"
withLocalDeclD `motive motiveType fun motive => do
if discrInfos.any fun info => info.hName?.isSome then
forallBoundedTelescope matchType numDiscrs fun discrs' _ => do
let (mvarType, isEqMask) ← withEqs discrs discrs' discrInfos fun eqs => do
let mvarType ← mkForallFVars eqs (mkAppN motive discrs')
let isEqMask ← eqs.mapM fun eq => return (← inferType eq).isEq
return (mvarType, isEqMask)
trace[Meta.Match.debug] "target: {mvarType}"
withAlts motive discrs discrInfos lhss fun alts minors => do
let mvar ← mkFreshExprMVar mvarType
trace[Meta.Match.debug] "goal\n{mvar.mvarId!}"
let examples := discrs'.toList.map fun discr => Example.var discr.fvarId!
let (_, s) ← (process { mvarId := mvar.mvarId!, vars := discrs'.toList, alts := alts, examples := examples }).run {}
let val ← mkLambdaFVars discrs' mvar
trace[Meta.Match.debug] "matcher\nvalue: {val}\ntype: {← inferType val}"
let mut rfls := #[]
let mut isEqMaskIdx := 0
for discr in discrs, info in discrInfos do
if info.hName?.isSome then
if isEqMask[isEqMaskIdx]! then
rfls := rfls.push (← mkEqRefl discr)
else
rfls := rfls.push (← mkHEqRefl discr)
isEqMaskIdx := isEqMaskIdx + 1
let val := mkAppN (mkAppN val discrs) rfls
let args := #[motive] ++ discrs ++ minors.map Prod.fst
let val ← mkLambdaFVars args val
let type ← mkForallFVars args (mkAppN motive discrs)
mkMatcher type val minors s
else
let mvarType := mkAppN motive discrs
trace[Meta.Match.debug] "target: {mvarType}"
withAlts motive discrs discrInfos lhss fun alts minors => do
let mvar ← mkFreshExprMVar mvarType
let examples := discrs.toList.map fun discr => Example.var discr.fvarId!
let (_, s) ← (process { mvarId := mvar.mvarId!, vars := discrs.toList, alts := alts, examples := examples }).run {}
let args := #[motive] ++ discrs ++ minors.map Prod.fst
let type ← mkForallFVars args mvarType
let val ← mkLambdaFVars args mvar
mkMatcher type val minors s
def getMkMatcherInputInContext (matcherApp : MatcherApp) : MetaM MkMatcherInput := do
let matcherName := matcherApp.matcherName
let some matcherInfo ← getMatcherInfo? matcherName | throwError "not a matcher: {matcherName}"
let matcherConst ← getConstInfo matcherName
let matcherType ← instantiateForall matcherConst.type <| matcherApp.params ++ #[matcherApp.motive]
let matchType ← do
let u :=
if let some idx := matcherInfo.uElimPos?
then mkLevelParam matcherConst.levelParams.toArray[idx]!
else levelZero
forallBoundedTelescope matcherType (some matcherInfo.numDiscrs) fun discrs _ => do
mkForallFVars discrs (mkConst ``PUnit [u])
let matcherType ← instantiateForall matcherType matcherApp.discrs
let lhss ← forallBoundedTelescope matcherType (some matcherApp.alts.size) fun alts _ =>
alts.mapM fun alt => do
let ty ← inferType alt
forallTelescope ty fun xs body => do
let xs ← xs.filterM fun x => dependsOn body x.fvarId!
body.withApp fun _ args => do
let ctx ← getLCtx
let localDecls := xs.map ctx.getFVar!
let patterns ← args.mapM Match.toPattern
return {
ref := Syntax.missing
fvarDecls := localDecls.toList
patterns := patterns.toList : Match.AltLHS }
return { matcherName, matchType, discrInfos := matcherInfo.discrInfos, lhss := lhss.toList }
/-- This function is only used for testing purposes -/
def withMkMatcherInput (matcherName : Name) (k : MkMatcherInput → MetaM α) : MetaM α := do
let some matcherInfo ← getMatcherInfo? matcherName | throwError "not a matcher: {matcherName}"
let matcherConst ← getConstInfo matcherName
forallBoundedTelescope matcherConst.type (some matcherInfo.arity) fun xs _ => do
let matcherApp ← mkConstWithLevelParams matcherConst.name
let matcherApp := mkAppN matcherApp xs
let some matcherApp ← matchMatcherApp? matcherApp | throwError "not a matcher app: {matcherApp}"
let mkMatcherInput ← getMkMatcherInputInContext matcherApp
k mkMatcherInput
end Match
/-- Auxiliary function for MatcherApp.addArg -/
private partial def updateAlts (typeNew : Expr) (altNumParams : Array Nat) (alts : Array Expr) (i : Nat) : MetaM (Array Nat × Array Expr) := do
if h : i < alts.size then
let alt := alts.get ⟨i, h⟩
let numParams := altNumParams[i]!
let typeNew ← whnfD typeNew
match typeNew with
| Expr.forallE _ d b _ =>
let alt ← forallBoundedTelescope d (some numParams) fun xs d => do
let alt ← try instantiateLambda alt xs catch _ => throwError "unexpected matcher application, insufficient number of parameters in alternative"
forallBoundedTelescope d (some 1) fun x _ => do
let alt ← mkLambdaFVars x alt -- x is the new argument we are adding to the alternative
mkLambdaFVars xs alt
updateAlts (b.instantiate1 alt) (altNumParams.set! i (numParams+1)) (alts.set ⟨i, h⟩ alt) (i+1)
| _ => throwError "unexpected type at MatcherApp.addArg"
else
return (altNumParams, alts)
/-- Given
- matcherApp `match_i As (fun xs => motive[xs]) discrs (fun ys_1 => (alt_1 : motive (C_1[ys_1])) ... (fun ys_n => (alt_n : motive (C_n[ys_n]) remaining`, and
- expression `e : B[discrs]`,
Construct the term
`match_i As (fun xs => B[xs] -> motive[xs]) discrs (fun ys_1 (y : B[C_1[ys_1]]) => alt_1) ... (fun ys_n (y : B[C_n[ys_n]]) => alt_n) e remaining`, and
We use `kabstract` to abstract the discriminants from `B[discrs]`.
This method assumes
- the `matcherApp.motive` is a lambda abstraction where `xs.size == discrs.size`
- each alternative is a lambda abstraction where `ys_i.size == matcherApp.altNumParams[i]`
-/
def MatcherApp.addArg (matcherApp : MatcherApp) (e : Expr) : MetaM MatcherApp :=
lambdaTelescope matcherApp.motive fun motiveArgs motiveBody => do
unless motiveArgs.size == matcherApp.discrs.size do
-- This error can only happen if someone implemented a transformation that rewrites the motive created by `mkMatcher`.
throwError "unexpected matcher application, motive must be lambda expression with #{matcherApp.discrs.size} arguments"
let eType ← inferType e
let eTypeAbst ← matcherApp.discrs.size.foldRevM (init := eType) fun i eTypeAbst => do
let motiveArg := motiveArgs[i]!
let discr := matcherApp.discrs[i]!
let eTypeAbst ← kabstract eTypeAbst discr
return eTypeAbst.instantiate1 motiveArg
let motiveBody ← mkArrow eTypeAbst motiveBody
let matcherLevels ← match matcherApp.uElimPos? with
| none => pure matcherApp.matcherLevels
| some pos =>
let uElim ← getLevel motiveBody
pure <| matcherApp.matcherLevels.set! pos uElim
let motive ← mkLambdaFVars motiveArgs motiveBody
-- Construct `aux` `match_i As (fun xs => B[xs] → motive[xs]) discrs`, and infer its type `auxType`.
-- We use `auxType` to infer the type `B[C_i[ys_i]]` of the new argument in each alternative.
let aux := mkAppN (mkConst matcherApp.matcherName matcherLevels.toList) matcherApp.params
let aux := mkApp aux motive
let aux := mkAppN aux matcherApp.discrs
unless (← isTypeCorrect aux) do
throwError "failed to add argument to matcher application, type error when constructing the new motive"
let auxType ← inferType aux
let (altNumParams, alts) ← updateAlts auxType matcherApp.altNumParams matcherApp.alts 0
return { matcherApp with
matcherLevels := matcherLevels,
motive := motive,
alts := alts,
altNumParams := altNumParams,
remaining := #[e] ++ matcherApp.remaining
}
/-- Similar `MatcherApp.addArg?`, but returns `none` on failure. -/
def MatcherApp.addArg? (matcherApp : MatcherApp) (e : Expr) : MetaM (Option MatcherApp) :=
try
return some (← matcherApp.addArg e)
catch _ =>
return none
builtin_initialize
registerTraceClass `Meta.Match.match
registerTraceClass `Meta.Match.debug
registerTraceClass `Meta.Match.unify
end Lean.Meta
|
c605d8b677d178a7cc98356129f444801b452704 | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /tests/lean/num2.lean | 2516627d7f843ac4da5906c63f6840cafc2ea173 | [
"Apache-2.0"
] | permissive | codyroux/lean | 7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3 | 0cca265db19f7296531e339192e9b9bae4a31f8b | refs/heads/master | 1,610,909,964,159 | 1,407,084,399,000 | 1,416,857,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 335 | lean | set_option pp.notation false
definition Prop := Type.{0}
constant eq {A : Type} : A → A → Prop
infixl `=`:50 := eq
constant N : Type.{1}
constant z : N
constant o : N
constant b : N
notation 0 := z
notation 1 := o
check 1
check 0
constant G : Type.{1}
constant gz : G
constant a : G
notation 0 := gz
check 0 = a
check b = 0
|
0eebde3f46f727856d5e6adc21dd762542bb2061 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/playground/forIn.lean | e237e81292e6080bd9df63073970acc11abfd144 | [
"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 | 4,522 | lean |
namespace ForIn
inductive Step.{u} (α : Type u)
| done : α → Step α
| yield : α → Step α
class Fold.{u, v, w, z} (m : Type w → Type z) [Monad m] (α : outParam (Type u)) (s : Type v) : Type (max v u z (w+1)):=
(fold {β : Type w} (as : s) (init : β) (f : α → β → m (Step β)) : m β)
export Fold (fold)
class FoldMap.{u, w} (m : Type u → Type w) [Monad m] (s : Type u → Type u) : Type (max (u+1) w):=
(foldMap {α β : Type u} (as : s α) (init : β) (f : α → β → m (Step (α × β))) : m (s α × β))
export FoldMap (foldMap)
@[inline] instance {m} {α} [Monad m] : Fold m α (List α) :=
{ fold := fun as init f =>
let rec @[specialize] loop
| [], b => pure b
| a::as, b => do
let s ← f a b
(match s with
| Step.done b => pure b
| Step.yield b => loop as b)
loop as init }
@[inline] instance {m} [Monad m] : FoldMap m List :=
{ foldMap := fun as init f =>
let rec @[specialize] loop
| [], rs, b => pure (rs.reverse, b)
| a::as, rs, b => do
let s ← f a b
(match s with
| Step.done (a, b) => pure ((a :: rs).reverse ++ as, b)
| Step.yield (a, b) => loop as (a::rs) b)
loop as [] init }
def tst1 : IO Nat :=
fold [1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 14] 0 fun a b =>
if a % 2 == 0 then do
IO.println (">> " ++ toString a ++ " " ++ toString b)
(if b > 20 then return Step.done b
else return Step.yield (a+b))
else
return Step.yield b
#eval tst1
def tst1' : IO Unit := do
let (as, b) ← foldMap [1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 14] 0 fun a b =>
if a % 2 == 0 then do
IO.println (">> " ++ toString a ++ " " ++ toString b)
(if b > 20 then return Step.done (a, b)
else return Step.yield (a/2, a+b))
else
return Step.yield (a, b)
IO.println as
IO.println b
pure ()
#eval tst1'
instance Prod.fold {m α β γ δ} [Monad m] [i₁ : Fold m α γ] [i₂ : Fold m β δ] : Fold m (α × β) (γ × δ) :=
{ fold := fun s init f =>
Fold.fold s.1 init fun a x => do
Fold.fold s.2 (Step.yield x) fun b x =>
match x with
| Step.done _ => return Step.done x
| Step.yield x => do
let s ← f (a, b) x
(match s with
| Step.done _ => return Step.done s
| Step.yield _ => return Step.yield s) }
def tst2 (threshold : Nat) : IO Nat :=
fold ([1, 2, 3, 4, 5, 10], [10, 20, 30, 40, 50]) 0 fun (a, b) s => do
IO.println (">> " ++ toString a ++ ", " ++ toString b ++ ", " ++ toString s)
(if s > threshold then return Step.done s
else return Step.yield (s+a+b))
#eval tst2 170
#eval tst2 800
structure Range :=
(lower upper : Nat)
@[inline] instance Range.fold {m} [Monad m] : Fold m Nat Range :=
{ fold := fun s init f =>
let base := s.lower + s.upper - 2
let rec @[specialize] loop : Nat → _ → _
| 0, b => pure b
| i+1, b =>
let j := base - i
if j >= s.upper then return b
else do
let s ← f j b
(match s with
| Step.done b => return b
| Step.yield b => loop i b)
loop (s.upper - 1) init }
@[inline] def range (a : Nat) (b : Option Nat := none) : Range :=
match b with
| none => ⟨0, a⟩
| some b => ⟨a, b⟩
instance : OfNat (Option Nat) :=
⟨fun n => some n⟩
def tst3 : IO Nat :=
fold (range 5 10) 0 fun i s => do
IO.println (">> " ++ toString i)
return Step.yield (s+i)
#eval tst3
theorem zeroLtOfLt : {a b : Nat} → a < b → 0 < b
| 0, _, h => h
| a+1, b, h =>
have a < b from Nat.ltTrans (Nat.ltSuccSelf _) h
zeroLtOfLt this
@[inline] instance {m} {α} [Monad m] : Fold m α (Array α) :=
{ fold := fun as init f =>
let rec @[specialize] loop : (i : Nat) → i ≤ as.size → _
| 0, h, b => pure b
| i+1, h, b =>
have h' : i < as.size from Nat.ltOfLtOfLe (Nat.ltSuccSelf i) h
have as.size - 1 < as.size from Nat.subLt (zeroLtOfLt h') (decide! (0 < 1))
have as.size - 1 - i < as.size from Nat.ltOfLeOfLt (Nat.subLe (as.size - 1) i) this; do
let s ← f (as.get ⟨as.size - 1 - i, this⟩) b
(match s with
| Step.done b => pure b
| Step.yield b => loop i (Nat.leOfLt h') b)
loop as.size (Nat.leRefl _) init }
-- set_option trace.compiler.ir.result true
def tst4 : IO Nat :=
fold (#[1, 2, 3, 4, 5] : Array Nat) 0 fun a b => do
IO.println (">> " ++ toString a ++ " " ++ toString b)
return Step.yield (a+b)
#eval tst4
end ForIn
|
98e05d92bfd6d7694f81c4b1b1e389d84b2b93bb | c31182a012eec69da0a1f6c05f42b0f0717d212d | /src/breen_deligne/eg.lean | 12221ae0af36581e2e1b196b23bb5242220c6fb5 | [] | no_license | Ja1941/lean-liquid | fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc | 8e80ed0cbdf5145d6814e833a674eaf05a1495c1 | refs/heads/master | 1,689,437,983,362 | 1,628,362,719,000 | 1,628,362,719,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,874 | lean | import breen_deligne.constants
open_locale nnreal
namespace breen_deligne
namespace eg
/-!
# An explicit nontrivial example of Breen-Deligne data
This example is explained in Definition 1.10 of
the blueprint https://leanprover-community.github.io/liquid/ .
-/
open universal_map
/-- The `i`-th rank of this BD package is `2^i`. -/
def rank (i : ℕ) : FreeMat := 2 ^ i
/-- `σπ n` is an abreviation for `proj n 2 - sum n 2`. -/
def σπ (n : ℕ) := universal_map.proj n 2 - universal_map.sum n 2
lemma σπ_comp_mul_two {m n} (f : universal_map m n) :
comp (σπ n) (mul 2 f) = comp f (σπ m) :=
by simp only [σπ, add_monoid_hom.map_sub, add_monoid_hom.sub_apply, sum_comp_mul, proj_comp_mul]
/-- The `i`-th map of this BD package is inductively defined
as the simplest solution to the homotopy condition,
so that the homotopy will consist of identity maps. -/
def map : Π n, rank (n+1) ⟶ rank n
| 0 := σπ 1
| (n+1) := σπ (rank (n+1)) - mul 2 (map n)
lemma map_succ (n : ℕ) : map (n+1) = σπ (rank (n+1)) - mul 2 (map n) := rfl
lemma is_complex_zero : map 1 ≫ map 0 = 0 :=
show comp (σπ 1) (σπ 2 - mul 2 (σπ 1)) = 0,
by { rw [add_monoid_hom.map_sub, σπ_comp_mul_two, sub_eq_zero], refl }
lemma is_complex_succ (n : ℕ) (ih : (comp (map n)) (map (n + 1)) = 0) :
comp (map (n+1)) (map (n+1+1)) = 0 :=
by rw [map_succ (n+1), add_monoid_hom.map_sub, ← σπ_comp_mul_two, ← add_monoid_hom.sub_apply,
← add_monoid_hom.map_sub, map_succ n, sub_sub_cancel, ← mul_comp, ← map_succ, ih,
add_monoid_hom.map_zero]
/-- The Breen--Deligne data for the example BD package. -/
def BD : data :=
{ X := rank,
d := λ i j, if h : j + 1 = i then by subst h; exact map j else 0,
shape' := λ i j h, dif_neg h,
d_comp_d' :=
begin
rintro i j k (rfl : j + 1 = i) (rfl : k + 1 = j),
simp only [dif_pos rfl],
induction k with k ih,
{ exact is_complex_zero },
{ exact is_complex_succ k ih }
end }
open category_theory category_theory.limits category_theory.preadditive
open homological_complex
/-- The `n`-th homotopy map for the example BD package is the identity. -/
def hmap : Π (j i : ℕ) (h : j + 1 = i), (((data.mul 2).obj BD).X j) ⟶ (BD.X i)
| j i rfl := 𝟙 _
/-- The identity maps form a homotopy between the chain maps `proj 2` and `sum 2`
for the Breen--Deligne data `eg.BD`. -/
def h : homotopy (BD.proj 2) (BD.sum 2) :=
{ hom := λ j i, if h : j + 1 = i then hmap j i h else 0,
zero' := λ i j h, dif_neg h,
comm :=
begin
intros j,
rw [d_next_nat, prev_d_eq], swap 2, { dsimp, refl },
cases j,
{ dsimp, rw [dif_pos rfl, dif_neg, comp_zero, zero_add],
swap, { dec_trivial },
dsimp [BD, hmap, map, σπ],
erw [dif_pos rfl, category.id_comp, ← sub_eq_iff_eq_add], refl, },
{ rw [dif_pos rfl, dif_pos], swap 2, { refl },
dsimp [BD, hmap, map, σπ],
erw [dif_pos rfl, dif_pos rfl, category.id_comp],
dsimp [nat.succ_eq_add_one],
erw [hmap, category.comp_id, ← sub_eq_iff_eq_add, add_sub, eq_comm, sub_eq_iff_eq_add'],
refl },
end }
end eg
/-- An example of a Breen--Deligne package coming from a nontrivial complex. -/
def eg : package := ⟨eg.BD, eg.h⟩
namespace eg
noncomputable theory
variables (r r' : ℝ≥0) [fact (r < 1)]
/-- Very suitable sequence of constants for the example Breen--Deligne package -/
def κ : ℕ → ℝ≥0 :=
eg.data.κ r r'
instance very_suitable [fact (0 < r')] : eg.data.very_suitable r r' (κ r r') :=
eg.data.c_very_suitable _ _
instance [fact (0 < r')] (n : ℕ) : fact (0 < κ r r' n) :=
data.c__pos _ _ _ _
/-- Adept sequence of constants for the example Breen--Deligne package -/
def κ' : ℕ → ℝ≥0 :=
eg.κ' (eg.κ r r')
instance adept [fact (0 < r')] : package.adept eg (κ r r') (κ' r r') :=
eg.κ'_adept _
end eg
end breen_deligne
#lint-
|
de325f69cb38af819cc49c3fca88151e7d1f7842 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/1385.lean | dffa4d1d3c9039634f551de70ce80198319bf766 | [
"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 | 1,029 | lean | def S := List Nat
opaque TSpec : NonemptyType
def T (s : S) : Type := TSpec.type
instance (s : S) : Nonempty (T s) :=
TSpec.property
inductive Op : (ishapes : List S) → (oshape : S) → Type
| binary : (shape : S) → Op [shape, shape] shape
| gemm : {m n p : Nat} → Op [[m, n], [n, p]] [m, p]
noncomputable def Op.f : {ishapes : List S} → {oshape : S} → Op ishapes oshape → T oshape
| [shape, _], _, binary _ => Classical.ofNonempty
| [[m, n], [_, p]], [_, _], gemm => Classical.ofNonempty
#print Op.f
noncomputable def Op.f2 : {ishapes : List S} → {oshape : S} → Op ishapes oshape → T oshape
| _, _, binary _ => Classical.ofNonempty
| _, _, gemm => Classical.ofNonempty
#print Op.f2
noncomputable def Op.f2' {ishapes : List S} {oshape : S} : Op ishapes oshape → T oshape
| binary _ => Classical.ofNonempty
| gemm => Classical.ofNonempty
noncomputable def Op.f2'' : Op i o → T o
| binary _ => Classical.ofNonempty
| gemm => Classical.ofNonempty
|
ce0f6548b8157a8a878da2a48ff70984ae4bcf62 | 31f556cdeb9239ffc2fad8f905e33987ff4feab9 | /stage0/src/Lean/Elab/Tactic/Delta.lean | 3e9b7fae76c7c2bb10fbc91198c68bd39142463d | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | tobiasgrosser/lean4 | ce0fd9cca0feba1100656679bf41f0bffdbabb71 | ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f | refs/heads/master | 1,673,103,412,948 | 1,664,930,501,000 | 1,664,930,501,000 | 186,870,185 | 0 | 0 | Apache-2.0 | 1,665,129,237,000 | 1,557,939,901,000 | Lean | UTF-8 | Lean | false | false | 1,436 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Tactic.Delta
import Lean.Elab.Tactic.Basic
import Lean.Elab.Tactic.Location
namespace Lean.Elab.Tactic
open Meta
def deltaLocalDecl (declNames : Array Name) (fvarId : FVarId) : TacticM Unit := do
let mvarId ← getMainGoal
let localDecl ← fvarId.getDecl
let typeNew ← deltaExpand localDecl.type declNames.contains
if typeNew == localDecl.type then
throwTacticEx `delta mvarId m!"did not delta reduce {declNames} at {localDecl.userName}"
replaceMainGoal [← mvarId.replaceLocalDeclDefEq fvarId typeNew]
def deltaTarget (declNames : Array Name) : TacticM Unit := do
let mvarId ← getMainGoal
let target ← getMainTarget
let targetNew ← deltaExpand target declNames.contains
if targetNew == target then
throwTacticEx `delta mvarId m!"did not delta reduce {declNames}"
replaceMainGoal [← mvarId.replaceTargetDefEq targetNew]
/-- "delta " ident+ (location)? -/
@[builtinTactic Lean.Parser.Tactic.delta] def evalDelta : Tactic := fun stx => do
let declNames ← stx[1].getArgs.mapM resolveGlobalConstNoOverloadWithInfo
let loc := expandOptLocation stx[2]
withLocation loc (deltaLocalDecl declNames) (deltaTarget declNames)
(throwTacticEx `delta · m!"did not delta reduce {declNames}")
end Lean.Elab.Tactic
|
a2e41bc4048c496d69c37dadbe72b2f5f27d1a47 | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/tactic/omega/nat/main.lean | a6abb2a6871221589aee0390997fc9eac733b555 | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 5,172 | lean | /-
Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Seul Baek
Main procedure for linear natural number arithmetic.
-/
import tactic.omega.prove_unsats
import tactic.omega.nat.dnf
import tactic.omega.nat.neg_elim
import tactic.omega.nat.sub_elim
open tactic
namespace omega
namespace nat
local notation `&` k := preterm.cst k
local infix ` ** ` : 300 := preterm.var
local notation t ` +* ` s := preterm.add t s
local notation t ` -* ` s := preterm.sub t s
local notation x ` =* ` y := form.eq x y
local notation x ` ≤* ` y := form.le x y
local notation `¬* ` p := form.not p
local notation p ` ∨* ` q := form.or p q
local notation p ` ∧* ` q := form.and p q
run_cmd mk_simp_attr `sugar_nat
attribute [sugar_nat]
not_le not_lt
nat.lt_iff_add_one_le
nat.succ_eq_add_one
or_false false_or
and_true true_and
ge gt mul_add add_mul mul_comm
classical.imp_iff_not_or
classical.iff_iff_not_or_and_or_not
meta def desugar := `[try {simp only with sugar_nat}]
lemma univ_close_of_unsat_neg_elim_not (m) (p : form) :
(neg_elim (¬* p)).unsat → univ_close p (λ _, 0) m :=
begin
intro h1, apply univ_close_of_valid,
apply valid_of_unsat_not, intro h2, apply h1,
apply form.sat_of_implies_of_sat implies_neg_elim h2,
end
meta def preterm.prove_sub_free : preterm → tactic expr
| (& m) := return `(trivial)
| (m ** n) := return `(trivial)
| (t +* s) :=
do x ← preterm.prove_sub_free t,
y ← preterm.prove_sub_free s,
return `(@and.intro (preterm.sub_free %%`(t))
(preterm.sub_free %%`(s)) %%x %%y)
| (_ -* _) := failed
meta def prove_neg_free : form → tactic expr
| (t =* s) := return `(trivial)
| (t ≤* s) := return `(trivial)
| (p ∨* q) :=
do x ← prove_neg_free p,
y ← prove_neg_free q,
return `(@and.intro (form.neg_free %%`(p))
(form.neg_free %%`(q)) %%x %%y)
| (p ∧* q) :=
do x ← prove_neg_free p,
y ← prove_neg_free q,
return `(@and.intro (form.neg_free %%`(p))
(form.neg_free %%`(q)) %%x %%y)
| _ := failed
meta def prove_sub_free : form → tactic expr
| (t =* s) :=
do x ← preterm.prove_sub_free t,
y ← preterm.prove_sub_free s,
return `(@and.intro (preterm.sub_free %%`(t))
(preterm.sub_free %%`(s)) %%x %%y)
| (t ≤* s) :=
do x ← preterm.prove_sub_free t,
y ← preterm.prove_sub_free s,
return `(@and.intro (preterm.sub_free %%`(t))
(preterm.sub_free %%`(s)) %%x %%y)
| (¬*p) := prove_sub_free p
| (p ∨* q) :=
do x ← prove_sub_free p,
y ← prove_sub_free q,
return `(@and.intro (form.sub_free %%`(p))
(form.sub_free %%`(q)) %%x %%y)
| (p ∧* q) :=
do x ← prove_sub_free p,
y ← prove_sub_free q,
return `(@and.intro (form.sub_free %%`(p))
(form.sub_free %%`(q)) %%x %%y)
/- Given a p : form, return the expr of a term t : p.unsat,
where p is subtraction- and negation-free. -/
meta def prove_unsat_sub_free (p : form) : tactic expr :=
do x ← prove_neg_free p,
y ← prove_sub_free p,
z ← prove_unsats (dnf p),
return `(unsat_of_unsat_dnf %%`(p) %%x %%y %%z)
/- Given a p : form, return the expr of a term t : p.unsat,
where p is negation-free. -/
meta def prove_unsat_neg_free : form → tactic expr | p :=
match p.sub_terms with
| none := prove_unsat_sub_free p
| (some (t,s)) :=
do x ← prove_unsat_neg_free (sub_elim t s p),
return `(unsat_of_unsat_sub_elim %%`(t) %%`(s) %%`(p) %%x)
end
/- Given a (m : nat) and (p : form),
return the expr of (t : univ_close m p) -/
meta def prove_univ_close (m : nat) (p : form) : tactic expr :=
do x ← prove_unsat_neg_free (neg_elim (¬*p)),
to_expr ``(univ_close_of_unsat_neg_elim_not %%`(m) %%`(p) %%x)
meta def to_preterm : expr → tactic preterm
| (expr.var k) := return (preterm.var 1 k)
| `(%%(expr.var k) * %%mx) :=
do m ← eval_expr nat mx,
return (preterm.var m k)
| `(%%t1x + %%t2x) :=
do t1 ← to_preterm t1x,
t2 ← to_preterm t2x,
return (preterm.add t1 t2)
| `(%%t1x - %%t2x) :=
do t1 ← to_preterm t1x,
t2 ← to_preterm t2x,
return (preterm.sub t1 t2)
| mx :=
do m ← eval_expr nat mx,
return (preterm.cst m)
meta def to_form_core : expr → tactic form
| `(%%tx1 = %%tx2) :=
do t1 ← to_preterm tx1,
t2 ← to_preterm tx2,
return (t1 =* t2)
| `(%%tx1 ≤ %%tx2) :=
do t1 ← to_preterm tx1,
t2 ← to_preterm tx2,
return (t1 ≤* t2)
| `(¬ %%px) := do p ← to_form_core px, return (¬* p)
| `(%%px ∨ %%qx) :=
do p ← to_form_core px,
q ← to_form_core qx,
return (p ∨* q)
| `(%%px ∧ %%qx) :=
do p ← to_form_core px,
q ← to_form_core qx,
return (p ∧* q)
| `(_ → %%px) := to_form_core px
| _ := failed
meta def to_form : nat → expr → tactic (form × nat)
| m `(_ → %%px) := to_form (m+1) px
| m x := do p ← to_form_core x, return (p,m)
meta def prove_lna : tactic expr :=
do (p,m) ← target >>= to_form 0,
prove_univ_close m p
end nat
end omega
open omega.nat
meta def omega_nat : tactic unit :=
desugar >> prove_lna >>= apply >> skip
|
d2e7a9e920675d6d2107e18b2b881b6e468c856c | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/linear_algebra/matrix/charpoly/minpoly.lean | f0722405b08807e3329b5196b4260153f29d402a | [
"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,852 | lean | /-
Copyright (c) 2020 Aaron Anderson, Jalex Stark. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson, Jalex Stark
-/
import linear_algebra.matrix.charpoly.coeff
import linear_algebra.matrix.to_lin
import ring_theory.power_basis
/-!
# The minimal polynomial divides the characteristic polynomial of a matrix.
-/
noncomputable theory
universes u v
open polynomial matrix
variables {R : Type u} [comm_ring R]
variables {n : Type v} [decidable_eq n] [fintype n]
open finset
variable {M : matrix n n R}
namespace matrix
theorem is_integral : is_integral R M := ⟨M.charpoly, ⟨charpoly_monic M, aeval_self_charpoly M⟩⟩
theorem minpoly_dvd_charpoly {K : Type*} [field K] (M : matrix n n K) :
(minpoly K M) ∣ M.charpoly :=
minpoly.dvd _ _ (aeval_self_charpoly M)
end matrix
section power_basis
open algebra
/-- The characteristic polynomial of the map `λ x, a * x` is the minimal polynomial of `a`.
In combination with `det_eq_sign_charpoly_coeff` or `trace_eq_neg_charpoly_coeff`
and a bit of rewriting, this will allow us to conclude the
field norm resp. trace of `x` is the product resp. sum of `x`'s conjugates.
-/
lemma charpoly_left_mul_matrix {K S : Type*} [field K] [comm_ring S] [algebra K S]
(h : power_basis K S) :
(left_mul_matrix h.basis h.gen).charpoly = minpoly K h.gen :=
begin
apply minpoly.unique,
{ apply matrix.charpoly_monic },
{ apply (injective_iff_map_eq_zero (left_mul_matrix _)).mp (left_mul_matrix_injective h.basis),
rw [← polynomial.aeval_alg_hom_apply, aeval_self_charpoly] },
{ intros q q_monic root_q,
rw [matrix.charpoly_degree_eq_dim, fintype.card_fin, degree_eq_nat_degree q_monic.ne_zero],
apply with_bot.some_le_some.mpr,
exact h.dim_le_nat_degree_of_root q_monic.ne_zero root_q }
end
end power_basis
|
cb647514c2a7d69f92928ffb2da3a7caa4ce6bc5 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/declareConfigElabBug.lean | af9e7eec8f1e08a06d5c29392019adcf49523780 | [
"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 | 194 | lean | set_option trace.Elab true
theorem ex (h : a = b) : (fun x => x) a = b := by
simp (config := { beta := false, failIfUnchanged := false })
trace_state
simp (config := { beta := true }) [h]
|
15f9e1d9d4ed668ebfd46afc466e43e4d471b660 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/combinatorics/quiver/basic.lean | 37c9b5a9eb9457d9bac9eaeb361ce84a4b8dbcd3 | [
"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 | 3,116 | lean | /-
Copyright (c) 2021 David Wärn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: David Wärn, Scott Morrison
-/
import data.opposite
/-!
# Quivers
This module defines quivers. A quiver on a type `V` of vertices assigns to every
pair `a b : V` of vertices a type `a ⟶ b` of arrows from `a` to `b`. This
is a very permissive notion of directed graph.
## Implementation notes
Currently `quiver` is defined with `arrow : V → V → Sort v`.
This is different from the category theory setup,
where we insist that morphisms live in some `Type`.
There's some balance here: it's nice to allow `Prop` to ensure there are no multiple arrows,
but it is also results in error-prone universe signatures when constraints require a `Type`.
-/
open opposite
-- We use the same universe order as in category theory.
-- See note [category_theory universes]
universes v v₁ v₂ u u₁ u₂
/--
A quiver `G` on a type `V` of vertices assigns to every pair `a b : V` of vertices
a type `a ⟶ b` of arrows from `a` to `b`.
For graphs with no repeated edges, one can use `quiver.{0} V`, which ensures
`a ⟶ b : Prop`. For multigraphs, one can use `quiver.{v+1} V`, which ensures
`a ⟶ b : Type v`.
Because `category` will later extend this class, we call the field `hom`.
Except when constructing instances, you should rarely see this, and use the `⟶` notation instead.
-/
class quiver (V : Type u) :=
(hom : V → V → Sort v)
infixr ` ⟶ `:10 := quiver.hom -- type as \h
/--
A morphism of quivers. As we will later have categorical functors extend this structure,
we call it a `prefunctor`.
-/
structure prefunctor (V : Type u₁) [quiver.{v₁} V] (W : Type u₂) [quiver.{v₂} W] :=
(obj [] : V → W)
(map : Π {X Y : V}, (X ⟶ Y) → (obj X ⟶ obj Y))
namespace prefunctor
/--
The identity morphism between quivers.
-/
@[simps]
def id (V : Type*) [quiver V] : prefunctor V V :=
{ obj := id,
map := λ X Y f, f, }
instance (V : Type*) [quiver V] : inhabited (prefunctor V V) := ⟨id V⟩
/--
Composition of morphisms between quivers.
-/
@[simps]
def comp {U : Type*} [quiver U] {V : Type*} [quiver V] {W : Type*} [quiver W]
(F : prefunctor U V) (G : prefunctor V W) : prefunctor U W :=
{ obj := λ X, G.obj (F.obj X),
map := λ X Y f, G.map (F.map f), }
end prefunctor
namespace quiver
/-- `Vᵒᵖ` reverses the direction of all arrows of `V`. -/
instance opposite {V} [quiver V] : quiver Vᵒᵖ :=
⟨λ a b, (unop b) ⟶ (unop a)⟩
/--
The opposite of an arrow in `V`.
-/
def hom.op {V} [quiver V] {X Y : V} (f : X ⟶ Y) : op Y ⟶ op X := f
/--
Given an arrow in `Vᵒᵖ`, we can take the "unopposite" back in `V`.
-/
def hom.unop {V} [quiver V] {X Y : Vᵒᵖ} (f : X ⟶ Y) : unop Y ⟶ unop X := f
attribute [irreducible] quiver.opposite
/-- A type synonym for a quiver with no arrows. -/
@[nolint has_nonempty_instance]
def empty (V) : Type u := V
instance empty_quiver (V : Type u) : quiver.{u} (empty V) := ⟨λ a b, pempty⟩
@[simp] lemma empty_arrow {V : Type u} (a b : empty V) : (a ⟶ b) = pempty := rfl
end quiver
|
96aad0d4f591c660e26b0c66e1bfadc93769048c | b7f22e51856f4989b970961f794f1c435f9b8f78 | /library/data/int/basic.lean | 16e23d7f050441d2e1f24a3a3c3d259fe39654b7 | [
"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 | 23,401 | 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 integers, with addition, multiplication, and subtraction. The representation of the integers is
chosen to compute efficiently.
To faciliate proving things about these operations, we show that the integers are a quotient of
ℕ × ℕ with the usual equivalence relation, ≡, and functions
abstr : ℕ × ℕ → ℤ
repr : ℤ → ℕ × ℕ
satisfying:
abstr_repr (a : ℤ) : abstr (repr a) = a
repr_abstr (p : ℕ × ℕ) : repr (abstr p) ≡ p
abstr_eq (p q : ℕ × ℕ) : p ≡ q → abstr p = abstr q
For example, to "lift" statements about add to statements about padd, we need to prove the
following:
repr_add (a b : ℤ) : repr (a + b) = padd (repr a) (repr b)
padd_congr (p p' q q' : ℕ × ℕ) (H1 : p ≡ p') (H2 : q ≡ q') : padd p q ≡ p' q'
-/
import data.nat.sub algebra.relation data.prod
open eq.ops
open prod relation nat
open decidable binary
/- the type of integers -/
inductive int : Type :=
| of_nat : nat → int
| neg_succ_of_nat : nat → int
notation `ℤ` := int
definition int.of_num [coercion] [reducible] [constructor] (n : num) : ℤ :=
int.of_nat (nat.of_num n)
namespace int
attribute int.of_nat [coercion]
notation `-[1+ ` n `]` := int.neg_succ_of_nat n -- for pretty-printing output
protected definition prio : num := num.pred nat.prio
definition int_has_zero [instance] [priority int.prio] : has_zero int :=
has_zero.mk (of_nat 0)
definition int_has_one [instance] [priority int.prio] : has_one int :=
has_one.mk (of_nat 1)
theorem of_nat_zero : of_nat (0:nat) = (0:int) :=
rfl
theorem of_nat_one : of_nat (1:nat) = (1:int) :=
rfl
/- definitions of basic functions -/
definition neg_of_nat : ℕ → ℤ
| 0 := 0
| (succ m) := -[1+ m]
definition sub_nat_nat (m n : ℕ) : ℤ :=
match (n - m : nat) with
| 0 := of_nat (m - n) -- m ≥ n
| (succ k) := -[1+ k] -- m < n, and n - m = succ k
end
protected definition neg (a : ℤ) : ℤ :=
int.cases_on a neg_of_nat succ
protected definition add : ℤ → ℤ → ℤ
| (of_nat m) (of_nat n) := m + n
| (of_nat m) -[1+ n] := sub_nat_nat m (succ n)
| -[1+ m] (of_nat n) := sub_nat_nat n (succ m)
| -[1+ m] -[1+ n] := neg_of_nat (succ m + succ n)
protected definition mul : ℤ → ℤ → ℤ
| (of_nat m) (of_nat n) := m * n
| (of_nat m) -[1+ n] := neg_of_nat (m * succ n)
| -[1+ m] (of_nat n) := neg_of_nat (succ m * n)
| -[1+ m] -[1+ n] := succ m * succ n
/- notation -/
definition int_has_add [instance] [priority int.prio] : has_add int := has_add.mk int.add
definition int_has_neg [instance] [priority int.prio] : has_neg int := has_neg.mk int.neg
definition int_has_mul [instance] [priority int.prio] : has_mul int := has_mul.mk int.mul
lemma mul_of_nat_of_nat (m n : nat) : of_nat m * of_nat n = of_nat (m * n) :=
rfl
lemma mul_of_nat_neg_succ_of_nat (m n : nat) : of_nat m * -[1+ n] = neg_of_nat (m * succ n) :=
rfl
lemma mul_neg_succ_of_nat_of_nat (m n : nat) : -[1+ m] * of_nat n = neg_of_nat (succ m * n) :=
rfl
lemma mul_neg_succ_of_nat_neg_succ_of_nat (m n : nat) : -[1+ m] * -[1+ n] = succ m * succ n :=
rfl
/- some basic functions and properties -/
theorem of_nat.inj {m n : ℕ} (H : of_nat m = of_nat n) : m = n :=
int.no_confusion H imp.id
theorem eq_of_of_nat_eq_of_nat {m n : ℕ} (H : of_nat m = of_nat n) : m = n :=
of_nat.inj H
theorem of_nat_eq_of_nat_iff (m n : ℕ) : of_nat m = of_nat n ↔ m = n :=
iff.intro of_nat.inj !congr_arg
theorem neg_succ_of_nat.inj {m n : ℕ} (H : neg_succ_of_nat m = neg_succ_of_nat n) : m = n :=
int.no_confusion H imp.id
theorem neg_succ_of_nat_eq (n : ℕ) : -[1+ n] = -(n + 1) := rfl
private definition has_decidable_eq₂ : Π (a b : ℤ), decidable (a = b)
| (of_nat m) (of_nat n) := decidable_of_decidable_of_iff
(nat.has_decidable_eq m n) (iff.symm (of_nat_eq_of_nat_iff m n))
| (of_nat m) -[1+ n] := inr (by contradiction)
| -[1+ m] (of_nat n) := inr (by contradiction)
| -[1+ m] -[1+ n] := if H : m = n then
inl (congr_arg neg_succ_of_nat H) else inr (not.mto neg_succ_of_nat.inj H)
definition has_decidable_eq [instance] [priority int.prio] : decidable_eq ℤ := has_decidable_eq₂
theorem of_nat_add (n m : nat) : of_nat (n + m) = of_nat n + of_nat m := rfl
theorem of_nat_succ (n : ℕ) : of_nat (succ n) = of_nat n + 1 := rfl
theorem of_nat_mul (n m : ℕ) : of_nat (n * m) = of_nat n * of_nat m := rfl
theorem sub_nat_nat_of_ge {m n : ℕ} (H : m ≥ n) : sub_nat_nat m n = of_nat (m - n) :=
show sub_nat_nat m n = nat.cases_on 0 (m -[nat] n) _, from (sub_eq_zero_of_le H) ▸ rfl
section
local attribute sub_nat_nat [reducible]
theorem sub_nat_nat_of_lt {m n : ℕ} (H : m < n) : sub_nat_nat m n = -[1+ pred (n - m)] :=
have H1 : n - m = succ (pred (n - m)), from eq.symm (succ_pred_of_pos (nat.sub_pos_of_lt H)),
show sub_nat_nat m n = nat.cases_on (succ (nat.pred (n - m))) (m -[nat] n) _, from H1 ▸ rfl
end
definition nat_abs (a : ℤ) : ℕ := int.cases_on a id succ
theorem nat_abs_of_nat (n : ℕ) : nat_abs n = n := rfl
theorem eq_zero_of_nat_abs_eq_zero : Π {a : ℤ}, nat_abs a = 0 → a = 0
| (of_nat m) H := congr_arg of_nat H
| -[1+ m'] H := absurd H !succ_ne_zero
theorem nat_abs_zero : nat_abs (0:int) = (0:nat) :=
rfl
theorem nat_abs_one : nat_abs (1:int) = (1:nat) :=
rfl
/- int is a quotient of ordered pairs of natural numbers -/
protected definition equiv (p q : ℕ × ℕ) : Prop := pr1 p + pr2 q = pr2 p + pr1 q
local infix ≡ := int.equiv
protected theorem equiv.refl [refl] {p : ℕ × ℕ} : p ≡ p := !add.comm
local attribute int.equiv [reducible]
protected theorem equiv.symm [symm] {p q : ℕ × ℕ} (H : p ≡ q) : q ≡ p :=
by simp
protected theorem equiv.trans [trans] {p q r : ℕ × ℕ} (H1 : p ≡ q) (H2 : q ≡ r) : p ≡ r :=
add.right_cancel (calc
pr1 p + pr2 r + pr2 q = pr1 p + pr2 q + pr2 r : by simp_nohyps
... = pr2 p + pr1 r + pr2 q : by simp)
protected theorem equiv_equiv : is_equivalence int.equiv :=
is_equivalence.mk @equiv.refl @equiv.symm @equiv.trans
protected theorem equiv_cases {p q : ℕ × ℕ} (H : p ≡ q) :
(pr1 p ≥ pr2 p ∧ pr1 q ≥ pr2 q) ∨ (pr1 p < pr2 p ∧ pr1 q < pr2 q) :=
or.elim (@le_or_gt _ _ (pr2 p) (pr1 p))
(suppose pr1 p ≥ pr2 p,
have pr2 p + pr1 q ≥ pr2 p + pr2 q, from H ▸ add_le_add_right this (pr2 q),
or.inl (and.intro `pr1 p ≥ pr2 p` (le_of_add_le_add_left this)))
(suppose H₁ : pr1 p < pr2 p,
have pr2 p + pr1 q < pr2 p + pr2 q, from H ▸ add_lt_add_right H₁ (pr2 q),
or.inr (and.intro H₁ (lt_of_add_lt_add_left this)))
protected theorem equiv_of_eq {p q : ℕ × ℕ} (H : p = q) : p ≡ q := H ▸ equiv.refl
/- the representation and abstraction functions -/
definition abstr (a : ℕ × ℕ) : ℤ := sub_nat_nat (pr1 a) (pr2 a)
theorem abstr_of_ge {p : ℕ × ℕ} (H : pr1 p ≥ pr2 p) : abstr p = of_nat (pr1 p - pr2 p) :=
sub_nat_nat_of_ge H
theorem abstr_of_lt {p : ℕ × ℕ} (H : pr1 p < pr2 p) :
abstr p = -[1+ pred (pr2 p - pr1 p)] :=
sub_nat_nat_of_lt H
definition repr : ℤ → ℕ × ℕ
| (of_nat m) := (m, 0)
| -[1+ m] := (0, succ m)
theorem abstr_repr : Π (a : ℤ), abstr (repr a) = a
| (of_nat m) := (sub_nat_nat_of_ge (zero_le m))
| -[1+ m] := rfl
theorem repr_sub_nat_nat (m n : ℕ) : repr (sub_nat_nat m n) ≡ (m, n) :=
nat.lt_ge_by_cases
(take H : m < n,
have H1 : repr (sub_nat_nat m n) = (0, n - m), by
rewrite [sub_nat_nat_of_lt H, -(succ_pred_of_pos (nat.sub_pos_of_lt H))],
H1⁻¹ ▸ (!zero_add ⬝ (nat.sub_add_cancel (le_of_lt H))⁻¹))
(take H : m ≥ n,
have H1 : repr (sub_nat_nat m n) = (m - n, 0), from sub_nat_nat_of_ge H ▸ rfl,
H1⁻¹ ▸ ((nat.sub_add_cancel H) ⬝ !zero_add⁻¹))
theorem repr_abstr (p : ℕ × ℕ) : repr (abstr p) ≡ p :=
!prod.eta ▸ !repr_sub_nat_nat
theorem abstr_eq {p q : ℕ × ℕ} (Hequiv : p ≡ q) : abstr p = abstr q :=
or.elim (int.equiv_cases Hequiv)
(and.rec (assume (Hp : pr1 p ≥ pr2 p) (Hq : pr1 q ≥ pr2 q),
have H : pr1 p - pr2 p = pr1 q - pr2 q, from
calc pr1 p - pr2 p
= pr1 p + pr2 q - pr2 q - pr2 p : by rewrite nat.add_sub_cancel
... = pr2 p + pr1 q - pr2 q - pr2 p : Hequiv
... = pr2 p + (pr1 q - pr2 q) - pr2 p : nat.add_sub_assoc Hq
... = pr1 q - pr2 q + pr2 p - pr2 p : by simp
... = pr1 q - pr2 q : by rewrite nat.add_sub_cancel,
abstr_of_ge Hp ⬝ (H ▸ rfl) ⬝ (abstr_of_ge Hq)⁻¹))
(and.rec (assume (Hp : pr1 p < pr2 p) (Hq : pr1 q < pr2 q),
have H : pr2 p - pr1 p = pr2 q - pr1 q, from
calc pr2 p - pr1 p
= pr2 p + pr1 q - pr1 q - pr1 p : by rewrite nat.add_sub_cancel
... = pr1 p + pr2 q - pr1 q - pr1 p : Hequiv
... = pr1 p + (pr2 q - pr1 q) - pr1 p : nat.add_sub_assoc (le_of_lt Hq)
... = pr2 q - pr1 q + pr1 p - pr1 p : by rewrite add.comm
... = pr2 q - pr1 q : by rewrite nat.add_sub_cancel,
abstr_of_lt Hp ⬝ (H ▸ rfl) ⬝ (abstr_of_lt Hq)⁻¹))
theorem equiv_iff (p q : ℕ × ℕ) : (p ≡ q) ↔ (abstr p = abstr q) :=
iff.intro abstr_eq (assume H, equiv.trans (H ▸ equiv.symm (repr_abstr p)) (repr_abstr q))
theorem equiv_iff3 (p q : ℕ × ℕ) : (p ≡ q) ↔ ((p ≡ p) ∧ (q ≡ q) ∧ (abstr p = abstr q)) :=
iff.trans !equiv_iff (iff.symm
(iff.trans (and_iff_right !equiv.refl) (and_iff_right !equiv.refl)))
theorem eq_abstr_of_equiv_repr {a : ℤ} {p : ℕ × ℕ} (Hequiv : repr a ≡ p) : a = abstr p :=
!abstr_repr⁻¹ ⬝ abstr_eq Hequiv
theorem eq_of_repr_equiv_repr {a b : ℤ} (H : repr a ≡ repr b) : a = b :=
eq_abstr_of_equiv_repr H ⬝ !abstr_repr
section
local attribute abstr [reducible]
local attribute dist [reducible]
theorem nat_abs_abstr : Π (p : ℕ × ℕ), nat_abs (abstr p) = dist (pr1 p) (pr2 p)
| (m, n) := nat.lt_ge_by_cases
(assume H : m < n,
calc
nat_abs (abstr (m, n)) = nat_abs (-[1+ pred (n - m)]) : int.abstr_of_lt H
... = n - m : succ_pred_of_pos (nat.sub_pos_of_lt H)
... = dist m n : dist_eq_sub_of_le (le_of_lt H))
(assume H : m ≥ n, (abstr_of_ge H)⁻¹ ▸ (dist_eq_sub_of_ge H)⁻¹)
end
theorem cases_of_nat_succ (a : ℤ) : (∃n : ℕ, a = of_nat n) ∨ (∃n : ℕ, a = - (of_nat (succ n))) :=
int.cases_on a (take m, or.inl (exists.intro _ rfl)) (take m, or.inr (exists.intro _ rfl))
theorem cases_of_nat (a : ℤ) : (∃n : ℕ, a = of_nat n) ∨ (∃n : ℕ, a = - of_nat n) :=
or.imp_right (Exists.rec (take n, (exists.intro _))) !cases_of_nat_succ
theorem by_cases_of_nat {P : ℤ → Prop} (a : ℤ)
(H1 : ∀n : ℕ, P (of_nat n)) (H2 : ∀n : ℕ, P (- of_nat n)) :
P a :=
or.elim (cases_of_nat a)
(assume H, obtain (n : ℕ) (H3 : a = n), from H, H3⁻¹ ▸ H1 n)
(assume H, obtain (n : ℕ) (H3 : a = -n), from H, H3⁻¹ ▸ H2 n)
theorem by_cases_of_nat_succ {P : ℤ → Prop} (a : ℤ)
(H1 : ∀n : ℕ, P (of_nat n)) (H2 : ∀n : ℕ, P (- of_nat (succ n))) :
P a :=
or.elim (cases_of_nat_succ a)
(assume H, obtain (n : ℕ) (H3 : a = n), from H, H3⁻¹ ▸ H1 n)
(assume H, obtain (n : ℕ) (H3 : a = -(succ n)), from H, H3⁻¹ ▸ H2 n)
/-
int is a ring
-/
/- addition -/
definition padd (p q : ℕ × ℕ) : ℕ × ℕ := (pr1 p + pr1 q, pr2 p + pr2 q)
theorem repr_add : Π (a b : ℤ), repr (add a b) ≡ padd (repr a) (repr b)
| (of_nat m) (of_nat n) := !equiv.refl
| (of_nat m) -[1+ n] :=
begin
change repr (sub_nat_nat m (succ n)) ≡ (m + 0, 0 + succ n),
rewrite [zero_add, add_zero],
apply repr_sub_nat_nat
end
| -[1+ m] (of_nat n) :=
begin
change repr (-[1+ m] + n) ≡ (0 + n, succ m + 0),
rewrite [zero_add, add_zero],
apply repr_sub_nat_nat
end
| -[1+ m] -[1+ n] := !repr_sub_nat_nat
theorem padd_congr {p p' q q' : ℕ × ℕ} (Ha : p ≡ p') (Hb : q ≡ q') : padd p q ≡ padd p' q' :=
calc pr1 p + pr1 q + (pr2 p' + pr2 q')
= pr1 p + pr2 p' + (pr1 q + pr2 q') : by simp_nohyps
... = pr2 p + pr1 p' + (pr2 q + pr1 q') : by simp
... = pr2 p + pr2 q + (pr1 p' + pr1 q') : by simp_nohyps
theorem padd_comm (p q : ℕ × ℕ) : padd p q = padd q p :=
calc (pr1 p + pr1 q, pr2 p + pr2 q) = (pr1 q + pr1 p, pr2 q + pr2 p) : by simp
theorem padd_assoc (p q r : ℕ × ℕ) : padd (padd p q) r = padd p (padd q r) :=
calc (pr1 p + pr1 q + pr1 r, pr2 p + pr2 q + pr2 r)
= (pr1 p + (pr1 q + pr1 r), pr2 p + (pr2 q + pr2 r)) : by simp
protected theorem add_comm (a b : ℤ) : a + b = b + a :=
eq_of_repr_equiv_repr (equiv.trans !repr_add
(equiv.symm (!padd_comm ▸ !repr_add)))
protected theorem add_assoc (a b c : ℤ) : a + b + c = a + (b + c) :=
eq_of_repr_equiv_repr (calc
repr (a + b + c)
≡ padd (repr (a + b)) (repr c) : repr_add
... ≡ padd (padd (repr a) (repr b)) (repr c) : padd_congr !repr_add !equiv.refl
... = padd (repr a) (padd (repr b) (repr c)) : !padd_assoc
... ≡ padd (repr a) (repr (b + c)) : padd_congr !equiv.refl !repr_add
... ≡ repr (a + (b + c)) : repr_add)
protected theorem add_zero : Π (a : ℤ), a + 0 = a := int.rec (λm, rfl) (λm, rfl)
protected theorem zero_add (a : ℤ) : 0 + a = a := !int.add_comm ▸ !int.add_zero
/- negation -/
definition pneg (p : ℕ × ℕ) : ℕ × ℕ := (pr2 p, pr1 p)
-- note: this is =, not just ≡
theorem repr_neg : Π (a : ℤ), repr (- a) = pneg (repr a)
| 0 := rfl
| (succ m) := rfl
| -[1+ m] := rfl
theorem pneg_congr {p p' : ℕ × ℕ} (H : p ≡ p') : pneg p ≡ pneg p' := eq.symm H
theorem pneg_pneg (p : ℕ × ℕ) : pneg (pneg p) = p := !prod.eta
theorem nat_abs_neg (a : ℤ) : nat_abs (-a) = nat_abs a :=
calc
nat_abs (-a) = nat_abs (abstr (repr (-a))) : abstr_repr
... = nat_abs (abstr (pneg (repr a))) : repr_neg
... = dist (pr1 (pneg (repr a))) (pr2 (pneg (repr a))) : nat_abs_abstr
... = dist (pr2 (pneg (repr a))) (pr1 (pneg (repr a))) : dist.comm
... = nat_abs (abstr (repr a)) : nat_abs_abstr
... = nat_abs a : abstr_repr
theorem padd_pneg (p : ℕ × ℕ) : padd p (pneg p) ≡ (0, 0) :=
show pr1 p + pr2 p + 0 = pr2 p + pr1 p + 0, from !nat.add_comm ▸ rfl
theorem padd_padd_pneg (p q : ℕ × ℕ) : padd (padd p q) (pneg q) ≡ p :=
by unfold [padd, pneg]; simp
protected theorem add_left_inv (a : ℤ) : -a + a = 0 :=
have H : repr (-a + a) ≡ repr 0, from
calc
repr (-a + a) ≡ padd (repr (neg a)) (repr a) : repr_add
... = padd (pneg (repr a)) (repr a) : repr_neg
... ≡ repr 0 : padd_pneg,
eq_of_repr_equiv_repr H
/- nat abs -/
definition pabs (p : ℕ × ℕ) : ℕ := dist (pr1 p) (pr2 p)
theorem pabs_congr {p q : ℕ × ℕ} (H : p ≡ q) : pabs p = pabs q :=
calc
pabs p = nat_abs (abstr p) : nat_abs_abstr
... = nat_abs (abstr q) : abstr_eq H
... = pabs q : nat_abs_abstr
theorem nat_abs_eq_pabs_repr (a : ℤ) : nat_abs a = pabs (repr a) :=
calc
nat_abs a = nat_abs (abstr (repr a)) : abstr_repr
... = pabs (repr a) : nat_abs_abstr
theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b :=
calc
nat_abs (a + b) = pabs (repr (a + b)) : nat_abs_eq_pabs_repr
... = pabs (padd (repr a) (repr b)) : pabs_congr !repr_add
... ≤ pabs (repr a) + pabs (repr b) : dist_add_add_le_add_dist_dist
... = pabs (repr a) + nat_abs b : nat_abs_eq_pabs_repr
... = nat_abs a + nat_abs b : nat_abs_eq_pabs_repr
theorem nat_abs_neg_of_nat (n : nat) : nat_abs (neg_of_nat n) = n :=
begin cases n, reflexivity, reflexivity end
section
local attribute nat_abs [reducible]
theorem nat_abs_mul : Π (a b : ℤ), nat_abs (a * b) = (nat_abs a) * (nat_abs b)
| (of_nat m) (of_nat n) := rfl
| (of_nat m) -[1+ n] := by rewrite [mul_of_nat_neg_succ_of_nat, nat_abs_neg_of_nat]
| -[1+ m] (of_nat n) := by rewrite [mul_neg_succ_of_nat_of_nat, nat_abs_neg_of_nat]
| -[1+ m] -[1+ n] := rfl
end
/- multiplication -/
definition pmul (p q : ℕ × ℕ) : ℕ × ℕ :=
(pr1 p * pr1 q + pr2 p * pr2 q, pr1 p * pr2 q + pr2 p * pr1 q)
theorem repr_neg_of_nat (m : ℕ) : repr (neg_of_nat m) = (0, m) :=
nat.cases_on m rfl (take m', rfl)
-- note: we have =, not just ≡
theorem repr_mul : Π (a b : ℤ), repr (a * b) = pmul (repr a) (repr b)
| (of_nat m) (of_nat n) := calc
(m * n + 0 * 0, m * 0 + 0) = (m * n + 0 * 0, m * 0 + 0 * n) : by rewrite *zero_mul
| (of_nat m) -[1+ n] := calc
repr ((m : int) * -[1+ n]) = (m * 0 + 0, m * succ n + 0 * 0) : repr_neg_of_nat
... = (m * 0 + 0 * succ n, m * succ n + 0 * 0) : by rewrite *zero_mul
| -[1+ m] (of_nat n) := calc
repr (-[1+ m] * (n:int)) = (0 + succ m * 0, succ m * n) : repr_neg_of_nat
... = (0 + succ m * 0, 0 + succ m * n) : nat.zero_add
... = (0 * n + succ m * 0, 0 + succ m * n) : by rewrite zero_mul
| -[1+ m] -[1+ n] := calc
(succ m * succ n, 0) = (succ m * succ n, 0 * succ n) : by rewrite zero_mul
... = (0 + succ m * succ n, 0 * succ n) : nat.zero_add
local attribute left_distrib right_distrib [simp]
theorem equiv_mul_prep {xa ya xb yb xn yn xm ym : ℕ}
(H1 : xa + yb = ya + xb) (H2 : xn + ym = yn + xm) : xa*xn+ya*yn+(xb*ym+yb*xm) = xa*yn+ya*xn+(xb*xm+yb*ym) :=
nat.add_right_cancel (
calc xa*xn+ya*yn + (xb*ym+yb*xm) + (yb*xn+xb*yn + (xb*xn+yb*yn))
= (xa + yb)*xn + (ya + xb)*yn + (xb*(xn + ym)) + (yb*(yn + xm)) : by simp_nohyps
... = (ya + xb)*xn + (xa + yb)*yn + (xb*(yn + xm)) + (yb*(xn + ym)) : by simp
... = xa*yn+ya*xn + (xb*xm+yb*ym) + (yb*xn+xb*yn + (xb*xn+yb*yn)) : by simp_nohyps)
theorem pmul_congr {p p' q q' : ℕ × ℕ} : p ≡ p' → q ≡ q' → pmul p q ≡ pmul p' q' := equiv_mul_prep
theorem pmul_comm (p q : ℕ × ℕ) : pmul p q = pmul q p :=
by unfold pmul; simp
protected theorem mul_comm (a b : ℤ) : a * b = b * a :=
eq_of_repr_equiv_repr
((calc
repr (a * b) = pmul (repr a) (repr b) : repr_mul
... = pmul (repr b) (repr a) : pmul_comm
... = repr (b * a) : repr_mul) ▸ !equiv.refl)
private theorem pmul_assoc_prep {p1 p2 q1 q2 r1 r2 : ℕ} :
((p1*q1+p2*q2)*r1+(p1*q2+p2*q1)*r2, (p1*q1+p2*q2)*r2+(p1*q2+p2*q1)*r1) =
(p1*(q1*r1+q2*r2)+p2*(q1*r2+q2*r1), p1*(q1*r2+q2*r1)+p2*(q1*r1+q2*r2)) :=
by simp
theorem pmul_assoc (p q r: ℕ × ℕ) : pmul (pmul p q) r = pmul p (pmul q r) := pmul_assoc_prep
protected theorem mul_assoc (a b c : ℤ) : (a * b) * c = a * (b * c) :=
eq_of_repr_equiv_repr
((calc
repr (a * b * c) = pmul (repr (a * b)) (repr c) : repr_mul
... = pmul (pmul (repr a) (repr b)) (repr c) : repr_mul
... = pmul (repr a) (pmul (repr b) (repr c)) : pmul_assoc
... = pmul (repr a) (repr (b * c)) : repr_mul
... = repr (a * (b * c)) : repr_mul) ▸ !equiv.refl)
protected theorem mul_one : Π (a : ℤ), a * 1 = a
| (of_nat m) := !int.zero_add -- zero_add happens to be def. = to this thm
| -[1+ m] := !nat.zero_add ▸ rfl
protected theorem one_mul (a : ℤ) : 1 * a = a :=
int.mul_comm a 1 ▸ int.mul_one a
private theorem mul_distrib_prep {a1 a2 b1 b2 c1 c2 : ℕ} :
((a1+b1)*c1+(a2+b2)*c2, (a1+b1)*c2+(a2+b2)*c1) =
(a1*c1+a2*c2+(b1*c1+b2*c2), a1*c2+a2*c1+(b1*c2+b2*c1)) :=
by simp
protected theorem right_distrib (a b c : ℤ) : (a + b) * c = a * c + b * c :=
eq_of_repr_equiv_repr
(calc
repr ((a + b) * c) = pmul (repr (a + b)) (repr c) : repr_mul
... ≡ pmul (padd (repr a) (repr b)) (repr c) : pmul_congr !repr_add equiv.refl
... = padd (pmul (repr a) (repr c)) (pmul (repr b) (repr c)) : mul_distrib_prep
... = padd (repr (a * c)) (pmul (repr b) (repr c)) : repr_mul
... = padd (repr (a * c)) (repr (b * c)) : repr_mul
... ≡ repr (a * c + b * c) : repr_add)
protected theorem left_distrib (a b c : ℤ) : a * (b + c) = a * b + a * c :=
calc
a * (b + c) = (b + c) * a : int.mul_comm
... = b * a + c * a : int.right_distrib
... = a * b + c * a : int.mul_comm
... = a * b + a * c : int.mul_comm
protected theorem zero_ne_one : (0 : int) ≠ 1 :=
assume H : 0 = 1, !succ_ne_zero (of_nat.inj H)⁻¹
protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {a b : ℤ} (H : a * b = 0) : a = 0 ∨ b = 0 :=
or.imp eq_zero_of_nat_abs_eq_zero eq_zero_of_nat_abs_eq_zero
(eq_zero_or_eq_zero_of_mul_eq_zero (by rewrite [-nat_abs_mul, H]))
protected definition integral_domain [trans_instance] : integral_domain int :=
⦃integral_domain,
add := int.add,
add_assoc := int.add_assoc,
zero := 0,
zero_add := int.zero_add,
add_zero := int.add_zero,
neg := int.neg,
add_left_inv := int.add_left_inv,
add_comm := int.add_comm,
mul := int.mul,
mul_assoc := int.mul_assoc,
one := 1,
one_mul := int.one_mul,
mul_one := int.mul_one,
left_distrib := int.left_distrib,
right_distrib := int.right_distrib,
mul_comm := int.mul_comm,
zero_ne_one := int.zero_ne_one,
eq_zero_or_eq_zero_of_mul_eq_zero := @int.eq_zero_or_eq_zero_of_mul_eq_zero⦄
definition int_has_sub [instance] [priority int.prio] : has_sub int :=
has_sub.mk has_sub.sub
definition int_has_dvd [instance] [priority int.prio] : has_dvd int :=
has_dvd.mk has_dvd.dvd
/- additional properties -/
theorem of_nat_sub {m n : ℕ} (H : m ≥ n) : of_nat (m - n) = of_nat m - of_nat n :=
have m - n + n = m, from nat.sub_add_cancel H,
begin
symmetry,
apply sub_eq_of_eq_add,
rewrite [-of_nat_add, this]
end
theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 :=
by rewrite [neg_succ_of_nat_eq, neg_add]
definition succ (a : ℤ) := a + (succ zero)
definition pred (a : ℤ) := a - (succ zero)
definition nat_succ_eq_int_succ (n : ℕ) : nat.succ n = int.succ n := rfl
theorem pred_succ (a : ℤ) : pred (succ a) = a := !sub_add_cancel
theorem succ_pred (a : ℤ) : succ (pred a) = a := !add_sub_cancel
theorem neg_succ (a : ℤ) : -succ a = pred (-a) :=
by rewrite [↑succ,neg_add]
theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a :=
by rewrite [neg_succ,succ_pred]
theorem neg_pred (a : ℤ) : -pred a = succ (-a) :=
by rewrite [↑pred,neg_sub,sub_eq_add_neg,add.comm]
theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a :=
by rewrite [neg_pred,pred_succ]
theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n
theorem neg_nat_succ (n : ℕ) : -nat.succ n = pred (-n) := !neg_succ
theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := !succ_neg_succ
definition rec_nat_on [unfold 2] {P : ℤ → Type} (z : ℤ) (H0 : P 0)
(Hsucc : Π⦃n : ℕ⦄, P n → P (succ n)) (Hpred : Π⦃n : ℕ⦄, P (-n) → P (-nat.succ n)) : P z :=
int.rec (nat.rec H0 Hsucc) (λn, nat.rec H0 Hpred (nat.succ n)) z
--the only computation rule of rec_nat_on which is not definitional
theorem rec_nat_on_neg {P : ℤ → Type} (n : nat) (H0 : P zero)
(Hsucc : Π⦃n : nat⦄, P n → P (succ n)) (Hpred : Π⦃n : nat⦄, P (-n) → P (-nat.succ n))
: rec_nat_on (-nat.succ n) H0 Hsucc Hpred = Hpred (rec_nat_on (-n) H0 Hsucc Hpred) :=
nat.rec rfl (λn H, rfl) n
end int
|
2646d664319b5dbe67543966ffbfb14e988c09a8 | 77c5b91fae1b966ddd1db969ba37b6f0e4901e88 | /counterexamples/canonically_ordered_comm_semiring_two_mul.lean | 10bbc8194f05af8a911e91ca85441bdd3ebbf3bc | [
"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 | 9,494 | lean | /-
Copyright (c) 2021 Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Damiano Testa
-/
import data.zmod.basic
import ring_theory.subsemiring
import algebra.order.monoid
/-!
A `canonically_ordered_comm_semiring` with two different elements `a` and `b` such that
`a ≠ b` and `2 * a = 2 * b`. Thus, multiplication by a fixed non-zero element of a canonically
ordered semiring need not be injective. In particular, multiplying by a strictly positive element
need not be strictly monotone.
Recall that a `canonically_ordered_comm_semiring` is a commutative semiring with a partial ordering
that is "canonical" in the sense that the inequality `a ≤ b` holds if and only if there is a `c`
such that `a + c = b`. There are several compatibility conditions among addition/multiplication
and the order relation. The point of the counterexample is to show that monotonicity of
multiplication cannot be strengthened to **strict** monotonicity.
Reference:
https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/canonically_ordered.20pathology
-/
namespace from_Bhavik
/-- Bhavik Mehta's example. There are only the initial definitions, but no proofs. The Type
`K` is a canonically ordered commutative semiring with the property that `2 * (1/2) ≤ 2 * 1`, even
though it is not true that `1/2 ≤ 1`, since `1/2` and `1` are not comparable. -/
@[derive [comm_semiring]]
def K : Type := subsemiring.closure ({1.5} : set ℚ)
instance : has_coe K ℚ := ⟨λ x, x.1⟩
instance inhabited_K : inhabited K := ⟨0⟩
instance : preorder K :=
{ le := λ x y, x = y ∨ (x : ℚ) + 1 ≤ (y : ℚ),
le_refl := λ x, or.inl rfl,
le_trans := λ x y z xy yz,
begin
rcases xy with (rfl | _), { apply yz },
rcases yz with (rfl | _), { right, apply xy },
right,
exact xy.trans (le_trans ((le_add_iff_nonneg_right _).mpr zero_le_one) yz)
end }
end from_Bhavik
lemma mem_zmod_2 (a : zmod 2) : a = 0 ∨ a = 1 :=
begin
rcases a with ⟨_ | _ | _ | _ | a_val, _ | ⟨_, _ | ⟨_, ⟨⟩⟩⟩⟩,
{ exact or.inl rfl },
{ exact or.inr rfl },
end
lemma add_self_zmod_2 (a : zmod 2) : a + a = 0 :=
begin
rcases mem_zmod_2 a with rfl | rfl;
refl,
end
namespace Nxzmod_2
variables {a b : ℕ × zmod 2}
/-- The preorder relation on `ℕ × ℤ/2ℤ` where we only compare the first coordinate,
except that we leave incomparable each pair of elements with the same first component.
For instance, `∀ α, β ∈ ℤ/2ℤ`, the inequality `(1,α) ≤ (2,β)` holds,
whereas, `∀ n ∈ ℤ`, the elements `(n,0)` and `(n,1)` are incomparable. -/
instance preN2 : partial_order (ℕ × zmod 2) :=
{ le := λ x y, x = y ∨ x.1 < y.1,
le_refl := λ a, or.inl rfl,
le_trans := λ x y z xy yz,
begin
rcases xy with (rfl | _),
{ exact yz },
{ rcases yz with (rfl | _),
{ exact or.inr xy},
{ exact or.inr (xy.trans yz) } }
end,
le_antisymm := begin
intros a b ab ba,
cases ab with ab ab,
{ exact ab },
{ cases ba with ba ba,
{ exact ba.symm },
{ exact (nat.lt_asymm ab ba).elim } }
end }
instance csrN2 : comm_semiring (ℕ × zmod 2) := by apply_instance
instance csrN2_1 : add_cancel_comm_monoid (ℕ × zmod 2) :=
{ add_left_cancel := λ a b c h, (add_right_inj a).mp h,
..Nxzmod_2.csrN2 }
/-- A strict inequality forces the first components to be different. -/
@[simp] lemma lt_def : a < b ↔ a.1 < b.1 :=
begin
refine ⟨λ h, _, λ h, _⟩,
{ rcases h with ⟨(rfl | a1), h1⟩,
{ exact ((not_or_distrib.mp h1).1).elim rfl },
{ exact a1 } },
refine ⟨or.inr h, not_or_distrib.mpr ⟨λ k, _, not_lt.mpr h.le⟩⟩,
rw k at h,
exact nat.lt_asymm h h
end
lemma add_left_cancel : ∀ (a b c : ℕ × zmod 2), a + b = a + c → b = c :=
λ a b c h, (add_right_inj a).mp h
lemma add_le_add_left : ∀ (a b : ℕ × zmod 2), a ≤ b → ∀ (c : ℕ × zmod 2), c + a ≤ c + b :=
begin
rintros a b (rfl | ab) c,
{ refl },
{ exact or.inr (by simpa) }
end
lemma le_of_add_le_add_left : ∀ (a b c : ℕ × zmod 2), a + b ≤ a + c → b ≤ c :=
begin
rintros a b c (bc | bc),
{ exact le_of_eq ((add_right_inj a).mp bc) },
{ exact or.inr (by simpa using bc) }
end
lemma zero_le_one : (0 : ℕ × zmod 2) ≤ 1 := dec_trivial
lemma mul_lt_mul_of_pos_left : ∀ (a b c : ℕ × zmod 2), a < b → 0 < c → c * a < c * b :=
λ a b c ab c0, lt_def.mpr ((mul_lt_mul_left (lt_def.mp c0)).mpr (lt_def.mp ab))
lemma mul_lt_mul_of_pos_right : ∀ (a b c : ℕ × zmod 2), a < b → 0 < c → a * c < b * c :=
λ a b c ab c0, lt_def.mpr ((mul_lt_mul_right (lt_def.mp c0)).mpr (lt_def.mp ab))
instance ocsN2 : ordered_comm_semiring (ℕ × zmod 2) :=
{ add_le_add_left := add_le_add_left,
le_of_add_le_add_left := le_of_add_le_add_left,
zero_le_one := zero_le_one,
mul_lt_mul_of_pos_left := mul_lt_mul_of_pos_left,
mul_lt_mul_of_pos_right := mul_lt_mul_of_pos_right,
..Nxzmod_2.csrN2_1,
..(infer_instance : partial_order (ℕ × zmod 2)),
..(infer_instance : comm_semiring (ℕ × zmod 2)) }
end Nxzmod_2
namespace ex_L
open Nxzmod_2 subtype
/-- Initially, `L` was defined as the subsemiring closure of `(1,0)`. -/
def L : Type := { l : (ℕ × zmod 2) // l ≠ (0, 1) }
instance zero : has_zero L := ⟨⟨(0, 0), dec_trivial⟩⟩
instance one : has_one L := ⟨⟨(1, 1), dec_trivial⟩⟩
instance inhabited : inhabited L := ⟨1⟩
lemma add_L {a b : ℕ × zmod 2} (ha : a ≠ (0, 1)) (hb : b ≠ (0, 1)) :
a + b ≠ (0, 1) :=
begin
rcases a with ⟨a, a2⟩,
rcases b with ⟨b, b2⟩,
cases b,
{ rcases mem_zmod_2 b2 with rfl | rfl,
{ simp [ha] },
{ simpa only } },
{ simp [(a + b).succ_ne_zero] }
end
lemma mul_L {a b : ℕ × zmod 2} (ha : a ≠ (0, 1)) (hb : b ≠ (0, 1)) :
a * b ≠ (0, 1) :=
begin
rcases a with ⟨a, a2⟩,
rcases b with ⟨b, b2⟩,
cases b,
{ rcases mem_zmod_2 b2 with rfl | rfl;
rcases mem_zmod_2 a2 with rfl | rfl;
-- while this looks like a non-terminal `simp`, it (almost) isn't: there is only one goal where
-- it does not finish the proof and on that goal it asks to prove `false`
simp,
exact hb rfl },
cases a,
{ rcases mem_zmod_2 b2 with rfl | rfl;
rcases mem_zmod_2 a2 with rfl | rfl;
-- while this looks like a non-terminal `simp`, it (almost) isn't: there is only one goal where
-- it does not finish the proof and on that goal it asks to prove `false`
simp,
exact ha rfl },
{ simp [mul_ne_zero _ _, nat.succ_ne_zero _] }
end
instance has_add_L : has_add L :=
{ add := λ ⟨a, ha⟩ ⟨b, hb⟩, ⟨a + b, add_L ha hb⟩ }
instance : has_mul L :=
{ mul := λ ⟨a, ha⟩ ⟨b, hb⟩, ⟨a * b, mul_L ha hb⟩ }
instance : ordered_comm_semiring L :=
begin
refine function.injective.ordered_comm_semiring _ subtype.coe_injective rfl rfl _ _;
{ refine λ x y, _,
cases x,
cases y,
refl }
end
lemma bot_le : ∀ (a : L), 0 ≤ a :=
begin
rintros ⟨⟨an, a2⟩, ha⟩,
cases an,
{ rcases mem_zmod_2 a2 with (rfl | rfl),
{ refl, },
{ exact (ha rfl).elim } },
{ refine or.inr _,
exact nat.succ_pos _ }
end
instance order_bot : order_bot L :=
{ bot := 0,
bot_le := bot_le,
..(infer_instance : partial_order L) }
lemma le_iff_exists_add : ∀ (a b : L), a ≤ b ↔ ∃ (c : L), b = a + c :=
begin
rintros ⟨⟨an, a2⟩, ha⟩ ⟨⟨bn, b2⟩, hb⟩,
rw subtype.mk_le_mk,
refine ⟨λ h, _, λ h, _⟩,
{ rcases h with ⟨rfl, rfl⟩ | h,
{ exact ⟨(0 : L), (add_zero _).symm⟩ },
{ refine ⟨⟨⟨bn - an, b2 + a2⟩, _⟩, _⟩,
{ rw [ne.def, prod.mk.inj_iff, not_and_distrib],
exact or.inl (ne_of_gt (nat.sub_pos_of_lt h)) },
{ congr,
{ exact (nat.add_sub_cancel' h.le).symm },
{ change b2 = a2 + (b2 + a2),
rw [add_comm b2, ← add_assoc, add_self_zmod_2, zero_add] } } } },
{ rcases h with ⟨⟨⟨c, c2⟩, hc⟩, abc⟩,
injection abc with abc,
rw [prod.mk_add_mk, prod.mk.inj_iff] at abc,
rcases abc with ⟨rfl, rfl⟩,
cases c,
{ refine or.inl _,
rw [ne.def, prod.mk.inj_iff, eq_self_iff_true, true_and] at hc,
rcases mem_zmod_2 c2 with rfl | rfl,
{ rw [add_zero, add_zero] },
{ exact (hc rfl).elim } },
{ refine or.inr _,
exact (lt_add_iff_pos_right _).mpr c.succ_pos } }
end
lemma eq_zero_or_eq_zero_of_mul_eq_zero : ∀ (a b : L), a * b = 0 → a = 0 ∨ b = 0 :=
begin
rintros ⟨⟨a, a2⟩, ha⟩ ⟨⟨b, b2⟩, hb⟩ ab1,
injection ab1 with ab,
injection ab with abn ab2,
rw mul_eq_zero at abn,
rcases abn with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩,
{ refine or.inl _,
rcases mem_zmod_2 a2 with rfl | rfl,
{ refl },
{ exact (ha rfl).elim } },
{ refine or.inr _,
rcases mem_zmod_2 b2 with rfl | rfl,
{ refl },
{ exact (hb rfl).elim } }
end
instance can : canonically_ordered_comm_semiring L :=
{ le_iff_exists_add := le_iff_exists_add,
eq_zero_or_eq_zero_of_mul_eq_zero := eq_zero_or_eq_zero_of_mul_eq_zero,
..(infer_instance : order_bot L),
..(infer_instance : ordered_comm_semiring L) }
/--
The elements `(1,0)` and `(1,1)` of `L` are different, but their doubles coincide.
-/
example : ∃ a b : L, a ≠ b ∧ 2 * a = 2 * b :=
begin
refine ⟨⟨(1,0), by simp⟩, 1, λ (h : (⟨(1, 0), _⟩ : L) = ⟨⟨1, 1⟩, _⟩), _, rfl⟩,
obtain (F : (0 : zmod 2) = 1) := congr_arg (λ j : L, j.1.2) h,
cases F,
end
end ex_L
|
786fb0831fc14ea7dfb8055d7c77be2c9c3d353f | e0f9ba56b7fedc16ef8697f6caeef5898b435143 | /src/field_theory/minimal_polynomial.lean | a3e898d5dc32b83394f884959090e2038f5416b4 | [
"Apache-2.0"
] | permissive | anrddh/mathlib | 6a374da53c7e3a35cb0298b0cd67824efef362b4 | a4266a01d2dcb10de19369307c986d038c7bb6a6 | refs/heads/master | 1,656,710,827,909 | 1,589,560,456,000 | 1,589,560,456,000 | 264,271,800 | 0 | 0 | Apache-2.0 | 1,589,568,062,000 | 1,589,568,061,000 | null | UTF-8 | Lean | false | false | 8,858 | lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johan Commelin
-/
import ring_theory.integral_closure
/-!
# Minimal polynomials
This file defines the minimal polynomial of an element x of an A-algebra B,
under the assumption that x is integral over A.
After stating the defining property we specialize to the setting of field extensions
and derive some well-known properties, amongst which the fact that minimal polynomials
are irreducible, and uniquely determined by their defining property.
-/
universes u v w
open_locale classical
open polynomial set function
variables {α : Type u} {β : Type v}
section min_poly_def
variables [comm_ring α] [comm_ring β] [algebra α β]
/-- Let B be an A-algebra, and x an element of B that is integral over A.
The minimal polynomial of x is a monic polynomial of smallest degree that has x as its root. -/
noncomputable def minimal_polynomial {x : β} (hx : is_integral α x) : polynomial α :=
well_founded.min polynomial.degree_lt_wf _ hx
end min_poly_def
namespace minimal_polynomial
section ring
variables [comm_ring α] [comm_ring β] [algebra α β]
variables {x : β} (hx : is_integral α x)
/--A minimal polynomial is monic.-/
lemma monic : monic (minimal_polynomial hx) :=
(well_founded.min_mem degree_lt_wf _ hx).1
/--An element is a root of its minimal polynomial.-/
@[simp] lemma aeval : aeval α β x (minimal_polynomial hx) = 0 :=
(well_founded.min_mem degree_lt_wf _ hx).2
/--The defining property of the minimal polynomial of an element x:
it is the monic polynomial with smallest degree that has x as its root.-/
lemma min {p : polynomial α} (pmonic : p.monic) (hp : polynomial.aeval α β x p = 0) :
degree (minimal_polynomial hx) ≤ degree p :=
le_of_not_lt $ well_founded.not_lt_min degree_lt_wf _ hx ⟨pmonic, hp⟩
end ring
section field
variables [field α] [field β] [algebra α β]
variables {x : β} (hx : is_integral α x)
/--A minimal polynomial is nonzero.-/
lemma ne_zero : (minimal_polynomial hx) ≠ 0 :=
ne_zero_of_monic (monic hx)
/--If an element x is a root of a nonzero polynomial p,
then the degree of p is at least the degree of the minimal polynomial of x.-/
lemma degree_le_of_ne_zero
{p : polynomial α} (pnz : p ≠ 0) (hp : polynomial.aeval α β x p = 0) :
degree (minimal_polynomial hx) ≤ degree p :=
calc degree (minimal_polynomial hx) ≤ degree (p * C (leading_coeff p)⁻¹) :
min _ (monic_mul_leading_coeff_inv pnz) (by simp [hp])
... = degree p : degree_mul_leading_coeff_inv p pnz
/--The minimal polynomial of an element x is uniquely characterized by its defining property:
if there is another monic polynomial of minimal degree that has x as a root,
then this polynomial is equal to the minimal polynomial of x.-/
lemma unique {p : polynomial α} (pmonic : p.monic) (hp : polynomial.aeval α β x p = 0)
(pmin : ∀ q : polynomial α, q.monic → polynomial.aeval α β x q = 0 → degree p ≤ degree q) :
p = minimal_polynomial hx :=
begin
symmetry, apply eq_of_sub_eq_zero,
by_contra hnz,
have := degree_le_of_ne_zero hx hnz (by simp [hp]),
contrapose! this,
apply degree_sub_lt _ (ne_zero hx),
{ rw [(monic hx).leading_coeff, pmonic.leading_coeff] },
{ exact le_antisymm (min hx pmonic hp)
(pmin (minimal_polynomial hx) (monic hx) (aeval hx)) },
end
/--If an element x is a root of a polynomial p, then the minimal polynomial of x divides p.-/
lemma dvd {p : polynomial α} (hp : polynomial.aeval α β x p = 0) :
minimal_polynomial hx ∣ p :=
begin
rw ← dvd_iff_mod_by_monic_eq_zero (monic hx),
by_contra hnz,
have := degree_le_of_ne_zero hx hnz _,
{ contrapose! this,
exact degree_mod_by_monic_lt _ (monic hx) (ne_zero hx) },
{ rw ← mod_by_monic_add_div p (monic hx) at hp,
simpa using hp }
end
/--The degree of a minimal polynomial is nonzero.-/
lemma degree_ne_zero : degree (minimal_polynomial hx) ≠ 0 :=
begin
assume deg_eq_zero,
have ndeg_eq_zero : nat_degree (minimal_polynomial hx) = 0,
{ simpa using congr_arg nat_degree (eq_C_of_degree_eq_zero deg_eq_zero) },
have eq_one : minimal_polynomial hx = 1,
{ rw eq_C_of_degree_eq_zero deg_eq_zero, congr,
simpa [ndeg_eq_zero.symm] using (monic hx).leading_coeff },
simpa [eq_one, aeval_def] using aeval hx
end
/--A minimal polynomial is not a unit.-/
lemma not_is_unit : ¬ is_unit (minimal_polynomial hx) :=
assume H, degree_ne_zero hx $ degree_eq_zero_of_is_unit H
/--The degree of a minimal polynomial is positive.-/
lemma degree_pos : 0 < degree (minimal_polynomial hx) :=
degree_pos_of_ne_zero_of_nonunit (ne_zero hx) (not_is_unit hx)
/--A minimal polynomial is prime.-/
lemma prime : prime (minimal_polynomial hx) :=
begin
refine ⟨ne_zero hx, not_is_unit hx, _⟩,
rintros p q ⟨d, h⟩,
have : polynomial.aeval α β x (p*q) = 0 := by simp [h, aeval hx],
replace : polynomial.aeval α β x p = 0 ∨ polynomial.aeval α β x q = 0 := by simpa,
cases this; [left, right]; apply dvd; assumption
end
/--A minimal polynomial is irreducible.-/
lemma irreducible : irreducible (minimal_polynomial hx) :=
irreducible_of_prime (prime hx)
/--If L/K is a field extension, and x is an element of L in the image of K,
then the minimal polynomial of x is X - C x.-/
@[simp] protected lemma algebra_map (a : α) (ha : is_integral α (algebra_map α β a)) :
minimal_polynomial ha = X - C a :=
begin
refine (unique ha (monic_X_sub_C a) (by simp [aeval_def]) _).symm,
intros q hq H,
rw degree_X_sub_C,
suffices : 0 < degree q,
{ -- This part is annoying and shouldn't be there.
have q_ne_zero : q ≠ 0,
{ apply polynomial.ne_zero_of_degree_gt this },
rw degree_eq_nat_degree q_ne_zero at this ⊢,
rw [← with_bot.coe_zero, with_bot.coe_lt_coe] at this,
rwa [← with_bot.coe_one, with_bot.coe_le_coe], },
apply degree_pos_of_root (ne_zero_of_monic hq),
show is_root q a,
apply (algebra_map α β).injective,
rw [(algebra_map α β).map_zero, ← H],
exact q.hom_eval₂ (ring_hom.id _) (algebra_map α β) _,
end
variable (β)
/--If L/K is a field extension, and x is an element of L in the image of K,
then the minimal polynomial of x is X - C x.-/
lemma algebra_map' (a : α) :
minimal_polynomial (@is_integral_algebra_map α β _ _ _ a) =
X - C a :=
minimal_polynomial.algebra_map _ _
variable {β}
/--The minimal polynomial of 0 is X.-/
@[simp] lemma zero {h₀ : is_integral α (0:β)} :
minimal_polynomial h₀ = X :=
by simpa only [add_zero, polynomial.C_0, sub_eq_add_neg, neg_zero, ring_hom.map_zero]
using algebra_map' β (0:α)
/--The minimal polynomial of 1 is X - 1.-/
@[simp] lemma one {h₁ : is_integral α (1:β)} :
minimal_polynomial h₁ = X - 1 :=
by simpa only [ring_hom.map_one, polynomial.C_1, sub_eq_add_neg]
using algebra_map' β (1:α)
/--If L/K is a field extension and an element y of K is a root of the minimal polynomial
of an element x ∈ L, then y maps to x under the field embedding.-/
lemma root {x : β} (hx : is_integral α x) {y : α}
(h : is_root (minimal_polynomial hx) y) : algebra_map α β y = x :=
begin
have ndeg_one : nat_degree (minimal_polynomial hx) = 1,
{ rw ← polynomial.degree_eq_iff_nat_degree_eq_of_pos (nat.zero_lt_one),
exact degree_eq_one_of_irreducible_of_root (irreducible hx) h },
have coeff_one : (minimal_polynomial hx).coeff 1 = 1,
{ simpa only [ndeg_one, leading_coeff] using (monic hx).leading_coeff },
have hy : y = - coeff (minimal_polynomial hx) 0,
{ rw (minimal_polynomial hx).as_sum at h,
apply eq_neg_of_add_eq_zero,
simpa only [ndeg_one, coeff_one, C_1, eval_C, eval_X, eval_add, mul_one, one_mul, pow_zero, pow_one,
is_root.def, finset.sum_range_succ, finset.insert_empty_eq_singleton, finset.sum_singleton, finset.range_one] using h, },
subst y,
rw [ring_hom.map_neg, neg_eq_iff_add_eq_zero],
have H := aeval hx,
rw (minimal_polynomial hx).as_sum at H,
simpa only [ndeg_one, coeff_one, aeval_def, C_1, eval₂_add, eval₂_C, eval₂_X,
mul_one, one_mul, pow_one, pow_zero, add_comm,
finset.sum_range_succ, finset.insert_empty_eq_singleton, finset.sum_singleton, finset.range_one] using H,
end
/--The constant coefficient of the minimal polynomial of x is 0
if and only if x = 0.-/
@[simp] lemma coeff_zero_eq_zero : coeff (minimal_polynomial hx) 0 = 0 ↔ x = 0 :=
begin
split,
{ intro h,
have zero_root := polynomial.zero_is_root_of_coeff_zero_eq_zero h,
rw ← root hx zero_root,
exact is_ring_hom.map_zero _ },
{ rintro rfl, simp }
end
/--The minimal polynomial of a nonzero element has nonzero constant coefficient.-/
lemma coeff_zero_ne_zero (h : x ≠ 0) : coeff (minimal_polynomial hx) 0 ≠ 0 :=
by { contrapose! h, simpa using h }
end field
end minimal_polynomial
|
c1970b34d80044ea20b3113d02d9bae793392cb4 | 08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4 | /src/Lean/Linter/MissingDocs.lean | 3d8200fc4748e7f9b642d5a2ba0882561bd16445 | [
"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 | 10,289 | lean | /-
Copyright (c) 2022 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Lean.Meta.Tactic.Simp.SimpTheorems
import Lean.Elab.Command
import Lean.Elab.SetOption
import Lean.Linter.Util
namespace Lean.Linter
open Elab.Command Parser.Command
open Parser.Term hiding «set_option»
register_builtin_option linter.missingDocs : Bool := {
defValue := false
descr := "enable the 'missing documentation' linter"
}
def getLinterMissingDocs (o : Options) : Bool := getLinterValue linter.missingDocs o
namespace MissingDocs
abbrev SimpleHandler := Syntax → CommandElabM Unit
abbrev Handler := Bool → SimpleHandler
def SimpleHandler.toHandler (h : SimpleHandler) : Handler :=
fun enabled stx => if enabled then h stx else pure ()
unsafe def mkHandlerUnsafe (constName : Name) : ImportM Handler := do
let env := (← read).env
let opts := (← read).opts
match env.find? constName with
| none => throw ↑s!"unknown constant '{constName}'"
| some info => match info.type with
| Expr.const ``SimpleHandler _ => do
let h ← IO.ofExcept $ env.evalConst SimpleHandler opts constName
pure h.toHandler
| Expr.const ``Handler _ =>
IO.ofExcept $ env.evalConst Handler opts constName
| _ => throw ↑s!"unexpected missing docs handler at '{constName}', `MissingDocs.Handler` or `MissingDocs.SimpleHandler` expected"
@[implemented_by mkHandlerUnsafe]
opaque mkHandler (constName : Name) : ImportM Handler
builtin_initialize builtinHandlersRef : IO.Ref (NameMap Handler) ← IO.mkRef {}
builtin_initialize missingDocsExt :
PersistentEnvExtension (Name × Name) (Name × Name × Handler) (List (Name × Name) × NameMap Handler) ←
registerPersistentEnvExtension {
mkInitial := return ([], ← builtinHandlersRef.get)
addImportedFn := fun as => do
([], ·) <$> as.foldlM (init := ← builtinHandlersRef.get) fun s as =>
as.foldlM (init := s) fun s (n, k) => s.insert k <$> mkHandler n
addEntryFn := fun (entries, s) (n, k, h) => ((n, k)::entries, s.insert k h)
exportEntriesFn := fun s => s.1.reverse.toArray
statsFn := fun s => format "number of local entries: " ++ format s.1.length
}
def addHandler (env : Environment) (declName key : Name) (h : Handler) : Environment :=
missingDocsExt.addEntry env (declName, key, h)
def getHandlers (env : Environment) : NameMap Handler := (missingDocsExt.getState env).2
partial def missingDocs : Linter := fun stx => do
if let some h := (getHandlers (← getEnv)).find? stx.getKind then
h (getLinterMissingDocs (← getOptions)) stx
builtin_initialize addLinter missingDocs
def addBuiltinHandler (key : Name) (h : Handler) : IO Unit :=
builtinHandlersRef.modify (·.insert key h)
builtin_initialize
let mkAttr (builtin : Bool) (name : Name) := registerBuiltinAttribute {
name
descr := (if builtin then "(builtin) " else "") ++
"adds a syntax traversal for the missing docs linter"
applicationTime := .afterCompilation
add := fun declName stx kind => do
unless kind == AttributeKind.global do throwError "invalid attribute '{name}', must be global"
let env ← getEnv
unless builtin || (env.getModuleIdxFor? declName).isNone do
throwError "invalid attribute '{name}', declaration is in an imported module"
let decl ← getConstInfo declName
let fnNameStx ← Attribute.Builtin.getIdent stx
let key ← Elab.resolveGlobalConstNoOverloadWithInfo fnNameStx
unless decl.levelParams.isEmpty && (decl.type == .const ``Handler [] || decl.type == .const ``SimpleHandler []) do
throwError "unexpected missing docs handler at '{declName}', `MissingDocs.Handler` or `MissingDocs.SimpleHandler` expected"
if builtin then
let h := if decl.type == .const ``SimpleHandler [] then
mkApp (mkConst ``SimpleHandler.toHandler) (mkConst declName)
else mkConst declName
declareBuiltin declName <| mkApp2 (mkConst ``addBuiltinHandler) (toExpr key) h
else
setEnv <| missingDocsExt.addEntry env (declName, key, ← mkHandler declName)
}
mkAttr true `builtin_missing_docs_handler
mkAttr false `missing_docs_handler
def lint (stx : Syntax) (msg : String) : CommandElabM Unit :=
logLint linter.missingDocs stx m!"missing doc string for {msg}"
def lintNamed (stx : Syntax) (msg : String) : CommandElabM Unit :=
lint stx s!"{msg} {stx.getId}"
def lintField (parent stx : Syntax) (msg : String) : CommandElabM Unit :=
lint stx s!"{msg} {parent.getId}.{stx.getId}"
def lintStructField (parent stx : Syntax) (msg : String) : CommandElabM Unit :=
lint stx s!"{msg} {parent.getId}.{stx.getId}"
def hasInheritDoc (attrs : Syntax) : Bool :=
attrs[0][1].getSepArgs.any fun attr =>
attr[1].isOfKind ``Parser.Attr.simple &&
attr[1][0].getId.eraseMacroScopes == `inherit_doc
def declModifiersPubNoDoc (mods : Syntax) : Bool :=
mods[2][0].getKind != ``«private» && mods[0].isNone && !hasInheritDoc mods[1]
def lintDeclHead (k : SyntaxNodeKind) (id : Syntax) : CommandElabM Unit := do
if k == ``«abbrev» then lintNamed id "public abbrev"
else if k == ``«def» then lintNamed id "public def"
else if k == ``«opaque» then lintNamed id "public opaque"
else if k == ``«axiom» then lintNamed id "public axiom"
else if k == ``«inductive» then lintNamed id "public inductive"
else if k == ``classInductive then lintNamed id "public inductive"
else if k == ``«structure» then lintNamed id "public structure"
@[builtin_missing_docs_handler declaration]
def checkDecl : SimpleHandler := fun stx => do
let head := stx[0]; let rest := stx[1]
if head[2][0].getKind == ``«private» then return -- not private
let k := rest.getKind
if declModifiersPubNoDoc head then -- no doc string
lintDeclHead k rest[1][0]
if k == ``«inductive» || k == ``classInductive then
for stx in rest[4].getArgs do
let head := stx[2]
if stx[0].isNone && declModifiersPubNoDoc head then
lintField rest[1][0] stx[3] "public constructor"
unless rest[5].isNone do
for stx in rest[5][0][1].getArgs do
let head := stx[0]
if declModifiersPubNoDoc head then -- no doc string
lintField rest[1][0] stx[1] "computed field"
else if rest.getKind == ``«structure» then
unless rest[5][2].isNone do
let redecls : HashSet String.Pos :=
(← get).infoState.trees.foldl (init := {}) fun s tree =>
tree.foldInfo (init := s) fun _ info s =>
if let .ofFieldRedeclInfo info := info then
if let some range := info.stx.getRange? then
s.insert range.start
else s
else s
let parent := rest[1][0]
let lint1 stx := do
if let some range := stx.getRange? then
if redecls.contains range.start then return
lintField parent stx "public field"
for stx in rest[5][2][0].getArgs do
let head := stx[0]
if declModifiersPubNoDoc head then
if stx.getKind == ``structSimpleBinder then
lint1 stx[1]
else
for stx in stx[2].getArgs do
lint1 stx
@[builtin_missing_docs_handler «initialize»]
def checkInit : SimpleHandler := fun stx => do
if !stx[2].isNone && declModifiersPubNoDoc stx[0] then
lintNamed stx[2][0] "initializer"
@[builtin_missing_docs_handler «notation»]
def checkNotation : SimpleHandler := fun stx => do
if stx[0].isNone && stx[2][0][0].getKind != ``«local» && !hasInheritDoc stx[1] then
if stx[5].isNone then lint stx[3] "notation"
else lintNamed stx[5][0][3] "notation"
@[builtin_missing_docs_handler «mixfix»]
def checkMixfix : SimpleHandler := fun stx => do
if stx[0].isNone && stx[2][0][0].getKind != ``«local» && !hasInheritDoc stx[1] then
if stx[5].isNone then lint stx[3] stx[3][0].getAtomVal
else lintNamed stx[5][0][3] stx[3][0].getAtomVal
@[builtin_missing_docs_handler «syntax»]
def checkSyntax : SimpleHandler := fun stx => do
if stx[0].isNone && stx[2][0][0].getKind != ``«local» && !hasInheritDoc stx[1] then
if stx[5].isNone then lint stx[3] "syntax"
else lintNamed stx[5][0][3] "syntax"
def mkSimpleHandler (name : String) : SimpleHandler := fun stx => do
if stx[0].isNone then
lintNamed stx[2] name
@[builtin_missing_docs_handler syntaxAbbrev]
def checkSyntaxAbbrev : SimpleHandler := mkSimpleHandler "syntax"
@[builtin_missing_docs_handler syntaxCat]
def checkSyntaxCat : SimpleHandler := mkSimpleHandler "syntax category"
@[builtin_missing_docs_handler «macro»]
def checkMacro : SimpleHandler := fun stx => do
if stx[0].isNone && stx[2][0][0].getKind != ``«local» && !hasInheritDoc stx[1] then
if stx[5].isNone then lint stx[3] "macro"
else lintNamed stx[5][0][3] "macro"
@[builtin_missing_docs_handler «elab»]
def checkElab : SimpleHandler := fun stx => do
if stx[0].isNone && stx[2][0][0].getKind != ``«local» && !hasInheritDoc stx[1] then
if stx[5].isNone then lint stx[3] "elab"
else lintNamed stx[5][0][3] "elab"
@[builtin_missing_docs_handler classAbbrev]
def checkClassAbbrev : SimpleHandler := fun stx => do
if declModifiersPubNoDoc stx[0] then
lintNamed stx[3] "class abbrev"
@[builtin_missing_docs_handler Parser.Tactic.declareSimpLikeTactic]
def checkSimpLike : SimpleHandler := mkSimpleHandler "simp-like tactic"
@[builtin_missing_docs_handler Option.registerBuiltinOption]
def checkRegisterBuiltinOption : SimpleHandler := mkSimpleHandler "option"
@[builtin_missing_docs_handler Option.registerOption]
def checkRegisterOption : SimpleHandler := mkSimpleHandler "option"
@[builtin_missing_docs_handler registerSimpAttr]
def checkRegisterSimpAttr : SimpleHandler := mkSimpleHandler "simp attr"
@[builtin_missing_docs_handler «in»]
def handleIn : Handler := fun _ stx => do
if stx[0].getKind == ``«set_option» then
let opts ← Elab.elabSetOption stx[0][1] stx[0][2]
withScope (fun scope => { scope with opts }) do
missingDocs stx[2]
else
missingDocs stx[2]
@[builtin_missing_docs_handler «mutual»]
def handleMutual : Handler := fun _ stx => do
stx[1].getArgs.forM missingDocs
|
9b94338a94f7af50701e9d78aaa9af728a20c2d1 | ce89339993655da64b6ccb555c837ce6c10f9ef4 | /bluejam/chap7/section7.2.lean | 74d1221ad05c4f0f0bca4dd6b0e0bd08f45b71b0 | [] | no_license | zeptometer/LearnLean | ef32dc36a22119f18d843f548d0bb42f907bff5d | bb84d5dbe521127ba134d4dbf9559b294a80b9f7 | refs/heads/master | 1,625,710,824,322 | 1,601,382,570,000 | 1,601,382,570,000 | 195,228,870 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 544 | lean | universe u
namespace hidden
variables {α β γ : Type u}
example : inhabited bool := inhabited.mk tt
example : inhabited nat := inhabited.mk 0
def partial_composite (f : α → option β) (g : β → option γ) (x : α) : option γ
:= option.rec_on (f x) none (λ x, g x)
def func1 (n : nat) : option nat := cond (2 ∣ n) (some n) none
def func2 (n : nat) : option nat := cond (4 ∣ n) (some n) none
def f12 : nat → option nat := partial_composite func1 func2
#eval f12 2
#eval f12 3
#eval f12 4
#eval f12 8
#eval f12 9
end hidden
|
9bf3af7056eb97fdb6b563c647f62e1d6eb61824 | 77c5b91fae1b966ddd1db969ba37b6f0e4901e88 | /src/ring_theory/valuation/basic.lean | 770878f7bbfff17cd7ddd7287b78af56ad699526 | [
"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,509 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard, Johan Commelin, Patrick Massot
-/
import algebra.order.with_zero
import algebra.group_power
import ring_theory.ideal.operations
import algebra.punit_instances
/-!
# The basics of valuation theory.
The basic theory of valuations (non-archimedean norms) on a commutative ring,
following T. Wedhorn's unpublished notes “Adic Spaces” ([wedhorn_adic]).
The definition of a valuation we use here is Definition 1.22 of [wedhorn_adic].
A valuation on a ring `R` is a monoid homomorphism `v` to a linearly ordered
commutative monoid with zero, that in addition satisfies the following two axioms:
* `v 0 = 0`
* `∀ x y, v (x + y) ≤ max (v x) (v y)`
`valuation R Γ₀`is the type of valuations `R → Γ₀`, with a coercion to the underlying
function. If `v` is a valuation from `R` to `Γ₀` then the induced group
homomorphism `units(R) → Γ₀` is called `unit_map v`.
The equivalence "relation" `is_equiv v₁ v₂ : Prop` defined in 1.27 of [wedhorn_adic] is not strictly
speaking a relation, because `v₁ : valuation R Γ₁` and `v₂ : valuation R Γ₂` might
not have the same type. This corresponds in ZFC to the set-theoretic difficulty
that the class of all valuations (as `Γ₀` varies) on a ring `R` is not a set.
The "relation" is however reflexive, symmetric and transitive in the obvious
sense. Note that we use 1.27(iii) of [wedhorn_adic] as the definition of equivalence.
The support of a valuation `v : valuation R Γ₀` is `supp v`. If `J` is an ideal of `R`
with `h : J ⊆ supp v` then the induced valuation
on R / J = `ideal.quotient J` is `on_quot v h`.
## Main definitions
* `valuation R Γ₀`, the type of valuations on `R` with values in `Γ₀`
* `valuation.is_equiv`, the heterogeneous equivalence relation on valuations
* `valuation.supp`, the support of a valuation
* `add_valuation R Γ₀`, the type of additive valuations on `R` with values in a
linearly ordered additive commutative group with a top element, `Γ₀`.
## Implementation Details
`add_valuation R Γ₀` is implemented as `valuation R (multiplicative (order_dual Γ₀))`.
-/
open_locale classical big_operators
noncomputable theory
open function ideal
variables {R : Type*} -- This will be a ring, assumed commutative in some sections
set_option old_structure_cmd true
section
variables (R) (Γ₀ : Type*) [linear_ordered_comm_monoid_with_zero Γ₀] [ring R]
/-- The type of `Γ₀`-valued valuations on `R`. -/
@[nolint has_inhabited_instance]
structure valuation extends monoid_with_zero_hom R Γ₀ :=
(map_add' : ∀ x y, to_fun (x + y) ≤ max (to_fun x) (to_fun y))
/-- The `monoid_with_zero_hom` underlying a valuation. -/
add_decl_doc valuation.to_monoid_with_zero_hom
end
namespace valuation
variables {Γ₀ : Type*}
variables {Γ'₀ : Type*}
variables {Γ''₀ : Type*} [linear_ordered_comm_monoid_with_zero Γ''₀]
section basic
variables (R) (Γ₀) [ring R]
section monoid
variables [linear_ordered_comm_monoid_with_zero Γ₀] [linear_ordered_comm_monoid_with_zero Γ'₀]
/-- A valuation is coerced to the underlying function `R → Γ₀`. -/
instance : has_coe_to_fun (valuation R Γ₀) := { F := λ _, R → Γ₀, coe := valuation.to_fun }
/-- A valuation is coerced to a monoid morphism R → Γ₀. -/
instance : has_coe (valuation R Γ₀) (monoid_with_zero_hom R Γ₀) :=
⟨valuation.to_monoid_with_zero_hom⟩
variables {R} {Γ₀} (v : valuation R Γ₀) {x y z : R}
@[simp, norm_cast] lemma coe_coe : ((v : monoid_with_zero_hom R Γ₀) : R → Γ₀) = v := rfl
@[simp] lemma map_zero : v 0 = 0 := v.map_zero'
@[simp] lemma map_one : v 1 = 1 := v.map_one'
@[simp] lemma map_mul : ∀ x y, v (x * y) = v x * v y := v.map_mul'
@[simp] lemma map_add : ∀ x y, v (x + y) ≤ max (v x) (v y) := v.map_add'
lemma map_add_le {x y g} (hx : v x ≤ g) (hy : v y ≤ g) : v (x + y) ≤ g :=
le_trans (v.map_add x y) $ max_le hx hy
lemma map_add_lt {x y g} (hx : v x < g) (hy : v y < g) : v (x + y) < g :=
lt_of_le_of_lt (v.map_add x y) $ max_lt hx hy
lemma map_sum_le {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hf : ∀ i ∈ s, v (f i) ≤ g) :
v (∑ i in s, f i) ≤ g :=
begin
refine finset.induction_on s
(λ _, trans_rel_right (≤) v.map_zero zero_le') (λ a s has ih hf, _) hf,
rw finset.forall_mem_insert at hf, rw finset.sum_insert has,
exact v.map_add_le hf.1 (ih hf.2)
end
lemma map_sum_lt {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hg : g ≠ 0)
(hf : ∀ i ∈ s, v (f i) < g) : v (∑ i in s, f i) < g :=
begin
refine finset.induction_on s
(λ _, trans_rel_right (<) v.map_zero (zero_lt_iff.2 hg)) (λ a s has ih hf, _) hf,
rw finset.forall_mem_insert at hf, rw finset.sum_insert has,
exact v.map_add_lt hf.1 (ih hf.2)
end
lemma map_sum_lt' {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hg : 0 < g)
(hf : ∀ i ∈ s, v (f i) < g) : v (∑ i in s, f i) < g :=
v.map_sum_lt (ne_of_gt hg) hf
@[simp] lemma map_pow : ∀ x (n:ℕ), v (x^n) = (v x)^n :=
v.to_monoid_with_zero_hom.to_monoid_hom.map_pow
@[ext] lemma ext {v₁ v₂ : valuation R Γ₀} (h : ∀ r, v₁ r = v₂ r) : v₁ = v₂ :=
by { cases v₁, cases v₂, congr, funext r, exact h r }
lemma ext_iff {v₁ v₂ : valuation R Γ₀} : v₁ = v₂ ↔ ∀ r, v₁ r = v₂ r :=
⟨λ h r, congr_arg _ h, ext⟩
-- The following definition is not an instance, because we have more than one `v` on a given `R`.
-- In addition, type class inference would not be able to infer `v`.
/-- A valuation gives a preorder on the underlying ring. -/
def to_preorder : preorder R := preorder.lift v
/-- If `v` is a valuation on a division ring then `v(x) = 0` iff `x = 0`. -/
@[simp] lemma zero_iff [nontrivial Γ₀] {K : Type*} [division_ring K]
(v : valuation K Γ₀) {x : K} : v x = 0 ↔ x = 0 :=
v.to_monoid_with_zero_hom.map_eq_zero
lemma ne_zero_iff [nontrivial Γ₀] {K : Type*} [division_ring K]
(v : valuation K Γ₀) {x : K} : v x ≠ 0 ↔ x ≠ 0 :=
v.to_monoid_with_zero_hom.map_ne_zero
theorem unit_map_eq (u : units R) :
(units.map (v : R →* Γ₀) u : Γ₀) = v u := rfl
/-- A ring homomorphism `S → R` induces a map `valuation R Γ₀ → valuation S Γ₀`. -/
def comap {S : Type*} [ring S] (f : S →+* R) (v : valuation R Γ₀) :
valuation S Γ₀ :=
{ to_fun := v ∘ f,
map_add' := λ x y, by simp only [comp_app, map_add, f.map_add],
.. v.to_monoid_with_zero_hom.comp f.to_monoid_with_zero_hom, }
@[simp] lemma comap_id : v.comap (ring_hom.id R) = v := ext $ λ r, rfl
lemma comap_comp {S₁ : Type*} {S₂ : Type*} [ring S₁] [ring S₂] (f : S₁ →+* S₂) (g : S₂ →+* R) :
v.comap (g.comp f) = (v.comap g).comap f :=
ext $ λ r, rfl
/-- A `≤`-preserving group homomorphism `Γ₀ → Γ'₀` induces a map `valuation R Γ₀ → valuation R Γ'₀`.
-/
def map (f : monoid_with_zero_hom Γ₀ Γ'₀) (hf : monotone f) (v : valuation R Γ₀) :
valuation R Γ'₀ :=
{ to_fun := f ∘ v,
map_add' := λ r s,
calc f (v (r + s)) ≤ f (max (v r) (v s)) : hf (v.map_add r s)
... = max (f (v r)) (f (v s)) : hf.map_max,
.. monoid_with_zero_hom.comp f v.to_monoid_with_zero_hom }
/-- Two valuations on `R` are defined to be equivalent if they induce the same preorder on `R`. -/
def is_equiv (v₁ : valuation R Γ₀) (v₂ : valuation R Γ'₀) : Prop :=
∀ r s, v₁ r ≤ v₁ s ↔ v₂ r ≤ v₂ s
end monoid
section group
variables [linear_ordered_comm_group_with_zero Γ₀] {R} {Γ₀} (v : valuation R Γ₀) {x y z : R}
@[simp] lemma map_inv {K : Type*} [division_ring K]
(v : valuation K Γ₀) {x : K} : v x⁻¹ = (v x)⁻¹ :=
v.to_monoid_with_zero_hom.map_inv x
lemma map_units_inv (x : units R) : v (x⁻¹ : units R) = (v x)⁻¹ :=
v.to_monoid_with_zero_hom.to_monoid_hom.map_units_inv x
@[simp] lemma map_neg (x : R) : v (-x) = v x :=
v.to_monoid_with_zero_hom.to_monoid_hom.map_neg x
lemma map_sub_swap (x y : R) : v (x - y) = v (y - x) :=
v.to_monoid_with_zero_hom.to_monoid_hom.map_sub_swap x y
lemma map_sub (x y : R) : v (x - y) ≤ max (v x) (v y) :=
calc v (x - y) = v (x + -y) : by rw [sub_eq_add_neg]
... ≤ max (v x) (v $ -y) : v.map_add _ _
... = max (v x) (v y) : by rw map_neg
lemma map_sub_le {x y g} (hx : v x ≤ g) (hy : v y ≤ g) : v (x - y) ≤ g :=
begin
rw sub_eq_add_neg,
exact v.map_add_le hx (le_trans (le_of_eq (v.map_neg y)) hy)
end
lemma map_add_of_distinct_val (h : v x ≠ v y) : v (x + y) = max (v x) (v y) :=
begin
suffices : ¬v (x + y) < max (v x) (v y),
from or_iff_not_imp_right.1 (le_iff_eq_or_lt.1 (v.map_add x y)) this,
intro h',
wlog vyx : v y < v x using x y,
{ apply lt_or_gt_of_ne h.symm },
{ rw max_eq_left_of_lt vyx at h',
apply lt_irrefl (v x),
calc v x = v ((x+y) - y) : by simp
... ≤ max (v $ x + y) (v y) : map_sub _ _ _
... < v x : max_lt h' vyx },
{ apply this h.symm,
rwa [add_comm, max_comm] at h' }
end
lemma map_eq_of_sub_lt (h : v (y - x) < v x) : v y = v x :=
begin
have := valuation.map_add_of_distinct_val v (ne_of_gt h).symm,
rw max_eq_right (le_of_lt h) at this,
simpa using this
end
end group
end basic -- end of section
namespace is_equiv
variables [ring R]
variables [linear_ordered_comm_monoid_with_zero Γ₀] [linear_ordered_comm_monoid_with_zero Γ'₀]
variables {v : valuation R Γ₀}
variables {v₁ : valuation R Γ₀} {v₂ : valuation R Γ'₀} {v₃ : valuation R Γ''₀}
@[refl] lemma refl : v.is_equiv v :=
λ _ _, iff.refl _
@[symm] lemma symm (h : v₁.is_equiv v₂) : v₂.is_equiv v₁ :=
λ _ _, iff.symm (h _ _)
@[trans] lemma trans (h₁₂ : v₁.is_equiv v₂) (h₂₃ : v₂.is_equiv v₃) : v₁.is_equiv v₃ :=
λ _ _, iff.trans (h₁₂ _ _) (h₂₃ _ _)
lemma of_eq {v' : valuation R Γ₀} (h : v = v') : v.is_equiv v' :=
by { subst h }
lemma map {v' : valuation R Γ₀} (f : monoid_with_zero_hom Γ₀ Γ'₀) (hf : monotone f)
(inf : injective f) (h : v.is_equiv v') :
(v.map f hf).is_equiv (v'.map f hf) :=
let H : strict_mono f := hf.strict_mono_of_injective inf in
λ r s,
calc f (v r) ≤ f (v s) ↔ v r ≤ v s : by rw H.le_iff_le
... ↔ v' r ≤ v' s : h r s
... ↔ f (v' r) ≤ f (v' s) : by rw H.le_iff_le
/-- `comap` preserves equivalence. -/
lemma comap {S : Type*} [ring S] (f : S →+* R) (h : v₁.is_equiv v₂) :
(v₁.comap f).is_equiv (v₂.comap f) :=
λ r s, h (f r) (f s)
lemma val_eq (h : v₁.is_equiv v₂) {r s : R} :
v₁ r = v₁ s ↔ v₂ r = v₂ s :=
by simpa only [le_antisymm_iff] using and_congr (h r s) (h s r)
lemma ne_zero (h : v₁.is_equiv v₂) {r : R} :
v₁ r ≠ 0 ↔ v₂ r ≠ 0 :=
begin
have : v₁ r ≠ v₁ 0 ↔ v₂ r ≠ v₂ 0 := not_iff_not_of_iff h.val_eq,
rwa [v₁.map_zero, v₂.map_zero] at this,
end
end is_equiv -- end of namespace
section
lemma is_equiv_of_map_strict_mono [linear_ordered_comm_monoid_with_zero Γ₀]
[linear_ordered_comm_monoid_with_zero Γ'₀]
[ring R] {v : valuation R Γ₀}
(f : monoid_with_zero_hom Γ₀ Γ'₀) (H : strict_mono f) :
is_equiv (v.map f (H.monotone)) v :=
λ x y, ⟨H.le_iff_le.mp, λ h, H.monotone h⟩
lemma is_equiv_of_val_le_one [linear_ordered_comm_group_with_zero Γ₀]
[linear_ordered_comm_group_with_zero Γ'₀]
{K : Type*} [division_ring K]
(v : valuation K Γ₀) (v' : valuation K Γ'₀) (h : ∀ {x:K}, v x ≤ 1 ↔ v' x ≤ 1) :
v.is_equiv v' :=
begin
intros x y,
by_cases hy : y = 0, { simp [hy, zero_iff], },
rw show y = 1 * y, by rw one_mul,
rw [← (inv_mul_cancel_right₀ hy x)],
iterate 2 {rw [v.map_mul _ y, v'.map_mul _ y]},
rw [v.map_one, v'.map_one],
split; intro H,
{ apply mul_le_mul_right',
replace hy := v.ne_zero_iff.mpr hy,
replace H := le_of_le_mul_right hy H,
rwa h at H, },
{ apply mul_le_mul_right',
replace hy := v'.ne_zero_iff.mpr hy,
replace H := le_of_le_mul_right hy H,
rwa h, },
end
end
section supp
variables [comm_ring R]
variables [linear_ordered_comm_monoid_with_zero Γ₀] [linear_ordered_comm_monoid_with_zero Γ'₀]
variables (v : valuation R Γ₀)
/-- The support of a valuation `v : R → Γ₀` is the ideal of `R` where `v` vanishes. -/
def supp : ideal R :=
{ carrier := {x | v x = 0},
zero_mem' := map_zero v,
add_mem' := λ x y hx hy, le_zero_iff.mp $
calc v (x + y) ≤ max (v x) (v y) : v.map_add x y
... ≤ 0 : max_le (le_zero_iff.mpr hx) (le_zero_iff.mpr hy),
smul_mem' := λ c x hx, calc v (c * x)
= v c * v x : map_mul v c x
... = v c * 0 : congr_arg _ hx
... = 0 : mul_zero _ }
@[simp] lemma mem_supp_iff (x : R) : x ∈ supp v ↔ v x = 0 := iff.rfl
-- @[simp] lemma mem_supp_iff' (x : R) : x ∈ (supp v : set R) ↔ v x = 0 := iff.rfl
/-- The support of a valuation is a prime ideal. -/
instance [nontrivial Γ₀] [no_zero_divisors Γ₀] : ideal.is_prime (supp v) :=
⟨λ (h : v.supp = ⊤), one_ne_zero $ show (1 : Γ₀) = 0,
from calc 1 = v 1 : v.map_one.symm
... = 0 : show (1:R) ∈ supp v, by { rw h, trivial },
λ x y hxy, begin
show v x = 0 ∨ v y = 0,
change v (x * y) = 0 at hxy,
rw [v.map_mul x y] at hxy,
exact eq_zero_or_eq_zero_of_mul_eq_zero hxy
end⟩
lemma map_add_supp (a : R) {s : R} (h : s ∈ supp v) : v (a + s) = v a :=
begin
have aux : ∀ a s, v s = 0 → v (a + s) ≤ v a,
{ intros a' s' h', refine le_trans (v.map_add a' s') (max_le (le_refl _) _), simp [h'], },
apply le_antisymm (aux a s h),
calc v a = v (a + s + -s) : by simp
... ≤ v (a + s) : aux (a + s) (-s) (by rwa ←ideal.neg_mem_iff at h)
end
/-- If `hJ : J ⊆ supp v` then `on_quot_val hJ` is the induced function on R/J as a function.
Note: it's just the function; the valuation is `on_quot hJ`. -/
def on_quot_val {J : ideal R} (hJ : J ≤ supp v) :
J.quotient → Γ₀ :=
λ q, quotient.lift_on' q v $ λ a b h,
calc v a = v (b + (a - b)) : by simp
... = v b : v.map_add_supp b (hJ h)
/-- The extension of valuation v on R to valuation on R/J if J ⊆ supp v -/
def on_quot {J : ideal R} (hJ : J ≤ supp v) :
valuation J.quotient Γ₀ :=
{ to_fun := v.on_quot_val hJ,
map_zero' := v.map_zero,
map_one' := v.map_one,
map_mul' := λ xbar ybar, quotient.ind₂' v.map_mul xbar ybar,
map_add' := λ xbar ybar, quotient.ind₂' v.map_add xbar ybar }
@[simp] lemma on_quot_comap_eq {J : ideal R} (hJ : J ≤ supp v) :
(v.on_quot hJ).comap (ideal.quotient.mk J) = v :=
ext $ λ r,
begin
refine @quotient.lift_on_mk _ _ (J.quotient_rel) v (λ a b h, _) _,
calc v a = v (b + (a - b)) : by simp
... = v b : v.map_add_supp b (hJ h)
end
lemma comap_supp {S : Type*} [comm_ring S] (f : S →+* R) :
supp (v.comap f) = ideal.comap f v.supp :=
ideal.ext $ λ x,
begin
rw [mem_supp_iff, ideal.mem_comap, mem_supp_iff],
refl,
end
lemma self_le_supp_comap (J : ideal R) (v : valuation (quotient J) Γ₀) :
J ≤ (v.comap (ideal.quotient.mk J)).supp :=
by { rw [comap_supp, ← ideal.map_le_iff_le_comap], simp }
@[simp] lemma comap_on_quot_eq (J : ideal R) (v : valuation J.quotient Γ₀) :
(v.comap (ideal.quotient.mk J)).on_quot (v.self_le_supp_comap J) = v :=
ext $ by { rintro ⟨x⟩, refl }
/-- The quotient valuation on R/J has support supp(v)/J if J ⊆ supp v. -/
lemma supp_quot {J : ideal R} (hJ : J ≤ supp v) :
supp (v.on_quot hJ) = (supp v).map (ideal.quotient.mk J) :=
begin
apply le_antisymm,
{ rintro ⟨x⟩ hx,
apply ideal.subset_span,
exact ⟨x, hx, rfl⟩ },
{ rw ideal.map_le_iff_le_comap,
intros x hx, exact hx }
end
lemma supp_quot_supp : supp (v.on_quot (le_refl _)) = 0 :=
by { rw supp_quot, exact ideal.map_quotient_self _ }
end supp -- end of section
end valuation
section add_monoid
variables (R) [ring R] (Γ₀ : Type*) [linear_ordered_add_comm_monoid_with_top Γ₀]
/-- The type of `Γ₀`-valued additive valuations on `R`. -/
@[nolint has_inhabited_instance]
def add_valuation := valuation R (multiplicative (order_dual Γ₀))
end add_monoid
namespace add_valuation
variables {Γ₀ : Type*} {Γ'₀ : Type*}
section basic
section monoid
variables [linear_ordered_add_comm_monoid_with_top Γ₀] [linear_ordered_add_comm_monoid_with_top Γ'₀]
variables (R) (Γ₀) [ring R]
/-- A valuation is coerced to the underlying function `R → Γ₀`. -/
instance : has_coe_to_fun (add_valuation R Γ₀) := { F := λ _, R → Γ₀, coe := valuation.to_fun }
variables {R} {Γ₀} (v : add_valuation R Γ₀) {x y z : R}
section
variables (f : R → Γ₀) (h0 : f 0 = ⊤) (h1 : f 1 = 0)
variables (hadd : ∀ x y, min (f x) (f y) ≤ f (x + y)) (hmul : ∀ x y, f (x * y) = f x + f y)
/-- An alternate constructor of `add_valuation`, that doesn't reference
`multiplicative (order_dual Γ₀)` -/
def of : add_valuation R Γ₀ :=
{ to_fun := f,
map_one' := h1,
map_zero' := h0,
map_add' := hadd,
map_mul' := hmul }
variables {h0} {h1} {hadd} {hmul} {r : R}
@[simp]
theorem of_apply : (of f h0 h1 hadd hmul) r = f r := rfl
end
@[simp] lemma map_zero : v 0 = ⊤ := v.map_zero
@[simp] lemma map_one : v 1 = 0 := v.map_one
@[simp] lemma map_mul : ∀ x y, v (x * y) = v x + v y := v.map_mul
@[simp] lemma map_add : ∀ x y, min (v x) (v y) ≤ v (x + y) := v.map_add
lemma map_le_add {x y g} (hx : g ≤ v x) (hy : g ≤ v y) : g ≤ v (x + y) := v.map_add_le hx hy
lemma map_lt_add {x y g} (hx : g < v x) (hy : g < v y) : g < v (x + y) := v.map_add_lt hx hy
lemma map_le_sum {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hf : ∀ i ∈ s, g ≤ v (f i)) :
g ≤ v (∑ i in s, f i) := v.map_sum_le hf
lemma map_lt_sum {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hg : g ≠ ⊤)
(hf : ∀ i ∈ s, g < v (f i)) : g < v (∑ i in s, f i) := v.map_sum_lt hg hf
lemma map_lt_sum' {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hg : g < ⊤)
(hf : ∀ i ∈ s, g < v (f i)) : g < v (∑ i in s, f i) := v.map_sum_lt' hg hf
@[simp] lemma map_pow : ∀ x (n:ℕ), v (x^n) = n • (v x) := v.map_pow
@[ext] lemma ext {v₁ v₂ : add_valuation R Γ₀} (h : ∀ r, v₁ r = v₂ r) : v₁ = v₂ :=
valuation.ext h
lemma ext_iff {v₁ v₂ : add_valuation R Γ₀} : v₁ = v₂ ↔ ∀ r, v₁ r = v₂ r :=
valuation.ext_iff
-- The following definition is not an instance, because we have more than one `v` on a given `R`.
-- In addition, type class inference would not be able to infer `v`.
/-- A valuation gives a preorder on the underlying ring. -/
def to_preorder : preorder R := preorder.lift v
/-- If `v` is an additive valuation on a division ring then `v(x) = ⊤` iff `x = 0`. -/
@[simp] lemma top_iff [nontrivial Γ₀] {K : Type*} [division_ring K]
(v : add_valuation K Γ₀) {x : K} : v x = ⊤ ↔ x = 0 :=
v.zero_iff
lemma ne_top_iff [nontrivial Γ₀] {K : Type*} [division_ring K]
(v : add_valuation K Γ₀) {x : K} : v x ≠ ⊤ ↔ x ≠ 0 := v.ne_zero_iff
/-- A ring homomorphism `S → R` induces a map `add_valuation R Γ₀ → add_valuation S Γ₀`. -/
def comap {S : Type*} [ring S] (f : S →+* R) (v : add_valuation R Γ₀) :
add_valuation S Γ₀ :=
v.comap f
@[simp] lemma comap_id : v.comap (ring_hom.id R) = v := v.comap_id
lemma comap_comp {S₁ : Type*} {S₂ : Type*} [ring S₁] [ring S₂] (f : S₁ →+* S₂) (g : S₂ →+* R) :
v.comap (g.comp f) = (v.comap g).comap f :=
v.comap_comp f g
/-- A `≤`-preserving, `⊤`-preserving group homomorphism `Γ₀ → Γ'₀` induces a map
`add_valuation R Γ₀ → add_valuation R Γ'₀`.
-/
def map (f : Γ₀ →+ Γ'₀) (ht : f ⊤ = ⊤) (hf : monotone f) (v : add_valuation R Γ₀) :
add_valuation R Γ'₀ :=
v.map {
to_fun := f,
map_mul' := f.map_add,
map_one' := f.map_zero,
map_zero' := ht } (λ x y h, hf h)
/-- Two additive valuations on `R` are defined to be equivalent if they induce the same
preorder on `R`. -/
def is_equiv (v₁ : add_valuation R Γ₀) (v₂ : add_valuation R Γ'₀) : Prop :=
v₁.is_equiv v₂
end monoid
section group
variables [linear_ordered_add_comm_group_with_top Γ₀] [ring R] (v : add_valuation R Γ₀) {x y z : R}
@[simp] lemma map_inv {K : Type*} [division_ring K]
(v : add_valuation K Γ₀) {x : K} : v x⁻¹ = - (v x) :=
v.map_inv
lemma map_units_inv (x : units R) : v (x⁻¹ : units R) = - (v x) :=
v.map_units_inv x
@[simp] lemma map_neg (x : R) : v (-x) = v x :=
v.map_neg x
lemma map_sub_swap (x y : R) : v (x - y) = v (y - x) :=
v.map_sub_swap x y
lemma map_sub (x y : R) : min (v x) (v y) ≤ v (x - y) :=
v.map_sub x y
lemma map_le_sub {x y g} (hx : g ≤ v x) (hy : g ≤ v y) : g ≤ v (x - y) := v.map_sub_le hx hy
lemma map_add_of_distinct_val (h : v x ≠ v y) : v (x + y) = min (v x) (v y) :=
v.map_add_of_distinct_val h
lemma map_eq_of_lt_sub (h : v x < v (y - x)) : v y = v x :=
v.map_eq_of_sub_lt h
end group
end basic
namespace is_equiv
variables [linear_ordered_add_comm_monoid_with_top Γ₀] [linear_ordered_add_comm_monoid_with_top Γ'₀]
variables [ring R]
variables {Γ''₀ : Type*} [linear_ordered_add_comm_monoid_with_top Γ''₀]
variables {v : add_valuation R Γ₀}
variables {v₁ : add_valuation R Γ₀} {v₂ : add_valuation R Γ'₀} {v₃ : add_valuation R Γ''₀}
@[refl] lemma refl : v.is_equiv v := valuation.is_equiv.refl
@[symm] lemma symm (h : v₁.is_equiv v₂) : v₂.is_equiv v₁ := h.symm
@[trans] lemma trans (h₁₂ : v₁.is_equiv v₂) (h₂₃ : v₂.is_equiv v₃) : v₁.is_equiv v₃ :=
h₁₂.trans h₂₃
lemma of_eq {v' : add_valuation R Γ₀} (h : v = v') : v.is_equiv v' :=
valuation.is_equiv.of_eq h
lemma map {v' : add_valuation R Γ₀} (f : Γ₀ →+ Γ'₀) (ht : f ⊤ = ⊤) (hf : monotone f)
(inf : injective f) (h : v.is_equiv v') :
(v.map f ht hf).is_equiv (v'.map f ht hf) :=
h.map {
to_fun := f,
map_mul' := f.map_add,
map_one' := f.map_zero,
map_zero' := ht } (λ x y h, hf h) inf
/-- `comap` preserves equivalence. -/
lemma comap {S : Type*} [ring S] (f : S →+* R) (h : v₁.is_equiv v₂) :
(v₁.comap f).is_equiv (v₂.comap f) :=
h.comap f
lemma val_eq (h : v₁.is_equiv v₂) {r s : R} :
v₁ r = v₁ s ↔ v₂ r = v₂ s :=
h.val_eq
lemma ne_top (h : v₁.is_equiv v₂) {r : R} :
v₁ r ≠ ⊤ ↔ v₂ r ≠ ⊤ :=
h.ne_zero
end is_equiv
section supp
variables [linear_ordered_add_comm_monoid_with_top Γ₀] [linear_ordered_add_comm_monoid_with_top Γ'₀]
variables [comm_ring R]
variables (v : add_valuation R Γ₀)
/-- The support of an additive valuation `v : R → Γ₀` is the ideal of `R` where `v x = ⊤` -/
def supp : ideal R := v.supp
@[simp] lemma mem_supp_iff (x : R) : x ∈ supp v ↔ v x = ⊤ := v.mem_supp_iff x
lemma map_add_supp (a : R) {s : R} (h : s ∈ supp v) : v (a + s) = v a :=
v.map_add_supp a h
/-- If `hJ : J ⊆ supp v` then `on_quot_val hJ` is the induced function on R/J as a function.
Note: it's just the function; the valuation is `on_quot hJ`. -/
def on_quot_val {J : ideal R} (hJ : J ≤ supp v) : J.quotient → Γ₀ := v.on_quot_val hJ
/-- The extension of valuation v on R to valuation on R/J if J ⊆ supp v -/
def on_quot {J : ideal R} (hJ : J ≤ supp v) :
add_valuation J.quotient Γ₀ :=
v.on_quot hJ
@[simp] lemma on_quot_comap_eq {J : ideal R} (hJ : J ≤ supp v) :
(v.on_quot hJ).comap (ideal.quotient.mk J) = v :=
v.on_quot_comap_eq hJ
lemma comap_supp {S : Type*} [comm_ring S] (f : S →+* R) :
supp (v.comap f) = ideal.comap f v.supp :=
v.comap_supp f
lemma self_le_supp_comap (J : ideal R) (v : add_valuation (quotient J) Γ₀) :
J ≤ (v.comap (ideal.quotient.mk J)).supp :=
v.self_le_supp_comap J
@[simp] lemma comap_on_quot_eq (J : ideal R) (v : add_valuation J.quotient Γ₀) :
(v.comap (ideal.quotient.mk J)).on_quot (v.self_le_supp_comap J) = v :=
v.comap_on_quot_eq J
/-- The quotient valuation on R/J has support supp(v)/J if J ⊆ supp v. -/
lemma supp_quot {J : ideal R} (hJ : J ≤ supp v) :
supp (v.on_quot hJ) = (supp v).map (ideal.quotient.mk J) :=
v.supp_quot hJ
lemma supp_quot_supp : supp (v.on_quot (le_refl _)) = 0 :=
v.supp_quot_supp
end supp -- end of section
attribute [irreducible] add_valuation
end add_valuation
|
dc2be34ddcd0b1ed1c07639df8555336e903806b | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/meta/smt/default.lean | 506567fa1412361ae402c0020992034b638de4bc | [] | 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 | 493 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.meta.smt.congruence_closure
import Mathlib.Lean3Lib.init.cc_lemmas
import Mathlib.Lean3Lib.init.meta.smt.ematch
import Mathlib.Lean3Lib.init.meta.smt.smt_tactic
import Mathlib.Lean3Lib.init.meta.smt.interactive
import Mathlib.Lean3Lib.init.meta.smt.rsimp
namespace Mathlib
|
86591f7cc70a3ad80dfb7dad4505092333750c26 | 957a80ea22c5abb4f4670b250d55534d9db99108 | /tests/lean/run/whnfinst.lean | a0d119f707377a61f33fe98da585424439e061d6 | [
"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 | 441 | lean | open decidable
attribute [reducible]
definition decidable_bin_rel {A : Type} (R : A → A → Prop) := Πx y, decidable (R x y)
section
variable {A : Type}
variable (R : A → A → Prop)
theorem tst1 (H : Πx y, decidable (R x y)) (a b c : A) : decidable (R a b ∧ R b a) :=
by tactic.apply_instance
theorem tst2 (H : decidable_bin_rel R) (a b c : A) : decidable (R a b ∧ R b a ∨ R b b) :=
by tactic.apply_instance
end
|
1e0a09d591f8cd6dfc9eda146bc1e5e2318d409a | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/ring_theory/ideal/quotient.lean | 9eeff6d9cb963f241c9b9e50ec49a19ce3f6e2b2 | [
"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 | 15,513 | 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, Anne Baanen
-/
import linear_algebra.quotient
import ring_theory.ideal.basic
/-!
# Ideal quotients
This file defines ideal quotients as a special case of submodule quotients and proves some basic
results about these quotients.
See `algebra.ring_quot` for quotients of non-commutative rings.
## Main definitions
- `ideal.quotient`: the quotient of a commutative ring `R` by an ideal `I : ideal R`
## Main results
- `ideal.quotient_inf_ring_equiv_pi_quotient`: the **Chinese Remainder Theorem**
-/
universes u v w
namespace ideal
open set
open_locale big_operators
variables {R : Type u} [comm_ring R] (I : ideal R) {a b : R}
variables {S : Type v}
/-- The quotient `R/I` of a ring `R` by an ideal `I`.
The ideal quotient of `I` is defined to equal the quotient of `I` as an `R`-submodule of `R`.
This definition is marked `reducible` so that typeclass instances can be shared between
`ideal.quotient I` and `submodule.quotient I`.
-/
-- Note that at present `ideal` means a left-ideal,
-- so this quotient is only useful in a commutative ring.
-- We should develop quotients by two-sided ideals as well.
@[reducible]
instance : has_quotient R (ideal R) := submodule.has_quotient
namespace quotient
variables {I} {x y : R}
instance has_one (I : ideal R) : has_one (R ⧸ I) := ⟨submodule.quotient.mk 1⟩
instance has_mul (I : ideal R) : has_mul (R ⧸ I) :=
⟨λ a b, quotient.lift_on₂' a b (λ a b, submodule.quotient.mk (a * b)) $
λ a₁ a₂ b₁ b₂ h₁ h₂, quot.sound $ begin
have F := I.add_mem (I.mul_mem_left a₂ h₁) (I.mul_mem_right b₁ h₂),
have : a₁ * a₂ - b₁ * b₂ = a₂ * (a₁ - b₁) + (a₂ - b₂) * b₁,
{ rw [mul_sub, sub_mul, sub_add_sub_cancel, mul_comm, mul_comm b₁] },
rw ← this at F,
change _ ∈ _, convert F,
end⟩
instance comm_ring (I : ideal R) : comm_ring (R ⧸ I) :=
{ mul := (*),
one := 1,
mul_assoc := λ a b c, quotient.induction_on₃' a b c $
λ a b c, congr_arg submodule.quotient.mk (mul_assoc a b c),
mul_comm := λ a b, quotient.induction_on₂' a b $
λ a b, congr_arg submodule.quotient.mk (mul_comm a b),
one_mul := λ a, quotient.induction_on' a $
λ a, congr_arg submodule.quotient.mk (one_mul a),
mul_one := λ a, quotient.induction_on' a $
λ a, congr_arg submodule.quotient.mk (mul_one a),
left_distrib := λ a b c, quotient.induction_on₃' a b c $
λ a b c, congr_arg submodule.quotient.mk (left_distrib a b c),
right_distrib := λ a b c, quotient.induction_on₃' a b c $
λ a b c, congr_arg submodule.quotient.mk (right_distrib a b c),
..submodule.quotient.add_comm_group I }
/-- The ring homomorphism from a ring `R` to a quotient ring `R/I`. -/
def mk (I : ideal R) : R →+* (R ⧸ I) :=
⟨λ a, submodule.quotient.mk a, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩
/- Two `ring_homs`s from the quotient by an ideal are equal if their
compositions with `ideal.quotient.mk'` are equal.
See note [partially-applied ext lemmas]. -/
@[ext]
lemma ring_hom_ext [non_assoc_semiring S] ⦃f g : R ⧸ I →+* S⦄
(h : f.comp (mk I) = g.comp (mk I)) : f = g :=
ring_hom.ext $ λ x, quotient.induction_on' x $ (ring_hom.congr_fun h : _)
instance inhabited : inhabited (R ⧸ I) := ⟨mk I 37⟩
protected theorem eq : mk I x = mk I y ↔ x - y ∈ I := submodule.quotient.eq I
@[simp] theorem mk_eq_mk (x : R) : (submodule.quotient.mk x : R ⧸ I) = mk I x := rfl
lemma eq_zero_iff_mem {I : ideal R} : mk I a = 0 ↔ a ∈ I :=
by conv {to_rhs, rw ← sub_zero a }; exact quotient.eq'
theorem zero_eq_one_iff {I : ideal R} : (0 : R ⧸ I) = 1 ↔ I = ⊤ :=
eq_comm.trans $ eq_zero_iff_mem.trans (eq_top_iff_one _).symm
theorem zero_ne_one_iff {I : ideal R} : (0 : R ⧸ I) ≠ 1 ↔ I ≠ ⊤ :=
not_congr zero_eq_one_iff
protected theorem nontrivial {I : ideal R} (hI : I ≠ ⊤) : nontrivial (R ⧸ I) :=
⟨⟨0, 1, zero_ne_one_iff.2 hI⟩⟩
lemma mk_surjective : function.surjective (mk I) :=
λ y, quotient.induction_on' y (λ x, exists.intro x rfl)
/-- If `I` is an ideal of a commutative ring `R`, if `q : R → R/I` is the quotient map, and if
`s ⊆ R` is a subset, then `q⁻¹(q(s)) = ⋃ᵢ(i + s)`, the union running over all `i ∈ I`. -/
lemma quotient_ring_saturate (I : ideal R) (s : set R) :
mk I ⁻¹' (mk I '' s) = (⋃ x : I, (λ y, x.1 + y) '' s) :=
begin
ext x,
simp only [mem_preimage, mem_image, mem_Union, ideal.quotient.eq],
exact ⟨λ ⟨a, a_in, h⟩, ⟨⟨_, I.neg_mem h⟩, a, a_in, by simp⟩,
λ ⟨⟨i, hi⟩, a, ha, eq⟩,
⟨a, ha, by rw [← eq, sub_add_eq_sub_sub_swap, sub_self, zero_sub]; exact I.neg_mem hi⟩⟩
end
instance is_domain (I : ideal R) [hI : I.is_prime] : is_domain (R ⧸ I) :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ a b,
quotient.induction_on₂' a b $ λ a b hab,
(hI.mem_or_mem (eq_zero_iff_mem.1 hab)).elim
(or.inl ∘ eq_zero_iff_mem.2)
(or.inr ∘ eq_zero_iff_mem.2),
.. quotient.nontrivial hI.1 }
lemma is_domain_iff_prime (I : ideal R) : is_domain (R ⧸ I) ↔ I.is_prime :=
⟨ λ ⟨h1, h2⟩, ⟨zero_ne_one_iff.1 $ @zero_ne_one _ _ ⟨h2⟩, λ x y h,
by { simp only [←eq_zero_iff_mem, (mk I).map_mul] at ⊢ h, exact h1 h}⟩,
λ h, by { resetI, apply_instance }⟩
lemma exists_inv {I : ideal R} [hI : I.is_maximal] :
∀ {a : (R ⧸ I)}, a ≠ 0 → ∃ b : (R ⧸ I), a * b = 1 :=
begin
rintro ⟨a⟩ h,
rcases hI.exists_inv (mt eq_zero_iff_mem.2 h) with ⟨b, c, hc, abc⟩,
rw [mul_comm] at abc,
refine ⟨mk _ b, quot.sound _⟩, --quot.sound hb
rw ← eq_sub_iff_add_eq' at abc,
rw [abc, ← neg_mem_iff, neg_sub] at hc,
convert hc,
end
open_locale classical
/-- quotient by maximal ideal is a field. def rather than instance, since users will have
computable inverses in some applications.
See note [reducible non-instances]. -/
@[reducible]
protected noncomputable def field (I : ideal R) [hI : I.is_maximal] : field (R ⧸ I) :=
{ inv := λ a, if ha : a = 0 then 0 else classical.some (exists_inv ha),
mul_inv_cancel := λ a (ha : a ≠ 0), show a * dite _ _ _ = _,
by rw dif_neg ha;
exact classical.some_spec (exists_inv ha),
inv_zero := dif_pos rfl,
..quotient.comm_ring I,
..quotient.is_domain I }
/-- If the quotient by an ideal is a field, then the ideal is maximal. -/
theorem maximal_of_is_field (I : ideal R)
(hqf : is_field (R ⧸ I)) : I.is_maximal :=
begin
apply ideal.is_maximal_iff.2,
split,
{ intro h,
rcases hqf.exists_pair_ne with ⟨⟨x⟩, ⟨y⟩, hxy⟩,
exact hxy (ideal.quotient.eq.2 (mul_one (x - y) ▸ I.mul_mem_left _ h)) },
{ intros J x hIJ hxnI hxJ,
rcases hqf.mul_inv_cancel (mt ideal.quotient.eq_zero_iff_mem.1 hxnI) with ⟨⟨y⟩, hy⟩,
rw [← zero_add (1 : R), ← sub_self (x * y), sub_add],
refine J.sub_mem (J.mul_mem_right _ hxJ) (hIJ (ideal.quotient.eq.1 hy)) }
end
/-- The quotient of a ring by an ideal is a field iff the ideal is maximal. -/
theorem maximal_ideal_iff_is_field_quotient (I : ideal R) :
I.is_maximal ↔ is_field (R ⧸ I) :=
⟨λ h, @field.to_is_field (R ⧸ I) (@ideal.quotient.field _ _ I h),
λ h, maximal_of_is_field I h⟩
variable [comm_ring S]
/-- Given a ring homomorphism `f : R →+* S` sending all elements of an ideal to zero,
lift it to the quotient by this ideal. -/
def lift (I : ideal R) (f : R →+* S) (H : ∀ (a : R), a ∈ I → f a = 0) :
R ⧸ I →+* S :=
{ to_fun := λ x, quotient.lift_on' x f $ λ (a b) (h : _ ∈ _),
eq_of_sub_eq_zero $ by rw [← f.map_sub, H _ h],
map_one' := f.map_one,
map_zero' := f.map_zero,
map_add' := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ f.map_add,
map_mul' := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ f.map_mul }
@[simp] lemma lift_mk (I : ideal R) (f : R →+* S) (H : ∀ (a : R), a ∈ I → f a = 0) :
lift I f H (mk I a) = f a := rfl
/-- The ring homomorphism from the quotient by a smaller ideal to the quotient by a larger ideal.
This is the `ideal.quotient` version of `quot.factor` -/
def factor (S T : ideal R) (H : S ≤ T) : R ⧸ S →+* R ⧸ T :=
ideal.quotient.lift S (T^.quotient.mk) (λ x hx, eq_zero_iff_mem.2 (H hx))
@[simp] lemma factor_mk (S T : ideal R) (H : S ≤ T) (x : R) :
factor S T H (mk S x) = mk T x := rfl
@[simp] lemma factor_comp_mk (S T : ideal R) (H : S ≤ T) : (factor S T H).comp (mk S) = mk T :=
by { ext x, rw [ring_hom.comp_apply, factor_mk] }
end quotient
/-- Quotienting by equal ideals gives equivalent rings.
See also `submodule.quot_equiv_of_eq`.
-/
def quot_equiv_of_eq {R : Type*} [comm_ring R] {I J : ideal R} (h : I = J) :
(R ⧸ I) ≃+* R ⧸ J :=
{ map_mul' := by { rintro ⟨x⟩ ⟨y⟩, refl },
.. submodule.quot_equiv_of_eq I J h }
@[simp]
lemma quot_equiv_of_eq_mk {R : Type*} [comm_ring R] {I J : ideal R} (h : I = J) (x : R) :
quot_equiv_of_eq h (ideal.quotient.mk I x) = ideal.quotient.mk J x :=
rfl
section pi
variables (ι : Type v)
/-- `R^n/I^n` is a `R/I`-module. -/
instance module_pi : module (R ⧸ I) ((ι → R) ⧸ I.pi ι) :=
{ smul := λ c m, quotient.lift_on₂' c m (λ r m, submodule.quotient.mk $ r • m) begin
intros c₁ m₁ c₂ m₂ hc hm,
apply ideal.quotient.eq.2,
intro i,
exact I.mul_sub_mul_mem hc (hm i),
end,
one_smul := begin
rintro ⟨a⟩,
change ideal.quotient.mk _ _ = ideal.quotient.mk _ _,
congr' with i, exact one_mul (a i),
end,
mul_smul := begin
rintro ⟨a⟩ ⟨b⟩ ⟨c⟩,
change ideal.quotient.mk _ _ = ideal.quotient.mk _ _,
simp only [(•)],
congr' with i, exact mul_assoc a b (c i),
end,
smul_add := begin
rintro ⟨a⟩ ⟨b⟩ ⟨c⟩,
change ideal.quotient.mk _ _ = ideal.quotient.mk _ _,
congr' with i, exact mul_add a (b i) (c i),
end,
smul_zero := begin
rintro ⟨a⟩,
change ideal.quotient.mk _ _ = ideal.quotient.mk _ _,
congr' with i, exact mul_zero a,
end,
add_smul := begin
rintro ⟨a⟩ ⟨b⟩ ⟨c⟩,
change ideal.quotient.mk _ _ = ideal.quotient.mk _ _,
congr' with i, exact add_mul a b (c i),
end,
zero_smul := begin
rintro ⟨a⟩,
change ideal.quotient.mk _ _ = ideal.quotient.mk _ _,
congr' with i, exact zero_mul (a i),
end, }
/-- `R^n/I^n` is isomorphic to `(R/I)^n` as an `R/I`-module. -/
noncomputable def pi_quot_equiv : ((ι → R) ⧸ I.pi ι) ≃ₗ[(R ⧸ I)] (ι → (R ⧸ I)) :=
{ to_fun := λ x, quotient.lift_on' x (λ f i, ideal.quotient.mk I (f i)) $
λ a b hab, funext (λ i, ideal.quotient.eq.2 (hab i)),
map_add' := by { rintros ⟨_⟩ ⟨_⟩, refl },
map_smul' := by { rintros ⟨_⟩ ⟨_⟩, refl },
inv_fun := λ x, ideal.quotient.mk (I.pi ι) $ λ i, quotient.out' (x i),
left_inv :=
begin
rintro ⟨x⟩,
exact ideal.quotient.eq.2 (λ i, ideal.quotient.eq.1 (quotient.out_eq' _))
end,
right_inv :=
begin
intro x,
ext i,
obtain ⟨r, hr⟩ := @quot.exists_rep _ _ (x i),
simp_rw ←hr,
convert quotient.out_eq' _
end }
/-- If `f : R^n → R^m` is an `R`-linear map and `I ⊆ R` is an ideal, then the image of `I^n` is
contained in `I^m`. -/
lemma map_pi {ι} [fintype ι] {ι' : Type w} (x : ι → R) (hi : ∀ i, x i ∈ I)
(f : (ι → R) →ₗ[R] (ι' → R)) (i : ι') : f x i ∈ I :=
begin
rw pi_eq_sum_univ x,
simp only [finset.sum_apply, smul_eq_mul, linear_map.map_sum, pi.smul_apply, linear_map.map_smul],
exact I.sum_mem (λ j hj, I.mul_mem_right _ (hi j))
end
end pi
section chinese_remainder
variables {ι : Type v}
theorem exists_sub_one_mem_and_mem (s : finset ι) {f : ι → ideal R}
(hf : ∀ i ∈ s, ∀ j ∈ s, i ≠ j → f i ⊔ f j = ⊤) (i : ι) (his : i ∈ s) :
∃ r : R, r - 1 ∈ f i ∧ ∀ j ∈ s, j ≠ i → r ∈ f j :=
begin
have : ∀ j ∈ s, j ≠ i → ∃ r : R, ∃ H : r - 1 ∈ f i, r ∈ f j,
{ intros j hjs hji, specialize hf i his j hjs hji.symm,
rw [eq_top_iff_one, submodule.mem_sup] at hf,
rcases hf with ⟨r, hri, s, hsj, hrs⟩, refine ⟨1 - r, _, _⟩,
{ rw [sub_right_comm, sub_self, zero_sub], exact (f i).neg_mem hri },
{ rw [← hrs, add_sub_cancel'], exact hsj } },
classical,
have : ∃ g : ι → R, (∀ j, g j - 1 ∈ f i) ∧ ∀ j ∈ s, j ≠ i → g j ∈ f j,
{ choose g hg1 hg2,
refine ⟨λ j, if H : j ∈ s ∧ j ≠ i then g j H.1 H.2 else 1, λ j, _, λ j, _⟩,
{ split_ifs with h, { apply hg1 }, rw sub_self, exact (f i).zero_mem },
{ intros hjs hji, rw dif_pos, { apply hg2 }, exact ⟨hjs, hji⟩ } },
rcases this with ⟨g, hgi, hgj⟩, use (∏ x in s.erase i, g x), split,
{ rw [← quotient.eq, ring_hom.map_one, ring_hom.map_prod],
apply finset.prod_eq_one, intros, rw [← ring_hom.map_one, quotient.eq], apply hgi },
intros j hjs hji, rw [← quotient.eq_zero_iff_mem, ring_hom.map_prod],
refine finset.prod_eq_zero (finset.mem_erase_of_ne_of_mem hji hjs) _,
rw quotient.eq_zero_iff_mem, exact hgj j hjs hji
end
theorem exists_sub_mem [fintype ι] {f : ι → ideal R}
(hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) (g : ι → R) :
∃ r : R, ∀ i, r - g i ∈ f i :=
begin
have : ∃ φ : ι → R, (∀ i, φ i - 1 ∈ f i) ∧ (∀ i j, i ≠ j → φ i ∈ f j),
{ have := exists_sub_one_mem_and_mem (finset.univ : finset ι) (λ i _ j _ hij, hf i j hij),
choose φ hφ,
existsi λ i, φ i (finset.mem_univ i),
exact ⟨λ i, (hφ i _).1, λ i j hij, (hφ i _).2 j (finset.mem_univ j) hij.symm⟩ },
rcases this with ⟨φ, hφ1, hφ2⟩,
use ∑ i, g i * φ i,
intros i,
rw [← quotient.eq, ring_hom.map_sum],
refine eq.trans (finset.sum_eq_single i _ _) _,
{ intros j _ hji, rw quotient.eq_zero_iff_mem, exact (f i).mul_mem_left _ (hφ2 j i hji) },
{ intros hi, exact (hi $ finset.mem_univ i).elim },
specialize hφ1 i, rw [← quotient.eq, ring_hom.map_one] at hφ1,
rw [ring_hom.map_mul, hφ1, mul_one]
end
/-- The homomorphism from `R/(⋂ i, f i)` to `∏ i, (R / f i)` featured in the Chinese
Remainder Theorem. It is bijective if the ideals `f i` are comaximal. -/
def quotient_inf_to_pi_quotient (f : ι → ideal R) :
R ⧸ (⨅ i, f i) →+* Π i, R ⧸ f i :=
quotient.lift (⨅ i, f i)
(pi.ring_hom (λ i : ι, (quotient.mk (f i) : _))) $
λ r hr, begin
rw submodule.mem_infi at hr,
ext i,
exact quotient.eq_zero_iff_mem.2 (hr i)
end
theorem quotient_inf_to_pi_quotient_bijective [fintype ι] {f : ι → ideal R}
(hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) :
function.bijective (quotient_inf_to_pi_quotient f) :=
⟨λ x y, quotient.induction_on₂' x y $ λ r s hrs, quotient.eq.2 $
(submodule.mem_infi _).2 $ λ i, quotient.eq.1 $
show quotient_inf_to_pi_quotient f (quotient.mk' r) i = _, by rw hrs; refl,
λ g, let ⟨r, hr⟩ := exists_sub_mem hf (λ i, quotient.out' (g i)) in
⟨quotient.mk _ r, funext $ λ i, quotient.out_eq' (g i) ▸ quotient.eq.2 (hr i)⟩⟩
/-- Chinese Remainder Theorem. Eisenbud Ex.2.6. Similar to Atiyah-Macdonald 1.10 and Stacks 00DT -/
noncomputable def quotient_inf_ring_equiv_pi_quotient [fintype ι] (f : ι → ideal R)
(hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) :
R ⧸ (⨅ i, f i) ≃+* Π i, R ⧸ f i :=
{ .. equiv.of_bijective _ (quotient_inf_to_pi_quotient_bijective hf),
.. quotient_inf_to_pi_quotient f }
end chinese_remainder
end ideal
|
a603f330e2d0afcfd5ddcc5c6ad2a95e5995781b | 46125763b4dbf50619e8846a1371029346f4c3db | /src/category_theory/category/default.lean | 68e48fadaebeadc9ff7f4085488d456e26a5a6b5 | [
"Apache-2.0"
] | permissive | thjread/mathlib | a9d97612cedc2c3101060737233df15abcdb9eb1 | 7cffe2520a5518bba19227a107078d83fa725ddc | refs/heads/master | 1,615,637,696,376 | 1,583,953,063,000 | 1,583,953,063,000 | 246,680,271 | 0 | 0 | Apache-2.0 | 1,583,960,875,000 | 1,583,960,875,000 | null | UTF-8 | Lean | false | false | 7,208 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Stephen Morgan, Scott Morrison, Johannes Hölzl, Reid Barton
-/
import tactic.basic
import tactic.tidy
/-!
# Categories
Defines a category, as a type class parametrised by the type of objects.
## Notations
Introduces notations
* `X ⟶ Y` for the morphism spaces,
* `f ≫ g` for composition in the 'arrows' convention.
Users may like to add `f ⊚ g` for composition in the standard convention, using
```
local notation f ` ⊚ `:80 g:80 := category.comp g f -- type as \oo
```
-/
universes v u -- The order in this declaration matters: v often needs to be explicitly specified while u often can be omitted
namespace category_theory
/-
The propositional fields of `category` are annotated with the auto_param `obviously`,
which is defined here as a
[`replacer` tactic](https://github.com/leanprover/mathlib/blob/master/docs/tactics.md#def_replacer).
We then immediately set up `obviously` to call `tidy`. Later, this can be replaced with more
powerful tactics.
-/
def_replacer obviously
@[obviously] meta def obviously' := tactic.tidy
class has_hom (obj : Type u) : Type (max u (v+1)) :=
(hom : obj → obj → Type v)
infixr ` ⟶ `:10 := has_hom.hom -- type as \h
section prio
set_option default_priority 100 -- see Note [default priority]
class category_struct (obj : Type u)
extends has_hom.{v} obj : Type (max u (v+1)) :=
(id : Π X : obj, hom X X)
(comp : Π {X Y Z : obj}, (X ⟶ Y) → (Y ⟶ Z) → (X ⟶ Z))
notation `𝟙` := category_struct.id -- type as \b1
infixr ` ≫ `:80 := category_struct.comp -- type as \gg
/--
The typeclass `category C` describes morphisms associated to objects of type `C`.
The universe levels of the objects and morphisms are unconstrained, and will often need to be
specified explicitly, as `category.{v} C`. (See also `large_category` and `small_category`.)
-/
class category (obj : Type u)
extends category_struct.{v} obj : Type (max u (v+1)) :=
(id_comp' : ∀ {X Y : obj} (f : hom X Y), 𝟙 X ≫ f = f . obviously)
(comp_id' : ∀ {X Y : obj} (f : hom X Y), f ≫ 𝟙 Y = f . obviously)
(assoc' : ∀ {W X Y Z : obj} (f : hom W X) (g : hom X Y) (h : hom Y Z),
(f ≫ g) ≫ h = f ≫ (g ≫ h) . obviously)
end prio
-- `restate_axiom` is a command that creates a lemma from a structure field,
-- discarding any auto_param wrappers from the type.
-- (It removes a backtick from the name, if it finds one, and otherwise adds "_lemma".)
restate_axiom category.id_comp'
restate_axiom category.comp_id'
restate_axiom category.assoc'
attribute [simp] category.id_comp category.comp_id category.assoc
attribute [trans] category_struct.comp
/--
A `large_category` has objects in one universe level higher than the universe level of
the morphisms. It is useful for examples such as the category of types, or the category
of groups, etc.
-/
abbreviation large_category (C : Type (u+1)) : Type (u+1) := category.{u} C
/--
A `small_category` has objects and morphisms in the same universe level.
-/
abbreviation small_category (C : Type u) : Type (u+1) := category.{u} C
section
variables {C : Type u} [𝒞 : category.{v} C] {X Y Z : C}
include 𝒞
lemma eq_of_comp_left_eq {f g : X ⟶ Y} (w : ∀ {Z : C} (h : Y ⟶ Z), f ≫ h = g ≫ h) : f = g :=
by { convert w (𝟙 Y), tidy }
lemma eq_of_comp_right_eq {f g : Y ⟶ Z} (w : ∀ {X : C} (h : X ⟶ Y), h ≫ f = h ≫ g) : f = g :=
by { convert w (𝟙 Y), tidy }
lemma eq_of_comp_left_eq' (f g : X ⟶ Y) (w : (λ {Z : C} (h : Y ⟶ Z), f ≫ h) = (λ {Z : C} (h : Y ⟶ Z), g ≫ h)) : f = g :=
eq_of_comp_left_eq (λ Z h, by convert congr_fun (congr_fun w Z) h)
lemma eq_of_comp_right_eq' (f g : Y ⟶ Z) (w : (λ {X : C} (h : X ⟶ Y), h ≫ f) = (λ {X : C} (h : X ⟶ Y), h ≫ g)) : f = g :=
eq_of_comp_right_eq (λ X h, by convert congr_fun (congr_fun w X) h)
lemma id_of_comp_left_id (f : X ⟶ X) (w : ∀ {Y : C} (g : X ⟶ Y), f ≫ g = g) : f = 𝟙 X :=
by { convert w (𝟙 X), tidy }
lemma id_of_comp_right_id (f : X ⟶ X) (w : ∀ {Y : C} (g : Y ⟶ X), g ≫ f = g) : f = 𝟙 X :=
by { convert w (𝟙 X), tidy }
class epi (f : X ⟶ Y) : Prop :=
(left_cancellation : Π {Z : C} (g h : Y ⟶ Z) (w : f ≫ g = f ≫ h), g = h)
class mono (f : X ⟶ Y) : Prop :=
(right_cancellation : Π {Z : C} (g h : Z ⟶ X) (w : g ≫ f = h ≫ f), g = h)
instance (X : C) : epi.{v} (𝟙 X) :=
⟨λ Z g h w, by simpa using w⟩
instance (X : C) : mono.{v} (𝟙 X) :=
⟨λ Z g h w, by simpa using w⟩
lemma cancel_epi (f : X ⟶ Y) [epi f] {g h : Y ⟶ Z} : (f ≫ g = f ≫ h) ↔ g = h :=
⟨ λ p, epi.left_cancellation g h p, begin intro a, subst a end ⟩
lemma cancel_mono (f : X ⟶ Y) [mono f] {g h : Z ⟶ X} : (g ≫ f = h ≫ f) ↔ g = h :=
⟨ λ p, mono.right_cancellation g h p, begin intro a, subst a end ⟩
lemma cancel_epi_id (f : X ⟶ Y) [epi f] {h : Y ⟶ Y} : (f ≫ h = f) ↔ h = 𝟙 Y :=
by { convert cancel_epi f, simp, }
lemma cancel_mono_id (f : X ⟶ Y) [mono f] {g : X ⟶ X} : (g ≫ f = f) ↔ g = 𝟙 X :=
by { convert cancel_mono f, simp, }
instance epi_comp {X Y Z : C} (f : X ⟶ Y) [epi f] (g : Y ⟶ Z) [epi g] : epi (f ≫ g) :=
begin
split, intros Z a b w,
apply (cancel_epi g).1,
apply (cancel_epi f).1,
simpa using w,
end
instance mono_comp {X Y Z : C} (f : X ⟶ Y) [mono f] (g : Y ⟶ Z) [mono g] : mono (f ≫ g) :=
begin
split, intros Z a b w,
apply (cancel_mono f).1,
apply (cancel_mono g).1,
simpa using w,
end
lemma mono_of_mono {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [mono (f ≫ g)] : mono f :=
begin
split, intros Z a b w,
replace w := congr_arg (λ k, k ≫ g) w,
dsimp at w,
rw [category.assoc, category.assoc] at w,
exact (cancel_mono _).1 w,
end
lemma mono_of_mono_fac {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} {h : X ⟶ Z} [mono h] (w : f ≫ g = h) : mono f :=
by { resetI, subst h, exact mono_of_mono f g, }
lemma epi_of_epi {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [epi (f ≫ g)] : epi g :=
begin
split, intros Z a b w,
replace w := congr_arg (λ k, f ≫ k) w,
dsimp at w,
rw [←category.assoc, ←category.assoc] at w,
exact (cancel_epi _).1 w,
end
lemma epi_of_epi_fac {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} {h : X ⟶ Z} [epi h] (w : f ≫ g = h) : epi g :=
by { resetI, subst h, exact epi_of_epi f g, }
end
section
variable (C : Type u)
variable [category.{v} C]
universe u'
instance ulift_category : category.{v} (ulift.{u'} C) :=
{ hom := λ X Y, (X.down ⟶ Y.down),
id := λ X, 𝟙 X.down,
comp := λ _ _ _ f g, f ≫ g }
-- We verify that this previous instance can lift small categories to large categories.
example (D : Type u) [small_category D] : large_category (ulift.{u+1} D) := by apply_instance
end
end category_theory
open category_theory
namespace preorder
variables (α : Type u)
@[priority 100] -- see Note [lower instance priority]
instance small_category [preorder α] : small_category α :=
{ hom := λ U V, ulift (plift (U ≤ V)),
id := λ X, ⟨ ⟨ le_refl X ⟩ ⟩,
comp := λ X Y Z f g, ⟨ ⟨ le_trans _ _ _ f.down.down g.down.down ⟩ ⟩ }
end preorder
|
481605d7207e9d2d07464a9b66d84a20c793e118 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /library/data/rat/default.lean | a9cb20ed7c0ee6a138b87d92031ed63eb4313c4a | [
"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 | 180 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad
-/
import .basic .order
|
4bd87340ef4c2a624a7fe2232d0c3d8f782cc98c | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/ring_theory/hahn_series.lean | bfe54278a2a602412a24309bcc2b1ab8580dccf4 | [
"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 | 56,874 | lean | /-
Copyright (c) 2021 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import order.well_founded_set
import algebra.big_operators.finprod
import ring_theory.valuation.basic
import algebra.module.pi
import ring_theory.power_series.basic
/-!
# Hahn Series
If `Γ` is ordered and `R` has zero, then `hahn_series Γ R` consists of formal series over `Γ` with
coefficients in `R`, whose supports are partially well-ordered. With further structure on `R` and
`Γ`, we can add further structure on `hahn_series Γ R`, with the most studied case being when `Γ` is
a linearly ordered abelian group and `R` is a field, in which case `hahn_series Γ R` is a
valued field, with value group `Γ`.
These generalize Laurent series (with value group `ℤ`), and Laurent series are implemented that way
in the file `ring_theory/laurent_series`.
## Main Definitions
* If `Γ` is ordered and `R` has zero, then `hahn_series Γ R` consists of
formal series over `Γ` with coefficients in `R`, whose supports are partially well-ordered.
* If `R` is a (commutative) additive monoid or group, then so is `hahn_series Γ R`.
* If `R` is a (comm_)(semi)ring, then so is `hahn_series Γ R`.
* `hahn_series.add_val Γ R` defines an `add_valuation` on `hahn_series Γ R` when `Γ` is linearly
ordered.
* A `hahn_series.summable_family` is a family of Hahn series such that the union of their supports
is well-founded and only finitely many are nonzero at any given coefficient. They have a formal
sum, `hahn_series.summable_family.hsum`, which can be bundled as a `linear_map` as
`hahn_series.summable_family.lsum`. Note that this is different from `summable` in the valuation
topology, because there are topologically summable families that do not satisfy the axioms of
`hahn_series.summable_family`, and formally summable families whose sums do not converge
topologically.
* Laurent series over `R` are implemented as `hahn_series ℤ R` in the file
`ring_theory/laurent_series`.
## TODO
* Build an API for the variable `X` (defined to be `single 1 1 : hahn_series Γ R`) in analogy to
`X : polynomial R` and `X : power_series R`
## References
- [J. van der Hoeven, *Operators on Generalized Power Series*][van_der_hoeven]
-/
open finset
open_locale big_operators classical pointwise
noncomputable theory
/-- If `Γ` is linearly ordered and `R` has zero, then `hahn_series Γ R` consists of
formal series over `Γ` with coefficients in `R`, whose supports are well-founded. -/
@[ext]
structure hahn_series (Γ : Type*) (R : Type*) [partial_order Γ] [has_zero R] :=
(coeff : Γ → R)
(is_pwo_support' : (function.support coeff).is_pwo)
variables {Γ : Type*} {R : Type*}
namespace hahn_series
section zero
variables [partial_order Γ] [has_zero R]
/-- The support of a Hahn series is just the set of indices whose coefficients are nonzero.
Notably, it is well-founded. -/
def support (x : hahn_series Γ R) : set Γ := function.support x.coeff
@[simp]
lemma is_pwo_support (x : hahn_series Γ R) : x.support.is_pwo := x.is_pwo_support'
@[simp]
lemma is_wf_support (x : hahn_series Γ R) : x.support.is_wf := x.is_pwo_support.is_wf
@[simp]
lemma mem_support (x : hahn_series Γ R) (a : Γ) : a ∈ x.support ↔ x.coeff a ≠ 0 := iff.refl _
instance : has_zero (hahn_series Γ R) :=
⟨{ coeff := 0,
is_pwo_support' := by simp }⟩
instance : inhabited (hahn_series Γ R) := ⟨0⟩
instance [subsingleton R] : subsingleton (hahn_series Γ R) :=
⟨λ a b, a.ext b (subsingleton.elim _ _)⟩
@[simp]
lemma zero_coeff {a : Γ} : (0 : hahn_series Γ R).coeff a = 0 := rfl
lemma ne_zero_of_coeff_ne_zero {x : hahn_series Γ R} {g : Γ} (h : x.coeff g ≠ 0) :
x ≠ 0 :=
mt (λ x0, (x0.symm ▸ zero_coeff : x.coeff g = 0)) h
@[simp]
lemma support_zero : support (0 : hahn_series Γ R) = ∅ := function.support_zero
@[simp]
lemma support_nonempty_iff {x : hahn_series Γ R} :
x.support.nonempty ↔ x ≠ 0 :=
begin
split,
{ rintro ⟨a, ha⟩ rfl,
apply ha zero_coeff },
{ contrapose!,
rw set.not_nonempty_iff_eq_empty,
intro h,
ext a,
have ha := set.not_mem_empty a,
rw [← h, mem_support, not_not] at ha,
rw [ha, zero_coeff] }
end
/-- `single a r` is the Hahn series which has coefficient `r` at `a` and zero otherwise. -/
def single (a : Γ) : zero_hom R (hahn_series Γ R) :=
{ to_fun := λ r, { coeff := pi.single a r,
is_pwo_support' := (set.is_pwo_singleton a).mono pi.support_single_subset },
map_zero' := ext _ _ (pi.single_zero _) }
variables {a b : Γ} {r : R}
@[simp]
theorem single_coeff_same (a : Γ) (r : R) : (single a r).coeff a = r := pi.single_eq_same a r
@[simp]
theorem single_coeff_of_ne (h : b ≠ a) : (single a r).coeff b = 0 := pi.single_eq_of_ne h r
theorem single_coeff : (single a r).coeff b = if (b = a) then r else 0 :=
by { split_ifs with h; simp [h] }
@[simp]
lemma support_single_of_ne (h : r ≠ 0) : support (single a r) = {a} :=
pi.support_single_of_ne h
lemma support_single_subset : support (single a r) ⊆ {a} :=
pi.support_single_subset
lemma eq_of_mem_support_single {b : Γ} (h : b ∈ support (single a r)) : b = a :=
support_single_subset h
@[simp]
lemma single_eq_zero : (single a (0 : R)) = 0 := (single a).map_zero
lemma single_injective (a : Γ) : function.injective (single a : R → hahn_series Γ R) :=
λ r s rs, by rw [← single_coeff_same a r, ← single_coeff_same a s, rs]
lemma single_ne_zero (h : r ≠ 0) : single a r ≠ 0 :=
λ con, h (single_injective a (con.trans single_eq_zero.symm))
instance [nonempty Γ] [nontrivial R] : nontrivial (hahn_series Γ R) :=
⟨begin
obtain ⟨r, s, rs⟩ := exists_pair_ne R,
inhabit Γ,
refine ⟨single (arbitrary Γ) r, single (arbitrary Γ) s, λ con, rs _⟩,
rw [← single_coeff_same (arbitrary Γ) r, con, single_coeff_same],
end⟩
section order
variable [has_zero Γ]
/-- The order of a nonzero Hahn series `x` is a minimal element of `Γ` where `x` has a
nonzero coefficient, the order of 0 is 0. -/
def order (x : hahn_series Γ R) : Γ :=
if h : x = 0 then 0 else x.is_wf_support.min (support_nonempty_iff.2 h)
@[simp]
lemma order_zero : order (0 : hahn_series Γ R) = 0 := dif_pos rfl
lemma order_of_ne {x : hahn_series Γ R} (hx : x ≠ 0) :
order x = x.is_wf_support.min (support_nonempty_iff.2 hx) := dif_neg hx
lemma coeff_order_ne_zero {x : hahn_series Γ R} (hx : x ≠ 0) :
x.coeff x.order ≠ 0 :=
begin
rw order_of_ne hx,
exact x.is_wf_support.min_mem (support_nonempty_iff.2 hx)
end
lemma order_le_of_coeff_ne_zero {Γ} [linear_ordered_cancel_add_comm_monoid Γ]
{x : hahn_series Γ R} {g : Γ} (h : x.coeff g ≠ 0) :
x.order ≤ g :=
le_trans (le_of_eq (order_of_ne (ne_zero_of_coeff_ne_zero h)))
(set.is_wf.min_le _ _ ((mem_support _ _).2 h))
@[simp]
lemma order_single (h : r ≠ 0) : (single a r).order = a :=
(order_of_ne (single_ne_zero h)).trans (support_single_subset ((single a r).is_wf_support.min_mem
(support_nonempty_iff.2 (single_ne_zero h))))
end order
section domain
variables {Γ' : Type*} [partial_order Γ']
/-- Extends the domain of a `hahn_series` by an `order_embedding`. -/
def emb_domain (f : Γ ↪o Γ') : hahn_series Γ R → hahn_series Γ' R :=
λ x, { coeff := λ (b : Γ'),
if h : b ∈ f '' x.support then x.coeff (classical.some h) else 0,
is_pwo_support' := (x.is_pwo_support.image_of_monotone f.monotone).mono (λ b hb, begin
contrapose! hb,
rw [function.mem_support, dif_neg hb, not_not],
end) }
@[simp]
lemma emb_domain_coeff {f : Γ ↪o Γ'} {x : hahn_series Γ R} {a : Γ} :
(emb_domain f x).coeff (f a) = x.coeff a :=
begin
rw emb_domain,
dsimp only,
by_cases ha : a ∈ x.support,
{ rw dif_pos (set.mem_image_of_mem f ha),
exact congr rfl (f.injective (classical.some_spec (set.mem_image_of_mem f ha)).2) },
{ rw [dif_neg, not_not.1 (λ c, ha ((mem_support _ _).2 c))],
contrapose! ha,
obtain ⟨b, hb1, hb2⟩ := (set.mem_image _ _ _).1 ha,
rwa f.injective hb2 at hb1 }
end
@[simp]
lemma emb_domain_mk_coeff {f : Γ → Γ'}
(hfi : function.injective f) (hf : ∀ g g' : Γ, f g ≤ f g' ↔ g ≤ g')
{x : hahn_series Γ R} {a : Γ} :
(emb_domain ⟨⟨f, hfi⟩, hf⟩ x).coeff (f a) = x.coeff a :=
emb_domain_coeff
lemma emb_domain_notin_image_support {f : Γ ↪o Γ'} {x : hahn_series Γ R} {b : Γ'}
(hb : b ∉ f '' x.support) : (emb_domain f x).coeff b = 0 :=
dif_neg hb
lemma support_emb_domain_subset {f : Γ ↪o Γ'} {x : hahn_series Γ R} :
support (emb_domain f x) ⊆ f '' x.support :=
begin
intros g hg,
contrapose! hg,
rw [mem_support, emb_domain_notin_image_support hg, not_not],
end
lemma emb_domain_notin_range {f : Γ ↪o Γ'} {x : hahn_series Γ R} {b : Γ'}
(hb : b ∉ set.range f) : (emb_domain f x).coeff b = 0 :=
emb_domain_notin_image_support (λ con, hb (set.image_subset_range _ _ con))
@[simp]
lemma emb_domain_zero {f : Γ ↪o Γ'} : emb_domain f (0 : hahn_series Γ R) = 0 :=
by { ext, simp [emb_domain_notin_image_support] }
@[simp]
lemma emb_domain_single {f : Γ ↪o Γ'} {g : Γ} {r : R} :
emb_domain f (single g r) = single (f g) r :=
begin
ext g',
by_cases h : g' = f g,
{ simp [h] },
rw [emb_domain_notin_image_support, single_coeff_of_ne h],
by_cases hr : r = 0,
{ simp [hr] },
rwa [support_single_of_ne hr, set.image_singleton, set.mem_singleton_iff],
end
lemma emb_domain_injective {f : Γ ↪o Γ'} :
function.injective (emb_domain f : hahn_series Γ R → hahn_series Γ' R) :=
λ x y xy, begin
ext g,
rw [ext_iff, function.funext_iff] at xy,
have xyg := xy (f g),
rwa [emb_domain_coeff, emb_domain_coeff] at xyg,
end
end domain
end zero
section addition
variable [partial_order Γ]
section add_monoid
variable [add_monoid R]
instance : has_add (hahn_series Γ R) :=
{ add := λ x y, { coeff := x.coeff + y.coeff,
is_pwo_support' := (x.is_pwo_support.union y.is_pwo_support).mono
(function.support_add _ _) } }
instance : add_monoid (hahn_series Γ R) :=
{ zero := 0,
add := (+),
add_assoc := λ x y z, by { ext, apply add_assoc },
zero_add := λ x, by { ext, apply zero_add },
add_zero := λ x, by { ext, apply add_zero } }
@[simp]
lemma add_coeff' {x y : hahn_series Γ R} :
(x + y).coeff = x.coeff + y.coeff := rfl
lemma add_coeff {x y : hahn_series Γ R} {a : Γ} :
(x + y).coeff a = x.coeff a + y.coeff a := rfl
lemma support_add_subset {x y : hahn_series Γ R} :
support (x + y) ⊆ support x ∪ support y :=
λ a ha, begin
rw [mem_support, add_coeff] at ha,
rw [set.mem_union, mem_support, mem_support],
contrapose! ha,
rw [ha.1, ha.2, add_zero],
end
lemma min_order_le_order_add {Γ} [linear_ordered_cancel_add_comm_monoid Γ] {x y : hahn_series Γ R}
(hx : x ≠ 0) (hy : y ≠ 0) (hxy : x + y ≠ 0) :
min x.order y.order ≤ (x + y).order :=
begin
rw [order_of_ne hx, order_of_ne hy, order_of_ne hxy],
refine le_trans _ (set.is_wf.min_le_min_of_subset support_add_subset),
{ exact x.is_wf_support.union y.is_wf_support },
{ exact set.nonempty.mono (set.subset_union_left _ _) (support_nonempty_iff.2 hx) },
rw set.is_wf.min_union,
end
/-- `single` as an additive monoid/group homomorphism -/
@[simps] def single.add_monoid_hom (a : Γ) : R →+ (hahn_series Γ R) :=
{ map_add' := λ x y, by { ext b, by_cases h : b = a; simp [h] },
..single a }
/-- `coeff g` as an additive monoid/group homomorphism -/
@[simps] def coeff.add_monoid_hom (g : Γ) : (hahn_series Γ R) →+ R :=
{ to_fun := λ f, f.coeff g,
map_zero' := zero_coeff,
map_add' := λ x y, add_coeff }
section domain
variables {Γ' : Type*} [partial_order Γ']
lemma emb_domain_add (f : Γ ↪o Γ') (x y : hahn_series Γ R) :
emb_domain f (x + y) = emb_domain f x + emb_domain f y :=
begin
ext g,
by_cases hg : g ∈ set.range f,
{ obtain ⟨a, rfl⟩ := hg,
simp },
{ simp [emb_domain_notin_range, hg] }
end
end domain
end add_monoid
instance [add_comm_monoid R] : add_comm_monoid (hahn_series Γ R) :=
{ add_comm := λ x y, by { ext, apply add_comm }
.. hahn_series.add_monoid }
section add_group
variable [add_group R]
instance : add_group (hahn_series Γ R) :=
{ neg := λ x, { coeff := λ a, - x.coeff a,
is_pwo_support' := by { rw function.support_neg,
exact x.is_pwo_support }, },
add_left_neg := λ x, by { ext, apply add_left_neg },
.. hahn_series.add_monoid }
@[simp]
lemma neg_coeff' {x : hahn_series Γ R} : (- x).coeff = - x.coeff := rfl
lemma neg_coeff {x : hahn_series Γ R} {a : Γ} : (- x).coeff a = - x.coeff a := rfl
@[simp]
lemma support_neg {x : hahn_series Γ R} : (- x).support = x.support :=
by { ext, simp }
@[simp]
lemma sub_coeff' {x y : hahn_series Γ R} :
(x - y).coeff = x.coeff - y.coeff := by { ext, simp [sub_eq_add_neg] }
lemma sub_coeff {x y : hahn_series Γ R} {a : Γ} :
(x - y).coeff a = x.coeff a - y.coeff a := by simp
end add_group
instance [add_comm_group R] : add_comm_group (hahn_series Γ R) :=
{ .. hahn_series.add_comm_monoid,
.. hahn_series.add_group }
end addition
section distrib_mul_action
variables [partial_order Γ] {V : Type*} [monoid R] [add_monoid V] [distrib_mul_action R V]
instance : has_scalar R (hahn_series Γ V) :=
⟨λ r x, { coeff := r • x.coeff,
is_pwo_support' := x.is_pwo_support.mono (function.support_smul_subset_right r x.coeff) }⟩
@[simp]
lemma smul_coeff {r : R} {x : hahn_series Γ V} {a : Γ} : (r • x).coeff a = r • (x.coeff a) := rfl
instance : distrib_mul_action R (hahn_series Γ V) :=
{ smul := (•),
one_smul := λ _, by { ext, simp },
smul_zero := λ _, by { ext, simp },
smul_add := λ _ _ _, by { ext, simp [smul_add] },
mul_smul := λ _ _ _, by { ext, simp [mul_smul] } }
variables {S : Type*} [monoid S] [distrib_mul_action S V]
instance [has_scalar R S] [is_scalar_tower R S V] :
is_scalar_tower R S (hahn_series Γ V) :=
⟨λ r s a, by { ext, simp }⟩
instance [smul_comm_class R S V] :
smul_comm_class R S (hahn_series Γ V) :=
⟨λ r s a, by { ext, simp [smul_comm] }⟩
end distrib_mul_action
section module
variables [partial_order Γ] [semiring R] {V : Type*} [add_comm_monoid V] [module R V]
instance : module R (hahn_series Γ V) :=
{ zero_smul := λ _, by { ext, simp },
add_smul := λ _ _ _, by { ext, simp [add_smul] },
.. hahn_series.distrib_mul_action }
/-- `single` as a linear map -/
@[simps] def single.linear_map (a : Γ) : R →ₗ[R] (hahn_series Γ R) :=
{ map_smul' := λ r s, by { ext b, by_cases h : b = a; simp [h] },
..single.add_monoid_hom a }
/-- `coeff g` as a linear map -/
@[simps] def coeff.linear_map (g : Γ) : (hahn_series Γ R) →ₗ[R] R :=
{ map_smul' := λ r s, rfl,
..coeff.add_monoid_hom g }
section domain
variables {Γ' : Type*} [partial_order Γ']
lemma emb_domain_smul (f : Γ ↪o Γ') (r : R) (x : hahn_series Γ R) :
emb_domain f (r • x) = r • emb_domain f x :=
begin
ext g,
by_cases hg : g ∈ set.range f,
{ obtain ⟨a, rfl⟩ := hg,
simp },
{ simp [emb_domain_notin_range, hg] }
end
/-- Extending the domain of Hahn series is a linear map. -/
@[simps] def emb_domain_linear_map (f : Γ ↪o Γ') : hahn_series Γ R →ₗ[R] hahn_series Γ' R :=
{ to_fun := emb_domain f, map_add' := emb_domain_add f, map_smul' := emb_domain_smul f }
end domain
end module
section multiplication
variable [ordered_cancel_add_comm_monoid Γ]
instance [has_zero R] [has_one R] : has_one (hahn_series Γ R) :=
⟨single 0 1⟩
@[simp]
lemma one_coeff [has_zero R] [has_one R] {a : Γ} :
(1 : hahn_series Γ R).coeff a = if a = 0 then 1 else 0 := single_coeff
@[simp]
lemma single_zero_one [has_zero R] [has_one R] : (single 0 (1 : R)) = 1 := rfl
@[simp]
lemma support_one [mul_zero_one_class R] [nontrivial R] :
support (1 : hahn_series Γ R) = {0} :=
support_single_of_ne one_ne_zero
@[simp]
lemma order_one [mul_zero_one_class R] :
order (1 : hahn_series Γ R) = 0 :=
begin
cases subsingleton_or_nontrivial R with h h; haveI := h,
{ rw [subsingleton.elim (1 : hahn_series Γ R) 0, order_zero] },
{ exact order_single one_ne_zero }
end
instance [non_unital_non_assoc_semiring R] : has_mul (hahn_series Γ R) :=
{ mul := λ x y, { coeff := λ a,
∑ ij in (add_antidiagonal x.is_pwo_support y.is_pwo_support a),
x.coeff ij.fst * y.coeff ij.snd,
is_pwo_support' := begin
have h : {a : Γ | ∑ (ij : Γ × Γ) in add_antidiagonal x.is_pwo_support
y.is_pwo_support a, x.coeff ij.fst * y.coeff ij.snd ≠ 0} ⊆
{a : Γ | (add_antidiagonal x.is_pwo_support y.is_pwo_support a).nonempty},
{ intros a ha,
contrapose! ha,
simp [not_nonempty_iff_eq_empty.1 ha] },
exact is_pwo_support_add_antidiagonal.mono h,
end, }, }
@[simp]
lemma mul_coeff [non_unital_non_assoc_semiring R] {x y : hahn_series Γ R} {a : Γ} :
(x * y).coeff a = ∑ ij in (add_antidiagonal x.is_pwo_support y.is_pwo_support a),
x.coeff ij.fst * y.coeff ij.snd := rfl
lemma mul_coeff_right' [non_unital_non_assoc_semiring R] {x y : hahn_series Γ R} {a : Γ} {s : set Γ}
(hs : s.is_pwo) (hys : y.support ⊆ s) :
(x * y).coeff a = ∑ ij in (add_antidiagonal x.is_pwo_support hs a),
x.coeff ij.fst * y.coeff ij.snd :=
begin
rw mul_coeff,
apply sum_subset_zero_on_sdiff (add_antidiagonal_mono_right hys) _ (λ _ _, rfl),
intros b hb,
simp only [not_and, not_not, mem_sdiff, mem_add_antidiagonal,
ne.def, set.mem_set_of_eq, mem_support] at hb,
rw [(hb.2 hb.1.1 hb.1.2.1), mul_zero]
end
lemma mul_coeff_left' [non_unital_non_assoc_semiring R] {x y : hahn_series Γ R} {a : Γ} {s : set Γ}
(hs : s.is_pwo) (hxs : x.support ⊆ s) :
(x * y).coeff a = ∑ ij in (add_antidiagonal hs y.is_pwo_support a),
x.coeff ij.fst * y.coeff ij.snd :=
begin
rw mul_coeff,
apply sum_subset_zero_on_sdiff (add_antidiagonal_mono_left hxs) _ (λ _ _, rfl),
intros b hb,
simp only [not_and, not_not, mem_sdiff, mem_add_antidiagonal,
ne.def, set.mem_set_of_eq, mem_support] at hb,
rw [not_not.1 (λ con, hb.1.2.2 (hb.2 hb.1.1 con)), zero_mul],
end
instance [non_unital_non_assoc_semiring R] : distrib (hahn_series Γ R) :=
{ left_distrib := λ x y z, begin
ext a,
have hwf := (y.is_pwo_support.union z.is_pwo_support),
rw [mul_coeff_right' hwf, add_coeff, mul_coeff_right' hwf (set.subset_union_right _ _),
mul_coeff_right' hwf (set.subset_union_left _ _)],
{ simp only [add_coeff, mul_add, sum_add_distrib] },
{ intro b,
simp only [add_coeff, ne.def, set.mem_union_eq, set.mem_set_of_eq, mem_support],
contrapose!,
intro h,
rw [h.1, h.2, add_zero], }
end,
right_distrib := λ x y z, begin
ext a,
have hwf := (x.is_pwo_support.union y.is_pwo_support),
rw [mul_coeff_left' hwf, add_coeff, mul_coeff_left' hwf (set.subset_union_right _ _),
mul_coeff_left' hwf (set.subset_union_left _ _)],
{ simp only [add_coeff, add_mul, sum_add_distrib] },
{ intro b,
simp only [add_coeff, ne.def, set.mem_union_eq, set.mem_set_of_eq, mem_support],
contrapose!,
intro h,
rw [h.1, h.2, add_zero], },
end,
.. hahn_series.has_mul,
.. hahn_series.has_add }
lemma single_mul_coeff_add [non_unital_non_assoc_semiring R] {r : R} {x : hahn_series Γ R} {a : Γ}
{b : Γ} :
((single b r) * x).coeff (a + b) = r * x.coeff a :=
begin
by_cases hr : r = 0,
{ simp [hr] },
simp only [hr, smul_coeff, mul_coeff, support_single_of_ne, ne.def, not_false_iff, smul_eq_mul],
by_cases hx : x.coeff a = 0,
{ simp only [hx, mul_zero],
rw [sum_congr _ (λ _ _, rfl), sum_empty],
ext ⟨a1, a2⟩,
simp only [not_mem_empty, not_and, set.mem_singleton_iff, not_not,
mem_add_antidiagonal, set.mem_set_of_eq, iff_false],
rintro h1 rfl h2,
rw add_comm at h1,
rw ← add_right_cancel h1 at hx,
exact h2 hx, },
transitivity ∑ (ij : Γ × Γ) in {(b, a)}, (single b r).coeff ij.fst * x.coeff ij.snd,
{ apply sum_congr _ (λ _ _, rfl),
ext ⟨a1, a2⟩,
simp only [set.mem_singleton_iff, prod.mk.inj_iff, mem_add_antidiagonal,
mem_singleton, set.mem_set_of_eq],
split,
{ rintro ⟨h1, rfl, h2⟩,
rw add_comm at h1,
refine ⟨rfl, add_right_cancel h1⟩ },
{ rintro ⟨rfl, rfl⟩,
refine ⟨add_comm _ _, _⟩,
simp [hx] } },
{ simp }
end
lemma mul_single_coeff_add [non_unital_non_assoc_semiring R] {r : R} {x : hahn_series Γ R} {a : Γ}
{b : Γ} :
(x * (single b r)).coeff (a + b) = x.coeff a * r :=
begin
by_cases hr : r = 0,
{ simp [hr] },
simp only [hr, smul_coeff, mul_coeff, support_single_of_ne, ne.def, not_false_iff, smul_eq_mul],
by_cases hx : x.coeff a = 0,
{ simp only [hx, zero_mul],
rw [sum_congr _ (λ _ _, rfl), sum_empty],
ext ⟨a1, a2⟩,
simp only [not_mem_empty, not_and, set.mem_singleton_iff, not_not,
mem_add_antidiagonal, set.mem_set_of_eq, iff_false],
rintro h1 h2 rfl,
rw ← add_right_cancel h1 at hx,
exact h2 hx, },
transitivity ∑ (ij : Γ × Γ) in {(a,b)}, x.coeff ij.fst * (single b r).coeff ij.snd,
{ apply sum_congr _ (λ _ _, rfl),
ext ⟨a1, a2⟩,
simp only [set.mem_singleton_iff, prod.mk.inj_iff, mem_add_antidiagonal,
mem_singleton, set.mem_set_of_eq],
split,
{ rintro ⟨h1, h2, rfl⟩,
refine ⟨add_right_cancel h1, rfl⟩ },
{ rintro ⟨rfl, rfl⟩,
simp [hx] } },
{ simp }
end
@[simp]
lemma mul_single_zero_coeff [non_unital_non_assoc_semiring R] {r : R} {x : hahn_series Γ R}
{a : Γ} :
(x * (single 0 r)).coeff a = x.coeff a * r :=
by rw [← add_zero a, mul_single_coeff_add, add_zero]
lemma single_zero_mul_coeff [non_unital_non_assoc_semiring R] {r : R} {x : hahn_series Γ R}
{a : Γ} :
((single 0 r) * x).coeff a = r * x.coeff a :=
by rw [← add_zero a, single_mul_coeff_add, add_zero]
@[simp]
lemma single_zero_mul_eq_smul [semiring R] {r : R} {x : hahn_series Γ R} :
(single 0 r) * x = r • x :=
by { ext, exact single_zero_mul_coeff }
theorem support_mul_subset_add_support [non_unital_non_assoc_semiring R] {x y : hahn_series Γ R} :
support (x * y) ⊆ support x + support y :=
begin
apply set.subset.trans (λ x hx, _) support_add_antidiagonal_subset_add,
{ exact x.is_pwo_support },
{ exact y.is_pwo_support },
contrapose! hx,
simp only [not_nonempty_iff_eq_empty, ne.def, set.mem_set_of_eq] at hx,
simp [hx],
end
lemma mul_coeff_order_add_order {Γ} [linear_ordered_cancel_add_comm_monoid Γ]
[non_unital_non_assoc_semiring R]
{x y : hahn_series Γ R} (hx : x ≠ 0) (hy : y ≠ 0) :
(x * y).coeff (x.order + y.order) = x.coeff x.order * y.coeff y.order :=
by rw [order_of_ne hx, order_of_ne hy, mul_coeff, finset.add_antidiagonal_min_add_min,
finset.sum_singleton]
private lemma mul_assoc' [non_unital_semiring R] (x y z : hahn_series Γ R) :
x * y * z = x * (y * z) :=
begin
ext b,
rw [mul_coeff_left' (x.is_pwo_support.add y.is_pwo_support) support_mul_subset_add_support,
mul_coeff_right' (y.is_pwo_support.add z.is_pwo_support) support_mul_subset_add_support],
simp only [mul_coeff, add_coeff, sum_mul, mul_sum, sum_sigma'],
refine sum_bij_ne_zero (λ a has ha0, ⟨⟨a.2.1, a.2.2 + a.1.2⟩, ⟨a.2.2, a.1.2⟩⟩) _ _ _ _,
{ rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H1 H2,
simp only [true_and, set.image2_add, eq_self_iff_true, mem_add_antidiagonal, ne.def,
set.image_prod, mem_sigma, set.mem_set_of_eq] at H1 H2 ⊢,
obtain ⟨⟨rfl, ⟨H3, nz⟩⟩, ⟨rfl, nx, ny⟩⟩ := H1,
refine ⟨⟨(add_assoc _ _ _).symm, nx, set.add_mem_add ny nz⟩, ny, nz⟩ },
{ rintros ⟨⟨i1,j1⟩, ⟨k1,l1⟩⟩ ⟨⟨i2,j2⟩, ⟨k2,l2⟩⟩ H1 H2 H3 H4 H5,
simp only [set.image2_add, prod.mk.inj_iff, mem_add_antidiagonal, ne.def,
set.image_prod, mem_sigma, set.mem_set_of_eq, heq_iff_eq] at H1 H3 H5,
obtain ⟨⟨rfl, H⟩, rfl, rfl⟩ := H5,
simp only [and_true, prod.mk.inj_iff, eq_self_iff_true, heq_iff_eq],
exact add_right_cancel (H1.1.1.trans H3.1.1.symm) },
{ rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H1 H2,
simp only [exists_prop, set.image2_add, prod.mk.inj_iff, mem_add_antidiagonal,
sigma.exists, ne.def, set.image_prod, mem_sigma, set.mem_set_of_eq, heq_iff_eq,
prod.exists] at H1 H2 ⊢,
obtain ⟨⟨rfl, nx, H⟩, rfl, ny, nz⟩ := H1,
exact ⟨i + k, l, i, k, ⟨⟨add_assoc _ _ _, set.add_mem_add nx ny, nz⟩, rfl, nx, ny⟩,
λ con, H2 ((mul_assoc _ _ _).symm.trans con), ⟨rfl, rfl⟩, rfl, rfl⟩ },
{ rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H1 H2,
simp [mul_assoc], }
end
instance [non_unital_non_assoc_semiring R] : non_unital_non_assoc_semiring (hahn_series Γ R) :=
{ zero := 0,
add := (+),
mul := (*),
zero_mul := λ _, by { ext, simp },
mul_zero := λ _, by { ext, simp },
.. hahn_series.add_comm_monoid,
.. hahn_series.distrib }
instance [non_unital_semiring R] : non_unital_semiring (hahn_series Γ R) :=
{ zero := 0,
add := (+),
mul := (*),
mul_assoc := mul_assoc',
.. hahn_series.non_unital_non_assoc_semiring }
instance [non_assoc_semiring R] : non_assoc_semiring (hahn_series Γ R) :=
{ zero := 0,
one := 1,
add := (+),
mul := (*),
one_mul := λ x, by { ext, exact single_zero_mul_coeff.trans (one_mul _) },
mul_one := λ x, by { ext, exact mul_single_zero_coeff.trans (mul_one _) },
.. hahn_series.non_unital_non_assoc_semiring }
instance [semiring R] : semiring (hahn_series Γ R) :=
{ zero := 0,
one := 1,
add := (+),
mul := (*),
.. hahn_series.non_assoc_semiring,
.. hahn_series.non_unital_semiring }
instance [comm_semiring R] : comm_semiring (hahn_series Γ R) :=
{ mul_comm := λ x y, begin
ext,
simp_rw [mul_coeff, mul_comm],
refine sum_bij (λ a ha, ⟨a.2, a.1⟩) _ (λ a ha, by simp) _ _,
{ intros a ha,
simp only [mem_add_antidiagonal, ne.def, set.mem_set_of_eq] at ha ⊢,
obtain ⟨h1, h2, h3⟩ := ha,
refine ⟨_, h3, h2⟩,
rw [add_comm, h1], },
{ rintros ⟨a1, a2⟩ ⟨b1, b2⟩ ha hb hab,
rw prod.ext_iff at *,
refine ⟨hab.2, hab.1⟩, },
{ intros a ha,
refine ⟨a.swap, _, by simp⟩,
simp only [prod.fst_swap, mem_add_antidiagonal, prod.snd_swap,
ne.def, set.mem_set_of_eq] at ha ⊢,
exact ⟨(add_comm _ _).trans ha.1, ha.2.2, ha.2.1⟩ }
end,
.. hahn_series.semiring }
instance [ring R] : ring (hahn_series Γ R) :=
{ .. hahn_series.semiring,
.. hahn_series.add_comm_group }
instance [comm_ring R] : comm_ring (hahn_series Γ R) :=
{ .. hahn_series.comm_semiring,
.. hahn_series.ring }
instance {Γ} [linear_ordered_cancel_add_comm_monoid Γ] [ring R] [is_domain R] :
is_domain (hahn_series Γ R) :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ x y xy, begin
by_cases hx : x = 0,
{ left, exact hx },
right,
contrapose! xy,
rw [hahn_series.ext_iff, function.funext_iff, not_forall],
refine ⟨x.order + y.order, _⟩,
rw [mul_coeff_order_add_order hx xy, zero_coeff, mul_eq_zero],
simp [coeff_order_ne_zero, hx, xy],
end,
.. hahn_series.nontrivial,
.. hahn_series.ring }
@[simp]
lemma order_mul {Γ} [linear_ordered_cancel_add_comm_monoid Γ] [ring R] [is_domain R]
{x y : hahn_series Γ R} (hx : x ≠ 0) (hy : y ≠ 0) :
(x * y).order = x.order + y.order :=
begin
apply le_antisymm,
{ apply order_le_of_coeff_ne_zero,
rw [mul_coeff_order_add_order hx hy],
exact mul_ne_zero (coeff_order_ne_zero hx) (coeff_order_ne_zero hy) },
{ rw [order_of_ne hx, order_of_ne hy, order_of_ne (mul_ne_zero hx hy), ← set.is_wf.min_add],
exact set.is_wf.min_le_min_of_subset (support_mul_subset_add_support) },
end
section non_unital_non_assoc_semiring
variables [non_unital_non_assoc_semiring R]
@[simp]
lemma single_mul_single {a b : Γ} {r s : R} :
single a r * single b s = single (a + b) (r * s) :=
begin
ext x,
by_cases h : x = a + b,
{ rw [h, mul_single_coeff_add],
simp },
{ rw [single_coeff_of_ne h, mul_coeff, sum_eq_zero],
rintros ⟨y1, y2⟩ hy,
obtain ⟨rfl, hy1, hy2⟩ := mem_add_antidiagonal.1 hy,
rw [eq_of_mem_support_single hy1, eq_of_mem_support_single hy2] at h,
exact (h rfl).elim }
end
end non_unital_non_assoc_semiring
section non_assoc_semiring
variables [non_assoc_semiring R]
/-- `C a` is the constant Hahn Series `a`. `C` is provided as a ring homomorphism. -/
@[simps] def C : R →+* (hahn_series Γ R) :=
{ to_fun := single 0,
map_zero' := single_eq_zero,
map_one' := rfl,
map_add' := λ x y, by { ext a, by_cases h : a = 0; simp [h] },
map_mul' := λ x y, by rw [single_mul_single, zero_add] }
@[simp]
lemma C_zero : C (0 : R) = (0 : hahn_series Γ R) := C.map_zero
@[simp]
lemma C_one : C (1 : R) = (1 : hahn_series Γ R) := C.map_one
lemma C_injective : function.injective (C : R → hahn_series Γ R) :=
begin
intros r s rs,
rw [ext_iff, function.funext_iff] at rs,
have h := rs 0,
rwa [C_apply, single_coeff_same, C_apply, single_coeff_same] at h,
end
lemma C_ne_zero {r : R} (h : r ≠ 0) : (C r : hahn_series Γ R) ≠ 0 :=
begin
contrapose! h,
rw ← C_zero at h,
exact C_injective h,
end
lemma order_C {r : R} : order (C r : hahn_series Γ R) = 0 :=
begin
by_cases h : r = 0,
{ rw [h, C_zero, order_zero] },
{ exact order_single h }
end
end non_assoc_semiring
section semiring
variables [semiring R]
lemma C_mul_eq_smul {r : R} {x : hahn_series Γ R} : C r * x = r • x :=
single_zero_mul_eq_smul
end semiring
section domain
variables {Γ' : Type*} [ordered_cancel_add_comm_monoid Γ']
lemma emb_domain_mul [non_unital_non_assoc_semiring R]
(f : Γ ↪o Γ') (hf : ∀ x y, f (x + y) = f x + f y) (x y : hahn_series Γ R) :
emb_domain f (x * y) = emb_domain f x * emb_domain f y :=
begin
ext g,
by_cases hg : g ∈ set.range f,
{ obtain ⟨g, rfl⟩ := hg,
simp only [mul_coeff, emb_domain_coeff],
transitivity ∑ ij in (add_antidiagonal x.is_pwo_support y.is_pwo_support g).map
(function.embedding.prod_map f.to_embedding f.to_embedding),
(emb_domain f x).coeff (ij.1) *
(emb_domain f y).coeff (ij.2),
{ simp },
apply sum_subset,
{ rintro ⟨i, j⟩ hij,
simp only [exists_prop, mem_map, prod.mk.inj_iff,
mem_add_antidiagonal, ne.def, function.embedding.coe_prod_map, mem_support,
prod.exists] at hij,
obtain ⟨i, j, ⟨rfl, hx, hy⟩, rfl, rfl⟩ := hij,
simp [hx, hy, hf], },
{ rintro ⟨_, _⟩ h1 h2,
contrapose! h2,
obtain ⟨i, hi, rfl⟩ := support_emb_domain_subset (ne_zero_and_ne_zero_of_mul h2).1,
obtain ⟨j, hj, rfl⟩ := support_emb_domain_subset (ne_zero_and_ne_zero_of_mul h2).2,
simp only [exists_prop, mem_map, prod.mk.inj_iff,
mem_add_antidiagonal, ne.def, function.embedding.coe_prod_map, mem_support,
prod.exists],
simp only [mem_add_antidiagonal, emb_domain_coeff, ne.def, mem_support, ← hf] at h1,
exact ⟨i, j, ⟨f.injective h1.1, h1.2⟩, rfl⟩, } },
{ rw [emb_domain_notin_range hg, eq_comm],
contrapose! hg,
obtain ⟨_, _, hi, hj, rfl⟩ := support_mul_subset_add_support ((mem_support _ _).2 hg),
obtain ⟨i, hi, rfl⟩ := support_emb_domain_subset hi,
obtain ⟨j, hj, rfl⟩ := support_emb_domain_subset hj,
refine ⟨i + j, hf i j⟩, }
end
lemma emb_domain_one [non_assoc_semiring R] (f : Γ ↪o Γ') (hf : f 0 = 0):
emb_domain f (1 : hahn_series Γ R) = (1 : hahn_series Γ' R) :=
emb_domain_single.trans $ hf.symm ▸ rfl
/-- Extending the domain of Hahn series is a ring homomorphism. -/
@[simps] def emb_domain_ring_hom [non_assoc_semiring R] (f : Γ →+ Γ') (hfi : function.injective f)
(hf : ∀ g g' : Γ, f g ≤ f g' ↔ g ≤ g') :
hahn_series Γ R →+* hahn_series Γ' R :=
{ to_fun := emb_domain ⟨⟨f, hfi⟩, hf⟩,
map_one' := emb_domain_one _ f.map_zero,
map_mul' := emb_domain_mul _ f.map_add,
map_zero' := emb_domain_zero,
map_add' := emb_domain_add _}
lemma emb_domain_ring_hom_C [non_assoc_semiring R] {f : Γ →+ Γ'} {hfi : function.injective f}
{hf : ∀ g g' : Γ, f g ≤ f g' ↔ g ≤ g'} {r : R} :
emb_domain_ring_hom f hfi hf (C r) = C r :=
emb_domain_single.trans (by simp)
end domain
section algebra
variables [comm_semiring R] {A : Type*} [semiring A] [algebra R A]
instance : algebra R (hahn_series Γ A) :=
{ to_ring_hom := C.comp (algebra_map R A),
smul_def' := λ r x, by { ext, simp },
commutes' := λ r x, by { ext, simp only [smul_coeff, single_zero_mul_eq_smul, ring_hom.coe_comp,
ring_hom.to_fun_eq_coe, C_apply, function.comp_app, algebra_map_smul, mul_single_zero_coeff],
rw [← algebra.commutes, algebra.smul_def], }, }
theorem C_eq_algebra_map : C = (algebra_map R (hahn_series Γ R)) := rfl
theorem algebra_map_apply {r : R} :
algebra_map R (hahn_series Γ A) r = C (algebra_map R A r) := rfl
instance [nontrivial Γ] [nontrivial R] : nontrivial (subalgebra R (hahn_series Γ R)) :=
⟨⟨⊥, ⊤, begin
rw [ne.def, set_like.ext_iff, not_forall],
obtain ⟨a, ha⟩ := exists_ne (0 : Γ),
refine ⟨single a 1, _⟩,
simp only [algebra.mem_bot, not_exists, set.mem_range, iff_true, algebra.mem_top],
intros x,
rw [ext_iff, function.funext_iff, not_forall],
refine ⟨a, _⟩,
rw [single_coeff_same, algebra_map_apply, C_apply, single_coeff_of_ne ha],
exact zero_ne_one
end⟩⟩
section domain
variables {Γ' : Type*} [ordered_cancel_add_comm_monoid Γ']
/-- Extending the domain of Hahn series is an algebra homomorphism. -/
@[simps] def emb_domain_alg_hom (f : Γ →+ Γ') (hfi : function.injective f)
(hf : ∀ g g' : Γ, f g ≤ f g' ↔ g ≤ g') :
hahn_series Γ A →ₐ[R] hahn_series Γ' A :=
{ commutes' := λ r, emb_domain_ring_hom_C,
.. emb_domain_ring_hom f hfi hf }
end domain
end algebra
end multiplication
section semiring
variables [semiring R]
/-- The ring `hahn_series ℕ R` is isomorphic to `power_series R`. -/
@[simps] def to_power_series : (hahn_series ℕ R) ≃+* power_series R :=
{ to_fun := λ f, power_series.mk f.coeff,
inv_fun := λ f, ⟨λ n, power_series.coeff R n f, (nat.lt_wf.is_wf _).is_pwo⟩,
left_inv := λ f, by { ext, simp },
right_inv := λ f, by { ext, simp },
map_add' := λ f g, by { ext, simp },
map_mul' := λ f g, begin
ext n,
simp only [power_series.coeff_mul, power_series.coeff_mk, mul_coeff, is_pwo_support],
classical,
refine sum_filter_ne_zero.symm.trans
((sum_congr _ (λ _ _, rfl)).trans sum_filter_ne_zero),
ext m,
simp only [nat.mem_antidiagonal, and.congr_left_iff, mem_add_antidiagonal, ne.def,
and_iff_left_iff_imp, mem_filter, mem_support],
intros h1 h2,
contrapose h1,
rw ← decidable.or_iff_not_and_not at h1,
cases h1; simp [h1]
end }
lemma coeff_to_power_series {f : hahn_series ℕ R} {n : ℕ} :
power_series.coeff R n f.to_power_series = f.coeff n :=
power_series.coeff_mk _ _
lemma coeff_to_power_series_symm {f : power_series R} {n : ℕ} :
(hahn_series.to_power_series.symm f).coeff n = power_series.coeff R n f := rfl
variables (Γ) (R) [ordered_semiring Γ] [nontrivial Γ]
/-- Casts a power series as a Hahn series with coefficients from an `ordered_semiring`. -/
def of_power_series : (power_series R) →+* hahn_series Γ R :=
(hahn_series.emb_domain_ring_hom (nat.cast_add_monoid_hom Γ) nat.strict_mono_cast.injective
(λ _ _, nat.cast_le)).comp
(ring_equiv.to_ring_hom to_power_series.symm)
variables {Γ} {R}
lemma of_power_series_injective : function.injective (of_power_series Γ R) :=
emb_domain_injective.comp to_power_series.symm.injective
@[simp] lemma of_power_series_apply (x : power_series R) :
of_power_series Γ R x = hahn_series.emb_domain
⟨⟨(coe : ℕ → Γ), nat.strict_mono_cast.injective⟩, λ a b, begin
simp only [function.embedding.coe_fn_mk],
exact nat.cast_le,
end⟩ (to_power_series.symm x) := rfl
lemma of_power_series_apply_coeff (x : power_series R) (n : ℕ) :
(of_power_series Γ R x).coeff n = power_series.coeff R n x :=
by simp
end semiring
section algebra
variables (R) [comm_semiring R] {A : Type*} [semiring A] [algebra R A]
/-- The `R`-algebra `hahn_series ℕ A` is isomorphic to `power_series A`. -/
@[simps] def to_power_series_alg : (hahn_series ℕ A) ≃ₐ[R] power_series A :=
{ commutes' := λ r, begin
ext n,
simp only [algebra_map_apply, power_series.algebra_map_apply, ring_equiv.to_fun_eq_coe, C_apply,
coeff_to_power_series],
cases n,
{ simp only [power_series.coeff_zero_eq_constant_coeff, single_coeff_same],
refl },
{ simp only [n.succ_ne_zero, ne.def, not_false_iff, single_coeff_of_ne],
rw [power_series.coeff_C, if_neg n.succ_ne_zero] }
end,
.. to_power_series }
variables (Γ) (R) [ordered_semiring Γ] [nontrivial Γ]
/-- Casting a power series as a Hahn series with coefficients from an `ordered_semiring`
is an algebra homomorphism. -/
@[simps] def of_power_series_alg : (power_series A) →ₐ[R] hahn_series Γ A :=
(hahn_series.emb_domain_alg_hom (nat.cast_add_monoid_hom Γ) nat.strict_mono_cast.injective
(λ _ _, nat.cast_le)).comp
(alg_equiv.to_alg_hom (to_power_series_alg R).symm)
end algebra
section valuation
variables [linear_ordered_add_comm_group Γ] [ring R] [is_domain R]
instance : linear_ordered_comm_group (multiplicative Γ) :=
{ .. (infer_instance : linear_order (multiplicative Γ)),
.. (infer_instance : ordered_comm_group (multiplicative Γ)) }
instance : linear_ordered_comm_group_with_zero (with_zero (multiplicative Γ)) :=
{ zero_le_one := with_zero.zero_le 1,
.. (with_zero.ordered_comm_monoid),
.. (infer_instance : linear_order (with_zero (multiplicative Γ))),
.. (infer_instance : comm_group_with_zero (with_zero (multiplicative Γ))) }
variables (Γ) (R)
/-- The additive valuation on `hahn_series Γ R`, returning the smallest index at which
a Hahn Series has a nonzero coefficient, or `⊤` for the 0 series. -/
def add_val : add_valuation (hahn_series Γ R) (with_top Γ) :=
add_valuation.of (λ x, if x = (0 : hahn_series Γ R) then (⊤ : with_top Γ) else x.order)
(if_pos rfl)
((if_neg one_ne_zero).trans (by simp [order_of_ne]))
(λ x y, begin
by_cases hx : x = 0,
{ by_cases hy : y = 0; { simp [hx, hy] } },
{ by_cases hy : y = 0,
{ simp [hx, hy] },
{ simp only [hx, hy, support_nonempty_iff, if_neg, not_false_iff, is_wf_support],
by_cases hxy : x + y = 0,
{ simp [hxy] },
rw [if_neg hxy, ← with_top.coe_min, with_top.coe_le_coe],
exact min_order_le_order_add hx hy hxy } },
end)
(λ x y, begin
by_cases hx : x = 0,
{ simp [hx] },
by_cases hy : y = 0,
{ simp [hy] },
rw [if_neg hx, if_neg hy, if_neg (mul_ne_zero hx hy),
← with_top.coe_add, with_top.coe_eq_coe, order_mul hx hy],
end)
variables {Γ} {R}
lemma add_val_apply {x : hahn_series Γ R} :
add_val Γ R x = if x = (0 : hahn_series Γ R) then (⊤ : with_top Γ) else x.order :=
add_valuation.of_apply _
@[simp]
lemma add_val_apply_of_ne {x : hahn_series Γ R} (hx : x ≠ 0) :
add_val Γ R x = x.order :=
if_neg hx
lemma add_val_le_of_coeff_ne_zero {x : hahn_series Γ R} {g : Γ} (h : x.coeff g ≠ 0) :
add_val Γ R x ≤ g :=
begin
rw [add_val_apply_of_ne (ne_zero_of_coeff_ne_zero h), with_top.coe_le_coe],
exact order_le_of_coeff_ne_zero h
end
end valuation
lemma is_pwo_Union_support_powers
[linear_ordered_add_comm_group Γ] [ring R] [is_domain R]
{x : hahn_series Γ R} (hx : 0 < add_val Γ R x) :
(⋃ n : ℕ, (x ^ n).support).is_pwo :=
begin
apply (x.is_wf_support.is_pwo.add_submonoid_closure (λ g hg, _)).mono _,
{ exact with_top.coe_le_coe.1 (le_trans (le_of_lt hx) (add_val_le_of_coeff_ne_zero hg)) },
refine set.Union_subset (λ n, _),
induction n with n ih;
intros g hn,
{ simp only [exists_prop, and_true, set.mem_singleton_iff, set.set_of_eq_eq_singleton,
mem_support, ite_eq_right_iff, ne.def, not_false_iff, one_ne_zero,
pow_zero, not_forall, one_coeff] at hn,
rw [hn, set_like.mem_coe],
exact add_submonoid.zero_mem _ },
{ obtain ⟨i, j, hi, hj, rfl⟩ := support_mul_subset_add_support hn,
exact set_like.mem_coe.2 (add_submonoid.add_mem _ (add_submonoid.subset_closure hi) (ih hj)) }
end
section
variables (Γ) (R) [partial_order Γ] [add_comm_monoid R]
/-- An infinite family of Hahn series which has a formal coefficient-wise sum.
The requirements for this are that the union of the supports of the series is well-founded,
and that only finitely many series are nonzero at any given coefficient. -/
structure summable_family (α : Type*) :=
(to_fun : α → hahn_series Γ R)
(is_pwo_Union_support' : set.is_pwo (⋃ (a : α), (to_fun a).support))
(finite_co_support' : ∀ (g : Γ), ({a | (to_fun a).coeff g ≠ 0}).finite)
end
namespace summable_family
section add_comm_monoid
variables [partial_order Γ] [add_comm_monoid R] {α : Type*}
instance : has_coe_to_fun (summable_family Γ R α) (λ _, α → hahn_series Γ R):=
⟨to_fun⟩
lemma is_pwo_Union_support (s : summable_family Γ R α) : set.is_pwo (⋃ (a : α), (s a).support) :=
s.is_pwo_Union_support'
lemma finite_co_support (s : summable_family Γ R α) (g : Γ) :
(function.support (λ a, (s a).coeff g)).finite :=
s.finite_co_support' g
lemma coe_injective : @function.injective (summable_family Γ R α) (α → hahn_series Γ R) coe_fn
| ⟨f1, hU1, hf1⟩ ⟨f2, hU2, hf2⟩ h :=
begin
change f1 = f2 at h,
subst h,
end
@[ext]
lemma ext {s t : summable_family Γ R α} (h : ∀ (a : α), s a = t a) : s = t :=
coe_injective $ funext h
instance : has_add (summable_family Γ R α) :=
⟨λ x y, { to_fun := x + y,
is_pwo_Union_support' := (x.is_pwo_Union_support.union y.is_pwo_Union_support).mono (begin
rw ← set.Union_union_distrib,
exact set.Union_subset_Union (λ a, support_add_subset)
end),
finite_co_support' := λ g, ((x.finite_co_support g).union (y.finite_co_support g)).subset begin
intros a ha,
change (x a).coeff g + (y a).coeff g ≠ 0 at ha,
rw [set.mem_union, function.mem_support, function.mem_support],
contrapose! ha,
rw [ha.1, ha.2, add_zero]
end }⟩
instance : has_zero (summable_family Γ R α) :=
⟨⟨0, by simp, by simp⟩⟩
instance : inhabited (summable_family Γ R α) := ⟨0⟩
@[simp]
lemma coe_add {s t : summable_family Γ R α} : ⇑(s + t) = s + t := rfl
lemma add_apply {s t : summable_family Γ R α} {a : α} : (s + t) a = s a + t a := rfl
@[simp]
lemma coe_zero : ((0 : summable_family Γ R α) : α → hahn_series Γ R) = 0 := rfl
lemma zero_apply {a : α} : (0 : summable_family Γ R α) a = 0 := rfl
instance : add_comm_monoid (summable_family Γ R α) :=
{ add := (+),
zero := 0,
zero_add := λ s, by { ext, apply zero_add },
add_zero := λ s, by { ext, apply add_zero },
add_comm := λ s t, by { ext, apply add_comm },
add_assoc := λ r s t, by { ext, apply add_assoc } }
/-- The infinite sum of a `summable_family` of Hahn series. -/
def hsum (s : summable_family Γ R α) :
hahn_series Γ R :=
{ coeff := λ g, ∑ᶠ i, (s i).coeff g,
is_pwo_support' := s.is_pwo_Union_support.mono (λ g, begin
contrapose,
rw [set.mem_Union, not_exists, function.mem_support, not_not],
simp_rw [mem_support, not_not],
intro h,
rw [finsum_congr h, finsum_zero],
end) }
@[simp]
lemma hsum_coeff {s : summable_family Γ R α} {g : Γ} :
s.hsum.coeff g = ∑ᶠ i, (s i).coeff g := rfl
lemma support_hsum_subset {s : summable_family Γ R α} :
s.hsum.support ⊆ ⋃ (a : α), (s a).support :=
λ g hg, begin
rw [mem_support, hsum_coeff, finsum_eq_sum _ (s.finite_co_support _)] at hg,
obtain ⟨a, h1, h2⟩ := exists_ne_zero_of_sum_ne_zero hg,
rw [set.mem_Union],
exact ⟨a, h2⟩,
end
@[simp]
lemma hsum_add {s t : summable_family Γ R α} : (s + t).hsum = s.hsum + t.hsum :=
begin
ext g,
simp only [hsum_coeff, add_coeff, add_apply],
exact finsum_add_distrib (s.finite_co_support _) (t.finite_co_support _)
end
end add_comm_monoid
section add_comm_group
variables [partial_order Γ] [add_comm_group R] {α : Type*} {s t : summable_family Γ R α} {a : α}
instance : add_comm_group (summable_family Γ R α) :=
{ neg := λ s, { to_fun := λ a, - s a,
is_pwo_Union_support' := by { simp_rw [support_neg], exact s.is_pwo_Union_support' },
finite_co_support' := λ g, by { simp only [neg_coeff', pi.neg_apply, ne.def, neg_eq_zero],
exact s.finite_co_support g } },
add_left_neg := λ a, by { ext, apply add_left_neg },
.. summable_family.add_comm_monoid }
@[simp]
lemma coe_neg : ⇑(-s) = - s := rfl
lemma neg_apply : (-s) a = - (s a) := rfl
@[simp]
lemma coe_sub : ⇑(s - t) = s - t := rfl
lemma sub_apply : (s - t) a = s a - t a := rfl
end add_comm_group
section semiring
variables [ordered_cancel_add_comm_monoid Γ] [semiring R] {α : Type*}
instance : has_scalar (hahn_series Γ R) (summable_family Γ R α) :=
{ smul := λ x s, { to_fun := λ a, x * (s a),
is_pwo_Union_support' := begin
apply (x.is_pwo_support.add s.is_pwo_Union_support).mono,
refine set.subset.trans (set.Union_subset_Union (λ a, support_mul_subset_add_support)) _,
intro g,
simp only [set.mem_Union, exists_imp_distrib],
exact λ a ha, (set.add_subset_add (set.subset.refl _) (set.subset_Union _ a)) ha,
end,
finite_co_support' := λ g, begin
refine ((add_antidiagonal x.is_pwo_support s.is_pwo_Union_support g).finite_to_set.bUnion
(λ ij hij, _)).subset (λ a ha, _),
{ exact λ ij hij, function.support (λ a, (s a).coeff ij.2) },
{ apply s.finite_co_support },
{ obtain ⟨i, j, hi, hj, rfl⟩ := support_mul_subset_add_support ha,
simp only [exists_prop, set.mem_Union, mem_add_antidiagonal,
mul_coeff, ne.def, mem_support, is_pwo_support, prod.exists],
refine ⟨i, j, mem_coe.2 (mem_add_antidiagonal.2 ⟨rfl, hi, set.mem_Union.2 ⟨a, hj⟩⟩), hj⟩, }
end } }
@[simp]
lemma smul_apply {x : hahn_series Γ R} {s : summable_family Γ R α} {a : α} :
(x • s) a = x * (s a) := rfl
instance : module (hahn_series Γ R) (summable_family Γ R α) :=
{ smul := (•),
smul_zero := λ x, ext (λ a, mul_zero _),
zero_smul := λ x, ext (λ a, zero_mul _),
one_smul := λ x, ext (λ a, one_mul _),
add_smul := λ x y s, ext (λ a, add_mul _ _ _),
smul_add := λ x s t, ext (λ a, mul_add _ _ _),
mul_smul := λ x y s, ext (λ a, mul_assoc _ _ _) }
@[simp]
lemma hsum_smul {x : hahn_series Γ R} {s : summable_family Γ R α} :
(x • s).hsum = x * s.hsum :=
begin
ext g,
simp only [mul_coeff, hsum_coeff, smul_apply],
have h : ∀ i, (s i).support ⊆ ⋃ j, (s j).support := set.subset_Union _,
refine (eq.trans (finsum_congr (λ a, _))
(finsum_sum_comm (add_antidiagonal x.is_pwo_support s.is_pwo_Union_support g)
(λ i ij, x.coeff (prod.fst ij) * (s i).coeff ij.snd) _)).trans _,
{ refine sum_subset (add_antidiagonal_mono_right (set.subset_Union _ a)) _,
rintro ⟨i, j⟩ hU ha,
rw mem_add_antidiagonal at *,
rw [not_not.1 (λ con, ha ⟨hU.1, hU.2.1, con⟩), mul_zero] },
{ rintro ⟨i, j⟩ hij,
refine (s.finite_co_support j).subset _,
simp_rw [function.support_subset_iff', function.mem_support, not_not],
intros a ha,
rw [ha, mul_zero] },
{ refine (sum_congr rfl _).trans (sum_subset (add_antidiagonal_mono_right _) _).symm,
{ rintro ⟨i, j⟩ hij,
rw mul_finsum,
apply s.finite_co_support, },
{ intros x hx,
simp only [set.mem_Union, ne.def, mem_support],
contrapose! hx,
simp [hx] },
{ rintro ⟨i, j⟩ hU ha,
rw mem_add_antidiagonal at *,
rw [← hsum_coeff, not_not.1 (λ con, ha ⟨hU.1, hU.2.1, con⟩), mul_zero] } }
end
/-- The summation of a `summable_family` as a `linear_map`. -/
@[simps] def lsum : (summable_family Γ R α) →ₗ[hahn_series Γ R] (hahn_series Γ R) :=
{ to_fun := hsum, map_add' := λ _ _, hsum_add, map_smul' := λ _ _, hsum_smul }
@[simp]
lemma hsum_sub {R : Type*} [ring R] {s t : summable_family Γ R α} :
(s - t).hsum = s.hsum - t.hsum :=
by rw [← lsum_apply, linear_map.map_sub, lsum_apply, lsum_apply]
end semiring
section of_finsupp
variables [partial_order Γ] [add_comm_monoid R] {α : Type*}
/-- A family with only finitely many nonzero elements is summable. -/
def of_finsupp (f : α →₀ (hahn_series Γ R)) :
summable_family Γ R α :=
{ to_fun := f,
is_pwo_Union_support' := begin
apply (f.support.is_pwo_sup (λ a, (f a).support) (λ a ha, (f a).is_pwo_support)).mono,
intros g hg,
obtain ⟨a, ha⟩ := set.mem_Union.1 hg,
have haf : a ∈ f.support,
{ rw finsupp.mem_support_iff,
contrapose! ha,
rw [ha, support_zero],
exact set.not_mem_empty _ },
have h : (λ i, (f i).support) a ≤ _ := le_sup haf,
exact h ha,
end,
finite_co_support' := λ g, begin
refine f.support.finite_to_set.subset (λ a ha, _),
simp only [coeff.add_monoid_hom_apply, mem_coe, finsupp.mem_support_iff,
ne.def, function.mem_support],
contrapose! ha,
simp [ha]
end }
@[simp]
lemma coe_of_finsupp {f : α →₀ (hahn_series Γ R)} : ⇑(summable_family.of_finsupp f) = f := rfl
@[simp]
lemma hsum_of_finsupp {f : α →₀ (hahn_series Γ R)} :
(of_finsupp f).hsum = f.sum (λ a, id) :=
begin
ext g,
simp only [hsum_coeff, coe_of_finsupp, finsupp.sum, ne.def],
simp_rw [← coeff.add_monoid_hom_apply, id.def],
rw [add_monoid_hom.map_sum, finsum_eq_sum_of_support_subset],
intros x h,
simp only [coeff.add_monoid_hom_apply, mem_coe, finsupp.mem_support_iff, ne.def],
contrapose! h,
simp [h]
end
end of_finsupp
section emb_domain
variables [partial_order Γ] [add_comm_monoid R] {α β : Type*}
/-- A summable family can be reindexed by an embedding without changing its sum. -/
def emb_domain (s : summable_family Γ R α) (f : α ↪ β) : summable_family Γ R β :=
{ to_fun := λ b, if h : b ∈ set.range f then s (classical.some h) else 0,
is_pwo_Union_support' := begin
refine s.is_pwo_Union_support.mono (set.Union_subset (λ b g h, _)),
by_cases hb : b ∈ set.range f,
{ rw dif_pos hb at h,
exact set.mem_Union.2 ⟨classical.some hb, h⟩ },
{ contrapose! h,
simp [hb] }
end,
finite_co_support' := λ g, ((s.finite_co_support g).image f).subset begin
intros b h,
by_cases hb : b ∈ set.range f,
{ simp only [ne.def, set.mem_set_of_eq, dif_pos hb] at h,
exact ⟨classical.some hb, h, classical.some_spec hb⟩ },
{ contrapose! h,
simp only [ne.def, set.mem_set_of_eq, dif_neg hb, not_not, zero_coeff] }
end }
variables (s : summable_family Γ R α) (f : α ↪ β) {a : α} {b : β}
lemma emb_domain_apply :
s.emb_domain f b = if h : b ∈ set.range f then s (classical.some h) else 0 := rfl
@[simp] lemma emb_domain_image : s.emb_domain f (f a) = s a :=
begin
rw [emb_domain_apply, dif_pos (set.mem_range_self a)],
exact congr rfl (f.injective (classical.some_spec (set.mem_range_self a)))
end
@[simp] lemma emb_domain_notin_range (h : b ∉ set.range f) : s.emb_domain f b = 0 :=
by rw [emb_domain_apply, dif_neg h]
@[simp] lemma hsum_emb_domain :
(s.emb_domain f).hsum = s.hsum :=
begin
ext g,
simp only [hsum_coeff, emb_domain_apply, apply_dite hahn_series.coeff, dite_apply, zero_coeff],
exact finsum_emb_domain f (λ a, (s a).coeff g)
end
end emb_domain
section powers
variables [linear_ordered_add_comm_group Γ] [comm_ring R] [is_domain R]
/-- The powers of an element of positive valuation form a summable family. -/
def powers (x : hahn_series Γ R) (hx : 0 < add_val Γ R x) :
summable_family Γ R ℕ :=
{ to_fun := λ n, x ^ n,
is_pwo_Union_support' := is_pwo_Union_support_powers hx,
finite_co_support' := λ g, begin
have hpwo := (is_pwo_Union_support_powers hx),
by_cases hg : g ∈ ⋃ n : ℕ, {g | (x ^ n).coeff g ≠ 0 },
swap, { exact set.finite_empty.subset (λ n hn, hg (set.mem_Union.2 ⟨n, hn⟩)) },
apply hpwo.is_wf.induction hg,
intros y ys hy,
refine ((((add_antidiagonal x.is_pwo_support hpwo y).finite_to_set.bUnion (λ ij hij,
hy ij.snd _ _)).image nat.succ).union (set.finite_singleton 0)).subset _,
{ exact (mem_add_antidiagonal.1 (mem_coe.1 hij)).2.2 },
{ obtain ⟨rfl, hi, hj⟩ := mem_add_antidiagonal.1 (mem_coe.1 hij),
rw [← zero_add ij.snd, ← add_assoc, add_zero],
exact add_lt_add_right (with_top.coe_lt_coe.1
(lt_of_lt_of_le hx (add_val_le_of_coeff_ne_zero hi))) _, },
{ intros n hn,
cases n,
{ exact set.mem_union_right _ (set.mem_singleton 0) },
{ obtain ⟨i, j, hi, hj, rfl⟩ := support_mul_subset_add_support hn,
refine set.mem_union_left _ ⟨n, set.mem_Union.2 ⟨⟨i, j⟩, set.mem_Union.2 ⟨_, hj⟩⟩, rfl⟩,
simp only [true_and, set.mem_Union, mem_add_antidiagonal, mem_coe, eq_self_iff_true,
ne.def, mem_support, set.mem_set_of_eq],
exact ⟨hi, ⟨n, hj⟩⟩ } }
end }
variables {x : hahn_series Γ R} (hx : 0 < add_val Γ R x)
@[simp] lemma coe_powers : ⇑(powers x hx) = pow x := rfl
lemma emb_domain_succ_smul_powers :
(x • powers x hx).emb_domain ⟨nat.succ, nat.succ_injective⟩ =
powers x hx - of_finsupp (finsupp.single 0 1) :=
begin
apply summable_family.ext (λ n, _),
cases n,
{ rw [emb_domain_notin_range, sub_apply, coe_powers, pow_zero, coe_of_finsupp,
finsupp.single_eq_same, sub_self],
rw [set.mem_range, not_exists],
exact nat.succ_ne_zero },
{ refine eq.trans (emb_domain_image _ ⟨nat.succ, nat.succ_injective⟩) _,
simp only [pow_succ, coe_powers, coe_sub, smul_apply, coe_of_finsupp, pi.sub_apply],
rw [finsupp.single_eq_of_ne (n.succ_ne_zero).symm, sub_zero] }
end
lemma one_sub_self_mul_hsum_powers :
(1 - x) * (powers x hx).hsum = 1 :=
begin
rw [← hsum_smul, sub_smul, one_smul, hsum_sub,
← hsum_emb_domain (x • powers x hx) ⟨nat.succ, nat.succ_injective⟩,
emb_domain_succ_smul_powers],
simp,
end
end powers
end summable_family
section inversion
variables [linear_ordered_add_comm_group Γ]
section is_domain
variables [comm_ring R] [is_domain R]
lemma unit_aux (x : hahn_series Γ R) {r : R} (hr : r * x.coeff x.order = 1) :
0 < add_val Γ R (1 - C r * (single (- x.order) 1) * x) :=
begin
have h10 : (1 : R) ≠ 0 := one_ne_zero,
have x0 : x ≠ 0 := ne_zero_of_coeff_ne_zero (right_ne_zero_of_mul_eq_one hr),
refine lt_of_le_of_ne ((add_val Γ R).map_le_sub (ge_of_eq (add_val Γ R).map_one) _) _,
{ simp only [add_valuation.map_mul],
rw [add_val_apply_of_ne x0, add_val_apply_of_ne (single_ne_zero h10),
add_val_apply_of_ne _, order_C, order_single h10, with_top.coe_zero, zero_add,
← with_top.coe_add, neg_add_self, with_top.coe_zero],
{ exact le_refl 0 },
{ exact C_ne_zero (left_ne_zero_of_mul_eq_one hr) } },
{ rw [add_val_apply, ← with_top.coe_zero],
split_ifs,
{ apply with_top.coe_ne_top },
rw [ne.def, with_top.coe_eq_coe],
intro con,
apply coeff_order_ne_zero h,
rw [← con, mul_assoc, sub_coeff, one_coeff, if_pos rfl, C_mul_eq_smul, smul_coeff, smul_eq_mul,
← add_neg_self x.order, single_mul_coeff_add, one_mul, hr, sub_self] }
end
lemma is_unit_iff {x : hahn_series Γ R} :
is_unit x ↔ is_unit (x.coeff x.order) :=
begin
split,
{ rintro ⟨⟨u, i, ui, iu⟩, rfl⟩,
refine is_unit_of_mul_eq_one (u.coeff u.order) (i.coeff i.order)
((mul_coeff_order_add_order (left_ne_zero_of_mul_eq_one ui)
(right_ne_zero_of_mul_eq_one ui)).symm.trans _),
rw [ui, one_coeff, if_pos],
rw [← order_mul (left_ne_zero_of_mul_eq_one ui)
(right_ne_zero_of_mul_eq_one ui), ui, order_one] },
{ rintro ⟨⟨u, i, ui, iu⟩, h⟩,
rw [units.coe_mk] at h,
rw h at iu,
have h := summable_family.one_sub_self_mul_hsum_powers (unit_aux x iu),
rw [sub_sub_cancel] at h,
exact is_unit_of_mul_is_unit_right (is_unit_of_mul_eq_one _ _ h) },
end
end is_domain
instance [field R] : field (hahn_series Γ R) :=
{ inv := λ x, if x0 : x = 0 then 0 else (C (x.coeff x.order)⁻¹ * (single (-x.order)) 1 *
(summable_family.powers _ (unit_aux x (inv_mul_cancel (coeff_order_ne_zero x0)))).hsum),
inv_zero := dif_pos rfl,
mul_inv_cancel := λ x x0, begin
refine (congr rfl (dif_neg x0)).trans _,
have h := summable_family.one_sub_self_mul_hsum_powers
(unit_aux x (inv_mul_cancel (coeff_order_ne_zero x0))),
rw [sub_sub_cancel] at h,
rw [← mul_assoc, mul_comm x, h],
end,
.. hahn_series.is_domain,
.. hahn_series.comm_ring }
end inversion
end hahn_series
|
e9a769bd20559c3602f94162e5defa1e7fdc296d | 9c2e8d73b5c5932ceb1333265f17febc6a2f0a39 | /src/S4/test.lean | 03ab1be1564b06d37d0b434966339b5dbe137742 | [
"MIT"
] | permissive | minchaowu/ModalTab | 2150392108dfdcaffc620ff280a8b55fe13c187f | 9bb0bf17faf0554d907ef7bdd639648742889178 | refs/heads/master | 1,626,266,863,244 | 1,592,056,874,000 | 1,592,056,874,000 | 153,314,364 | 12 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 396 | lean | import .tableau
open fml
def fml.iff (φ ψ : fml) := and (impl φ ψ) (impl ψ φ)
def test (ϕ : fml) := fml_is_sat [neg ϕ]
local infix ` ∨ `:1000 := fml.or
local infix ` ∧ `:1000 := fml.and
local infix ` -> `:1000 := fml.impl
local infix ` <-> `:1000 := fml.iff
local prefix `~` := fml.neg
precedence `p`:max
local prefix ` p ` := fml.var
set_option profiler true
-- #eval test ()
|
f96d1bbb5e9b7c13058fe3c7da2450c2bdf0e58c | 08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4 | /src/Lean/Elab/LetRec.lean | 41a5153137f126426937d05a272d802b3ed14551 | [
"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 | 5,040 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.Attributes
import Lean.Elab.Binders
import Lean.Elab.DeclModifiers
import Lean.Elab.SyntheticMVars
import Lean.Elab.DeclarationRange
namespace Lean.Elab.Term
open Meta
structure LetRecDeclView where
ref : Syntax
attrs : Array Attribute
shortDeclName : Name
declName : Name
binderIds : Array Syntax
type : Expr
mvar : Expr -- auxiliary metavariable used to lift the 'let rec'
valStx : Syntax
structure LetRecView where
decls : Array LetRecDeclView
body : Syntax
/- group ("let " >> nonReservedSymbol "rec ") >> sepBy1 (group (optional «attributes» >> letDecl)) ", " >> "; " >> termParser -/
private def mkLetRecDeclView (letRec : Syntax) : TermElabM LetRecView := do
let decls ← letRec[1][0].getSepArgs.mapM fun (attrDeclStx : Syntax) => do
let docStr? ← expandOptDocComment? attrDeclStx[0]
let attrOptStx := attrDeclStx[1]
let attrs ← if attrOptStx.isNone then pure #[] else elabDeclAttrs attrOptStx[0]
let decl := attrDeclStx[2][0]
if decl.isOfKind `Lean.Parser.Term.letPatDecl then
throwErrorAt decl "patterns are not allowed in 'let rec' expressions"
else if decl.isOfKind `Lean.Parser.Term.letIdDecl || decl.isOfKind `Lean.Parser.Term.letEqnsDecl then
let declId := decl[0]
let shortDeclName := declId.getId
let currDeclName? ← getDeclName?
let declName := currDeclName?.getD Name.anonymous ++ shortDeclName
checkNotAlreadyDeclared declName
applyAttributesAt declName attrs AttributeApplicationTime.beforeElaboration
addDocString' declName docStr?
addAuxDeclarationRanges declName decl declId
let binders := decl[1].getArgs
let typeStx := expandOptType declId decl[2]
let (type, binderIds) ← elabBindersEx binders fun xs => do
let type ← elabType typeStx
registerCustomErrorIfMVar type typeStx "failed to infer 'let rec' declaration type"
let (binderIds, xs) := xs.unzip
let type ← mkForallFVars xs type
pure (type, binderIds)
let mvar ← mkFreshExprMVar type MetavarKind.syntheticOpaque
let valStx ← if decl.isOfKind `Lean.Parser.Term.letIdDecl then
pure decl[4]
else
liftMacroM <| expandMatchAltsIntoMatch decl decl[3]
pure { ref := declId, attrs, shortDeclName, declName, binderIds, type, mvar, valStx : LetRecDeclView }
else
throwUnsupportedSyntax
return { decls, body := letRec[3] }
private partial def withAuxLocalDecls {α} (views : Array LetRecDeclView) (k : Array Expr → TermElabM α) : TermElabM α :=
let rec loop (i : Nat) (fvars : Array Expr) : TermElabM α :=
if h : i < views.size then
let view := views.get ⟨i, h⟩
withAuxDecl view.shortDeclName view.type view.declName fun fvar => loop (i+1) (fvars.push fvar)
else
k fvars
loop 0 #[]
private def elabLetRecDeclValues (view : LetRecView) : TermElabM (Array Expr) :=
view.decls.mapM fun view => do
forallBoundedTelescope view.type view.binderIds.size fun xs type => do
-- Add new info nodes for new fvars. The server will detect all fvars of a binder by the binder's source location.
for i in [0:view.binderIds.size] do
addLocalVarInfo view.binderIds[i]! xs[i]!
withDeclName view.declName do
let value ← elabTermEnsuringType view.valStx type
mkLambdaFVars xs value
private def registerLetRecsToLift (views : Array LetRecDeclView) (fvars : Array Expr) (values : Array Expr) : TermElabM Unit := do
let letRecsToLiftCurr := (← get).letRecsToLift
for view in views do
if letRecsToLiftCurr.any fun toLift => toLift.declName == view.declName then
withRef view.ref do
throwError "'{view.declName}' has already been declared"
let lctx ← getLCtx
let localInstances ← getLocalInstances
let toLift := views.mapIdx fun i view => {
ref := view.ref
fvarId := fvars[i]!.fvarId!
attrs := view.attrs
shortDeclName := view.shortDeclName
declName := view.declName
lctx
localInstances
type := view.type
val := values[i]!
mvarId := view.mvar.mvarId!
: LetRecToLift }
modify fun s => { s with letRecsToLift := toLift.toList ++ s.letRecsToLift }
@[builtin_term_elab «letrec»] def elabLetRec : TermElab := fun stx expectedType? => do
let view ← mkLetRecDeclView stx
withAuxLocalDecls view.decls fun fvars => do
for decl in view.decls, fvar in fvars do
addLocalVarInfo decl.ref fvar
let values ← elabLetRecDeclValues view
let body ← elabTermEnsuringType view.body expectedType?
registerLetRecsToLift view.decls fvars values
let mvars := view.decls.map (·.mvar)
return mkAppN (← mkLambdaFVars fvars body) mvars
end Lean.Elab.Term
|
d2956f7b09994c61cf1a9b5974f7097df81c7f6a | b70447c014d9e71cf619ebc9f539b262c19c2e0b | /hott/types/equiv.hlean | 0af87c1241e06ae494745f262d040027b9eb89f8 | [
"Apache-2.0"
] | permissive | ia0/lean2 | c20d8da69657f94b1d161f9590a4c635f8dc87f3 | d86284da630acb78fa5dc3b0b106153c50ffccd0 | refs/heads/master | 1,611,399,322,751 | 1,495,751,007,000 | 1,495,751,007,000 | 93,104,167 | 0 | 0 | null | 1,496,355,488,000 | 1,496,355,487,000 | null | UTF-8 | Lean | false | false | 12,921 | hlean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Ported from Coq HoTT
Theorems about the types equiv and is_equiv
-/
import .fiber .arrow arity ..prop_trunc cubical.square .pointed
open eq is_trunc sigma sigma.ops pi fiber function equiv
namespace is_equiv
variables {A B : Type} (f : A → B) [H : is_equiv f]
include H
/- is_equiv f is a mere proposition -/
definition is_contr_fiber_of_is_equiv [instance] (b : B) : is_contr (fiber f b) :=
is_contr.mk
(fiber.mk (f⁻¹ b) (right_inv f b))
(λz, fiber.rec_on z (λa p,
fiber_eq ((ap f⁻¹ p)⁻¹ ⬝ left_inv f a) (calc
right_inv f b = (ap (f ∘ f⁻¹) p)⁻¹ ⬝ ((ap (f ∘ f⁻¹) p) ⬝ right_inv f b)
: by rewrite inv_con_cancel_left
... = (ap (f ∘ f⁻¹) p)⁻¹ ⬝ (right_inv f (f a) ⬝ p) : by rewrite ap_con_eq_con
... = (ap (f ∘ f⁻¹) p)⁻¹ ⬝ (ap f (left_inv f a) ⬝ p) : by rewrite [adj f]
... = (ap (f ∘ f⁻¹) p)⁻¹ ⬝ ap f (left_inv f a) ⬝ p : by rewrite con.assoc
... = (ap f (ap f⁻¹ p))⁻¹ ⬝ ap f (left_inv f a) ⬝ p : by rewrite ap_compose
... = ap f (ap f⁻¹ p)⁻¹ ⬝ ap f (left_inv f a) ⬝ p : by rewrite ap_inv
... = ap f ((ap f⁻¹ p)⁻¹ ⬝ left_inv f a) ⬝ p : by rewrite ap_con)))
definition is_contr_right_inverse : is_contr (Σ(g : B → A), f ∘ g ~ id) :=
begin
fapply is_trunc_equiv_closed,
{apply sigma_equiv_sigma_right, intro g, apply eq_equiv_homotopy},
fapply is_trunc_equiv_closed,
{apply fiber.sigma_char},
fapply is_contr_fiber_of_is_equiv,
apply (to_is_equiv (arrow_equiv_arrow_right B (equiv.mk f H))),
end
definition is_contr_right_coherence (u : Σ(g : B → A), f ∘ g ~ id)
: is_contr (Σ(η : u.1 ∘ f ~ id), Π(a : A), u.2 (f a) = ap f (η a)) :=
begin
fapply is_trunc_equiv_closed,
{apply equiv.symm, apply sigma_pi_equiv_pi_sigma},
fapply is_trunc_equiv_closed,
{apply pi_equiv_pi_right, intro a,
apply (fiber_eq_equiv (fiber.mk (u.1 (f a)) (u.2 (f a))) (fiber.mk a idp))},
end
omit H
protected definition sigma_char : (is_equiv f) ≃
(Σ(g : B → A) (ε : f ∘ g ~ id) (η : g ∘ f ~ id), Π(a : A), ε (f a) = ap f (η a)) :=
equiv.MK (λH, ⟨inv f, right_inv f, left_inv f, adj f⟩)
(λp, is_equiv.mk f p.1 p.2.1 p.2.2.1 p.2.2.2)
(λp, begin
induction p with p1 p2,
induction p2 with p21 p22,
induction p22 with p221 p222,
reflexivity
end)
(λH, by induction H; reflexivity)
protected definition sigma_char' : (is_equiv f) ≃
(Σ(u : Σ(g : B → A), f ∘ g ~ id) (η : u.1 ∘ f ~ id), Π(a : A), u.2 (f a) = ap f (η a)) :=
calc
(is_equiv f) ≃
(Σ(g : B → A) (ε : f ∘ g ~ id) (η : g ∘ f ~ id), Π(a : A), ε (f a) = ap f (η a))
: is_equiv.sigma_char
... ≃ (Σ(u : Σ(g : B → A), f ∘ g ~ id), Σ(η : u.1 ∘ f ~ id), Π(a : A), u.2 (f a) = ap f (η a))
: sigma_assoc_equiv (λu, Σ(η : u.1 ∘ f ~ id), Π(a : A), u.2 (f a) = ap f (η a))
local attribute is_contr_right_inverse [instance] [priority 1600]
local attribute is_contr_right_coherence [instance] [priority 1600]
theorem is_prop_is_equiv [instance] : is_prop (is_equiv f) :=
is_prop_of_imp_is_contr
(λ(H : is_equiv f), is_trunc_equiv_closed -2 (equiv.symm !is_equiv.sigma_char'))
definition inv_eq_inv {A B : Type} {f f' : A → B} {Hf : is_equiv f} {Hf' : is_equiv f'}
(p : f = f') : f⁻¹ = f'⁻¹ :=
apd011 inv p !is_prop.elimo
/- contractible fibers -/
definition is_contr_fun_of_is_equiv [H : is_equiv f] : is_contr_fun f :=
is_contr_fiber_of_is_equiv f
definition is_prop_is_contr_fun (f : A → B) : is_prop (is_contr_fun f) := _
definition is_equiv_of_is_contr_fun [H : is_contr_fun f] : is_equiv f :=
adjointify _ (λb, point (center (fiber f b)))
(λb, point_eq (center (fiber f b)))
(λa, ap point (center_eq (fiber.mk a idp)))
definition is_equiv_of_imp_is_equiv (H : B → is_equiv f) : is_equiv f :=
@is_equiv_of_is_contr_fun _ _ f (λb, @is_contr_fiber_of_is_equiv _ _ _ (H b) _)
definition is_equiv_equiv_is_contr_fun : is_equiv f ≃ is_contr_fun f :=
equiv_of_is_prop _ (λH, !is_equiv_of_is_contr_fun)
theorem inv_commute'_fn {A : Type} {B C : A → Type} (f : Π{a}, B a → C a) [H : Πa, is_equiv (@f a)]
{g : A → A} (h : Π{a}, B a → B (g a)) (h' : Π{a}, C a → C (g a))
(p : Π⦃a : A⦄ (b : B a), f (h b) = h' (f b)) {a : A} (b : B a) :
inv_commute' @f @h @h' p (f b)
= (ap f⁻¹ (p b))⁻¹ ⬝ left_inv f (h b) ⬝ (ap h (left_inv f b))⁻¹ :=
begin
rewrite [↑[inv_commute',eq_of_fn_eq_fn'],+ap_con,-adj_inv f,+con.assoc,inv_con_cancel_left,
adj f,+ap_inv,-+ap_compose,
eq_bot_of_square (natural_square_tr (λb, (left_inv f (h b))⁻¹ ⬝ ap f⁻¹ (p b)) (left_inv f b))⁻¹ʰ,
con_inv,inv_inv,+con.assoc],
do 3 apply whisker_left,
rewrite [con_inv_cancel_left,con.left_inv]
end
end is_equiv
/- Moving equivalences around in homotopies -/
namespace is_equiv
variables {A B C : Type} (f : A → B) [Hf : is_equiv f]
include Hf
section pre_compose
variables (α : A → C) (β : B → C)
-- homotopy_inv_of_homotopy_pre is in init.equiv
protected definition inv_homotopy_of_homotopy_pre.is_equiv
: is_equiv (inv_homotopy_of_homotopy_pre f α β) :=
adjointify _ (homotopy_of_inv_homotopy_pre f α β)
abstract begin
intro q, apply eq_of_homotopy, intro b,
unfold inv_homotopy_of_homotopy_pre,
unfold homotopy_of_inv_homotopy_pre,
apply inverse, apply eq_bot_of_square,
apply eq_hconcat (ap02 α (adj_inv f b)),
apply eq_hconcat (ap_compose α f⁻¹ (right_inv f b))⁻¹,
apply natural_square q (right_inv f b)
end end
abstract begin
intro p, apply eq_of_homotopy, intro a,
unfold inv_homotopy_of_homotopy_pre,
unfold homotopy_of_inv_homotopy_pre,
apply trans (con.assoc
(ap α (left_inv f a))⁻¹
(p (f⁻¹ (f a)))
(ap β (right_inv f (f a))))⁻¹,
apply inverse, apply eq_bot_of_square,
refine hconcat_eq _ (ap02 β (adj f a))⁻¹,
refine hconcat_eq _ (ap_compose β f (left_inv f a)),
apply natural_square p (left_inv f a)
end end
end pre_compose
section post_compose
variables (α : C → A) (β : C → B)
-- homotopy_inv_of_homotopy_post is in init.equiv
protected definition inv_homotopy_of_homotopy_post.is_equiv
: is_equiv (inv_homotopy_of_homotopy_post f α β) :=
adjointify _ (homotopy_of_inv_homotopy_post f α β)
abstract begin
intro q, apply eq_of_homotopy, intro c,
unfold inv_homotopy_of_homotopy_post,
unfold homotopy_of_inv_homotopy_post,
apply trans (whisker_right (left_inv f (α c))
(ap_con f⁻¹ (right_inv f (β c))⁻¹ (ap f (q c))
⬝ whisker_right (ap f⁻¹ (ap f (q c)))
(ap_inv f⁻¹ (right_inv f (β c))))),
apply inverse, apply eq_bot_of_square,
apply eq_hconcat (adj_inv f (β c))⁻¹,
apply eq_vconcat (ap_compose f⁻¹ f (q c))⁻¹,
refine vconcat_eq _ (ap_id (q c)),
apply natural_square_tr (left_inv f) (q c)
end end
abstract begin
intro p, apply eq_of_homotopy, intro c,
unfold inv_homotopy_of_homotopy_post,
unfold homotopy_of_inv_homotopy_post,
apply trans (whisker_left (right_inv f (β c))⁻¹
(ap_con f (ap f⁻¹ (p c)) (left_inv f (α c)))),
apply trans (con.assoc (right_inv f (β c))⁻¹ (ap f (ap f⁻¹ (p c)))
(ap f (left_inv f (α c))))⁻¹,
apply inverse, apply eq_bot_of_square,
refine hconcat_eq _ (adj f (α c)),
apply eq_vconcat (ap_compose f f⁻¹ (p c))⁻¹,
refine vconcat_eq _ (ap_id (p c)),
apply natural_square_tr (right_inv f) (p c)
end end
end post_compose
end is_equiv
namespace is_equiv
/- Theorem 4.7.7 -/
variables {A : Type} {P Q : A → Type}
variable (f : Πa, P a → Q a)
definition is_fiberwise_equiv [reducible] := Πa, is_equiv (f a)
definition is_equiv_total_of_is_fiberwise_equiv [H : is_fiberwise_equiv f] : is_equiv (total f) :=
is_equiv_sigma_functor id f
definition is_fiberwise_equiv_of_is_equiv_total [H : is_equiv (total f)]
: is_fiberwise_equiv f :=
begin
intro a,
apply is_equiv_of_is_contr_fun, intro q,
apply @is_contr_equiv_closed _ _ (fiber_total_equiv f q)
end
end is_equiv
namespace equiv
open is_equiv
variables {A B C : Type}
definition equiv_mk_eq {f f' : A → B} [H : is_equiv f] [H' : is_equiv f'] (p : f = f')
: equiv.mk f H = equiv.mk f' H' :=
apd011 equiv.mk p !is_prop.elimo
definition equiv_eq' {f f' : A ≃ B} (p : to_fun f = to_fun f') : f = f' :=
by (cases f; cases f'; apply (equiv_mk_eq p))
definition equiv_eq {f f' : A ≃ B} (p : to_fun f ~ to_fun f') : f = f' :=
by apply equiv_eq'; apply eq_of_homotopy p
definition trans_symm (f : A ≃ B) (g : B ≃ C) : (f ⬝e g)⁻¹ᵉ = g⁻¹ᵉ ⬝e f⁻¹ᵉ :> (C ≃ A) :=
equiv_eq' idp
definition symm_symm (f : A ≃ B) : f⁻¹ᵉ⁻¹ᵉ = f :> (A ≃ B) :=
equiv_eq' idp
protected definition equiv.sigma_char [constructor]
(A B : Type) : (A ≃ B) ≃ Σ(f : A → B), is_equiv f :=
begin
fapply equiv.MK,
{intro F, exact ⟨to_fun F, to_is_equiv F⟩},
{intro p, cases p with f H, exact (equiv.mk f H)},
{intro p, cases p, exact idp},
{intro F, cases F, exact idp},
end
definition equiv_eq_char (f f' : A ≃ B) : (f = f') ≃ (to_fun f = to_fun f') :=
calc
(f = f') ≃ (to_fun !equiv.sigma_char f = to_fun !equiv.sigma_char f')
: eq_equiv_fn_eq (to_fun !equiv.sigma_char)
... ≃ ((to_fun !equiv.sigma_char f).1 = (to_fun !equiv.sigma_char f').1 ) : equiv_subtype
... ≃ (to_fun f = to_fun f') : equiv.rfl
definition is_equiv_ap_to_fun (f f' : A ≃ B)
: is_equiv (ap to_fun : f = f' → to_fun f = to_fun f') :=
begin
fapply adjointify,
{intro p, cases f with f H, cases f' with f' H', cases p, apply ap (mk f'), apply is_prop.elim},
{intro p, cases f with f H, cases f' with f' H', cases p,
apply @concat _ _ (ap to_fun (ap (equiv.mk f') (is_prop.elim H H'))), {apply idp},
generalize is_prop.elim H H', intro q, cases q, apply idp},
{intro p, cases p, cases f with f H, apply ap (ap (equiv.mk f)), apply is_set.elim}
end
definition equiv_pathover {A : Type} {a a' : A} (p : a = a')
{B : A → Type} {C : A → Type} (f : B a ≃ C a) (g : B a' ≃ C a')
(r : Π(b : B a) (b' : B a') (q : b =[p] b'), f b =[p] g b') : f =[p] g :=
begin
fapply pathover_of_fn_pathover_fn,
{ intro a, apply equiv.sigma_char},
{ fapply sigma_pathover,
esimp, apply arrow_pathover, exact r,
apply is_prop.elimo}
end
definition is_contr_equiv (A B : Type) [HA : is_contr A] [HB : is_contr B] : is_contr (A ≃ B) :=
begin
apply @is_contr_of_inhabited_prop, apply is_prop.mk,
intro x y, cases x with fx Hx, cases y with fy Hy, generalize Hy,
apply (eq_of_homotopy (λ a, !eq_of_is_contr)) ▸ (λ Hy, !is_prop.elim ▸ rfl),
apply equiv_of_is_contr_of_is_contr
end
definition is_trunc_succ_equiv (n : trunc_index) (A B : Type)
[HA : is_trunc n.+1 A] [HB : is_trunc n.+1 B] : is_trunc n.+1 (A ≃ B) :=
@is_trunc_equiv_closed _ _ n.+1 (equiv.symm !equiv.sigma_char)
(@is_trunc_sigma _ _ _ _ (λ f, !is_trunc_succ_of_is_prop))
definition is_trunc_equiv (n : trunc_index) (A B : Type)
[HA : is_trunc n A] [HB : is_trunc n B] : is_trunc n (A ≃ B) :=
by cases n; apply !is_contr_equiv; apply !is_trunc_succ_equiv
definition eq_of_fn_eq_fn'_idp {A B : Type} (f : A → B) [is_equiv f] (x : A)
: eq_of_fn_eq_fn' f (idpath (f x)) = idpath x :=
!con.left_inv
definition eq_of_fn_eq_fn'_con {A B : Type} (f : A → B) [is_equiv f] {x y z : A}
(p : f x = f y) (q : f y = f z)
: eq_of_fn_eq_fn' f (p ⬝ q) = eq_of_fn_eq_fn' f p ⬝ eq_of_fn_eq_fn' f q :=
begin
unfold eq_of_fn_eq_fn',
refine _ ⬝ !con.assoc, apply whisker_right,
refine _ ⬝ !con.assoc⁻¹ ⬝ !con.assoc⁻¹, apply whisker_left,
refine !ap_con ⬝ _, apply whisker_left,
refine !con_inv_cancel_left⁻¹
end
end equiv
namespace pointed
open equiv is_equiv
definition pequiv_eq {A B : Type*} {p q : A ≃* B} (H : p = q :> (A →* B)) : p = q :=
begin
cases p with f Hf, cases q with g Hg, esimp at *,
exact apd011 pequiv_of_pmap H !is_prop.elimo
end
end pointed
|
49fbd439ef746fcfdbff5ebd70eb65e10b5a9f55 | ce89339993655da64b6ccb555c837ce6c10f9ef4 | /zeptometer/topprover/16.lean | 7ac6871112a0aea3918e1d2a39f6ff80deeb3823 | [] | no_license | zeptometer/LearnLean | ef32dc36a22119f18d843f548d0bb42f907bff5d | bb84d5dbe521127ba134d4dbf9559b294a80b9f7 | refs/heads/master | 1,625,710,824,322 | 1,601,382,570,000 | 1,601,382,570,000 | 195,228,870 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 465 | lean | inductive gcd : ℕ → ℕ → ℕ → Prop
| gcd_0 : ∀ n, gcd n 0 n
| gcd_step : ∀ n m p, gcd m n p → gcd (n + m) n p
| gcd_swap : ∀ n m p, gcd m n p → gcd n m p
example : forall n, gcd n (n + 1) 1 := begin
intros n,
apply gcd.gcd_swap,
apply gcd.gcd_step,
induction n,
apply gcd.gcd_0,
apply gcd.gcd_swap,
rw nat.succ_eq_add_one,
rw nat.add_comm n_n 1,
apply gcd.gcd_step,
apply gcd.gcd_swap,
assumption
end |
e04d3cbdeb959ae0efd7d89685c4c7676b7a125d | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/probability/conditional_probability.lean | 6fc49d21525362e0f6a1184f4ab753ce00789c1e | [
"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,772 | lean | /-
Copyright (c) 2022 Rishikesh Vaishnav. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rishikesh Vaishnav
-/
import measure_theory.measure.measure_space
/-!
# Conditional Probability
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines conditional probability and includes basic results relating to it.
Given some measure `μ` defined on a measure space on some type `Ω` and some `s : set Ω`,
we define the measure of `μ` conditioned on `s` as the restricted measure scaled by
the inverse of the measure of `s`: `cond μ s = (μ s)⁻¹ • μ.restrict s`. The scaling
ensures that this is a probability measure (when `μ` is a finite measure).
From this definition, we derive the "axiomatic" definition of conditional probability
based on application: for any `s t : set Ω`, we have `μ[t|s] = (μ s)⁻¹ * μ (s ∩ t)`.
## Main Statements
* `cond_cond_eq_cond_inter`: conditioning on one set and then another is equivalent
to conditioning on their intersection.
* `cond_eq_inv_mul_cond_mul`: Bayes' Theorem, `μ[t|s] = (μ s)⁻¹ * μ[s|t] * (μ t)`.
## Notations
This file uses the notation `μ[|s]` the measure of `μ` conditioned on `s`,
and `μ[t|s]` for the probability of `t` given `s` under `μ` (equivalent to the
application `μ[|s] t`).
These notations are contained in the locale `probability_theory`.
## Implementation notes
Because we have the alternative measure restriction application principles
`measure.restrict_apply` and `measure.restrict_apply'`, which require
measurability of the restricted and restricting sets, respectively,
many of the theorems here will have corresponding alternatives as well.
For the sake of brevity, we've chosen to only go with `measure.restrict_apply'`
for now, but the alternative theorems can be added if needed.
Use of `@[simp]` generally follows the rule of removing conditions on a measure
when possible.
Hypotheses that are used to "define" a conditional distribution by requiring that
the conditioning set has non-zero measure should be named using the abbreviation
"c" (which stands for "conditionable") rather than "nz". For example `(hci : μ (s ∩ t) ≠ 0)`
(rather than `hnzi`) should be used for a hypothesis ensuring that `μ[|s ∩ t]` is defined.
## Tags
conditional, conditioned, bayes
-/
noncomputable theory
open_locale ennreal
open measure_theory measurable_space
variables {Ω : Type*} {m : measurable_space Ω} (μ : measure Ω) {s t : set Ω}
namespace probability_theory
section definitions
/-- The conditional probability measure of measure `μ` on set `s` is `μ` restricted to `s`
and scaled by the inverse of `μ s` (to make it a probability measure):
`(μ s)⁻¹ • μ.restrict s`. -/
def cond (s : set Ω) : measure Ω :=
(μ s)⁻¹ • μ.restrict s
end definitions
localized "notation (name := probability_theory.cond)
μ `[` s `|` t `]` := probability_theory.cond μ t s" in probability_theory
localized "notation (name := probability_theory.cond_fn)
μ `[|`:60 t`]` := probability_theory.cond μ t" in probability_theory
/-- The conditional probability measure of any finite measure on any set of positive measure
is a probability measure. -/
lemma cond_is_probability_measure [is_finite_measure μ] (hcs : μ s ≠ 0) :
is_probability_measure $ μ[|s] :=
⟨by { rw [cond, measure.smul_apply, measure.restrict_apply measurable_set.univ,
set.univ_inter], exact ennreal.inv_mul_cancel hcs (measure_ne_top _ s) }⟩
section bayes
@[simp] lemma cond_empty : μ[|∅] = 0 :=
by simp [cond]
@[simp] lemma cond_univ [is_probability_measure μ] :
μ[|set.univ] = μ :=
by simp [cond, measure_univ, measure.restrict_univ]
/-- The axiomatic definition of conditional probability derived from a measure-theoretic one. -/
lemma cond_apply (hms : measurable_set s) (t : set Ω) :
μ[t|s] = (μ s)⁻¹ * μ (s ∩ t) :=
by { rw [cond, measure.smul_apply, measure.restrict_apply' hms, set.inter_comm], refl }
lemma cond_inter_self (hms : measurable_set s) (t : set Ω) :
μ[s ∩ t|s] = μ[t|s] :=
by rw [cond_apply _ hms, ← set.inter_assoc, set.inter_self, ← cond_apply _ hms]
lemma inter_pos_of_cond_ne_zero (hms : measurable_set s) (hcst : μ[t|s] ≠ 0) :
0 < μ (s ∩ t) :=
begin
refine pos_iff_ne_zero.mpr (right_ne_zero_of_mul _),
{ exact (μ s)⁻¹ },
convert hcst,
simp [hms, set.inter_comm]
end
lemma cond_pos_of_inter_ne_zero [is_finite_measure μ]
(hms : measurable_set s) (hci : μ (s ∩ t) ≠ 0) :
0 < μ[|s] t :=
begin
rw cond_apply _ hms,
refine ennreal.mul_pos _ hci,
exact ennreal.inv_ne_zero.mpr (measure_ne_top _ _),
end
lemma cond_cond_eq_cond_inter'
(hms : measurable_set s) (hmt : measurable_set t) (hcs : μ s ≠ ∞) (hci : μ (s ∩ t) ≠ 0) :
μ[|s][|t] = μ[|s ∩ t] :=
begin
have hcs : μ s ≠ 0 := (μ.to_outer_measure.pos_of_subset_ne_zero
(set.inter_subset_left _ _) hci).ne',
ext u,
simp [*, hms.inter hmt, cond_apply, ← mul_assoc, ← set.inter_assoc,
ennreal.mul_inv, mul_comm, ← mul_assoc, ennreal.inv_mul_cancel],
end
/-- Conditioning first on `s` and then on `t` results in the same measure as conditioning
on `s ∩ t`. -/
lemma cond_cond_eq_cond_inter [is_finite_measure μ]
(hms : measurable_set s) (hmt : measurable_set t) (hci : μ (s ∩ t) ≠ 0) :
μ[|s][|t] = μ[|s ∩ t] :=
cond_cond_eq_cond_inter' μ hms hmt (measure_ne_top μ s) hci
lemma cond_mul_eq_inter'
(hms : measurable_set s) (hcs : μ s ≠ 0) (hcs' : μ s ≠ ∞) (t : set Ω) :
μ[t|s] * μ s = μ (s ∩ t) :=
by rw [cond_apply μ hms t, mul_comm, ←mul_assoc,
ennreal.mul_inv_cancel hcs hcs', one_mul]
lemma cond_mul_eq_inter [is_finite_measure μ]
(hms : measurable_set s) (hcs : μ s ≠ 0) (t : set Ω) :
μ[t|s] * μ s = μ (s ∩ t) :=
cond_mul_eq_inter' μ hms hcs (measure_ne_top _ s) t
/-- A version of the law of total probability. -/
lemma cond_add_cond_compl_eq [is_finite_measure μ]
(hms : measurable_set s) (hcs : μ s ≠ 0) (hcs' : μ sᶜ ≠ 0) :
μ[t|s] * μ s + μ[t|sᶜ] * μ sᶜ = μ t :=
begin
rw [cond_mul_eq_inter μ hms hcs, cond_mul_eq_inter μ hms.compl hcs', set.inter_comm _ t,
set.inter_comm _ t],
exact measure_inter_add_diff t hms,
end
/-- **Bayes' Theorem** -/
theorem cond_eq_inv_mul_cond_mul [is_finite_measure μ]
(hms : measurable_set s) (hmt : measurable_set t) :
μ[t|s] = (μ s)⁻¹ * μ[s|t] * (μ t) :=
begin
by_cases ht : μ t = 0,
{ simp [cond, ht, measure.restrict_apply hmt, or.inr (measure_inter_null_of_null_left s ht)] },
{ rw [mul_assoc, cond_mul_eq_inter μ hmt ht s, set.inter_comm, cond_apply _ hms] }
end
end bayes
end probability_theory
|
c5431a533272a2f5b9dbd42062e2966a27e2649c | 491068d2ad28831e7dade8d6dff871c3e49d9431 | /tests/lean/run/parity.lean | c5664ea347e9c6e24c17a74ac9a82d7e33dd01f2 | [
"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 | 676 | lean | import data.nat
open nat
namespace foo
inductive Parity : nat → Type :=
| even : ∀ n : nat, Parity (2 * n)
| odd : ∀ n : nat, Parity (2 * n + 1)
open Parity
definition parity : Π (n : nat), Parity n
| parity 0 := even 0
| parity (n+1) :=
begin
have aux : Parity n, from parity n,
cases aux with [k, k],
begin
apply (Parity.odd k)
end,
begin
change (Parity (2*k + 2*1)),
rewrite -mul.left_distrib,
apply (Parity.even (k+1))
end
end
print definition parity
definition half (n : nat) : nat :=
match ⟨n, parity n⟩ with
| ⟨⌞2 * k⌟, even k⟩ := k
| ⟨⌞2 * k + 1⌟, odd k⟩ := k
end
end foo
|
e6fad2c5f4f5e6f67311a98be7496b019e1460ca | 5c7fe6c4a9d4079b5457ffa5f061797d42a1cd65 | /src/exercises/src_07_existential_quantification.lean | fb2425f6ea7691e65cbf73cf65820da8527fd2c1 | [] | no_license | gihanmarasingha/mth1001_tutorial | 8e0817feeb96e7c1bb3bac49b63e3c9a3a329061 | bb277eebd5013766e1418365b91416b406275130 | refs/heads/master | 1,675,008,746,310 | 1,607,993,443,000 | 1,607,993,443,000 | 321,511,270 | 3 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,910 | lean | import tactic.linarith
namespace mth1001
section existential_quantification
/-
An integer `n` is `even` if there is some integer `m` such that `n = 2*m`. This condition is
expressed as
`∃ m, n = 2 * m`,
where the symbol `∃` is called 'the universal quantifier', read as 'there exists' or 'there is',
and typed as `\ex`.
-/
/-
The following is a Lean representation of the above definition.
-/
def even (n : ℤ) := ∃ m, n = 2*m
/-
To *prove* a particular number `n` is even, it suffices to provide an intger `m` and then
show that `n = 2 *m ` holds.
-/
/-
Below, the goal is initially to show `∃ m, 10 = 2 *m`. The tactic `use 5` removes the
universal quantifier and replaces `m` with `5`, leaving the goal `10 = 2 * 5`.
The tactic `norm_num` closes goals that involve simple arithmetic on numerical expressions.
-/
example : even 10 :=
begin
use 5,
norm_num,
end
-- Exercise 039:
example : even 18 :=
begin
sorry
end
/-
We aren't restricted to using numerical expressions. As seen in a previous section, the
`linarith` tactic solves linear equations and inequalities.
-/
variables a b c d : ℤ
example (h : b = 6 * a) : even b :=
begin
use (3*a), -- After this tactic, the goal is to prove `b = 2 * (3 * a)`.
linarith, -- This tactic closes the goal.
end
-- Exercise 040:
example (h₁ : c = 2 * a + 1) (h₂ : d = 2 * b + 1) : even (c + d) :=
begin
sorry
end
/-
An integer `n` is `odd` if `∃ m, n = 2 * m + 1`.
-/
def odd (n : ℤ) := ∃ m, n = 2 * m + 1
-- Exercise 041:
example : odd 7 :=
begin
sorry
end
-- Exercise 042:
example (h₁ : c = 2 * a) (h₂ : d = 2 * b + 1) : odd (c + d) :=
begin
sorry
end
/-
We've seen how to *prove* a number is even or even. Now we'll see how to *apply* the fact that
a number is even or even.
Given a premise `h : even a`, the tactic `cases h with k hk` removes `h` and introduces into the
context a new variable `k` and the premise `hk : a = 2 * k`. As usual, there is nothing special
about the names `k` or `hk`.
-/
example (h : even a) : even (5*a) :=
begin
cases h with k hk,
use (5*k),
linarith,
end
-- Exercise 043:
-- Prove that the square of an even number is even.
example (h : even a) : even (a*a) :=
begin
sorry
end
-- Exercise 044:
-- Prove that the sum of two odd numbers is even.
example (h₁ : odd a) (h₂ : odd b) : even (a + b) :=
begin
sorry
end
-- Exercise 045:
/-
The results of this section can be rewritten to remove any premises, producing statements
that involve implication.
For example, you should only need to add one line to the beginning of a previous proof to
conclude the following.
-/
example : even a → even (a*a) :=
begin
sorry
end
end existential_quantification
/-
SUMMARY:
* Definitions in Lean.
* Recap of the `norm_num` and `linarith` tactics.
* Introduction of `∃` via `use`.
* Elimination of `∃` via `cases`.
-/
end mth1001
|
5a004cdc0ea90f78d0b996166c3ef1cd7ccbcb72 | df7bb3acd9623e489e95e85d0bc55590ab0bc393 | /lean/love03_forward_proofs_exercise_sheet.lean | 84f939941c7ecf83dc79109b01c63f01aec81311 | [] | no_license | MaschavanderMarel/logical_verification_2020 | a41c210b9237c56cb35f6cd399e3ac2fe42e775d | 7d562ef174cc6578ca6013f74db336480470b708 | refs/heads/master | 1,692,144,223,196 | 1,634,661,675,000 | 1,634,661,675,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,792 | lean | import .lovelib
/- # LoVe Exercise 3: Forward Proofs -/
set_option pp.beta true
set_option pp.generalized_field_notation false
namespace LoVe
/- ## Question 1: Connectives and Quantifiers
1.1. Supply structured proofs of the following lemmas. -/
lemma I (a : Prop) :
a → a :=
sorry
lemma K (a b : Prop) :
a → b → b :=
sorry
lemma C (a b c : Prop) :
(a → b → c) → b → a → c :=
sorry
lemma proj_1st (a : Prop) :
a → a → a :=
sorry
/- Please give a different answer than for `proj_1st`. -/
lemma proj_2nd (a : Prop) :
a → a → a :=
sorry
lemma some_nonsense (a b c : Prop) :
(a → b → c) → a → (a → c) → b → c :=
sorry
/- 1.2. Supply a structured proof of the contraposition rule. -/
lemma contrapositive (a b : Prop) :
(a → b) → ¬ b → ¬ a :=
sorry
/- 1.3. Supply a structured proof of the distributivity of `∀` over `∧`. -/
lemma forall_and {α : Type} (p q : α → Prop) :
(∀x, p x ∧ q x) ↔ (∀x, p x) ∧ (∀x, q x) :=
sorry
/- 1.4. Reuse, if possible, the lemma `forall_and` you proved above to prove
the following instance of the lemma. -/
lemma forall_and_inst {α : Type} (r s : α → α → Prop) :
(∀x, r x x ∧ s x x) ↔ (∀x, r x x) ∧ (∀x, s x x) :=
sorry
/- ## Question 2: Chain of Equalities
2.1. Write the following proof using `calc`.
`(a + b) * (a + b)`
`= a * (a + b) + b * (a + b)`
`= a * a + a * b + b * a + b * b`
`= a * a + a * b + a * b + b * b`
`= a * a + 2 * a * b + b * b`
Hint: You might need the tactics `simp` and `cc` and the lemmas `mul_add`,
`add_mul`, and `two_mul`. -/
lemma binomial_square (a b : ℕ) :
(a + b) * (a + b) = a * a + 2 * a * b + b * b :=
sorry
/- 2.2. Prove the same argument again, this time as a structured proof. Try to
reuse as much of the above proof idea as possible. -/
lemma binomial_square₂ (a b : ℕ) :
(a + b) * (a + b) = a * a + 2 * a * b + b * b :=
sorry
/- 2.3. Prove the same lemma again, this time using tactics. -/
lemma binomial_square₃ (a b : ℕ) :
(a + b) * (a + b) = a * a + 2 * a * b + b * b :=
begin
sorry
end
/- ## Question 3 (**optional**): One-Point Rules
3.1 (**optional**). Prove that the following wrong formulation of the one-point
rule for `∀` is inconsistent, using a structured proof. -/
axiom forall.one_point_wrong {α : Type} {t : α} {p : α → Prop} :
(∀x : α, x = t ∧ p x) ↔ p t
lemma proof_of_false :
false :=
sorry
/- 3.2 (**optional**). Prove that the following wrong formulation of the
one-point rule for `∃` is inconsistent, using a tactical or structured proof. -/
axiom exists.one_point_wrong {α : Type} {t : α} {p : α → Prop} :
(∃x : α, x = t → p x) ↔ p t
lemma proof_of_false₂ :
false :=
sorry
end LoVe
|
f0ce1a69aa63520ddac132224ab2d267508fb494 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Compiler/IR/EmitUtil.lean | e5d0b1087c6a9543360f06bd85d9c9b73c98bb4f | [
"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 | 3,177 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Compiler.InitAttr
import Lean.Compiler.IR.CompilerM
/-! # Helper functions for backend code generators -/
namespace Lean.IR
/-- Return true iff `b` is of the form `let x := g ys; ret x` -/
def isTailCallTo (g : Name) (b : FnBody) : Bool :=
match b with
| FnBody.vdecl x _ (Expr.fap f _) (FnBody.ret (Arg.var y)) => x == y && f == g
| _ => false
def usesModuleFrom (env : Environment) (modulePrefix : Name) : Bool :=
env.allImportedModuleNames.toList.any fun modName => modulePrefix.isPrefixOf modName
namespace CollectUsedDecls
abbrev M := ReaderT Environment (StateM NameSet)
@[inline] def collect (f : FunId) : M Unit :=
modify fun s => s.insert f
partial def collectFnBody : FnBody → M Unit
| .vdecl _ _ v b =>
match v with
| .fap f _ => collect f *> collectFnBody b
| .pap f _ => collect f *> collectFnBody b
| _ => collectFnBody b
| .jdecl _ _ v b => collectFnBody v *> collectFnBody b
| .case _ _ _ alts => alts.forM fun alt => collectFnBody alt.body
| e => do unless e.isTerminal do collectFnBody e.body
def collectInitDecl (fn : Name) : M Unit := do
let env ← read
match getInitFnNameFor? env fn with
| some initFn => collect initFn
| _ => pure ()
def collectDecl : Decl → M NameSet
| .fdecl (f := f) (body := b) .. => collectInitDecl f *> CollectUsedDecls.collectFnBody b *> get
| .extern (f := f) .. => collectInitDecl f *> get
end CollectUsedDecls
def collectUsedDecls (env : Environment) (decl : Decl) (used : NameSet := {}) : NameSet :=
(CollectUsedDecls.collectDecl decl env).run' used
abbrev VarTypeMap := HashMap VarId IRType
abbrev JPParamsMap := HashMap JoinPointId (Array Param)
namespace CollectMaps
abbrev Collector := (VarTypeMap × JPParamsMap) → (VarTypeMap × JPParamsMap)
@[inline] def collectVar (x : VarId) (t : IRType) : Collector
| (vs, js) => (vs.insert x t, js)
def collectParams (ps : Array Param) : Collector :=
fun s => ps.foldl (fun s p => collectVar p.x p.ty s) s
@[inline] def collectJP (j : JoinPointId) (xs : Array Param) : Collector
| (vs, js) => (vs, js.insert j xs)
/-- `collectFnBody` assumes the variables in -/
partial def collectFnBody : FnBody → Collector
| .vdecl x t _ b => collectVar x t ∘ collectFnBody b
| .jdecl j xs v b => collectJP j xs ∘ collectParams xs ∘ collectFnBody v ∘ collectFnBody b
| .case _ _ _ alts => fun s => alts.foldl (fun s alt => collectFnBody alt.body s) s
| e => if e.isTerminal then id else collectFnBody e.body
def collectDecl : Decl → Collector
| .fdecl (xs := xs) (body := b) .. => collectParams xs ∘ collectFnBody b
| _ => id
end CollectMaps
/-- Return a pair `(v, j)`, where `v` is a mapping from variable/parameter to type,
and `j` is a mapping from join point to parameters.
This function assumes `d` has normalized indexes (see `normids.lean`). -/
def mkVarJPMaps (d : Decl) : VarTypeMap × JPParamsMap :=
CollectMaps.collectDecl d ({}, {})
end IR
end Lean
|
6ed57b3ee421eda6f072471138f114832837b4db | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/data/list/basic.lean | b1c895ff94181c9c036d4ac3c5d2bccf995661c9 | [
"Apache-2.0"
] | permissive | gebner/mathlib | eab0150cc4f79ec45d2016a8c21750244a2e7ff0 | cc6a6edc397c55118df62831e23bfbd6e6c6b4ab | refs/heads/master | 1,625,574,853,976 | 1,586,712,827,000 | 1,586,712,827,000 | 99,101,412 | 1 | 0 | Apache-2.0 | 1,586,716,389,000 | 1,501,667,958,000 | Lean | UTF-8 | Lean | false | false | 141,573 | 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
tactic.interactive
logic.basic logic.function
algebra.group order.basic
data.list.defs data.nat.basic data.option.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 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)
theorem cons_inj {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' :=
⟨λ e, cons_inj e, congr_arg _⟩
/- 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 eq_or_ne_mem_of_mem {a b : α} {l : list α} (h : a ∈ b :: l) : a = b ∨ (a ≠ b ∧ a ∈ l) :=
classical.by_cases or.inl $ assume : a ≠ b, h.elim or.inl $ assume h, or.inr ⟨this, h⟩
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_inj {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 _⟩
@[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]
/- length -/
theorem length_eq_zero {l : list α} : length l = 0 ↔ l = [] :=
⟨eq_nil_of_length_eq_zero, λ h, h.symm ▸ 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⟩
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⟩
lemma injective_length_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
lemma injective_length [subsingleton α] : injective (length : list α → ℕ) :=
injective_length_iff.mpr $ by apply_instance
/- set-theoretic notation of lists -/
lemma empty_eq : (∅ : list α) = [] := by refl
lemma singleton_eq [decidable_eq α] (x : α) : ({x} : list α) = [x] := by refl
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 α) = [y, x] :=
by { rw [insert_neg, singleton_eq], show y ∉ [x], rw [mem_singleton], exact h.symm }
/- bounded quantifiers over lists -/
theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x.
@[simp] theorem forall_mem_cons' {p : α → Prop} {a : α} {l : list α} :
(∀ (x : α), x = a ∨ x ∈ l → p x) ↔ p a ∧ ∀ x ∈ l, p x :=
by simp only [or_imp_distrib, forall_and_distrib, forall_eq]
theorem forall_mem_cons {p : α → Prop} {a : α} {l : list α} :
(∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x :=
by simp only [mem_cons_iff, forall_mem_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
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_left {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_right {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_left' {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_right' {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_left h rfl
theorem append_right_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ :=
append_inj_right' h rfl
theorem append_left_inj {t₁ t₂ : list α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ :=
⟨append_left_cancel, congr_arg _⟩
theorem append_right_inj {s₁ s₂ : list α} (t) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ :=
⟨append_right_cancel, congr_arg _⟩
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
/- join -/
attribute [simp] join
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]]
lemma join_join (l : list (list (list α))) : l.join.join = (l.map join).join :=
by { induction l, simp, simp [l_ih] }
/- repeat -/
@[simp] theorem repeat_succ (a : α) (n) : repeat a (n + 1) = a :: repeat a n := rfl
theorem eq_of_mem_repeat {a b : α} : ∀ {n}, b ∈ repeat a n → b = a
| (n+1) h := or.elim h id $ @eq_of_mem_repeat _
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]]
/- 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
@[simp] theorem bind_append (f : α → list β) (l₁ l₂ : list α) :
(l₁ ++ l₂).bind f = l₁.bind f ++ l₂.bind f :=
append_bind _ _ _
/- 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 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]]
@[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l :=
by induction l; [refl, simp only [*, reverse_cons, reverse_append]]; refl
theorem reverse_injective : injective (@reverse α) :=
injective_of_left_inverse reverse_reverse
@[simp] theorem reverse_inj {l₁ l₂ : list α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ :=
reverse_injective.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)⟩
@[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
/- 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 last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) :
last l₁ h₁ = last l₂ h₂ :=
by subst l₁
/- head(') and tail -/
theorem head_eq_head' [inhabited α] (l : list α) : head l = (head' l).iget :=
by cases l; refl
@[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 cons_head_tail [inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l :=
by {induction l, contradiction, refl}
/- 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 append_sublist_append_of_sublist_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 reverse_sublist {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 append_sublist_append_of_sublist_right ih [a] }
end
@[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ :=
⟨λ h, by have := reverse_sublist h; simp only [reverse_reverse] at this; assumption, reverse_sublist⟩
@[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ :=
⟨λ h, by have := reverse_sublist h; simp only [reverse_append, append_sublist_append_left, reverse_sublist_iff] at this; assumption,
λ h, append_sublist_append_of_sublist_right h l⟩
theorem append_sublist_append {l₁ l₂ r₁ r₂ : list α}
(hl : l₁ <+ l₂) (hr : r₁ <+ r₂) : l₁ ++ r₁ <+ l₂ ++ r₂ :=
(append_sublist_append_of_sublist_right hl _).trans
((append_sublist_append_left _).2 hr)
theorem subset_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂
| ._ ._ sublist.slnil b h := h
| ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (subset_of_sublist 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 _ (subset_of_sublist s h)
end
theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l :=
⟨λ h, subset_of_sublist h (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 $ subset_of_sublist s
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, 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 _⟩
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
@[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 _ _
@[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₂ := (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 < n) :
(list.repeat a n).nth_le m (by rwa list.length_repeat) = 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 le_add_right _ _),
by rw [nth_le_nth hn, nth_le_nth hn', nth_le_append]
lemma last_eq_nth_le : ∀ (l : list α) (h : l ≠ []),
last l h = l.nth_le (l.length - 1) (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 = a
| [] a := rfl
| (b::l) a := by rw [cons_append, length_cons, nth, nth_concat_length]
@[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 (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 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 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_nil (a : α) : insert_nth 0 a [] = [a] := 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 → m ≥ n →
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
end insert_nth
/- map -/
@[simp] lemma map_nil (f : α → β) : map f [] = [] := rfl
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
@[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_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]] }
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 injective_map_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
/- 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
/- 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 [min_zero, take_zero, take_nil]
| 0 m l := by rw [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
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], }
@[simp] theorem drop_nil : ∀ n, drop n [] = ([] : list α)
| 0 := rfl
| (n+1) := rfl
@[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)]
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)]
@[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]
@[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
/- scanl -/
lemma length_scanl {β : Type*} {f : α → β → α} :
∀ a l, length (scanl f a l) = l.length + 1
| a [] := rfl
| a (x :: l) := by erw [length_cons, length_cons, length_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 -/
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
variables [is_lawful_monad m]
@[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, 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, 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, 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]]
@[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 : α → β) [is_monoid_hom f] :
(l.map f).prod = f l.prod :=
by { simp only [prod, foldl_map, (is_monoid_hom.map_one f).symm],
exact l.foldl_hom _ _ _ 1 (is_monoid_hom.map_mul f) }
-- `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, }, }
end monoid
@[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], }
/-- 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, }, }
-- 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 the previous, 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 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_semiring α] {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 [decidable_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 [decidable_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
-- 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, refl, }, { 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]
/- lexicographic ordering -/
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 ne_iff {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 _) },
{ cases classical.em (a = b) with ab ab,
{ subst b, apply cons,
exact IH (le_of_succ_le_succ H) (mt (congr_arg _) h) },
{ exact rel ab } }
end⟩
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 _
instance [decidable_linear_order α] : decidable_linear_order (list α) :=
decidable_linear_order_of_STO' (lex (<))
/- 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 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_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
/- 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
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 filter_map_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 map_sublist_map (f : α → β) {l₁ l₂ : list α}
(s : l₁ <+ l₂) : map f l₁ <+ map f l₂ :=
by rw ← filter_map_eq_map; exact filter_map_sublist_filter_map _ s
/- filter -/
section filter
variables {p : α → Prop} [decidable_pred p]
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 :=
subset_of_sublist $ filter_sublist l
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]
theorem filter_sublist_filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ :=
by rw ← filter_map_eq_filter; exact filter_map_sublist_filter_map _ s
theorem filter_of_map (f : β → α) (l) : 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 (p : α → Prop) [decidable_pred p] : ∀ (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 (p : α → Prop) [decidable_pred p] : ∀ (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 (p : α → Prop) [decidable_pred p] : 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 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 :=
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⟩
@[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))
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
theorem eq_nil_of_prefix_nil {l : list α} (s : l <+: []) : l = [] :=
eq_nil_of_infix_nil $ infix_of_prefix s
theorem eq_nil_of_suffix_nil {l : list α} (s : l <:+ []) : l = [] :=
eq_nil_of_infix_nil $ infix_of_suffix s
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 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_left_inj {l₁ l₂ : list α} (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ :=
exists_congr $ λ r, by rw [append_assoc, append_left_inj]
theorem prefix_cons_inj {l₁ l₂ : list α} (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ :=
prefix_append_left_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 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
@[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⟩
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⟩⟩
/- sublists -/
@[simp] theorem sublists'_nil : sublists' (@nil α) = [[]] := rfl
@[simp, priority 1100] theorem sublists'_singleton (a : α) : sublists' [a] = [[], [a]] := rfl
theorem map_sublists'_aux (g : list β → list γ) (l : list α) (f r) :
map g (sublists'_aux l f r) = sublists'_aux l (g ∘ f) (map g r) :=
by induction l generalizing f r; [refl, simp only [*, sublists'_aux]]
theorem sublists'_aux_append (r' : list (list β)) (l : list α) (f r) :
sublists'_aux l f (r ++ r') = sublists'_aux l f r ++ r' :=
by induction l generalizing f r; [refl, simp only [*, sublists'_aux]]
theorem sublists'_aux_eq_sublists' (l f r) :
@sublists'_aux α β l f r = map f (sublists' l) ++ r :=
by rw [sublists', map_sublists'_aux, ← sublists'_aux_append]; refl
@[simp] theorem sublists'_cons (a : α) (l : list α) :
sublists' (a :: l) = sublists' l ++ map (cons a) (sublists' l) :=
by rw [sublists', sublists'_aux]; simp only [sublists'_aux_eq_sublists', map_id, append_nil]; refl
@[simp] theorem mem_sublists' {s t : list α} : s ∈ sublists' t ↔ s <+ t :=
begin
induction t with a t IH generalizing s,
{ simp only [sublists'_nil, mem_singleton],
exact ⟨λ h, by rw h, eq_nil_of_sublist_nil⟩ },
simp only [sublists'_cons, mem_append, IH, mem_map],
split; intro h, rcases h with h | ⟨s, h, rfl⟩,
{ exact sublist_cons_of_sublist _ h },
{ exact cons_sublist_cons _ h },
{ cases h with _ _ _ h s _ _ h,
{ exact or.inl h },
{ exact or.inr ⟨s, h, rfl⟩ } }
end
@[simp] theorem length_sublists' : ∀ l : list α, length (sublists' l) = 2 ^ length l
| [] := rfl
| (a::l) := by simp only [sublists'_cons, length_append, length_sublists' l, length_map,
length, pow_succ, mul_succ, mul_zero, zero_add]
@[simp] theorem sublists_nil : sublists (@nil α) = [[]] := rfl
@[simp] theorem sublists_singleton (a : α) : sublists [a] = [[], [a]] := rfl
theorem sublists_aux₁_eq_sublists_aux : ∀ l (f : list α → list β),
sublists_aux₁ l f = sublists_aux l (λ ys r, f ys ++ r)
| [] f := rfl
| (a::l) f := by rw [sublists_aux₁, sublists_aux]; simp only [*, append_assoc]
theorem sublists_aux_cons_eq_sublists_aux₁ (l : list α) :
sublists_aux l cons = sublists_aux₁ l (λ x, [x]) :=
by rw [sublists_aux₁_eq_sublists_aux]; refl
theorem sublists_aux_eq_foldr.aux {a : α} {l : list α}
(IH₁ : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons))
(IH₂ : ∀ (f : list α → list (list α) → list (list α)),
sublists_aux l f = foldr f [] (sublists_aux l cons))
(f : list α → list β → list β) : sublists_aux (a::l) f = foldr f [] (sublists_aux (a::l) cons) :=
begin
simp only [sublists_aux, foldr_cons], rw [IH₂, IH₁], congr' 1,
induction sublists_aux l cons with _ _ ih, {refl},
simp only [ih, foldr_cons]
end
theorem sublists_aux_eq_foldr (l : list α) : ∀ (f : list α → list β → list β),
sublists_aux l f = foldr f [] (sublists_aux l cons) :=
suffices _ ∧ ∀ f : list α → list (list α) → list (list α),
sublists_aux l f = foldr f [] (sublists_aux l cons),
from this.1,
begin
induction l with a l IH, {split; intro; refl},
exact ⟨sublists_aux_eq_foldr.aux IH.1 IH.2,
sublists_aux_eq_foldr.aux IH.2 IH.2⟩
end
theorem sublists_aux_cons_cons (l : list α) (a : α) :
sublists_aux (a::l) cons = [a] :: foldr (λys r, ys :: (a :: ys) :: r) [] (sublists_aux l cons) :=
by rw [← sublists_aux_eq_foldr]; refl
theorem sublists_aux₁_append : ∀ (l₁ l₂ : list α) (f : list α → list β),
sublists_aux₁ (l₁ ++ l₂) f = sublists_aux₁ l₁ f ++
sublists_aux₁ l₂ (λ x, f x ++ sublists_aux₁ l₁ (f ∘ (++ x)))
| [] l₂ f := by simp only [sublists_aux₁, nil_append, append_nil]
| (a::l₁) l₂ f := by simp only [sublists_aux₁, cons_append, sublists_aux₁_append l₁, append_assoc]; refl
theorem sublists_aux₁_concat (l : list α) (a : α) (f : list α → list β) :
sublists_aux₁ (l ++ [a]) f = sublists_aux₁ l f ++
f [a] ++ sublists_aux₁ l (λ x, f (x ++ [a])) :=
by simp only [sublists_aux₁_append, sublists_aux₁, append_assoc, append_nil]
theorem sublists_aux₁_bind : ∀ (l : list α)
(f : list α → list β) (g : β → list γ),
(sublists_aux₁ l f).bind g = sublists_aux₁ l (λ x, (f x).bind g)
| [] f g := rfl
| (a::l) f g := by simp only [sublists_aux₁, bind_append, sublists_aux₁_bind l]
theorem sublists_aux_cons_append (l₁ l₂ : list α) :
sublists_aux (l₁ ++ l₂) cons = sublists_aux l₁ cons ++
(do x ← sublists_aux l₂ cons, (++ x) <$> sublists l₁) :=
begin
simp only [sublists, sublists_aux_cons_eq_sublists_aux₁, sublists_aux₁_append, bind_eq_bind, sublists_aux₁_bind],
congr, funext x, apply congr_arg _,
rw [← bind_ret_eq_map, sublists_aux₁_bind], exact (append_nil _).symm
end
theorem sublists_append (l₁ l₂ : list α) :
sublists (l₁ ++ l₂) = (do x ← sublists l₂, (++ x) <$> sublists l₁) :=
by simp only [map, sublists, sublists_aux_cons_append, map_eq_map, bind_eq_bind,
cons_bind, map_id', append_nil, cons_append, map_id' (λ _, rfl)]; split; refl
@[simp] theorem sublists_concat (l : list α) (a : α) :
sublists (l ++ [a]) = sublists l ++ map (λ x, x ++ [a]) (sublists l) :=
by rw [sublists_append, sublists_singleton, bind_eq_bind, cons_bind, cons_bind, nil_bind,
map_eq_map, map_eq_map, map_id' (append_nil), append_nil]
theorem sublists_reverse (l : list α) : sublists (reverse l) = map reverse (sublists' l) :=
by induction l with hd tl ih; [refl,
simp only [reverse_cons, sublists_append, sublists'_cons, map_append, ih, sublists_singleton,
map_eq_map, bind_eq_bind, map_map, cons_bind, append_nil, nil_bind, (∘)]]
theorem sublists_eq_sublists' (l : list α) : sublists l = map reverse (sublists' (reverse l)) :=
by rw [← sublists_reverse, reverse_reverse]
theorem sublists'_reverse (l : list α) : sublists' (reverse l) = map reverse (sublists l) :=
by simp only [sublists_eq_sublists', map_map, map_id' (reverse_reverse)]
theorem sublists'_eq_sublists (l : list α) : sublists' l = map reverse (sublists (reverse l)) :=
by rw [← sublists'_reverse, reverse_reverse]
theorem sublists_aux_ne_nil : ∀ (l : list α), [] ∉ sublists_aux l cons
| [] := id
| (a::l) := begin
rw [sublists_aux_cons_cons],
refine not_mem_cons_of_ne_of_not_mem (cons_ne_nil _ _).symm _,
have := sublists_aux_ne_nil l, revert this,
induction sublists_aux l cons; intro, {rwa foldr},
simp only [foldr, mem_cons_iff, false_or, not_or_distrib],
exact ⟨ne_of_not_mem_cons this, ih (not_mem_of_not_mem_cons this)⟩
end
@[simp] theorem mem_sublists {s t : list α} : s ∈ sublists t ↔ s <+ t :=
by rw [← reverse_sublist_iff, ← mem_sublists',
sublists'_reverse, mem_map_of_inj reverse_injective]
@[simp] theorem length_sublists (l : list α) : length (sublists l) = 2 ^ length l :=
by simp only [sublists_eq_sublists', length_map, length_sublists', length_reverse]
theorem map_ret_sublist_sublists (l : list α) : map list.ret l <+ sublists l :=
reverse_rec_on l (nil_sublist _) $
λ l a IH, by simp only [map, map_append, sublists_concat]; exact
((append_sublist_append_left _).2 $ singleton_sublist.2 $
mem_map.2 ⟨[], mem_sublists.2 (nil_sublist _), by refl⟩).trans
((append_sublist_append_right _).2 IH)
/- sublists_len -/
def sublists_len_aux {α β : Type*} : ℕ → list α → (list α → β) → list β → list β
| 0 l f r := f [] :: r
| (n+1) [] f r := r
| (n+1) (a::l) f r := sublists_len_aux (n + 1) l f
(sublists_len_aux n l (f ∘ list.cons a) r)
def sublists_len {α : Type*} (n : ℕ) (l : list α) : list (list α) :=
sublists_len_aux n l id []
lemma sublists_len_aux_append {α β γ : Type*} :
∀ (n : ℕ) (l : list α) (f : list α → β) (g : β → γ) (r : list β) (s : list γ),
sublists_len_aux n l (g ∘ f) (r.map g ++ s) =
(sublists_len_aux n l f r).map g ++ s
| 0 l f g r s := rfl
| (n+1) [] f g r s := rfl
| (n+1) (a::l) f g r s := begin
unfold sublists_len_aux,
rw [show ((g ∘ f) ∘ list.cons a) = (g ∘ f ∘ list.cons a), by refl,
sublists_len_aux_append, sublists_len_aux_append]
end
lemma sublists_len_aux_eq {α β : Type*} (l : list α) (n) (f : list α → β) (r) :
sublists_len_aux n l f r = (sublists_len n l).map f ++ r :=
by rw [sublists_len, ← sublists_len_aux_append]; refl
lemma sublists_len_aux_zero {α : Type*} (l : list α) (f : list α → β) (r) :
sublists_len_aux 0 l f r = f [] :: r := by cases l; refl
@[simp] lemma sublists_len_zero {α : Type*} (l : list α) :
sublists_len 0 l = [[]] := sublists_len_aux_zero _ _ _
@[simp] lemma sublists_len_succ_nil {α : Type*} (n) :
sublists_len (n+1) (@nil α) = [] := rfl
@[simp] lemma sublists_len_succ_cons {α : Type*} (n) (a : α) (l) :
sublists_len (n + 1) (a::l) =
sublists_len (n + 1) l ++ (sublists_len n l).map (cons a) :=
by rw [sublists_len, sublists_len_aux, sublists_len_aux_eq,
sublists_len_aux_eq, map_id, append_nil]; refl
@[simp] lemma length_sublists_len {α : Type*} : ∀ n (l : list α),
length (sublists_len n l) = nat.choose (length l) n
| 0 l := by simp
| (n+1) [] := by simp
| (n+1) (a::l) := by simp [-add_comm, nat.choose, *]; apply add_comm
lemma sublists_len_sublist_sublists' {α : Type*} : ∀ n (l : list α),
sublists_len n l <+ sublists' l
| 0 l := singleton_sublist.2 (mem_sublists'.2 (nil_sublist _))
| (n+1) [] := nil_sublist _
| (n+1) (a::l) := begin
rw [sublists_len_succ_cons, sublists'_cons],
exact append_sublist_append
(sublists_len_sublist_sublists' _ _)
(map_sublist_map _ (sublists_len_sublist_sublists' _ _))
end
lemma sublists_len_sublist_of_sublist
{α : Type*} (n) {l₁ l₂ : list α} (h : l₁ <+ l₂) : sublists_len n l₁ <+ sublists_len n l₂ :=
begin
induction n with n IHn generalizing l₁ l₂, {simp},
induction h with l₁ l₂ a s IH l₁ l₂ a s IH, {refl},
{ refine IH.trans _,
rw sublists_len_succ_cons,
apply sublist_append_left },
{ simp [sublists_len_succ_cons],
exact append_sublist_append IH (map_sublist_map _ (IHn s)) }
end
lemma length_of_sublists_len {α : Type*} : ∀ {n} {l l' : list α},
l' ∈ sublists_len n l → length l' = n
| 0 l l' (or.inl rfl) := rfl
| (n+1) (a::l) l' h := begin
rw [sublists_len_succ_cons, mem_append, mem_map] at h,
rcases h with h | ⟨l', h, rfl⟩,
{ exact length_of_sublists_len h },
{ exact congr_arg (+1) (length_of_sublists_len h) },
end
lemma mem_sublists_len_self {α : Type*} {l l' : list α}
(h : l' <+ l) : l' ∈ sublists_len (length l') l :=
begin
induction h with l₁ l₂ a s IH l₁ l₂ a s IH,
{ exact or.inl rfl },
{ cases l₁ with b l₁,
{ exact or.inl rfl },
{ rw [length, sublists_len_succ_cons],
exact mem_append_left _ IH } },
{ rw [length, sublists_len_succ_cons],
exact mem_append_right _ (mem_map.2 ⟨_, IH, rfl⟩) }
end
@[simp] lemma mem_sublists_len {α : Type*} {n} {l l' : list α} :
l' ∈ sublists_len n l ↔ l' <+ l ∧ length l' = n :=
⟨λ h, ⟨mem_sublists'.1
(subset_of_sublist (sublists_len_sublist_sublists' _ _) h),
length_of_sublists_len h⟩,
λ ⟨h₁, h₂⟩, h₂ ▸ mem_sublists_len_self h₁⟩
/- permutations -/
section permutations
@[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
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 :=
subset_of_sublist (erasep_sublist l)
theorem erasep_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 :=
subset_of_sublist (erase_sublist a l)
theorem erase_sublist_erase (a : α) {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.erase a <+ l₂.erase a :=
by simp [erase_eq_erasep]; exact erasep_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]
@[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₁ :=
subset_of_sublist $ diff_sublist _ _
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 diff_sublist_of_sublist : ∀ {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, diff_sublist_of_sublist (erase_sublist_erase _ h)]
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 (erase_sublist_erase b h)
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
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
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
-- A jumble of lost 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
end list
|
3a8709a4b7fefe3c38b77110d065ea0b33bdcdd9 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/data/int/gcd.lean | a2077e651c53c9e5f3c5cbf8dcd3d94d2962e7ff | [
"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 | 26,464 | lean | /-
Copyright (c) 2018 Guy Leroy. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sangwoo Jo (aka Jason), Guy Leroy, Johannes Hölzl, Mario Carneiro
-/
import data.nat.prime
import data.int.order
/-!
# Extended GCD and divisibility over ℤ
## Main definitions
* Given `x y : ℕ`, `xgcd x y` computes the pair of integers `(a, b)` such that
`gcd x y = x * a + y * b`. `gcd_a x y` and `gcd_b x y` are defined to be `a` and `b`,
respectively.
## Main statements
* `gcd_eq_gcd_ab`: Bézout's lemma, given `x y : ℕ`, `gcd x y = x * gcd_a x y + y * gcd_b x y`.
## Tags
Bézout's lemma, Bezout's lemma
-/
/-! ### Extended Euclidean algorithm -/
namespace nat
/-- Helper function for the extended GCD algorithm (`nat.xgcd`). -/
def xgcd_aux : ℕ → ℤ → ℤ → ℕ → ℤ → ℤ → ℕ × ℤ × ℤ
| 0 s t r' s' t' := (r', s', t')
| r@(succ _) s t r' s' t' :=
have r' % r < r, from mod_lt _ $ succ_pos _,
let q := r' / r in xgcd_aux (r' % r) (s' - q * s) (t' - q * t) r s t
@[simp] theorem xgcd_zero_left {s t r' s' t'} : xgcd_aux 0 s t r' s' t' = (r', s', t') :=
by simp [xgcd_aux]
theorem xgcd_aux_rec {r s t r' s' t'} (h : 0 < r) :
xgcd_aux r s t r' s' t' = xgcd_aux (r' % r) (s' - (r' / r) * s) (t' - (r' / r) * t) r s t :=
by cases r; [exact absurd h (lt_irrefl _), {simp only [xgcd_aux], refl}]
/-- Use the extended GCD algorithm to generate the `a` and `b` values
satisfying `gcd x y = x * a + y * b`. -/
def xgcd (x y : ℕ) : ℤ × ℤ := (xgcd_aux x 1 0 y 0 1).2
/-- The extended GCD `a` value in the equation `gcd x y = x * a + y * b`. -/
def gcd_a (x y : ℕ) : ℤ := (xgcd x y).1
/-- The extended GCD `b` value in the equation `gcd x y = x * a + y * b`. -/
def gcd_b (x y : ℕ) : ℤ := (xgcd x y).2
@[simp] theorem gcd_a_zero_left {s : ℕ} : gcd_a 0 s = 0 :=
by { unfold gcd_a, rw [xgcd, xgcd_zero_left] }
@[simp] theorem gcd_b_zero_left {s : ℕ} : gcd_b 0 s = 1 :=
by { unfold gcd_b, rw [xgcd, xgcd_zero_left] }
@[simp] theorem gcd_a_zero_right {s : ℕ} (h : s ≠ 0) : gcd_a s 0 = 1 :=
begin
unfold gcd_a xgcd,
induction s,
{ exact absurd rfl h, },
{ simp [xgcd_aux], }
end
@[simp] theorem gcd_b_zero_right {s : ℕ} (h : s ≠ 0) : gcd_b s 0 = 0 :=
begin
unfold gcd_b xgcd,
induction s,
{ exact absurd rfl h, },
{ simp [xgcd_aux], }
end
@[simp] theorem xgcd_aux_fst (x y) : ∀ s t s' t',
(xgcd_aux x s t y s' t').1 = gcd x y :=
gcd.induction x y (by simp) (λ x y h IH s t s' t', by simp [xgcd_aux_rec, h, IH]; rw ← gcd_rec)
theorem xgcd_aux_val (x y) : xgcd_aux x 1 0 y 0 1 = (gcd x y, xgcd x y) :=
by rw [xgcd, ← xgcd_aux_fst x y 1 0 0 1]; cases xgcd_aux x 1 0 y 0 1; refl
theorem xgcd_val (x y) : xgcd x y = (gcd_a x y, gcd_b x y) :=
by unfold gcd_a gcd_b; cases xgcd x y; refl
section
parameters (x y : ℕ)
private def P : ℕ × ℤ × ℤ → Prop
| (r, s, t) := (r : ℤ) = x * s + y * t
theorem xgcd_aux_P {r r'} : ∀ {s t s' t'}, P (r, s, t) → P (r', s', t') →
P (xgcd_aux r s t r' s' t') :=
gcd.induction r r' (by simp) $ λ a b h IH s t s' t' p p', begin
rw [xgcd_aux_rec h], refine IH _ p, dsimp [P] at *,
rw [int.mod_def], generalize : (b / a : ℤ) = k,
rw [p, p'],
simp [mul_add, mul_comm, mul_left_comm, add_comm, add_left_comm, sub_eq_neg_add, mul_assoc]
end
/-- **Bézout's lemma**: given `x y : ℕ`, `gcd x y = x * a + y * b`, where `a = gcd_a x y` and
`b = gcd_b x y` are computed by the extended Euclidean algorithm.
-/
theorem gcd_eq_gcd_ab : (gcd x y : ℤ) = x * gcd_a x y + y * gcd_b x y :=
by have := @xgcd_aux_P x y x y 1 0 0 1 (by simp [P]) (by simp [P]);
rwa [xgcd_aux_val, xgcd_val] at this
end
lemma exists_mul_mod_eq_gcd {k n : ℕ} (hk : gcd n k < k) :
∃ m, n * m % k = gcd n k :=
begin
have hk' := int.coe_nat_ne_zero.mpr (ne_of_gt (lt_of_le_of_lt (zero_le (gcd n k)) hk)),
have key := congr_arg (λ m, int.nat_mod m k) (gcd_eq_gcd_ab n k),
simp_rw int.nat_mod at key,
rw [int.add_mul_mod_self_left, ←int.coe_nat_mod, int.to_nat_coe_nat, mod_eq_of_lt hk] at key,
refine ⟨(n.gcd_a k % k).to_nat, eq.trans (int.coe_nat_inj _) key.symm⟩,
rw [int.coe_nat_mod, int.coe_nat_mul, int.to_nat_of_nonneg (int.mod_nonneg _ hk'),
int.to_nat_of_nonneg (int.mod_nonneg _ hk'), int.mul_mod, int.mod_mod, ←int.mul_mod],
end
lemma exists_mul_mod_eq_one_of_coprime {k n : ℕ} (hkn : coprime n k) (hk : 1 < k) :
∃ m, n * m % k = 1 :=
Exists.cases_on (exists_mul_mod_eq_gcd (lt_of_le_of_lt (le_of_eq hkn) hk))
(λ m hm, ⟨m, hm.trans hkn⟩)
end nat
/-! ### Divisibility over ℤ -/
namespace int
protected lemma coe_nat_gcd (m n : ℕ) : int.gcd ↑m ↑n = nat.gcd m n := rfl
/-- The extended GCD `a` value in the equation `gcd x y = x * a + y * b`. -/
def gcd_a : ℤ → ℤ → ℤ
| (of_nat m) n := m.gcd_a n.nat_abs
| -[1+ m] n := -m.succ.gcd_a n.nat_abs
/-- The extended GCD `b` value in the equation `gcd x y = x * a + y * b`. -/
def gcd_b : ℤ → ℤ → ℤ
| m (of_nat n) := m.nat_abs.gcd_b n
| m -[1+ n] := -m.nat_abs.gcd_b n.succ
/-- **Bézout's lemma** -/
theorem gcd_eq_gcd_ab : ∀ x y : ℤ, (gcd x y : ℤ) = x * gcd_a x y + y * gcd_b x y
| (m : ℕ) (n : ℕ) := nat.gcd_eq_gcd_ab _ _
| (m : ℕ) -[1+ n] := show (_ : ℤ) = _ + -(n+1) * -_, by rw neg_mul_neg; apply nat.gcd_eq_gcd_ab
| -[1+ m] (n : ℕ) := show (_ : ℤ) = -(m+1) * -_ + _ , by rw neg_mul_neg; apply nat.gcd_eq_gcd_ab
| -[1+ m] -[1+ n] := show (_ : ℤ) = -(m+1) * -_ + -(n+1) * -_,
by { rw [neg_mul_neg, neg_mul_neg], apply nat.gcd_eq_gcd_ab }
theorem nat_abs_div (a b : ℤ) (H : b ∣ a) : nat_abs (a / b) = (nat_abs a) / (nat_abs b) :=
begin
cases (nat.eq_zero_or_pos (nat_abs b)),
{rw eq_zero_of_nat_abs_eq_zero h, simp [int.div_zero]},
calc
nat_abs (a / b) = nat_abs (a / b) * 1 : by rw mul_one
... = nat_abs (a / b) * (nat_abs b / nat_abs b) : by rw nat.div_self h
... = nat_abs (a / b) * nat_abs b / nat_abs b : by rw (nat.mul_div_assoc _ dvd_rfl)
... = nat_abs (a / b * b) / nat_abs b : by rw (nat_abs_mul (a / b) b)
... = nat_abs a / nat_abs b : by rw int.div_mul_cancel H,
end
lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : nat.prime p) {m n : ℤ} {k l : ℕ}
(hpm : ↑(p ^ k) ∣ m)
(hpn : ↑(p ^ l) ∣ n) (hpmn : ↑(p ^ (k+l+1)) ∣ m*n) : ↑(p ^ (k+1)) ∣ m ∨ ↑(p ^ (l+1)) ∣ n :=
have hpm' : p ^ k ∣ m.nat_abs, from int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpm,
have hpn' : p ^ l ∣ n.nat_abs, from int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpn,
have hpmn' : (p ^ (k+l+1)) ∣ m.nat_abs*n.nat_abs,
by rw ←int.nat_abs_mul; apply (int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpmn),
let hsd := nat.succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul p_prime hpm' hpn' hpmn' in
hsd.elim
(λ hsd1, or.inl begin apply int.dvd_nat_abs.1, apply int.coe_nat_dvd.2 hsd1 end)
(λ hsd2, or.inr begin apply int.dvd_nat_abs.1, apply int.coe_nat_dvd.2 hsd2 end)
theorem dvd_of_mul_dvd_mul_left {i j k : ℤ} (k_non_zero : k ≠ 0) (H : k * i ∣ k * j) : i ∣ j :=
dvd.elim H (λl H1, by rw mul_assoc at H1; exact ⟨_, mul_left_cancel₀ k_non_zero H1⟩)
theorem dvd_of_mul_dvd_mul_right {i j k : ℤ} (k_non_zero : k ≠ 0) (H : i * k ∣ j * k) : i ∣ j :=
by rw [mul_comm i k, mul_comm j k] at H; exact dvd_of_mul_dvd_mul_left k_non_zero H
lemma prime.dvd_nat_abs_of_coe_dvd_sq {p : ℕ} (hp : p.prime) (k : ℤ) (h : ↑p ∣ k ^ 2) :
p ∣ k.nat_abs :=
begin
apply @nat.prime.dvd_of_dvd_pow _ _ 2 hp,
rwa [sq, ← nat_abs_mul, ← coe_nat_dvd_left, ← sq]
end
/-- ℤ 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
protected lemma coe_nat_lcm (m n : ℕ) : int.lcm ↑m ↑n = nat.lcm m n := rfl
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_iff_dvd.2 h1) (nat_abs_dvd_iff_dvd.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]
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 { rw [int.gcd, int.gcd, nat_abs_mul, nat_abs_mul], apply nat.gcd_mul_left }
theorem gcd_mul_right (i j k : ℤ) : gcd (i * j) (k * j) = gcd i k * nat_abs j :=
by { rw [int.gcd, int.gcd, nat_abs_mul, nat_abs_mul], apply nat.gcd_mul_right }
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 :=
begin
rw int.gcd,
split,
{ intro h,
exact ⟨nat_abs_eq_zero.mp (nat.eq_zero_of_gcd_eq_zero_left h),
nat_abs_eq_zero.mp (nat.eq_zero_of_gcd_eq_zero_right h)⟩ },
{ intro h, rw [nat_abs_eq_zero.mpr h.left, nat_abs_eq_zero.mpr h.right],
apply nat.gcd_zero_left }
end
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_iff_dvd.mpr H1) (nat_abs_dvd_iff_dvd.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 ((gcd_dvd_left i j).trans 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) ((gcd_dvd_right j i).trans 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_rfl (nat_abs_dvd_iff_dvd.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_iff_dvd.mp,
apply (nat.pow_dvd_pow_iff k0).mp,
rw [← int.nat_abs_pow, ← int.nat_abs_pow],
exact int.nat_abs_dvd_iff_dvd.mpr h
end
lemma gcd_dvd_iff {a b : ℤ} {n : ℕ} : gcd a b ∣ n ↔ ∃ x y : ℤ, ↑n = a * x + b * y :=
begin
split,
{ intro h,
rw [← nat.mul_div_cancel' h, int.coe_nat_mul, gcd_eq_gcd_ab, add_mul, mul_assoc, mul_assoc],
refine ⟨_, _, rfl⟩, },
{ rintro ⟨x, y, h⟩,
rw [←int.coe_nat_dvd, h],
exact dvd_add (dvd_mul_of_dvd_left (gcd_dvd_left a b) _)
(dvd_mul_of_dvd_left (gcd_dvd_right a b) y) }
end
lemma gcd_greatest {a b d : ℤ} (hd_pos : 0 ≤ d) (hda : d ∣ a) (hdb : d ∣ b)
(hd : ∀ e : ℤ, e ∣ a → e ∣ b → e ∣ d) : d = gcd a b :=
dvd_antisymm hd_pos
(coe_zero_le (gcd a b)) (dvd_gcd hda hdb) (hd _ (gcd_dvd_left a b) (gcd_dvd_right a b))
/-- Euclid's lemma: if `a ∣ b * c` and `gcd a c = 1` then `a ∣ b`.
Compare with `is_coprime.dvd_of_dvd_mul_left` and
`unique_factorization_monoid.dvd_of_dvd_mul_left_of_no_prime_factors` -/
lemma dvd_of_dvd_mul_left_of_gcd_one {a b c : ℤ} (habc : a ∣ b * c) (hab : gcd a c = 1) : a ∣ b :=
begin
have := gcd_eq_gcd_ab a c,
simp only [hab, int.coe_nat_zero, int.coe_nat_succ, zero_add] at this,
have : b * a * gcd_a a c + b * c * gcd_b a c = b, { simp [mul_assoc, ←mul_add, ←this] },
rw ←this,
exact dvd_add (dvd_mul_of_dvd_left (dvd_mul_left a b) _) (dvd_mul_of_dvd_left habc _),
end
/-- Euclid's lemma: if `a ∣ b * c` and `gcd a b = 1` then `a ∣ c`.
Compare with `is_coprime.dvd_of_dvd_mul_right` and
`unique_factorization_monoid.dvd_of_dvd_mul_right_of_no_prime_factors` -/
lemma dvd_of_dvd_mul_right_of_gcd_one {a b c : ℤ} (habc : a ∣ b * c) (hab : gcd a b = 1) : a ∣ c :=
by { rw mul_comm at habc, exact dvd_of_dvd_mul_left_of_gcd_one habc hab }
/-- For nonzero integers `a` and `b`, `gcd a b` is the smallest positive natural number that can be
written in the form `a * x + b * y` for some pair of integers `x` and `y` -/
theorem gcd_least_linear {a b : ℤ} (ha : a ≠ 0) :
is_least { n : ℕ | 0 < n ∧ ∃ x y : ℤ, ↑n = a * x + b * y } (a.gcd b) :=
begin
simp_rw ←gcd_dvd_iff,
split,
{ simpa [and_true, dvd_refl, set.mem_set_of_eq] using gcd_pos_of_non_zero_left b ha },
{ simp only [lower_bounds, and_imp, set.mem_set_of_eq],
exact λ n hn_pos hn, nat.le_of_dvd hn_pos hn },
end
/-! ### lcm -/
theorem lcm_comm (i j : ℤ) : lcm i j = lcm j i :=
by { rw [int.lcm, int.lcm], exact nat.lcm_comm _ _ }
theorem lcm_assoc (i j k : ℤ) : lcm (lcm i j) k = lcm i (lcm j k) :=
by { rw [int.lcm, int.lcm, int.lcm, int.lcm, nat_abs_of_nat, nat_abs_of_nat], apply nat.lcm_assoc }
@[simp] theorem lcm_zero_left (i : ℤ) : lcm 0 i = 0 :=
by { rw [int.lcm], apply nat.lcm_zero_left }
@[simp] theorem lcm_zero_right (i : ℤ) : lcm i 0 = 0 :=
by { rw [int.lcm], apply nat.lcm_zero_right }
@[simp] theorem lcm_one_left (i : ℤ) : lcm 1 i = nat_abs i :=
by { rw int.lcm, apply nat.lcm_one_left }
@[simp] theorem lcm_one_right (i : ℤ) : lcm i 1 = nat_abs i :=
by { rw int.lcm, apply nat.lcm_one_right }
@[simp] theorem lcm_self (i : ℤ) : lcm i i = nat_abs i :=
by { rw int.lcm, apply nat.lcm_self }
theorem dvd_lcm_left (i j : ℤ) : i ∣ lcm i j :=
by { rw int.lcm, apply coe_nat_dvd_right.mpr, apply nat.dvd_lcm_left }
theorem dvd_lcm_right (i j : ℤ) : j ∣ lcm i j :=
by { rw int.lcm, apply coe_nat_dvd_right.mpr, apply nat.dvd_lcm_right }
theorem lcm_dvd {i j k : ℤ} : i ∣ k → j ∣ k → (lcm i j : ℤ) ∣ k :=
begin
rw int.lcm,
intros hi hj,
exact coe_nat_dvd_left.mpr
(nat.lcm_dvd (nat_abs_dvd_iff_dvd.mpr hi) (nat_abs_dvd_iff_dvd.mpr hj))
end
end int
lemma pow_gcd_eq_one {M : Type*} [monoid M] (x : M) {m n : ℕ} (hm : x ^ m = 1) (hn : x ^ n = 1) :
x ^ m.gcd n = 1 :=
begin
cases m, { simp only [hn, nat.gcd_zero_left] },
obtain ⟨x, rfl⟩ : is_unit x,
{ apply is_unit_of_pow_eq_one _ _ hm m.succ_pos },
simp only [← units.coe_pow] at *,
rw [← units.coe_one, ← zpow_coe_nat, ← units.ext_iff] at *,
simp only [nat.gcd_eq_gcd_ab, zpow_add, zpow_mul, hm, hn, one_zpow, one_mul]
end
lemma gcd_nsmul_eq_zero {M : Type*} [add_monoid M] (x : M) {m n : ℕ} (hm : m • x = 0)
(hn : n • x = 0) : (m.gcd n) • x = 0 :=
begin
apply multiplicative.of_add.injective,
rw [of_add_nsmul, of_add_zero, pow_gcd_eq_one];
rwa [←of_add_nsmul, ←of_add_zero, equiv.apply_eq_iff_eq]
end
attribute [to_additive gcd_nsmul_eq_zero] pow_gcd_eq_one
/-! ### GCD prover -/
open norm_num
namespace tactic
namespace norm_num
lemma int_gcd_helper' {d : ℕ} {x y a b : ℤ} (h₁ : (d:ℤ) ∣ x) (h₂ : (d:ℤ) ∣ y)
(h₃ : x * a + y * b = d) : int.gcd x y = d :=
begin
refine nat.dvd_antisymm _ (int.coe_nat_dvd.1 (int.dvd_gcd h₁ h₂)),
rw [← int.coe_nat_dvd, ← h₃],
apply dvd_add,
{ exact (int.gcd_dvd_left _ _).mul_right _ },
{ exact (int.gcd_dvd_right _ _).mul_right _ }
end
lemma nat_gcd_helper_dvd_left (x y a : ℕ) (h : x * a = y) : nat.gcd x y = x :=
nat.gcd_eq_left ⟨a, h.symm⟩
lemma nat_gcd_helper_dvd_right (x y a : ℕ) (h : y * a = x) : nat.gcd x y = y :=
nat.gcd_eq_right ⟨a, h.symm⟩
lemma nat_gcd_helper_2 (d x y a b u v tx ty : ℕ) (hu : d * u = x) (hv : d * v = y)
(hx : x * a = tx) (hy : y * b = ty) (h : ty + d = tx) : nat.gcd x y = d :=
begin
rw ← int.coe_nat_gcd, apply @int_gcd_helper' _ _ _ a (-b)
(int.coe_nat_dvd.2 ⟨_, hu.symm⟩) (int.coe_nat_dvd.2 ⟨_, hv.symm⟩),
rw [mul_neg_eq_neg_mul_symm, ← sub_eq_add_neg, sub_eq_iff_eq_add'],
norm_cast, rw [hx, hy, h]
end
lemma nat_gcd_helper_1 (d x y a b u v tx ty : ℕ) (hu : d * u = x) (hv : d * v = y)
(hx : x * a = tx) (hy : y * b = ty) (h : tx + d = ty) : nat.gcd x y = d :=
(nat.gcd_comm _ _).trans $ nat_gcd_helper_2 _ _ _ _ _ _ _ _ _ hv hu hy hx h
lemma nat_lcm_helper (x y d m n : ℕ) (hd : nat.gcd x y = d) (d0 : 0 < d)
(xy : x * y = n) (dm : d * m = n) : nat.lcm x y = m :=
(nat.mul_right_inj d0).1 $ by rw [dm, ← xy, ← hd, nat.gcd_mul_lcm]
lemma nat_coprime_helper_zero_left (x : ℕ) (h : 1 < x) : ¬ nat.coprime 0 x :=
mt (nat.coprime_zero_left _).1 $ ne_of_gt h
lemma nat_coprime_helper_zero_right (x : ℕ) (h : 1 < x) : ¬ nat.coprime x 0 :=
mt (nat.coprime_zero_right _).1 $ ne_of_gt h
lemma nat_coprime_helper_1 (x y a b tx ty : ℕ)
(hx : x * a = tx) (hy : y * b = ty) (h : tx + 1 = ty) : nat.coprime x y :=
nat_gcd_helper_1 _ _ _ _ _ _ _ _ _ (one_mul _) (one_mul _) hx hy h
lemma nat_coprime_helper_2 (x y a b tx ty : ℕ)
(hx : x * a = tx) (hy : y * b = ty) (h : ty + 1 = tx) : nat.coprime x y :=
nat_gcd_helper_2 _ _ _ _ _ _ _ _ _ (one_mul _) (one_mul _) hx hy h
lemma nat_not_coprime_helper (d x y u v : ℕ) (hu : d * u = x) (hv : d * v = y)
(h : 1 < d) : ¬ nat.coprime x y :=
nat.not_coprime_of_dvd_of_dvd h ⟨_, hu.symm⟩ ⟨_, hv.symm⟩
lemma int_gcd_helper (x y : ℤ) (nx ny d : ℕ) (hx : (nx:ℤ) = x) (hy : (ny:ℤ) = y)
(h : nat.gcd nx ny = d) : int.gcd x y = d :=
by rwa [← hx, ← hy, int.coe_nat_gcd]
lemma int_gcd_helper_neg_left (x y : ℤ) (d : ℕ) (h : int.gcd x y = d) : int.gcd (-x) y = d :=
by rw int.gcd at h ⊢; rwa int.nat_abs_neg
lemma int_gcd_helper_neg_right (x y : ℤ) (d : ℕ) (h : int.gcd x y = d) : int.gcd x (-y) = d :=
by rw int.gcd at h ⊢; rwa int.nat_abs_neg
lemma int_lcm_helper (x y : ℤ) (nx ny d : ℕ) (hx : (nx:ℤ) = x) (hy : (ny:ℤ) = y)
(h : nat.lcm nx ny = d) : int.lcm x y = d :=
by rwa [← hx, ← hy, int.coe_nat_lcm]
lemma int_lcm_helper_neg_left (x y : ℤ) (d : ℕ) (h : int.lcm x y = d) : int.lcm (-x) y = d :=
by rw int.lcm at h ⊢; rwa int.nat_abs_neg
lemma int_lcm_helper_neg_right (x y : ℤ) (d : ℕ) (h : int.lcm x y = d) : int.lcm x (-y) = d :=
by rw int.lcm at h ⊢; rwa int.nat_abs_neg
/-- Evaluates the `nat.gcd` function. -/
meta def prove_gcd_nat (c : instance_cache) (ex ey : expr) :
tactic (instance_cache × expr × expr) := do
x ← ex.to_nat,
y ← ey.to_nat,
match x, y with
| 0, _ := pure (c, ey, `(nat.gcd_zero_left).mk_app [ey])
| _, 0 := pure (c, ex, `(nat.gcd_zero_right).mk_app [ex])
| 1, _ := pure (c, `(1:ℕ), `(nat.gcd_one_left).mk_app [ey])
| _, 1 := pure (c, `(1:ℕ), `(nat.gcd_one_right).mk_app [ex])
| _, _ := do
let (d, a, b) := nat.xgcd_aux x 1 0 y 0 1,
if d = x then do
(c, ea) ← c.of_nat (y / x),
(c, _, p) ← prove_mul_nat c ex ea,
pure (c, ex, `(nat_gcd_helper_dvd_left).mk_app [ex, ey, ea, p])
else if d = y then do
(c, ea) ← c.of_nat (x / y),
(c, _, p) ← prove_mul_nat c ey ea,
pure (c, ey, `(nat_gcd_helper_dvd_right).mk_app [ex, ey, ea, p])
else do
(c, ed) ← c.of_nat d,
(c, ea) ← c.of_nat a.nat_abs,
(c, eb) ← c.of_nat b.nat_abs,
(c, eu) ← c.of_nat (x / d),
(c, ev) ← c.of_nat (y / d),
(c, _, pu) ← prove_mul_nat c ed eu,
(c, _, pv) ← prove_mul_nat c ed ev,
(c, etx, px) ← prove_mul_nat c ex ea,
(c, ety, py) ← prove_mul_nat c ey eb,
(c, p) ← if a ≥ 0 then prove_add_nat c ety ed etx else prove_add_nat c etx ed ety,
let pf : expr := if a ≥ 0 then `(nat_gcd_helper_2) else `(nat_gcd_helper_1),
pure (c, ed, pf.mk_app [ed, ex, ey, ea, eb, eu, ev, etx, ety, pu, pv, px, py, p])
end
/-- Evaluates the `nat.lcm` function. -/
meta def prove_lcm_nat (c : instance_cache) (ex ey : expr) :
tactic (instance_cache × expr × expr) := do
x ← ex.to_nat,
y ← ey.to_nat,
match x, y with
| 0, _ := pure (c, `(0:ℕ), `(nat.lcm_zero_left).mk_app [ey])
| _, 0 := pure (c, `(0:ℕ), `(nat.lcm_zero_right).mk_app [ex])
| 1, _ := pure (c, ey, `(nat.lcm_one_left).mk_app [ey])
| _, 1 := pure (c, ex, `(nat.lcm_one_right).mk_app [ex])
| _, _ := do
(c, ed, pd) ← prove_gcd_nat c ex ey,
(c, p0) ← prove_pos c ed,
(c, en, xy) ← prove_mul_nat c ex ey,
d ← ed.to_nat,
(c, em) ← c.of_nat ((x * y) / d),
(c, _, dm) ← prove_mul_nat c ed em,
pure (c, em, `(nat_lcm_helper).mk_app [ex, ey, ed, em, en, pd, p0, xy, dm])
end
/-- Evaluates the `int.gcd` function. -/
meta def prove_gcd_int (zc nc : instance_cache) : expr → expr →
tactic (instance_cache × instance_cache × expr × expr)
| x y := match match_neg x with
| some x := do
(zc, nc, d, p) ← prove_gcd_int x y,
pure (zc, nc, d, `(int_gcd_helper_neg_left).mk_app [x, y, d, p])
| none := match match_neg y with
| some y := do
(zc, nc, d, p) ← prove_gcd_int x y,
pure (zc, nc, d, `(int_gcd_helper_neg_right).mk_app [x, y, d, p])
| none := do
(zc, nc, nx, px) ← prove_nat_uncast zc nc x,
(zc, nc, ny, py) ← prove_nat_uncast zc nc y,
(nc, d, p) ← prove_gcd_nat nc nx ny,
pure (zc, nc, d, `(int_gcd_helper).mk_app [x, y, nx, ny, d, px, py, p])
end
end
/-- Evaluates the `int.lcm` function. -/
meta def prove_lcm_int (zc nc : instance_cache) : expr → expr →
tactic (instance_cache × instance_cache × expr × expr)
| x y := match match_neg x with
| some x := do
(zc, nc, d, p) ← prove_lcm_int x y,
pure (zc, nc, d, `(int_lcm_helper_neg_left).mk_app [x, y, d, p])
| none := match match_neg y with
| some y := do
(zc, nc, d, p) ← prove_lcm_int x y,
pure (zc, nc, d, `(int_lcm_helper_neg_right).mk_app [x, y, d, p])
| none := do
(zc, nc, nx, px) ← prove_nat_uncast zc nc x,
(zc, nc, ny, py) ← prove_nat_uncast zc nc y,
(nc, d, p) ← prove_lcm_nat nc nx ny,
pure (zc, nc, d, `(int_lcm_helper).mk_app [x, y, nx, ny, d, px, py, p])
end
end
/-- Evaluates the `nat.coprime` function. -/
meta def prove_coprime_nat (c : instance_cache) (ex ey : expr) :
tactic (instance_cache × (expr ⊕ expr)) := do
x ← ex.to_nat,
y ← ey.to_nat,
match x, y with
| 1, _ := pure (c, sum.inl $ `(nat.coprime_one_left).mk_app [ey])
| _, 1 := pure (c, sum.inl $ `(nat.coprime_one_right).mk_app [ex])
| 0, 0 := pure (c, sum.inr `(nat.not_coprime_zero_zero))
| 0, _ := do
c ← mk_instance_cache `(ℕ),
(c, p) ← prove_lt_nat c `(1) ey,
pure (c, sum.inr $ `(nat_coprime_helper_zero_left).mk_app [ey, p])
| _, 0 := do
c ← mk_instance_cache `(ℕ),
(c, p) ← prove_lt_nat c `(1) ex,
pure (c, sum.inr $ `(nat_coprime_helper_zero_right).mk_app [ex, p])
| _, _ := do
c ← mk_instance_cache `(ℕ),
let (d, a, b) := nat.xgcd_aux x 1 0 y 0 1,
if d = 1 then do
(c, ea) ← c.of_nat a.nat_abs,
(c, eb) ← c.of_nat b.nat_abs,
(c, etx, px) ← prove_mul_nat c ex ea,
(c, ety, py) ← prove_mul_nat c ey eb,
(c, p) ← if a ≥ 0 then prove_add_nat c ety `(1) etx else prove_add_nat c etx `(1) ety,
let pf : expr := if a ≥ 0 then `(nat_coprime_helper_2) else `(nat_coprime_helper_1),
pure (c, sum.inl $ pf.mk_app [ex, ey, ea, eb, etx, ety, px, py, p])
else do
(c, ed) ← c.of_nat d,
(c, eu) ← c.of_nat (x / d),
(c, ev) ← c.of_nat (y / d),
(c, _, pu) ← prove_mul_nat c ed eu,
(c, _, pv) ← prove_mul_nat c ed ev,
(c, p) ← prove_lt_nat c `(1) ed,
pure (c, sum.inr $ `(nat_not_coprime_helper).mk_app [ed, ex, ey, eu, ev, pu, pv, p])
end
/-- Evaluates the `gcd`, `lcm`, and `coprime` functions. -/
@[norm_num] meta def eval_gcd : expr → tactic (expr × expr)
| `(nat.gcd %%ex %%ey) := do
c ← mk_instance_cache `(ℕ),
prod.snd <$> prove_gcd_nat c ex ey
| `(nat.lcm %%ex %%ey) := do
c ← mk_instance_cache `(ℕ),
prod.snd <$> prove_lcm_nat c ex ey
| `(nat.coprime %%ex %%ey) := do
c ← mk_instance_cache `(ℕ),
prove_coprime_nat c ex ey >>= sum.elim true_intro false_intro ∘ prod.snd
| `(int.gcd %%ex %%ey) := do
zc ← mk_instance_cache `(ℤ),
nc ← mk_instance_cache `(ℕ),
(prod.snd ∘ prod.snd) <$> prove_gcd_int zc nc ex ey
| `(int.lcm %%ex %%ey) := do
zc ← mk_instance_cache `(ℤ),
nc ← mk_instance_cache `(ℕ),
(prod.snd ∘ prod.snd) <$> prove_lcm_int zc nc ex ey
| _ := failed
end norm_num
end tactic
|
5db4152fc8d4aa72f2ca8862e9e195cd967a70de | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /tests/lean/run/e16.lean | a92cc0a1bdf0d1221bd77c8610bfd9213907aaef | [
"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 | 555 | lean | prelude
inductive nat : Type
| zero : nat
| succ : nat → nat
namespace nat end nat open nat
inductive {u} list (A : Type u) : Type u
| nil {} : list
| cons : A → list → list
namespace list end list open list
check nil
check nil.{0}
check @nil.{0} nat
check @nil nat
check cons zero nil
inductive {u} vector (A : Type u) : nat → Type u
| vnil {} : vector zero
| vcons : forall {n : nat}, A → vector n → vector (succ n)
namespace vector end vector open vector
check vcons zero vnil
constant n : nat
check vcons n vnil
check vector.rec
|
6da33f9e637afb01eeaeadc7d86470cb67e059de | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/data/subtype.lean | be2fbfbe7887964e2e6ee695d23334468879d29d | [
"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 | 7,157 | 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.ext
import tactic.lint
import tactic.simps
/-!
# Subtypes
This file provides basic API for subtypes, which are defined in core.
A subtype is a type made from restricting another type, say `α`, to its elements that satisfy some
predicate, say `p : α → Prop`. Specifically, it is the type of pairs `⟨val, property⟩` where
`val : α` and `property : p val`. It is denoted `subtype p` and notation `{val : α // p val}` is
available.
A subtype has a natural coercion to the parent type, by coercing `⟨val, property⟩` to `val`. As
such, subtypes can be thought of as bundled sets, the difference being that elements of a set are
still of type `α` while elements of a subtype aren't.
-/
open function
namespace subtype
variables {α β γ : Sort*} {p q : α → Prop}
/-- See Note [custom simps projection] -/
def simps.coe (x : subtype p) : α := x
initialize_simps_projections subtype (val → coe)
/-- A version of `x.property` or `x.2` where `p` is syntactically applied to the coercion of `x`
instead of `x.1`. A similar result is `subtype.mem` in `data.set.basic`. -/
lemma prop (x : subtype p) : p x := x.2
@[simp] lemma val_eq_coe {x : subtype p} : x.1 = ↑x := rfl
@[simp] protected theorem «forall» {q : {a // p a} → Prop} :
(∀ x, q x) ↔ (∀ a b, q ⟨a, b⟩) :=
⟨assume h a b, h ⟨a, b⟩, assume h ⟨a, b⟩, h a b⟩
/-- An alternative version of `subtype.forall`. This one is useful if Lean cannot figure out `q`
when using `subtype.forall` from right to left. -/
protected theorem forall' {q : ∀ x, p x → Prop} :
(∀ x h, q x h) ↔ (∀ x : {a // p a}, q x x.2) :=
(@subtype.forall _ _ (λ x, q x.1 x.2)).symm
@[simp] protected theorem «exists» {q : {a // p a} → Prop} :
(∃ x, q x) ↔ (∃ a b, q ⟨a, b⟩) :=
⟨assume ⟨⟨a, b⟩, h⟩, ⟨a, b, h⟩, assume ⟨a, b, h⟩, ⟨⟨a, b⟩, h⟩⟩
/-- An alternative version of `subtype.exists`. This one is useful if Lean cannot figure out `q`
when using `subtype.exists` from right to left. -/
protected theorem exists' {q : ∀x, p x → Prop} :
(∃ x h, q x h) ↔ (∃ x : {a // p a}, q x x.2) :=
(@subtype.exists _ _ (λ x, q x.1 x.2)).symm
@[ext] protected lemma ext : ∀ {a1 a2 : {x // p x}}, (a1 : α) = (a2 : α) → a1 = a2
| ⟨x, h1⟩ ⟨.(x), h2⟩ rfl := rfl
lemma ext_iff {a1 a2 : {x // p x}} : a1 = a2 ↔ (a1 : α) = (a2 : α) :=
⟨congr_arg _, subtype.ext⟩
lemma heq_iff_coe_eq (h : ∀ x, p x ↔ q x) {a1 : {x // p x}} {a2 : {x // q x}} :
a1 == a2 ↔ (a1 : α) = (a2 : α) :=
eq.rec (λ a2', heq_iff_eq.trans ext_iff) (funext $ λ x, propext (h x)) a2
lemma heq_iff_coe_heq {α β : Sort*} {p : α → Prop} {q : β → Prop} {a : {x // p x}}
{b : {y // q y}} (h : α = β) (h' : p == q) :
a == b ↔ (a : α) == (b : β) :=
by { subst h, subst h', rw [heq_iff_eq, heq_iff_eq, ext_iff] }
lemma ext_val {a1 a2 : {x // p x}} : a1.1 = a2.1 → a1 = a2 :=
subtype.ext
lemma ext_iff_val {a1 a2 : {x // p x}} : a1 = a2 ↔ a1.1 = a2.1 :=
ext_iff
@[simp] theorem coe_eta (a : {a // p a}) (h : p a) : mk ↑a h = a := subtype.ext rfl
@[simp] theorem coe_mk (a h) : (@mk α p a h : α) = a := rfl
@[simp, nolint simp_nf] -- built-in reduction doesn't always work
theorem mk_eq_mk {a h a' h'} : @mk α p a h = @mk α p a' h' ↔ a = a' :=
ext_iff
theorem coe_eq_iff {a : {a // p a}} {b : α} : ↑a = b ↔ ∃ h, a = ⟨b, h⟩ :=
⟨λ h, h ▸ ⟨a.2, (coe_eta _ _).symm⟩, λ ⟨hb, ha⟩, ha.symm ▸ rfl⟩
theorem coe_injective : injective (coe : subtype p → α) :=
λ a b, subtype.ext
theorem val_injective : injective (@val _ p) :=
coe_injective
/-- Restrict a (dependent) function to a subtype -/
def restrict {α} {β : α → Type*} (f : Π x, β x) (p : α → Prop) (x : subtype p) : β x.1 :=
f x
lemma restrict_apply {α} {β : α → Type*} (f : Π x, β x) (p : α → Prop) (x : subtype p) :
restrict f p x = f x.1 :=
by refl
lemma restrict_def {α β} (f : α → β) (p : α → Prop) : restrict f p = f ∘ coe :=
by refl
lemma restrict_injective {α β} {f : α → β} (p : α → Prop) (h : injective f) :
injective (restrict f p) :=
h.comp coe_injective
/-- Defining a map into a subtype, this can be seen as an "coinduction principle" of `subtype`-/
@[simps] def coind {α β} (f : α → β) {p : β → Prop} (h : ∀ a, p (f a)) : α → subtype p :=
λ a, ⟨f a, h a⟩
theorem coind_injective {α β} {f : α → β} {p : β → Prop} (h : ∀ a, p (f a))
(hf : injective f) : injective (coind f h) :=
λ x y hxy, hf $ by apply congr_arg subtype.val hxy
theorem coind_surjective {α β} {f : α → β} {p : β → Prop} (h : ∀ a, p (f a))
(hf : surjective f) : surjective (coind f h) :=
λ x, let ⟨a, ha⟩ := hf x in ⟨a, coe_injective ha⟩
theorem coind_bijective {α β} {f : α → β} {p : β → Prop} (h : ∀ a, p (f a))
(hf : bijective f) : bijective (coind f h) :=
⟨coind_injective h hf.1, coind_surjective h hf.2⟩
/-- Restriction of a function to a function on subtypes. -/
@[simps] def map {p : α → Prop} {q : β → Prop} (f : α → β) (h : ∀ a, p a → q (f a)) :
subtype p → subtype q :=
λ x, ⟨f x, h x x.prop⟩
theorem map_comp {p : α → Prop} {q : β → Prop} {r : γ → Prop} {x : subtype p}
(f : α → β) (h : ∀ a, p a → q (f a)) (g : β → γ) (l : ∀ a, q a → r (g a)) :
map g l (map f h x) = map (g ∘ f) (assume a ha, l (f a) $ h a ha) x :=
rfl
theorem map_id {p : α → Prop} {h : ∀ a, p a → p (id a)} : map (@id α) h = id :=
funext $ assume ⟨v, h⟩, rfl
lemma map_injective {p : α → Prop} {q : β → Prop} {f : α → β} (h : ∀ a, p a → q (f a))
(hf : injective f) : injective (map f h) :=
coind_injective _ $ hf.comp coe_injective
lemma map_involutive {p : α → Prop} {f : α → α} (h : ∀ a, p a → p (f a))
(hf : involutive f) : involutive (map f h) :=
λ x, subtype.ext (hf x)
instance [has_equiv α] (p : α → Prop) : has_equiv (subtype p) :=
⟨λ s t, (s : α) ≈ (t : α)⟩
theorem equiv_iff [has_equiv α] {p : α → Prop} {s t : subtype p} :
s ≈ t ↔ (s : α) ≈ (t : α) :=
iff.rfl
variables [setoid α]
protected theorem refl (s : subtype p) : s ≈ s :=
setoid.refl ↑s
protected theorem symm {s t : subtype p} (h : s ≈ t) : t ≈ s :=
setoid.symm h
protected theorem trans {s t u : subtype p} (h₁ : s ≈ t) (h₂ : t ≈ u) : s ≈ u :=
setoid.trans h₁ h₂
theorem equivalence (p : α → Prop) : equivalence (@has_equiv.equiv (subtype p) _) :=
mk_equivalence _ subtype.refl (@subtype.symm _ p _) (@subtype.trans _ p _)
instance (p : α → Prop) : setoid (subtype p) :=
setoid.mk (≈) (equivalence p)
end subtype
namespace subtype
/-! Some facts about sets, which require that `α` is a type. -/
variables {α β γ : Type*} {p : α → Prop}
@[simp] lemma coe_prop {S : set α} (a : {a // a ∈ S}) : ↑a ∈ S := a.prop
lemma val_prop {S : set α} (a : {a // a ∈ S}) : a.val ∈ S := a.property
end subtype
|
a353717c61d6f841b642e7e2d815ce7de3df6aed | 4727251e0cd73359b15b664c3170e5d754078599 | /src/order/filter/partial.lean | fd96d8812e96609075b86825f8fdc3b662d280d0 | [
"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 | 10,766 | lean | /-
Copyright (c) 2019 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
-/
import order.filter.basic
import data.pfun
/-!
# `tendsto` for relations and partial functions
This file generalizes `filter` definitions from functions to partial functions and relations.
## Considering functions and partial functions as relations
A function `f : α → β` can be considered as the relation `rel α β` which relates `x` and `f x` for
all `x`, and nothing else. This relation is called `function.graph f`.
A partial function `f : α →. β` can be considered as the relation `rel α β` which relates `x` and
`f x` for all `x` for which `f x` exists, and nothing else. This relation is called
`pfun.graph' f`.
In this regard, a function is a relation for which every element in `α` is related to exactly one
element in `β` and a partial function is a relation for which every element in `α` is related to at
most one element in `β`.
This file leverages this analogy to generalize `filter` definitions from functions to partial
functions and relations.
## Notes
`set.preimage` can be generalized to relations in two ways:
* `rel.preimage` returns the image of the set under the inverse relation.
* `rel.core` returns the set of elements that are only related to those in the set.
Both generalizations are sensible in the context of filters, so `filter.comap` and `filter.tendsto`
get two generalizations each.
We first take care of relations. Then the definitions for partial functions are taken as special
cases of the definitions for relations.
-/
universes u v w
namespace filter
variables {α : Type u} {β : Type v} {γ : Type w}
open_locale filter
/-! ### Relations -/
/-- The forward map of a filter under a relation. Generalization of `filter.map` to relations. Note
that `rel.core` generalizes `set.preimage`. -/
def rmap (r : rel α β) (l : filter α) : filter β :=
{ sets := {s | r.core s ∈ l},
univ_sets := by simp,
sets_of_superset := λ s t hs st, mem_of_superset hs $ rel.core_mono _ st,
inter_sets := λ s t hs ht, by simp [rel.core_inter, inter_mem hs ht] }
theorem rmap_sets (r : rel α β) (l : filter α) : (l.rmap r).sets = r.core ⁻¹' l.sets := rfl
@[simp]
theorem mem_rmap (r : rel α β) (l : filter α) (s : set β) :
s ∈ l.rmap r ↔ r.core s ∈ l :=
iff.rfl
@[simp]
theorem rmap_rmap (r : rel α β) (s : rel β γ) (l : filter α) :
rmap s (rmap r l) = rmap (r.comp s) l :=
filter_eq $
by simp [rmap_sets, set.preimage, rel.core_comp]
@[simp]
lemma rmap_compose (r : rel α β) (s : rel β γ) : rmap s ∘ rmap r = rmap (r.comp s) :=
funext $ rmap_rmap _ _
/-- Generic "limit of a relation" predicate. `rtendsto r l₁ l₂` asserts that for every
`l₂`-neighborhood `a`, the `r`-core of `a` is an `l₁`-neighborhood. One generalization of
`filter.tendsto` to relations. -/
def rtendsto (r : rel α β) (l₁ : filter α) (l₂ : filter β) := l₁.rmap r ≤ l₂
theorem rtendsto_def (r : rel α β) (l₁ : filter α) (l₂ : filter β) :
rtendsto r l₁ l₂ ↔ ∀ s ∈ l₂, r.core s ∈ l₁ :=
iff.rfl
/-- One way of taking the inverse map of a filter under a relation. One generalization of
`filter.comap` to relations. Note that `rel.core` generalizes `set.preimage`. -/
def rcomap (r : rel α β) (f : filter β) : filter α :=
{ sets := rel.image (λ s t, r.core s ⊆ t) f.sets,
univ_sets := ⟨set.univ, univ_mem, set.subset_univ _⟩,
sets_of_superset := λ a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', ma'a.trans ab⟩,
inter_sets := λ a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩,
⟨a' ∩ b', inter_mem ha₁ hb₁,
(r.core_inter a' b').subset.trans (set.inter_subset_inter ha₂ hb₂)⟩ }
theorem rcomap_sets (r : rel α β) (f : filter β) :
(rcomap r f).sets = rel.image (λ s t, r.core s ⊆ t) f.sets := rfl
theorem rcomap_rcomap (r : rel α β) (s : rel β γ) (l : filter γ) :
rcomap r (rcomap s l) = rcomap (r.comp s) l :=
filter_eq $
begin
ext t, simp [rcomap_sets, rel.image, rel.core_comp], split,
{ rintros ⟨u, ⟨v, vsets, hv⟩, h⟩,
exact ⟨v, vsets, set.subset.trans (rel.core_mono _ hv) h⟩ },
rintros ⟨t, tsets, ht⟩,
exact ⟨rel.core s t, ⟨t, tsets, set.subset.rfl⟩, ht⟩
end
@[simp]
lemma rcomap_compose (r : rel α β) (s : rel β γ) : rcomap r ∘ rcomap s = rcomap (r.comp s) :=
funext $ rcomap_rcomap _ _
theorem rtendsto_iff_le_rcomap (r : rel α β) (l₁ : filter α) (l₂ : filter β) :
rtendsto r l₁ l₂ ↔ l₁ ≤ l₂.rcomap r :=
begin
rw rtendsto_def,
change (∀ (s : set β), s ∈ l₂.sets → r.core s ∈ l₁) ↔ l₁ ≤ rcomap r l₂,
simp [filter.le_def, rcomap, rel.mem_image], split,
{ exact λ h s t tl₂, mem_of_superset (h t tl₂) },
{ exact λ h t tl₂, h _ t tl₂ set.subset.rfl }
end
-- Interestingly, there does not seem to be a way to express this relation using a forward map.
-- Given a filter `f` on `α`, we want a filter `f'` on `β` such that `r.preimage s ∈ f` if
-- and only if `s ∈ f'`. But the intersection of two sets satisfying the lhs may be empty.
/-- One way of taking the inverse map of a filter under a relation. Generalization of `filter.comap`
to relations. -/
def rcomap' (r : rel α β) (f : filter β) : filter α :=
{ sets := rel.image (λ s t, r.preimage s ⊆ t) f.sets,
univ_sets := ⟨set.univ, univ_mem, set.subset_univ _⟩,
sets_of_superset := λ a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', ma'a.trans ab⟩,
inter_sets := λ a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩,
⟨a' ∩ b', inter_mem ha₁ hb₁,
(@rel.preimage_inter _ _ r _ _).trans (set.inter_subset_inter ha₂ hb₂)⟩ }
@[simp]
lemma mem_rcomap' (r : rel α β) (l : filter β) (s : set α) :
s ∈ l.rcomap' r ↔ ∃ t ∈ l, r.preimage t ⊆ s :=
iff.rfl
theorem rcomap'_sets (r : rel α β) (f : filter β) :
(rcomap' r f).sets = rel.image (λ s t, r.preimage s ⊆ t) f.sets := rfl
@[simp]
theorem rcomap'_rcomap' (r : rel α β) (s : rel β γ) (l : filter γ) :
rcomap' r (rcomap' s l) = rcomap' (r.comp s) l :=
filter.ext $ λ t,
begin
simp [rcomap'_sets, rel.image, rel.preimage_comp], split,
{ rintro ⟨u, ⟨v, vsets, hv⟩, h⟩,
exact ⟨v, vsets, (rel.preimage_mono _ hv).trans h⟩ },
rintro ⟨t, tsets, ht⟩,
exact ⟨s.preimage t, ⟨t, tsets, set.subset.rfl⟩, ht⟩
end
@[simp]
lemma rcomap'_compose (r : rel α β) (s : rel β γ) : rcomap' r ∘ rcomap' s = rcomap' (r.comp s) :=
funext $ rcomap'_rcomap' _ _
/-- Generic "limit of a relation" predicate. `rtendsto' r l₁ l₂` asserts that for every
`l₂`-neighborhood `a`, the `r`-preimage of `a` is an `l₁`-neighborhood. One generalization of
`filter.tendsto` to relations. -/
def rtendsto' (r : rel α β) (l₁ : filter α) (l₂ : filter β) := l₁ ≤ l₂.rcomap' r
theorem rtendsto'_def (r : rel α β) (l₁ : filter α) (l₂ : filter β) :
rtendsto' r l₁ l₂ ↔ ∀ s ∈ l₂, r.preimage s ∈ l₁ :=
begin
unfold rtendsto' rcomap', simp [le_def, rel.mem_image], split,
{ exact λ h s hs, h _ _ hs set.subset.rfl },
{ exact λ h s t ht, mem_of_superset (h t ht) }
end
theorem tendsto_iff_rtendsto (l₁ : filter α) (l₂ : filter β) (f : α → β) :
tendsto f l₁ l₂ ↔ rtendsto (function.graph f) l₁ l₂ :=
by { simp [tendsto_def, function.graph, rtendsto_def, rel.core, set.preimage] }
theorem tendsto_iff_rtendsto' (l₁ : filter α) (l₂ : filter β) (f : α → β) :
tendsto f l₁ l₂ ↔ rtendsto' (function.graph f) l₁ l₂ :=
by { simp [tendsto_def, function.graph, rtendsto'_def, rel.preimage_def, set.preimage] }
/-! ### Partial functions -/
/-- The forward map of a filter under a partial function. Generalization of `filter.map` to partial
functions. -/
def pmap (f : α →. β) (l : filter α) : filter β :=
filter.rmap f.graph' l
@[simp]
lemma mem_pmap (f : α →. β) (l : filter α) (s : set β) : s ∈ l.pmap f ↔ f.core s ∈ l :=
iff.rfl
/-- Generic "limit of a partial function" predicate. `ptendsto r l₁ l₂` asserts that for every
`l₂`-neighborhood `a`, the `p`-core of `a` is an `l₁`-neighborhood. One generalization of
`filter.tendsto` to partial function. -/
def ptendsto (f : α →. β) (l₁ : filter α) (l₂ : filter β) := l₁.pmap f ≤ l₂
theorem ptendsto_def (f : α →. β) (l₁ : filter α) (l₂ : filter β) :
ptendsto f l₁ l₂ ↔ ∀ s ∈ l₂, f.core s ∈ l₁ :=
iff.rfl
theorem ptendsto_iff_rtendsto (l₁ : filter α) (l₂ : filter β) (f : α →. β) :
ptendsto f l₁ l₂ ↔ rtendsto f.graph' l₁ l₂ :=
iff.rfl
theorem pmap_res (l : filter α) (s : set α) (f : α → β) :
pmap (pfun.res f s) l = map f (l ⊓ 𝓟 s) :=
begin
ext t,
simp only [pfun.core_res, mem_pmap, mem_map, mem_inf_principal, imp_iff_not_or],
refl
end
theorem tendsto_iff_ptendsto (l₁ : filter α) (l₂ : filter β) (s : set α) (f : α → β) :
tendsto f (l₁ ⊓ 𝓟 s) l₂ ↔ ptendsto (pfun.res f s) l₁ l₂ :=
by simp only [tendsto, ptendsto, pmap_res]
theorem tendsto_iff_ptendsto_univ (l₁ : filter α) (l₂ : filter β) (f : α → β) :
tendsto f l₁ l₂ ↔ ptendsto (pfun.res f set.univ) l₁ l₂ :=
by { rw ← tendsto_iff_ptendsto, simp [principal_univ] }
/-- Inverse map of a filter under a partial function. One generalization of `filter.comap` to
partial functions. -/
def pcomap' (f : α →. β) (l : filter β) : filter α :=
filter.rcomap' f.graph' l
/-- Generic "limit of a partial function" predicate. `ptendsto' r l₁ l₂` asserts that for every
`l₂`-neighborhood `a`, the `p`-preimage of `a` is an `l₁`-neighborhood. One generalization of
`filter.tendsto` to partial functions. -/
def ptendsto' (f : α →. β) (l₁ : filter α) (l₂ : filter β) := l₁ ≤ l₂.rcomap' f.graph'
theorem ptendsto'_def (f : α →. β) (l₁ : filter α) (l₂ : filter β) :
ptendsto' f l₁ l₂ ↔ ∀ s ∈ l₂, f.preimage s ∈ l₁ :=
rtendsto'_def _ _ _
theorem ptendsto_of_ptendsto' {f : α →. β} {l₁ : filter α} {l₂ : filter β} :
ptendsto' f l₁ l₂ → ptendsto f l₁ l₂ :=
begin
rw [ptendsto_def, ptendsto'_def],
exact λ h s sl₂, mem_of_superset (h s sl₂) (pfun.preimage_subset_core _ _),
end
theorem ptendsto'_of_ptendsto {f : α →. β} {l₁ : filter α} {l₂ : filter β} (h : f.dom ∈ l₁) :
ptendsto f l₁ l₂ → ptendsto' f l₁ l₂ :=
begin
rw [ptendsto_def, ptendsto'_def],
intros h' s sl₂,
rw pfun.preimage_eq,
exact inter_mem (h' s sl₂) h
end
end filter
|
809c0a3fcf0cd1858184a999211dad3fe9ef0ab8 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/category_theory/monoidal/preadditive.lean | 9e9e69a16954d458d8b94c616ef159adea7c82e2 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 8,859 | 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.additive_functor
import category_theory.monoidal.category
/-!
# Preadditive monoidal categories
A monoidal category is `monoidal_preadditive` if it is preadditive and tensor product of morphisms
is linear in both factors.
-/
noncomputable theory
namespace category_theory
open category_theory.limits
open category_theory.monoidal_category
variables (C : Type*) [category C] [preadditive C] [monoidal_category C]
/--
A category is `monoidal_preadditive` if tensoring is additive in both factors.
Note we don't `extend preadditive C` here, as `abelian C` already extends it,
and we'll need to have both typeclasses sometimes.
-/
class monoidal_preadditive :=
(tensor_zero' : ∀ {W X Y Z : C} (f : W ⟶ X), f ⊗ (0 : Y ⟶ Z) = 0 . obviously)
(zero_tensor' : ∀ {W X Y Z : C} (f : Y ⟶ Z), (0 : W ⟶ X) ⊗ f = 0 . obviously)
(tensor_add' : ∀ {W X Y Z : C} (f : W ⟶ X) (g h : Y ⟶ Z), f ⊗ (g + h) = f ⊗ g + f ⊗ h . obviously)
(add_tensor' : ∀ {W X Y Z : C} (f g : W ⟶ X) (h : Y ⟶ Z), (f + g) ⊗ h = f ⊗ h + g ⊗ h . obviously)
restate_axiom monoidal_preadditive.tensor_zero'
restate_axiom monoidal_preadditive.zero_tensor'
restate_axiom monoidal_preadditive.tensor_add'
restate_axiom monoidal_preadditive.add_tensor'
attribute [simp] monoidal_preadditive.tensor_zero monoidal_preadditive.zero_tensor
variables [monoidal_preadditive C]
local attribute [simp] monoidal_preadditive.tensor_add monoidal_preadditive.add_tensor
instance tensor_left_additive (X : C) : (tensor_left X).additive := {}
instance tensor_right_additive (X : C) : (tensor_right X).additive := {}
instance tensoring_left_additive (X : C) : ((tensoring_left C).obj X).additive := {}
instance tensoring_right_additive (X : C) : ((tensoring_right C).obj X).additive := {}
open_locale big_operators
lemma tensor_sum {P Q R S : C} {J : Type*} (s : finset J) (f : P ⟶ Q) (g : J → (R ⟶ S)) :
f ⊗ ∑ j in s, g j = ∑ j in s, f ⊗ g j :=
begin
rw ←tensor_id_comp_id_tensor,
let tQ := (((tensoring_left C).obj Q).map_add_hom : (R ⟶ S) →+ _),
change _ ≫ tQ _ = _,
rw [tQ.map_sum, preadditive.comp_sum],
dsimp [tQ],
simp only [tensor_id_comp_id_tensor],
end
lemma sum_tensor {P Q R S : C} {J : Type*} (s : finset J) (f : P ⟶ Q) (g : J → (R ⟶ S)) :
(∑ j in s, g j) ⊗ f = ∑ j in s, g j ⊗ f :=
begin
rw ←tensor_id_comp_id_tensor,
let tQ := (((tensoring_right C).obj P).map_add_hom : (R ⟶ S) →+ _),
change tQ _ ≫ _ = _,
rw [tQ.map_sum, preadditive.sum_comp],
dsimp [tQ],
simp only [tensor_id_comp_id_tensor],
end
variables {C}
-- In a closed monoidal category, this would hold because
-- `tensor_left X` is a left adjoint and hence preserves all colimits.
-- In any case it is true in any preadditive category.
instance (X : C) : preserves_finite_biproducts (tensor_left X) :=
{ preserves := λ J _ _, by exactI
{ preserves := λ f,
{ preserves := λ b i, is_bilimit_of_total _ begin
dsimp,
simp only [←tensor_comp, category.comp_id, ←tensor_sum, ←tensor_id, is_bilimit.total i],
end } } }
instance (X : C) : preserves_finite_biproducts (tensor_right X) :=
{ preserves := λ J _ _, by exactI
{ preserves := λ f,
{ preserves := λ b i, is_bilimit_of_total _ begin
dsimp,
simp only [←tensor_comp, category.comp_id, ←sum_tensor, ←tensor_id, is_bilimit.total i],
end } } }
variables [has_finite_biproducts C]
/-- The isomorphism showing how tensor product on the left distributes over direct sums. -/
def left_distributor {J : Type*} [decidable_eq J] [fintype J] (X : C) (f : J → C) :
X ⊗ (⨁ f) ≅ ⨁ (λ j, X ⊗ f j) :=
(tensor_left X).map_biproduct f
@[simp]
lemma left_distributor_hom {J : Type*} [decidable_eq J] [fintype J] (X : C) (f : J → C) :
(left_distributor X f).hom = ∑ j : J, (𝟙 X ⊗ biproduct.π f j) ≫ biproduct.ι _ j :=
begin
ext, dsimp [tensor_left, left_distributor],
simp [preadditive.sum_comp, biproduct.ι_π, comp_dite],
end
@[simp]
lemma left_distributor_inv {J : Type*} [decidable_eq J] [fintype J] (X : C) (f : J → C) :
(left_distributor X f).inv = ∑ j : J, biproduct.π _ j ≫ (𝟙 X ⊗ biproduct.ι f j) :=
begin
ext, dsimp [tensor_left, left_distributor],
simp [preadditive.comp_sum, biproduct.ι_π_assoc, dite_comp],
end
lemma left_distributor_assoc {J : Type*} [decidable_eq J] [fintype J] (X Y : C) (f : J → C) :
(as_iso (𝟙 X) ⊗ left_distributor Y f) ≪≫ left_distributor X _ =
(α_ X Y (⨁ f)).symm ≪≫ left_distributor (X ⊗ Y) f ≪≫ biproduct.map_iso (λ j, α_ X Y _) :=
begin
ext,
simp only [category.comp_id, category.assoc, eq_to_hom_refl,
iso.trans_hom, iso.symm_hom, as_iso_hom, comp_zero, comp_dite,
preadditive.sum_comp, preadditive.comp_sum,
tensor_sum, id_tensor_comp, tensor_iso_hom, left_distributor_hom,
biproduct.map_iso_hom, biproduct.ι_map, biproduct.ι_π,
finset.sum_dite_irrel, finset.sum_dite_eq', finset.sum_const_zero],
simp only [←id_tensor_comp, biproduct.ι_π],
simp only [id_tensor_comp, tensor_dite, comp_dite],
simp only [category.comp_id, comp_zero, monoidal_preadditive.tensor_zero, eq_to_hom_refl,
tensor_id, if_true, dif_ctx_congr, finset.sum_congr, finset.mem_univ, finset.sum_dite_eq'],
simp only [←tensor_id, associator_naturality, iso.inv_hom_id_assoc],
end
/-- The isomorphism showing how tensor product on the right distributes over direct sums. -/
def right_distributor {J : Type*} [decidable_eq J] [fintype J] (X : C) (f : J → C) :
(⨁ f) ⊗ X ≅ ⨁ (λ j, f j ⊗ X) :=
(tensor_right X).map_biproduct f
@[simp]
lemma right_distributor_hom {J : Type*} [decidable_eq J] [fintype J] (X : C) (f : J → C) :
(right_distributor X f).hom = ∑ j : J, (biproduct.π f j ⊗ 𝟙 X) ≫ biproduct.ι _ j :=
begin
ext, dsimp [tensor_right, right_distributor],
simp [preadditive.sum_comp, biproduct.ι_π, comp_dite],
end
@[simp]
lemma right_distributor_inv {J : Type*} [decidable_eq J] [fintype J] (X : C) (f : J → C) :
(right_distributor X f).inv = ∑ j : J, biproduct.π _ j ≫ (biproduct.ι f j ⊗ 𝟙 X) :=
begin
ext, dsimp [tensor_right, right_distributor],
simp [preadditive.comp_sum, biproduct.ι_π_assoc, dite_comp],
end
lemma right_distributor_assoc {J : Type*} [decidable_eq J] [fintype J] (X Y : C) (f : J → C) :
(right_distributor X f ⊗ as_iso (𝟙 Y)) ≪≫ right_distributor Y _ =
α_ (⨁ f) X Y ≪≫ right_distributor (X ⊗ Y) f ≪≫ biproduct.map_iso (λ j, (α_ _ X Y).symm) :=
begin
ext,
simp only [category.comp_id, category.assoc, eq_to_hom_refl, iso.symm_hom,
iso.trans_hom, as_iso_hom, comp_zero, comp_dite, preadditive.sum_comp, preadditive.comp_sum,
sum_tensor, comp_tensor_id, tensor_iso_hom, right_distributor_hom,
biproduct.map_iso_hom, biproduct.ι_map, biproduct.ι_π,
finset.sum_dite_irrel, finset.sum_dite_eq', finset.sum_const_zero, finset.mem_univ, if_true],
simp only [←comp_tensor_id, biproduct.ι_π, dite_tensor, comp_dite],
simp only [category.comp_id, comp_tensor_id, eq_to_hom_refl, tensor_id, comp_zero,
monoidal_preadditive.zero_tensor,
if_true, dif_ctx_congr, finset.mem_univ, finset.sum_congr, finset.sum_dite_eq'],
simp only [←tensor_id, associator_inv_naturality, iso.hom_inv_id_assoc]
end
lemma left_distributor_right_distributor_assoc
{J : Type*} [decidable_eq J] [fintype J] (X Y : C) (f : J → C) :
(left_distributor X f ⊗ as_iso (𝟙 Y)) ≪≫ right_distributor Y _ =
α_ X (⨁ f) Y ≪≫ (as_iso (𝟙 X) ⊗ right_distributor Y _) ≪≫ left_distributor X _ ≪≫
biproduct.map_iso (λ j, (α_ _ _ _).symm) :=
begin
ext,
simp only [category.comp_id, category.assoc, eq_to_hom_refl, iso.symm_hom,
iso.trans_hom, as_iso_hom, comp_zero, comp_dite, preadditive.sum_comp, preadditive.comp_sum,
sum_tensor, tensor_sum, comp_tensor_id, tensor_iso_hom,
left_distributor_hom, right_distributor_hom,
biproduct.map_iso_hom, biproduct.ι_map, biproduct.ι_π,
finset.sum_dite_irrel, finset.sum_dite_eq', finset.sum_const_zero, finset.mem_univ, if_true],
simp only [←comp_tensor_id, ←id_tensor_comp_assoc, category.assoc, biproduct.ι_π,
comp_dite, dite_comp, tensor_dite, dite_tensor],
simp only [category.comp_id, category.id_comp, category.assoc, id_tensor_comp,
comp_zero, zero_comp, monoidal_preadditive.tensor_zero, monoidal_preadditive.zero_tensor,
comp_tensor_id, eq_to_hom_refl, tensor_id,
if_true, dif_ctx_congr, finset.sum_congr, finset.mem_univ, finset.sum_dite_eq'],
simp only [associator_inv_naturality, iso.hom_inv_id_assoc]
end
end category_theory
|
d64419f22d71dc50dc01e3ff149723f223a22102 | ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5 | /tests/compiler/lazylist.lean | 4c0df537d45d2411bfd21e5f93ee1c899b2ed772 | [
"Apache-2.0"
] | permissive | dupuisf/lean4 | d082d13b01243e1de29ae680eefb476961221eef | 6a39c65bd28eb0e28c3870188f348c8914502718 | refs/heads/master | 1,676,948,755,391 | 1,610,665,114,000 | 1,610,665,114,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,909 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
universes u v w
inductive LazyList (α : Type u)
| nil : LazyList α
| cons (hd : α) (tl : LazyList α) : LazyList α
| delayed (t : Thunk $ LazyList α) : LazyList α
@[extern c inline "#2"]
def List.toLazy {α : Type u} : List α → LazyList α
| [] => LazyList.nil
| h::t => LazyList.cons h (toLazy t)
namespace LazyList
variables {α : Type u} {β : Type v} {δ : Type w}
instance : Inhabited (LazyList α) :=
⟨nil⟩
@[inline] def pure : α → LazyList α
| a => cons a nil
partial def isEmpty : LazyList α → Bool
| nil => true
| cons _ _ => false
| delayed as => isEmpty as.get
partial def toList : LazyList α → List α
| nil => []
| cons a as => a :: toList as
| delayed as => toList as.get
partial def head [Inhabited α] : LazyList α → α
| nil => arbitrary
| cons a as => a
| delayed as => head as.get
partial def tail : LazyList α → LazyList α
| nil => nil
| cons a as => as
| delayed as => tail as.get
partial def append : LazyList α → LazyList α → LazyList α
| nil, bs => bs
| cons a as, bs => delayed (cons a (append as bs))
| delayed as, bs => delayed (append as.get bs)
instance : Append (LazyList α) :=
⟨LazyList.append⟩
partial def interleave : LazyList α → LazyList α → LazyList α
| nil, bs => bs
| cons a as, bs => delayed (cons a (interleave bs as))
| delayed as, bs => delayed (interleave as.get bs)
partial def map (f : α → β) : LazyList α → LazyList β
| nil => nil
| cons a as => delayed (cons (f a) (map f as))
| delayed as => delayed (map f as.get)
partial def map₂ (f : α → β → δ) : LazyList α → LazyList β → LazyList δ
| nil, _ => nil
| _, nil => nil
| cons a as, cons b bs => delayed (cons (f a b) (map₂ f as bs))
| delayed as, bs => delayed (map₂ f as.get bs)
| as, delayed bs => delayed (map₂ f as bs.get)
@[inline] def zip : LazyList α → LazyList β → LazyList (α × β) :=
map₂ Prod.mk
partial def join : LazyList (LazyList α) → LazyList α
| nil => nil
| cons a as => delayed (append a (join as))
| delayed as => delayed (join as.get)
@[inline] partial def bind (x : LazyList α) (f : α → LazyList β) : LazyList β :=
join (x.map f)
instance isMonad : Monad LazyList :=
{ pure := @LazyList.pure, bind := @LazyList.bind, map := @LazyList.map }
instance : Alternative LazyList :=
{ LazyList.isMonad with
failure := nil,
orElse := LazyList.append }
partial def approx : Nat → LazyList α → List α
| 0, as => []
| _, nil => []
| i+1, cons a as => a :: approx i as
| i+1, delayed as => approx (i+1) as.get
partial def iterate (f : α → α) : α → LazyList α
| x => cons x (delayed (iterate f (f x)))
partial def iterate₂ (f : α → α → α) : α → α → LazyList α
| x, y => cons x (delayed (iterate₂ f y (f x y)))
partial def filter (p : α → Bool) : LazyList α → LazyList α
| nil => nil
| cons a as => delayed (if p a then cons a (filter p as) else filter p as)
| delayed as => delayed (filter p as.get)
end LazyList
def fib : LazyList Nat :=
LazyList.iterate₂ (· + ·) 0 1
def iota (i : Nat := 0) : LazyList Nat :=
LazyList.iterate Nat.succ i
def tst : LazyList String := do
let x ← [1, 2, 3].toLazy;
let y ← [2, 3, 4].toLazy;
guard (x + y > 5);
pure s!"{x} + {y} = {x+y}"
def main : IO Unit := do
let n := 40;
IO.println tst.isEmpty;
IO.println tst.head;
IO.println <| fib.interleave (iota.map (· + 100)) |>.approx n;
IO.println <| iota.map (· + 10) |>.filter (· % 2 == 0) |>.approx n
|
59673724f7ef1ed9d8c084389397a322238f5c94 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebraic_topology/split_simplicial_object.lean | 718739e71a906f1fe4f8587cbc00349a00cc9b4b | [
"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 | 13,770 | lean | /-
Copyright (c) 2022 Joël Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joël Riou
-/
import algebraic_topology.simplicial_object
import category_theory.limits.shapes.finite_products
/-!
# Split simplicial objects
In this file, we introduce the notion of split simplicial object.
If `C` is a category that has finite coproducts, a splitting
`s : splitting X` of a simplical object `X` in `C` consists
of the datum of a sequence of objects `s.N : ℕ → C` (which
we shall refer to as "nondegenerate simplices") and a
sequence of morphisms `s.ι n : s.N n → X _[n]` that have
the property that a certain canonical map identifies `X _[n]`
with the coproduct of objects `s.N i` indexed by all possible
epimorphisms `[n] ⟶ [i]` in `simplex_category`. (We do not
assume that the morphisms `s.ι n` are monomorphisms: in the
most common categories, this would be a consequence of the
axioms.)
Simplicial objects equipped with a splitting form a category
`simplicial_object.split C`.
## References
* [Stacks: Splitting simplicial objects] https://stacks.math.columbia.edu/tag/017O
-/
noncomputable theory
open category_theory category_theory.category category_theory.limits
opposite simplex_category
open_locale simplicial
universe u
variables {C : Type*} [category C]
namespace simplicial_object
namespace splitting
/-- The index set which appears in the definition of split simplicial objects. -/
def index_set (Δ : simplex_categoryᵒᵖ) :=
Σ (Δ' : simplex_categoryᵒᵖ), { α : Δ.unop ⟶ Δ'.unop // epi α }
namespace index_set
/-- The element in `splitting.index_set Δ` attached to an epimorphism `f : Δ ⟶ Δ'`. -/
@[simps]
def mk {Δ Δ' : simplex_category} (f : Δ ⟶ Δ') [epi f] : index_set (op Δ) :=
⟨op Δ', f, infer_instance⟩
variables {Δ' Δ : simplex_categoryᵒᵖ} (A : index_set Δ)
/-- The epimorphism in `simplex_category` associated to `A : splitting.index_set Δ` -/
def e := A.2.1
instance : epi A.e := A.2.2
lemma ext' : A = ⟨A.1, ⟨A.e, A.2.2⟩⟩ := by tidy
lemma ext (A₁ A₂ : index_set Δ) (h₁ : A₁.1 = A₂.1)
(h₂ : A₁.e ≫ eq_to_hom (by rw h₁) = A₂.e) : A₁ = A₂ :=
begin
rcases A₁ with ⟨Δ₁, ⟨α₁, hα₁⟩⟩,
rcases A₂ with ⟨Δ₂, ⟨α₂, hα₂⟩⟩,
simp only at h₁,
subst h₁,
simp only [eq_to_hom_refl, comp_id, index_set.e] at h₂,
simp only [h₂],
end
instance : fintype (index_set Δ) :=
fintype.of_injective
((λ A, ⟨⟨A.1.unop.len, nat.lt_succ_iff.mpr
(len_le_of_epi (infer_instance : epi A.e))⟩, A.e.to_order_hom⟩) :
index_set Δ → (sigma (λ (k : fin (Δ.unop.len+1)), (fin (Δ.unop.len+1) → fin (k+1)))))
begin
rintros ⟨Δ₁, α₁⟩ ⟨Δ₂, α₂⟩ h₁,
induction Δ₁ using opposite.rec,
induction Δ₂ using opposite.rec,
simp only at h₁,
have h₂ : Δ₁ = Δ₂ := by { ext1, simpa only [fin.mk_eq_mk] using h₁.1, },
subst h₂,
refine ext _ _ rfl _,
ext : 2,
exact eq_of_heq h₁.2,
end
variable (Δ)
/-- The distinguished element in `splitting.index_set Δ` which corresponds to the
identity of `Δ`. -/
def id : index_set Δ := ⟨Δ, ⟨𝟙 _, by apply_instance,⟩⟩
instance : inhabited (index_set Δ) := ⟨id Δ⟩
variable {Δ}
/-- The condition that an element `splitting.index_set Δ` is the distinguished
element `splitting.index_set.id Δ`. -/
@[simp]
def eq_id : Prop := A = id _
lemma eq_id_iff_eq : A.eq_id ↔ A.1 = Δ :=
begin
split,
{ intro h,
dsimp at h,
rw h,
refl, },
{ intro h,
rcases A with ⟨Δ', ⟨f, hf⟩⟩,
simp only at h,
subst h,
refine ext _ _ rfl _,
{ haveI := hf,
simp only [eq_to_hom_refl, comp_id],
exact eq_id_of_epi f, }, },
end
lemma eq_id_iff_len_eq : A.eq_id ↔ A.1.unop.len = Δ.unop.len :=
begin
rw eq_id_iff_eq,
split,
{ intro h,
rw h, },
{ intro h,
rw ← unop_inj_iff,
ext,
exact h, },
end
lemma eq_id_iff_len_le : A.eq_id ↔ Δ.unop.len ≤ A.1.unop.len :=
begin
rw eq_id_iff_len_eq,
split,
{ intro h,
rw h, },
{ exact le_antisymm (len_le_of_epi (infer_instance : epi A.e)), },
end
lemma eq_id_iff_mono : A.eq_id ↔ mono A.e :=
begin
split,
{ intro h,
dsimp at h,
subst h,
dsimp only [id, e],
apply_instance, },
{ intro h,
rw eq_id_iff_len_le,
exact len_le_of_mono h, }
end
/-- Given `A : index_set Δ₁`, if `p.unop : unop Δ₂ ⟶ unop Δ₁` is an epi, this
is the obvious element in `A : index_set Δ₂` associated to the composition
of epimorphisms `p.unop ≫ A.e`. -/
@[simps]
def epi_comp {Δ₁ Δ₂ : simplex_categoryᵒᵖ} (A : index_set Δ₁) (p : Δ₁ ⟶ Δ₂) [epi p.unop] :
index_set Δ₂ := ⟨A.1, ⟨p.unop ≫ A.e, epi_comp _ _⟩⟩
end index_set
variables (N : ℕ → C) (Δ : simplex_categoryᵒᵖ)
(X : simplicial_object C) (φ : Π n, N n ⟶ X _[n])
/-- Given a sequences of objects `N : ℕ → C` in a category `C`, this is
a family of objects indexed by the elements `A : splitting.index_set Δ`.
The `Δ`-simplices of a split simplicial objects shall identify to the
coproduct of objects in such a family. -/
@[simp, nolint unused_arguments]
def summand (A : index_set Δ) : C := N A.1.unop.len
variable [has_finite_coproducts C]
/-- The coproduct of the family `summand N Δ` -/
@[simp]
def coprod := ∐ summand N Δ
variable {Δ}
/-- The inclusion of a summand in the coproduct. -/
@[simp]
def ι_coprod (A : index_set Δ) : N A.1.unop.len ⟶ coprod N Δ := sigma.ι _ A
variables {N}
/-- The canonical morphism `coprod N Δ ⟶ X.obj Δ` attached to a sequence
of objects `N` and a sequence of morphisms `N n ⟶ X _[n]`. -/
@[simp]
def map (Δ : simplex_categoryᵒᵖ) : coprod N Δ ⟶ X.obj Δ :=
sigma.desc (λ A, φ A.1.unop.len ≫ X.map A.e.op)
end splitting
variable [has_finite_coproducts C]
/-- A splitting of a simplicial object `X` consists of the datum of a sequence
of objects `N`, a sequence of morphisms `ι : N n ⟶ X _[n]` such that
for all `Δ : simplex_categoryhᵒᵖ`, the canonical map `splitting.map X ι Δ`
is an isomorphism. -/
@[nolint has_nonempty_instance]
structure splitting (X : simplicial_object C) :=
(N : ℕ → C)
(ι : Π n, N n ⟶ X _[n])
(map_is_iso' : ∀ (Δ : simplex_categoryᵒᵖ), is_iso (splitting.map X ι Δ))
namespace splitting
variables {X Y : simplicial_object C} (s : splitting X)
instance map_is_iso (Δ : simplex_categoryᵒᵖ) : is_iso (splitting.map X s.ι Δ) :=
s.map_is_iso' Δ
/-- The isomorphism on simplices given by the axiom `splitting.map_is_iso'` -/
@[simps]
def iso (Δ : simplex_categoryᵒᵖ) : coprod s.N Δ ≅ X.obj Δ :=
as_iso (splitting.map X s.ι Δ)
/-- Via the isomorphism `s.iso Δ`, this is the inclusion of a summand
in the direct sum decomposition given by the splitting `s : splitting X`. -/
def ι_summand {Δ : simplex_categoryᵒᵖ} (A : index_set Δ) :
s.N A.1.unop.len ⟶ X.obj Δ :=
splitting.ι_coprod s.N A ≫ (s.iso Δ).hom
@[reassoc]
lemma ι_summand_eq {Δ : simplex_categoryᵒᵖ} (A : index_set Δ) :
s.ι_summand A = s.ι A.1.unop.len ≫ X.map A.e.op :=
begin
dsimp only [ι_summand, iso.hom],
erw [colimit.ι_desc, cofan.mk_ι_app],
end
lemma ι_summand_id (n : ℕ) : s.ι_summand (index_set.id (op [n])) = s.ι n :=
by { erw [ι_summand_eq, X.map_id, comp_id], refl, }
/-- As it is stated in `splitting.hom_ext`, a morphism `f : X ⟶ Y` from a split
simplicial object to any simplicial object is determined by its restrictions
`s.φ f n : s.N n ⟶ Y _[n]` to the distinguished summands in each degree `n`. -/
@[simp]
def φ (f : X ⟶ Y) (n : ℕ) : s.N n ⟶ Y _[n] := s.ι n ≫ f.app (op [n])
@[simp, reassoc]
lemma ι_summand_comp_app (f : X ⟶ Y) {Δ : simplex_categoryᵒᵖ} (A : index_set Δ) :
s.ι_summand A ≫ f.app Δ = s.φ f A.1.unop.len ≫ Y.map A.e.op :=
by simp only [ι_summand_eq_assoc, φ, nat_trans.naturality, assoc]
lemma hom_ext' {Z : C} {Δ : simplex_categoryᵒᵖ} (f g : X.obj Δ ⟶ Z)
(h : ∀ (A : index_set Δ), s.ι_summand A ≫ f = s.ι_summand A ≫ g) :
f = g :=
begin
rw ← cancel_epi (s.iso Δ).hom,
ext A,
discrete_cases,
simpa only [ι_summand_eq, iso_hom, colimit.ι_desc_assoc, cofan.mk_ι_app, assoc] using h A,
end
lemma hom_ext (f g : X ⟶ Y) (h : ∀ n : ℕ, s.φ f n = s.φ g n) : f = g :=
begin
ext Δ,
apply s.hom_ext',
intro A,
induction Δ using opposite.rec,
induction Δ using simplex_category.rec with n,
dsimp,
simp only [s.ι_summand_comp_app, h],
end
/-- The map `X.obj Δ ⟶ Z` obtained by providing a family of morphisms on all the
terms of decomposition given by a splitting `s : splitting X` -/
def desc {Z : C} (Δ : simplex_categoryᵒᵖ)
(F : Π (A : index_set Δ), s.N A.1.unop.len ⟶ Z) : X.obj Δ ⟶ Z :=
(s.iso Δ).inv ≫ sigma.desc F
@[simp, reassoc]
lemma ι_desc {Z : C} (Δ : simplex_categoryᵒᵖ)
(F : Π (A : index_set Δ), s.N A.1.unop.len ⟶ Z) (A : index_set Δ) :
s.ι_summand A ≫ s.desc Δ F = F A :=
begin
dsimp only [ι_summand, desc],
simp only [assoc, iso.hom_inv_id_assoc, ι_coprod],
erw [colimit.ι_desc, cofan.mk_ι_app],
end
/-- A simplicial object that is isomorphic to a split simplicial object is split. -/
@[simps]
def of_iso (e : X ≅ Y) : splitting Y :=
{ N := s.N,
ι := λ n, s.ι n ≫ e.hom.app (op [n]),
map_is_iso' := λ Δ, begin
convert (infer_instance : is_iso ((s.iso Δ).hom ≫ e.hom.app Δ)),
tidy,
end, }
@[reassoc]
lemma ι_summand_epi_naturality {Δ₁ Δ₂ : simplex_categoryᵒᵖ} (A : index_set Δ₁)
(p : Δ₁ ⟶ Δ₂) [epi p.unop] :
s.ι_summand A ≫ X.map p = s.ι_summand (A.epi_comp p) :=
begin
dsimp [ι_summand],
erw [colimit.ι_desc, colimit.ι_desc, cofan.mk_ι_app, cofan.mk_ι_app],
dsimp only [index_set.epi_comp, index_set.e],
rw [op_comp, X.map_comp, assoc, quiver.hom.op_unop],
end
end splitting
variable (C)
/-- The category `simplicial_object.split C` is the category of simplicial objects
in `C` equipped with a splitting, and morphisms are morphisms of simplicial objects
which are compatible with the splittings. -/
@[ext, nolint has_nonempty_instance]
structure split := (X : simplicial_object C) (s : splitting X)
namespace split
variable {C}
/-- The object in `simplicial_object.split C` attached to a splitting `s : splitting X`
of a simplicial object `X`. -/
@[simps]
def mk' {X : simplicial_object C} (s : splitting X) : split C := ⟨X, s⟩
/-- Morphisms in `simplicial_object.split C` are morphisms of simplicial objects that
are compatible with the splittings. -/
@[nolint has_nonempty_instance]
structure hom (S₁ S₂ : split C) :=
(F : S₁.X ⟶ S₂.X)
(f : Π (n : ℕ), S₁.s.N n ⟶ S₂.s.N n)
(comm' : ∀ (n : ℕ), S₁.s.ι n ≫ F.app (op [n]) = f n ≫ S₂.s.ι n)
@[ext]
lemma hom.ext {S₁ S₂ : split C} (Φ₁ Φ₂ : hom S₁ S₂) (h : ∀ (n : ℕ), Φ₁.f n = Φ₂.f n) :
Φ₁ = Φ₂ :=
begin
rcases Φ₁ with ⟨F₁, f₁, c₁⟩,
rcases Φ₂ with ⟨F₂, f₂, c₂⟩,
have h' : f₁ = f₂ := by { ext, apply h, },
subst h',
simp only [eq_self_iff_true, and_true],
apply S₁.s.hom_ext,
intro n,
dsimp,
rw [c₁, c₂],
end
restate_axiom hom.comm'
attribute [simp, reassoc] hom.comm
end split
instance : category (split C) :=
{ hom := split.hom,
id := λ S, { F := 𝟙 _, f := λ n, 𝟙 _, comm' := by tidy, },
comp := λ S₁ S₂ S₃ Φ₁₂ Φ₂₃,
{ F := Φ₁₂.F ≫ Φ₂₃.F, f := λ n, Φ₁₂.f n ≫ Φ₂₃.f n, comm' := by tidy, }, }
variable {C}
namespace split
lemma congr_F {S₁ S₂ : split C} {Φ₁ Φ₂ : S₁ ⟶ S₂} (h : Φ₁ = Φ₂) : Φ₁.F = Φ₂.F := by rw h
lemma congr_f {S₁ S₂ : split C} {Φ₁ Φ₂ : S₁ ⟶ S₂} (h : Φ₁ = Φ₂) (n : ℕ) :
Φ₁.f n = Φ₂.f n := by rw h
@[simp]
lemma id_F (S : split C) : (𝟙 S : S ⟶ S).F = 𝟙 (S.X) := rfl
@[simp]
lemma id_f (S : split C) (n : ℕ) : (𝟙 S : S ⟶ S).f n = 𝟙 (S.s.N n) := rfl
@[simp]
lemma comp_F {S₁ S₂ S₃ : split C} (Φ₁₂ : S₁ ⟶ S₂) (Φ₂₃ : S₂ ⟶ S₃) :
(Φ₁₂ ≫ Φ₂₃).F = Φ₁₂.F ≫ Φ₂₃.F := rfl
@[simp]
lemma comp_f {S₁ S₂ S₃ : split C} (Φ₁₂ : S₁ ⟶ S₂) (Φ₂₃ : S₂ ⟶ S₃) (n : ℕ) :
(Φ₁₂ ≫ Φ₂₃).f n = Φ₁₂.f n ≫ Φ₂₃.f n := rfl
@[simp, reassoc]
lemma ι_summand_naturality_symm {S₁ S₂ : split C} (Φ : S₁ ⟶ S₂)
{Δ : simplex_categoryᵒᵖ} (A : splitting.index_set Δ) :
S₁.s.ι_summand A ≫ Φ.F.app Δ = Φ.f A.1.unop.len ≫ S₂.s.ι_summand A :=
by rw [S₁.s.ι_summand_eq, S₂.s.ι_summand_eq, assoc, Φ.F.naturality, ← Φ.comm_assoc]
variable (C)
/-- The functor `simplicial_object.split C ⥤ simplicial_object C` which forgets
the splitting. -/
@[simps]
def forget : split C ⥤ simplicial_object C :=
{ obj := λ S, S.X,
map := λ S₁ S₂ Φ, Φ.F, }
/-- The functor `simplicial_object.split C ⥤ C` which sends a simplicial object equipped
with a splitting to its nondegenerate `n`-simplices. -/
@[simps]
def eval_N (n : ℕ) : split C ⥤ C :=
{ obj := λ S, S.s.N n,
map := λ S₁ S₂ Φ, Φ.f n, }
/-- The inclusion of each summand in the coproduct decomposition of simplices
in split simplicial objects is a natural transformation of functors
`simplicial_object.split C ⥤ C` -/
@[simps]
def nat_trans_ι_summand {Δ : simplex_categoryᵒᵖ} (A : splitting.index_set Δ) :
eval_N C A.1.unop.len ⟶ forget C ⋙ (evaluation simplex_categoryᵒᵖ C).obj Δ :=
{ app := λ S, S.s.ι_summand A,
naturality' := λ S₁ S₂ Φ, (ι_summand_naturality_symm Φ A).symm, }
end split
end simplicial_object
|
cad9d63171101775b362033585d772f8c8077b17 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/analysis/complex/cauchy_integral.lean | 18fe7a89179125cc2cee8c06daebdccfe8f67dba | [
"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 | 36,813 | 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 measure_theory.measure.complex_lebesgue
import measure_theory.integral.divergence_theorem
import measure_theory.integral.circle_integral
import analysis.calculus.dslope
import analysis.analytic.basic
import analysis.complex.re_im_topology
import analysis.calculus.diff_cont_on_cl
import data.real.cardinality
/-!
# Cauchy integral formula
In this file we prove the Cauchy-Goursat theorem and the Cauchy integral formula for integrals over
circles. Most results are formulated for a function `f : ℂ → E` that takes values in a complex
Banach space with second countable topology.
## Main statements
In the following theorems, if the name ends with `off_countable`, then the actual theorem assumes
differentiability at all but countably many points of the set mentioned below.
* `complex.integral_boundary_rect_of_has_fderiv_within_at_real_off_countable`: If a function
`f : ℂ → E` is continuous on a closed rectangle and *real* differentiable on its interior, then
its integral over the boundary of this rectangle is equal to the integral of
`I • f' (x + y * I) 1 - f' (x + y * I) I` over the rectangle, where `f' z w : E` is the derivative
of `f` at `z` in the direction `w` and `I = complex.I` is the imaginary unit.
* `complex.integral_boundary_rect_eq_zero_of_differentiable_on_off_countable`: If a function
`f : ℂ → E` is continuous on a closed rectangle and is *complex* differentiable on its interior,
then its integral over the boundary of this rectangle is equal to zero.
* `complex.circle_integral_sub_center_inv_smul_eq_of_differentiable_on_annulus_off_countable`: If a
function `f : ℂ → E` is continuous on a closed annulus `{z | r ≤ |z - c| ≤ R}` and is complex
differentiable on its interior `{z | r < |z - c| < R}`, then the integrals of `(z - c)⁻¹ • f z`
over the outer boundary and over the inner boundary are equal.
* `complex.circle_integral_sub_center_inv_smul_of_differentiable_on_off_countable_of_tendsto`,
`complex.circle_integral_sub_center_inv_smul_of_differentiable_on_off_countable`:
If a function `f : ℂ → E` is continuous on a punctured closed disc `{z | |z - c| ≤ R ∧ z ≠ c}`, is
complex differentiable on the corresponding punctured open disc, and tends to `y` as `z → c`,
`z ≠ c`, then the integral of `(z - c)⁻¹ • f z` over the circle `|z - c| = R` is equal to
`2πiy`. In particular, if `f` is continuous on the whole closed disc and is complex differentiable
on the corresponding open disc, then this integral is equal to `2πif(c)`.
* `complex.circle_integral_sub_inv_smul_of_differentiable_on_off_countable`,
`complex.two_pi_I_inv_smul_circle_integral_sub_inv_smul_of_differentiable_on_off_countable`
**Cauchy integral formula**: if `f : ℂ → E` is continuous on a closed disc of radius `R` and is
complex differentiable on the corresponding open disc, then for any `w` in the corresponding open
disc the integral of `(z - w)⁻¹ • f z` over the boundary of the disc is equal to `2πif(w)`.
Two versions of the lemma put the multiplier `2πi` at the different sides of the equality.
* `complex.has_fpower_series_on_ball_of_differentiable_off_countable`: If `f : ℂ → E` is continuous
on a closed disc of positive radius and is complex differentiable on the corresponding open disc,
then it is analytic on the corresponding open disc, and the coefficients of the power series are
given by Cauchy integral formulas.
* `differentiable_on.has_fpower_series_on_ball`: If `f : ℂ → E` is complex differentiable on a
closed disc of positive radius, then it is analytic on the corresponding open disc, and the
coefficients of the power series are given by Cauchy integral formulas.
* `differentiable_on.analytic_at`, `differentiable.analytic_at`: If `f : ℂ → E` is differentiable
on a neighborhood of a point, then it is analytic at this point. In particular, if `f : ℂ → E`
is differentiable on the whole `ℂ`, then it is analytic at every point `z : ℂ`.
* `differentiable.has_power_series_on_ball`: If `f : ℂ → E` is differentiable everywhere then the
`cauchy_power_series f z R` is a formal power series representing `f` at `z` with infinite
radius of convergence (this holds for any choice of `0 < R`).
## Implementation details
The proof of the Cauchy integral formula in this file is based on a very general version of the
divergence theorem, see `measure_theory.integral_divergence_of_has_fderiv_within_at_off_countable`
(a version for functions defined on `fin (n + 1) → ℝ`),
`measure_theory.integral_divergence_prod_Icc_of_has_fderiv_within_at_off_countable_of_le`, and
`measure_theory.integral2_divergence_prod_of_has_fderiv_within_at_off_countable` (versions for
functions defined on `ℝ × ℝ`).
Usually, the divergence theorem is formulated for a $C^1$ smooth function. The theorems formulated
above deal with a function that is
* continuous on a closed box/rectangle;
* differentiable at all but countably many points of its interior;
* have divergence integrable over the closed box/rectangle.
First, we reformulate the theorem for a *real*-differentiable map `ℂ → E`, and relate the integral
of `f` over the boundary of a rectangle in `ℂ` to the integral of the derivative
$\frac{\partial f}{\partial \bar z}$ over the interior of this box. In particular, for a *complex*
differentiable function, the latter derivative is zero, hence the integral over the boundary of a
rectangle is zero. Thus we get the Cauchy-Goursat theorem for a rectangle in `ℂ`.
Next, we apply the this theorem to the function $F(z)=f(c+e^{z})$ on the rectangle
$[\ln r, \ln R]\times [0, 2\pi]$ to prove that
$$
\oint_{|z-c|=r}\frac{f(z)\,dz}{z-c}=\oint_{|z-c|=R}\frac{f(z)\,dz}{z-c}
$$
provided that `f` is continuous on the closed annulus `r ≤ |z - c| ≤ R` and is complex
differentiable on its interior `r < |z - c| < R` (possibly, at all but countably many points).
Here and below, we write $\frac{f(z)}{z-c}$ in the documentation while the actual lemmas use
`(z - c)⁻¹ • f z` because `f z` belongs to some Banach space over `ℂ` and `f z / (z - c)` is
undefined.
Taking the limit of this equality as `r` tends to `𝓝[>] 0`, we prove
$$
\oint_{|z-c|=R}\frac{f(z)\,dz}{z-c}=2\pi if(c)
$$
provided that `f` is continuous on the closed disc `|z - c| ≤ R` and is differentiable at all but
countably many points of its interior. This is the Cauchy integral formula for the center of a
circle. In particular, if we apply this function to `F z = (z - c) • f z`, then we get
$$
\oint_{|z-c|=R} f(z)\,dz=0.
$$
In order to deduce the Cauchy integral formula for any point `w`, `|w - c| < R`, we consider the
slope function `g : ℂ → E` given by `g z = (z - w)⁻¹ • (f z - f w)` if `z ≠ w` and `g w = f' w`.
This function satisfies assumptions of the previous theorem, so we have
$$
\oint_{|z-c|=R} \frac{f(z)\,dz}{z-w}=\oint_{|z-c|=R} \frac{f(w)\,dz}{z-w}=
\left(\oint_{|z-c|=R} \frac{dz}{z-w}\right)f(w).
$$
The latter integral was computed in `circle_integral.integral_sub_inv_of_mem_ball` and is equal to
`2 * π * complex.I`.
There is one more step in the actual proof. Since we allow `f` to be non-differentiable on a
countable set `s`, we cannot immediately claim that `g` is continuous at `w` if `w ∈ s`. So, we use
the proof outlined in the previous paragraph for `w ∉ s` (see
`complex.circle_integral_sub_inv_smul_of_differentiable_on_off_countable_aux`), then use continuity
of both sides of the formula and density of `sᶜ` to prove the formula for all points of the open
ball, see `complex.circle_integral_sub_inv_smul_of_differentiable_on_off_countable`.
Finally, we use the properties of the Cauchy integrals established elsewhere (see
`has_fpower_series_on_cauchy_integral`) and Cauchy integral formula to prove that the original
function is analytic on the open ball.
## Tags
Cauchy-Goursat theorem, Cauchy integral formula
-/
open topological_space set measure_theory interval_integral metric filter function
open_locale interval real nnreal ennreal topological_space big_operators
noncomputable theory
universes u
variables {E : Type u} [normed_add_comm_group E] [normed_space ℂ E] [complete_space E]
namespace complex
/-- Suppose that a function `f : ℂ → E` is continuous on a closed rectangle with opposite corners at
`z w : ℂ`, is *real* differentiable at all but countably many points of the corresponding open
rectangle, and $\frac{\partial f}{\partial \bar z}$ is integrable on this rectangle. Then the
integral of `f` over the boundary of the rectangle is equal to the integral of
$2i\frac{\partial f}{\partial \bar z}=i\frac{\partial f}{\partial x}-\frac{\partial f}{\partial y}$
over the rectangle. -/
lemma integral_boundary_rect_of_has_fderiv_at_real_off_countable (f : ℂ → E)
(f' : ℂ → ℂ →L[ℝ] E) (z w : ℂ) (s : set ℂ) (hs : s.countable)
(Hc : continuous_on f ([z.re, w.re] ×ℂ [z.im, w.im]))
(Hd : ∀ x ∈ (Ioo (min z.re w.re) (max z.re w.re) ×ℂ Ioo (min z.im w.im) (max z.im w.im)) \ s,
has_fderiv_at f (f' x) x)
(Hi : integrable_on (λ z, I • f' z 1 - f' z I) ([z.re, w.re] ×ℂ [z.im, w.im])) :
(∫ x : ℝ in z.re..w.re, f (x + z.im * I)) - (∫ x : ℝ in z.re..w.re, f (x + w.im * I)) +
(I • ∫ y : ℝ in z.im..w.im, f (re w + y * I)) - I • ∫ y : ℝ in z.im..w.im, f (re z + y * I) =
∫ x : ℝ in z.re..w.re, ∫ y : ℝ in z.im..w.im, I • f' (x + y * I) 1 - f' (x + y * I) I :=
begin
set e : (ℝ × ℝ) ≃L[ℝ] ℂ := equiv_real_prodₗ.symm,
have he : ∀ x y : ℝ, ↑x + ↑y * I = e (x, y), from λ x y, (mk_eq_add_mul_I x y).symm,
have he₁ : e (1, 0) = 1 := rfl, have he₂ : e (0, 1) = I := rfl,
simp only [he] at *,
set F : (ℝ × ℝ) → E := f ∘ e,
set F' : (ℝ × ℝ) → (ℝ × ℝ) →L[ℝ] E := λ p, (f' (e p)).comp (e : (ℝ × ℝ) →L[ℝ] ℂ),
have hF' : ∀ p : ℝ × ℝ, (-(I • F' p)) (1, 0) + F' p (0, 1) = -(I • f' (e p) 1 - f' (e p) I),
{ rintro ⟨x, y⟩, simp [F', he₁, he₂, ← sub_eq_neg_add], },
set R : set (ℝ × ℝ) := [z.re, w.re] ×ˢ [w.im, z.im],
set t : set (ℝ × ℝ) := e ⁻¹' s,
rw [interval_swap z.im] at Hc Hi, rw [min_comm z.im, max_comm z.im] at Hd,
have hR : e ⁻¹' ([z.re, w.re] ×ℂ [w.im, z.im]) = R := rfl,
have htc : continuous_on F R, from Hc.comp e.continuous_on hR.ge,
have htd : ∀ p ∈ Ioo (min z.re w.re) (max z.re w.re) ×ˢ Ioo (min w.im z.im) (max w.im z.im) \ t,
has_fderiv_at F (F' p) p := λ p hp, (Hd (e p) hp).comp p e.has_fderiv_at,
simp_rw [← interval_integral.integral_smul, interval_integral.integral_symm w.im z.im,
← interval_integral.integral_neg, ← hF'],
refine (integral2_divergence_prod_of_has_fderiv_within_at_off_countable
(λ p, -(I • F p)) F (λ p, - (I • F' p)) F' z.re w.im w.re z.im t (hs.preimage e.injective)
(htc.const_smul _).neg htc (λ p hp, ((htd p hp).const_smul I).neg) htd _).symm,
rw [← (volume_preserving_equiv_real_prod.symm _).integrable_on_comp_preimage
(measurable_equiv.measurable_embedding _)] at Hi,
simpa only [hF'] using Hi.neg
end
/-- Suppose that a function `f : ℂ → E` is continuous on a closed rectangle with opposite corners at
`z w : ℂ`, is *real* differentiable on the corresponding open rectangle, and
$\frac{\partial f}{\partial \bar z}$ is integrable on this rectangle. Then the integral of `f` over
the boundary of the rectangle is equal to the integral of
$2i\frac{\partial f}{\partial \bar z}=i\frac{\partial f}{\partial x}-\frac{\partial f}{\partial y}$
over the rectangle. -/
lemma integral_boundary_rect_of_continuous_on_of_has_fderiv_at_real (f : ℂ → E)
(f' : ℂ → ℂ →L[ℝ] E) (z w : ℂ)
(Hc : continuous_on f ([z.re, w.re] ×ℂ [z.im, w.im]))
(Hd : ∀ x ∈ (Ioo (min z.re w.re) (max z.re w.re) ×ℂ Ioo (min z.im w.im) (max z.im w.im)),
has_fderiv_at f (f' x) x)
(Hi : integrable_on (λ z, I • f' z 1 - f' z I) ([z.re, w.re] ×ℂ [z.im, w.im])) :
(∫ x : ℝ in z.re..w.re, f (x + z.im * I)) - (∫ x : ℝ in z.re..w.re, f (x + w.im * I)) +
(I • ∫ y : ℝ in z.im..w.im, f (re w + y * I)) - I • ∫ y : ℝ in z.im..w.im, f (re z + y * I) =
∫ x : ℝ in z.re..w.re, ∫ y : ℝ in z.im..w.im, I • f' (x + y * I) 1 - f' (x + y * I) I :=
integral_boundary_rect_of_has_fderiv_at_real_off_countable f f' z w ∅ countable_empty Hc
(λ x hx, Hd x hx.1) Hi
/-- Suppose that a function `f : ℂ → E` is *real* differentiable on a closed rectangle with opposite
corners at `z w : ℂ` and $\frac{\partial f}{\partial \bar z}$ is integrable on this rectangle. Then
the integral of `f` over the boundary of the rectangle is equal to the integral of
$2i\frac{\partial f}{\partial \bar z}=i\frac{\partial f}{\partial x}-\frac{\partial f}{\partial y}$
over the rectangle. -/
lemma integral_boundary_rect_of_differentiable_on_real (f : ℂ → E) (z w : ℂ)
(Hd : differentiable_on ℝ f ([z.re, w.re] ×ℂ [z.im, w.im]))
(Hi : integrable_on (λ z, I • fderiv ℝ f z 1 - fderiv ℝ f z I) ([z.re, w.re] ×ℂ [z.im, w.im])) :
(∫ x : ℝ in z.re..w.re, f (x + z.im * I)) - (∫ x : ℝ in z.re..w.re, f (x + w.im * I)) +
(I • ∫ y : ℝ in z.im..w.im, f (re w + y * I)) - I • ∫ y : ℝ in z.im..w.im, f (re z + y * I) =
∫ x : ℝ in z.re..w.re, ∫ y : ℝ in z.im..w.im,
I • fderiv ℝ f (x + y * I) 1 - fderiv ℝ f (x + y * I) I :=
integral_boundary_rect_of_has_fderiv_at_real_off_countable f (fderiv ℝ f) z w ∅ countable_empty
Hd.continuous_on
(λ x hx, Hd.has_fderiv_at $ by simpa only [← mem_interior_iff_mem_nhds,
interior_re_prod_im, interval, interior_Icc] using hx.1) Hi
/-- **Cauchy-Goursat theorem** for a rectangle: the integral of a complex differentiable function
over the boundary of a rectangle equals zero. More precisely, if `f` is continuous on a closed
rectangle and is complex differentiable at all but countably many points of the corresponding open
rectangle, then its integral over the boundary of the rectangle equals zero. -/
lemma integral_boundary_rect_eq_zero_of_differentiable_on_off_countable (f : ℂ → E)
(z w : ℂ) (s : set ℂ) (hs : s.countable) (Hc : continuous_on f ([z.re, w.re] ×ℂ [z.im, w.im]))
(Hd : ∀ x ∈ (Ioo (min z.re w.re) (max z.re w.re) ×ℂ Ioo (min z.im w.im) (max z.im w.im)) \ s,
differentiable_at ℂ f x) :
(∫ x : ℝ in z.re..w.re, f (x + z.im * I)) - (∫ x : ℝ in z.re..w.re, f (x + w.im * I)) +
(I • ∫ y : ℝ in z.im..w.im, f (re w + y * I)) -
I • ∫ y : ℝ in z.im..w.im, f (re z + y * I) = 0 :=
by refine (integral_boundary_rect_of_has_fderiv_at_real_off_countable f
(λ z, (fderiv ℂ f z).restrict_scalars ℝ) z w s hs Hc
(λ x hx, (Hd x hx).has_fderiv_at.restrict_scalars ℝ) _).trans _;
simp [← continuous_linear_map.map_smul]
/-- **Cauchy-Goursat theorem for a rectangle**: the integral of a complex differentiable function
over the boundary of a rectangle equals zero. More precisely, if `f` is continuous on a closed
rectangle and is complex differentiable on the corresponding open rectangle, then its integral over
the boundary of the rectangle equals zero. -/
lemma integral_boundary_rect_eq_zero_of_continuous_on_of_differentiable_on (f : ℂ → E) (z w : ℂ)
(Hc : continuous_on f ([z.re, w.re] ×ℂ [z.im, w.im]))
(Hd : differentiable_on ℂ f
(Ioo (min z.re w.re) (max z.re w.re) ×ℂ Ioo (min z.im w.im) (max z.im w.im))) :
(∫ x : ℝ in z.re..w.re, f (x + z.im * I)) - (∫ x : ℝ in z.re..w.re, f (x + w.im * I)) +
(I • ∫ y : ℝ in z.im..w.im, f (re w + y * I)) -
I • ∫ y : ℝ in z.im..w.im, f (re z + y * I) = 0 :=
integral_boundary_rect_eq_zero_of_differentiable_on_off_countable f z w ∅ countable_empty
Hc $ λ x hx, Hd.differentiable_at $ (is_open_Ioo.re_prod_im is_open_Ioo).mem_nhds hx.1
/-- **Cauchy-Goursat theorem** for a rectangle: the integral of a complex differentiable function
over the boundary of a rectangle equals zero. More precisely, if `f` is complex differentiable on a
closed rectangle, then its integral over the boundary of the rectangle equals zero. -/
lemma integral_boundary_rect_eq_zero_of_differentiable_on (f : ℂ → E) (z w : ℂ)
(H : differentiable_on ℂ f ([z.re, w.re] ×ℂ [z.im, w.im])) :
(∫ x : ℝ in z.re..w.re, f (x + z.im * I)) - (∫ x : ℝ in z.re..w.re, f (x + w.im * I)) +
(I • ∫ y : ℝ in z.im..w.im, f (re w + y * I)) -
I • ∫ y : ℝ in z.im..w.im, f (re z + y * I) = 0 :=
integral_boundary_rect_eq_zero_of_continuous_on_of_differentiable_on f z w H.continuous_on $
H.mono $
inter_subset_inter (preimage_mono Ioo_subset_Icc_self) (preimage_mono Ioo_subset_Icc_self)
/-- If `f : ℂ → E` is continuous the closed annulus `r ≤ ‖z - c‖ ≤ R`, `0 < r ≤ R`, and is complex
differentiable at all but countably many points of its interior, then the integrals of
`f z / (z - c)` (formally, `(z - c)⁻¹ • f z`) over the circles `‖z - c‖ = r` and `‖z - c‖ = R` are
equal to each other. -/
lemma circle_integral_sub_center_inv_smul_eq_of_differentiable_on_annulus_off_countable
{c : ℂ} {r R : ℝ} (h0 : 0 < r) (hle : r ≤ R) {f : ℂ → E} {s : set ℂ} (hs : s.countable)
(hc : continuous_on f (closed_ball c R \ ball c r))
(hd : ∀ z ∈ ball c R \ closed_ball c r \ s, differentiable_at ℂ f z) :
∮ z in C(c, R), (z - c)⁻¹ • f z = ∮ z in C(c, r), (z - c)⁻¹ • f z :=
begin
/- We apply the previous lemma to `λ z, f (c + exp z)` on the rectangle
`[log r, log R] × [0, 2 * π]`. -/
set A := closed_ball c R \ ball c r,
obtain ⟨a, rfl⟩ : ∃ a, real.exp a = r, from ⟨real.log r, real.exp_log h0⟩,
obtain ⟨b, rfl⟩ : ∃ b, real.exp b = R, from ⟨real.log R, real.exp_log (h0.trans_le hle)⟩,
rw [real.exp_le_exp] at hle,
-- Unfold definition of `circle_integral` and cancel some terms.
suffices : ∫ θ in 0..2 * π, I • f (circle_map c (real.exp b) θ) =
∫ θ in 0..2 * π, I • f (circle_map c (real.exp a) θ),
by simpa only [circle_integral, add_sub_cancel', of_real_exp, ← exp_add, smul_smul,
← div_eq_mul_inv, mul_div_cancel_left _ (circle_map_ne_center (real.exp_pos _).ne'),
circle_map_sub_center, deriv_circle_map],
set R := [a, b] ×ℂ [0, 2 * π],
set g : ℂ → ℂ := (+) c ∘ exp,
have hdg : differentiable ℂ g := differentiable_exp.const_add _,
replace hs : (g ⁻¹' s).countable := (hs.preimage (add_right_injective c)).preimage_cexp,
have h_maps : maps_to g R A,
{ rintro z ⟨h, -⟩, simpa [dist_eq, g, abs_exp, hle] using h.symm },
replace hc : continuous_on (f ∘ g) R, from hc.comp hdg.continuous.continuous_on h_maps,
replace hd : ∀ z ∈ (Ioo (min a b) (max a b) ×ℂ Ioo (min 0 (2 * π)) (max 0 (2 * π))) \ g ⁻¹' s,
differentiable_at ℂ (f ∘ g) z,
{ refine λ z hz, (hd (g z) ⟨_, hz.2⟩).comp z (hdg _),
simpa [g, dist_eq, abs_exp, hle, and.comm] using hz.1.1 },
simpa [g, circle_map, exp_periodic _, sub_eq_zero, ← exp_add]
using integral_boundary_rect_eq_zero_of_differentiable_on_off_countable _ ⟨a, 0⟩ ⟨b, 2 * π⟩
_ hs hc hd
end
/-- **Cauchy-Goursat theorem** for an annulus. If `f : ℂ → E` is continuous on the closed annulus
`r ≤ ‖z - c‖ ≤ R`, `0 < r ≤ R`, and is complex differentiable at all but countably many points of
its interior, then the integrals of `f` over the circles `‖z - c‖ = r` and `‖z - c‖ = R` are equal
to each other. -/
lemma circle_integral_eq_of_differentiable_on_annulus_off_countable
{c : ℂ} {r R : ℝ} (h0 : 0 < r) (hle : r ≤ R) {f : ℂ → E} {s : set ℂ} (hs : s.countable)
(hc : continuous_on f (closed_ball c R \ ball c r))
(hd : ∀ z ∈ ball c R \ closed_ball c r \ s, differentiable_at ℂ f z) :
∮ z in C(c, R), f z = ∮ z in C(c, r), f z :=
calc ∮ z in C(c, R), f z = ∮ z in C(c, R), (z - c)⁻¹ • (z - c) • f z :
(circle_integral.integral_sub_inv_smul_sub_smul _ _ _ _).symm
... = ∮ z in C(c, r), (z - c)⁻¹ • (z - c) • f z :
circle_integral_sub_center_inv_smul_eq_of_differentiable_on_annulus_off_countable h0 hle hs
((continuous_on_id.sub continuous_on_const).smul hc)
(λ z hz, (differentiable_at_id.sub_const _).smul (hd z hz))
... = ∮ z in C(c, r), f z : circle_integral.integral_sub_inv_smul_sub_smul _ _ _ _
/-- **Cauchy integral formula** for the value at the center of a disc. If `f` is continuous on a
punctured closed disc of radius `R`, is differentiable at all but countably many points of the
interior of this disc, and has a limit `y` at the center of the disc, then the integral
$\oint_{‖z-c‖=R} \frac{f(z)}{z-c}\,dz$ is equal to $2πiy`. -/
lemma circle_integral_sub_center_inv_smul_of_differentiable_on_off_countable_of_tendsto
{c : ℂ} {R : ℝ} (h0 : 0 < R) {f : ℂ → E} {y : E} {s : set ℂ} (hs : s.countable)
(hc : continuous_on f (closed_ball c R \ {c}))
(hd : ∀ z ∈ ball c R \ {c} \ s, differentiable_at ℂ f z) (hy : tendsto f (𝓝[{c}ᶜ] c) (𝓝 y)) :
∮ z in C(c, R), (z - c)⁻¹ • f z = (2 * π * I : ℂ) • y :=
begin
rw [← sub_eq_zero, ← norm_le_zero_iff],
refine le_of_forall_le_of_dense (λ ε ε0, _),
obtain ⟨δ, δ0, hδ⟩ :
∃ δ > (0 : ℝ), ∀ z ∈ closed_ball c δ \ {c}, dist (f z) y < ε / (2 * π),
from ((nhds_within_has_basis nhds_basis_closed_ball _).tendsto_iff nhds_basis_ball).1 hy _
(div_pos ε0 real.two_pi_pos),
obtain ⟨r, hr0, hrδ, hrR⟩ : ∃ r, 0 < r ∧ r ≤ δ ∧ r ≤ R :=
⟨min δ R, lt_min δ0 h0, min_le_left _ _, min_le_right _ _⟩,
have hsub : closed_ball c R \ ball c r ⊆ closed_ball c R \ {c},
from diff_subset_diff_right (singleton_subset_iff.2 $ mem_ball_self hr0),
have hsub' : ball c R \ closed_ball c r ⊆ ball c R \ {c},
from diff_subset_diff_right (singleton_subset_iff.2 $ mem_closed_ball_self hr0.le),
have hzne : ∀ z ∈ sphere c r, z ≠ c,
from λ z hz, ne_of_mem_of_not_mem hz (λ h, hr0.ne' $ dist_self c ▸ eq.symm h),
/- The integral `∮ z in C(c, r), f z / (z - c)` does not depend on `0 < r ≤ R` and tends to
`2πIy` as `r → 0`. -/
calc ‖(∮ z in C(c, R), (z - c)⁻¹ • f z) - (2 * ↑π * I) • y‖
= ‖(∮ z in C(c, r), (z - c)⁻¹ • f z) - ∮ z in C(c, r), (z - c)⁻¹ • y‖ :
begin
congr' 2,
{ exact circle_integral_sub_center_inv_smul_eq_of_differentiable_on_annulus_off_countable
hr0 hrR hs (hc.mono hsub) (λ z hz, hd z ⟨hsub' hz.1, hz.2⟩) },
{ simp [hr0.ne'] }
end
... = ‖∮ z in C(c, r), (z - c)⁻¹ • (f z - y)‖ :
begin
simp only [smul_sub],
have hc' : continuous_on (λ z, (z - c)⁻¹) (sphere c r),
from (continuous_on_id.sub continuous_on_const).inv₀ (λ z hz, sub_ne_zero.2 $ hzne _ hz),
rw circle_integral.integral_sub; refine (hc'.smul _).circle_integrable hr0.le,
{ exact hc.mono (subset_inter (sphere_subset_closed_ball.trans $
closed_ball_subset_closed_ball hrR) hzne) },
{ exact continuous_on_const }
end
... ≤ 2 * π * r * (r⁻¹ * (ε / (2 * π))) :
begin
refine circle_integral.norm_integral_le_of_norm_le_const hr0.le (λ z hz, _),
specialize hzne z hz,
rw [mem_sphere, dist_eq_norm] at hz,
rw [norm_smul, norm_inv, hz, ← dist_eq_norm],
refine mul_le_mul_of_nonneg_left (hδ _ ⟨_, hzne⟩).le (inv_nonneg.2 hr0.le),
rwa [mem_closed_ball_iff_norm, hz]
end
... = ε : by { field_simp [hr0.ne', real.two_pi_pos.ne'], ac_refl }
end
/-- **Cauchy integral formula** for the value at the center of a disc. If `f : ℂ → E` is continuous
on a closed disc of radius `R` and is complex differentiable at all but countably many points of its
interior, then the integral $\oint_{|z-c|=R} \frac{f(z)}{z-c}\,dz$ is equal to $2πiy`. -/
lemma circle_integral_sub_center_inv_smul_of_differentiable_on_off_countable {R : ℝ} (h0 : 0 < R)
{f : ℂ → E} {c : ℂ} {s : set ℂ} (hs : s.countable)
(hc : continuous_on f (closed_ball c R)) (hd : ∀ z ∈ ball c R \ s, differentiable_at ℂ f z) :
∮ z in C(c, R), (z - c)⁻¹ • f z = (2 * π * I : ℂ) • f c :=
circle_integral_sub_center_inv_smul_of_differentiable_on_off_countable_of_tendsto h0 hs
(hc.mono $ diff_subset _ _) (λ z hz, hd z ⟨hz.1.1, hz.2⟩)
(hc.continuous_at $ closed_ball_mem_nhds _ h0).continuous_within_at
/-- **Cauchy-Goursat theorem** for a disk: if `f : ℂ → E` is continuous on a closed disk
`{z | ‖z - c‖ ≤ R}` and is complex differentiable at all but countably many points of its interior,
then the integral $\oint_{|z-c|=R}f(z)\,dz$ equals zero. -/
lemma circle_integral_eq_zero_of_differentiable_on_off_countable {R : ℝ} (h0 : 0 ≤ R) {f : ℂ → E}
{c : ℂ} {s : set ℂ} (hs : s.countable) (hc : continuous_on f (closed_ball c R))
(hd : ∀ z ∈ ball c R \ s, differentiable_at ℂ f z) :
∮ z in C(c, R), f z = 0 :=
begin
rcases h0.eq_or_lt with rfl|h0, { apply circle_integral.integral_radius_zero },
calc ∮ z in C(c, R), f z = ∮ z in C(c, R), (z - c)⁻¹ • (z - c) • f z :
(circle_integral.integral_sub_inv_smul_sub_smul _ _ _ _).symm
... = (2 * ↑π * I : ℂ) • (c - c) • f c :
circle_integral_sub_center_inv_smul_of_differentiable_on_off_countable h0 hs
((continuous_on_id.sub continuous_on_const).smul hc)
(λ z hz, (differentiable_at_id.sub_const _).smul (hd z hz))
... = 0 : by rw [sub_self, zero_smul, smul_zero]
end
/-- An auxiliary lemma for
`complex.circle_integral_sub_inv_smul_of_differentiable_on_off_countable`. This lemma assumes
`w ∉ s` while the main lemma drops this assumption. -/
lemma circle_integral_sub_inv_smul_of_differentiable_on_off_countable_aux {R : ℝ} {c w : ℂ}
{f : ℂ → E} {s : set ℂ} (hs : s.countable) (hw : w ∈ ball c R \ s)
(hc : continuous_on f (closed_ball c R)) (hd : ∀ x ∈ ball c R \ s, differentiable_at ℂ f x) :
∮ z in C(c, R), (z - w)⁻¹ • f z = (2 * π * I : ℂ) • f w :=
begin
have hR : 0 < R := dist_nonneg.trans_lt hw.1,
set F : ℂ → E := dslope f w,
have hws : (insert w s).countable := hs.insert w,
have hnhds : closed_ball c R ∈ 𝓝 w, from closed_ball_mem_nhds_of_mem hw.1,
have hcF : continuous_on F (closed_ball c R),
from (continuous_on_dslope $ closed_ball_mem_nhds_of_mem hw.1).2 ⟨hc, hd _ hw⟩,
have hdF : ∀ z ∈ ball (c : ℂ) R \ (insert w s), differentiable_at ℂ F z,
from λ z hz, (differentiable_at_dslope_of_ne
(ne_of_mem_of_not_mem (mem_insert _ _) hz.2).symm).2
(hd _ (diff_subset_diff_right (subset_insert _ _) hz)),
have HI := circle_integral_eq_zero_of_differentiable_on_off_countable hR.le hws hcF hdF,
have hne : ∀ z ∈ sphere c R, z ≠ w, from λ z hz, ne_of_mem_of_not_mem hz (ne_of_lt hw.1),
have hFeq : eq_on F (λ z, (z - w)⁻¹ • f z - (z - w)⁻¹ • f w) (sphere c R),
{ intros z hz,
calc F z = (z - w)⁻¹ • (f z - f w) : update_noteq (hne z hz) _ _
... = (z - w)⁻¹ • f z - (z - w)⁻¹ • f w : smul_sub _ _ _ },
have hc' : continuous_on (λ z, (z - w)⁻¹) (sphere c R),
from (continuous_on_id.sub continuous_on_const).inv₀ (λ z hz, sub_ne_zero.2 $ hne z hz),
rw [← circle_integral.integral_sub_inv_of_mem_ball hw.1, ← circle_integral.integral_smul_const,
← sub_eq_zero, ← circle_integral.integral_sub, ← circle_integral.integral_congr hR.le hFeq, HI],
exacts [(hc'.smul (hc.mono sphere_subset_closed_ball)).circle_integrable hR.le,
(hc'.smul continuous_on_const).circle_integrable hR.le]
end
/-- **Cauchy integral formula**: if `f : ℂ → E` is continuous on a closed disc of radius `R` and is
complex differentiable at all but countably many points of its interior, then for any `w` in this
interior we have $\frac{1}{2πi}\oint_{|z-c|=R}(z-w)^{-1}f(z)\,dz=f(w)$.
-/
lemma two_pi_I_inv_smul_circle_integral_sub_inv_smul_of_differentiable_on_off_countable
{R : ℝ} {c w : ℂ} {f : ℂ → E} {s : set ℂ} (hs : s.countable) (hw : w ∈ ball c R)
(hc : continuous_on f (closed_ball c R)) (hd : ∀ x ∈ ball c R \ s, differentiable_at ℂ f x) :
(2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), (z - w)⁻¹ • f z = f w :=
begin
have hR : 0 < R := dist_nonneg.trans_lt hw,
suffices : w ∈ closure (ball c R \ s),
{ lift R to ℝ≥0 using hR.le,
have A : continuous_at (λ w, (2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), (z - w)⁻¹ • f z) w,
{ have := has_fpower_series_on_cauchy_integral
((hc.mono sphere_subset_closed_ball).circle_integrable R.coe_nonneg) hR,
refine this.continuous_on.continuous_at (emetric.is_open_ball.mem_nhds _),
rwa metric.emetric_ball_nnreal },
have B : continuous_at f w, from hc.continuous_at (closed_ball_mem_nhds_of_mem hw),
refine tendsto_nhds_unique_of_frequently_eq A B ((mem_closure_iff_frequently.1 this).mono _),
intros z hz,
rw [circle_integral_sub_inv_smul_of_differentiable_on_off_countable_aux hs hz hc hd,
inv_smul_smul₀],
simp [real.pi_ne_zero, I_ne_zero] },
refine mem_closure_iff_nhds.2 (λ t ht, _),
-- TODO: generalize to any vector space over `ℝ`
set g : ℝ → ℂ := λ x, w + x,
have : tendsto g (𝓝 0) (𝓝 w),
from (continuous_const.add continuous_of_real).tendsto' 0 w (add_zero _),
rcases mem_nhds_iff_exists_Ioo_subset.1 (this $ inter_mem ht $ is_open_ball.mem_nhds hw)
with ⟨l, u, hlu₀, hlu_sub⟩,
obtain ⟨x, hx⟩ : (Ioo l u \ g ⁻¹' s).nonempty,
{ refine nonempty_diff.2 (λ hsub, _),
have : (Ioo l u).countable,
from (hs.preimage ((add_right_injective w).comp of_real_injective)).mono hsub,
rw [← cardinal.le_aleph_0_iff_set_countable,
cardinal.mk_Ioo_real (hlu₀.1.trans hlu₀.2)] at this,
exact this.not_lt cardinal.aleph_0_lt_continuum },
exact ⟨g x, (hlu_sub hx.1).1, (hlu_sub hx.1).2, hx.2⟩
end
/-- **Cauchy integral formula**: if `f : ℂ → E` is continuous on a closed disc of radius `R` and is
complex differentiable at all but countably many points of its interior, then for any `w` in this
interior we have $\oint_{|z-c|=R}(z-w)^{-1}f(z)\,dz=2πif(w)$.
-/
lemma circle_integral_sub_inv_smul_of_differentiable_on_off_countable
{R : ℝ} {c w : ℂ} {f : ℂ → E} {s : set ℂ} (hs : s.countable) (hw : w ∈ ball c R)
(hc : continuous_on f (closed_ball c R)) (hd : ∀ x ∈ ball c R \ s, differentiable_at ℂ f x) :
∮ z in C(c, R), (z - w)⁻¹ • f z = (2 * π * I : ℂ) • f w :=
by { rw [← two_pi_I_inv_smul_circle_integral_sub_inv_smul_of_differentiable_on_off_countable
hs hw hc hd, smul_inv_smul₀], simp [real.pi_ne_zero, I_ne_zero] }
/-- **Cauchy integral formula**: if `f : ℂ → E` is complex differentiable on an open disc and is
continuous on its closure, then for any `w` in this open ball we have
$\oint_{|z-c|=R}(z-w)^{-1}f(z)\,dz=2πif(w)$. -/
lemma _root_.diff_cont_on_cl.circle_integral_sub_inv_smul {R : ℝ} {c w : ℂ} {f : ℂ → E}
(h : diff_cont_on_cl ℂ f (ball c R)) (hw : w ∈ ball c R) :
∮ z in C(c, R), (z - w)⁻¹ • f z = (2 * π * I : ℂ) • f w :=
circle_integral_sub_inv_smul_of_differentiable_on_off_countable countable_empty hw
h.continuous_on_ball $ λ x hx, h.differentiable_at is_open_ball hx.1
/-- **Cauchy integral formula**: if `f : ℂ → E` is complex differentiable on a closed disc of radius
`R`, then for any `w` in its interior we have $\oint_{|z-c|=R}(z-w)^{-1}f(z)\,dz=2πif(w)$. -/
lemma _root_.differentiable_on.circle_integral_sub_inv_smul {R : ℝ} {c w : ℂ} {f : ℂ → E}
(hd : differentiable_on ℂ f (closed_ball c R)) (hw : w ∈ ball c R) :
∮ z in C(c, R), (z - w)⁻¹ • f z = (2 * π * I : ℂ) • f w :=
(hd.mono closure_ball_subset_closed_ball).diff_cont_on_cl.circle_integral_sub_inv_smul hw
/-- **Cauchy integral formula**: if `f : ℂ → ℂ` is continuous on a closed disc of radius `R` and is
complex differentiable at all but countably many points of its interior, then for any `w` in this
interior we have $\oint_{|z-c|=R}\frac{f(z)}{z-w}dz=2\pi i\,f(w)$.
-/
lemma circle_integral_div_sub_of_differentiable_on_off_countable {R : ℝ} {c w : ℂ} {s : set ℂ}
(hs : s.countable) (hw : w ∈ ball c R) {f : ℂ → ℂ} (hc : continuous_on f (closed_ball c R))
(hd : ∀ z ∈ ball c R \ s, differentiable_at ℂ f z) :
∮ z in C(c, R), f z / (z - w) = 2 * π * I * f w :=
by simpa only [smul_eq_mul, div_eq_inv_mul]
using circle_integral_sub_inv_smul_of_differentiable_on_off_countable hs hw hc hd
/-- If `f : ℂ → E` is continuous on a closed ball of positive radius and is differentiable at all
but countably many points of the corresponding open ball, then it is analytic on the open ball with
coefficients of the power series given by Cauchy integral formulas. -/
lemma has_fpower_series_on_ball_of_differentiable_off_countable {R : ℝ≥0} {c : ℂ} {f : ℂ → E}
{s : set ℂ} (hs : s.countable) (hc : continuous_on f (closed_ball c R))
(hd : ∀ z ∈ ball c R \ s, differentiable_at ℂ f z) (hR : 0 < R) :
has_fpower_series_on_ball f (cauchy_power_series f c R) c R :=
{ r_le := le_radius_cauchy_power_series _ _ _,
r_pos := ennreal.coe_pos.2 hR,
has_sum := λ w hw,
begin
have hw' : c + w ∈ ball c R,
by simpa only [add_mem_ball_iff_norm, ← coe_nnnorm, mem_emetric_ball_zero_iff,
nnreal.coe_lt_coe, ennreal.coe_lt_coe] using hw,
rw ← two_pi_I_inv_smul_circle_integral_sub_inv_smul_of_differentiable_on_off_countable hs
hw' hc hd,
exact (has_fpower_series_on_cauchy_integral
((hc.mono sphere_subset_closed_ball).circle_integrable R.2) hR).has_sum hw
end }
/-- If `f : ℂ → E` is complex differentiable on an open disc of positive radius and is continuous
on its closure, then it is analytic on the open disc with coefficients of the power series given by
Cauchy integral formulas. -/
lemma _root_.diff_cont_on_cl.has_fpower_series_on_ball {R : ℝ≥0} {c : ℂ} {f : ℂ → E}
(hf : diff_cont_on_cl ℂ f (ball c R)) (hR : 0 < R) :
has_fpower_series_on_ball f (cauchy_power_series f c R) c R :=
has_fpower_series_on_ball_of_differentiable_off_countable countable_empty hf.continuous_on_ball
(λ z hz, hf.differentiable_at is_open_ball hz.1) hR
/-- If `f : ℂ → E` is complex differentiable on a closed disc of positive radius, then it is
analytic on the corresponding open disc, and the coefficients of the power series are given by
Cauchy integral formulas. See also
`complex.has_fpower_series_on_ball_of_differentiable_off_countable` for a version of this lemma with
weaker assumptions. -/
protected lemma _root_.differentiable_on.has_fpower_series_on_ball {R : ℝ≥0} {c : ℂ} {f : ℂ → E}
(hd : differentiable_on ℂ f (closed_ball c R)) (hR : 0 < R) :
has_fpower_series_on_ball f (cauchy_power_series f c R) c R :=
(hd.mono closure_ball_subset_closed_ball).diff_cont_on_cl.has_fpower_series_on_ball hR
/-- If `f : ℂ → E` is complex differentiable on some set `s`, then it is analytic at any point `z`
such that `s ∈ 𝓝 z` (equivalently, `z ∈ interior s`). -/
protected lemma _root_.differentiable_on.analytic_at {s : set ℂ} {f : ℂ → E} {z : ℂ}
(hd : differentiable_on ℂ f s) (hz : s ∈ 𝓝 z) : analytic_at ℂ f z :=
begin
rcases nhds_basis_closed_ball.mem_iff.1 hz with ⟨R, hR0, hRs⟩,
lift R to ℝ≥0 using hR0.le,
exact ((hd.mono hRs).has_fpower_series_on_ball hR0).analytic_at
end
lemma _root_.differentiable_on.analytic_on {s : set ℂ} {f : ℂ → E} (hd : differentiable_on ℂ f s)
(hs : is_open s) : analytic_on ℂ f s :=
λ z hz, hd.analytic_at (hs.mem_nhds hz)
/-- A complex differentiable function `f : ℂ → E` is analytic at every point. -/
protected lemma _root_.differentiable.analytic_at {f : ℂ → E} (hf : differentiable ℂ f) (z : ℂ) :
analytic_at ℂ f z :=
hf.differentiable_on.analytic_at univ_mem
/-- When `f : ℂ → E` is differentiable, the `cauchy_power_series f z R` represents `f` as a power
series centered at `z` in the entirety of `ℂ`, regardless of `R : ℝ≥0`, with `0 < R`. -/
protected lemma _root_.differentiable.has_fpower_series_on_ball {f : ℂ → E}
(h : differentiable ℂ f) (z : ℂ) {R : ℝ≥0} (hR : 0 < R) :
has_fpower_series_on_ball f (cauchy_power_series f z R) z ∞ :=
(h.differentiable_on.has_fpower_series_on_ball hR).r_eq_top_of_exists $ λ r hr,
⟨_, h.differentiable_on.has_fpower_series_on_ball hr⟩
end complex
|
91a3d35215a7f5034b85361579a4ce18be0ab83b | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /src/Lean/Parser/Tactic.lean | 531dfb6b225e1b0b906e50b65c20b8579b0482ac | [
"Apache-2.0"
] | permissive | WojciechKarpiel/lean4 | 7f89706b8e3c1f942b83a2c91a3a00b05da0e65b | f6e1314fa08293dea66a329e05b6c196a0189163 | refs/heads/master | 1,686,633,402,214 | 1,625,821,189,000 | 1,625,821,258,000 | 384,640,886 | 0 | 0 | Apache-2.0 | 1,625,903,617,000 | 1,625,903,026,000 | null | UTF-8 | Lean | false | false | 1,250 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
import Lean.Parser.Term
namespace Lean
namespace Parser
namespace Tactic
builtin_initialize
register_parser_alias "tacticSeq" tacticSeq
@[builtinTacticParser] def «unknown» := leading_parser withPosition (ident >> errorAtSavedPos "unknown tactic" true)
@[builtinTacticParser] def nestedTactic := tacticSeqBracketed
/- Auxiliary parser for expanding `match` tactic -/
@[builtinTacticParser] def eraseAuxDiscrs := leading_parser:maxPrec "eraseAuxDiscrs!"
def matchRhs := Term.hole <|> Term.syntheticHole <|> tacticSeq
def matchAlts := Term.matchAlts (rhsParser := matchRhs)
@[builtinTacticParser] def «match» := leading_parser:leadPrec "match " >> optional Term.generalizingParam >> sepBy1 Term.matchDiscr ", " >> Term.optType >> " with " >> matchAlts
@[builtinTacticParser] def introMatch := leading_parser nonReservedSymbol "intro " >> matchAlts
@[builtinTacticParser] def decide := leading_parser nonReservedSymbol "decide"
@[builtinTacticParser] def nativeDecide := leading_parser nonReservedSymbol "nativeDecide"
end Tactic
end Parser
end Lean
|
5114e15ea65aaa1276c98639132cf224ce4478b2 | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/tactic/lint.lean | cbf5403a2952dfc1d61255b6c1f0826c6884a14b | [
"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 | 24,957 | lean | /-
Copyright (c) 2019 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Robert Y. Lewis
-/
import tactic.core
/-!
# lint command
This file defines the following user commands to spot common mistakes in the code.
* `#lint`: check all declarations in the current file
* `#lint_mathlib`: check all declarations in mathlib (so excluding core or other projects,
and also excluding the current file)
* `#lint_all`: check all declarations in the environment (the current file and all
imported files)
The following linters are run by default:
1. `unused_arguments` checks for unused arguments in declarations.
2. `def_lemma` checks whether a declaration is incorrectly marked as a def/lemma.
3. `dup_namespce` checks whether a namespace is duplicated in the name of a declaration.
4. `illegal_constant` checks whether ≥/> is used in the declaration.
5. `instance_priority` checks that instances that always apply have priority below default.
6. `doc_blame` checks for missing doc strings on definitions and constants.
Another linter, `doc_blame_thm`, checks for missing doc strings on lemmas and theorems.
This is not run by default.
The command `#list_linters` prints a list of the names of all available linters.
You can append a `*` to any command (e.g. `#lint_mathlib*`) to omit the slow tests (4).
You can append a `-` to any command (e.g. `#lint_mathlib-`) to run a silent lint
that suppresses the output of passing checks.
A silent lint will fail if any test fails.
You can append a sequence of linter names to any command to run extra tests, in addition to the
default ones. e.g. `#lint doc_blame_thm` will run all default tests and `doc_blame_thm`.
You can append `only name1 name2 ...` to any command to run a subset of linters, e.g.
`#lint only unused_arguments`
You can add custom linters by defining a term of type `linter` in the `linter` namespace.
A linter defined with the name `linter.my_new_check` can be run with `#lint my_new_check`
or `lint only my_new_check`.
If you add the attribute `@[linter]` to `linter.my_new_check` it will run by default.
Adding the attribute `@[nolint]` to a declaration omits it from all linter checks.
## Tags
sanity check, lint, cleanup, command, tactic
-/
universe variable u
open expr tactic native
reserve notation `#lint`
reserve notation `#lint_mathlib`
reserve notation `#lint_all`
reserve notation `#list_linters`
run_cmd tactic.skip -- apparently doc strings can't come directly after `reserve notation`
/-- Defines the user attribute `nolint` for skipping `#lint` -/
@[user_attribute]
meta def nolint_attr : user_attribute :=
{ name := "nolint",
descr := "Do not report this declaration in any of the tests of `#lint`" }
attribute [nolint] imp_intro
classical.dec classical.dec_pred classical.dec_rel classical.dec_eq
/--
A linting test for the `#lint` command.
`test` defines a test to perform on every declaration. It should never fail. Returning `none`
signifies a passing test. Returning `some msg` reports a failing test with error `msg`.
`no_errors_found` is the message printed when all tests are negative, and `errors_found` is printed
when at least one test is positive.
If `is_fast` is false, this test will be omitted from `#lint-`.
-/
meta structure linter :=
(test : declaration → tactic (option string))
(no_errors_found : string)
(errors_found : string)
(is_fast : bool := tt)
/-- Takes a list of names that resolve to declarations of type `linter`,
and produces a list of linters. -/
meta def get_linters (l : list name) : tactic (list linter) :=
l.mmap (λ n, mk_const n >>= eval_expr linter <|> fail format!"invalid linter: {n}")
/-- Defines the user attribute `linter` for adding a linter to the default set.
Linters should be defined in the `linter` namespace.
A linter `linter.my_new_linter` is referred to as `my_new_linter` (without the `linter` namespace)
when used in `#lint`.
-/
@[user_attribute]
meta def linter_attr : user_attribute unit unit :=
{ name := "linter",
descr := "Use this declaration as a linting test in #lint",
after_set := some $ λ nm _ _,
mk_const nm >>= infer_type >>= unify `(linter) }
setup_tactic_parser
universe variable v
/-- Find all declarations in `l` where tac returns `some x` and list them. -/
meta def fold_over_with_cond {α} (l : list declaration) (tac : declaration → tactic (option α)) :
tactic (list (declaration × α)) :=
l.mmap_filter $ λ d, option.map (λ x, (d, x)) <$> tac d
/-- Find all declarations in `l` where tac returns `some x` and sort the resulting list by file name. -/
meta def fold_over_with_cond_sorted {α} (l : list declaration)
(tac : declaration → tactic (option α)) : tactic (list (string × list (declaration × α))) := do
e ← get_env,
ds ← fold_over_with_cond l tac,
let ds₂ := rb_lmap.of_list (ds.map (λ x, ((e.decl_olean x.1.to_name).iget, x))),
return $ ds₂.to_list
/-- Make the output of `fold_over_with_cond` printable, in the following form:
`#print <name> <open multiline comment> <elt of α> <close multiline comment>` -/
meta def print_decls {α} [has_to_format α] (ds : list (declaration × α)) : format :=
ds.foldl
(λ f x, f ++ "\n" ++ to_fmt "#print " ++ to_fmt x.1.to_name ++ " /- " ++ to_fmt x.2 ++ " -/")
format.nil
/-- Make the output of `fold_over_with_cond_sorted` printable, with the file path + name inserted.-/
meta def print_decls_sorted {α} [has_to_format α] (ds : list (string × list (declaration × α))) :
format :=
ds.foldl
(λ f x, f ++ "\n\n" ++ to_fmt "-- " ++ to_fmt x.1 ++ print_decls x.2)
format.nil
/-- Same as `print_decls_sorted`, but removing the first `n` characters from the string.
Useful for omitting the mathlib directory from the output. -/
meta def print_decls_sorted_mathlib {α} [has_to_format α] (n : ℕ)
(ds : list (string × list (declaration × α))) : format :=
ds.foldl
(λ f x, f ++ "\n\n" ++ to_fmt "-- " ++ to_fmt (x.1.popn n) ++ print_decls x.2)
format.nil
/-- Auxilliary definition for `check_unused_arguments` -/
meta def check_unused_arguments_aux : list ℕ → ℕ → ℕ → expr → list ℕ | l n n_max e :=
if n > n_max then l else
if ¬ is_lambda e ∧ ¬ is_pi e then l else
let b := e.binding_body in
let l' := if b.has_var_idx 0 then l else n :: l in check_unused_arguments_aux l' (n+1) n_max b
/-- Check which arguments of a declaration are not used.
Prints a list of natural numbers corresponding to which arguments are not used (e.g.
this outputs [1, 4] if the first and fourth arguments are unused).
Checks both the type and the value of `d` for whether the argument is used
(in rare cases an argument is used in the type but not in the value).
We return [] if the declaration was automatically generated.
We print arguments that are larger than the arity of the type of the declaration
(without unfolding definitions). -/
meta def check_unused_arguments (d : declaration) : option (list ℕ) :=
let l := check_unused_arguments_aux [] 1 d.type.pi_arity d.value in
if l = [] then none else
let l2 := check_unused_arguments_aux [] 1 d.type.pi_arity d.type in
(l.filter $ λ n, n ∈ l2).reverse
/-- Check for unused arguments, and print them with their position, variable name, type and whether
the argument is a duplicate.
See also `check_unused_arguments`.
This tactic additionally filters out all unused arguments of type `parse _` -/
meta def unused_arguments (d : declaration) : tactic (option string) := do
let ns := check_unused_arguments d,
if ¬ ns.is_some then return none else do
let ns := ns.iget,
(ds, _) ← get_pi_binders d.type,
let ns := ns.map (λ n, (n, (ds.nth $ n - 1).iget)),
let ns := ns.filter (λ x, x.2.type.get_app_fn ≠ const `interactive.parse []),
if ns = [] then return none else do
ds' ← ds.mmap pp,
ns ← ns.mmap (λ ⟨n, b⟩, (λ s, to_fmt "argument " ++ to_fmt n ++ ": " ++ s ++
(if ds.countp (λ b', b.type = b'.type) ≥ 2 then " (duplicate)" else "")) <$> pp b),
return $ some $ ns.to_string_aux tt
/-- A linter object for checking for unused arguments. This is in the default linter set. -/
@[linter, priority 1500] meta def linter.unused_arguments : linter :=
{ test := unused_arguments,
no_errors_found := "No unused arguments",
errors_found := "UNUSED ARGUMENTS" }
/-- Checks whether the correct declaration constructor (definition or theorem) by comparing it
to its sort. Instances will not be printed. -/
/- This test is not very quick: maybe we can speed-up testing that something is a proposition?
This takes almost all of the execution time. -/
meta def incorrect_def_lemma (d : declaration) : tactic (option string) :=
if d.is_constant ∨ d.is_axiom
then return none else do
is_instance_d ← is_instance d.to_name,
if is_instance_d then return none else do
-- the following seems to be a little quicker than `is_prop d.type`.
expr.sort n ← infer_type d.type, return $
if d.is_theorem ↔ n = level.zero then none
else if (d.is_definition : bool) then "is a def, should be a lemma/theorem"
else "is a lemma/theorem, should be a def"
/-- A linter for checking whether the correct declaration constructor (definition or theorem)
has been used. -/
@[linter, priority 1490] meta def linter.def_lemma : linter :=
{ test := incorrect_def_lemma,
no_errors_found := "All declarations correctly marked as def/lemma",
errors_found := "INCORRECT DEF/LEMMA" }
/-- Checks whether a declaration has a namespace twice consecutively in its name -/
meta def dup_namespace (d : declaration) : tactic (option string) :=
is_instance d.to_name >>= λ is_inst,
return $ let nm := d.to_name.components in if nm.chain' (≠) ∨ is_inst then none
else let s := (nm.find $ λ n, nm.count n ≥ 2).iget.to_string in
some $ "The namespace `" ++ s ++ "` is duplicated in the name"
/-- A linter for checking whether a declaration has a namespace twice consecutively in its name. -/
@[linter, priority 1480] meta def linter.dup_namespace : linter :=
{ test := dup_namespace,
no_errors_found := "No declarations have a duplicate namespace",
errors_found := "DUPLICATED NAMESPACES IN NAME" }
/-- Checks whether a `>`/`≥` is used in the statement of `d`. -/
-- TODO: the commented out code also checks for classicality in statements, but needs fixing
-- TODO: this probably needs to also check whether the argument is a variable or @eq <var> _ _
-- meta def illegal_constants_in_statement (d : declaration) : tactic (option string) :=
-- return $ if d.type.contains_constant (λ n, (n.get_prefix = `classical ∧
-- n.last ∈ ["prop_decidable", "dec", "dec_rel", "dec_eq"]) ∨ n ∈ [`gt, `ge])
-- then
-- let illegal1 := [`classical.prop_decidable, `classical.dec, `classical.dec_rel, `classical.dec_eq],
-- illegal2 := [`gt, `ge],
-- occur1 := illegal1.filter (λ n, d.type.contains_constant (eq n)),
-- occur2 := illegal2.filter (λ n, d.type.contains_constant (eq n)) in
-- some $ sformat!"the type contains the following declarations: {occur1 ++ occur2}." ++
-- (if occur1 = [] then "" else " Add decidability type-class arguments instead.") ++
-- (if occur2 = [] then "" else " Use ≤/< instead.")
-- else none
meta def illegal_constants_in_statement (d : declaration) : tactic (option string) :=
return $ let illegal := [`gt, `ge] in if d.type.contains_constant (λ n, n ∈ illegal)
then some "the type contains ≥/>. Use ≤/< instead."
else none
/-- A linter for checking whether illegal constants (≥, >) appear in a declaration's type. -/
@[linter, priority 1470] meta def linter.illegal_constants : linter :=
{ test := illegal_constants_in_statement,
no_errors_found := "No illegal constants in declarations",
errors_found := "ILLEGAL CONSTANTS IN DECLARATIONS",
is_fast := ff }
/-- checks whether an instance that always applies has priority ≥ 1000. -/
-- TODO: instance_priority should also be tested on automatically-generated declarations
meta def instance_priority (d : declaration) : tactic (option string) := do
let nm := d.to_name,
b ← is_instance nm,
/- return `none` if `d` is not an instance -/
if ¬ b then return none else do
prio ← has_attribute `instance nm,
/- return `none` if `d` is has low priority -/
if prio < 1000 then return none else do
let (fn, args) := d.type.pi_codomain.get_app_fn_args,
cls ← get_decl fn.const_name,
let (pi_args, _) := cls.type.pi_binders,
guard (args.length = pi_args.length),
/- List all the arguments of the class that block type-class inference from firing
(if they are metavariables). These are all the arguments except instance-arguments and
out-params. -/
let relevant_args := (args.zip pi_args).filter_map $ λ⟨e, ⟨_, info, tp⟩⟩,
if info = binder_info.inst_implicit ∨ tp.get_app_fn.is_constant_of `out_param
then none else some e,
let always_applies := relevant_args.all expr.is_var ∧ relevant_args.nodup,
if always_applies then return $ some "set priority below 1000" else return none
library_note "lower instance priority"
"Certain instances always apply during type-class resolution. For example, the instance
`add_comm_group.to_add_group {α} [add_comm_group α] : add_group α` applies to all type-class
resolution problems of the form `add_group _`, and type-class inference will then do an
exhaustive search to find a commutative group. These instances take a long time to fail.
Other instances will only apply if the goal has a certain shape. For example
`int.add_group : add_group ℤ` or
`add_group.prod {α β} [add_group α] [add_group β] : add_group (α × β)`. Usually these instances
will fail quickly, and when they apply, they are almost the desired instance.
For this reason, we want the instances of the second type (that only apply in specific cases) to
always have higher priority than the instances of the first type (that always apply).
See also #1561.
Therefore, if we create an instance that always applies, we set the priority of these instances to
100 (or something similar, which is below the default value of 1000)."
library_note "default priority"
"Instances that always apply should be applied after instances that only apply in specific cases,
see note [lower instance priority] above.
Classes that use the `extends` keyword automatically generate instances that always apply.
Therefore, we set the priority of these instances to 100 (or something similar, which is below the
default value of 1000) using `set_option default_priority 100`.
We have to put this option inside a section, so that the default priority is the default
1000 outside the section."
/-- A linter object for checking instance priorities of instances that always apply.
This is in the default linter set. -/
@[linter, priority 1460] meta def linter.instance_priority : linter :=
{ test := instance_priority,
no_errors_found := "All instance priorities are good",
errors_found := "DANGEROUS INSTANCE PRIORITIES.\nThe following instances always apply, and therefore should have a priority < 1000.\nIf you don't know what priority to choose, use priority 100." }
/-- Reports definitions and constants that are missing doc strings -/
meta def doc_blame_report_defn : declaration → tactic (option string)
| (declaration.defn n _ _ _ _ _) := doc_string n >> return none <|> return "def missing doc string"
| (declaration.cnst n _ _ _) := doc_string n >> return none <|> return "constant missing doc string"
| _ := return none
/-- Reports definitions and constants that are missing doc strings -/
meta def doc_blame_report_thm : declaration → tactic (option string)
| (declaration.thm n _ _ _) := doc_string n >> return none <|> return "theorem missing doc string"
| _ := return none
/-- A linter for checking definition doc strings -/
@[linter, priority 1450] meta def linter.doc_blame : linter :=
{ test := λ d, mcond (bnot <$> has_attribute' `instance d.to_name) (doc_blame_report_defn d) (return none),
no_errors_found := "No definitions are missing documentation.",
errors_found := "DEFINITIONS ARE MISSING DOCUMENTATION STRINGS" }
/-- A linter for checking theorem doc strings. This is not in the default linter set. -/
meta def linter.doc_blame_thm : linter :=
{ test := doc_blame_report_thm,
no_errors_found := "No theorems are missing documentation.",
errors_found := "THEOREMS ARE MISSING DOCUMENTATION STRINGS",
is_fast := ff }
/-- `get_checks slow extra use_only` produces a list of linters.
`extras` is a list of names that should resolve to declarations with type `linter`.
If `use_only` is true, it only uses the linters in `extra`.
Otherwise, it uses all linters in the environment tagged with `@[linter]`.
If `slow` is false, it only uses the fast default tests. -/
meta def get_checks (slow : bool) (extra : list name) (use_only : bool) :
tactic (list linter) := do
default ← if use_only then return [] else attribute.get_instances `linter >>= get_linters,
let default := if slow then default else default.filter (λ l, l.is_fast),
list.append default <$> get_linters extra
/-- If `verbose` is true, return `old ++ new`, else return `old`. -/
private meta def append_when (verbose : bool) (old new : format) : format :=
cond verbose (old ++ new) old
private meta def check_fold (printer : (declaration → tactic (option string)) → tactic (name_set × format))
(verbose : bool) : name_set × format → linter → tactic (name_set × format)
| (ns, s) ⟨tac, ok_string, warning_string, _⟩ :=
do (new_ns, f) ← printer tac,
if f.is_nil then return $ (ns, append_when verbose s format!"/- OK: {ok_string}. -/\n")
else return $ (ns.union new_ns, s ++ format!"/- {warning_string}: -/" ++ f ++ "\n\n")
/-- The common denominator of `#lint[|mathlib|all]`.
The different commands have different configurations for `l`, `printer` and `where_desc`.
If `slow` is false, doesn't do the checks that take a lot of time.
If `verbose` is false, it will suppress messages from passing checks.
By setting `checks` you can customize which checks are performed.
Returns a `name_set` containing the names of all declarations that fail any check in `check`,
and a `format` object describing the failures. -/
meta def lint_aux (l : list declaration)
(printer : (declaration → tactic (option string)) → tactic (name_set × format))
(where_desc : string) (slow verbose : bool) (checks : list linter) : tactic (name_set × format) := do
let s : format := append_when verbose format.nil "/- Note: This command is still in development. -/\n",
let s := append_when verbose s format!"/- Checking {l.length} declarations {where_desc} -/\n\n",
(ns, s) ← checks.mfoldl (check_fold printer verbose) (mk_name_set, s),
return $ (ns, if slow then s else append_when verbose s "/- (slow tests skipped) -/\n")
/-- Return the message printed by `#lint` and a `name_set` containing all declarations that fail. -/
meta def lint (slow : bool := tt) (verbose : bool := tt) (extra : list name := [])
(use_only : bool := ff) : tactic (name_set × format) := do
checks ← get_checks slow extra use_only,
e ← get_env,
l ← e.mfilter (λ d,
if e.in_current_file' d.to_name ∧ ¬ d.to_name.is_internal ∧ ¬ d.is_auto_generated e
then bnot <$> has_attribute' `nolint d.to_name else return ff),
lint_aux l (λ t, do lst ← fold_over_with_cond l t, return
(name_set.of_list (lst.map (declaration.to_name ∘ prod.fst)), print_decls lst))
"in the current file" slow verbose checks
private meta def name_list_of_decl_lists (l : list (string × list (declaration × string))) :
name_set :=
name_set.of_list $ list.join $ l.map $ λ ⟨_, l'⟩, l'.map $ declaration.to_name ∘ prod.fst
/-- Return the message printed by `#lint_mathlib` and a `name_set` containing all declarations that fail. -/
meta def lint_mathlib (slow : bool := tt) (verbose : bool := tt) (extra : list name := [])
(use_only : bool := ff) : tactic (name_set × format) := do
checks ← get_checks slow extra use_only,
e ← get_env,
ml ← get_mathlib_dir,
/- note: we don't separate out some of these tests in `lint_aux` because that causes a
performance hit. That is also the reason for the current formulation using if then else. -/
l ← e.mfilter (λ d,
if e.is_prefix_of_file ml d.to_name ∧ ¬ d.to_name.is_internal ∧ ¬ d.is_auto_generated e
then bnot <$> has_attribute' `nolint d.to_name else return ff),
let ml' := ml.length,
lint_aux l (λ t, do lst ← fold_over_with_cond_sorted l t,
return (name_list_of_decl_lists lst, print_decls_sorted_mathlib ml' lst))
"in mathlib (only in imported files)" slow verbose checks
/-- Return the message printed by `#lint_all` and a `name_set` containing all declarations that fail. -/
meta def lint_all (slow : bool := tt) (verbose : bool := tt) (extra : list name := [])
(use_only : bool := ff) : tactic (name_set × format) := do
checks ← get_checks slow extra use_only,
e ← get_env,
l ← e.mfilter (λ d, if ¬ d.to_name.is_internal ∧ ¬ d.is_auto_generated e
then bnot <$> has_attribute' `nolint d.to_name else return ff),
lint_aux l (λ t, do lst ← fold_over_with_cond_sorted l t,
return (name_list_of_decl_lists lst, print_decls_sorted lst))
"in all imported files (including this one)" slow verbose checks
/-- Parses an optional `only`, followed by a sequence of zero or more identifiers.
Prepends `linter.` to each of these identifiers. -/
private meta def parse_lint_additions : parser (bool × list name) :=
prod.mk <$> only_flag <*> (list.map (name.append `linter) <$> ident_*)
/-- The common denominator of `lint_cmd`, `lint_mathlib_cmd`, `lint_all_cmd` -/
private meta def lint_cmd_aux (scope : bool → bool → list name → bool → tactic (name_set × format)) :
parser unit :=
do silent ← optional (tk "-"),
fast_only ← optional (tk "*"),
silent ← if silent.is_some then return silent else optional (tk "-"), -- allow either order of *-
(use_only, extra) ← parse_lint_additions,
(_, s) ← scope fast_only.is_none silent.is_none extra use_only,
when (¬ s.is_nil) $ do
trace s,
when silent.is_some $ fail "Linting did not succeed"
/-- The command `#lint` at the bottom of a file will warn you about some common mistakes
in that file. Usage: `#lint`, `#lint linter_1 linter_2`, `#lint only linter_1 linter_2`.
`#lint-` will suppress the output of passing checks.
Use the command `#list_linters` to see all available linters. -/
@[user_command] meta def lint_cmd (_ : parse $ tk "#lint") : parser unit :=
lint_cmd_aux @lint
/-- The command `#lint_mathlib` checks all of mathlib for certain mistakes.
Usage: `#lint_mathlib`, `#lint_mathlib linter_1 linter_2`, `#lint_mathlib only linter_1 linter_2`.
`#lint_mathlib-` will suppress the output of passing checks.
Use the command `#list_linters` to see all available linters. -/
@[user_command] meta def lint_mathlib_cmd (_ : parse $ tk "#lint_mathlib") : parser unit :=
lint_cmd_aux @lint_mathlib
/-- The command `#lint_all` checks all imported files for certain mistakes.
Usage: `#lint_all`, `#lint_all linter_1 linter_2`, `#lint_all only linter_1 linter_2`.
`#lint_all-` will suppress the output of passing checks.
Use the command `#list_linters` to see all available linters. -/
@[user_command] meta def lint_all_cmd (_ : parse $ tk "#lint_all") : parser unit :=
lint_cmd_aux @lint_all
/-- The command `#list_linters` prints a list of all available linters. -/
@[user_command] meta def list_linters (_ : parse $ tk "#list_linters") : parser unit :=
do env ← get_env,
let ns := env.decl_filter_map $ λ dcl,
if (dcl.to_name.get_prefix = `linter) && (dcl.type = `(linter)) then some dcl.to_name else none,
trace "Available linters:\n linters marked with (*) are in the default lint set\n",
ns.mmap' $ λ n, do
b ← has_attribute' `linter n,
trace $ n.pop_prefix.to_string ++ if b then " (*)" else ""
/-- Use `lint` as a hole command. Note: In a large file, there might be some delay between
choosing the option and the information appearing -/
@[hole_command] meta def lint_hole_cmd : hole_command :=
{ name := "Lint",
descr := "Lint: Find common mistakes in current file.",
action := λ es, do (_, s) ← lint, return [(s.to_string,"")] }
/-- Tries to apply the `nolint` attribute to a list of declarations. Always succeeds, even if some
of the declarations don't exist. -/
meta def apply_nolint_tac (decls : list name) : tactic unit :=
decls.mmap' (λ d, try (nolint_attr.set d () tt))
/-- `apply_nolint id1 id2 ...` tries to apply the `nolint` attribute to `id1`, `id2`, ...
It will always succeed, even if some of the declarations do not exist. -/
@[user_command] meta def apply_nolint_cmd (_ : parse $ tk "apply_nolint") : parser unit :=
ident_* >>= ↑apply_nolint_tac
|
949796dd001d86c9622d59dabd42564e7c9aed97 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/category_theory/concrete_category/unbundled_hom.lean | 22237c3b072b5296eeb21ef824da30d92dfb3f7e | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 2,302 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import category_theory.concrete_category.bundled_hom
/-!
# Category instances for structures that use unbundled homs
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file provides basic infrastructure to define concrete
categories using unbundled homs (see `class unbundled_hom`), and
define forgetful functors between them (see
`unbundled_hom.mk_has_forget₂`).
-/
universes v u
namespace category_theory
/-- A class for unbundled homs used to define a category. `hom` must
take two types `α`, `β` and instances of the corresponding structures,
and return a predicate on `α → β`. -/
class unbundled_hom {c : Type u → Type u} (hom : Π {α β}, c α → c β → (α → β) → Prop) :=
(hom_id [] : ∀ {α} (ia : c α), hom ia ia id)
(hom_comp [] : ∀ {α β γ} {Iα : c α} {Iβ : c β} {Iγ : c γ} {g : β → γ} {f : α → β}
(hg : hom Iβ Iγ g) (hf : hom Iα Iβ f), hom Iα Iγ (g ∘ f))
namespace unbundled_hom
variables (c : Type u → Type u) (hom : Π ⦃α β⦄, c α → c β → (α → β) → Prop) [𝒞 : unbundled_hom hom]
include 𝒞
instance bundled_hom : bundled_hom (λ α β (Iα : c α) (Iβ : c β), subtype (hom Iα Iβ)) :=
{ to_fun := λ _ _ _ _, subtype.val,
id := λ α Iα, ⟨id, hom_id hom Iα⟩,
id_to_fun := by intros; refl,
comp := λ _ _ _ _ _ _ g f, ⟨g.1 ∘ f.1, hom_comp c g.2 f.2⟩,
comp_to_fun := by intros; refl,
hom_ext := by intros; apply subtype.eq }
section has_forget₂
variables {c hom} {c' : Type u → Type u} {hom' : Π ⦃α β⦄, c' α → c' β → (α → β) → Prop}
[𝒞' : unbundled_hom hom']
include 𝒞'
variables (obj : Π ⦃α⦄, c α → c' α)
(map : ∀ ⦃α β Iα Iβ f⦄, @hom α β Iα Iβ f → hom' (obj Iα) (obj Iβ) f)
/-- A custom constructor for forgetful functor
between concrete categories defined using `unbundled_hom`. -/
def mk_has_forget₂ : has_forget₂ (bundled c) (bundled c') :=
bundled_hom.mk_has_forget₂ obj (λ X Y f, ⟨f.val, map f.property⟩) (λ _ _ _, rfl)
end has_forget₂
end unbundled_hom
end category_theory
|
b8b3157391cb52c1bee092db76c675e66e9d3a94 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /src/Lean/Util/CollectMVars.lean | 58b1e107887217fe8934b03643253f5e6f494098 | [
"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 | 1,152 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Expr
namespace Lean
namespace CollectMVars
structure State where
visitedExpr : ExprSet := {}
result : Array MVarId := #[]
instance : Inhabited State := ⟨{}⟩
abbrev Visitor := State → State
mutual
partial def visit (e : Expr) : Visitor := fun s =>
if !e.hasMVar || s.visitedExpr.contains e then s
else main e { s with visitedExpr := s.visitedExpr.insert e }
partial def main : Expr → Visitor
| Expr.proj _ _ e _ => visit e
| Expr.forallE _ d b _ => visit b ∘ visit d
| Expr.lam _ d b _ => visit b ∘ visit d
| Expr.letE _ t v b _ => visit b ∘ visit v ∘ visit t
| Expr.app f a _ => visit a ∘ visit f
| Expr.mdata _ b _ => visit b
| Expr.mvar mvarId _ => fun s => { s with result := s.result.push mvarId }
| _ => id
end
end CollectMVars
def Expr.collectMVars (s : CollectMVars.State) (e : Expr) : CollectMVars.State :=
CollectMVars.visit e s
end Lean
|
943cf942c785e07f532a7ba27a8f576dc4d17822 | 934eae675a9d997202bb021816325184e7d694aa | /_notes/Languages/lean/myproject/typeclass.lean | bf07c24a9a45dec91b4dff3f4d3fea0818e3fad3 | [] | no_license | philzook58/philzook58.github.io | da78841df4ffd9a19c81e0eab833983d95a64b70 | 76000a5847bd6ee41dff25937ae916835bbcf03f | refs/heads/master | 1,692,951,958,916 | 1,692,631,945,000 | 1,692,631,945,000 | 91,513,884 | 9 | 4 | null | 1,677,330,791,000 | 1,494,977,989,000 | Jupyter Notebook | UTF-8 | Lean | false | false | 1,629 | lean |
-- Use and abuse of instance parameters in the Lean mathematical library
-- https://arxiv.org/pdf/2202.01629.pdf
class GoodNum (n : Int) where
instance : GoodNum 3 where
instance : GoodNum 4 where
#check (inferInstance : GoodNum 4)
-- set_option in
--variable (mylist : Type)
def mylist := Type
--variable (cons : Int -> mylist -> mylist) --(nil : mylist)
--variable (myappend : mylist -> mylist -> mylist -> Prop)
axiom nil : mylist
axiom cons : Int -> mylist -> mylist
class MyAppend (x : Type) (y : Type) (z : Type) where
#check MyAppend Int Int Int
instance myfoo (x : mylist) : MyAppend nil x x where
instance [MyAppend xs ys zs] : MyAppend (cons x xs) (ys) (cons x zs) where
#check myfoo
#check inferInstance
#check (inferInstance : MyAppend nil nil nil)
#synth (MyAppend nil nil nil)
#check exists x, x
--theorem mytest : (Σ z, MyAppend (cons 7 nil) nil z) := by
-- exists
-- exact inferInstance
--#print mytest
-- instance : MyAppend (cons x xs) (ys) (cons x zs) where
axiom A : Type
axiom B : Type
axiom C : Type
axiom D : Type
class R (a : Type) (b : Type) where
instance I1 : R A B where
instance I2 : R A C where
instance I3 : R C D where
instance I4 {X Y Z : Type} [R X Y] [R Y Z] : R X Z where
#check (inferInstance : R A D)
set_option trace.Meta.synthInstance true
#synth R A D
class Quant (a : Type) where
class Foo (a : Type) where
class Biz (a : Type) where
-- https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/quantified_constraints.html
instance [Biz a] : Quant a where
instance biz [forall a, [Biz a] : Quant a] : Foo Int where
#check biz
#synth Foo Int
-- unification hints
|
947d191edd6c004cc3783895fdb58047d7e00372 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/category_theory/monoidal/rigid/basic.lean | 60a4001ff3ccc8d6a53691050b9a928d0cc41ffe | [
"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 | 28,240 | lean | /-
Copyright (c) 2021 Jakob von Raumer. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jakob von Raumer
-/
import category_theory.monoidal.coherence_lemmas
import category_theory.closed.monoidal
import tactic.apply_fun
/-!
# Rigid (autonomous) monoidal categories
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines rigid (autonomous) monoidal categories and the necessary theory about
exact pairings and duals.
## Main definitions
* `exact_pairing` of two objects of a monoidal category
* Type classes `has_left_dual` and `has_right_dual` that capture that a pairing exists
* The `right_adjoint_mate f` as a morphism `fᘁ : Yᘁ ⟶ Xᘁ` for a morphism `f : X ⟶ Y`
* The classes of `right_rigid_category`, `left_rigid_category` and `rigid_category`
## Main statements
* `comp_right_adjoint_mate`: The adjoint mates of the composition is the composition of
adjoint mates.
## Notations
* `η_` and `ε_` denote the coevaluation and evaluation morphism of an exact pairing.
* `Xᘁ` and `ᘁX` denote the right and left dual of an object, as well as the adjoint
mate of a morphism.
## Future work
* Show that `X ⊗ Y` and `Yᘁ ⊗ Xᘁ` form an exact pairing.
* Show that the left adjoint mate of the right adjoint mate of a morphism is the morphism itself.
* Simplify constructions in the case where a symmetry or braiding is present.
* Show that `ᘁ` gives an equivalence of categories `C ≅ (Cᵒᵖ)ᴹᵒᵖ`.
* Define pivotal categories (rigid categories equipped with a natural isomorphism `ᘁᘁ ≅ 𝟙 C`).
## Notes
Although we construct the adjunction `tensor_left Y ⊣ tensor_left X` from `exact_pairing X Y`,
this is not a bijective correspondence.
I think the correct statement is that `tensor_left Y` and `tensor_left X` are
module endofunctors of `C` as a right `C` module category,
and `exact_pairing X Y` is in bijection with adjunctions compatible with this right `C` action.
## References
* <https://ncatlab.org/nlab/show/rigid+monoidal+category>
## Tags
rigid category, monoidal category
-/
open category_theory
universes v v₁ v₂ v₃ u u₁ u₂ u₃
noncomputable theory
namespace category_theory
variables {C : Type u₁} [category.{v₁} C] [monoidal_category C]
/-- An exact pairing is a pair of objects `X Y : C` which admit
a coevaluation and evaluation morphism which fulfill two triangle equalities. -/
class exact_pairing (X Y : C) :=
(coevaluation [] : 𝟙_ C ⟶ X ⊗ Y)
(evaluation [] : Y ⊗ X ⟶ 𝟙_ C)
(coevaluation_evaluation' [] :
(𝟙 Y ⊗ coevaluation) ≫ (α_ _ _ _).inv ≫ (evaluation ⊗ 𝟙 Y)
= (ρ_ Y).hom ≫ (λ_ Y).inv . obviously)
(evaluation_coevaluation' [] :
(coevaluation ⊗ 𝟙 X) ≫ (α_ _ _ _).hom ≫ (𝟙 X ⊗ evaluation)
= (λ_ X).hom ≫ (ρ_ X).inv . obviously)
open exact_pairing
notation `η_` := exact_pairing.coevaluation
notation `ε_` := exact_pairing.evaluation
restate_axiom coevaluation_evaluation'
attribute [simp, reassoc] exact_pairing.coevaluation_evaluation
restate_axiom evaluation_coevaluation'
attribute [simp, reassoc] exact_pairing.evaluation_coevaluation
instance exact_pairing_unit : exact_pairing (𝟙_ C) (𝟙_ C) :=
{ coevaluation := (ρ_ _).inv,
evaluation := (ρ_ _).hom,
coevaluation_evaluation' := by coherence,
evaluation_coevaluation' := by coherence, }
/-- A class of objects which have a right dual. -/
class has_right_dual (X : C) :=
(right_dual : C)
[exact : exact_pairing X right_dual]
/-- A class of objects with have a left dual. -/
class has_left_dual (Y : C) :=
(left_dual : C)
[exact : exact_pairing left_dual Y]
attribute [instance] has_right_dual.exact
attribute [instance] has_left_dual.exact
open exact_pairing has_right_dual has_left_dual monoidal_category
prefix (name := left_dual) `ᘁ`:1025 := left_dual
postfix (name := right_dual) `ᘁ`:1025 := right_dual
instance has_right_dual_unit : has_right_dual (𝟙_ C) :=
{ right_dual := 𝟙_ C }
instance has_left_dual_unit : has_left_dual (𝟙_ C) :=
{ left_dual := 𝟙_ C }
instance has_right_dual_left_dual {X : C} [has_left_dual X] : has_right_dual (ᘁX) :=
{ right_dual := X }
instance has_left_dual_right_dual {X : C} [has_right_dual X] : has_left_dual Xᘁ :=
{ left_dual := X }
@[simp]
lemma left_dual_right_dual {X : C} [has_right_dual X] : ᘁ(Xᘁ) = X := rfl
@[simp]
lemma right_dual_left_dual {X : C} [has_left_dual X] : (ᘁX)ᘁ = X := rfl
/-- The right adjoint mate `fᘁ : Xᘁ ⟶ Yᘁ` of a morphism `f : X ⟶ Y`. -/
def right_adjoint_mate {X Y : C} [has_right_dual X] [has_right_dual Y] (f : X ⟶ Y) : Yᘁ ⟶ Xᘁ :=
(ρ_ _).inv ≫ (𝟙 _ ⊗ η_ _ _) ≫ (𝟙 _ ⊗ (f ⊗ 𝟙 _))
≫ (α_ _ _ _).inv ≫ ((ε_ _ _) ⊗ 𝟙 _) ≫ (λ_ _).hom
/-- The left adjoint mate `ᘁf : ᘁY ⟶ ᘁX` of a morphism `f : X ⟶ Y`. -/
def left_adjoint_mate {X Y : C} [has_left_dual X] [has_left_dual Y] (f : X ⟶ Y) : ᘁY ⟶ ᘁX :=
(λ_ _).inv ≫ (η_ (ᘁX) X ⊗ 𝟙 _) ≫ ((𝟙 _ ⊗ f) ⊗ 𝟙 _)
≫ (α_ _ _ _).hom ≫ (𝟙 _ ⊗ ε_ _ _) ≫ (ρ_ _).hom
notation (name := right_adjoint_mate) f `ᘁ` := right_adjoint_mate f
notation (name := left_adjoint_mate) `ᘁ` f := left_adjoint_mate f
@[simp]
lemma right_adjoint_mate_id {X : C} [has_right_dual X] : (𝟙 X)ᘁ = 𝟙 (Xᘁ) :=
by simp only [right_adjoint_mate, monoidal_category.tensor_id, category.id_comp,
coevaluation_evaluation_assoc, category.comp_id, iso.inv_hom_id]
@[simp]
lemma left_adjoint_mate_id {X : C} [has_left_dual X] : ᘁ(𝟙 X) = 𝟙 (ᘁX) :=
by simp only [left_adjoint_mate, monoidal_category.tensor_id, category.id_comp,
evaluation_coevaluation_assoc, category.comp_id, iso.inv_hom_id]
lemma right_adjoint_mate_comp {X Y Z : C} [has_right_dual X]
[has_right_dual Y] {f : X ⟶ Y} {g : Xᘁ ⟶ Z} :
fᘁ ≫ g
= (ρ_ Yᘁ).inv ≫ (𝟙 _ ⊗ η_ X Xᘁ) ≫ (𝟙 _ ⊗ f ⊗ g)
≫ (α_ Yᘁ Y Z).inv ≫ (ε_ Y Yᘁ ⊗ 𝟙 _) ≫ (λ_ Z).hom :=
begin
dunfold right_adjoint_mate,
rw [category.assoc, category.assoc, associator_inv_naturality_assoc,
associator_inv_naturality_assoc, ←tensor_id_comp_id_tensor g, category.assoc, category.assoc,
category.assoc, category.assoc, id_tensor_comp_tensor_id_assoc, ←left_unitor_naturality,
tensor_id_comp_id_tensor_assoc],
end
lemma left_adjoint_mate_comp {X Y Z : C} [has_left_dual X] [has_left_dual Y]
{f : X ⟶ Y} {g : ᘁX ⟶ Z} :
ᘁf ≫ g
= (λ_ _).inv ≫ (η_ (ᘁX) X ⊗ 𝟙 _) ≫ ((g ⊗ f) ⊗ 𝟙 _)
≫ (α_ _ _ _).hom ≫ (𝟙 _ ⊗ ε_ _ _) ≫ (ρ_ _).hom :=
begin
dunfold left_adjoint_mate,
rw [category.assoc, category.assoc, associator_naturality_assoc, associator_naturality_assoc,
←id_tensor_comp_tensor_id _ g, category.assoc, category.assoc, category.assoc, category.assoc,
tensor_id_comp_id_tensor_assoc, ←right_unitor_naturality, id_tensor_comp_tensor_id_assoc],
end
/-- The composition of right adjoint mates is the adjoint mate of the composition. -/
@[reassoc]
lemma comp_right_adjoint_mate {X Y Z : C}
[has_right_dual X] [has_right_dual Y] [has_right_dual Z] {f : X ⟶ Y} {g : Y ⟶ Z} :
(f ≫ g)ᘁ = gᘁ ≫ fᘁ :=
begin
rw right_adjoint_mate_comp,
simp only [right_adjoint_mate, comp_tensor_id, iso.cancel_iso_inv_left, id_tensor_comp,
category.assoc],
symmetry, iterate 5 { transitivity, rw [←category.id_comp g, tensor_comp] },
rw ←category.assoc,
symmetry, iterate 2 { transitivity, rw ←category.assoc }, apply eq_whisker,
repeat { rw ←id_tensor_comp }, congr' 1,
rw [←id_tensor_comp_tensor_id (λ_ Xᘁ).hom g, id_tensor_right_unitor_inv, category.assoc,
category.assoc, right_unitor_inv_naturality_assoc, ←associator_naturality_assoc, tensor_id,
tensor_id_comp_id_tensor_assoc, ←associator_naturality_assoc],
slice_rhs 2 3 { rw [←tensor_comp, tensor_id, category.comp_id,
←category.id_comp (η_ Y Yᘁ), tensor_comp] },
rw [←id_tensor_comp_tensor_id _ (η_ Y Yᘁ), ←tensor_id],
repeat { rw category.assoc },
rw [pentagon_hom_inv_assoc, ←associator_naturality_assoc, associator_inv_naturality_assoc],
slice_rhs 5 7 { rw [←comp_tensor_id, ←comp_tensor_id, evaluation_coevaluation, comp_tensor_id] },
rw associator_inv_naturality_assoc,
slice_rhs 4 5 { rw [←tensor_comp, left_unitor_naturality, tensor_comp] },
repeat { rw category.assoc },
rw [triangle_assoc_comp_right_inv_assoc, ←left_unitor_tensor_assoc,
left_unitor_naturality_assoc, unitors_equal, ←category.assoc, ←category.assoc], simp
end
/-- The composition of left adjoint mates is the adjoint mate of the composition. -/
@[reassoc]
lemma comp_left_adjoint_mate {X Y Z : C}
[has_left_dual X] [has_left_dual Y] [has_left_dual Z] {f : X ⟶ Y} {g : Y ⟶ Z} :
ᘁ(f ≫ g) = ᘁg ≫ ᘁf :=
begin
rw left_adjoint_mate_comp,
simp only [left_adjoint_mate, id_tensor_comp, iso.cancel_iso_inv_left,
comp_tensor_id, category.assoc],
symmetry, iterate 5 { transitivity, rw [←category.id_comp g, tensor_comp] },
rw ← category.assoc,
symmetry, iterate 2 { transitivity, rw ←category.assoc }, apply eq_whisker,
repeat { rw ←comp_tensor_id }, congr' 1,
rw [←tensor_id_comp_id_tensor g (ρ_ (ᘁX)).hom, left_unitor_inv_tensor_id, category.assoc,
category.assoc, left_unitor_inv_naturality_assoc, ←associator_inv_naturality_assoc, tensor_id,
id_tensor_comp_tensor_id_assoc, ←associator_inv_naturality_assoc],
slice_rhs 2 3 { rw [←tensor_comp, tensor_id, category.comp_id,
←category.id_comp (η_ (ᘁY) Y), tensor_comp] },
rw [←tensor_id_comp_id_tensor (η_ (ᘁY) Y), ←tensor_id],
repeat { rw category.assoc },
rw [pentagon_inv_hom_assoc, ←associator_inv_naturality_assoc, associator_naturality_assoc],
slice_rhs 5 7 { rw [←id_tensor_comp, ←id_tensor_comp, coevaluation_evaluation, id_tensor_comp ]},
rw associator_naturality_assoc,
slice_rhs 4 5 { rw [←tensor_comp, right_unitor_naturality, tensor_comp] },
repeat { rw category.assoc },
rw [triangle_assoc_comp_left_inv_assoc, ←right_unitor_tensor_assoc,
right_unitor_naturality_assoc, ←unitors_equal, ←category.assoc, ←category.assoc], simp
end
/--
Given an exact pairing on `Y Y'`,
we get a bijection on hom-sets `(Y' ⊗ X ⟶ Z) ≃ (X ⟶ Y ⊗ Z)`
by "pulling the string on the left" up or down.
This gives the adjunction `tensor_left_adjunction Y Y' : tensor_left Y' ⊣ tensor_left Y`.
This adjunction is often referred to as "Frobenius reciprocity" in the
fusion categories / planar algebras / subfactors literature.
-/
def tensor_left_hom_equiv (X Y Y' Z : C) [exact_pairing Y Y'] :
(Y' ⊗ X ⟶ Z) ≃ (X ⟶ Y ⊗ Z) :=
{ to_fun := λ f, (λ_ _).inv ≫ (η_ _ _ ⊗ 𝟙 _) ≫ (α_ _ _ _).hom ≫ (𝟙 _ ⊗ f),
inv_fun := λ f, (𝟙 Y' ⊗ f) ≫ (α_ _ _ _).inv ≫ (ε_ _ _ ⊗ 𝟙 _) ≫ (λ_ _).hom,
left_inv := λ f, begin
dsimp,
simp only [id_tensor_comp],
slice_lhs 4 5 { rw associator_inv_naturality, },
slice_lhs 5 6 { rw [tensor_id, id_tensor_comp_tensor_id, ←tensor_id_comp_id_tensor], },
slice_lhs 2 5 { simp only [←tensor_id, associator_inv_conjugation], },
have c : (α_ Y' (Y ⊗ Y') X).hom ≫ (𝟙 Y' ⊗ (α_ Y Y' X).hom) ≫ (α_ Y' Y (Y' ⊗ X)).inv ≫
(α_ (Y' ⊗ Y) Y' X).inv = (α_ _ _ _).inv ⊗ 𝟙 _, pure_coherence,
slice_lhs 4 7 { rw c, },
slice_lhs 3 5 { rw [←comp_tensor_id, ←comp_tensor_id, coevaluation_evaluation], },
simp only [left_unitor_conjugation],
coherence,
end,
right_inv := λ f, begin
dsimp,
simp only [id_tensor_comp],
slice_lhs 3 4 { rw ←associator_naturality, },
slice_lhs 2 3 { rw [tensor_id, tensor_id_comp_id_tensor, ←id_tensor_comp_tensor_id], },
slice_lhs 3 6 { simp only [←tensor_id, associator_inv_conjugation], },
have c : (α_ (Y ⊗ Y') Y Z).hom ≫ (α_ Y Y' (Y ⊗ Z)).hom ≫ (𝟙 Y ⊗ (α_ Y' Y Z).inv) ≫
(α_ Y (Y' ⊗ Y) Z).inv = (α_ _ _ _).hom ⊗ 𝟙 Z, pure_coherence,
slice_lhs 5 8 { rw c, },
slice_lhs 4 6 { rw [←comp_tensor_id, ←comp_tensor_id, evaluation_coevaluation], },
simp only [left_unitor_conjugation],
coherence,
end, }
/--
Given an exact pairing on `Y Y'`,
we get a bijection on hom-sets `(X ⊗ Y ⟶ Z) ≃ (X ⟶ Z ⊗ Y')`
by "pulling the string on the right" up or down.
-/
def tensor_right_hom_equiv (X Y Y' Z : C) [exact_pairing Y Y'] :
(X ⊗ Y ⟶ Z) ≃ (X ⟶ Z ⊗ Y') :=
{ to_fun := λ f, (ρ_ _).inv ≫ (𝟙 _ ⊗ η_ _ _) ≫ (α_ _ _ _).inv ≫ (f ⊗ 𝟙 _),
inv_fun := λ f, (f ⊗ 𝟙 _) ≫ (α_ _ _ _).hom ≫ (𝟙 _ ⊗ ε_ _ _) ≫ (ρ_ _).hom,
left_inv := λ f, begin
dsimp,
simp only [comp_tensor_id],
slice_lhs 4 5 { rw associator_naturality, },
slice_lhs 5 6 { rw [tensor_id, tensor_id_comp_id_tensor, ←id_tensor_comp_tensor_id], },
slice_lhs 2 5 { simp only [←tensor_id, associator_conjugation], },
have c : (α_ X (Y ⊗ Y') Y).inv ≫ ((α_ X Y Y').inv ⊗ 𝟙 Y) ≫ (α_ (X ⊗ Y) Y' Y).hom ≫
(α_ X Y (Y' ⊗ Y)).hom = 𝟙 _ ⊗ (α_ _ _ _).hom, pure_coherence,
slice_lhs 4 7 { rw c, },
slice_lhs 3 5 { rw [←id_tensor_comp, ←id_tensor_comp, evaluation_coevaluation], },
simp only [right_unitor_conjugation],
coherence,
end,
right_inv := λ f, begin
dsimp,
simp only [comp_tensor_id],
slice_lhs 3 4 { rw ←associator_inv_naturality, },
slice_lhs 2 3 { rw [tensor_id, id_tensor_comp_tensor_id, ←tensor_id_comp_id_tensor], },
slice_lhs 3 6 { simp only [←tensor_id, associator_conjugation], },
have c : (α_ Z Y' (Y ⊗ Y')).inv ≫ (α_ (Z ⊗ Y') Y Y').inv ≫ ((α_ Z Y' Y).hom ⊗ 𝟙 Y') ≫
(α_ Z (Y' ⊗ Y) Y').hom = 𝟙 _ ⊗ (α_ _ _ _).inv, pure_coherence,
slice_lhs 5 8 { rw c, },
slice_lhs 4 6 { rw [←id_tensor_comp, ←id_tensor_comp, coevaluation_evaluation], },
simp only [right_unitor_conjugation],
coherence,
end, }
lemma tensor_left_hom_equiv_naturality
{X Y Y' Z Z' : C} [exact_pairing Y Y'] (f : Y' ⊗ X ⟶ Z) (g : Z ⟶ Z') :
(tensor_left_hom_equiv X Y Y' Z') (f ≫ g) =
(tensor_left_hom_equiv X Y Y' Z) f ≫ (𝟙 Y ⊗ g) :=
begin
dsimp [tensor_left_hom_equiv],
simp only [id_tensor_comp, category.assoc],
end
lemma tensor_left_hom_equiv_symm_naturality {X X' Y Y' Z : C} [exact_pairing Y Y']
(f : X ⟶ X') (g : X' ⟶ Y ⊗ Z) :
(tensor_left_hom_equiv X Y Y' Z).symm (f ≫ g) =
(𝟙 _ ⊗ f) ≫ (tensor_left_hom_equiv X' Y Y' Z).symm g :=
begin
dsimp [tensor_left_hom_equiv],
simp only [id_tensor_comp, category.assoc],
end
lemma tensor_right_hom_equiv_naturality {X Y Y' Z Z' : C} [exact_pairing Y Y']
(f : X ⊗ Y ⟶ Z) (g : Z ⟶ Z') :
(tensor_right_hom_equiv X Y Y' Z') (f ≫ g) =
(tensor_right_hom_equiv X Y Y' Z) f ≫ (g ⊗ 𝟙 Y') :=
begin
dsimp [tensor_right_hom_equiv],
simp only [comp_tensor_id, category.assoc],
end
lemma tensor_right_hom_equiv_symm_naturality
{X X' Y Y' Z : C} [exact_pairing Y Y'] (f : X ⟶ X') (g : X' ⟶ Z ⊗ Y') :
((tensor_right_hom_equiv X Y Y' Z).symm) (f ≫ g) =
(f ⊗ 𝟙 Y) ≫ ((tensor_right_hom_equiv X' Y Y' Z).symm) g :=
begin
dsimp [tensor_right_hom_equiv],
simp only [comp_tensor_id, category.assoc],
end
/--
If `Y Y'` have an exact pairing,
then the functor `tensor_left Y'` is left adjoint to `tensor_left Y`.
-/
def tensor_left_adjunction (Y Y' : C) [exact_pairing Y Y'] : tensor_left Y' ⊣ tensor_left Y :=
adjunction.mk_of_hom_equiv
{ hom_equiv := λ X Z, tensor_left_hom_equiv X Y Y' Z,
hom_equiv_naturality_left_symm' :=
λ X X' Z f g, tensor_left_hom_equiv_symm_naturality f g,
hom_equiv_naturality_right' :=
λ X Z Z' f g, tensor_left_hom_equiv_naturality f g, }
/--
If `Y Y'` have an exact pairing,
then the functor `tensor_right Y` is left adjoint to `tensor_right Y'`.
-/
def tensor_right_adjunction (Y Y' : C) [exact_pairing Y Y'] : tensor_right Y ⊣ tensor_right Y' :=
adjunction.mk_of_hom_equiv
{ hom_equiv := λ X Z, tensor_right_hom_equiv X Y Y' Z,
hom_equiv_naturality_left_symm' :=
λ X X' Z f g, tensor_right_hom_equiv_symm_naturality f g,
hom_equiv_naturality_right' :=
λ X Z Z' f g, tensor_right_hom_equiv_naturality f g, }
/--
If `Y` has a left dual `ᘁY`, then it is a closed object, with the internal hom functor `Y ⟶[C] -`
given by left tensoring by `ᘁY`.
This has to be a definition rather than an instance to avoid diamonds, for example between
`category_theory.monoidal_closed.functor_closed` and
`category_theory.monoidal.functor_has_left_dual`. Moreover, in concrete applications there is often
a more useful definition of the internal hom object than `ᘁY ⊗ X`, in which case the closed
structure shouldn't come from `has_left_dual` (e.g. in the category `FinVect k`, it is more
convenient to define the internal hom as `Y →ₗ[k] X` rather than `ᘁY ⊗ X` even though these are
naturally isomorphic).
-/
@[priority 100]
def closed_of_has_left_dual (Y : C) [has_left_dual Y] : closed Y :=
{ is_adj := ⟨_, tensor_left_adjunction (ᘁY) Y⟩, }
/-- `tensor_left_hom_equiv` commutes with tensoring on the right -/
lemma tensor_left_hom_equiv_tensor {X X' Y Y' Z Z' : C} [exact_pairing Y Y']
(f : X ⟶ Y ⊗ Z) (g : X' ⟶ Z') :
(tensor_left_hom_equiv (X ⊗ X') Y Y' (Z ⊗ Z')).symm ((f ⊗ g) ≫ (α_ _ _ _).hom) =
(α_ _ _ _).inv ≫ ((tensor_left_hom_equiv X Y Y' Z).symm f ⊗ g) :=
begin
dsimp [tensor_left_hom_equiv],
simp only [id_tensor_comp],
simp only [associator_inv_conjugation],
slice_lhs 2 2 { rw ←id_tensor_comp_tensor_id, },
conv_rhs { rw [←id_tensor_comp_tensor_id, comp_tensor_id, comp_tensor_id], },
simp, coherence,
end
/-- `tensor_right_hom_equiv` commutes with tensoring on the left -/
lemma tensor_right_hom_equiv_tensor {X X' Y Y' Z Z' : C} [exact_pairing Y Y']
(f : X ⟶ Z ⊗ Y') (g : X' ⟶ Z') :
(tensor_right_hom_equiv (X' ⊗ X) Y Y' (Z' ⊗ Z)).symm ((g ⊗ f) ≫ (α_ _ _ _).inv) =
(α_ _ _ _).hom ≫ (g ⊗ (tensor_right_hom_equiv X Y Y' Z).symm f) :=
begin
dsimp [tensor_right_hom_equiv],
simp only [comp_tensor_id],
simp only [associator_conjugation],
slice_lhs 2 2 { rw ←tensor_id_comp_id_tensor, },
conv_rhs { rw [←tensor_id_comp_id_tensor, id_tensor_comp, id_tensor_comp], },
simp only [←tensor_id, associator_conjugation],
simp, coherence,
end
@[simp]
lemma tensor_left_hom_equiv_symm_coevaluation_comp_id_tensor
{Y Y' Z : C} [exact_pairing Y Y'] (f : Y' ⟶ Z) :
(tensor_left_hom_equiv _ _ _ _).symm (η_ _ _ ≫ (𝟙 Y ⊗ f)) = (ρ_ _).hom ≫ f :=
begin
dsimp [tensor_left_hom_equiv],
rw id_tensor_comp,
slice_lhs 2 3 { rw associator_inv_naturality, },
slice_lhs 3 4 { rw [tensor_id, id_tensor_comp_tensor_id, ←tensor_id_comp_id_tensor], },
slice_lhs 1 3 { rw coevaluation_evaluation, },
simp,
end
@[simp]
lemma tensor_left_hom_equiv_symm_coevaluation_comp_tensor_id
{X Y : C} [has_right_dual X] [has_right_dual Y] (f : X ⟶ Y) :
(tensor_left_hom_equiv _ _ _ _).symm (η_ _ _ ≫ (f ⊗ 𝟙 Xᘁ)) = (ρ_ _).hom ≫ fᘁ :=
begin
dsimp [tensor_left_hom_equiv, right_adjoint_mate],
simp,
end
@[simp]
lemma tensor_right_hom_equiv_symm_coevaluation_comp_id_tensor
{X Y : C} [has_left_dual X] [has_left_dual Y] (f : X ⟶ Y) :
(tensor_right_hom_equiv _ (ᘁY) _ _).symm (η_ (ᘁX) X ≫ (𝟙 (ᘁX) ⊗ f)) = (λ_ _).hom ≫ (ᘁf) :=
begin
dsimp [tensor_right_hom_equiv, left_adjoint_mate],
simp,
end
@[simp]
lemma tensor_right_hom_equiv_symm_coevaluation_comp_tensor_id
{Y Y' Z : C} [exact_pairing Y Y'] (f : Y ⟶ Z) :
(tensor_right_hom_equiv _ Y _ _).symm (η_ Y Y' ≫ (f ⊗ 𝟙 Y')) = (λ_ _).hom ≫ f :=
begin
dsimp [tensor_right_hom_equiv],
rw comp_tensor_id,
slice_lhs 2 3 { rw associator_naturality, },
slice_lhs 3 4 { rw [tensor_id, tensor_id_comp_id_tensor, ←id_tensor_comp_tensor_id], },
slice_lhs 1 3 { rw evaluation_coevaluation, },
simp,
end
@[simp]
lemma tensor_left_hom_equiv_id_tensor_comp_evaluation
{Y Z : C} [has_left_dual Z] (f : Y ⟶ (ᘁZ)) :
(tensor_left_hom_equiv _ _ _ _) ((𝟙 Z ⊗ f) ≫ ε_ _ _) = f ≫ (ρ_ _).inv :=
begin
dsimp [tensor_left_hom_equiv],
rw id_tensor_comp,
slice_lhs 3 4 { rw ←associator_naturality, },
slice_lhs 2 3 { rw [tensor_id, tensor_id_comp_id_tensor, ←id_tensor_comp_tensor_id], },
slice_lhs 3 5 { rw evaluation_coevaluation, },
simp,
end
@[simp]
lemma tensor_left_hom_equiv_tensor_id_comp_evaluation
{X Y : C} [has_left_dual X] [has_left_dual Y] (f : X ⟶ Y) :
(tensor_left_hom_equiv _ _ _ _) ((f ⊗ 𝟙 _) ≫ ε_ _ _) = (ᘁf) ≫ (ρ_ _).inv :=
begin
dsimp [tensor_left_hom_equiv, left_adjoint_mate],
simp,
end
@[simp]
lemma tensor_right_hom_equiv_id_tensor_comp_evaluation
{X Y : C} [has_right_dual X] [has_right_dual Y] (f : X ⟶ Y) :
(tensor_right_hom_equiv _ _ _ _) ((𝟙 Yᘁ ⊗ f) ≫ ε_ _ _) = fᘁ ≫ (λ_ _).inv :=
begin
dsimp [tensor_right_hom_equiv, right_adjoint_mate],
simp,
end
@[simp]
lemma tensor_right_hom_equiv_tensor_id_comp_evaluation
{X Y : C} [has_right_dual X] (f : Y ⟶ Xᘁ) :
(tensor_right_hom_equiv _ _ _ _) ((f ⊗ 𝟙 X) ≫ ε_ X Xᘁ) = f ≫ (λ_ _).inv :=
begin
dsimp [tensor_right_hom_equiv],
rw comp_tensor_id,
slice_lhs 3 4 { rw ←associator_inv_naturality, },
slice_lhs 2 3 { rw [tensor_id, id_tensor_comp_tensor_id, ←tensor_id_comp_id_tensor], },
slice_lhs 3 5 { rw coevaluation_evaluation, },
simp,
end
-- Next four lemmas passing `fᘁ` or `ᘁf` through (co)evaluations.
lemma coevaluation_comp_right_adjoint_mate
{X Y : C} [has_right_dual X] [has_right_dual Y] (f : X ⟶ Y) :
η_ Y Yᘁ ≫ (𝟙 _ ⊗ fᘁ) = η_ _ _ ≫ (f ⊗ 𝟙 _) :=
begin
apply_fun (tensor_left_hom_equiv _ Y Yᘁ _).symm,
simp,
end
lemma left_adjoint_mate_comp_evaluation
{X Y : C} [has_left_dual X] [has_left_dual Y] (f : X ⟶ Y) :
(𝟙 X ⊗ (ᘁf)) ≫ ε_ _ _ = (f ⊗ 𝟙 _) ≫ ε_ _ _ :=
begin
apply_fun (tensor_left_hom_equiv _ (ᘁX) X _),
simp,
end
lemma coevaluation_comp_left_adjoint_mate
{X Y : C} [has_left_dual X] [has_left_dual Y] (f : X ⟶ Y) :
η_ (ᘁY) Y ≫ ((ᘁf) ⊗ 𝟙 Y) = η_ (ᘁX) X ≫ (𝟙 (ᘁX) ⊗ f) :=
begin
apply_fun (tensor_right_hom_equiv _ (ᘁY) Y _).symm,
simp,
end
lemma right_adjoint_mate_comp_evaluation
{X Y : C} [has_right_dual X] [has_right_dual Y] (f : X ⟶ Y) :
(fᘁ ⊗ 𝟙 X) ≫ ε_ X Xᘁ = (𝟙 Yᘁ ⊗ f) ≫ ε_ Y Yᘁ :=
begin
apply_fun (tensor_right_hom_equiv _ X (Xᘁ) _),
simp,
end
/-- Transport an exact pairing across an isomorphism in the first argument. -/
def exact_pairing_congr_left {X X' Y : C} [exact_pairing X' Y] (i : X ≅ X') : exact_pairing X Y :=
{ evaluation := (𝟙 Y ⊗ i.hom) ≫ ε_ _ _,
coevaluation := η_ _ _ ≫ (i.inv ⊗ 𝟙 Y),
evaluation_coevaluation' := begin
rw [id_tensor_comp, comp_tensor_id],
slice_lhs 2 3 { rw [associator_naturality], },
slice_lhs 3 4 { rw [tensor_id, tensor_id_comp_id_tensor, ←id_tensor_comp_tensor_id], },
slice_lhs 4 5 { rw [tensor_id_comp_id_tensor, ←id_tensor_comp_tensor_id], },
slice_lhs 2 3 { rw [←associator_naturality], },
slice_lhs 1 2 { rw [tensor_id, tensor_id_comp_id_tensor, ←id_tensor_comp_tensor_id], },
slice_lhs 2 4 { rw [evaluation_coevaluation], },
slice_lhs 1 2 { rw [left_unitor_naturality], },
slice_lhs 3 4 { rw [←right_unitor_inv_naturality], },
simp,
end,
coevaluation_evaluation' := begin
rw [id_tensor_comp, comp_tensor_id],
simp only [iso.inv_hom_id_assoc, associator_conjugation, category.assoc],
slice_lhs 2 3 { rw [←tensor_comp], simp, },
simp,
end, }
/-- Transport an exact pairing across an isomorphism in the second argument. -/
def exact_pairing_congr_right {X Y Y' : C} [exact_pairing X Y'] (i : Y ≅ Y') : exact_pairing X Y :=
{ evaluation := (i.hom ⊗ 𝟙 X) ≫ ε_ _ _,
coevaluation := η_ _ _ ≫ (𝟙 X ⊗ i.inv),
evaluation_coevaluation' := begin
rw [id_tensor_comp, comp_tensor_id],
simp only [iso.inv_hom_id_assoc, associator_conjugation, category.assoc],
slice_lhs 3 4 { rw [←tensor_comp], simp, },
simp,
end,
coevaluation_evaluation' := begin
rw [id_tensor_comp, comp_tensor_id],
slice_lhs 3 4 { rw [←associator_inv_naturality], },
slice_lhs 2 3 { rw [tensor_id, id_tensor_comp_tensor_id, ←tensor_id_comp_id_tensor], },
slice_lhs 1 2 { rw [id_tensor_comp_tensor_id, ←tensor_id_comp_id_tensor], },
slice_lhs 3 4 { rw [associator_inv_naturality], },
slice_lhs 4 5 { rw [tensor_id, id_tensor_comp_tensor_id, ←tensor_id_comp_id_tensor], },
slice_lhs 2 4 { rw [coevaluation_evaluation], },
slice_lhs 1 2 { rw [right_unitor_naturality], },
slice_lhs 3 4 { rw [←left_unitor_inv_naturality], },
simp,
end, }
/-- Transport an exact pairing across isomorphisms. -/
def exact_pairing_congr {X X' Y Y' : C} [exact_pairing X' Y'] (i : X ≅ X') (j : Y ≅ Y') :
exact_pairing X Y :=
begin
haveI : exact_pairing X' Y := exact_pairing_congr_right j,
exact exact_pairing_congr_left i,
end
/-- Right duals are isomorphic. -/
def right_dual_iso {X Y₁ Y₂ : C} (_ : exact_pairing X Y₁) (_ : exact_pairing X Y₂) :
Y₁ ≅ Y₂ :=
{ hom := @right_adjoint_mate C _ _ X X ⟨Y₂⟩ ⟨Y₁⟩ (𝟙 X),
inv := @right_adjoint_mate C _ _ X X ⟨Y₁⟩ ⟨Y₂⟩ (𝟙 X),
hom_inv_id' := by rw [←comp_right_adjoint_mate, category.comp_id, right_adjoint_mate_id],
inv_hom_id' := by rw [←comp_right_adjoint_mate, category.comp_id, right_adjoint_mate_id] }
/-- Left duals are isomorphic. -/
def left_dual_iso {X₁ X₂ Y : C} (p₁ : exact_pairing X₁ Y) (p₂ : exact_pairing X₂ Y) :
X₁ ≅ X₂ :=
{ hom := @left_adjoint_mate C _ _ Y Y ⟨X₂⟩ ⟨X₁⟩ (𝟙 Y),
inv := @left_adjoint_mate C _ _ Y Y ⟨X₁⟩ ⟨X₂⟩ (𝟙 Y),
hom_inv_id' := by rw [←comp_left_adjoint_mate, category.comp_id, left_adjoint_mate_id],
inv_hom_id' := by rw [←comp_left_adjoint_mate, category.comp_id, left_adjoint_mate_id] }
@[simp]
lemma right_dual_iso_id {X Y : C} (p : exact_pairing X Y) :
right_dual_iso p p = iso.refl Y :=
by { ext, simp only [right_dual_iso, iso.refl_hom, right_adjoint_mate_id] }
@[simp]
lemma left_dual_iso_id {X Y : C} (p : exact_pairing X Y) :
left_dual_iso p p = iso.refl X :=
by { ext, simp only [left_dual_iso, iso.refl_hom, left_adjoint_mate_id] }
/-- A right rigid monoidal category is one in which every object has a right dual. -/
class right_rigid_category (C : Type u) [category.{v} C] [monoidal_category.{v} C] :=
[right_dual : Π (X : C), has_right_dual X]
/-- A left rigid monoidal category is one in which every object has a right dual. -/
class left_rigid_category (C : Type u) [category.{v} C] [monoidal_category.{v} C] :=
[left_dual : Π (X : C), has_left_dual X]
attribute [instance, priority 100] right_rigid_category.right_dual
attribute [instance, priority 100] left_rigid_category.left_dual
/-- Any left rigid category is monoidal closed, with the internal hom `X ⟶[C] Y = ᘁX ⊗ Y`.
This has to be a definition rather than an instance to avoid diamonds, for example between
`category_theory.monoidal_closed.functor_category` and
`category_theory.monoidal.left_rigid_functor_category`. Moreover, in concrete applications there is
often a more useful definition of the internal hom object than `ᘁY ⊗ X`, in which case the monoidal
closed structure shouldn't come the rigid structure (e.g. in the category `FinVect k`, it is more
convenient to define the internal hom as `Y →ₗ[k] X` rather than `ᘁY ⊗ X` even though these are
naturally isomorphic). -/
@[priority 100]
def monoidal_closed_of_left_rigid_category
(C : Type u) [category.{v} C] [monoidal_category.{v} C] [left_rigid_category C] :
monoidal_closed C :=
{ closed' := λ X, closed_of_has_left_dual X, }
/-- A rigid monoidal category is a monoidal category which is left rigid and right rigid. -/
class rigid_category (C : Type u) [category.{v} C] [monoidal_category.{v} C]
extends right_rigid_category C, left_rigid_category C
end category_theory
|
f9da18e11a85b56aeff8e694b92fc81448bcff42 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/notation2.lean | b9a1d2593c468d023a561bec467ff7e60b4df841 | [
"Apache-2.0"
] | permissive | leanprover-community/lean | 12b87f69d92e614daea8bcc9d4de9a9ace089d0e | cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0 | refs/heads/master | 1,687,508,156,644 | 1,684,951,104,000 | 1,684,951,104,000 | 169,960,991 | 457 | 107 | Apache-2.0 | 1,686,744,372,000 | 1,549,790,268,000 | C++ | UTF-8 | Lean | false | false | 323 | lean | --
inductive List (T : Type) : Type
| nil {} : List
| cons : T → List → List
open List
notation (name := cons2) h :: t := cons h t
notation (name := list2) `[` l:(foldr `,` (h t, cons h t) nil) `]` := l
infixr (name := cons) `::` := cons
#check (1:nat) :: 2 :: nil
#check (1:nat) :: 2 :: 3 :: 4 :: 5 :: nil
#print ]
|
641156a215981b2d36764a94d9dd63de375041a0 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/tactic11.lean | 9aa53a80b26b9d41c123148a367bd50485577e66 | [
"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 | 517 | lean | import logic
theorem tst (a b : Prop) (H : a ↔ b) : b ↔ a
:= have H1 : a → b, -- We need to mark H1 as fact, otherwise it is not visible by tactics
from iff.elim_left H,
by apply iff.intro;
intro Hb;
apply (iff.elim_right H Hb);
intro Ha;
apply (H1 Ha)
theorem tst2 (a b : Prop) (H : a ↔ b) : b ↔ a
:= have H1 : a → b,
from iff.elim_left H,
begin
apply iff.intro,
intro Hb;
apply (iff.elim_right H Hb),
intro Ha;
apply (H1 Ha)
end
|
2167a483c62eefa18e432b9d322d65e09782ca72 | 432d948a4d3d242fdfb44b81c9e1b1baacd58617 | /src/linear_algebra/free_module.lean | bd78f69c81d1204570007ddcbad89a0742b8f5ed | [
"Apache-2.0"
] | permissive | JLimperg/aesop3 | 306cc6570c556568897ed2e508c8869667252e8a | a4a116f650cc7403428e72bd2e2c4cda300fe03f | refs/heads/master | 1,682,884,916,368 | 1,620,320,033,000 | 1,620,320,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 17,039 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
-/
import linear_algebra.basis
import linear_algebra.finsupp_vector_space
import ring_theory.principal_ideal_domain
import ring_theory.finiteness
/-! # Free modules
A free `R`-module `M` is a module with a basis over `R`,
equivalently it is an `R`-module linearly equivalent to `ι →₀ R` for some `ι`.
This file proves a submodule of a free `R`-module of finite rank is also
a free `R`-module of finite rank, if `R` is a principal ideal domain.
We express "free `R`-module of finite rank" as a module `M` which has a basis
`b : ι → R`, where `ι` is a `fintype`.
We call the cardinality of `ι` the rank of `M` in this file;
it would be equal to `finrank R M` if `R` is a field and `M` is a vector space.
## Main results
- `submodule.induction_on_rank`: if `M` is free and finitely generated,
if `P` holds for `⊥ : submodule R M` and if `P N` follows from `P N'`
for all `N'` that are of lower rank, then `P` holds on all submodules
- `submodule.exists_is_basis`: if `M` is free and finitely generated
and `R` is a PID, then `N : submodule R M` is free and finitely generated.
This is the first part of the structure theorem for modules.
## Tags
free module, finitely generated module, rank, structure theorem
-/
open_locale big_operators
section comm_ring
universes u v
variables {R : Type u} {M : Type v} [comm_ring R] [add_comm_group M] [module R M]
variables {ι : Type*} {b : ι → M} (hb : is_basis R b)
open submodule.is_principal
lemma eq_bot_of_rank_eq_zero [no_zero_divisors R] (hb : is_basis R b) (N : submodule R M)
(rank_eq : ∀ {m : ℕ} (v : fin m → N),
linear_independent R (coe ∘ v : fin m → M) → m = 0) :
N = ⊥ :=
begin
rw submodule.eq_bot_iff,
intros x hx,
contrapose! rank_eq with x_ne,
refine ⟨1, λ _, ⟨x, hx⟩, _, one_ne_zero⟩,
rw fintype.linear_independent_iff,
rintros g sum_eq i,
fin_cases i,
simp only [function.const_apply, fin.default_eq_zero, submodule.coe_mk, univ_unique,
function.comp_const, finset.sum_singleton] at sum_eq,
exact (hb.smul_eq_zero.mp sum_eq).resolve_right x_ne
end
open submodule
lemma eq_bot_of_generator_maximal_map_eq_zero (hb : is_basis R b) {N : submodule R M}
{ϕ : M →ₗ[R] R} (hϕ : ∀ (ψ : M →ₗ[R] R), N.map ϕ ≤ N.map ψ → N.map ψ = N.map ϕ)
[(N.map ϕ).is_principal] (hgen : generator (N.map ϕ) = 0) : N = ⊥ :=
begin
rw submodule.eq_bot_iff,
intros x hx,
refine hb.ext_elem (λ i, _),
rw (eq_bot_iff_generator_eq_zero _).mpr hgen at hϕ,
rw [linear_map.map_zero, finsupp.zero_apply],
exact (submodule.eq_bot_iff _).mp (hϕ ((finsupp.lapply i).comp hb.repr) bot_le) _ ⟨x, hx, rfl⟩
end
-- Note that the converse may not hold if `ϕ` is not injective.
lemma generator_map_dvd_of_mem {N : submodule R M}
(ϕ : M →ₗ[R] R) [(N.map ϕ).is_principal] {x : M} (hx : x ∈ N) :
generator (N.map ϕ) ∣ ϕ x :=
by { rw [← mem_iff_generator_dvd, submodule.mem_map], exact ⟨x, hx, rfl⟩ }
end comm_ring
section integral_domain
variables {ι : Type*} {R : Type*} [integral_domain R]
variables {M : Type*} [add_comm_group M] [module R M] {b : ι → M}
lemma not_mem_of_ortho {x : M} {N : submodule R M}
(ortho : ∀ (c : R) (y ∈ N), c • x + y = (0 : M) → c = 0) :
x ∉ N :=
by { intro hx, simpa using ortho (-1) x hx }
lemma ne_zero_of_ortho {x : M} {N : submodule R M}
(ortho : ∀ (c : R) (y ∈ N), c • x + y = (0 : M) → c = 0) :
x ≠ 0 :=
mt (λ h, show x ∈ N, from h.symm ▸ N.zero_mem) (not_mem_of_ortho ortho)
/-- If `N` is a submodule with finite rank, do induction on adjoining a linear independent
element to a submodule. -/
def submodule.induction_on_rank_aux (hb : is_basis R b) (P : submodule R M → Sort*)
(ih : ∀ (N : submodule R M),
(∀ (N' ≤ N) (x ∈ N), (∀ (c : R) (y ∈ N'), c • x + y = (0 : M) → c = 0) → P N') → P N)
(n : ℕ) (N : submodule R M)
(rank_le : ∀ {m : ℕ} (v : fin m → N),
linear_independent R (coe ∘ v : fin m → M) → m ≤ n) :
P N :=
begin
haveI : decidable_eq M := classical.dec_eq M,
have Pbot : P ⊥,
{ apply ih,
intros N N_le x x_mem x_ortho,
exfalso,
simpa using x_ortho 1 0 N.zero_mem },
induction n with n rank_ih generalizing N,
{ suffices : N = ⊥,
{ rwa this },
apply eq_bot_of_rank_eq_zero hb _ (λ m v hv, nat.le_zero_iff.mp (rank_le v hv)) },
apply ih,
intros N' N'_le x x_mem x_ortho,
apply rank_ih,
intros m v hli,
refine nat.succ_le_succ_iff.mp (rank_le (fin.cons ⟨x, x_mem⟩ (λ i, ⟨v i, N'_le (v i).2⟩)) _),
convert hli.fin_cons' x _ _,
{ ext i, refine fin.cases _ _ i; simp },
{ intros c y hcy,
refine x_ortho c y (submodule.span_le.mpr _ y.2) hcy,
rintros _ ⟨z, rfl⟩,
exact (v z).2 }
end
/-- In an `n`-dimensional space, the rank is at most `m`. -/
lemma is_basis.card_le_card_of_linear_independent_aux
{R : Type*} [integral_domain R]
(n : ℕ) {m : ℕ} (v : fin m → fin n → R) :
linear_independent R v → m ≤ n :=
begin
revert m,
refine nat.rec_on n _ _,
{ intros m v hv,
cases m, { refl },
exfalso,
have : v 0 = 0,
{ ext i, exact fin_zero_elim i },
have := hv.ne_zero 0,
contradiction },
intros n ih m v hv,
cases m,
{ exact nat.zero_le _ },
-- Induction: try deleting a dimension and a vector.
suffices : ∃ (v' : fin m → fin n → R), linear_independent R v',
{ obtain ⟨v', hv'⟩ := this,
exact nat.succ_le_succ (ih v' hv') },
-- Either the `0`th dimension is irrelevant...
by_cases this : linear_independent R (λ i, v i ∘ fin.succ),
{ exact ⟨_, this.comp fin.succ (fin.succ_injective _)⟩ },
-- ... or we can write (x, 0, 0, ...) = ∑ i, c i • v i where c i ≠ 0 for some i.
simp only [fintype.linear_independent_iff, not_forall, not_imp] at this,
obtain ⟨c, hc, i, hi⟩ := this,
have hc : ∀ (j : fin n), ∑ (i : fin m.succ), c i * v i j.succ = 0,
{ intro j,
convert congr_fun hc j,
rw [@finset.sum_apply (fin n) (λ _, R) _ _ _],
simp },
set x := ∑ i', c i' * v i' 0 with x_eq,
-- We'll show each equation of the form (y, 0, 0, ...) = ∑ i', c' i' • v i' must have c' i ≠ 0.
use λ i' j', v (i.succ_above i') j'.succ,
rw fintype.linear_independent_iff at ⊢ hv,
-- Assume that ∑ i, c' i • v i = (y, 0, 0, ...).
intros c' hc' i',
set y := ∑ i', c' i' * v (i.succ_above i') 0 with y_eq,
have hc' : ∀ (j : fin n), (∑ (i' : fin m), c' i' * v (i.succ_above i') j.succ) = 0,
{ intro j,
convert congr_fun hc' j,
rw [@finset.sum_apply (fin n) (λ _, R) _ _ _],
simp },
-- Combine these equations to get a linear dependence on the full space.
have : ∑ i', (y * c i' - x * (@fin.insert_nth _ (λ _, R) i 0 c') i') • v i' = 0,
{ simp only [sub_smul, mul_smul, finset.sum_sub_distrib, ← finset.smul_sum],
ext j,
rw [pi.zero_apply, @pi.sub_apply (fin n.succ) (λ _, R) _ _ _ _],
simp only [finset.sum_apply, pi.smul_apply, smul_eq_mul, sub_eq_zero],
symmetry,
rw [fin.sum_univ_succ_above _ i, fin.insert_nth_apply_same, zero_mul, zero_add, mul_comm],
simp only [fin.insert_nth_apply_succ_above],
refine fin.cases _ _ j,
{ simp },
{ intro j,
rw [hc', hc, zero_mul, mul_zero] } },
have hyc := hv _ this i,
simp only [fin.insert_nth_apply_same, mul_zero, sub_zero, mul_eq_zero] at hyc,
-- Therefore, either `c i = 0` (which contradicts the assumption on `i`) or `y = 0`.
have hy := hyc.resolve_right hi,
-- If `y = 0`, then we can extend `c'` to a linear dependence on the full space,
-- which implies `c'` is trivial.
convert hv (@fin.insert_nth _ (λ _, R) i 0 c') _ (i.succ_above i'),
{ rw fin.insert_nth_apply_succ_above },
ext j,
-- After a bit of calculation, we find that `∑ i, c' i • v i = (y, 0, 0, ...) = 0` as promised.
rw [@finset.sum_apply (fin n.succ) (λ _, R) _ _ _, pi.zero_apply],
simp only [pi.smul_apply, smul_eq_mul],
rw [fin.sum_univ_succ_above _ i, fin.insert_nth_apply_same, zero_mul, zero_add],
simp only [fin.insert_nth_apply_succ_above],
refine fin.cases _ _ j,
{ rw [← y_eq, hy] },
{ exact hc' },
end
lemma is_basis.card_le_card_of_linear_independent
{R : Type*} [integral_domain R] [module R M]
{ι : Type*} [fintype ι] {b : ι → M} (hb : is_basis R b)
{ι' : Type*} [fintype ι'] {v : ι' → M} (hv : linear_independent R v) :
fintype.card ι' ≤ fintype.card ι :=
begin
haveI := classical.dec_eq ι,
haveI := classical.dec_eq ι',
let e := fintype.equiv_fin ι,
let e' := fintype.equiv_fin ι',
have hb := hb.comp _ e.symm.bijective,
have hv := (linear_independent_equiv e'.symm).mpr hv,
have hv := hv.map' _ hb.equiv_fun.ker,
exact is_basis.card_le_card_of_linear_independent_aux (fintype.card ι) _ hv,
end
/-- If `N` is a submodule in a free, finitely generated module,
do induction on adjoining a linear independent element to a submodule. -/
def submodule.induction_on_rank [fintype ι] (hb : is_basis R b) (P : submodule R M → Sort*)
(ih : ∀ (N : submodule R M),
(∀ (N' ≤ N) (x ∈ N), (∀ (c : R) (y ∈ N'), c • x + y = (0 : M) → c = 0) → P N') →
P N)
(N : submodule R M) : P N :=
submodule.induction_on_rank_aux hb P ih (fintype.card ι) N (λ s hs hli,
by simpa using hb.card_le_card_of_linear_independent hli)
open submodule.is_principal
end integral_domain
section principal_ideal_domain
open submodule.is_principal set submodule
variables {ι : Type*} {R : Type*} [integral_domain R] [is_principal_ideal_ring R]
variables {M : Type*} [add_comm_group M] [module R M] {b : ι → M}
open_locale matrix
/-- A submodule of a free `R`-module of finite rank is also a free `R`-module of finite rank,
if `R` is a principal ideal domain. -/
theorem submodule.exists_is_basis {ι : Type*} [fintype ι]
{b : ι → M} (hb : is_basis R b) (N : submodule R M) :
∃ (n : ℕ) (bN : fin n → N), is_basis R bN :=
begin
haveI := classical.dec_eq M,
refine N.induction_on_rank hb _ _,
intros N ih,
-- Let `ϕ` be a maximal projection of `M` onto `R`, in the sense that there is
-- no `ψ` whose image of `N` is larger than `ϕ`'s image of `N`.
obtain ⟨ϕ, ϕ_max⟩ : ∃ ϕ : M →ₗ[R] R, ∀ (ψ : M →ₗ[R] R), N.map ϕ ≤ N.map ψ → N.map ψ = N.map ϕ,
{ obtain ⟨P, P_eq, P_max⟩ := set_has_maximal_iff_noetherian.mpr
(infer_instance : is_noetherian R R) _ (submodule.range_map_nonempty N),
obtain ⟨ϕ, rfl⟩ := set.mem_range.mp P_eq,
use ϕ,
intros ψ hψ,
exact P_max (N.map ψ) ⟨_, rfl⟩ hψ },
-- Since `N.map ϕ` is a `R`-submodule of the PID `R`, it is principal and generated by some `a`.
have a_mem : generator (N.map ϕ) ∈ N.map ϕ := generator_mem _,
-- If `a` is zero, then the submodule is trivial. So let's assume `a ≠ 0`, `N ≠ ⊥`
by_cases N_bot : N = ⊥,
{ rw N_bot,
refine ⟨0, λ _, 0, is_basis_empty _ _⟩,
rintro ⟨i, ⟨⟩⟩ },
by_cases a_zero : generator (N.map ϕ) = 0,
{ have := eq_bot_of_generator_maximal_map_eq_zero hb ϕ_max a_zero,
contradiction },
-- We claim that `ϕ⁻¹ a = y` can be taken as basis element of `N`.
obtain ⟨y, y_mem, ϕy_eq⟩ := a_mem,
have ϕy_ne_zero := λ h, a_zero (ϕy_eq.symm.trans h),
-- If `N'` is `ker (ϕ : N → R)`, it is smaller than `N` so by the induction hypothesis,
-- it has a basis `bN'`.
have N'_le_ker : (ϕ.ker ⊓ N) ≤ ϕ.ker := inf_le_left,
have N'_le_N : (ϕ.ker ⊓ N) ≤ N := inf_le_right,
-- Note that `y` is orthogonal to `N'`.
have y_ortho_N' : ∀ (c : R) (z : M), z ∈ ϕ.ker ⊓ N → c • y + z = 0 → c = 0,
{ intros c x hx hc,
have hx' : x ∈ ϕ.ker := (inf_le_left : _ ⊓ N ≤ _) hx,
rw linear_map.mem_ker at hx',
simpa [ϕy_ne_zero, hx'] using congr_arg ϕ hc },
obtain ⟨nN', bN', hbN'⟩ := ih (ϕ.ker ⊓ N) N'_le_N y y_mem y_ortho_N',
use nN'.succ,
-- Extend `bN'` with `y`, we'll show it's linear independent and spans `N`.
use fin.cons ⟨y, y_mem⟩ (submodule.of_le N'_le_N ∘ bN'),
split,
{ apply (hbN'.1.map' (submodule.of_le N'_le_N) (submodule.ker_of_le _ _ _)).fin_cons' _ _ _,
intros c z hc,
apply y_ortho_N' c z (submodule.mem_inf.mpr ⟨_, z.1.2⟩) (congr_arg coe hc),
have : submodule.span R (set.range (submodule.of_le N'_le_N ∘ bN')) ≤ (ϕ.dom_restrict N).ker,
{ rw submodule.span_le,
rintros _ ⟨i, rfl⟩,
exact N'_le_ker (bN' i).2 },
exact this z.2 },
{ rw eq_top_iff,
rintro x -,
rw [fin.range_cons, set.range_comp, submodule.mem_span_insert, submodule.span_image],
obtain ⟨b, hb⟩ : _ ∣ ϕ x := generator_map_dvd_of_mem ϕ x.2,
refine ⟨b, x - b • ⟨_, y_mem⟩, _, _⟩,
{ rw submodule.mem_map,
refine ⟨⟨x - b • _, _⟩, hbN'.mem_span _, rfl⟩,
refine submodule.mem_inf.mpr ⟨linear_map.mem_ker.mpr _, N.sub_mem x.2 (N.smul_mem _ y_mem)⟩,
simp [hb, ϕy_eq, mul_comm] },
{ ext, simp only [ϕy_eq, add_sub_cancel'_right] } },
end
lemma submodule.exists_is_basis_of_le {ι : Type*} [fintype ι]
{N O : submodule R M} (hNO : N ≤ O) {b : ι → O} (hb : is_basis R b) :
∃ (n : ℕ) (b : fin n → N), is_basis R b :=
let ⟨n, bN', hbN'⟩ := submodule.exists_is_basis hb (N.comap O.subtype)
in ⟨n, _, (submodule.comap_subtype_equiv_of_le hNO).is_basis hbN'⟩
lemma submodule.exists_is_basis_of_le_span
{ι : Type*} [fintype ι] {b : ι → M} (hb : linear_independent R b)
{N : submodule R M} (le : N ≤ submodule.span R (set.range b)) :
∃ (n : ℕ) (b : fin n → N), is_basis R b :=
submodule.exists_is_basis_of_le le (is_basis_span hb)
variable {M}
/-- A finite type torsion free module over a PID is free. -/
lemma module.free_of_finite_type_torsion_free [fintype ι] {s : ι → M} (hs : span R (range s) = ⊤)
[no_zero_smul_divisors R M] :
∃ (n : ℕ) (B : fin n → M), is_basis R B :=
begin
classical,
-- We define `N` as the submodule spanned by a maximal linear independent subfamily of `s`
obtain ⟨I : set ι,
indepI : linear_independent R (s ∘ coe : I → M),
hI : ∀ i ∉ I, ∃ a : R, a ≠ 0 ∧ a • s i ∈ span R (s '' I)⟩ :=
exists_maximal_independent R s,
let N := span R (range $ (s ∘ coe : I → M)), -- same as `span R (s '' I)` but more convenient
let sI : I → N := λ i, ⟨s i.1, subset_span (mem_range_self i)⟩, -- `s` restricted to `I`
have sI_basis : is_basis R sI, -- `s` restricted to `I` is a basis of `N`
from is_basis_span indepI,
-- Our first goal is to build `A ≠ 0` such that `A • M ⊆ N`
have exists_a : ∀ i : ι, ∃ a : R, a ≠ 0 ∧ a • s i ∈ N,
{ intro i,
by_cases hi : i ∈ I,
{ use [1, zero_ne_one.symm],
rw one_smul,
exact subset_span (mem_range_self (⟨i, hi⟩ : I)) },
{ simpa [image_eq_range s I] using hI i hi } },
choose a ha ha' using exists_a,
let A := ∏ i, a i,
have hA : A ≠ 0,
{ rw finset.prod_ne_zero_iff,
simpa using ha },
-- `M ≃ A • M` because `M` is torsion free and `A ≠ 0`
let φ : M →ₗ[R] M := linear_map.lsmul R M A,
have : φ.ker = ⊥,
from linear_map.ker_lsmul hA,
let ψ : M ≃ₗ[R] φ.range := linear_equiv.of_injective φ this,
have : φ.range ≤ N, -- as announced, `A • M ⊆ N`
{ suffices : ∀ i, φ (s i) ∈ N,
{ rw [linear_map.range_eq_map, ← hs, φ.map_span_le],
rintros _ ⟨i, rfl⟩, apply this },
intro i,
calc (∏ j, a j) • s i = (∏ j in {i}ᶜ, a j) • a i • s i :
by rw [fintype.prod_eq_prod_compl_mul i, mul_smul]
... ∈ N : N.smul_mem _ (ha' i) },
-- Since a submodule of a free `R`-module is free, we get that `A • M` is free
obtain ⟨n, B : fin n → φ.range, hB : is_basis R B⟩ :=
submodule.exists_is_basis_of_le this sI_basis,
-- hence `M` is free.
exact ⟨n, ψ.symm ∘ B, linear_equiv.is_basis hB ψ.symm⟩
end
/-- A finite type torsion free module over a PID is free. -/
lemma module.free_of_finite_type_torsion_free' [module.finite R M] [no_zero_smul_divisors R M] :
∃ (n : ℕ) (B : fin n → M), is_basis R B :=
let ⟨n, s, hs⟩ := module.finite.exists_fin in module.free_of_finite_type_torsion_free hs
end principal_ideal_domain
/-- A set of linearly independent vectors in a module `M` over a semiring `S` is also linearly
independent over a subring `R` of `K`. -/
lemma linear_independent.restrict_scalars_algebras {R S M ι : Type*} [comm_semiring R] [semiring S]
[add_comm_monoid M] [algebra R S] [module R M] [module S M] [is_scalar_tower R S M]
(hinj : function.injective (algebra_map R S)) {v : ι → M} (li : linear_independent S v) :
linear_independent R v :=
linear_independent.restrict_scalars (by rwa algebra.algebra_map_eq_smul_one' at hinj) li
|
09e305b60953a23e53bf54b19f4a59eedd495c3b | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/data/vector2.lean | 4e8906ae91225a41e12c61bfa337a21bc5ea8452 | [
"Apache-2.0"
] | permissive | gebner/mathlib | eab0150cc4f79ec45d2016a8c21750244a2e7ff0 | cc6a6edc397c55118df62831e23bfbd6e6c6b4ab | refs/heads/master | 1,625,574,853,976 | 1,586,712,827,000 | 1,586,712,827,000 | 99,101,412 | 1 | 0 | Apache-2.0 | 1,586,716,389,000 | 1,501,667,958,000 | Lean | UTF-8 | Lean | false | false | 10,289 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
Additional theorems about the `vector` type.
-/
import data.vector data.list.nodup data.list.of_fn
import category.traversable.basic data.set.basic tactic.tauto
universes u
variables {n : ℕ}
namespace vector
variables {α : Type*}
attribute [simp] head_cons tail_cons
instance [inhabited α] : inhabited (vector α n) :=
⟨of_fn (λ _, default α)⟩
theorem to_list_injective : function.injective (@to_list α n) :=
subtype.val_injective
@[simp] theorem to_list_of_fn : ∀ {n} (f : fin n → α), to_list (of_fn f) = list.of_fn f
| 0 f := rfl
| (n+1) f := by rw [of_fn, list.of_fn_succ, to_list_cons, to_list_of_fn]
@[simp] theorem mk_to_list :
∀ (v : vector α n) h, (⟨to_list v, h⟩ : vector α n) = v
| ⟨l, h₁⟩ h₂ := rfl
@[simp] lemma to_list_map {β : Type*} (v : vector α n) (f : α → β) : (v.map f).to_list =
v.to_list.map f := by cases v; refl
theorem nth_eq_nth_le : ∀ (v : vector α n) (i),
nth v i = v.to_list.nth_le i.1 (by rw to_list_length; exact i.2)
| ⟨l, h⟩ i := rfl
@[simp] lemma nth_map {β : Type*} (v : vector α n) (f : α → β) (i : fin n) :
(v.map f).nth i = f (v.nth i) :=
by simp [nth_eq_nth_le]
@[simp] theorem nth_of_fn {n} (f : fin n → α) (i) : nth (of_fn f) i = f i :=
by rw [nth_eq_nth_le, ← list.nth_le_of_fn f];
congr; apply to_list_of_fn
@[simp] theorem of_fn_nth (v : vector α n) : of_fn (nth v) = v :=
begin
rcases v with ⟨l, rfl⟩,
apply to_list_injective,
change nth ⟨l, eq.refl _⟩ with λ i, nth ⟨l, rfl⟩ i,
simp [nth, list.of_fn_nth_le]
end
@[simp] theorem nth_tail : ∀ (v : vector α n.succ) (i : fin n),
nth (tail v) i = nth v i.succ
| ⟨a::l, e⟩ ⟨i, h⟩ := by simp [nth_eq_nth_le]; refl
@[simp] theorem tail_of_fn {n : ℕ} (f : fin n.succ → α) :
tail (of_fn f) = of_fn (λ i, f i.succ) :=
(of_fn_nth _).symm.trans $ by congr; funext i; simp
lemma mem_iff_nth {a : α} {v : vector α n} : a ∈ v.to_list ↔ ∃ i, v.nth i = a :=
by simp only [list.mem_iff_nth_le, fin.exists_iff, vector.nth_eq_nth_le];
exact ⟨λ ⟨i, hi, h⟩, ⟨i, by rwa to_list_length at hi, h⟩,
λ ⟨i, hi, h⟩, ⟨i, by rwa to_list_length, h⟩⟩
lemma nodup_iff_nth_inj {v : vector α n} : v.to_list.nodup ↔ function.injective v.nth :=
begin
cases v with l hl,
subst hl,
simp only [list.nodup_iff_nth_le_inj],
split,
{ intros h i j hij,
cases i, cases j, simp [nth_eq_nth_le] at *, tauto },
{ intros h i j hi hj hij,
have := @h ⟨i, hi⟩ ⟨j, hj⟩, simp [nth_eq_nth_le] at *, tauto }
end
@[simp] lemma nth_mem (i : fin n) (v : vector α n) : v.nth i ∈ v.to_list :=
by rw [nth_eq_nth_le]; exact list.nth_le_mem _ _ _
theorem head'_to_list : ∀ (v : vector α n.succ),
(to_list v).head' = some (head v)
| ⟨a::l, e⟩ := rfl
def reverse (v : vector α n) : vector α n :=
⟨v.to_list.reverse, by simp⟩
@[simp] theorem nth_zero : ∀ (v : vector α n.succ), nth v 0 = head v
| ⟨a::l, e⟩ := rfl
@[simp] theorem head_of_fn
{n : ℕ} (f : fin n.succ → α) : head (of_fn f) = f 0 :=
by rw [← nth_zero, nth_of_fn]
@[simp] theorem nth_cons_zero
(a : α) (v : vector α n) : nth (a :: v) 0 = a :=
by simp [nth_zero]
@[simp] theorem nth_cons_succ
(a : α) (v : vector α n) (i : fin n) : nth (a :: v) i.succ = nth v i :=
by rw [← nth_tail, tail_cons]
def m_of_fn {m} [monad m] {α : Type u} : ∀ {n}, (fin n → m α) → m (vector α n)
| 0 f := pure nil
| (n+1) f := do a ← f 0, v ← m_of_fn (λi, f i.succ), pure (a :: v)
theorem m_of_fn_pure {m} [monad m] [is_lawful_monad m] {α} :
∀ {n} (f : fin n → α), @m_of_fn m _ _ _ (λ i, pure (f i)) = pure (of_fn f)
| 0 f := rfl
| (n+1) f := by simp [m_of_fn, @m_of_fn_pure n, of_fn]
def mmap {m} [monad m] {α} {β : Type u} (f : α → m β) :
∀ {n}, vector α n → m (vector β n)
| _ ⟨[], rfl⟩ := pure nil
| _ ⟨a::l, rfl⟩ := do h' ← f a, t' ← mmap ⟨l, rfl⟩, pure (h' :: t')
@[simp] theorem mmap_nil {m} [monad m] {α β} (f : α → m β) :
mmap f nil = pure nil := rfl
@[simp] theorem mmap_cons {m} [monad m] {α β} (f : α → m β) (a) :
∀ {n} (v : vector α n), mmap f (a::v) =
do h' ← f a, t' ← mmap f v, pure (h' :: t')
| _ ⟨l, rfl⟩ := rfl
@[ext] theorem ext : ∀ {v w : vector α n}
(h : ∀ m : fin n, vector.nth v m = vector.nth w m), v = w
| ⟨v, hv⟩ ⟨w, hw⟩ h := subtype.eq (list.ext_le (by rw [hv, hw])
(λ m hm hn, h ⟨m, hv ▸ hm⟩))
instance zero_subsingleton : subsingleton (vector α 0) :=
⟨λ _ _, vector.ext (λ m, fin.elim0 m)⟩
def to_array : vector α n → array n α
| ⟨xs, h⟩ := cast (by rw h) xs.to_array
section insert_nth
variable {a : α}
def insert_nth (a : α) (i : fin (n+1)) (v : vector α n) : vector α (n+1) :=
⟨v.1.insert_nth i.1 a,
begin
rw [list.length_insert_nth, v.2],
rw [v.2, ← nat.succ_le_succ_iff],
exact i.2
end⟩
lemma insert_nth_val {i : fin (n+1)} {v : vector α n} :
(v.insert_nth a i).val = v.val.insert_nth i.1 a :=
rfl
@[simp] lemma remove_nth_val {i : fin n} :
∀{v : vector α n}, (remove_nth i v).val = v.val.remove_nth i.1
| ⟨l, hl⟩ := rfl
lemma remove_nth_insert_nth {v : vector α n} {i : fin (n+1)} : remove_nth i (insert_nth a i v) = v :=
subtype.eq $ list.remove_nth_insert_nth i.1 v.1
lemma remove_nth_insert_nth_ne {v : vector α (n+1)} :
∀{i j : fin (n+2)} (h : i ≠ j),
remove_nth i (insert_nth a j v) = insert_nth a (i.pred_above j h.symm) (remove_nth (j.pred_above i h) v)
| ⟨i, hi⟩ ⟨j, hj⟩ ne :=
begin
have : i ≠ j := fin.vne_of_ne ne,
refine subtype.eq _,
dsimp [insert_nth, remove_nth, fin.pred_above, fin.cast_lt],
rcases lt_trichotomy i j with h | h | h,
{ have h_nji : ¬ j < i := lt_asymm h,
have j_pos : 0 < j := lt_of_le_of_lt (zero_le i) h,
simp [h, h_nji, fin.lt_iff_val_lt_val],
rw [show j.pred = j - 1, from rfl, list.insert_nth_remove_nth_of_ge, nat.sub_add_cancel j_pos],
{ rw [v.2], exact lt_of_lt_of_le h (nat.le_of_succ_le_succ hj) },
{ exact nat.le_sub_right_of_add_le h } },
{ exact (this h).elim },
{ have h_nij : ¬ i < j := lt_asymm h,
have i_pos : 0 < i := lt_of_le_of_lt (zero_le j) h,
simp [h, h_nij, fin.lt_iff_val_lt_val],
rw [show i.pred = i - 1, from rfl, list.insert_nth_remove_nth_of_le, nat.sub_add_cancel i_pos],
{ show i - 1 + 1 ≤ v.val.length,
rw [v.2, nat.sub_add_cancel i_pos],
exact nat.le_of_lt_succ hi },
{ exact nat.le_sub_right_of_add_le h } }
end
lemma insert_nth_comm (a b : α) (i j : fin (n+1)) (h : i ≤ j) :
∀(v : vector α n), (v.insert_nth a i).insert_nth b j.succ = (v.insert_nth b j).insert_nth a i.cast_succ
| ⟨l, hl⟩ :=
begin
refine subtype.eq _,
simp [insert_nth_val, fin.succ_val, fin.cast_succ],
apply list.insert_nth_comm,
{ assumption },
{ rw hl, exact nat.le_of_succ_le_succ j.2 }
end
end insert_nth
section update_nth
/-- `update_nth v n a` replaces the `n`th element of `v` with `a` -/
def update_nth (v : vector α n) (i : fin n) (a : α) : vector α n :=
⟨v.1.update_nth i.1 a, by rw [list.update_nth_length, v.2]⟩
@[simp] lemma nth_update_nth_same (v : vector α n) (i : fin n) (a : α) :
(v.update_nth i a).nth i = a :=
by cases v; cases i; simp [vector.update_nth, vector.nth_eq_nth_le]
lemma nth_update_nth_of_ne {v : vector α n} {i j : fin n} (h : i ≠ j) (a : α) :
(v.update_nth i a).nth j = v.nth j :=
by cases v; cases i; cases j; simp [vector.update_nth, vector.nth_eq_nth_le,
list.nth_le_update_nth_of_ne (fin.vne_of_ne h)]
lemma nth_update_nth_eq_if {v : vector α n} {i j : fin n} (a : α) :
(v.update_nth i a).nth j = if i = j then a else v.nth j :=
by split_ifs; try {simp *}; try {rw nth_update_nth_of_ne}; assumption
end update_nth
end vector
namespace vector
section traverse
variables {F G : Type u → Type u}
variables [applicative F] [applicative G]
open applicative functor
open list (cons) nat
private def traverse_aux {α β : Type u} (f : α → F β) :
Π (x : list α), F (vector β x.length)
| [] := pure vector.nil
| (x::xs) := vector.cons <$> f x <*> traverse_aux xs
protected def traverse {α β : Type u} (f : α → F β) : vector α n → F (vector β n)
| ⟨v, Hv⟩ := cast (by rw Hv) $ traverse_aux f v
variables [is_lawful_applicative F] [is_lawful_applicative G]
variables {α β γ : Type u}
@[simp] protected lemma traverse_def
(f : α → F β) (x : α) : ∀ (xs : vector α n),
(x :: xs).traverse f = cons <$> f x <*> xs.traverse f :=
by rintro ⟨xs, rfl⟩; refl
protected lemma id_traverse : ∀ (x : vector α n), x.traverse id.mk = x :=
begin
rintro ⟨x, rfl⟩, dsimp [vector.traverse, cast],
induction x with x xs IH, {refl},
simp! [IH], refl
end
open function
protected lemma comp_traverse (f : β → F γ) (g : α → G β) : ∀ (x : vector α n),
vector.traverse (comp.mk ∘ functor.map f ∘ g) x =
comp.mk (vector.traverse f <$> vector.traverse g x) :=
by rintro ⟨x, rfl⟩; dsimp [vector.traverse, cast];
induction x with x xs; simp! [cast, *] with functor_norm;
[refl, simp [(∘)]]
protected lemma traverse_eq_map_id {α β} (f : α → β) : ∀ (x : vector α n),
x.traverse (id.mk ∘ f) = id.mk (map f x) :=
by rintro ⟨x, rfl⟩; simp!;
induction x; simp! * with functor_norm; refl
variable (η : applicative_transformation F G)
protected lemma naturality {α β : Type*}
(f : α → F β) : ∀ (x : vector α n),
η (x.traverse f) = x.traverse (@η _ ∘ f) :=
by rintro ⟨x, rfl⟩; simp! [cast];
induction x with x xs IH; simp! * with functor_norm
end traverse
instance : traversable.{u} (flip vector n) :=
{ traverse := @vector.traverse n,
map := λ α β, @vector.map.{u u} α β n }
instance : is_lawful_traversable.{u} (flip vector n) :=
{ id_traverse := @vector.id_traverse n,
comp_traverse := @vector.comp_traverse n,
traverse_eq_map_id := @vector.traverse_eq_map_id n,
naturality := @vector.naturality n,
id_map := by intros; cases x; simp! [(<$>)],
comp_map := by intros; cases x; simp! [(<$>)] }
end vector
|
7a655bdcda5be22adfd4f76920e829641bb8aef5 | 4950bf76e5ae40ba9f8491647d0b6f228ddce173 | /src/data/set/basic.lean | 4267eb8310719ff4b4c9c13e39b12fa52ce10403 | [
"Apache-2.0"
] | permissive | ntzwq/mathlib | ca50b21079b0a7c6781c34b62199a396dd00cee2 | 36eec1a98f22df82eaccd354a758ef8576af2a7f | refs/heads/master | 1,675,193,391,478 | 1,607,822,996,000 | 1,607,822,996,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 93,597 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura
-/
import logic.unique
import order.boolean_algebra
/-!
# Basic properties of sets
Sets in Lean are homogeneous; all their elements have the same type. Sets whose elements
have type `X` are thus defined as `set X := X → Prop`. Note that this function need not
be decidable. The definition is in the core library.
This file provides some basic definitions related to sets and functions not present in the core
library, as well as extra lemmas for functions in the core library (empty set, univ, union,
intersection, insert, singleton, set-theoretic difference, complement, and powerset).
Note that a set is a term, not a type. There is a coersion from `set α` to `Type*` sending
`s` to the corresponding subtype `↥s`.
See also the file `set_theory/zfc.lean`, which contains an encoding of ZFC set theory in Lean.
## Main definitions
Notation used here:
- `f : α → β` is a function,
- `s : set α` and `s₁ s₂ : set α` are subsets of `α`
- `t : set β` is a subset of `β`.
Definitions in the file:
* `strict_subset s₁ s₂ : Prop` : the predicate `s₁ ⊆ s₂` but `s₁ ≠ s₂`.
* `nonempty s : Prop` : the predicate `s ≠ ∅`. Note that this is the preferred way to express the
fact that `s` has an element (see the Implementation Notes).
* `preimage f t : set α` : the preimage f⁻¹(t) (written `f ⁻¹' t` in Lean) of a subset of β.
* `subsingleton s : Prop` : the predicate saying that `s` has at most one element.
* `range f : set β` : the image of `univ` under `f`.
Also works for `{p : Prop} (f : p → α)` (unlike `image`)
* `prod s t : set (α × β)` : the subset `s × t`.
* `inclusion s₁ s₂ : ↥s₁ → ↥s₂` : the map `↥s₁ → ↥s₂` induced by an inclusion `s₁ ⊆ s₂`.
## Notation
* `f ⁻¹' t` for `preimage f t`
* `f '' s` for `image f s`
* `sᶜ` for the complement of `s`
## Implementation notes
* `s.nonempty` is to be preferred to `s ≠ ∅` or `∃ x, x ∈ s`. It has the advantage that
the `s.nonempty` dot notation can be used.
* For `s : set α`, do not use `subtype s`. Instead use `↥s` or `(s : Type*)` or `s`.
## Tags
set, sets, subset, subsets, image, preimage, pre-image, range, union, intersection, insert,
singleton, complement, powerset
-/
/-! ### Set coercion to a type -/
open function
universe variables u v w x
run_cmd do e ← tactic.get_env,
tactic.set_env $ e.mk_protected `set.compl
namespace set
variable {α : Type*}
instance : has_le (set α) := ⟨(⊆)⟩
instance : has_lt (set α) := ⟨λ s t, s ≤ t ∧ ¬t ≤ s⟩ -- `⊂` is not defined until further down
instance {α : Type*} : boolean_algebra (set α) :=
{ sup := (∪),
le := (≤),
lt := (<),
inf := (∩),
bot := ∅,
compl := set.compl,
top := univ,
sdiff := (\),
.. (infer_instance : boolean_algebra (α → Prop)) }
@[simp] lemma top_eq_univ : (⊤ : set α) = univ := rfl
@[simp] lemma bot_eq_empty : (⊥ : set α) = ∅ := rfl
@[simp] lemma sup_eq_union (s t : set α) : s ⊔ t = s ∪ t := rfl
@[simp] lemma inf_eq_inter (s t : set α) : s ⊓ t = s ∩ t := rfl
@[simp] lemma le_eq_subset (s t : set α) : s ≤ t = (s ⊆ t) := rfl
/-! `set.lt_eq_ssubset` is defined further down -/
/-- Coercion from a set to the corresponding subtype. -/
instance {α : Type*} : has_coe_to_sort (set α) := ⟨_, λ s, {x // x ∈ s}⟩
end set
section set_coe
variables {α : Type u}
theorem set.set_coe_eq_subtype (s : set α) :
coe_sort.{(u+1) (u+2)} s = {x // x ∈ s} := rfl
@[simp] theorem set_coe.forall {s : set α} {p : s → Prop} :
(∀ x : s, p x) ↔ (∀ x (h : x ∈ s), p ⟨x, h⟩) :=
subtype.forall
@[simp] theorem set_coe.exists {s : set α} {p : s → Prop} :
(∃ x : s, p x) ↔ (∃ x (h : x ∈ s), p ⟨x, h⟩) :=
subtype.exists
theorem set_coe.exists' {s : set α} {p : Π x, x ∈ s → Prop} :
(∃ x (h : x ∈ s), p x h) ↔ (∃ x : s, p x x.2) :=
(@set_coe.exists _ _ $ λ x, p x.1 x.2).symm
theorem set_coe.forall' {s : set α} {p : Π x, x ∈ s → Prop} :
(∀ x (h : x ∈ s), p x h) ↔ (∀ x : s, p x x.2) :=
(@set_coe.forall _ _ $ λ x, p x.1 x.2).symm
@[simp] theorem set_coe_cast : ∀ {s t : set α} (H' : s = t) (H : @eq (Type u) s t) (x : s),
cast H x = ⟨x.1, H' ▸ x.2⟩
| s _ rfl _ ⟨x, h⟩ := rfl
theorem set_coe.ext {s : set α} {a b : s} : (↑a : α) = ↑b → a = b :=
subtype.eq
theorem set_coe.ext_iff {s : set α} {a b : s} : (↑a : α) = ↑b ↔ a = b :=
iff.intro set_coe.ext (assume h, h ▸ rfl)
end set_coe
/-- See also `subtype.prop` -/
lemma subtype.mem {α : Type*} {s : set α} (p : s) : (p : α) ∈ s := p.prop
lemma eq.subset {α} {s t : set α} : s = t → s ⊆ t :=
by { rintro rfl x hx, exact hx }
namespace set
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a : α} {s t : set α}
instance : inhabited (set α) := ⟨∅⟩
@[ext]
theorem ext {a b : set α} (h : ∀ x, x ∈ a ↔ x ∈ b) : a = b :=
funext (assume x, propext (h x))
theorem ext_iff {s t : set α} : s = t ↔ ∀ x, x ∈ s ↔ x ∈ t :=
⟨λ h x, by rw h, ext⟩
@[trans] theorem mem_of_mem_of_subset {x : α} {s t : set α} (hx : x ∈ s) (h : s ⊆ t) : x ∈ t := h hx
/-! ### Lemmas about `mem` and `set_of` -/
@[simp] theorem mem_set_of_eq {a : α} {p : α → Prop} : a ∈ {a | p a} = p a := rfl
theorem nmem_set_of_eq {a : α} {P : α → Prop} : a ∉ {a : α | P a} = ¬ P a := rfl
@[simp] theorem set_of_mem_eq {s : set α} : {x | x ∈ s} = s := rfl
theorem set_of_set {s : set α} : set_of s = s := rfl
lemma set_of_app_iff {p : α → Prop} {x : α} : { x | p x } x ↔ p x := iff.rfl
theorem mem_def {a : α} {s : set α} : a ∈ s ↔ s a := iff.rfl
instance decidable_mem (s : set α) [H : decidable_pred s] : ∀ a, decidable (a ∈ s) := H
instance decidable_set_of (p : α → Prop) [H : decidable_pred p] : decidable_pred {a | p a} := H
@[simp] theorem set_of_subset_set_of {p q : α → Prop} :
{a | p a} ⊆ {a | q a} ↔ (∀a, p a → q a) := iff.rfl
@[simp] lemma sep_set_of {p q : α → Prop} : {a ∈ {a | p a } | q a} = {a | p a ∧ q a} := rfl
lemma set_of_and {p q : α → Prop} : {a | p a ∧ q a} = {a | p a} ∩ {a | q a} := rfl
lemma set_of_or {p q : α → Prop} : {a | p a ∨ q a} = {a | p a} ∪ {a | q a} := rfl
/-! ### Lemmas about subsets -/
-- TODO(Jeremy): write a tactic to unfold specific instances of generic notation?
theorem subset_def {s t : set α} : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t := rfl
@[refl] theorem subset.refl (a : set α) : a ⊆ a := assume x, id
theorem subset.rfl {s : set α} : s ⊆ s := subset.refl s
@[trans] theorem subset.trans {a b c : set α} (ab : a ⊆ b) (bc : b ⊆ c) : a ⊆ c :=
assume x h, bc (ab h)
@[trans] theorem mem_of_eq_of_mem {x y : α} {s : set α} (hx : x = y) (h : y ∈ s) : x ∈ s :=
hx.symm ▸ h
theorem subset.antisymm {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b :=
ext (λ x, iff.intro (λ ina, h₁ ina) (λ inb, h₂ inb))
theorem subset.antisymm_iff {a b : set α} : a = b ↔ a ⊆ b ∧ b ⊆ a :=
⟨λ e, e ▸ ⟨subset.refl _, subset.refl _⟩,
λ ⟨h₁, h₂⟩, subset.antisymm h₁ h₂⟩
-- an alternative name
theorem eq_of_subset_of_subset {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b :=
subset.antisymm h₁ h₂
theorem mem_of_subset_of_mem {s₁ s₂ : set α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ :=
assume h₁ h₂, h₁ h₂
theorem not_subset : (¬ s ⊆ t) ↔ ∃a ∈ s, a ∉ t :=
by simp [subset_def, not_forall]
/-! ### Definition of strict subsets `s ⊂ t` and basic properties. -/
instance : has_ssubset (set α) := ⟨(<)⟩
@[simp] lemma lt_eq_ssubset (s t : set α) : s < t = (s ⊂ t) := rfl
theorem ssubset_def : (s ⊂ t) = (s ⊆ t ∧ ¬ (t ⊆ s)) := rfl
theorem eq_or_ssubset_of_subset (h : s ⊆ t) : s = t ∨ s ⊂ t :=
classical.by_cases
(λ H : t ⊆ s, or.inl $ subset.antisymm h H)
(λ H, or.inr ⟨h, H⟩)
lemma exists_of_ssubset {s t : set α} (h : s ⊂ t) : (∃x∈t, x ∉ s) :=
not_subset.1 h.2
lemma ssubset_iff_subset_ne {s t : set α} : s ⊂ t ↔ s ⊆ t ∧ s ≠ t :=
by split; simp [set.ssubset_def, ne.def, set.subset.antisymm_iff] {contextual := tt}
lemma ssubset_iff_of_subset {s t : set α} (h : s ⊆ t) : s ⊂ t ↔ ∃ x ∈ t, x ∉ s :=
⟨exists_of_ssubset, λ ⟨x, hxt, hxs⟩, ⟨h, λ h, hxs $ h hxt⟩⟩
theorem not_mem_empty (x : α) : ¬ (x ∈ (∅ : set α)) :=
assume h : x ∈ ∅, h
@[simp] theorem not_not_mem : ¬ (a ∉ s) ↔ a ∈ s :=
by { classical, exact not_not }
/-! ### Non-empty sets -/
/-- The property `s.nonempty` expresses the fact that the set `s` is not empty. It should be used
in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks
to the dot notation. -/
protected def nonempty (s : set α) : Prop := ∃ x, x ∈ s
lemma nonempty_def : s.nonempty ↔ ∃ x, x ∈ s := iff.rfl
lemma nonempty_of_mem {x} (h : x ∈ s) : s.nonempty := ⟨x, h⟩
theorem nonempty.not_subset_empty : s.nonempty → ¬(s ⊆ ∅)
| ⟨x, hx⟩ hs := hs hx
theorem nonempty.ne_empty : s.nonempty → s ≠ ∅
| ⟨x, hx⟩ hs := by { rw hs at hx, exact hx }
/-- Extract a witness from `s.nonempty`. This function might be used instead of case analysis
on the argument. Note that it makes a proof depend on the `classical.choice` axiom. -/
protected noncomputable def nonempty.some (h : s.nonempty) : α := classical.some h
protected lemma nonempty.some_mem (h : s.nonempty) : h.some ∈ s := classical.some_spec h
lemma nonempty.mono (ht : s ⊆ t) (hs : s.nonempty) : t.nonempty := hs.imp ht
lemma nonempty_of_not_subset (h : ¬s ⊆ t) : (s \ t).nonempty :=
let ⟨x, xs, xt⟩ := not_subset.1 h in ⟨x, xs, xt⟩
lemma nonempty_of_ssubset (ht : s ⊂ t) : (t \ s).nonempty :=
nonempty_of_not_subset ht.2
lemma nonempty.of_diff (h : (s \ t).nonempty) : s.nonempty := h.imp $ λ _, and.left
lemma nonempty_of_ssubset' (ht : s ⊂ t) : t.nonempty := (nonempty_of_ssubset ht).of_diff
lemma nonempty.inl (hs : s.nonempty) : (s ∪ t).nonempty := hs.imp $ λ _, or.inl
lemma nonempty.inr (ht : t.nonempty) : (s ∪ t).nonempty := ht.imp $ λ _, or.inr
@[simp] lemma union_nonempty : (s ∪ t).nonempty ↔ s.nonempty ∨ t.nonempty := exists_or_distrib
lemma nonempty.left (h : (s ∩ t).nonempty) : s.nonempty := h.imp $ λ _, and.left
lemma nonempty.right (h : (s ∩ t).nonempty) : t.nonempty := h.imp $ λ _, and.right
lemma nonempty_inter_iff_exists_right : (s ∩ t).nonempty ↔ ∃ x : t, ↑x ∈ s :=
⟨λ ⟨x, xs, xt⟩, ⟨⟨x, xt⟩, xs⟩, λ ⟨⟨x, xt⟩, xs⟩, ⟨x, xs, xt⟩⟩
lemma nonempty_inter_iff_exists_left : (s ∩ t).nonempty ↔ ∃ x : s, ↑x ∈ t :=
⟨λ ⟨x, xs, xt⟩, ⟨⟨x, xs⟩, xt⟩, λ ⟨⟨x, xt⟩, xs⟩, ⟨x, xt, xs⟩⟩
lemma nonempty_iff_univ_nonempty : nonempty α ↔ (univ : set α).nonempty :=
⟨λ ⟨x⟩, ⟨x, trivial⟩, λ ⟨x, _⟩, ⟨x⟩⟩
@[simp] lemma univ_nonempty : ∀ [h : nonempty α], (univ : set α).nonempty
| ⟨x⟩ := ⟨x, trivial⟩
lemma nonempty.to_subtype (h : s.nonempty) : nonempty s :=
nonempty_subtype.2 h
@[simp] lemma nonempty_insert (a : α) (s : set α) : (insert a s).nonempty := ⟨a, or.inl rfl⟩
/-! ### Lemmas about the empty set -/
theorem empty_def : (∅ : set α) = {x | false} := rfl
@[simp] theorem mem_empty_eq (x : α) : x ∈ (∅ : set α) = false := rfl
@[simp] theorem set_of_false : {a : α | false} = ∅ := rfl
theorem eq_empty_iff_forall_not_mem {s : set α} : s = ∅ ↔ ∀ x, x ∉ s :=
by simp [ext_iff]
@[simp] theorem empty_subset (s : set α) : ∅ ⊆ s :=
assume x, assume h, false.elim h
theorem subset_empty_iff {s : set α} : s ⊆ ∅ ↔ s = ∅ :=
by simp [subset.antisymm_iff]
theorem eq_empty_of_subset_empty {s : set α} : s ⊆ ∅ → s = ∅ :=
subset_empty_iff.1
theorem eq_empty_of_not_nonempty (h : ¬nonempty α) (s : set α) : s = ∅ :=
eq_empty_of_subset_empty $ λ x hx, h ⟨x⟩
lemma not_nonempty_iff_eq_empty {s : set α} : ¬s.nonempty ↔ s = ∅ :=
by simp only [set.nonempty, eq_empty_iff_forall_not_mem, not_exists]
lemma empty_not_nonempty : ¬(∅ : set α).nonempty :=
not_nonempty_iff_eq_empty.2 rfl
lemma eq_empty_or_nonempty (s : set α) : s = ∅ ∨ s.nonempty :=
classical.by_cases or.inr (λ h, or.inl $ not_nonempty_iff_eq_empty.1 h)
theorem ne_empty_iff_nonempty : s ≠ ∅ ↔ s.nonempty :=
(not_congr not_nonempty_iff_eq_empty.symm).trans not_not
theorem subset_eq_empty {s t : set α} (h : t ⊆ s) (e : s = ∅) : t = ∅ :=
subset_empty_iff.1 $ e ▸ h
theorem ball_empty_iff {p : α → Prop} :
(∀ x ∈ (∅ : set α), p x) ↔ true :=
by simp [iff_def]
/-!
### Universal set.
In Lean `@univ α` (or `univ : set α`) is the set that contains all elements of type `α`.
Mathematically it is the same as `α` but it has a different type.
-/
@[simp] theorem set_of_true : {x : α | true} = univ := rfl
@[simp] theorem mem_univ (x : α) : x ∈ @univ α := trivial
theorem empty_ne_univ [h : nonempty α] : (∅ : set α) ≠ univ :=
by simp [ext_iff]
@[simp] theorem subset_univ (s : set α) : s ⊆ univ := λ x H, trivial
theorem univ_subset_iff {s : set α} : univ ⊆ s ↔ s = univ :=
by simp [subset.antisymm_iff]
theorem eq_univ_of_univ_subset {s : set α} : univ ⊆ s → s = univ :=
univ_subset_iff.1
theorem eq_univ_iff_forall {s : set α} : s = univ ↔ ∀ x, x ∈ s :=
by simp [ext_iff]
theorem eq_univ_of_forall {s : set α} : (∀ x, x ∈ s) → s = univ := eq_univ_iff_forall.2
lemma eq_univ_of_subset {s t : set α} (h : s ⊆ t) (hs : s = univ) : t = univ :=
eq_univ_of_univ_subset $ hs ▸ h
@[simp] lemma univ_eq_empty_iff : (univ : set α) = ∅ ↔ ¬ nonempty α :=
eq_empty_iff_forall_not_mem.trans ⟨λ H ⟨x⟩, H x trivial, λ H x _, H ⟨x⟩⟩
lemma exists_mem_of_nonempty (α) : ∀ [nonempty α], ∃x:α, x ∈ (univ : set α)
| ⟨x⟩ := ⟨x, trivial⟩
instance univ_decidable : decidable_pred (@set.univ α) :=
λ x, is_true trivial
/-- `diagonal α` is the subset of `α × α` consisting of all pairs of the form `(a, a)`. -/
def diagonal (α : Type*) : set (α × α) := {p | p.1 = p.2}
@[simp]
lemma mem_diagonal {α : Type*} (x : α) : (x, x) ∈ diagonal α :=
by simp [diagonal]
/-! ### Lemmas about union -/
theorem union_def {s₁ s₂ : set α} : s₁ ∪ s₂ = {a | a ∈ s₁ ∨ a ∈ s₂} := rfl
theorem mem_union_left {x : α} {a : set α} (b : set α) : x ∈ a → x ∈ a ∪ b := or.inl
theorem mem_union_right {x : α} {b : set α} (a : set α) : x ∈ b → x ∈ a ∪ b := or.inr
theorem mem_or_mem_of_mem_union {x : α} {a b : set α} (H : x ∈ a ∪ b) : x ∈ a ∨ x ∈ b := H
theorem mem_union.elim {x : α} {a b : set α} {P : Prop}
(H₁ : x ∈ a ∪ b) (H₂ : x ∈ a → P) (H₃ : x ∈ b → P) : P :=
or.elim H₁ H₂ H₃
theorem mem_union (x : α) (a b : set α) : x ∈ a ∪ b ↔ x ∈ a ∨ x ∈ b := iff.rfl
@[simp] theorem mem_union_eq (x : α) (a b : set α) : x ∈ a ∪ b = (x ∈ a ∨ x ∈ b) := rfl
@[simp] theorem union_self (a : set α) : a ∪ a = a :=
ext (assume x, or_self _)
@[simp] theorem union_empty (a : set α) : a ∪ ∅ = a :=
ext (assume x, or_false _)
@[simp] theorem empty_union (a : set α) : ∅ ∪ a = a :=
ext (assume x, false_or _)
theorem union_comm (a b : set α) : a ∪ b = b ∪ a :=
ext (assume x, or.comm)
theorem union_assoc (a b c : set α) : (a ∪ b) ∪ c = a ∪ (b ∪ c) :=
ext (assume x, or.assoc)
instance union_is_assoc : is_associative (set α) (∪) :=
⟨union_assoc⟩
instance union_is_comm : is_commutative (set α) (∪) :=
⟨union_comm⟩
theorem union_left_comm (s₁ s₂ s₃ : set α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) :=
by finish
theorem union_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ :=
by finish
theorem union_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∪ t = t :=
by finish [subset_def, ext_iff, iff_def]
theorem union_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∪ t = s :=
by finish [subset_def, ext_iff, iff_def]
@[simp] theorem subset_union_left (s t : set α) : s ⊆ s ∪ t := λ x, or.inl
@[simp] theorem subset_union_right (s t : set α) : t ⊆ s ∪ t := λ x, or.inr
theorem union_subset {s t r : set α} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r :=
by finish [subset_def, union_def]
@[simp] theorem union_subset_iff {s t u : set α} : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u :=
by finish [iff_def, subset_def]
theorem union_subset_union {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ s₂) (h₂ : t₁ ⊆ t₂) : s₁ ∪ t₁ ⊆ s₂ ∪ t₂ :=
by finish [subset_def]
theorem union_subset_union_left {s₁ s₂ : set α} (t) (h : s₁ ⊆ s₂) : s₁ ∪ t ⊆ s₂ ∪ t :=
union_subset_union h (by refl)
theorem union_subset_union_right (s) {t₁ t₂ : set α} (h : t₁ ⊆ t₂) : s ∪ t₁ ⊆ s ∪ t₂ :=
union_subset_union (by refl) h
lemma subset_union_of_subset_left {s t : set α} (h : s ⊆ t) (u : set α) : s ⊆ t ∪ u :=
subset.trans h (subset_union_left t u)
lemma subset_union_of_subset_right {s u : set α} (h : s ⊆ u) (t : set α) : s ⊆ t ∪ u :=
subset.trans h (subset_union_right t u)
@[simp] theorem union_empty_iff {s t : set α} : s ∪ t = ∅ ↔ s = ∅ ∧ t = ∅ :=
⟨by finish [ext_iff], by finish [ext_iff]⟩
/-! ### Lemmas about intersection -/
theorem inter_def {s₁ s₂ : set α} : s₁ ∩ s₂ = {a | a ∈ s₁ ∧ a ∈ s₂} := rfl
theorem mem_inter_iff (x : α) (a b : set α) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b := iff.rfl
@[simp] theorem mem_inter_eq (x : α) (a b : set α) : x ∈ a ∩ b = (x ∈ a ∧ x ∈ b) := rfl
theorem mem_inter {x : α} {a b : set α} (ha : x ∈ a) (hb : x ∈ b) : x ∈ a ∩ b :=
⟨ha, hb⟩
theorem mem_of_mem_inter_left {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ a :=
h.left
theorem mem_of_mem_inter_right {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ b :=
h.right
@[simp] theorem inter_self (a : set α) : a ∩ a = a :=
ext (assume x, and_self _)
@[simp] theorem inter_empty (a : set α) : a ∩ ∅ = ∅ :=
ext (assume x, and_false _)
@[simp] theorem empty_inter (a : set α) : ∅ ∩ a = ∅ :=
ext (assume x, false_and _)
theorem inter_comm (a b : set α) : a ∩ b = b ∩ a :=
ext (assume x, and.comm)
theorem inter_assoc (a b c : set α) : (a ∩ b) ∩ c = a ∩ (b ∩ c) :=
ext (assume x, and.assoc)
instance inter_is_assoc : is_associative (set α) (∩) :=
⟨inter_assoc⟩
instance inter_is_comm : is_commutative (set α) (∩) :=
⟨inter_comm⟩
theorem inter_left_comm (s₁ s₂ s₃ : set α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) :=
by finish
theorem inter_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ :=
by finish
@[simp] theorem inter_subset_left (s t : set α) : s ∩ t ⊆ s := λ x H, and.left H
@[simp] theorem inter_subset_right (s t : set α) : s ∩ t ⊆ t := λ x H, and.right H
theorem subset_inter {s t r : set α} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t :=
by finish [subset_def, inter_def]
@[simp] theorem subset_inter_iff {s t r : set α} : r ⊆ s ∩ t ↔ r ⊆ s ∧ r ⊆ t :=
⟨λ h, ⟨subset.trans h (inter_subset_left _ _), subset.trans h (inter_subset_right _ _)⟩,
λ ⟨h₁, h₂⟩, subset_inter h₁ h₂⟩
@[simp] theorem inter_univ (a : set α) : a ∩ univ = a :=
ext (assume x, and_true _)
@[simp] theorem univ_inter (a : set α) : univ ∩ a = a :=
ext (assume x, true_and _)
theorem inter_subset_inter_left {s t : set α} (u : set α) (H : s ⊆ t) : s ∩ u ⊆ t ∩ u :=
by finish [subset_def]
theorem inter_subset_inter_right {s t : set α} (u : set α) (H : s ⊆ t) : u ∩ s ⊆ u ∩ t :=
by finish [subset_def]
theorem inter_subset_inter {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ ∩ s₂ ⊆ t₁ ∩ t₂ :=
by finish [subset_def]
theorem inter_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∩ t = s :=
by finish [subset_def, ext_iff, iff_def]
theorem inter_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∩ t = t :=
by finish [subset_def, ext_iff, iff_def]
lemma inter_compl_nonempty_iff {s t : set α} : (s ∩ tᶜ).nonempty ↔ ¬ s ⊆ t :=
begin
split,
{ rintros ⟨x ,xs, xt⟩ sub,
exact xt (sub xs) },
{ intros h,
rcases not_subset.mp h with ⟨x, xs, xt⟩,
exact ⟨x, xs, xt⟩ }
end
theorem union_inter_cancel_left {s t : set α} : (s ∪ t) ∩ s = s :=
by finish [ext_iff, iff_def]
theorem union_inter_cancel_right {s t : set α} : (s ∪ t) ∩ t = t :=
by finish [ext_iff, iff_def]
/-! ### Distributivity laws -/
theorem inter_distrib_left (s t u : set α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) :=
ext (assume x, and_or_distrib_left)
theorem inter_distrib_right (s t u : set α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) :=
ext (assume x, or_and_distrib_right)
theorem union_distrib_left (s t u : set α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) :=
ext (assume x, or_and_distrib_left)
theorem union_distrib_right (s t u : set α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) :=
ext (assume x, and_or_distrib_right)
/-!
### Lemmas about `insert`
`insert α s` is the set `{α} ∪ s`.
-/
theorem insert_def (x : α) (s : set α) : insert x s = { y | y = x ∨ y ∈ s } := rfl
@[simp] theorem subset_insert (x : α) (s : set α) : s ⊆ insert x s :=
assume y ys, or.inr ys
theorem mem_insert (x : α) (s : set α) : x ∈ insert x s :=
or.inl rfl
theorem mem_insert_of_mem {x : α} {s : set α} (y : α) : x ∈ s → x ∈ insert y s := or.inr
theorem eq_or_mem_of_mem_insert {x a : α} {s : set α} : x ∈ insert a s → x = a ∨ x ∈ s := id
theorem mem_of_mem_insert_of_ne {x a : α} {s : set α} (xin : x ∈ insert a s) : x ≠ a → x ∈ s :=
by finish [insert_def]
@[simp] theorem mem_insert_iff {x a : α} {s : set α} : x ∈ insert a s ↔ (x = a ∨ x ∈ s) := iff.rfl
@[simp] theorem insert_eq_of_mem {a : α} {s : set α} (h : a ∈ s) : insert a s = s :=
by finish [ext_iff, iff_def]
lemma ne_insert_of_not_mem {s : set α} (t : set α) {a : α} (h : a ∉ s) :
s ≠ insert a t :=
by { contrapose! h, simp [h] }
theorem insert_subset : insert a s ⊆ t ↔ (a ∈ t ∧ s ⊆ t) :=
by simp [subset_def, or_imp_distrib, forall_and_distrib]
theorem insert_subset_insert (h : s ⊆ t) : insert a s ⊆ insert a t :=
assume a', or.imp_right (@h a')
theorem ssubset_iff_insert {s t : set α} : s ⊂ t ↔ ∃ a ∉ s, insert a s ⊆ t :=
begin
simp only [insert_subset, exists_and_distrib_right, ssubset_def, not_subset],
simp only [exists_prop, and_comm]
end
theorem ssubset_insert {s : set α} {a : α} (h : a ∉ s) : s ⊂ insert a s :=
ssubset_iff_insert.2 ⟨a, h, subset.refl _⟩
theorem insert_comm (a b : α) (s : set α) : insert a (insert b s) = insert b (insert a s) :=
by { ext, simp [or.left_comm] }
theorem insert_union : insert a s ∪ t = insert a (s ∪ t) :=
by { ext, simp [or.comm, or.left_comm] }
@[simp] theorem union_insert : s ∪ insert a t = insert a (s ∪ t) :=
by { ext, simp [or.comm, or.left_comm] }
theorem insert_nonempty (a : α) (s : set α) : (insert a s).nonempty :=
⟨a, mem_insert a s⟩
lemma insert_inter (x : α) (s t : set α) : insert x (s ∩ t) = insert x s ∩ insert x t :=
by { ext y, simp [←or_and_distrib_left] }
-- useful in proofs by induction
theorem forall_of_forall_insert {P : α → Prop} {a : α} {s : set α} (h : ∀ x, x ∈ insert a s → P x) :
∀ x, x ∈ s → P x :=
by finish
theorem forall_insert_of_forall {P : α → Prop} {a : α} {s : set α} (h : ∀ x, x ∈ s → P x) (ha : P a) :
∀ x, x ∈ insert a s → P x :=
by finish
theorem bex_insert_iff {P : α → Prop} {a : α} {s : set α} :
(∃ x ∈ insert a s, P x) ↔ (∃ x ∈ s, P x) ∨ P a :=
by finish [iff_def]
theorem ball_insert_iff {P : α → Prop} {a : α} {s : set α} :
(∀ x ∈ insert a s, P x) ↔ P a ∧ (∀x ∈ s, P x) :=
by finish [iff_def]
/-! ### Lemmas about singletons -/
theorem singleton_def (a : α) : ({a} : set α) = insert a ∅ :=
(insert_emptyc_eq _).symm
@[simp] theorem mem_singleton_iff {a b : α} : a ∈ ({b} : set α) ↔ a = b :=
iff.rfl
@[simp]
lemma set_of_eq_eq_singleton {a : α} : {n | n = a} = {a} :=
set.ext $ λ n, (set.mem_singleton_iff).symm
-- TODO: again, annotation needed
@[simp] theorem mem_singleton (a : α) : a ∈ ({a} : set α) := by finish
theorem eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : set α)) : x = y :=
by finish
@[simp] theorem singleton_eq_singleton_iff {x y : α} : {x} = ({y} : set α) ↔ x = y :=
by finish [ext_iff, iff_def]
theorem mem_singleton_of_eq {x y : α} (H : x = y) : x ∈ ({y} : set α) :=
by finish
theorem insert_eq (x : α) (s : set α) : insert x s = ({x} : set α) ∪ s :=
by finish [ext_iff, or_comm]
@[simp] theorem pair_eq_singleton (a : α) : ({a, a} : set α) = {a} :=
by finish
theorem pair_comm (a b : α) : ({a, b} : set α) = {b, a} :=
ext $ λ x, or_comm _ _
@[simp] theorem singleton_nonempty (a : α) : ({a} : set α).nonempty :=
⟨a, rfl⟩
@[simp] theorem singleton_subset_iff {a : α} {s : set α} : {a} ⊆ s ↔ a ∈ s :=
⟨λh, h (by simp), λh b e, by { rw [mem_singleton_iff] at e, simp [*] }⟩
theorem set_compr_eq_eq_singleton {a : α} : {b | b = a} = {a} :=
by { ext, simp }
@[simp] theorem singleton_union : {a} ∪ s = insert a s :=
rfl
@[simp] theorem union_singleton : s ∪ {a} = insert a s :=
by rw [union_comm, singleton_union]
@[simp] theorem singleton_inter_eq_empty : {a} ∩ s = ∅ ↔ a ∉ s :=
by simp [eq_empty_iff_forall_not_mem]
@[simp] theorem inter_singleton_eq_empty : s ∩ {a} = ∅ ↔ a ∉ s :=
by rw [inter_comm, singleton_inter_eq_empty]
@[simp] theorem singleton_inter_nonempty : ({a} ∩ s).nonempty ↔ a ∈ s :=
by rw [← ne_empty_iff_nonempty, ne.def, singleton_inter_eq_empty, not_not]
@[simp] theorem inter_singleton_nonempty : (s ∩ {a}).nonempty ↔ a ∈ s :=
by rw [inter_comm, singleton_inter_nonempty]
lemma nmem_singleton_empty {s : set α} : s ∉ ({∅} : set (set α)) ↔ s.nonempty :=
by rw [mem_singleton_iff, ← ne.def, ne_empty_iff_nonempty]
instance unique_singleton (a : α) : unique ↥({a} : set α) :=
{ default := ⟨a, mem_singleton a⟩,
uniq :=
begin
intros x,
apply subtype.ext,
apply eq_of_mem_singleton (subtype.mem x),
end}
lemma eq_singleton_iff_unique_mem {s : set α} {a : α} :
s = {a} ↔ a ∈ s ∧ ∀ x ∈ s, x = a :=
by simp [ext_iff, @iff_def (_ ∈ s), forall_and_distrib, and_comm]
/-! ### Lemmas about sets defined as `{x ∈ s | p x}`. -/
theorem mem_sep {s : set α} {p : α → Prop} {x : α} (xs : x ∈ s) (px : p x) : x ∈ {x ∈ s | p x} :=
⟨xs, px⟩
@[simp] theorem sep_mem_eq {s t : set α} : {x ∈ s | x ∈ t} = s ∩ t := rfl
@[simp] theorem mem_sep_eq {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} = (x ∈ s ∧ p x) := rfl
theorem mem_sep_iff {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} ↔ x ∈ s ∧ p x :=
iff.rfl
theorem eq_sep_of_subset {s t : set α} (ssubt : s ⊆ t) : s = {x ∈ t | x ∈ s} :=
by finish [ext_iff, iff_def, subset_def]
theorem sep_subset (s : set α) (p : α → Prop) : {x ∈ s | p x} ⊆ s :=
assume x, and.left
theorem forall_not_of_sep_empty {s : set α} {p : α → Prop} (h : {x ∈ s | p x} = ∅) :
∀ x ∈ s, ¬ p x :=
by finish [ext_iff]
@[simp] lemma sep_univ {α} {p : α → Prop} : {a ∈ (univ : set α) | p a} = {a | p a} :=
by { ext, simp }
@[simp] lemma subset_singleton_iff {α : Type*} {s : set α} {x : α} : s ⊆ {x} ↔ ∀ y ∈ s, y = x :=
iff.rfl
/-! ### Lemmas about complement -/
theorem mem_compl {s : set α} {x : α} (h : x ∉ s) : x ∈ sᶜ := h
lemma compl_set_of {α} (p : α → Prop) : {a | p a}ᶜ = { a | ¬ p a } := rfl
theorem not_mem_of_mem_compl {s : set α} {x : α} (h : x ∈ sᶜ) : x ∉ s := h
@[simp] theorem mem_compl_eq (s : set α) (x : α) : x ∈ sᶜ = (x ∉ s) := rfl
theorem mem_compl_iff (s : set α) (x : α) : x ∈ sᶜ ↔ x ∉ s := iff.rfl
@[simp] theorem inter_compl_self (s : set α) : s ∩ sᶜ = ∅ :=
by finish [ext_iff]
@[simp] theorem compl_inter_self (s : set α) : sᶜ ∩ s = ∅ :=
by finish [ext_iff]
@[simp] theorem compl_empty : (∅ : set α)ᶜ = univ :=
by finish [ext_iff]
@[simp] theorem compl_union (s t : set α) : (s ∪ t)ᶜ = sᶜ ∩ tᶜ :=
by finish [ext_iff]
local attribute [simp] -- Will be generalized to lattices in `compl_compl'`
theorem compl_compl (s : set α) : sᶜᶜ = s :=
by finish [ext_iff]
-- ditto
theorem compl_inter (s t : set α) : (s ∩ t)ᶜ = sᶜ ∪ tᶜ :=
by finish [ext_iff]
@[simp] theorem compl_univ : (univ : set α)ᶜ = ∅ :=
by finish [ext_iff]
lemma compl_empty_iff {s : set α} : sᶜ = ∅ ↔ s = univ :=
by { split, intro h, rw [←compl_compl s, h, compl_empty], intro h, rw [h, compl_univ] }
lemma compl_univ_iff {s : set α} : sᶜ = univ ↔ s = ∅ :=
by rw [←compl_empty_iff, compl_compl]
lemma nonempty_compl {s : set α} : sᶜ.nonempty ↔ s ≠ univ :=
ne_empty_iff_nonempty.symm.trans $ not_congr $ compl_empty_iff
lemma mem_compl_singleton_iff {a x : α} : x ∈ ({a} : set α)ᶜ ↔ x ≠ a :=
not_iff_not_of_iff mem_singleton_iff
lemma compl_singleton_eq (a : α) : ({a} : set α)ᶜ = {x | x ≠ a} :=
ext $ λ x, mem_compl_singleton_iff
theorem union_eq_compl_compl_inter_compl (s t : set α) : s ∪ t = (sᶜ ∩ tᶜ)ᶜ :=
by simp [compl_inter, compl_compl]
theorem inter_eq_compl_compl_union_compl (s t : set α) : s ∩ t = (sᶜ ∪ tᶜ)ᶜ :=
by simp [compl_compl]
@[simp] theorem union_compl_self (s : set α) : s ∪ sᶜ = univ :=
by finish [ext_iff]
@[simp] theorem compl_union_self (s : set α) : sᶜ ∪ s = univ :=
by finish [ext_iff]
theorem compl_comp_compl : compl ∘ compl = @id (set α) :=
funext compl_compl
theorem compl_subset_comm {s t : set α} : sᶜ ⊆ t ↔ tᶜ ⊆ s :=
by haveI := classical.prop_decidable; exact
forall_congr (λ a, not_imp_comm)
lemma compl_subset_compl {s t : set α} : sᶜ ⊆ tᶜ ↔ t ⊆ s :=
by rw [compl_subset_comm, compl_compl]
theorem compl_subset_iff_union {s t : set α} : sᶜ ⊆ t ↔ s ∪ t = univ :=
iff.symm $ eq_univ_iff_forall.trans $ forall_congr $ λ a,
by haveI := classical.prop_decidable; exact or_iff_not_imp_left
theorem subset_compl_comm {s t : set α} : s ⊆ tᶜ ↔ t ⊆ sᶜ :=
forall_congr $ λ a, imp_not_comm
theorem subset_compl_iff_disjoint {s t : set α} : s ⊆ tᶜ ↔ s ∩ t = ∅ :=
iff.trans (forall_congr $ λ a, and_imp.symm) subset_empty_iff
lemma subset_compl_singleton_iff {a : α} {s : set α} : s ⊆ {a}ᶜ ↔ a ∉ s :=
by { rw subset_compl_comm, simp }
theorem inter_subset (a b c : set α) : a ∩ b ⊆ c ↔ a ⊆ bᶜ ∪ c :=
begin
classical,
split,
{ intros h x xa, by_cases h' : x ∈ b, simp [h ⟨xa, h'⟩], simp [h'] },
intros h x, rintro ⟨xa, xb⟩, cases h xa, contradiction, assumption
end
/-! ### Lemmas about set difference -/
theorem diff_eq (s t : set α) : s \ t = s ∩ tᶜ := rfl
@[simp] theorem mem_diff {s t : set α} (x : α) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := iff.rfl
theorem mem_diff_of_mem {s t : set α} {x : α} (h1 : x ∈ s) (h2 : x ∉ t) : x ∈ s \ t :=
⟨h1, h2⟩
theorem mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∈ s :=
h.left
theorem not_mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∉ t :=
h.right
theorem diff_eq_compl_inter {s t : set α} : s \ t = tᶜ ∩ s :=
by rw [diff_eq, inter_comm]
theorem nonempty_diff {s t : set α} : (s \ t).nonempty ↔ ¬ (s ⊆ t) :=
⟨λ ⟨x, xs, xt⟩, not_subset.2 ⟨x, xs, xt⟩,
λ h, let ⟨x, xs, xt⟩ := not_subset.1 h in ⟨x, xs, xt⟩⟩
theorem union_diff_cancel' {s t u : set α} (h₁ : s ⊆ t) (h₂ : t ⊆ u) : t ∪ (u \ s) = u :=
by finish [ext_iff, iff_def, subset_def]
theorem union_diff_cancel {s t : set α} (h : s ⊆ t) : s ∪ (t \ s) = t :=
union_diff_cancel' (subset.refl s) h
theorem union_diff_cancel_left {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ s = t :=
by finish [ext_iff, iff_def, subset_def]
theorem union_diff_cancel_right {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ t = s :=
by finish [ext_iff, iff_def, subset_def]
theorem union_diff_left {s t : set α} : (s ∪ t) \ s = t \ s :=
by finish [ext_iff, iff_def]
theorem union_diff_right {s t : set α} : (s ∪ t) \ t = s \ t :=
by finish [ext_iff, iff_def]
theorem union_diff_distrib {s t u : set α} : (s ∪ t) \ u = s \ u ∪ t \ u :=
inter_distrib_right _ _ _
theorem inter_union_distrib_left {s t u : set α} : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) :=
set.ext $ λ _, and_or_distrib_left
theorem inter_union_distrib_right {s t u : set α} : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) :=
set.ext $ λ _, and_or_distrib_right
theorem union_inter_distrib_left {s t u : set α} : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) :=
set.ext $ λ _, or_and_distrib_left
theorem union_inter_distrib_right {s t u : set α} : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) :=
set.ext $ λ _, or_and_distrib_right
theorem inter_diff_assoc (a b c : set α) : (a ∩ b) \ c = a ∩ (b \ c) :=
inter_assoc _ _ _
theorem inter_diff_self (a b : set α) : a ∩ (b \ a) = ∅ :=
by finish [ext_iff]
theorem inter_union_diff (s t : set α) : (s ∩ t) ∪ (s \ t) = s :=
by finish [ext_iff, iff_def]
theorem inter_union_compl (s t : set α) : (s ∩ t) ∪ (s ∩ tᶜ) = s := inter_union_diff _ _
theorem diff_subset (s t : set α) : s \ t ⊆ s :=
by finish [subset_def]
theorem diff_subset_diff {s₁ s₂ t₁ t₂ : set α} : s₁ ⊆ s₂ → t₂ ⊆ t₁ → s₁ \ t₁ ⊆ s₂ \ t₂ :=
by finish [subset_def]
theorem diff_subset_diff_left {s₁ s₂ t : set α} (h : s₁ ⊆ s₂) : s₁ \ t ⊆ s₂ \ t :=
diff_subset_diff h (by refl)
theorem diff_subset_diff_right {s t u : set α} (h : t ⊆ u) : s \ u ⊆ s \ t :=
diff_subset_diff (subset.refl s) h
theorem compl_eq_univ_diff (s : set α) : sᶜ = univ \ s :=
by finish [ext_iff]
@[simp] lemma empty_diff (s : set α) : (∅ \ s : set α) = ∅ :=
eq_empty_of_subset_empty $ assume x ⟨hx, _⟩, hx
theorem diff_eq_empty {s t : set α} : s \ t = ∅ ↔ s ⊆ t :=
⟨assume h x hx, classical.by_contradiction $ assume : x ∉ t, show x ∈ (∅ : set α), from h ▸ ⟨hx, this⟩,
assume h, eq_empty_of_subset_empty $ assume x ⟨hx, hnx⟩, hnx $ h hx⟩
@[simp] theorem diff_empty {s : set α} : s \ ∅ = s :=
ext $ assume x, ⟨assume ⟨hx, _⟩, hx, assume h, ⟨h, not_false⟩⟩
theorem diff_diff {u : set α} : s \ t \ u = s \ (t ∪ u) :=
ext $ by simp [not_or_distrib, and.comm, and.left_comm]
-- the following statement contains parentheses to help the reader
lemma diff_diff_comm {s t u : set α} : (s \ t) \ u = (s \ u) \ t :=
by simp_rw [diff_diff, union_comm]
lemma diff_subset_iff {s t u : set α} : s \ t ⊆ u ↔ s ⊆ t ∪ u :=
⟨assume h x xs, classical.by_cases or.inl (assume nxt, or.inr (h ⟨xs, nxt⟩)),
assume h x ⟨xs, nxt⟩, or.resolve_left (h xs) nxt⟩
lemma subset_diff_union (s t : set α) : s ⊆ (s \ t) ∪ t :=
by rw [union_comm, ←diff_subset_iff]
@[simp] lemma diff_singleton_subset_iff {x : α} {s t : set α} : s \ {x} ⊆ t ↔ s ⊆ insert x t :=
by { rw [←union_singleton, union_comm], apply diff_subset_iff }
lemma subset_diff_singleton {x : α} {s t : set α} (h : s ⊆ t) (hx : x ∉ s) : s ⊆ t \ {x} :=
subset_inter h $ subset_compl_comm.1 $ singleton_subset_iff.2 hx
lemma subset_insert_diff_singleton (x : α) (s : set α) : s ⊆ insert x (s \ {x}) :=
by rw [←diff_singleton_subset_iff]
lemma diff_subset_comm {s t u : set α} : s \ t ⊆ u ↔ s \ u ⊆ t :=
by rw [diff_subset_iff, diff_subset_iff, union_comm]
lemma diff_inter {s t u : set α} : s \ (t ∩ u) = (s \ t) ∪ (s \ u) :=
ext $ λ x, by simp [not_and_distrib, and_or_distrib_left]
lemma diff_inter_diff {s t u : set α} : s \ t ∩ (s \ u) = s \ (t ∪ u) :=
by { ext x, simp only [mem_inter_eq, mem_union_eq, mem_diff, not_or_distrib, and.left_comm,
and.assoc, and_self_left] }
lemma diff_compl : s \ tᶜ = s ∩ t := by rw [diff_eq, compl_compl]
lemma diff_diff_right {s t u : set α} : s \ (t \ u) = (s \ t) ∪ (s ∩ u) :=
by rw [diff_eq t u, diff_inter, diff_compl]
@[simp] theorem insert_diff_of_mem (s) (h : a ∈ t) : insert a s \ t = s \ t :=
by { ext, split; simp [or_imp_distrib, h] {contextual := tt} }
theorem insert_diff_of_not_mem (s) (h : a ∉ t) : insert a s \ t = insert a (s \ t) :=
begin
classical,
ext x,
by_cases h' : x ∈ t,
{ have : x ≠ a,
{ assume H,
rw H at h',
exact h h' },
simp [h, h', this] },
{ simp [h, h'] }
end
lemma insert_diff_self_of_not_mem {a : α} {s : set α} (h : a ∉ s) :
insert a s \ {a} = s :=
by { ext, simp [and_iff_left_of_imp (λ hx : x ∈ s, show x ≠ a, from λ hxa, h $ hxa ▸ hx)] }
theorem union_diff_self {s t : set α} : s ∪ (t \ s) = s ∪ t :=
by finish [ext_iff, iff_def]
theorem diff_union_self {s t : set α} : (s \ t) ∪ t = s ∪ t :=
by rw [union_comm, union_diff_self, union_comm]
theorem diff_inter_self {a b : set α} : (b \ a) ∩ a = ∅ :=
by { ext, by simp [iff_def] {contextual:=tt} }
theorem diff_inter_self_eq_diff {s t : set α} : s \ (t ∩ s) = s \ t :=
by { ext, simp [iff_def] {contextual := tt} }
theorem diff_self_inter {s t : set α} : s \ (s ∩ t) = s \ t :=
by rw [inter_comm, diff_inter_self_eq_diff]
theorem diff_eq_self {s t : set α} : s \ t = s ↔ t ∩ s ⊆ ∅ :=
by finish [ext_iff, iff_def, subset_def]
@[simp] theorem diff_singleton_eq_self {a : α} {s : set α} (h : a ∉ s) : s \ {a} = s :=
diff_eq_self.2 $ by simp [singleton_inter_eq_empty.2 h]
@[simp] theorem insert_diff_singleton {a : α} {s : set α} :
insert a (s \ {a}) = insert a s :=
by simp [insert_eq, union_diff_self, -union_singleton, -singleton_union]
@[simp] lemma diff_self {s : set α} : s \ s = ∅ := by { ext, simp }
lemma diff_diff_cancel_left {s t : set α} (h : s ⊆ t) : t \ (t \ s) = s :=
by simp only [diff_diff_right, diff_self, inter_eq_self_of_subset_right h, empty_union]
lemma mem_diff_singleton {x y : α} {s : set α} : x ∈ s \ {y} ↔ (x ∈ s ∧ x ≠ y) :=
iff.rfl
lemma mem_diff_singleton_empty {s : set α} {t : set (set α)} :
s ∈ t \ {∅} ↔ (s ∈ t ∧ s.nonempty) :=
mem_diff_singleton.trans $ and_congr iff.rfl ne_empty_iff_nonempty
/-! ### Powerset -/
theorem mem_powerset {x s : set α} (h : x ⊆ s) : x ∈ powerset s := h
theorem subset_of_mem_powerset {x s : set α} (h : x ∈ powerset s) : x ⊆ s := h
@[simp] theorem mem_powerset_iff (x s : set α) : x ∈ powerset s ↔ x ⊆ s := iff.rfl
theorem powerset_inter (s t : set α) : 𝒫 (s ∩ t) = 𝒫 s ∩ 𝒫 t :=
ext $ λ u, subset_inter_iff
@[simp] theorem powerset_mono : 𝒫 s ⊆ 𝒫 t ↔ s ⊆ t :=
⟨λ h, h (subset.refl s), λ h u hu, subset.trans hu h⟩
theorem monotone_powerset : monotone (powerset : set α → set (set α)) :=
λ s t, powerset_mono.2
@[simp] theorem powerset_nonempty : (𝒫 s).nonempty :=
⟨∅, empty_subset s⟩
@[simp] theorem powerset_empty : 𝒫 (∅ : set α) = {∅} :=
ext $ λ s, subset_empty_iff
/-! ### Inverse image -/
/-- The preimage of `s : set β` by `f : α → β`, written `f ⁻¹' s`,
is the set of `x : α` such that `f x ∈ s`. -/
def preimage {α : Type u} {β : Type v} (f : α → β) (s : set β) : set α := {x | f x ∈ s}
infix ` ⁻¹' `:80 := preimage
section preimage
variables {f : α → β} {g : β → γ}
@[simp] theorem preimage_empty : f ⁻¹' ∅ = ∅ := rfl
@[simp] theorem mem_preimage {s : set β} {a : α} : (a ∈ f ⁻¹' s) ↔ (f a ∈ s) := iff.rfl
lemma preimage_congr {f g : α → β} {s : set β} (h : ∀ (x : α), f x = g x) : f ⁻¹' s = g ⁻¹' s :=
by { congr' with x, apply_assumption }
theorem preimage_mono {s t : set β} (h : s ⊆ t) : f ⁻¹' s ⊆ f ⁻¹' t :=
assume x hx, h hx
@[simp] theorem preimage_univ : f ⁻¹' univ = univ := rfl
theorem subset_preimage_univ {s : set α} : s ⊆ f ⁻¹' univ := subset_univ _
@[simp] theorem preimage_inter {s t : set β} : f ⁻¹' (s ∩ t) = f ⁻¹' s ∩ f ⁻¹' t := rfl
@[simp] theorem preimage_union {s t : set β} : f ⁻¹' (s ∪ t) = f ⁻¹' s ∪ f ⁻¹' t := rfl
@[simp] theorem preimage_compl {s : set β} : f ⁻¹' sᶜ = (f ⁻¹' s)ᶜ := rfl
@[simp] theorem preimage_diff (f : α → β) (s t : set β) :
f ⁻¹' (s \ t) = f ⁻¹' s \ f ⁻¹' t := rfl
@[simp] theorem preimage_set_of_eq {p : α → Prop} {f : β → α} : f ⁻¹' {a | p a} = {a | p (f a)} :=
rfl
@[simp] theorem preimage_id {s : set α} : id ⁻¹' s = s := rfl
@[simp] theorem preimage_id' {s : set α} : (λ x, x) ⁻¹' s = s := rfl
theorem preimage_const_of_mem {b : β} {s : set β} (h : b ∈ s) :
(λ (x : α), b) ⁻¹' s = univ :=
eq_univ_of_forall $ λ x, h
theorem preimage_const_of_not_mem {b : β} {s : set β} (h : b ∉ s) :
(λ (x : α), b) ⁻¹' s = ∅ :=
eq_empty_of_subset_empty $ λ x hx, h hx
theorem preimage_const (b : β) (s : set β) [decidable (b ∈ s)] :
(λ (x : α), b) ⁻¹' s = if b ∈ s then univ else ∅ :=
by { split_ifs with hb hb, exacts [preimage_const_of_mem hb, preimage_const_of_not_mem hb] }
theorem preimage_comp {s : set γ} : (g ∘ f) ⁻¹' s = f ⁻¹' (g ⁻¹' s) := rfl
lemma preimage_preimage {g : β → γ} {f : α → β} {s : set γ} :
f ⁻¹' (g ⁻¹' s) = (λ x, g (f x)) ⁻¹' s :=
preimage_comp.symm
theorem eq_preimage_subtype_val_iff {p : α → Prop} {s : set (subtype p)} {t : set α} :
s = subtype.val ⁻¹' t ↔ (∀x (h : p x), (⟨x, h⟩ : subtype p) ∈ s ↔ x ∈ t) :=
⟨assume s_eq x h, by { rw [s_eq], simp },
assume h, ext $ λ ⟨x, hx⟩, by simp [h]⟩
lemma preimage_coe_coe_diagonal {α : Type*} (s : set α) :
(prod.map coe coe) ⁻¹' (diagonal α) = diagonal s :=
begin
ext ⟨⟨x, x_in⟩, ⟨y, y_in⟩⟩,
simp [set.diagonal],
end
end preimage
/-! ### Image of a set under a function -/
section image
infix ` '' `:80 := image
theorem mem_image_iff_bex {f : α → β} {s : set α} {y : β} :
y ∈ f '' s ↔ ∃ x (_ : x ∈ s), f x = y := bex_def.symm
theorem mem_image_eq (f : α → β) (s : set α) (y: β) : y ∈ f '' s = ∃ x, x ∈ s ∧ f x = y := rfl
@[simp] theorem mem_image (f : α → β) (s : set α) (y : β) :
y ∈ f '' s ↔ ∃ x, x ∈ s ∧ f x = y := iff.rfl
lemma image_eta (f : α → β) : f '' s = (λ x, f x) '' s := rfl
theorem mem_image_of_mem (f : α → β) {x : α} {a : set α} (h : x ∈ a) : f x ∈ f '' a :=
⟨_, h, rfl⟩
theorem mem_image_of_injective {f : α → β} {a : α} {s : set α} (hf : injective f) :
f a ∈ f '' s ↔ a ∈ s :=
iff.intro
(assume ⟨b, hb, eq⟩, (hf eq) ▸ hb)
(assume h, mem_image_of_mem _ h)
theorem ball_image_iff {f : α → β} {s : set α} {p : β → Prop} :
(∀ y ∈ f '' s, p y) ↔ (∀ x ∈ s, p (f x)) :=
by simp
theorem ball_image_of_ball {f : α → β} {s : set α} {p : β → Prop}
(h : ∀ x ∈ s, p (f x)) : ∀ y ∈ f '' s, p y :=
ball_image_iff.2 h
theorem bex_image_iff {f : α → β} {s : set α} {p : β → Prop} :
(∃ y ∈ f '' s, p y) ↔ (∃ x ∈ s, p (f x)) :=
by simp
theorem mem_image_elim {f : α → β} {s : set α} {C : β → Prop} (h : ∀ (x : α), x ∈ s → C (f x)) :
∀{y : β}, y ∈ f '' s → C y
| ._ ⟨a, a_in, rfl⟩ := h a a_in
theorem mem_image_elim_on {f : α → β} {s : set α} {C : β → Prop} {y : β} (h_y : y ∈ f '' s)
(h : ∀ (x : α), x ∈ s → C (f x)) : C y :=
mem_image_elim h h_y
@[congr] lemma image_congr {f g : α → β} {s : set α}
(h : ∀a∈s, f a = g a) : f '' s = g '' s :=
by safe [ext_iff, iff_def]
/-- A common special case of `image_congr` -/
lemma image_congr' {f g : α → β} {s : set α} (h : ∀ (x : α), f x = g x) : f '' s = g '' s :=
image_congr (λx _, h x)
theorem image_comp (f : β → γ) (g : α → β) (a : set α) : (f ∘ g) '' a = f '' (g '' a) :=
subset.antisymm
(ball_image_of_ball $ assume a ha, mem_image_of_mem _ $ mem_image_of_mem _ ha)
(ball_image_of_ball $ ball_image_of_ball $ assume a ha, mem_image_of_mem _ ha)
/-- A variant of `image_comp`, useful for rewriting -/
lemma image_image (g : β → γ) (f : α → β) (s : set α) : g '' (f '' s) = (λ x, g (f x)) '' s :=
(image_comp g f s).symm
/-- Image is monotone with respect to `⊆`. See `set.monotone_image` for the statement in
terms of `≤`. -/
theorem image_subset {a b : set α} (f : α → β) (h : a ⊆ b) : f '' a ⊆ f '' b :=
by finish [subset_def, mem_image_eq]
theorem image_union (f : α → β) (s t : set α) :
f '' (s ∪ t) = f '' s ∪ f '' t :=
by finish [ext_iff, iff_def, mem_image_eq]
@[simp] theorem image_empty (f : α → β) : f '' ∅ = ∅ := by { ext, simp }
lemma image_inter_subset (f : α → β) (s t : set α) :
f '' (s ∩ t) ⊆ f '' s ∩ f '' t :=
subset_inter (image_subset _ $ inter_subset_left _ _) (image_subset _ $ inter_subset_right _ _)
theorem image_inter_on {f : α → β} {s t : set α} (h : ∀x∈t, ∀y∈s, f x = f y → x = y) :
f '' s ∩ f '' t = f '' (s ∩ t) :=
subset.antisymm
(assume b ⟨⟨a₁, ha₁, h₁⟩, ⟨a₂, ha₂, h₂⟩⟩,
have a₂ = a₁, from h _ ha₂ _ ha₁ (by simp *),
⟨a₁, ⟨ha₁, this ▸ ha₂⟩, h₁⟩)
(image_inter_subset _ _ _)
theorem image_inter {f : α → β} {s t : set α} (H : injective f) :
f '' s ∩ f '' t = f '' (s ∩ t) :=
image_inter_on (assume x _ y _ h, H h)
theorem image_univ_of_surjective {ι : Type*} {f : ι → β} (H : surjective f) : f '' univ = univ :=
eq_univ_of_forall $ by { simpa [image] }
@[simp] theorem image_singleton {f : α → β} {a : α} : f '' {a} = {f a} :=
by { ext, simp [image, eq_comm] }
@[simp] theorem nonempty.image_const {s : set α} (hs : s.nonempty) (a : β) : (λ _, a) '' s = {a} :=
ext $ λ x, ⟨λ ⟨y, _, h⟩, h ▸ mem_singleton _,
λ h, (eq_of_mem_singleton h).symm ▸ hs.imp (λ y hy, ⟨hy, rfl⟩)⟩
@[simp] lemma image_eq_empty {α β} {f : α → β} {s : set α} : f '' s = ∅ ↔ s = ∅ :=
by { simp only [eq_empty_iff_forall_not_mem],
exact ⟨λ H a ha, H _ ⟨_, ha, rfl⟩, λ H b ⟨_, ha, _⟩, H _ ha⟩ }
-- TODO(Jeremy): there is an issue with - t unfolding to compl t
theorem mem_compl_image (t : set α) (S : set (set α)) :
t ∈ compl '' S ↔ tᶜ ∈ S :=
begin
suffices : ∀ x, xᶜ = t ↔ tᶜ = x, { simp [this] },
intro x, split; { intro e, subst e, simp }
end
/-- A variant of `image_id` -/
@[simp] lemma image_id' (s : set α) : (λx, x) '' s = s := by { ext, simp }
theorem image_id (s : set α) : id '' s = s := by simp
theorem compl_compl_image (S : set (set α)) :
compl '' (compl '' S) = S :=
by rw [← image_comp, compl_comp_compl, image_id]
theorem image_insert_eq {f : α → β} {a : α} {s : set α} :
f '' (insert a s) = insert (f a) (f '' s) :=
by { ext, simp [and_or_distrib_left, exists_or_distrib, eq_comm, or_comm, and_comm] }
theorem image_pair (f : α → β) (a b : α) : f '' {a, b} = {f a, f b} :=
by simp only [image_insert_eq, image_singleton]
theorem image_subset_preimage_of_inverse {f : α → β} {g : β → α}
(I : left_inverse g f) (s : set α) : f '' s ⊆ g ⁻¹' s :=
λ b ⟨a, h, e⟩, e ▸ ((I a).symm ▸ h : g (f a) ∈ s)
theorem preimage_subset_image_of_inverse {f : α → β} {g : β → α}
(I : left_inverse g f) (s : set β) : f ⁻¹' s ⊆ g '' s :=
λ b h, ⟨f b, h, I b⟩
theorem image_eq_preimage_of_inverse {f : α → β} {g : β → α}
(h₁ : left_inverse g f) (h₂ : right_inverse g f) :
image f = preimage g :=
funext $ λ s, subset.antisymm
(image_subset_preimage_of_inverse h₁ s)
(preimage_subset_image_of_inverse h₂ s)
theorem mem_image_iff_of_inverse {f : α → β} {g : β → α} {b : β} {s : set α}
(h₁ : left_inverse g f) (h₂ : right_inverse g f) :
b ∈ f '' s ↔ g b ∈ s :=
by rw image_eq_preimage_of_inverse h₁ h₂; refl
theorem image_compl_subset {f : α → β} {s : set α} (H : injective f) : f '' sᶜ ⊆ (f '' s)ᶜ :=
subset_compl_iff_disjoint.2 $ by simp [image_inter H]
theorem subset_image_compl {f : α → β} {s : set α} (H : surjective f) : (f '' s)ᶜ ⊆ f '' sᶜ :=
compl_subset_iff_union.2 $
by { rw ← image_union, simp [image_univ_of_surjective H] }
theorem image_compl_eq {f : α → β} {s : set α} (H : bijective f) : f '' sᶜ = (f '' s)ᶜ :=
subset.antisymm (image_compl_subset H.1) (subset_image_compl H.2)
theorem subset_image_diff (f : α → β) (s t : set α) :
f '' s \ f '' t ⊆ f '' (s \ t) :=
begin
rw [diff_subset_iff, ← image_union, union_diff_self],
exact image_subset f (subset_union_right t s)
end
theorem image_diff {f : α → β} (hf : injective f) (s t : set α) :
f '' (s \ t) = f '' s \ f '' t :=
subset.antisymm
(subset.trans (image_inter_subset _ _ _) $ inter_subset_inter_right _ $ image_compl_subset hf)
(subset_image_diff f s t)
lemma nonempty.image (f : α → β) {s : set α} : s.nonempty → (f '' s).nonempty
| ⟨x, hx⟩ := ⟨f x, mem_image_of_mem f hx⟩
lemma nonempty.of_image {f : α → β} {s : set α} : (f '' s).nonempty → s.nonempty
| ⟨y, x, hx, _⟩ := ⟨x, hx⟩
@[simp] lemma nonempty_image_iff {f : α → β} {s : set α} :
(f '' s).nonempty ↔ s.nonempty :=
⟨nonempty.of_image, λ h, h.image f⟩
/-- image and preimage are a Galois connection -/
@[simp] theorem image_subset_iff {s : set α} {t : set β} {f : α → β} :
f '' s ⊆ t ↔ s ⊆ f ⁻¹' t :=
ball_image_iff
theorem image_preimage_subset (f : α → β) (s : set β) :
f '' (f ⁻¹' s) ⊆ s :=
image_subset_iff.2 (subset.refl _)
theorem subset_preimage_image (f : α → β) (s : set α) :
s ⊆ f ⁻¹' (f '' s) :=
λ x, mem_image_of_mem f
theorem preimage_image_eq {f : α → β} (s : set α) (h : injective f) : f ⁻¹' (f '' s) = s :=
subset.antisymm
(λ x ⟨y, hy, e⟩, h e ▸ hy)
(subset_preimage_image f s)
theorem image_preimage_eq {f : α → β} {s : set β} (h : surjective f) : f '' (f ⁻¹' s) = s :=
subset.antisymm
(image_preimage_subset f s)
(λ x hx, let ⟨y, e⟩ := h x in ⟨y, (e.symm ▸ hx : f y ∈ s), e⟩)
lemma preimage_eq_preimage {f : β → α} (hf : surjective f) : f ⁻¹' s = preimage f t ↔ s = t :=
iff.intro
(assume eq, by rw [← @image_preimage_eq β α f s hf, ← @image_preimage_eq β α f t hf, eq])
(assume eq, eq ▸ rfl)
lemma image_inter_preimage (f : α → β) (s : set α) (t : set β) :
f '' (s ∩ f ⁻¹' t) = f '' s ∩ t :=
begin
apply subset.antisymm,
{ calc f '' (s ∩ f ⁻¹' t) ⊆ f '' s ∩ (f '' (f⁻¹' t)) : image_inter_subset _ _ _
... ⊆ f '' s ∩ t : inter_subset_inter_right _ (image_preimage_subset f t) },
{ rintros _ ⟨⟨x, h', rfl⟩, h⟩,
exact ⟨x, ⟨h', h⟩, rfl⟩ }
end
lemma image_preimage_inter (f : α → β) (s : set α) (t : set β) :
f '' (f ⁻¹' t ∩ s) = t ∩ f '' s :=
by simp only [inter_comm, image_inter_preimage]
@[simp] lemma image_inter_nonempty_iff {f : α → β} {s : set α} {t : set β} :
(f '' s ∩ t).nonempty ↔ (s ∩ f ⁻¹' t).nonempty :=
by rw [←image_inter_preimage, nonempty_image_iff]
lemma image_diff_preimage {f : α → β} {s : set α} {t : set β} : f '' (s \ f ⁻¹' t) = f '' s \ t :=
by simp_rw [diff_eq, ← preimage_compl, image_inter_preimage]
theorem compl_image : image (compl : set α → set α) = preimage compl :=
image_eq_preimage_of_inverse compl_compl compl_compl
theorem compl_image_set_of {p : set α → Prop} :
compl '' {s | p s} = {s | p sᶜ} :=
congr_fun compl_image p
theorem inter_preimage_subset (s : set α) (t : set β) (f : α → β) :
s ∩ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∩ t) :=
λ x h, ⟨mem_image_of_mem _ h.left, h.right⟩
theorem union_preimage_subset (s : set α) (t : set β) (f : α → β) :
s ∪ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∪ t) :=
λ x h, or.elim h (λ l, or.inl $ mem_image_of_mem _ l) (λ r, or.inr r)
theorem subset_image_union (f : α → β) (s : set α) (t : set β) :
f '' (s ∪ f ⁻¹' t) ⊆ f '' s ∪ t :=
image_subset_iff.2 (union_preimage_subset _ _ _)
lemma preimage_subset_iff {A : set α} {B : set β} {f : α → β} :
f⁻¹' B ⊆ A ↔ (∀ a : α, f a ∈ B → a ∈ A) := iff.rfl
lemma image_eq_image {f : α → β} (hf : injective f) : f '' s = f '' t ↔ s = t :=
iff.symm $ iff.intro (assume eq, eq ▸ rfl) $ assume eq,
by rw [← preimage_image_eq s hf, ← preimage_image_eq t hf, eq]
lemma image_subset_image_iff {f : α → β} (hf : injective f) : f '' s ⊆ f '' t ↔ s ⊆ t :=
begin
refine (iff.symm $ iff.intro (image_subset f) $ assume h, _),
rw [← preimage_image_eq s hf, ← preimage_image_eq t hf],
exact preimage_mono h
end
lemma prod_quotient_preimage_eq_image [s : setoid α] (g : quotient s → β) {h : α → β}
(Hh : h = g ∘ quotient.mk) (r : set (β × β)) :
{x : quotient s × quotient s | (g x.1, g x.2) ∈ r} =
(λ a : α × α, (⟦a.1⟧, ⟦a.2⟧)) '' ((λ a : α × α, (h a.1, h a.2)) ⁻¹' r) :=
Hh.symm ▸ set.ext (λ ⟨a₁, a₂⟩, ⟨quotient.induction_on₂ a₁ a₂
(λ a₁ a₂ h, ⟨(a₁, a₂), h, rfl⟩),
λ ⟨⟨b₁, b₂⟩, h₁, h₂⟩, show (g a₁, g a₂) ∈ r, from
have h₃ : ⟦b₁⟧ = a₁ ∧ ⟦b₂⟧ = a₂ := prod.ext_iff.1 h₂,
h₃.1 ▸ h₃.2 ▸ h₁⟩)
/-- Restriction of `f` to `s` factors through `s.image_factorization f : s → f '' s`. -/
def image_factorization (f : α → β) (s : set α) : s → f '' s :=
λ p, ⟨f p.1, mem_image_of_mem f p.2⟩
lemma image_factorization_eq {f : α → β} {s : set α} :
subtype.val ∘ image_factorization f s = f ∘ subtype.val :=
funext $ λ p, rfl
lemma surjective_onto_image {f : α → β} {s : set α} :
surjective (image_factorization f s) :=
λ ⟨_, ⟨a, ha, rfl⟩⟩, ⟨⟨a, ha⟩, rfl⟩
end image
/-! ### Subsingleton -/
/-- A set `s` is a `subsingleton`, if it has at most one element. -/
protected def subsingleton (s : set α) : Prop :=
∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), x = y
lemma subsingleton.mono (ht : t.subsingleton) (hst : s ⊆ t) : s.subsingleton :=
λ x hx y hy, ht (hst hx) (hst hy)
lemma subsingleton.image (hs : s.subsingleton) (f : α → β) : (f '' s).subsingleton :=
λ _ ⟨x, hx, Hx⟩ _ ⟨y, hy, Hy⟩, Hx ▸ Hy ▸ congr_arg f (hs hx hy)
lemma subsingleton.eq_singleton_of_mem (hs : s.subsingleton) {x:α} (hx : x ∈ s) :
s = {x} :=
ext $ λ y, ⟨λ hy, (hs hx hy) ▸ mem_singleton _, λ hy, (eq_of_mem_singleton hy).symm ▸ hx⟩
lemma subsingleton_empty : (∅ : set α).subsingleton := λ x, false.elim
lemma subsingleton_singleton {a} : ({a} : set α).subsingleton :=
λ x hx y hy, (eq_of_mem_singleton hx).symm ▸ (eq_of_mem_singleton hy).symm ▸ rfl
lemma subsingleton.eq_empty_or_singleton (hs : s.subsingleton) :
s = ∅ ∨ ∃ x, s = {x} :=
s.eq_empty_or_nonempty.elim or.inl (λ ⟨x, hx⟩, or.inr ⟨x, hs.eq_singleton_of_mem hx⟩)
lemma subsingleton_univ [subsingleton α] : (univ : set α).subsingleton :=
λ x hx y hy, subsingleton.elim x y
/-- `s`, coerced to a type, is a subsingleton type if and only if `s`
is a subsingleton set. -/
@[simp, norm_cast] lemma subsingleton_coe (s : set α) : subsingleton s ↔ s.subsingleton :=
begin
split,
{ refine λ h, (λ a ha b hb, _),
exact set_coe.ext_iff.2 (@subsingleton.elim s h ⟨a, ha⟩ ⟨b, hb⟩) },
{ exact λ h, subsingleton.intro (λ a b, set_coe.ext (h a.property b.property)) }
end
theorem univ_eq_true_false : univ = ({true, false} : set Prop) :=
eq.symm $ eq_univ_of_forall $ classical.cases (by simp) (by simp)
/-! ### Lemmas about range of a function. -/
section range
variables {f : ι → α}
open function
/-- Range of a function.
This function is more flexible than `f '' univ`, as the image requires that the domain is in Type
and not an arbitrary Sort. -/
def range (f : ι → α) : set α := {x | ∃y, f y = x}
@[simp] theorem mem_range {x : α} : x ∈ range f ↔ ∃ y, f y = x := iff.rfl
@[simp] theorem mem_range_self (i : ι) : f i ∈ range f := ⟨i, rfl⟩
theorem forall_range_iff {p : α → Prop} : (∀ a ∈ range f, p a) ↔ (∀ i, p (f i)) :=
by simp
theorem exists_range_iff {p : α → Prop} : (∃ a ∈ range f, p a) ↔ (∃ i, p (f i)) :=
by simp
lemma exists_range_iff' {p : α → Prop} :
(∃ a, a ∈ range f ∧ p a) ↔ ∃ i, p (f i) :=
by simpa only [exists_prop] using exists_range_iff
theorem range_iff_surjective : range f = univ ↔ surjective f :=
eq_univ_iff_forall
alias range_iff_surjective ↔ _ function.surjective.range_eq
@[simp] theorem range_id : range (@id α) = univ := range_iff_surjective.2 surjective_id
theorem is_compl_range_inl_range_inr : is_compl (range $ @sum.inl α β) (range sum.inr) :=
⟨by { rintro y ⟨⟨x₁, rfl⟩, ⟨x₂, _⟩⟩, cc },
by { rintro (x|y) -; [left, right]; exact mem_range_self _ }⟩
@[simp] theorem range_inl_union_range_inr : range (sum.inl : α → α ⊕ β) ∪ range sum.inr = univ :=
is_compl_range_inl_range_inr.sup_eq_top
@[simp] theorem range_inl_inter_range_inr : range (sum.inl : α → α ⊕ β) ∩ range sum.inr = ∅ :=
is_compl_range_inl_range_inr.inf_eq_bot
@[simp] theorem range_inr_union_range_inl : range (sum.inr : β → α ⊕ β) ∪ range sum.inl = univ :=
is_compl_range_inl_range_inr.symm.sup_eq_top
@[simp] theorem range_inr_inter_range_inl : range (sum.inr : β → α ⊕ β) ∩ range sum.inl = ∅ :=
is_compl_range_inl_range_inr.symm.inf_eq_bot
@[simp] theorem preimage_inl_range_inr : sum.inl ⁻¹' range (sum.inr : β → α ⊕ β) = ∅ :=
by { ext, simp }
@[simp] theorem preimage_inr_range_inl : sum.inr ⁻¹' range (sum.inl : α → α ⊕ β) = ∅ :=
by { ext, simp }
@[simp] theorem range_quot_mk (r : α → α → Prop) : range (quot.mk r) = univ :=
(surjective_quot_mk r).range_eq
@[simp] theorem image_univ {ι : Type*} {f : ι → β} : f '' univ = range f :=
by { ext, simp [image, range] }
theorem image_subset_range {ι : Type*} (f : ι → β) (s : set ι) : f '' s ⊆ range f :=
by rw ← image_univ; exact image_subset _ (subset_univ _)
theorem range_comp (g : α → β) (f : ι → α) : range (g ∘ f) = g '' range f :=
subset.antisymm
(forall_range_iff.mpr $ assume i, mem_image_of_mem g (mem_range_self _))
(ball_image_iff.mpr $ forall_range_iff.mpr mem_range_self)
theorem range_subset_iff {s : set α} : range f ⊆ s ↔ ∀ y, f y ∈ s :=
forall_range_iff
lemma range_comp_subset_range (f : α → β) (g : β → γ) : range (g ∘ f) ⊆ range g :=
by rw range_comp; apply image_subset_range
lemma range_nonempty_iff_nonempty : (range f).nonempty ↔ nonempty ι :=
⟨λ ⟨y, x, hxy⟩, ⟨x⟩, λ ⟨x⟩, ⟨f x, mem_range_self x⟩⟩
lemma range_nonempty [h : nonempty ι] (f : ι → α) : (range f).nonempty :=
range_nonempty_iff_nonempty.2 h
@[simp] lemma range_eq_empty {f : ι → α} : range f = ∅ ↔ ¬ nonempty ι :=
not_nonempty_iff_eq_empty.symm.trans $ not_congr range_nonempty_iff_nonempty
@[simp] lemma image_union_image_compl_eq_range (f : α → β) :
(f '' s) ∪ (f '' sᶜ) = range f :=
by rw [← image_union, ← image_univ, ← union_compl_self]
theorem image_preimage_eq_inter_range {f : α → β} {t : set β} :
f '' (f ⁻¹' t) = t ∩ range f :=
ext $ assume x, ⟨assume ⟨x, hx, heq⟩, heq ▸ ⟨hx, mem_range_self _⟩,
assume ⟨hx, ⟨y, h_eq⟩⟩, h_eq ▸ mem_image_of_mem f $
show y ∈ f ⁻¹' t, by simp [preimage, h_eq, hx]⟩
lemma image_preimage_eq_of_subset {f : α → β} {s : set β} (hs : s ⊆ range f) :
f '' (f ⁻¹' s) = s :=
by rw [image_preimage_eq_inter_range, inter_eq_self_of_subset_left hs]
lemma image_preimage_eq_iff {f : α → β} {s : set β} : f '' (f ⁻¹' s) = s ↔ s ⊆ range f :=
⟨by { intro h, rw [← h], apply image_subset_range }, image_preimage_eq_of_subset⟩
lemma preimage_subset_preimage_iff {s t : set α} {f : β → α} (hs : s ⊆ range f) :
f ⁻¹' s ⊆ f ⁻¹' t ↔ s ⊆ t :=
begin
split,
{ intros h x hx, rcases hs hx with ⟨y, rfl⟩, exact h hx },
intros h x, apply h
end
lemma preimage_eq_preimage' {s t : set α} {f : β → α} (hs : s ⊆ range f) (ht : t ⊆ range f) :
f ⁻¹' s = f ⁻¹' t ↔ s = t :=
begin
split,
{ intro h, apply subset.antisymm, rw [←preimage_subset_preimage_iff hs, h],
rw [←preimage_subset_preimage_iff ht, h] },
rintro rfl, refl
end
@[simp] theorem preimage_inter_range {f : α → β} {s : set β} : f ⁻¹' (s ∩ range f) = f ⁻¹' s :=
set.ext $ λ x, and_iff_left ⟨x, rfl⟩
@[simp] theorem preimage_range_inter {f : α → β} {s : set β} : f ⁻¹' (range f ∩ s) = f ⁻¹' s :=
by rw [inter_comm, preimage_inter_range]
theorem preimage_image_preimage {f : α → β} {s : set β} :
f ⁻¹' (f '' (f ⁻¹' s)) = f ⁻¹' s :=
by rw [image_preimage_eq_inter_range, preimage_inter_range]
@[simp] theorem quot_mk_range_eq [setoid α] : range (λx : α, ⟦x⟧) = univ :=
range_iff_surjective.2 quot.exists_rep
lemma range_const_subset {c : α} : range (λx:ι, c) ⊆ {c} :=
range_subset_iff.2 $ λ x, rfl
@[simp] lemma range_const : ∀ [nonempty ι] {c : α}, range (λx:ι, c) = {c}
| ⟨x⟩ c := subset.antisymm range_const_subset $
assume y hy, (mem_singleton_iff.1 hy).symm ▸ mem_range_self x
lemma diagonal_eq_range {α : Type*} : diagonal α = range (λ x, (x, x)) :=
by { ext ⟨x, y⟩, simp [diagonal, eq_comm] }
theorem preimage_singleton_nonempty {f : α → β} {y : β} :
(f ⁻¹' {y}).nonempty ↔ y ∈ range f :=
iff.rfl
theorem preimage_singleton_eq_empty {f : α → β} {y : β} :
f ⁻¹' {y} = ∅ ↔ y ∉ range f :=
not_nonempty_iff_eq_empty.symm.trans $ not_congr preimage_singleton_nonempty
lemma range_subset_singleton {f : ι → α} {x : α} : range f ⊆ {x} ↔ f = const ι x :=
by simp [range_subset_iff, funext_iff, mem_singleton]
lemma image_compl_preimage {f : α → β} {s : set β} : f '' ((f ⁻¹' s)ᶜ) = range f \ s :=
by rw [compl_eq_univ_diff, image_diff_preimage, image_univ]
@[simp] theorem range_sigma_mk {β : α → Type*} (a : α) :
range (sigma.mk a : β a → Σ a, β a) = sigma.fst ⁻¹' {a} :=
begin
apply subset.antisymm,
{ rintros _ ⟨b, rfl⟩, simp },
{ rintros ⟨x, y⟩ (rfl|_),
exact mem_range_self y }
end
/-- Any map `f : ι → β` factors through a map `range_factorization f : ι → range f`. -/
def range_factorization (f : ι → β) : ι → range f :=
λ i, ⟨f i, mem_range_self i⟩
lemma range_factorization_eq {f : ι → β} :
subtype.val ∘ range_factorization f = f :=
funext $ λ i, rfl
lemma surjective_onto_range : surjective (range_factorization f) :=
λ ⟨_, ⟨i, rfl⟩⟩, ⟨i, rfl⟩
lemma image_eq_range (f : α → β) (s : set α) : f '' s = range (λ(x : s), f x) :=
by { ext, split, rintro ⟨x, h1, h2⟩, exact ⟨⟨x, h1⟩, h2⟩, rintro ⟨⟨x, h1⟩, h2⟩, exact ⟨x, h1, h2⟩ }
@[simp] lemma sum.elim_range {α β γ : Type*} (f : α → γ) (g : β → γ) :
range (sum.elim f g) = range f ∪ range g :=
by simp [set.ext_iff, mem_range]
lemma range_ite_subset' {p : Prop} [decidable p] {f g : α → β} :
range (if p then f else g) ⊆ range f ∪ range g :=
begin
by_cases h : p, {rw if_pos h, exact subset_union_left _ _},
{rw if_neg h, exact subset_union_right _ _}
end
lemma range_ite_subset {p : α → Prop} [decidable_pred p] {f g : α → β} :
range (λ x, if p x then f x else g x) ⊆ range f ∪ range g :=
begin
rw range_subset_iff, intro x, by_cases h : p x,
simp [if_pos h, mem_union, mem_range_self],
simp [if_neg h, mem_union, mem_range_self]
end
@[simp] lemma preimage_range (f : α → β) : f ⁻¹' (range f) = univ :=
eq_univ_of_forall mem_range_self
/-- The range of a function from a `unique` type contains just the
function applied to its single value. -/
lemma range_unique [h : unique ι] : range f = {f $ default ι} :=
begin
ext x,
rw mem_range,
split,
{ rintros ⟨i, hi⟩,
rw h.uniq i at hi,
exact hi ▸ mem_singleton _ },
{ exact λ h, ⟨default ι, h.symm⟩ }
end
lemma range_diff_image_subset (f : α → β) (s : set α) :
range f \ f '' s ⊆ f '' sᶜ :=
λ y ⟨⟨x, h₁⟩, h₂⟩, ⟨x, λ h, h₂ ⟨x, h, h₁⟩, h₁⟩
lemma range_diff_image {f : α → β} (H : injective f) (s : set α) :
range f \ f '' s = f '' sᶜ :=
subset.antisymm (range_diff_image_subset f s) $ λ y ⟨x, hx, hy⟩, hy ▸
⟨mem_range_self _, λ ⟨x', hx', eq⟩, hx $ H eq ▸ hx'⟩
end range
/-- The set `s` is pairwise `r` if `r x y` for all *distinct* `x y ∈ s`. -/
def pairwise_on (s : set α) (r : α → α → Prop) := ∀ x ∈ s, ∀ y ∈ s, x ≠ y → r x y
theorem pairwise_on.mono {s t : set α} {r}
(h : t ⊆ s) (hp : pairwise_on s r) : pairwise_on t r :=
λ x xt y yt, hp x (h xt) y (h yt)
theorem pairwise_on.mono' {s : set α} {r r' : α → α → Prop}
(H : ∀ a b, r a b → r' a b) (hp : pairwise_on s r) : pairwise_on s r' :=
λ x xs y ys h, H _ _ (hp x xs y ys h)
/-- If and only if `f` takes pairwise equal values on `s`, there is
some value it takes everywhere on `s`. -/
lemma pairwise_on_eq_iff_exists_eq [nonempty β] (s : set α) (f : α → β) :
(pairwise_on s (λ x y, f x = f y)) ↔ ∃ z, ∀ x ∈ s, f x = z :=
begin
split,
{ intro h,
rcases eq_empty_or_nonempty s with rfl | ⟨x, hx⟩,
{ exact ⟨classical.arbitrary β, λ x hx, false.elim hx⟩ },
{ use f x,
intros y hy,
by_cases hyx : y = x,
{ rw hyx },
{ exact h y hy x hx hyx } } },
{ rintros ⟨z, hz⟩ x hx y hy hne,
rw [hz x hx, hz y hy] }
end
end set
open set
namespace function
variables {ι : Sort*} {α : Type*} {β : Type*} {f : α → β}
lemma surjective.preimage_injective (hf : surjective f) : injective (preimage f) :=
assume s t, (preimage_eq_preimage hf).1
lemma injective.preimage_surjective (hf : injective f) : surjective (preimage f) :=
by { intro s, use f '' s, rw preimage_image_eq _ hf }
lemma surjective.image_surjective (hf : surjective f) : surjective (image f) :=
by { intro s, use f ⁻¹' s, rw image_preimage_eq hf }
lemma injective.image_injective (hf : injective f) : injective (image f) :=
by { intros s t h, rw [←preimage_image_eq s hf, ←preimage_image_eq t hf, h] }
lemma surjective.preimage_subset_preimage_iff {s t : set β} (hf : surjective f) :
f ⁻¹' s ⊆ f ⁻¹' t ↔ s ⊆ t :=
by { apply preimage_subset_preimage_iff, rw [hf.range_eq], apply subset_univ }
lemma surjective.range_comp {ι' : Sort*} {f : ι → ι'} (hf : surjective f) (g : ι' → α) :
range (g ∘ f) = range g :=
ext $ λ y, (@surjective.exists _ _ _ hf (λ x, g x = y)).symm
lemma injective.nonempty_apply_iff {f : set α → set β} (hf : injective f)
(h2 : f ∅ = ∅) {s : set α} : (f s).nonempty ↔ s.nonempty :=
by rw [← ne_empty_iff_nonempty, ← h2, ← ne_empty_iff_nonempty, hf.ne_iff]
end function
open function
/-! ### Image and preimage on subtypes -/
namespace subtype
variable {α : Type*}
lemma coe_image {p : α → Prop} {s : set (subtype p)} :
coe '' s = {x | ∃h : p x, (⟨x, h⟩ : subtype p) ∈ s} :=
set.ext $ assume a,
⟨assume ⟨⟨a', ha'⟩, in_s, h_eq⟩, h_eq ▸ ⟨ha', in_s⟩,
assume ⟨ha, in_s⟩, ⟨⟨a, ha⟩, in_s, rfl⟩⟩
lemma range_coe {s : set α} :
range (coe : s → α) = s :=
by { rw ← set.image_univ, simp [-set.image_univ, coe_image] }
/-- A variant of `range_coe`. Try to use `range_coe` if possible.
This version is useful when defining a new type that is defined as the subtype of something.
In that case, the coercion doesn't fire anymore. -/
lemma range_val {s : set α} :
range (subtype.val : s → α) = s :=
range_coe
/-- We make this the simp lemma instead of `range_coe`. The reason is that if we write
for `s : set α` the function `coe : s → α`, then the inferred implicit arguments of `coe` are
`coe α (λ x, x ∈ s)`. -/
@[simp] lemma range_coe_subtype {p : α → Prop} :
range (coe : subtype p → α) = {x | p x} :=
range_coe
@[simp] lemma coe_preimage_self (s : set α) : (coe : s → α) ⁻¹' s = univ :=
by rw [← preimage_range (coe : s → α), range_coe]
lemma range_val_subtype {p : α → Prop} :
range (subtype.val : subtype p → α) = {x | p x} :=
range_coe
theorem coe_image_subset (s : set α) (t : set s) : coe '' t ⊆ s :=
λ x ⟨y, yt, yvaleq⟩, by rw ←yvaleq; exact y.property
theorem coe_image_univ (s : set α) : (coe : s → α) '' set.univ = s :=
image_univ.trans range_coe
@[simp] theorem image_preimage_coe (s t : set α) :
(coe : s → α) '' (coe ⁻¹' t) = t ∩ s :=
image_preimage_eq_inter_range.trans $ congr_arg _ range_coe
theorem image_preimage_val (s t : set α) :
(subtype.val : s → α) '' (subtype.val ⁻¹' t) = t ∩ s :=
image_preimage_coe s t
theorem preimage_coe_eq_preimage_coe_iff {s t u : set α} :
((coe : s → α) ⁻¹' t = coe ⁻¹' u) ↔ t ∩ s = u ∩ s :=
begin
rw [←image_preimage_coe, ←image_preimage_coe],
split, { intro h, rw h },
intro h, exact coe_injective.image_injective h
end
theorem preimage_val_eq_preimage_val_iff (s t u : set α) :
((subtype.val : s → α) ⁻¹' t = subtype.val ⁻¹' u) ↔ (t ∩ s = u ∩ s) :=
preimage_coe_eq_preimage_coe_iff
lemma exists_set_subtype {t : set α} (p : set α → Prop) :
(∃(s : set t), p (coe '' s)) ↔ ∃(s : set α), s ⊆ t ∧ p s :=
begin
split,
{ rintro ⟨s, hs⟩, refine ⟨coe '' s, _, hs⟩,
convert image_subset_range _ _, rw [range_coe] },
rintro ⟨s, hs₁, hs₂⟩, refine ⟨coe ⁻¹' s, _⟩,
rw [image_preimage_eq_of_subset], exact hs₂, rw [range_coe], exact hs₁
end
lemma preimage_coe_nonempty {s t : set α} : ((coe : s → α) ⁻¹' t).nonempty ↔ (s ∩ t).nonempty :=
by rw [inter_comm, ← image_preimage_coe, nonempty_image_iff]
lemma preimage_coe_eq_empty {s t : set α} : (coe : s → α) ⁻¹' t = ∅ ↔ s ∩ t = ∅ :=
by simp only [← not_nonempty_iff_eq_empty, preimage_coe_nonempty]
@[simp] lemma preimage_coe_compl (s : set α) : (coe : s → α) ⁻¹' sᶜ = ∅ :=
preimage_coe_eq_empty.2 (inter_compl_self s)
@[simp] lemma preimage_coe_compl' (s : set α) : (coe : sᶜ → α) ⁻¹' s = ∅ :=
preimage_coe_eq_empty.2 (compl_inter_self s)
end subtype
namespace set
/-! ### Lemmas about cartesian product of sets -/
section prod
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
variables {s s₁ s₂ : set α} {t t₁ t₂ : set β}
/-- The cartesian product `prod s t` is the set of `(a, b)`
such that `a ∈ s` and `b ∈ t`. -/
protected def prod (s : set α) (t : set β) : set (α × β) :=
{p | p.1 ∈ s ∧ p.2 ∈ t}
lemma prod_eq (s : set α) (t : set β) : s.prod t = prod.fst ⁻¹' s ∩ prod.snd ⁻¹' t := rfl
theorem mem_prod_eq {p : α × β} : p ∈ s.prod t = (p.1 ∈ s ∧ p.2 ∈ t) := rfl
@[simp] theorem mem_prod {p : α × β} : p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl
@[simp] theorem prod_mk_mem_set_prod_eq {a : α} {b : β} :
(a, b) ∈ s.prod t = (a ∈ s ∧ b ∈ t) := rfl
lemma mk_mem_prod {a : α} {b : β} (a_in : a ∈ s) (b_in : b ∈ t) : (a, b) ∈ s.prod t :=
⟨a_in, b_in⟩
theorem prod_mono {s₁ s₂ : set α} {t₁ t₂ : set β} (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) :
s₁.prod t₁ ⊆ s₂.prod t₂ :=
assume x ⟨h₁, h₂⟩, ⟨hs h₁, ht h₂⟩
lemma prod_subset_iff {P : set (α × β)} :
(s.prod t ⊆ P) ↔ ∀ (x ∈ s) (y ∈ t), (x, y) ∈ P :=
⟨λ h _ xin _ yin, h (mk_mem_prod xin yin), λ h ⟨_, _⟩ pin, h _ pin.1 _ pin.2⟩
lemma forall_prod_set {p : α × β → Prop} :
(∀ x ∈ s.prod t, p x) ↔ ∀ (x ∈ s) (y ∈ t), p (x, y) :=
prod_subset_iff
lemma exists_prod_set {p : α × β → Prop} :
(∃ x ∈ s.prod t, p x) ↔ ∃ (x ∈ s) (y ∈ t), p (x, y) :=
by simp [and_assoc]
@[simp] theorem prod_empty : s.prod ∅ = (∅ : set (α × β)) :=
by { ext, simp }
@[simp] theorem empty_prod : set.prod ∅ t = (∅ : set (α × β)) :=
by { ext, simp }
@[simp] theorem univ_prod_univ : (@univ α).prod (@univ β) = univ :=
by { ext ⟨x, y⟩, simp }
lemma univ_prod {t : set β} : set.prod (univ : set α) t = prod.snd ⁻¹' t :=
by simp [prod_eq]
lemma prod_univ {s : set α} : set.prod s (univ : set β) = prod.fst ⁻¹' s :=
by simp [prod_eq]
@[simp] theorem singleton_prod {a : α} : set.prod {a} t = prod.mk a '' t :=
by { ext ⟨x, y⟩, simp [and.left_comm, eq_comm] }
@[simp] theorem prod_singleton {b : β} : s.prod {b} = (λ a, (a, b)) '' s :=
by { ext ⟨x, y⟩, simp [and.left_comm, eq_comm] }
theorem singleton_prod_singleton {a : α} {b : β} : set.prod {a} {b} = ({(a, b)} : set (α × β)) :=
by simp
@[simp] theorem union_prod : (s₁ ∪ s₂).prod t = s₁.prod t ∪ s₂.prod t :=
by { ext ⟨x, y⟩, simp [or_and_distrib_right] }
@[simp] theorem prod_union : s.prod (t₁ ∪ t₂) = s.prod t₁ ∪ s.prod t₂ :=
by { ext ⟨x, y⟩, simp [and_or_distrib_left] }
theorem prod_inter_prod : s₁.prod t₁ ∩ s₂.prod t₂ = (s₁ ∩ s₂).prod (t₁ ∩ t₂) :=
by { ext ⟨x, y⟩, simp [and_assoc, and.left_comm] }
theorem insert_prod {a : α} : (insert a s).prod t = (prod.mk a '' t) ∪ s.prod t :=
by { ext ⟨x, y⟩, simp [image, iff_def, or_imp_distrib, imp.swap] {contextual := tt} }
theorem prod_insert {b : β} : s.prod (insert b t) = ((λa, (a, b)) '' s) ∪ s.prod t :=
by { ext ⟨x, y⟩, simp [image, iff_def, or_imp_distrib, imp.swap] {contextual := tt} }
theorem prod_preimage_eq {f : γ → α} {g : δ → β} :
(preimage f s).prod (preimage g t) = preimage (λp, (f p.1, g p.2)) (s.prod t) := rfl
@[simp] lemma mk_preimage_prod_left {y : β} (h : y ∈ t) : (λ x, (x, y)) ⁻¹' s.prod t = s :=
by { ext x, simp [h] }
@[simp] lemma mk_preimage_prod_right {x : α} (h : x ∈ s) : prod.mk x ⁻¹' s.prod t = t :=
by { ext y, simp [h] }
@[simp] lemma mk_preimage_prod_left_eq_empty {y : β} (hy : y ∉ t) :
(λ x, (x, y)) ⁻¹' s.prod t = ∅ :=
by { ext z, simp [hy] }
@[simp] lemma mk_preimage_prod_right_eq_empty {x : α} (hx : x ∉ s) :
prod.mk x ⁻¹' s.prod t = ∅ :=
by { ext z, simp [hx] }
lemma mk_preimage_prod_left_eq_if {y : β} [decidable_pred (∈ t)] :
(λ x, (x, y)) ⁻¹' s.prod t = if y ∈ t then s else ∅ :=
by { split_ifs; simp [h] }
lemma mk_preimage_prod_right_eq_if {x : α} [decidable_pred (∈ s)] :
prod.mk x ⁻¹' s.prod t = if x ∈ s then t else ∅ :=
by { split_ifs; simp [h] }
theorem image_swap_eq_preimage_swap : image (@prod.swap α β) = preimage prod.swap :=
image_eq_preimage_of_inverse prod.swap_left_inverse prod.swap_right_inverse
theorem preimage_swap_prod {s : set α} {t : set β} : prod.swap ⁻¹' t.prod s = s.prod t :=
by { ext ⟨x, y⟩, simp [and_comm] }
theorem image_swap_prod : prod.swap '' t.prod s = s.prod t :=
by rw [image_swap_eq_preimage_swap, preimage_swap_prod]
theorem prod_image_image_eq {m₁ : α → γ} {m₂ : β → δ} :
(image m₁ s).prod (image m₂ t) = image (λp:α×β, (m₁ p.1, m₂ p.2)) (s.prod t) :=
ext $ by simp [-exists_and_distrib_right, exists_and_distrib_right.symm, and.left_comm,
and.assoc, and.comm]
theorem prod_range_range_eq {α β γ δ} {m₁ : α → γ} {m₂ : β → δ} :
(range m₁).prod (range m₂) = range (λp:α×β, (m₁ p.1, m₂ p.2)) :=
ext $ by simp [range]
theorem prod_range_univ_eq {α β γ} {m₁ : α → γ} :
(range m₁).prod (univ : set β) = range (λp:α×β, (m₁ p.1, p.2)) :=
ext $ by simp [range]
theorem prod_univ_range_eq {α β δ} {m₂ : β → δ} :
(univ : set α).prod (range m₂) = range (λp:α×β, (p.1, m₂ p.2)) :=
ext $ by simp [range]
theorem nonempty.prod : s.nonempty → t.nonempty → (s.prod t).nonempty
| ⟨x, hx⟩ ⟨y, hy⟩ := ⟨(x, y), ⟨hx, hy⟩⟩
theorem nonempty.fst : (s.prod t).nonempty → s.nonempty
| ⟨p, hp⟩ := ⟨p.1, hp.1⟩
theorem nonempty.snd : (s.prod t).nonempty → t.nonempty
| ⟨p, hp⟩ := ⟨p.2, hp.2⟩
theorem prod_nonempty_iff : (s.prod t).nonempty ↔ s.nonempty ∧ t.nonempty :=
⟨λ h, ⟨h.fst, h.snd⟩, λ h, nonempty.prod h.1 h.2⟩
theorem prod_eq_empty_iff :
s.prod t = ∅ ↔ (s = ∅ ∨ t = ∅) :=
by simp only [not_nonempty_iff_eq_empty.symm, prod_nonempty_iff, not_and_distrib]
lemma prod_sub_preimage_iff {W : set γ} {f : α × β → γ} :
s.prod t ⊆ f ⁻¹' W ↔ ∀ a b, a ∈ s → b ∈ t → f (a, b) ∈ W :=
by simp [subset_def]
lemma fst_image_prod_subset (s : set α) (t : set β) :
prod.fst '' (s.prod t) ⊆ s :=
λ _ h, let ⟨_, ⟨h₂, _⟩, h₁⟩ := (set.mem_image _ _ _).1 h in h₁ ▸ h₂
lemma prod_subset_preimage_fst (s : set α) (t : set β) :
s.prod t ⊆ prod.fst ⁻¹' s :=
image_subset_iff.1 (fst_image_prod_subset s t)
lemma fst_image_prod (s : set β) {t : set α} (ht : t.nonempty) :
prod.fst '' (s.prod t) = s :=
set.subset.antisymm (fst_image_prod_subset _ _)
$ λ y y_in, let ⟨x, x_in⟩ := ht in
⟨(y, x), ⟨y_in, x_in⟩, rfl⟩
lemma snd_image_prod_subset (s : set α) (t : set β) :
prod.snd '' (s.prod t) ⊆ t :=
λ _ h, let ⟨_, ⟨_, h₂⟩, h₁⟩ := (set.mem_image _ _ _).1 h in h₁ ▸ h₂
lemma prod_subset_preimage_snd (s : set α) (t : set β) :
s.prod t ⊆ prod.snd ⁻¹' t :=
image_subset_iff.1 (snd_image_prod_subset s t)
lemma snd_image_prod {s : set α} (hs : s.nonempty) (t : set β) :
prod.snd '' (s.prod t) = t :=
set.subset.antisymm (snd_image_prod_subset _ _)
$ λ y y_in, let ⟨x, x_in⟩ := hs in
⟨(x, y), ⟨x_in, y_in⟩, rfl⟩
/-- A product set is included in a product set if and only factors are included, or a factor of the
first set is empty. -/
lemma prod_subset_prod_iff :
(s.prod t ⊆ s₁.prod t₁) ↔ (s ⊆ s₁ ∧ t ⊆ t₁) ∨ (s = ∅) ∨ (t = ∅) :=
begin
classical,
cases (s.prod t).eq_empty_or_nonempty with h h,
{ simp [h, prod_eq_empty_iff.1 h] },
{ have st : s.nonempty ∧ t.nonempty, by rwa [prod_nonempty_iff] at h,
split,
{ assume H : s.prod t ⊆ s₁.prod t₁,
have h' : s₁.nonempty ∧ t₁.nonempty := prod_nonempty_iff.1 (h.mono H),
refine or.inl ⟨_, _⟩,
show s ⊆ s₁,
{ have := image_subset (prod.fst : α × β → α) H,
rwa [fst_image_prod _ st.2, fst_image_prod _ h'.2] at this },
show t ⊆ t₁,
{ have := image_subset (prod.snd : α × β → β) H,
rwa [snd_image_prod st.1, snd_image_prod h'.1] at this } },
{ assume H,
simp only [st.1.ne_empty, st.2.ne_empty, or_false] at H,
exact prod_mono H.1 H.2 } }
end
end prod
/-! ### Lemmas about set-indexed products of sets -/
section pi
variables {ι : Type*} {α : ι → Type*} {s : set ι} {t t₁ t₂ : Π i, set (α i)}
/-- Given an index set `i` and a family of sets `s : Π i, set (α i)`, `pi i s`
is the set of dependent functions `f : Πa, π a` such that `f a` belongs to `π a`
whenever `a ∈ i`. -/
def pi (s : set ι) (t : Π i, set (α i)) : set (Π i, α i) := { f | ∀i ∈ s, f i ∈ t i }
@[simp] lemma mem_pi {f : Π i, α i} : f ∈ s.pi t ↔ ∀ i ∈ s, f i ∈ t i :=
by refl
@[simp] lemma mem_univ_pi {f : Π i, α i} : f ∈ pi univ t ↔ ∀ i, f i ∈ t i :=
by simp
@[simp] lemma empty_pi (s : Π i, set (α i)) : pi ∅ s = univ := by { ext, simp [pi] }
lemma pi_mono (h : ∀ i ∈ s, t₁ i ⊆ t₂ i) : pi s t₁ ⊆ pi s t₂ :=
λ x hx i hi, (h i hi $ hx i hi)
lemma pi_eq_empty {i : ι} (hs : i ∈ s) (ht : t i = ∅) : s.pi t = ∅ :=
by { ext f, simp only [mem_empty_eq, not_forall, iff_false, mem_pi, not_imp],
exact ⟨i, hs, by simp [ht]⟩ }
lemma univ_pi_eq_empty {i : ι} (ht : t i = ∅) : pi univ t = ∅ :=
pi_eq_empty (mem_univ i) ht
lemma pi_nonempty_iff : (s.pi t).nonempty ↔ ∀ i, ∃ x, i ∈ s → x ∈ t i :=
by simp [classical.skolem, set.nonempty]
lemma univ_pi_nonempty_iff : (pi univ t).nonempty ↔ ∀ i, (t i).nonempty :=
by simp [classical.skolem, set.nonempty]
lemma pi_eq_empty_iff : s.pi t = ∅ ↔ ∃ i, (α i → false) ∨ (i ∈ s ∧ t i = ∅) :=
begin
rw [← not_nonempty_iff_eq_empty, pi_nonempty_iff], push_neg, apply exists_congr, intro i,
split,
{ intro h, by_cases hα : nonempty (α i),
{ cases hα with x, refine or.inr ⟨(h x).1, by simp [eq_empty_iff_forall_not_mem, h]⟩ },
{ exact or.inl (λ x, hα ⟨x⟩) }},
{ rintro (h|h) x, exfalso, exact h x, simp [h] }
end
lemma univ_pi_eq_empty_iff : pi univ t = ∅ ↔ ∃ i, t i = ∅ :=
by simp [← not_nonempty_iff_eq_empty, univ_pi_nonempty_iff]
@[simp] lemma insert_pi (i : ι) (s : set ι) (t : Π i, set (α i)) :
pi (insert i s) t = (eval i ⁻¹' t i) ∩ pi s t :=
by { ext, simp [pi, or_imp_distrib, forall_and_distrib] }
@[simp] lemma singleton_pi (i : ι) (t : Π i, set (α i)) :
pi {i} t = (eval i ⁻¹' t i) :=
by { ext, simp [pi] }
lemma pi_if {p : ι → Prop} [h : decidable_pred p] (s : set ι) (t₁ t₂ : Π i, set (α i)) :
pi s (λ i, if p i then t₁ i else t₂ i) = pi {i ∈ s | p i} t₁ ∩ pi {i ∈ s | ¬ p i} t₂ :=
begin
ext f,
split,
{ assume h, split; { rintros i ⟨his, hpi⟩, simpa [*] using h i } },
{ rintros ⟨ht₁, ht₂⟩ i his,
by_cases p i; simp * at * }
end
open_locale classical
lemma eval_image_pi {i : ι} (hs : i ∈ s) (ht : (s.pi t).nonempty) : eval i '' s.pi t = t i :=
begin
ext x, rcases ht with ⟨f, hf⟩, split,
{ rintro ⟨g, hg, rfl⟩, exact hg i hs },
{ intro hg, refine ⟨update f i x, _, by simp⟩,
intros j hj, by_cases hji : j = i,
{ subst hji, simp [hg] },
{ rw [mem_pi] at hf, simp [hji, hf, hj] }},
end
@[simp] lemma eval_image_univ_pi {i : ι} (ht : (pi univ t).nonempty) :
(λ f : Π i, α i, f i) '' pi univ t = t i :=
eval_image_pi (mem_univ i) ht
lemma update_preimage_pi {i : ι} {f : Π i, α i} (hi : i ∈ s)
(hf : ∀ j ∈ s, j ≠ i → f j ∈ t j) : (update f i) ⁻¹' s.pi t = t i :=
begin
ext x, split,
{ intro h, convert h i hi, simp },
{ intros hx j hj, by_cases h : j = i,
{ cases h, simpa },
{ rw [update_noteq h], exact hf j hj h }}
end
lemma update_preimage_univ_pi {i : ι} {f : Π i, α i} (hf : ∀ j ≠ i, f j ∈ t j) :
(update f i) ⁻¹' pi univ t = t i :=
update_preimage_pi (mem_univ i) (λ j _, hf j)
lemma subset_pi_eval_image (s : set ι) (u : set (Π i, α i)) : u ⊆ pi s (λ i, eval i '' u) :=
λ f hf i hi, ⟨f, hf, rfl⟩
end pi
/-! ### Lemmas about `inclusion`, the injection of subtypes induced by `⊆` -/
section inclusion
variable {α : Type*}
/-- `inclusion` is the "identity" function between two subsets `s` and `t`, where `s ⊆ t` -/
def inclusion {s t : set α} (h : s ⊆ t) : s → t :=
λ x : s, (⟨x, h x.2⟩ : t)
@[simp] lemma inclusion_self {s : set α} (x : s) :
inclusion (set.subset.refl _) x = x :=
by { cases x, refl }
@[simp] lemma inclusion_right {s t : set α} (h : s ⊆ t) (x : t) (m : (x : α) ∈ s) :
inclusion h ⟨x, m⟩ = x :=
by { cases x, refl }
@[simp] lemma inclusion_inclusion {s t u : set α} (hst : s ⊆ t) (htu : t ⊆ u)
(x : s) : inclusion htu (inclusion hst x) = inclusion (set.subset.trans hst htu) x :=
by { cases x, refl }
@[simp] lemma coe_inclusion {s t : set α} (h : s ⊆ t) (x : s) :
(inclusion h x : α) = (x : α) := rfl
lemma inclusion_injective {s t : set α} (h : s ⊆ t) :
function.injective (inclusion h)
| ⟨_, _⟩ ⟨_, _⟩ := subtype.ext_iff_val.2 ∘ subtype.ext_iff_val.1
lemma eq_of_inclusion_surjective {s t : set α} {h : s ⊆ t}
(h_surj : function.surjective (inclusion h)) : s = t :=
begin
apply set.subset.antisymm h,
intros x hx,
cases h_surj ⟨x, hx⟩ with y key,
rw [←subtype.coe_mk x hx, ←key, coe_inclusion],
exact subtype.mem y,
end
lemma range_inclusion {s t : set α} (h : s ⊆ t) : range (inclusion h) = {x : t | (x:α) ∈ s} :=
by { ext ⟨x, hx⟩, simp [inclusion] }
end inclusion
/-! ### Injectivity and surjectivity lemmas for image and preimage -/
section image_preimage
variables {α : Type u} {β : Type v} {f : α → β}
@[simp]
lemma preimage_injective : injective (preimage f) ↔ surjective f :=
begin
refine ⟨λ h y, _, surjective.preimage_injective⟩,
obtain ⟨x, hx⟩ : (f ⁻¹' {y}).nonempty,
{ rw [h.nonempty_apply_iff preimage_empty], apply singleton_nonempty },
exact ⟨x, hx⟩
end
@[simp]
lemma preimage_surjective : surjective (preimage f) ↔ injective f :=
begin
refine ⟨λ h x x' hx, _, injective.preimage_surjective⟩,
cases h {x} with s hs, have := mem_singleton x,
rwa [← hs, mem_preimage, hx, ← mem_preimage, hs, mem_singleton_iff, eq_comm] at this
end
@[simp] lemma image_surjective : surjective (image f) ↔ surjective f :=
begin
refine ⟨λ h y, _, surjective.image_surjective⟩,
cases h {y} with s hs,
have := mem_singleton y, rw [← hs] at this, rcases this with ⟨x, h1x, h2x⟩,
exact ⟨x, h2x⟩
end
@[simp] lemma image_injective : injective (image f) ↔ injective f :=
begin
refine ⟨λ h x x' hx, _, injective.image_injective⟩,
rw [← singleton_eq_singleton_iff], apply h,
rw [image_singleton, image_singleton, hx]
end
end image_preimage
/-! ### Lemmas about images of binary and ternary functions -/
section n_ary_image
variables {α β γ δ ε : Type*} {f f' : α → β → γ} {g g' : α → β → γ → δ}
variables {s s' : set α} {t t' : set β} {u u' : set γ} {a a' : α} {b b' : β} {c c' : γ} {d d' : δ}
/-- The image of a binary function `f : α → β → γ` as a function `set α → set β → set γ`.
Mathematically this should be thought of as the image of the corresponding function `α × β → γ`.
-/
def image2 (f : α → β → γ) (s : set α) (t : set β) : set γ :=
{c | ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c }
lemma mem_image2_eq : c ∈ image2 f s t = ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c := rfl
@[simp] lemma mem_image2 : c ∈ image2 f s t ↔ ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c := iff.rfl
lemma mem_image2_of_mem (h1 : a ∈ s) (h2 : b ∈ t) : f a b ∈ image2 f s t :=
⟨a, b, h1, h2, rfl⟩
lemma mem_image2_iff (hf : injective2 f) : f a b ∈ image2 f s t ↔ a ∈ s ∧ b ∈ t :=
⟨ by { rintro ⟨a', b', ha', hb', h⟩, rcases hf h with ⟨rfl, rfl⟩, exact ⟨ha', hb'⟩ },
λ ⟨ha, hb⟩, mem_image2_of_mem ha hb⟩
/-- image2 is monotone with respect to `⊆`. -/
lemma image2_subset (hs : s ⊆ s') (ht : t ⊆ t') : image2 f s t ⊆ image2 f s' t' :=
by { rintro _ ⟨a, b, ha, hb, rfl⟩, exact mem_image2_of_mem (hs ha) (ht hb) }
lemma forall_image2_iff {p : γ → Prop} :
(∀ z ∈ image2 f s t, p z) ↔ ∀ (x ∈ s) (y ∈ t), p (f x y) :=
⟨λ h x hx y hy, h _ ⟨x, y, hx, hy, rfl⟩, λ h z ⟨x, y, hx, hy, hz⟩, hz ▸ h x hx y hy⟩
@[simp] lemma image2_subset_iff {u : set γ} :
image2 f s t ⊆ u ↔ ∀ (x ∈ s) (y ∈ t), f x y ∈ u :=
forall_image2_iff
lemma image2_union_left : image2 f (s ∪ s') t = image2 f s t ∪ image2 f s' t :=
begin
ext c, split,
{ rintros ⟨a, b, h1a|h2a, hb, rfl⟩;[left, right]; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ },
{ rintro (⟨_, _, _, _, rfl⟩|⟨_, _, _, _, rfl⟩); refine ⟨_, _, _, ‹_›, rfl⟩; simp [mem_union, *] }
end
lemma image2_union_right : image2 f s (t ∪ t') = image2 f s t ∪ image2 f s t' :=
begin
ext c, split,
{ rintros ⟨a, b, ha, h1b|h2b, rfl⟩;[left, right]; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ },
{ rintro (⟨_, _, _, _, rfl⟩|⟨_, _, _, _, rfl⟩); refine ⟨_, _, ‹_›, _, rfl⟩; simp [mem_union, *] }
end
@[simp] lemma image2_empty_left : image2 f ∅ t = ∅ := ext $ by simp
@[simp] lemma image2_empty_right : image2 f s ∅ = ∅ := ext $ by simp
lemma image2_inter_subset_left : image2 f (s ∩ s') t ⊆ image2 f s t ∩ image2 f s' t :=
by { rintro _ ⟨a, b, ⟨h1a, h2a⟩, hb, rfl⟩, split; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ }
lemma image2_inter_subset_right : image2 f s (t ∩ t') ⊆ image2 f s t ∩ image2 f s t' :=
by { rintro _ ⟨a, b, ha, ⟨h1b, h2b⟩, rfl⟩, split; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ }
@[simp] lemma image2_singleton_left : image2 f {a} t = f a '' t :=
ext $ λ x, by simp
@[simp] lemma image2_singleton_right : image2 f s {b} = (λ a, f a b) '' s :=
ext $ λ x, by simp
lemma image2_singleton : image2 f {a} {b} = {f a b} := by simp
@[congr] lemma image2_congr (h : ∀ (a ∈ s) (b ∈ t), f a b = f' a b) :
image2 f s t = image2 f' s t :=
by { ext, split; rintro ⟨a, b, ha, hb, rfl⟩; refine ⟨a, b, ha, hb, by rw h a ha b hb⟩ }
/-- A common special case of `image2_congr` -/
lemma image2_congr' (h : ∀ a b, f a b = f' a b) : image2 f s t = image2 f' s t :=
image2_congr (λ a _ b _, h a b)
/-- The image of a ternary function `f : α → β → γ → δ` as a function
`set α → set β → set γ → set δ`. Mathematically this should be thought of as the image of the
corresponding function `α × β × γ → δ`.
-/
def image3 (g : α → β → γ → δ) (s : set α) (t : set β) (u : set γ) : set δ :=
{d | ∃ a b c, a ∈ s ∧ b ∈ t ∧ c ∈ u ∧ g a b c = d }
@[simp] lemma mem_image3 : d ∈ image3 g s t u ↔ ∃ a b c, a ∈ s ∧ b ∈ t ∧ c ∈ u ∧ g a b c = d :=
iff.rfl
@[congr] lemma image3_congr (h : ∀ (a ∈ s) (b ∈ t) (c ∈ u), g a b c = g' a b c) :
image3 g s t u = image3 g' s t u :=
by { ext x,
split; rintro ⟨a, b, c, ha, hb, hc, rfl⟩; refine ⟨a, b, c, ha, hb, hc, by rw h a ha b hb c hc⟩ }
/-- A common special case of `image3_congr` -/
lemma image3_congr' (h : ∀ a b c, g a b c = g' a b c) : image3 g s t u = image3 g' s t u :=
image3_congr (λ a _ b _ c _, h a b c)
lemma image2_image2_left (f : δ → γ → ε) (g : α → β → δ) :
image2 f (image2 g s t) u = image3 (λ a b c, f (g a b) c) s t u :=
begin
ext, split,
{ rintro ⟨_, c, ⟨a, b, ha, hb, rfl⟩, hc, rfl⟩, refine ⟨a, b, c, ha, hb, hc, rfl⟩ },
{ rintro ⟨a, b, c, ha, hb, hc, rfl⟩, refine ⟨_, c, ⟨a, b, ha, hb, rfl⟩, hc, rfl⟩ }
end
lemma image2_image2_right (f : α → δ → ε) (g : β → γ → δ) :
image2 f s (image2 g t u) = image3 (λ a b c, f a (g b c)) s t u :=
begin
ext, split,
{ rintro ⟨a, _, ha, ⟨b, c, hb, hc, rfl⟩, rfl⟩, refine ⟨a, b, c, ha, hb, hc, rfl⟩ },
{ rintro ⟨a, b, c, ha, hb, hc, rfl⟩, refine ⟨a, _, ha, ⟨b, c, hb, hc, rfl⟩, rfl⟩ }
end
lemma image2_assoc {ε'} {f : δ → γ → ε} {g : α → β → δ} {f' : α → ε' → ε} {g' : β → γ → ε'}
(h_assoc : ∀ a b c, f (g a b) c = f' a (g' b c)) :
image2 f (image2 g s t) u = image2 f' s (image2 g' t u) :=
by simp only [image2_image2_left, image2_image2_right, h_assoc]
lemma image_image2 (f : α → β → γ) (g : γ → δ) :
g '' image2 f s t = image2 (λ a b, g (f a b)) s t :=
begin
ext, split,
{ rintro ⟨_, ⟨a, b, ha, hb, rfl⟩, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ },
{ rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨_, ⟨a, b, ha, hb, rfl⟩, rfl⟩ }
end
lemma image2_image_left (f : γ → β → δ) (g : α → γ) :
image2 f (g '' s) t = image2 (λ a b, f (g a) b) s t :=
begin
ext, split,
{ rintro ⟨_, b, ⟨a, ha, rfl⟩, hb, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ },
{ rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨_, b, ⟨a, ha, rfl⟩, hb, rfl⟩ }
end
lemma image2_image_right (f : α → γ → δ) (g : β → γ) :
image2 f s (g '' t) = image2 (λ a b, f a (g b)) s t :=
begin
ext, split,
{ rintro ⟨a, _, ha, ⟨b, hb, rfl⟩, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ },
{ rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨a, _, ha, ⟨b, hb, rfl⟩, rfl⟩ }
end
lemma image2_swap (f : α → β → γ) (s : set α) (t : set β) :
image2 f s t = image2 (λ a b, f b a) t s :=
by { ext, split; rintro ⟨a, b, ha, hb, rfl⟩; refine ⟨b, a, hb, ha, rfl⟩ }
@[simp] lemma image2_left (h : t.nonempty) : image2 (λ x y, x) s t = s :=
by simp [nonempty_def.mp h, ext_iff]
@[simp] lemma image2_right (h : s.nonempty) : image2 (λ x y, y) s t = t :=
by simp [nonempty_def.mp h, ext_iff]
@[simp] lemma image_prod (f : α → β → γ) : (λ x : α × β, f x.1 x.2) '' s.prod t = image2 f s t :=
set.ext $ λ a,
⟨ by { rintros ⟨_, _, rfl⟩, exact ⟨_, _, (mem_prod.mp ‹_›).1, (mem_prod.mp ‹_›).2, rfl⟩ },
by { rintros ⟨_, _, _, _, rfl⟩, exact ⟨(_, _), mem_prod.mpr ⟨‹_›, ‹_›⟩, rfl⟩ }⟩
lemma nonempty.image2 (hs : s.nonempty) (ht : t.nonempty) : (image2 f s t).nonempty :=
by { cases hs with a ha, cases ht with b hb, exact ⟨f a b, ⟨a, b, ha, hb, rfl⟩⟩ }
end n_ary_image
end set
namespace subsingleton
variables {α : Type*} [subsingleton α]
lemma eq_univ_of_nonempty {s : set α} : s.nonempty → s = univ :=
λ ⟨x, hx⟩, eq_univ_of_forall $ λ y, subsingleton.elim x y ▸ hx
@[elab_as_eliminator]
lemma set_cases {p : set α → Prop} (h0 : p ∅) (h1 : p univ) (s) : p s :=
s.eq_empty_or_nonempty.elim (λ h, h.symm ▸ h0) $ λ h, (eq_univ_of_nonempty h).symm ▸ h1
end subsingleton
|
f0d2995125cc142419e2e19b01c1535d6439b618 | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/linear_algebra/determinant.lean | d875e938de4456998e2e2e448193ddfc8b7116b3 | [
"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 | 4,663 | 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
-/
import data.matrix.basic
import group_theory.perm.sign
universes u v
open equiv equiv.perm finset function
namespace matrix
variables {n : Type u} [fintype n] [decidable_eq n] {R : Type v} [comm_ring R]
local notation `ε` σ:max := ((sign σ : ℤ ) : R)
definition det (M : matrix n n R) : R :=
univ.sum (λ (σ : perm n), ε σ * univ.prod (λ i, M (σ i) i))
@[simp] lemma det_diagonal {d : n → R} : det (diagonal d) = univ.prod d :=
begin
refine (finset.sum_eq_single 1 _ _).trans _,
{ intros σ h1 h2,
cases not_forall.1 (mt (equiv.ext _ _) h2) with x h3,
convert ring.mul_zero _,
apply finset.prod_eq_zero,
{ change x ∈ _, simp },
exact if_neg h3 },
{ simp },
{ simp }
end
@[simp] lemma det_zero (h : nonempty n) : det (0 : matrix n n R) = 0 :=
by rw [← diagonal_zero, det_diagonal, finset.prod_const, ← fintype.card,
zero_pow (fintype.card_pos_iff.2 h)]
@[simp] lemma det_one : det (1 : matrix n n R) = 1 :=
by rw [← diagonal_one]; simp [-diagonal_one]
lemma det_mul_aux {M N : matrix n n R} {p : n → n} (H : ¬bijective p) :
univ.sum (λ σ : perm n, (ε σ) * (univ.prod (λ x, M (σ x) (p x) * N (p x) x))) = 0 :=
begin
obtain ⟨i, j, hpij, hij⟩ : ∃ i j, p i = p j ∧ i ≠ j,
{ rw [← fintype.injective_iff_bijective, injective] at H,
push_neg at H,
exact H },
exact sum_involution
(λ σ _, σ * swap i j)
(λ σ _,
have ∀ a, p (swap i j a) = p a := λ a, by simp only [swap_apply_def]; split_ifs; cc,
have univ.prod (λ x, M (σ x) (p x)) = univ.prod (λ x, M ((σ * swap i j) x) (p x)),
from prod_bij (λ a _, swap i j a) (λ _ _, mem_univ _) (by simp [this])
(λ _ _ _ _ h, (swap i j).injective h)
(λ b _, ⟨swap i j b, mem_univ _, by simp⟩),
by simp [sign_mul, this, sign_swap hij, prod_mul_distrib])
(λ σ _ _ h, hij (σ.injective $ by conv {to_lhs, rw ← h}; simp))
(λ _ _, mem_univ _)
(λ _ _, equiv.ext _ _ $ by simp)
end
@[simp] lemma det_mul (M N : matrix n n R) : det (M * N) = det M * det N :=
calc det (M * N) = univ.sum (λ σ : perm n, (univ.pi (λ a, univ)).sum
(λ (p : Π (a : n), a ∈ univ → n), ε σ *
univ.attach.prod (λ i, M (σ i.1) (p i.1 (mem_univ _)) * N (p i.1 (mem_univ _)) i.1))) :
by simp only [det, mul_val', prod_sum, mul_sum]
... = univ.sum (λ σ : perm n, univ.sum
(λ p : n → n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) :
sum_congr rfl (λ σ _, sum_bij
(λ f h i, f i (mem_univ _)) (λ _ _, mem_univ _)
(by simp) (by simp [funext_iff]) (λ b _, ⟨λ i hi, b i, by simp⟩))
... = univ.sum (λ p : n → n, univ.sum
(λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) :
finset.sum_comm
... = ((@univ (n → n) _).filter bijective).sum (λ p : n → n, univ.sum
(λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) :
eq.symm $ sum_subset (filter_subset _)
(λ f _ hbij, det_mul_aux $ by simpa using hbij)
... = (@univ (perm n) _).sum (λ τ, univ.sum
(λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (τ i) * N (τ i) i))) :
sum_bij (λ p h, equiv.of_bijective (mem_filter.1 h).2) (λ _ _, mem_univ _)
(λ _ _, rfl) (λ _ _ _ _ h, by injection h)
(λ b _, ⟨b, mem_filter.2 ⟨mem_univ _, b.bijective⟩, eq_of_to_fun_eq rfl⟩)
... = univ.sum (λ σ : perm n, univ.sum (λ τ : perm n,
(univ.prod (λ i, N (σ i) i) * ε τ) * univ.prod (λ j, M (τ j) (σ j)))) :
by simp [mul_sum, det, mul_comm, mul_left_comm, prod_mul_distrib, mul_assoc]
... = univ.sum (λ σ : perm n, univ.sum (λ τ : perm n,
(univ.prod (λ i, N (σ i) i) * (ε σ * ε τ)) *
univ.prod (λ i, M (τ i) i))) :
sum_congr rfl (λ σ _, sum_bij (λ τ _, τ * σ⁻¹) (λ _ _, mem_univ _)
(λ τ _,
have univ.prod (λ j, M (τ j) (σ j)) = univ.prod (λ j, M ((τ * σ⁻¹) j) j),
by rw prod_univ_perm σ⁻¹; simp [mul_apply],
have h : ε σ * ε (τ * σ⁻¹) = ε τ :=
calc ε σ * ε (τ * σ⁻¹) = ε ((τ * σ⁻¹) * σ) :
by rw [mul_comm, sign_mul (τ * σ⁻¹)]; simp [sign_mul]
... = ε τ : by simp,
by rw h; simp [this, mul_comm, mul_assoc, mul_left_comm])
(λ _ _ _ _, (mul_right_inj _).1) (λ τ _, ⟨τ * σ, by simp⟩))
... = det M * det N : by simp [det, mul_assoc, mul_sum, mul_comm, mul_left_comm]
instance : is_monoid_hom (det : matrix n n R → R) :=
{ map_one := det_one,
map_mul := det_mul }
end matrix
|
e0b9d54a2443df8280aae540ccf33b4c0008546f | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/polynomial/identities_auto.lean | 750257fc346642544794f8c289be2b514f849f39 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,622 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.polynomial.derivative
import Mathlib.PostPort
universes u_1 u
namespace Mathlib
/-!
# Theory of univariate polynomials
The main def is `binom_expansion`.
-/
namespace polynomial
/- @TODO: pow_add_expansion and pow_sub_pow_factor are not specific to polynomials.
These belong somewhere else. But not in group_power because they depend on tactic.ring_exp
Maybe use data.nat.choose to prove it.
-/
def pow_add_expansion {R : Type u_1} [comm_semiring R] (x : R) (y : R) (n : ℕ) :
Subtype fun (k : R) => (x + y) ^ n = x ^ n + ↑n * x ^ (n - 1) * y + k * y ^ bit0 1 :=
sorry
def binom_expansion {R : Type u} [comm_ring R] (f : polynomial R) (x : R) (y : R) :
Subtype
fun (k : R) =>
eval (x + y) f = eval x f + eval x (coe_fn derivative f) * y + k * y ^ bit0 1 :=
{ val := finsupp.sum f fun (e : ℕ) (a : R) => a * subtype.val (poly_binom_aux1 x y e a),
property := sorry }
def pow_sub_pow_factor {R : Type u} [comm_ring R] (x : R) (y : R) (i : ℕ) :
Subtype fun (z : R) => x ^ i - y ^ i = z * (x - y) :=
sorry
def eval_sub_factor {R : Type u} [comm_ring R] (f : polynomial R) (x : R) (y : R) :
Subtype fun (z : R) => eval x f - eval y f = z * (x - y) :=
{ val := finsupp.sum f fun (i : ℕ) (r : R) => r * subtype.val (pow_sub_pow_factor x y i),
property := sorry }
end Mathlib |
7c4f06c8a9ab097c8cb8dc209d68b7758eb454c7 | 205f0fc16279a69ea36e9fd158e3a97b06834ce2 | /src/07_Negation/in-class-quiz.lean | ba3b2cf3ae5cafe1524b8ddf55dcc8927fb9fed3 | [] | 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 | 1,875 | lean | /-
This in-class exercise requires solutions to two problems
-/
/-
PROBLEM #1.
In Lean, define pf1 to be a proof of the proposition
that, "for any proposition, Q, (Q ∧ ¬ Q) → false.
Here is a start on an answer. We use λ to
introduce the assumption that Q is some proposition.
The underscore is what you have to fill in.
If you need hints, continue reading the comment
below. Once you're done with this problem, move
onto the second problem in this quiz
-/
theorem pf1 : ∀ Q : Prop, ¬ (Q ∧ ¬ Q) :=
λ (Q : Prop),
( _ )
/-
Hint #1: Remember that, assuming that A is any
proposition, ¬ A simply means (A → false).
Hint #2: Hover your mouse cursor over the underscore
in the preceding code. You will see that what you
need to replace it is a proof of (Q ∧ ¬ Q) → false.
Lean writes this as ¬ (Q ∧ ¬ Q), but as you know,
the two expressions are equivalent.
Hint #3: (Q ∧ ¬ Q) → false is an implication.
Remember what a proof of an implication looks like.
Use a corresponding expression in place of the _.
Hint #4: Remember your elimination rules for ∧ (and).
Hint #5: Remember again: ¬ Q means (Q → false).
If you have a proof of Q → false, then you have
a function that if it is given an assumed proof
of Q it reduces to a proof of false. Look for a
way to give this function a proof of Q!
-/
/-
PROBLEM #2.
Produce a proof, pf2, of the proposition, that
for any propositions, P and Q, (P ∧ Q) ∧ (P ∧ ¬ Q)
→ false. You can use the partial solution that we
gave for the last problem as a model. You'll have
to change the name, pf1, the proposition to be
proved, and the lambda expressions to at least
take (P Q : Prop) as an argument. Your code goes
below. Hint: Remember your and elimination rules.
Also, for this problme, you might want, but are
not required, to use a tactic script.
-/
|
713c92d9a9b654a6420a11ba04ec504058e4d6a4 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/int/div.lean | 3a93b34352da62477fce325605f21b4925781e38 | [
"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,820 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
-/
import data.int.dvd.basic
import data.nat.order.lemmas
import algebra.ring.regular
/-!
# Lemmas relating `/` in `ℤ` with the ordering.
-/
open nat
namespace int
theorem eq_mul_div_of_mul_eq_mul_of_dvd_left {a b c d : ℤ} (hb : b ≠ 0) (hbc : b ∣ c)
(h : b * a = c * d) :
a = c / b * d :=
begin
cases hbc with k hk,
subst hk,
rw [int.mul_div_cancel_left _ hb],
rw mul_assoc at h,
apply mul_left_cancel₀ hb h
end
/-- If an integer with larger absolute value divides an integer, it is
zero. -/
lemma eq_zero_of_dvd_of_nat_abs_lt_nat_abs {a b : ℤ} (w : a ∣ b) (h : nat_abs b < nat_abs a) :
b = 0 :=
begin
rw [←nat_abs_dvd, ←dvd_nat_abs, coe_nat_dvd] at w,
rw ←nat_abs_eq_zero,
exact eq_zero_of_dvd_of_lt w h
end
lemma eq_zero_of_dvd_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) (h : b ∣ a) : a = 0 :=
eq_zero_of_dvd_of_nat_abs_lt_nat_abs h (nat_abs_lt_nat_abs_of_nonneg_of_lt w₁ w₂)
/-- If two integers are congruent to a sufficiently large modulus,
they are equal. -/
lemma eq_of_mod_eq_of_nat_abs_sub_lt_nat_abs {a b c : ℤ} (h1 : a % b = c)
(h2 : nat_abs (a - c) < nat_abs b) :
a = c :=
eq_of_sub_eq_zero (eq_zero_of_dvd_of_nat_abs_lt_nat_abs (dvd_sub_of_mod_eq h1) h2)
theorem of_nat_add_neg_succ_of_nat_of_ge {m n : ℕ}
(h : n.succ ≤ m) : of_nat m + -[1+n] = of_nat (m - n.succ) :=
begin
change sub_nat_nat _ _ = _,
have h' : n.succ - m = 0,
apply tsub_eq_zero_iff_le.mpr h,
simp [*, sub_nat_nat]
end
lemma nat_abs_le_of_dvd_ne_zero {s t : ℤ} (hst : s ∣ t) (ht : t ≠ 0) : nat_abs s ≤ nat_abs t :=
not_lt.mp (mt (eq_zero_of_dvd_of_nat_abs_lt_nat_abs hst) ht)
end int
|
dbbcd3a6415079f7a8fc09cc494e3cb591509106 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/topology/dense_embedding.lean | a57dde88d904dd5d4642b66c9ad86c92d70ba557 | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 12,912 | lean | /-
Copyright (c) 2019 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot
-/
import topology.separation
import topology.bases
/-!
# Dense embeddings
This file defines three properties of functions:
* `dense_range f` means `f` has dense image;
* `dense_inducing i` means `i` is also `inducing`;
* `dense_embedding e` means `e` is also an `embedding`.
The main theorem `continuous_extend` gives a criterion for a function
`f : X → Z` to a regular (T₃) space Z to extend along a dense embedding
`i : X → Y` to a continuous function `g : Y → Z`. Actually `i` only
has to be `dense_inducing` (not necessarily injective).
-/
noncomputable theory
open set filter
open_locale classical topological_space filter
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
/-- `i : α → β` is "dense inducing" if it has dense range and the topology on `α`
is the one induced by `i` from the topology on `β`. -/
structure dense_inducing [topological_space α] [topological_space β] (i : α → β)
extends inducing i : Prop :=
(dense : dense_range i)
namespace dense_inducing
variables [topological_space α] [topological_space β]
variables {i : α → β} (di : dense_inducing i)
lemma nhds_eq_comap (di : dense_inducing i) :
∀ a : α, 𝓝 a = comap i (𝓝 $ i a) :=
di.to_inducing.nhds_eq_comap
protected lemma continuous (di : dense_inducing i) : continuous i :=
di.to_inducing.continuous
lemma closure_range : closure (range i) = univ :=
di.dense.closure_range
lemma self_sub_closure_image_preimage_of_open {s : set β} (di : dense_inducing i) :
is_open s → s ⊆ closure (i '' (i ⁻¹' s)) :=
begin
intros s_op b b_in_s,
rw [image_preimage_eq_inter_range, mem_closure_iff],
intros U U_op b_in,
rw ←inter_assoc,
exact (dense_iff_inter_open.1 di.dense) _ (is_open.inter U_op s_op) ⟨b, b_in, b_in_s⟩
end
lemma closure_image_nhds_of_nhds {s : set α} {a : α} (di : dense_inducing i) :
s ∈ 𝓝 a → closure (i '' s) ∈ 𝓝 (i a) :=
begin
rw [di.nhds_eq_comap a, mem_comap_sets],
intro h,
rcases h with ⟨t, t_nhd, sub⟩,
rw mem_nhds_iff at t_nhd,
rcases t_nhd with ⟨U, U_sub, ⟨U_op, e_a_in_U⟩⟩,
have := calc i ⁻¹' U ⊆ i⁻¹' t : preimage_mono U_sub
... ⊆ s : sub,
have := calc U ⊆ closure (i '' (i ⁻¹' U)) : self_sub_closure_image_preimage_of_open di U_op
... ⊆ closure (i '' s) : closure_mono (image_subset i this),
have U_nhd : U ∈ 𝓝 (i a) := is_open.mem_nhds U_op e_a_in_U,
exact (𝓝 (i a)).sets_of_superset U_nhd this
end
/-- The product of two dense inducings is a dense inducing -/
protected lemma prod [topological_space γ] [topological_space δ]
{e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_inducing e₁) (de₂ : dense_inducing e₂) :
dense_inducing (λ(p : α × γ), (e₁ p.1, e₂ p.2)) :=
{ induced := (de₁.to_inducing.prod_mk de₂.to_inducing).induced,
dense := de₁.dense.prod_map de₂.dense }
open topological_space
/-- If the domain of a `dense_inducing` map is a separable space, then so is the codomain. -/
protected lemma separable_space [separable_space α] : separable_space β :=
di.dense.separable_space di.continuous
variables [topological_space δ] {f : γ → α} {g : γ → δ} {h : δ → β}
/--
γ -f→ α
g↓ ↓e
δ -h→ β
-/
lemma tendsto_comap_nhds_nhds {d : δ} {a : α} (di : dense_inducing i)
(H : tendsto h (𝓝 d) (𝓝 (i a))) (comm : h ∘ g = i ∘ f) : tendsto f (comap g (𝓝 d)) (𝓝 a) :=
begin
have lim1 : map g (comap g (𝓝 d)) ≤ 𝓝 d := map_comap_le,
replace lim1 : map h (map g (comap g (𝓝 d))) ≤ map h (𝓝 d) := map_mono lim1,
rw [filter.map_map, comm, ← filter.map_map, map_le_iff_le_comap] at lim1,
have lim2 : comap i (map h (𝓝 d)) ≤ comap i (𝓝 (i a)) := comap_mono H,
rw ← di.nhds_eq_comap at lim2,
exact le_trans lim1 lim2,
end
protected lemma nhds_within_ne_bot (di : dense_inducing i) (b : β) :
ne_bot (𝓝[range i] b) :=
di.dense.nhds_within_ne_bot b
lemma comap_nhds_ne_bot (di : dense_inducing i) (b : β) : ne_bot (comap i (𝓝 b)) :=
comap_ne_bot $ λ s hs,
let ⟨_, ⟨ha, a, rfl⟩⟩ := mem_closure_iff_nhds.1 (di.dense b) s hs in ⟨a, ha⟩
variables [topological_space γ]
/-- If `i : α → β` is a dense inducing, then any function `f : α → γ` "extends"
to a function `g = extend di f : β → γ`. If `γ` is Hausdorff and `f` has a
continuous extension, then `g` is the unique such extension. In general,
`g` might not be continuous or even extend `f`. -/
def extend (di : dense_inducing i) (f : α → γ) (b : β) : γ :=
@@lim _ ⟨f (di.dense.some b)⟩ (comap i (𝓝 b)) f
lemma extend_eq_of_tendsto [t2_space γ] {b : β} {c : γ} {f : α → γ}
(hf : tendsto f (comap i (𝓝 b)) (𝓝 c)) :
di.extend f b = c :=
by haveI := di.comap_nhds_ne_bot; exact hf.lim_eq
lemma extend_eq_at [t2_space γ] {f : α → γ} (a : α) (hf : continuous_at f a) :
di.extend f (i a) = f a :=
extend_eq_of_tendsto _ $ di.nhds_eq_comap a ▸ hf
lemma extend_eq [t2_space γ] {f : α → γ} (hf : continuous f) (a : α) :
di.extend f (i a) = f a :=
di.extend_eq_at a hf.continuous_at
lemma extend_unique_at [t2_space γ] {b : β} {f : α → γ} {g : β → γ} (di : dense_inducing i)
(hf : ∀ᶠ x in comap i (𝓝 b), g (i x) = f x) (hg : continuous_at g b) :
di.extend f b = g b :=
begin
refine di.extend_eq_of_tendsto (λ s hs, mem_map.2 _),
suffices : ∀ᶠ (x : α) in comap i (𝓝 b), g (i x) ∈ s,
from hf.mp (this.mono $ λ x hgx hfx, hfx ▸ hgx),
clear hf f,
refine eventually_comap.2 ((hg.eventually hs).mono _),
rintros _ hxs x rfl,
exact hxs
end
lemma extend_unique [t2_space γ] {f : α → γ} {g : β → γ} (di : dense_inducing i)
(hf : ∀ x, g (i x) = f x) (hg : continuous g) :
di.extend f = g :=
funext $ λ b, extend_unique_at di (eventually_of_forall hf) hg.continuous_at
lemma continuous_at_extend [regular_space γ] {b : β} {f : α → γ} (di : dense_inducing i)
(hf : ∀ᶠ x in 𝓝 b, ∃c, tendsto f (comap i $ 𝓝 x) (𝓝 c)) :
continuous_at (di.extend f) b :=
begin
set φ := di.extend f,
haveI := di.comap_nhds_ne_bot,
suffices : ∀ V' ∈ 𝓝 (φ b), is_closed V' → φ ⁻¹' V' ∈ 𝓝 b,
by simpa [continuous_at, (closed_nhds_basis _).tendsto_right_iff],
intros V' V'_in V'_closed,
set V₁ := {x | tendsto f (comap i $ 𝓝 x) (𝓝 $ φ x)},
have V₁_in : V₁ ∈ 𝓝 b,
{ filter_upwards [hf],
rintros x ⟨c, hc⟩,
dsimp [V₁, φ],
rwa di.extend_eq_of_tendsto hc },
obtain ⟨V₂, V₂_in, V₂_op, hV₂⟩ : ∃ V₂ ∈ 𝓝 b, is_open V₂ ∧ ∀ x ∈ i ⁻¹' V₂, f x ∈ V',
{ simpa [and_assoc] using ((nhds_basis_opens' b).comap i).tendsto_left_iff.mp
(mem_of_mem_nhds V₁_in : b ∈ V₁) V' V'_in },
suffices : ∀ x ∈ V₁ ∩ V₂, φ x ∈ V',
{ filter_upwards [inter_mem_sets V₁_in V₂_in], exact this },
rintros x ⟨x_in₁, x_in₂⟩,
have hV₂x : V₂ ∈ 𝓝 x := is_open.mem_nhds V₂_op x_in₂,
apply V'_closed.mem_of_tendsto x_in₁,
use V₂,
tauto,
end
lemma continuous_extend [regular_space γ] {f : α → γ} (di : dense_inducing i)
(hf : ∀b, ∃c, tendsto f (comap i (𝓝 b)) (𝓝 c)) : continuous (di.extend f) :=
continuous_iff_continuous_at.mpr $ assume b, di.continuous_at_extend $ univ_mem_sets' hf
lemma mk'
(i : α → β)
(c : continuous i)
(dense : ∀x, x ∈ closure (range i))
(H : ∀ (a:α) s ∈ 𝓝 a,
∃t ∈ 𝓝 (i a), ∀ b, i b ∈ t → b ∈ s) :
dense_inducing i :=
{ induced := (induced_iff_nhds_eq i).2 $
λ a, le_antisymm (tendsto_iff_comap.1 $ c.tendsto _) (by simpa [le_def] using H a),
dense := dense }
end dense_inducing
/-- A dense embedding is an embedding with dense image. -/
structure dense_embedding [topological_space α] [topological_space β] (e : α → β)
extends dense_inducing e : Prop :=
(inj : function.injective e)
theorem dense_embedding.mk'
[topological_space α] [topological_space β] (e : α → β)
(c : continuous e)
(dense : dense_range e)
(inj : function.injective e)
(H : ∀ (a:α) s ∈ 𝓝 a,
∃t ∈ 𝓝 (e a), ∀ b, e b ∈ t → b ∈ s) :
dense_embedding e :=
{ inj := inj,
..dense_inducing.mk' e c dense H}
namespace dense_embedding
open topological_space
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
variables {e : α → β} (de : dense_embedding e)
lemma inj_iff {x y} : e x = e y ↔ x = y := de.inj.eq_iff
lemma to_embedding : embedding e :=
{ induced := de.induced,
inj := de.inj }
/-- If the domain of a `dense_embedding` is a separable space, then so is its codomain. -/
protected lemma separable_space [separable_space α] : separable_space β :=
de.to_dense_inducing.separable_space
/-- The product of two dense embeddings is a dense embedding. -/
protected lemma prod {e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_embedding e₁)
(de₂ : dense_embedding e₂) :
dense_embedding (λ(p : α × γ), (e₁ p.1, e₂ p.2)) :=
{ inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩,
by simp; exact assume h₁ h₂, ⟨de₁.inj h₁, de₂.inj h₂⟩,
..dense_inducing.prod de₁.to_dense_inducing de₂.to_dense_inducing }
/-- The dense embedding of a subtype inside its closure. -/
def subtype_emb {α : Type*} (p : α → Prop) (e : α → β) (x : {x // p x}) :
{x // x ∈ closure (e '' {x | p x})} :=
⟨e x, subset_closure $ mem_image_of_mem e x.prop⟩
protected lemma subtype (p : α → Prop) : dense_embedding (subtype_emb p e) :=
{ dense_embedding .
dense := assume ⟨x, hx⟩, closure_subtype.mpr $
have (λ (x : {x // p x}), e x) = e ∘ coe, from rfl,
begin
rw ← image_univ,
simp [(image_comp _ _ _).symm, (∘), subtype_emb, -image_univ],
rw [this, image_comp, subtype.coe_image],
simp,
assumption
end,
inj := assume ⟨x, hx⟩ ⟨y, hy⟩ h, subtype.eq $ de.inj $ @@congr_arg subtype.val h,
induced := (induced_iff_nhds_eq _).2 (assume ⟨x, hx⟩,
by simp [subtype_emb, nhds_subtype_eq_comap, de.to_inducing.nhds_eq_comap, comap_comap, (∘)]) }
end dense_embedding
lemma is_closed_property [topological_space β] {e : α → β} {p : β → Prop}
(he : dense_range e) (hp : is_closed {x | p x}) (h : ∀a, p (e a)) :
∀b, p b :=
have univ ⊆ {b | p b},
from calc univ = closure (range e) : he.closure_range.symm
... ⊆ closure {b | p b} : closure_mono $ range_subset_iff.mpr h
... = _ : hp.closure_eq,
assume b, this trivial
lemma is_closed_property2 [topological_space β] {e : α → β} {p : β → β → Prop}
(he : dense_range e) (hp : is_closed {q:β×β | p q.1 q.2}) (h : ∀a₁ a₂, p (e a₁) (e a₂)) :
∀b₁ b₂, p b₁ b₂ :=
have ∀q:β×β, p q.1 q.2,
from is_closed_property (he.prod_map he) hp $ λ _, h _ _,
assume b₁ b₂, this ⟨b₁, b₂⟩
lemma is_closed_property3 [topological_space β] {e : α → β} {p : β → β → β → Prop}
(he : dense_range e) (hp : is_closed {q:β×β×β | p q.1 q.2.1 q.2.2})
(h : ∀a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃)) :
∀b₁ b₂ b₃, p b₁ b₂ b₃ :=
have ∀q:β×β×β, p q.1 q.2.1 q.2.2,
from is_closed_property (he.prod_map $ he.prod_map he) hp $ λ _, h _ _ _,
assume b₁ b₂ b₃, this ⟨b₁, b₂, b₃⟩
@[elab_as_eliminator]
lemma dense_range.induction_on [topological_space β] {e : α → β} (he : dense_range e) {p : β → Prop}
(b₀ : β) (hp : is_closed {b | p b}) (ih : ∀a:α, p $ e a) : p b₀ :=
is_closed_property he hp ih b₀
@[elab_as_eliminator]
lemma dense_range.induction_on₂ [topological_space β] {e : α → β} {p : β → β → Prop}
(he : dense_range e) (hp : is_closed {q:β×β | p q.1 q.2}) (h : ∀a₁ a₂, p (e a₁) (e a₂))
(b₁ b₂ : β) : p b₁ b₂ := is_closed_property2 he hp h _ _
@[elab_as_eliminator]
lemma dense_range.induction_on₃ [topological_space β] {e : α → β} {p : β → β → β → Prop}
(he : dense_range e) (hp : is_closed {q:β×β×β | p q.1 q.2.1 q.2.2})
(h : ∀a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃))
(b₁ b₂ b₃ : β) : p b₁ b₂ b₃ := is_closed_property3 he hp h _ _ _
section
variables [topological_space β] [topological_space γ] [t2_space γ]
variables {f : α → β}
/-- Two continuous functions to a t2-space that agree on the dense range of a function are equal. -/
lemma dense_range.equalizer (hfd : dense_range f)
{g h : β → γ} (hg : continuous g) (hh : continuous h) (H : g ∘ f = h ∘ f) :
g = h :=
funext $ λ y, hfd.induction_on y (is_closed_eq hg hh) $ congr_fun H
end
|
310cb2f6980d82db25b4020242703f961b1ea22b | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/category_theory/adjunction/limits.lean | 3421e92e79d0e1d52a7e7b1cf96f4abab7f5f329 | [
"Apache-2.0"
] | permissive | ChrisHughes24/mathlib | 98322577c460bc6b1fe5c21f42ce33ad1c3e5558 | a2a867e827c2a6702beb9efc2b9282bd801d5f9a | refs/heads/master | 1,583,848,251,477 | 1,565,164,247,000 | 1,565,164,247,000 | 129,409,993 | 0 | 1 | Apache-2.0 | 1,565,164,817,000 | 1,523,628,059,000 | Lean | UTF-8 | Lean | false | false | 5,535 | 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.preserves
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+1} C] {D : Type u₂} [𝒟 : category.{v+1} D]
include 𝒞 𝒟
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)
def functoriality_is_left_adjoint :
is_left_adjoint (@cocones.functoriality _ _ _ _ K _ _ F) :=
{ right := (cocones.functoriality G) ⋙ (cocones.precompose
(K.right_unitor.inv ≫ (whisker_left K adj.unit) ≫ (associator _ _ _).inv)),
adj := mk_of_unit_counit
{ unit := { app := λ c, { hom := adj.unit.app c.X } },
counit := { app := λ c, { hom := adj.counit.app c.X } } } }
/-- A left adjoint preserves colimits. -/
instance 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, (((adj.functoriality_is_left_adjoint _).adj).hom_equiv _ _).unique_of_equiv $
is_colimit_iso_unique_cocone_morphism.hom hc _ ) } } }.
omit adj
instance is_equivalence_preserves_colimits (E : C ⥤ D) [is_equivalence E] : preserves_colimits E :=
adjunction.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) :=
by apply_instance
instance has_colimit_comp_equivalence (E : C ⥤ D) [is_equivalence E] [has_colimit K] :
has_colimit (K ⋙ E) :=
{ cocone := E.map_cocone (colimit.cocone K) }
def 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)
def functoriality_is_right_adjoint :
is_right_adjoint (@cones.functoriality _ _ _ _ K _ _ G) :=
{ left := (cones.functoriality F) ⋙ (cones.postcompose
((associator _ _ _).hom ≫ (whisker_left K adj.counit) ≫ K.right_unitor.hom)),
adj := mk_of_unit_counit
{ unit := { app := λ c, { hom := adj.unit.app c.X, } },
counit := { app := λ c, { hom := adj.counit.app c.X, } } } }
/-- A right adjoint preserves limits. -/
instance 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, (((adj.functoriality_is_right_adjoint _).adj).hom_equiv _ _).symm.unique_of_equiv $
is_limit_iso_unique_cone_morphism.hom hc _) } } }.
omit adj
instance is_equivalence_preserves_limits (E : D ⥤ C) [is_equivalence E] : preserves_limits E :=
adjunction.right_adjoint_preserves_limits E.inv.adjunction
-- 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) :=
by apply_instance
instance has_limit_comp_equivalence (E : D ⥤ C) [is_equivalence E] [has_limit K] :
has_limit (K ⋙ E) :=
{ cone := E.map_cone (limit.cone K) }
def 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
-- 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 := λ t,
{ 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 },
inv := λ t,
{ 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 } } )
(by tidy)
-- Note: this is natural in K, but we do not yet have the tools to formulate that.
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 := λ t,
{ 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 },
inv := λ t,
{ 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 } } )
(by tidy)
end category_theory.adjunction
|
bf52de57e056f1e8773ec72bf3f6734d85cc34a9 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/check.lean | 092c1427e851ac6aaa02def7a5dd579a024c69cc | [
"Apache-2.0"
] | permissive | leanprover-community/lean | 12b87f69d92e614daea8bcc9d4de9a9ace089d0e | cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0 | refs/heads/master | 1,687,508,156,644 | 1,684,951,104,000 | 1,684,951,104,000 | 169,960,991 | 457 | 107 | Apache-2.0 | 1,686,744,372,000 | 1,549,790,268,000 | C++ | UTF-8 | Lean | false | false | 60 | lean | --
#check and.intro
#check or.elim
#check eq
#check eq.rec
|
ddaf5b3101016fb808d8d76b2319d1e8b6e6ed93 | 8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3 | /src/data/polynomial/ring_division.lean | f5c1fb1dec489f958ee9a243409393b3a4f23cd5 | [
"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 | 27,881 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker, Johan Commelin
-/
import data.polynomial.algebra_map
import data.polynomial.degree.lemmas
import data.polynomial.div
/-!
# Theory of univariate polynomials
This file starts looking like the ring theory of $ R[X] $
-/
noncomputable theory
open_locale classical
open finset
namespace polynomial
universes u v w z
variables {R : Type u} {S : Type v} {T : Type w} {A : Type z} {a b : R} {n : ℕ}
section comm_ring
variables [comm_ring R] {p q : polynomial R}
variables [comm_ring S]
lemma nat_degree_pos_of_aeval_root [algebra R S] {p : polynomial R} (hp : p ≠ 0)
{z : S} (hz : aeval z p = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) :
0 < p.nat_degree :=
nat_degree_pos_of_eval₂_root hp (algebra_map R S) hz inj
lemma degree_pos_of_aeval_root [algebra R S] {p : polynomial R} (hp : p ≠ 0)
{z : S} (hz : aeval z p = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) :
0 < p.degree :=
nat_degree_pos_iff_degree_pos.mp (nat_degree_pos_of_aeval_root hp hz inj)
lemma aeval_mod_by_monic_eq_self_of_root [algebra R S]
{p q : polynomial R} (hq : q.monic) {x : S} (hx : aeval x q = 0) :
aeval x (p %ₘ q) = aeval x p :=
eval₂_mod_by_monic_eq_self_of_root hq hx
end comm_ring
section no_zero_divisors
variables [comm_ring R] [no_zero_divisors R] {p q : polynomial R}
instance : no_zero_divisors (polynomial R) :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin
rw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero],
refine eq_zero_or_eq_zero_of_mul_eq_zero _,
rw [← leading_coeff_zero, ← leading_coeff_mul, h],
end }
lemma nat_degree_mul (hp : p ≠ 0) (hq : q ≠ 0) : nat_degree (p * q) =
nat_degree p + nat_degree q :=
by rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree (mul_ne_zero hp hq),
with_bot.coe_add, ← degree_eq_nat_degree hp,
← degree_eq_nat_degree hq, degree_mul]
@[simp] lemma nat_degree_pow (p : polynomial R) (n : ℕ) :
nat_degree (p ^ n) = n * nat_degree p :=
if hp0 : p = 0
then if hn0 : n = 0 then by simp [hp0, hn0]
else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp
else nat_degree_pow'
(by rw [← leading_coeff_pow, ne.def, leading_coeff_eq_zero]; exact pow_ne_zero _ hp0)
lemma root_mul : is_root (p * q) a ↔ is_root p a ∨ is_root q a :=
by simp_rw [is_root, eval_mul, mul_eq_zero]
lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a :=
root_mul.1 h
lemma degree_le_mul_left (p : polynomial R) (hq : q ≠ 0) : degree p ≤ degree (p * q) :=
if hp : p = 0 then by simp only [hp, zero_mul, le_refl]
else by rw [degree_mul, degree_eq_nat_degree hp,
degree_eq_nat_degree hq];
exact with_bot.coe_le_coe.2 (nat.le_add_right _ _)
theorem nat_degree_le_of_dvd {p q : polynomial R} (h1 : p ∣ q) (h2 : q ≠ 0) :
p.nat_degree ≤ q.nat_degree :=
begin
rcases h1 with ⟨q, rfl⟩, rw mul_ne_zero_iff at h2,
rw [nat_degree_mul h2.1 h2.2], exact nat.le_add_right _ _
end
end no_zero_divisors
section integral_domain
variables [integral_domain R] {p q : polynomial R}
instance : integral_domain (polynomial R) :=
{ ..polynomial.no_zero_divisors,
..polynomial.nontrivial,
..polynomial.comm_ring }
lemma nat_trailing_degree_mul (hp : p ≠ 0) (hq : q ≠ 0) :
(p * q).nat_trailing_degree = p.nat_trailing_degree + q.nat_trailing_degree :=
begin
simp only [←nat.sub_eq_of_eq_add (nat_degree_eq_reverse_nat_degree_add_nat_trailing_degree _)],
rw [reverse_mul_of_domain, nat_degree_mul hp hq, nat_degree_mul (mt reverse_eq_zero.mp hp)
(mt reverse_eq_zero.mp hq), reverse_nat_degree, reverse_nat_degree, ←nat.sub_sub, nat.add_comm,
nat.add_sub_assoc (nat.sub_le _ _), add_comm, nat.add_sub_assoc (nat.sub_le _ _)],
end
section roots
open multiset
local attribute [semireducible] with_zero
lemma degree_eq_zero_of_is_unit (h : is_unit p) : degree p = 0 :=
let ⟨q, hq⟩ := is_unit_iff_dvd_one.1 h in
have hp0 : p ≠ 0, from λ hp0, by simpa [hp0] using hq,
have hq0 : q ≠ 0, from λ hp0, by simpa [hp0] using hq,
have nat_degree (1 : polynomial R) = nat_degree (p * q),
from congr_arg _ hq,
by rw [nat_degree_one, nat_degree_mul hp0 hq0, eq_comm,
_root_.add_eq_zero_iff, ← with_bot.coe_eq_coe,
← degree_eq_nat_degree hp0] at this;
exact this.1
@[simp] lemma degree_coe_units (u : units (polynomial R)) :
degree (u : polynomial R) = 0 :=
degree_eq_zero_of_is_unit ⟨u, rfl⟩
theorem prime_X_sub_C (r : R) : prime (X - C r) :=
⟨X_sub_C_ne_zero r, not_is_unit_X_sub_C,
λ _ _, by { simp_rw [dvd_iff_is_root, is_root.def, eval_mul, mul_eq_zero], exact id }⟩
theorem prime_X : prime (X : polynomial R) :=
by { convert (prime_X_sub_C (0 : R)), simp }
lemma monic.prime_of_degree_eq_one (hp1 : degree p = 1) (hm : monic p) :
prime p :=
have p = X - C (- p.coeff 0),
by simpa [hm.leading_coeff] using eq_X_add_C_of_degree_eq_one hp1,
this.symm ▸ prime_X_sub_C _
theorem irreducible_X_sub_C (r : R) : irreducible (X - C r) :=
(prime_X_sub_C r).irreducible
theorem irreducible_X : irreducible (X : polynomial R) :=
prime.irreducible prime_X
lemma monic.irreducible_of_degree_eq_one (hp1 : degree p = 1) (hm : monic p) :
irreducible p :=
(hm.prime_of_degree_eq_one hp1).irreducible
theorem eq_of_monic_of_associated (hp : p.monic) (hq : q.monic) (hpq : associated p q) : p = q :=
begin
obtain ⟨u, hu⟩ := hpq,
unfold monic at hp hq,
rw eq_C_of_degree_le_zero (le_of_eq $ degree_coe_units _) at hu,
rw [← hu, leading_coeff_mul, hp, one_mul, leading_coeff_C] at hq,
rwa [hq, C_1, mul_one] at hu
end
@[simp] lemma root_multiplicity_zero {x : R} : root_multiplicity x 0 = 0 := dif_pos rfl
lemma root_multiplicity_eq_zero {p : polynomial R} {x : R} (h : ¬ is_root p x) :
root_multiplicity x p = 0 :=
begin
rw root_multiplicity_eq_multiplicity,
split_ifs, { refl },
rw [← enat.coe_inj, enat.coe_get, multiplicity.multiplicity_eq_zero_of_not_dvd, enat.coe_zero],
intro hdvd,
exact h (dvd_iff_is_root.mp hdvd)
end
lemma root_multiplicity_pos {p : polynomial R} (hp : p ≠ 0) {x : R} :
0 < root_multiplicity x p ↔ is_root p x :=
begin
rw [← dvd_iff_is_root, root_multiplicity_eq_multiplicity, dif_neg hp,
← enat.coe_lt_coe, enat.coe_get],
exact multiplicity.dvd_iff_multiplicity_pos
end
lemma root_multiplicity_mul {p q : polynomial R} {x : R} (hpq : p * q ≠ 0) :
root_multiplicity x (p * q) = root_multiplicity x p + root_multiplicity x q :=
begin
have hp : p ≠ 0 := left_ne_zero_of_mul hpq,
have hq : q ≠ 0 := right_ne_zero_of_mul hpq,
rw [root_multiplicity_eq_multiplicity (p * q), dif_neg hpq,
root_multiplicity_eq_multiplicity p, dif_neg hp,
root_multiplicity_eq_multiplicity q, dif_neg hq,
multiplicity.mul' (prime_X_sub_C x)],
end
lemma root_multiplicity_X_sub_C_self {x : R} :
root_multiplicity x (X - C x) = 1 :=
by rw [root_multiplicity_eq_multiplicity, dif_neg (X_sub_C_ne_zero x),
multiplicity.get_multiplicity_self]
lemma root_multiplicity_X_sub_C {x y : R} :
root_multiplicity x (X - C y) = if x = y then 1 else 0 :=
begin
split_ifs with hxy,
{ rw hxy,
exact root_multiplicity_X_sub_C_self },
exact root_multiplicity_eq_zero (mt root_X_sub_C.mp (ne.symm hxy))
end
/-- The multiplicity of `a` as root of `(X - a) ^ n` is `n`. -/
lemma root_multiplicity_X_sub_C_pow (a : R) (n : ℕ) : root_multiplicity a ((X - C a) ^ n) = n :=
begin
induction n with n hn,
{ refine root_multiplicity_eq_zero _,
simp only [eval_one, is_root.def, not_false_iff, one_ne_zero, pow_zero] },
have hzero := (ne_zero_of_monic (monic_pow (monic_X_sub_C a) n.succ)),
rw pow_succ (X - C a) n at hzero ⊢,
simp only [root_multiplicity_mul hzero, root_multiplicity_X_sub_C_self, hn, nat.one_add]
end
/-- If `(X - a) ^ n` divides a polynomial `p` then the multiplicity of `a` as root of `p` is at
least `n`. -/
lemma root_multiplicity_of_dvd {p : polynomial R} {a : R} {n : ℕ}
(hzero : p ≠ 0) (h : (X - C a) ^ n ∣ p) : n ≤ root_multiplicity a p :=
begin
obtain ⟨q, hq⟩ := exists_eq_mul_right_of_dvd h,
rw hq at hzero,
simp only [hq, root_multiplicity_mul hzero, root_multiplicity_X_sub_C_pow,
ge_iff_le, _root_.zero_le, le_add_iff_nonneg_right],
end
/-- The multiplicity of `p + q` is at least the minimum of the multiplicities. -/
lemma root_multiplicity_add {p q : polynomial R} (a : R) (hzero : p + q ≠ 0) :
min (root_multiplicity a p) (root_multiplicity a q) ≤ root_multiplicity a (p + q) :=
begin
refine root_multiplicity_of_dvd hzero _,
have hdivp : (X - C a) ^ root_multiplicity a p ∣ p := pow_root_multiplicity_dvd p a,
have hdivq : (X - C a) ^ root_multiplicity a q ∣ q := pow_root_multiplicity_dvd q a,
exact min_pow_dvd_add hdivp hdivq
end
lemma exists_multiset_roots : ∀ {p : polynomial R} (hp : p ≠ 0),
∃ s : multiset R, (s.card : with_bot ℕ) ≤ degree p ∧ ∀ a, s.count a = root_multiplicity a p
| p := λ hp, by haveI := classical.prop_decidable (∃ x, is_root p x); exact
if h : ∃ x, is_root p x
then
let ⟨x, hx⟩ := h in
have hpd : 0 < degree p := degree_pos_of_root hp hx,
have hd0 : p /ₘ (X - C x) ≠ 0 :=
λ h, by rw [← mul_div_by_monic_eq_iff_is_root.2 hx, h, mul_zero] at hp; exact hp rfl,
have wf : degree (p /ₘ _) < degree p :=
degree_div_by_monic_lt _ (monic_X_sub_C x) hp
((degree_X_sub_C x).symm ▸ dec_trivial),
let ⟨t, htd, htr⟩ := @exists_multiset_roots (p /ₘ (X - C x)) hd0 in
have hdeg : degree (X - C x) ≤ degree p := begin
rw [degree_X_sub_C, degree_eq_nat_degree hp],
rw degree_eq_nat_degree hp at hpd,
exact with_bot.coe_le_coe.2 (with_bot.coe_lt_coe.1 hpd)
end,
have hdiv0 : p /ₘ (X - C x) ≠ 0 := mt (div_by_monic_eq_zero_iff (monic_X_sub_C x)
(ne_zero_of_monic (monic_X_sub_C x))).1 $ not_lt.2 hdeg,
⟨x ::ₘ t, calc (card (x ::ₘ t) : with_bot ℕ) = t.card + 1 :
by exact_mod_cast card_cons _ _
... ≤ degree p :
by rw [← degree_add_div_by_monic (monic_X_sub_C x) hdeg,
degree_X_sub_C, add_comm];
exact add_le_add (le_refl (1 : with_bot ℕ)) htd,
begin
assume a,
conv_rhs { rw ← mul_div_by_monic_eq_iff_is_root.mpr hx },
rw [root_multiplicity_mul (mul_ne_zero (X_sub_C_ne_zero x) hdiv0),
root_multiplicity_X_sub_C, ← htr a],
split_ifs with ha,
{ rw [ha, count_cons_self, nat.succ_eq_add_one, add_comm] },
{ rw [count_cons_of_ne ha, zero_add] },
end⟩
else
⟨0, (degree_eq_nat_degree hp).symm ▸ with_bot.coe_le_coe.2 (nat.zero_le _),
by { intro a, rw [count_zero, root_multiplicity_eq_zero (not_exists.mp h a)] }⟩
using_well_founded {dec_tac := tactic.assumption}
/-- `roots p` noncomputably gives a multiset containing all the roots of `p`,
including their multiplicities. -/
noncomputable def roots (p : polynomial R) : multiset R :=
if h : p = 0 then ∅ else classical.some (exists_multiset_roots h)
@[simp] lemma roots_zero : (0 : polynomial R).roots = 0 :=
dif_pos rfl
lemma card_roots (hp0 : p ≠ 0) : ((roots p).card : with_bot ℕ) ≤ degree p :=
begin
unfold roots,
rw dif_neg hp0,
exact (classical.some_spec (exists_multiset_roots hp0)).1
end
lemma card_roots' {p : polynomial R} (hp0 : p ≠ 0) : p.roots.card ≤ nat_degree p :=
with_bot.coe_le_coe.1 (le_trans (card_roots hp0) (le_of_eq $ degree_eq_nat_degree hp0))
lemma card_roots_sub_C {p : polynomial R} {a : R} (hp0 : 0 < degree p) :
((p - C a).roots.card : with_bot ℕ) ≤ degree p :=
calc ((p - C a).roots.card : with_bot ℕ) ≤ degree (p - C a) :
card_roots $ mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le
... = degree p : by rw [sub_eq_add_neg, ← C_neg]; exact degree_add_C hp0
lemma card_roots_sub_C' {p : polynomial R} {a : R} (hp0 : 0 < degree p) :
(p - C a).roots.card ≤ nat_degree p :=
with_bot.coe_le_coe.1 (le_trans (card_roots_sub_C hp0) (le_of_eq $ degree_eq_nat_degree
(λ h, by simp [*, lt_irrefl] at *)))
@[simp] lemma count_roots (hp : p ≠ 0) : p.roots.count a = root_multiplicity a p :=
by { rw [roots, dif_neg hp], exact (classical.some_spec (exists_multiset_roots hp)).2 a }
@[simp] lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a :=
by rw [← count_pos, count_roots hp, root_multiplicity_pos hp]
lemma eq_zero_of_infinite_is_root
(p : polynomial R) (h : set.infinite {x | is_root p x}) : p = 0 :=
begin
by_contradiction hp,
apply h,
convert p.roots.to_finset.finite_to_set using 1,
ext1 r,
simp only [mem_roots hp, multiset.mem_to_finset, set.mem_set_of_eq, finset.mem_coe]
end
lemma exists_max_root [linear_order R] (p : polynomial R) (hp : p ≠ 0) :
∃ x₀, ∀ x, p.is_root x → x ≤ x₀ :=
set.exists_upper_bound_image _ _ $ not_not.mp (mt (eq_zero_of_infinite_is_root p) hp)
lemma exists_min_root [linear_order R] (p : polynomial R) (hp : p ≠ 0) :
∃ x₀, ∀ x, p.is_root x → x₀ ≤ x :=
set.exists_lower_bound_image _ _ $ not_not.mp (mt (eq_zero_of_infinite_is_root p) hp)
lemma eq_of_infinite_eval_eq {R : Type*} [integral_domain R]
(p q : polynomial R) (h : set.infinite {x | eval x p = eval x q}) : p = q :=
begin
rw [← sub_eq_zero],
apply eq_zero_of_infinite_is_root,
simpa only [is_root, eval_sub, sub_eq_zero]
end
lemma roots_mul {p q : polynomial R} (hpq : p * q ≠ 0) : (p * q).roots = p.roots + q.roots :=
multiset.ext.mpr $ λ r,
by rw [count_add, count_roots hpq, count_roots (left_ne_zero_of_mul hpq),
count_roots (right_ne_zero_of_mul hpq), root_multiplicity_mul hpq]
@[simp] lemma mem_roots_sub_C {p : polynomial R} {a x : R} (hp0 : 0 < degree p) :
x ∈ (p - C a).roots ↔ p.eval x = a :=
(mem_roots (show p - C a ≠ 0, from mt sub_eq_zero.1 $ λ h,
not_le_of_gt hp0 $ h.symm ▸ degree_C_le)).trans
(by rw [is_root.def, eval_sub, eval_C, sub_eq_zero])
@[simp] lemma roots_X_sub_C (r : R) : roots (X - C r) = r ::ₘ 0 :=
begin
ext s,
rw [count_roots (X_sub_C_ne_zero r), root_multiplicity_X_sub_C],
split_ifs with h,
{ rw [h, count_singleton] },
{ rw [count_cons_of_ne h, count_zero] }
end
@[simp] lemma roots_C (x : R) : (C x).roots = 0 :=
if H : x = 0 then by rw [H, C_0, roots_zero] else multiset.ext.mpr $ λ r,
have h : C x ≠ 0, from λ h, H $ C_inj.1 $ h.symm ▸ C_0.symm,
have not_root : ¬ is_root (C x) r := mt (λ (h : eval r (C x) = 0), trans eval_C.symm h) H,
by rw [count_roots h, count_zero, root_multiplicity_eq_zero not_root]
@[simp] lemma roots_one : (1 : polynomial R).roots = ∅ :=
roots_C 1
lemma roots_list_prod (L : list (polynomial R)) :
((0 : polynomial R) ∉ L) → L.prod.roots = (L : multiset (polynomial R)).bind roots :=
list.rec_on L (λ _, roots_one) $ λ hd tl ih H,
begin
rw [list.mem_cons_iff, not_or_distrib] at H,
rw [list.prod_cons, roots_mul (mul_ne_zero (ne.symm H.1) $ list.prod_ne_zero H.2),
← multiset.cons_coe, multiset.cons_bind, ih H.2]
end
lemma roots_multiset_prod (m : multiset (polynomial R)) :
(0 : polynomial R) ∉ m → m.prod.roots = m.bind roots :=
by { rcases m with ⟨L⟩, simpa only [coe_prod, quot_mk_to_coe''] using roots_list_prod L }
lemma roots_prod {ι : Type*} (f : ι → polynomial R) (s : finset ι) :
s.prod f ≠ 0 → (s.prod f).roots = s.val.bind (λ i, roots (f i)) :=
begin
rcases s with ⟨m, hm⟩,
simpa [multiset.prod_eq_zero_iff, bind_map] using roots_multiset_prod (m.map f)
end
lemma roots_prod_X_sub_C (s : finset R) :
(s.prod (λ a, X - C a)).roots = s.val :=
(roots_prod (λ a, X - C a) s (prod_ne_zero_iff.mpr (λ a _, X_sub_C_ne_zero a))).trans
(by simp_rw [roots_X_sub_C, bind_cons, bind_zero, add_zero, multiset.map_id'])
lemma card_roots_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) :
(roots ((X : polynomial R) ^ n - C a)).card ≤ n :=
with_bot.coe_le_coe.1 $
calc ((roots ((X : polynomial R) ^ n - C a)).card : with_bot ℕ)
≤ degree ((X : polynomial R) ^ n - C a) : card_roots (X_pow_sub_C_ne_zero hn a)
... = n : degree_X_pow_sub_C hn a
section nth_roots
/-- `nth_roots n a` noncomputably returns the solutions to `x ^ n = a`-/
def nth_roots (n : ℕ) (a : R) : multiset R :=
roots ((X : polynomial R) ^ n - C a)
@[simp] lemma mem_nth_roots {n : ℕ} (hn : 0 < n) {a x : R} :
x ∈ nth_roots n a ↔ x ^ n = a :=
by rw [nth_roots, mem_roots (X_pow_sub_C_ne_zero hn a),
is_root.def, eval_sub, eval_C, eval_pow, eval_X, sub_eq_zero]
@[simp] lemma nth_roots_zero (r : R) : nth_roots 0 r = 0 :=
by simp only [empty_eq_zero, pow_zero, nth_roots, ← C_1, ← C_sub, roots_C]
lemma card_nth_roots (n : ℕ) (a : R) :
(nth_roots n a).card ≤ n :=
if hn : n = 0
then if h : (X : polynomial R) ^ n - C a = 0
then by simp only [nat.zero_le, nth_roots, roots, h, dif_pos rfl, empty_eq_zero, card_zero]
else with_bot.coe_le_coe.1 (le_trans (card_roots h)
(by { rw [hn, pow_zero, ← C_1, ← ring_hom.map_sub ],
exact degree_C_le }))
else by rw [← with_bot.coe_le_coe, ← degree_X_pow_sub_C (nat.pos_of_ne_zero hn) a];
exact card_roots (X_pow_sub_C_ne_zero (nat.pos_of_ne_zero hn) a)
/-- The multiset `nth_roots ↑n (1 : R)` as a finset. -/
def nth_roots_finset (n : ℕ) (R : Type*) [integral_domain R] : finset R :=
multiset.to_finset (nth_roots n (1 : R))
@[simp] lemma mem_nth_roots_finset {n : ℕ} (h : 0 < n) {x : R} :
x ∈ nth_roots_finset n R ↔ x ^ (n : ℕ) = 1 :=
by rw [nth_roots_finset, mem_to_finset, mem_nth_roots h]
end nth_roots
lemma coeff_comp_degree_mul_degree (hqd0 : nat_degree q ≠ 0) :
coeff (p.comp q) (nat_degree p * nat_degree q) =
leading_coeff p * leading_coeff q ^ nat_degree p :=
if hp0 : p = 0 then by simp [hp0] else
calc coeff (p.comp q) (nat_degree p * nat_degree q)
= p.sum (λ n a, coeff (C a * q ^ n) (nat_degree p * nat_degree q)) :
by rw [comp, eval₂, coeff_sum]
... = coeff (C (leading_coeff p) * q ^ nat_degree p) (nat_degree p * nat_degree q) :
finset.sum_eq_single _
begin
assume b hbs hbp,
have hq0 : q ≠ 0, from λ hq0, hqd0 (by rw [hq0, nat_degree_zero]),
have : coeff p b ≠ 0, by rwa mem_support_iff at hbs,
refine coeff_eq_zero_of_degree_lt _,
erw [degree_mul, degree_C this, degree_pow, zero_add, degree_eq_nat_degree hq0,
← with_bot.coe_nsmul, nsmul_eq_mul, with_bot.coe_lt_coe, nat.cast_id,
mul_lt_mul_right (pos_iff_ne_zero.mpr hqd0)],
exact lt_of_le_of_ne (le_nat_degree_of_ne_zero this) hbp,
end
begin
intro h, contrapose! hp0,
rw mem_support_iff at h, push_neg at h,
rwa ← leading_coeff_eq_zero,
end
... = _ :
have coeff (q ^ nat_degree p) (nat_degree p * nat_degree q) = leading_coeff (q ^ nat_degree p),
by rw [leading_coeff, nat_degree_pow],
by rw [coeff_C_mul, this, leading_coeff_pow]
lemma nat_degree_comp : nat_degree (p.comp q) = nat_degree p * nat_degree q :=
le_antisymm nat_degree_comp_le
(if hp0 : p = 0 then by rw [hp0, zero_comp, nat_degree_zero, zero_mul]
else if hqd0 : nat_degree q = 0
then have degree q ≤ 0, by rw [← with_bot.coe_zero, ← hqd0]; exact degree_le_nat_degree,
by rw [eq_C_of_degree_le_zero this]; simp
else le_nat_degree_of_ne_zero $
have hq0 : q ≠ 0, from λ hq0, hqd0 $ by rw [hq0, nat_degree_zero],
calc coeff (p.comp q) (nat_degree p * nat_degree q)
= leading_coeff p * leading_coeff q ^ nat_degree p :
coeff_comp_degree_mul_degree hqd0
... ≠ 0 : mul_ne_zero (mt leading_coeff_eq_zero.1 hp0)
(pow_ne_zero _ (mt leading_coeff_eq_zero.1 hq0)))
lemma leading_coeff_comp (hq : nat_degree q ≠ 0) : leading_coeff (p.comp q) =
leading_coeff p * leading_coeff q ^ nat_degree p :=
by rw [← coeff_comp_degree_mul_degree hq, ← nat_degree_comp]; refl
lemma units_coeff_zero_smul (c : units (polynomial R)) (p : polynomial R) :
(c : polynomial R).coeff 0 • p = c * p :=
by rw [←polynomial.C_mul', ←polynomial.eq_C_of_degree_eq_zero (degree_coe_units c)]
@[simp] lemma nat_degree_coe_units (u : units (polynomial R)) :
nat_degree (u : polynomial R) = 0 :=
nat_degree_eq_of_degree_eq_some (degree_coe_units u)
lemma comp_eq_zero_iff :
p.comp q = 0 ↔ p = 0 ∨ (p.eval (q.coeff 0) = 0 ∧ q = C (q.coeff 0)) :=
begin
split,
{ intro h,
have key : p.nat_degree = 0 ∨ q.nat_degree = 0,
{ rw [←mul_eq_zero, ←nat_degree_comp, h, nat_degree_zero] },
replace key := or.imp eq_C_of_nat_degree_eq_zero eq_C_of_nat_degree_eq_zero key,
cases key,
{ rw [key, C_comp] at h,
exact or.inl (key.trans h) },
{ rw [key, comp_C, C_eq_zero] at h,
exact or.inr ⟨h, key⟩ }, },
{ exact λ h, or.rec (λ h, by rw [h, zero_comp]) (λ h, by rw [h.2, comp_C, h.1, C_0]) h },
end
lemma zero_of_eval_zero [infinite R] (p : polynomial R) (h : ∀ x, p.eval x = 0) : p = 0 :=
by classical; by_contradiction hp; exact
fintype.false ⟨p.roots.to_finset, λ x, multiset.mem_to_finset.mpr ((mem_roots hp).mpr (h _))⟩
lemma funext [infinite R] {p q : polynomial R} (ext : ∀ r : R, p.eval r = q.eval r) : p = q :=
begin
rw ← sub_eq_zero,
apply zero_of_eval_zero,
intro x,
rw [eval_sub, sub_eq_zero, ext],
end
/-- The set of distinct roots of `p` in `E`.
If you have a non-separable polynomial, use `polynomial.roots` for the multiset
where multiple roots have the appropriate multiplicity. -/
def root_set (p : polynomial R) (S) [integral_domain S] [algebra R S] : set S :=
(p.map (algebra_map R S)).roots.to_finset
lemma root_set_def (p : polynomial R) (S) [integral_domain S] [algebra R S] :
p.root_set S = (p.map (algebra_map R S)).roots.to_finset :=
rfl
@[simp] lemma root_set_zero (S) [integral_domain S] [algebra R S] :
(0 : polynomial R).root_set S = ∅ :=
by rw [root_set_def, polynomial.map_zero, roots_zero, to_finset_zero, finset.coe_empty]
@[simp] lemma root_set_C [integral_domain S] [algebra R S] (a : R) : (C a).root_set S = ∅ :=
by rw [root_set_def, map_C, roots_C, multiset.to_finset_zero, finset.coe_empty]
instance root_set_fintype {R : Type*} [integral_domain R] (p : polynomial R) (S : Type*)
[integral_domain S] [algebra R S] : fintype (p.root_set S) :=
finset_coe.fintype _
lemma root_set_finite {R : Type*} [integral_domain R] (p : polynomial R) (S : Type*)
[integral_domain S] [algebra R S] : (p.root_set S).finite :=
⟨polynomial.root_set_fintype p S⟩
end roots
theorem is_unit_iff {f : polynomial R} : is_unit f ↔ ∃ r : R, is_unit r ∧ C r = f :=
⟨λ hf, ⟨f.coeff 0,
is_unit_C.1 $ eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf) ▸ hf,
(eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf)).symm⟩,
λ ⟨r, hr, hrf⟩, hrf ▸ is_unit_C.2 hr⟩
lemma coeff_coe_units_zero_ne_zero (u : units (polynomial R)) :
coeff (u : polynomial R) 0 ≠ 0 :=
begin
conv in (0) { rw [← nat_degree_coe_units u] },
rw [← leading_coeff, ne.def, leading_coeff_eq_zero],
exact units.ne_zero _
end
lemma degree_eq_degree_of_associated (h : associated p q) : degree p = degree q :=
let ⟨u, hu⟩ := h in by simp [hu.symm]
lemma degree_eq_one_of_irreducible_of_root (hi : irreducible p) {x : R} (hx : is_root p x) :
degree p = 1 :=
let ⟨g, hg⟩ := dvd_iff_is_root.2 hx in
have is_unit (X - C x) ∨ is_unit g, from hi.is_unit_or_is_unit hg,
this.elim
(λ h, have h₁ : degree (X - C x) = 1, from degree_X_sub_C x,
have h₂ : degree (X - C x) = 0, from degree_eq_zero_of_is_unit h,
by rw h₁ at h₂; exact absurd h₂ dec_trivial)
(λ hgu, by rw [hg, degree_mul, degree_X_sub_C, degree_eq_zero_of_is_unit hgu, add_zero])
/-- Division by a monic polynomial doesn't change the leading coefficient. -/
lemma leading_coeff_div_by_monic_of_monic {R : Type u} [integral_domain R] {p q : polynomial R}
(hmonic : q.monic) (hdegree : q.degree ≤ p.degree) : (p /ₘ q).leading_coeff = p.leading_coeff :=
begin
have hp := mod_by_monic_add_div p hmonic,
have hzero : (p /ₘ q) ≠ 0,
{ intro h,
exact not_lt_of_le hdegree ((div_by_monic_eq_zero_iff hmonic (monic.ne_zero hmonic)).1 h) },
have deglt : (p %ₘ q).degree < (q * (p /ₘ q)).degree,
{ rw degree_mul,
refine lt_of_lt_of_le (degree_mod_by_monic_lt p hmonic (monic.ne_zero hmonic)) _,
rw [degree_eq_nat_degree (monic.ne_zero hmonic), degree_eq_nat_degree hzero],
norm_cast,
simp only [zero_le, le_add_iff_nonneg_right] },
have hrew := (leading_coeff_add_of_degree_lt deglt),
rw leading_coeff_mul q (p /ₘ q) at hrew,
simp only [hmonic, one_mul, monic.leading_coeff] at hrew,
nth_rewrite 1 ← hp,
exact hrew.symm
end
lemma eq_of_monic_of_dvd_of_nat_degree_le (hp : p.monic) (hq : q.monic) (hdiv : p ∣ q)
(hdeg : q.nat_degree ≤ p.nat_degree) : q = p :=
begin
obtain ⟨r, hr⟩ := hdiv,
have rzero : r ≠ 0,
{ intro h,
simpa [h, monic.ne_zero hq] using hr },
rw [hr, nat_degree_mul (monic.ne_zero hp) rzero] at hdeg,
have hdegeq : p.nat_degree + r.nat_degree = p.nat_degree,
{ suffices hdegle : p.nat_degree ≤ p.nat_degree + r.nat_degree,
{ exact le_antisymm hdeg hdegle },
exact nat.le.intro rfl },
replace hdegeq := eq_C_of_nat_degree_eq_zero (((@add_right_inj _ _ p.nat_degree) _ 0).1 hdegeq),
suffices hlead : 1 = r.leading_coeff,
{ have hcoeff := leading_coeff_C (r.coeff 0),
rw [← hdegeq, ← hlead] at hcoeff,
rw [← hcoeff, C_1] at hdegeq,
rwa [hdegeq, mul_one] at hr },
have hprod : q.leading_coeff = p.leading_coeff * r.leading_coeff,
{ simp only [hr, leading_coeff_mul] },
rwa [monic.leading_coeff hp, monic.leading_coeff hq, one_mul] at hprod
end
end integral_domain
section
variables [semiring R] [integral_domain S] (φ : R →+* S)
lemma is_unit_of_is_unit_leading_coeff_of_is_unit_map
(f : polynomial R) (hf : is_unit (leading_coeff f)) (H : is_unit (map φ f)) :
is_unit f :=
begin
have dz := degree_eq_zero_of_is_unit H,
rw degree_map_eq_of_leading_coeff_ne_zero at dz,
{ rw eq_C_of_degree_eq_zero dz,
refine is_unit.map (C.to_monoid_hom : R →* polynomial R) _,
convert hf,
rw (degree_eq_iff_nat_degree_eq _).1 dz,
rintro rfl,
simpa using H, },
{ intro h,
have u : is_unit (φ f.leading_coeff) := is_unit.map φ.to_monoid_hom hf,
rw h at u,
simpa using u, }
end
end
section
variables [integral_domain R] [integral_domain S] (φ : R →+* S)
/--
A polynomial over an integral domain `R` is irreducible if it is monic and
irreducible after mapping into an integral domain `S`.
A special case of this lemma is that a polynomial over `ℤ` is irreducible if
it is monic and irreducible over `ℤ/pℤ` for some prime `p`.
-/
lemma monic.irreducible_of_irreducible_map (f : polynomial R)
(h_mon : monic f) (h_irr : irreducible (map φ f)) :
irreducible f :=
begin
fsplit,
{ intro h,
exact h_irr.not_unit (is_unit.map (map_ring_hom φ).to_monoid_hom h), },
{ intros a b h,
have q := (leading_coeff_mul a b).symm,
rw ←h at q,
dsimp [monic] at h_mon,
rw h_mon at q,
have au : is_unit a.leading_coeff := is_unit_of_mul_eq_one _ _ q,
rw mul_comm at q,
have bu : is_unit b.leading_coeff := is_unit_of_mul_eq_one _ _ q,
clear q h_mon,
have h' := congr_arg (map φ) h,
simp only [map_mul] at h',
cases h_irr.is_unit_or_is_unit h' with w w,
{ left,
exact is_unit_of_is_unit_leading_coeff_of_is_unit_map _ _ au w, },
{ right,
exact is_unit_of_is_unit_leading_coeff_of_is_unit_map _ _ bu w, }, }
end
end
end polynomial
namespace is_integral_domain
variables {R : Type*} [comm_ring R]
/-- Lift evidence that `is_integral_domain R` to `is_integral_domain (polynomial R)`. -/
lemma polynomial (h : is_integral_domain R) : is_integral_domain (polynomial R) :=
@integral_domain.to_is_integral_domain _ (@polynomial.integral_domain _ (h.to_integral_domain _))
end is_integral_domain
|
dcf7c7cfd817bb3099baed25a88d062c7b4decc5 | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/tactic/omega/coeffs.lean | 1aa233e78a758e78df528dfb03b9ebeb5614a742 | [
"Apache-2.0"
] | permissive | mcncm/mathlib | 8d25099344d9d2bee62822cb9ed43aa3e09fa05e | fde3d78cadeec5ef827b16ae55664ef115e66f57 | refs/heads/master | 1,672,743,316,277 | 1,602,618,514,000 | 1,602,618,514,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,610 | lean | /-
Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Seul Baek
-/
/-
Non-constant terms of linear constraints are represented
by storing their coefficients in integer lists.
-/
import data.list.func
import tactic.ring
import tactic.omega.misc
namespace omega
namespace coeffs
open list.func
variable {v : nat → int}
/-- `val_between v as l o` is the value (under valuation `v`) of the term
obtained taking the term represented by `(0, as)` and dropping all
subterms that include variables outside the range `[l,l+o)` -/
@[simp] def val_between (v : nat → int) (as : list int) (l : nat) : nat → int
| 0 := 0
| (o+1) := (val_between o) + (get (l+o) as * v (l+o))
@[simp] lemma val_between_nil {l : nat} :
∀ m, val_between v [] l m = 0
| 0 := by simp only [val_between]
| (m+1) :=
by simp only [val_between_nil m, omega.coeffs.val_between,
get_nil, zero_add, zero_mul, int.default_eq_zero]
/-- Evaluation of the nonconstant component of a normalized linear arithmetic term. -/
def val (v : nat → int) (as : list int) : int :=
val_between v as 0 as.length
@[simp] lemma val_nil : val v [] = 0 := rfl
lemma val_between_eq_of_le {as : list int} {l : nat} :
∀ m, as.length ≤ l + m →
val_between v as l m = val_between v as l (as.length - l)
| 0 h1 :=
begin rw (nat.sub_eq_zero_iff_le.elim_right _), apply h1 end
| (m+1) h1 :=
begin
rw le_iff_eq_or_lt at h1, cases h1,
{ rw [h1, add_comm l, nat.add_sub_cancel] },
have h2 : list.length as ≤ l + m,
{ rw ← nat.lt_succ_iff, apply h1 },
simpa [ get_eq_default_of_le _ h2, zero_mul, add_zero,
val_between ] using val_between_eq_of_le _ h2
end
lemma val_eq_of_le {as : list int} {k : nat} :
as.length ≤ k → val v as = val_between v as 0 k :=
begin
intro h1, unfold val,
rw [val_between_eq_of_le k _], refl,
rw zero_add, exact h1
end
lemma val_between_eq_val_between
{v w : nat → int} {as bs : list int} {l : nat} :
∀ {m}, (∀ x, l ≤ x → x < l + m → v x = w x) →
(∀ x, l ≤ x → x < l + m → get x as = get x bs) →
val_between v as l m = val_between w bs l m
| 0 h1 h2 := rfl
| (m+1) h1 h2 :=
begin
unfold val_between,
have h3 : l + m < l + (m + 1),
{ rw ← add_assoc, apply lt_add_one },
apply fun_mono_2,
apply val_between_eq_val_between; intros x h4 h5,
{ apply h1 _ h4 (lt_trans h5 h3) },
{ apply h2 _ h4 (lt_trans h5 h3) },
rw [h1 _ _ h3, h2 _ _ h3];
apply nat.le_add_right
end
open_locale list.func
lemma val_between_set {a : int} {l n : nat} :
∀ {m}, l ≤ n → n < l + m → val_between v ([] {n ↦ a}) l m = a * v n
| 0 h1 h2 :=
begin exfalso, apply lt_irrefl l (lt_of_le_of_lt h1 h2) end
| (m+1) h1 h2 :=
begin
rw [← add_assoc, nat.lt_succ_iff, le_iff_eq_or_lt] at h2,
cases h2; unfold val_between,
{ have h3 : val_between v ([] {l + m ↦ a}) l m = 0,
{ apply @eq.trans _ _ (val_between v [] l m),
{ apply val_between_eq_val_between,
{ intros, refl },
{ intros x h4 h5, rw [get_nil,
get_set_eq_of_ne, get_nil],
apply ne_of_lt h5 } },
apply val_between_nil },
rw h2,
simp only [h3, zero_add, list.func.get_set] },
{ have h3 : l + m ≠ n,
{ apply ne_of_gt h2 },
rw [@val_between_set m h1 h2, get_set_eq_of_ne _ _ h3],
simp only [h3, get_nil, add_zero, zero_mul, int.default_eq_zero] }
end
@[simp] lemma val_set {m : nat} {a : int} :
val v ([] {m ↦ a}) = a * v m :=
begin
apply val_between_set, apply zero_le,
apply lt_of_lt_of_le (lt_add_one _),
simp only [length_set, zero_add, le_max_right],
end
lemma val_between_neg {as : list int} {l : nat} :
∀ {o}, val_between v (neg as) l o = -(val_between v as l o)
| 0 := rfl
| (o+1) :=
begin
unfold val_between,
rw [neg_add, neg_mul_eq_neg_mul],
apply fun_mono_2,
apply val_between_neg,
apply fun_mono_2 _ rfl,
apply get_neg
end
@[simp] lemma val_neg {as : list int} :
val v (neg as) = -(val v as) :=
by simpa only [val, length_neg] using val_between_neg
lemma val_between_add {is js : list int} {l : nat} :
∀ m, val_between v (add is js) l m =
(val_between v is l m) + (val_between v js l m)
| 0 := rfl
| (m+1) :=
by { simp only [val_between, val_between_add m,
list.func.get, get_add], ring }
@[simp] lemma val_add {is js : list int} :
val v (add is js) = (val v is) + (val v js) :=
begin
unfold val,
rw val_between_add, apply fun_mono_2;
apply val_between_eq_of_le;
rw [zero_add, length_add],
apply le_max_left, apply le_max_right
end
lemma val_between_sub {is js : list int} {l : nat} :
∀ m, val_between v (sub is js) l m =
(val_between v is l m) - (val_between v js l m)
| 0 := rfl
| (m+1) :=
by { simp only [val_between, val_between_sub m,
list.func.get, get_sub], ring }
@[simp] lemma val_sub {is js : list int} :
val v (sub is js) = (val v is) - (val v js) :=
begin
unfold val,
rw val_between_sub,
apply fun_mono_2;
apply val_between_eq_of_le;
rw [zero_add, length_sub],
apply le_max_left,
apply le_max_right
end
/-- `val_except k v as` is the value (under valuation `v`) of the term
obtained taking the term represented by `(0, as)` and dropping the
subterm that includes the `k`th variable. -/
def val_except (k : nat) (v : nat → int) (as) :=
val_between v as 0 k + val_between v as (k+1) (as.length - (k+1))
lemma val_except_eq_val_except
{k : nat} {is js : list int} {v w : nat → int} :
(∀ x ≠ k, v x = w x) → (∀ x ≠ k, get x is = get x js) →
val_except k v is = val_except k w js :=
begin
intros h1 h2, unfold val_except,
apply fun_mono_2,
{ apply val_between_eq_val_between;
intros x h3 h4;
[ {apply h1}, {apply h2} ];
apply ne_of_lt;
rw zero_add at h4;
apply h4 },
{ repeat { rw ← val_between_eq_of_le
((max is.length js.length) - (k+1)) },
{ apply val_between_eq_val_between;
intros x h3 h4;
[ {apply h1}, {apply h2} ];
apply ne.symm;
apply ne_of_lt;
rw nat.lt_iff_add_one_le;
exact h3 },
repeat { rw add_comm,
apply le_trans _ (nat.le_sub_add _ _),
{ apply le_max_right <|> apply le_max_left } } }
end
open_locale omega
lemma val_except_update_set
{n : nat} {as : list int} {i j : int} :
val_except n (v⟨n ↦ i⟩) (as {n ↦ j}) = val_except n v as :=
by apply val_except_eq_val_except update_eq_of_ne (get_set_eq_of_ne _)
lemma val_between_add_val_between {as : list int} {l m : nat} :
∀ {n}, val_between v as l m + val_between v as (l+m) n =
val_between v as l (m+n)
| 0 := by simp only [val_between, add_zero]
| (n+1) :=
begin
rw ← add_assoc,
unfold val_between,
rw add_assoc,
rw ← @val_between_add_val_between n,
ring,
end
lemma val_except_add_eq (n : nat) {as : list int} :
(val_except n v as) + ((get n as) * (v n)) = val v as :=
begin
unfold val_except, unfold val,
by_cases h1 : n + 1 ≤ as.length,
{ have h4 := @val_between_add_val_between v as 0 (n+1) (as.length - (n+1)),
have h5 : n + 1 + (as.length - (n + 1)) = as.length,
{ rw [add_comm, nat.sub_add_cancel h1] },
rw h5 at h4, apply eq.trans _ h4,
simp only [val_between, zero_add], ring },
have h2 : (list.length as - (n + 1)) = 0,
{ apply nat.sub_eq_zero_of_le
(le_trans (not_lt.1 h1) (nat.le_add_right _ _)) },
have h3 : val_between v as 0 (list.length as) =
val_between v as 0 (n + 1),
{ simpa only [val] using @val_eq_of_le v as (n+1)
(le_trans (not_lt.1 h1) (nat.le_add_right _ _)) },
simp only [add_zero, val_between, zero_add, h2, h3]
end
@[simp] lemma val_between_map_mul {i : int} {as: list int} {l : nat} :
∀ {m}, val_between v (list.map ((*) i) as) l m = i * val_between v as l m
| 0 := by simp only [val_between, mul_zero, list.map]
| (m+1) :=
begin
unfold val_between,
rw [@val_between_map_mul m, mul_add],
apply fun_mono_2 rfl,
by_cases h1 : l + m < as.length,
{ rw [get_map h1, mul_assoc] },
rw not_lt at h1,
rw [get_eq_default_of_le, get_eq_default_of_le];
try {simp}; apply h1
end
lemma forall_val_dvd_of_forall_mem_dvd {i : int} {as : list int} :
(∀ x ∈ as, i ∣ x) → (∀ n, i ∣ get n as) | h1 n :=
by { apply forall_val_of_forall_mem _ h1,
apply dvd_zero }
lemma dvd_val_between {i} {as: list int} {l : nat} :
∀ {m}, (∀ x ∈ as, i ∣ x) → (i ∣ val_between v as l m)
| 0 h1 := dvd_zero _
| (m+1) h1 :=
begin
unfold val_between,
apply dvd_add,
apply dvd_val_between h1,
apply dvd_mul_of_dvd_left,
by_cases h2 : get (l+m) as = 0,
{ rw h2, apply dvd_zero },
apply h1, apply mem_get_of_ne_zero h2
end
lemma dvd_val {as : list int} {i : int} :
(∀ x ∈ as, i ∣ x) → (i ∣ val v as) := by apply dvd_val_between
@[simp] lemma val_between_map_div
{as: list int} {i : int} {l : nat} (h1 : ∀ x ∈ as, i ∣ x) :
∀ {m}, val_between v (list.map (λ x, x / i) as) l m = (val_between v as l m) / i
| 0 := by simp only [int.zero_div, val_between, list.map]
| (m+1) :=
begin
unfold val_between,
rw [@val_between_map_div m, int.add_div_of_dvd (dvd_val_between h1)],
apply fun_mono_2 rfl,
{ apply calc get (l + m) (list.map (λ (x : ℤ), x / i) as) * v (l + m)
= ((get (l + m) as) / i) * v (l + m) :
begin
apply fun_mono_2 _ rfl,
rw get_map',
apply int.zero_div
end
... = get (l + m) as * v (l + m) / i :
begin
repeat {rw mul_comm _ (v (l+m))},
rw int.mul_div_assoc,
apply forall_val_dvd_of_forall_mem_dvd h1
end },
apply dvd_mul_of_dvd_left,
apply forall_val_dvd_of_forall_mem_dvd h1,
end
@[simp] lemma val_map_div {as : list int} {i : int} :
(∀ x ∈ as, i ∣ x) → val v (list.map (λ x, x / i) as) = (val v as) / i :=
by {intro h1, simpa only [val, list.length_map] using val_between_map_div h1}
lemma val_between_eq_zero {is: list int} {l : nat} :
∀ {m}, (∀ x : int, x ∈ is → x = 0) → val_between v is l m = 0
| 0 h1 := rfl
| (m+1) h1 :=
begin
have h2 := @forall_val_of_forall_mem _ _ is (λ x, x = 0) rfl h1,
simpa only [val_between, h2 (l+m), zero_mul, add_zero]
using @val_between_eq_zero m h1,
end
lemma val_eq_zero {is : list int} :
(∀ x : int, x ∈ is → x = 0) → val v is = 0 :=
by apply val_between_eq_zero
end coeffs
end omega
|
ad1a4e9c7c512dece311dafb0d3ce7f7f30ef137 | a4673261e60b025e2c8c825dfa4ab9108246c32e | /stage0/src/Lean/Elab/Syntax.lean | 6a294dfd35ba5c3ebe3cea258d6f08e53ef86a17 | [
"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 | 23,972 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.Command
import Lean.Elab.Quotation
namespace Lean.Elab.Term
/-
Expand `optional «precedence»` where
«precedence» := parser! " : " >> precedenceLit
precedenceLit : Parser := numLit <|> maxSymbol
maxSymbol := parser! nonReservedSymbol "max" -/
def expandOptPrecedence (stx : Syntax) : Option Nat :=
if stx.isNone then
none
else match stx[0][1].isNatLit? with
| some v => some v
| _ => some Parser.maxPrec
private def mkParserSeq (ds : Array Syntax) : TermElabM Syntax := do
if ds.size == 0 then
throwUnsupportedSyntax
else if ds.size == 1 then
pure ds[0]
else
let mut r := ds[0]
for d in ds[1:ds.size] do
r ← `(ParserDescr.binary `andthen $r $d)
return r
structure ToParserDescrContext :=
(catName : Name)
(first : Bool)
(leftRec : Bool) -- true iff left recursion is allowed
/- When `leadingIdentAsSymbol == true` we convert
`Lean.Parser.Syntax.atom` into `Lean.ParserDescr.nonReservedSymbol`
See comment at `Parser.ParserCategory`. -/
(leadingIdentAsSymbol : Bool)
abbrev ToParserDescrM := ReaderT ToParserDescrContext (StateRefT Bool TermElabM)
private def markAsTrailingParser : ToParserDescrM Unit := set true
@[inline] private def withNotFirst {α} (x : ToParserDescrM α) : ToParserDescrM α :=
withReader (fun ctx => { ctx with first := false }) x
@[inline] private def withNestedParser {α} (x : ToParserDescrM α) : ToParserDescrM α :=
withReader (fun ctx => { ctx with leftRec := false, first := false }) x
def checkLeftRec (stx : Syntax) : ToParserDescrM Bool := do
let ctx ← read
if ctx.first && stx.getKind == `Lean.Parser.Syntax.cat then
let cat := stx[0].getId.eraseMacroScopes
if cat == ctx.catName then
let prec? : Option Nat := expandOptPrecedence stx[1]
unless prec?.isNone do throwErrorAt stx[1] ("invalid occurrence of ':<num>' modifier in head")
unless ctx.leftRec do
throwErrorAt! stx[3] "invalid occurrence of '{cat}', parser algorithm does not allow this form of left recursion"
markAsTrailingParser -- mark as trailing par
pure true
else
pure false
else
pure false
partial def toParserDescrAux (stx : Syntax) : ToParserDescrM Syntax := withRef stx do
let kind := stx.getKind
if kind == nullKind then
let args := stx.getArgs
if (← checkLeftRec stx[0]) then
if args.size == 1 then throwErrorAt stx "invalid atomic left recursive syntax"
let args := args.eraseIdx 0
let args ← args.mapM fun arg => withNestedParser $ toParserDescrAux arg
mkParserSeq args
else
let args ← args.mapIdxM fun i arg => withReader (fun ctx => { ctx with first := ctx.first && i.val == 0 }) $ toParserDescrAux arg
mkParserSeq args
else if kind == choiceKind then
toParserDescrAux stx[0]
else if kind == `Lean.Parser.Syntax.paren then
toParserDescrAux stx[1]
else if kind == `Lean.Parser.Syntax.unary then
let aliasName := (stx[0].getId).eraseMacroScopes
Parser.ensureUnaryParserAlias aliasName
let d ← withNestedParser $ toParserDescrAux stx[2]
`(ParserDescr.unary $(quote aliasName) $d)
else if kind == `Lean.Parser.Syntax.binary then
let aliasName := (stx[0].getId).eraseMacroScopes
Parser.ensureBinaryParserAlias aliasName
let d₁ ← withNestedParser $ toParserDescrAux stx[2]
let d₂ ← withNestedParser $ toParserDescrAux stx[4]
`(ParserDescr.binary $(quote aliasName) $d₁ $d₂)
else if kind == `Lean.Parser.Syntax.cat then
let cat := stx[0].getId.eraseMacroScopes
let prec? : Option Nat := expandOptPrecedence stx[1]
if (← Parser.isParserAlias cat) then
Parser.ensureConstantParserAlias cat
if prec?.isSome then
throwErrorAt! stx[1] "unexpected precedence in atomic parser"
`(ParserDescr.const $(quote cat))
else
let ctx ← read
if ctx.first && cat == ctx.catName then
throwErrorAt stx "invalid atomic left recursive syntax"
else
let env ← getEnv
if Parser.isParserCategory env cat then
let prec := prec?.getD 0
`(ParserDescr.cat $(quote cat) $(quote prec))
else
-- `cat` is not a valid category name. Thus, we test whether it is a valid constant
let candidates ← resolveGlobalConst cat
/- Convert `candidates` in a list of pairs `(c, isDescr)`, where `c` is the parser name,
and `isDescr` is true iff `c` has type `Lean.ParserDescr` or `Lean.TrailingParser` -/
let candidates := candidates.filterMap fun c =>
match env.find? c with
| none => none
| some info =>
match info.type with
| Expr.const `Lean.Parser.TrailingParser _ _ => (c, false)
| Expr.const `Lean.Parser.Parser _ _ => (c, false)
| Expr.const `Lean.ParserDescr _ _ => (c, true)
| Expr.const `Lean.TrailingParserDescr _ _ => (c, true)
| _ => none
match candidates with
| [] => throwErrorAt! stx[3] "unknown category '{cat}' or parser declaration"
| [(c, isDescr)] =>
unless prec?.isNone do throwErrorAt stx[3] "unexpected precedence"
if isDescr then
mkIdentFrom stx c
else
`(ParserDescr.parser $(quote c))
| cs => throwErrorAt! stx[3] "ambiguous parser declaration {cs}"
else if kind == `Lean.Parser.Syntax.atom then
match stx[0].isStrLit? with
| some atom =>
/- For syntax categories where initialized with `leadingIdentAsSymbol` (e.g., `tactic`), we automatically mark
the first symbol as nonReserved. -/
if (← read).leadingIdentAsSymbol && (← read).first then
`(ParserDescr.nonReservedSymbol $(quote atom) false)
else
`(ParserDescr.symbol $(quote atom))
| none => throwUnsupportedSyntax
else if kind == `Lean.Parser.Syntax.nonReserved then
match stx[1].isStrLit? with
| some atom => `(ParserDescr.nonReservedSymbol $(quote atom) false)
| none => throwUnsupportedSyntax
else
let stxNew? ← liftM (liftMacroM (expandMacro? stx) : TermElabM _)
match stxNew? with
| some stxNew => toParserDescrAux stxNew
| none => throwErrorAt! stx "unexpected syntax kind of category `syntax`: {kind}"
/--
Given a `stx` of category `syntax`, return a pair `(newStx, trailingParser)`,
where `newStx` is of category `term`. After elaboration, `newStx` should have type
`TrailingParserDescr` if `trailingParser == true`, and `ParserDescr` otherwise. -/
def toParserDescr (stx : Syntax) (catName : Name) : TermElabM (Syntax × Bool) := do
let env ← getEnv
let leadingIdentAsSymbol := Parser.leadingIdentAsSymbol env catName
(toParserDescrAux stx { catName := catName, first := true, leftRec := true, leadingIdentAsSymbol := leadingIdentAsSymbol }).run false
end Term
namespace Command
private def getCatSuffix (catName : Name) : String :=
match catName with
| Name.str _ s _ => s
| _ => unreachable!
private def declareSyntaxCatQuotParser (catName : Name) : CommandElabM Unit := do
let quotSymbol := "`(" ++ getCatSuffix catName ++ "|"
let kind := catName ++ `quot
let cmd ← `(
@[termParser] def $(mkIdent kind) : Lean.ParserDescr :=
Lean.ParserDescr.node $(quote kind) $(quote Lean.Parser.maxPrec)
(Lean.ParserDescr.binary `andthen (Lean.ParserDescr.symbol $(quote quotSymbol))
(Lean.ParserDescr.binary `andthen (Lean.ParserDescr.cat $(quote catName) 0) (Lean.ParserDescr.symbol ")"))))
elabCommand cmd
@[builtinCommandElab syntaxCat] def elabDeclareSyntaxCat : CommandElab := fun stx => do
let catName := stx[1].getId
let attrName := catName.appendAfter "Parser"
let env ← getEnv
let env ← liftIO $ Parser.registerParserCategory env attrName catName
setEnv env
declareSyntaxCatQuotParser catName
def mkFreshKind (catName : Name) : MacroM Name :=
Macro.addMacroScope (`_kind ++ catName.eraseMacroScopes)
private def elabKindPrio (stx : Syntax) (catName : Name) : CommandElabM (Name × Nat) := do
if stx.isNone then
let k ← liftMacroM $ mkFreshKind catName
pure (k, 0)
else
let arg := stx[1]
if arg.getKind == `Lean.Parser.Command.parserKind then
let k := arg[0].getId
pure (k, 0)
else if arg.getKind == `Lean.Parser.Command.parserPrio then
let k ← liftMacroM $ mkFreshKind catName
let prio := arg[0].isNatLit?.getD 0
pure (k, prio)
else if arg.getKind == `Lean.Parser.Command.parserKindPrio then
let k := arg[0].getId
let prio := arg[2].isNatLit?.getD 0
pure (k, prio)
else
throwError "unexpected syntax kind/priority"
/- We assume a new syntax can be treated as an atom when it starts and ends with a token.
Here are examples of atom-like syntax.
```
syntax "(" term ")" : term
syntax "[" (sepBy term ",") "]" : term
syntax "foo" : term
```
-/
private partial def isAtomLikeSyntax (stx : Syntax) : Bool :=
let kind := stx.getKind
if kind == nullKind then
isAtomLikeSyntax stx[0] && isAtomLikeSyntax stx[stx.getNumArgs - 1]
else if kind == choiceKind then
isAtomLikeSyntax stx[0] -- see toParserDescrAux
else if kind == `Lean.Parser.Syntax.paren then
isAtomLikeSyntax stx[1]
else
kind == `Lean.Parser.Syntax.atom
/-
def «syntax» := parser! "syntax " >> optPrecedence >> optKindPrio >> many1 syntaxParser >> " : " >> ident
-/
@[builtinCommandElab «syntax»] def elabSyntax : CommandElab := fun stx => do
let env ← getEnv
let cat := stx[5].getId.eraseMacroScopes
unless (Parser.isParserCategory env cat) do throwErrorAt stx[5] ("unknown category '" ++ cat ++ "'")
let syntaxParser := stx[3]
-- If the user did not provide an explicit precedence, we assign `maxPrec` to atom-like syntax and `leadPrec` otherwise.
let precDefault := if isAtomLikeSyntax syntaxParser then Parser.maxPrec else Parser.leadPrec
let prec := (Term.expandOptPrecedence stx[1]).getD precDefault
let (kind, prio) ← elabKindPrio stx[2] cat
/-
The declaration name and the syntax node kind should be the same.
We are using `def $kind ...`. So, we must append the current namespace to create the name fo the Syntax `node`. -/
let stxNodeKind := (← getCurrNamespace) ++ kind
let catParserId := mkIdentFrom stx (cat.appendAfter "Parser")
let (val, trailingParser) ← runTermElabM none fun _ => Term.toParserDescr syntaxParser cat
let d ←
if trailingParser then
`(@[$catParserId:ident $(quote prio):numLit] def $(mkIdentFrom stx kind) : Lean.TrailingParserDescr :=
ParserDescr.trailingNode $(quote stxNodeKind) $(quote prec) $val)
else
`(@[$catParserId:ident $(quote prio):numLit] def $(mkIdentFrom stx kind) : Lean.ParserDescr :=
ParserDescr.node $(quote stxNodeKind) $(quote prec) $val)
trace `Elab fun _ => d
withMacroExpansion stx d $ elabCommand d
/-
def syntaxAbbrev := parser! "syntax " >> ident >> " := " >> many1 syntaxParser
-/
@[builtinCommandElab «syntaxAbbrev»] def elabSyntaxAbbrev : CommandElab := fun stx => do
let declName := stx[1]
-- TODO: nonatomic names
let (val, _) ← runTermElabM none $ fun _ => Term.toParserDescr stx[3] Name.anonymous
let stxNodeKind := (← getCurrNamespace) ++ declName.getId
let stx' ← `(def $declName : Lean.ParserDescr := ParserDescr.nodeWithAntiquot $(quote (toString declName.getId)) $(quote stxNodeKind) $val)
withMacroExpansion stx stx' $ elabCommand stx'
/-
Remark: `k` is the user provided kind with the current namespace included.
Recall that syntax node kinds contain the current namespace.
-/
def elabMacroRulesAux (k : SyntaxNodeKind) (alts : Array Syntax) : CommandElabM Syntax := do
let alts ← alts.mapSepElemsM fun alt => do
let lhs := alt[0]
let pat := lhs[0]
if !pat.isQuot then
throwUnsupportedSyntax
let quot := pat[1]
let k' := quot.getKind
if k' == k then
pure alt
else if k' == choiceKind then
match quot.getArgs.find? fun quotAlt => quotAlt.getKind == k with
| none => throwErrorAt! alt "invalid macro_rules alternative, expected syntax node kind '{k}'"
| some quot =>
let pat := pat.setArg 1 quot
let lhs := lhs.setArg 0 pat
pure $ alt.setArg 0 lhs
else
throwErrorAt! alt "invalid macro_rules alternative, unexpected syntax node kind '{k'}'"
`(@[macro $(Lean.mkIdent k)] def myMacro : Macro :=
fun stx => match_syntax stx with $alts:matchAlt* | _ => throw Lean.Macro.Exception.unsupportedSyntax)
def inferMacroRulesAltKind (alt : Syntax) : CommandElabM SyntaxNodeKind := do
let lhs := alt[0]
let pat := lhs[0]
if !pat.isQuot then
throwUnsupportedSyntax
let quot := pat[1]
pure quot.getKind
def elabNoKindMacroRulesAux (alts : Array Syntax) : CommandElabM Syntax := do
let k ← inferMacroRulesAltKind (alts.get! 0)
if k == choiceKind then
throwErrorAt! alts[0]
"invalid macro_rules alternative, multiple interpretations for pattern (solution: specify node kind using `macro_rules [<kind>] ...`)"
else
let altsK ← alts.filterSepElemsM fun alt => do pure $ k == (← inferMacroRulesAltKind alt)
let altsNotK ← alts.filterSepElemsM fun alt => do pure $ k != (← inferMacroRulesAltKind alt)
let defCmd ← elabMacroRulesAux k altsK
if altsNotK.isEmpty then
pure defCmd
else
`($defCmd:command macro_rules $altsNotK:matchAlt*)
@[builtinCommandElab «macro_rules»] def elabMacroRules : CommandElab :=
adaptExpander fun stx => match_syntax stx with
| `(macro_rules $alts:matchAlt*) => elabNoKindMacroRulesAux alts
| `(macro_rules | $alts:matchAlt*) => elabNoKindMacroRulesAux alts
| `(macro_rules [$kind] $alts:matchAlt*) => do elabMacroRulesAux ((← getCurrNamespace) ++ kind.getId) alts
| `(macro_rules [$kind] | $alts:matchAlt*) => do elabMacroRulesAux ((← getCurrNamespace) ++ kind.getId) alts
| _ => throwUnsupportedSyntax
@[builtinMacro Lean.Parser.Command.mixfix] def expandMixfix : Macro :=
fun stx => match_syntax stx with
| `(infix:$prec $op => $f) => `(infixl:$prec $op => $f)
| `(infixr:$prec $op => $f) => `(notation:$prec lhs $op:strLit rhs:$prec => $f lhs rhs)
| `(infixl:$prec $op => $f) => let prec1 : Syntax := quote (prec.toNat+1); `(notation:$prec lhs $op:strLit rhs:$prec1 => $f lhs rhs)
| `(prefix:$prec $op => $f) => `(notation:$prec $op:strLit arg:$prec => $f arg)
| `(postfix:$prec $op => $f) => `(notation:$prec arg $op:strLit => $f arg)
| _ => Macro.throwUnsupported
/- Wrap all occurrences of the given `ident` nodes in antiquotations -/
private partial def antiquote (vars : Array Syntax) : Syntax → Syntax
| stx => match_syntax stx with
| `($id:ident) =>
if (vars.findIdx? (fun var => var.getId == id.getId)).isSome then
Syntax.node `antiquot #[mkAtom "$", mkNullNode, id, mkNullNode, mkNullNode]
else
stx
| _ => match stx with
| Syntax.node k args => Syntax.node k (args.map (antiquote vars))
| stx => stx
/- Convert `notation` command lhs item into a `syntax` command item -/
def expandNotationItemIntoSyntaxItem (stx : Syntax) : MacroM Syntax :=
let k := stx.getKind
if k == `Lean.Parser.Command.identPrec then
pure $ Syntax.node `Lean.Parser.Syntax.cat #[mkIdentFrom stx `term, stx[1]]
else if k == strLitKind then
pure $ Syntax.node `Lean.Parser.Syntax.atom #[stx]
else
Macro.throwUnsupported
def strLitToPattern (stx: Syntax) : MacroM Syntax :=
match stx.isStrLit? with
| some str => pure $ mkAtomFrom stx str
| none => Macro.throwUnsupported
/- Convert `notation` command lhs item a pattern element -/
def expandNotationItemIntoPattern (stx : Syntax) : MacroM Syntax :=
let k := stx.getKind
if k == `Lean.Parser.Command.identPrec then
let item := stx[0]
pure $ mkNode `antiquot #[mkAtom "$", mkNullNode, item, mkNullNode, mkNullNode]
else if k == strLitKind then
strLitToPattern stx
else
Macro.throwUnsupported
private def expandNotationAux (ref : Syntax) (currNamespace : Name) (prec? : Option Syntax) (items : Array Syntax) (rhs : Syntax) : MacroM Syntax := do
let kind ← mkFreshKind `term
-- build parser
let syntaxParts ← items.mapM expandNotationItemIntoSyntaxItem
let cat := mkIdentFrom ref `term
-- build macro rules
let vars := items.filter fun item => item.getKind == `Lean.Parser.Command.identPrec
let vars := vars.map fun var => var[0]
let rhs := antiquote vars rhs
let patArgs ← items.mapM expandNotationItemIntoPattern
/- The command `syntax [<kind>] ...` adds the current namespace to the syntax node kind.
So, we must include current namespace when we create a pattern for the following `macro_rules` commands. -/
let pat := Syntax.node (currNamespace ++ kind) patArgs
match prec? with
| none => `(syntax [$(mkIdentFrom ref kind):ident] $syntaxParts* : $cat macro_rules | `($pat) => `($rhs))
| some prec => `(syntax:$prec [$(mkIdentFrom ref kind):ident] $syntaxParts* : $cat macro_rules | `($pat) => `($rhs))
@[builtinCommandElab «notation»] def expandNotation : CommandElab :=
adaptExpander fun stx => do
let currNamespace ← getCurrNamespace
match_syntax stx with
| `(notation:$prec $items* => $rhs) => liftMacroM $ expandNotationAux stx currNamespace prec items rhs
| `(notation $items:notationItem* => $rhs) => liftMacroM $ expandNotationAux stx currNamespace none items rhs
| _ => throwUnsupportedSyntax
/- Convert `macro` argument into a `syntax` command item -/
def expandMacroArgIntoSyntaxItem (stx : Syntax) : MacroM Syntax :=
let k := stx.getKind
if k == `Lean.Parser.Command.macroArgSimple then
pure stx[2]
else if k == strLitKind then
pure $ Syntax.node `Lean.Parser.Syntax.atom #[stx]
else
Macro.throwUnsupported
/- Convert `macro` head into a `syntax` command item -/
def expandMacroHeadIntoSyntaxItem (stx : Syntax) : MacroM Syntax :=
if stx.isIdent then
let info := stx.getHeadInfo.getD {}
let id := stx.getId
pure $ Syntax.node `Lean.Parser.Syntax.atom #[Syntax.mkStrLit (toString id) info]
else
expandMacroArgIntoSyntaxItem stx
/- Convert `macro` arg into a pattern element -/
def expandMacroArgIntoPattern (stx : Syntax) : MacroM Syntax :=
let k := stx.getKind
if k == `Lean.Parser.Command.macroArgSimple then
let item := stx[0]
pure $ mkNode `antiquot #[mkAtom "$", mkNullNode, item, mkNullNode, mkNullNode]
else if k == strLitKind then
strLitToPattern stx
else
Macro.throwUnsupported
/- Convert `macro` head into a pattern element -/
def expandMacroHeadIntoPattern (stx : Syntax) : MacroM Syntax :=
if stx.isIdent then
pure $ mkAtomFrom stx (toString stx.getId)
else
expandMacroArgIntoPattern stx
def expandOptPrio (stx : Syntax) : Nat :=
if stx.isNone then
0
else
stx[1].isNatLit?.getD 0
def expandMacro (currNamespace : Name) (stx : Syntax) : MacroM Syntax := do
let prec := stx[1].getArgs
let prio := expandOptPrio stx[2]
let head := stx[3]
let args := stx[4].getArgs
let cat := stx[6]
let kind ← mkFreshKind cat.getId
-- build parser
let stxPart ← expandMacroHeadIntoSyntaxItem head
let stxParts ← args.mapM expandMacroArgIntoSyntaxItem
let stxParts := #[stxPart] ++ stxParts
-- build macro rules
let patHead ← expandMacroHeadIntoPattern head
let patArgs ← args.mapM expandMacroArgIntoPattern
/- The command `syntax [<kind>] ...` adds the current namespace to the syntax node kind.
So, we must include current namespace when we create a pattern for the following `macro_rules` commands. -/
let pat := Syntax.node (currNamespace ++ kind) (#[patHead] ++ patArgs)
if stx.getArgs.size == 9 then
-- `stx` is of the form `macro $head $args* : $cat => term`
let rhs := stx[8]
`(syntax $prec* [$(mkIdentFrom stx kind):ident, $(quote prio):numLit] $stxParts* : $cat
macro_rules | `($pat) => $rhs)
else
-- `stx` is of the form `macro $head $args* : $cat => `( $body )`
let rhsBody := stx[9]
`(syntax $prec* [$(mkIdentFrom stx kind):ident, $(quote prio):numLit] $stxParts* : $cat
macro_rules | `($pat) => `($rhsBody))
@[builtinCommandElab «macro»] def elabMacro : CommandElab :=
adaptExpander fun stx => do
liftMacroM $ expandMacro (← getCurrNamespace) stx
builtin_initialize
registerTraceClass `Elab.syntax
@[inline] def withExpectedType (expectedType? : Option Expr) (x : Expr → TermElabM Expr) : TermElabM Expr := do
Term.tryPostponeIfNoneOrMVar expectedType?
let some expectedType ← pure expectedType?
| throwError "expected type must be known"
x expectedType
/-
def elabTail := try (" : " >> ident) >> darrow >> termParser
parser! "elab " >> optPrecedence >> optPrio >> elabHead >> many elabArg >> elabTail
-/
def expandElab (currNamespace : Name) (stx : Syntax) : MacroM Syntax := do
let ref := stx
let prec := stx[1].getArgs
let prio := expandOptPrio stx[2]
let head := stx[3]
let args := stx[4].getArgs
let cat := stx[6]
let expectedTypeSpec := stx[7]
let rhs := stx[9]
let catName := cat.getId
let kind ← mkFreshKind catName
-- build parser
let stxPart ← expandMacroHeadIntoSyntaxItem head
let stxParts ← args.mapM expandMacroArgIntoSyntaxItem
let stxParts := #[stxPart] ++ stxParts
-- build pattern for `martch_syntax
let patHead ← expandMacroHeadIntoPattern head
let patArgs ← args.mapM expandMacroArgIntoPattern
let pat := Syntax.node (currNamespace ++ kind) (#[patHead] ++ patArgs)
let kindId := mkIdentFrom ref kind
if expectedTypeSpec.hasArgs then
if catName == `term then
let expId := expectedTypeSpec[1]
`(syntax $prec* [$kindId:ident, $(quote prio):numLit] $stxParts* : $cat
@[termElab $kindId:ident] def elabFn : Lean.Elab.Term.TermElab :=
fun stx expectedType? => match_syntax stx with
| `($pat) => Lean.Elab.Command.withExpectedType expectedType? fun $expId => $rhs
| _ => throwUnsupportedSyntax)
else
Macro.throwErrorAt expectedTypeSpec s!"syntax category '{catName}' does not support expected type specification"
else if catName == `term then
`(syntax $prec* [$kindId:ident, $(quote prio):numLit] $stxParts* : $cat
@[termElab $kindId:ident] def elabFn : Lean.Elab.Term.TermElab :=
fun stx _ => match_syntax stx with
| `($pat) => $rhs
| _ => throwUnsupportedSyntax)
else if catName == `command then
`(syntax $prec* [$kindId:ident, $(quote prio):numLit] $stxParts* : $cat
@[commandElab $kindId:ident] def elabFn : Lean.Elab.Command.CommandElab :=
fun stx => match_syntax stx with
| `($pat) => $rhs
| _ => throwUnsupportedSyntax)
else if catName == `tactic then
`(syntax $prec* [$kindId:ident, $(quote prio):numLit] $stxParts* : $cat
@[tactic $kindId:ident] def elabFn : Lean.Elab.Tactic.Tactic :=
fun stx => match_syntax stx with
| `(tactic|$pat) => $rhs
| _ => throwUnsupportedSyntax)
else
-- We considered making the command extensible and support new user-defined categories. We think it is unnecessary.
-- If users want this feature, they add their own `elab` macro that uses this one as a fallback.
Macro.throwError s!"unsupported syntax category '{catName}'"
@[builtinCommandElab «elab»] def elabElab : CommandElab :=
adaptExpander fun stx => do
liftMacroM $ expandElab (← getCurrNamespace) stx
end Lean.Elab.Command
|
bd9fc1140401070e59095be839fff19c8f6824e4 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/algebraic_topology/dold_kan/notations.lean | 67fda8f17e311e498f950cfe0656c7dd9ab5a815 | [
"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 | 891 | lean | /-
Copyright (c) 2022 Joël Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joël Riou
-/
import algebraic_topology.alternating_face_map_complex
/-!
# Notations for the Dold-Kan equivalence
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines the notation `K[X] : chain_complex C ℕ` for the alternating face
map complex of `(X : simplicial_object C)` where `C` is a preadditive category, as well
as `N[X]` for the normalized subcomplex in the case `C` is an abelian category.
-/
localized "notation (name := alternating_face_map_complex) `K[`X`]` :=
algebraic_topology.alternating_face_map_complex.obj X" in dold_kan
localized "notation (name := normalized_Moore_complex) `N[`X`]` :=
algebraic_topology.normalized_Moore_complex.obj X" in dold_kan
|
9945275ae490623434381a034018e6d73fe28480 | e953c38599905267210b87fb5d82dcc3e52a4214 | /library/data/finset/comb.lean | afce8c5f1eb0ca57291e8a8c06558147c14f37f5 | [
"Apache-2.0"
] | permissive | c-cube/lean | 563c1020bff98441c4f8ba60111fef6f6b46e31b | 0fb52a9a139f720be418dafac35104468e293b66 | refs/heads/master | 1,610,753,294,113 | 1,440,451,356,000 | 1,440,499,588,000 | 41,748,334 | 0 | 0 | null | 1,441,122,656,000 | 1,441,122,656,000 | null | UTF-8 | Lean | false | false | 17,807 | 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, Jeremy Avigad
Combinators for finite sets.
-/
import data.finset.basic logic.identities
open list quot subtype decidable perm function
namespace finset
/- image (corresponds to map on list) -/
section image
variables {A B : Type}
variable [h : decidable_eq B]
include h
definition image (f : A → B) (s : finset A) : finset B :=
quot.lift_on s
(λ l, to_finset (list.map f (elt_of l)))
(λ l₁ l₂ p, quot.sound (perm_erase_dup_of_perm (perm_map _ p)))
notation [priority finset.prio] f `'[`:max a `]` := image f a
theorem image_empty (f : A → B) : image f ∅ = ∅ :=
rfl
theorem mem_image_of_mem (f : A → B) {s : finset A} {a : A} : a ∈ s → f a ∈ image f s :=
quot.induction_on s (take l, assume H : a ∈ elt_of l, mem_to_finset (mem_map f H))
theorem mem_image {f : A → B} {s : finset A} {a : A} {b : B}
(H1 : a ∈ s) (H2 : f a = b) :
b ∈ image f s :=
eq.subst H2 (mem_image_of_mem f H1)
theorem exists_of_mem_image {f : A → B} {s : finset A} {b : B} :
b ∈ image f s → ∃a, a ∈ s ∧ f a = b :=
quot.induction_on s
(take l, assume H : b ∈ erase_dup (list.map f (elt_of l)),
exists_of_mem_map (mem_of_mem_erase_dup H))
theorem mem_image_iff (f : A → B) {s : finset A} {y : B} : y ∈ image f s ↔ ∃x, x ∈ s ∧ f x = y :=
iff.intro exists_of_mem_image
(assume H,
obtain x (H₁ : x ∈ s) (H₂ : f x = y), from H,
mem_image H₁ H₂)
theorem mem_image_eq (f : A → B) {s : finset A} {y : B} : y ∈ image f s = ∃x, x ∈ s ∧ f x = y :=
propext (mem_image_iff f)
theorem mem_image_of_mem_image_of_subset {f : A → B} {s t : finset A} {y : B}
(H1 : y ∈ image f s) (H2 : s ⊆ t) : y ∈ image f t :=
obtain x (H3: x ∈ s) (H4 : f x = y), from exists_of_mem_image H1,
have H5 : x ∈ t, from mem_of_subset_of_mem H2 H3,
show y ∈ image f t, from mem_image H5 H4
theorem image_insert [h' : decidable_eq A] (f : A → B) (s : finset A) (a : A) :
image f (insert a s) = insert (f a) (image f s) :=
ext (take y, iff.intro
(assume H : y ∈ image f (insert a s),
obtain x (H1l : x ∈ insert a s) (H1r :f x = y), from exists_of_mem_image H,
have x = a ∨ x ∈ s, from eq_or_mem_of_mem_insert H1l,
or.elim this
(suppose x = a,
have f a = y, from eq.subst this H1r,
show y ∈ insert (f a) (image f s), from eq.subst this !mem_insert)
(suppose x ∈ s,
have f x ∈ image f s, from mem_image_of_mem f this,
show y ∈ insert (f a) (image f s), from eq.subst H1r (mem_insert_of_mem _ this)))
(suppose y ∈ insert (f a) (image f s),
have y = f a ∨ y ∈ image f s, from eq_or_mem_of_mem_insert this,
or.elim this
(suppose y = f a,
have f a ∈ image f (insert a s), from mem_image_of_mem f !mem_insert,
show y ∈ image f (insert a s), from eq.subst (eq.symm `y = f a`) this)
(suppose y ∈ image f s,
show y ∈ image f (insert a s), from mem_image_of_mem_image_of_subset this !subset_insert)))
lemma image_compose {C : Type} [deceqC : decidable_eq C] {f : B → C} {g : A → B} {s : finset A} :
image (f∘g) s = image f (image g s) :=
ext (take z, iff.intro
(suppose z ∈ image (f∘g) s,
obtain x (Hx : x ∈ s) (Hgfx : f (g x) = z), from exists_of_mem_image this,
by rewrite -Hgfx; apply mem_image_of_mem _ (mem_image_of_mem _ Hx))
(suppose z ∈ image f (image g s),
obtain y (Hy : y ∈ image g s) (Hfy : f y = z), from exists_of_mem_image this,
obtain x (Hx : x ∈ s) (Hgx : g x = y), from exists_of_mem_image Hy,
mem_image Hx (by esimp; rewrite [Hgx, Hfy])))
lemma image_subset {a b : finset A} (f : A → B) (H : a ⊆ b) : f '[a] ⊆ f '[b] :=
subset_of_forall
(take y, assume Hy : y ∈ f '[a],
obtain x (Hx₁ : x ∈ a) (Hx₂ : f x = y), from exists_of_mem_image Hy,
mem_image (mem_of_subset_of_mem H Hx₁) Hx₂)
theorem image_union [h' : decidable_eq A] (f : A → B) (s t : finset A) :
image f (s ∪ t) = image f s ∪ image f t :=
ext (take y, iff.intro
(assume H : y ∈ image f (s ∪ t),
obtain x [(xst : x ∈ s ∪ t) (fxy : f x = y)], from exists_of_mem_image H,
or.elim (mem_or_mem_of_mem_union xst)
(assume xs, mem_union_l (mem_image xs fxy))
(assume xt, mem_union_r (mem_image xt fxy)))
(assume H : y ∈ image f s ∪ image f t,
or.elim (mem_or_mem_of_mem_union H)
(assume yifs : y ∈ image f s,
obtain x [(xs : x ∈ s) (fxy : f x = y)], from exists_of_mem_image yifs,
mem_image (mem_union_l xs) fxy)
(assume yift : y ∈ image f t,
obtain x [(xt : x ∈ t) (fxy : f x = y)], from exists_of_mem_image yift,
mem_image (mem_union_r xt) fxy)))
end image
/- separation and set-builder notation -/
section sep
variables {A : Type} [deceq : decidable_eq A]
include deceq
variables (p : A → Prop) [decp : decidable_pred p] (s : finset A) {x : A}
include decp
definition sep : finset A :=
quot.lift_on s
(λl, to_finset_of_nodup
(list.filter p (subtype.elt_of l))
(list.nodup_filter p (subtype.has_property l)))
(λ l₁ l₂ u, quot.sound (perm.perm_filter u))
notation [priority finset.prio] `{` binder ∈ s `|` r:(scoped:1 p, sep p s) `}` := r
theorem sep_empty : sep p ∅ = ∅ := rfl
variables {p s}
theorem of_mem_sep : x ∈ sep p s → p x :=
quot.induction_on s (take l, list.of_mem_filter)
theorem mem_of_mem_sep : x ∈ sep p s → x ∈ s :=
quot.induction_on s (take l, list.mem_of_mem_filter)
theorem mem_sep_of_mem {x : A} : x ∈ s → p x → x ∈ sep p s :=
quot.induction_on s (take l, list.mem_filter_of_mem)
variables (p s)
theorem mem_sep_iff : x ∈ sep p s ↔ x ∈ s ∧ p x :=
iff.intro
(assume H, and.intro (mem_of_mem_sep H) (of_mem_sep H))
(assume H, mem_sep_of_mem (and.left H) (and.right H))
theorem mem_sep_eq : x ∈ sep p s = (x ∈ s ∧ p x) :=
propext !mem_sep_iff
variable t : finset A
theorem mem_sep_union_iff : x ∈ sep p (s ∪ t) ↔ x ∈ sep p s ∨ x ∈ sep p t :=
by rewrite [*mem_sep_iff, mem_union_iff, and.right_distrib]
end sep
section
variables {A : Type} [deceqA : decidable_eq A]
include deceqA
theorem eq_sep_of_subset {s t : finset A} (ssubt : s ⊆ t) : s = {x ∈ t | x ∈ s} :=
ext (take x, iff.intro
(suppose x ∈ s, mem_sep_of_mem (mem_of_subset_of_mem ssubt this) this)
(suppose x ∈ {x ∈ t | x ∈ s}, of_mem_sep this))
theorem mem_singleton_eq' (x a : A) : x ∈ '{a} = (x = a) :=
by rewrite [mem_insert_eq, mem_empty_eq, or_false]
end
/- set difference -/
section diff
variables {A : Type} [deceq : decidable_eq A]
include deceq
definition diff (s t : finset A) : finset A := {x ∈ s | x ∉ t}
infix [priority finset.prio] `\`:70 := diff
theorem mem_of_mem_diff {s t : finset A} {x : A} (H : x ∈ s \ t) : x ∈ s :=
mem_of_mem_sep H
theorem not_mem_of_mem_diff {s t : finset A} {x : A} (H : x ∈ s \ t) : x ∉ t :=
of_mem_sep H
theorem mem_diff {s t : finset A} {x : A} (H1 : x ∈ s) (H2 : x ∉ t) : x ∈ s \ t :=
mem_sep_of_mem H1 H2
theorem mem_diff_iff (s t : finset A) (x : A) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t :=
iff.intro
(assume H, and.intro (mem_of_mem_diff H) (not_mem_of_mem_diff H))
(assume H, mem_diff (and.left H) (and.right H))
theorem mem_diff_eq (s t : finset A) (x : A) : x ∈ s \ t = (x ∈ s ∧ x ∉ t) :=
propext !mem_diff_iff
theorem union_diff_cancel {s t : finset A} (H : s ⊆ t) : s ∪ (t \ s) = t :=
ext (take x, iff.intro
(suppose x ∈ s ∪ (t \ s),
or.elim (mem_or_mem_of_mem_union this)
(suppose x ∈ s, mem_of_subset_of_mem H this)
(suppose x ∈ t \ s, mem_of_mem_diff this))
(suppose x ∈ t,
decidable.by_cases
(suppose x ∈ s, mem_union_left _ this)
(suppose x ∉ s, mem_union_right _ (mem_diff `x ∈ t` this))))
theorem diff_union_cancel {s t : finset A} (H : s ⊆ t) : (t \ s) ∪ s = t :=
eq.subst !union.comm (!union_diff_cancel H)
end diff
/- all -/
section all
variables {A : Type}
definition all (s : finset A) (p : A → Prop) : Prop :=
quot.lift_on s
(λ l, all (elt_of l) p)
(λ l₁ l₂ p, foldr_eq_of_perm (λ a₁ a₂ q, propext !and.left_comm) p true)
theorem all_empty (p : A → Prop) : all ∅ p = true :=
rfl
theorem of_mem_of_all {p : A → Prop} {a : A} {s : finset A} : a ∈ s → all s p → p a :=
quot.induction_on s (λ l i h, list.of_mem_of_all i h)
theorem forall_of_all {p : A → Prop} {s : finset A} (H : all s p) : ∀{a}, a ∈ s → p a :=
λ a H', of_mem_of_all H' H
theorem all_of_forall {p : A → Prop} {s : finset A} : (∀a, a ∈ s → p a) → all s p :=
quot.induction_on s (λ l H, list.all_of_forall H)
theorem all_iff_forall (p : A → Prop) (s : finset A) : all s p ↔ (∀a, a ∈ s → p a) :=
iff.intro forall_of_all all_of_forall
definition decidable_all [instance] (p : A → Prop) [h : decidable_pred p] (s : finset A) :
decidable (all s p) :=
quot.rec_on_subsingleton s (λ l, list.decidable_all p (elt_of l))
theorem all_implies {p q : A → Prop} {s : finset A} : all s p → (∀ x, p x → q x) → all s q :=
quot.induction_on s (λ l h₁ h₂, list.all_implies h₁ h₂)
variable [h : decidable_eq A]
include h
theorem all_union {p : A → Prop} {s₁ s₂ : finset A} : all s₁ p → all s₂ p → all (s₁ ∪ s₂) p :=
quot.induction_on₂ s₁ s₂ (λ l₁ l₂ a₁ a₂, all_union a₁ a₂)
theorem all_of_all_union_left {p : A → Prop} {s₁ s₂ : finset A} : all (s₁ ∪ s₂) p → all s₁ p :=
quot.induction_on₂ s₁ s₂ (λ l₁ l₂ a, list.all_of_all_union_left a)
theorem all_of_all_union_right {p : A → Prop} {s₁ s₂ : finset A} : all (s₁ ∪ s₂) p → all s₂ p :=
quot.induction_on₂ s₁ s₂ (λ l₁ l₂ a, list.all_of_all_union_right a)
theorem all_insert_of_all {p : A → Prop} {a : A} {s : finset A} : p a → all s p → all (insert a s) p :=
quot.induction_on s (λ l h₁ h₂, list.all_insert_of_all h₁ h₂)
theorem all_erase_of_all {p : A → Prop} (a : A) {s : finset A}: all s p → all (erase a s) p :=
quot.induction_on s (λ l h, list.all_erase_of_all a h)
theorem all_inter_of_all_left {p : A → Prop} {s₁ : finset A} (s₂ : finset A) : all s₁ p → all (s₁ ∩ s₂) p :=
quot.induction_on₂ s₁ s₂ (λ l₁ l₂ h, list.all_inter_of_all_left _ h)
theorem all_inter_of_all_right {p : A → Prop} {s₁ : finset A} (s₂ : finset A) : all s₂ p → all (s₁ ∩ s₂) p :=
quot.induction_on₂ s₁ s₂ (λ l₁ l₂ h, list.all_inter_of_all_right _ h)
theorem subset_iff_all (s t : finset A) : s ⊆ t ↔ all s (λ x, x ∈ t) :=
iff.intro
(suppose s ⊆ t, all_of_forall (take x, suppose x ∈ s, mem_of_subset_of_mem `s ⊆ t` `x ∈ s`))
(suppose all s (λ x, x ∈ t), subset_of_forall (take x, suppose x ∈ s, of_mem_of_all `x ∈ s` `all s (λ x, x ∈ t)`))
definition decidable_subset [instance] (s t : finset A) : decidable (s ⊆ t) :=
decidable_of_decidable_of_iff _ (iff.symm !subset_iff_all)
end all
/- any -/
section any
variables {A : Type}
definition any (s : finset A) (p : A → Prop) : Prop :=
quot.lift_on s
(λ l, any (elt_of l) p)
(λ l₁ l₂ p, foldr_eq_of_perm (λ a₁ a₂ q, propext !or.left_comm) p false)
theorem any_empty (p : A → Prop) : any ∅ p = false := rfl
theorem exists_of_any {p : A → Prop} {s : finset A} : any s p → ∃a, a ∈ s ∧ p a :=
quot.induction_on s (λ l H, list.exists_of_any H)
theorem any_of_mem {p : A → Prop} {s : finset A} {a : A} : a ∈ s → p a → any s p :=
quot.induction_on s (λ l H1 H2, list.any_of_mem H1 H2)
theorem any_of_exists {p : A → Prop} {s : finset A} (H : ∃a, a ∈ s ∧ p a) : any s p :=
obtain a H₁ H₂, from H,
any_of_mem H₁ H₂
theorem any_iff_exists (p : A → Prop) (s : finset A) : any s p ↔ (∃a, a ∈ s ∧ p a) :=
iff.intro exists_of_any any_of_exists
theorem any_of_insert [h : decidable_eq A] {p : A → Prop} (s : finset A) {a : A} (H : p a) :
any (insert a s) p :=
any_of_mem (mem_insert a s) H
theorem any_of_insert_right [h : decidable_eq A] {p : A → Prop} {s : finset A} (a : A) (H : any s p) :
any (insert a s) p :=
obtain b (H₁ : b ∈ s) (H₂ : p b), from exists_of_any H,
any_of_mem (mem_insert_of_mem a H₁) H₂
definition decidable_any [instance] (p : A → Prop) [h : decidable_pred p] (s : finset A) :
decidable (any s p) :=
quot.rec_on_subsingleton s (λ l, list.decidable_any p (elt_of l))
end any
section product
variables {A B : Type}
definition product (s₁ : finset A) (s₂ : finset B) : finset (A × B) :=
quot.lift_on₂ s₁ s₂
(λ l₁ l₂,
to_finset_of_nodup (product (elt_of l₁) (elt_of l₂))
(nodup_product (has_property l₁) (has_property l₂)))
(λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound (perm_product p₁ p₂))
infix [priority finset.prio] * := product
theorem empty_product (s : finset B) : @empty A * s = ∅ :=
quot.induction_on s (λ l, rfl)
theorem mem_product {a : A} {b : B} {s₁ : finset A} {s₂ : finset B}
: a ∈ s₁ → b ∈ s₂ → (a, b) ∈ s₁ * s₂ :=
quot.induction_on₂ s₁ s₂ (λ l₁ l₂ i₁ i₂, list.mem_product i₁ i₂)
theorem mem_of_mem_product_left {a : A} {b : B} {s₁ : finset A} {s₂ : finset B}
: (a, b) ∈ s₁ * s₂ → a ∈ s₁ :=
quot.induction_on₂ s₁ s₂ (λ l₁ l₂ i, list.mem_of_mem_product_left i)
theorem mem_of_mem_product_right {a : A} {b : B} {s₁ : finset A} {s₂ : finset B}
: (a, b) ∈ s₁ * s₂ → b ∈ s₂ :=
quot.induction_on₂ s₁ s₂ (λ l₁ l₂ i, list.mem_of_mem_product_right i)
theorem product_empty (s : finset A) : s * @empty B = ∅ :=
ext (λ p,
match p with
| (a, b) := iff.intro
(λ i, absurd (mem_of_mem_product_right i) !not_mem_empty)
(λ i, absurd i !not_mem_empty)
end)
end product
/- powerset -/
section powerset
variables {A : Type} [deceqA : decidable_eq A]
include deceqA
section list_powerset
open list
definition list_powerset : list A → finset (finset A)
| [] := '{∅}
| (a :: l) := list_powerset l ∪ image (insert a) (list_powerset l)
end list_powerset
private theorem image_insert_comm (a b : A) (s : finset (finset A)) :
image (insert a) (image (insert b) s) = image (insert b) (image (insert a) s) :=
have aux' : ∀ a b : A, ∀ x : finset A,
x ∈ image (insert a) (image (insert b) s) →
x ∈ image (insert b) (image (insert a) s), from
begin
intros [a, b, x, H],
cases (exists_of_mem_image H) with [y, Hy],
cases Hy with [Hy1, Hy2],
cases (exists_of_mem_image Hy1) with [z, Hz],
cases Hz with [Hz1, Hz2],
substvars,
rewrite insert.comm,
repeat (apply mem_image_of_mem),
assumption
end,
ext (take x, iff.intro (aux' a b x) (aux' b a x))
theorem list_powerset_eq_list_powerset_of_perm {l₁ l₂ : list A} (p : l₁ ~ l₂) :
list_powerset l₁ = list_powerset l₂ :=
perm.induction_on p
rfl
(λ x l₁ l₂ p ih, by rewrite [↑list_powerset, ih])
(λ x y l, by rewrite [↑list_powerset, ↑list_powerset, *image_union, image_insert_comm,
*union.assoc, union.left_comm (finset.image (finset.insert x) _)])
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, eq.trans r₁ r₂)
definition powerset (s : finset A) : finset (finset A) :=
quot.lift_on s
(λ l, list_powerset (elt_of l))
(λ l₁ l₂ p, list_powerset_eq_list_powerset_of_perm p)
prefix [priority finset.prio] `𝒫`:100 := powerset
theorem powerset_empty : 𝒫 (∅ : finset A) = '{∅} := rfl
theorem powerset_insert {a : A} {s : finset A} : a ∉ s → 𝒫 (insert a s) = 𝒫 s ∪ image (insert a) (𝒫 s) :=
quot.induction_on s
(λ l,
assume H : a ∉ quot.mk l,
calc
𝒫 (insert a (quot.mk l))
= list_powerset (list.insert a (elt_of l)) : rfl
... = list_powerset (#list a :: elt_of l) : by rewrite [list.insert_eq_of_not_mem H]
... = 𝒫 (quot.mk l) ∪ image (insert a) (𝒫 (quot.mk l)) : rfl)
theorem mem_powerset_iff_subset (s : finset A) : ∀ x, x ∈ 𝒫 s ↔ x ⊆ s :=
begin
induction s with a s nains ih,
intro x,
rewrite powerset_empty,
show x ∈ '{∅} ↔ x ⊆ ∅, by rewrite [mem_singleton_eq', subset_empty_iff],
intro x,
rewrite [powerset_insert nains, mem_union_iff, ih, mem_image_iff],
exact
(iff.intro
(assume H,
or.elim H
(suppose x ⊆ s, subset.trans this !subset_insert)
(suppose ∃ y, y ∈ 𝒫 s ∧ insert a y = x,
obtain y [yps iay], from this,
show x ⊆ insert a s,
begin
rewrite [-iay],
apply insert_subset_insert,
rewrite -ih,
apply yps
end))
(assume H : x ⊆ insert a s,
assert H' : erase a x ⊆ s, from erase_subset_of_subset_insert H,
decidable.by_cases
(suppose a ∈ x,
or.inr (exists.intro (erase a x)
(and.intro
(show erase a x ∈ 𝒫 s, by rewrite ih; apply H')
(show insert a (erase a x) = x, from insert_erase this))))
(suppose a ∉ x, or.inl
(show x ⊆ s, by rewrite [(erase_eq_of_not_mem this) at H']; apply H'))))
end
theorem subset_of_mem_powerset {s t : finset A} (H : s ∈ 𝒫 t) : s ⊆ t :=
iff.mp (mem_powerset_iff_subset t s) H
theorem mem_powerset_of_subset {s t : finset A} (H : s ⊆ t) : s ∈ 𝒫 t :=
iff.mpr (mem_powerset_iff_subset t s) H
theorem empty_mem_powerset (s : finset A) : ∅ ∈ 𝒫 s :=
mem_powerset_of_subset (empty_subset s)
end powerset
end finset
|
ebefd61e71be8e9a3bf64e45f614c80fcd0e6d60 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/data/multiset/interval.lean | 0171872d6b22b0de76a27e9e241d9a6e8869fc15 | [
"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 | 2,807 | lean | /-
Copyright (c) 2021 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import data.finset.interval
/-!
# Intervals as multisets
This file provides basic results about all the `multiset.Ixx`, which are defined in
`order.locally_finite`.
## TODO
Bring the lemmas about `multiset.Ico` in `data.multiset.intervals` here and in `data.nat.interval`.
-/
variables {α : Type*}
namespace multiset
section preorder
variables [preorder α] [locally_finite_order α] {a b : α}
@[simp] lemma Icc_eq_zero_iff : Icc a b = 0 ↔ ¬a ≤ b :=
by rw [Icc, finset.val_eq_zero, finset.Icc_eq_empty_iff]
@[simp] lemma Ioc_eq_zero_iff : Ioc a b = 0 ↔ ¬a < b :=
by rw [Ioc, finset.val_eq_zero, finset.Ioc_eq_empty_iff]
@[simp] lemma Ioo_eq_zero_iff [densely_ordered α] : Ioo a b = 0 ↔ ¬a < b :=
by rw [Ioo, finset.val_eq_zero, finset.Ioo_eq_empty_iff]
alias Icc_eq_zero_iff ↔ _ multiset.Icc_eq_zero
alias Ioc_eq_zero_iff ↔ _ multiset.Ioc_eq_zero
@[simp] lemma Ioo_eq_zero (h : ¬a < b) : Ioo a b = 0 :=
eq_zero_iff_forall_not_mem.2 $ λ x hx, h ((mem_Ioo.1 hx).1.trans (mem_Ioo.1 hx).2)
@[simp] lemma Icc_eq_zero_of_lt (h : b < a) : Icc a b = 0 :=
Icc_eq_zero h.not_le
@[simp] lemma Ioc_eq_zero_of_le (h : b ≤ a) : Ioc a b = 0 :=
Ioc_eq_zero h.not_lt
@[simp] lemma Ioo_eq_zero_of_le (h : b ≤ a) : Ioo a b = 0 :=
Ioo_eq_zero h.not_lt
variables (a)
@[simp] lemma Ioc_self : Ioc a a = 0 :=
by rw [Ioc, finset.Ioc_self, finset.empty_val]
@[simp] lemma Ioo_self : Ioo a a = 0 :=
by rw [Ioo, finset.Ioo_self, finset.empty_val]
end preorder
section partial_order
variables [partial_order α] [locally_finite_order α] {a b : α}
@[simp] lemma Icc_self (a : α) : Icc a a = {a} :=
by rw [Icc, finset.Icc_self, finset.singleton_val]
end partial_order
section ordered_cancel_add_comm_monoid
variables [ordered_cancel_add_comm_monoid α] [has_exists_add_of_le α]
[locally_finite_order α]
lemma map_add_const_Icc (a b c : α) : (Icc a b).map ((+) c) = Icc (a + c) (b + c) :=
by { classical, rw [Icc, Icc, ←finset.image_add_const_Icc, finset.image_val,
multiset.nodup.erase_dup (multiset.nodup_map (add_right_injective c) (finset.nodup _))] }
lemma map_add_const_Ioc (a b c : α) : (Ioc a b).map ((+) c) = Ioc (a + c) (b + c) :=
by { classical, rw [Ioc, Ioc, ←finset.image_add_const_Ioc, finset.image_val,
multiset.nodup.erase_dup (multiset.nodup_map (add_right_injective c) (finset.nodup _))] }
lemma map_add_const_Ioo (a b c : α) : (Ioo a b).map ((+) c) = Ioo (a + c) (b + c) :=
by { classical, rw [Ioo, Ioo, ←finset.image_add_const_Ioo, finset.image_val,
multiset.nodup.erase_dup (multiset.nodup_map (add_right_injective c) (finset.nodup _))] }
end ordered_cancel_add_comm_monoid
end multiset
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.