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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aafb63f86d64c4314311882932e8c4684d6bb7a1 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/algebra/homology/homotopy.lean | 8897e94c996512c625a35f57674d946f03919114 | [
"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 | 24,836 | lean | /-
Copyright (c) 2021 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import algebra.homology.additive
import tactic.abel
/-!
# Chain homotopies
We define chain homotopies, and prove that homotopic chain maps induce the same map on homology.
-/
universes v u
open_locale classical
noncomputable theory
open category_theory category_theory.limits homological_complex
variables {ι : Type*}
variables {V : Type u} [category.{v} V] [preadditive V]
variables {c : complex_shape ι} {C D E : homological_complex V c}
variables (f g : C ⟶ D) (h k : D ⟶ E) (i : ι)
section
/-- The composition of `C.d i i' ≫ f i' i` if there is some `i'` coming after `i`,
and `0` otherwise. -/
def d_next (i : ι) : (Π i j, C.X i ⟶ D.X j) →+ (C.X i ⟶ D.X i) :=
add_monoid_hom.mk' (λ f, match c.next i with
| none := 0
| some ⟨i',w⟩ := C.d i i' ≫ f i' i
end)
begin
intros f g,
rcases c.next i with _|⟨i',w⟩,
exact (zero_add _).symm,
exact preadditive.comp_add _ _ _ _ _ _,
end
/-- `f i' i` if `i'` comes after `i`, and 0 if there's no such `i'`.
Hopefully there won't be much need for this, except in `d_next_eq_d_from_from_next`
to see that `d_next` factors through `C.d_from i`. -/
def from_next [has_zero_object V] (i : ι) : (Π i j, C.X i ⟶ D.X j) →+ (C.X_next i ⟶ D.X i) :=
add_monoid_hom.mk' (λ f, match c.next i with
| none := 0
| some ⟨i',w⟩ := (C.X_next_iso w).hom ≫ f i' i
end)
begin
intros f g,
rcases c.next i with _|⟨i',w⟩,
exact (zero_add _).symm,
exact preadditive.comp_add _ _ _ _ _ _,
end
lemma d_next_eq_d_from_from_next [has_zero_object V] (f : Π i j, C.X i ⟶ D.X j) (i : ι) :
d_next i f = C.d_from i ≫ from_next i f :=
begin
dsimp [d_next, from_next],
rcases c.next i with ⟨⟩|⟨⟨i', w⟩⟩;
{ dsimp [d_next, from_next], simp },
end
lemma d_next_eq (f : Π i j, C.X i ⟶ D.X j) {i i' : ι} (w : c.rel i i') :
d_next i f = C.d i i' ≫ f i' i :=
begin
dsimp [d_next],
rw c.next_eq_some w,
refl,
end
@[simp] lemma d_next_comp_left (f : C ⟶ D) (g : Π i j, D.X i ⟶ E.X j) (i : ι) :
d_next i (λ i j, f.f i ≫ g i j) = f.f i ≫ d_next i g :=
begin
dsimp [d_next],
rcases c.next i with _|⟨i',w⟩,
{ exact comp_zero.symm, },
{ dsimp [d_next],
simp, },
end
@[simp] lemma d_next_comp_right (f : Π i j, C.X i ⟶ D.X j) (g : D ⟶ E) (i : ι) :
d_next i (λ i j, f i j ≫ g.f j) = d_next i f ≫ g.f i :=
begin
dsimp [d_next],
rcases c.next i with _|⟨i',w⟩,
{ exact zero_comp.symm, },
{ dsimp [d_next],
simp, },
end
/-- The composition of `f j j' ≫ D.d j' j` if there is some `j'` coming before `j`,
and `0` otherwise. -/
def prev_d (j : ι) : (Π i j, C.X i ⟶ D.X j) →+ (C.X j ⟶ D.X j) :=
add_monoid_hom.mk' (λ f, match c.prev j with
| none := 0
| some ⟨j',w⟩ := f j j' ≫ D.d j' j
end)
begin
intros f g,
rcases c.prev j with _|⟨j',w⟩,
exact (zero_add _).symm,
exact preadditive.add_comp _ _ _ _ _ _,
end
/-- `f j j'` if `j'` comes after `j`, and 0 if there's no such `j'`.
Hopefully there won't be much need for this, except in `d_next_eq_d_from_from_next`
to see that `d_next` factors through `C.d_from i`. -/
def to_prev [has_zero_object V] (j : ι) : (Π i j, C.X i ⟶ D.X j) →+ (C.X j ⟶ D.X_prev j) :=
add_monoid_hom.mk' (λ f, match c.prev j with
| none := 0
| some ⟨j',w⟩ := f j j' ≫ (D.X_prev_iso w).inv
end)
begin
intros f g,
rcases c.prev j with _|⟨j',w⟩,
exact (zero_add _).symm,
exact preadditive.add_comp _ _ _ _ _ _,
end
lemma prev_d_eq_to_prev_d_to [has_zero_object V] (f : Π i j, C.X i ⟶ D.X j) (j : ι) :
prev_d j f = to_prev j f ≫ D.d_to j :=
begin
dsimp [prev_d, to_prev],
rcases c.prev j with ⟨⟩|⟨⟨j', w⟩⟩;
{ dsimp [prev_d, to_prev], simp },
end
lemma prev_d_eq (f : Π i j, C.X i ⟶ D.X j) {j j' : ι} (w : c.rel j' j) :
prev_d j f = f j j' ≫ D.d j' j :=
begin
dsimp [prev_d],
rw c.prev_eq_some w,
refl,
end
@[simp] lemma prev_d_comp_left (f : C ⟶ D) (g : Π i j, D.X i ⟶ E.X j) (j : ι) :
prev_d j (λ i j, f.f i ≫ g i j) = f.f j ≫ prev_d j g :=
begin
dsimp [prev_d],
rcases c.prev j with _|⟨j',w⟩,
{ exact comp_zero.symm, },
{ dsimp [prev_d, hom.prev],
simp, },
end
@[simp] lemma to_prev'_comp_right (f : Π i j, C.X i ⟶ D.X j) (g : D ⟶ E) (j : ι) :
prev_d j (λ i j, f i j ≫ g.f j) = prev_d j f ≫ g.f j :=
begin
dsimp [prev_d],
rcases c.prev j with _|⟨j',w⟩,
{ exact zero_comp.symm, },
{ dsimp [prev_d],
simp, },
end
lemma d_next_nat (C D : chain_complex V ℕ) (i : ℕ) (f : Π i j, C.X i ⟶ D.X j) :
d_next i f = C.d i (i-1) ≫ f (i-1) i :=
begin
cases i,
{ dsimp [d_next],
rcases (complex_shape.down ℕ).next 0 with _|⟨j,hj⟩;
dsimp [d_next],
{ rw [C.shape, zero_comp], dsimp, dec_trivial },
{ dsimp at hj, exact (nat.succ_ne_zero _ hj).elim } },
rw d_next_eq, dsimp, refl
end
lemma prev_d_nat (C D : cochain_complex V ℕ) (i : ℕ) (f : Π i j, C.X i ⟶ D.X j) :
prev_d i f = f i (i-1) ≫ D.d (i-1) i :=
begin
cases i,
{ dsimp [prev_d],
rcases (complex_shape.up ℕ).prev 0 with _|⟨j,hj⟩;
dsimp [prev_d],
{ rw [D.shape, comp_zero], dsimp, dec_trivial },
{ dsimp at hj, exact (nat.succ_ne_zero _ hj).elim } },
rw prev_d_eq, dsimp, refl
end
/--
A homotopy `h` between chain maps `f` and `g` consists of components `h i j : C.X i ⟶ D.X j`
which are zero unless `c.rel j i`, satisfying the homotopy condition.
-/
@[ext, nolint has_inhabited_instance]
structure homotopy (f g : C ⟶ D) :=
(hom : Π i j, C.X i ⟶ D.X j)
(zero' : ∀ i j, ¬ c.rel j i → hom i j = 0 . obviously)
(comm : ∀ i, f.f i = d_next i hom + prev_d i hom + g.f i . obviously')
variables {f g}
namespace homotopy
restate_axiom homotopy.zero'
/--
`f` is homotopic to `g` iff `f - g` is homotopic to `0`.
-/
def equiv_sub_zero : homotopy f g ≃ homotopy (f - g) 0 :=
{ to_fun := λ h,
{ hom := λ i j, h.hom i j,
zero' := λ i j w, h.zero _ _ w,
comm := λ i, by simp [h.comm] },
inv_fun := λ h,
{ hom := λ i j, h.hom i j,
zero' := λ i j w, h.zero _ _ w,
comm := λ i, by simpa [sub_eq_iff_eq_add] using h.comm i },
left_inv := by tidy,
right_inv := by tidy, }
/-- Equal chain maps are homotopic. -/
@[simps]
def of_eq (h : f = g) : homotopy f g :=
{ hom := 0,
zero' := λ _ _ _, rfl,
comm := λ _, by simp only [add_monoid_hom.map_zero, zero_add, h] }
/-- Every chain map is homotopic to itself. -/
@[simps, refl]
def refl (f : C ⟶ D) : homotopy f f :=
of_eq (rfl : f = f)
/-- `f` is homotopic to `g` iff `g` is homotopic to `f`. -/
@[simps, symm]
def symm {f g : C ⟶ D} (h : homotopy f g) : homotopy g f :=
{ hom := -h.hom,
zero' := λ i j w, by rw [pi.neg_apply, pi.neg_apply, h.zero i j w, neg_zero],
comm := λ i, by rw [add_monoid_hom.map_neg, add_monoid_hom.map_neg, h.comm, ← neg_add,
← add_assoc, neg_add_self, zero_add] }
/-- homotopy is a transitive relation. -/
@[simps, trans]
def trans {e f g : C ⟶ D} (h : homotopy e f) (k : homotopy f g) : homotopy e g :=
{ hom := h.hom + k.hom,
zero' := λ i j w, by rw [pi.add_apply, pi.add_apply, h.zero i j w, k.zero i j w, zero_add],
comm := λ i, by { rw [add_monoid_hom.map_add, add_monoid_hom.map_add, h.comm, k.comm], abel }, }
/-- the sum of two homotopies is a homotopy between the sum of the respective morphisms. -/
@[simps]
def add {f₁ g₁ f₂ g₂: C ⟶ D}
(h₁ : homotopy f₁ g₁) (h₂ : homotopy f₂ g₂) : homotopy (f₁+f₂) (g₁+g₂) :=
{ hom := h₁.hom + h₂.hom,
zero' := λ i j hij, by
rw [pi.add_apply, pi.add_apply, h₁.zero' i j hij, h₂.zero' i j hij, add_zero],
comm := λ i, by
{ simp only [homological_complex.add_f_apply, h₁.comm, h₂.comm,
add_monoid_hom.map_add],
abel, }, }
/-- homotopy is closed under composition (on the right) -/
@[simps]
def comp_right {e f : C ⟶ D} (h : homotopy e f) (g : D ⟶ E) : homotopy (e ≫ g) (f ≫ g) :=
{ hom := λ i j, h.hom i j ≫ g.f j,
zero' := λ i j w, by rw [h.zero i j w, zero_comp],
comm := λ i, by simp only [h.comm i, d_next_comp_right, preadditive.add_comp,
to_prev'_comp_right, comp_f], }
/-- homotopy is closed under composition (on the left) -/
@[simps]
def comp_left {f g : D ⟶ E} (h : homotopy f g) (e : C ⟶ D) : homotopy (e ≫ f) (e ≫ g) :=
{ hom := λ i j, e.f i ≫ h.hom i j,
zero' := λ i j w, by rw [h.zero i j w, comp_zero],
comm := λ i, by simp only [h.comm i, d_next_comp_left, preadditive.comp_add,
prev_d_comp_left, comp_f], }
/-- homotopy is closed under composition -/
@[simps]
def comp {C₁ C₂ C₃ : homological_complex V c} {f₁ g₁ : C₁ ⟶ C₂} {f₂ g₂ : C₂ ⟶ C₃}
(h₁ : homotopy f₁ g₁) (h₂ : homotopy f₂ g₂) : homotopy (f₁ ≫ f₂) (g₁ ≫ g₂) :=
(h₁.comp_right _).trans (h₂.comp_left _)
/-- a variant of `homotopy.comp_right` useful for dealing with homotopy equivalences. -/
@[simps]
def comp_right_id {f : C ⟶ C} (h : homotopy f (𝟙 C)) (g : C ⟶ D) : homotopy (f ≫ g) g :=
(h.comp_right g).trans (of_eq $ category.id_comp _)
/-- a variant of `homotopy.comp_left` useful for dealing with homotopy equivalences. -/
@[simps]
def comp_left_id {f : D ⟶ D} (h : homotopy f (𝟙 D)) (g : C ⟶ D) : homotopy (g ≫ f) g :=
(h.comp_left g).trans (of_eq $ category.comp_id _)
/-!
Null homotopic maps can be constructed using the formula `hd+dh`. We show that
these morphisms are homotopic to `0` and provide some convenient simplification
lemmas that give a degreewise description of `hd+dh`, depending on whether we have
two differentials going to and from a certain degree, only one, or none.
-/
/-- The null homotopic map associated to a family `hom` of morphisms `C_i ⟶ D_j`.
This is the same datum as for the field `hom` in the structure `homotopy`. For
this definition, we do not need the field `zero` of that structure
as this definition uses only the maps `C_i ⟶ C_j` when `c.rel j i`. -/
def null_homotopic_map (hom : Π i j, C.X i ⟶ D.X j) : C ⟶ D :=
{ f := λ i, d_next i hom + prev_d i hom,
comm' := λ i j hij,
begin
have eq1 : prev_d i hom ≫ D.d i j = 0,
{ rcases h : c.prev i with _|⟨i',w⟩,
{ dsimp [prev_d], rw h, erw zero_comp, },
{ rw [prev_d_eq hom w, category.assoc, D.d_comp_d' i' i j w hij, comp_zero], }, },
have eq2 : C.d i j ≫ d_next j hom = 0,
{ rcases h : c.next j with _|⟨j',w⟩,
{ dsimp [d_next], rw h, erw comp_zero, },
{ rw [d_next_eq hom w, ← category.assoc, C.d_comp_d' i j j' hij w, zero_comp], }, },
rw [d_next_eq hom hij, prev_d_eq hom hij, preadditive.comp_add, preadditive.add_comp,
eq1, eq2, add_zero, zero_add, category.assoc],
end }
/-- Variant of `null_homotopic_map` where the input consists only of the
relevant maps `C_i ⟶ D_j` such that `c.rel j i`. -/
def null_homotopic_map' (h : Π i j, c.rel j i → (C.X i ⟶ D.X j)) : C ⟶ D :=
null_homotopic_map (λ i j, dite (c.rel j i) (h i j) (λ _, 0))
/-- Tautological construction of the `homotopy` to zero for maps constructed by
`null_homotopic_map`, at least when we have the `zero'` condition. -/
@[simps]
def null_homotopy (hom : Π i j, C.X i ⟶ D.X j) (zero' : ∀ i j, ¬ c.rel j i → hom i j = 0) :
homotopy (null_homotopic_map hom) 0 :=
{ hom := hom,
zero' := zero',
comm := by { intro i, rw [homological_complex.zero_f_apply, add_zero], refl, }, }
/-- Homotopy to zero for maps constructed with `null_homotopic_map'` -/
@[simps]
def null_homotopy' (h : Π i j, c.rel j i → (C.X i ⟶ D.X j)) :
homotopy (null_homotopic_map' h) 0 :=
begin
apply null_homotopy (λ i j, dite (c.rel j i) (h i j) (λ _, 0)),
intros i j hij,
dsimp,
rw [dite_eq_right_iff],
intro hij',
exfalso,
exact hij hij',
end
/-! This lemma and the following ones can be used in order to compute
the degreewise morphisms induced by the null homotopic maps constructed
with `null_homotopic_map` or `null_homotopic_map'` -/
@[simp]
lemma null_homotopic_map_f {k₂ k₁ k₀ : ι} (r₂₁ : c.rel k₂ k₁) (r₁₀ : c.rel k₁ k₀)
(hom : Π i j, C.X i ⟶ D.X j) :
(null_homotopic_map hom).f k₁ = C.d k₁ k₀ ≫ hom k₀ k₁ + hom k₁ k₂ ≫ D.d k₂ k₁ :=
by { dsimp [null_homotopic_map], rw [d_next_eq hom r₁₀, prev_d_eq hom r₂₁], }
@[simp]
lemma null_homotopic_map'_f {k₂ k₁ k₀ : ι} (r₂₁ : c.rel k₂ k₁) (r₁₀ : c.rel k₁ k₀)
(h : Π i j, c.rel j i → (C.X i ⟶ D.X j)) :
(null_homotopic_map' h).f k₁ = C.d k₁ k₀ ≫ h k₀ k₁ r₁₀ + h k₁ k₂ r₂₁ ≫ D.d k₂ k₁ :=
begin
simp only [← null_homotopic_map'],
rw null_homotopic_map_f r₂₁ r₁₀ (λ i j, dite (c.rel j i) (h i j) (λ _, 0)),
dsimp,
split_ifs,
refl,
end
@[simp]
lemma null_homotopic_map_f_of_not_rel_left {k₁ k₀ : ι} (r₁₀ : c.rel k₁ k₀)
(hk₀ : ∀ l : ι, ¬c.rel k₀ l)
(hom : Π i j, C.X i ⟶ D.X j) :
(null_homotopic_map hom).f k₀ = hom k₀ k₁ ≫ D.d k₁ k₀ :=
begin
dsimp [null_homotopic_map],
rw prev_d_eq hom r₁₀,
rcases h : c.next k₀ with _|⟨l,w⟩, swap, exfalso, exact hk₀ l w,
dsimp [d_next], rw h, erw zero_add,
end
@[simp]
lemma null_homotopic_map'_f_of_not_rel_left {k₁ k₀ : ι} (r₁₀ : c.rel k₁ k₀)
(hk₀ : ∀ l : ι, ¬c.rel k₀ l)
(h : Π i j, c.rel j i → (C.X i ⟶ D.X j)) :
(null_homotopic_map' h).f k₀ = h k₀ k₁ r₁₀ ≫ D.d k₁ k₀ :=
begin
simp only [← null_homotopic_map'],
rw null_homotopic_map_f_of_not_rel_left r₁₀ hk₀ (λ i j, dite (c.rel j i) (h i j) (λ _, 0)),
dsimp,
split_ifs,
refl,
end
@[simp]
lemma null_homotopic_map_f_of_not_rel_right {k₁ k₀ : ι} (r₁₀ : c.rel k₁ k₀)
(hk₁ : ∀ l : ι, ¬c.rel l k₁)
(hom : Π i j, C.X i ⟶ D.X j) :
(null_homotopic_map hom).f k₁ = C.d k₁ k₀ ≫ hom k₀ k₁ :=
begin
dsimp [null_homotopic_map],
rw d_next_eq hom r₁₀,
rcases h : c.prev k₁ with _|⟨l,w⟩, swap, exfalso, exact hk₁ l w,
dsimp [prev_d], rw h, erw add_zero,
end
@[simp]
lemma null_homotopic_map'_f_of_not_rel_right {k₁ k₀ : ι} (r₁₀ : c.rel k₁ k₀)
(hk₁ : ∀ l : ι, ¬c.rel l k₁)
(h : Π i j, c.rel j i → (C.X i ⟶ D.X j)) :
(null_homotopic_map' h).f k₁ = C.d k₁ k₀ ≫ h k₀ k₁ r₁₀ :=
begin
simp only [← null_homotopic_map'],
rw null_homotopic_map_f_of_not_rel_right r₁₀ hk₁ (λ i j, dite (c.rel j i) (h i j) (λ _, 0)),
dsimp,
split_ifs,
refl,
end
@[simp]
lemma null_homotopic_map_f_eq_zero {k₀ : ι}
(hk₀ : ∀ l : ι, ¬c.rel k₀ l) (hk₀' : ∀ l : ι, ¬c.rel l k₀)
(hom : Π i j, C.X i ⟶ D.X j) :
(null_homotopic_map hom).f k₀ = 0 :=
begin
dsimp [null_homotopic_map],
rcases h1 : c.next k₀ with _|⟨l,w⟩, swap, exfalso, exact hk₀ l w,
rcases h2 : c.prev k₀ with _|⟨l,w⟩, swap, exfalso, exact hk₀' l w,
dsimp [d_next, prev_d],
rw [h1, h2],
erw zero_add,
refl,
end
@[simp]
lemma null_homotopic_map'_f_eq_zero {k₀ : ι}
(hk₀ : ∀ l : ι, ¬c.rel k₀ l) (hk₀' : ∀ l : ι, ¬c.rel l k₀)
(h : Π i j, c.rel j i → (C.X i ⟶ D.X j)) :
(null_homotopic_map' h).f k₀ = 0 :=
begin
simp only [← null_homotopic_map'],
exact null_homotopic_map_f_eq_zero hk₀ hk₀'
(λ i j, dite (c.rel j i) (h i j) (λ _, 0)),
end
/-!
`homotopy.mk_inductive` allows us to build a homotopy inductively,
so that as we construct each component, we have available the previous two components,
and the fact that they satisfy the homotopy condition.
To simplify the situation, we only construct homotopies of the form `homotopy e 0`.
`homotopy.equiv_sub_zero` can provide the general case.
Notice however, that this construction does not have particularly good definitional properties:
we have to insert `eq_to_hom` in several places.
Hopefully this is okay in most applications, where we only need to have the existence of some
homotopy.
-/
section mk_inductive
variables {P Q : chain_complex V ℕ}
@[simp] lemma prev_d_chain_complex (f : Π i j, P.X i ⟶ Q.X j) (j : ℕ) :
prev_d j f = f j (j+1) ≫ Q.d _ _ :=
begin
dsimp [prev_d],
simp only [chain_complex.prev],
refl,
end
@[simp] lemma d_next_succ_chain_complex (f : Π i j, P.X i ⟶ Q.X j) (i : ℕ) :
d_next (i+1) f = P.d _ _ ≫ f i (i+1) :=
begin
dsimp [d_next],
simp only [chain_complex.next_nat_succ],
refl,
end
@[simp] lemma d_next_zero_chain_complex (f : Π i j, P.X i ⟶ Q.X j) :
d_next 0 f = 0 :=
begin
dsimp [d_next],
simp only [chain_complex.next_nat_zero],
refl,
end
variables (e : P ⟶ Q)
(zero : P.X 0 ⟶ Q.X 1)
(comm_zero : e.f 0 = zero ≫ Q.d 1 0)
(one : P.X 1 ⟶ Q.X 2)
(comm_one : e.f 1 = P.d 1 0 ≫ zero + one ≫ Q.d 2 1)
(succ : ∀ (n : ℕ)
(p : Σ' (f : P.X n ⟶ Q.X (n+1)) (f' : P.X (n+1) ⟶ Q.X (n+2)),
e.f (n+1) = P.d (n+1) n ≫ f + f' ≫ Q.d (n+2) (n+1)),
Σ' f'' : P.X (n+2) ⟶ Q.X (n+3), e.f (n+2) = P.d (n+2) (n+1) ≫ p.2.1 + f'' ≫ Q.d (n+3) (n+2))
include comm_one comm_zero
/--
An auxiliary construction for `mk_inductive`.
Here we build by induction a family of diagrams,
but don't require at the type level that these successive diagrams actually agree.
They do in fact agree, and we then capture that at the type level (i.e. by constructing a homotopy)
in `mk_inductive`.
At this stage, we don't check the homotopy condition in degree 0,
because it "falls off the end", and is easier to treat using `X_next` and `X_prev`,
which we do in `mk_inductive_aux₂`.
-/
@[simp, nolint unused_arguments]
def mk_inductive_aux₁ :
Π n, Σ' (f : P.X n ⟶ Q.X (n+1)) (f' : P.X (n+1) ⟶ Q.X (n+2)),
e.f (n+1) = P.d (n+1) n ≫ f + f' ≫ Q.d (n+2) (n+1)
| 0 := ⟨zero, one, comm_one⟩
| 1 := ⟨one, (succ 0 ⟨zero, one, comm_one⟩).1, (succ 0 ⟨zero, one, comm_one⟩).2⟩
| (n+2) :=
⟨(mk_inductive_aux₁ (n+1)).2.1,
(succ (n+1) (mk_inductive_aux₁ (n+1))).1,
(succ (n+1) (mk_inductive_aux₁ (n+1))).2⟩
section
variable [has_zero_object V]
/--
An auxiliary construction for `mk_inductive`.
-/
@[simp]
def mk_inductive_aux₂ :
Π n, Σ' (f : P.X_next n ⟶ Q.X n) (f' : P.X n ⟶ Q.X_prev n), e.f n = P.d_from n ≫ f + f' ≫ Q.d_to n
| 0 := ⟨0, zero ≫ (Q.X_prev_iso rfl).inv, by simpa using comm_zero⟩
| (n+1) := let I := mk_inductive_aux₁ e zero comm_zero one comm_one succ n in
⟨(P.X_next_iso rfl).hom ≫ I.1, I.2.1 ≫ (Q.X_prev_iso rfl).inv, by simpa using I.2.2⟩
lemma mk_inductive_aux₃ (i : ℕ) :
(mk_inductive_aux₂ e zero comm_zero one comm_one succ i).2.1 ≫ (Q.X_prev_iso rfl).hom
= (P.X_next_iso rfl).inv ≫ (mk_inductive_aux₂ e zero comm_zero one comm_one succ (i+1)).1 :=
by rcases i with (_|_|i); { dsimp, simp, }
/--
A constructor for a `homotopy e 0`, for `e` a chain map between `ℕ`-indexed chain complexes,
working by induction.
You need to provide the components of the homotopy in degrees 0 and 1,
show that these satisfy the homotopy condition,
and then give a construction of each component,
and the fact that it satisfies the homotopy condition,
using as an inductive hypothesis the data and homotopy condition for the previous two components.
-/
def mk_inductive : homotopy e 0 :=
{ hom := λ i j, if h : i + 1 = j then
(mk_inductive_aux₂ e zero comm_zero one comm_one succ i).2.1 ≫ (Q.X_prev_iso h).hom
else
0,
zero' := λ i j w, by rwa dif_neg,
comm := λ i, begin
dsimp, simp only [add_zero],
convert (mk_inductive_aux₂ e zero comm_zero one comm_one succ i).2.2,
{ rcases i with (_|_|_|i),
{ dsimp,
simp only [d_next_zero_chain_complex, d_from_eq_zero, limits.comp_zero], },
all_goals
{ simp only [d_next_succ_chain_complex],
dsimp,
simp only [category.comp_id, category.assoc, iso.inv_hom_id, d_from_comp_X_next_iso_assoc,
dite_eq_ite, if_true, eq_self_iff_true]}, },
{ cases i,
all_goals
{ simp only [prev_d_chain_complex],
dsimp,
simp only [category.comp_id, category.assoc, iso.inv_hom_id, X_prev_iso_comp_d_to,
dite_eq_ite, if_true, eq_self_iff_true], }, },
end, }
end
end mk_inductive
end homotopy
/--
A homotopy equivalence between two chain complexes consists of a chain map each way,
and homotopies from the compositions to the identity chain maps.
Note that this contains data;
arguably it might be more useful for many applications if we truncated it to a Prop.
-/
structure homotopy_equiv (C D : homological_complex V c) :=
(hom : C ⟶ D)
(inv : D ⟶ C)
(homotopy_hom_inv_id : homotopy (hom ≫ inv) (𝟙 C))
(homotopy_inv_hom_id : homotopy (inv ≫ hom) (𝟙 D))
namespace homotopy_equiv
/-- Any complex is homotopy equivalent to itself. -/
@[refl] def refl (C : homological_complex V c) : homotopy_equiv C C :=
{ hom := 𝟙 C,
inv := 𝟙 C,
homotopy_hom_inv_id := by simp,
homotopy_inv_hom_id := by simp, }
instance : inhabited (homotopy_equiv C C) := ⟨refl C⟩
/-- Being homotopy equivalent is a symmetric relation. -/
@[symm] def symm
{C D : homological_complex V c} (f : homotopy_equiv C D) :
homotopy_equiv D C :=
{ hom := f.inv,
inv := f.hom,
homotopy_hom_inv_id := f.homotopy_inv_hom_id,
homotopy_inv_hom_id := f.homotopy_hom_inv_id, }
/-- Homotopy equivalence is a transitive relation. -/
@[trans] def trans
{C D E : homological_complex V c} (f : homotopy_equiv C D) (g : homotopy_equiv D E) :
homotopy_equiv C E :=
{ hom := f.hom ≫ g.hom,
inv := g.inv ≫ f.inv,
homotopy_hom_inv_id := by simpa using
((g.homotopy_hom_inv_id.comp_right_id f.inv).comp_left f.hom).trans f.homotopy_hom_inv_id,
homotopy_inv_hom_id := by simpa using
((f.homotopy_inv_hom_id.comp_right_id g.hom).comp_left g.inv).trans g.homotopy_inv_hom_id, }
end homotopy_equiv
variables [has_equalizers V] [has_cokernels V] [has_images V] [has_image_maps V]
variable [has_zero_object V]
/--
Homotopic maps induce the same map on homology.
-/
theorem homology_map_eq_of_homotopy (h : homotopy f g) (i : ι) :
(homology_functor V c i).map f = (homology_functor V c i).map g :=
begin
dsimp [homology_functor],
apply eq_of_sub_eq_zero,
ext,
simp only [homology.π_map, comp_zero, preadditive.comp_sub],
dsimp [kernel_subobject_map],
simp_rw [h.comm i],
simp only [zero_add, zero_comp, d_next_eq_d_from_from_next, kernel_subobject_arrow_comp_assoc,
preadditive.comp_add],
rw [←preadditive.sub_comp],
simp only [category_theory.subobject.factor_thru_add_sub_factor_thru_right],
erw [subobject.factor_thru_of_le (D.boundaries_le_cycles i)],
{ simp, },
{ rw [prev_d_eq_to_prev_d_to, ←category.assoc],
apply image_subobject_factors_comp_self, },
end
/-- Homotopy equivalent complexes have isomorphic homologies. -/
def homology_obj_iso_of_homotopy_equiv (f : homotopy_equiv C D) (i : ι) :
(homology_functor V c i).obj C ≅ (homology_functor V c i).obj D :=
{ hom := (homology_functor V c i).map f.hom,
inv := (homology_functor V c i).map f.inv,
hom_inv_id' := begin
rw [←functor.map_comp, homology_map_eq_of_homotopy f.homotopy_hom_inv_id,
category_theory.functor.map_id],
end,
inv_hom_id' := begin
rw [←functor.map_comp, homology_map_eq_of_homotopy f.homotopy_inv_hom_id,
category_theory.functor.map_id],
end, }
end
namespace category_theory
variables {W : Type*} [category W] [preadditive W]
/-- An additive functor takes homotopies to homotopies. -/
@[simps]
def functor.map_homotopy (F : V ⥤ W) [F.additive] {f g : C ⟶ D} (h : homotopy f g) :
homotopy ((F.map_homological_complex c).map f) ((F.map_homological_complex c).map g) :=
{ hom := λ i j, F.map (h.hom i j),
zero' := λ i j w, by { rw [h.zero i j w, F.map_zero], },
comm := λ i, begin
have := h.comm i,
dsimp [d_next, prev_d] at *,
rcases c.next i with _|⟨inext,wn⟩;
rcases c.prev i with _|⟨iprev,wp⟩;
dsimp [d_next, prev_d] at *;
{ intro h,
simp [h] },
end, }
/-- An additive functor preserves homotopy equivalences. -/
@[simps]
def functor.map_homotopy_equiv (F : V ⥤ W) [F.additive] (h : homotopy_equiv C D) :
homotopy_equiv ((F.map_homological_complex c).obj C) ((F.map_homological_complex c).obj D) :=
{ hom := (F.map_homological_complex c).map h.hom,
inv := (F.map_homological_complex c).map h.inv,
homotopy_hom_inv_id := begin
rw [←(F.map_homological_complex c).map_comp, ←(F.map_homological_complex c).map_id],
exact F.map_homotopy h.homotopy_hom_inv_id,
end,
homotopy_inv_hom_id := begin
rw [←(F.map_homological_complex c).map_comp, ←(F.map_homological_complex c).map_id],
exact F.map_homotopy h.homotopy_inv_hom_id,
end }
end category_theory
|
4a3786d342966b444ace19b5e893d125a379345d | 64874bd1010548c7f5a6e3e8902efa63baaff785 | /library/logic/axioms/hilbert.lean | 411f6a20601c8c2f26806ad28442a9cc01eec1a6 | [
"Apache-2.0"
] | permissive | tjiaqi/lean | 4634d729795c164664d10d093f3545287c76628f | d0ce4cf62f4246b0600c07e074d86e51f2195e30 | refs/heads/master | 1,622,323,796,480 | 1,422,643,069,000 | 1,422,643,069,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,501 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: logic.axioms.hilbert
Authors: Leonardo de Moura, Jeremy Avigad
Follows Coq.Logic.ClassicalEpsilon (but our definition of "inhabited" is the constructive one).
-/
import logic.quantifiers
import data.subtype data.sum
open subtype inhabited nonempty
/- the axiom -/
-- In the presence of classical logic, we could prove this from a weaker statement:
-- axiom indefinite_description {A : Type} {P : A->Prop} (H : ∃x, P x) : {x : A, P x}
axiom strong_indefinite_description {A : Type} (P : A → Prop) (H : nonempty A) :
{ x | (∃y : A, P y) → P x}
theorem exists_true_of_nonempty {A : Type} (H : nonempty A) : ∃x : A, true :=
nonempty.elim H (take x, exists.intro x trivial)
theorem inhabited_of_nonempty {A : Type} (H : nonempty A) : inhabited A :=
let u : {x | (∃y : A, true) → true} := strong_indefinite_description (λa, true) H in
inhabited.mk (elt_of u)
theorem inhabited_of_exists {A : Type} {P : A → Prop} (H : ∃x, P x) : inhabited A :=
inhabited_of_nonempty (obtain w Hw, from H, nonempty.intro w)
/- the Hilbert epsilon function -/
opaque definition epsilon {A : Type} [H : nonempty A] (P : A → Prop) : A :=
let u : {x | (∃y, P y) → P x} :=
strong_indefinite_description P H in
elt_of u
theorem epsilon_spec_aux {A : Type} (H : nonempty A) (P : A → Prop) (Hex : ∃y, P y) :
P (@epsilon A H P) :=
let u : {x | (∃y, P y) → P x} :=
strong_indefinite_description P H in
has_property u Hex
theorem epsilon_spec {A : Type} {P : A → Prop} (Hex : ∃y, P y) :
P (@epsilon A (nonempty_of_exists Hex) P) :=
epsilon_spec_aux (nonempty_of_exists Hex) P Hex
theorem epsilon_singleton {A : Type} (a : A) : @epsilon A (nonempty.intro a) (λx, x = a) = a :=
epsilon_spec (exists.intro a (eq.refl a))
/- the axiom of choice -/
theorem axiom_of_choice {A : Type} {B : A → Type} {R : Πx, B x → Prop} (H : ∀x, ∃y, R x y) :
∃f, ∀x, R x (f x) :=
let f := λx, @epsilon _ (nonempty_of_exists (H x)) (λy, R x y),
H := take x, epsilon_spec (H x)
in exists.intro f H
theorem skolem {A : Type} {B : A → Type} {P : Πx, B x → Prop} :
(∀x, ∃y, P x y) ↔ ∃f, (∀x, P x (f x)) :=
iff.intro
(assume H : (∀x, ∃y, P x y), axiom_of_choice H)
(assume H : (∃f, (∀x, P x (f x))),
take x, obtain (fw : ∀x, B x) (Hw : ∀x, P x (fw x)), from H,
exists.intro (fw x) (Hw x))
|
fea2cc0a1a4e8e1c0b03c658bdebc3a9dfa46bf7 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /stage0/src/Lean/Meta/Tactic/Simp/Main.lean | af691ce68226f658405a56f2ca90ef45ac8dd1b2 | [
"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 | 40,734 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Transform
import Lean.Meta.CongrTheorems
import Lean.Meta.Tactic.Replace
import Lean.Meta.Tactic.Util
import Lean.Meta.Tactic.Clear
import Lean.Meta.Tactic.UnifyEq
import Lean.Meta.Tactic.Simp.Types
import Lean.Meta.Tactic.Simp.Rewrite
namespace Lean.Meta
namespace Simp
builtin_initialize congrHypothesisExceptionId : InternalExceptionId ←
registerInternalExceptionId `congrHypothesisFailed
def throwCongrHypothesisFailed : MetaM α :=
throw <| Exception.internal congrHypothesisExceptionId
/--
Helper method for bootstrapping purposes. It disables `arith` if support theorems have not been defined yet.
-/
def Config.updateArith (c : Config) : CoreM Config := do
if c.arith then
if (← getEnv).contains ``Nat.Linear.ExprCnstr.eq_of_toNormPoly_eq then
return c
else
return { c with arith := false }
else
return c
def Result.getProof (r : Result) : MetaM Expr := do
match r.proof? with
| some p => return p
| none => mkEqRefl r.expr
/--
Similar to `Result.getProof`, but adds a `mkExpectedTypeHint` if `proof?` is `none`
(i.e., result is definitionally equal to input), but we cannot establish that
`source` and `r.expr` are definitionally when using `TransparencyMode.reducible`. -/
def Result.getProof' (source : Expr) (r : Result) : MetaM Expr := do
match r.proof? with
| some p => return p
| none =>
if (← isDefEq source r.expr) then
mkEqRefl r.expr
else
/- `source` and `r.expr` must be definitionally equal, but
are not definitionally equal at `TransparencyMode.reducible` -/
mkExpectedTypeHint (← mkEqRefl r.expr) (← mkEq source r.expr)
def mkCongrFun (r : Result) (a : Expr) : MetaM Result :=
match r.proof? with
| none => return { expr := mkApp r.expr a, proof? := none }
| some h => return { expr := mkApp r.expr a, proof? := (← Meta.mkCongrFun h a) }
def mkCongr (r₁ r₂ : Result) : MetaM Result :=
let e := mkApp r₁.expr r₂.expr
match r₁.proof?, r₂.proof? with
| none, none => return { expr := e, proof? := none }
| some h, none => return { expr := e, proof? := (← Meta.mkCongrFun h r₂.expr) }
| none, some h => return { expr := e, proof? := (← Meta.mkCongrArg r₁.expr h) }
| some h₁, some h₂ => return { expr := e, proof? := (← Meta.mkCongr h₁ h₂) }
private def mkImpCongr (src : Expr) (r₁ r₂ : Result) : MetaM Result := do
let e := src.updateForallE! r₁.expr r₂.expr
match r₁.proof?, r₂.proof? with
| none, none => return { expr := e, proof? := none }
| _, _ => return { expr := e, proof? := (← Meta.mkImpCongr (← r₁.getProof) (← r₂.getProof)) } -- TODO specialize if bootleneck
/-- Return true if `e` is of the form `ofNat n` where `n` is a kernel Nat literal -/
def isOfNatNatLit (e : Expr) : Bool :=
e.isAppOfArity ``OfNat.ofNat 3 && e.appFn!.appArg!.isNatLit
private def reduceProj (e : Expr) : MetaM Expr := do
match (← reduceProj? e) with
| some e => return e
| _ => return e
private def reduceProjFn? (e : Expr) : SimpM (Option Expr) := do
matchConst e.getAppFn (fun _ => pure none) fun cinfo _ => do
match (← getProjectionFnInfo? cinfo.name) with
| none => return none
| some projInfo =>
if projInfo.fromClass then
if (← read).isDeclToUnfold cinfo.name then
-- We only unfold class projections when the user explicitly requested them to be unfolded.
-- Recall that `unfoldDefinition?` has support for unfolding this kind of projection.
withReducibleAndInstances <| unfoldDefinition? e
else
return none
else
-- `structure` projection
match (← unfoldDefinition? e) with
| none => pure none
| some e =>
match (← reduceProj? e.getAppFn) with
| some f => return some (mkAppN f e.getAppArgs)
| none => return none
private def reduceFVar (cfg : Config) (e : Expr) : MetaM Expr := do
if cfg.zeta then
match (← getFVarLocalDecl e).value? with
| some v => return v
| none => return e
else
return e
/--
Return true if `declName` is the name of a definition of the form
```
def declName ... :=
match ... with
| ...
```
-/
private partial def isMatchDef (declName : Name) : CoreM Bool := do
let .defnInfo info ← getConstInfo declName | return false
return go (← getEnv) info.value
where
go (env : Environment) (e : Expr) : Bool :=
if e.isLambda then
go env e.bindingBody!
else
let f := e.getAppFn
f.isConst && isMatcherCore env f.constName!
private def unfold? (e : Expr) : SimpM (Option Expr) := do
let f := e.getAppFn
if !f.isConst then
return none
let fName := f.constName!
if (← isProjectionFn fName) then
return none -- should be reduced by `reduceProjFn?`
let ctx ← read
if ctx.config.autoUnfold then
if ctx.simpTheorems.isErased fName then
return none
else if hasSmartUnfoldingDecl (← getEnv) fName then
withDefault <| unfoldDefinition? e
else if (← isMatchDef fName) then
let some value ← withDefault <| unfoldDefinition? e | return none
let .reduced value ← reduceMatcher? value | return none
return some value
else
return none
else if ctx.isDeclToUnfold fName then
withDefault <| unfoldDefinition? e
else
return none
private partial def reduce (e : Expr) : SimpM Expr := withIncRecDepth do
let cfg := (← read).config
if cfg.beta then
let e' := e.headBeta
if e' != e then
return (← reduce e')
-- TODO: eta reduction
if cfg.proj then
match (← reduceProjFn? e) with
| some e => return (← reduce e)
| none => pure ()
if cfg.iota then
match (← reduceRecMatcher? e) with
| some e => return (← reduce e)
| none => pure ()
match (← unfold? e) with
| some e => reduce e
| none => return e
private partial def dsimp (e : Expr) : M Expr := do
let cfg ← getConfig
unless cfg.dsimp do
return e
let pre (e : Expr) : M TransformStep := do
if let Step.visit r ← rewritePre e (fun _ => pure none) (rflOnly := true) then
if r.expr != e then
return .visit r.expr
return .visit e
let post (e : Expr) : M TransformStep := do
if let Step.visit r ← rewritePost e (fun _ => pure none) (rflOnly := true) then
if r.expr != e then
return .visit r.expr
let mut eNew ← reduce e
if cfg.zeta && eNew.isFVar then
eNew ← reduceFVar cfg eNew
if eNew != e then return .visit eNew else return .done e
transform (usedLetOnly := cfg.zeta) e (pre := pre) (post := post)
instance : Inhabited (M α) where
default := fun _ _ _ => default
partial def lambdaTelescopeDSimp (e : Expr) (k : Array Expr → Expr → M α) : M α := do
go #[] e
where
go (xs : Array Expr) (e : Expr) : M α := do
match e with
| .lam n d b c => withLocalDecl n c (← dsimp d) fun x => go (xs.push x) (b.instantiate1 x)
| e => k xs e
inductive SimpLetCase where
| dep -- `let x := v; b` is not equivalent to `(fun x => b) v`
| nondepDepVar -- `let x := v; b` is equivalent to `(fun x => b) v`, but result type depends on `x`
| nondep -- `let x := v; b` is equivalent to `(fun x => b) v`, and result type does not depend on `x`
def getSimpLetCase (n : Name) (t : Expr) (b : Expr) : MetaM SimpLetCase := do
withLocalDeclD n t fun x => do
let bx := b.instantiate1 x
/- The following step is potentially very expensive when we have many nested let-decls.
TODO: handle a block of nested let decls in a single pass if this becomes a performance problem. -/
if (← isTypeCorrect bx) then
let bxType ← whnf (← inferType bx)
if (← dependsOn bxType x.fvarId!) then
return SimpLetCase.nondepDepVar
else
return SimpLetCase.nondep
else
return SimpLetCase.dep
/-- Given the application `e`, remove unnecessary casts of the form `Eq.rec a rfl` and `Eq.ndrec a rfl`. -/
partial def removeUnnecessaryCasts (e : Expr) : MetaM Expr := do
let mut args := e.getAppArgs
let mut modified := false
for i in [:args.size] do
let arg := args[i]!
if isDummyEqRec arg then
args := args.set! i (elimDummyEqRec arg)
modified := true
if modified then
return mkAppN e.getAppFn args
else
return e
where
isDummyEqRec (e : Expr) : Bool :=
(e.isAppOfArity ``Eq.rec 6 || e.isAppOfArity ``Eq.ndrec 6) && e.appArg!.isAppOf ``Eq.refl
elimDummyEqRec (e : Expr) : Expr :=
if isDummyEqRec e then
elimDummyEqRec e.appFn!.appFn!.appArg!
else
e
partial def simp (e : Expr) : M Result := withIncRecDepth do
checkMaxHeartbeats "simp"
let cfg ← getConfig
if (← isProof e) then
return { expr := e }
if cfg.memoize then
if let some result := (← get).cache.find? e then
/-
If the result was cached at a dischargeDepth > the current one, it may not be valid.
See issue #1234
-/
if result.dischargeDepth ≤ (← readThe Simp.Context).dischargeDepth then
return result
simpLoop { expr := e }
where
simpLoop (r : Result) : M Result := do
let cfg ← getConfig
if (← get).numSteps > cfg.maxSteps then
throwError "simp failed, maximum number of steps exceeded"
else
let init := r.expr
modify fun s => { s with numSteps := s.numSteps + 1 }
match (← pre r.expr) with
| Step.done r' => cacheResult cfg (← mkEqTrans r r')
| Step.visit r' =>
let r ← mkEqTrans r r'
let r ← mkEqTrans r (← simpStep r.expr)
match (← post r.expr) with
| Step.done r' => cacheResult cfg (← mkEqTrans r r')
| Step.visit r' =>
let r ← mkEqTrans r r'
if cfg.singlePass || init == r.expr then
cacheResult cfg r
else
simpLoop r
simpStep (e : Expr) : M Result := do
match e with
| Expr.mdata m e => let r ← simp e; return { r with expr := mkMData m r.expr }
| Expr.proj .. => simpProj e
| Expr.app .. => simpApp e
| Expr.lam .. => simpLambda e
| Expr.forallE .. => simpForall e
| Expr.letE .. => simpLet e
| Expr.const .. => simpConst e
| Expr.bvar .. => unreachable!
| Expr.sort .. => return { expr := e }
| Expr.lit .. => simpLit e
| Expr.mvar .. => return { expr := (← instantiateMVars e) }
| Expr.fvar .. => return { expr := (← reduceFVar (← getConfig) e) }
simpLit (e : Expr) : M Result := do
match e.natLit? with
| some n =>
/- If `OfNat.ofNat` is marked to be unfolded, we do not pack orphan nat literals as `OfNat.ofNat` applications
to avoid non-termination. See issue #788. -/
if (← readThe Simp.Context).isDeclToUnfold ``OfNat.ofNat then
return { expr := e }
else
return { expr := (← mkNumeral (mkConst ``Nat) n) }
| none => return { expr := e }
simpProj (e : Expr) : M Result := do
match (← reduceProj? e) with
| some e => return { expr := e }
| none =>
let s := e.projExpr!
let motive? ← withLocalDeclD `s (← inferType s) fun s => do
let p := e.updateProj! s
if (← dependsOn (← inferType p) s.fvarId!) then
return none
else
let motive ← mkLambdaFVars #[s] (← mkEq e p)
if !(← isTypeCorrect motive) then
return none
else
return some motive
if let some motive := motive? then
let r ← simp s
let eNew := e.updateProj! r.expr
match r.proof? with
| none => return { expr := eNew }
| some h =>
let hNew ← mkEqNDRec motive (← mkEqRefl e) h
return { expr := eNew, proof? := some hNew }
else
return { expr := (← dsimp e) }
congrArgs (r : Result) (args : Array Expr) : M Result := do
if args.isEmpty then
return r
else
let infos := (← getFunInfoNArgs r.expr args.size).paramInfo
let mut r := r
let mut i := 0
for arg in args do
trace[Debug.Meta.Tactic.simp] "app [{i}] {infos.size} {arg} hasFwdDeps: {infos[i]!.hasFwdDeps}"
if i < infos.size && !infos[i]!.hasFwdDeps then
r ← mkCongr r (← simp arg)
else if (← whnfD (← inferType r.expr)).isArrow then
r ← mkCongr r (← simp arg)
else
r ← mkCongrFun r (← dsimp arg)
i := i + 1
return r
visitFn (e : Expr) : M Result := do
let f := e.getAppFn
let fNew ← simp f
if fNew.expr == f then
return { expr := e }
else
let args := e.getAppArgs
let eNew := mkAppN fNew.expr args
if fNew.proof?.isNone then return { expr := eNew }
let mut proof ← fNew.getProof
for arg in args do
proof ← Meta.mkCongrFun proof arg
return { expr := eNew, proof? := proof }
mkCongrSimp? (f : Expr) : M (Option CongrTheorem) := do
if f.isConst then if (← isMatcher f.constName!) then
-- We always use simple congruence theorems for auxiliary match applications
return none
let info ← getFunInfo f
let kinds := getCongrSimpKinds info
if kinds.all fun k => match k with | CongrArgKind.fixed => true | CongrArgKind.eq => true | _ => false then
/- If all argument kinds are `fixed` or `eq`, then using
simple congruence theorems `congr`, `congrArg`, and `congrFun` produces a more compact proof -/
return none
match (← get).congrCache.find? f with
| some thm? => return thm?
| none =>
let thm? ← mkCongrSimpCore? f info kinds
modify fun s => { s with congrCache := s.congrCache.insert f thm? }
return thm?
/-- Try to use automatically generated congruence theorems. See `mkCongrSimp?`. -/
tryAutoCongrTheorem? (e : Expr) : M (Option Result) := do
let f := e.getAppFn
-- TODO: cache
let some cgrThm ← mkCongrSimp? f | return none
if cgrThm.argKinds.size != e.getAppNumArgs then return none
let mut simplified := false
let mut hasProof := false
let mut hasCast := false
let mut argsNew := #[]
let mut argResults := #[]
let args := e.getAppArgs
for arg in args, kind in cgrThm.argKinds do
match kind with
| CongrArgKind.fixed => argsNew := argsNew.push (← dsimp arg)
| CongrArgKind.cast => hasCast := true; argsNew := argsNew.push arg
| CongrArgKind.subsingletonInst => argsNew := argsNew.push arg
| CongrArgKind.eq =>
let argResult ← simp arg
argResults := argResults.push argResult
argsNew := argsNew.push argResult.expr
if argResult.proof?.isSome then hasProof := true
if arg != argResult.expr then simplified := true
| _ => unreachable!
if !simplified then return some { expr := e }
/-
If `hasProof` is false, we used to return `mkAppN f argsNew` with `proof? := none`.
However, this created a regression when we started using `proof? := none` for `rfl` theorems.
Consider the following goal
```
m n : Nat
a : Fin n
h₁ : m < n
h₂ : Nat.pred (Nat.succ m) < n
⊢ Fin.succ (Fin.mk m h₁) = Fin.succ (Fin.mk m.succ.pred h₂)
```
The term `m.succ.pred` is simplified to `m` using a `Nat.pred_succ` which is a `rfl` theorem.
The auto generated theorem for `Fin.mk` has casts and if used here at `Fin.mk m.succ.pred h₂`,
it produces the term `Fin.mk m (id (Eq.refl m) ▸ h₂)`. The key property here is that the
proof `(id (Eq.refl m) ▸ h₂)` has type `m < n`. If we had just returned `mkAppN f argsNew`,
the resulting term would be `Fin.mk m h₂` which is type correct, but later we would not be
able to apply `eq_self` to
```lean
Fin.succ (Fin.mk m h₁) = Fin.succ (Fin.mk m h₂)
```
because we would not be able to establish that `m < n` and `Nat.pred (Nat.succ m) < n` are definitionally
equal using `TransparencyMode.reducible` (`Nat.pred` is not reducible).
Thus, we decided to return here only if the auto generated congruence theorem does not introduce casts.
-/
if !hasProof && !hasCast then return some { expr := mkAppN f argsNew }
let mut proof := cgrThm.proof
let mut type := cgrThm.type
let mut j := 0 -- index at argResults
let mut subst := #[]
for arg in args, kind in cgrThm.argKinds do
proof := mkApp proof arg
subst := subst.push arg
type := type.bindingBody!
match kind with
| CongrArgKind.fixed => pure ()
| CongrArgKind.cast => pure ()
| CongrArgKind.subsingletonInst =>
let clsNew := type.bindingDomain!.instantiateRev subst
let instNew ← if (← isDefEq (← inferType arg) clsNew) then
pure arg
else
match (← trySynthInstance clsNew) with
| LOption.some val => pure val
| _ =>
trace[Meta.Tactic.simp.congr] "failed to synthesize instance{indentExpr clsNew}"
return none
proof := mkApp proof instNew
subst := subst.push instNew
type := type.bindingBody!
| CongrArgKind.eq =>
let argResult := argResults[j]!
let argProof ← argResult.getProof' arg
j := j + 1
proof := mkApp2 proof argResult.expr argProof
subst := subst.push argResult.expr |>.push argProof
type := type.bindingBody!.bindingBody!
| _ => unreachable!
let some (_, _, rhs) := type.instantiateRev subst |>.eq? | unreachable!
let rhs ← if hasCast then removeUnnecessaryCasts rhs else pure rhs
if hasProof then
return some { expr := rhs, proof? := proof }
else
/- See comment above. This is reachable if `hasCast == true`. The `rhs` is not structurally equal to `mkAppN f argsNew` -/
return some { expr := rhs }
congrDefault (e : Expr) : M Result := do
if let some result ← tryAutoCongrTheorem? e then
mkEqTrans result (← visitFn result.expr)
else
withParent e <| e.withApp fun f args => do
congrArgs (← simp f) args
/-- Process the given congruence theorem hypothesis. Return true if it made "progress". -/
processCongrHypothesis (h : Expr) : M Bool := do
forallTelescopeReducing (← inferType h) fun xs hType => withNewLemmas xs do
let lhs ← instantiateMVars hType.appFn!.appArg!
let r ← simp lhs
let rhs := hType.appArg!
rhs.withApp fun m zs => do
let val ← mkLambdaFVars zs r.expr
unless (← isDefEq m val) do
throwCongrHypothesisFailed
unless (← isDefEq h (← mkLambdaFVars xs (← r.getProof))) do
throwCongrHypothesisFailed
/- We used to return `false` if `r.proof? = none` (i.e., an implicit `rfl` proof) because we
assumed `dsimp` would also be able to simplify the term, but this is not true
for non-trivial user-provided theorems.
Example:
```
@[congr] theorem image_congr {f g : α → β} {s : Set α} (h : ∀ a, mem a s → f a = g a) : image f s = image g s :=
...
example {Γ: Set Nat}: (image (Nat.succ ∘ Nat.succ) Γ) = (image (fun a => a.succ.succ) Γ) := by
simp only [Function.comp_apply]
```
`Function.comp_apply` is a `rfl` theorem, but `dsimp` will not apply it because the composition
is not fully applied. See comment at issue #1113
Thus, we have an extra check now if `xs.size > 0`. TODO: refine this test.
-/
return r.proof?.isSome || (xs.size > 0 && lhs != r.expr)
/-- Try to rewrite `e` children using the given congruence theorem -/
trySimpCongrTheorem? (c : SimpCongrTheorem) (e : Expr) : M (Option Result) := withNewMCtxDepth do
trace[Debug.Meta.Tactic.simp.congr] "{c.theoremName}, {e}"
let thm ← mkConstWithFreshMVarLevels c.theoremName
let (xs, bis, type) ← forallMetaTelescopeReducing (← inferType thm)
if c.hypothesesPos.any (· ≥ xs.size) then
return none
let lhs := type.appFn!.appArg!
let rhs := type.appArg!
let numArgs := lhs.getAppNumArgs
let mut e := e
let mut extraArgs := #[]
if e.getAppNumArgs > numArgs then
let args := e.getAppArgs
e := mkAppN e.getAppFn args[:numArgs]
extraArgs := args[numArgs:].toArray
if (← isDefEq lhs e) then
let mut modified := false
for i in c.hypothesesPos do
let x := xs[i]!
try
if (← processCongrHypothesis x) then
modified := true
catch ex =>
trace[Meta.Tactic.simp.congr] "processCongrHypothesis {c.theoremName} failed {← inferType x}"
if ex.isMaxRecDepth then
-- Recall that `processCongrHypothesis` invokes `simp` recursively.
throw ex
else
return none
unless modified do
trace[Meta.Tactic.simp.congr] "{c.theoremName} not modified"
return none
unless (← synthesizeArgs c.theoremName xs bis (← read).discharge?) do
trace[Meta.Tactic.simp.congr] "{c.theoremName} synthesizeArgs failed"
return none
let eNew ← instantiateMVars rhs
let proof ← instantiateMVars (mkAppN thm xs)
congrArgs { expr := eNew, proof? := proof } extraArgs
else
return none
congr (e : Expr) : M Result := do
let f := e.getAppFn
if f.isConst then
let congrThms ← getSimpCongrTheorems
let cs := congrThms.get f.constName!
for c in cs do
match (← trySimpCongrTheorem? c e) with
| none => pure ()
| some r => return r
congrDefault e
else
congrDefault e
simpApp (e : Expr) : M Result := do
let e ← reduce e
if !e.isApp then
simp e
else if isOfNatNatLit e then
-- Recall that we expand "orphan" kernel nat literals `n` into `ofNat n`
return { expr := e }
else
congr e
simpConst (e : Expr) : M Result :=
return { expr := (← reduce e) }
withNewLemmas {α} (xs : Array Expr) (f : M α) : M α := do
if (← getConfig).contextual then
let mut s ← getSimpTheorems
let mut updated := false
for x in xs do
if (← isProof x) then
s ← s.addTheorem x
updated := true
if updated then
withSimpTheorems s f
else
f
else
f
simpLambda (e : Expr) : M Result :=
withParent e <| lambdaTelescopeDSimp e fun xs e => withNewLemmas xs do
let r ← simp e
let eNew ← mkLambdaFVars xs r.expr
match r.proof? with
| none => return { expr := eNew }
| some h =>
let p ← xs.foldrM (init := h) fun x h => do
mkFunExt (← mkLambdaFVars #[x] h)
return { expr := eNew, proof? := p }
simpArrow (e : Expr) : M Result := do
trace[Debug.Meta.Tactic.simp] "arrow {e}"
let p := e.bindingDomain!
let q := e.bindingBody!
let rp ← simp p
trace[Debug.Meta.Tactic.simp] "arrow [{(← getConfig).contextual}] {p} [{← isProp p}] -> {q} [{← isProp q}]"
if (← pure (← getConfig).contextual <&&> isProp p <&&> isProp q) then
trace[Debug.Meta.Tactic.simp] "ctx arrow {rp.expr} -> {q}"
withLocalDeclD e.bindingName! rp.expr fun h => do
let s ← getSimpTheorems
let s ← s.addTheorem h
withSimpTheorems s do
let rq ← simp q
match rq.proof? with
| none => mkImpCongr e rp rq
| some hq =>
let hq ← mkLambdaFVars #[h] hq
/-
We use the default reducibility setting at `mkImpDepCongrCtx` and `mkImpCongrCtx` because they use the theorems
```lean
@implies_dep_congr_ctx : ∀ {p₁ p₂ q₁ : Prop}, p₁ = p₂ → ∀ {q₂ : p₂ → Prop}, (∀ (h : p₂), q₁ = q₂ h) → (p₁ → q₁) = ∀ (h : p₂), q₂ h
@implies_congr_ctx : ∀ {p₁ p₂ q₁ q₂ : Prop}, p₁ = p₂ → (p₂ → q₁ = q₂) → (p₁ → q₁) = (p₂ → q₂)
```
And the proofs may be from `rfl` theorems which are now omitted. Moreover, we cannot establish that the two
terms are definitionally equal using `withReducible`.
TODO (better solution): provide the problematic implicit arguments explicitly. It is more efficient and avoids this
problem.
-/
if rq.expr.containsFVar h.fvarId! then
return { expr := (← mkForallFVars #[h] rq.expr), proof? := (← withDefault <| mkImpDepCongrCtx (← rp.getProof) hq) }
else
return { expr := e.updateForallE! rp.expr rq.expr, proof? := (← withDefault <| mkImpCongrCtx (← rp.getProof) hq) }
else
mkImpCongr e rp (← simp q)
simpForall (e : Expr) : M Result := withParent e do
trace[Debug.Meta.Tactic.simp] "forall {e}"
if e.isArrow then
simpArrow e
else if (← isProp e) then
withLocalDecl e.bindingName! e.bindingInfo! e.bindingDomain! fun x => withNewLemmas #[x] do
let b := e.bindingBody!.instantiate1 x
let rb ← simp b
let eNew ← mkForallFVars #[x] rb.expr
match rb.proof? with
| none => return { expr := eNew }
| some h => return { expr := eNew, proof? := (← mkForallCongr (← mkLambdaFVars #[x] h)) }
else
return { expr := (← dsimp e) }
simpLet (e : Expr) : M Result := do
let Expr.letE n t v b _ := e | unreachable!
if (← getConfig).zeta then
return { expr := b.instantiate1 v }
else
match (← getSimpLetCase n t b) with
| SimpLetCase.dep => return { expr := (← dsimp e) }
| SimpLetCase.nondep =>
let rv ← simp v
withLocalDeclD n t fun x => do
let bx := b.instantiate1 x
let rbx ← simp bx
let hb? ← match rbx.proof? with
| none => pure none
| some h => pure (some (← mkLambdaFVars #[x] h))
let e' := mkLet n t rv.expr (← rbx.expr.abstractM #[x])
match rv.proof?, hb? with
| none, none => return { expr := e' }
| some h, none => return { expr := e', proof? := some (← mkLetValCongr (← mkLambdaFVars #[x] rbx.expr) h) }
| _, some h => return { expr := e', proof? := some (← mkLetCongr (← rv.getProof) h) }
| SimpLetCase.nondepDepVar =>
let v' ← dsimp v
withLocalDeclD n t fun x => do
let bx := b.instantiate1 x
let rbx ← simp bx
let e' := mkLet n t v' (← rbx.expr.abstractM #[x])
match rbx.proof? with
| none => return { expr := e' }
| some h =>
let h ← mkLambdaFVars #[x] h
return { expr := e', proof? := some (← mkLetBodyCongr v' h) }
cacheResult (cfg : Config) (r : Result) : M Result := do
if cfg.memoize then
let dischargeDepth := (← readThe Simp.Context).dischargeDepth
modify fun s => { s with cache := s.cache.insert e { r with dischargeDepth } }
return r
def main (e : Expr) (ctx : Context) (methods : Methods := {}) : MetaM Result := do
let ctx := { ctx with config := (← ctx.config.updateArith) }
withConfig (fun c => { c with etaStruct := ctx.config.etaStruct }) <| withReducible do
try
simp e methods ctx |>.run' {}
catch ex =>
if ex.isMaxHeartbeat then throwNestedTacticEx `simp ex else throw ex
def dsimpMain (e : Expr) (ctx : Context) (methods : Methods := {}) : MetaM Expr := do
withConfig (fun c => { c with etaStruct := ctx.config.etaStruct }) <| withReducible do
try
dsimp e methods ctx |>.run' {}
catch ex =>
if ex.isMaxHeartbeat then throwNestedTacticEx `dsimp ex else throw ex
/--
Return true if `e` is of the form `(x : α) → ... → s = t → ... → False`
Recall that this kind of proposition is generated by Lean when creating equations for
functions and match-expressions with overlapping cases.
Example: the following `match`-expression has overlapping cases.
```
def f (x y : Nat) :=
match x, y with
| Nat.succ n, Nat.succ m => ...
| _, _ => 0
```
The second equation is of the form
```
(x y : Nat) → ((n m : Nat) → x = Nat.succ n → y = Nat.succ m → False) → f x y = 0
```
The hypothesis `(n m : Nat) → x = Nat.succ n → y = Nat.succ m → False` is essentially
saying the first case is not applicable.
-/
partial def isEqnThmHypothesis (e : Expr) : Bool :=
e.isForall && go e
where
go (e : Expr) : Bool :=
match e with
| .forallE _ d b _ => (d.isEq || d.isHEq || b.hasLooseBVar 0) && go b
| _ => e.isConstOf ``False
abbrev Discharge := Expr → SimpM (Option Expr)
def dischargeUsingAssumption? (e : Expr) : SimpM (Option Expr) := do
(← getLCtx).findDeclRevM? fun localDecl => do
if localDecl.isAuxDecl then
return none
else if (← isDefEq e localDecl.type) then
return some localDecl.toExpr
else
return none
/--
Tries to solve `e` using `unifyEq?`.
It assumes that `isEqnThmHypothesis e` is `true`.
-/
partial def dischargeEqnThmHypothesis? (e : Expr) : MetaM (Option Expr) := do
assert! isEqnThmHypothesis e
let mvar ← mkFreshExprSyntheticOpaqueMVar e
withReader (fun ctx => { ctx with canUnfold? := canUnfoldAtMatcher }) do
if let .none ← go? mvar.mvarId! then
instantiateMVars mvar
else
return none
where
go? (mvarId : MVarId) : MetaM (Option MVarId) :=
try
let (fvarId, mvarId) ← mvarId.intro1
mvarId.withContext do
let localDecl ← fvarId.getDecl
if localDecl.type.isEq || localDecl.type.isHEq then
if let some { mvarId, .. } ← unifyEq? mvarId fvarId {} then
go? mvarId
else
return none
else
go? mvarId
catch _ =>
return some mvarId
namespace DefaultMethods
mutual
partial def discharge? (e : Expr) : SimpM (Option Expr) := do
if isEqnThmHypothesis e then
if let some r ← dischargeUsingAssumption? e then
return some r
if let some r ← dischargeEqnThmHypothesis? e then
return some r
let ctx ← read
trace[Meta.Tactic.simp.discharge] ">> discharge?: {e}"
if ctx.dischargeDepth >= ctx.config.maxDischargeDepth then
trace[Meta.Tactic.simp.discharge] "maximum discharge depth has been reached"
return none
else
withReader (fun ctx => { ctx with dischargeDepth := ctx.dischargeDepth + 1 }) do
let r ← simp e { pre := pre, post := post, discharge? := discharge? }
if r.expr.isConstOf ``True then
try
return some (← mkOfEqTrue (← r.getProof))
catch _ =>
return none
else
return none
partial def pre (e : Expr) : SimpM Step :=
preDefault e discharge?
partial def post (e : Expr) : SimpM Step :=
postDefault e discharge?
end
def methods : Methods :=
{ pre := pre, post := post, discharge? := discharge? }
end DefaultMethods
end Simp
def simp (e : Expr) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) : MetaM Simp.Result := do profileitM Exception "simp" (← getOptions) do
match discharge? with
| none => Simp.main e ctx (methods := Simp.DefaultMethods.methods)
| some d => Simp.main e ctx (methods := { pre := (Simp.preDefault · d), post := (Simp.postDefault · d), discharge? := d })
def dsimp (e : Expr) (ctx : Simp.Context) : MetaM Expr := do profileitM Exception "dsimp" (← getOptions) do
Simp.dsimpMain e ctx (methods := Simp.DefaultMethods.methods)
/--
Auxiliary method.
Given the current `target` of `mvarId`, apply `r` which is a new target and proof that it is equaal to the current one.
-/
def applySimpResultToTarget (mvarId : MVarId) (target : Expr) (r : Simp.Result) : MetaM MVarId := do
match r.proof? with
| some proof => mvarId.replaceTargetEq r.expr proof
| none =>
if target != r.expr then
mvarId.replaceTargetDefEq r.expr
else
return mvarId
/-- See `simpTarget`. This method assumes `mvarId` is not assigned, and we are already using `mvarId`s local context. -/
def simpTargetCore (mvarId : MVarId) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) (mayCloseGoal := true) : MetaM (Option MVarId) := do
let target ← instantiateMVars (← mvarId.getType)
let r ← simp target ctx discharge?
if mayCloseGoal && r.expr.isConstOf ``True then
match r.proof? with
| some proof => mvarId.assign (← mkOfEqTrue proof)
| none => mvarId.assign (mkConst ``True.intro)
return none
else
applySimpResultToTarget mvarId target r
/--
Simplify the given goal target (aka type). Return `none` if the goal was closed. Return `some mvarId'` otherwise,
where `mvarId'` is the simplified new goal. -/
def simpTarget (mvarId : MVarId) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) (mayCloseGoal := true) : MetaM (Option MVarId) :=
mvarId.withContext do
mvarId.checkNotAssigned `simp
simpTargetCore mvarId ctx discharge? mayCloseGoal
/--
Apply the result `r` for `prop` (which is inhabited by `proof`). Return `none` if the goal was closed. Return `some (proof', prop')`
otherwise, where `proof' : prop'` and `prop'` is the simplified `prop`.
This method assumes `mvarId` is not assigned, and we are already using `mvarId`s local context. -/
def applySimpResultToProp (mvarId : MVarId) (proof : Expr) (prop : Expr) (r : Simp.Result) (mayCloseGoal := true) : MetaM (Option (Expr × Expr)) := do
if mayCloseGoal && r.expr.isConstOf ``False then
match r.proof? with
| some eqProof => mvarId.assign (← mkFalseElim (← mvarId.getType) (← mkEqMP eqProof proof))
| none => mvarId.assign (← mkFalseElim (← mvarId.getType) proof)
return none
else
match r.proof? with
| some eqProof => return some ((← mkEqMP eqProof proof), r.expr)
| none =>
if r.expr != prop then
return some ((← mkExpectedTypeHint proof r.expr), r.expr)
else
return some (proof, r.expr)
def applySimpResultToFVarId (mvarId : MVarId) (fvarId : FVarId) (r : Simp.Result) (mayCloseGoal : Bool) : MetaM (Option (Expr × Expr)) := do
let localDecl ← fvarId.getDecl
applySimpResultToProp mvarId (mkFVar fvarId) localDecl.type r mayCloseGoal
/--
Simplify `prop` (which is inhabited by `proof`). Return `none` if the goal was closed. Return `some (proof', prop')`
otherwise, where `proof' : prop'` and `prop'` is the simplified `prop`.
This method assumes `mvarId` is not assigned, and we are already using `mvarId`s local context. -/
def simpStep (mvarId : MVarId) (proof : Expr) (prop : Expr) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) (mayCloseGoal := true) : MetaM (Option (Expr × Expr)) := do
let r ← simp prop ctx discharge?
applySimpResultToProp mvarId proof prop r (mayCloseGoal := mayCloseGoal)
def applySimpResultToLocalDeclCore (mvarId : MVarId) (fvarId : FVarId) (r : Option (Expr × Expr)) : MetaM (Option (FVarId × MVarId)) := do
match r with
| none => return none
| some (value, type') =>
let localDecl ← fvarId.getDecl
if localDecl.type != type' then
let mvarId ← mvarId.assert localDecl.userName type' value
let mvarId ← mvarId.tryClear localDecl.fvarId
let (fvarId, mvarId) ← mvarId.intro1P
return some (fvarId, mvarId)
else
return some (fvarId, mvarId)
/--
Simplify `simp` result to the given local declaration. Return `none` if the goal was closed.
This method assumes `mvarId` is not assigned, and we are already using `mvarId`s local context. -/
def applySimpResultToLocalDecl (mvarId : MVarId) (fvarId : FVarId) (r : Simp.Result) (mayCloseGoal : Bool) : MetaM (Option (FVarId × MVarId)) := do
if r.proof?.isNone then
-- New result is definitionally equal to input. Thus, we can avoid creating a new variable if there are dependencies
let mvarId ← mvarId.replaceLocalDeclDefEq fvarId r.expr
if mayCloseGoal && r.expr.isConstOf ``False then
mvarId.assign (← mkFalseElim (← mvarId.getType) (mkFVar fvarId))
return none
else
return some (fvarId, mvarId)
else
applySimpResultToLocalDeclCore mvarId fvarId (← applySimpResultToFVarId mvarId fvarId r mayCloseGoal)
def simpLocalDecl (mvarId : MVarId) (fvarId : FVarId) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) (mayCloseGoal := true) : MetaM (Option (FVarId × MVarId)) := do
mvarId.withContext do
mvarId.checkNotAssigned `simp
let type ← instantiateMVars (← fvarId.getType)
applySimpResultToLocalDeclCore mvarId fvarId (← simpStep mvarId (mkFVar fvarId) type ctx discharge? mayCloseGoal)
abbrev FVarIdToLemmaId := FVarIdMap Name
def simpGoal (mvarId : MVarId) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) (simplifyTarget : Bool := true) (fvarIdsToSimp : Array FVarId := #[]) (fvarIdToLemmaId : FVarIdToLemmaId := {}) : MetaM (Option (Array FVarId × MVarId)) := do
mvarId.withContext do
mvarId.checkNotAssigned `simp
let mut mvarId := mvarId
let mut toAssert := #[]
let mut replaced := #[]
for fvarId in fvarIdsToSimp do
let localDecl ← fvarId.getDecl
let type ← instantiateMVars localDecl.type
let ctx ← match fvarIdToLemmaId.find? localDecl.fvarId with
| none => pure ctx
| some thmId => pure { ctx with simpTheorems := ctx.simpTheorems.eraseTheorem thmId }
let r ← simp type ctx discharge?
match r.proof? with
| some _ => match (← applySimpResultToProp mvarId (mkFVar fvarId) type r) with
| none => return none
| some (value, type) => toAssert := toAssert.push { userName := localDecl.userName, type := type, value := value }
| none =>
if r.expr.isConstOf ``False then
mvarId.assign (← mkFalseElim (← mvarId.getType) (mkFVar fvarId))
return none
-- TODO: if there are no forwards dependencies we may consider using the same approach we used when `r.proof?` is a `some ...`
-- Reason: it introduces a `mkExpectedTypeHint`
mvarId ← mvarId.replaceLocalDeclDefEq fvarId r.expr
replaced := replaced.push fvarId
if simplifyTarget then
match (← simpTarget mvarId ctx discharge?) with
| none => return none
| some mvarIdNew => mvarId := mvarIdNew
let (fvarIdsNew, mvarIdNew) ← mvarId.assertHypotheses toAssert
let toClear := fvarIdsToSimp.filter fun fvarId => !replaced.contains fvarId
let mvarIdNew ← mvarIdNew.tryClearMany toClear
return (fvarIdsNew, mvarIdNew)
def simpTargetStar (mvarId : MVarId) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) : MetaM TacticResultCNM := mvarId.withContext do
let mut ctx := ctx
for h in (← getPropHyps) do
let localDecl ← h.getDecl
let proof := localDecl.toExpr
let simpTheorems ← ctx.simpTheorems.addTheorem proof
ctx := { ctx with simpTheorems }
match (← simpTarget mvarId ctx discharge?) with
| none => return TacticResultCNM.closed
| some mvarId' =>
if (← mvarId.getType) == (← mvarId'.getType) then
return TacticResultCNM.noChange
else
return TacticResultCNM.modified mvarId'
def dsimpGoal (mvarId : MVarId) (ctx : Simp.Context) (simplifyTarget : Bool := true) (fvarIdsToSimp : Array FVarId := #[]) : MetaM (Option MVarId) := do
mvarId.withContext do
mvarId.checkNotAssigned `simp
let mut mvarId := mvarId
for fvarId in fvarIdsToSimp do
let type ← instantiateMVars (← fvarId.getType)
let typeNew ← dsimp type ctx
if typeNew.isConstOf ``False then
mvarId.assign (← mkFalseElim (← mvarId.getType) (mkFVar fvarId))
return none
if typeNew != type then
mvarId ← mvarId.replaceLocalDeclDefEq fvarId typeNew
if simplifyTarget then
let target ← mvarId.getType
let targetNew ← dsimp target ctx
if targetNew.isConstOf ``True then
mvarId.assign (mkConst ``True.intro)
return none
if let some (_, lhs, rhs) := targetNew.eq? then
if (← withReducible <| isDefEq lhs rhs) then
mvarId.assign (← mkEqRefl lhs)
return none
if target != targetNew then
mvarId ← mvarId.replaceTargetDefEq targetNew
return some mvarId
end Lean.Meta
|
cce3d38bdf4a8d35f00ca9c21e99bd6d68b08f6d | 3dd1b66af77106badae6edb1c4dea91a146ead30 | /tests/lean/run/tactic24.lean | e7e60aa17528c5e94e654b0280af91e12a3c1a5d | [
"Apache-2.0"
] | permissive | silky/lean | 79c20c15c93feef47bb659a2cc139b26f3614642 | df8b88dca2f8da1a422cb618cd476ef5be730546 | refs/heads/master | 1,610,737,587,697 | 1,406,574,534,000 | 1,406,574,534,000 | 22,362,176 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 554 | lean | import standard
using tactic
definition my_tac1 := apply @refl
definition my_tac2 := repeat (apply @and_intro; assumption)
tactic_hint my_tac1
tactic_hint my_tac2
theorem T1 {A : Type.{2}} (a : A) : a = a
:= _
theorem T2 {a b c : Prop} (Ha : a) (Hb : b) (Hc : c) : a ∧ b ∧ c
:= _
definition my_tac3 := fixpoint (λ f, [apply @or_intro_left; f |
apply @or_intro_right; f |
assumption])
tactic_hint [or] my_tac3
theorem T3 {a b c : Prop} (Hb : b) : a ∨ b ∨ c
:= _
|
c46329ac1e81cbf09dcc78c0ed44899e8b5cb215 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/seq/seq.lean | 003053ca0f475490e83bd86b4bbf837822c72ef3 | [
"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 | 30,072 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.list.basic
import data.lazy_list
import data.nat.basic
import data.stream.init
import data.seq.computation
universes u v w
/-
coinductive seq (α : Type u) : Type u
| nil : seq α
| cons : α → seq α → seq α
-/
/--
A stream `s : option α` is a sequence if `s.nth n = none` implies `s.nth (n + 1) = none`.
-/
def stream.is_seq {α : Type u} (s : stream (option α)) : Prop :=
∀ {n : ℕ}, s n = none → s (n + 1) = none
/-- `seq α` is the type of possibly infinite lists (referred here as sequences).
It is encoded as an infinite stream of options such that if `f n = none`, then
`f m = none` for all `m ≥ n`. -/
def seq (α : Type u) : Type u := {f : stream (option α) // f.is_seq}
/-- `seq1 α` is the type of nonempty sequences. -/
def seq1 (α) := α × seq α
namespace seq
variables {α : Type u} {β : Type v} {γ : Type w}
/-- The empty sequence -/
def nil : seq α := ⟨stream.const none, λ n h, rfl⟩
instance : inhabited (seq α) := ⟨nil⟩
/-- Prepend an element to a sequence -/
def cons (a : α) (s : seq α) : seq α :=
⟨some a :: s.1, begin
rintros (n | _) h,
{ contradiction },
{ exact s.2 h }
end⟩
@[simp] lemma val_cons (s : seq α) (x : α) : (cons x s).val = some x :: s.val := rfl
/-- Get the nth element of a sequence (if it exists) -/
def nth : seq α → ℕ → option α := subtype.val
@[simp] theorem nth_mk (f hf) : @nth α ⟨f, hf⟩ = f := rfl
@[simp] theorem nth_nil (n : ℕ) : (@nil α).nth n = none := rfl
@[simp] theorem nth_cons_zero (a : α) (s : seq α) : (cons a s).nth 0 = some a := rfl
@[simp] theorem nth_cons_succ (a : α) (s : seq α) (n : ℕ) : (cons a s).nth (n + 1) = s.nth n := rfl
@[ext] protected lemma ext {s t : seq α} (h : ∀ n : ℕ, s.nth n = t.nth n) : s = t :=
subtype.eq $ funext h
lemma cons_injective2 : function.injective2 (cons : α → seq α → seq α) :=
λ x y s t h, ⟨by rw [←option.some_inj, ←nth_cons_zero, h, nth_cons_zero],
seq.ext $ λ n, by simp_rw [←nth_cons_succ x s n, h, nth_cons_succ]⟩
lemma cons_left_injective (s : seq α) : function.injective (λ x, cons x s) :=
cons_injective2.left _
lemma cons_right_injective (x : α) : function.injective (cons x) :=
cons_injective2.right _
/-- A sequence has terminated at position `n` if the value at position `n` equals `none`. -/
def terminated_at (s : seq α) (n : ℕ) : Prop := s.nth n = none
/-- It is decidable whether a sequence terminates at a given position. -/
instance terminated_at_decidable (s : seq α) (n : ℕ) : decidable (s.terminated_at n) :=
decidable_of_iff' (s.nth n).is_none $ by unfold terminated_at; cases s.nth n; simp
/-- A sequence terminates if there is some position `n` at which it has terminated. -/
def terminates (s : seq α) : Prop := ∃ (n : ℕ), s.terminated_at n
theorem not_terminates_iff {s : seq α} : ¬ s.terminates ↔ ∀ n, (s.nth n).is_some :=
by simp [terminates, terminated_at, ←ne.def, option.ne_none_iff_is_some]
/-- Functorial action of the functor `option (α × _)` -/
@[simp] def omap (f : β → γ) : option (α × β) → option (α × γ)
| none := none
| (some (a, b)) := some (a, f b)
/-- Get the first element of a sequence -/
def head (s : seq α) : option α := nth s 0
/-- Get the tail of a sequence (or `nil` if the sequence is `nil`) -/
def tail (s : seq α) : seq α := ⟨s.1.tail, λ n, by { cases s with f al, exact al }⟩
protected def mem (a : α) (s : seq α) := some a ∈ s.1
instance : has_mem α (seq α) :=
⟨seq.mem⟩
theorem le_stable (s : seq α) {m n} (h : m ≤ n) : s.nth m = none → s.nth n = none :=
by { cases s with f al, induction h with n h IH, exacts [id, λ h2, al (IH h2)] }
/-- If a sequence terminated at position `n`, it also terminated at `m ≥ n `. -/
lemma terminated_stable : ∀ (s : seq α) {m n : ℕ}, m ≤ n → s.terminated_at m →
s.terminated_at n :=
le_stable
/--
If `s.nth n = some aₙ` for some value `aₙ`, then there is also some value `aₘ` such
that `s.nth = some aₘ` for `m ≤ n`.
-/
lemma ge_stable (s : seq α) {aₙ : α} {n m : ℕ} (m_le_n : m ≤ n)
(s_nth_eq_some : s.nth n = some aₙ) :
∃ (aₘ : α), s.nth m = some aₘ :=
have s.nth n ≠ none, by simp [s_nth_eq_some],
have s.nth m ≠ none, from mt (s.le_stable m_le_n) this,
option.ne_none_iff_exists'.mp this
theorem not_mem_nil (a : α) : a ∉ @nil α :=
λ ⟨n, (h : some a = none)⟩, by injection h
theorem mem_cons (a : α) : ∀ (s : seq α), a ∈ cons a s
| ⟨f, al⟩ := stream.mem_cons (some a) _
theorem mem_cons_of_mem (y : α) {a : α} : ∀ {s : seq α}, a ∈ s → a ∈ cons y s
| ⟨f, al⟩ := stream.mem_cons_of_mem (some y)
theorem eq_or_mem_of_mem_cons {a b : α} : ∀ {s : seq α}, a ∈ cons b s → a = b ∨ a ∈ s
| ⟨f, al⟩ h := (stream.eq_or_mem_of_mem_cons h).imp_left (λ h, by injection h)
@[simp] theorem mem_cons_iff {a b : α} {s : seq α} : a ∈ cons b s ↔ a = b ∨ a ∈ s :=
⟨eq_or_mem_of_mem_cons, by rintro (rfl|m); [apply mem_cons, exact mem_cons_of_mem _ m]⟩
/-- Destructor for a sequence, resulting in either `none` (for `nil`) or
`some (a, s)` (for `cons a s`). -/
def destruct (s : seq α) : option (seq1 α) :=
(λ a', (a', s.tail)) <$> nth s 0
theorem destruct_eq_nil {s : seq α} : destruct s = none → s = nil :=
begin
dsimp [destruct],
induction f0 : nth s 0; intro h,
{ apply subtype.eq,
funext n,
induction n with n IH, exacts [f0, s.2 IH] },
{ contradiction }
end
theorem destruct_eq_cons {s : seq α} {a s'} : destruct s = some (a, s') → s = cons a s' :=
begin
dsimp [destruct],
induction f0 : nth s 0 with a'; intro h,
{ contradiction },
{ cases s with f al,
injections with _ h1 h2,
rw ←h2, apply subtype.eq, dsimp [tail, cons],
rw h1 at f0, rw ←f0,
exact (stream.eta f).symm }
end
@[simp] theorem destruct_nil : destruct (nil : seq α) = none := rfl
@[simp] theorem destruct_cons (a : α) : ∀ s, destruct (cons a s) = some (a, s)
| ⟨f, al⟩ := begin
unfold cons destruct functor.map,
apply congr_arg (λ s, some (a, s)),
apply subtype.eq, dsimp [tail], rw [stream.tail_cons]
end
theorem head_eq_destruct (s : seq α) : head s = prod.fst <$> destruct s :=
by unfold destruct head; cases nth s 0; refl
@[simp] theorem head_nil : head (nil : seq α) = none := rfl
@[simp] theorem head_cons (a : α) (s) : head (cons a s) = some a :=
by rw [head_eq_destruct, destruct_cons]; refl
@[simp] theorem tail_nil : tail (nil : seq α) = nil := rfl
@[simp] theorem tail_cons (a : α) (s) : tail (cons a s) = s :=
by cases s with f al; apply subtype.eq; dsimp [tail, cons]; rw [stream.tail_cons]
@[simp] theorem nth_tail (s : seq α) (n) : nth (tail s) n = nth s (n + 1) := rfl
/-- Recursion principle for sequences, compare with `list.rec_on`. -/
def rec_on {C : seq α → Sort v} (s : seq α)
(h1 : C nil) (h2 : ∀ x s, C (cons x s)) : C s := begin
induction H : destruct s with v v,
{ rw destruct_eq_nil H, apply h1 },
{ cases v with a s', rw destruct_eq_cons H, apply h2 }
end
theorem mem_rec_on {C : seq α → Prop} {a s} (M : a ∈ s)
(h1 : ∀ b s', (a = b ∨ C s') → C (cons b s')) : C s :=
begin
cases M with k e, unfold stream.nth at e,
induction k with k IH generalizing s,
{ have TH : s = cons a (tail s),
{ apply destruct_eq_cons,
unfold destruct nth functor.map, rw ←e, refl },
rw TH, apply h1 _ _ (or.inl rfl) },
revert e, apply s.rec_on _ (λ b s', _); intro e,
{ injection e },
{ have h_eq : (cons b s').val (nat.succ k) = s'.val k, { cases s'; refl },
rw [h_eq] at e,
apply h1 _ _ (or.inr (IH e)) }
end
def corec.F (f : β → option (α × β)) : option β → option α × option β
| none := (none, none)
| (some b) := match f b with none := (none, none) | some (a, b') := (some a, some b') end
/-- Corecursor for `seq α` as a coinductive type. Iterates `f` to produce new elements
of the sequence until `none` is obtained. -/
def corec (f : β → option (α × β)) (b : β) : seq α :=
begin
refine ⟨stream.corec' (corec.F f) (some b), λ n h, _⟩,
rw stream.corec'_eq,
change stream.corec' (corec.F f) (corec.F f (some b)).2 n = none,
revert h, generalize : some b = o, revert o,
induction n with n IH; intro o,
{ change (corec.F f o).1 = none → (corec.F f (corec.F f o).2).1 = none,
cases o with b; intro h, { refl },
dsimp [corec.F] at h, dsimp [corec.F],
cases f b with s, { refl },
{ cases s with a b', contradiction } },
{ rw [stream.corec'_eq (corec.F f) (corec.F f o).2,
stream.corec'_eq (corec.F f) o],
exact IH (corec.F f o).2 }
end
@[simp] theorem corec_eq (f : β → option (α × β)) (b : β) :
destruct (corec f b) = omap (corec f) (f b) :=
begin
dsimp [corec, destruct, nth],
change stream.corec' (corec.F f) (some b) 0 with (corec.F f (some b)).1,
dsimp [corec.F],
induction h : f b with s, { refl },
cases s with a b', dsimp [corec.F],
apply congr_arg (λ b', some (a, b')),
apply subtype.eq,
dsimp [corec, tail],
rw [stream.corec'_eq, stream.tail_cons],
dsimp [corec.F], rw h, refl
end
section bisim
variable (R : seq α → seq α → Prop)
local infix (name := R) ` ~ `:50 := R
def bisim_o : option (seq1 α) → option (seq1 α) → Prop
| none none := true
| (some (a, s)) (some (a', s')) := a = a' ∧ R s s'
| _ _ := false
attribute [simp] bisim_o
def is_bisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → bisim_o R (destruct s₁) (destruct s₂)
-- If two streams are bisimilar, then they are equal
theorem eq_of_bisim (bisim : is_bisimulation R) {s₁ s₂} (r : s₁ ~ s₂) : s₁ = s₂ :=
begin
apply subtype.eq,
apply stream.eq_of_bisim (λ x y, ∃ s s' : seq α, s.1 = x ∧ s'.1 = y ∧ R s s'),
dsimp [stream.is_bisimulation],
intros t₁ t₂ e,
exact match t₁, t₂, e with ._, ._, ⟨s, s', rfl, rfl, r⟩ :=
suffices head s = head s' ∧ R (tail s) (tail s'), from
and.imp id (λ r, ⟨tail s, tail s',
by cases s; refl, by cases s'; refl, r⟩) this,
begin
have := bisim r, revert r this,
apply rec_on s _ _; intros; apply rec_on s' _ _; intros; intros r this,
{ constructor, refl, assumption },
{ rw [destruct_nil, destruct_cons] at this,
exact false.elim this },
{ rw [destruct_nil, destruct_cons] at this,
exact false.elim this },
{ rw [destruct_cons, destruct_cons] at this,
rw [head_cons, head_cons, tail_cons, tail_cons],
cases this with h1 h2,
constructor, rw h1, exact h2 }
end
end,
exact ⟨s₁, s₂, rfl, rfl, r⟩
end
end bisim
theorem coinduction : ∀ {s₁ s₂ : seq α}, head s₁ = head s₂ →
(∀ (β : Type u) (fr : seq α → β),
fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂)) → s₁ = s₂
| ⟨f₁, a₁⟩ ⟨f₂, a₂⟩ hh ht :=
subtype.eq (stream.coinduction hh (λ β fr, ht β (λ s, fr s.1)))
theorem coinduction2 (s) (f g : seq α → seq β)
(H : ∀ s, bisim_o (λ (s1 s2 : seq β), ∃ (s : seq α), s1 = f s ∧ s2 = g s)
(destruct (f s)) (destruct (g s)))
: f s = g s :=
begin
refine eq_of_bisim (λ s1 s2, ∃ s, s1 = f s ∧ s2 = g s) _ ⟨s, rfl, rfl⟩,
intros s1 s2 h, rcases h with ⟨s, h1, h2⟩,
rw [h1, h2], apply H
end
/-- Embed a list as a sequence -/
def of_list (l : list α) : seq α :=
⟨list.nth l, λ n h, begin
rw list.nth_eq_none_iff at h ⊢,
exact h.trans (nat.le_succ n)
end⟩
instance coe_list : has_coe (list α) (seq α) := ⟨of_list⟩
@[simp] theorem of_list_nil : of_list [] = (nil : seq α) := rfl
@[simp] theorem of_list_nth (l : list α) (n : ℕ) : (of_list l).nth n = l.nth n := rfl
@[simp] theorem of_list_cons (a : α) (l : list α) : of_list (a :: l) = cons a (of_list l) :=
by ext1 (_|n); refl
/-- Embed an infinite stream as a sequence -/
def of_stream (s : stream α) : seq α :=
⟨s.map some, λ n h, by contradiction⟩
instance coe_stream : has_coe (stream α) (seq α) := ⟨of_stream⟩
/-- Embed a `lazy_list α` as a sequence. Note that even though this
is non-meta, it will produce infinite sequences if used with
cyclic `lazy_list`s created by meta constructions. -/
def of_lazy_list : lazy_list α → seq α :=
corec (λ l, match l with
| lazy_list.nil := none
| lazy_list.cons a l' := some (a, l' ())
end)
instance coe_lazy_list : has_coe (lazy_list α) (seq α) := ⟨of_lazy_list⟩
/-- Translate a sequence into a `lazy_list`. Since `lazy_list` and `list`
are isomorphic as non-meta types, this function is necessarily meta. -/
meta def to_lazy_list : seq α → lazy_list α | s :=
match destruct s with
| none := lazy_list.nil
| some (a, s') := lazy_list.cons a (to_lazy_list s')
end
/-- Translate a sequence to a list. This function will run forever if
run on an infinite sequence. -/
meta def force_to_list (s : seq α) : list α := (to_lazy_list s).to_list
/-- The sequence of natural numbers some 0, some 1, ... -/
def nats : seq ℕ := stream.nats
@[simp]
lemma nats_nth (n : ℕ) : nats.nth n = some n := rfl
/-- Append two sequences. If `s₁` is infinite, then `s₁ ++ s₂ = s₁`,
otherwise it puts `s₂` at the location of the `nil` in `s₁`. -/
def append (s₁ s₂ : seq α) : seq α :=
@corec α (seq α × seq α) (λ ⟨s₁, s₂⟩,
match destruct s₁ with
| none := omap (λ s₂, (nil, s₂)) (destruct s₂)
| some (a, s₁') := some (a, s₁', s₂)
end) (s₁, s₂)
/-- Map a function over a sequence. -/
def map (f : α → β) : seq α → seq β | ⟨s, al⟩ :=
⟨s.map (option.map f),
λ n, begin
dsimp [stream.map, stream.nth],
induction e : s n; intro,
{ rw al e, assumption }, { contradiction }
end⟩
/-- Flatten a sequence of sequences. (It is required that the
sequences be nonempty to ensure productivity; in the case
of an infinite sequence of `nil`, the first element is never
generated.) -/
def join : seq (seq1 α) → seq α :=
corec (λ S, match destruct S with
| none := none
| some ((a, s), S') := some (a, match destruct s with
| none := S'
| some s' := cons s' S'
end)
end)
/-- Remove the first `n` elements from the sequence. -/
def drop (s : seq α) : ℕ → seq α
| 0 := s
| (n+1) := tail (drop n)
attribute [simp] drop
/-- Take the first `n` elements of the sequence (producing a list) -/
def take : ℕ → seq α → list α
| 0 s := []
| (n+1) s := match destruct s with
| none := []
| some (x, r) := list.cons x (take n r)
end
/-- Split a sequence at `n`, producing a finite initial segment
and an infinite tail. -/
def split_at : ℕ → seq α → list α × seq α
| 0 s := ([], s)
| (n+1) s := match destruct s with
| none := ([], nil)
| some (x, s') := let (l, r) := split_at n s' in (list.cons x l, r)
end
section zip_with
/-- Combine two sequences with a function -/
def zip_with (f : α → β → γ) : seq α → seq β → seq γ
| ⟨f₁, a₁⟩ ⟨f₂, a₂⟩ := ⟨λ n,
match f₁ n, f₂ n with
| some a, some b := some (f a b)
| _, _ := none
end,
λ n, begin
induction h1 : f₁ n,
{ intro H, simp only [(a₁ h1)], refl },
induction h2 : f₂ n; dsimp [seq.zip_with._match_1]; intro H,
{ rw (a₂ h2), cases f₁ (n + 1); refl },
{ rw [h1, h2] at H, contradiction }
end⟩
variables {s : seq α} {s' : seq β} {n : ℕ}
lemma zip_with_nth_some {a : α} {b : β} (s_nth_eq_some : s.nth n = some a)
(s_nth_eq_some' : s'.nth n = some b) (f : α → β → γ) :
(zip_with f s s').nth n = some (f a b) :=
begin
cases s with st,
have : st n = some a, from s_nth_eq_some,
cases s' with st',
have : st' n = some b, from s_nth_eq_some',
simp only [zip_with, seq.nth, *]
end
lemma zip_with_nth_none (s_nth_eq_none : s.nth n = none) (f : α → β → γ) :
(zip_with f s s').nth n = none :=
begin
cases s with st,
have : st n = none, from s_nth_eq_none,
cases s' with st',
cases st'_nth_eq : st' n;
simp only [zip_with, seq.nth, *]
end
lemma zip_with_nth_none' (s'_nth_eq_none : s'.nth n = none) (f : α → β → γ) :
(zip_with f s s').nth n = none :=
begin
cases s' with st',
have : st' n = none, from s'_nth_eq_none,
cases s with st,
cases st_nth_eq : st n;
simp only [zip_with, seq.nth, *]
end
lemma nth_zip_with (f : α → β → γ) (s : seq α) (t : seq β) (n : ℕ) :
nth (zip_with f s t) n = option.bind (nth s n) (λ x, option.map (f x) (nth t n)) :=
begin
cases hx : nth s n with x,
{ rw [zip_with_nth_none hx, option.none_bind'] },
cases hy : nth t n with y,
{ rw [zip_with_nth_none' hy, option.some_bind', option.map_none'] },
{ rw [zip_with_nth_some hx hy, option.some_bind', option.map_some'] }
end
end zip_with
/-- Pair two sequences into a sequence of pairs -/
def zip : seq α → seq β → seq (α × β) := zip_with prod.mk
lemma nth_zip (s : seq α) (t : seq β) (n : ℕ) :
nth (zip s t) n = option.bind (nth s n) (λ x, option.map (prod.mk x) (nth t n)) :=
nth_zip_with _ _ _ _
/-- Separate a sequence of pairs into two sequences -/
def unzip (s : seq (α × β)) : seq α × seq β := (map prod.fst s, map prod.snd s)
/-- Enumerate a sequence by tagging each element with its index. -/
def enum (s : seq α) : seq (ℕ × α) := seq.zip nats s
@[simp] lemma nth_enum (s : seq α) (n : ℕ) : nth (enum s) n = option.map (prod.mk n) (nth s n) :=
nth_zip _ _ _
@[simp] lemma enum_nil : enum (nil : seq α) = nil := rfl
/-- Convert a sequence which is known to terminate into a list -/
def to_list (s : seq α) (h : s.terminates) : list α :=
take (nat.find h) s
/-- Convert a sequence which is known not to terminate into a stream -/
def to_stream (s : seq α) (h : ¬ s.terminates) : stream α :=
λ n, option.get $ not_terminates_iff.1 h n
/-- Convert a sequence into either a list or a stream depending on whether
it is finite or infinite. (Without decidability of the infiniteness predicate,
this is not constructively possible.) -/
def to_list_or_stream (s : seq α) [decidable s.terminates] : list α ⊕ stream α :=
if h : s.terminates
then sum.inl (to_list s h)
else sum.inr (to_stream s h)
@[simp] theorem nil_append (s : seq α) : append nil s = s :=
begin
apply coinduction2, intro s,
dsimp [append], rw [corec_eq],
dsimp [append], apply rec_on s _ _,
{ trivial },
{ intros x s,
rw [destruct_cons], dsimp,
exact ⟨rfl, s, rfl, rfl⟩ }
end
@[simp] theorem cons_append (a : α) (s t) : append (cons a s) t = cons a (append s t) :=
destruct_eq_cons $ begin
dsimp [append], rw [corec_eq],
dsimp [append], rw [destruct_cons],
dsimp [append], refl
end
@[simp] theorem append_nil (s : seq α) : append s nil = s :=
begin
apply coinduction2 s, intro s,
apply rec_on s _ _,
{ trivial },
{ intros x s,
rw [cons_append, destruct_cons, destruct_cons], dsimp,
exact ⟨rfl, s, rfl, rfl⟩ }
end
@[simp] theorem append_assoc (s t u : seq α) :
append (append s t) u = append s (append t u) :=
begin
apply eq_of_bisim (λ s1 s2, ∃ s t u,
s1 = append (append s t) u ∧ s2 = append s (append t u)),
{ intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, t, u, rfl, rfl⟩ := begin
apply rec_on s; simp,
{ apply rec_on t; simp,
{ apply rec_on u; simp,
{ intros x u, refine ⟨nil, nil, u, _, _⟩; simp } },
{ intros x t, refine ⟨nil, t, u, _, _⟩; simp } },
{ intros x s, exact ⟨s, t, u, rfl, rfl⟩ }
end end },
{ exact ⟨s, t, u, rfl, rfl⟩ }
end
@[simp] theorem map_nil (f : α → β) : map f nil = nil := rfl
@[simp] theorem map_cons (f : α → β) (a) : ∀ s, map f (cons a s) = cons (f a) (map f s)
| ⟨s, al⟩ := by apply subtype.eq; dsimp [cons, map]; rw stream.map_cons; refl
@[simp] theorem map_id : ∀ (s : seq α), map id s = s
| ⟨s, al⟩ := begin
apply subtype.eq; dsimp [map],
rw [option.map_id, stream.map_id]; refl
end
@[simp] theorem map_tail (f : α → β) : ∀ s, map f (tail s) = tail (map f s)
| ⟨s, al⟩ := by apply subtype.eq; dsimp [tail, map]; rw stream.map_tail; refl
theorem map_comp (f : α → β) (g : β → γ) : ∀ (s : seq α), map (g ∘ f) s = map g (map f s)
| ⟨s, al⟩ := begin
apply subtype.eq; dsimp [map],
rw stream.map_map,
apply congr_arg (λ f : _ → option γ, stream.map f s),
ext ⟨⟩; refl
end
@[simp] theorem map_append (f : α → β) (s t) : map f (append s t) = append (map f s) (map f t) :=
begin
apply eq_of_bisim (λ s1 s2, ∃ s t,
s1 = map f (append s t) ∧ s2 = append (map f s) (map f t)) _ ⟨s, t, rfl, rfl⟩,
intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, t, rfl, rfl⟩ := begin
apply rec_on s; simp,
{ apply rec_on t; simp,
{ intros x t, refine ⟨nil, t, _, _⟩; simp } },
{ intros x s, refine ⟨s, t, rfl, rfl⟩ }
end end
end
@[simp] theorem map_nth (f : α → β) : ∀ s n, nth (map f s) n = (nth s n).map f
| ⟨s, al⟩ n := rfl
instance : functor seq := {map := @map}
instance : is_lawful_functor seq :=
{ id_map := @map_id, comp_map := @map_comp }
@[simp] theorem join_nil : join nil = (nil : seq α) := destruct_eq_nil rfl
@[simp] theorem join_cons_nil (a : α) (S) :
join (cons (a, nil) S) = cons a (join S) :=
destruct_eq_cons $ by simp [join]
@[simp] theorem join_cons_cons (a b : α) (s S) :
join (cons (a, cons b s) S) = cons a (join (cons (b, s) S)) :=
destruct_eq_cons $ by simp [join]
@[simp, priority 990] theorem join_cons (a : α) (s S) :
join (cons (a, s) S) = cons a (append s (join S)) :=
begin
apply eq_of_bisim (λ s1 s2, s1 = s2 ∨
∃ a s S, s1 = join (cons (a, s) S) ∧
s2 = cons a (append s (join S))) _ (or.inr ⟨a, s, S, rfl, rfl⟩),
intros s1 s2 h,
exact match s1, s2, h with
| _, _, (or.inl $ eq.refl s) := begin
apply rec_on s, { trivial },
{ intros x s, rw [destruct_cons], exact ⟨rfl, or.inl rfl⟩ }
end
| ._, ._, (or.inr ⟨a, s, S, rfl, rfl⟩) := begin
apply rec_on s,
{ simp },
{ intros x s, simp, refine or.inr ⟨x, s, S, rfl, rfl⟩ }
end
end
end
@[simp] theorem join_append (S T : seq (seq1 α)) :
join (append S T) = append (join S) (join T) :=
begin
apply eq_of_bisim (λ s1 s2, ∃ s S T,
s1 = append s (join (append S T)) ∧
s2 = append s (append (join S) (join T))),
{ intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, S, T, rfl, rfl⟩ := begin
apply rec_on s; simp,
{ apply rec_on S; simp,
{ apply rec_on T, { simp },
{ intros s T, cases s with a s; simp,
refine ⟨s, nil, T, _, _⟩; simp } },
{ intros s S, cases s with a s; simp,
exact ⟨s, S, T, rfl, rfl⟩ } },
{ intros x s, exact ⟨s, S, T, rfl, rfl⟩ }
end end },
{ refine ⟨nil, S, T, _, _⟩; simp }
end
@[simp] theorem of_stream_cons (a : α) (s) :
of_stream (a :: s) = cons a (of_stream s) :=
by apply subtype.eq; simp [of_stream, cons]; rw stream.map_cons
@[simp] theorem of_list_append (l l' : list α) :
of_list (l ++ l') = append (of_list l) (of_list l') :=
by induction l; simp [*]
@[simp] theorem of_stream_append (l : list α) (s : stream α) :
of_stream (l ++ₛ s) = append (of_list l) (of_stream s) :=
by induction l; simp [*, stream.nil_append_stream, stream.cons_append_stream]
/-- Convert a sequence into a list, embedded in a computation to allow for
the possibility of infinite sequences (in which case the computation
never returns anything). -/
def to_list' {α} (s : seq α) : computation (list α) :=
@computation.corec (list α) (list α × seq α) (λ ⟨l, s⟩,
match destruct s with
| none := sum.inl l.reverse
| some (a, s') := sum.inr (a::l, s')
end) ([], s)
theorem dropn_add (s : seq α) (m) : ∀ n, drop s (m + n) = drop (drop s m) n
| 0 := rfl
| (n+1) := congr_arg tail (dropn_add n)
theorem dropn_tail (s : seq α) (n) : drop (tail s) n = drop s (n + 1) :=
by rw add_comm; symmetry; apply dropn_add
@[simp] theorem head_dropn (s : seq α) (n) : head (drop s n) = nth s n :=
begin
induction n with n IH generalizing s, { refl },
rw [nat.succ_eq_add_one, ←nth_tail, ←dropn_tail], apply IH
end
theorem mem_map (f : α → β) {a : α} : ∀ {s : seq α}, a ∈ s → f a ∈ map f s
| ⟨g, al⟩ := stream.mem_map (option.map f)
theorem exists_of_mem_map {f} {b : β} : ∀ {s : seq α}, b ∈ map f s → ∃ a, a ∈ s ∧ f a = b
| ⟨g, al⟩ h := let ⟨o, om, oe⟩ := stream.exists_of_mem_map h in
by cases o with a; injection oe with h'; exact ⟨a, om, h'⟩
theorem of_mem_append {s₁ s₂ : seq α} {a : α} (h : a ∈ append s₁ s₂) : a ∈ s₁ ∨ a ∈ s₂ :=
begin
have := h, revert this,
generalize e : append s₁ s₂ = ss, intro h, revert s₁,
apply mem_rec_on h _,
intros b s' o s₁,
apply s₁.rec_on _ (λ c t₁, _); intros m e;
have := congr_arg destruct e,
{ apply or.inr, simpa using m },
{ cases (show a = c ∨ a ∈ append t₁ s₂, by simpa using m) with e' m,
{ rw e', exact or.inl (mem_cons _ _) },
{ cases (show c = b ∧ append t₁ s₂ = s', by simpa) with i1 i2,
cases o with e' IH,
{ simp [i1, e'] },
{ exact or.imp_left (mem_cons_of_mem _) (IH m i2) } } }
end
theorem mem_append_left {s₁ s₂ : seq α} {a : α} (h : a ∈ s₁) : a ∈ append s₁ s₂ :=
by apply mem_rec_on h; intros; simp [*]
@[simp] lemma enum_cons (s : seq α) (x : α) :
enum (cons x s) = cons (0, x) (map (prod.map nat.succ id) (enum s)) :=
begin
ext ⟨n⟩ : 1,
{ simp, },
{ simp only [nth_enum, nth_cons_succ, map_nth, option.map_map],
congr }
end
end seq
namespace seq1
variables {α : Type u} {β : Type v} {γ : Type w}
open seq
/-- Convert a `seq1` to a sequence. -/
def to_seq : seq1 α → seq α
| (a, s) := cons a s
instance coe_seq : has_coe (seq1 α) (seq α) := ⟨to_seq⟩
/-- Map a function on a `seq1` -/
def map (f : α → β) : seq1 α → seq1 β
| (a, s) := (f a, seq.map f s)
theorem map_id : ∀ (s : seq1 α), map id s = s | ⟨a, s⟩ := by simp [map]
/-- Flatten a nonempty sequence of nonempty sequences -/
def join : seq1 (seq1 α) → seq1 α
| ((a, s), S) := match destruct s with
| none := (a, seq.join S)
| some s' := (a, seq.join (cons s' S))
end
@[simp] theorem join_nil (a : α) (S) : join ((a, nil), S) = (a, seq.join S) := rfl
@[simp] theorem join_cons (a b : α) (s S) :
join ((a, cons b s), S) = (a, seq.join (cons (b, s) S)) :=
by dsimp [join]; rw [destruct_cons]; refl
/-- The `return` operator for the `seq1` monad,
which produces a singleton sequence. -/
def ret (a : α) : seq1 α := (a, nil)
instance [inhabited α] : inhabited (seq1 α) := ⟨ret default⟩
/-- The `bind` operator for the `seq1` monad,
which maps `f` on each element of `s` and appends the results together.
(Not all of `s` may be evaluated, because the first few elements of `s`
may already produce an infinite result.) -/
def bind (s : seq1 α) (f : α → seq1 β) : seq1 β :=
join (map f s)
@[simp] theorem join_map_ret (s : seq α) : seq.join (seq.map ret s) = s :=
by apply coinduction2 s; intro s; apply rec_on s; simp [ret]
@[simp] theorem bind_ret (f : α → β) : ∀ s, bind s (ret ∘ f) = map f s
| ⟨a, s⟩ := begin
dsimp [bind, map], change (λ x, ret (f x)) with (ret ∘ f),
rw [map_comp], simp [function.comp, ret]
end
@[simp] theorem ret_bind (a : α) (f : α → seq1 β) : bind (ret a) f = f a :=
begin
simp [ret, bind, map],
cases f a with a s,
apply rec_on s; intros; simp
end
@[simp] theorem map_join' (f : α → β) (S) :
seq.map f (seq.join S) = seq.join (seq.map (map f) S) :=
begin
apply eq_of_bisim (λ s1 s2,
∃ s S, s1 = append s (seq.map f (seq.join S)) ∧
s2 = append s (seq.join (seq.map (map f) S))),
{ intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, S, rfl, rfl⟩ := begin
apply rec_on s; simp,
{ apply rec_on S; simp,
{ intros x S, cases x with a s; simp [map],
exact ⟨_, _, rfl, rfl⟩ } },
{ intros x s, refine ⟨s, S, rfl, rfl⟩ }
end end },
{ refine ⟨nil, S, _, _⟩; simp }
end
@[simp] theorem map_join (f : α → β) : ∀ S, map f (join S) = join (map (map f) S)
| ((a, s), S) := by apply rec_on s; intros; simp [map]
@[simp] theorem join_join (SS : seq (seq1 (seq1 α))) :
seq.join (seq.join SS) = seq.join (seq.map join SS) :=
begin
apply eq_of_bisim (λ s1 s2,
∃ s SS, s1 = seq.append s (seq.join (seq.join SS)) ∧
s2 = seq.append s (seq.join (seq.map join SS))),
{ intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, SS, rfl, rfl⟩ := begin
apply rec_on s; simp,
{ apply rec_on SS; simp,
{ intros S SS, cases S with s S; cases s with x s; simp [map],
apply rec_on s; simp,
{ exact ⟨_, _, rfl, rfl⟩ },
{ intros x s,
refine ⟨cons x (append s (seq.join S)), SS, _, _⟩; simp } } },
{ intros x s, exact ⟨s, SS, rfl, rfl⟩ }
end end },
{ refine ⟨nil, SS, _, _⟩; simp }
end
@[simp] theorem bind_assoc (s : seq1 α) (f : α → seq1 β) (g : β → seq1 γ) :
bind (bind s f) g = bind s (λ (x : α), bind (f x) g) :=
begin
cases s with a s,
simp [bind, map],
rw [←map_comp],
change (λ x, join (map g (f x))) with (join ∘ ((map g) ∘ f)),
rw [map_comp _ join],
generalize : seq.map (map g ∘ f) s = SS,
rcases map g (f a) with ⟨⟨a, s⟩, S⟩,
apply rec_on s; intros; apply rec_on S; intros; simp,
{ cases x with x t, apply rec_on t; intros; simp },
{ cases x_1 with y t; simp }
end
instance : monad seq1 :=
{ map := @map,
pure := @ret,
bind := @bind }
instance : is_lawful_monad seq1 :=
{ id_map := @map_id,
bind_pure_comp_eq_map := @bind_ret,
pure_bind := @ret_bind,
bind_assoc := @bind_assoc }
end seq1
|
3d8ef631653e1ecf4dd85a4d08195f0a7aba4194 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/order/default.lean | b565d70b2b21c78266ddc360582fb223a25bd15b | [
"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 | 59 | lean | import order.boolean_algebra
import order.complete_lattice
|
857ad9e15256954653979c0e355a76c73b83564d | 618003631150032a5676f229d13a079ac875ff77 | /test/nth_rewrite.lean | e48b12355c268e0a376182c0a6c34c8b98a23650 | [
"Apache-2.0"
] | permissive | awainverse/mathlib | 939b68c8486df66cfda64d327ad3d9165248c777 | ea76bd8f3ca0a8bf0a166a06a475b10663dec44a | refs/heads/master | 1,659,592,962,036 | 1,590,987,592,000 | 1,590,987,592,000 | 268,436,019 | 1 | 0 | Apache-2.0 | 1,590,990,500,000 | 1,590,990,500,000 | null | UTF-8 | Lean | false | false | 3,167 | lean | /-
Copyright (c) 2018 Keeley Hoek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Keeley Hoek, Scott Morrison
-/
import tactic.nth_rewrite
import init_.data.nat.lemmas
import data.vector
structure F :=
(a : ℕ)
(v : vector ℕ a)
(p : v.val = [])
example (f : F) : f.v.val = [] :=
begin
nth_rewrite 0 [f.p],
end
structure cat :=
(O : Type)
(H : O → O → Type)
(i : Π o : O, H o o)
(c : Π {X Y Z : O} (f : H X Y) (g : H Y Z), H X Z)
(li : Π {X Y : O} (f : H X Y), c (i X) f = f)
(ri : Π {X Y : O} (f : H X Y), c f (i Y) = f)
(a : Π {W X Y Z : O} (f : H W X) (g : H X Y) (h : H Y Z), c (c f g) h = c f (c g h))
open tactic
example (C : cat) (W X Y Z : C.O) (f : C.H X Y) (g : C.H W X) (h k : C.H Y Z) : C.c (C.c g f) h = C.c g (C.c f h) :=
begin
nth_rewrite 0 [C.a],
end
example (C : cat) (X Y : C.O) (f : C.H X Y) : C.c f (C.i Y) = f :=
begin
nth_rewrite 0 [C.ri],
end
-- The next two examples fail when using the kabstract backend.
axiom foo : [1] = [2]
example : [[1], [1], [1]] = [[1], [2], [1]] :=
begin
nth_rewrite_lhs 1 [foo],
end
axiom foo' : [6] = [7]
axiom bar' : [[5],[5]] = [[6],[6]]
example : [[7],[6]] = [[5],[5]] :=
begin
nth_rewrite_lhs 0 foo',
nth_rewrite_rhs 0 bar',
nth_rewrite_lhs 0 ←foo',
nth_rewrite_lhs 0 ←foo',
end
axiom wowzer : (3, 3) = (5, 2)
axiom kachow (n : ℕ) : (4, n) = (5, n)
axiom pchew (n : ℕ) : (n, 5) = (5, n)
axiom smash (n m : ℕ) : (n, m) = (1, 1)
example : [(3, 3), (5, 9), (5, 9)] = [(4, 5), (3, 6), (1, 1)] :=
begin
nth_rewrite_lhs 0 wowzer,
nth_rewrite_lhs 2 ←pchew,
nth_rewrite_rhs 0 pchew,
nth_rewrite_rhs 0 smash,
nth_rewrite_rhs 1 smash,
nth_rewrite_rhs 2 smash,
nth_rewrite_lhs 0 smash,
nth_rewrite_lhs 1 smash,
nth_rewrite_lhs 2 smash,
end
example (a b c : ℕ) : c + a + b = a + c + b :=
begin
nth_rewrite_rhs 1 add_comm,
end
-- With the `kabstract` backend, we only find one rewrite, even though there are obviously two.
-- The problem is that `(a + b) + c` matches directly, so the WHOLE THING gets replaced with a
-- metavariable, per the `kabstract` strategy. This is devastating to the search, since we cannot
-- see inside this metavariable.
-- I still think it's fixable. Because all applications have an order, I'm pretty sure we can't
-- miss any rewrites if we also look inside every thing we chunk-up into a metavariable as well.
-- In almost every case this will bring up no results (with the exception of situations like this
-- one), so there should be essentially no change in complexity.
example (x y : Prop) (h₁ : x ↔ y) (h₂ : x ↔ x ∧ x) : x ∧ x ↔ x :=
begin
nth_rewrite_rhs 1 [h₁] at h₂,
nth_rewrite_rhs 0 [← h₁] at h₂,
nth_rewrite_rhs 0 h₂,
end
example (x y : ℕ) (h₁ : x = y) (h₂ : x = x + x) : x + x = x :=
begin
nth_rewrite_rhs 1 [h₁] at h₂,
nth_rewrite_rhs 0 [← h₁] at h₂,
nth_rewrite_rhs 0 h₂,
end
example (x y z : ℕ) (h1 : x = y) (h2 : y = z) :
x + x + x + y = y + y + x + x :=
begin
nth_rewrite 2 [h1, h2], -- h2 is not used
nth_rewrite 2 [h2],
repeat { rw h1 },
repeat { rw h2 },
end
|
11df34493da33360c4eca09ae07a7a229ead3726 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /tests/lean/namelit.lean | 1068ff04fb375b355849648954931a53f3772629 | [
"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 | 270 | lean | new_frontend
#check `foo
#check `foo.bla
#check `«foo bla»
#check `«foo bla».«hello world»
#check `«foo bla».boo.«hello world»
#check `foo.«hello»
macro dummy1 : term => `(`hello)
macro dummy2 : term => `(`hello.«world !!!»)
#check dummy1
#check dummy2
|
322b728a2af078ea99c71043b293b062bff1b74d | af6139dd14451ab8f69cf181cf3a20f22bd699be | /library/init/meta/expr.lean | d18b4604414fe633dbc92bbe282ce2133a84e64b | [
"Apache-2.0"
] | permissive | gitter-badger/lean-1 | 1cca01252d3113faa45681b6a00e1b5e3a0f6203 | 5c7ade4ee4f1cdf5028eabc5db949479d6737c85 | refs/heads/master | 1,611,425,383,521 | 1,487,871,140,000 | 1,487,871,140,000 | 82,995,612 | 0 | 0 | null | 1,487,905,618,000 | 1,487,905,618,000 | null | UTF-8 | Lean | false | false | 10,592 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta.level
structure pos :=
(line : nat)
(column : nat)
instance : decidable_eq pos
| ⟨l₁, c₁⟩ ⟨l₂, c₂⟩ := if h₁ : l₁ = l₂ then
if h₂ : c₁ = c₂ then is_true (eq.rec_on h₁ (eq.rec_on h₂ rfl))
else is_false (λ contra, pos.no_confusion contra (λ e₁ e₂, absurd e₂ h₂))
else is_false (λ contra, pos.no_confusion contra (λ e₁ e₂, absurd e₁ h₁))
inductive binder_info
| default | implicit | strict_implicit | inst_implicit | other
instance : has_to_string binder_info :=
⟨λ bi, match bi with
| binder_info.default := "default"
| binder_info.implicit := "implicit"
| binder_info.strict_implicit := "strict_implicit"
| binder_info.inst_implicit := "inst_implicit"
| binder_info.other := "other"
end⟩
meta constant macro_def : Type
/- Reflect a C++ expr object. The VM replaces it with the C++ implementation. -/
meta inductive expr
| var : unsigned → expr
| sort : level → expr
| const : name → list level → expr
| mvar : name → expr → expr
| local_const : name → name → binder_info → expr → expr
| app : expr → expr → expr
| lam : name → binder_info → expr → expr → expr
| pi : name → binder_info → expr → expr → expr
| elet : name → expr → expr → expr → expr
| macro : macro_def → ∀ n : unsigned, (fin (unsigned.to_nat n) → expr) → expr
meta instance : inhabited expr :=
⟨expr.sort level.zero⟩
meta constant expr.mk_macro (d : macro_def) : list expr → expr
meta constant expr.macro_def_name (d : macro_def) : name
meta def expr.mk_var (n : nat) : expr :=
expr.var (unsigned.of_nat n)
/- Choice macros are used to implement overloading. -/
meta constant expr.is_choice_macro : expr → bool
-- Compares expressions, including binder names.
meta constant expr.has_decidable_eq : decidable_eq expr
attribute [instance] expr.has_decidable_eq
-- Compares expressions while ignoring binder names.
meta constant expr.alpha_eqv : expr → expr → bool
notation a ` =ₐ `:50 b:50 := expr.alpha_eqv a b = bool.tt
protected meta constant expr.to_string : expr → string
meta instance : has_to_string expr :=
has_to_string.mk expr.to_string
/- Coercion for letting users write (f a) instead of (expr.app f a) -/
meta instance : has_coe_to_fun expr :=
{ F := λ e, expr → expr, coe := λ e, expr.app e }
meta constant expr.hash : expr → nat
-- Compares expressions, ignoring binder names, and sorting by hash.
meta constant expr.lt : expr → expr → bool
-- Compares expressions, ignoring binder names.
meta constant expr.lex_lt : expr → expr → bool
-- Compares expressions, ignoring binder names, and sorting by hash.
meta def expr.cmp (a b : expr) : ordering :=
if expr.lt a b then ordering.lt
else if a =ₐ b then ordering.eq
else ordering.gt
meta constant expr.fold {α : Type} : expr → α → (expr → nat → α → α) → α
meta constant expr.replace : expr → (expr → nat → option expr) → expr
meta constant expr.abstract_local : expr → name → expr
meta constant expr.abstract_locals : expr → list name → expr
meta def expr.abstract : expr → expr → expr
| e (expr.local_const n m bi t) := e^.abstract_local n
| e _ := e
meta constant expr.instantiate_univ_params : expr → list (name × level) → expr
meta constant expr.instantiate_var : expr → expr → expr
meta constant expr.instantiate_vars : expr → list expr → expr
meta constant expr.has_var : expr → bool
meta constant expr.has_var_idx : expr → nat → bool
meta constant expr.has_local : expr → bool
meta constant expr.has_meta_var : expr → bool
meta constant expr.lift_vars : expr → nat → nat → expr
meta constant expr.lower_vars : expr → nat → nat → expr
/- (copy_pos_info src tgt) copy position information from src to tgt. -/
meta constant expr.copy_pos_info : expr → expr → expr
meta constant expr.is_internal_cnstr : expr → option unsigned
meta constant expr.get_nat_value : expr → option nat
meta constant expr.collect_univ_params : expr → list name
/-- `occurs e t` returns `tt` iff `e` occurs in `t` -/
meta constant expr.occurs : expr → expr → bool
namespace expr
open decidable
-- Compares expressions, ignoring binder names, and sorting by hash.
meta instance : has_ordering expr :=
⟨ expr.cmp ⟩
meta def mk_true : expr :=
const `true []
meta def mk_false : expr :=
const `false []
/-- Returns the sorry macro with the given type. -/
meta constant mk_sorry (type : expr) : expr
/-- Checks whether e is sorry, and returns its type. -/
meta constant is_sorry (e : expr) : option expr
meta def is_var : expr → bool
| (var _) := tt
| _ := ff
meta def app_of_list : expr → list expr → expr
| f [] := f
| f (p::ps) := app_of_list (f p) ps
meta def is_app : expr → bool
| (app f a) := tt
| e := ff
meta def app_fn : expr → expr
| (app f a) := f
| a := a
meta def app_arg : expr → expr
| (app f a) := a
| a := a
meta def get_app_fn : expr → expr
| (app f a) := get_app_fn f
| a := a
meta def get_app_num_args : expr → nat
| (app f a) := get_app_num_args f + 1
| e := 0
meta def get_app_args_aux : list expr → expr → list expr
| r (app f a) := get_app_args_aux (a::r) f
| r e := r
meta def get_app_args : expr → list expr :=
get_app_args_aux []
meta def mk_app : expr → list expr → expr
| e [] := e
| e (x::xs) := mk_app (e x) xs
meta def ith_arg_aux : expr → nat → expr
| (app f a) 0 := a
| (app f a) (n+1) := ith_arg_aux f n
| e _ := e
meta def ith_arg (e : expr) (i : nat) : expr :=
ith_arg_aux e (get_app_num_args e - i - 1)
meta def const_name : expr → name
| (const n ls) := n
| e := name.anonymous
meta def is_constant : expr → bool
| (const n ls) := tt
| e := ff
meta def is_local_constant : expr → bool
| (local_const n m bi t) := tt
| e := ff
meta def local_uniq_name : expr → name
| (local_const n m bi t) := n
| e := name.anonymous
meta def local_pp_name : expr → name
| (local_const x n bi t) := n
| e := name.anonymous
meta def local_type : expr → expr
| (local_const _ _ _ t) := t
| e := e
meta def is_constant_of : expr → name → bool
| (const n₁ ls) n₂ := n₁ = n₂
| e n := ff
meta def is_app_of (e : expr) (n : name) : bool :=
is_constant_of (get_app_fn e) n
meta def is_napp_of (e : expr) (c : name) (n : nat) : bool :=
is_app_of e c ∧ get_app_num_args e = n
meta def is_false : expr → bool
| ``(false) := tt
| _ := ff
meta def is_not : expr → option expr
| ``(not %%a) := some a
| ``(%%a → false) := some a
| e := none
meta def is_eq : expr → option (expr × expr)
| ``((%%a: %%α) = %%b) := some (a, b)
| _ := none
meta def is_ne : expr → option (expr × expr)
| ``((%%a: %%α) ≠ %%b) := some (a, b)
| _ := none
meta def is_bin_arith_app (e : expr) (op : name) : option (expr × expr) :=
if is_napp_of e op 4
then some (app_arg (app_fn e), app_arg e)
else none
meta def is_lt (e : expr) : option (expr × expr) :=
is_bin_arith_app e `lt
meta def is_gt (e : expr) : option (expr × expr) :=
is_bin_arith_app e `gt
meta def is_le (e : expr) : option (expr × expr) :=
is_bin_arith_app e `le
meta def is_ge (e : expr) : option (expr × expr) :=
is_bin_arith_app e `ge
meta def is_heq : expr → option (expr × expr × expr × expr)
| ``(@heq %%α %%a %%β %%b) := some (α, a, β, b)
| _ := none
meta def is_pi : expr → bool
| (pi _ _ _ _) := tt
| e := ff
meta def is_arrow : expr → bool
| (pi _ _ _ b) := bnot (has_var b)
| e := ff
meta def is_let : expr → bool
| (elet _ _ _ _) := tt
| e := ff
meta def binding_name : expr → name
| (pi n _ _ _) := n
| (lam n _ _ _) := n
| e := name.anonymous
meta def binding_info : expr → binder_info
| (pi _ bi _ _) := bi
| (lam _ bi _ _) := bi
| e := binder_info.default
meta def binding_domain : expr → expr
| (pi _ _ d _) := d
| (lam _ _ d _) := d
| e := e
meta def binding_body : expr → expr
| (pi _ _ _ b) := b
| (lam _ _ _ b) := b
| e := e
meta def prop : expr := expr.sort level.zero
meta def imp (a b : expr) : expr :=
pi `a binder_info.default a b
meta def and_ (a b : expr) : expr :=
app (app (const ``and []) a) b
meta def not_ (a : expr) : expr :=
app (const ``not []) a
meta def false_ : expr := const ``false []
meta def lambdas : list expr → expr → expr
| (local_const uniq pp info t :: es) f :=
lam pp info t (abstract_local (lambdas es f) uniq)
| _ f := f
meta def pis : list expr → expr → expr
| (local_const uniq pp info t :: es) f :=
pi pp info t (abstract_local (pis es f) uniq)
| _ f := f
open format
private meta def p := λ xs, paren (format.join (list.intersperse " " xs))
private meta def macro_args_to_list_aux (n : unsigned) (args : fin (unsigned.to_nat n) → expr) : Π (i : nat), i ≤ n^.to_nat → list expr
| 0 _ := []
| (i+1) h := args ⟨i, h⟩ :: macro_args_to_list_aux i (nat.le_trans (nat.le_succ _) h)
meta def macro_args_to_list (n : unsigned) (args : fin (unsigned.to_nat n) → expr) : list expr :=
macro_args_to_list_aux n args n^.to_nat (nat.le_refl _)
meta def to_raw_fmt : expr → format
| (var n) := p ["var", to_fmt n^.to_nat]
| (sort l) := p ["sort", to_fmt l]
| (const n ls) := p ["const", to_fmt n, to_fmt ls]
| (mvar n t) := p ["mvar", to_fmt n, to_raw_fmt t]
| (local_const n m bi t) := p ["local_const", to_fmt n, to_fmt m, to_raw_fmt t]
| (app e f) := p ["app", to_raw_fmt e, to_raw_fmt f]
| (lam n bi e t) := p ["lam", to_fmt n, to_string bi, to_raw_fmt e, to_raw_fmt t]
| (pi n bi e t) := p ["pi", to_fmt n, to_string bi, to_raw_fmt e, to_raw_fmt t]
| (elet n g e f) := p ["elet", to_fmt n, to_raw_fmt g, to_raw_fmt e, to_raw_fmt f]
| (macro d n args) := sbracket (format.join (list.intersperse " " ("macro" :: to_fmt (macro_def_name d) :: list.map to_raw_fmt (macro_args_to_list n args))))
meta def mfold {α : Type} {m : Type → Type} [monad m] (e : expr) (a : α) (fn : expr → nat → α → m α) : m α :=
fold e (return a) (λ e n a, a >>= fn e n)
end expr
|
5e66f531d8b8f35e9fe6091825e2462af8a185db | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /stage0/src/Init/Lean/Compiler/IR/LiveVars.lean | 915022935e9de4dab449e5749330dd141a624394 | [
"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 | 6,916 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Lean.Compiler.IR.Basic
import Init.Lean.Compiler.IR.FreeVars
import Init.Control.Reader
import Init.Control.Conditional
namespace Lean
namespace IR
/- Remark: in the paper "Counting Immutable Beans" the concepts of
free and live variables coincide because the paper does *not* consider
join points. For example, consider the function body `B`
```
let x := ctor_0;
jmp block_1 x
```
in a context where we have the join point `block_1` defined as
```
block_1 (x : obj) : obj :=
let z := ctor_0 x y;
ret z
``
The variable `y` is live in the function body `B` since it occurs in
`block_1` which is "invoked" by `B`.
-/
namespace IsLive
/-
We use `State Context` instead of `ReaderT Context Id` because we remove
non local joint points from `Context` whenever we visit them instead of
maintaining a set of visited non local join points.
Remark: we don't need to track local join points because we assume there is
no variable or join point shadowing in our IR.
-/
abbrev M := StateM LocalContext
@[inline] def visitVar (w : Index) (x : VarId) : M Bool := pure (HasIndex.visitVar w x)
@[inline] def visitJP (w : Index) (x : JoinPointId) : M Bool := pure (HasIndex.visitJP w x)
@[inline] def visitArg (w : Index) (a : Arg) : M Bool := pure (HasIndex.visitArg w a)
@[inline] def visitArgs (w : Index) (as : Array Arg) : M Bool := pure (HasIndex.visitArgs w as)
@[inline] def visitExpr (w : Index) (e : Expr) : M Bool := pure (HasIndex.visitExpr w e)
partial def visitFnBody (w : Index) : FnBody → M Bool
| FnBody.vdecl x _ v b => visitExpr w v <||> visitFnBody b
| FnBody.jdecl j ys v b => visitFnBody v <||> visitFnBody b
| FnBody.set x _ y b => visitVar w x <||> visitArg w y <||> visitFnBody b
| FnBody.uset x _ y b => visitVar w x <||> visitVar w y <||> visitFnBody b
| FnBody.sset x _ _ y _ b => visitVar w x <||> visitVar w y <||> visitFnBody b
| FnBody.setTag x _ b => visitVar w x <||> visitFnBody b
| FnBody.inc x _ _ _ b => visitVar w x <||> visitFnBody b
| FnBody.dec x _ _ _ b => visitVar w x <||> visitFnBody b
| FnBody.del x b => visitVar w x <||> visitFnBody b
| FnBody.mdata _ b => visitFnBody b
| FnBody.jmp j ys => visitArgs w ys <||> do {
ctx ← get;
match ctx.getJPBody j with
| some b =>
-- `j` is not a local join point since we assume we cannot shadow join point declarations.
-- Instead of marking the join points that we have already been visited, we permanently remove `j` from the context.
set (ctx.eraseJoinPointDecl j) *> visitFnBody b
| none =>
-- `j` must be a local join point. So do nothing since we have already visite its body.
pure false
}
| FnBody.ret x => visitArg w x
| FnBody.case _ x _ alts => visitVar w x <||> alts.anyM (fun alt => visitFnBody alt.body)
| FnBody.unreachable => pure false
end IsLive
/- Return true if `x` is live in the function body `b` in the context `ctx`.
Remark: the context only needs to contain all (free) join point declarations.
Recall that we say that a join point `j` is free in `b` if `b` contains
`FnBody.jmp j ys` and `j` is not local. -/
def FnBody.hasLiveVar (b : FnBody) (ctx : LocalContext) (x : VarId) : Bool :=
(IsLive.visitFnBody x.idx b).run' ctx
abbrev LiveVarSet := VarIdSet
abbrev JPLiveVarMap := RBMap JoinPointId LiveVarSet (fun j₁ j₂ => j₁.idx < j₂.idx)
instance LiveVarSet.inhabited : Inhabited LiveVarSet := ⟨{}⟩
def mkLiveVarSet (x : VarId) : LiveVarSet :=
RBTree.empty.insert x
namespace LiveVars
abbrev Collector := LiveVarSet → LiveVarSet
@[inline] private def skip : Collector := fun s => s
@[inline] private def collectVar (x : VarId) : Collector := fun s => s.insert x
private def collectArg : Arg → Collector
| Arg.var x => collectVar x
| irrelevant => skip
@[specialize] private def collectArray {α : Type} (as : Array α) (f : α → Collector) : Collector :=
fun s => as.foldl (fun s a => f a s) s
private def collectArgs (as : Array Arg) : Collector :=
collectArray as collectArg
private def accumulate (s' : LiveVarSet) : Collector :=
fun s => s'.fold (fun s x => s.insert x) s
private def collectJP (m : JPLiveVarMap) (j : JoinPointId) : Collector :=
match m.find? j with
| some xs => accumulate xs
| none => skip -- unreachable for well-formed code
private def bindVar (x : VarId) : Collector :=
fun s => s.erase x
private def bindParams (ps : Array Param) : Collector :=
fun s => ps.foldl (fun s p => s.erase p.x) s
def collectExpr : Expr → Collector
| Expr.ctor _ ys => collectArgs ys
| Expr.reset _ x => collectVar x
| Expr.reuse x _ _ ys => collectVar x ∘ collectArgs ys
| Expr.proj _ x => collectVar x
| Expr.uproj _ x => collectVar x
| Expr.sproj _ _ x => collectVar x
| Expr.fap _ ys => collectArgs ys
| Expr.pap _ ys => collectArgs ys
| Expr.ap x ys => collectVar x ∘ collectArgs ys
| Expr.box _ x => collectVar x
| Expr.unbox x => collectVar x
| Expr.lit v => skip
| Expr.isShared x => collectVar x
| Expr.isTaggedPtr x => collectVar x
partial def collectFnBody : FnBody → JPLiveVarMap → Collector
| FnBody.vdecl x _ v b, m => collectExpr v ∘ bindVar x ∘ collectFnBody b m
| FnBody.jdecl j ys v b, m =>
let jLiveVars := (bindParams ys ∘ collectFnBody v m) {};
let m := m.insert j jLiveVars;
collectFnBody b m
| FnBody.set x _ y b, m => collectVar x ∘ collectArg y ∘ collectFnBody b m
| FnBody.setTag x _ b, m => collectVar x ∘ collectFnBody b m
| FnBody.uset x _ y b, m => collectVar x ∘ collectVar y ∘ collectFnBody b m
| FnBody.sset x _ _ y _ b, m => collectVar x ∘ collectVar y ∘ collectFnBody b m
| FnBody.inc x _ _ _ b, m => collectVar x ∘ collectFnBody b m
| FnBody.dec x _ _ _ b, m => collectVar x ∘ collectFnBody b m
| FnBody.del x b, m => collectVar x ∘ collectFnBody b m
| FnBody.mdata _ b, m => collectFnBody b m
| FnBody.ret x, m => collectArg x
| FnBody.case _ x _ alts, m => collectVar x ∘ collectArray alts (fun alt => collectFnBody alt.body m)
| FnBody.unreachable, m => skip
| FnBody.jmp j xs, m => collectJP m j ∘ collectArgs xs
def updateJPLiveVarMap (j : JoinPointId) (ys : Array Param) (v : FnBody) (m : JPLiveVarMap) : JPLiveVarMap :=
let jLiveVars := (bindParams ys ∘ collectFnBody v m) {};
m.insert j jLiveVars
end LiveVars
def updateLiveVars (e : Expr) (v : LiveVarSet) : LiveVarSet :=
LiveVars.collectExpr e v
def collectLiveVars (b : FnBody) (m : JPLiveVarMap) (v : LiveVarSet := {}) : LiveVarSet :=
LiveVars.collectFnBody b m v
export LiveVars (updateJPLiveVarMap)
end IR
end Lean
|
11e8ee41f0b5075fa56644049bfe50b14323faed | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/category_theory/limits/shapes/products.lean | ffa7c3d21aed659e2dbc3b9ef80552ffca9f5a3f | [
"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 | 3,535 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.limits.limits
import category_theory.discrete_category
universes v u
open category_theory
namespace category_theory.limits
variables {β : Type v}
variables {C : Type u} [category.{v} C]
-- We don't need an analogue of `pair` (for binary products), `parallel_pair` (for equalizers),
-- or `(co)span`, since we already have `discrete.functor`.
abbreviation fan (f : β → C) := cone (discrete.functor f)
abbreviation cofan (f : β → C) := cocone (discrete.functor f)
def fan.mk {f : β → C} {P : C} (p : Π b, P ⟶ f b) : fan f :=
{ X := P,
π := { app := p } }
def cofan.mk {f : β → C} {P : C} (p : Π b, f b ⟶ P) : cofan f :=
{ X := P,
ι := { app := p } }
@[simp] lemma fan.mk_π_app {f : β → C} {P : C} (p : Π b, P ⟶ f b) (b : β) : (fan.mk p).π.app b = p b := rfl
@[simp] lemma cofan.mk_π_app {f : β → C} {P : C} (p : Π b, f b ⟶ P) (b : β) : (cofan.mk p).ι.app b = p b := rfl
/-- An abbreviation for `has_limit (discrete.functor f)`. -/
abbreviation has_product (f : β → C) := has_limit (discrete.functor f)
/-- An abbreviation for `has_colimit (discrete.functor f)`. -/
abbreviation has_coproduct (f : β → C) := has_colimit (discrete.functor f)
section
variables (C)
/-- An abbreviation for `has_limits_of_shape (discrete f)`. -/
abbreviation has_products_of_shape (β : Type v) := has_limits_of_shape.{v} (discrete β)
/-- An abbreviation for `has_colimits_of_shape (discrete f)`. -/
abbreviation has_coproducts_of_shape (β : Type v) := has_colimits_of_shape.{v} (discrete β)
end
/-- `pi_obj f` computes the product of a family of elements `f`. (It is defined as an abbreviation
for `limit (discrete.functor f)`, so for most facts about `pi_obj f`, you will just use general facts
about limits.) -/
abbreviation pi_obj (f : β → C) [has_product f] := limit (discrete.functor f)
/-- `sigma_obj f` computes the coproduct of a family of elements `f`. (It is defined as an abbreviation
for `colimit (discrete.functor f)`, so for most facts about `sigma_obj f`, you will just use general facts
about colimits.) -/
abbreviation sigma_obj (f : β → C) [has_coproduct f] := colimit (discrete.functor f)
notation `∏ ` f:20 := pi_obj f
notation `∐ ` f:20 := sigma_obj f
abbreviation pi.π (f : β → C) [has_product f] (b : β) : ∏ f ⟶ f b :=
limit.π (discrete.functor f) b
abbreviation sigma.ι (f : β → C) [has_coproduct f] (b : β) : f b ⟶ ∐ f :=
colimit.ι (discrete.functor f) b
abbreviation pi.lift {f : β → C} [has_product f] {P : C} (p : Π b, P ⟶ f b) : P ⟶ ∏ f :=
limit.lift _ (fan.mk p)
abbreviation sigma.desc {f : β → C} [has_coproduct f] {P : C} (p : Π b, f b ⟶ P) : ∐ f ⟶ P :=
colimit.desc _ (cofan.mk p)
abbreviation pi.map {f g : β → C} [has_products_of_shape β C]
(p : Π b, f b ⟶ g b) : ∏ f ⟶ ∏ g :=
lim.map (discrete.nat_trans p)
abbreviation sigma.map {f g : β → C} [has_coproducts_of_shape β C]
(p : Π b, f b ⟶ g b) : ∐ f ⟶ ∐ g :=
colim.map (discrete.nat_trans p)
variables (C)
class has_products :=
(has_limits_of_shape : Π (J : Type v), has_limits_of_shape (discrete J) C)
class has_coproducts :=
(has_colimits_of_shape : Π (J : Type v), has_colimits_of_shape (discrete J) C)
attribute [instance] has_products.has_limits_of_shape has_coproducts.has_colimits_of_shape
end category_theory.limits
|
0f902a4fa0ee40b449dac6a5c07d9e748903b585 | bdc27058d2df65f1c05b3dd4ff23a30af9332a2b | /src/euclid_props.lean | e366c52d8d4c359a9664b9b3dfdcd621e5cbbfd4 | [] | no_license | bakerjd99/leanteach2020 | 19e3dda4167f7bb8785fe0e2fe762a9c53a9214d | 2160909674f3aec475eabb51df73af7fa1d91c65 | refs/heads/master | 1,668,724,511,289 | 1,594,407,424,000 | 1,594,407,424,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,579 | lean | import .euclid
import tactic
-- Redo the local notation
--------------------------
local infix ` ≃ `:55 := congruent -- typed as \ equiv
local infix `⬝`:56 := Segment.mk -- typed as \ cdot
-- Lemma needed for Proposition 1
lemma hypothesis1_about_circles_radius (s : Segment) :
let c₁ : Circle := ⟨s.p1, s.p2⟩ in
let c₂ : Circle := ⟨s.p2, s.p1⟩ in
distance c₁.center c₂.center ≤ radius c₁ + radius c₂ :=
by simp [radius, radius_segment, distance_not_neg]
-- Another lemma needed for Proposition 1
lemma hypothesis2_about_circles_radius (s : Segment) :
let c₁ : Circle := ⟨s.p1, s.p2⟩ in
let c₂ : Circle := ⟨s.p2, s.p1⟩ in
abs (radius c₁ - radius c₂) ≤ distance c₁.center c₂.center :=
by simp [radius, radius_segment, distance_is_symm, distance_not_neg]
-- # Proposition 1
------------------
theorem construct_equilateral (a b : Point) :
∃ (c : Point),
let abc : Triangle := ⟨a, b, c⟩ in
is_equilateral abc :=
begin
set c₁ : Circle := ⟨a, b⟩,
set c₂ : Circle := ⟨b, a⟩,
have h₁ := hypothesis1_about_circles_radius (a⬝b),
have h₂ := hypothesis2_about_circles_radius (a⬝b),
set c := circles_intersect h₁ h₂,
use c,
simp only [],
have hp₁ := (circles_intersect' h₁ h₂).1,
have hp₂ := (circles_intersect' h₁ h₂).2,
set c := circles_intersect h₁ h₂,
fsplit; -- Cleaning up the context.
dsimp only [circumference, sides_of_triangle, radius_segment] at *,
{ rwa segment_symm},
{ transitivity,
apply cong_symm,
assumption,
conv_lhs {rw segment_symm},
conv_rhs {rw segment_symm},
assumption},
end
-- Lemma needed for proposition 2
lemma line_circle_intersect {a b : Point} (ne : a ≠ b) {C : Circle} :
circle_interior a C
→ ∃ x : Point, lies_on x (line_of_points a b ne)
∧ x ∈ circumference C
∧ between x a b := sorry
-- Use *have* for introducing new facts. Follow it up with a proof of
-- said fact.
-- have x_pos : x > 0, .....
-- Use *let* for introducing new terms (of a given type). Follow it up
-- with a definition of the term.
-- Ex: let x : ℕ := 5
-- Use *set* is similar to *let*, but it additionally replaces every term
-- in the context with the new definition.
-- Ex: set x : ℕ := 5, -> replace x with 5 everywhere
-- Lemma needed for Proposition 2
lemma equilateral_triangle_nonzero_sides {a b c : Point} :
a ≠ b
→ is_equilateral ⟨a, b, c⟩
→ b ≠ c ∧ c ≠ a :=
begin
set abc : Triangle := ⟨a, b, c⟩,
rintros ne_a_b ⟨h₁, h₂⟩,
set sides := sides_of_triangle abc,
change sides.fst with a⬝b at h₁ h₂,
change sides.snd.fst with b⬝c at h₁ h₂,
change sides.snd.snd with c⬝a at h₁ h₂,
split,
{ intros eq_b_c,
subst eq_b_c,
have eq_a_b : a = b := zero_segment h₁,
cc},
{ intros eq_c_a,
subst eq_c_a,
have eq_b_c : b = c := zero_segment h₂,
cc},
end
lemma radii_equal {c : Circle} {a b : Point} :
a ∈ circumference c
→ b ∈ circumference c
→ c.center⬝a ≃ c.center⬝b :=
begin
intros h₁ h₂,
transitivity,
apply cong_symm,
repeat {assumption},
end
-- # Proposition 2
------------------
theorem segment_copy {a b c : Point} :
a ≠ b
→ b ≠ c
→ ∃ (l : Point), (a⬝l) ≃ (b⬝c) :=
begin
intros ne_a_b ne_b_c,
choose d h using construct_equilateral a b,
set c₁ : Circle := ⟨b, c⟩,
have ne_d_b : d ≠ b,
{ symmetry,
apply (equilateral_triangle_nonzero_sides ne_a_b h).1},
have b_in_c₁ : circle_interior b c₁ := center_in_circle ne_b_c,
have db_intersect_c₁ := line_circle_intersect ne_d_b.symm b_in_c₁,
rcases db_intersect_c₁ with ⟨g, g_on_bd, g_on_c₁, bet_g_b_d⟩,
set c₂ : Circle := ⟨d, g⟩,
have ne_d_a : d ≠ a,
by apply (equilateral_triangle_nonzero_sides ne_a_b h).2,
have ne_d_g : d ≠ g,
{ rw [distance_pos, distance_is_symm, ←distance_between.1 bet_g_b_d],
have h₁ : distance b d > 0 := distance_pos.1 ne_d_b.symm,
have h₂ : distance g b ≥ 0 := distance_not_neg,
linarith},
have d_in_c₂ : circle_interior d c₂ := center_in_circle ne_d_g,
have c_on_c₁ : c ∈ circumference c₁ := radius_on_circumference _ _,
have a_in_c₂ : circle_interior a c₂,
{ dsimp only [circle_interior, radius, radius_segment],
rw [distance_is_symm d g, ← distance_between.1 bet_g_b_d],
rcases h with ⟨h₁, h₂⟩,
change (sides_of_triangle ⟨a, b, d⟩).fst with a⬝b at h₁ h₂,
change (sides_of_triangle ⟨a, b, d⟩).snd.fst with b⬝d at h₁ h₂,
change (sides_of_triangle ⟨a, b, d⟩).snd.snd with d⬝a at h₂ h₂,
have eq_ad_bd : distance d a = distance b d,
{ rw ← distance_congruent,
apply cong_symm,
assumption},
simp only [eq_ad_bd, lt_add_iff_pos_left],
have re := radii_equal g_on_c₁ c_on_c₁,
simp only [distance_congruent] at re,
rwa [distance_is_symm, re, ← distance_pos]},
have da_intersect_c₂ := line_circle_intersect ne_d_a.symm a_in_c₂,
rcases da_intersect_c₂ with ⟨l, l_on_ad, l_on_c₂, bet_l_a_d⟩,
have dl_eq_da_al : distance d l = distance d a + distance a l,
{ replace bet_l_a_d := between_symm bet_l_a_d,
rwa [distance_between.1 bet_l_a_d]},
have dg_eq_db_bg : distance d g = distance d b + distance b g,
{ replace bet_g_b_d := between_symm bet_g_b_d,
rwa [distance_between.1 bet_g_b_d]},
have g_on_c₂ : g ∈ circumference c₂ := radius_on_circumference _ _,
rcases h with ⟨h₁, h₂⟩,
set sides := sides_of_triangle ⟨a, b, d⟩,
change sides.fst with a⬝b at h₁ h₂,
change sides.snd.fst with b⬝d at h₁ h₂,
change sides.snd.snd with d⬝a at h₁ h₂,
use l,
rw distance_congruent,
calc distance a l = distance d l - distance d a :
by simp only [dl_eq_da_al, add_sub_cancel']
... = distance d l - distance b d : by rw distance_congruent.1 h₂
... = distance d g - distance b d : by rw distance_congruent.1
(radii_equal l_on_c₂ g_on_c₂)
... = distance d g - distance d b : by simp only [distance_is_symm]
... = distance b g : by simp only [dg_eq_db_bg, add_sub_cancel']
... = distance b c : by rw distance_congruent.1
(radii_equal g_on_c₁ c_on_c₁)
end
-- # Proposition 3
------------------
-- To cut off from the greater of two given unequal straight lines a
-- straight line equal to the less.
lemma prop3 (a b c c' : Point) :
a ≠ c
→ c ≠ c'
→ a ≠ b
→ length (c⬝c') ≤ length (a⬝b)
→ ∃ (e : Point), length (a⬝e) = length (c⬝c') :=
begin
intros ne_a_c ne_c_c' ne_a_b le_cc'_ab,
choose d eq_ad_cc' using segment_copy ne_a_c ne_c_c',
set c₁ : Circle := ⟨a, d⟩,
have ne_a_d : a ≠ d,
{ intros eq_a_d,
subst eq_a_d,
have eq_c_c' : c = c' := zero_segment (cong_symm _ _ eq_ad_cc'),
cc},
have a_in_c₁ : circle_interior a c₁ := center_in_circle ne_a_d,
choose e h using line_circle_intersect ne_a_b a_in_c₁,
rcases h with ⟨e_on_ab, e_on_c₁, bet_e_a_b⟩,
use e,
dsimp only [length],
have d_on_c₁ : d ∈ circumference c₁ := radius_on_circumference _ _,
have eq_ae_ad : distance a e = distance a d,
{ apply distance_congruent.1,
exact radii_equal e_on_c₁ d_on_c₁},
rw eq_ae_ad,
apply distance_congruent.1,
assumption,
end
#exit
-- # Proposition 4
------------------
-- If two triangles have two sides equal to two sides respectively,
-- and have the angles contained by the equal straight lines equal,
-- then they also have the base equal to the base, the triangle equals
-- the triangle, and the remaining angles equal the remaining angles
-- respectively, namely those opposite the equal sides.
-- SAS congruency.
lemma prop4 (a b c d e f : Point) :
a⬝b ≃ d⬝e
→ a⬝c ≃ d⬝f
→
begin
sorry
end
-- # Proposition 5
-- # Proposition 7
-- # Proposition 8
-- # Proposition 10
-- # Proposition 11
-- # Proposition 13
-- # Proposition 14
-- # Proposition 15
-- # Proposition 16
-- # Proposition 18
-- # Proposition 19
-- # Proposition 20
-- # Proposition 22
-- # Proposition 26
-- # Proposition 29
-- # Proposition 31
-- # Proposition 34
-- # Proposition 37
-- # Proposition 41
-- # Proposition 46
-- # Proposition 47
-- # Proposition 48
|
360510b2c10c1f3857b8f8311511db46d7c1358b | 77c5b91fae1b966ddd1db969ba37b6f0e4901e88 | /src/tactic/lean_core_docs.lean | 94d1d4640043c37f3862759acada243061688a91 | [
"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 | 25,119 | lean | /-
Copyright (c) 2020 Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard, Bryan Gin-ge Chen, Robert Y. Lewis, Scott Morrison
-/
import tactic.doc_commands
/-!
# Core tactic documentation
This file adds the majority of the interactive tactics from core Lean (i.e. pre-mathlib) to
the API documentation.
## TODO
* Make a PR to core changing core docstrings to the docstrings below,
and also changing the docstrings of `cc`, `simp` and `conv` to the ones
already in the API docs.
* SMT tactics are currently not documented.
* `rsimp` and `constructor_matching` are currently not documented.
* `dsimp` deserves better documentation.
-/
add_tactic_doc
{ name := "abstract",
category := doc_category.tactic,
decl_names := [`tactic.interactive.abstract],
tags := ["core", "proof extraction"] }
/-- Proves a goal of the form `s = t` when `s` and `t` are expressions built up out of a binary
operation, and equality can be proved using associativity and commutativity of that operation. -/
add_tactic_doc
{ name := "ac_refl",
category := doc_category.tactic,
decl_names := [`tactic.interactive.ac_refl, `tactic.interactive.ac_reflexivity],
tags := ["core", "lemma application", "finishing"] }
add_tactic_doc
{ name := "all_goals",
category := doc_category.tactic,
decl_names := [`tactic.interactive.all_goals],
tags := ["core", "goal management"] }
add_tactic_doc
{ name := "any_goals",
category := doc_category.tactic,
decl_names := [`tactic.interactive.any_goals],
tags := ["core", "goal management"] }
add_tactic_doc
{ name := "apply",
category := doc_category.tactic,
decl_names := [`tactic.interactive.apply],
tags := ["core", "basic", "lemma application"] }
add_tactic_doc
{ name := "apply_auto_param",
category := doc_category.tactic,
decl_names := [`tactic.interactive.apply_auto_param],
tags := ["core", "lemma application"] }
add_tactic_doc
{ name := "apply_instance",
category := doc_category.tactic,
decl_names := [`tactic.interactive.apply_instance],
tags := ["core", "type class"] }
add_tactic_doc
{ name := "apply_opt_param",
category := doc_category.tactic,
decl_names := [`tactic.interactive.apply_opt_param],
tags := ["core", "lemma application"] }
add_tactic_doc
{ name := "apply_with",
category := doc_category.tactic,
decl_names := [`tactic.interactive.apply_with],
tags := ["core", "lemma application"] }
add_tactic_doc
{ name := "assume",
category := doc_category.tactic,
decl_names := [`tactic.interactive.assume],
tags := ["core", "logic"] }
add_tactic_doc
{ name := "assumption",
category := doc_category.tactic,
decl_names := [`tactic.interactive.assumption],
tags := ["core", "basic", "finishing"] }
add_tactic_doc
{ name := "assumption'",
category := doc_category.tactic,
decl_names := [`tactic.interactive.assumption'],
tags := ["core", "goal management"] }
add_tactic_doc
{ name := "async",
category := doc_category.tactic,
decl_names := [`tactic.interactive.async],
tags := ["core", "goal management", "combinator", "proof extraction"] }
/--
`by_cases p` splits the main goal into two cases, assuming `h : p` in the first branch, and
`h : ¬ p` in the second branch. You can specify the name of the new hypothesis using the syntax
`by_cases h : p`.
If `p` is not already decidable, `by_cases` will use the instance `classical.prop_decidable p`.
-/
add_tactic_doc
{ name := "by_cases",
category := doc_category.tactic,
decl_names := [`tactic.interactive.by_cases],
tags := ["core", "basic", "logic", "case bashing"] }
/--
If the target of the main goal is a proposition `p`, `by_contra h` reduces the goal to proving
`false` using the additional hypothesis `h : ¬ p`. If `h` is omitted, a name is generated
automatically.
This tactic requires that `p` is decidable. To ensure that all propositions are decidable via
classical reasoning, use `open_locale classical`
(or `local attribute [instance, priority 10] classical.prop_decidable` if you are not using
mathlib).
-/
add_tactic_doc
{ name := "by_contra / by_contradiction",
category := doc_category.tactic,
decl_names := [`tactic.interactive.by_contra, `tactic.interactive.by_contradiction],
tags := ["core", "logic"] }
add_tactic_doc
{ name := "case",
category := doc_category.tactic,
decl_names := [`tactic.interactive.case],
tags := ["core", "goal management"] }
add_tactic_doc
{ name := "cases",
category := doc_category.tactic,
decl_names := [`tactic.interactive.cases],
tags := ["core", "basic", "induction"] }
/--
`cases_matching p` applies the `cases` tactic to a hypothesis `h : type`
if `type` matches the pattern `p`.
`cases_matching [p_1, ..., p_n]` applies the `cases` tactic to a hypothesis `h : type`
if `type` matches one of the given patterns.
`cases_matching* p` is a more efficient and compact version
of `focus1 { repeat { cases_matching p } }`.
It is more efficient because the pattern is compiled once.
`casesm` is shorthand for `cases_matching`.
Example: The following tactic destructs all conjunctions and disjunctions in the current context.
```
cases_matching* [_ ∨ _, _ ∧ _]
```
-/
add_tactic_doc
{ name := "cases_matching / casesm",
category := doc_category.tactic,
decl_names := [`tactic.interactive.cases_matching, `tactic.interactive.casesm],
tags := ["core", "induction", "context management"] }
/--
* `cases_type I` applies the `cases` tactic to a hypothesis `h : (I ...)`
* `cases_type I_1 ... I_n` applies the `cases` tactic to a hypothesis
`h : (I_1 ...)` or ... or `h : (I_n ...)`
* `cases_type* I` is shorthand for `focus1 { repeat { cases_type I } }`
* `cases_type! I` only applies `cases` if the number of resulting subgoals is <= 1.
Example: The following tactic destructs all conjunctions and disjunctions in the current context.
```
cases_type* or and
```
-/
add_tactic_doc
{ name := "cases_type",
category := doc_category.tactic,
decl_names := [`tactic.interactive.cases_type],
tags := ["core", "induction", "context management"] }
add_tactic_doc
{ name := "change",
category := doc_category.tactic,
decl_names := [`tactic.interactive.change],
tags := ["core", "basic", "renaming"] }
add_tactic_doc
{ name := "clear",
category := doc_category.tactic,
decl_names := [`tactic.interactive.clear],
tags := ["core", "context management"] }
/--
Close goals of the form `n ≠ m` when `n` and `m` have type `nat`, `char`, `string`, `int`
or `fin sz`, and they are literals. It also closes goals of the form `n < m`, `n > m`, `n ≤ m` and
`n ≥ m` for `nat`. If the goal is of the form `n = m`, then it tries to close it using reflexivity.
In mathlib, consider using `norm_num` instead for numeric types.
-/
add_tactic_doc
{ name := "comp_val",
category := doc_category.tactic,
decl_names := [`tactic.interactive.comp_val],
tags := ["core", "arithmetic"] }
/--
The `congr` tactic attempts to identify both sides of an equality goal `A = B`,
leaving as new goals the subterms of `A` and `B` which are not definitionally equal.
Example: suppose the goal is `x * f y = g w * f z`. Then `congr` will produce two goals:
`x = g w` and `y = z`.
If `x y : t`, and an instance `subsingleton t` is in scope, then any goals of the form
`x = y` are solved automatically.
Note that `congr` can be over-aggressive at times; the `congr'` tactic in mathlib
provides a more refined approach, by taking a parameter that limits the recursion depth.
-/
add_tactic_doc
{ name := "congr",
category := doc_category.tactic,
decl_names := [`tactic.interactive.congr],
tags := ["core", "congruence"] }
add_tactic_doc
{ name := "constructor",
category := doc_category.tactic,
decl_names := [`tactic.interactive.constructor],
tags := ["core", "logic"] }
add_tactic_doc
{ name := "contradiction",
category := doc_category.tactic,
decl_names := [`tactic.interactive.contradiction],
tags := ["core", "basic", "finishing"] }
add_tactic_doc
{ name := "delta",
category := doc_category.tactic,
decl_names := [`tactic.interactive.delta],
tags := ["core", "simplification"] }
add_tactic_doc
{ name := "destruct",
category := doc_category.tactic,
decl_names := [`tactic.interactive.destruct],
tags := ["core", "induction"] }
add_tactic_doc
{ name := "done",
category := doc_category.tactic,
decl_names := [`tactic.interactive.done],
tags := ["core", "goal management"] }
add_tactic_doc
{ name := "dsimp",
category := doc_category.tactic,
decl_names := [`tactic.interactive.dsimp],
tags := ["core", "simplification"] }
add_tactic_doc
{ name := "dunfold",
category := doc_category.tactic,
decl_names := [`tactic.interactive.dunfold],
tags := ["core", "simplification"] }
add_tactic_doc
{ name := "eapply",
category := doc_category.tactic,
decl_names := [`tactic.interactive.eapply],
tags := ["core", "lemma application"] }
add_tactic_doc
{ name := "econstructor",
category := doc_category.tactic,
decl_names := [`tactic.interactive.econstructor],
tags := ["core", "logic"] }
/--
A variant of `rw` that uses the unifier more aggressively, unfolding semireducible definitions.
-/
add_tactic_doc
{ name := "erewrite / erw",
category := doc_category.tactic,
decl_names := [`tactic.interactive.erewrite, `tactic.interactive.erw],
tags := ["core", "rewriting"] }
add_tactic_doc
{ name := "exact",
category := doc_category.tactic,
decl_names := [`tactic.interactive.exact],
tags := ["core", "basic", "finishing"] }
add_tactic_doc
{ name := "exacts",
category := doc_category.tactic,
decl_names := [`tactic.interactive.exacts],
tags := ["core", "finishing"] }
add_tactic_doc
{ name := "exfalso",
category := doc_category.tactic,
decl_names := [`tactic.interactive.exfalso],
tags := ["core", "basic", "logic"] }
/--
`existsi e` will instantiate an existential quantifier in the target with `e` and leave the
instantiated body as the new target. More generally, it applies to any inductive type with one
constructor and at least two arguments, applying the constructor with `e` as the first argument
and leaving the remaining arguments as goals.
`existsi [e₁, ..., eₙ]` iteratively does the same for each expression in the list.
Note: in mathlib, the `use` tactic is an equivalent tactic which sometimes is smarter with
unification.
-/
add_tactic_doc
{ name := "existsi",
category := doc_category.tactic,
decl_names := [`tactic.interactive.existsi],
tags := ["core", "logic"] }
add_tactic_doc
{ name := "fail_if_success",
category := doc_category.tactic,
decl_names := [`tactic.interactive.fail_if_success],
tags := ["core", "testing", "combinator"] }
add_tactic_doc
{ name := "fapply",
category := doc_category.tactic,
decl_names := [`tactic.interactive.fapply],
tags := ["core", "lemma application"] }
add_tactic_doc
{ name := "focus",
category := doc_category.tactic,
decl_names := [`tactic.interactive.focus],
tags := ["core", "goal management", "combinator"] }
add_tactic_doc
{ name := "from",
category := doc_category.tactic,
decl_names := [`tactic.interactive.from],
tags := ["core", "finishing"] }
/--
Apply function extensionality and introduce new hypotheses.
The tactic `funext` will keep applying new the `funext` lemma until the goal target is not reducible
to
```
|- ((fun x, ...) = (fun x, ...))
```
The variant `funext h₁ ... hₙ` applies `funext` `n` times, and uses the given identifiers to name
the new hypotheses.
Note also the mathlib tactic `ext`, which applies as many extensionality lemmas as possible.
-/
add_tactic_doc
{ name := "funext",
category := doc_category.tactic,
decl_names := [`tactic.interactive.funext],
tags := ["core", "logic"] }
add_tactic_doc
{ name := "generalize",
category := doc_category.tactic,
decl_names := [`tactic.interactive.generalize],
tags := ["core", "context management"] }
add_tactic_doc
{ name := "guard_hyp",
category := doc_category.tactic,
decl_names := [`tactic.interactive.guard_hyp],
tags := ["core", "testing", "context management"] }
add_tactic_doc
{ name := "guard_target",
category := doc_category.tactic,
decl_names := [`tactic.interactive.guard_target],
tags := ["core", "testing", "goal management"] }
add_tactic_doc
{ name := "have",
category := doc_category.tactic,
decl_names := [`tactic.interactive.have],
tags := ["core", "basic", "context management"] }
add_tactic_doc
{ name := "induction",
category := doc_category.tactic,
decl_names := [`tactic.interactive.induction],
tags := ["core", "basic", "induction"] }
add_tactic_doc
{ name := "injection",
category := doc_category.tactic,
decl_names := [`tactic.interactive.injection],
tags := ["core", "structures", "induction"] }
add_tactic_doc
{ name := "injections",
category := doc_category.tactic,
decl_names := [`tactic.interactive.injections],
tags := ["core", "structures", "induction"] }
/--
If the current goal is a Pi/forall `∀ x : t, u` (resp. `let x := t in u`) then `intro` puts
`x : t` (resp. `x := t`) in the local context. The new subgoal target is `u`.
If the goal is an arrow `t → u`, then it puts `h : t` in the local context and the new goal
target is `u`.
If the goal is neither a Pi/forall nor begins with a let binder, the tactic `intro` applies the
tactic `whnf` until an introduction can be applied or the goal is not head reducible. In the latter
case, the tactic fails.
The variant `intro z` uses the identifier `z` to name the new hypothesis.
The variant `intros` will keep introducing new hypotheses until the goal target is not a Pi/forall
or let binder.
The variant `intros h₁ ... hₙ` introduces `n` new hypotheses using the given identifiers to name
them.
-/
add_tactic_doc
{ name := "intro / intros",
category := doc_category.tactic,
decl_names := [`tactic.interactive.intro, `tactic.interactive.intros],
tags := ["core", "basic", "logic"] }
add_tactic_doc
{ name := "introv",
category := doc_category.tactic,
decl_names := [`tactic.interactive.introv],
tags := ["core", "logic"] }
add_tactic_doc
{ name := "iterate",
category := doc_category.tactic,
decl_names := [`tactic.interactive.iterate],
tags := ["core", "combinator"] }
/--
`left` applies the first constructor when the type of the target is an inductive data type with
two constructors.
Similarly, `right` applies the second constructor.
-/
add_tactic_doc
{ name := "left / right",
category := doc_category.tactic,
decl_names := [`tactic.interactive.left, `tactic.interactive.right],
tags := ["core", "basic", "logic"] }
/--
`let h : t := p` adds the hypothesis `h : t := p` to the current goal if `p` a term of type `t`.
If `t` is omitted, it will be inferred.
`let h : t` adds the hypothesis `h : t := ?M` to the current goal and opens a new subgoal `?M : t`.
The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh
metavariable.
If `h` is omitted, the name `this` is used.
Note the related mathlib tactic `set a := t with h`, which adds the hypothesis `h : a = t` to
the local context and replaces `t` with `a` everywhere it can.
-/
add_tactic_doc
{ name := "let",
category := doc_category.tactic,
decl_names := [`tactic.interactive.let],
tags := ["core", "basic", "logic", "context management"] }
add_tactic_doc
{ name := "mapply",
category := doc_category.tactic,
decl_names := [`tactic.interactive.mapply],
tags := ["core", "lemma application"] }
add_tactic_doc
{ name := "match_target",
category := doc_category.tactic,
decl_names := [`tactic.interactive.match_target],
tags := ["core", "testing", "goal management"] }
add_tactic_doc
{ name := "refine",
category := doc_category.tactic,
decl_names := [`tactic.interactive.refine],
tags := ["core", "basic", "lemma application"] }
/--
This tactic applies to a goal whose target has the form `t ~ u` where `~` is a reflexive relation,
that is, a relation which has a reflexivity lemma tagged with the attribute `[refl]`.
The tactic checks whether `t` and `u` are definitionally equal and then solves the goal.
-/
add_tactic_doc
{ name := "refl / reflexivity",
category := doc_category.tactic,
decl_names := [`tactic.interactive.refl, `tactic.interactive.reflexivity],
tags := ["core", "basic", "finishing"] }
add_tactic_doc
{ name := "rename",
category := doc_category.tactic,
decl_names := [`tactic.interactive.rename],
tags := ["core", "renaming"] }
add_tactic_doc
{ name := "repeat",
category := doc_category.tactic,
decl_names := [`tactic.interactive.repeat],
tags := ["core", "combinator"] }
add_tactic_doc
{ name := "revert",
category := doc_category.tactic,
decl_names := [`tactic.interactive.revert],
tags := ["core", "context management", "goal management"] }
/--
`rw e` applies an equation or iff `e` as a rewrite rule to the main goal. If `e` is preceded by
left arrow (`←` or `<-`), the rewrite is applied in the reverse direction. If `e` is a defined
constant, then the equational lemmas associated with `e` are used. This provides a convenient
way to unfold `e`.
`rw [e₁, ..., eₙ]` applies the given rules sequentially.
`rw e at l` rewrites `e` at location(s) `l`, where `l` is either `*` or a list of hypotheses
in the local context. In the latter case, a turnstile `⊢` or `|-` can also be used, to signify
the target of the goal.
`rewrite` is synonymous with `rw`.
-/
add_tactic_doc
{ name := "rw / rewrite",
category := doc_category.tactic,
decl_names := [`tactic.interactive.rw, `tactic.interactive.rewrite],
tags := ["core", "basic", "rewriting"] }
add_tactic_doc
{ name := "rwa",
category := doc_category.tactic,
decl_names := [`tactic.interactive.rwa],
tags := ["core", "rewriting"] }
add_tactic_doc
{ name := "show",
category := doc_category.tactic,
decl_names := [`tactic.interactive.show],
tags := ["core", "goal management", "renaming"] }
add_tactic_doc
{ name := "simp_intros",
category := doc_category.tactic,
decl_names := [`tactic.interactive.simp_intros],
tags := ["core", "simplification"] }
add_tactic_doc
{ name := "skip",
category := doc_category.tactic,
decl_names := [`tactic.interactive.skip],
tags := ["core", "combinator"] }
add_tactic_doc
{ name := "solve1",
category := doc_category.tactic,
decl_names := [`tactic.interactive.solve1],
tags := ["core", "combinator", "goal management"] }
add_tactic_doc
{ name := "sorry / admit",
category := doc_category.tactic,
decl_names := [`tactic.interactive.sorry, `tactic.interactive.admit],
inherit_description_from := `tactic.interactive.sorry,
tags := ["core", "testing", "debugging"] }
add_tactic_doc
{ name := "specialize",
category := doc_category.tactic,
decl_names := [`tactic.interactive.specialize],
tags := ["core", "context management", "lemma application"] }
add_tactic_doc
{ name := "split",
category := doc_category.tactic,
decl_names := [`tactic.interactive.split],
tags := ["core", "basic", "logic"] }
add_tactic_doc
{ name := "subst",
category := doc_category.tactic,
decl_names := [`tactic.interactive.subst],
tags := ["core", "rewriting"] }
add_tactic_doc
{ name := "subst_vars",
category := doc_category.tactic,
decl_names := [`tactic.interactive.subst_vars],
tags := ["core", "rewriting"] }
add_tactic_doc
{ name := "success_if_fail",
category := doc_category.tactic,
decl_names := [`tactic.interactive.success_if_fail],
tags := ["core", "testing", "combinator"] }
add_tactic_doc
{ name := "suffices",
category := doc_category.tactic,
decl_names := [`tactic.interactive.suffices],
tags := ["core", "basic", "goal management"] }
add_tactic_doc
{ name := "symmetry",
category := doc_category.tactic,
decl_names := [`tactic.interactive.symmetry],
tags := ["core", "basic", "lemma application"] }
add_tactic_doc
{ name := "trace",
category := doc_category.tactic,
decl_names := [`tactic.interactive.trace],
tags := ["core", "debugging", "testing"] }
add_tactic_doc
{ name := "trace_simp_set",
category := doc_category.tactic,
decl_names := [`tactic.interactive.trace_simp_set],
tags := ["core", "debugging", "testing"] }
add_tactic_doc
{ name := "trace_state",
category := doc_category.tactic,
decl_names := [`tactic.interactive.trace_state],
tags := ["core", "debugging", "testing"] }
add_tactic_doc
{ name := "transitivity",
category := doc_category.tactic,
decl_names := [`tactic.interactive.transitivity],
tags := ["core", "lemma application"] }
add_tactic_doc
{ name := "trivial",
category := doc_category.tactic,
decl_names := [`tactic.interactive.trivial],
tags := ["core", "finishing"] }
add_tactic_doc
{ name := "try",
category := doc_category.tactic,
decl_names := [`tactic.interactive.try],
tags := ["core", "combinator"] }
add_tactic_doc
{ name := "type_check",
category := doc_category.tactic,
decl_names := [`tactic.interactive.type_check],
tags := ["core", "debugging", "testing"] }
add_tactic_doc
{ name := "unfold",
category := doc_category.tactic,
decl_names := [`tactic.interactive.unfold],
tags := ["core", "basic", "rewriting"] }
add_tactic_doc
{ name := "unfold1",
category := doc_category.tactic,
decl_names := [`tactic.interactive.unfold1],
tags := ["core", "rewriting"] }
add_tactic_doc
{ name := "unfold_projs",
category := doc_category.tactic,
decl_names := [`tactic.interactive.unfold_projs],
tags := ["core", "rewriting"] }
add_tactic_doc
{ name := "with_cases",
category := doc_category.tactic,
decl_names := [`tactic.interactive.with_cases],
tags := ["core", "combinator"] }
/- conv mode tactics -/
/--
Navigate to the left-hand-side of a relation.
A goal of `| a = b` will turn into the the goal `| a`.
-/
add_tactic_doc
{ name := "conv: to_lhs",
category := doc_category.tactic,
decl_names := [`conv.interactive.to_lhs],
tags := ["conv"] }
/--
Navigate to the right-hand-side of a relation.
A goal of `| a = b` will turn into the the goal `| b`.
-/
add_tactic_doc
{ name := "conv: to_rhs",
category := doc_category.tactic,
decl_names := [`conv.interactive.to_rhs],
tags := ["conv"] }
/--
Navigate into every argument of the current head function.
A target of `| (a * b) * c` will turn into the two targets `| a * b` and `| c`.
-/
add_tactic_doc
{ name := "conv: congr",
category := doc_category.tactic,
decl_names := [`conv.interactive.congr],
tags := ["conv"] }
/--
Navigate into the contents of top-level `λ` binders.
A target of `| λ a, a + b` will turn into the target `| a + b` and introduce `a` into the local
context.
If there are multiple binders, all of them will be entered, and if there are none, this tactic is a
no-op.
-/
add_tactic_doc
{ name := "conv: funext",
category := doc_category.tactic,
decl_names := [`conv.interactive.funext],
tags := ["conv"] }
/--
Navigate into the first scope matching the expression.
For a target of `| ∀ c, a + (b + c) = 1`, `find (b + _) { ... }` will run the tactics within the
`{}` with a target of `| b + c`.
-/
add_tactic_doc
{ name := "conv: find",
category := doc_category.tactic,
decl_names := [`conv.interactive.find],
tags := ["conv"] }
/--
Navigate into the numbered scopes matching the expression.
For a target of `| λ c, 10 * c + 20 * c + 30 * c`, `for (_ * _) [1, 3] { ... }` will run the
tactics within the `{}` with first a target of `| 10 * c`, then a target of `| 30 * c`.
-/
add_tactic_doc
{ name := "conv: for",
category := doc_category.tactic,
decl_names := [`conv.interactive.for],
tags := ["conv"] }
/--
End conversion of the current goal. This is often what is needed when muscle memory would type
`sorry`.
-/
add_tactic_doc
{ name := "conv: skip",
category := doc_category.tactic,
decl_names := [`conv.interactive.skip],
tags := ["conv"] }
|
c63e9c9b5ada3c6e997c7e454fffababd084c955 | 82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7 | /stage0/src/Lean/Meta/Tactic/Apply.lean | 3a037737c92de50e5abe756605b8025a146140b7 | [
"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 | 4,228 | 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.FindMVar
import Lean.Meta.ExprDefEq
import Lean.Meta.SynthInstance
import Lean.Meta.CollectMVars
import Lean.Meta.Tactic.Util
namespace Lean.Meta
/-
Compute the number of expected arguments and whether the result type is of the form
(?m ...) where ?m is an unassigned metavariable.
-/
private def getExpectedNumArgsAux (e : Expr) : MetaM (Nat × Bool) :=
withReducible $ forallTelescopeReducing e fun xs body =>
pure (xs.size, body.getAppFn.isMVar)
private def getExpectedNumArgs (e : Expr) : MetaM Nat := do
let (numArgs, _) ← getExpectedNumArgsAux e
pure numArgs
private def throwApplyError {α} (mvarId : MVarId) (eType : Expr) (targetType : Expr) : MetaM α :=
throwTacticEx `apply mvarId msg!"failed to unify{indentExpr eType}\nwith{indentExpr targetType}"
def synthAppInstances (tacticName : Name) (mvarId : MVarId) (newMVars : Array Expr) (binderInfos : Array BinderInfo) : MetaM Unit :=
newMVars.size.forM fun i => do
if binderInfos[i].isInstImplicit then
let mvar := newMVars[i]
let mvarType ← inferType mvar
let mvarVal ← synthInstance mvarType
unless (← isDefEq mvar mvarVal) do
throwTacticEx tacticName mvarId "failed to assign synthesized instance"
def appendParentTag (mvarId : MVarId) (newMVars : Array Expr) (binderInfos : Array BinderInfo) : MetaM Unit := do
let parentTag ← getMVarTag mvarId
if newMVars.size == 1 then
-- if there is only one subgoal, we inherit the parent tag
setMVarTag newMVars[0].mvarId! parentTag
else
unless parentTag.isAnonymous do
newMVars.size.forM fun i => do
let newMVarId := newMVars[i].mvarId!
unless (← isExprMVarAssigned newMVarId) do
unless binderInfos[i].isInstImplicit do
let currTag ← getMVarTag newMVarId
setMVarTag newMVarId (appendTag parentTag currTag)
def postprocessAppMVars (tacticName : Name) (mvarId : MVarId) (newMVars : Array Expr) (binderInfos : Array BinderInfo) : MetaM Unit := do
synthAppInstances tacticName mvarId newMVars binderInfos
-- TODO: default and auto params
appendParentTag mvarId newMVars binderInfos
private def dependsOnOthers (mvar : Expr) (otherMVars : Array Expr) : MetaM Bool :=
otherMVars.anyM fun otherMVar => do
if mvar == otherMVar then
pure false
else
let otherMVarType ← inferType otherMVar
pure $ (otherMVarType.findMVar? fun mvarId => mvarId == mvar.mvarId!).isSome
private def reorderNonDependentFirst (newMVars : Array Expr) : MetaM (List MVarId) := do
let (nonDeps, deps) ← newMVars.foldlM (init := (#[], #[])) fun (nonDeps, deps) mvar => do
let currMVarId := mvar.mvarId!
if (← dependsOnOthers mvar newMVars) then
pure (nonDeps, deps.push currMVarId)
else
pure (nonDeps.push currMVarId, deps)
pure $ nonDeps.toList ++ deps.toList
inductive ApplyNewGoals
| nonDependentFirst | nonDependentOnly | all
def apply (mvarId : MVarId) (e : Expr) : MetaM (List MVarId) :=
withMVarContext mvarId do
checkNotAssigned mvarId `apply
let targetType ← getMVarType mvarId
let eType ← inferType e
let mut (numArgs, hasMVarHead) ← getExpectedNumArgsAux eType
if hasMVarHead then
let targetTypeNumArgs ← getExpectedNumArgs targetType
numArgs := numArgs - targetTypeNumArgs
let (newMVars, binderInfos, eType) ← forallMetaTelescopeReducing eType (some numArgs)
unless (← isDefEq eType targetType) do throwApplyError mvarId eType targetType
postprocessAppMVars `apply mvarId newMVars binderInfos
let e ← instantiateMVars e
assignExprMVar mvarId (mkAppN e newMVars)
let newMVars ← newMVars.filterM $ fun mvar => not <$> isExprMVarAssigned mvar.mvarId!
let otherMVarIds ← getMVarsNoDelayed e
-- TODO: add option `ApplyNewGoals` and implement other orders
let newMVarIds ← reorderNonDependentFirst newMVars
let otherMVarIds := otherMVarIds.filter fun mvarId => !newMVarIds.contains mvarId
pure $ newMVarIds ++ otherMVarIds.toList
end Lean.Meta
|
e90fe94211a65b65fddffd8000afcde30f85bab3 | 3446e92e64a5de7ed1f2109cfb024f83cd904c34 | /src/game/world4/level3.lean | a1735f0fac2ce3b8b994cb52728a25bab9fef8f9 | [] | no_license | kckennylau/natural_number_game | 019f4a5f419c9681e65234ecd124c564f9a0a246 | ad8c0adaa725975be8a9f978c8494a39311029be | refs/heads/master | 1,598,784,137,722 | 1,571,905,156,000 | 1,571,905,156,000 | 218,354,686 | 0 | 0 | null | 1,572,373,319,000 | 1,572,373,318,000 | null | UTF-8 | Lean | false | false | 337 | lean | import game.world4.level2 -- hide
namespace mynat -- hide
/-
# World 4 : Power World
## Level 3 of 7 : `pow_one`
-/
/- Lemma
For all naturals $m$, $m ^ 1 = m$.
-/
lemma pow_one (m : mynat) : m ^ (1 : mynat) = m :=
begin [less_leaky]
rw one_eq_succ_zero,
rw pow_succ,
rw pow_zero,
rw one_mul,
refl,
end
end mynat -- hide
|
d44d7d0ed52f72cf2f6eae0ac6c063606662d2f3 | 99b36386640f67a61e85dddccbc0f82edec9bf9c | /src/fundamental_group.lean | ba81c0a4865ac8e40f2cceae3813e90c93bd379b | [] | no_license | aymonwuolanne/lean-theorem-proving | 1ba46fb89f446b78b7f8f8cb084aad68fadce9a3 | 701a7873f9f66f2c24962b02450ec90b20935702 | refs/heads/master | 1,586,068,982,414 | 1,575,091,205,000 | 1,575,091,205,000 | 156,647,753 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,234 | lean | import topology.continuity
import category_theory.instances.topological_spaces
import topology.instances.real
import category_theory.limits.binary_products
import category_theory.instances.Top.products
import piecewise
universe u
noncomputable theory
open category_theory.instances
open category_theory.limits
open category_theory
open set
local attribute [instance] has_binary_product_of_has_product
@[reducible] def I := {x : ℝ // 0 ≤ x ∧ x ≤ 1}
def 𝕀 : Top := { α := I, str := by apply_instance}
-- shorthands for 0 and 1 as elements of I
def I_0 : I := ⟨ 0, le_refl 0, le_of_lt zero_lt_one ⟩
def I_1 : I := ⟨ 1, le_of_lt zero_lt_one, le_refl 1 ⟩
-- says that the path has initial point x and final point y
def path_prop {X : Top} (x y : X.α) (map : 𝕀 ⟶ X) : Prop := map.val I_0 = x ∧ map.val I_1 = y
structure path {X : Top} (x y : X.α) :=
(map : 𝕀 ⟶ X)
(property : path_prop x y map)
def const_map (X Y : Top) (y : Y.α) : X ⟶ Y :=
{ val := (λ x, y),
property := continuous_const }
-- a homotopy of paths is a map F from I × I → X such that
-- F(s,0) = f
-- F(s,1) = g
-- F(s,t) is a path from x to y for any fixed t
structure homotopy {X : Top} {x y : X.α} (f g : path x y) :=
(map : limits.prod 𝕀 𝕀 ⟶ X)
(left : prod.lift (𝟙 𝕀) (const_map 𝕀 𝕀 I_0) ≫ map = f.map)
(right : prod.lift (𝟙 𝕀) (const_map 𝕀 𝕀 I_1) ≫ map = g.map)
(endpts : ∀ t : I, path_prop x y (prod.lift (𝟙 𝕀) (const_map 𝕀 𝕀 t) ≫ map))
def homotopic {X : Top} {x y : X.α} (f g : path x y) := nonempty (homotopy f g)
namespace homotopic
-- we want to show that homotopic is an equivalence relation
-- given a map f this returns the homotopy from f to itself
def id_htpy {X : Top} (f : 𝕀 ⟶ X) : limits.prod 𝕀 𝕀 ⟶ X := limits.prod.fst 𝕀 𝕀 ≫ f
def reverse : ℝ → ℝ := λ x, 1 - x
lemma cont_reverse : continuous reverse := continuous_sub continuous_const continuous_id
lemma reverse_in_I (x : ℝ) (h : 0 ≤ x ∧ x ≤ 1) : 0 ≤ reverse x ∧ reverse x ≤ 1 := begin
simp only [reverse],
have h₁ : 0 ≤ x := h.left,
have h₂ : x ≤ 1 := h.right,
apply and.intro,
linarith,
linarith
end
def reverseI : I → I := λ x, ⟨reverse x.val, reverse_in_I x.val x.property⟩
lemma cont_reverseI : continuous reverseI := continuous_induced_rng $
have h : subtype.val ∘ reverseI = reverse ∘ subtype.val,
from rfl,
have h₂ : continuous (reverse ∘ subtype.val),
from continuous.comp continuous_induced_dom cont_reverse,
h ▸ h₂
@[refl] theorem refl {X : Top} {x y : X.α} (f : path x y) : homotopic f f := ⟨ {
map := id_htpy f.map,
left := by rw [id_htpy, ←category.assoc]; simp,
right := by rw [id_htpy, ←category.assoc]; simp,
endpts := λ t, f.property
} ⟩
@[symm] theorem symm {X : Top} {x y : X.α} (f g : path x y) : homotopic f g → homotopic g f :=
have h : homotopy f g → homotopic g f,
from λ ⟨G, left, right, endpts⟩, ⟨ {
map := sorry,
left := sorry,
right := sorry,
endpts := sorry
} ⟩,
nonempty.rec h
@[trans] theorem trans {X : Top} {x y : X.α} (f g h : path x y) : homotopic f g → homotopic g h → homotopic f h :=
sorry
end homotopic
namespace path_comp
lemma in_I_of_le_half (x : I) (h : x.val ≤ 2⁻¹) : 0 ≤ 2 * x.val ∧ 2 * x.val ≤ 1 :=
⟨ zero_le_mul (le_of_lt two_pos) (x.property.left),
calc
2 * x.val ≤ 2 * 2⁻¹ : mul_le_mul_of_nonneg_left h (le_of_lt two_pos)
... = 1 : mul_inv_cancel (ne_of_gt two_pos) ⟩
lemma in_I_of_ge_half (x : I) (h : x.val ≥ 2⁻¹) :
0 ≤ 2 * x.val - 1 ∧ 2 * x.val - 1 ≤ 1 := ⟨
have h₁ : 2 * x.val ≥ 2 * 2⁻¹,
from mul_le_mul_of_nonneg_left h (le_of_lt two_pos),
have h₂ : 2 * x.val ≥ 1,
by rwa [mul_inv_cancel (ne_of_gt two_pos)] at h₁,
by linarith,
have h₁ : 2 * x.val ≤ 2*1,
from mul_le_mul_of_nonneg_left (x.property.right) (le_of_lt two_pos),
by linarith ⟩
def double : ℝ → ℝ := λ x, 2 * x
lemma cont1 : continuous double := continuous_mul continuous_const continuous_id
def double_sub_one : ℝ → ℝ := λ x, 2*x - 1
lemma cont2 : continuous double_sub_one := continuous_sub cont1 continuous_const
def s := {x : I | x.val ≤ 2⁻¹}
instance : decidable_pred s := λ x : I, has_le.le.decidable (x.val) 2⁻¹
lemma closure1 : closure s = {x : I | x.val ≤ 2⁻¹} :=
(closure_le_eq continuous_induced_dom continuous_const)
lemma closure2 : closure (-s) ⊆ {x : I | x.val ≥ 2⁻¹} :=
have h₁ : -s ⊆ {x : I | x.val ≥ 2⁻¹},
from assume x hx,
have h₁ : x.val > 2⁻¹,
from lt_of_not_ge hx,
le_of_lt h₁,
have h₂ : is_closed {x : I | x.val ≥ 2⁻¹},
from is_closed_le continuous_const continuous_induced_dom,
closure_minimal h₁ h₂
def first_half : subtype (closure s) → I := λ x,
have h: x.val ∈ {x : I | x.val ≤ 2⁻¹},
from (subset.antisymm_iff.mp closure1).left x.property,
⟨ double x.val.val, in_I_of_le_half x.val h ⟩
def second_half : subtype (closure (-s)) → I := λ x,
have h : x.val ∈ {x : I | x.val ≥ 2⁻¹},
from closure2 x.property,
⟨ double_sub_one x.val.val, in_I_of_ge_half x.val h ⟩
lemma cont_first_half : continuous first_half :=
continuous_induced_rng $
have h : subtype.val ∘ first_half = double ∘ subtype.val ∘ subtype.val,
from rfl,
by rw [h]; exact continuous.comp
(continuous.comp continuous_induced_dom continuous_induced_dom)
cont1
lemma cont_second_half : continuous second_half :=
continuous_induced_rng $
have h : subtype.val ∘ second_half = double_sub_one ∘ subtype.val ∘ subtype.val,
from rfl,
by rw [h]; exact continuous.comp
(continuous.comp continuous_induced_dom continuous_induced_dom)
cont2
def path_comp_map {X : Top} (f g : I → X.α) : I → X.α := pw (f ∘ first_half) (g ∘ second_half)
lemma computation1 : double 2⁻¹ = 1 := mul_inv_cancel (ne_of_gt two_pos)
lemma computation2 : double_sub_one 2⁻¹ = 0 :=
have h : (2 : ℝ) * 2⁻¹ = 1 := mul_inv_cancel (ne_of_gt two_pos),
calc
(2 : ℝ) * 2⁻¹ - 1 = 1 - 1 : by rw [h]
... = 0 : sub_self 1
-- Formatting suggestion from Scott: put `begin` on a new-line, no indenting
theorem path_comp_continuous {X : Top} (f g : I → X.α) (hf : continuous f) (hg : continuous g)
(h : f I_1 = g I_0) : continuous (path_comp_map f g) :=
begin
have hp : ∀ x hx,
(f ∘ first_half) ⟨x, frontier_subset_closure hx⟩ = (g ∘ second_half) ⟨x, frontier_subset_closure_compl hx⟩,
intros x hx,
have h₁ : frontier s ⊆ {x : I | x.val = 2⁻¹},
from frontier_le_subset_eq continuous_induced_dom continuous_const,
have h₂ : x.val = 2⁻¹ := h₁ hx,
have hf1 : first_half ⟨x, frontier_subset_closure hx⟩ = I_1,
have : double x.val = 1,
rw [h₂],
exact mul_inv_cancel (ne_of_gt two_pos),
exact subtype.eq this,
have hg0 : second_half ⟨x, frontier_subset_closure_compl hx⟩ = I_0,
have : double_sub_one x.val = 0,
simp [h₂, double_sub_one, mul_inv_cancel (ne_of_gt two_pos)],
ring,
exact subtype.eq this,
simp [hf1, hg0, h],
exact continuous_pw (f ∘ first_half) (g ∘ second_half)
hp (continuous.comp cont_first_half hf) (continuous.comp cont_second_half hg),
end
end path_comp
open path_comp
-- this defines the type of homotopy classes of paths from x to y
def htpy_class {X : Top} (x y : X.α) := quot (@homotopic X x y)
-- to define the fundamental group(oid) we need to instantiate the category of paths in X
-- with homotopy classes of paths as morphisms between each point.
def paths (X : Top) := X.α
-- TODO
def path_composition {X : Top} {x y z : paths X} (f : path x y) (g : path y z) : path x z := {
map := {val := path_comp_map f.map g.map,
property := path_comp_continuous f.map.val g.map.val f.map.property g.map.property
(trans f.property.right (symm g.property.left) )
},
property := sorry
}
-- [f][g] = [fg]
def composition {X : Top} {x y z : paths X} (f : path x y) : htpy_class y z → htpy_class x z :=
quot.lift
(λ g, quot.mk (@homotopic X x z) (path_composition f g))
(λ a b (h : homotopic a b), quot.sound sorry)
-- want h : quot.mk (@homotopic X x z) (path_composition f a) = quot.mk (@homotopic X x z) (path_composition f b)
-- using quot.sound it is enough to have
-- h : homotopic (path_composition f a) (homotopic path_composition f b)
-- TODO ^that
lemma path_comp_associative {X : Top} {x₀ x₁ x₂ x₃ : paths X} (f : path x₀ x₁) (g : path x₁ x₂)
(h : path x₂ x₃) :
homotopic (path_composition f (path_composition g h)) (path_composition (path_composition f g) h) :=
sorry
instance (X : Top) : category (paths X) := {
hom := λ x y, htpy_class x y,
id := λ x, quot.mk (λ f g, homotopic f g)
{ map := const_map 𝕀 X x, property := by tidy },
comp := sorry,
assoc' := sorry,
comp_id' := sorry,
id_comp' := sorry
}
def fundamental_group (X : Top) (x : paths X) : Type := sorry |
8009e069b237f9fa661d26ebd42f7ff7839d6f60 | 93b17e1ec33b7fd9fb0d8f958cdc9f2214b131a2 | /src/sep/rel.lean | f5f1ce730fc7a3d1a25df0abe296ee4de99bb06e | [] | no_license | intoverflow/timesink | 93f8535cd504bc128ba1b57ce1eda4efc74e5136 | c25be4a2edb866ad0a9a87ee79e209afad6ab303 | refs/heads/master | 1,620,033,920,087 | 1,524,995,105,000 | 1,524,995,105,000 | 120,576,102 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 47,044 | lean | /- Relations between separation algebras
-
-/
import .basic
namespace Sep
universes ℓ₁ ℓ₂ ℓ₃ ℓ₄
/- Relations between separation algebras
-
-/
def Rel (A₁ : Alg.{ℓ₁}) (A₂ : Alg.{ℓ₂})
:= A₁.τ → Set A₂
def FunRel {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}}
(f : A₁.τ → A₂.τ)
: Rel A₁ A₂
:= λ x y, y = f x
def InvFunRel {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}}
(f : A₁.τ → A₂.τ)
: Rel A₂ A₁
:= λ y x, y = f x
instance Rel_has_le {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} : has_le (Rel A₁ A₂)
:= { le := λ r₁ r₂, ∀ x, r₁ x ⊆ r₂ x
}
def Rel.Refl {A : Alg.{ℓ₁}} (r : Rel A A)
: Prop
:= ∀ x, r x x
def Rel.Trans {A : Alg.{ℓ₁}} (r : Rel A A)
: Prop
:= ∀ x₁ x₂ x₃, r x₁ x₂ → r x₂ x₃ → r x₁ x₃
def Rel.WellDefined {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= ∀ {x} {y₁ y₂}
(R₁ : r x y₁)
(R₂ : r x y₂)
, y₁ = y₂
def Rel.Total {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= ∀ x, ∃ y, r x y
def Rel.Surj {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= ∀ y, ∃ x, r x y
-- An equivalence relation on relations; happens to imply equality but is easier to prove
def RelEq {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r₁ r₂ : Rel A₁ A₂) : Prop
:= ∀ x₁ x₂, r₁ x₁ x₂ ↔ r₂ x₁ x₂
def RelEq.refl {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : RelEq r r
:= λ x₁ x₂, by trivial
def RelEq.symm {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r₁ r₂ : Rel A₁ A₂}
(H : RelEq r₁ r₂)
: RelEq r₂ r₁
:= λ x₁ x₂, iff.symm (H _ _)
def RelEq.trans {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r₁ r₂ r₃ : Rel A₁ A₂}
(H₁₂ : RelEq r₁ r₂) (H₂₃ : RelEq r₂ r₃)
: RelEq r₁ r₃
:= λ x₁ x₂, iff.trans (H₁₂ _ _) (H₂₃ _ _)
def RelEq.to_eq {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r₁ r₂ : Rel A₁ A₂}
: RelEq r₁ r₂ → r₁ = r₂
:= begin
intro H,
apply funext, intro x₁,
apply funext, intro x₂,
apply iff.to_eq,
apply H
end
-- The identity relation
def Alg.IdRel (A : Alg.{ℓ₁})
: Rel A A
:= λ x, eq x
def Rel.Reflexive {A : Alg.{ℓ₁}} (r : Rel A A) : Prop
:= A.IdRel ≤ r
def Rel.Discrete {A : Alg.{ℓ₁}} (r : Rel A A) : Prop
:= r ≤ A.IdRel
-- Composition of relations
def Rel_comp {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {A₃ : Alg.{ℓ₃}}
: Rel A₂ A₃ → Rel A₁ A₂ → Rel A₁ A₃
:= λ r₂ r₁ x₁ x₃
, ∃ x₂, r₁ x₁ x₂ ∧ r₂ x₂ x₃
reserve infixr ` ∘ ` : 100
infixr ` ∘ ` := λ {A₁} {A₂} {A₃}
(r₂₃ : Rel A₂ A₃) (r₁₂ : Rel A₁ A₂)
, Rel_comp r₂₃ r₁₂
def Rel_comp.id_l {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}}
(r : Rel A₁ A₂)
: Rel_comp A₂.IdRel r = r
:= begin
apply RelEq.to_eq,
intros x₀ y₀,
apply iff.intro,
{ intro H, cases H with y H,
cases H with R E,
simp [Alg.IdRel] at E,
subst E, assumption
},
{ intro H,
existsi y₀,
exact and.intro H rfl
}
end
def Rel_comp.id_r {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}}
(r : Rel A₁ A₂)
: Rel_comp r A₁.IdRel = r
:= begin
apply RelEq.to_eq,
intros x₀ y₀,
apply iff.intro,
{ intro H,
cases H with y H,
cases H with E R,
simp [Alg.IdRel] at E,
subst E, assumption
},
{ intro H,
existsi x₀,
exact and.intro rfl H
}
end
def Rel_comp.congr {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {A₃ : Alg.{ℓ₃}}
{s₁ s₂ : Rel A₂ A₃} {r₁ r₂ : Rel A₁ A₂}
(Es : s₁ = s₂) (Er : r₁ = r₂)
: s₁ ∘ r₁ = s₂ ∘ r₂
:= begin subst Es, subst Er end
-- Composition is associative
def Rel_comp.assoc {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {A₃ : Alg.{ℓ₃}} {A₄ : Alg.{ℓ₄}}
{r₃₄ : Rel A₃ A₄} {r₂₃ : Rel A₂ A₃} {r₁₂ : Rel A₁ A₂}
: ((r₃₄ ∘ r₂₃) ∘ r₁₂) = (r₃₄ ∘ (r₂₃ ∘ r₁₂))
:= RelEq.to_eq
(λ x₁ x₄
, iff.intro
(λ H, begin
cases H with x₂ H, cases H with H₁₂ H,
cases H with x₃ H, cases H with H₂₃ H₃₄,
existsi x₃, refine and.intro _ H₃₄,
existsi x₂, exact and.intro H₁₂ H₂₃
end)
(λ H, begin
cases H with x₃ H, cases H with H H₃₄,
cases H with x₂ H, cases H with H₁₂ H₂₃,
existsi x₂, apply and.intro H₁₂,
existsi x₃, exact and.intro H₂₃ H₃₄
end))
-- The complement relation
def Rel.Compl {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂)
: Rel A₁ A₂
:= λ x y, ¬ r x y
def Rel.Compl.Involutive {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂)
: r.Compl.Compl = r
:= begin
apply funext, intro x,
apply funext, intro y,
simp [Rel.Compl],
apply iff.to_eq,
apply iff.intro,
{ intro H₁,
apply classical.by_contradiction,
intro H₂,
exact H₁ H₂
},
{ intros H₁ H₂,
exact H₂ H₁
}
end
-- The function induced by a relation
def Rel.Fn {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (f : Rel A₁ A₂)
: Set A₁ → Set A₂
:= λ X, λ y, ∃ x, X x ∧ f x y
def Rel.Fn.show {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {f : Rel A₁ A₂}
{X : Set A₁} {y} (x) (Hx : x ∈ X) (Hf : f x y)
: y ∈ f.Fn X
:= exists.intro x (and.intro Hx Hf)
def Rel.Fn.elim {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {f : Rel A₁ A₂}
{X : Set A₁} {y} (H : y ∈ f.Fn X)
{P : Prop}
(C : ∀ {x}, x ∈ X → f x y → P)
: P
:= begin cases H with x H, exact C H.1 H.2 end
def Rel.Fn.subset {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (f : Rel A₁ A₂)
: ∀ (X₁ X₂ : Set A₁)
, X₁ ⊆ X₂ → f.Fn X₁ ⊆ f.Fn X₂
:= λ X₁ X₂ H y Hy
, begin
cases Hy with x Hx,
existsi x,
exact and.intro (H Hx.1) Hx.2
end
-- The inverse image of the function induced by a relation
def Rel.FnInv {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂)
: Set A₂ → Set A₁
:= λ Y x, (∃ y, y ∈ Y ∧ r x y)
def Rel.FnInv.show {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {f : Rel A₁ A₂}
{Y : Set A₂} {x} {y} (Hxy : f x y) (Hy : y ∈ Y)
: x ∈ f.FnInv Y
:= exists.intro y (and.intro Hy Hxy)
def Rel.FnInv.elim {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
{Y : Set A₂} {x} (Hx : x ∈ r.FnInv Y)
{P : Prop}
: (∀ y, y ∈ Y → r x y → P)
→ P
:= begin
intro C,
{ cases Hx with y Hy,
exact C y Hy.1 Hy.2
}
end
def Rel.FnInv.subset {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂)
: ∀ (Y₁ Y₂ : Set A₂)
, Y₁ ⊆ Y₂ → r.FnInv Y₁ ⊆ r.FnInv Y₂
:= λ Y₁ Y₂ HYY x Hx
, begin
apply Rel.FnInv.elim Hx,
{ intros y Hy Rxy,
apply Rel.FnInv.show Rxy (HYY Hy)
}
end
def Rel.FnInv.Empty {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂)
: r.FnInv ∅ = ∅
:= begin
apply funext, intro x,
apply iff.to_eq, apply iff.intro,
{ intro H,
cases H with y H,
cases H with F Rxy,
cases F
},
{ intro H, cases H }
end
-- The image of the function induced by a relation
def Rel.Im {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂)
: Set A₂
:= λ y, ∃ x, r x y
def Rel.FinIm {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂)
: Prop
:= ∀ x, ∃ (ys : list A₂.τ), (∀ y, r x y ↔ y ∈ ys)
-- Increasing elements
def Rel.increasing {A : Alg.{ℓ₁}} (r : Rel A A)
: Set A
:= λ s, ∀ x y, A.join s x y → r x y
-- The proper domain of the function induced by a relation
def Rel.Dom {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂)
: Set A₁
:= λ x, ∃ y, r x y
def Rel.IdealDom {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= ∀ {x₁ x₂ x₃} (Dx₁ : x₁ ∈ r.Dom) (Jx : A₁.join x₁ x₂ x₃)
, x₃ ∈ r.Dom
def Total.IdealDom {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
(rT : r.Total)
: r.IdealDom
:= begin intros x₁ x₂ x₃ Dx₁ Jx, apply rT end
def Rel.FnIdealDom {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= r.Dom.Ideal
def Rel.FnIdealDom_iff {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂)
: r.FnIdealDom ↔ r.IdealDom
:= begin
apply iff.intro,
{ intro rID, exact @rID },
{ intro rID, exact @rID }
end
-- Fibers
def Rel.Fib {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) (y : A₂.τ)
: Set A₁
:= λ x, r x y
def Rel.FinFib {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂)
: Prop
:= ∀ (y : A₂.τ), ∃ (xs : list A₁.τ), (r.Fib y = λ x, x ∈ xs)
-- The kernel of the function induced by a relation
def Rel.Ker {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂)
: Set A₁
:= λ x, ∀ y, ¬ r x y
def Rel.IdealKer {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= ∀ {x₁ x₃}
, A₁.Divides x₁ x₃
→ (∀ y₁, ¬ r x₁ y₁)
→ (∀ y₃, ¬ r x₃ y₃)
def Rel.FnIdealKer {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= r.Ker.Ideal
def Rel.FnIdealKerl_iff {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂)
: r.FnIdealKer ↔ r.IdealKer
:= begin
apply iff.intro,
{ intro rLinear,
intros x₁ x₃ Dx₁x₃ Kx₁ y₃ Rx₃y₃,
apply Dx₁x₃,
{ intros x₂ Jx,
apply rLinear Kx₁ Jx,
assumption
},
{ intro E, subst E,
exact Kx₁ _ Rx₃y₃
}
},
{ intro rLinear,
intros x₁ x₂ x₃ Kx₁ Jx y₃ Rx₃y₃,
refine rLinear _ Kx₁ _ Rx₃y₃,
intros P C₁ C₂, exact C₁ Jx
}
end
def Rel.PrimeKer {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= ∀ {x₁ x₂ x₃}
, A₁.join x₁ x₂ x₃
→ (∀ y₃, ¬ r x₃ y₃)
→ (∀ y₁, ¬ r x₁ y₁) ∨ (∀ y₂, ¬ r x₂ y₂)
def Rel.FnPrimeKer {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= r.Ker.Prime
def Rel.FnPrimeKer_iff {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂)
: r.FnPrimeKer ↔ r.PrimeKer
:= begin
apply iff.intro,
{ intro rKP,
intros x₁ x₂ x₃ Jx Kx₃,
exact rKP _ _ _ Jx Kx₃
},
{ intro rKP,
intros x₁ x₂ x₃ Jx Kx₃,
exact rKP Jx Kx₃
}
end
-- Preservation of ideals, join-closed sets, prime sets, division, etc
def Rel.FnComplSubAlgPres {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= ∀ {S : Set A₂} (S_CSA : S.Compl.SubAlg)
, (r.FnInv S).Compl.SubAlg
def Rel.FnJoinClosedPres {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= ∀ {S : Set A₁} (SJC : S.JoinClosed)
, (r.Fn S).JoinClosed
def Rel.FnWeakIdealPres {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= ∀ {I : Set A₂} (Iideal : I.WeakIdeal)
, (r.FnInv I).WeakIdeal
def Rel.IdealPres {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= ∀ {x₁ x₂ x₃} {y₁}
, A₁.join x₁ x₂ x₃ → r x₁ y₁
→ (r x₃ y₁) ∨ (∃ y₂ y₃, r x₃ y₃ ∧ A₂.join y₁ y₂ y₃)
def Rel.FnIdealPres {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= ∀ {I : Set A₂} (Iideal : I.Ideal)
, (r.FnInv I).Ideal
def Rel.IdealPres_iff {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
: r.FnIdealPres ↔ r.IdealPres
:= begin
apply iff.intro,
{ intro rIP,
intros x₁ x₂ x₃ y₁ Jx Rx₁y₁,
have Q₀ : x₁ ∈ Rel.FnInv r (Alg.GenIdeal₁ A₂ y₁), from
begin
existsi y₁,
apply and.intro,
{apply GenIdeal₁.mem},
{assumption}
end,
have Q := rIP (@GenIdeal₁.Ideal _ y₁) Q₀ Jx,
cases Q with y₃ Hy₃,
cases Hy₃ with Hy₁ Rx₃y₃,
cases Hy₁ with y₁' Hy₁',
cases Hy₁' with Dy₁y₃ E,
subst E,
apply Dy₁y₃,
{ intros y₂ Jy,
apply or.inr,
existsi y₂, existsi y₃,
apply and.intro,
repeat { assumption }
},
{ intro E, subst E,
exact or.inl Rx₃y₃
}
},
{ intro rIP,
intros I Iideal,
intros x₁ x₂ x₃ Hx₁ Hx,
apply Rel.FnInv.elim Hx₁,
intros y₁ Iy₁ Rx₁y₁,
cases rIP Hx Rx₁y₁ with Rx₃y₁ Hy,
{ existsi y₁, apply and.intro, repeat {assumption}
},
{ cases Hy with y₂ Hy, cases Hy with y₃ Hy,
exact Rel.FnInv.show Hy.1 (Iideal Iy₁ Hy.2)
}
}
end
def Rel.PrimePres {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= ∀ {p : Set A₂} (pPrime : p.Prime)
{x₁ x₂ x₃} {y₃}
(Jx : x₃ ∈ A₁.join x₁ x₂)
(Rx₃y₃ : r x₃ y₃)
(Py₃ : y₃ ∈ p)
, (∃ y₁, r x₁ y₁ ∧ y₁ ∈ p) ∨ (∃ y₂, r x₂ y₂ ∧ y₂ ∈ p)
def Rel.FnPrimePres {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= ∀ {p : Set A₂} (pPrime : p.Prime)
, (r.FnInv p).Prime
def Rel.PrimePres_iff {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
: r.FnPrimePres ↔ r.PrimePres
:= begin
apply iff.intro,
{ intro rPP,
intros p pPrime x₁ x₂ x₃ y₃ Jx Rx₃y₃ Py₃,
have Px₃ : x₃ ∈ r.FnInv p := Rel.FnInv.show Rx₃y₃ Py₃,
cases rPP pPrime _ _ _ Jx Px₃ with H H,
{ apply Rel.FnInv.elim H,
intros y₁ Py₁ Rx₁y₁,
apply or.inl, existsi y₁,
apply and.intro, repeat {assumption}
},
{ apply Rel.FnInv.elim H,
intros y₂ Py₂ Rx₂y₂,
apply or.inr, existsi y₂,
apply and.intro, repeat {assumption}
}
},
{ intro rPP,
intros p pPrime x₁ x₂ x₃ Jx Px₃,
apply Rel.FnInv.elim Px₃,
intros y₃ Py₃ Rx₃y₃,
cases rPP @pPrime Jx Rx₃y₃ Py₃ with H H,
{ cases H with y₁ Hy₁,
apply or.inl,
exact Rel.FnInv.show Hy₁.1 Hy₁.2
},
{ cases H with y₂ Hy₂,
apply or.inr,
exact Rel.FnInv.show Hy₂.1 Hy₂.2
}
}
end
def Rel.DivPres_r {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= ∀ {x₁ x₃} {y₃}
, A₁.Divides x₁ x₃
→ r x₃ y₃
→ ∃ y₁, r x₁ y₁ ∧ A₂.Divides y₁ y₃
def DivPres_r.IdealKer {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
(rDP : r.DivPres_r)
: r.IdealKer
:= begin
intros x₁ x₃ Dx₁x₃ Kx₁ y₃ Rx₃y₃,
cases rDP @Dx₁x₃ Rx₃y₃ with y₁ Hy₁,
exact Kx₁ _ Hy₁.1
end
def DivPres_r.GenPrime.Prime {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
(rDP : r.DivPres_r)
: ∀ {gen}, (r.FnInv (A₂.GenPrime₁ gen)).Prime
:= begin
intros y x₁ x₂ x₃ Jx Rx₃,
apply Rel.FnInv.elim Rx₃,
intros y₃ Hy₃ Rx₃y₃,
cases rDP (λ P C₁ C₂, C₁ Jx) Rx₃y₃ with y₁ Hy,
cases Hy with Rx₁y₁ Dy₁y₃,
apply or.inl,
apply Rel.FnInv.show Rx₁y₁,
existsi y,
refine and.intro _ rfl,
apply Divides.trans @Dy₁y₃,
cases Hy₃ with y' Hy',
cases Hy' with Hy' E,
subst E, assumption
end
def Rel.DivPres_l {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= ∀ {x₁ x₃} {y₁}
, A₁.Divides x₁ x₃
→ r x₁ y₁
→ (r x₃ y₁) ∨ (∃ y₃, r x₃ y₃ ∧ A₂.Divides y₁ y₃)
def DivPres_l.PrimeKer {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
(rDP : r.DivPres_l)
: r.PrimeKer
:= begin
intros x₁ x₃ x₃ Jx Kx₃,
apply or.inl,
intros y₁ Rx₁y₁,
cases rDP (λ P C₁ C₂, C₁ Jx) Rx₁y₁ with Rx₃y₁ Hy,
{ exact Kx₃ _ Rx₃y₁ },
{ cases Hy with y Hy,
exact Kx₃ _ Hy.1
}
end
def Rel.IdealPres_iff' {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
: r.IdealPres ↔ r.DivPres_l
:= begin
apply iff.intro,
{ intro rIP,
intros x₁ x₃ y₁ Dx₁x₃ Rx₁y₁,
apply Dx₁x₃,
{ intros x₂ Jx,
have Ix₁ : x₁ ∈ r.FnInv (A₂.GenIdeal₁ y₁), from
begin
apply Rel.FnInv.show Rx₁y₁,
apply GenIdeal₁.mem
end,
cases rIP Jx Rx₁y₁ with Rx₃y₁ Hy,
{ exact or.inl Rx₃y₁ },
{ apply or.inr,
cases Hy with y₂ Hy,
cases Hy with y₃ Hy,
cases Hy with Rx₃y₃ Jy,
existsi y₃, apply and.intro Rx₃y₃,
intros P C₁ C₂, exact C₁ Jy
}
},
{ intro E, subst E,
exact or.inl Rx₁y₁
}
},
{ intro rDP,
intros x₁ x₂ x₃ y₁ Jx Rx₁y₁,
have Dx₁x₃ : A₁.Divides x₁ x₃ := λ P C₁ C₂, C₁ Jx,
cases rDP @Dx₁x₃ Rx₁y₁ with Rx₃y₁ Hy₃,
{ exact or.inl Rx₃y₁ },
{ cases Hy₃ with y₃ Hy₃,
apply Hy₃.2,
{ intros y₂ Jy,
apply or.inr,
existsi y₂, existsi y₃,
exact and.intro Hy₃.1 Jy
},
{ intro E, subst E,
exact or.inl Hy₃.1
}
}
}
end
-- Downwards, (quasi)-upwards, and quasi-closure
def Rel.QuasiClosed {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (f : Rel A₁ A₂) : Prop
:= ∀ {a₁ a₂ a₁₂} {fa₁₂ b₁ b₂ b₁₂}
(Ha : A₁.join a₁ a₂ a₁₂) (Hfa₁₂ : f a₁₂ fa₁₂)
(Ha₁b₁ : f a₁ b₁) (Ha₂b₂ : f a₂ b₂) (Hb : A₂.join b₁ b₂ b₁₂)
, ∃ y a₁₂' b₁' b₂'
, f a₁ b₁' ∧ f a₂ b₂'
∧ A₁.join a₁ a₂ a₁₂' ∧ f a₁₂' y ∧ A₂.join b₁' b₂' y
def Rel.FnQuasiClosed {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (f : Rel A₁ A₂) : Prop
:= ∀ (X₁ X₂ : Set A₁)
, Set.nonempty (f.Fn (X₁ <*> X₂))
→ Set.nonempty (f.Fn X₁ <*> f.Fn X₂)
→ Set.nonempty (f.Fn (X₁ <*> X₂) ∩ (f.Fn X₁ <*> f.Fn X₂))
-- note that the converse does not appear to be true.
def Rel.QuasiClosed_if {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (f : Rel A₁ A₂)
: f.FnQuasiClosed → f.QuasiClosed
:= begin
intros H_qc a₁ a₂ a₁₂ fa₁₂ b₁ b₂ b₁₂ Ha Hfa₁₂ Ha₁b₁ Ha₂b₂ Hb,
refine exists.elim (H_qc (eq a₁) (eq a₂)
(exists.intro fa₁₂
(Rel.Fn.show a₁₂ (Alg.Join.show rfl rfl Ha) Hfa₁₂))
(exists.intro b₁₂
(Alg.Join.show
(Rel.Fn.show a₁ rfl Ha₁b₁)
(Rel.Fn.show a₂ rfl Ha₂b₂)
Hb))) _,
intros y Hy,
cases Hy with Hy₁ Hy₂,
apply Rel.Fn.elim Hy₁, clear Hy₁,
intros a₁₂' Ha₁₂' Ha₁₂y,
apply Alg.Join.elim Hy₂, clear Hy₂,
intros b₁' b₂' Hb₁' Hb₂' HJb,
apply Rel.Fn.elim Hb₁', clear Hb₁', intros a₁' Ha₁' Hfa₁b₁', have Q : a₁ = a₁' := Ha₁', subst Q,
apply Rel.Fn.elim Hb₂', clear Hb₂', intros a₂' Ha₂' Hfa₂b₂', have Q : a₂ = a₂' := Ha₂', subst Q,
apply Alg.Join.elim Ha₁₂',
intros a₁' a₂' Ha₁' Ha₂' HJa, subst Ha₁', subst Ha₂',
existsi y, existsi a₁₂', existsi b₁', existsi b₂',
repeat {try {assumption}, apply and.intro, assumption },
assumption
end
def Rel.DownClosed {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (f : Rel A₁ A₂) : Prop
:= ∀ {n₁ n₂} {m₁ m₂ m₃}
, f n₁ m₁ → f n₂ m₂ → A₂.join m₁ m₂ m₃
→ ∃ n₃, f n₃ m₃ ∧ A₁.join n₁ n₂ n₃
def DownClosed.QuasiClosed {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (f : Rel A₁ A₂)
: f.DownClosed → f.QuasiClosed
:= λ H a₁ a₂ a₁₂ fa₁₂ b₁ b₂ b₁₂ Ha Hfa₁₂ Ha₁b₁ Ha₂b₂ Hb
, begin
apply exists.elim (H Ha₁b₁ Ha₂b₂ Hb),
intros x Hx, cases Hx with Hx₁ Hx₂,
existsi b₁₂, existsi x, existsi b₁, existsi b₂,
repeat {try {assumption}, apply and.intro, assumption },
assumption
end
def DownClosed.JoinClosedPres {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
(rDC : r.DownClosed)
: r.FnJoinClosedPres
:= begin
intros S SJC,
intros b₁ b₂ b₃ Jb Sb₁ Sb₂,
apply Rel.Fn.elim Sb₁, intros a₁ Sa₁ Ra₁b₁,
apply Rel.Fn.elim Sb₂, intros a₂ Sa₂ Ra₂b₂,
cases rDC Ra₁b₁ Ra₂b₂ Jb with a₃ Ha,
cases Ha with Ra₃b₃ Ja,
have Sa₃ : a₃ ∈ S := SJC _ _ _ Ja Sa₁ Sa₂,
exact Rel.Fn.show _ Sa₃ Ra₃b₃
end
-- This condition is too strong
def Rel.QuasiDownClosed {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= ∀ {n₁ n₂ n₃} {m₁ m₂ m₃}
, r n₁ m₁ → r n₂ m₂ → r n₃ m₃
→ A₂.join m₁ m₂ m₃
→ A₁.join n₁ n₂ n₃
def QuasiDownClosed.DownClosed {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂)
(rIM : r.Im.JoinClosed)
(rDC : r.QuasiDownClosed)
: r.DownClosed
:= begin
intros n₁ n₂ m₁ m₂ m₃ Rn₁m₁ Rn₂m₂ Jm,
have Im₁ : m₁ ∈ r.Im := exists.intro n₁ Rn₁m₁,
have Im₂ : m₂ ∈ r.Im := exists.intro n₂ Rn₂m₂,
cases rIM _ _ _ Jm Im₁ Im₂ with n₃ Rn₃m₃,
existsi n₃, apply and.intro Rn₃m₃,
exact rDC Rn₁m₁ Rn₂m₂ Rn₃m₃ Jm
end
def Rel.FnDownClosed {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (f : Rel A₁ A₂) : Prop
:= ∀ (X₁ X₂ : Set A₁)
, (f.Fn X₁ <*> f.Fn X₂) ⊆ f.Fn (X₁ <*> X₂)
def Rel.DownClosed_iff {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (f : Rel A₁ A₂)
: f.FnDownClosed ↔ f.DownClosed
:= begin
apply iff.intro,
{ intros H_dc n₁ n₂ fn₁ fn₂ m₃ Hfn₁ Hfn₂ HJ,
apply Rel.Fn.elim
(H_dc (eq n₁) (eq n₂)
(Alg.Join.show (Rel.Fn.show _ rfl Hfn₁)
(Rel.Fn.show _ rfl Hfn₂)
HJ)),
intros fx H' Hfx,
existsi fx,
apply and.intro Hfx,
apply Alg.Join.elim H', clear H',
intros x₁' x₂' Hx₁' Hx₂' HJ',
subst Hx₁', subst Hx₂', assumption
},
{ intros H_dc X₁ X₂ y Hy,
apply Alg.Join.elim Hy, clear Hy,
intros y₁ y₂ Hy₁ Hy₂ HJy,
apply Rel.Fn.elim Hy₁, intros x₁ Hx₁ Hx₁y₁, clear Hy₁,
apply Rel.Fn.elim Hy₂, intros x₂ Hx₂ Hx₂y₂, clear Hy₂,
cases (H_dc Hx₁y₁ Hx₂y₂ HJy) with x H', cases H' with Hxy HJx,
exact Rel.Fn.show x (Alg.Join.show Hx₁ Hx₂ HJx) Hxy
}
end
def Rel.UpClosed {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (f : Rel A₁ A₂) : Prop
:= ∀ {m₁ m₂ m₃} {n₃}
, A₁.join m₁ m₂ m₃ → f m₃ n₃
→ ∃ n₁ n₂, A₂.join n₁ n₂ n₃ ∧ f m₁ n₁ ∧ f m₂ n₂
def UpClosed.QuasiClosed {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
: r.UpClosed → r.QuasiClosed
:= λ H a₁ a₂ a₁₂ fa₁₂ b₁ b₂ b₁₂ Ha Hfa₁₂ Ha₁b₁ Ha₂b₂ Hb
, begin
apply exists.elim (H Ha Hfa₁₂),
intros y₁ Hy,
cases Hy with y₂ Hy,
cases Hy with Hy₁ Hy, cases Hy with Hy₂ H₃,
existsi fa₁₂, existsi a₁₂, existsi y₁, existsi y₂,
repeat {try {assumption}, apply and.intro, assumption },
assumption
end
def UpClosed.IdealPres {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
(rUC : r.UpClosed)
(rID : r.IdealDom)
(rWD : r.WellDefined)
: r.IdealPres
:= begin
intros x₁ x₂ x₃ y₁ Jx Rx₁y₁,
have Dx₁ : x₁ ∈ r.Dom, from begin existsi y₁, assumption end,
cases rID Dx₁ Jx with y₃ Rx₃y₃, -- Uses rID
have Q := rUC Jx Rx₃y₃, -- Uses rUC
cases Q with y₁' Q, cases Q with y₂' Q,
have E : y₁' = y₁ := rWD Q.2.1 Rx₁y₁, -- Uses rWD
subst E,
apply or.inr,
existsi y₂', existsi y₃,
exact and.intro Rx₃y₃ Q.1
end
def UpClosed.PrimePres {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
(rUC : r.UpClosed)
: r.FnPrimePres
:= begin
intros p pPrime,
intros x₁ x₂ x₃ Jx Px₃,
apply Rel.FnInv.elim Px₃,
intros y₃ Py₃ Rx₃y₃,
cases rUC Jx Rx₃y₃ with n₁ Hn,
cases Hn with n₂ Hn,
cases pPrime _ _ _ Hn.1 Py₃ with H H,
{ exact or.inl (Rel.FnInv.show Hn.2.1 H) },
{ exact or.inr (Rel.FnInv.show Hn.2.2 H) }
end
def UpClosed.DivPres_r {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
(rUC : r.UpClosed)
: r.DivPres_r
:= begin
intros x₁ x₃ y₃ Dx₁x₃ Rx₃y₃,
apply Dx₁x₃,
{ intros x₂ Jx,
cases rUC Jx Rx₃y₃ with y₁ Hy,
cases Hy with y₂ Hy,
existsi y₁,
apply and.intro Hy.2.1,
intros P C₁ C₂, exact C₁ Hy.1
},
{ intro E, subst E,
existsi y₃,
apply and.intro Rx₃y₃,
apply Divides.refl
}
end
def UpClosed.IdealKer {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
(rUC : r.UpClosed)
: r.IdealKer
:= begin
apply DivPres_r.IdealKer,
apply UpClosed.DivPres_r,
assumption
end
def Rel.FnUpClosed {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (f : Rel A₁ A₂) : Prop
:= ∀ (X₁ X₂ : Set A₁)
, f.Fn (X₁ <*> X₂) ⊆ (f.Fn X₁ <*> f.Fn X₂)
def Rel.UpClosed_iff {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (f : Rel A₁ A₂)
: f.FnUpClosed ↔ f.UpClosed
:= begin
apply iff.intro,
{ intros H_uc m₁ m₂ m₃ n₃ HJm Hm₃n₃,
apply Alg.Join.elim
(H_uc (eq m₁) (eq m₂)
(Rel.Fn.show m₃ (Alg.Join.show rfl rfl HJm) Hm₃n₃)),
intros n₁ n₂ Hn₁ Hn₂ HJn,
existsi n₁, existsi n₂,
apply and.intro HJn,
apply Rel.Fn.elim Hn₁, intros m₁' Hm₁' Hm₁n₁, have Q : m₁ = m₁' := Hm₁', subst Q,
apply Rel.Fn.elim Hn₂, intros m₂' Hm₂' Hm₂n₂, have Q : m₂ = m₂' := Hm₂', subst Q,
exact and.intro Hm₁n₁ Hm₂n₂
},
{ intros H_uc X₁ X₂ y Hy,
apply Rel.Fn.elim Hy, clear Hy,
intros x Hx Hxy,
apply Alg.Join.elim Hx, clear Hx,
intros x₁ x₂ Hx₁ Hx₂ HJx,
cases (H_uc HJx Hxy) with y₁ H, cases H with y₂ H,
exact Alg.Join.show (Rel.Fn.show x₁ Hx₁ H.2.1) (Rel.Fn.show x₂ Hx₂ H.2.2) H.1
}
end
def Rel.QuasiUpClosed {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= ∀ {x₁ x₂ x₃} {y₃}
, A₁.join x₁ x₂ x₃
→ ¬ x₁ ∈ r.Ker → ¬ x₂ ∈ r.Ker → r x₃ y₃
→ ∃ y₁' y₂', A₂.join y₁' y₂' y₃ ∧ r x₁ y₁' ∧ r x₂ y₂'
def Rel.UpClosed_iff' {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂)
: r.UpClosed ↔ r.IdealKer ∧ r.QuasiUpClosed
:= begin
apply iff.intro,
{ intro rUC,
apply and.intro,
{ apply UpClosed.IdealKer,
assumption
},
{ intros x₁ x₂ x₃ y₃ Jx Kx₁ Kx₂ Rx₃y₃,
exact rUC Jx Rx₃y₃
}
},
{ intro rH, cases rH with rKI rL,
intros m₁ m₂ m₃ n₃ Jm Rn₃m₃,
have Km₁ : ¬ m₁ ∈ r.Ker, from
begin
intro H,
have Q : m₃ ∈ r.Ker := rKI (λ P C₁ C₂, C₁ Jm) @H,
exact Q _ Rn₃m₃
end,
have Km₂ : ¬ m₂ ∈ r.Ker, from
begin
intro H,
have Q : m₃ ∈ r.Ker := rKI (λ P C₁ C₂, C₁ (A₁.comm Jm)) @H,
exact Q _ Rn₃m₃
end,
apply rL Jm Km₁ Km₂ Rn₃m₃
}
end
-- DownPrime and UpJoin
def Rel.DownPrime {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂)
: Set A₁
:= λ x, ∃ x₂ y₁ y₂ y₃, r x y₁ ∧ r x₂ y₂ ∧ A₂.join y₁ y₂ y₃
def Rel.PreDownPrime {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂)
: Set A₂
:= λ y, ∃ y₂ y₃ x₁ x₂, r x₁ y ∧ r x₂ y₂ ∧ A₂.join y y₂ y₃
def PreDownPrime_DownPrime {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
: r.DownPrime = r.FnInv (GenPrime r.PreDownPrime)
:= begin
apply funext, intro x₁,
apply iff.to_eq, apply iff.intro,
{ intro H,
cases H with x₂ H,
cases H with y₁ H,
cases H with y₂ H,
cases H with y₃ H,
cases H with R₁ H,
cases H with R₂ Jy,
existsi y₁,
refine and.intro _ R₁,
existsi y₁,
refine and.intro _ _,
{ intros P C₁ C₂, exact C₂ rfl },
existsi y₂, existsi y₃,
existsi x₁, existsi x₂,
apply and.intro R₁,
exact and.intro R₂ Jy
},
{ intro H,
cases H with y₁ H,
cases H with H R₁,
cases H with y₁' H,
cases H with Dy₁y₁' H,
cases H with y₂ H,
cases H with y₃ H,
cases H with x₁' H,
cases H with x₂ H,
cases H with R₁' H,
cases H with R₂ Jy,
apply Dy₁y₁' ; clear Dy₁y₁',
{ intros y₁'' Jy',
apply A₂.assoc (A₂.comm Jy') Jy,
intro a,
existsi x₂,
existsi y₁, existsi y₂, existsi a.x,
apply and.intro R₁,
apply and.intro R₂,
exact a.J₁
},
{ intro E, subst E,
existsi x₂,
existsi y₁, existsi y₂, existsi y₃,
exact and.intro R₁ (and.intro R₂ Jy),
}
}
end
def FnPrimePres.DownPrime.Prime {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
(rPP : r.FnPrimePres)
: r.DownPrime.Prime
:= begin
rw PreDownPrime_DownPrime,
apply rPP,
apply GenPrime.Prime
end
def UpClosed.DownPrime.Prime {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
(rUC : r.UpClosed)
: r.DownPrime.Prime
:= begin
intros x₁ x₂ x₃ Jx Dx₃,
cases Dx₃ with x₃' Dx₃,
cases Dx₃ with y₁ Dx₃,
cases Dx₃ with y₂ Dx₃,
cases Dx₃ with y₃ Dx₃,
cases Dx₃ with Rx₃y₁ Dx₃,
cases Dx₃ with Rx₃y₂ Jx₃,
have Q := rUC Jx Rx₃y₁,
cases Q with y₁₁ Q,
cases Q with y₁₂ Q,
cases Q with Jy₁ Q,
apply or.inl,
existsi x₂,
existsi y₁₁, existsi y₁₂, existsi y₁,
apply and.intro Q.1,
exact and.intro Q.2 Jy₁
end
def Rel.UpJoin {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂)
: Set A₂
:= λ y, ∃ x₁ x₂ x, r x y ∧ A₁.join x₁ x₂ x
def Rel.PreUpJoin {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂)
: Set A₁
:= λ x, ∃ x₁ x₂ y, r x y ∧ A₁.join x₁ x₂ x
def PreUpJoin_UpJoin {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
: r.UpJoin = r.Fn (JoinClosure r.PreUpJoin)
:= begin
apply funext, intro y,
apply iff.to_eq, apply iff.intro,
{ intro H,
cases H with x₁ H,
cases H with x₂ H,
cases H with x H,
cases H with R₃ Jx,
existsi x,
refine and.intro _ R₃,
apply JoinClosure.gen,
existsi x₁, existsi x₂, existsi y,
exact and.intro R₃ Jx
},
{ intro H,
cases H with x H,
cases H with H R₃,
cases H with H H,
{ cases H with x₁ H,
cases H with x₂ H,
cases H with y' H,
cases H with R₃' Jx,
existsi x₁, existsi x₂, existsi x,
exact and.intro R₃ Jx
},
{ existsi x₁, existsi x₂, existsi x,
apply and.intro R₃,
assumption
}
}
end
def FnJoinClosedPres.UpJoin.JoinClosed {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
(rJP : r.FnJoinClosedPres)
: r.UpJoin.JoinClosed
:= begin
rw PreUpJoin_UpJoin,
apply rJP,
apply JoinClosure.JoinClosed
end
def DownClosed.UpJoin.JoinClosed {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
(rDC : r.DownClosed)
: r.UpJoin.JoinClosed
:= begin
intros y₁ y₂ y₃ Jy Uy₁ Uy₂,
cases Uy₁ with x₁₁ Uy₁,
cases Uy₁ with x₁₂ Uy₁,
cases Uy₁ with x₁₃ Uy₁,
cases Uy₁ with Rx₁₃y₁ Uy₁,
cases Uy₂ with x₂₁ Uy₂,
cases Uy₂ with x₂₂ Uy₂,
cases Uy₂ with x₂₃ Uy₂,
cases Uy₂ with Rx₂₃y₂ Uy₂,
have Q := rDC Rx₁₃y₁ Rx₂₃y₂ Jy,
cases Q with x₃₃ Q,
existsi x₁₃, existsi x₂₃, existsi x₃₃,
exact Q
end
def UpJoin_PreDownPrime {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
(rUC : r.UpClosed)
: r.UpJoin ⊆ JoinClosure r.PreDownPrime
:= begin
intros y H,
cases H with x₁ H,
cases H with x₂ H,
cases H with x₃ H,
cases H with R₃ Jx,
have Q := rUC Jx R₃,
cases Q with y₁ Q,
cases Q with y₂ Q,
cases Q with Jy Q,
cases Q with R₁ R₂,
apply JoinClosure.mul Jy,
{ apply JoinClosure.gen,
existsi y₂, existsi y,
existsi x₁, existsi x₂,
apply and.intro R₁,
exact and.intro R₂ Jy
},
{ apply JoinClosure.gen,
existsi y₁, existsi y,
existsi x₂, existsi x₁,
apply and.intro R₂,
exact and.intro R₁ (A₂.comm Jy)
}
end
def DownClosed.DownPrime_PreUpJoin {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
(rDC : r.DownClosed)
: r.DownPrime ⊆ GenPrime r.PreUpJoin
:= begin
intros x₁ H,
cases H with x₂ H,
cases H with y₁ H,
cases H with y₂ H,
cases H with y₃ H,
cases H with R₁ H,
cases H with R₂ Jy,
have Q := rDC R₁ R₂ Jy,
cases Q with x₃ Q,
existsi x₃,
apply and.intro,
{ intros P C₁ C₂, exact C₁ Q.2 },
{ existsi x₁, existsi x₂, existsi y₃, exact Q }
end
def UpClosed.DownPrime_PreUpJoin {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
(rUC : r.UpClosed)
{x x₂' x₃'}
(Jx' : A₁.join x x₂' x₃')
(H : x₃' ∈ r.PreUpJoin)
: x ∈ r.DownPrime
:= begin
cases H with x₃ H,
cases H with x₁ H,
cases H with y H,
cases H with R₃ Jx,
have Q := rUC Jx' R₃,
cases Q with y₁ Q,
cases Q with y₂ Q,
cases Q with Jy Q,
cases Q with R₁ R₂,
existsi x₂',
existsi y₁, existsi y₂, existsi y,
apply and.intro R₁,
exact and.intro R₂ Jy
end
def Flat.DownPrime_PreUpJoin {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
(rUC : r.UpClosed)
(rDC : r.DownClosed)
: r.DownPrime ∪ r.PreUpJoin = GenPrime r.PreUpJoin
:= begin
apply funext, intro x,
apply iff.to_eq, apply iff.intro,
{ intro H, cases H with H H,
{ exact DownClosed.DownPrime_PreUpJoin @rDC H },
{ exact GenPrime.mem _ H }
},
{ intro H, cases H with x' H,
cases H with Dxx' H,
apply Dxx',
{ intros x₀ Jx',
exact or.inl (UpClosed.DownPrime_PreUpJoin @rUC Jx' H)
},
{ intro E, subst E, exact or.inr H }
}
end
def Flat.DownPrime_PreUpJoin.Prime {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
(rUC : r.UpClosed)
(rDC : r.DownClosed)
: (r.DownPrime ∪ r.PreUpJoin).Prime
:= begin
rw Flat.DownPrime_PreUpJoin @rUC @rDC,
apply GenPrime.Prime
end
def Rel.WeakUnitPres {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= ∀ x, A₁.Unit x → ∃ y, r x y ∧ A₂.Unit y
def UpClosed.AlmostUnitPres {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
(rUC : r.UpClosed)
(H : ∃ x y, r x y ∧ A₁.Unit x ∧ A₂.Unit y)
: r.WeakUnitPres
:= begin
intros x Hx,
cases H with x₀ H,
cases H with y₀ H,
cases H with R₀ H,
cases H with Hx₀ Hy₀,
apply Hx x₀,
{ intros x' Jx,
have Q := rUC Jx R₀,
cases Q with y Q,
cases Q with y' Q,
cases Q with Jy Q,
existsi y,
apply and.intro Q.1,
have Dyy₀ : A₂.Divides y y₀ := λ P C₁ C₂, C₁ Jy,
exact Unit.Divides Hy₀ _ Dyy₀
},
{ intro E, subst E,
existsi y₀,
exact and.intro R₀ Hy₀
}
end
def Rel.UpUnitPres {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= r.Fn A₁.LinearUnit ⊆ A₂.LinearUnit
def Rel.IntegralPres {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= ∀ {I : Set A₂} (Iintegral : I.Integral)
, (r.FnInv I).Integral
def UnitPres.IntegralPres {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} {r : Rel A₁ A₂}
: r.UpUnitPres ↔ r.IntegralPres
:= begin
apply iff.intro,
{ intro Hr,
intros I Iintegral,
intros x Hy Hx,
cases Hy with y Hy,
cases Hy with Iy Rxy,
apply Iintegral y Iy,
apply Hr,
existsi x,
exact and.intro Hx Rxy
},
{ intro Hr,
intros y H,
cases H with x H,
cases H with Hx Rxy,
apply @classical.by_contradiction (y ∈ A₂.LinearUnit),
intro F,
have Q : @Set.Integral A₂ (eq y), from
begin
intros y' Hy',
have E : y = y' := Hy', subst E,
exact F
end,
have Q' := Hr Q,
have Q'' : x ∈ Rel.FnInv r (eq y), from
begin
existsi y,
exact and.intro rfl Rxy
end,
exact Q' x Q'' Hx
}
end
def Rel.DownUnitPres {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= A₂.LinearUnit ⊆ r.Fn A₁.LinearUnit
def Reflexive.DownUnitPres {A : Alg.{ℓ₁}} (r : Rel A A)
(r_refl : ∀ a, r a a)
: r.DownUnitPres
:= begin
intros x Hx,
existsi x,
exact and.intro Hx (r_refl x)
end
def Rel.RationalPres {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= ∀ {R : Set A₁} (Rrational : R.Rational)
, (r.Fn R).Rational
def UnitPres.RationalPres {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂)
: r.DownUnitPres ↔ r.RationalPres
:= begin
apply iff.intro,
{ intro Hr,
intros R Rrational,
intros x Ux,
cases Hr Ux with y Hy,
existsi y,
refine and.intro _ Hy.2,
exact Rrational Hy.1
},
{ intro Hr,
intros y Hy,
refine Hr _ Hy,
intros x Hx,
exact Hx
}
end
def Rel.WeakIdPres {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= ∀ x y, r x y → A₁.WeakIdentity x → A₂.WeakIdentity y
def Rel.FnGenPres {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= ∀ {p : Set A₁} (pNG : p.Generating)
, (r.Fn p).Generating
def Rel.FnNonGenPres {A₁ : Alg.{ℓ₁}} {A₂ : Alg.{ℓ₂}} (r : Rel A₁ A₂) : Prop
:= ∀ {p : Set A₂} (pNG : p.NonGenerating)
, (r.FnInv p).NonGenerating
-- Local and confined sets
def Rel.Local {A : Alg.{ℓ₁}} (r : Rel A A) (S : Set A)
: Prop
:= r.Fn S ⊆ S ∪ r.increasing
def Rel.Local.Fn {A : Alg.{ℓ₁}} (S : Set A) (r : Rel A A)
(r_trans : r.Trans)
: r.Local (r.Fn S)
:= begin
intros z H,
cases H with y H,
cases H with H Ryz,
cases H with x H,
cases H with HSx Rxy,
apply or.inl,
existsi x,
apply and.intro, assumption,
apply r_trans, repeat { assumption }
end
def Rel.Local.FnInv {A : Alg.{ℓ₁}} (p : Set A) (r : Rel A A)
(r_trans : r.Trans)
(Hp : r.Local p.Compl)
: r.Local (r.FnInv p).Compl
:= begin
intros y H, cases H with x H,
cases H with H Rxy,
apply or.inl,
intro F,
cases F with x' F,
cases F with Hx' Ryx',
apply H,
existsi x',
apply and.intro Hx',
apply r_trans,
repeat { assumption }
end
def Rel.Confined {A : Alg.{ℓ₁}} (r : Rel A A) (p : Set A)
: Prop
:= r.FnInv p ⊆ p
def Rel.Confined.Fn {A : Alg.{ℓ₁}} (r : Rel A A) (S : Set A)
(r_trans : r.Trans)
(HS : r.Confined S.Compl)
: r.Confined (r.Fn S).Compl
:= begin
intros y H,
cases H with z H,
cases H with H Ryz,
intro F,
cases F with x F,
cases F with HSx Rxy,
apply H,
existsi x,
apply and.intro HSx,
apply r_trans, repeat { assumption }
end
def Rel.Confined.FnInv {A : Alg.{ℓ₁}} (r : Rel A A) (p : Set A)
(r_trans : r.Trans)
(Hp : r.Confined p)
: r.Confined (r.FnInv p)
:= begin
intros x H,
cases H with y H,
cases H with H Rxy,
cases H with z H,
cases H with Hpz Ryz,
existsi z,
apply and.intro Hpz,
apply r_trans, repeat { assumption }
end
def Confined.Local {A : Alg.{ℓ₁}} {p : Set A} {r : Rel A A}
(Hp : r.Confined p.Compl)
: r.Local p
:= begin
intros y H,
cases H with x H, cases H with Hpx Rxy,
apply classical.by_contradiction,
intro F,
apply Hp ⟨y, and.intro (λ F', F (or.inl F')) Rxy⟩,
assumption
end
def Local.Confined {A : Alg.{ℓ₁}} {S : Set A} {r : Rel A A}
(HS₁ : r.Local S)
(HS₂ : r.increasing ⊆ S)
: r.Confined S.Compl
:= begin
intros x H,
cases H with y H,
cases H with HSy Rxy,
intro F,
have Q := HS₁ ⟨x, and.intro F Rxy⟩,
cases Q with Q Q,
{ exact HSy Q },
{ exact HSy (HS₂ Q) }
end
def Rel.LocallyUpClosed {A : Alg.{ℓ₁}} {B : Alg.{ℓ₂}} (r: Rel A B) (S : Set A)
: Prop
:= ∀ s x₂ x₃ y₃
(Hs : s ∈ S)
(J : A.join s x₂ x₃)
(R₃ : r x₃ y₃)
, ∃ n₁ n₂, B.join n₁ n₂ y₃ ∧ r s n₁ ∧ r x₂ n₂
def Rel.LocallyDownClosed {A : Alg.{ℓ₁}} {B : Alg.{ℓ₂}} (r: Rel A B) (S : Set B)
: Prop
:= ∀ s x₂ x₃ m₁ m₂
(Hs : s ∈ S)
(J : B.join s x₂ x₃)
(R₁ : r m₁ s)
(R₂ : r m₂ x₂)
, ∃ m₃, r m₃ x₃ ∧ A.join m₁ m₂ m₃
structure Rel.LocallyFlat {A : Alg.{ℓ₁}} (r : Rel A A) (S : Set A) : Prop
:= (up : r.LocallyUpClosed S)
(down : r.LocallyDownClosed S)
def LocallyUpClosed.Union {A : Alg.{ℓ₁}} {B : Alg.{ℓ₂}} {r: Rel A B}
{S₁ S₂ : Set A}
(H₁ : r.LocallyUpClosed S₁)
(H₂ : r.LocallyUpClosed S₂)
: r.LocallyUpClosed (S₁ ∪ S₂)
:= begin
intros s x₂ x₃ y₃ Hs J R₃,
cases Hs with Hs Hs,
{ apply H₁, repeat { assumption } },
{ apply H₂, repeat { assumption } }
end
def LocallyDownClosed.Union {A : Alg.{ℓ₁}} {B : Alg.{ℓ₂}} {r: Rel A B}
{S₁ S₂ : Set B}
(H₁ : r.LocallyDownClosed S₁)
(H₂ : r.LocallyDownClosed S₂)
: r.LocallyDownClosed (S₁ ∪ S₂)
:= begin
intros s x₂ x₃ m₁ m₂ Hs J R₁ R₂,
cases Hs with Hs Hs,
{ apply H₁, repeat { assumption } },
{ apply H₂, repeat { assumption } }
end
def LocallyFlat.Union {A : Alg.{ℓ₁}} {r: Rel A A}
{S₁ S₂ : Set A}
(H₁ : r.LocallyFlat S₁)
(H₂ : r.LocallyFlat S₂)
: r.LocallyFlat (S₁ ∪ S₂)
:= { up := LocallyUpClosed.Union H₁.up H₂.up
, down := LocallyDownClosed.Union H₁.down H₂.down
}
def LocallyUpClosed.Subset {A : Alg.{ℓ₁}} {B : Alg.{ℓ₂}} {r: Rel A B}
(S T : Set A)
(HST : S ⊆ T) (HT : r.LocallyUpClosed T)
: r.LocallyUpClosed S
:= begin
intros s x₂ x₃ y₃ Hs J R₃,
refine HT _ _ _ _ _ J R₃,
apply HST,
assumption
end
def LocallyDownClosed.Subset {A : Alg.{ℓ₁}} {B : Alg.{ℓ₂}} {r: Rel A B}
(S T : Set B)
(HST : S ⊆ T) (HT : r.LocallyDownClosed T)
: r.LocallyDownClosed S
:= begin
intros s x₂ x₃ m₁ m₂ Hs J R₁ R₂,
refine HT _ _ _ _ _ _ J R₁ R₂,
apply HST,
assumption
end
def UpClosed.LocallyUpClosed {A : Alg.{ℓ₁}} {B : Alg.{ℓ₂}} {r: Rel A B}
(rUC : r.UpClosed) (S : Set A)
: r.LocallyUpClosed S
:= begin
intros s x₂ x₃ y₃ Hs J R₃,
exact rUC J R₃
end
def DownClosed.LocallyDownClosed {A : Alg.{ℓ₁}} {B : Alg.{ℓ₂}} {r: Rel A B}
(rDC : r.DownClosed) (S : Set B)
: r.LocallyDownClosed S
:= begin
intros s x₂ x₃ m₁ m₂ Hs J R₁ R₂,
exact rDC R₁ R₂ J
end
-- def Rel.LocallyClosed {A : Alg.{ℓ₁}} (r: Rel A A) (S : Set A)
-- : Prop
-- := r.LocallyUpClosed S ∨ r.LocallyDownClosed S
-- def UpClosed.LocallyClosed {A : Alg.{ℓ₁}} {r: Rel A A}
-- (rUC : r.UpClosed) (S : Set A)
-- : r.LocallyClosed S
-- := or.inl (UpClosed.LocallyUpClosed @rUC S)
-- def DownClosed.LocallyClosed {A : Alg.{ℓ₁}} {r: Rel A A}
-- (rDC : r.DownClosed) (S : Set A)
-- : r.LocallyClosed S
-- := or.inr (DownClosed.LocallyDownClosed @rDC S)
def Rel.Closed {A : Alg.{ℓ₁}} {B : Alg.{ℓ₂}} (r: Rel A B)
: Prop
:= r.UpClosed ∨ r.DownClosed
def Rel.Flip {A : Alg.{ℓ₁}} {B : Alg.{ℓ₂}}
(r: Rel A B)
: Rel B A
:= λ b a, r a b
end Sep
|
de0c118aa4113f6db07ec300787c8b88f4aa21c7 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/data/hash_map.lean | fa351286dacc5626e6dea310cbb2c2f04848b039 | [
"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 | 27,860 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Mario Carneiro
-/
import data.pnat.basic
import data.list.range
import data.array.lemmas
import algebra.group
import data.sigma.basic
universes u v w
/-- `bucket_array α β` is the underlying data type for `hash_map α β`,
an array of linked lists of key-value pairs. -/
def bucket_array (α : Type u) (β : α → Type v) (n : ℕ+) :=
array n (list Σ a, β a)
/-- Make a hash_map index from a `nat` hash value and a (positive) buffer size -/
def hash_map.mk_idx (n : ℕ+) (i : nat) : fin n :=
⟨i % n, nat.mod_lt _ n.2⟩
namespace bucket_array
section
parameters {α : Type u} {β : α → Type v} (hash_fn : α → nat)
variables {n : ℕ+} (data : bucket_array α β n)
instance : inhabited (bucket_array α β n) :=
⟨mk_array _ []⟩
/-- Read the bucket corresponding to an element -/
def read (a : α) : list Σ a, β a :=
let bidx := hash_map.mk_idx n (hash_fn a) in
data.read bidx
/-- Write the bucket corresponding to an element -/
def write (a : α) (l : list Σ a, β a) : bucket_array α β n :=
let bidx := hash_map.mk_idx n (hash_fn a) in
data.write bidx l
/-- Modify (read, apply `f`, and write) the bucket corresponding to an element -/
def modify (a : α) (f : list (Σ a, β a) → list (Σ a, β a)) : bucket_array α β n :=
let bidx := hash_map.mk_idx n (hash_fn a) in
array.write data bidx (f (array.read data bidx))
/-- The list of all key-value pairs in the bucket list -/
def as_list : list Σ a, β a := data.to_list.join
theorem mem_as_list {a : Σ a, β a} : a ∈ data.as_list ↔ ∃i, a ∈ array.read data i :=
have (∃ (l : list (Σ (a : α), β a)) (i : fin (n.val)), a ∈ l ∧ array.read data i = l) ↔
∃ (i : fin (n.val)), a ∈ array.read data i,
by rw exists_swap; exact exists_congr (λ i, by simp),
by simp [as_list]; simpa [array.mem.def, and_comm]
/-- Fold a function `f` over the key-value pairs in the bucket list -/
def foldl {δ : Type w} (d : δ) (f : δ → Π a, β a → δ) : δ :=
data.foldl d (λ b d, b.foldl (λ r a, f r a.1 a.2) d)
theorem foldl_eq {δ : Type w} (d : δ) (f : δ → Π a, β a → δ) :
data.foldl d f = data.as_list.foldl (λ r a, f r a.1 a.2) d :=
by rw [foldl, as_list, list.foldl_join, ← array.to_list_foldl]
end
end bucket_array
namespace hash_map
section
parameters {α : Type u} {β : α → Type v} (hash_fn : α → nat)
/-- Insert the pair `⟨a, b⟩` into the correct location in the bucket array
(without checking for duplication) -/
def reinsert_aux {n} (data : bucket_array α β n) (a : α) (b : β a) : bucket_array α β n :=
data.modify hash_fn a (λl, ⟨a, b⟩ :: l)
theorem mk_as_list (n : ℕ+) : bucket_array.as_list (mk_array n [] : bucket_array α β n) = [] :=
list.eq_nil_iff_forall_not_mem.mpr $ λ x m,
let ⟨i, h⟩ := (bucket_array.mem_as_list _).1 m in h
parameter [decidable_eq α]
/-- Search a bucket for a key `a` and return the value -/
def find_aux (a : α) : list (Σ a, β a) → option (β a)
| [] := none
| (⟨a',b⟩::t) := if h : a' = a then some (eq.rec_on h b) else find_aux t
theorem find_aux_iff {a : α} {b : β a} :
Π {l : list Σ a, β a}, (l.map sigma.fst).nodup → (find_aux a l = some b ↔ sigma.mk a b ∈ l)
| [] nd := ⟨λn, by injection n, false.elim⟩
| (⟨a',b'⟩::t) nd := begin
by_cases a' = a,
{ clear find_aux_iff, subst h,
suffices : b' = b ↔ b' = b ∨ sigma.mk a' b ∈ t, {simpa [find_aux, eq_comm]},
refine (or_iff_left_of_imp (λ m, _)).symm,
have : a' ∉ t.map sigma.fst, from list.not_mem_of_nodup_cons nd,
exact this.elim (list.mem_map_of_mem sigma.fst m) },
{ have : sigma.mk a b ≠ ⟨a', b'⟩,
{ intro e, injection e with e, exact h e.symm },
simp at nd, simp [find_aux, h, ne.symm h, find_aux_iff, nd] }
end
/-- Returns `tt` if the bucket `l` contains the key `a` -/
def contains_aux (a : α) (l : list Σ a, β a) : bool :=
(find_aux a l).is_some
theorem contains_aux_iff {a : α} {l : list Σ a, β a} (nd : (l.map sigma.fst).nodup) :
contains_aux a l ↔ a ∈ l.map sigma.fst :=
begin
unfold contains_aux,
cases h : find_aux a l with b; simp,
{ assume (b : β a) (m : sigma.mk a b ∈ l),
rw (find_aux_iff nd).2 m at h,
contradiction },
{ show ∃ (b : β a), sigma.mk a b ∈ l,
exact ⟨_, (find_aux_iff nd).1 h⟩ },
end
/-- Modify a bucket to replace a value in the list. Leaves the list
unchanged if the key is not found. -/
def replace_aux (a : α) (b : β a) : list (Σ a, β a) → list (Σ a, β a)
| [] := []
| (⟨a', b'⟩::t) := if a' = a then ⟨a, b⟩::t else ⟨a', b'⟩ :: replace_aux t
/-- Modify a bucket to remove a key, if it exists. -/
def erase_aux (a : α) : list (Σ a, β a) → list (Σ a, β a)
| [] := []
| (⟨a', b'⟩::t) := if a' = a then t else ⟨a', b'⟩ :: erase_aux t
/-- The predicate `valid bkts sz` means that `bkts` satisfies the `hash_map`
invariants: There are exactly `sz` elements in it, every pair is in the
bucket determined by its key and the hash function, and no key appears
multiple times in the list. -/
structure valid {n} (bkts : bucket_array α β n) (sz : nat) : Prop :=
(len : bkts.as_list.length = sz)
(idx : ∀ {i} {a : Σ a, β a}, a ∈ array.read bkts i →
mk_idx n (hash_fn a.1) = i)
(nodup : ∀i, ((array.read bkts i).map sigma.fst).nodup)
theorem valid.idx_enum {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz)
{i l} (he : (i, l) ∈ bkts.to_list.enum) {a} {b : β a} (hl : sigma.mk a b ∈ l) :
∃ h, mk_idx n (hash_fn a) = ⟨i, h⟩ :=
(array.mem_to_list_enum.mp he).imp (λ h e, by subst e; exact v.idx hl)
theorem valid.idx_enum_1 {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz)
{i l} (he : (i, l) ∈ bkts.to_list.enum) {a} {b : β a} (hl : sigma.mk a b ∈ l) :
(mk_idx n (hash_fn a)).1 = i :=
let ⟨h, e⟩ := v.idx_enum _ he hl in by rw e; refl
theorem valid.as_list_nodup {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) :
(bkts.as_list.map sigma.fst).nodup :=
begin
suffices : (bkts.to_list.map (list.map sigma.fst)).pairwise list.disjoint,
{ simp [bucket_array.as_list, list.nodup_join, this],
change ∀ l s, array.mem s bkts → list.map sigma.fst s = l → l.nodup,
introv m e, subst e, cases m with i e, subst e,
apply v.nodup },
rw [← list.enum_map_snd bkts.to_list, list.pairwise_map, list.pairwise_map],
have : (bkts.to_list.enum.map prod.fst).nodup := by simp [list.nodup_range],
refine list.pairwise.imp_of_mem _ ((list.pairwise_map _).1 this),
rw prod.forall, intros i l₁,
rw prod.forall, intros j l₂ me₁ me₂ ij,
simp [list.disjoint], intros a b ml₁ b' ml₂,
apply ij, rwa [← v.idx_enum_1 _ me₁ ml₁, ← v.idx_enum_1 _ me₂ ml₂]
end
theorem mk_valid (n : ℕ+) : @valid n (mk_array n []) 0 :=
⟨by simp [mk_as_list], λ i a h, by cases h, λ i, list.nodup_nil⟩
theorem valid.find_aux_iff {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) {a : α}
{b : β a} :
find_aux a (bkts.read hash_fn a) = some b ↔ sigma.mk a b ∈ bkts.as_list :=
(find_aux_iff (v.nodup _)).trans $
by rw bkts.mem_as_list; exact ⟨λ h, ⟨_, h⟩, λ ⟨i, h⟩, (v.idx h).symm ▸ h⟩
theorem valid.contains_aux_iff {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz)
(a : α) :
contains_aux a (bkts.read hash_fn a) ↔ a ∈ bkts.as_list.map sigma.fst :=
by simp [contains_aux, option.is_some_iff_exists, v.find_aux_iff hash_fn]
section
parameters {n : ℕ+} {bkts : bucket_array α β n}
{bidx : fin n} {f : list (Σ a, β a) → list (Σ a, β a)}
(u v1 v2 w : list Σ a, β a)
local notation `L` := array.read bkts bidx
private def bkts' : bucket_array α β n := array.write bkts bidx (f L)
variables (hl : L = u ++ v1 ++ w)
(hfl : f L = u ++ v2 ++ w)
include hl hfl
theorem append_of_modify :
∃ u' w', bkts.as_list = u' ++ v1 ++ w' ∧ bkts'.as_list = u' ++ v2 ++ w' :=
begin
unfold bucket_array.as_list,
have h : bidx.1 < bkts.to_list.length, {simp [bidx.2]},
refine ⟨(bkts.to_list.take bidx.1).join ++ u, w ++ (bkts.to_list.drop (bidx.1+1)).join, _, _⟩,
{ conv { to_lhs,
rw [← list.take_append_drop bidx.1 bkts.to_list, list.drop_eq_nth_le_cons h],
simp [hl] }, simp },
{ conv { to_lhs,
rw [bkts', array.write_to_list, list.update_nth_eq_take_cons_drop _ h],
simp [hfl] }, simp }
end
variables (hvnd : (v2.map sigma.fst).nodup)
(hal : ∀ (a : Σ a, β a), a ∈ v2 → mk_idx n (hash_fn a.1) = bidx)
(djuv : (u.map sigma.fst).disjoint (v2.map sigma.fst))
(djwv : (w.map sigma.fst).disjoint (v2.map sigma.fst))
include hvnd hal djuv djwv
theorem valid.modify {sz : ℕ} (v : valid bkts sz) :
v1.length ≤ sz + v2.length ∧ valid bkts' (sz + v2.length - v1.length) :=
begin
rcases append_of_modify u v1 v2 w hl hfl with ⟨u', w', e₁, e₂⟩,
rw [← v.len, e₁],
suffices : valid bkts' (u' ++ v2 ++ w').length,
{ simpa [ge, add_comm, add_left_comm, nat.le_add_right, nat.add_sub_cancel_left] },
refine ⟨congr_arg _ e₂, λ i a, _, λ i, _⟩,
{ by_cases bidx = i,
{ subst i, rw [bkts', array.read_write, hfl],
have := @valid.idx _ _ _ v bidx a,
simp only [hl, list.mem_append, or_imp_distrib, forall_and_distrib] at this ⊢,
exact ⟨⟨this.1.1, hal _⟩, this.2⟩ },
{ rw [bkts', array.read_write_of_ne _ _ h], apply v.idx } },
{ by_cases bidx = i,
{ subst i, rw [bkts', array.read_write, hfl],
have := @valid.nodup _ _ _ v bidx,
simp [hl, list.nodup_append] at this,
simp [list.nodup_append, this, hvnd, djuv, djwv.symm] },
{ rw [bkts', array.read_write_of_ne _ _ h], apply v.nodup } }
end
end
theorem valid.replace_aux (a : α) (b : β a) : Π (l : list (Σ a, β a)), a ∈ l.map sigma.fst →
∃ (u w : list Σ a, β a) b', l = u ++ [⟨a, b'⟩] ++ w ∧ replace_aux a b l = u ++ [⟨a, b⟩] ++ w
| [] := false.elim
| (⟨a', b'⟩::t) := begin
by_cases e : a' = a,
{ subst a',
suffices : ∃ (u w : list Σ a, β a) (b'' : β a),
(sigma.mk a b') :: t = u ++ ⟨a, b''⟩ :: w ∧
replace_aux a b (⟨a, b'⟩ :: t) = u ++ ⟨a, b⟩ :: w, {simpa},
refine ⟨[], t, b', _⟩, simp [replace_aux] },
{ suffices : ∀ (x : β a) (_ : sigma.mk a x ∈ t), ∃ u w (b'' : β a),
(sigma.mk a' b') :: t = u ++ ⟨a, b''⟩ :: w ∧
(sigma.mk a' b') :: (replace_aux a b t) = u ++ ⟨a, b⟩ :: w,
{ simpa [replace_aux, ne.symm e, e] },
intros x m,
have IH : ∀ (x : β a) (_ : sigma.mk a x ∈ t), ∃ u w (b'' : β a),
t = u ++ ⟨a, b''⟩ :: w ∧ replace_aux a b t = u ++ ⟨a, b⟩ :: w,
{ simpa using valid.replace_aux t },
rcases IH x m with ⟨u, w, b'', hl, hfl⟩,
exact ⟨⟨a', b'⟩ :: u, w, b'', by simp [hl, hfl.symm, ne.symm e]⟩ }
end
theorem valid.replace {n : ℕ+}
{bkts : bucket_array α β n} {sz : ℕ} (a : α) (b : β a)
(Hc : contains_aux a (bkts.read hash_fn a))
(v : valid bkts sz) : valid (bkts.modify hash_fn a (replace_aux a b)) sz :=
begin
have nd := v.nodup (mk_idx n (hash_fn a)),
rcases hash_map.valid.replace_aux a b (array.read bkts (mk_idx n (hash_fn a)))
((contains_aux_iff nd).1 Hc) with ⟨u, w, b', hl, hfl⟩,
simp [hl, list.nodup_append] at nd,
refine (v.modify hash_fn
u [⟨a, b'⟩] [⟨a, b⟩] w hl hfl (list.nodup_singleton _)
(λa' e, by simp at e; rw e)
(λa' e1 e2, _)
(λa' e1 e2, _)).2;
{ revert e1, simp [-sigma.exists] at e2, subst a', simp [nd] }
end
theorem valid.insert {n : ℕ+}
{bkts : bucket_array α β n} {sz : ℕ} (a : α) (b : β a)
(Hnc : ¬ contains_aux a (bkts.read hash_fn a))
(v : valid bkts sz) : valid (reinsert_aux bkts a b) (sz+1) :=
begin
have nd := v.nodup (mk_idx n (hash_fn a)),
refine (v.modify hash_fn
[] [] [⟨a, b⟩] (bkts.read hash_fn a) rfl rfl (list.nodup_singleton _)
(λa' e, by simp at e; rw e)
(λa', false.elim)
(λa' e1 e2, _)).2,
simp [-sigma.exists] at e2, subst a',
exact Hnc ((contains_aux_iff nd).2 e1)
end
theorem valid.erase_aux (a : α) : Π (l : list (Σ a, β a)), a ∈ l.map sigma.fst →
∃ (u w : list Σ a, β a) b, l = u ++ [⟨a, b⟩] ++ w ∧ erase_aux a l = u ++ [] ++ w
| [] := false.elim
| (⟨a', b'⟩::t) := begin
by_cases e : a' = a,
{ subst a',
simpa [erase_aux, and_comm] using show ∃ u w (x : β a),
t = u ++ w ∧ (sigma.mk a b') :: t = u ++ ⟨a, x⟩ :: w,
from ⟨[], t, b', by simp⟩ },
{ simp [erase_aux, e, ne.symm e],
suffices : ∀ (b : β a) (_ : sigma.mk a b ∈ t), ∃ u w (x : β a),
(sigma.mk a' b') :: t = u ++ ⟨a, x⟩ :: w ∧
(sigma.mk a' b') :: (erase_aux a t) = u ++ w,
{ simpa [replace_aux, ne.symm e, e] },
intros b m,
have IH : ∀ (x : β a) (_ : sigma.mk a x ∈ t), ∃ u w (x : β a),
t = u ++ ⟨a, x⟩ :: w ∧ erase_aux a t = u ++ w,
{ simpa using valid.erase_aux t },
rcases IH b m with ⟨u, w, b'', hl, hfl⟩,
exact ⟨⟨a', b'⟩ :: u, w, b'', by simp [hl, hfl.symm]⟩ }
end
theorem valid.erase {n} {bkts : bucket_array α β n} {sz}
(a : α) (Hc : contains_aux a (bkts.read hash_fn a))
(v : valid bkts sz) : valid (bkts.modify hash_fn a (erase_aux a)) (sz-1) :=
begin
have nd := v.nodup (mk_idx n (hash_fn a)),
rcases hash_map.valid.erase_aux a (array.read bkts (mk_idx n (hash_fn a)))
((contains_aux_iff nd).1 Hc) with ⟨u, w, b, hl, hfl⟩,
refine (v.modify hash_fn u [⟨a, b⟩] [] w hl hfl list.nodup_nil _ _ _).2;
simp
end
end
end hash_map
/-- A hash map data structure, representing a finite key-value map
with key type `α` and value type `β` (which may depend on `α`). -/
structure hash_map (α : Type u) [decidable_eq α] (β : α → Type v) :=
(hash_fn : α → nat)
(size : ℕ)
(nbuckets : ℕ+)
(buckets : bucket_array α β nbuckets)
(is_valid : hash_map.valid hash_fn buckets size)
/-- Construct an empty hash map with buffer size `nbuckets` (default 8). -/
def mk_hash_map {α : Type u} [decidable_eq α] {β : α → Type v} (hash_fn : α → nat) (nbuckets := 8) :
hash_map α β :=
let n := if nbuckets = 0 then 8 else nbuckets in
let nz : n > 0 := by abstract { cases nbuckets; simp [if_pos, nat.succ_ne_zero] } in
{ hash_fn := hash_fn,
size := 0,
nbuckets := ⟨n, nz⟩,
buckets := mk_array n [],
is_valid := hash_map.mk_valid _ _ }
namespace hash_map
variables {α : Type u} {β : α → Type v} [decidable_eq α]
/-- Return the value corresponding to a key, or `none` if not found -/
def find (m : hash_map α β) (a : α) : option (β a) :=
find_aux a (m.buckets.read m.hash_fn a)
/-- Return `tt` if the key exists in the map -/
def contains (m : hash_map α β) (a : α) : bool :=
(m.find a).is_some
instance : has_mem α (hash_map α β) := ⟨λa m, m.contains a⟩
/-- Fold a function over the key-value pairs in the map -/
def fold {δ : Type w} (m : hash_map α β) (d : δ) (f : δ → Π a, β a → δ) : δ :=
m.buckets.foldl d f
/-- The list of key-value pairs in the map -/
def entries (m : hash_map α β) : list Σ a, β a :=
m.buckets.as_list
/-- The list of keys in the map -/
def keys (m : hash_map α β) : list α :=
m.entries.map sigma.fst
theorem find_iff (m : hash_map α β) (a : α) (b : β a) :
m.find a = some b ↔ sigma.mk a b ∈ m.entries :=
m.is_valid.find_aux_iff _
theorem contains_iff (m : hash_map α β) (a : α) :
m.contains a ↔ a ∈ m.keys :=
m.is_valid.contains_aux_iff _ _
theorem entries_empty (hash_fn : α → nat) (n) :
(@mk_hash_map α _ β hash_fn n).entries = [] :=
mk_as_list _
theorem keys_empty (hash_fn : α → nat) (n) :
(@mk_hash_map α _ β hash_fn n).keys = [] :=
by dsimp [keys]; rw entries_empty; refl
theorem find_empty (hash_fn : α → nat) (n a) :
(@mk_hash_map α _ β hash_fn n).find a = none :=
by induction h : (@mk_hash_map α _ β hash_fn n).find a; [refl,
{ have := (find_iff _ _ _).1 h, rw entries_empty at this, contradiction }]
theorem not_contains_empty (hash_fn : α → nat) (n a) :
¬ (@mk_hash_map α _ β hash_fn n).contains a :=
by apply bool_iff_false.2; dsimp [contains]; rw [find_empty]; refl
theorem insert_lemma (hash_fn : α → nat) {n n'}
{bkts : bucket_array α β n} {sz} (v : valid hash_fn bkts sz) :
valid hash_fn (bkts.foldl (mk_array _ [] : bucket_array α β n') (reinsert_aux hash_fn)) sz :=
begin
suffices : ∀ (l : list Σ a, β a) (t : bucket_array α β n') sz,
valid hash_fn t sz → ((l ++ t.as_list).map sigma.fst).nodup →
valid hash_fn (l.foldl (λr (a : Σ a, β a), reinsert_aux hash_fn r a.1 a.2) t) (sz + l.length),
{ have p := this bkts.as_list _ _ (mk_valid _ _),
rw [mk_as_list, list.append_nil, zero_add, v.len] at p,
rw bucket_array.foldl_eq,
exact p (v.as_list_nodup _) },
intro l, induction l with c l IH; intros t sz v nd, {exact v},
rw show sz + (c :: l).length = sz + 1 + l.length, by simp [add_comm, add_assoc],
rcases (show (l.map sigma.fst).nodup ∧
((bucket_array.as_list t).map sigma.fst).nodup ∧
c.fst ∉ l.map sigma.fst ∧
c.fst ∉ (bucket_array.as_list t).map sigma.fst ∧
(l.map sigma.fst).disjoint ((bucket_array.as_list t).map sigma.fst),
by simpa [list.nodup_append, not_or_distrib, and_comm, and.left_comm] using nd)
with ⟨nd1, nd2, nm1, nm2, dj⟩,
have v' := v.insert _ _ c.2 (λHc, nm2 $ (v.contains_aux_iff _ c.1).1 Hc),
apply IH _ _ v',
suffices : ∀ ⦃a : α⦄ (b : β a), sigma.mk a b ∈ l →
∀ (b' : β a), sigma.mk a b' ∈ (reinsert_aux hash_fn t c.1 c.2).as_list → false,
{ simpa [list.nodup_append, nd1, v'.as_list_nodup _, list.disjoint] },
intros a b m1 b' m2,
rcases (reinsert_aux hash_fn t c.1 c.2).mem_as_list.1 m2 with ⟨i, im⟩,
have : sigma.mk a b' ∉ array.read t i,
{ intro m3,
have : a ∈ list.map sigma.fst t.as_list :=
list.mem_map_of_mem sigma.fst (t.mem_as_list.2 ⟨_, m3⟩),
exact dj (list.mem_map_of_mem sigma.fst m1) this },
by_cases h : mk_idx n' (hash_fn c.1) = i,
{ subst h,
have e : sigma.mk a b' = ⟨c.1, c.2⟩,
{ simpa [reinsert_aux, bucket_array.modify, array.read_write, this] using im },
injection e with e, subst a,
exact nm1.elim (@list.mem_map_of_mem _ _ sigma.fst _ _ m1) },
{ apply this,
simpa [reinsert_aux, bucket_array.modify, array.read_write_of_ne _ _ h] using im }
end
/-- Insert a key-value pair into the map. (Modifies `m` in-place when applicable) -/
def insert : Π (m : hash_map α β) (a : α) (b : β a), hash_map α β
| ⟨hash_fn, size, n, buckets, v⟩ a b :=
let bkt := buckets.read hash_fn a in
if hc : contains_aux a bkt then
{ hash_fn := hash_fn,
size := size,
nbuckets := n,
buckets := buckets.modify hash_fn a (replace_aux a b),
is_valid := v.replace _ a b hc }
else
let size' := size + 1,
buckets' := buckets.modify hash_fn a (λl, ⟨a, b⟩::l),
valid' := v.insert _ a b hc in
if size' ≤ n then
{ hash_fn := hash_fn,
size := size',
nbuckets := n,
buckets := buckets',
is_valid := valid' }
else
let n' : ℕ+ := ⟨n * 2, mul_pos n.2 dec_trivial⟩,
buckets'' : bucket_array α β n' :=
buckets'.foldl (mk_array _ []) (reinsert_aux hash_fn) in
{ hash_fn := hash_fn,
size := size',
nbuckets := n',
buckets := buckets'',
is_valid := insert_lemma _ valid' }
theorem mem_insert : Π (m : hash_map α β) (a b a' b'),
(sigma.mk a' b' : sigma β) ∈ (m.insert a b).entries ↔
if a = a' then b == b' else sigma.mk a' b' ∈ m.entries
| ⟨hash_fn, size, n, bkts, v⟩ a b a' b' := begin
let bkt := bkts.read hash_fn a,
have nd : (bkt.map sigma.fst).nodup := v.nodup (mk_idx n (hash_fn a)),
have lem : Π (bkts' : bucket_array α β n) (v1 u w)
(hl : bucket_array.as_list bkts = u ++ v1 ++ w)
(hfl : bucket_array.as_list bkts' = u ++ [⟨a, b⟩] ++ w)
(veq : (v1 = [] ∧ ¬ contains_aux a bkt) ∨ ∃b'', v1 = [⟨a, b''⟩]),
sigma.mk a' b' ∈ bkts'.as_list ↔
if a = a' then b == b' else sigma.mk a' b' ∈ bkts.as_list,
{ intros bkts' v1 u w hl hfl veq,
rw [hl, hfl],
by_cases h : a = a',
{ subst a',
suffices : b = b' ∨ sigma.mk a b' ∈ u ∨ sigma.mk a b' ∈ w ↔ b = b',
{ simpa [eq_comm, or.left_comm] },
refine or_iff_left_of_imp (not.elim $ not_or_distrib.2 _),
rcases veq with ⟨rfl, Hnc⟩ | ⟨b'', rfl⟩,
{ have na := (not_iff_not_of_iff $ v.contains_aux_iff _ _).1 Hnc,
simp [hl, not_or_distrib] at na, simp [na] },
{ have nd' := v.as_list_nodup _,
simp [hl, list.nodup_append] at nd', simp [nd'] } },
{ suffices : sigma.mk a' b' ∉ v1, {simp [h, ne.symm h, this]},
rcases veq with ⟨rfl, Hnc⟩ | ⟨b'', rfl⟩; simp [ne.symm h] } },
by_cases Hc : (contains_aux a bkt : Prop),
{ rcases hash_map.valid.replace_aux a b (array.read bkts (mk_idx n (hash_fn a)))
((contains_aux_iff nd).1 Hc) with ⟨u', w', b'', hl', hfl'⟩,
rcases (append_of_modify u' [⟨a, b''⟩] [⟨a, b⟩] w' hl' hfl') with ⟨u, w, hl, hfl⟩,
simpa [insert, @dif_pos (contains_aux a bkt) _ Hc]
using lem _ _ u w hl hfl (or.inr ⟨b'', rfl⟩) },
{ let size' := size + 1,
let bkts' := bkts.modify hash_fn a (λl, ⟨a, b⟩::l),
have mi : sigma.mk a' b' ∈ bkts'.as_list ↔
if a = a' then b == b' else sigma.mk a' b' ∈ bkts.as_list :=
let ⟨u, w, hl, hfl⟩ := append_of_modify [] [] [⟨a, b⟩] _ rfl rfl in
lem bkts' _ u w hl hfl $ or.inl ⟨rfl, Hc⟩,
simp [insert, @dif_neg (contains_aux a bkt) _ Hc],
by_cases h : size' ≤ n,
-- TODO(Mario): Why does the by_cases assumption look different than the stated one?
{ simpa [show size' ≤ n, from h] using mi },
{ let n' : ℕ+ := ⟨n * 2, mul_pos n.2 dec_trivial⟩,
let bkts'' : bucket_array α β n' := bkts'.foldl (mk_array _ []) (reinsert_aux hash_fn),
suffices : sigma.mk a' b' ∈ bkts''.as_list ↔ sigma.mk a' b' ∈ bkts'.as_list.reverse,
{ simpa [show ¬ size' ≤ n, from h, mi] },
rw [show bkts'' = bkts'.as_list.foldl _ _, from bkts'.foldl_eq _ _,
← list.foldr_reverse],
induction bkts'.as_list.reverse with a l IH,
{ simp [mk_as_list] },
{ cases a with a'' b'',
let B := l.foldr (λ (y : sigma β) (x : bucket_array α β n'),
reinsert_aux hash_fn x y.1 y.2) (mk_array n' []),
rcases append_of_modify [] [] [⟨a'', b''⟩] _ rfl rfl with ⟨u, w, hl, hfl⟩,
simp [IH.symm, or.left_comm, show B.as_list = _, from hl,
show (reinsert_aux hash_fn B a'' b'').as_list = _, from hfl] } } }
end
theorem find_insert_eq (m : hash_map α β) (a : α) (b : β a) : (m.insert a b).find a = some b :=
(find_iff (m.insert a b) a b).2 $ (mem_insert m a b a b).2 $ by rw if_pos rfl
theorem find_insert_ne (m : hash_map α β) (a a' : α) (b : β a) (h : a ≠ a') :
(m.insert a b).find a' = m.find a' :=
option.eq_of_eq_some $ λb',
let t := mem_insert m a b a' b' in
(find_iff _ _ _).trans $ iff.trans (by rwa if_neg h at t) (find_iff _ _ _).symm
theorem find_insert (m : hash_map α β) (a' a : α) (b : β a) :
(m.insert a b).find a' = if h : a = a' then some (eq.rec_on h b) else m.find a' :=
if h : a = a' then by rw dif_pos h; exact
match a', h with ._, rfl := find_insert_eq m a b end
else by rw dif_neg h; exact find_insert_ne m a a' b h
/-- Insert a list of key-value pairs into the map. (Modifies `m` in-place when applicable) -/
def insert_all (l : list (Σ a, β a)) (m : hash_map α β) : hash_map α β :=
l.foldl (λ m ⟨a, b⟩, insert m a b) m
/-- Construct a hash map from a list of key-value pairs. -/
def of_list (l : list (Σ a, β a)) (hash_fn) : hash_map α β :=
insert_all l (mk_hash_map hash_fn (2 * l.length))
/-- Remove a key from the map. (Modifies `m` in-place when applicable) -/
def erase (m : hash_map α β) (a : α) : hash_map α β :=
match m with ⟨hash_fn, size, n, buckets, v⟩ :=
if hc : contains_aux a (buckets.read hash_fn a) then
{ hash_fn := hash_fn,
size := size - 1,
nbuckets := n,
buckets := buckets.modify hash_fn a (erase_aux a),
is_valid := v.erase _ a hc }
else m
end
theorem mem_erase : Π (m : hash_map α β) (a a' b'),
(sigma.mk a' b' : sigma β) ∈ (m.erase a).entries ↔
a ≠ a' ∧ sigma.mk a' b' ∈ m.entries
| ⟨hash_fn, size, n, bkts, v⟩ a a' b' := begin
let bkt := bkts.read hash_fn a,
by_cases Hc : (contains_aux a bkt : Prop),
{ let bkts' := bkts.modify hash_fn a (erase_aux a),
suffices : sigma.mk a' b' ∈ bkts'.as_list ↔ a ≠ a' ∧ sigma.mk a' b' ∈ bkts.as_list,
{ simpa [erase, @dif_pos (contains_aux a bkt) _ Hc] },
have nd := v.nodup (mk_idx n (hash_fn a)),
rcases valid.erase_aux a bkt ((contains_aux_iff nd).1 Hc) with ⟨u', w', b, hl', hfl'⟩,
rcases append_of_modify u' [⟨a, b⟩] [] _ hl' hfl' with ⟨u, w, hl, hfl⟩,
suffices : ∀_:sigma.mk a' b' ∈ u ∨ sigma.mk a' b' ∈ w, a ≠ a',
{ have : sigma.mk a' b' ∈ u ∨ sigma.mk a' b' ∈ w ↔ (¬a = a' ∧ a' = a) ∧ b' == b ∨
¬a = a' ∧ (sigma.mk a' b' ∈ u ∨ sigma.mk a' b' ∈ w),
{ simp [eq_comm, not_and_self_iff, and_iff_right_of_imp this] },
simpa [hl, show bkts'.as_list = _, from hfl, and_or_distrib_left,
and_comm, and.left_comm, or.left_comm] },
intros m e, subst a', revert m, apply not_or_distrib.2,
have nd' := v.as_list_nodup _,
simp [hl, list.nodup_append] at nd', simp [nd'] },
{ suffices : ∀_:sigma.mk a' b' ∈ bucket_array.as_list bkts, a ≠ a',
{ simp [erase, @dif_neg (contains_aux a bkt) _ Hc, entries, and_iff_right_of_imp this] },
intros m e, subst a',
exact Hc ((v.contains_aux_iff _ _).2 (list.mem_map_of_mem sigma.fst m)) }
end
theorem find_erase_eq (m : hash_map α β) (a : α) : (m.erase a).find a = none :=
begin
cases h : (m.erase a).find a with b, {refl},
exact absurd rfl ((mem_erase m a a b).1 ((find_iff (m.erase a) a b).1 h)).left
end
theorem find_erase_ne (m : hash_map α β) (a a' : α) (h : a ≠ a') :
(m.erase a).find a' = m.find a' :=
option.eq_of_eq_some $ λb',
(find_iff _ _ _).trans $ (mem_erase m a a' b').trans $
(and_iff_right h).trans (find_iff _ _ _).symm
theorem find_erase (m : hash_map α β) (a' a : α) :
(m.erase a).find a' = if a = a' then none else m.find a' :=
if h : a = a' then by subst a'; simp [find_erase_eq m a]
else by rw if_neg h; exact find_erase_ne m a a' h
section string
variables [has_to_string α] [∀ a, has_to_string (β a)]
open prod
private def key_data_to_string (a : α) (b : β a) (first : bool) : string :=
(if first then "" else ", ") ++ sformat!"{a} ← {b}"
private def to_string (m : hash_map α β) : string :=
"⟨" ++ (fst (fold m ("", tt) (λ p a b, (fst p ++ key_data_to_string a b (snd p), ff)))) ++ "⟩"
instance : has_to_string (hash_map α β) :=
⟨to_string⟩
end string
section format
open format prod
variables [has_to_format α] [∀ a, has_to_format (β a)]
private meta def format_key_data (a : α) (b : β a) (first : bool) : format :=
(if first then to_fmt "" else to_fmt "," ++ line) ++
to_fmt a ++ space ++ to_fmt "←" ++ space ++ to_fmt b
private meta def to_format (m : hash_map α β) : format :=
group $ to_fmt "⟨" ++
nest 1 (fst (fold m (to_fmt "", tt) (λ p a b, (fst p ++ format_key_data a b (snd p), ff)))) ++
to_fmt "⟩"
meta instance : has_to_format (hash_map α β) :=
⟨to_format⟩
end format
end hash_map
|
18b57a2b6dc5cab6407a12759126cc6dbd884be3 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/field_theory/krull_topology.lean | 6f3d2db0657f4dc7fdf123750e4b8f43ba5c03b1 | [
"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 | 13,205 | lean | /-
Copyright (c) 2022 Sebastian Monnet. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Monnet
-/
import field_theory.galois
import topology.algebra.filter_basis
import topology.algebra.open_subgroup
import tactic.by_contra
/-!
# Krull topology
We define the Krull topology on `L ≃ₐ[K] L` for an arbitrary field extension `L/K`. In order to do
this, we first define a `group_filter_basis` on `L ≃ₐ[K] L`, whose sets are `E.fixing_subgroup` for
all intermediate fields `E` with `E/K` finite dimensional.
## Main Definitions
- `finite_exts K L`. Given a field extension `L/K`, this is the set of intermediate fields that are
finite-dimensional over `K`.
- `fixed_by_finite K L`. Given a field extension `L/K`, `fixed_by_finite K L` is the set of
subsets `Gal(L/E)` of `Gal(L/K)`, where `E/K` is finite
- `gal_basis K L`. Given a field extension `L/K`, this is the filter basis on `L ≃ₐ[K] L` whose
sets are `Gal(L/E)` for intermediate fields `E` with `E/K` finite.
- `gal_group_basis K L`. This is the same as `gal_basis K L`, but with the added structure
that it is a group filter basis on `L ≃ₐ[K] L`, rather than just a filter basis.
- `krull_topology K L`. Given a field extension `L/K`, this is the topology on `L ≃ₐ[K] L`, induced
by the group filter basis `gal_group_basis K L`.
## Main Results
- `krull_topology_t2 K L`. For an integral field extension `L/K`, the topology `krull_topology K L`
is Hausdorff.
- `krull_topology_totally_disconnected K L`. For an integral field extension `L/K`, the topology
`krull_topology K L` is totally disconnected.
## Notations
- In docstrings, we will write `Gal(L/E)` to denote the fixing subgroup of an intermediate field
`E`. That is, `Gal(L/E)` is the subgroup of `L ≃ₐ[K] L` consisting of automorphisms that fix
every element of `E`. In particular, we distinguish between `L ≃ₐ[E] L` and `Gal(L/E)`, since the
former is defined to be a subgroup of `L ≃ₐ[K] L`, while the latter is a group in its own right.
## Implementation Notes
- `krull_topology K L` is defined as an instance for type class inference.
-/
open_locale classical
/-- Mapping intermediate fields along algebra equivalences preserves the partial order -/
lemma intermediate_field.map_mono {K L M : Type*} [field K] [field L] [field M]
[algebra K L] [algebra K M] {E1 E2 : intermediate_field K L}
(e : L ≃ₐ[K] M) (h12 : E1 ≤ E2) : E1.map e.to_alg_hom ≤ E2.map e.to_alg_hom :=
set.image_subset e h12
/-- Mapping intermediate fields along the identity does not change them -/
lemma intermediate_field.map_id {K L : Type*} [field K] [field L] [algebra K L]
(E : intermediate_field K L) :
E.map (alg_hom.id K L) = E :=
set_like.coe_injective $ set.image_id _
/-- Mapping a finite dimensional intermediate field along an algebra equivalence gives
a finite-dimensional intermediate field. -/
instance im_finite_dimensional {K L : Type*} [field K] [field L] [algebra K L]
{E : intermediate_field K L} (σ : L ≃ₐ[K] L) [finite_dimensional K E]:
finite_dimensional K (E.map σ.to_alg_hom) :=
linear_equiv.finite_dimensional (intermediate_field.intermediate_field_map σ E).to_linear_equiv
/-- Given a field extension `L/K`, `finite_exts K L` is the set of
intermediate field extensions `L/E/K` such that `E/K` is finite -/
def finite_exts (K : Type*) [field K] (L : Type*) [field L] [algebra K L] :
set (intermediate_field K L) :=
{E | finite_dimensional K E}
/-- Given a field extension `L/K`, `fixed_by_finite K L` is the set of
subsets `Gal(L/E)` of `L ≃ₐ[K] L`, where `E/K` is finite -/
def fixed_by_finite (K L : Type*) [field K] [field L] [algebra K L]: set (subgroup (L ≃ₐ[K] L)) :=
intermediate_field.fixing_subgroup '' (finite_exts K L)
/-- For an field extension `L/K`, the intermediate field `K` is finite-dimensional over `K` -/
lemma intermediate_field.finite_dimensional_bot (K L : Type*) [field K]
[field L] [algebra K L] : finite_dimensional K (⊥ : intermediate_field K L) :=
finite_dimensional_of_dim_eq_one intermediate_field.dim_bot
/-- This lemma says that `Gal(L/K) = L ≃ₐ[K] L` -/
lemma intermediate_field.fixing_subgroup.bot {K L : Type*} [field K]
[field L] [algebra K L] :
intermediate_field.fixing_subgroup (⊥ : intermediate_field K L) = ⊤ :=
begin
ext f,
refine ⟨λ _, subgroup.mem_top _, λ _, _⟩,
rintro ⟨x, hx : x ∈ (⊥ : intermediate_field K L)⟩,
rw intermediate_field.mem_bot at hx,
rcases hx with ⟨y, rfl⟩,
exact f.commutes y,
end
/-- If `L/K` is a field extension, then we have `Gal(L/K) ∈ fixed_by_finite K L` -/
lemma top_fixed_by_finite {K L : Type*} [field K] [field L] [algebra K L] :
⊤ ∈ fixed_by_finite K L :=
⟨⊥, intermediate_field.finite_dimensional_bot K L, intermediate_field.fixing_subgroup.bot⟩
/-- If `E1` and `E2` are finite-dimensional intermediate fields, then so is their compositum.
This rephrases a result already in mathlib so that it is compatible with our type classes -/
lemma finite_dimensional_sup {K L: Type*} [field K] [field L] [algebra K L]
(E1 E2 : intermediate_field K L) (h1 : finite_dimensional K E1)
(h2 : finite_dimensional K E2) : finite_dimensional K ↥(E1 ⊔ E2) :=
by exactI intermediate_field.finite_dimensional_sup E1 E2
/-- An element of `L ≃ₐ[K] L` is in `Gal(L/E)` if and only if it fixes every element of `E`-/
lemma intermediate_field.mem_fixing_subgroup_iff {K L : Type*} [field K] [field L] [algebra K L]
(E : intermediate_field K L) (σ : (L ≃ₐ[K] L)) :
σ ∈ E.fixing_subgroup ↔∀ (x : L), x ∈ E → σ x = x :=
⟨λ hσ x hx, hσ ⟨x, hx⟩, λ h ⟨x, hx⟩, h x hx⟩
/-- The map `E ↦ Gal(L/E)` is inclusion-reversing -/
lemma intermediate_field.fixing_subgroup.antimono {K L : Type*} [field K] [field L] [algebra K L]
{E1 E2 : intermediate_field K L} (h12 : E1 ≤ E2) : E2.fixing_subgroup ≤ E1.fixing_subgroup :=
begin
rintro σ hσ ⟨x, hx⟩,
exact hσ ⟨x, h12 hx⟩,
end
/-- Given a field extension `L/K`, `gal_basis K L` is the filter basis on `L ≃ₐ[K] L` whose sets
are `Gal(L/E)` for intermediate fields `E` with `E/K` finite dimensional -/
def gal_basis (K L : Type*) [field K] [field L] [algebra K L] : filter_basis (L ≃ₐ[K] L) :=
{ sets := subgroup.carrier '' (fixed_by_finite K L),
nonempty := ⟨⊤, ⊤, top_fixed_by_finite, rfl⟩,
inter_sets :=
begin
rintros X Y ⟨H1, ⟨E1, h_E1, rfl⟩, rfl⟩ ⟨H2, ⟨E2, h_E2, rfl⟩, rfl⟩,
use (intermediate_field.fixing_subgroup (E1 ⊔ E2)).carrier,
refine ⟨⟨_, ⟨_, finite_dimensional_sup E1 E2 h_E1 h_E2, rfl⟩, rfl⟩, _⟩,
rw set.subset_inter_iff,
exact ⟨intermediate_field.fixing_subgroup.antimono le_sup_left,
intermediate_field.fixing_subgroup.antimono le_sup_right⟩,
end }
/-- A subset of `L ≃ₐ[K] L` is a member of `gal_basis K L` if and only if it is the underlying set
of `Gal(L/E)` for some finite subextension `E/K`-/
lemma mem_gal_basis_iff (K L : Type*) [field K] [field L] [algebra K L]
(U : set (L ≃ₐ[K] L)) : U ∈ gal_basis K L ↔ U ∈ subgroup.carrier '' (fixed_by_finite K L) :=
iff.rfl
/-- For a field extension `L/K`, `gal_group_basis K L` is the group filter basis on `L ≃ₐ[K] L`
whose sets are `Gal(L/E)` for finite subextensions `E/K` -/
def gal_group_basis (K L : Type*) [field K] [field L] [algebra K L] :
group_filter_basis (L ≃ₐ[K] L) :=
{ to_filter_basis := gal_basis K L,
one' := λ U ⟨H, hH, h2⟩, h2 ▸ H.one_mem,
mul' := λ U hU, ⟨U, hU, begin
rcases hU with ⟨H, hH, rfl⟩,
rintros x ⟨a, b, haH, hbH, rfl⟩,
exact H.mul_mem haH hbH,
end⟩,
inv' := λ U hU, ⟨U, hU, begin
rcases hU with ⟨H, hH, rfl⟩,
exact H.inv_mem',
end⟩,
conj' :=
begin
rintros σ U ⟨H, ⟨E, hE, rfl⟩, rfl⟩,
let F : intermediate_field K L := E.map (σ.symm.to_alg_hom),
refine ⟨F.fixing_subgroup.carrier, ⟨⟨F.fixing_subgroup, ⟨F,
_, rfl⟩, rfl⟩, λ g hg, _⟩⟩,
{ apply im_finite_dimensional σ.symm,
exact hE },
change σ * g * σ⁻¹ ∈ E.fixing_subgroup,
rw intermediate_field.mem_fixing_subgroup_iff,
intros x hx,
change σ(g(σ⁻¹ x)) = x,
have h_in_F : σ⁻¹ x ∈ F := ⟨x, hx, by {dsimp, rw ← alg_equiv.inv_fun_eq_symm, refl }⟩,
have h_g_fix : g (σ⁻¹ x) = (σ⁻¹ x),
{ rw [subgroup.mem_carrier, intermediate_field.mem_fixing_subgroup_iff F g] at hg,
exact hg (σ⁻¹ x) h_in_F },
rw h_g_fix,
change σ(σ⁻¹ x) = x,
exact alg_equiv.apply_symm_apply σ x,
end }
/-- For a field extension `L/K`, `krull_topology K L` is the topological space structure on
`L ≃ₐ[K] L` induced by the group filter basis `gal_group_basis K L` -/
instance krull_topology (K L : Type*) [field K] [field L] [algebra K L] :
topological_space (L ≃ₐ[K] L) :=
group_filter_basis.topology (gal_group_basis K L)
/-- For a field extension `L/K`, the Krull topology on `L ≃ₐ[K] L` makes it a topological group. -/
instance (K L : Type*) [field K] [field L] [algebra K L] :
topological_group (L ≃ₐ[K] L) :=
group_filter_basis.is_topological_group (gal_group_basis K L)
section krull_t2
open_locale topological_space filter
/-- Let `L/E/K` be a tower of fields with `E/K` finite. Then `Gal(L/E)` is an open subgroup of
`L ≃ₐ[K] L`. -/
lemma intermediate_field.fixing_subgroup_is_open {K L : Type*} [field K] [field L] [algebra K L]
(E : intermediate_field K L) [finite_dimensional K E] :
is_open (E.fixing_subgroup : set (L ≃ₐ[K] L)) :=
begin
have h_basis : E.fixing_subgroup.carrier ∈ (gal_group_basis K L) :=
⟨E.fixing_subgroup, ⟨E, _inst_4, rfl⟩, rfl⟩,
have h_nhd := group_filter_basis.mem_nhds_one (gal_group_basis K L) h_basis,
rw mem_nhds_iff at h_nhd,
rcases h_nhd with ⟨U, hU_le, hU_open, h1U⟩,
exact subgroup.is_open_of_one_mem_interior ⟨U, ⟨hU_open, hU_le⟩, h1U⟩,
end
/-- Given a tower of fields `L/E/K`, with `E/K` finite, the subgroup `Gal(L/E) ≤ L ≃ₐ[K] L` is
closed. -/
lemma intermediate_field.fixing_subgroup_is_closed {K L : Type*} [field K] [field L] [algebra K L]
(E : intermediate_field K L) [finite_dimensional K E] :
is_closed (E.fixing_subgroup : set (L ≃ₐ[K] L)) :=
open_subgroup.is_closed ⟨E.fixing_subgroup, E.fixing_subgroup_is_open⟩
/-- If `L/K` is an algebraic extension, then the Krull topology on `L ≃ₐ[K] L` is Hausdorff. -/
lemma krull_topology_t2 {K L : Type*} [field K] [field L] [algebra K L]
(h_int : algebra.is_integral K L) : t2_space (L ≃ₐ[K] L) :=
{ t2 := λ f g hfg,
begin
let φ := f⁻¹ * g,
cases (fun_like.exists_ne hfg) with x hx,
have hφx : φ x ≠ x,
{ apply ne_of_apply_ne f,
change f (f.symm (g x)) ≠ f x,
rw [alg_equiv.apply_symm_apply f (g x), ne_comm],
exact hx },
let E : intermediate_field K L := intermediate_field.adjoin K {x},
let h_findim : finite_dimensional K E :=
intermediate_field.adjoin.finite_dimensional (h_int x),
let H := E.fixing_subgroup,
have h_basis : (H : set (L ≃ₐ[K] L)) ∈ gal_group_basis K L := ⟨H, ⟨E, ⟨h_findim, rfl⟩⟩, rfl⟩,
have h_nhd := group_filter_basis.mem_nhds_one (gal_group_basis K L) h_basis,
rw mem_nhds_iff at h_nhd,
rcases h_nhd with ⟨W, hWH, hW_open, hW_1⟩,
refine ⟨left_coset f W, left_coset g W,
⟨hW_open.left_coset f, hW_open.left_coset g, ⟨1, hW_1, mul_one _⟩, ⟨1, hW_1, mul_one _⟩, _⟩⟩,
rintro σ ⟨⟨w1, hw1, h⟩, w2, hw2, hgw2⟩,
rw ← hgw2 at h,
rw [eq_inv_mul_iff_mul_eq.symm, ← mul_assoc, mul_inv_eq_iff_eq_mul.symm] at h,
have h_in_H : w1 * w2⁻¹ ∈ H := H.mul_mem (hWH hw1) (H.inv_mem (hWH hw2)),
rw h at h_in_H,
change φ ∈ E.fixing_subgroup at h_in_H,
rw intermediate_field.mem_fixing_subgroup_iff at h_in_H,
specialize h_in_H x,
have hxE : x ∈ E,
{ apply intermediate_field.subset_adjoin,
apply set.mem_singleton },
exact hφx (h_in_H hxE),
end }
end krull_t2
section totally_disconnected
/-- If `L/K` is an algebraic field extension, then the Krull topology on `L ≃ₐ[K] L` is
totally disconnected. -/
lemma krull_topology_totally_disconnected {K L : Type*} [field K] [field L] [algebra K L]
(h_int : algebra.is_integral K L) : is_totally_disconnected (set.univ : set (L ≃ₐ[K] L)) :=
begin
apply is_totally_disconnected_of_clopen_set,
intros σ τ h_diff,
have hστ : σ⁻¹ * τ ≠ 1,
{ rwa [ne.def, inv_mul_eq_one] },
rcases (fun_like.exists_ne hστ) with ⟨x, hx : (σ⁻¹ * τ) x ≠ x⟩,
let E := intermediate_field.adjoin K ({x} : set L),
haveI := intermediate_field.adjoin.finite_dimensional (h_int x),
refine ⟨left_coset σ E.fixing_subgroup,
⟨E.fixing_subgroup_is_open.left_coset σ, E.fixing_subgroup_is_closed.left_coset σ⟩,
⟨1, E.fixing_subgroup.one_mem', by simp⟩, _⟩,
simp only [mem_left_coset_iff, set_like.mem_coe, intermediate_field.mem_fixing_subgroup_iff,
not_forall],
exact ⟨x, intermediate_field.mem_adjoin_simple_self K x, hx⟩,
end
end totally_disconnected
|
450307c82c20da068bec05d0097650a23176a955 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /test/integration.lean | b0fab645e853534dfee7923b4c32b25fe01b79b0 | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,365 | lean | /-
Copyright (c) 2021 Benjamin Davidson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Benjamin Davidson
-/
import analysis.special_functions.integrals
open interval_integral real
open_locale real
/-- constants -/
example : ∫ x : ℝ in 8..11, (1 : ℝ) = 3 := by norm_num
example : ∫ x : ℝ in 5..19, (12 : ℝ) = 168 := by norm_num
/-- the identity function -/
example : ∫ x : ℝ in (-1)..4, x = 15 / 2 := by norm_num
example : ∫ x : ℝ in 4..5, x * 2 = 9 := by norm_num
/-- inverse -/
example : ∫ x : ℝ in 2..3, x⁻¹ = log (3 / 2) := by norm_num
/-- natural powers -/
example : ∫ x : ℝ in 2..4, x ^ (3 : ℕ) = 60 := by norm_num
/-- trigonometric functions -/
example : ∫ x in 0..π, sin x = 2 := by norm_num
example : ∫ x in 0..π/4, cos x = sqrt 2 / 2 := by simp
example : ∫ x in 0..π, 2 * sin x = 4 := by norm_num
example : ∫ x in 0..π/2, cos x / 2 = 1 / 2 := by simp
example : ∫ x : ℝ in 0..1, 1 / (1 + x ^ 2) = π/4 := by simp
/-- the exponential function -/
example : ∫ x in 0..2, -exp x = 1 - exp 2 := by simp
/-- linear combinations (e.g. polynomials) -/
example : ∫ x : ℝ in 0..2, 6*x^5 + 3*x^4 + x^3 - 2*x^2 + x - 7 = 1048 / 15 := by norm_num
example : ∫ x : ℝ in 0..1, exp x + 9 * x^8 + x^3 - x/2 + (1 + x^2)⁻¹ = exp 1 + π / 4 := by norm_num
|
17c118dbe62616d59cd406a13671a9c269f86912 | bb31430994044506fa42fd667e2d556327e18dfe | /src/linear_algebra/quotient.lean | 2e91ca51d780df650ae6d3f9f1fee1d249869284 | [
"Apache-2.0"
] | permissive | sgouezel/mathlib | 0cb4e5335a2ba189fa7af96d83a377f83270e503 | 00638177efd1b2534fc5269363ebf42a7871df9a | refs/heads/master | 1,674,527,483,042 | 1,673,665,568,000 | 1,673,665,568,000 | 119,598,202 | 0 | 0 | null | 1,517,348,647,000 | 1,517,348,646,000 | null | UTF-8 | Lean | false | false | 21,257 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Kevin Buzzard, Yury Kudryashov
-/
import group_theory.quotient_group
import linear_algebra.span
/-!
# Quotients by submodules
* If `p` is a submodule of `M`, `M ⧸ p` is the quotient of `M` with respect to `p`:
that is, elements of `M` are identified if their difference is in `p`. This is itself a module.
-/
-- For most of this file we work over a noncommutative ring
section ring
namespace submodule
variables {R M : Type*} {r : R} {x y : M} [ring R] [add_comm_group M] [module R M]
variables (p p' : submodule R M)
open linear_map quotient_add_group
/-- The equivalence relation associated to a submodule `p`, defined by `x ≈ y` iff `-x + y ∈ p`.
Note this is equivalent to `y - x ∈ p`, but defined this way to be be defeq to the `add_subgroup`
version, where commutativity can't be assumed. -/
def quotient_rel : setoid M :=
quotient_add_group.left_rel p.to_add_subgroup
lemma quotient_rel_r_def {x y : M} : @setoid.r _ (p.quotient_rel) x y ↔ x - y ∈ p :=
iff.trans (by { rw [left_rel_apply, sub_eq_add_neg, neg_add, neg_neg], refl }) neg_mem_iff
/-- The quotient of a module `M` by a submodule `p ⊆ M`. -/
instance has_quotient : has_quotient M (submodule R M) := ⟨λ p, quotient (quotient_rel p)⟩
namespace quotient
/-- Map associating to an element of `M` the corresponding element of `M/p`,
when `p` is a submodule of `M`. -/
def mk {p : submodule R M} : M → M ⧸ p := quotient.mk'
@[simp] theorem mk_eq_mk {p : submodule R M} (x : M) :
(@_root_.quotient.mk _ (quotient_rel p) x) = mk x := rfl
@[simp] theorem mk'_eq_mk {p : submodule R M} (x : M) : (quotient.mk' x : M ⧸ p) = mk x := rfl
@[simp] theorem quot_mk_eq_mk {p : submodule R M} (x : M) : (quot.mk _ x : M ⧸ p) = mk x := rfl
protected theorem eq' {x y : M} : (mk x : M ⧸ p) = mk y ↔ -x + y ∈ p := quotient_add_group.eq
protected theorem eq {x y : M} : (mk x : M ⧸ p) = mk y ↔ x - y ∈ p :=
(p^.quotient.eq').trans (left_rel_apply.symm.trans p.quotient_rel_r_def)
instance : has_zero (M ⧸ p) := ⟨mk 0⟩
instance : inhabited (M ⧸ p) := ⟨0⟩
@[simp] theorem mk_zero : mk 0 = (0 : M ⧸ p) := rfl
@[simp] theorem mk_eq_zero : (mk x : M ⧸ p) = 0 ↔ x ∈ p :=
by simpa using (quotient.eq p : mk x = 0 ↔ _)
instance add_comm_group : add_comm_group (M ⧸ p) :=
quotient_add_group.quotient.add_comm_group p.to_add_subgroup
@[simp] theorem mk_add : (mk (x + y) : M ⧸ p) = mk x + mk y := rfl
@[simp] theorem mk_neg : (mk (-x) : M ⧸ p) = -mk x := rfl
@[simp] theorem mk_sub : (mk (x - y) : M ⧸ p) = mk x - mk y := rfl
section has_smul
variables {S : Type*} [has_smul S R] [has_smul S M] [is_scalar_tower S R M] (P : submodule R M)
instance has_smul' : has_smul S (M ⧸ P) :=
⟨λ a, quotient.map' ((•) a) $ λ x y h, left_rel_apply.mpr $
by simpa [smul_sub] using P.smul_mem (a • 1 : R) (left_rel_apply.mp h)⟩
/-- Shortcut to help the elaborator in the common case. -/
instance has_smul : has_smul R (M ⧸ P) :=
quotient.has_smul' P
@[simp] theorem mk_smul (r : S) (x : M) : (mk (r • x) : M ⧸ p) = r • mk x := rfl
instance smul_comm_class (T : Type*) [has_smul T R] [has_smul T M] [is_scalar_tower T R M]
[smul_comm_class S T M] : smul_comm_class S T (M ⧸ P) :=
{ smul_comm := λ x y, quotient.ind' $ by exact λ z, congr_arg mk (smul_comm _ _ _) }
instance is_scalar_tower (T : Type*) [has_smul T R] [has_smul T M] [is_scalar_tower T R M]
[has_smul S T] [is_scalar_tower S T M] : is_scalar_tower S T (M ⧸ P) :=
{ smul_assoc := λ x y, quotient.ind' $ by exact λ z, congr_arg mk (smul_assoc _ _ _) }
instance is_central_scalar [has_smul Sᵐᵒᵖ R] [has_smul Sᵐᵒᵖ M] [is_scalar_tower Sᵐᵒᵖ R M]
[is_central_scalar S M] : is_central_scalar S (M ⧸ P) :=
{ op_smul_eq_smul := λ x, quotient.ind' $ by exact λ z, congr_arg mk $ op_smul_eq_smul _ _ }
end has_smul
section module
variables {S : Type*}
instance mul_action' [monoid S] [has_smul S R] [mul_action S M] [is_scalar_tower S R M]
(P : submodule R M) : mul_action S (M ⧸ P) :=
function.surjective.mul_action mk (surjective_quot_mk _) P^.quotient.mk_smul
instance mul_action (P : submodule R M) : mul_action R (M ⧸ P) :=
quotient.mul_action' P
instance smul_zero_class' [has_smul S R] [smul_zero_class S M]
[is_scalar_tower S R M]
(P : submodule R M) : smul_zero_class S (M ⧸ P) :=
zero_hom.smul_zero_class ⟨mk, mk_zero _⟩ P^.quotient.mk_smul
instance smul_zero_class (P : submodule R M) : smul_zero_class R (M ⧸ P) :=
quotient.smul_zero_class' P
instance distrib_smul' [has_smul S R] [distrib_smul S M]
[is_scalar_tower S R M]
(P : submodule R M) : distrib_smul S (M ⧸ P) :=
function.surjective.distrib_smul
⟨mk, rfl, λ _ _, rfl⟩ (surjective_quot_mk _) P^.quotient.mk_smul
instance distrib_smul (P : submodule R M) : distrib_smul R (M ⧸ P) :=
quotient.distrib_smul' P
instance distrib_mul_action' [monoid S] [has_smul S R] [distrib_mul_action S M]
[is_scalar_tower S R M]
(P : submodule R M) : distrib_mul_action S (M ⧸ P) :=
function.surjective.distrib_mul_action
⟨mk, rfl, λ _ _, rfl⟩ (surjective_quot_mk _) P^.quotient.mk_smul
instance distrib_mul_action (P : submodule R M) : distrib_mul_action R (M ⧸ P) :=
quotient.distrib_mul_action' P
instance module' [semiring S] [has_smul S R] [module S M] [is_scalar_tower S R M]
(P : submodule R M) : module S (M ⧸ P) :=
function.surjective.module _
⟨mk, rfl, λ _ _, rfl⟩ (surjective_quot_mk _) P^.quotient.mk_smul
instance module (P : submodule R M) : module R (M ⧸ P) :=
quotient.module' P
variables (S)
/-- The quotient of `P` as an `S`-submodule is the same as the quotient of `P` as an `R`-submodule,
where `P : submodule R M`.
-/
def restrict_scalars_equiv [ring S] [has_smul S R] [module S M] [is_scalar_tower S R M]
(P : submodule R M) :
(M ⧸ P.restrict_scalars S) ≃ₗ[S] M ⧸ P :=
{ map_add' := λ x y, quotient.induction_on₂' x y (λ x' y', rfl),
map_smul' := λ c x, quotient.induction_on' x (λ x', rfl),
..quotient.congr_right $ λ _ _, iff.rfl }
@[simp] lemma restrict_scalars_equiv_mk
[ring S] [has_smul S R] [module S M] [is_scalar_tower S R M] (P : submodule R M)
(x : M) : restrict_scalars_equiv S P (mk x) = mk x :=
rfl
@[simp] lemma restrict_scalars_equiv_symm_mk
[ring S] [has_smul S R] [module S M] [is_scalar_tower S R M] (P : submodule R M)
(x : M) : (restrict_scalars_equiv S P).symm (mk x) = mk x :=
rfl
end module
lemma mk_surjective : function.surjective (@mk _ _ _ _ _ p) :=
by { rintros ⟨x⟩, exact ⟨x, rfl⟩ }
lemma nontrivial_of_lt_top (h : p < ⊤) : nontrivial (M ⧸ p) :=
begin
obtain ⟨x, _, not_mem_s⟩ := set_like.exists_of_lt h,
refine ⟨⟨mk x, 0, _⟩⟩,
simpa using not_mem_s
end
end quotient
instance quotient_bot.infinite [infinite M] : infinite (M ⧸ (⊥ : submodule R M)) :=
infinite.of_injective submodule.quotient.mk $ λ x y h, sub_eq_zero.mp $
(submodule.quotient.eq ⊥).mp h
instance quotient_top.unique : unique (M ⧸ (⊤ : submodule R M)) :=
{ default := 0,
uniq := λ x, quotient.induction_on' x $ λ x, (submodule.quotient.eq ⊤).mpr submodule.mem_top }
instance quotient_top.fintype : fintype (M ⧸ (⊤ : submodule R M)) :=
fintype.of_subsingleton 0
variables {p}
lemma subsingleton_quotient_iff_eq_top : subsingleton (M ⧸ p) ↔ p = ⊤ :=
begin
split,
{ rintro h,
refine eq_top_iff.mpr (λ x _, _),
have this : x - 0 ∈ p := (submodule.quotient.eq p).mp (by exactI subsingleton.elim _ _),
rwa sub_zero at this },
{ rintro rfl,
apply_instance }
end
lemma unique_quotient_iff_eq_top : nonempty (unique (M ⧸ p)) ↔ p = ⊤ :=
⟨λ ⟨h⟩, subsingleton_quotient_iff_eq_top.mp (@@unique.subsingleton h),
by { rintro rfl, exact ⟨quotient_top.unique⟩ }⟩
variables (p)
noncomputable instance quotient.fintype [fintype M] (S : submodule R M) :
fintype (M ⧸ S) :=
@@quotient.fintype _ _ (λ _ _, classical.dec _)
lemma card_eq_card_quotient_mul_card [fintype M] (S : submodule R M) [decidable_pred (∈ S)] :
fintype.card M = fintype.card S * fintype.card (M ⧸ S) :=
by { rw [mul_comm, ← fintype.card_prod],
exact fintype.card_congr add_subgroup.add_group_equiv_quotient_times_add_subgroup }
section
variables {M₂ : Type*} [add_comm_group M₂] [module R M₂]
lemma quot_hom_ext ⦃f g : M ⧸ p →ₗ[R] M₂⦄ (h : ∀ x, f (quotient.mk x) = g (quotient.mk x)) :
f = g :=
linear_map.ext $ λ x, quotient.induction_on' x h
/-- The map from a module `M` to the quotient of `M` by a submodule `p` as a linear map. -/
def mkq : M →ₗ[R] M ⧸ p :=
{ to_fun := quotient.mk, map_add' := by simp, map_smul' := by simp }
@[simp] theorem mkq_apply (x : M) : p.mkq x = quotient.mk x := rfl
lemma mkq_surjective (A : submodule R M) : function.surjective A.mkq :=
by rintro ⟨x⟩; exact ⟨x, rfl⟩
end
variables {R₂ M₂ : Type*} [ring R₂] [add_comm_group M₂] [module R₂ M₂] {τ₁₂ : R →+* R₂}
/-- Two `linear_map`s from a quotient module are equal if their compositions with
`submodule.mkq` are equal.
See note [partially-applied ext lemmas]. -/
@[ext]
lemma linear_map_qext ⦃f g : M ⧸ p →ₛₗ[τ₁₂] M₂⦄ (h : f.comp p.mkq = g.comp p.mkq) : f = g :=
linear_map.ext $ λ x, quotient.induction_on' x $ (linear_map.congr_fun h : _)
/-- The map from the quotient of `M` by a submodule `p` to `M₂` induced by a linear map `f : M → M₂`
vanishing on `p`, as a linear map. -/
def liftq (f : M →ₛₗ[τ₁₂] M₂) (h : p ≤ f.ker) : M ⧸ p →ₛₗ[τ₁₂] M₂ :=
{ map_smul' := by rintro a ⟨x⟩; exact f.map_smulₛₗ a x,
..quotient_add_group.lift p.to_add_subgroup f.to_add_monoid_hom h }
@[simp] theorem liftq_apply (f : M →ₛₗ[τ₁₂] M₂) {h} (x : M) :
p.liftq f h (quotient.mk x) = f x := rfl
@[simp] theorem liftq_mkq (f : M →ₛₗ[τ₁₂] M₂) (h) : (p.liftq f h).comp p.mkq = f :=
by ext; refl
/--Special case of `liftq` when `p` is the span of `x`. In this case, the condition on `f` simply
becomes vanishing at `x`.-/
def liftq_span_singleton (x : M) (f : M →ₛₗ[τ₁₂] M₂) (h : f x = 0) : (M ⧸ R ∙ x) →ₛₗ[τ₁₂] M₂ :=
(R ∙ x).liftq f $ by rw [span_singleton_le_iff_mem, linear_map.mem_ker, h]
@[simp] lemma liftq_span_singleton_apply (x : M) (f : M →ₛₗ[τ₁₂] M₂) (h : f x = 0) (y : M) :
liftq_span_singleton x f h (quotient.mk y) = f y := rfl
@[simp] theorem range_mkq : p.mkq.range = ⊤ :=
eq_top_iff'.2 $ by rintro ⟨x⟩; exact ⟨x, rfl⟩
@[simp] theorem ker_mkq : p.mkq.ker = p :=
by ext; simp
lemma le_comap_mkq (p' : submodule R (M ⧸ p)) : p ≤ comap p.mkq p' :=
by simpa using (comap_mono bot_le : p.mkq.ker ≤ comap p.mkq p')
@[simp] theorem mkq_map_self : map p.mkq p = ⊥ :=
by rw [eq_bot_iff, map_le_iff_le_comap, comap_bot, ker_mkq]; exact le_rfl
@[simp] theorem comap_map_mkq : comap p.mkq (map p.mkq p') = p ⊔ p' :=
by simp [comap_map_eq, sup_comm]
@[simp] theorem map_mkq_eq_top : map p.mkq p' = ⊤ ↔ p ⊔ p' = ⊤ :=
by simp only [map_eq_top_iff p.range_mkq, sup_comm, ker_mkq]
variables (q : submodule R₂ M₂)
/-- The map from the quotient of `M` by submodule `p` to the quotient of `M₂` by submodule `q` along
`f : M → M₂` is linear. -/
def mapq (f : M →ₛₗ[τ₁₂] M₂) (h : p ≤ comap f q) :
(M ⧸ p) →ₛₗ[τ₁₂] (M₂ ⧸ q) :=
p.liftq (q.mkq.comp f) $ by simpa [ker_comp] using h
@[simp] theorem mapq_apply (f : M →ₛₗ[τ₁₂] M₂) {h} (x : M) :
mapq p q f h (quotient.mk x) = quotient.mk (f x) := rfl
theorem mapq_mkq (f : M →ₛₗ[τ₁₂] M₂) {h} : (mapq p q f h).comp p.mkq = q.mkq.comp f :=
by ext x; refl
@[simp] lemma mapq_zero (h : p ≤ q.comap (0 : M →ₛₗ[τ₁₂] M₂) := by simp) :
p.mapq q (0 : M →ₛₗ[τ₁₂] M₂) h = 0 :=
by { ext, simp, }
/-- Given submodules `p ⊆ M`, `p₂ ⊆ M₂`, `p₃ ⊆ M₃` and maps `f : M → M₂`, `g : M₂ → M₃` inducing
`mapq f : M ⧸ p → M₂ ⧸ p₂` and `mapq g : M₂ ⧸ p₂ → M₃ ⧸ p₃` then
`mapq (g ∘ f) = (mapq g) ∘ (mapq f)`. -/
lemma mapq_comp {R₃ M₃ : Type*} [ring R₃] [add_comm_group M₃] [module R₃ M₃]
(p₂ : submodule R₂ M₂) (p₃ : submodule R₃ M₃)
{τ₂₃ : R₂ →+* R₃} {τ₁₃ : R →+* R₃} [ring_hom_comp_triple τ₁₂ τ₂₃ τ₁₃]
(f : M →ₛₗ[τ₁₂] M₂) (g : M₂ →ₛₗ[τ₂₃] M₃) (hf : p ≤ p₂.comap f) (hg : p₂ ≤ p₃.comap g)
(h := (hf.trans (comap_mono hg))) :
p.mapq p₃ (g.comp f) h = (p₂.mapq p₃ g hg).comp (p.mapq p₂ f hf) :=
by { ext, simp, }
@[simp] lemma mapq_id (h : p ≤ p.comap linear_map.id := by { rw comap_id, exact le_refl _ }) :
p.mapq p linear_map.id h = linear_map.id :=
by { ext, simp, }
lemma mapq_pow {f : M →ₗ[R] M} (h : p ≤ p.comap f) (k : ℕ)
(h' : p ≤ p.comap (f^k) := p.le_comap_pow_of_le_comap h k) :
p.mapq p (f^k) h' = (p.mapq p f h)^k :=
begin
induction k with k ih,
{ simp [linear_map.one_eq_id], },
{ simp only [linear_map.iterate_succ, ← ih],
apply p.mapq_comp, },
end
theorem comap_liftq (f : M →ₛₗ[τ₁₂] M₂) (h) :
q.comap (p.liftq f h) = (q.comap f).map (mkq p) :=
le_antisymm
(by rintro ⟨x⟩ hx; exact ⟨_, hx, rfl⟩)
(by rw [map_le_iff_le_comap, ← comap_comp, liftq_mkq]; exact le_rfl)
theorem map_liftq [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) (h) (q : submodule R (M ⧸ p)) :
q.map (p.liftq f h) = (q.comap p.mkq).map f :=
le_antisymm
(by rintro _ ⟨⟨x⟩, hxq, rfl⟩; exact ⟨x, hxq, rfl⟩)
(by rintro _ ⟨x, hxq, rfl⟩; exact ⟨quotient.mk x, hxq, rfl⟩)
theorem ker_liftq (f : M →ₛₗ[τ₁₂] M₂) (h) :
ker (p.liftq f h) = (ker f).map (mkq p) := comap_liftq _ _ _ _
theorem range_liftq [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) (h) :
range (p.liftq f h) = range f :=
by simpa only [range_eq_map] using map_liftq _ _ _ _
theorem ker_liftq_eq_bot (f : M →ₛₗ[τ₁₂] M₂) (h) (h' : ker f ≤ p) : ker (p.liftq f h) = ⊥ :=
by rw [ker_liftq, le_antisymm h h', mkq_map_self]
/-- The correspondence theorem for modules: there is an order isomorphism between submodules of the
quotient of `M` by `p`, and submodules of `M` larger than `p`. -/
def comap_mkq.rel_iso :
submodule R (M ⧸ p) ≃o {p' : submodule R M // p ≤ p'} :=
{ to_fun := λ p', ⟨comap p.mkq p', le_comap_mkq p _⟩,
inv_fun := λ q, map p.mkq q,
left_inv := λ p', map_comap_eq_self $ by simp,
right_inv := λ ⟨q, hq⟩, subtype.ext_val $ by simpa [comap_map_mkq p],
map_rel_iff' := λ p₁ p₂, comap_le_comap_iff $ range_mkq _ }
/-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules
of `M`. -/
def comap_mkq.order_embedding :
submodule R (M ⧸ p) ↪o submodule R M :=
(rel_iso.to_rel_embedding $ comap_mkq.rel_iso p).trans (subtype.rel_embedding _ _)
@[simp] lemma comap_mkq_embedding_eq (p' : submodule R (M ⧸ p)) :
comap_mkq.order_embedding p p' = comap p.mkq p' := rfl
lemma span_preimage_eq [ring_hom_surjective τ₁₂] {f : M →ₛₗ[τ₁₂] M₂} {s : set M₂} (h₀ : s.nonempty)
(h₁ : s ⊆ range f) :
span R (f ⁻¹' s) = (span R₂ s).comap f :=
begin
suffices : (span R₂ s).comap f ≤ span R (f ⁻¹' s),
{ exact le_antisymm (span_preimage_le f s) this, },
have hk : ker f ≤ span R (f ⁻¹' s),
{ let y := classical.some h₀, have hy : y ∈ s, { exact classical.some_spec h₀, },
rw ker_le_iff, use [y, h₁ hy], rw ← set.singleton_subset_iff at hy,
exact set.subset.trans subset_span (span_mono (set.preimage_mono hy)), },
rw ← left_eq_sup at hk, rw f.range_coe at h₁,
rw [hk, ←linear_map.map_le_map_iff, map_span, map_comap_eq, set.image_preimage_eq_of_subset h₁],
exact inf_le_right,
end
/-- If `P` is a submodule of `M` and `Q` a submodule of `N`,
and `f : M ≃ₗ N` maps `P` to `Q`, then `M ⧸ P` is equivalent to `N ⧸ Q`. -/
@[simps] def quotient.equiv {N : Type*} [add_comm_group N] [module R N]
(P : submodule R M) (Q : submodule R N)
(f : M ≃ₗ[R] N) (hf : P.map f = Q) : (M ⧸ P) ≃ₗ[R] N ⧸ Q :=
{ to_fun := P.mapq Q (f : M →ₗ[R] N) (λ x hx, hf ▸ submodule.mem_map_of_mem hx),
inv_fun := Q.mapq P (f.symm : N →ₗ[R] M) (λ x hx, begin
rw [← hf, submodule.mem_map] at hx,
obtain ⟨y, hy, rfl⟩ := hx,
simpa
end),
left_inv := λ x, quotient.induction_on' x (by simp),
right_inv := λ x, quotient.induction_on' x (by simp),
.. P.mapq Q (f : M →ₗ[R] N) (λ x hx, hf ▸ submodule.mem_map_of_mem hx) }
@[simp] lemma quotient.equiv_symm {R M N : Type*} [comm_ring R]
[add_comm_group M] [module R M] [add_comm_group N] [module R N]
(P : submodule R M) (Q : submodule R N)
(f : M ≃ₗ[R] N) (hf : P.map f = Q) :
(quotient.equiv P Q f hf).symm =
quotient.equiv Q P f.symm ((submodule.map_symm_eq_iff f).mpr hf) :=
rfl
@[simp] lemma quotient.equiv_trans {N O : Type*} [add_comm_group N] [module R N]
[add_comm_group O] [module R O]
(P : submodule R M) (Q : submodule R N) (S : submodule R O)
(e : M ≃ₗ[R] N) (f : N ≃ₗ[R] O)
(he : P.map e = Q) (hf : Q.map f = S) (hef : P.map (e.trans f) = S) :
quotient.equiv P S (e.trans f) hef = (quotient.equiv P Q e he).trans (quotient.equiv Q S f hf) :=
begin
ext,
-- `simp` can deal with `hef` depending on `e` and `f`
simp only [quotient.equiv_apply, linear_equiv.trans_apply, linear_equiv.coe_trans],
-- `rw` can deal with `mapq_comp` needing extra hypotheses coming from the RHS
rw [mapq_comp, linear_map.comp_apply]
end
end submodule
open submodule
namespace linear_map
section ring
variables {R M R₂ M₂ R₃ M₃ : Type*}
variables [ring R] [ring R₂] [ring R₃]
variables [add_comm_monoid M] [add_comm_group M₂] [add_comm_monoid M₃]
variables [module R M] [module R₂ M₂] [module R₃ M₃]
variables {τ₁₂ : R →+* R₂} {τ₂₃ : R₂ →+* R₃} {τ₁₃ : R →+* R₃}
variables [ring_hom_comp_triple τ₁₂ τ₂₃ τ₁₃] [ring_hom_surjective τ₁₂]
lemma range_mkq_comp (f : M →ₛₗ[τ₁₂] M₂) : f.range.mkq.comp f = 0 :=
linear_map.ext $ λ x, by simp
lemma ker_le_range_iff {f : M →ₛₗ[τ₁₂] M₂} {g : M₂ →ₛₗ[τ₂₃] M₃} :
g.ker ≤ f.range ↔ f.range.mkq.comp g.ker.subtype = 0 :=
by rw [←range_le_ker_iff, submodule.ker_mkq, submodule.range_subtype]
/-- An epimorphism is surjective. -/
lemma range_eq_top_of_cancel {f : M →ₛₗ[τ₁₂] M₂}
(h : ∀ (u v : M₂ →ₗ[R₂] M₂ ⧸ f.range), u.comp f = v.comp f → u = v) : f.range = ⊤ :=
begin
have h₁ : (0 : M₂ →ₗ[R₂] M₂ ⧸ f.range).comp f = 0 := zero_comp _,
rw [←submodule.ker_mkq f.range, ←h 0 f.range.mkq (eq.trans h₁ (range_mkq_comp _).symm)],
exact ker_zero
end
end ring
end linear_map
open linear_map
namespace submodule
variables {R M : Type*} {r : R} {x y : M} [ring R] [add_comm_group M] [module R M]
variables (p p' : submodule R M)
/-- If `p = ⊥`, then `M / p ≃ₗ[R] M`. -/
def quot_equiv_of_eq_bot (hp : p = ⊥) : (M ⧸ p) ≃ₗ[R] M :=
linear_equiv.of_linear (p.liftq id $ hp.symm ▸ bot_le) p.mkq (liftq_mkq _ _ _) $
p.quot_hom_ext $ λ x, rfl
@[simp] lemma quot_equiv_of_eq_bot_apply_mk (hp : p = ⊥) (x : M) :
p.quot_equiv_of_eq_bot hp (quotient.mk x) = x := rfl
@[simp] lemma quot_equiv_of_eq_bot_symm_apply (hp : p = ⊥) (x : M) :
(p.quot_equiv_of_eq_bot hp).symm x = quotient.mk x := rfl
@[simp] lemma coe_quot_equiv_of_eq_bot_symm (hp : p = ⊥) :
((p.quot_equiv_of_eq_bot hp).symm : M →ₗ[R] M ⧸ p) = p.mkq := rfl
/-- Quotienting by equal submodules gives linearly equivalent quotients. -/
def quot_equiv_of_eq (h : p = p') : (M ⧸ p) ≃ₗ[R] M ⧸ p' :=
{ map_add' := by { rintros ⟨x⟩ ⟨y⟩, refl }, map_smul' := by { rintros x ⟨y⟩, refl },
..@quotient.congr _ _ (quotient_rel p) (quotient_rel p') (equiv.refl _) $
λ a b, by { subst h, refl } }
@[simp]
lemma quot_equiv_of_eq_mk (h : p = p') (x : M) :
submodule.quot_equiv_of_eq p p' h (submodule.quotient.mk x) = submodule.quotient.mk x :=
rfl
@[simp] lemma quotient.equiv_refl (P : submodule R M) (Q : submodule R M)
(hf : P.map (linear_equiv.refl R M : M →ₗ[R] M) = Q) :
quotient.equiv P Q (linear_equiv.refl R M) hf = quot_equiv_of_eq _ _ (by simpa using hf) :=
rfl
end submodule
end ring
section comm_ring
variables {R M M₂ : Type*} {r : R} {x y : M} [comm_ring R]
[add_comm_group M] [module R M] [add_comm_group M₂] [module R M₂]
(p : submodule R M) (q : submodule R M₂)
namespace submodule
/-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`,
the natural map $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \} \to Hom(M/p, M₂/q)$ is linear. -/
def mapq_linear : compatible_maps p q →ₗ[R] (M ⧸ p) →ₗ[R] (M₂ ⧸ q) :=
{ to_fun := λ f, mapq _ _ f.val f.property,
map_add' := λ x y, by { ext, refl, },
map_smul' := λ c f, by { ext, refl, } }
end submodule
end comm_ring
|
b6aa6b542ab18e248ef2130dc0f9db7e66d9c429 | de91c42b87530c3bdcc2b138ef1a3c3d9bee0d41 | /old/imperative_DSL/physlang_test.lean | ad9159f6cb518355eac342a703fa1bd2794eb911 | [] | no_license | kevinsullivan/lang | d3e526ba363dc1ddf5ff1c2f36607d7f891806a7 | e9d869bff94fb13ad9262222a6f3c4aafba82d5e | refs/heads/master | 1,687,840,064,795 | 1,628,047,969,000 | 1,628,047,969,000 | 282,210,749 | 0 | 1 | null | 1,608,153,830,000 | 1,595,592,637,000 | Lean | UTF-8 | Lean | false | false | 560 | lean | import .physlang
import .environment
/-
Test code
-/
def g1 := lang.classicalGeometry.var.mk 0
def g2 := lang.classicalGeometry.var.mk 1
--default environments
def geomDefaultEnv : environment.env := environment.env.mk
(λ v, worldGeometry)
(λ v, worldTime)
(λ v, worldVelocity)
(λ v, worldAcceleration)
def my_var : lang.classicalGeometry.var := lang.classicalGeometry.var.mk 0
def myProgram : cmd := cmd.classicalGeometryAssmt my_var (lang.classicalGeometry.expr.lit (classicalGeometry.mk 0 3))
#eval cmdEval myProgram geomDefaultEnv
|
5c4bfc297541c2b62b20a1d90b3c40fbbab5c1ad | 12ba6fe891179eac82e287c24c8812a046221563 | /src/colex.lean | 1a3d940f4b06a1f2a0b000289a76d5f6e6fd74c5 | [] | no_license | b-mehta/combinatorics | eca586b4cb7b5e1fd22ec3288f5a2cb4ed6ce4dd | 2a8b30709d35f124f3fc9baa5652d231389e9f63 | refs/heads/master | 1,653,708,057,336 | 1,626,885,184,000 | 1,626,885,184,000 | 228,850,404 | 19 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,905 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import data.finset
import data.fintype.basic
import algebra.geom_sum
import combinatorics.colex
import to_mathlib
-- /-!
-- # Colex
-- We define the colex ordering for finite sets, and give a couple of important
-- lemmas and properties relating to it.
-- The colex ordering likes to avoid large values - it can be thought of on
-- `finset ℕ` as the "binary" ordering. That is, order A based on
-- `∑_{i ∈ A} 2^i`.
-- It's defined here a slightly more general way, requiring only `has_lt α` in
-- the definition of colex on `finset α`. In the context of the Kruskal-Katona
-- theorem, we are interested in particular on how colex behaves for sets of a
-- fixed size. If the size is 3, colex on ℕ starts
-- 123, 124, 134, 234, 125, 135, 235, 145, 245, 345, ...
-- ## Main statements
-- * `colex_hom`: strictly monotone functions preserve colex
-- * Colex order properties - linearity, decidability and so on.
-- * `max_colex`: if A < B in colex, and everything in B is < t, then everything
-- in A is < t. This confirms the idea that an enumeration under colex will
-- exhaust all sets using elements < t before allowing t to be included.
-- * `binary_iff`: colex for α = ℕ is the same as binary
-- (this also proves binary expansions are unique)
-- ## Notation
-- We define `<ᶜ` and `≤ᶜ` to denote colex ordering, useful in particular when
-- multiple orderings are available in context.
-- ## Tags
-- colex, colexicographic, binary
-- ## References
-- * http://b-mehta.github.io/maths-notes/iii/mich/combinatorics.pdf
-- -/
variable {α : Type*}
-- open finset
-- /--
-- A <ᶜ B if the largest thing that's not in both sets is in B.
-- In other words, max (A ▵ B) ∈ B.
-- -/
-- def colex_lt [has_lt α] (A B : finset α) : Prop :=
-- ∃ (k : α), (∀ {x}, k < x → (x ∈ A ↔ x ∈ B)) ∧ k ∉ A ∧ k ∈ B
-- /--
-- We can define ≤ in the obvious way.
-- -/
abbreviation colex_le [has_lt α] (A B : finset α) : Prop := A.to_colex ≤ B.to_colex
abbreviation colex_lt [has_lt α] (A B : finset α) : Prop := A.to_colex < B.to_colex
-- infix ` <ᶜ `:50 := colex_lt
infix ` ≤ᶜ `:50 := colex_le
infix ` <ᶜ `:50 := colex_lt
-- /-- Strictly monotone functions preserve the colex ordering. -/
-- lemma colex_hom {β : Type*} [linear_order α] [decidable_eq β] [preorder β]
-- {f : α → β} (h₁ : strict_mono f) (A B : finset α) :
-- image f A <ᶜ image f B ↔ A <ᶜ B :=
-- begin
-- simp [colex_lt],
-- split,
-- rintro ⟨k, z, q, k', _, rfl⟩,
-- refine ⟨k', λ x hx, _, λ t, q _ t rfl, ‹k' ∈ B›⟩, have := z (h₁ hx),
-- simp [strict_mono.injective h₁] at this, assumption,
-- rintro ⟨k, z, ka, _⟩,
-- refine ⟨f k, λ x hx, _, _, k, ‹k ∈ B›, rfl⟩,
-- split, any_goals {
-- rintro ⟨x', x'in, rfl⟩, refine ⟨x', _, rfl⟩,
-- rwa ← z _ <|> rwa z _, rwa strict_mono.lt_iff_lt h₁ at hx },
-- simp [strict_mono.injective h₁], exact λ x hx, ne_of_mem_of_not_mem hx ka
-- end
-- /-- A special case of `colex_hom` which is sometimes useful. -/
-- lemma colex_hom_fin {n : ℕ} (A B : finset (fin n)) :
-- image fin.val A <ᶜ image fin.val B ↔ A <ᶜ B :=
-- colex_hom (λ x y k, k) _ _
-- -- The basic order properties of colex.
-- instance [has_lt α] : is_irrefl (finset α) (<ᶜ) :=
-- ⟨λ A h, exists.elim h (λ _ ⟨_,a,b⟩, a b)⟩
-- instance [has_lt α] : is_refl (finset α) (≤ᶜ) := ⟨λ A, or.inr rfl⟩
-- instance [linear_order α] : is_trans (finset α) (<ᶜ) :=
-- begin
-- constructor,
-- rintros A B C ⟨k₁, k₁z, notinA, inB⟩ ⟨k₂, k₂z, notinB, inC⟩,
-- have: k₁ ≠ k₂ := ne_of_mem_of_not_mem inB notinB,
-- cases lt_or_gt_of_ne this,
-- refine ⟨k₂, _, by rwa k₁z h, inC⟩,
-- intros x hx, rw ← k₂z hx, apply k₁z (trans h hx),
-- refine ⟨k₁, _, notinA, by rwa ← k₂z h⟩,
-- intros x hx, rw k₁z hx, apply k₂z (trans h hx)
-- end
-- instance [linear_order α] : is_asymm (finset α) (<ᶜ) := by apply_instance
-- instance [linear_order α] : is_antisymm (finset α) (≤ᶜ) :=
-- ⟨λ A B AB BA, AB.elim (λ k, BA.elim (λ t, (asymm k t).elim) (λ t, t.symm)) id⟩
-- instance [linear_order α] : is_trans (finset α) (≤ᶜ) :=
-- ⟨λ A B C AB BC, AB.elim (λ k, BC.elim (λ t, or.inl (trans k t)) (λ t, t ▸ AB))
-- (λ k, k.symm ▸ BC)⟩
-- instance [linear_order α] : is_strict_order (finset α) (<ᶜ) := {}
-- instance [linear_order α] [decidable_eq α] : is_trichotomous (finset α) (<ᶜ) :=
-- begin
-- split, intros A B,
-- by_cases (A = B), right, left, assumption,
-- rcases (exists_max' (A \ B ∪ B \ A) id _) with ⟨k, hk, z⟩,
-- simp at hk, cases hk, right, right, swap, left, swap,
-- any_goals { refine ⟨k, λ t th, _, hk.2, hk.1⟩, specialize z t, by_contra,
-- simp only [mem_union, mem_sdiff, id] at z, rw [not_iff,
-- iff_iff_and_or_not_and_not, not_not, and_comm] at a,
-- apply not_le_of_lt th (z _) },
-- { exact a }, { exact a.symm },
-- intro a, simp only [union_empty_iff, sdiff_eq_empty_iff_subset] at a,
-- apply h (subset.antisymm a.1 a.2)
-- end
-- instance [linear_order α] [decidable_eq α] : is_total (finset α) (≤ᶜ) := ⟨λ A B,
-- (trichotomous A B).elim3 (or.inl ∘ or.inl) (or.inl ∘ or.inr) (or.inr ∘ or.inl)⟩
-- instance [linear_order α] [decidable_eq α] :
-- is_linear_order (finset α) (≤ᶜ) := {}
-- instance [linear_order α] [decidable_eq α] : is_incomp_trans (finset α) (<ᶜ) :=
-- begin
-- constructor,
-- rintros A B C ⟨nAB, nBA⟩ ⟨nBC, nCB⟩,
-- have: A = B := ((trichotomous A B).resolve_left nAB).resolve_right nBA,
-- have: B = C := ((trichotomous B C).resolve_left nBC).resolve_right nCB,
-- rw [‹A = B›, ‹B = C›], rw and_self, apply irrefl
-- end
-- instance [linear_order α] [decidable_eq α] :
-- is_strict_weak_order (finset α) (<ᶜ) := {}
-- instance [linear_order α] [decidable_eq α] :
-- is_strict_total_order (finset α) (<ᶜ) := {}
-- instance colex_order [has_lt α] : has_le (finset α) := {le := (≤ᶜ)}
-- instance colex_preorder [linear_order α] : preorder (finset α) :=
-- {le_refl := refl_of (≤ᶜ), le_trans := is_trans.trans, ..colex_order}
-- instance colex_partial_order [linear_order α] : partial_order (finset α) :=
-- {le_antisymm := is_antisymm.antisymm, ..colex_preorder}
-- instance colex_linear_order [linear_order α] [decidable_eq α] :
-- linear_order (finset α) :=
-- {le_total := is_total.total (≤ᶜ), ..colex_partial_order}
-- /--
-- Rewrite colex in a particular way so that it uses only bounded quantification,
-- so we can infer decidability.
-- -/
-- lemma colex_dec [has_lt α] (A B : finset α) : A <ᶜ B ↔
-- ∃ (k ∈ B), (∀ x ∈ A, k < x → x ∈ B) ∧ (∀ x ∈ B, k < x → x ∈ A) ∧ k ∉ A :=
-- begin
-- rw colex_lt, split,
-- { rintro ⟨k, z, kA, kB⟩,
-- refine ⟨k, kB, λ t th kt, (z kt).1 th, λ t th kt, (z kt).2 th, kA⟩ },
-- { rintro ⟨k, kB, zAB, zBA, kA⟩,
-- refine ⟨k, λ t th, _, kA, kB⟩, refine ⟨λ z, zAB _ z th, λ z, zBA _ z th⟩ }
-- end
-- instance colex_lt_decidable [decidable_linear_order α] (A B : finset α) :
-- decidable (A <ᶜ B) := by rw colex_dec; apply_instance
-- instance colex_le_decidable [decidable_linear_order α] (A B : finset α) :
-- decidable (A ≤ᶜ B) := or.decidable
-- instance colex_decidable_order [decidable_linear_order α] :
-- decidable_linear_order (finset α) :=
-- {decidable_le := infer_instance, ..colex_linear_order}
-- /-- Colex is an extension of the base ordering on α. -/
-- lemma colex_singleton [linear_order α] {x y : α} :
-- finset.singleton x <ᶜ finset.singleton y ↔ x < y :=
-- begin
-- rw colex_lt, simp, conv_lhs { conv {congr, funext, rw and_comm,
-- rw and_comm (¬k=x), rw and_assoc},
-- rw exists_eq_left },
-- split, rintro ⟨p, q⟩, apply (lt_trichotomy x y).resolve_right,
-- rw not_or_distrib, split, intro, apply p, symmetry, assumption,
-- intro a, specialize q a, apply p, symmetry, rw ← q,
-- intro, split, apply ne_of_gt a, intros z hz, rw iff_false_left,
-- apply ne_of_gt hz, apply ne_of_gt (trans hz a)
-- end
-- /--
-- If A is before B in colex, and everything in B is small, then everything in
-- A is small.
-- -/
-- lemma max_colex [decidable_linear_order α] {A B : finset α} (t : α)
-- (h₁ : A <ᶜ B) (h₂ : ∀ x ∈ B, x < t) :
-- ∀ x ∈ A, x < t :=
-- begin
-- rw colex_lt at h₁, rcases h₁ with ⟨k, z, _, _⟩,
-- intros x hx, apply lt_of_not_ge, intro, apply not_lt_of_ge a, apply h₂,
-- rwa ← z, apply lt_of_lt_of_le (h₂ k ‹_›) a,
-- end
-- /-- If everything in A is less than k, we can bound the sum of powers. -/
-- lemma binary_sum_nat {k : ℕ} {A : finset ℕ} (h₁ : ∀ {x}, x ∈ A → x < k) :
-- A.sum (pow 2) < 2^k :=
-- begin
-- apply lt_of_le_of_lt (sum_le_sum_of_subset (λ t, mem_range.2 ∘ h₁)),
-- have z := geom_sum_mul_add 1 k, rw [geom_series, mul_one] at z,
-- simp only [nat.pow_eq_pow] at z, rw ← z, apply nat.lt_succ_self
-- end
-- /-- Colex doesn't care if you remove the other set -/
-- lemma colex_ignores_sdiff [has_lt α] [decidable_eq α] (A B : finset α) :
-- A <ᶜ B ↔ A \ B <ᶜ B \ A :=
-- begin
-- rw colex_lt, rw colex_lt, apply exists_congr, intro k,
-- split; rintro ⟨z, kA, kB⟩; refine ⟨_, _, _⟩; simp at kA kB z ⊢,
-- intros x hx, rw z hx, intro, exact kB, exact ⟨kB, kA⟩,
-- intros x hx, specialize z hx, tauto, tauto, tauto
-- end
-- /-- For subsets of ℕ, we can show that colex is equivalent to binary. -/
-- lemma binary_iff (A B : finset ℕ) : A.sum (pow 2) < B.sum (pow 2) ↔ A <ᶜ B :=
-- begin
-- have z: ∀ (A B : finset ℕ), A <ᶜ B → A.sum (pow 2) < B.sum (pow 2),
-- intros A B, rw colex_ignores_sdiff, rintro ⟨k, z, kA, kB⟩,
-- rw ← sdiff_union_inter A B, conv_rhs {rw ← sdiff_union_inter B A},
-- rw [sum_union (sdiff_inter_inter _ _), sum_union (sdiff_inter_inter _ _),
-- inter_comm, add_lt_add_iff_right],
-- apply lt_of_lt_of_le (@binary_sum_nat k (A \ B) _),
-- apply single_le_sum (λ _ _, nat.zero_le _) kB,
-- intros x hx, apply lt_of_le_of_ne (le_of_not_lt (λ kx, _)),
-- apply (ne_of_mem_of_not_mem hx kA), specialize z kx, have := z.1 hx,
-- rw mem_sdiff at this hx, exact hx.2 this.1,
-- refine ⟨λ h, (trichotomous A B).resolve_right
-- (λ h₁, h₁.elim _ (not_lt_of_gt h ∘ z _ _)), z A B⟩,
-- rintro rfl, apply irrefl _ h
-- end |
3feb0997bf2cc4454294da87bff3a6ea2f062214 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/bigctor.lean | fd8d32b2c041246aec7eae09a4652d3ac4f54c1d | [
"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,353 | lean | set_option genInjectivity false
structure Foo where
x1 : Nat := 0
x2 : Nat := 0
x3 : Nat := 0
x4 : Nat := 0
x5 : Nat := 0
x6 : Nat := 0
x7 : Nat := 0
x8 : Nat := 0
x9 : Nat := 0
x10 : Nat := 0
y1 : Nat := 0
y2 : Nat := 0
y3 : Nat := 0
y4 : Nat := 0
y5 : Nat := 0
y6 : Nat := 0
y7 : Nat := 0
y8 : Nat := 0
y9 : Nat := 0
y10 : Nat := 0
z1 : Nat := 0
z2 : Nat := 0
z3 : Nat := 0
z4 : Nat := 0
z5 : Nat := 0
z6 : Nat := 0
z7 : Nat := 0
z8 : Nat := 0
z9 : Nat := 0
z10 : Nat := 0
w1 : Nat := 0
w2 : Nat := 0
w3 : Nat := 0
w4 : Nat := 0
w5 : Nat := 0
w6 : Nat := 0
w7 : Nat := 0
w8 : Nat := 0
w9 : Nat := 0
w10 : Nat := 0
xx1 : Nat := 0
xx2 : Nat := 0
xx3 : Nat := 0
xx4 : Nat := 0
xx5 : Nat := 0
xx6 : Nat := 0
xx7 : Nat := 0
xx8 : Nat := 0
xx9 : Nat := 0
xx10 : Nat := 0
yy1 : Nat := 0
yy2 : Nat := 0
yy3 : Nat := 0
yy4 : Nat := 0
yy5 : Nat := 0
yy6 : Nat := 0
yy7 : Nat := 0
yy8 : Nat := 0
yy9 : Nat := 0
yy10 : Nat := 0
ww1 : Nat := 0
ww2 : Nat := 0
ww3 : Nat := 0
ww4 : Nat := 0
ww5 : Nat := 0
ww6 : Nat := 0
ww7 : Nat := 0
ww8 : Nat := 0
ww9 : Nat := 0
ww10 : Nat := 0
@[noinline] def mkFoo (x : Nat) : Foo :=
{ yy10 := x }
#eval (mkFoo 10).yy10
|
3489fe2fb5c8b111932be60ca6a9b947952a92e8 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/analysis/convex/hull.lean | efbc727029664053ff6f7eb90f9ce863fc8ddcf2 | [
"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 | 7,195 | lean | /-
Copyright (c) 2020 Yury Kudriashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudriashov, Yaël Dillies
-/
import analysis.convex.basic
import order.closure
/-!
# Convex hull
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines the convex hull of a set `s` in a module. `convex_hull 𝕜 s` is the smallest convex
set containing `s`. In order theory speak, this is a closure operator.
## Implementation notes
`convex_hull` is defined as a closure operator. This gives access to the `closure_operator` API
while the impact on writing code is minimal as `convex_hull 𝕜 s` is automatically elaborated as
`⇑(convex_hull 𝕜) s`.
-/
open set
open_locale pointwise
variables {𝕜 E F : Type*}
section convex_hull
section ordered_semiring
variables [ordered_semiring 𝕜]
section add_comm_monoid
variables (𝕜) [add_comm_monoid E] [add_comm_monoid F] [module 𝕜 E] [module 𝕜 F]
/-- The convex hull of a set `s` is the minimal convex set that includes `s`. -/
def convex_hull : closure_operator (set E) :=
closure_operator.mk₃
(λ s, ⋂ (t : set E) (hst : s ⊆ t) (ht : convex 𝕜 t), t)
(convex 𝕜)
(λ s, set.subset_Inter (λ t, set.subset_Inter $ λ hst, set.subset_Inter $ λ ht, hst))
(λ s, convex_Inter $ λ t, convex_Inter $ λ ht, convex_Inter id)
(λ s t hst ht, set.Inter_subset_of_subset t $ set.Inter_subset_of_subset hst $
set.Inter_subset _ ht)
variables (s : set E)
lemma subset_convex_hull : s ⊆ convex_hull 𝕜 s := (convex_hull 𝕜).le_closure s
lemma convex_convex_hull : convex 𝕜 (convex_hull 𝕜 s) := closure_operator.closure_mem_mk₃ s
lemma convex_hull_eq_Inter : convex_hull 𝕜 s = ⋂ (t : set E) (hst : s ⊆ t) (ht : convex 𝕜 t), t :=
rfl
variables {𝕜 s} {t : set E} {x y : E}
lemma mem_convex_hull_iff : x ∈ convex_hull 𝕜 s ↔ ∀ t, s ⊆ t → convex 𝕜 t → x ∈ t :=
by simp_rw [convex_hull_eq_Inter, mem_Inter]
lemma convex_hull_min (hst : s ⊆ t) (ht : convex 𝕜 t) : convex_hull 𝕜 s ⊆ t :=
closure_operator.closure_le_mk₃_iff (show s ≤ t, from hst) ht
lemma convex.convex_hull_subset_iff (ht : convex 𝕜 t) : convex_hull 𝕜 s ⊆ t ↔ s ⊆ t :=
⟨(subset_convex_hull _ _).trans, λ h, convex_hull_min h ht⟩
@[mono] lemma convex_hull_mono (hst : s ⊆ t) : convex_hull 𝕜 s ⊆ convex_hull 𝕜 t :=
(convex_hull 𝕜).monotone hst
lemma convex.convex_hull_eq (hs : convex 𝕜 s) : convex_hull 𝕜 s = s :=
closure_operator.mem_mk₃_closed hs
@[simp] lemma convex_hull_univ : convex_hull 𝕜 (univ : set E) = univ :=
closure_operator.closure_top (convex_hull 𝕜)
@[simp] lemma convex_hull_empty : convex_hull 𝕜 (∅ : set E) = ∅ := convex_empty.convex_hull_eq
@[simp] lemma convex_hull_empty_iff : convex_hull 𝕜 s = ∅ ↔ s = ∅ :=
begin
split,
{ intro h,
rw [←set.subset_empty_iff, ←h],
exact subset_convex_hull 𝕜 _ },
{ rintro rfl,
exact convex_hull_empty }
end
@[simp] lemma convex_hull_nonempty_iff : (convex_hull 𝕜 s).nonempty ↔ s.nonempty :=
begin
rw [nonempty_iff_ne_empty, nonempty_iff_ne_empty, ne.def, ne.def],
exact not_congr convex_hull_empty_iff,
end
alias convex_hull_nonempty_iff ↔ _ set.nonempty.convex_hull
attribute [protected] set.nonempty.convex_hull
lemma segment_subset_convex_hull (hx : x ∈ s) (hy : y ∈ s) : segment 𝕜 x y ⊆ convex_hull 𝕜 s :=
(convex_convex_hull _ _).segment_subset (subset_convex_hull _ _ hx) (subset_convex_hull _ _ hy)
@[simp] lemma convex_hull_singleton (x : E) : convex_hull 𝕜 ({x} : set E) = {x} :=
(convex_singleton x).convex_hull_eq
@[simp] lemma convex_hull_pair (x y : E) : convex_hull 𝕜 {x, y} = segment 𝕜 x y :=
begin
refine (convex_hull_min _ $ convex_segment _ _).antisymm
(segment_subset_convex_hull (mem_insert _ _) $ mem_insert_of_mem _ $ mem_singleton _),
rw [insert_subset, singleton_subset_iff],
exact ⟨left_mem_segment _ _ _, right_mem_segment _ _ _⟩,
end
lemma convex_hull_convex_hull_union_left (s t : set E) :
convex_hull 𝕜 (convex_hull 𝕜 s ∪ t) = convex_hull 𝕜 (s ∪ t) :=
closure_operator.closure_sup_closure_left _ _ _
lemma convex_hull_convex_hull_union_right (s t : set E) :
convex_hull 𝕜 (s ∪ convex_hull 𝕜 t) = convex_hull 𝕜 (s ∪ t) :=
closure_operator.closure_sup_closure_right _ _ _
lemma convex.convex_remove_iff_not_mem_convex_hull_remove {s : set E} (hs : convex 𝕜 s) (x : E) :
convex 𝕜 (s \ {x}) ↔ x ∉ convex_hull 𝕜 (s \ {x}) :=
begin
split,
{ rintro hsx hx,
rw hsx.convex_hull_eq at hx,
exact hx.2 (mem_singleton _) },
rintro hx,
suffices h : s \ {x} = convex_hull 𝕜 (s \ {x}), { convert convex_convex_hull 𝕜 _ },
exact subset.antisymm (subset_convex_hull 𝕜 _) (λ y hy, ⟨convex_hull_min (diff_subset _ _) hs hy,
by { rintro (rfl : y = x), exact hx hy }⟩),
end
lemma is_linear_map.convex_hull_image {f : E → F} (hf : is_linear_map 𝕜 f) (s : set E) :
convex_hull 𝕜 (f '' s) = f '' convex_hull 𝕜 s :=
set.subset.antisymm (convex_hull_min (image_subset _ (subset_convex_hull 𝕜 s)) $
(convex_convex_hull 𝕜 s).is_linear_image hf)
(image_subset_iff.2 $ convex_hull_min
(image_subset_iff.1 $ subset_convex_hull 𝕜 _)
((convex_convex_hull 𝕜 _).is_linear_preimage hf))
lemma linear_map.convex_hull_image (f : E →ₗ[𝕜] F) (s : set E) :
convex_hull 𝕜 (f '' s) = f '' convex_hull 𝕜 s :=
f.is_linear.convex_hull_image s
end add_comm_monoid
end ordered_semiring
section ordered_comm_semiring
variables [ordered_comm_semiring 𝕜] [add_comm_monoid E] [module 𝕜 E]
lemma convex_hull_smul (a : 𝕜) (s : set E) : convex_hull 𝕜 (a • s) = a • convex_hull 𝕜 s :=
(linear_map.lsmul _ _ a).convex_hull_image _
end ordered_comm_semiring
section ordered_ring
variables [ordered_ring 𝕜]
section add_comm_group
variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] (s : set E)
lemma affine_map.image_convex_hull (f : E →ᵃ[𝕜] F) :
f '' convex_hull 𝕜 s = convex_hull 𝕜 (f '' s) :=
begin
apply set.subset.antisymm,
{ rw set.image_subset_iff,
refine convex_hull_min _ ((convex_convex_hull 𝕜 (⇑f '' s)).affine_preimage f),
rw ← set.image_subset_iff,
exact subset_convex_hull 𝕜 (f '' s) },
{ exact convex_hull_min (set.image_subset _ (subset_convex_hull 𝕜 s))
((convex_convex_hull 𝕜 s).affine_image f) }
end
lemma convex_hull_subset_affine_span : convex_hull 𝕜 s ⊆ (affine_span 𝕜 s : set E) :=
convex_hull_min (subset_affine_span 𝕜 s) (affine_span 𝕜 s).convex
@[simp] lemma affine_span_convex_hull : affine_span 𝕜 (convex_hull 𝕜 s) = affine_span 𝕜 s :=
begin
refine le_antisymm _ (affine_span_mono 𝕜 (subset_convex_hull 𝕜 s)),
rw affine_span_le,
exact convex_hull_subset_affine_span s,
end
lemma convex_hull_neg (s : set E) : convex_hull 𝕜 (-s) = -convex_hull 𝕜 s :=
by { simp_rw ←image_neg, exact (affine_map.image_convex_hull _ $ -1).symm }
end add_comm_group
end ordered_ring
end convex_hull
|
f6f5ad328cd0aea9b6ab7f5ba70ed687dfd63ad1 | c777c32c8e484e195053731103c5e52af26a25d1 | /archive/oxford_invariants/2021summer/week3_p1.lean | d0a8fb0731ff8bc70d1cefde2dcd2370d966f08d | [
"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 | 6,777 | lean | /-
Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies, Bhavik Mehta
-/
import algebra.big_operators.order
import algebra.big_operators.ring
import algebra.char_zero.lemmas
import data.rat.cast
/-!
# The Oxford Invariants Puzzle Challenges - Summer 2021, Week 3, Problem 1
## Original statement
Let `n ≥ 3`, `a₁, ..., aₙ` be strictly positive integers such that `aᵢ ∣ aᵢ₋₁ + aᵢ₊₁` for
`i = 2, ..., n - 1`. Show that $\sum_{i=1}^{n-1}\dfrac{a_0a_n}{a_ia_{i+1}} ∈ \mathbb N$.
## Comments
Mathlib is based on type theory, so saying that a rational is a natural doesn't make sense. Instead,
we ask that there exists `b : ℕ` whose cast to `α` is the sum we want.
In mathlib, `ℕ` starts at `0`. To make the indexing cleaner, we use `a₀, ..., aₙ₋₁` instead of
`a₁, ..., aₙ`. Similarly, it's nicer to not use subtraction of naturals, so we replace
`aᵢ ∣ aᵢ₋₁ + aᵢ₊₁` by `aᵢ₊₁ ∣ aᵢ + aᵢ₊₂`.
We don't actually have to work in `ℚ` or `ℝ`. We can be even more general by stating the result for
any linearly ordered field.
Instead of having `n` naturals, we use a function `a : ℕ → ℕ`.
In the proof itself, we replace `n : ℕ, 1 ≤ n` by `n + 1`.
The statement is actually true for `n = 0, 1` (`n = 1, 2` before the reindexing) as the sum is
simply `0` and `1` respectively. So the version we prove is slightly more general.
Overall, the indexing is a bit of a mess to understand. But, trust Lean, it works.
## Formalised statement
Let `n : ℕ`, `a : ℕ → ℕ`, `∀ i ≤ n, 0 < a i`, `∀ i, i + 2 ≤ n → aᵢ₊₁ ∣ aᵢ + aᵢ₊₂` (read `→` as
"implies"). Then there exists `b : ℕ` such that `b` as an element of any linearly ordered field
equals $\sum_{i=0}^{n-1} (a_0 a_n) / (a_i a_{i+1})$.
## Proof outline
The case `n = 0` is trivial.
For `n + 1`, we prove the result by induction but by adding `aₙ₊₁ ∣ aₙ * b - a₀` to the induction
hypothesis, where `b` is the previous sum, $\sum_{i=0}^{n-1} (a_0 a_n) / (a_i a_{i+1})$, as a
natural.
* Base case:
* $\sum_{i=0}^0 (a_0 a_{0+1}) / (a_0 a_{0+1})$ is a natural:
$\sum_{i=0}^0 (a_0 a_{0+1}) / (a_0 a_{0+1}) = (a_0 a_1) / (a_0 a_1) = 1$.
* Divisibility condition:
`a₀ * 1 - a₀ = 0` is clearly divisible by `a₁`.
* Induction step:
* $\sum_{i=0}^n (a_0 a_{n+1}) / (a_i a_{i+1})$ is a natural:
$$\sum_{i=0}^{n+1} (a_0 a_{n+2}) / (a_i a_{i+1})
= \sum_{i=0}^n\ (a_0 a_{n+2}) / (a_i a_{i+1}) + (a_0 a_{n+2}) / (a_{n+1} a_{n+2})
= a_{n+2} / a_{n+1} × \sum_{i=0}^n (a_0 a_{n+1}) / (a_i a_{i+1}) + a_0 / a_{n+1}
= a_{n+2} / a_{n+1} × b + a_0 / a_{n+1}
= (a_n + a_{n+2}) / a_{n+1} × b - (a_n b - a_0)(a_{n+1})$$
which is a natural because `(aₙ + aₙ₊₂)/aₙ₊₁`, `b` and `(aₙ * b - a₀)/aₙ₊₁` are (plus an
annoying inequality, or the fact that the original sum is positive because its terms are).
* Divisibility condition:
`aₙ₊₁ * ((aₙ + aₙ₊₂)/aₙ₊₁ * b - (aₙ * b - a₀)/aₙ₊₁) - a₀ = aₙ₊₁aₙ₊₂b` is divisible by `aₙ₊₂`.
-/
open_locale big_operators
variables {α : Type*} [linear_ordered_field α]
theorem week3_p1 (n : ℕ) (a : ℕ → ℕ) (a_pos : ∀ i ≤ n, 0 < a i)
(ha : ∀ i, i + 2 ≤ n → a (i + 1) ∣ a i + a (i + 2)) :
∃ b : ℕ, (b : α) = ∑ i in finset.range n, (a 0 * a n)/(a i * a (i + 1)) :=
begin
-- Treat separately `n = 0` and `n ≥ 1`
cases n,
/- Case `n = 0`
The sum is trivially equal to `0` -/
{ exact ⟨0, by rw [nat.cast_zero, finset.sum_range_zero]⟩ }, -- `⟨Claim it, Prove it⟩`
/- Case `n ≥ 1`. We replace `n` by `n + 1` everywhere to make this inequality explicit
Set up the stronger induction hypothesis -/
rsuffices ⟨b, hb, -⟩ :
∃ b : ℕ, (b : α) = ∑ i in finset.range (n + 1), (a 0 * a (n + 1)) / (a i * a (i + 1))
∧ a (n + 1) ∣ a n * b - a 0,
{ exact ⟨b, hb⟩ },
simp_rw ←@nat.cast_pos α at a_pos,
/- Declare the induction
`ih` will be the induction hypothesis -/
induction n with n ih,
/- Base case
Claim that the sum equals `1`-/
{ refine ⟨1, _, _⟩,
-- Check that this indeed equals the sum
{ rw [nat.cast_one, finset.sum_range_one, div_self],
exact (mul_pos (a_pos 0 (nat.zero_le _)) (a_pos 1 (nat.zero_lt_succ _))).ne' },
-- Check the divisibility condition
{ rw [mul_one, tsub_self],
exact dvd_zero _ } },
/- Induction step
`b` is the value of the previous sum as a natural, `hb` is the proof that it is indeed the value,
and `han` is the divisibility condition -/
obtain ⟨b, hb, han⟩ := ih (λ i hi, ha i $ nat.le_succ_of_le hi)
(λ i hi, a_pos i $ nat.le_succ_of_le hi),
specialize ha n le_rfl,
have ha₀ : a 0 ≤ a n * b, -- Needing this is an artifact of `ℕ`-subtraction.
{ rw [←@nat.cast_le α, nat.cast_mul, hb, ←div_le_iff' (a_pos _ $ n.le_succ.trans $ nat.le_succ _),
←mul_div_mul_right _ _ (a_pos _ $ nat.le_succ _).ne'],
suffices h : ∀ i, i ∈ finset.range (n + 1) → 0 ≤ (a 0 : α) * a (n + 1) / (a i * a (i + 1)),
{ exact finset.single_le_sum h (finset.self_mem_range_succ n) },
refine (λ i _, div_nonneg _ _); refine mul_nonneg _ _; exact nat.cast_nonneg _ },
-- Claim that the sum equals `(aₙ + aₙ₊₂)/aₙ₊₁ * b - (aₙ * b - a₀)/aₙ₊₁`
refine ⟨(a n + a (n + 2))/ a (n + 1) * b - (a n * b - a 0) / a (n + 1), _, _⟩,
-- Check that this indeed equals the sum
{ calc
(((a n + a (n + 2)) / a (n + 1) * b - (a n * b - a 0) / a (n + 1) : ℕ) : α)
= (a n + a (n + 2)) / a (n + 1) * b - (a n * b - a 0) / a (n + 1) : begin
norm_cast,
rw nat.cast_sub (nat.div_le_of_le_mul _),
rw [←mul_assoc, nat.mul_div_cancel' ha, add_mul],
exact tsub_le_self.trans (nat.le_add_right _ _),
end
... = a (n + 2) / a (n + 1) * b + (a 0 * a (n + 2)) / (a (n + 1) * a (n + 2))
: by rw [add_div, add_mul, sub_div, mul_div_right_comm, add_sub_sub_cancel,
mul_div_mul_right _ _ (a_pos _ le_rfl).ne']
... = ∑ (i : ℕ) in finset.range (n + 2), a 0 * a (n + 2) / (a i * a (i + 1))
: begin
rw [finset.sum_range_succ, hb, finset.mul_sum],
congr, ext i,
rw [←mul_div_assoc, ←mul_div_right_comm, mul_div_assoc, mul_div_cancel _
(a_pos _ $ nat.le_succ _).ne', mul_comm],
end },
-- Check the divisibility condition
{ rw [mul_tsub, ← mul_assoc, nat.mul_div_cancel' ha, add_mul,
nat.mul_div_cancel' han, add_tsub_tsub_cancel ha₀, add_tsub_cancel_right],
exact dvd_mul_right _ _ }
end
|
2373ab71eb086fe89c712d627776152a65d82345 | e151e9053bfd6d71740066474fc500a087837323 | /src/hott/algebra/bundled.lean | f5e85b0bb02b7ff4a6f34503813b824203624b75 | [
"Apache-2.0"
] | permissive | daniel-carranza/hott3 | 15bac2d90589dbb952ef15e74b2837722491963d | 913811e8a1371d3a5751d7d32ff9dec8aa6815d9 | refs/heads/master | 1,610,091,349,670 | 1,596,222,336,000 | 1,596,222,336,000 | 241,957,822 | 0 | 0 | Apache-2.0 | 1,582,222,839,000 | 1,582,222,838,000 | null | UTF-8 | Lean | false | false | 3,480 | lean | /-
Copyright (c) 2015 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
Bundled structures
-/
import .ring
universes u v w
hott_theory
namespace hott
open algebra pointed is_trunc
namespace algebra
@[hott] structure Semigroup :=
(carrier : Type _) (struct : semigroup carrier)
@[hott] instance has_coe_to_sort_Semigroup : has_coe_to_sort Semigroup :=
⟨_, Semigroup.carrier⟩
attribute [instance] Semigroup.struct
@[hott] structure CommSemigroup :=
(carrier : Type _) (struct : comm_semigroup carrier)
@[hott] instance has_coe_to_sort_CommSemigroup : has_coe_to_sort CommSemigroup :=
⟨_, CommSemigroup.carrier⟩
attribute [instance] CommSemigroup.struct
@[hott] structure Monoid :=
(carrier : Type _) (struct : monoid carrier)
@[hott] instance has_coe_to_sort_Monoid : has_coe_to_sort Monoid :=
⟨_, Monoid.carrier⟩
attribute [instance] Monoid.struct
@[hott] structure CommMonoid :=
(carrier : Type _) (struct : comm_monoid carrier)
@[hott] instance has_coe_to_sort_CommMonoid : has_coe_to_sort CommMonoid :=
⟨_, CommMonoid.carrier⟩
attribute [instance] CommMonoid.struct
@[hott] structure Group :=
(carrier : Type _) (struct' : group carrier)
attribute [instance] Group.struct'
@[hott, reducible] def pSet_of_Group (G : Group) : Set* :=
ptrunctype.mk (pType.mk (Group.carrier G) 1) (semigroup.is_set_carrier _)
@[hott] instance has_coe_Group_pSet : has_coe Group Set* :=
⟨pSet_of_Group⟩
@[hott, instance, priority 2000] def Group.struct (G : Group) : group G :=
Group.struct' G
@[hott, reducible] def pType_of_Group (G : Group.{u}) : pType.{u} :=
↑(↑G : pSet.{u})
@[hott, reducible] def Set_of_Group (G : Group.{u}) : Set.{u} :=
↑(↑G : pSet.{u})
@[hott] structure AbGroup :=
(carrier : Type _) (struct' : ab_group carrier)
attribute [instance] AbGroup.struct'
section
@[hott] def Group_of_AbGroup (G : AbGroup) : Group :=
Group.mk G.carrier (ab_group.to_group _)
@[hott] instance has_coe_AbGroup_Group : has_coe AbGroup Group :=
⟨Group_of_AbGroup⟩
end
@[hott, instance, priority 2000] def AbGroup.struct (G : AbGroup) : ab_group G :=
AbGroup.struct' G
-- some bundled infinity-structures
@[hott] structure InfGroup :=
(carrier : Type _) (struct' : inf_group carrier)
attribute [instance] InfGroup.struct'
@[hott, reducible] def pType_of_InfGroup (G : InfGroup) : Type* :=
pType.mk G.carrier 1
@[hott] instance has_coe_InfGroup_pType : has_coe InfGroup Type* :=
⟨pType_of_InfGroup⟩
@[hott, instance, priority 2000] def InfGroup.struct (G : InfGroup) : inf_group G :=
InfGroup.struct' G
@[hott] structure AbInfGroup :=
(carrier : Type _) (struct' : ab_inf_group carrier)
attribute [instance] AbInfGroup.struct'
@[hott] def InfGroup_of_AbInfGroup (G : AbInfGroup) : InfGroup :=
⟨G.carrier, by apply_instance⟩
@[hott] instance has_coe_AbInfGroup_InfGroup : has_coe AbInfGroup InfGroup :=
⟨InfGroup_of_AbInfGroup⟩
@[hott, instance, priority 2000] def AbInfGroup.struct (G : AbInfGroup) : ab_inf_group G :=
G.struct'
@[hott] def InfGroup_of_Group (G : Group) : InfGroup :=
InfGroup.mk G (by apply_instance)
@[hott] def AbInfGroup_of_AbGroup (G : AbGroup) : AbInfGroup :=
AbInfGroup.mk G (by apply_instance)
/- rings -/
@[hott] structure Ring :=
(carrier : Type _) (struct : ring carrier)
instance has_coe_Ring : has_coe_to_sort Ring.{u} :=
⟨Type u, Ring.carrier⟩
attribute [instance] Ring.struct
end algebra
end hott |
5658af4900f456a10f45e615228dc41405130a1e | b968a51def12e5685e3c38f4c04a60ef2adcfad1 | /leanclient/test.lean | 5e064c681eb8c1ca3a2579b166d2e2ebe34d052b | [] | no_license | Augustindou/mapros | 3627bb0a8a34a607f947c9006ead2476a6af6e60 | 20e5431a5632a10fdaef80c07257df7bf6319bb7 | refs/heads/main | 1,685,136,641,725 | 1,623,589,718,000 | 1,623,589,718,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 156 | lean | lemma zero_max (m : ℕ) : max 0 m = m :=
begin
apply max_eq_right,
exact nat.zero_le m,
end
example (m n : ℕ) : m + n = n + m :=
by simp [add_comm]
|
7d58afe1af74439c47879d8f347bdb12b2633fc9 | d1bbf1801b3dcb214451d48214589f511061da63 | /src/measure_theory/measure_space.lean | 2cb0203cbd40ec8fb2f2ee0fca475afda468506b | [
"Apache-2.0"
] | permissive | cheraghchi/mathlib | 5c366f8c4f8e66973b60c37881889da8390cab86 | f29d1c3038422168fbbdb2526abf7c0ff13e86db | refs/heads/master | 1,676,577,831,283 | 1,610,894,638,000 | 1,610,894,638,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 99,835 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import measure_theory.outer_measure
import order.filter.countable_Inter
import data.set.accumulate
/-!
# Measure spaces
Given a measurable space `α`, a measure on `α` is a function that sends measurable sets to the
extended nonnegative reals that satisfies the following conditions:
1. `μ ∅ = 0`;
2. `μ` is countably additive. This means that the measure of a countable union of pairwise disjoint
sets is equal to the measure of the individual sets.
Every measure can be canonically extended to an outer measure, so that it assigns values to
all subsets, not just the measurable subsets. On the other hand, a measure that is countably
additive on measurable sets can be restricted to measurable sets to obtain a measure.
In this file a measure is defined to be an outer measure that is countably additive on
measurable sets, with the additional assumption that the outer measure is the canonical
extension of the restricted measure.
Measures on `α` form a complete lattice, and are closed under scalar multiplication with `ennreal`.
We introduce the following typeclasses for measures:
* `probability_measure μ`: `μ univ = 1`;
* `finite_measure μ`: `μ univ < ⊤`;
* `sigma_finite μ`: there exists a countable collection of measurable sets that cover `univ`
where `μ` is finite;
* `locally_finite_measure μ` : `∀ x, ∃ s ∈ 𝓝 x, μ s < ⊤`;
* `has_no_atoms μ` : `∀ x, μ {x} = 0`; possibly should be redefined as
`∀ s, 0 < μ s → ∃ t ⊆ s, 0 < μ t ∧ μ t < μ s`.
Given a measure, the null sets are the sets where `μ s = 0`, where `μ` denotes the corresponding
outer measure (so `s` might not be measurable). We can then define the completion of `μ` as the
measure on the least `σ`-algebra that also contains all null sets, by defining the measure to be `0`
on the null sets.
## Main statements
* `completion` is the completion of a measure to all null measurable sets.
* `measure.of_measurable` and `outer_measure.to_measure` are two important ways to define a measure.
## Implementation notes
Given `μ : measure α`, `μ s` is the value of the *outer measure* applied to `s`.
This conveniently allows us to apply the measure to sets without proving that they are measurable.
We get countable subadditivity for all sets, but only countable additivity for measurable sets.
You often don't want to define a measure via its constructor.
Two ways that are sometimes more convenient:
* `measure.of_measurable` is a way to define a measure by only giving its value on measurable sets
and proving the properties (1) and (2) mentioned above.
* `outer_measure.to_measure` is a way of obtaining a measure from an outer measure by showing that
all measurable sets in the measurable space are Carathéodory measurable.
To prove that two measures are equal, there are multiple options:
* `ext`: two measures are equal if they are equal on all measurable sets.
* `ext_of_generate_from_of_Union`: two measures are equal if they are equal on a π-system generating
the measurable sets, if the π-system contains a spanning increasing sequence of sets where the
measures take finite value (in particular the measures are σ-finite). This is a special case of the
more general `ext_of_generate_from_of_cover`
* `ext_of_generate_finite`: two finite measures are equal if they are equal on a π-system
generating the measurable sets. This is a special case of `ext_of_generate_from_of_Union` using
`C ∪ {univ}`, but is easier to work with.
A `measure_space` is a class that is a measurable space with a canonical measure.
The measure is denoted `volume`.
## References
* <https://en.wikipedia.org/wiki/Measure_(mathematics)>
* <https://en.wikipedia.org/wiki/Complete_measure>
* <https://en.wikipedia.org/wiki/Almost_everywhere>
## Tags
measure, almost everywhere, measure space, completion, null set, null measurable set
-/
noncomputable theory
open classical set filter (hiding map) function measurable_space
open_locale classical topological_space big_operators filter
variables {α β γ δ ι : Type*}
namespace measure_theory
/-- A measure is defined to be an outer measure that is countably additive on
measurable sets, with the additional assumption that the outer measure is the canonical
extension of the restricted measure. -/
structure measure (α : Type*) [measurable_space α] extends outer_measure α :=
(m_Union ⦃f : ℕ → set α⦄ :
(∀ i, is_measurable (f i)) → pairwise (disjoint on f) →
measure_of (⋃ i, f i) = ∑' i, measure_of (f i))
(trimmed : to_outer_measure.trim = to_outer_measure)
/-- Measure projections for a measure space.
For measurable sets this returns the measure assigned by the `measure_of` field in `measure`.
But we can extend this to _all_ sets, but using the outer measure. This gives us monotonicity and
subadditivity for all sets.
-/
instance measure.has_coe_to_fun [measurable_space α] : has_coe_to_fun (measure α) :=
⟨λ _, set α → ennreal, λ m, m.to_outer_measure⟩
section
variables [measurable_space α] {μ μ₁ μ₂ : measure α} {s s₁ s₂ t : set α}
namespace measure
/-! ### General facts about measures -/
/-- Obtain a measure by giving a countably additive function that sends `∅` to `0`. -/
def of_measurable (m : Π (s : set α), is_measurable s → ennreal)
(m0 : m ∅ is_measurable.empty = 0)
(mU : ∀ {{f : ℕ → set α}} (h : ∀ i, is_measurable (f i)), pairwise (disjoint on f) →
m (⋃ i, f i) (is_measurable.Union h) = ∑' i, m (f i) (h i)) : measure α :=
{ m_Union := λ f hf hd,
show induced_outer_measure m _ m0 (Union f) =
∑' i, induced_outer_measure m _ m0 (f i), begin
rw [induced_outer_measure_eq m0 mU, mU hf hd],
congr, funext n, rw induced_outer_measure_eq m0 mU
end,
trimmed :=
show (induced_outer_measure m _ m0).trim = induced_outer_measure m _ m0, begin
unfold outer_measure.trim,
congr, funext s hs,
exact induced_outer_measure_eq m0 mU hs
end,
..induced_outer_measure m _ m0 }
lemma of_measurable_apply {m : Π (s : set α), is_measurable s → ennreal}
{m0 : m ∅ is_measurable.empty = 0}
{mU : ∀ {{f : ℕ → set α}} (h : ∀ i, is_measurable (f i)), pairwise (disjoint on f) →
m (⋃ i, f i) (is_measurable.Union h) = ∑' i, m (f i) (h i)}
(s : set α) (hs : is_measurable s) : of_measurable m m0 mU s = m s hs :=
induced_outer_measure_eq m0 mU hs
lemma to_outer_measure_injective : injective (to_outer_measure : measure α → outer_measure α) :=
λ ⟨m₁, u₁, h₁⟩ ⟨m₂, u₂, h₂⟩ h, by { congr, exact h }
@[ext] lemma ext (h : ∀ s, is_measurable s → μ₁ s = μ₂ s) : μ₁ = μ₂ :=
to_outer_measure_injective $ by rw [← trimmed, outer_measure.trim_congr h, trimmed]
lemma ext_iff : μ₁ = μ₂ ↔ ∀ s, is_measurable s → μ₁ s = μ₂ s :=
⟨by { rintro rfl s hs, refl }, measure.ext⟩
end measure
@[simp] lemma coe_to_outer_measure : ⇑μ.to_outer_measure = μ := rfl
lemma to_outer_measure_apply (s : set α) : μ.to_outer_measure s = μ s := rfl
lemma measure_eq_trim (s : set α) : μ s = μ.to_outer_measure.trim s :=
by rw μ.trimmed; refl
lemma measure_eq_infi (s : set α) : μ s = ⨅ t (st : s ⊆ t) (ht : is_measurable t), μ t :=
by rw [measure_eq_trim, outer_measure.trim_eq_infi]; refl
/-- A variant of `measure_eq_infi` which has a single `infi`. This is useful when applying a
lemma next that only works for non-empty infima, in which case you can use
`nonempty_measurable_superset`. -/
lemma measure_eq_infi' (μ : measure α) (s : set α) :
μ s = ⨅ t : { t // s ⊆ t ∧ is_measurable t}, μ t :=
by simp_rw [infi_subtype, infi_and, subtype.coe_mk, ← measure_eq_infi]
lemma measure_eq_induced_outer_measure :
μ s = induced_outer_measure (λ s _, μ s) is_measurable.empty μ.empty s :=
measure_eq_trim _
lemma to_outer_measure_eq_induced_outer_measure :
μ.to_outer_measure = induced_outer_measure (λ s _, μ s) is_measurable.empty μ.empty :=
μ.trimmed.symm
lemma measure_eq_extend (hs : is_measurable s) :
μ s = extend (λ t (ht : is_measurable t), μ t) s :=
by { rw [measure_eq_induced_outer_measure, induced_outer_measure_eq_extend _ _ hs],
exact μ.m_Union }
@[simp] lemma measure_empty : μ ∅ = 0 := μ.empty
lemma nonempty_of_measure_ne_zero (h : μ s ≠ 0) : s.nonempty :=
ne_empty_iff_nonempty.1 $ λ h', h $ h'.symm ▸ measure_empty
lemma measure_mono (h : s₁ ⊆ s₂) : μ s₁ ≤ μ s₂ := μ.mono h
lemma measure_mono_null (h : s₁ ⊆ s₂) (h₂ : μ s₂ = 0) : μ s₁ = 0 :=
nonpos_iff_eq_zero.1 $ h₂ ▸ measure_mono h
lemma measure_mono_top (h : s₁ ⊆ s₂) (h₁ : μ s₁ = ⊤) : μ s₂ = ⊤ :=
top_unique $ h₁ ▸ measure_mono h
lemma exists_is_measurable_superset (μ : measure α) (s : set α) :
∃ t, s ⊆ t ∧ is_measurable t ∧ μ t = μ s :=
by simpa only [← measure_eq_trim] using μ.to_outer_measure.exists_is_measurable_superset_eq_trim s
/-- A measurable set `t ⊇ s` such that `μ t = μ s`. -/
def to_measurable (μ : measure α) (s : set α) :=
classical.some (exists_is_measurable_superset μ s)
lemma subset_to_measurable (μ : measure α) (s : set α) : s ⊆ to_measurable μ s :=
(classical.some_spec (exists_is_measurable_superset μ s)).1
@[simp] lemma is_measurable_to_measurable (μ : measure α) (s : set α) :
is_measurable (to_measurable μ s) :=
(classical.some_spec (exists_is_measurable_superset μ s)).2.1
@[simp] lemma measure_to_measurable (s : set α) : μ (to_measurable μ s) = μ s :=
(classical.some_spec (exists_is_measurable_superset μ s)).2.2
lemma exists_is_measurable_superset_of_null (h : μ s = 0) :
∃ t, s ⊆ t ∧ is_measurable t ∧ μ t = 0 :=
outer_measure.exists_is_measurable_superset_of_trim_eq_zero (by rw [← measure_eq_trim, h])
lemma exists_is_measurable_superset_iff_measure_eq_zero :
(∃ t, s ⊆ t ∧ is_measurable t ∧ μ t = 0) ↔ μ s = 0 :=
⟨λ ⟨t, hst, _, ht⟩, measure_mono_null hst ht, exists_is_measurable_superset_of_null⟩
theorem measure_Union_le [encodable β] (s : β → set α) : μ (⋃ i, s i) ≤ ∑' i, μ (s i) :=
μ.to_outer_measure.Union _
lemma measure_bUnion_le {s : set β} (hs : countable s) (f : β → set α) :
μ (⋃ b ∈ s, f b) ≤ ∑' p : s, μ (f p) :=
begin
haveI := hs.to_encodable,
rw [bUnion_eq_Union],
apply measure_Union_le
end
lemma measure_bUnion_finset_le (s : finset β) (f : β → set α) :
μ (⋃ b ∈ s, f b) ≤ ∑ p in s, μ (f p) :=
begin
rw [← finset.sum_attach, finset.attach_eq_univ, ← tsum_fintype],
exact measure_bUnion_le s.countable_to_set f
end
lemma measure_bUnion_lt_top {s : set β} {f : β → set α} (hs : finite s)
(hfin : ∀ i ∈ s, μ (f i) < ⊤) : μ (⋃ i ∈ s, f i) < ⊤ :=
begin
convert (measure_bUnion_finset_le hs.to_finset f).trans_lt _,
{ ext, rw [finite.mem_to_finset] },
apply ennreal.sum_lt_top, simpa only [finite.mem_to_finset]
end
lemma measure_Union_null [encodable β] {s : β → set α} :
(∀ i, μ (s i) = 0) → μ (⋃ i, s i) = 0 :=
μ.to_outer_measure.Union_null
lemma measure_Union_null_iff [encodable ι] {s : ι → set α} :
μ (⋃ i, s i) = 0 ↔ ∀ i, μ (s i) = 0 :=
⟨λ h i, measure_mono_null (subset_Union _ _) h, measure_Union_null⟩
theorem measure_union_le (s₁ s₂ : set α) : μ (s₁ ∪ s₂) ≤ μ s₁ + μ s₂ :=
μ.to_outer_measure.union _ _
lemma measure_union_null : μ s₁ = 0 → μ s₂ = 0 → μ (s₁ ∪ s₂) = 0 :=
μ.to_outer_measure.union_null
lemma measure_union_null_iff : μ (s₁ ∪ s₂) = 0 ↔ μ s₁ = 0 ∧ μ s₂ = 0:=
⟨λ h, ⟨measure_mono_null (subset_union_left _ _) h, measure_mono_null (subset_union_right _ _) h⟩,
λ h, measure_union_null h.1 h.2⟩
lemma measure_Union [encodable β] {f : β → set α}
(hn : pairwise (disjoint on f)) (h : ∀ i, is_measurable (f i)) :
μ (⋃ i, f i) = ∑' i, μ (f i) :=
begin
rw [measure_eq_extend (is_measurable.Union h),
extend_Union is_measurable.empty _ is_measurable.Union _ hn h],
{ simp [measure_eq_extend, h] },
{ exact μ.empty },
{ exact μ.m_Union }
end
lemma measure_union (hd : disjoint s₁ s₂) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) :
μ (s₁ ∪ s₂) = μ s₁ + μ s₂ :=
begin
rw [union_eq_Union, measure_Union, tsum_fintype, fintype.sum_bool, cond, cond],
exacts [pairwise_disjoint_on_bool.2 hd, λ b, bool.cases_on b h₂ h₁]
end
lemma measure_bUnion {s : set β} {f : β → set α} (hs : countable s)
(hd : pairwise_on s (disjoint on f)) (h : ∀ b ∈ s, is_measurable (f b)) :
μ (⋃ b ∈ s, f b) = ∑' p : s, μ (f p) :=
begin
haveI := hs.to_encodable,
rw bUnion_eq_Union,
exact measure_Union (hd.on_injective subtype.coe_injective $ λ x, x.2) (λ x, h x x.2)
end
lemma measure_sUnion {S : set (set α)} (hs : countable S)
(hd : pairwise_on S disjoint) (h : ∀ s ∈ S, is_measurable s) :
μ (⋃₀ S) = ∑' s : S, μ s :=
by rw [sUnion_eq_bUnion, measure_bUnion hs hd h]
lemma measure_bUnion_finset {s : finset ι} {f : ι → set α} (hd : pairwise_on ↑s (disjoint on f))
(hm : ∀ b ∈ s, is_measurable (f b)) :
μ (⋃ b ∈ s, f b) = ∑ p in s, μ (f p) :=
begin
rw [← finset.sum_attach, finset.attach_eq_univ, ← tsum_fintype],
exact measure_bUnion s.countable_to_set hd hm
end
/-- If `s` is a countable set, then the measure of its preimage can be found as the sum of measures
of the fibers `f ⁻¹' {y}`. -/
lemma tsum_measure_preimage_singleton {s : set β} (hs : countable s) {f : α → β}
(hf : ∀ y ∈ s, is_measurable (f ⁻¹' {y})) :
∑' b : s, μ (f ⁻¹' {↑b}) = μ (f ⁻¹' s) :=
by rw [← set.bUnion_preimage_singleton, measure_bUnion hs (pairwise_on_disjoint_fiber _ _) hf]
/-- If `s` is a `finset`, then the measure of its preimage can be found as the sum of measures
of the fibers `f ⁻¹' {y}`. -/
lemma sum_measure_preimage_singleton (s : finset β) {f : α → β}
(hf : ∀ y ∈ s, is_measurable (f ⁻¹' {y})) :
∑ b in s, μ (f ⁻¹' {b}) = μ (f ⁻¹' ↑s) :=
by simp only [← measure_bUnion_finset (pairwise_on_disjoint_fiber _ _) hf,
finset.bUnion_preimage_singleton]
lemma measure_diff (h : s₂ ⊆ s₁) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂)
(h_fin : μ s₂ < ⊤) :
μ (s₁ \ s₂) = μ s₁ - μ s₂ :=
begin
refine (ennreal.add_sub_self' h_fin).symm.trans _,
rw [← measure_union disjoint_diff h₂ (h₁.diff h₂), union_diff_cancel h]
end
lemma measure_compl (h₁ : is_measurable s) (h_fin : μ s < ⊤) : μ (sᶜ) = μ univ - μ s :=
by { rw compl_eq_univ_diff, exact measure_diff (subset_univ s) is_measurable.univ h₁ h_fin }
lemma sum_measure_le_measure_univ {s : finset ι} {t : ι → set α} (h : ∀ i ∈ s, is_measurable (t i))
(H : pairwise_on ↑s (disjoint on t)) :
∑ i in s, μ (t i) ≤ μ (univ : set α) :=
by { rw ← measure_bUnion_finset H h, exact measure_mono (subset_univ _) }
lemma tsum_measure_le_measure_univ {s : ι → set α} (hs : ∀ i, is_measurable (s i))
(H : pairwise (disjoint on s)) :
∑' i, μ (s i) ≤ μ (univ : set α) :=
begin
rw [ennreal.tsum_eq_supr_sum],
exact supr_le (λ s, sum_measure_le_measure_univ (λ i hi, hs i) (λ i hi j hj hij, H i j hij))
end
/-- Pigeonhole principle for measure spaces: if `∑' i, μ (s i) > μ univ`, then
one of the intersections `s i ∩ s j` is not empty. -/
lemma exists_nonempty_inter_of_measure_univ_lt_tsum_measure (μ : measure α) {s : ι → set α}
(hs : ∀ i, is_measurable (s i)) (H : μ (univ : set α) < ∑' i, μ (s i)) :
∃ i j (h : i ≠ j), (s i ∩ s j).nonempty :=
begin
contrapose! H,
apply tsum_measure_le_measure_univ hs,
exact λ i j hij x hx, H i j hij ⟨x, hx⟩
end
/-- Pigeonhole principle for measure spaces: if `s` is a `finset` and
`∑ i in s, μ (t i) > μ univ`, then one of the intersections `t i ∩ t j` is not empty. -/
lemma exists_nonempty_inter_of_measure_univ_lt_sum_measure (μ : measure α) {s : finset ι}
{t : ι → set α} (h : ∀ i ∈ s, is_measurable (t i)) (H : μ (univ : set α) < ∑ i in s, μ (t i)) :
∃ (i ∈ s) (j ∈ s) (h : i ≠ j), (t i ∩ t j).nonempty :=
begin
contrapose! H,
apply sum_measure_le_measure_univ h,
exact λ i hi j hj hij x hx, H i hi j hj hij ⟨x, hx⟩
end
/-- Continuity from below: the measure of the union of a directed sequence of measurable sets
is the supremum of the measures. -/
lemma measure_Union_eq_supr [encodable ι] {s : ι → set α} (h : ∀ i, is_measurable (s i))
(hd : directed (⊆) s) : μ (⋃ i, s i) = ⨆ i, μ (s i) :=
begin
by_cases hι : nonempty ι, swap,
{ simp only [supr_of_empty hι, Union], exact measure_empty },
resetI,
refine le_antisymm _ (supr_le $ λ i, measure_mono $ subset_Union _ _),
have : ∀ n, is_measurable (disjointed (λ n, ⋃ b ∈ encodable.decode2 ι n, s b) n) :=
is_measurable.disjointed (is_measurable.bUnion_decode2 h),
rw [← encodable.Union_decode2, ← Union_disjointed, measure_Union disjoint_disjointed this,
ennreal.tsum_eq_supr_nat],
simp only [← measure_bUnion_finset (disjoint_disjointed.pairwise_on _) (λ n _, this n)],
refine supr_le (λ n, _),
refine le_trans (_ : _ ≤ μ (⋃ (k ∈ finset.range n) (i ∈ encodable.decode2 ι k), s i)) _,
exact measure_mono (bUnion_subset_bUnion_right (λ k hk, disjointed_subset)),
simp only [← finset.bUnion_option_to_finset, ← finset.bUnion_bind],
generalize : (finset.range n).bind (λ k, (encodable.decode2 ι k).to_finset) = t,
rcases hd.finset_le t with ⟨i, hi⟩,
exact le_supr_of_le i (measure_mono $ bUnion_subset hi)
end
lemma measure_bUnion_eq_supr {s : ι → set α} {t : set ι} (ht : countable t)
(h : ∀ i ∈ t, is_measurable (s i)) (hd : directed_on ((⊆) on s) t) :
μ (⋃ i ∈ t, s i) = ⨆ i ∈ t, μ (s i) :=
begin
haveI := ht.to_encodable,
rw [bUnion_eq_Union, measure_Union_eq_supr (set_coe.forall'.1 h) hd.directed_coe,
supr_subtype'],
refl
end
/-- Continuity from above: the measure of the intersection of a decreasing sequence of measurable
sets is the infimum of the measures. -/
lemma measure_Inter_eq_infi [encodable ι] {s : ι → set α}
(h : ∀ i, is_measurable (s i)) (hd : directed (⊇) s)
(hfin : ∃ i, μ (s i) < ⊤) :
μ (⋂ i, s i) = (⨅ i, μ (s i)) :=
begin
rcases hfin with ⟨k, hk⟩,
rw [← ennreal.sub_sub_cancel (by exact hk) (infi_le _ k), ennreal.sub_infi,
← ennreal.sub_sub_cancel (by exact hk) (measure_mono (Inter_subset _ k)),
← measure_diff (Inter_subset _ k) (h k) (is_measurable.Inter h)
(lt_of_le_of_lt (measure_mono (Inter_subset _ k)) hk),
diff_Inter, measure_Union_eq_supr],
{ congr' 1,
refine le_antisymm (supr_le_supr2 $ λ i, _) (supr_le_supr $ λ i, _),
{ rcases hd i k with ⟨j, hji, hjk⟩,
use j,
rw [← measure_diff hjk (h _) (h _) ((measure_mono hjk).trans_lt hk)],
exact measure_mono (diff_subset_diff_right hji) },
{ rw [ennreal.sub_le_iff_le_add, ← measure_union disjoint_diff.symm ((h k).diff (h i)) (h i),
set.union_comm],
exact measure_mono (diff_subset_iff.1 $ subset.refl _) } },
{ exact λ i, (h k).diff (h i) },
{ exact hd.mono_comp _ (λ _ _, diff_subset_diff_right) }
end
lemma measure_eq_inter_diff (hs : is_measurable s) (ht : is_measurable t) :
μ s = μ (s ∩ t) + μ (s \ t) :=
have hd : disjoint (s ∩ t) (s \ t) := assume a ⟨⟨_, hs⟩, _, hns⟩, hns hs ,
by rw [← measure_union hd (hs.inter ht) (hs.diff ht), inter_union_diff s t]
lemma measure_union_add_inter (hs : is_measurable s) (ht : is_measurable t) :
μ (s ∪ t) + μ (s ∩ t) = μ s + μ t :=
by { rw [measure_eq_inter_diff (hs.union ht) ht, set.union_inter_cancel_right,
union_diff_right, measure_eq_inter_diff hs ht], ac_refl }
/-- Continuity from below: the measure of the union of an increasing sequence of measurable sets
is the limit of the measures. -/
lemma tendsto_measure_Union {s : ℕ → set α} (hs : ∀ n, is_measurable (s n)) (hm : monotone s) :
tendsto (μ ∘ s) at_top (𝓝 (μ (⋃ n, s n))) :=
begin
rw measure_Union_eq_supr hs (directed_of_sup hm),
exact tendsto_at_top_supr (assume n m hnm, measure_mono $ hm hnm)
end
/-- Continuity from above: the measure of the intersection of a decreasing sequence of measurable
sets is the limit of the measures. -/
lemma tendsto_measure_Inter {s : ℕ → set α}
(hs : ∀ n, is_measurable (s n)) (hm : ∀ ⦃n m⦄, n ≤ m → s m ⊆ s n) (hf : ∃ i, μ (s i) < ⊤) :
tendsto (μ ∘ s) at_top (𝓝 (μ (⋂ n, s n))) :=
begin
rw measure_Inter_eq_infi hs (directed_of_sup hm) hf,
exact tendsto_at_top_infi (assume n m hnm, measure_mono $ hm hnm),
end
/-- One direction of the Borel-Cantelli lemma: if (sᵢ) is a sequence of measurable sets such that
∑ μ sᵢ exists, then the limit superior of the sᵢ is a null set. -/
lemma measure_limsup_eq_zero {s : ℕ → set α} (hs : ∀ i, is_measurable (s i))
(hs' : ∑' i, μ (s i) ≠ ⊤) : μ (limsup at_top s) = 0 :=
begin
rw limsup_eq_infi_supr_of_nat',
-- We will show that both `μ (⨅ n, ⨆ i, s (i + n))` and `0` are the limit of `μ (⊔ i, s (i + n))`
-- as `n` tends to infinity. For the former, we use continuity from above.
refine tendsto_nhds_unique
(tendsto_measure_Inter (λ i, is_measurable.Union (λ b, hs (b + i))) _
⟨0, lt_of_le_of_lt (measure_Union_le s) (ennreal.lt_top_iff_ne_top.2 hs')⟩) _,
{ intros n m hnm x,
simp only [set.mem_Union],
exact λ ⟨i, hi⟩, ⟨i + (m - n), by simpa only [add_assoc, nat.sub_add_cancel hnm] using hi⟩ },
{ -- For the latter, notice that, `μ (⨆ i, s (i + n)) ≤ ∑' s (i + n)`. Since the right hand side
-- converges to `0` by hypothesis, so does the former and the proof is complete.
exact (tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds
(ennreal.tendsto_sum_nat_add (μ ∘ s) hs')
(eventually_of_forall (by simp only [forall_const, zero_le]))
(eventually_of_forall (λ i, measure_Union_le _))) }
end
lemma measure_if {x : β} {t : set β} {s : set α} {μ : measure α} :
μ (if x ∈ t then s else ∅) = indicator t (λ _, μ s) x :=
by { split_ifs; simp [h] }
end
section outer_measure
variables [ms : measurable_space α] {s t : set α}
include ms
/-- Obtain a measure by giving an outer measure where all sets in the σ-algebra are
Carathéodory measurable. -/
def outer_measure.to_measure (m : outer_measure α) (h : ms ≤ m.caratheodory) : measure α :=
measure.of_measurable (λ s _, m s) m.empty
(λ f hf hd, m.Union_eq_of_caratheodory (λ i, h _ (hf i)) hd)
lemma le_to_outer_measure_caratheodory (μ : measure α) : ms ≤ μ.to_outer_measure.caratheodory :=
begin
assume s hs,
rw to_outer_measure_eq_induced_outer_measure,
refine outer_measure.of_function_caratheodory (λ t, le_infi $ λ ht, _),
rw [← measure_eq_extend (ht.inter hs),
← measure_eq_extend (ht.diff hs),
← measure_union _ (ht.inter hs) (ht.diff hs),
inter_union_diff],
exact le_refl _,
exact λ x ⟨⟨_, h₁⟩, _, h₂⟩, h₂ h₁
end
@[simp] lemma to_measure_to_outer_measure (m : outer_measure α) (h : ms ≤ m.caratheodory) :
(m.to_measure h).to_outer_measure = m.trim := rfl
@[simp] lemma to_measure_apply (m : outer_measure α) (h : ms ≤ m.caratheodory)
{s : set α} (hs : is_measurable s) : m.to_measure h s = m s :=
m.trim_eq hs
lemma le_to_measure_apply (m : outer_measure α) (h : ms ≤ m.caratheodory) (s : set α) :
m s ≤ m.to_measure h s :=
m.le_trim s
@[simp] lemma to_outer_measure_to_measure {μ : measure α} :
μ.to_outer_measure.to_measure (le_to_outer_measure_caratheodory _) = μ :=
measure.ext $ λ s, μ.to_outer_measure.trim_eq
end outer_measure
variables [measurable_space α] [measurable_space β] [measurable_space γ]
variables {μ μ₁ μ₂ ν ν' ν₁ ν₂ : measure α} {s s' t : set α}
namespace measure
protected lemma caratheodory (μ : measure α) (hs : is_measurable s) : μ (t ∩ s) + μ (t \ s) = μ t :=
(le_to_outer_measure_caratheodory μ s hs t).symm
/-! ### The `ennreal`-module of measures -/
instance : has_zero (measure α) :=
⟨{ to_outer_measure := 0,
m_Union := λ f hf hd, tsum_zero.symm,
trimmed := outer_measure.trim_zero }⟩
@[simp] theorem zero_to_outer_measure : (0 : measure α).to_outer_measure = 0 := rfl
@[simp, norm_cast] theorem coe_zero : ⇑(0 : measure α) = 0 := rfl
lemma eq_zero_of_not_nonempty (h : ¬nonempty α) (μ : measure α) : μ = 0 :=
ext $ λ s hs, by simp only [eq_empty_of_not_nonempty h s, measure_empty]
instance : inhabited (measure α) := ⟨0⟩
instance : has_add (measure α) :=
⟨λ μ₁ μ₂, {
to_outer_measure := μ₁.to_outer_measure + μ₂.to_outer_measure,
m_Union := λ s hs hd,
show μ₁ (⋃ i, s i) + μ₂ (⋃ i, s i) = ∑' i, (μ₁ (s i) + μ₂ (s i)),
by rw [ennreal.tsum_add, measure_Union hd hs, measure_Union hd hs],
trimmed := by rw [outer_measure.trim_add, μ₁.trimmed, μ₂.trimmed] }⟩
@[simp] theorem add_to_outer_measure (μ₁ μ₂ : measure α) :
(μ₁ + μ₂).to_outer_measure = μ₁.to_outer_measure + μ₂.to_outer_measure := rfl
@[simp, norm_cast] theorem coe_add (μ₁ μ₂ : measure α) : ⇑(μ₁ + μ₂) = μ₁ + μ₂ := rfl
theorem add_apply (μ₁ μ₂ : measure α) (s : set α) : (μ₁ + μ₂) s = μ₁ s + μ₂ s := rfl
instance add_comm_monoid : add_comm_monoid (measure α) :=
to_outer_measure_injective.add_comm_monoid to_outer_measure zero_to_outer_measure
add_to_outer_measure
instance : has_scalar ennreal (measure α) :=
⟨λ c μ,
{ to_outer_measure := c • μ.to_outer_measure,
m_Union := λ s hs hd, by simp [measure_Union, *, ennreal.tsum_mul_left],
trimmed := by rw [outer_measure.trim_smul, μ.trimmed] }⟩
@[simp] theorem smul_to_outer_measure (c : ennreal) (μ : measure α) :
(c • μ).to_outer_measure = c • μ.to_outer_measure :=
rfl
@[simp, norm_cast] theorem coe_smul (c : ennreal) (μ : measure α) : ⇑(c • μ) = c • μ :=
rfl
theorem smul_apply (c : ennreal) (μ : measure α) (s : set α) : (c • μ) s = c * μ s :=
rfl
instance : semimodule ennreal (measure α) :=
injective.semimodule ennreal ⟨to_outer_measure, zero_to_outer_measure, add_to_outer_measure⟩
to_outer_measure_injective smul_to_outer_measure
/-! ### The complete lattice of measures -/
instance : partial_order (measure α) :=
{ le := λ m₁ m₂, ∀ s, is_measurable s → m₁ s ≤ m₂ s,
le_refl := assume m s hs, le_refl _,
le_trans := assume m₁ m₂ m₃ h₁ h₂ s hs, le_trans (h₁ s hs) (h₂ s hs),
le_antisymm := assume m₁ m₂ h₁ h₂, ext $
assume s hs, le_antisymm (h₁ s hs) (h₂ s hs) }
theorem le_iff : μ₁ ≤ μ₂ ↔ ∀ s, is_measurable s → μ₁ s ≤ μ₂ s := iff.rfl
theorem to_outer_measure_le : μ₁.to_outer_measure ≤ μ₂.to_outer_measure ↔ μ₁ ≤ μ₂ :=
by rw [← μ₂.trimmed, outer_measure.le_trim_iff]; refl
theorem le_iff' : μ₁ ≤ μ₂ ↔ ∀ s, μ₁ s ≤ μ₂ s :=
to_outer_measure_le.symm
theorem lt_iff : μ < ν ↔ μ ≤ ν ∧ ∃ s, is_measurable s ∧ μ s < ν s :=
lt_iff_le_not_le.trans $ and_congr iff.rfl $ by simp only [le_iff, not_forall, not_le, exists_prop]
theorem lt_iff' : μ < ν ↔ μ ≤ ν ∧ ∃ s, μ s < ν s :=
lt_iff_le_not_le.trans $ and_congr iff.rfl $ by simp only [le_iff', not_forall, not_le]
-- TODO: add typeclasses for `∀ c, monotone ((*) c)` and `∀ c, monotone ((+) c)`
protected lemma add_le_add_left (ν : measure α) (hμ : μ₁ ≤ μ₂) : ν + μ₁ ≤ ν + μ₂ :=
λ s hs, add_le_add_left (hμ s hs) _
protected lemma add_le_add_right (hμ : μ₁ ≤ μ₂) (ν : measure α) : μ₁ + ν ≤ μ₂ + ν :=
λ s hs, add_le_add_right (hμ s hs) _
protected lemma add_le_add (hμ : μ₁ ≤ μ₂) (hν : ν₁ ≤ ν₂) :
μ₁ + ν₁ ≤ μ₂ + ν₂ :=
λ s hs, add_le_add (hμ s hs) (hν s hs)
protected lemma le_add_left (h : μ ≤ ν) : μ ≤ ν' + ν :=
λ s hs, le_add_left (h s hs)
protected lemma le_add_right (h : μ ≤ ν) : μ ≤ ν + ν' :=
λ s hs, le_add_right (h s hs)
section Inf
variables {m : set (measure α)}
lemma Inf_caratheodory (s : set α) (hs : is_measurable s) :
(Inf (to_outer_measure '' m)).caratheodory.is_measurable' s :=
begin
rw [outer_measure.Inf_eq_bounded_by_Inf_gen],
refine outer_measure.bounded_by_caratheodory (λ t, _),
simp only [outer_measure.Inf_gen, le_infi_iff, ball_image_iff, coe_to_outer_measure,
measure_eq_infi t],
intros μ hμ u htu hu,
have hm : ∀ {s t}, s ⊆ t → outer_measure.Inf_gen (to_outer_measure '' m) s ≤ μ t,
{ intros s t hst,
rw [outer_measure.Inf_gen_def],
refine infi_le_of_le (μ.to_outer_measure) (infi_le_of_le (mem_image_of_mem _ hμ) _),
rw [to_outer_measure_apply],
refine measure_mono hst },
rw [measure_eq_inter_diff hu hs],
refine add_le_add (hm $ inter_subset_inter_left _ htu) (hm $ diff_subset_diff_left htu)
end
instance : has_Inf (measure α) :=
⟨λ m, (Inf (to_outer_measure '' m)).to_measure $ Inf_caratheodory⟩
lemma Inf_apply (hs : is_measurable s) : Inf m s = Inf (to_outer_measure '' m) s :=
to_measure_apply _ _ hs
private lemma measure_Inf_le (h : μ ∈ m) : Inf m ≤ μ :=
have Inf (to_outer_measure '' m) ≤ μ.to_outer_measure := Inf_le (mem_image_of_mem _ h),
assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s
private lemma measure_le_Inf (h : ∀ μ' ∈ m, μ ≤ μ') : μ ≤ Inf m :=
have μ.to_outer_measure ≤ Inf (to_outer_measure '' m) :=
le_Inf $ ball_image_of_ball $ assume μ hμ, to_outer_measure_le.2 $ h _ hμ,
assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s
instance : complete_lattice (measure α) :=
{ bot := 0,
bot_le := assume a s hs, by exact bot_le,
/- Adding an explicit `top` makes `leanchecker` fail, see lean#364, disable for now
top := (⊤ : outer_measure α).to_measure (by rw [outer_measure.top_caratheodory]; exact le_top),
le_top := assume a s hs,
by cases s.eq_empty_or_nonempty with h h;
simp [h, to_measure_apply ⊤ _ hs, outer_measure.top_apply],
-/
.. complete_lattice_of_Inf (measure α) (λ ms, ⟨λ _, measure_Inf_le, λ _, measure_le_Inf⟩) }
end Inf
protected lemma zero_le (μ : measure α) : 0 ≤ μ := bot_le
lemma nonpos_iff_eq_zero' : μ ≤ 0 ↔ μ = 0 :=
μ.zero_le.le_iff_eq
@[simp] lemma measure_univ_eq_zero : μ univ = 0 ↔ μ = 0 :=
⟨λ h, bot_unique $ λ s hs, trans_rel_left (≤) (measure_mono (subset_univ s)) h, λ h, h.symm ▸ rfl⟩
/-! ### Pushforward and pullback -/
/-- Lift a linear map between `outer_measure` spaces such that for each measure `μ` every measurable
set is caratheodory-measurable w.r.t. `f μ` to a linear map between `measure` spaces. -/
def lift_linear (f : outer_measure α →ₗ[ennreal] outer_measure β)
(hf : ∀ μ : measure α, ‹_› ≤ (f μ.to_outer_measure).caratheodory) :
measure α →ₗ[ennreal] measure β :=
{ to_fun := λ μ, (f μ.to_outer_measure).to_measure (hf μ),
map_add' := λ μ₁ μ₂, ext $ λ s hs, by simp [hs],
map_smul' := λ c μ, ext $ λ s hs, by simp [hs] }
@[simp] lemma lift_linear_apply {f : outer_measure α →ₗ[ennreal] outer_measure β} (hf)
{s : set β} (hs : is_measurable s) : lift_linear f hf μ s = f μ.to_outer_measure s :=
to_measure_apply _ _ hs
lemma le_lift_linear_apply {f : outer_measure α →ₗ[ennreal] outer_measure β} (hf) (s : set β) :
f μ.to_outer_measure s ≤ lift_linear f hf μ s :=
le_to_measure_apply _ _ s
/-- The pushforward of a measure. It is defined to be `0` if `f` is not a measurable function. -/
def map (f : α → β) : measure α →ₗ[ennreal] measure β :=
if hf : measurable f then
lift_linear (outer_measure.map f) $ λ μ s hs t,
le_to_outer_measure_caratheodory μ _ (hf hs) (f ⁻¹' t)
else 0
/-- We can evaluate the pushforward on measurable sets. For non-measurable sets, see
`measure_theory.measure.le_map_apply` and `measurable_equiv.map_apply`. -/
@[simp] theorem map_apply {f : α → β} (hf : measurable f) {s : set β} (hs : is_measurable s) :
map f μ s = μ (f ⁻¹' s) :=
by simp [map, dif_pos hf, hs]
@[simp] lemma map_id : map id μ = μ :=
ext $ λ s, map_apply measurable_id
lemma map_map {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) :
map g (map f μ) = map (g ∘ f) μ :=
ext $ λ s hs,
by simp [hf, hg, hs, hg hs, hg.comp hf, ← preimage_comp]
lemma map_mono {f : α → β} (hf : measurable f) (h : μ ≤ ν) : map f μ ≤ map f ν :=
λ s hs, by simp [hf, hs, h _ (hf hs)]
/-- Even if `s` is not measurable, we can bound `map f μ s` from below.
See also `measurable_equiv.map_apply`. -/
theorem le_map_apply {f : α → β} (hf : measurable f) (s : set β) : μ (f ⁻¹' s) ≤ map f μ s :=
begin
rw [measure_eq_infi' (map f μ)], refine le_infi _, rintro ⟨t, hst, ht⟩,
convert measure_mono (preimage_mono hst),
exact map_apply hf ht
end
/-- Pullback of a `measure`. If `f` sends each `measurable` set to a `measurable` set, then for each
measurable set `s` we have `comap f μ s = μ (f '' s)`. -/
def comap (f : α → β) : measure β →ₗ[ennreal] measure α :=
if hf : injective f ∧ ∀ s, is_measurable s → is_measurable (f '' s) then
lift_linear (outer_measure.comap f) $ λ μ s hs t,
begin
simp only [coe_to_outer_measure, outer_measure.comap_apply, ← image_inter hf.1,
image_diff hf.1],
apply le_to_outer_measure_caratheodory,
exact hf.2 s hs
end
else 0
lemma comap_apply (f : α → β) (hfi : injective f)
(hf : ∀ s, is_measurable s → is_measurable (f '' s)) (μ : measure β) (hs : is_measurable s) :
comap f μ s = μ (f '' s) :=
begin
rw [comap, dif_pos, lift_linear_apply _ hs, outer_measure.comap_apply, coe_to_outer_measure],
exact ⟨hfi, hf⟩
end
/-! ### Restricting a measure -/
/-- Restrict a measure `μ` to a set `s` as an `ennreal`-linear map. -/
def restrictₗ (s : set α) : measure α →ₗ[ennreal] measure α :=
lift_linear (outer_measure.restrict s) $ λ μ s' hs' t,
begin
suffices : μ (s ∩ t) = μ (s ∩ t ∩ s') + μ (s ∩ t \ s'),
{ simpa [← set.inter_assoc, set.inter_comm _ s, ← inter_diff_assoc] },
exact le_to_outer_measure_caratheodory _ _ hs' _,
end
/-- Restrict a measure `μ` to a set `s`. -/
def restrict (μ : measure α) (s : set α) : measure α := restrictₗ s μ
@[simp] lemma restrictₗ_apply (s : set α) (μ : measure α) :
restrictₗ s μ = μ.restrict s :=
rfl
@[simp] lemma restrict_apply (ht : is_measurable t) : μ.restrict s t = μ (t ∩ s) :=
by simp [← restrictₗ_apply, restrictₗ, ht]
lemma restrict_apply_univ (s : set α) : μ.restrict s univ = μ s :=
by rw [restrict_apply is_measurable.univ, set.univ_inter]
lemma le_restrict_apply (s t : set α) :
μ (t ∩ s) ≤ μ.restrict s t :=
by { rw [restrict, restrictₗ], convert le_lift_linear_apply _ t, simp }
@[simp] lemma restrict_add (μ ν : measure α) (s : set α) :
(μ + ν).restrict s = μ.restrict s + ν.restrict s :=
(restrictₗ s).map_add μ ν
@[simp] lemma restrict_zero (s : set α) : (0 : measure α).restrict s = 0 :=
(restrictₗ s).map_zero
@[simp] lemma restrict_smul (c : ennreal) (μ : measure α) (s : set α) :
(c • μ).restrict s = c • μ.restrict s :=
(restrictₗ s).map_smul c μ
@[simp] lemma restrict_restrict (hs : is_measurable s) :
(μ.restrict t).restrict s = μ.restrict (s ∩ t) :=
ext $ λ u hu, by simp [*, set.inter_assoc]
lemma restrict_apply_eq_zero (ht : is_measurable t) : μ.restrict s t = 0 ↔ μ (t ∩ s) = 0 :=
by rw [restrict_apply ht]
lemma measure_inter_eq_zero_of_restrict (h : μ.restrict s t = 0) : μ (t ∩ s) = 0 :=
nonpos_iff_eq_zero.1 (h ▸ le_restrict_apply _ _)
lemma restrict_apply_eq_zero' (hs : is_measurable s) : μ.restrict s t = 0 ↔ μ (t ∩ s) = 0 :=
begin
refine ⟨measure_inter_eq_zero_of_restrict, λ h, _⟩,
rcases exists_is_measurable_superset_of_null h with ⟨t', htt', ht', ht'0⟩,
apply measure_mono_null ((inter_subset _ _ _).1 htt'),
rw [restrict_apply (hs.compl.union ht'), union_inter_distrib_right, compl_inter_self,
set.empty_union],
exact measure_mono_null (inter_subset_left _ _) ht'0
end
@[simp] lemma restrict_eq_zero : μ.restrict s = 0 ↔ μ s = 0 :=
by rw [← measure_univ_eq_zero, restrict_apply_univ]
@[simp] lemma restrict_empty : μ.restrict ∅ = 0 := ext $ λ s hs, by simp [hs]
@[simp] lemma restrict_univ : μ.restrict univ = μ := ext $ λ s hs, by simp [hs]
lemma restrict_union_apply (h : disjoint (t ∩ s) (t ∩ s')) (hs : is_measurable s)
(hs' : is_measurable s') (ht : is_measurable t) :
μ.restrict (s ∪ s') t = μ.restrict s t + μ.restrict s' t :=
begin
simp only [restrict_apply, ht, set.inter_union_distrib_left],
exact measure_union h (ht.inter hs) (ht.inter hs'),
end
lemma restrict_union (h : disjoint s t) (hs : is_measurable s) (ht : is_measurable t) :
μ.restrict (s ∪ t) = μ.restrict s + μ.restrict t :=
ext $ λ t' ht', restrict_union_apply (h.mono inf_le_right inf_le_right) hs ht ht'
lemma restrict_union_add_inter (hs : is_measurable s) (ht : is_measurable t) :
μ.restrict (s ∪ t) + μ.restrict (s ∩ t) = μ.restrict s + μ.restrict t :=
begin
ext1 u hu,
simp only [add_apply, restrict_apply hu, inter_union_distrib_left],
convert measure_union_add_inter (hu.inter hs) (hu.inter ht) using 3,
rw [set.inter_left_comm (u ∩ s), set.inter_assoc, ← set.inter_assoc u u, set.inter_self]
end
@[simp] lemma restrict_add_restrict_compl (hs : is_measurable s) :
μ.restrict s + μ.restrict sᶜ = μ :=
by rw [← restrict_union disjoint_compl_right hs hs.compl, union_compl_self, restrict_univ]
@[simp] lemma restrict_compl_add_restrict (hs : is_measurable s) :
μ.restrict sᶜ + μ.restrict s = μ :=
by rw [add_comm, restrict_add_restrict_compl hs]
lemma restrict_union_le (s s' : set α) : μ.restrict (s ∪ s') ≤ μ.restrict s + μ.restrict s' :=
begin
intros t ht,
suffices : μ (t ∩ s ∪ t ∩ s') ≤ μ (t ∩ s) + μ (t ∩ s'),
by simpa [ht, inter_union_distrib_left],
apply measure_union_le
end
lemma restrict_Union_apply [encodable ι] {s : ι → set α} (hd : pairwise (disjoint on s))
(hm : ∀ i, is_measurable (s i)) {t : set α} (ht : is_measurable t) :
μ.restrict (⋃ i, s i) t = ∑' i, μ.restrict (s i) t :=
begin
simp only [restrict_apply, ht, inter_Union],
exact measure_Union (λ i j hij, (hd i j hij).mono inf_le_right inf_le_right)
(λ i, ht.inter (hm i))
end
lemma restrict_Union_apply_eq_supr [encodable ι] {s : ι → set α}
(hm : ∀ i, is_measurable (s i)) (hd : directed (⊆) s) {t : set α} (ht : is_measurable t) :
μ.restrict (⋃ i, s i) t = ⨆ i, μ.restrict (s i) t :=
begin
simp only [restrict_apply ht, inter_Union],
rw [measure_Union_eq_supr],
exacts [λ i, ht.inter (hm i), hd.mono_comp _ (λ s₁ s₂, inter_subset_inter_right _)]
end
lemma restrict_map {f : α → β} (hf : measurable f) {s : set β} (hs : is_measurable s) :
(map f μ).restrict s = map f (μ.restrict $ f ⁻¹' s) :=
ext $ λ t ht, by simp [*, hf ht]
lemma map_comap_subtype_coe (hs : is_measurable s) :
(map (coe : s → α)).comp (comap coe) = restrictₗ s :=
linear_map.ext $ λ μ, ext $ λ t ht,
by rw [restrictₗ_apply, restrict_apply ht, linear_map.comp_apply,
map_apply measurable_subtype_coe ht,
comap_apply (coe : s → α) subtype.val_injective (λ _, hs.subtype_image) _
(measurable_subtype_coe ht), subtype.image_preimage_coe]
/-- Restriction of a measure to a subset is monotone both in set and in measure. -/
@[mono] lemma restrict_mono ⦃s s' : set α⦄ (hs : s ⊆ s') ⦃μ ν : measure α⦄ (hμν : μ ≤ ν) :
μ.restrict s ≤ ν.restrict s' :=
assume t ht,
calc μ.restrict s t = μ (t ∩ s) : restrict_apply ht
... ≤ μ (t ∩ s') : measure_mono $ inter_subset_inter_right _ hs
... ≤ ν (t ∩ s') : le_iff'.1 hμν (t ∩ s')
... = ν.restrict s' t : (restrict_apply ht).symm
lemma restrict_le_self : μ.restrict s ≤ μ :=
assume t ht,
calc μ.restrict s t = μ (t ∩ s) : restrict_apply ht
... ≤ μ t : measure_mono $ inter_subset_left t s
lemma restrict_congr_meas (hs : is_measurable s) :
μ.restrict s = ν.restrict s ↔ ∀ t ⊆ s, is_measurable t → μ t = ν t :=
⟨λ H t hts ht,
by rw [← inter_eq_self_of_subset_left hts, ← restrict_apply ht, H, restrict_apply ht],
λ H, ext $ λ t ht,
by rw [restrict_apply ht, restrict_apply ht, H _ (inter_subset_right _ _) (ht.inter hs)]⟩
lemma restrict_congr_mono (hs : s ⊆ t) (hm : is_measurable s) (h : μ.restrict t = ν.restrict t) :
μ.restrict s = ν.restrict s :=
by rw [← inter_eq_self_of_subset_left hs, ← restrict_restrict hm, h, restrict_restrict hm]
/-- If two measures agree on all measurable subsets of `s` and `t`, then they agree on all
measurable subsets of `s ∪ t`. -/
lemma restrict_union_congr (hsm : is_measurable s) (htm : is_measurable t) :
μ.restrict (s ∪ t) = ν.restrict (s ∪ t) ↔
μ.restrict s = ν.restrict s ∧ μ.restrict t = ν.restrict t :=
begin
refine ⟨λ h, ⟨restrict_congr_mono (subset_union_left _ _) hsm h,
restrict_congr_mono (subset_union_right _ _) htm h⟩, _⟩,
simp only [restrict_congr_meas, hsm, htm, hsm.union htm],
rintros ⟨hs, ht⟩ u hu hum,
rw [measure_eq_inter_diff hum hsm, measure_eq_inter_diff hum hsm,
hs _ (inter_subset_right _ _) (hum.inter hsm),
ht _ (diff_subset_iff.2 hu) (hum.diff hsm)]
end
lemma restrict_finset_bUnion_congr {s : finset ι} {t : ι → set α}
(htm : ∀ i ∈ s, is_measurable (t i)) :
μ.restrict (⋃ i ∈ s, t i) = ν.restrict (⋃ i ∈ s, t i) ↔
∀ i ∈ s, μ.restrict (t i) = ν.restrict (t i) :=
begin
induction s using finset.induction_on with i s hi hs, { simp },
simp only [finset.mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at htm ⊢,
simp only [finset.bUnion_insert, ← hs htm.2],
exact restrict_union_congr htm.1 (s.is_measurable_bUnion htm.2)
end
lemma restrict_Union_congr [encodable ι] {s : ι → set α} (hm : ∀ i, is_measurable (s i)) :
μ.restrict (⋃ i, s i) = ν.restrict (⋃ i, s i) ↔
∀ i, μ.restrict (s i) = ν.restrict (s i) :=
begin
refine ⟨λ h i, restrict_congr_mono (subset_Union _ _) (hm i) h, λ h, _⟩,
ext1 t ht,
have M : ∀ t : finset ι, is_measurable (⋃ i ∈ t, s i) :=
λ t, t.is_measurable_bUnion (λ i _, hm i),
have D : directed (⊆) (λ t : finset ι, ⋃ i ∈ t, s i) :=
directed_of_sup (λ t₁ t₂ ht, bUnion_subset_bUnion_left ht),
rw [Union_eq_Union_finset],
simp only [restrict_Union_apply_eq_supr M D ht,
(restrict_finset_bUnion_congr (λ i hi, hm i)).2 (λ i hi, h i)],
end
lemma restrict_bUnion_congr {s : set ι} {t : ι → set α} (hc : countable s)
(htm : ∀ i ∈ s, is_measurable (t i)) :
μ.restrict (⋃ i ∈ s, t i) = ν.restrict (⋃ i ∈ s, t i) ↔
∀ i ∈ s, μ.restrict (t i) = ν.restrict (t i) :=
begin
simp only [bUnion_eq_Union, set_coe.forall'] at htm ⊢,
haveI := hc.to_encodable,
exact restrict_Union_congr htm
end
lemma restrict_sUnion_congr {S : set (set α)} (hc : countable S) (hm : ∀ s ∈ S, is_measurable s) :
μ.restrict (⋃₀ S) = ν.restrict (⋃₀ S) ↔ ∀ s ∈ S, μ.restrict s = ν.restrict s :=
by rw [sUnion_eq_bUnion, restrict_bUnion_congr hc hm]
/-- This lemma shows that `restrict` and `to_outer_measure` commute. Note that the LHS has a
restrict on measures and the RHS has a restrict on outer measures. -/
lemma restrict_to_outer_measure_eq_to_outer_measure_restrict (h : is_measurable s) :
(μ.restrict s).to_outer_measure = outer_measure.restrict s μ.to_outer_measure :=
by simp_rw [restrict, restrictₗ, lift_linear, linear_map.coe_mk, to_measure_to_outer_measure,
outer_measure.restrict_trim h, μ.trimmed]
/-- This lemma shows that `Inf` and `restrict` commute for measures. -/
lemma restrict_Inf_eq_Inf_restrict {m : set (measure α)} (hm : m.nonempty) (ht : is_measurable t) :
(Inf m).restrict t = Inf ((λ μ : measure α, μ.restrict t) '' m) :=
begin
ext1 s hs,
simp_rw [Inf_apply hs, restrict_apply hs, Inf_apply (is_measurable.inter hs ht), set.image_image,
restrict_to_outer_measure_eq_to_outer_measure_restrict ht, ← set.image_image _ to_outer_measure,
← outer_measure.restrict_Inf_eq_Inf_restrict _ (hm.image _),
outer_measure.restrict_apply]
end
/-! ### Extensionality results -/
/-- Two measures are equal if they have equal restrictions on a spanning collection of sets
(formulated using `Union`). -/
lemma ext_iff_of_Union_eq_univ [encodable ι] {s : ι → set α}
(hm : ∀ i, is_measurable (s i)) (hs : (⋃ i, s i) = univ) :
μ = ν ↔ ∀ i, μ.restrict (s i) = ν.restrict (s i) :=
by rw [← restrict_Union_congr hm, hs, restrict_univ, restrict_univ]
alias ext_iff_of_Union_eq_univ ↔ _ measure_theory.measure.ext_of_Union_eq_univ
/-- Two measures are equal if they have equal restrictions on a spanning collection of sets
(formulated using `bUnion`). -/
lemma ext_iff_of_bUnion_eq_univ {S : set ι} {s : ι → set α} (hc : countable S)
(hm : ∀ i ∈ S, is_measurable (s i)) (hs : (⋃ i ∈ S, s i) = univ) :
μ = ν ↔ ∀ i ∈ S, μ.restrict (s i) = ν.restrict (s i) :=
by rw [← restrict_bUnion_congr hc hm, hs, restrict_univ, restrict_univ]
alias ext_iff_of_bUnion_eq_univ ↔ _ measure_theory.measure.ext_of_bUnion_eq_univ
/-- Two measures are equal if they have equal restrictions on a spanning collection of sets
(formulated using `sUnion`). -/
lemma ext_iff_of_sUnion_eq_univ {S : set (set α)} (hc : countable S)
(hm : ∀ s ∈ S, is_measurable s) (hs : (⋃₀ S) = univ) :
μ = ν ↔ ∀ s ∈ S, μ.restrict s = ν.restrict s :=
ext_iff_of_bUnion_eq_univ hc hm $ by rwa ← sUnion_eq_bUnion
alias ext_iff_of_sUnion_eq_univ ↔ _ measure_theory.measure.ext_of_sUnion_eq_univ
lemma ext_of_generate_from_of_cover {S T : set (set α)}
(h_gen : ‹_› = generate_from S) (hc : countable T)
(h_inter : is_pi_system S)
(hm : ∀ t ∈ T, is_measurable t) (hU : ⋃₀ T = univ) (htop : ∀ t ∈ T, μ t < ⊤)
(ST_eq : ∀ (t ∈ T) (s ∈ S), μ (s ∩ t) = ν (s ∩ t)) (T_eq : ∀ t ∈ T, μ t = ν t) :
μ = ν :=
begin
refine ext_of_sUnion_eq_univ hc hm hU (λ t ht, _),
ext1 u hu,
simp only [restrict_apply hu],
refine induction_on_inter h_gen h_inter _ (ST_eq t ht) _ _ hu,
{ simp only [set.empty_inter, measure_empty] },
{ intros v hv hvt,
have := T_eq t ht,
rw [set.inter_comm] at hvt ⊢,
rwa [measure_eq_inter_diff (hm _ ht) hv, measure_eq_inter_diff (hm _ ht) hv, ← hvt,
ennreal.add_right_inj] at this,
exact (measure_mono $ set.inter_subset_left _ _).trans_lt (htop t ht) },
{ intros f hfd hfm h_eq,
have : pairwise (disjoint on λ n, f n ∩ t) :=
λ m n hmn, (hfd m n hmn).mono (inter_subset_left _ _) (inter_subset_left _ _),
simp only [Union_inter, measure_Union this (λ n, is_measurable.inter (hfm n) (hm t ht)), h_eq] }
end
/-- Two measures are equal if they are equal on the π-system generating the σ-algebra,
and they are both finite on a increasing spanning sequence of sets in the π-system.
This lemma is formulated using `sUnion`. -/
lemma ext_of_generate_from_of_cover_subset {S T : set (set α)}
(h_gen : ‹_› = generate_from S)
(h_inter : is_pi_system S)
(h_sub : T ⊆ S) (hc : countable T) (hU : ⋃₀ T = univ) (htop : ∀ s ∈ T, μ s < ⊤)
(h_eq : ∀ s ∈ S, μ s = ν s) :
μ = ν :=
begin
refine ext_of_generate_from_of_cover h_gen hc h_inter _ hU htop _ (λ t ht, h_eq t (h_sub ht)),
{ intros t ht, rw [h_gen], exact generate_measurable.basic _ (h_sub ht) },
{ intros t ht s hs, cases (s ∩ t).eq_empty_or_nonempty with H H,
{ simp only [H, measure_empty] },
{ exact h_eq _ (h_inter _ _ hs (h_sub ht) H) } }
end
/-- Two measures are equal if they are equal on the π-system generating the σ-algebra,
and they are both finite on a increasing spanning sequence of sets in the π-system.
This lemma is formulated using `Union`.
`finite_spanning_sets_in.ext` is a reformulation of this lemma. -/
lemma ext_of_generate_from_of_Union (C : set (set α)) (B : ℕ → set α)
(hA : ‹_› = generate_from C) (hC : is_pi_system C) (h1B : (⋃ i, B i) = univ)
(h2B : ∀ i, B i ∈ C) (hμB : ∀ i, μ (B i) < ⊤) (h_eq : ∀ s ∈ C, μ s = ν s) : μ = ν :=
begin
refine ext_of_generate_from_of_cover_subset hA hC _ (countable_range B) h1B _ h_eq,
{ rintro _ ⟨i, rfl⟩, apply h2B },
{ rintro _ ⟨i, rfl⟩, apply hμB }
end
/-- The dirac measure. -/
def dirac (a : α) : measure α :=
(outer_measure.dirac a).to_measure (by simp)
lemma le_dirac_apply {a} : s.indicator 1 a ≤ dirac a s :=
outer_measure.dirac_apply a s ▸ le_to_measure_apply _ _ _
@[simp] lemma dirac_apply' (a : α) (hs : is_measurable s) :
dirac a s = s.indicator 1 a :=
to_measure_apply _ _ hs
@[simp] lemma dirac_apply_of_mem {a : α} (h : a ∈ s) :
dirac a s = 1 :=
begin
have : ∀ t : set α, a ∈ t → t.indicator (1 : α → ennreal) a = 1,
from λ t ht, indicator_of_mem ht 1,
refine le_antisymm (this univ trivial ▸ _) (this s h ▸ le_dirac_apply),
rw [← dirac_apply' a is_measurable.univ],
exact measure_mono (subset_univ s)
end
@[simp] lemma dirac_apply [measurable_singleton_class α] (a : α) (s : set α) :
dirac a s = s.indicator 1 a :=
begin
by_cases h : a ∈ s, by rw [dirac_apply_of_mem h, indicator_of_mem h, pi.one_apply],
rw [indicator_of_not_mem h, ← nonpos_iff_eq_zero],
calc dirac a s ≤ dirac a {a}ᶜ : measure_mono (subset_compl_comm.1 $ singleton_subset_iff.2 h)
... = 0 : by simp [dirac_apply' _ (is_measurable_singleton _).compl]
end
lemma map_dirac {f : α → β} (hf : measurable f) (a : α) :
map f (dirac a) = dirac (f a) :=
ext $ assume s hs, by simp [hs, map_apply hf hs, hf hs, indicator_apply]
/-- Sum of an indexed family of measures. -/
def sum (f : ι → measure α) : measure α :=
(outer_measure.sum (λ i, (f i).to_outer_measure)).to_measure $
le_trans
(by exact le_infi (λ i, le_to_outer_measure_caratheodory _))
(outer_measure.le_sum_caratheodory _)
lemma le_sum_apply (f : ι → measure α) (s : set α) :
(∑' i, f i s) ≤ sum f s :=
le_to_measure_apply _ _ _
@[simp] lemma sum_apply (f : ι → measure α) {s : set α} (hs : is_measurable s) :
sum f s = ∑' i, f i s :=
to_measure_apply _ _ hs
lemma le_sum (μ : ι → measure α) (i : ι) : μ i ≤ sum μ :=
λ s hs, by simp only [sum_apply μ hs, ennreal.le_tsum i]
lemma restrict_Union [encodable ι] {s : ι → set α} (hd : pairwise (disjoint on s))
(hm : ∀ i, is_measurable (s i)) :
μ.restrict (⋃ i, s i) = sum (λ i, μ.restrict (s i)) :=
ext $ λ t ht, by simp only [sum_apply _ ht, restrict_Union_apply hd hm ht]
lemma restrict_Union_le [encodable ι] {s : ι → set α} :
μ.restrict (⋃ i, s i) ≤ sum (λ i, μ.restrict (s i)) :=
begin
intros t ht,
suffices : μ (⋃ i, t ∩ s i) ≤ ∑' i, μ (t ∩ s i), by simpa [ht, inter_Union],
apply measure_Union_le
end
@[simp] lemma sum_bool (f : bool → measure α) : sum f = f tt + f ff :=
ext $ λ s hs, by simp [hs, tsum_fintype]
@[simp] lemma sum_cond (μ ν : measure α) : sum (λ b, cond b μ ν) = μ + ν :=
sum_bool _
@[simp] lemma restrict_sum (μ : ι → measure α) {s : set α} (hs : is_measurable s) :
(sum μ).restrict s = sum (λ i, (μ i).restrict s) :=
ext $ λ t ht, by simp only [sum_apply, restrict_apply, ht, ht.inter hs]
/-- Counting measure on any measurable space. -/
def count : measure α := sum dirac
lemma le_count_apply : (∑' i : s, 1 : ennreal) ≤ count s :=
calc (∑' i : s, 1 : ennreal) = ∑' i, indicator s 1 i : tsum_subtype s 1
... ≤ ∑' i, dirac i s : ennreal.tsum_le_tsum $ λ x, le_dirac_apply
... ≤ count s : le_sum_apply _ _
lemma count_apply (hs : is_measurable s) : count s = ∑' i : s, 1 :=
by simp only [count, sum_apply, hs, dirac_apply', ← tsum_subtype s 1, pi.one_apply]
@[simp] lemma count_apply_finset [measurable_singleton_class α] (s : finset α) :
count (↑s : set α) = s.card :=
calc count (↑s : set α) = ∑' i : (↑s : set α), 1 : count_apply s.is_measurable
... = ∑ i in s, 1 : s.tsum_subtype 1
... = s.card : by simp
lemma count_apply_finite [measurable_singleton_class α] (s : set α) (hs : finite s) :
count s = hs.to_finset.card :=
by rw [← count_apply_finset, finite.coe_to_finset]
/-- `count` measure evaluates to infinity at infinite sets. -/
lemma count_apply_infinite (hs : s.infinite) : count s = ⊤ :=
begin
refine top_unique (le_of_tendsto' ennreal.tendsto_nat_nhds_top $ λ n, _),
rcases hs.exists_subset_card_eq n with ⟨t, ht, rfl⟩,
calc (t.card : ennreal) = ∑ i in t, 1 : by simp
... = ∑' i : (t : set α), 1 : (t.tsum_subtype 1).symm
... ≤ count (t : set α) : le_count_apply
... ≤ count s : measure_mono ht
end
@[simp] lemma count_apply_eq_top [measurable_singleton_class α] : count s = ⊤ ↔ s.infinite :=
begin
by_cases hs : s.finite,
{ simp [set.infinite, hs, count_apply_finite] },
{ change s.infinite at hs,
simp [hs, count_apply_infinite] }
end
@[simp] lemma count_apply_lt_top [measurable_singleton_class α] : count s < ⊤ ↔ s.finite :=
calc count s < ⊤ ↔ count s ≠ ⊤ : lt_top_iff_ne_top
... ↔ ¬s.infinite : not_congr count_apply_eq_top
... ↔ s.finite : not_not
/-! ### The almost everywhere filter -/
/-- The “almost everywhere” filter of co-null sets. -/
def ae (μ : measure α) : filter α :=
{ sets := {s | μ sᶜ = 0},
univ_sets := by simp,
inter_sets := λ s t hs ht, by simp only [compl_inter, mem_set_of_eq];
exact measure_union_null hs ht,
sets_of_superset := λ s t hs hst, measure_mono_null (set.compl_subset_compl.2 hst) hs }
/-- The filter of sets `s` such that `sᶜ` has finite measure. -/
def cofinite (μ : measure α) : filter α :=
{ sets := {s | μ sᶜ < ⊤},
univ_sets := by simp,
inter_sets := λ s t hs ht, by { simp only [compl_inter, mem_set_of_eq],
calc μ (sᶜ ∪ tᶜ) ≤ μ sᶜ + μ tᶜ : measure_union_le _ _
... < ⊤ : ennreal.add_lt_top.2 ⟨hs, ht⟩ },
sets_of_superset := λ s t hs hst, lt_of_le_of_lt (measure_mono $ compl_subset_compl.2 hst) hs }
lemma mem_cofinite : s ∈ μ.cofinite ↔ μ sᶜ < ⊤ := iff.rfl
lemma compl_mem_cofinite : sᶜ ∈ μ.cofinite ↔ μ s < ⊤ :=
by rw [mem_cofinite, compl_compl]
lemma eventually_cofinite {p : α → Prop} : (∀ᶠ x in μ.cofinite, p x) ↔ μ {x | ¬p x} < ⊤ := iff.rfl
end measure
open measure
notation `∀ᵐ` binders ` ∂` μ `, ` r:(scoped P, filter.eventually P (measure.ae μ)) := r
notation f ` =ᵐ[`:50 μ:50 `] `:0 g:50 := f =ᶠ[measure.ae μ] g
notation f ` ≤ᵐ[`:50 μ:50 `] `:0 g:50 := f ≤ᶠ[measure.ae μ] g
lemma mem_ae_iff {s : set α} : s ∈ μ.ae ↔ μ sᶜ = 0 := iff.rfl
lemma ae_iff {p : α → Prop} : (∀ᵐ a ∂ μ, p a) ↔ μ { a | ¬ p a } = 0 := iff.rfl
lemma compl_mem_ae_iff {s : set α} : sᶜ ∈ μ.ae ↔ μ s = 0 := by simp only [mem_ae_iff, compl_compl]
lemma measure_zero_iff_ae_nmem {s : set α} : μ s = 0 ↔ ∀ᵐ a ∂ μ, a ∉ s :=
compl_mem_ae_iff.symm
@[simp] lemma ae_eq_bot : μ.ae = ⊥ ↔ μ = 0 :=
by rw [← empty_in_sets_eq_bot, mem_ae_iff, compl_empty, measure_univ_eq_zero]
@[simp] lemma ae_zero : (0 : measure α).ae = ⊥ := ae_eq_bot.2 rfl
lemma ae_of_all {p : α → Prop} (μ : measure α) : (∀ a, p a) → ∀ᵐ a ∂ μ, p a :=
eventually_of_forall
@[mono] lemma ae_mono {μ ν : measure α} (h : μ ≤ ν) : μ.ae ≤ ν.ae :=
λ s hs, bot_unique $ trans_rel_left (≤) (measure.le_iff'.1 h _) hs
instance : countable_Inter_filter μ.ae :=
⟨begin
intros S hSc hS,
simp only [mem_ae_iff, compl_sInter, sUnion_image, bUnion_eq_Union] at hS ⊢,
haveI := hSc.to_encodable,
exact measure_Union_null (subtype.forall.2 hS)
end⟩
instance ae_is_measurably_generated : is_measurably_generated μ.ae :=
⟨λ s hs, let ⟨t, hst, htm, htμ⟩ := exists_is_measurable_superset_of_null hs in
⟨tᶜ, compl_mem_ae_iff.2 htμ, htm.compl, compl_subset_comm.1 hst⟩⟩
lemma ae_all_iff [encodable ι] {p : α → ι → Prop} :
(∀ᵐ a ∂ μ, ∀ i, p a i) ↔ (∀ i, ∀ᵐ a ∂ μ, p a i) :=
eventually_countable_forall
lemma ae_ball_iff {S : set ι} (hS : countable S) {p : Π (x : α) (i ∈ S), Prop} :
(∀ᵐ x ∂ μ, ∀ i ∈ S, p x i ‹_›) ↔ ∀ i ∈ S, ∀ᵐ x ∂ μ, p x i ‹_› :=
eventually_countable_ball hS
lemma ae_eq_refl (f : α → δ) : f =ᵐ[μ] f := eventually_eq.refl _ _
lemma ae_eq_symm {f g : α → δ} (h : f =ᵐ[μ] g) : g =ᵐ[μ] f :=
h.symm
lemma ae_eq_trans {f g h: α → δ} (h₁ : f =ᵐ[μ] g) (h₂ : g =ᵐ[μ] h) :
f =ᵐ[μ] h :=
h₁.trans h₂
lemma ae_eq_empty : s =ᵐ[μ] (∅ : set α) ↔ μ s = 0 :=
eventually_eq_empty.trans $ by simp [ae_iff]
lemma ae_le_set : s ≤ᵐ[μ] t ↔ μ (s \ t) = 0 :=
calc s ≤ᵐ[μ] t ↔ ∀ᵐ x ∂μ, x ∈ s → x ∈ t : iff.rfl
... ↔ μ (s \ t) = 0 : by simp [ae_iff]; refl
lemma union_ae_eq_right : (s ∪ t : set α) =ᵐ[μ] t ↔ μ (s \ t) = 0 :=
by simp [eventually_le_antisymm_iff, ae_le_set, union_diff_right,
diff_eq_empty.2 (set.subset_union_right _ _)]
lemma diff_ae_eq_self : (s \ t : set α) =ᵐ[μ] s ↔ μ (s ∩ t) = 0 :=
by simp [eventually_le_antisymm_iff, ae_le_set, diff_diff_right,
diff_diff, diff_eq_empty.2 (set.subset_union_right _ _)]
lemma ae_eq_set {s t : set α} :
s =ᵐ[μ] t ↔ μ (s \ t) = 0 ∧ μ (t \ s) = 0 :=
by simp [eventually_le_antisymm_iff, ae_le_set]
lemma mem_ae_map_iff {f : α → β} (hf : measurable f) {s : set β} (hs : is_measurable s) :
s ∈ (map f μ).ae ↔ (f ⁻¹' s) ∈ μ.ae :=
by simp only [mem_ae_iff, map_apply hf hs.compl, preimage_compl]
lemma ae_map_iff {f : α → β} (hf : measurable f) {p : β → Prop} (hp : is_measurable {x | p x}) :
(∀ᵐ y ∂ (map f μ), p y) ↔ ∀ᵐ x ∂ μ, p (f x) :=
mem_ae_map_iff hf hp
lemma ae_restrict_iff {p : α → Prop} (hp : is_measurable {x | p x}) :
(∀ᵐ x ∂(μ.restrict s), p x) ↔ ∀ᵐ x ∂μ, x ∈ s → p x :=
begin
simp only [ae_iff, ← compl_set_of, restrict_apply hp.compl],
congr' with x, simp [and_comm]
end
lemma ae_imp_of_ae_restrict {s : set α} {p : α → Prop} (h : ∀ᵐ x ∂(μ.restrict s), p x) :
∀ᵐ x ∂μ, x ∈ s → p x :=
begin
simp only [ae_iff] at h ⊢,
simpa [set_of_and, inter_comm] using measure_inter_eq_zero_of_restrict h
end
lemma ae_restrict_iff' {s : set α} {p : α → Prop} (hp : is_measurable s) :
(∀ᵐ x ∂(μ.restrict s), p x) ↔ ∀ᵐ x ∂μ, x ∈ s → p x :=
begin
simp only [ae_iff, ← compl_set_of, restrict_apply_eq_zero' hp],
congr' with x, simp [and_comm]
end
lemma ae_smul_measure {p : α → Prop} (h : ∀ᵐ x ∂μ, p x) (c : ennreal) : ∀ᵐ x ∂(c • μ), p x :=
ae_iff.2 $ by rw [smul_apply, ae_iff.1 h, mul_zero]
lemma ae_smul_measure_iff {p : α → Prop} {c : ennreal} (hc : c ≠ 0) :
(∀ᵐ x ∂(c • μ), p x) ↔ ∀ᵐ x ∂μ, p x :=
by simp [ae_iff, hc]
lemma ae_add_measure_iff {p : α → Prop} {ν} : (∀ᵐ x ∂μ + ν, p x) ↔ (∀ᵐ x ∂μ, p x) ∧ ∀ᵐ x ∂ν, p x :=
add_eq_zero_iff
lemma ae_eq_comp {f : α → β} {g g' : β → δ} (hf : measurable f)
(h : g =ᵐ[measure.map f μ] g') : g ∘ f =ᵐ[μ] g' ∘ f :=
begin
rcases exists_is_measurable_superset_of_null h with ⟨t, ht, tmeas, tzero⟩,
refine le_antisymm _ bot_le,
calc μ {x | g (f x) ≠ g' (f x)} ≤ μ (f⁻¹' t) : measure_mono (λ x hx, ht hx)
... = 0 : by rwa ← measure.map_apply hf tmeas
end
lemma le_ae_restrict : μ.ae ⊓ 𝓟 s ≤ (μ.restrict s).ae :=
λ s hs, eventually_inf_principal.2 (ae_imp_of_ae_restrict hs)
@[simp] lemma ae_restrict_eq (hs : is_measurable s) : (μ.restrict s).ae = μ.ae ⊓ 𝓟 s :=
begin
ext t,
simp only [mem_inf_principal, mem_ae_iff, restrict_apply_eq_zero' hs, compl_set_of,
not_imp, and_comm (_ ∈ s)],
refl
end
@[simp] lemma ae_restrict_eq_bot {s} : (μ.restrict s).ae = ⊥ ↔ μ s = 0 :=
ae_eq_bot.trans restrict_eq_zero
@[simp] lemma ae_restrict_ne_bot {s} : (μ.restrict s).ae.ne_bot ↔ 0 < μ s :=
(not_congr ae_restrict_eq_bot).trans pos_iff_ne_zero.symm
/-- A version of the Borel-Cantelli lemma: if `sᵢ` is a sequence of measurable sets such that
`∑ μ sᵢ` exists, then for almost all `x`, `x` does not belong to almost all `s`ᵢ. -/
lemma ae_eventually_not_mem {s : ℕ → set α} (hs : ∀ i, is_measurable (s i))
(hs' : ∑' i, μ (s i) ≠ ⊤) : ∀ᵐ x ∂ μ, ∀ᶠ n in at_top, x ∉ s n :=
begin
refine measure_mono_null _ (measure_limsup_eq_zero hs hs'),
rw ←set.le_eq_subset,
refine le_Inf (λ t ht x hx, _),
simp only [le_eq_subset, not_exists, eventually_map, exists_prop, ge_iff_le, mem_set_of_eq,
eventually_at_top, mem_compl_eq, not_forall, not_not_mem] at hx ht,
rcases ht with ⟨i, hi⟩,
rcases hx i with ⟨j, ⟨hj, hj'⟩⟩,
exact hi j hj hj'
end
lemma mem_ae_dirac_iff {a : α} (hs : is_measurable s) : s ∈ (dirac a).ae ↔ a ∈ s :=
by by_cases a ∈ s; simp [mem_ae_iff, dirac_apply', hs.compl, indicator_apply, *]
lemma ae_dirac_iff {a : α} {p : α → Prop} (hp : is_measurable {x | p x}) :
(∀ᵐ x ∂(dirac a), p x) ↔ p a :=
mem_ae_dirac_iff hp
@[simp] lemma ae_dirac_eq [measurable_singleton_class α] (a : α) : (dirac a).ae = pure a :=
by { ext s, simp [mem_ae_iff, imp_false] }
lemma ae_eq_dirac' [measurable_singleton_class β] {a : α} {f : α → β} (hf : measurable f) :
f =ᵐ[dirac a] const α (f a) :=
(ae_dirac_iff $ show is_measurable (f ⁻¹' {f a}), from hf $ is_measurable_singleton _).2 rfl
lemma ae_eq_dirac [measurable_singleton_class α] {a : α} (f : α → δ) :
f =ᵐ[dirac a] const α (f a) :=
by simp [filter.eventually_eq]
/-- If `s ⊆ t` modulo a set of measure `0`, then `μ s ≤ μ t`. -/
lemma measure_mono_ae (H : s ≤ᵐ[μ] t) : μ s ≤ μ t :=
calc μ s ≤ μ (s ∪ t) : measure_mono $ subset_union_left s t
... = μ (t ∪ s \ t) : by rw [union_diff_self, set.union_comm]
... ≤ μ t + μ (s \ t) : measure_union_le _ _
... = μ t : by rw [ae_le_set.1 H, add_zero]
alias measure_mono_ae ← filter.eventually_le.measure_le
/-- If two sets are equal modulo a set of measure zero, then `μ s = μ t`. -/
lemma measure_congr (H : s =ᵐ[μ] t) : μ s = μ t :=
le_antisymm H.le.measure_le H.symm.le.measure_le
lemma restrict_mono_ae (h : s ≤ᵐ[μ] t) : μ.restrict s ≤ μ.restrict t :=
begin
intros u hu,
simp only [restrict_apply hu],
exact measure_mono_ae (h.mono $ λ x hx, and.imp id hx)
end
lemma restrict_congr_set (H : s =ᵐ[μ] t) : μ.restrict s = μ.restrict t :=
le_antisymm (restrict_mono_ae H.le) (restrict_mono_ae H.symm.le)
/-- A measure `μ` is called a probability measure if `μ univ = 1`. -/
class probability_measure (μ : measure α) : Prop := (measure_univ : μ univ = 1)
instance measure.dirac.probability_measure {x : α} : probability_measure (dirac x) :=
⟨dirac_apply_of_mem $ mem_univ x⟩
/-- A measure `μ` is called finite if `μ univ < ⊤`. -/
class finite_measure (μ : measure α) : Prop := (measure_univ_lt_top : μ univ < ⊤)
instance restrict.finite_measure (μ : measure α) [hs : fact (μ s < ⊤)] :
finite_measure (μ.restrict s) :=
⟨by simp [hs.elim]⟩
/-- Measure `μ` *has no atoms* if the measure of each singleton is zero.
NB: Wikipedia assumes that for any measurable set `s` with positive `μ`-measure,
there exists a measurable `t ⊆ s` such that `0 < μ t < μ s`. While this implies `μ {x} = 0`,
the converse is not true. -/
class has_no_atoms (μ : measure α) : Prop :=
(measure_singleton : ∀ x, μ {x} = 0)
export probability_measure (measure_univ) has_no_atoms (measure_singleton)
attribute [simp] measure_singleton
lemma measure_lt_top (μ : measure α) [finite_measure μ] (s : set α) : μ s < ⊤ :=
(measure_mono (subset_univ s)).trans_lt finite_measure.measure_univ_lt_top
lemma measure_ne_top (μ : measure α) [finite_measure μ] (s : set α) : μ s ≠ ⊤ :=
ne_of_lt (measure_lt_top μ s)
/-- `le_of_add_le_add_left` is normally applicable to `ordered_cancel_add_comm_monoid`,
but it holds for measures with the additional assumption that μ is finite. -/
lemma measure.le_of_add_le_add_left {μ ν₁ ν₂ : measure α} [finite_measure μ]
(A2 : μ + ν₁ ≤ μ + ν₂) : ν₁ ≤ ν₂ :=
λ S B1, ennreal.le_of_add_le_add_left (measure_theory.measure_lt_top μ S) (A2 S B1)
@[priority 100]
instance probability_measure.to_finite_measure (μ : measure α) [probability_measure μ] :
finite_measure μ :=
⟨by simp only [measure_univ, ennreal.one_lt_top]⟩
lemma probability_measure.ne_zero (μ : measure α) [probability_measure μ] : μ ≠ 0 :=
mt measure_univ_eq_zero.2 $ by simp [measure_univ]
section no_atoms
variables [has_no_atoms μ]
lemma measure_countable (h : countable s) : μ s = 0 :=
begin
rw [← bUnion_of_singleton s, ← nonpos_iff_eq_zero],
refine le_trans (measure_bUnion_le h _) _,
simp
end
lemma measure_finite (h : s.finite) : μ s = 0 :=
measure_countable h.countable
lemma measure_finset (s : finset α) : μ ↑s = 0 :=
measure_finite s.finite_to_set
lemma insert_ae_eq_self (a : α) (s : set α) :
(insert a s : set α) =ᵐ[μ] s :=
union_ae_eq_right.2 $ measure_mono_null (diff_subset _ _) (measure_singleton _)
variables [partial_order α] {a b : α}
lemma Iio_ae_eq_Iic : Iio a =ᵐ[μ] Iic a :=
by simp only [← Iic_diff_right, diff_ae_eq_self,
measure_mono_null (set.inter_subset_right _ _) (measure_singleton a)]
lemma Ioi_ae_eq_Ici : Ioi a =ᵐ[μ] Ici a :=
@Iio_ae_eq_Iic (order_dual α) ‹_› ‹_› _ _ _
lemma Ioo_ae_eq_Ioc : Ioo a b =ᵐ[μ] Ioc a b :=
(ae_eq_refl _).inter Iio_ae_eq_Iic
lemma Ioc_ae_eq_Icc : Ioc a b =ᵐ[μ] Icc a b :=
Ioi_ae_eq_Ici.inter (ae_eq_refl _)
lemma Ioo_ae_eq_Ico : Ioo a b =ᵐ[μ] Ico a b :=
Ioi_ae_eq_Ici.inter (ae_eq_refl _)
lemma Ioo_ae_eq_Icc : Ioo a b =ᵐ[μ] Icc a b :=
Ioi_ae_eq_Ici.inter Iio_ae_eq_Iic
lemma Ico_ae_eq_Icc : Ico a b =ᵐ[μ] Icc a b :=
(ae_eq_refl _).inter Iio_ae_eq_Iic
lemma Ico_ae_eq_Ioc : Ico a b =ᵐ[μ] Ioc a b :=
Ioo_ae_eq_Ico.symm.trans Ioo_ae_eq_Ioc
end no_atoms
namespace measure
/-- A measure is called finite at filter `f` if it is finite at some set `s ∈ f`.
Equivalently, it is eventually finite at `s` in `f.lift' powerset`. -/
def finite_at_filter (μ : measure α) (f : filter α) : Prop := ∃ s ∈ f, μ s < ⊤
lemma finite_at_filter_of_finite (μ : measure α) [finite_measure μ] (f : filter α) :
μ.finite_at_filter f :=
⟨univ, univ_mem_sets, measure_lt_top μ univ⟩
lemma finite_at_filter.exists_mem_basis {μ : measure α} {f : filter α} (hμ : finite_at_filter μ f)
{p : ι → Prop} {s : ι → set α} (hf : f.has_basis p s) :
∃ i (hi : p i), μ (s i) < ⊤ :=
(hf.exists_iff (λ s t hst ht, (measure_mono hst).trans_lt ht)).1 hμ
lemma finite_at_bot (μ : measure α) : μ.finite_at_filter ⊥ :=
⟨∅, mem_bot_sets, by simp only [measure_empty, with_top.zero_lt_top]⟩
/-- `μ` has finite spanning sets in `C` if there is a countable sequence of sets in `C` that have
finite measures. This structure is a type, which is useful if we want to record extra properties
about the sets, such as that they are monotone.
`sigma_finite` is defined in terms of this: `μ` is σ-finite if there exists a sequence of
finite spanning sets in the collection of all measurable sets. -/
@[protect_proj, nolint has_inhabited_instance]
structure finite_spanning_sets_in (μ : measure α) (C : set (set α)) :=
(set : ℕ → set α)
(set_mem : ∀ i, set i ∈ C)
(finite : ∀ i, μ (set i) < ⊤)
(spanning : (⋃ i, set i) = univ)
end measure
open measure
/-- A measure `μ` is called σ-finite if there is a countable collection of sets
`{ A i | i ∈ ℕ }` such that `μ (A i) < ⊤` and `⋃ i, A i = s`. -/
@[class] def sigma_finite (μ : measure α) : Prop :=
nonempty (μ.finite_spanning_sets_in {s | is_measurable s})
/-- If `μ` is σ-finite it has finite spanning sets in the collection of all measurable sets. -/
def measure.to_finite_spanning_sets_in (μ : measure α) [h : sigma_finite μ] :
μ.finite_spanning_sets_in {s | is_measurable s} :=
classical.choice h
/-- A noncomputable way to get a monotone collection of sets that span `univ` and have finite
measure using `classical.some`. This definition satisfies monotonicity in addition to all other
properties in `sigma_finite`. -/
def spanning_sets (μ : measure α) [sigma_finite μ] (i : ℕ) : set α :=
accumulate μ.to_finite_spanning_sets_in.set i
lemma monotone_spanning_sets (μ : measure α) [sigma_finite μ] :
monotone (spanning_sets μ) :=
monotone_accumulate
lemma is_measurable_spanning_sets (μ : measure α) [sigma_finite μ] (i : ℕ) :
is_measurable (spanning_sets μ i) :=
is_measurable.Union $ λ j, is_measurable.Union_Prop $
λ hij, μ.to_finite_spanning_sets_in.set_mem j
lemma measure_spanning_sets_lt_top (μ : measure α) [sigma_finite μ] (i : ℕ) :
μ (spanning_sets μ i) < ⊤ :=
measure_bUnion_lt_top (finite_le_nat i) $ λ j _, μ.to_finite_spanning_sets_in.finite j
lemma Union_spanning_sets (μ : measure α) [sigma_finite μ] :
(⋃ i : ℕ, spanning_sets μ i) = univ :=
by simp_rw [spanning_sets, Union_accumulate, μ.to_finite_spanning_sets_in.spanning]
lemma is_countably_spanning_spanning_sets (μ : measure α) [sigma_finite μ] :
is_countably_spanning (range (spanning_sets μ)) :=
⟨spanning_sets μ, mem_range_self, Union_spanning_sets μ⟩
namespace measure
lemma supr_restrict_spanning_sets [sigma_finite μ] (hs : is_measurable s) :
(⨆ i, μ.restrict (spanning_sets μ i) s) = μ s :=
begin
convert (restrict_Union_apply_eq_supr (is_measurable_spanning_sets μ) _ hs).symm,
{ simp [Union_spanning_sets] },
{ exact directed_of_sup (monotone_spanning_sets μ) }
end
namespace finite_spanning_sets_in
variables {C D : set (set α)}
/-- If `μ` has finite spanning sets in `C` and `C ⊆ D` then `μ` has finite spanning sets in `D`. -/
protected def mono (h : μ.finite_spanning_sets_in C) (hC : C ⊆ D) : μ.finite_spanning_sets_in D :=
⟨h.set, λ i, hC (h.set_mem i), h.finite, h.spanning⟩
/-- If `μ` has finite spanning sets in the collection of measurable sets `C`, then `μ` is σ-finite.
-/
protected lemma sigma_finite (h : μ.finite_spanning_sets_in C) (hC : ∀ s ∈ C, is_measurable s) :
sigma_finite μ :=
⟨h.mono hC⟩
/-- An extensionality for measures. It is `ext_of_generate_from_of_Union` formulated in terms of
`finite_spanning_sets_in`. -/
protected lemma ext {ν : measure α} {C : set (set α)} (hA : ‹_› = generate_from C)
(hC : is_pi_system C) (h : μ.finite_spanning_sets_in C) (h_eq : ∀ s ∈ C, μ s = ν s) : μ = ν :=
ext_of_generate_from_of_Union C _ hA hC h.spanning h.set_mem h.finite h_eq
protected lemma is_countably_spanning (h : μ.finite_spanning_sets_in C) : is_countably_spanning C :=
⟨_, h.set_mem, h.spanning⟩
end finite_spanning_sets_in
lemma sigma_finite_of_not_nonempty (μ : measure α) (hα : ¬ nonempty α) : sigma_finite μ :=
⟨⟨λ _, ∅, λ n, is_measurable.empty, λ n, by simp, by simp [eq_empty_of_not_nonempty hα univ]⟩⟩
lemma sigma_finite_of_countable {S : set (set α)} (hc : countable S)
(hμ : ∀ s ∈ S, μ s < ⊤) (hU : ⋃₀ S = univ) :
sigma_finite μ :=
begin
obtain ⟨s, hμ, hs⟩ : ∃ s : ℕ → set α, (∀ n, μ (s n) < ⊤) ∧ (⋃ n, s n) = univ,
from (exists_seq_cover_iff_countable ⟨∅, by simp⟩).2 ⟨S, hc, hμ, hU⟩,
refine ⟨⟨λ n, to_measurable μ (s n), λ n, is_measurable_to_measurable _ _, by simpa, _⟩⟩,
exact eq_univ_of_subset (Union_subset_Union $ λ n, subset_to_measurable μ (s n)) hs
end
end measure
/-- Every finite measure is σ-finite. -/
@[priority 100]
instance finite_measure.to_sigma_finite (μ : measure α) [finite_measure μ] : sigma_finite μ :=
⟨⟨λ _, univ, λ _, is_measurable.univ, λ _, measure_lt_top μ _, Union_const _⟩⟩
instance restrict.sigma_finite (μ : measure α) [sigma_finite μ] (s : set α) :
sigma_finite (μ.restrict s) :=
begin
refine ⟨⟨spanning_sets μ, is_measurable_spanning_sets μ, λ i, _, Union_spanning_sets μ⟩⟩,
rw [restrict_apply (is_measurable_spanning_sets μ i)],
exact (measure_mono $ inter_subset_left _ _).trans_lt (measure_spanning_sets_lt_top μ i)
end
instance sum.sigma_finite {ι} [fintype ι] (μ : ι → measure α) [∀ i, sigma_finite (μ i)] :
sigma_finite (sum μ) :=
begin
haveI : encodable ι := (encodable.trunc_encodable_of_fintype ι).out,
have : ∀ n, is_measurable (⋂ (i : ι), spanning_sets (μ i) n) :=
λ n, is_measurable.Inter (λ i, is_measurable_spanning_sets (μ i) n),
refine ⟨⟨λ n, ⋂ i, spanning_sets (μ i) n, this, λ n, _, _⟩⟩,
{ rw [sum_apply _ (this n), tsum_fintype, ennreal.sum_lt_top_iff],
rintro i -,
exact (measure_mono $ Inter_subset _ i).trans_lt (measure_spanning_sets_lt_top (μ i) n) },
{ rw [Union_Inter_of_monotone], simp_rw [Union_spanning_sets, Inter_univ],
exact λ i, monotone_spanning_sets (μ i), }
end
instance add.sigma_finite (μ ν : measure α) [sigma_finite μ] [sigma_finite ν] :
sigma_finite (μ + ν) :=
by { rw [← sum_cond], refine @sum.sigma_finite _ _ _ _ _ (bool.rec _ _); simpa }
/-- A measure is called locally finite if it is finite in some neighborhood of each point. -/
class locally_finite_measure [topological_space α] (μ : measure α) : Prop :=
(finite_at_nhds : ∀ x, μ.finite_at_filter (𝓝 x))
@[priority 100] -- see Note [lower instance priority]
instance finite_measure.to_locally_finite_measure [topological_space α] (μ : measure α)
[finite_measure μ] :
locally_finite_measure μ :=
⟨λ x, finite_at_filter_of_finite _ _⟩
lemma measure.finite_at_nhds [topological_space α] (μ : measure α)
[locally_finite_measure μ] (x : α) :
μ.finite_at_filter (𝓝 x) :=
locally_finite_measure.finite_at_nhds x
lemma measure.exists_is_open_measure_lt_top [topological_space α] (μ : measure α)
[locally_finite_measure μ] (x : α) :
∃ s : set α, x ∈ s ∧ is_open s ∧ μ s < ⊤ :=
by simpa only [exists_prop, and.assoc]
using (μ.finite_at_nhds x).exists_mem_basis (nhds_basis_opens x)
@[priority 100] -- see Note [lower instance priority]
instance sigma_finite_of_locally_finite [topological_space α]
[topological_space.second_countable_topology α]
{μ : measure α} [locally_finite_measure μ] :
sigma_finite μ :=
begin
choose s hsx hsμ using μ.finite_at_nhds,
rcases topological_space.countable_cover_nhds hsx with ⟨t, htc, htU⟩,
refine measure.sigma_finite_of_countable (htc.image s) (ball_image_iff.2 $ λ x hx, hsμ x) _,
rwa sUnion_image
end
/-- Two finite measures are equal if they are equal on the π-system generating the σ-algebra
(and `univ`). -/
lemma ext_of_generate_finite (C : set (set α)) (hA : _inst_1 = generate_from C)
(hC : is_pi_system C) {μ ν : measure α}
[finite_measure μ] [finite_measure ν] (hμν : ∀ s ∈ C, μ s = ν s) (h_univ : μ univ = ν univ) :
μ = ν :=
begin
ext1 s hs,
refine induction_on_inter hA hC (by simp) hμν _ _ hs,
{ rintros t h1t h2t, change is_measurable t at h1t, simp [measure_compl, measure_lt_top, *] },
{ rintros f h1f h2f h3f, simp [measure_Union, is_measurable.Union, *] }
end
namespace measure
namespace finite_at_filter
variables {f g : filter α}
lemma filter_mono (h : f ≤ g) : μ.finite_at_filter g → μ.finite_at_filter f :=
λ ⟨s, hs, hμ⟩, ⟨s, h hs, hμ⟩
lemma inf_of_left (h : μ.finite_at_filter f) : μ.finite_at_filter (f ⊓ g) :=
h.filter_mono inf_le_left
lemma inf_of_right (h : μ.finite_at_filter g) : μ.finite_at_filter (f ⊓ g) :=
h.filter_mono inf_le_right
@[simp] lemma inf_ae_iff : μ.finite_at_filter (f ⊓ μ.ae) ↔ μ.finite_at_filter f :=
begin
refine ⟨_, λ h, h.filter_mono inf_le_left⟩,
rintros ⟨s, ⟨t, ht, u, hu, hs⟩, hμ⟩,
suffices : μ t ≤ μ s, from ⟨t, ht, this.trans_lt hμ⟩,
exact measure_mono_ae (mem_sets_of_superset hu (λ x hu ht, hs ⟨ht, hu⟩))
end
alias inf_ae_iff ↔ measure_theory.measure.finite_at_filter.of_inf_ae _
lemma filter_mono_ae (h : f ⊓ μ.ae ≤ g) (hg : μ.finite_at_filter g) : μ.finite_at_filter f :=
inf_ae_iff.1 (hg.filter_mono h)
protected lemma measure_mono (h : μ ≤ ν) : ν.finite_at_filter f → μ.finite_at_filter f :=
λ ⟨s, hs, hν⟩, ⟨s, hs, (measure.le_iff'.1 h s).trans_lt hν⟩
@[mono] protected lemma mono (hf : f ≤ g) (hμ : μ ≤ ν) :
ν.finite_at_filter g → μ.finite_at_filter f :=
λ h, (h.filter_mono hf).measure_mono hμ
protected lemma eventually (h : μ.finite_at_filter f) : ∀ᶠ s in f.lift' powerset, μ s < ⊤ :=
(eventually_lift'_powerset' $ λ s t hst ht, (measure_mono hst).trans_lt ht).2 h
lemma filter_sup : μ.finite_at_filter f → μ.finite_at_filter g → μ.finite_at_filter (f ⊔ g) :=
λ ⟨s, hsf, hsμ⟩ ⟨t, htg, htμ⟩,
⟨s ∪ t, union_mem_sup hsf htg, (measure_union_le s t).trans_lt (ennreal.add_lt_top.2 ⟨hsμ, htμ⟩)⟩
end finite_at_filter
lemma finite_at_nhds_within [topological_space α] (μ : measure α) [locally_finite_measure μ]
(x : α) (s : set α) :
μ.finite_at_filter (𝓝[s] x) :=
(finite_at_nhds μ x).inf_of_left
@[simp] lemma finite_at_principal : μ.finite_at_filter (𝓟 s) ↔ μ s < ⊤ :=
⟨λ ⟨t, ht, hμ⟩, (measure_mono ht).trans_lt hμ, λ h, ⟨s, mem_principal_self s, h⟩⟩
/-! ### Subtraction of measures -/
/-- The measure `μ - ν` is defined to be the least measure `τ` such that `μ ≤ τ + ν`.
It is the equivalent of `(μ - ν) ⊔ 0` if `μ` and `ν` were signed measures.
Compare with `ennreal.has_sub`.
Specifically, note that if you have `α = {1,2}`, and `μ {1} = 2`, `μ {2} = 0`, and
`ν {2} = 2`, `ν {1} = 0`, then `(μ - ν) {1, 2} = 2`. However, if `μ ≤ ν`, and
`ν univ ≠ ⊤`, then `(μ - ν) + ν = μ`. -/
noncomputable instance has_sub {α : Type*} [measurable_space α] : has_sub (measure α) :=
⟨λ μ ν, Inf {τ | μ ≤ τ + ν} ⟩
section measure_sub
lemma sub_def : μ - ν = Inf {d | μ ≤ d + ν} := rfl
lemma sub_eq_zero_of_le (h : μ ≤ ν) : μ - ν = 0 :=
begin
rw [← nonpos_iff_eq_zero', measure.sub_def],
apply @Inf_le (measure α) _ _,
simp [h],
end
/-- This application lemma only works in special circumstances. Given knowledge of
when `μ ≤ ν` and `ν ≤ μ`, a more general application lemma can be written. -/
lemma sub_apply [finite_measure ν] (h₁ : is_measurable s) (h₂ : ν ≤ μ) : (μ - ν) s = μ s - ν s :=
begin
-- We begin by defining `measure_sub`, which will be equal to `(μ - ν)`.
let measure_sub : measure α := @measure_theory.measure.of_measurable α _
(λ (t : set α) (h_t_is_measurable : is_measurable t), (μ t - ν t))
begin
simp
end
begin
intros g h_meas h_disj, simp only, rw ennreal.tsum_sub,
repeat { rw ← measure_theory.measure_Union h_disj h_meas },
apply measure_theory.measure_lt_top, intro i, apply h₂, apply h_meas
end,
-- Now, we demonstrate `μ - ν = measure_sub`, and apply it.
begin
have h_measure_sub_add : (ν + measure_sub = μ),
{ ext t h_t_is_measurable,
simp only [pi.add_apply, coe_add],
rw [measure_theory.measure.of_measurable_apply _ h_t_is_measurable, add_comm,
ennreal.sub_add_cancel_of_le (h₂ t h_t_is_measurable)] },
have h_measure_sub_eq : (μ - ν) = measure_sub,
{ rw measure_theory.measure.sub_def, apply le_antisymm,
{ apply @Inf_le (measure α) (measure.complete_lattice), simp [le_refl, add_comm, h_measure_sub_add] },
apply @le_Inf (measure α) (measure.complete_lattice),
intros d h_d, rw [← h_measure_sub_add, mem_set_of_eq, add_comm d] at h_d,
apply measure.le_of_add_le_add_left h_d },
rw h_measure_sub_eq,
apply measure.of_measurable_apply _ h₁,
end
end
lemma sub_add_cancel_of_le [finite_measure ν] (h₁ : ν ≤ μ) : μ - ν + ν = μ :=
begin
ext s h_s_meas,
rw [add_apply, sub_apply h_s_meas h₁, ennreal.sub_add_cancel_of_le (h₁ s h_s_meas)],
end
end measure_sub
end measure
end measure_theory
open measure_theory measure_theory.measure
namespace measurable_equiv
/-! Interactions of measurable equivalences and measures -/
open equiv measure_theory.measure
variables [measurable_space α] [measurable_space β] {μ : measure α} {ν : measure β}
/-- If we map a measure along a measurable equivalence, we can compute the measure on all sets
(not just the measurable ones). -/
protected theorem map_apply (f : α ≃ᵐ β) (s : set β) : map f μ s = μ (f ⁻¹' s) :=
begin
refine le_antisymm _ (le_map_apply f.measurable s),
rw [measure_eq_infi' μ],
refine le_infi _, rintro ⟨t, hst, ht⟩,
rw [subtype.coe_mk],
have := f.symm.to_equiv.image_eq_preimage,
simp only [←coe_eq, symm_symm, symm_to_equiv] at this,
rw [← this, image_subset_iff] at hst,
convert measure_mono hst,
rw [map_apply, preimage_preimage],
{ refine congr_arg μ (eq.symm _), convert preimage_id, exact funext f.left_inv },
exacts [f.measurable, f.measurable_inv_fun ht]
end
@[simp] lemma map_symm_map (e : α ≃ᵐ β) : map e.symm (map e μ) = μ :=
by simp [map_map e.symm.measurable e.measurable]
@[simp] lemma map_map_symm (e : α ≃ᵐ β) : map e (map e.symm ν) = ν :=
by simp [map_map e.measurable e.symm.measurable]
lemma map_measurable_equiv_injective (e : α ≃ᵐ β) : injective (map e) :=
by { intros μ₁ μ₂ hμ, apply_fun map e.symm at hμ, simpa [map_symm_map e] using hμ }
lemma map_apply_eq_iff_map_symm_apply_eq (e : α ≃ᵐ β) : map e μ = ν ↔ map e.symm ν = μ :=
by rw [← (map_measurable_equiv_injective e).eq_iff, map_map_symm, eq_comm]
end measurable_equiv
section is_complete
/-- A measure is complete if every null set is also measurable.
A null set is a subset of a measurable set with measure `0`.
Since every measure is defined as a special case of an outer measure, we can more simply state
that a set `s` is null if `μ s = 0`. -/
@[class] def measure_theory.measure.is_complete {_ : measurable_space α} (μ : measure α) :
Prop :=
∀ s, μ s = 0 → is_measurable s
variables [measurable_space α] {μ : measure α} {s t z : set α}
/-- A set is null measurable if it is the union of a null set and a measurable set. -/
def is_null_measurable (μ : measure α) (s : set α) : Prop :=
∃ t z, s = t ∪ z ∧ is_measurable t ∧ μ z = 0
theorem is_null_measurable_iff : is_null_measurable μ s ↔
∃ t, t ⊆ s ∧ is_measurable t ∧ μ (s \ t) = 0 :=
begin
split,
{ rintro ⟨t, z, rfl, ht, hz⟩,
refine ⟨t, set.subset_union_left _ _, ht, measure_mono_null _ hz⟩,
simp [union_diff_left, diff_subset] },
{ rintro ⟨t, st, ht, hz⟩,
exact ⟨t, _, (union_diff_cancel st).symm, ht, hz⟩ }
end
theorem is_null_measurable_measure_eq (st : t ⊆ s) (hz : μ (s \ t) = 0) : μ s = μ t :=
begin
refine le_antisymm _ (measure_mono st),
have := measure_union_le t (s \ t),
rw [union_diff_cancel st, hz] at this, simpa
end
theorem is_measurable.is_null_measurable (μ : measure α) (hs : is_measurable s) :
is_null_measurable μ s :=
⟨s, ∅, by simp, hs, μ.empty⟩
theorem is_null_measurable_of_complete (μ : measure α) [c : μ.is_complete] :
is_null_measurable μ s ↔ is_measurable s :=
⟨by rintro ⟨t, z, rfl, ht, hz⟩; exact
is_measurable.union ht (c _ hz),
λ h, h.is_null_measurable _⟩
theorem is_null_measurable.union_null (hs : is_null_measurable μ s) (hz : μ z = 0) :
is_null_measurable μ (s ∪ z) :=
begin
rcases hs with ⟨t, z', rfl, ht, hz'⟩,
exact ⟨t, z' ∪ z, set.union_assoc _ _ _, ht, nonpos_iff_eq_zero.1
(le_trans (measure_union_le _ _) $ by simp [hz, hz'])⟩
end
theorem null_is_null_measurable (hz : μ z = 0) : is_null_measurable μ z :=
by simpa using (is_measurable.empty.is_null_measurable _).union_null hz
theorem is_null_measurable.Union_nat {s : ℕ → set α} (hs : ∀ i, is_null_measurable μ (s i)) :
is_null_measurable μ (Union s) :=
begin
choose t ht using assume i, is_null_measurable_iff.1 (hs i),
simp [forall_and_distrib] at ht,
rcases ht with ⟨st, ht, hz⟩,
refine is_null_measurable_iff.2
⟨Union t, Union_subset_Union st, is_measurable.Union ht,
measure_mono_null _ (measure_Union_null hz)⟩,
rw [diff_subset_iff, ← Union_union_distrib],
exact Union_subset_Union (λ i, by rw ← diff_subset_iff)
end
theorem is_measurable.diff_null (hs : is_measurable s) (hz : μ z = 0) :
is_null_measurable μ (s \ z) :=
begin
rw measure_eq_infi at hz,
choose f hf using show ∀ q : {q : ℚ // q > 0}, ∃ t : set α,
z ⊆ t ∧ is_measurable t ∧ μ t < (nnreal.of_real q.1 : ennreal),
{ rintro ⟨ε, ε0⟩,
have : 0 < (nnreal.of_real ε : ennreal), { simpa using ε0 },
rw ← hz at this, simpa [infi_lt_iff] },
refine is_null_measurable_iff.2 ⟨s \ Inter f,
diff_subset_diff_right (subset_Inter (λ i, (hf i).1)),
hs.diff (is_measurable.Inter (λ i, (hf i).2.1)),
measure_mono_null _ (nonpos_iff_eq_zero.1 $ le_of_not_lt $ λ h, _)⟩,
{ exact Inter f },
{ rw [diff_subset_iff, diff_union_self],
exact subset.trans (diff_subset _ _) (subset_union_left _ _) },
rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨ε, ε0', ε0, h⟩,
simp at ε0,
apply not_le_of_lt (lt_trans (hf ⟨ε, ε0⟩).2.2 h),
exact measure_mono (Inter_subset _ _)
end
theorem is_null_measurable.diff_null (hs : is_null_measurable μ s) (hz : μ z = 0) :
is_null_measurable μ (s \ z) :=
begin
rcases hs with ⟨t, z', rfl, ht, hz'⟩,
rw [set.union_diff_distrib],
exact (ht.diff_null hz).union_null (measure_mono_null (diff_subset _ _) hz')
end
theorem is_null_measurable.compl (hs : is_null_measurable μ s) : is_null_measurable μ sᶜ :=
begin
rcases hs with ⟨t, z, rfl, ht, hz⟩,
rw compl_union,
exact ht.compl.diff_null hz
end
theorem is_null_measurable_iff_ae {s : set α} :
is_null_measurable μ s ↔ ∃ t, is_measurable t ∧ s =ᵐ[μ] t :=
begin
simp only [ae_eq_set],
split,
{ assume h,
rcases is_null_measurable_iff.1 h with ⟨t, ts, tmeas, ht⟩,
refine ⟨t, tmeas, ht, _⟩,
rw [diff_eq_empty.2 ts, measure_empty] },
{ rintros ⟨t, tmeas, h₁, h₂⟩,
have : is_null_measurable μ (t ∪ (s \ t)) :=
is_null_measurable.union_null (tmeas.is_null_measurable _) h₁,
have A : is_null_measurable μ ((t ∪ (s \ t)) \ (t \ s)) :=
is_null_measurable.diff_null this h₂,
have : (t ∪ (s \ t)) \ (t \ s) = s,
{ apply subset.antisymm,
{ assume x hx,
simp only [mem_union_eq, not_and, mem_diff, not_not_mem] at hx,
cases hx.1, { exact hx.2 h }, { exact h.1 } },
{ assume x hx,
simp [hx, classical.em (x ∈ t)] } },
rwa this at A }
end
theorem is_null_measurable_iff_sandwich {s : set α} :
is_null_measurable μ s ↔
∃ (t u : set α), is_measurable t ∧ is_measurable u ∧ t ⊆ s ∧ s ⊆ u ∧ μ (u \ t) = 0 :=
begin
split,
{ assume h,
rcases is_null_measurable_iff.1 h with ⟨t, ts, tmeas, ht⟩,
rcases is_null_measurable_iff.1 h.compl with ⟨u', u's, u'meas, hu'⟩,
have A : s ⊆ u'ᶜ := subset_compl_comm.mp u's,
refine ⟨t, u'ᶜ, tmeas, u'meas.compl, ts, A, _⟩,
have : sᶜ \ u' = u'ᶜ \ s, by simp [compl_eq_univ_diff, diff_diff, union_comm],
rw this at hu',
apply le_antisymm _ bot_le,
calc μ (u'ᶜ \ t) ≤ μ ((u'ᶜ \ s) ∪ (s \ t)) :
begin
apply measure_mono,
assume x hx,
simp at hx,
simp [hx, or_comm, classical.em],
end
... ≤ μ (u'ᶜ \ s) + μ (s \ t) : measure_union_le _ _
... = 0 : by rw [ht, hu', zero_add] },
{ rintros ⟨t, u, tmeas, umeas, ts, su, hμ⟩,
refine is_null_measurable_iff.2 ⟨t, ts, tmeas, _⟩,
apply le_antisymm _ bot_le,
calc μ (s \ t) ≤ μ (u \ t) : measure_mono (diff_subset_diff_left su)
... = 0 : hμ }
end
lemma restrict_apply_of_is_null_measurable {s t : set α}
(ht : is_null_measurable (μ.restrict s) t) : μ.restrict s t = μ (t ∩ s) :=
begin
rcases is_null_measurable_iff_sandwich.1 ht with ⟨u, v, umeas, vmeas, ut, tv, huv⟩,
apply le_antisymm _ (le_restrict_apply _ _),
calc μ.restrict s t ≤ μ.restrict s v : measure_mono tv
... = μ (v ∩ s) : restrict_apply vmeas
... ≤ μ ((u ∩ s) ∪ ((v \ u) ∩ s)) : measure_mono $
by { assume x hx, simp at hx, simp [hx, classical.em] }
... ≤ μ (u ∩ s) + μ ((v \ u) ∩ s) : measure_union_le _ _
... = μ (u ∩ s) + μ.restrict s (v \ u) : by rw measure.restrict_apply (vmeas.diff umeas)
... = μ (u ∩ s) : by rw [huv, add_zero]
... ≤ μ (t ∩ s) : measure_mono $ inter_subset_inter_left s ut
end
/-- The measurable space of all null measurable sets. -/
def null_measurable (μ : measure α) : measurable_space α :=
{ is_measurable' := is_null_measurable μ,
is_measurable_empty := is_measurable.empty.is_null_measurable _,
is_measurable_compl := λ s hs, hs.compl,
is_measurable_Union := λ f, is_null_measurable.Union_nat }
/-- Given a measure we can complete it to a (complete) measure on all null measurable sets. -/
def completion (μ : measure α) : @measure_theory.measure α (null_measurable μ) :=
{ to_outer_measure := μ.to_outer_measure,
m_Union := λ s hs hd, show μ (Union s) = ∑' i, μ (s i), begin
choose t ht using assume i, is_null_measurable_iff.1 (hs i),
simp [forall_and_distrib] at ht, rcases ht with ⟨st, ht, hz⟩,
rw is_null_measurable_measure_eq (Union_subset_Union st),
{ rw measure_Union _ ht,
{ congr, funext i,
exact (is_null_measurable_measure_eq (st i) (hz i)).symm },
{ rintro i j ij x ⟨h₁, h₂⟩,
exact hd i j ij ⟨st i h₁, st j h₂⟩ } },
{ refine measure_mono_null _ (measure_Union_null hz),
rw [diff_subset_iff, ← Union_union_distrib],
exact Union_subset_Union (λ i, by rw ← diff_subset_iff) }
end,
trimmed := begin
letI := null_measurable μ,
refine le_antisymm (λ s, _) (outer_measure.le_trim _),
rw outer_measure.trim_eq_infi,
dsimp,
clear _inst,
resetI,
rw measure_eq_infi s,
exact infi_le_infi (λ t, infi_le_infi $ λ st,
infi_le_infi2 $ λ ht, ⟨ht.is_null_measurable _, le_refl _⟩)
end }
instance completion.is_complete (μ : measure α) : (completion μ).is_complete :=
λ z hz, null_is_null_measurable hz
lemma measurable.ae_eq {α β} [measurable_space α] [measurable_space β] {μ : measure α}
[hμ : μ.is_complete] {f g : α → β} (hf : measurable f) (hfg : f =ᵐ[μ] g) :
measurable g :=
begin
intros s hs,
let t := {x | f x = g x},
have ht_compl : μ tᶜ = 0, by rwa [filter.eventually_eq, ae_iff] at hfg,
rw (set.inter_union_compl (g ⁻¹' s) t).symm,
refine is_measurable.union _ _,
{ have h_g_to_f : (g ⁻¹' s) ∩ t = (f ⁻¹' s) ∩ t,
{ ext,
simp only [set.mem_inter_iff, set.mem_preimage, and.congr_left_iff, set.mem_set_of_eq],
exact λ hx, by rw hx, },
rw h_g_to_f,
exact is_measurable.inter (hf hs) (is_measurable.compl_iff.mp (hμ tᶜ ht_compl)), },
{ exact hμ (g ⁻¹' s ∩ tᶜ) (measure_mono_null (set.inter_subset_right _ _) ht_compl), },
end
end is_complete
namespace measure_theory
/-- A measure space is a measurable space equipped with a
measure, referred to as `volume`. -/
class measure_space (α : Type*) extends measurable_space α :=
(volume : measure α)
export measure_space (volume)
/-- `volume` is the canonical measure on `α`. -/
add_decl_doc volume
section measure_space
variables [measure_space α] {s₁ s₂ : set α}
notation `∀ᵐ` binders `, ` r:(scoped P, filter.eventually P (measure.ae volume)) := r
/-- The tactic `exact volume`, to be used in optional (`auto_param`) arguments. -/
meta def volume_tac : tactic unit := `[exact measure_theory.measure_space.volume]
end measure_space
end measure_theory
/-!
# Almost everywhere measurable functions
A function is almost everywhere measurable if it coincides almost everywhere with a measurable
function. We define this property, called `ae_measurable f μ`, and discuss several of its properties
that are analogous to properties of measurable functions.
-/
section
open measure_theory
variables [measurable_space α] [measurable_space β]
{f g : α → β} {μ ν : measure α}
/-- A function is almost everywhere measurable if it coincides almost everywhere with a measurable
function. -/
def ae_measurable (f : α → β) (μ : measure α . measure_theory.volume_tac) : Prop :=
∃ g : α → β, measurable g ∧ f =ᵐ[μ] g
lemma measurable.ae_measurable (h : measurable f) : ae_measurable f μ :=
⟨f, h, ae_eq_refl f⟩
@[nontriviality] lemma subsingleton.ae_measurable [subsingleton α] : ae_measurable f μ :=
subsingleton.measurable.ae_measurable
@[simp] lemma ae_measurable_zero : ae_measurable f 0 :=
begin
nontriviality α, inhabit α,
exact ⟨λ x, f (default α), measurable_const, rfl⟩
end
lemma ae_measurable_iff_measurable [μ.is_complete] :
ae_measurable f μ ↔ measurable f :=
begin
split; intro h,
{ rcases h with ⟨g, hg_meas, hfg⟩,
exact hg_meas.ae_eq hfg.symm, },
{ exact h.ae_measurable, },
end
namespace ae_measurable
/-- Given an almost everywhere measurable function `f`, associate to it a measurable function
that coincides with it almost everywhere. `f` is explicit in the definition to make sure that
it shows in pretty-printing. -/
def mk (f : α → β) (h : ae_measurable f μ) : α → β := classical.some h
lemma measurable_mk (h : ae_measurable f μ) : measurable (h.mk f) :=
(classical.some_spec h).1
lemma ae_eq_mk (h : ae_measurable f μ) : f =ᵐ[μ] (h.mk f) :=
(classical.some_spec h).2
lemma congr (hf : ae_measurable f μ) (h : f =ᵐ[μ] g) : ae_measurable g μ :=
⟨hf.mk f, hf.measurable_mk, h.symm.trans hf.ae_eq_mk⟩
lemma mono_measure (h : ae_measurable f μ) (h' : ν ≤ μ) : ae_measurable f ν :=
⟨h.mk f, h.measurable_mk, eventually.filter_mono (ae_mono h') h.ae_eq_mk⟩
lemma mono_set {s t} (h : s ⊆ t) (ht : ae_measurable f (μ.restrict t)) :
ae_measurable f (μ.restrict s) :=
ht.mono_measure (restrict_mono h le_rfl)
lemma ae_mem_imp_eq_mk {s} (h : ae_measurable f (μ.restrict s)) :
∀ᵐ x ∂μ, x ∈ s → f x = h.mk f x :=
ae_imp_of_ae_restrict h.ae_eq_mk
lemma ae_inf_principal_eq_mk {s} (h : ae_measurable f (μ.restrict s)) :
f =ᶠ[μ.ae ⊓ 𝓟 s] h.mk f :=
le_ae_restrict h.ae_eq_mk
lemma add_measure {f : α → β} (hμ : ae_measurable f μ) (hν : ae_measurable f ν) :
ae_measurable f (μ + ν) :=
begin
let s := {x | f x ≠ hμ.mk f x},
have : μ s = 0 := hμ.ae_eq_mk,
obtain ⟨t, st, t_meas, μt⟩ : ∃ t, s ⊆ t ∧ is_measurable t ∧ μ t = 0 :=
exists_is_measurable_superset_of_null this,
let g : α → β := t.piecewise (hν.mk f) (hμ.mk f),
refine ⟨g, measurable.piecewise t_meas hν.measurable_mk hμ.measurable_mk, _⟩,
change μ {x | f x ≠ g x} + ν {x | f x ≠ g x} = 0,
suffices : μ {x | f x ≠ g x} = 0 ∧ ν {x | f x ≠ g x} = 0, by simp [this.1, this.2],
have ht : {x | f x ≠ g x} ⊆ t,
{ assume x hx,
by_contra h,
simp only [g, h, mem_set_of_eq, ne.def, not_false_iff, piecewise_eq_of_not_mem] at hx,
exact h (st hx) },
split,
{ have : μ {x | f x ≠ g x} ≤ μ t := measure_mono ht,
rw μt at this,
exact le_antisymm this bot_le },
{ have : {x | f x ≠ g x} ⊆ {x | f x ≠ hν.mk f x},
{ assume x hx,
simpa [ht hx, g] using hx },
apply le_antisymm _ bot_le,
calc ν {x | f x ≠ g x} ≤ ν {x | f x ≠ hν.mk f x} : measure_mono this
... = 0 : hν.ae_eq_mk }
end
lemma smul_measure (h : ae_measurable f μ) (c : ennreal) :
ae_measurable f (c • μ) :=
⟨h.mk f, h.measurable_mk, ae_smul_measure h.ae_eq_mk c⟩
lemma comp_measurable [measurable_space δ] {f : α → δ} {g : δ → β}
(hg : ae_measurable g (measure.map f μ)) (hf : measurable f) : ae_measurable (g ∘ f) μ :=
⟨(hg.mk g) ∘ f, hg.measurable_mk.comp hf, ae_eq_comp hf hg.ae_eq_mk⟩
lemma prod_mk {γ : Type*} [measurable_space γ] {f : α → β} {g : α → γ}
(hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ x, (f x, g x)) μ :=
⟨λ a, (hf.mk f a, hg.mk g a), hf.measurable_mk.prod_mk hg.measurable_mk,
eventually_eq.prod_mk hf.ae_eq_mk hg.ae_eq_mk⟩
lemma is_null_measurable (h : ae_measurable f μ) {s : set β} (hs : is_measurable s) :
is_null_measurable μ (f ⁻¹' s) :=
begin
apply is_null_measurable_iff_ae.2,
refine ⟨(h.mk f) ⁻¹' s, h.measurable_mk hs, _⟩,
filter_upwards [h.ae_eq_mk],
assume x hx,
change (f x ∈ s) = ((h.mk f) x ∈ s),
rwa hx
end
end ae_measurable
lemma ae_measurable_congr (h : f =ᵐ[μ] g) :
ae_measurable f μ ↔ ae_measurable g μ :=
⟨λ hf, ae_measurable.congr hf h, λ hg, ae_measurable.congr hg h.symm⟩
@[simp] lemma ae_measurable_add_measure_iff :
ae_measurable f (μ + ν) ↔ ae_measurable f μ ∧ ae_measurable f ν :=
⟨λ h, ⟨h.mono_measure (measure.le_add_right (le_refl _)),
h.mono_measure (measure.le_add_left (le_refl _))⟩,
λ h, h.1.add_measure h.2⟩
@[simp] lemma ae_measurable_const {b : β} : ae_measurable (λ a : α, b) μ :=
measurable_const.ae_measurable
@[simp] lemma ae_measurable_smul_measure_iff {c : ennreal} (hc : c ≠ 0) :
ae_measurable f (c • μ) ↔ ae_measurable f μ :=
⟨λ h, ⟨h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).1 h.ae_eq_mk⟩,
λ h, ⟨h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).2 h.ae_eq_mk⟩⟩
lemma measurable.comp_ae_measurable [measurable_space δ] {f : α → δ} {g : δ → β}
(hg : measurable g) (hf : ae_measurable f μ) : ae_measurable (g ∘ f) μ :=
⟨g ∘ hf.mk f, hg.comp hf.measurable_mk, eventually_eq.fun_comp hf.ae_eq_mk _⟩
end
namespace is_compact
variables [topological_space α] [measurable_space α] {μ : measure α} {s : set α}
lemma finite_measure_of_nhds_within (hs : is_compact s) :
(∀ a ∈ s, μ.finite_at_filter (𝓝[s] a)) → μ s < ⊤ :=
by simpa only [← measure.compl_mem_cofinite, measure.finite_at_filter]
using hs.compl_mem_sets_of_nhds_within
lemma finite_measure [locally_finite_measure μ] (hs : is_compact s) : μ s < ⊤ :=
hs.finite_measure_of_nhds_within $ λ a ha, μ.finite_at_nhds_within _ _
lemma measure_zero_of_nhds_within (hs : is_compact s) :
(∀ a ∈ s, ∃ t ∈ 𝓝[s] a, μ t = 0) → μ s = 0 :=
by simpa only [← compl_mem_ae_iff] using hs.compl_mem_sets_of_nhds_within
end is_compact
lemma metric.bounded.finite_measure [metric_space α] [proper_space α]
[measurable_space α] {μ : measure α} [locally_finite_measure μ] {s : set α}
(hs : metric.bounded s) :
μ s < ⊤ :=
(measure_mono subset_closure).trans_lt (metric.compact_iff_closed_bounded.2
⟨is_closed_closure, metric.bounded_closure_of_bounded hs⟩).finite_measure
|
a7973cf779b86495fabeee9b22f13ffba2270f59 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/algebraic_geometry/ringed_space.lean | 0f9858751f581536a3995f3fd5c808fd93de3278 | [
"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 | 4,761 | lean | /-
Copyright (c) 2021 Justus Springer. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Justus Springer
-/
import algebraic_geometry.sheafed_space
import algebraic_geometry.stalks
import algebra.category.CommRing.limits
import algebra.category.CommRing.colimits
import algebra.category.CommRing.filtered_colimits
/-!
# Ringed spaces
We introduce the category of ringed spaces, as an alias for `SheafedSpace CommRing`.
The facts collected in this file are typically stated for locally ringed spaces, but never actually
make use of the locality of stalks. See for instance https://stacks.math.columbia.edu/tag/01HZ.
-/
universe v
open category_theory
open topological_space
open opposite
open Top
open Top.presheaf
namespace algebraic_geometry
/-- The type of Ringed spaces, as an abbreviation for `SheafedSpace CommRing`. -/
abbreviation RingedSpace : Type* := SheafedSpace CommRing
namespace RingedSpace
open SheafedSpace
variables (X : RingedSpace.{v})
/--
If the germ of a section `f` is a unit in the stalk at `x`, then `f` must be a unit on some small
neighborhood around `x`.
-/
lemma is_unit_res_of_is_unit_germ (U : opens X) (f : X.presheaf.obj (op U)) (x : U)
(h : is_unit (X.presheaf.germ x f)) :
∃ (V : opens X) (i : V ⟶ U) (hxV : x.1 ∈ V), is_unit (X.presheaf.map i.op f) :=
begin
obtain ⟨g', heq⟩ := h.exists_right_inv,
obtain ⟨V, hxV, g, rfl⟩ := X.presheaf.germ_exist x.1 g',
let W := U ⊓ V,
have hxW : x.1 ∈ W := ⟨x.2, hxV⟩,
erw [← X.presheaf.germ_res_apply (opens.inf_le_left U V) ⟨x.1, hxW⟩ f,
← X.presheaf.germ_res_apply (opens.inf_le_right U V) ⟨x.1, hxW⟩ g,
← ring_hom.map_mul, ← ring_hom.map_one (X.presheaf.germ (⟨x.1, hxW⟩ : W))] at heq,
obtain ⟨W', hxW', i₁, i₂, heq'⟩ := X.presheaf.germ_eq x.1 hxW hxW _ _ heq,
use [W', i₁ ≫ opens.inf_le_left U V, hxW'],
rw [ring_hom.map_one, ring_hom.map_mul, ← comp_apply, ← X.presheaf.map_comp, ← op_comp] at heq',
exact is_unit_of_mul_eq_one _ _ heq',
end
/-- If a section `f` is a unit in each stalk, `f` must be a unit. -/
lemma is_unit_of_is_unit_germ (U : opens X) (f : X.presheaf.obj (op U))
(h : ∀ x : U, is_unit (X.presheaf.germ x f)) :
is_unit f :=
begin
-- We pick a cover of `U` by open sets `V x`, such that `f` is a unit on each `V x`.
choose V iVU m h_unit using λ x : U, X.is_unit_res_of_is_unit_germ U f x (h x),
have hcover : U ≤ supr V,
{ intros x hxU,
rw [opens.mem_coe, opens.mem_supr],
exact ⟨⟨x, hxU⟩, m ⟨x, hxU⟩⟩ },
-- Let `g x` denote the inverse of `f` in `U x`.
choose g hg using λ x : U, is_unit.exists_right_inv (h_unit x),
-- We claim that these local inverses glue together to a global inverse of `f`.
obtain ⟨gl, gl_spec, -⟩ := X.sheaf.exists_unique_gluing' V U iVU hcover g _,
swap,
{ intros x y,
apply section_ext X.sheaf (V x ⊓ V y),
rintro ⟨z, hzVx, hzVy⟩,
rw [germ_res_apply, germ_res_apply],
apply (is_unit.mul_right_inj (h ⟨z, (iVU x).le hzVx⟩)).mp,
erw [← X.presheaf.germ_res_apply (iVU x) ⟨z, hzVx⟩ f, ← ring_hom.map_mul,
congr_arg (X.presheaf.germ (⟨z, hzVx⟩ : V x)) (hg x), germ_res_apply,
← X.presheaf.germ_res_apply (iVU y) ⟨z, hzVy⟩ f, ← ring_hom.map_mul,
congr_arg (X.presheaf.germ (⟨z, hzVy⟩ : V y)) (hg y),
ring_hom.map_one, ring_hom.map_one] },
apply is_unit_of_mul_eq_one f gl,
apply X.sheaf.eq_of_locally_eq' V U iVU hcover,
intro i,
rw [ring_hom.map_one, ring_hom.map_mul, gl_spec],
exact hg i,
end
/--
The basic open of a global section `f` is the set of all points `x`, such that the germ of `f` at
`x` is a unit.
-/
def basic_open (f : Γ.obj (op X)) : opens X :=
{ val := { x : X | is_unit (X.presheaf.germ (⟨x, trivial⟩ : (⊤ : opens X)) f) },
property := begin
rw is_open_iff_forall_mem_open,
intros x hx,
obtain ⟨U, i, hxU, hf⟩ := X.is_unit_res_of_is_unit_germ ⊤ f ⟨x, trivial⟩ hx,
use U.1,
refine ⟨_, U.2, hxU⟩,
intros y hy,
rw set.mem_set_of_eq,
convert ring_hom.is_unit_map (X.presheaf.germ ⟨y, hy⟩) hf,
exact (X.presheaf.germ_res_apply i ⟨y, hy⟩ f).symm,
end }
@[simp]
lemma mem_basic_open (f : Γ.obj (op X)) (x : X) :
x ∈ X.basic_open f ↔ is_unit (X.presheaf.germ (⟨x, trivial⟩ : (⊤ : opens X)) f) := iff.rfl
/-- The restriction of a global section `f` to the basic open of `f` is a unit. -/
lemma is_unit_res_basic_open (f : Γ.obj (op X)) :
is_unit (X.presheaf.map (opens.le_top (X.basic_open f)).op f) :=
begin
apply is_unit_of_is_unit_germ,
rintro ⟨x, hx⟩,
convert hx,
rw germ_res_apply,
refl,
end
end RingedSpace
end algebraic_geometry
|
262959beb8419be8eb56391972e88171e6b532b1 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/blast_unit.lean | 3c58c1ad2ccdf1216386c6873c9ad54a3b3e1d12 | [
"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 | 5,441 | lean | -- Testing all possible cases of [unit_action]
set_option blast.strategy "unit"
variables {A₁ A₂ A₃ A₄ B₁ B₂ B₃ B₄ : Prop}
-- H first, all pos
example (H : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) (a1 : A₁) (a2 : A₂) (a3 : A₃) (n1 : ¬ B₁) (n2 : ¬ B₂) (n3 : ¬ B₃) : B₄ := by blast
example (H : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) (a1 : A₁) (a2 : A₂) (a3 : A₃) (n1 : ¬ B₁) (n2 : ¬ B₂) (n3 : ¬ B₄) : B₃ := by blast
example (H : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) (a1 : A₁) (a2 : A₂) (a3 : A₃) (n1 : ¬ B₁) (n3 : ¬ B₃) (n3 : ¬ B₄) : B₂ := by blast
example (H : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) (a1 : A₁) (a2 : A₂) (a3 : A₃) (n2 : ¬ B₂) (n3 : ¬ B₃) (n3 : ¬ B₄) : B₁ := by blast
example (H : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) (a1 : A₁) (a2 : A₂) (n1 : ¬ B₁) (n2 : ¬ B₂) (n3 : ¬ B₃) (n3 : ¬ B₄) : ¬ A₃ := by blast
example (H : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) (a1 : A₁) (a3 : A₃) (n1 : ¬ B₁) (n2 : ¬ B₂) (n3 : ¬ B₃) (n3 : ¬ B₄) : ¬ A₂ := by blast
example (H : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) (a2 : A₂) (a3 : A₃) (n1 : ¬ B₁) (n2 : ¬ B₂) (n3 : ¬ B₃) (n3 : ¬ B₄) : ¬ A₁ := by blast
-- H last, all pos
example (a1 : A₁) (a2 : A₂) (a3 : A₃) (n1 : ¬ B₁) (n2 : ¬ B₂) (n3 : ¬ B₃) (H : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) : B₄ := by blast
example (a1 : A₁) (a2 : A₂) (a3 : A₃) (n1 : ¬ B₁) (n2 : ¬ B₂) (n3 : ¬ B₄) (H : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) : B₃ := by blast
example (a1 : A₁) (a2 : A₂) (a3 : A₃) (n1 : ¬ B₁) (n3 : ¬ B₃) (n3 : ¬ B₄) (H : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) : B₂ := by blast
example (a1 : A₁) (a2 : A₂) (a3 : A₃) (n2 : ¬ B₂) (n3 : ¬ B₃) (n3 : ¬ B₄) (H : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) : B₁ := by blast
example (a1 : A₁) (a2 : A₂) (n1 : ¬ B₁) (n2 : ¬ B₂) (n3 : ¬ B₃) (n3 : ¬ B₄) (H : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) : ¬ A₃ := by blast
example (a1 : A₁) (a3 : A₃) (n1 : ¬ B₁) (n2 : ¬ B₂) (n3 : ¬ B₃) (n3 : ¬ B₄) (H : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) : ¬ A₂ := by blast
example (a2 : A₂) (a3 : A₃) (n1 : ¬ B₁) (n2 : ¬ B₂) (n3 : ¬ B₃) (n3 : ¬ B₄) (H : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) : ¬ A₁ := by blast
-- H first, all neg
example (H : ¬ A₁ → ¬ A₂ → ¬ A₃ → ¬ B₁ ∨ ¬ B₂ ∨ ¬ B₃ ∨ ¬ B₄) (n1 : ¬ A₁) (n2 : ¬ A₂) (n3 : ¬ A₃) (b1 : B₁) (b2 : B₂) (b3 : B₃) : ¬ B₄ := by blast
example (H : ¬ A₁ → ¬ A₂ → ¬ A₃ → ¬ B₁ ∨ ¬ B₂ ∨ ¬ B₃ ∨ ¬ B₄) (n1 : ¬ A₁) (n2 : ¬ A₂) (n3 : ¬ A₃) (b1 : B₁) (b2 : B₂) (b4 : B₄) : ¬ B₃ := by blast
example (H : ¬ A₁ → ¬ A₂ → ¬ A₃ → ¬ B₁ ∨ ¬ B₂ ∨ ¬ B₃ ∨ ¬ B₄) (n1 : ¬ A₁) (n2 : ¬ A₂) (n3 : ¬ A₃) (b1 : B₁) (b3 : B₃) (b4 : B₄) : ¬ B₂ := by blast
example (H : ¬ A₁ → ¬ A₂ → ¬ A₃ → ¬ B₁ ∨ ¬ B₂ ∨ ¬ B₃ ∨ ¬ B₄) (n1 : ¬ A₁) (n2 : ¬ A₂) (n3 : ¬ A₃) (b2 : B₂) (b3 : B₃) (b4 : B₄) : ¬ B₁ := by blast
example (H : ¬ A₁ → ¬ A₂ → ¬ A₃ → ¬ B₁ ∨ ¬ B₂ ∨ ¬ B₃ ∨ ¬ B₄) (n1 : ¬ A₁) (n2 : ¬ A₂) (b1 : B₁) (b2 : B₂) (b3 : B₃) (b4 : B₄) : ¬ ¬ A₃ := by blast
example (H : ¬ A₁ → ¬ A₂ → ¬ A₃ → ¬ B₁ ∨ ¬ B₂ ∨ ¬ B₃ ∨ ¬ B₄) (n1 : ¬ A₁) (n3 : ¬ A₃) (b1 : B₁) (b2 : B₂) (b3 : B₃) (b4 : B₄) : ¬ ¬ A₂ := by blast
example (H : ¬ A₁ → ¬ A₂ → ¬ A₃ → ¬ B₁ ∨ ¬ B₂ ∨ ¬ B₃ ∨ ¬ B₄) (n2 : ¬ A₂) (n3 : ¬ A₃) (b1 : B₁) (b2 : B₂) (b3 : B₃) (b4 : B₄) : ¬ ¬ A₁ := by blast
-- H last, all neg
example (n1 : ¬ A₁) (n2 : ¬ A₂) (n3 : ¬ A₃) (b1 : B₁) (b2 : B₂) (b3 : B₃) (H : ¬ A₁ → ¬ A₂ → ¬ A₃ → ¬ B₁ ∨ ¬ B₂ ∨ ¬ B₃ ∨ ¬ B₄) : ¬ B₄ := by blast
example (n1 : ¬ A₁) (n2 : ¬ A₂) (n3 : ¬ A₃) (b1 : B₁) (b2 : B₂) (b4 : B₄) (H : ¬ A₁ → ¬ A₂ → ¬ A₃ → ¬ B₁ ∨ ¬ B₂ ∨ ¬ B₃ ∨ ¬ B₄) : ¬ B₃ := by blast
example (n1 : ¬ A₁) (n2 : ¬ A₂) (n3 : ¬ A₃) (b1 : B₁) (b3 : B₃) (b4 : B₄) (H : ¬ A₁ → ¬ A₂ → ¬ A₃ → ¬ B₁ ∨ ¬ B₂ ∨ ¬ B₃ ∨ ¬ B₄) : ¬ B₂ := by blast
example (n1 : ¬ A₁) (n2 : ¬ A₂) (n3 : ¬ A₃) (b2 : B₂) (b3 : B₃) (b4 : B₄) (H : ¬ A₁ → ¬ A₂ → ¬ A₃ → ¬ B₁ ∨ ¬ B₂ ∨ ¬ B₃ ∨ ¬ B₄) : ¬ B₁ := by blast
example (n1 : ¬ A₁) (n2 : ¬ A₂) (b1 : B₁) (b2 : B₂) (b3 : B₃) (b4 : B₄) (H : ¬ A₁ → ¬ A₂ → ¬ A₃ → ¬ B₁ ∨ ¬ B₂ ∨ ¬ B₃ ∨ ¬ B₄) : ¬ ¬ A₃ := by blast
example (n1 : ¬ A₁) (n3 : ¬ A₃) (b1 : B₁) (b2 : B₂) (b3 : B₃) (b4 : B₄) (H : ¬ A₁ → ¬ A₂ → ¬ A₃ → ¬ B₁ ∨ ¬ B₂ ∨ ¬ B₃ ∨ ¬ B₄) : ¬ ¬ A₂ := by blast
example (n2 : ¬ A₂) (n3 : ¬ A₃) (b1 : B₁) (b2 : B₂) (b3 : B₃) (b4 : B₄) (H : ¬ A₁ → ¬ A₂ → ¬ A₃ → ¬ B₁ ∨ ¬ B₂ ∨ ¬ B₃ ∨ ¬ B₄) : ¬ ¬ A₁ := by blast
|
ad2c68b1937f0b7d0927a6cb0462f1c281f16168 | 947b78d97130d56365ae2ec264df196ce769371a | /src/Lean/Compiler/IR/ExpandResetReuse.lean | cc2485a30623b6f9e82ceb88979388001dd11562 | [
"Apache-2.0"
] | permissive | shyamalschandra/lean4 | 27044812be8698f0c79147615b1d5090b9f4b037 | 6e7a883b21eaf62831e8111b251dc9b18f40e604 | refs/heads/master | 1,671,417,126,371 | 1,601,859,995,000 | 1,601,860,020,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,689 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Compiler.IR.CompilerM
import Lean.Compiler.IR.NormIds
import Lean.Compiler.IR.FreeVars
namespace Lean
namespace IR
namespace ExpandResetReuse
/- Mapping from variable to projections -/
abbrev ProjMap := Std.HashMap VarId Expr
namespace CollectProjMap
abbrev Collector := ProjMap → ProjMap
@[inline] def collectVDecl (x : VarId) (v : Expr) : Collector :=
fun m => match v with
| Expr.proj _ _ => m.insert x v
| Expr.sproj _ _ _ => m.insert x v
| Expr.uproj _ _ => m.insert x v
| _ => m
partial def collectFnBody : FnBody → Collector
| FnBody.vdecl x _ v b => collectVDecl x v ∘ collectFnBody b
| FnBody.jdecl _ _ v b => collectFnBody v ∘ collectFnBody b
| FnBody.case _ _ _ alts => fun s => alts.foldl (fun s alt => collectFnBody alt.body s) s
| e => if e.isTerminal then id else collectFnBody e.body
end CollectProjMap
/- Create a mapping from variables to projections.
This function assumes variable ids have been normalized -/
def mkProjMap (d : Decl) : ProjMap :=
match d with
| Decl.fdecl _ _ _ b => CollectProjMap.collectFnBody b {}
| _ => {}
structure Context :=
(projMap : ProjMap)
/- Return true iff `x` is consumed in all branches of the current block.
Here consumption means the block contains a `dec x` or `reuse x ...`. -/
partial def consumed (x : VarId) : FnBody → Bool
| FnBody.vdecl _ _ v b =>
match v with
| Expr.reuse y _ _ _ => x == y || consumed b
| _ => consumed b
| FnBody.dec y _ _ _ b => x == y || consumed b
| FnBody.case _ _ _ alts => alts.all $ fun alt => consumed alt.body
| e => !e.isTerminal && consumed e.body
abbrev Mask := Array (Option VarId)
/- Auxiliary function for eraseProjIncFor -/
partial def eraseProjIncForAux (y : VarId) : Array FnBody → Mask → Array FnBody → Array FnBody × Mask
| bs, mask, keep =>
let done (_ : Unit) := (bs ++ keep.reverse, mask);
let keepInstr (b : FnBody) := eraseProjIncForAux bs.pop mask (keep.push b);
if bs.size < 2 then done ()
else
let b := bs.back;
match b with
| (FnBody.vdecl _ _ (Expr.sproj _ _ _) _) => keepInstr b
| (FnBody.vdecl _ _ (Expr.uproj _ _) _) => keepInstr b
| (FnBody.inc z n c p _) =>
if n == 0 then done () else
let b' := bs.get! (bs.size - 2);
match b' with
| (FnBody.vdecl w _ (Expr.proj i x) _) =>
if w == z && y == x then
/- Found
```
let z := proj[i] y;
inc z n c
```
We keep `proj`, and `inc` when `n > 1`
-/
let bs := bs.pop.pop;
let mask := mask.set! i (some z);
let keep := keep.push b';
let keep := if n == 1 then keep else keep.push (FnBody.inc z (n-1) c p FnBody.nil);
eraseProjIncForAux bs mask keep
else done ()
| other => done ()
| other => done ()
/- Try to erase `inc` instructions on projections of `y` occurring in the tail of `bs`.
Return the updated `bs` and a bit mask specifying which `inc`s have been removed. -/
def eraseProjIncFor (n : Nat) (y : VarId) (bs : Array FnBody) : Array FnBody × Mask :=
eraseProjIncForAux y bs (mkArray n none) #[]
/- Replace `reuse x ctor ...` with `ctor ...`, and remoce `dec x` -/
partial def reuseToCtor (x : VarId) : FnBody → FnBody
| FnBody.dec y n c p b =>
if x == y then b -- n must be 1 since `x := reset ...`
else FnBody.dec y n c p (reuseToCtor b)
| FnBody.vdecl z t v b =>
match v with
| Expr.reuse y c u xs =>
if x == y then FnBody.vdecl z t (Expr.ctor c xs) b
else FnBody.vdecl z t v (reuseToCtor b)
| _ =>
FnBody.vdecl z t v (reuseToCtor b)
| FnBody.case tid y yType alts =>
let alts := alts.map $ fun alt => alt.modifyBody reuseToCtor;
FnBody.case tid y yType alts
| e =>
if e.isTerminal then e
else
let (instr, b) := e.split;
let b := reuseToCtor b;
instr.setBody b
/-
replace
```
x := reset y; b
```
with
```
inc z_1; ...; inc z_i; dec y; b'
```
where `z_i`'s are the variables in `mask`,
and `b'` is `b` where we removed `dec x` and replaced `reuse x ctor_i ...` with `ctor_i ...`.
-/
def mkSlowPath (x y : VarId) (mask : Mask) (b : FnBody) : FnBody :=
let b := reuseToCtor x b;
let b := FnBody.dec y 1 true false b;
mask.foldl
(fun b m => match m with
| some z => FnBody.inc z 1 true false b
| none => b)
b
abbrev M := ReaderT Context (StateM Nat)
def mkFresh : M VarId :=
modifyGet $ fun n => ({ idx := n }, n + 1)
def releaseUnreadFields (y : VarId) (mask : Mask) (b : FnBody) : M FnBody :=
mask.size.foldM
(fun i b =>
match mask.get! i with
| some _ => pure b -- code took ownership of this field
| none => do
fld ← mkFresh;
pure (FnBody.vdecl fld IRType.object (Expr.proj i y) (FnBody.dec fld 1 true false b)))
b
def setFields (y : VarId) (zs : Array Arg) (b : FnBody) : FnBody :=
zs.size.fold
(fun i b => FnBody.set y i (zs.get! i) b)
b
/- Given `set x[i] := y`, return true iff `y := proj[i] x` -/
def isSelfSet (ctx : Context) (x : VarId) (i : Nat) (y : Arg) : Bool :=
match y with
| Arg.var y =>
match ctx.projMap.find? y with
| some (Expr.proj j w) => j == i && w == x
| _ => false
| _ => false
/- Given `uset x[i] := y`, return true iff `y := uproj[i] x` -/
def isSelfUSet (ctx : Context) (x : VarId) (i : Nat) (y : VarId) : Bool :=
match ctx.projMap.find? y with
| some (Expr.uproj j w) => j == i && w == x
| _ => false
/- Given `sset x[n, i] := y`, return true iff `y := sproj[n, i] x` -/
def isSelfSSet (ctx : Context) (x : VarId) (n : Nat) (i : Nat) (y : VarId) : Bool :=
match ctx.projMap.find? y with
| some (Expr.sproj m j w) => n == m && j == i && w == x
| _ => false
/- Remove unnecessary `set/uset/sset` operations -/
partial def removeSelfSet (ctx : Context) : FnBody → FnBody
| FnBody.set x i y b =>
if isSelfSet ctx x i y then removeSelfSet b
else FnBody.set x i y (removeSelfSet b)
| FnBody.uset x i y b =>
if isSelfUSet ctx x i y then removeSelfSet b
else FnBody.uset x i y (removeSelfSet b)
| FnBody.sset x n i y t b =>
if isSelfSSet ctx x n i y then removeSelfSet b
else FnBody.sset x n i y t (removeSelfSet b)
| FnBody.case tid y yType alts =>
let alts := alts.map $ fun alt => alt.modifyBody removeSelfSet;
FnBody.case tid y yType alts
| e =>
if e.isTerminal then e
else
let (instr, b) := e.split;
let b := removeSelfSet b;
instr.setBody b
partial def reuseToSet (ctx : Context) (x y : VarId) : FnBody → FnBody
| FnBody.dec z n c p b =>
if x == z then FnBody.del y b
else FnBody.dec z n c p (reuseToSet b)
| FnBody.vdecl z t v b =>
match v with
| Expr.reuse w c u zs =>
if x == w then
let b := setFields y zs (b.replaceVar z y);
let b := if u then FnBody.setTag y c.cidx b else b;
removeSelfSet ctx b
else FnBody.vdecl z t v (reuseToSet b)
| _ => FnBody.vdecl z t v (reuseToSet b)
| FnBody.case tid y yType alts =>
let alts := alts.map $ fun alt => alt.modifyBody reuseToSet;
FnBody.case tid y yType alts
| e =>
if e.isTerminal then e
else
let (instr, b) := e.split;
let b := reuseToSet b;
instr.setBody b
/-
replace
```
x := reset y; b
```
with
```
let f_i_1 := proj[i_1] y;
...
let f_i_k := proj[i_k] y;
b'
```
where `i_j`s are the field indexes
that the code did not touch immediately before the reset.
That is `mask[j] == none`.
`b'` is `b` where `y` `dec x` is replaced with `del y`,
and `z := reuse x ctor_i ws; F` is replaced with
`set x i ws[i]` operations, and we replace `z` with `x` in `F`
-/
def mkFastPath (x y : VarId) (mask : Mask) (b : FnBody) : M FnBody := do
ctx ← read;
let b := reuseToSet ctx x y b;
releaseUnreadFields y mask b
-- Expand `bs; x := reset[n] y; b`
partial def expand (mainFn : FnBody → Array FnBody → M FnBody)
(bs : Array FnBody) (x : VarId) (n : Nat) (y : VarId) (b : FnBody) : M FnBody := do
let bOld := FnBody.vdecl x IRType.object (Expr.reset n y) b;
let (bs, mask) := eraseProjIncFor n y bs;
/- Remark: we may be duplicting variable/JP indices. That is, `bSlow` and `bFast` may
have duplicate indices. We run `normalizeIds` to fix the ids after we have expand them. -/
let bSlow := mkSlowPath x y mask b;
bFast ← mkFastPath x y mask b;
/- We only optimize recursively the fast. -/
bFast ← mainFn bFast #[];
c ← mkFresh;
let b := FnBody.vdecl c IRType.uint8 (Expr.isShared y) (mkIf c bSlow bFast);
pure $ reshape bs b
partial def searchAndExpand : FnBody → Array FnBody → M FnBody
| d@(FnBody.vdecl x t (Expr.reset n y) b), bs =>
if consumed x b then do
expand searchAndExpand bs x n y b
else
searchAndExpand b (push bs d)
| FnBody.jdecl j xs v b, bs => do
v ← searchAndExpand v #[];
searchAndExpand b (push bs (FnBody.jdecl j xs v FnBody.nil))
| FnBody.case tid x xType alts, bs => do
alts ← alts.mapM $ fun alt => alt.mmodifyBody $ fun b => searchAndExpand b #[];
pure $ reshape bs (FnBody.case tid x xType alts)
| b, bs =>
if b.isTerminal then pure $ reshape bs b
else searchAndExpand b.body (push bs b)
def main (d : Decl) : Decl :=
match d with
| (Decl.fdecl f xs t b) =>
let m := mkProjMap d;
let nextIdx := d.maxIndex + 1;
let b := (searchAndExpand b #[] { projMap := m }).run' nextIdx;
Decl.fdecl f xs t b
| d => d
end ExpandResetReuse
/-- (Try to) expand `reset` and `reuse` instructions. -/
def Decl.expandResetReuse (d : Decl) : Decl :=
(ExpandResetReuse.main d).normalizeIds
end IR
end Lean
|
ee5f49b8b713612e50a25b6e192cda9bb258c121 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /tests/lean/run/typeclass_metas_internal_goals3.lean | 7f4add86670954f8f34500a5794e92a633a126fd | [
"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 | 604 | lean | class Base (α : Type) := (u:Unit)
class Depends (α : Type) [Base α] := (u:Unit)
class Top := (u:Unit)
instance AllBase {α : Type} : Base α := {u:=()}
instance DependsNotConstrainingImplicit {α : Type} /- [Base α] -/ {_:Base α} : Depends α := {u:=()}
instance BaseAsImplicit₁ {α : Type} {_:Base α} [Depends α] : Top := {u:=()}
instance BaseAsInstImplicit {α : Type} [Base α] [Depends α] : Top := {u:=()}
instance BaseAsImplicit₂ {α : Type} {_:Base α} [Depends α] : Top := {u:=()}
axiom K : Type
instance BaseK : Base K := {u:=()}
new_frontend
set_option pp.all true
#synth Top
|
39c9637ff296cc81a1d43f6f5903b0f65febe686 | 0845ae2ca02071debcfd4ac24be871236c01784f | /library/init/data/hashmap/basic.lean | 01ecb8e51992360506ae38923a5d13aa306efeae | [
"Apache-2.0"
] | permissive | GaloisInc/lean4 | 74c267eb0e900bfaa23df8de86039483ecbd60b7 | 228ddd5fdcd98dd4e9c009f425284e86917938aa | refs/heads/master | 1,643,131,356,301 | 1,562,715,572,000 | 1,562,715,572,000 | 192,390,898 | 0 | 0 | null | 1,560,792,750,000 | 1,560,792,749,000 | null | UTF-8 | Lean | false | false | 6,637 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import init.data.array.basic init.data.assoclist
import init.data.option.basic init.data.hashable
universes u v w
def HashMapBucket (α : Type u) (β : Type v) :=
{ b : Array (AssocList α β) // b.size > 0 }
def HashMapBucket.update {α : Type u} {β : Type v} (data : HashMapBucket α β) (i : USize) (d : AssocList α β) (h : i.toNat < data.val.size) : HashMapBucket α β :=
⟨ data.val.uset i d h,
transRelRight Greater (Array.szFSetEq (data.val) ⟨USize.toNat i, h⟩ d) data.property ⟩
structure HashMapImp (α : Type u) (β : Type v) :=
(size : Nat)
(buckets : HashMapBucket α β)
def mkHashMapImp {α : Type u} {β : Type v} (nbuckets := 8) : HashMapImp α β :=
let n := if nbuckets = 0 then 8 else nbuckets;
{ size := 0,
buckets :=
⟨ mkArray n AssocList.nil,
have p₁ : (mkArray n (@AssocList.nil α β)).size = n from Array.szMkArrayEq _ _;
have p₂ : n = (if nbuckets = 0 then 8 else nbuckets) from rfl;
have p₃ : (if nbuckets = 0 then 8 else nbuckets) > 0 from
match nbuckets with
| 0 => Nat.zeroLtSucc _
| (Nat.succ x) => Nat.zeroLtSucc _;
transRelRight Greater (Eq.trans p₁ p₂) p₃ ⟩ }
namespace HashMapImp
variables {α : Type u} {β : Type v}
def mkIdx {n : Nat} (h : n > 0) (u : USize) : { u : USize // u.toNat < n } :=
⟨u %ₙ n, USize.modnLt _ h⟩
@[inline] def reinsertAux (hashFn : α → USize) (data : HashMapBucket α β) (a : α) (b : β) : HashMapBucket α β :=
let ⟨i, h⟩ := mkIdx data.property (hashFn a);
data.update i (AssocList.cons a b (data.val.uget i h)) h
@[inline] def mfoldBuckets {δ : Type w} {m : Type w → Type w} [Monad m] (data : HashMapBucket α β) (d : δ) (f : δ → α → β → m δ) : m δ :=
data.val.mfoldl (fun d b => b.mfoldl f d) d
@[inline] def foldBuckets {δ : Type w} (data : HashMapBucket α β) (d : δ) (f : δ → α → β → δ) : δ :=
Id.run $ mfoldBuckets data d f
@[inline] def mfold {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → β → m δ) (d : δ) (h : HashMapImp α β) : m δ :=
mfoldBuckets h.buckets d f
@[inline] def fold {δ : Type w} (f : δ → α → β → δ) (d : δ) (m : HashMapImp α β) : δ :=
foldBuckets m.buckets d f
def find [HasBeq α] [Hashable α] (m : HashMapImp α β) (a : α) : Option β :=
match m with
| ⟨_, buckets⟩ =>
let ⟨i, h⟩ := mkIdx buckets.property (hash a);
(buckets.val.uget i h).find a
def contains [HasBeq α] [Hashable α] (m : HashMapImp α β) (a : α) : Bool :=
match m with
| ⟨_, buckets⟩ =>
let ⟨i, h⟩ := mkIdx buckets.property (hash a);
(buckets.val.uget i h).contains a
-- TODO: remove `partial` by using well-founded recursion
partial def moveEntries [Hashable α] : Nat → Array (AssocList α β) → HashMapBucket α β → HashMapBucket α β
| i source target :=
if h : i < source.size then
let idx : Fin source.size := ⟨i, h⟩;
let es : AssocList α β := source.fget idx;
-- We remove `es` from `source` to make sure we can reuse its memory cells when performing es.foldl
let source := source.fset idx AssocList.nil;
let target := es.foldl (reinsertAux hash) target;
moveEntries (i+1) source target
else target
def expand [Hashable α] (size : Nat) (buckets : HashMapBucket α β) : HashMapImp α β :=
let nbuckets := buckets.val.size * 2;
have aux₁ : nbuckets > 0 from Nat.mulPos buckets.property (Nat.zeroLtBit0 Nat.oneNeZero);
have aux₂ : (mkArray nbuckets (@AssocList.nil α β)).size = nbuckets from Array.szMkArrayEq _ _;
let new_buckets : HashMapBucket α β := ⟨mkArray nbuckets AssocList.nil, aux₂.symm ▸ aux₁⟩;
{ size := size,
buckets := moveEntries 0 buckets.val new_buckets }
def insert [HasBeq α] [Hashable α] (m : HashMapImp α β) (a : α) (b : β) : HashMapImp α β :=
match m with
| ⟨size, buckets⟩ =>
let ⟨i, h⟩ := mkIdx buckets.property (hash a);
let bkt := buckets.val.uget i h;
if bkt.contains a
then ⟨size, buckets.update i (bkt.replace a b) h⟩
else
let size' := size + 1;
let buckets' := buckets.update i (AssocList.cons a b bkt) h;
if size' ≤ buckets.val.size
then { size := size', buckets := buckets' }
else expand size' buckets'
def erase [HasBeq α] [Hashable α] (m : HashMapImp α β) (a : α) : HashMapImp α β :=
match m with
| ⟨ size, buckets ⟩ =>
let ⟨i, h⟩ := mkIdx buckets.property (hash a);
let bkt := buckets.val.uget i h;
if bkt.contains a then ⟨size - 1, buckets.update i (bkt.erase a) h⟩
else m
inductive WellFormed [HasBeq α] [Hashable α] : HashMapImp α β → Prop
| mkWff : ∀ n, WellFormed (mkHashMapImp n)
| insertWff : ∀ m a b, WellFormed m → WellFormed (insert m a b)
| eraseWff : ∀ m a, WellFormed m → WellFormed (erase m a)
end HashMapImp
def HashMap (α : Type u) (β : Type v) [HasBeq α] [Hashable α] :=
{ m : HashMapImp α β // m.WellFormed }
open HashMapImp
def mkHashMap {α : Type u} {β : Type v} [HasBeq α] [Hashable α] (nbuckets := 8) : HashMap α β :=
⟨ mkHashMapImp nbuckets, WellFormed.mkWff nbuckets ⟩
namespace HashMap
variables {α : Type u} {β : Type v} [HasBeq α] [Hashable α]
instance : Inhabited (HashMap α β) :=
⟨mkHashMap⟩
instance : HasEmptyc (HashMap α β) :=
⟨mkHashMap⟩
@[inline] def insert (m : HashMap α β) (a : α) (b : β) : HashMap α β :=
match m with
| ⟨ m, hw ⟩ => ⟨ m.insert a b, WellFormed.insertWff m a b hw ⟩
@[inline] def erase (m : HashMap α β) (a : α) : HashMap α β :=
match m with
| ⟨ m, hw ⟩ => ⟨ m.erase a, WellFormed.eraseWff m a hw ⟩
@[inline] def find (m : HashMap α β) (a : α) : Option β :=
match m with
| ⟨ m, _ ⟩ => m.find a
@[inline] def contains (m : HashMap α β) (a : α) : Bool :=
match m with
| ⟨ m, _ ⟩ => m.contains a
@[inline] def mfold {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → β → m δ) (d : δ) (h : HashMap α β) : m δ :=
match h with
| ⟨ h, _ ⟩ => h.mfold f d
@[inline] def fold {δ : Type w} (f : δ → α → β → δ) (d : δ) (m : HashMap α β) : δ :=
match m with
| ⟨ m, _ ⟩ => m.fold f d
@[inline] def size (m : HashMap α β) : Nat :=
match m with
| ⟨ {size := sz, ..}, _ ⟩ => sz
@[inline] def empty (m : HashMap α β) : Bool :=
m.size = 0
def numBuckets (m : HashMap α β) : Nat :=
m.val.buckets.val.size
end HashMap
|
3fdd3e676772a25e9bffdb0293cbaf8c08efeb3c | 30b012bb72d640ec30c8fdd4c45fdfa67beb012c | /group_theory/quotient_group.lean | e61cabe7ba09ac691a886ca3cf39fa05b367b58b | [
"Apache-2.0"
] | permissive | kckennylau/mathlib | 21fb810b701b10d6606d9002a4004f7672262e83 | 47b3477e20ffb5a06588dd3abb01fe0fe3205646 | refs/heads/master | 1,634,976,409,281 | 1,542,042,832,000 | 1,542,319,733,000 | 109,560,458 | 0 | 0 | Apache-2.0 | 1,542,369,208,000 | 1,509,867,494,000 | Lean | UTF-8 | Lean | false | false | 7,210 | lean | /-
Copyright (c) 2018 Kevin Buzzard and Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard, Patrick Massot.
This file is to a certain extent based on `quotient_module.lean` by Johannes Hölzl.
-/
import group_theory.coset
universes u v
variables {G : Type u} [group G] (N : set G) [normal_subgroup N] {H : Type v} [group H]
namespace quotient_group
instance : group (quotient N) :=
{ one := (1 : G),
mul := λ a b, quotient.lift_on₂' a b
(λ a b, ((a * b : G) : quotient N))
(λ a₁ a₂ b₁ b₂ hab₁ hab₂,
quot.sound
((is_subgroup.mul_mem_cancel_left N (is_subgroup.inv_mem hab₂)).1
(by rw [mul_inv_rev, mul_inv_rev, ← mul_assoc (a₂⁻¹ * a₁⁻¹),
mul_assoc _ b₂, ← mul_assoc b₂, mul_inv_self, one_mul, mul_assoc (a₂⁻¹)];
exact normal_subgroup.normal _ hab₁ _))),
mul_assoc := λ a b c, quotient.induction_on₃' a b c
(λ a b c, congr_arg mk (mul_assoc a b c)),
one_mul := λ a, quotient.induction_on' a
(λ a, congr_arg mk (one_mul a)),
mul_one := λ a, quotient.induction_on' a
(λ a, congr_arg mk (mul_one a)),
inv := λ a, quotient.lift_on' a (λ a, ((a⁻¹ : G) : quotient N))
(λ a b hab, quotient.sound' begin
show a⁻¹⁻¹ * b⁻¹ ∈ N,
rw ← mul_inv_rev,
exact is_subgroup.inv_mem (is_subgroup.mem_norm_comm hab)
end),
mul_left_inv := λ a, quotient.induction_on' a
(λ a, congr_arg mk (mul_left_inv a)) }
attribute [to_additive quotient_add_group.add_group._proof_6] quotient_group.group._proof_6
attribute [to_additive quotient_add_group.add_group._proof_5] quotient_group.group._proof_5
attribute [to_additive quotient_add_group.add_group._proof_4] quotient_group.group._proof_4
attribute [to_additive quotient_add_group.add_group._proof_3] quotient_group.group._proof_3
attribute [to_additive quotient_add_group.add_group._proof_2] quotient_group.group._proof_2
attribute [to_additive quotient_add_group.add_group._proof_1] quotient_group.group._proof_1
attribute [to_additive quotient_add_group.add_group] quotient_group.group
attribute [to_additive quotient_add_group.quotient.equations._eqn_1] quotient_group.quotient.equations._eqn_1
attribute [to_additive quotient_add_group.add_group.equations._eqn_1] quotient_group.group.equations._eqn_1
instance : is_group_hom (mk : G → quotient N) := ⟨λ _ _, rfl⟩
attribute [to_additive quotient_add_group.is_add_group_hom] quotient_group.is_group_hom
attribute [to_additive quotient_add_group.is_add_group_hom.equations._eqn_1] quotient_group.is_group_hom.equations._eqn_1
instance {G : Type*} [comm_group G] (s : set G) [is_subgroup s] : comm_group (quotient s) :=
{ mul_comm := λ a b, quotient.induction_on₂' a b
(λ a b, congr_arg mk (mul_comm a b)),
..@quotient_group.group _ _ s (normal_subgroup_of_comm_group s) }
attribute [to_additive quotient_add_group.add_comm_group._proof_6] quotient_group.comm_group._proof_6
attribute [to_additive quotient_add_group.add_comm_group._proof_5] quotient_group.comm_group._proof_5
attribute [to_additive quotient_add_group.add_comm_group._proof_4] quotient_group.comm_group._proof_4
attribute [to_additive quotient_add_group.add_comm_group._proof_3] quotient_group.comm_group._proof_3
attribute [to_additive quotient_add_group.add_comm_group._proof_2] quotient_group.comm_group._proof_2
attribute [to_additive quotient_add_group.add_comm_group._proof_1] quotient_group.comm_group._proof_1
attribute [to_additive quotient_add_group.add_comm_group] quotient_group.comm_group
attribute [to_additive quotient_add_group.add_comm_group.equations._eqn_1] quotient_group.comm_group.equations._eqn_1
@[simp] lemma coe_one : ((1 : G) : quotient N) = 1 := rfl
@[simp] lemma coe_mul (a b : G) : ((a * b : G) : quotient N) = a * b := rfl
@[simp] lemma coe_inv (a : G) : ((a⁻¹ : G) : quotient N) = a⁻¹ := rfl
@[simp] lemma coe_pow (a : G) (n : ℕ) : ((a ^ n : G) : quotient N) = a ^ n :=
@is_group_hom.pow _ _ _ _ mk _ a n
attribute [to_additive quotient_add_group.coe_zero] coe_one
attribute [to_additive quotient_add_group.coe_add] coe_mul
attribute [to_additive quotient_add_group.coe_neg] coe_inv
@[simp] lemma coe_gpow (a : G) (n : ℤ) : ((a ^ n : G) : quotient N) = a ^ n :=
@is_group_hom.gpow _ _ _ _ mk _ a n
local notation ` Q ` := quotient N
instance is_group_hom_quotient_group_mk : is_group_hom (mk : G → Q) :=
by refine {..}; intros; refl
attribute [to_additive quotient_add_group.is_add_group_hom_quotient_add_group_mk] quotient_group.is_group_hom_quotient_group_mk
attribute [to_additive quotient_add_group.is_add_group_hom_quotient_add_group_mk.equations._eqn_1] quotient_group.is_group_hom_quotient_group_mk.equations._eqn_1
def lift (φ : G → H) [is_group_hom φ] (HN : ∀x∈N, φ x = 1) (q : Q) : H :=
q.lift_on' φ $ assume a b (hab : a⁻¹ * b ∈ N),
(calc φ a = φ a * 1 : by simp
... = φ a * φ (a⁻¹ * b) : by rw HN (a⁻¹ * b) hab
... = φ (a * (a⁻¹ * b)) : by rw is_group_hom.mul φ a (a⁻¹ * b)
... = φ b : by simp)
attribute [to_additive quotient_add_group.lift._proof_1] lift._proof_1
attribute [to_additive quotient_add_group.lift] lift
attribute [to_additive quotient_add_group.lift.equations._eqn_1] lift.equations._eqn_1
@[simp] lemma lift_mk {φ : G → H} [is_group_hom φ] (HN : ∀x∈N, φ x = 1) (g : G) :
lift N φ HN (g : Q) = φ g := rfl
attribute [to_additive quotient_add_group.lift_mk] lift_mk
@[simp] lemma lift_mk' {φ : G → H} [is_group_hom φ] (HN : ∀x∈N, φ x = 1) (g : G) :
lift N φ HN (mk g : Q) = φ g := rfl
attribute [to_additive quotient_add_group.lift_mk'] lift_mk'
def map (M : set H) [normal_subgroup M] (f : G → H) [is_group_hom f] (h : N ⊆ f ⁻¹' M) :
quotient N → quotient M :=
begin
haveI : is_group_hom ((mk : H → quotient M) ∘ f) := is_group_hom.comp _ _,
refine quotient_group.lift N (mk ∘ f) _,
assume x hx,
refine quotient_group.eq.2 _,
rw [mul_one, is_subgroup.inv_mem_iff],
exact h hx,
end
attribute [to_additive quotient_add_group.map._proof_1] map._proof_1
attribute [to_additive quotient_add_group.map._proof_2] map._proof_2
attribute [to_additive quotient_add_group.map] map
variables (φ : G → H) [is_group_hom φ] (HN : ∀x∈N, φ x = 1)
instance is_group_hom_quotient_lift :
is_group_hom (lift N φ HN) :=
⟨λ q r, quotient.induction_on₂' q r $ λ a b,
show φ (a * b) = φ a * φ b, from is_group_hom.mul φ a b⟩
attribute [to_additive quotient_add_group.is_add_group_hom_quotient_lift] quotient_group.is_group_hom_quotient_lift
attribute [to_additive quotient_add_group.is_add_group_hom_quotient_lift.equations._eqn_1] quotient_group.is_group_hom_quotient_lift.equations._eqn_1
open function is_group_hom
@[to_additive quotient_add_group.injective_ker_lift]
lemma injective_ker_lift : injective (lift (ker φ) φ $ λ x h, (mem_ker φ).1 h) :=
assume a b, quotient.induction_on₂' a b $ assume a b (h : φ a = φ b), quotient.sound' $
show a⁻¹ * b ∈ ker φ, by rw [mem_ker φ,
is_group_hom.mul φ, ← h, is_group_hom.inv φ, inv_mul_self]
end quotient_group
|
d53a53dd6e2e7b3ce0aadbddbe4d09363645c83e | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/order/zorn.lean | 7d1e922a3b6670754b5c34ed3e17e93bb2855035 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 8,983 | 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 order.chain
/-!
# Zorn's lemmas
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file proves several formulations of Zorn's Lemma.
## Variants
The primary statement of Zorn's lemma is `exists_maximal_of_chains_bounded`. Then it is specialized
to particular relations:
* `(≤)` with `zorn_partial_order`
* `(⊆)` with `zorn_subset`
* `(⊇)` with `zorn_superset`
Lemma names carry modifiers:
* `₀`: Quantifies over a set, as opposed to over a type.
* `_nonempty`: Doesn't ask to prove that the empty chain is bounded and lets you give an element
that will be smaller than the maximal element found (the maximal element is no smaller than any
other element, but it can also be incomparable to some).
## How-to
This file comes across as confusing to those who haven't yet used it, so here is a detailed
walkthrough:
1. Know what relation on which type/set you're looking for. See Variants above. You can discharge
some conditions to Zorn's lemma directly using a `_nonempty` variant.
2. Write down the definition of your type/set, put a `suffices : ∃ m, ∀ a, m ≺ a → a ≺ m, { ... },`
(or whatever you actually need) followed by a `apply some_version_of_zorn`.
3. Fill in the details. This is where you start talking about chains.
A typical proof using Zorn could look like this
```lean
lemma zorny_lemma : zorny_statement :=
begin
let s : set α := {x | whatever x},
suffices : ∃ x ∈ s, ∀ y ∈ s, y ⊆ x → y = x, -- or with another operator
{ exact proof_post_zorn },
apply zorn_subset, -- or another variant
rintro c hcs hc,
obtain rfl | hcnemp := c.eq_empty_or_nonempty, -- you might need to disjunct on c empty or not
{ exact ⟨edge_case_construction,
proof_that_edge_case_construction_respects_whatever,
proof_that_edge_case_construction_contains_all_stuff_in_c⟩ },
exact ⟨construction,
proof_that_construction_respects_whatever,
proof_that_construction_contains_all_stuff_in_c⟩,
end
```
## Notes
Originally ported from Isabelle/HOL. The
[original file](https://isabelle.in.tum.de/dist/library/HOL/HOL/Zorn.html) was written by Jacques D.
Fleuriot, Tobias Nipkow, Christian Sternagel.
-/
open classical set
variables {α β : Type*} {r : α → α → Prop} {c : set α}
local infix ` ≺ `:50 := r
/-- **Zorn's lemma**
If every chain has an upper bound, then there exists a maximal element. -/
lemma exists_maximal_of_chains_bounded (h : ∀ c, is_chain r c → ∃ ub, ∀ a ∈ c, a ≺ ub)
(trans : ∀ {a b c}, a ≺ b → b ≺ c → a ≺ c) :
∃ m, ∀ a, m ≺ a → a ≺ m :=
have ∃ ub, ∀ a ∈ max_chain r, a ≺ ub,
from h _ $ max_chain_spec.left,
let ⟨ub, (hub : ∀ a ∈ max_chain r, a ≺ ub)⟩ := this in
⟨ub, λ a ha,
have is_chain r (insert a $ max_chain r),
from max_chain_spec.1.insert $ λ b hb _, or.inr $ trans (hub b hb) ha,
hub a $ by { rw max_chain_spec.right this (subset_insert _ _), exact mem_insert _ _ }⟩
/-- A variant of Zorn's lemma. If every nonempty chain of a nonempty type has an upper bound, then
there is a maximal element.
-/
theorem exists_maximal_of_nonempty_chains_bounded [nonempty α]
(h : ∀ c, is_chain r c → c.nonempty → ∃ ub, ∀ a ∈ c, a ≺ ub)
(trans : ∀ {a b c}, a ≺ b → b ≺ c → a ≺ c) :
∃ m, ∀ a, m ≺ a → a ≺ m :=
exists_maximal_of_chains_bounded
(λ c hc,
(eq_empty_or_nonempty c).elim
(λ h, ⟨classical.arbitrary α, λ x hx, (h ▸ hx : x ∈ (∅ : set α)).elim⟩)
(h c hc))
(λ a b c, trans)
section preorder
variables [preorder α]
theorem zorn_preorder (h : ∀ c : set α, is_chain (≤) c → bdd_above c) :
∃ m : α, ∀ a, m ≤ a → a ≤ m :=
exists_maximal_of_chains_bounded h (λ a b c, le_trans)
theorem zorn_nonempty_preorder [nonempty α]
(h : ∀ (c : set α), is_chain (≤) c → c.nonempty → bdd_above c) :
∃ (m : α), ∀ a, m ≤ a → a ≤ m :=
exists_maximal_of_nonempty_chains_bounded h (λ a b c, le_trans)
theorem zorn_preorder₀ (s : set α)
(ih : ∀ c ⊆ s, is_chain (≤) c → ∃ ub ∈ s, ∀ z ∈ c, z ≤ ub) :
∃ m ∈ s, ∀ z ∈ s, m ≤ z → z ≤ m :=
let ⟨⟨m, hms⟩, h⟩ := @zorn_preorder s _
(λ c hc,
let ⟨ub, hubs, hub⟩ := ih (subtype.val '' c) (λ _ ⟨⟨x, hx⟩, _, h⟩, h ▸ hx)
(by { rintro _ ⟨p, hpc, rfl⟩ _ ⟨q, hqc, rfl⟩ hpq;
refine hc hpc hqc (λ t, hpq (subtype.ext_iff.1 t)) })
in ⟨⟨ub, hubs⟩, λ ⟨y, hy⟩ hc, hub _ ⟨_, hc, rfl⟩⟩)
in ⟨m, hms, λ z hzs hmz, h ⟨z, hzs⟩ hmz⟩
theorem zorn_nonempty_preorder₀ (s : set α)
(ih : ∀ c ⊆ s, is_chain (≤) c → ∀ y ∈ c, ∃ ub ∈ s, ∀ z ∈ c, z ≤ ub) (x : α) (hxs : x ∈ s) :
∃ m ∈ s, x ≤ m ∧ ∀ z ∈ s, m ≤ z → z ≤ m :=
begin
rcases zorn_preorder₀ {y ∈ s | x ≤ y} (λ c hcs hc, _) with ⟨m, ⟨hms, hxm⟩, hm⟩,
{ exact ⟨m, hms, hxm, λ z hzs hmz, hm _ ⟨hzs, (hxm.trans hmz)⟩ hmz⟩ },
{ rcases c.eq_empty_or_nonempty with rfl|⟨y, hy⟩,
{ exact ⟨x, ⟨hxs, le_rfl⟩, λ z, false.elim⟩ },
{ rcases ih c (λ z hz, (hcs hz).1) hc y hy with ⟨z, hzs, hz⟩,
exact ⟨z, ⟨hzs, (hcs hy).2.trans $ hz _ hy⟩, hz⟩ } }
end
lemma zorn_nonempty_Ici₀ (a : α)
(ih : ∀ c ⊆ Ici a, is_chain (≤) c → ∀ y ∈ c, ∃ ub, a ≤ ub ∧ ∀ z ∈ c, z ≤ ub) (x : α)
(hax : a ≤ x) :
∃ m, x ≤ m ∧ ∀ z, m ≤ z → z ≤ m :=
let ⟨m, hma, hxm, hm⟩ := zorn_nonempty_preorder₀ (Ici a) (by simpa using ih) x hax in
⟨m, hxm, λ z hmz, hm _ (hax.trans $ hxm.trans hmz) hmz⟩
end preorder
section partial_order
variables [partial_order α]
lemma zorn_partial_order (h : ∀ c : set α, is_chain (≤) c → bdd_above c) :
∃ m : α, ∀ a, m ≤ a → a = m :=
let ⟨m, hm⟩ := zorn_preorder h in ⟨m, λ a ha, le_antisymm (hm a ha) ha⟩
theorem zorn_nonempty_partial_order [nonempty α]
(h : ∀ (c : set α), is_chain (≤) c → c.nonempty → bdd_above c) :
∃ (m : α), ∀ a, m ≤ a → a = m :=
let ⟨m, hm⟩ := zorn_nonempty_preorder h in ⟨m, λ a ha, le_antisymm (hm a ha) ha⟩
theorem zorn_partial_order₀ (s : set α)
(ih : ∀ c ⊆ s, is_chain (≤) c → ∃ ub ∈ s, ∀ z ∈ c, z ≤ ub) :
∃ m ∈ s, ∀ z ∈ s, m ≤ z → z = m :=
let ⟨m, hms, hm⟩ := zorn_preorder₀ s ih in ⟨m, hms, λ z hzs hmz, (hm z hzs hmz).antisymm hmz⟩
lemma zorn_nonempty_partial_order₀ (s : set α)
(ih : ∀ c ⊆ s, is_chain (≤) c → ∀ y ∈ c, ∃ ub ∈ s, ∀ z ∈ c, z ≤ ub) (x : α) (hxs : x ∈ s) :
∃ m ∈ s, x ≤ m ∧ ∀ z ∈ s, m ≤ z → z = m :=
let ⟨m, hms, hxm, hm⟩ := zorn_nonempty_preorder₀ s ih x hxs
in ⟨m, hms, hxm, λ z hzs hmz, (hm z hzs hmz).antisymm hmz⟩
end partial_order
lemma zorn_subset (S : set (set α)) (h : ∀ c ⊆ S, is_chain (⊆) c → ∃ ub ∈ S, ∀ s ∈ c, s ⊆ ub) :
∃ m ∈ S, ∀ a ∈ S, m ⊆ a → a = m :=
zorn_partial_order₀ S h
lemma zorn_subset_nonempty (S : set (set α))
(H : ∀ c ⊆ S, is_chain (⊆) c → c.nonempty → ∃ ub ∈ S, ∀ s ∈ c, s ⊆ ub) (x) (hx : x ∈ S) :
∃ m ∈ S, x ⊆ m ∧ ∀ a ∈ S, m ⊆ a → a = m :=
zorn_nonempty_partial_order₀ _ (λ c cS hc y yc, H _ cS hc ⟨y, yc⟩) _ hx
lemma zorn_superset (S : set (set α))
(h : ∀ c ⊆ S, is_chain (⊆) c → ∃ lb ∈ S, ∀ s ∈ c, lb ⊆ s) :
∃ m ∈ S, ∀ a ∈ S, a ⊆ m → a = m :=
@zorn_partial_order₀ (set α)ᵒᵈ _ S $ λ c cS hc, h c cS hc.symm
lemma zorn_superset_nonempty (S : set (set α))
(H : ∀ c ⊆ S, is_chain (⊆) c → c.nonempty → ∃ lb ∈ S, ∀ s ∈ c, lb ⊆ s) (x) (hx : x ∈ S) :
∃ m ∈ S, m ⊆ x ∧ ∀ a ∈ S, a ⊆ m → a = m :=
@zorn_nonempty_partial_order₀ (set α)ᵒᵈ _ S (λ c cS hc y yc, H _ cS hc.symm ⟨y, yc⟩) _ hx
/-- Every chain is contained in a maximal chain. This generalizes Hausdorff's maximality principle.
-/
lemma is_chain.exists_max_chain (hc : is_chain r c) : ∃ M, @is_max_chain _ r M ∧ c ⊆ M :=
begin
obtain ⟨M, ⟨_, hM₀⟩, hM₁, hM₂⟩ :=
zorn_subset_nonempty {s | c ⊆ s ∧ is_chain r s} _ c ⟨subset.rfl, hc⟩,
{ exact ⟨M, ⟨hM₀, λ d hd hMd, (hM₂ _ ⟨hM₁.trans hMd, hd⟩ hMd).symm⟩, hM₁⟩ },
rintros cs hcs₀ hcs₁ ⟨s, hs⟩,
refine ⟨⋃₀ cs, ⟨λ _ ha, set.mem_sUnion_of_mem ((hcs₀ hs).left ha) hs, _⟩,
λ _, set.subset_sUnion_of_mem⟩,
rintros y ⟨sy, hsy, hysy⟩ z ⟨sz, hsz, hzsz⟩ hyz,
obtain rfl | hsseq := eq_or_ne sy sz,
{ exact (hcs₀ hsy).right hysy hzsz hyz },
cases hcs₁ hsy hsz hsseq with h h,
{ exact (hcs₀ hsz).right (h hysy) hzsz hyz },
{ exact (hcs₀ hsy).right hysy (h hzsz) hyz }
end
|
2fee5960de2c94580d6c7f8ae55e3aab29895d37 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/probability/martingale/borel_cantelli.lean | fb9014347322b6a800471c97ac2480f61a136787 | [
"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 | 18,714 | lean | /-
Copyright (c) 2022 Kexing Ying. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kexing Ying
-/
import probability.martingale.convergence
import probability.martingale.optional_stopping
import probability.martingale.centering
/-!
# Generalized Borel-Cantelli lemma
This file proves Lévy's generalized Borel-Cantelli lemma which is a generalization of the
Borel-Cantelli lemmas. With this generalization, one can easily deduce the Borel-Cantelli lemmas
by choosing appropriate filtrations. This file also contains the one sided martingale bound which
is required to prove the generalized Borel-Cantelli.
## Main results
- `measure_theory.submartingale.bdd_above_iff_exists_tendsto`: the one sided martingale bound: given
a submartingale `f` with uniformly bounded differences, the set for which `f` converges is almost
everywhere equal to the set for which it is bounded.
- `measure_theory.ae_mem_limsup_at_top_iff`: Lévy's generalized Borel-Cantelli:
given a filtration `ℱ` and a sequence of sets `s` such that `s n ∈ ℱ n` for all `n`,
`limsup at_top s` is almost everywhere equal to the set for which `∑ ℙ[s (n + 1)∣ℱ n] = ∞`.
-/
open filter
open_locale nnreal ennreal measure_theory probability_theory big_operators topology
namespace measure_theory
variables {Ω : Type*} {m0 : measurable_space Ω} {μ : measure Ω}
{ℱ : filtration ℕ m0} {f : ℕ → Ω → ℝ} {ω : Ω}
/-!
### One sided martingale bound
-/
-- TODO: `least_ge` should be defined taking values in `with_top ℕ` once the `stopped_process`
-- refactor is complete
/-- `least_ge f r n` is the stopping time corresponding to the first time `f ≥ r`. -/
noncomputable
def least_ge (f : ℕ → Ω → ℝ) (r : ℝ) (n : ℕ) := hitting f (set.Ici r) 0 n
lemma adapted.is_stopping_time_least_ge (r : ℝ) (n : ℕ) (hf : adapted ℱ f) :
is_stopping_time ℱ (least_ge f r n) :=
hitting_is_stopping_time hf measurable_set_Ici
lemma least_ge_le {i : ℕ} {r : ℝ} (ω : Ω) : least_ge f r i ω ≤ i :=
hitting_le ω
-- The following four lemmas shows `least_ge` behaves like a stopped process. Ideally we should
-- define `least_ge` as a stopping time and take its stopped process. However, we can't do that
-- with our current definition since a stopping time takes only finite indicies. An upcomming
-- refactor should hopefully make it possible to have stopping times taking infinity as a value
lemma least_ge_mono {n m : ℕ} (hnm : n ≤ m) (r : ℝ) (ω : Ω) :
least_ge f r n ω ≤ least_ge f r m ω :=
hitting_mono hnm
lemma least_ge_eq_min (π : Ω → ℕ) (r : ℝ) (ω : Ω)
{n : ℕ} (hπn : ∀ ω, π ω ≤ n) :
least_ge f r (π ω) ω = min (π ω) (least_ge f r n ω) :=
begin
classical,
refine le_antisymm (le_min (least_ge_le _) (least_ge_mono (hπn ω) r ω)) _,
by_cases hle : π ω ≤ least_ge f r n ω,
{ rw [min_eq_left hle, least_ge],
by_cases h : ∃ j ∈ set.Icc 0 (π ω), f j ω ∈ set.Ici r,
{ refine hle.trans (eq.le _),
rw [least_ge, ← hitting_eq_hitting_of_exists (hπn ω) h] },
{ simp only [hitting, if_neg h] } },
{ rw [min_eq_right (not_le.1 hle).le, least_ge, least_ge,
← hitting_eq_hitting_of_exists (hπn ω) _],
rw [not_le, least_ge, hitting_lt_iff _ (hπn ω)] at hle,
exact let ⟨j, hj₁, hj₂⟩ := hle in ⟨j, ⟨hj₁.1, hj₁.2.le⟩, hj₂⟩ }
end
lemma stopped_value_stopped_value_least_ge (f : ℕ → Ω → ℝ) (π : Ω → ℕ) (r : ℝ)
{n : ℕ} (hπn : ∀ ω, π ω ≤ n) :
stopped_value (λ i, stopped_value f (least_ge f r i)) π
= stopped_value (stopped_process f (least_ge f r n)) π :=
by { ext1 ω, simp_rw [stopped_process, stopped_value], rw least_ge_eq_min _ _ _ hπn, }
lemma submartingale.stopped_value_least_ge [is_finite_measure μ]
(hf : submartingale f ℱ μ) (r : ℝ) :
submartingale (λ i, stopped_value f (least_ge f r i)) ℱ μ :=
begin
rw submartingale_iff_expected_stopped_value_mono,
{ intros σ π hσ hπ hσ_le_π hπ_bdd,
obtain ⟨n, hπ_le_n⟩ := hπ_bdd,
simp_rw stopped_value_stopped_value_least_ge f σ r (λ i, (hσ_le_π i).trans (hπ_le_n i)),
simp_rw stopped_value_stopped_value_least_ge f π r hπ_le_n,
refine hf.expected_stopped_value_mono _ _ _ (λ ω, (min_le_left _ _).trans (hπ_le_n ω)),
{ exact hσ.min (hf.adapted.is_stopping_time_least_ge _ _), },
{ exact hπ.min (hf.adapted.is_stopping_time_least_ge _ _), },
{ exact λ ω, min_le_min (hσ_le_π ω) le_rfl, }, },
{ exact λ i, strongly_measurable_stopped_value_of_le hf.adapted.prog_measurable_of_discrete
(hf.adapted.is_stopping_time_least_ge _ _) least_ge_le, },
{ exact λ i, integrable_stopped_value _ ((hf.adapted.is_stopping_time_least_ge _ _))
(hf.integrable) least_ge_le, },
end
variables {r : ℝ} {R : ℝ≥0}
lemma norm_stopped_value_least_ge_le (hr : 0 ≤ r) (hf0 : f 0 = 0)
(hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) (i : ℕ) :
∀ᵐ ω ∂μ, stopped_value f (least_ge f r i) ω ≤ r + R :=
begin
filter_upwards [hbdd] with ω hbddω,
change f (least_ge f r i ω) ω ≤ r + R,
by_cases heq : least_ge f r i ω = 0,
{ rw [heq, hf0, pi.zero_apply],
exact add_nonneg hr R.coe_nonneg },
{ obtain ⟨k, hk⟩ := nat.exists_eq_succ_of_ne_zero heq,
rw [hk, add_comm, ← sub_le_iff_le_add],
have := not_mem_of_lt_hitting (hk.symm ▸ k.lt_succ_self : k < least_ge f r i ω) (zero_le _),
simp only [set.mem_union, set.mem_Iic, set.mem_Ici, not_or_distrib, not_le] at this,
exact (sub_lt_sub_left this _).le.trans ((le_abs_self _).trans (hbddω _)) }
end
lemma submartingale.stopped_value_least_ge_snorm_le [is_finite_measure μ]
(hf : submartingale f ℱ μ) (hr : 0 ≤ r) (hf0 : f 0 = 0)
(hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) (i : ℕ) :
snorm (stopped_value f (least_ge f r i)) 1 μ ≤ 2 * μ set.univ * ennreal.of_real (r + R) :=
begin
refine snorm_one_le_of_le' ((hf.stopped_value_least_ge r).integrable _) _
(norm_stopped_value_least_ge_le hr hf0 hbdd i),
rw ← integral_univ,
refine le_trans _ ((hf.stopped_value_least_ge r).set_integral_le (zero_le _)
measurable_set.univ),
simp_rw [stopped_value, least_ge, hitting_of_le le_rfl, hf0, integral_zero']
end
lemma submartingale.stopped_value_least_ge_snorm_le' [is_finite_measure μ]
(hf : submartingale f ℱ μ) (hr : 0 ≤ r) (hf0 : f 0 = 0)
(hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) (i : ℕ) :
snorm (stopped_value f (least_ge f r i)) 1 μ ≤
ennreal.to_nnreal (2 * μ set.univ * ennreal.of_real (r + R)) :=
begin
refine (hf.stopped_value_least_ge_snorm_le hr hf0 hbdd i).trans _,
simp [ennreal.coe_to_nnreal (measure_ne_top μ _), ennreal.coe_to_nnreal],
end
/-- This lemma is superceded by `submartingale.bdd_above_iff_exists_tendsto`. -/
lemma submartingale.exists_tendsto_of_abs_bdd_above_aux [is_finite_measure μ]
(hf : submartingale f ℱ μ) (hf0 : f 0 = 0)
(hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) :
∀ᵐ ω ∂μ, bdd_above (set.range $ λ n, f n ω) → ∃ c, tendsto (λ n, f n ω) at_top (𝓝 c) :=
begin
have ht : ∀ᵐ ω ∂μ, ∀ i : ℕ, ∃ c, tendsto (λ n, stopped_value f (least_ge f i n) ω) at_top (𝓝 c),
{ rw ae_all_iff,
exact λ i, submartingale.exists_ae_tendsto_of_bdd (hf.stopped_value_least_ge i)
(hf.stopped_value_least_ge_snorm_le' i.cast_nonneg hf0 hbdd) },
filter_upwards [ht] with ω hω hωb,
rw bdd_above at hωb,
obtain ⟨i, hi⟩ := exists_nat_gt hωb.some,
have hib : ∀ n, f n ω < i,
{ intro n,
exact lt_of_le_of_lt ((mem_upper_bounds.1 hωb.some_mem) _ ⟨n, rfl⟩) hi },
have heq : ∀ n, stopped_value f (least_ge f i n) ω = f n ω,
{ intro n,
rw [least_ge, hitting, stopped_value],
simp only,
rw if_neg,
simp only [set.mem_Icc, set.mem_union, set.mem_Ici],
push_neg,
exact λ j _, hib j },
simp only [← heq, hω i],
end
lemma submartingale.bdd_above_iff_exists_tendsto_aux [is_finite_measure μ]
(hf : submartingale f ℱ μ) (hf0 : f 0 = 0)
(hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) :
∀ᵐ ω ∂μ, bdd_above (set.range $ λ n, f n ω) ↔ ∃ c, tendsto (λ n, f n ω) at_top (𝓝 c) :=
by filter_upwards [hf.exists_tendsto_of_abs_bdd_above_aux hf0 hbdd] with ω hω using
⟨hω, λ ⟨c, hc⟩, hc.bdd_above_range⟩
/-- One sided martingale bound: If `f` is a submartingale which has uniformly bounded differences,
then for almost every `ω`, `f n ω` is bounded above (in `n`) if and only if it converges. -/
lemma submartingale.bdd_above_iff_exists_tendsto [is_finite_measure μ]
(hf : submartingale f ℱ μ) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) :
∀ᵐ ω ∂μ, bdd_above (set.range $ λ n, f n ω) ↔ ∃ c, tendsto (λ n, f n ω) at_top (𝓝 c) :=
begin
set g : ℕ → Ω → ℝ := λ n ω, f n ω - f 0 ω with hgdef,
have hg : submartingale g ℱ μ :=
hf.sub_martingale (martingale_const_fun _ _ (hf.adapted 0) (hf.integrable 0)),
have hg0 : g 0 = 0,
{ ext ω,
simp only [hgdef, sub_self, pi.zero_apply] },
have hgbdd : ∀ᵐ ω ∂μ, ∀ (i : ℕ), |g (i + 1) ω - g i ω| ≤ ↑R,
{ simpa only [sub_sub_sub_cancel_right] },
filter_upwards [hg.bdd_above_iff_exists_tendsto_aux hg0 hgbdd] with ω hω,
convert hω using 1; rw eq_iff_iff,
{ simp only [hgdef],
refine ⟨λ h, _, λ h, _⟩;
obtain ⟨b, hb⟩ := h;
refine ⟨b + |f 0 ω|, λ y hy, _⟩;
obtain ⟨n, rfl⟩ := hy,
{ simp_rw [sub_eq_add_neg],
exact add_le_add (hb ⟨n, rfl⟩) (neg_le_abs_self _) },
{ exact sub_le_iff_le_add.1 (le_trans (sub_le_sub_left (le_abs_self _) _) (hb ⟨n, rfl⟩)) } },
{ simp only [hgdef],
refine ⟨λ h, _, λ h, _⟩;
obtain ⟨c, hc⟩ := h,
{ exact ⟨c - f 0 ω, hc.sub_const _⟩ },
{ refine ⟨c + f 0 ω, _⟩,
have := hc.add_const (f 0 ω),
simpa only [sub_add_cancel] } }
end
/-!
### Lévy's generalization of the Borel-Cantelli lemma
Lévy's generalization of the Borel-Cantelli lemma states that: given a natural number indexed
filtration $(\mathcal{F}_n)$, and a sequence of sets $(s_n)$ such that for all
$n$, $s_n \in \mathcal{F}_n$, $limsup_n s_n$ is almost everywhere equal to the set for which
$\sum_n \mathbb{P}[s_n \mid \mathcal{F}_n] = \infty$.
The proof strategy follows by constructing a martingale satisfying the one sided martingale bound.
In particular, we define
$$
f_n := \sum_{k < n} \mathbf{1}_{s_{n + 1}} - \mathbb{P}[s_{n + 1} \mid \mathcal{F}_n].
$$
Then, as a martingale is both a sub and a super-martingale, the set for which it is unbounded from
above must agree with the set for which it is unbounded from below almost everywhere. Thus, it
can only converge to $\pm \infty$ with probability 0. Thus, by considering
$$
\limsup_n s_n = \{\sum_n \mathbf{1}_{s_n} = \infty\}
$$
almost everywhere, the result follows.
-/
lemma martingale.bdd_above_range_iff_bdd_below_range [is_finite_measure μ]
(hf : martingale f ℱ μ) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) :
∀ᵐ ω ∂μ, bdd_above (set.range (λ n, f n ω)) ↔ bdd_below (set.range (λ n, f n ω)) :=
begin
have hbdd' : ∀ᵐ ω ∂μ, ∀ i, |(-f) (i + 1) ω - (-f) i ω| ≤ R,
{ filter_upwards [hbdd] with ω hω i,
erw [← abs_neg, neg_sub, sub_neg_eq_add, neg_add_eq_sub],
exact hω i },
have hup := hf.submartingale.bdd_above_iff_exists_tendsto hbdd,
have hdown := hf.neg.submartingale.bdd_above_iff_exists_tendsto hbdd',
filter_upwards [hup, hdown] with ω hω₁ hω₂,
have : (∃ c, tendsto (λ n, f n ω) at_top (𝓝 c)) ↔ ∃ c, tendsto (λ n, (-f) n ω) at_top (𝓝 c),
{ split; rintro ⟨c, hc⟩,
{ exact ⟨-c, hc.neg⟩ },
{ refine ⟨-c, _⟩,
convert hc.neg,
simp only [neg_neg, pi.neg_apply] } },
rw [hω₁, this, ← hω₂],
split; rintro ⟨c, hc⟩; refine ⟨-c, λ ω hω, _⟩,
{ rw mem_upper_bounds at hc,
refine neg_le.2 (hc _ _),
simpa only [pi.neg_apply, set.mem_range, neg_inj] },
{ rw mem_lower_bounds at hc,
simp_rw [set.mem_range, pi.neg_apply, neg_eq_iff_eq_neg] at hω,
refine le_neg.1 (hc _ _),
simpa only [set.mem_range] }
end
lemma martingale.ae_not_tendsto_at_top_at_top [is_finite_measure μ]
(hf : martingale f ℱ μ) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) :
∀ᵐ ω ∂μ, ¬ tendsto (λ n, f n ω) at_top at_top :=
by filter_upwards [hf.bdd_above_range_iff_bdd_below_range hbdd] with ω hω htop using
unbounded_of_tendsto_at_top htop (hω.2 $ bdd_below_range_of_tendsto_at_top_at_top htop)
lemma martingale.ae_not_tendsto_at_top_at_bot [is_finite_measure μ]
(hf : martingale f ℱ μ) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) :
∀ᵐ ω ∂μ, ¬ tendsto (λ n, f n ω) at_top at_bot :=
by filter_upwards [hf.bdd_above_range_iff_bdd_below_range hbdd] with ω hω htop using
unbounded_of_tendsto_at_bot htop (hω.1 $ bdd_above_range_of_tendsto_at_top_at_bot htop)
namespace borel_cantelli
/-- Auxiliary definition required to prove Lévy's generalization of the Borel-Cantelli lemmas for
which we will take the martingale part. -/
noncomputable
def process (s : ℕ → set Ω) (n : ℕ) : Ω → ℝ :=
∑ k in finset.range n, (s (k + 1)).indicator 1
variables {s : ℕ → set Ω}
lemma process_zero : process s 0 = 0 :=
by rw [process, finset.range_zero, finset.sum_empty]
lemma adapted_process (hs : ∀ n, measurable_set[ℱ n] (s n)) :
adapted ℱ (process s) :=
λ n, finset.strongly_measurable_sum' _ $ λ k hk, strongly_measurable_one.indicator $
ℱ.mono (finset.mem_range.1 hk) _ $ hs _
lemma martingale_part_process_ae_eq (ℱ : filtration ℕ m0) (μ : measure Ω) (s : ℕ → set Ω) (n : ℕ) :
martingale_part (process s) ℱ μ n =
∑ k in finset.range n, ((s (k + 1)).indicator 1 - μ[(s (k + 1)).indicator 1 | ℱ k]) :=
begin
simp only [martingale_part_eq_sum, process_zero, zero_add],
refine finset.sum_congr rfl (λ k hk, _),
simp only [process, finset.sum_range_succ_sub_sum],
end
lemma predictable_part_process_ae_eq (ℱ : filtration ℕ m0) (μ : measure Ω) (s : ℕ → set Ω) (n : ℕ) :
predictable_part (process s) ℱ μ n =
∑ k in finset.range n, μ[(s (k + 1)).indicator (1 : Ω → ℝ) | ℱ k] :=
begin
have := martingale_part_process_ae_eq ℱ μ s n,
simp_rw [martingale_part, process, finset.sum_sub_distrib] at this,
exact sub_right_injective this,
end
lemma process_difference_le (s : ℕ → set Ω) (ω : Ω) (n : ℕ) :
|process s (n + 1) ω - process s n ω| ≤ (1 : ℝ≥0) :=
begin
rw [nonneg.coe_one, process, process, finset.sum_apply, finset.sum_apply,
finset.sum_range_succ_sub_sum, ← real.norm_eq_abs, norm_indicator_eq_indicator_norm],
refine set.indicator_le' (λ _ _, _) (λ _ _, zero_le_one) _,
rw [pi.one_apply, norm_one]
end
lemma integrable_process (μ : measure Ω) [is_finite_measure μ]
(hs : ∀ n, measurable_set[ℱ n] (s n)) (n : ℕ) :
integrable (process s n) μ :=
integrable_finset_sum' _ $ λ k hk,
integrable_on.integrable_indicator (integrable_const 1) $ ℱ.le _ _ $ hs _
end borel_cantelli
open borel_cantelli
/-- An a.e. monotone adapted process `f` with uniformly bounded differences converges to `+∞` if
and only if its predictable part also converges to `+∞`. -/
lemma tendsto_sum_indicator_at_top_iff [is_finite_measure μ]
(hfmono : ∀ᵐ ω ∂μ, ∀ n, f n ω ≤ f (n + 1) ω)
(hf : adapted ℱ f) (hint : ∀ n, integrable (f n) μ)
(hbdd : ∀ᵐ ω ∂μ, ∀ n, |f (n + 1) ω - f n ω| ≤ R) :
∀ᵐ ω ∂μ, tendsto (λ n, f n ω) at_top at_top ↔
tendsto (λ n, predictable_part f ℱ μ n ω) at_top at_top :=
begin
have h₁ := (martingale_martingale_part hf hint).ae_not_tendsto_at_top_at_top
(martingale_part_bdd_difference ℱ hbdd),
have h₂ := (martingale_martingale_part hf hint).ae_not_tendsto_at_top_at_bot
(martingale_part_bdd_difference ℱ hbdd),
have h₃ : ∀ᵐ ω ∂μ, ∀ n, 0 ≤ μ[f (n + 1) - f n | ℱ n] ω,
{ refine ae_all_iff.2 (λ n, condexp_nonneg _),
filter_upwards [ae_all_iff.1 hfmono n] with ω hω using sub_nonneg.2 hω },
filter_upwards [h₁, h₂, h₃, hfmono] with ω hω₁ hω₂ hω₃ hω₄,
split; intro ht,
{ refine tendsto_at_top_at_top_of_monotone' _ _,
{ intros n m hnm,
simp only [predictable_part, finset.sum_apply],
refine finset.sum_mono_set_of_nonneg hω₃ (finset.range_mono hnm) },
rintro ⟨b, hbdd⟩,
rw ← tendsto_neg_at_bot_iff at ht,
simp only [martingale_part, sub_eq_add_neg] at hω₁,
exact hω₁ (tendsto_at_top_add_right_of_le _ (-b)
(tendsto_neg_at_bot_iff.1 ht) $ λ n, neg_le_neg (hbdd ⟨n, rfl⟩)) },
{ refine tendsto_at_top_at_top_of_monotone' (monotone_nat_of_le_succ hω₄) _,
rintro ⟨b, hbdd⟩,
exact hω₂ (tendsto_at_bot_add_left_of_ge _ b (λ n, hbdd ⟨n, rfl⟩) $
tendsto_neg_at_bot_iff.2 ht) },
end
open borel_cantelli
lemma tendsto_sum_indicator_at_top_iff' [is_finite_measure μ]
{s : ℕ → set Ω} (hs : ∀ n, measurable_set[ℱ n] (s n)) :
∀ᵐ ω ∂μ,
tendsto (λ n, ∑ k in finset.range n, (s (k + 1)).indicator (1 : Ω → ℝ) ω) at_top at_top ↔
tendsto (λ n, ∑ k in finset.range n, μ[(s (k + 1)).indicator (1 : Ω → ℝ) | ℱ k] ω)
at_top at_top :=
begin
have := tendsto_sum_indicator_at_top_iff (eventually_of_forall $ λ ω n, _) (adapted_process hs)
(integrable_process μ hs) (eventually_of_forall $ process_difference_le s),
swap,
{ rw [process, process, ← sub_nonneg, finset.sum_apply, finset.sum_apply,
finset.sum_range_succ_sub_sum],
exact set.indicator_nonneg (λ _ _, zero_le_one) _ },
simp_rw [process, predictable_part_process_ae_eq] at this,
simpa using this,
end
/-- **Lévy's generalization of the Borel-Cantelli lemma**: given a sequence of sets `s` and a
filtration `ℱ` such that for all `n`, `s n` is `ℱ n`-measurable, `at_top.limsup s` is almost
everywhere equal to the set for which `∑ k, ℙ(s (k + 1) | ℱ k) = ∞`. -/
theorem ae_mem_limsup_at_top_iff (μ : measure Ω) [is_finite_measure μ]
{s : ℕ → set Ω} (hs : ∀ n, measurable_set[ℱ n] (s n)) :
∀ᵐ ω ∂μ, ω ∈ limsup s at_top ↔
tendsto (λ n, ∑ k in finset.range n, μ[(s (k + 1)).indicator (1 : Ω → ℝ) | ℱ k] ω)
at_top at_top :=
(limsup_eq_tendsto_sum_indicator_at_top ℝ s).symm ▸ tendsto_sum_indicator_at_top_iff' hs
end measure_theory
|
c3a4dc92f56ef370618d0d67917ea1795197f69d | 94e33a31faa76775069b071adea97e86e218a8ee | /src/algebra/module/ulift.lean | ecec2c73c349729b7701a72ed391577bfa96d8f4 | [
"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 | 4,338 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import algebra.ring.ulift
import algebra.module.equiv
/-!
# `ulift` instances for module and multiplicative actions
This file defines instances for module, mul_action and related structures on `ulift` types.
(Recall `ulift α` is just a "copy" of a type `α` in a higher universe.)
We also provide `ulift.module_equiv : ulift M ≃ₗ[R] M`.
-/
namespace ulift
universes u v w
variable {R : Type u}
variable {M : Type v}
variable {N : Type w}
instance has_smul_left [has_smul R M] :
has_smul (ulift R) M :=
⟨λ s x, s.down • x⟩
@[simp] lemma smul_down [has_smul R M] (s : ulift R) (x : M) : (s • x) = s.down • x := rfl
@[simp]
lemma smul_down' [has_smul R M] (s : R) (x : ulift M) :
(s • x).down = s • x.down :=
rfl
instance is_scalar_tower [has_smul R M] [has_smul M N] [has_smul R N]
[is_scalar_tower R M N] : is_scalar_tower (ulift R) M N :=
⟨λ x y z, show (x.down • y) • z = x.down • y • z, from smul_assoc _ _ _⟩
instance is_scalar_tower' [has_smul R M] [has_smul M N] [has_smul R N]
[is_scalar_tower R M N] : is_scalar_tower R (ulift M) N :=
⟨λ x y z, show (x • y.down) • z = x • y.down • z, from smul_assoc _ _ _⟩
instance is_scalar_tower'' [has_smul R M] [has_smul M N] [has_smul R N]
[is_scalar_tower R M N] : is_scalar_tower R M (ulift N) :=
⟨λ x y z, show up ((x • y) • z.down) = ⟨x • y • z.down⟩, by rw smul_assoc⟩
instance [has_smul R M] [has_smul Rᵐᵒᵖ M] [is_central_scalar R M] :
is_central_scalar R (ulift M) :=
⟨λ r m, congr_arg up $ op_smul_eq_smul r m.down⟩
instance mul_action [monoid R] [mul_action R M] : mul_action (ulift R) M :=
{ smul := (•),
mul_smul := λ _ _, mul_smul _ _,
one_smul := one_smul _ }
instance mul_action' [monoid R] [mul_action R M] :
mul_action R (ulift M) :=
{ smul := (•),
mul_smul := λ r s f, by { cases f, ext, simp [mul_smul], },
one_smul := λ f, by { ext, simp [one_smul], } }
instance distrib_mul_action [monoid R] [add_monoid M] [distrib_mul_action R M] :
distrib_mul_action (ulift R) M :=
{ smul_zero := λ _, smul_zero _,
smul_add := λ _, smul_add _ }
instance distrib_mul_action' [monoid R] [add_monoid M] [distrib_mul_action R M] :
distrib_mul_action R (ulift M) :=
{ smul_zero := λ c, by { ext, simp [smul_zero], },
smul_add := λ c f g, by { ext, simp [smul_add], },
..ulift.mul_action' }
instance mul_distrib_mul_action [monoid R] [monoid M] [mul_distrib_mul_action R M] :
mul_distrib_mul_action (ulift R) M :=
{ smul_one := λ _, smul_one _,
smul_mul := λ _, smul_mul' _ }
instance mul_distrib_mul_action' [monoid R] [monoid M] [mul_distrib_mul_action R M] :
mul_distrib_mul_action R (ulift M) :=
{ smul_one := λ _, by { ext, simp [smul_one], },
smul_mul := λ c f g, by { ext, simp [smul_mul'], },
..ulift.mul_action' }
instance smul_with_zero [has_zero R] [has_zero M] [smul_with_zero R M] :
smul_with_zero (ulift R) M :=
{ smul_zero := λ _, smul_zero' _ _,
zero_smul := zero_smul _,
..ulift.has_smul_left }
instance smul_with_zero' [has_zero R] [has_zero M] [smul_with_zero R M] :
smul_with_zero R (ulift M) :=
{ smul_zero := λ _, ulift.ext _ _ $ smul_zero' _ _,
zero_smul := λ _, ulift.ext _ _ $ zero_smul _ _ }
instance mul_action_with_zero [monoid_with_zero R] [has_zero M] [mul_action_with_zero R M] :
mul_action_with_zero (ulift R) M :=
{ ..ulift.smul_with_zero }
instance mul_action_with_zero' [monoid_with_zero R] [has_zero M] [mul_action_with_zero R M] :
mul_action_with_zero R (ulift M) :=
{ ..ulift.smul_with_zero' }
instance module [semiring R] [add_comm_monoid M] [module R M] : module (ulift R) M :=
{ add_smul := λ _ _, add_smul _ _,
..ulift.smul_with_zero }
instance module' [semiring R] [add_comm_monoid M] [module R M] : module R (ulift M) :=
{ add_smul := λ _ _ _, ulift.ext _ _ $ add_smul _ _ _,
..ulift.smul_with_zero' }
/--
The `R`-linear equivalence between `ulift M` and `M`.
-/
def module_equiv [semiring R] [add_comm_monoid M] [module R M] : ulift M ≃ₗ[R] M :=
{ to_fun := ulift.down,
inv_fun := ulift.up,
map_smul' := λ r x, rfl,
map_add' := λ x y, rfl,
left_inv := by tidy,
right_inv := by tidy, }
end ulift
|
54ce6dc50facee5dc13a4b1eff7240046f7f5812 | e030b0259b777fedcdf73dd966f3f1556d392178 | /library/init/data/list/basic.lean | 5fdb26c9293cd73da63512100dd19c4e69879023 | [
"Apache-2.0"
] | permissive | fgdorais/lean | 17b46a095b70b21fa0790ce74876658dc5faca06 | c3b7c54d7cca7aaa25328f0a5660b6b75fe26055 | refs/heads/master | 1,611,523,590,686 | 1,484,412,902,000 | 1,484,412,902,000 | 38,489,734 | 0 | 0 | null | 1,435,923,380,000 | 1,435,923,379,000 | null | UTF-8 | Lean | false | false | 4,525 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import init.logic init.data.nat.basic
open decidable list
notation h :: t := cons h t
notation `[` l:(foldr `, ` (h t, cons h t) nil `]`) := l
universe variables u v w
instance (α : Type u) : inhabited (list α) :=
⟨list.nil⟩
variables {α : Type u} {β : Type v} {γ : Type w}
namespace list
protected def append : list α → list α → list α
| [] l := l
| (h :: s) t := h :: (append s t)
instance : has_append (list α) :=
⟨list.append⟩
protected def mem : α → list α → Prop
| a [] := false
| a (b :: l) := a = b ∨ mem a l
instance : has_mem α list :=
⟨list.mem⟩
instance decidable_mem [decidable_eq α] (a : α) : ∀ (l : list α), decidable (a ∈ l)
| [] := is_false not_false
| (b::l) :=
if h₁ : a = b then is_true (or.inl h₁)
else match decidable_mem l with
| is_true h₂ := is_true (or.inr h₂)
| is_false h₂ := is_false (not_or h₁ h₂)
end
def concat : list α → α → list α
| [] a := [a]
| (b::l) a := b :: concat l a
instance : has_emptyc (list α) :=
⟨list.nil⟩
protected def insert [decidable_eq α] (a : α) (l : list α) : list α :=
if a ∈ l then l else concat l a
instance [decidable_eq α] : has_insert α list :=
⟨list.insert⟩
protected def union [decidable_eq α] : list α → list α → list α
| l₁ [] := l₁
| l₁ (a::l₂) := union (insert a l₁) l₂
instance [decidable_eq α] : has_union (list α) :=
⟨list.union⟩
protected def inter [decidable_eq α] : list α → list α → list α
| [] l₂ := []
| (a::l₁) l₂ := if a ∈ l₂ then a :: inter l₁ l₂ else inter l₁ l₂
instance [decidable_eq α] : has_inter (list α) :=
⟨list.inter⟩
def length : list α → nat
| [] := 0
| (a :: l) := length l + 1
def empty : list α → bool
| [] := tt
| (_ :: _) := ff
open option nat
def nth : list α → nat → option α
| [] n := none
| (a :: l) 0 := some a
| (a :: l) (n+1) := nth l n
def update_nth : list α → ℕ → α → list α
| (x::xs) 0 a := a :: xs
| (x::xs) (i+1) a := x :: update_nth xs i a
| [] _ _ := []
def remove_nth : list α → ℕ → list α
| [] _ := []
| (x::xs) 0 := xs
| (x::xs) (i+1) := x :: remove_nth xs i
def head [inhabited α] : list α → α
| [] := default α
| (a :: l) := a
def tail : list α → list α
| [] := []
| (a :: l) := l
def reverse_core : list α → list α → list α
| [] r := r
| (a::l) r := reverse_core l (a::r)
def reverse : list α → list α :=
λ l, reverse_core l []
def map (f : α → β) : list α → list β
| [] := []
| (a :: l) := f a :: map l
def for : list α → (α → β) → list β :=
flip map
def join : list (list α) → list α
| [] := []
| (l :: ls) := append l (join ls)
def filter (p : α → Prop) [decidable_pred p] : list α → list α
| [] := []
| (a::l) := if p a then a :: filter l else filter l
def dropn : ℕ → list α → list α
| 0 a := a
| (succ n) [] := []
| (succ n) (x::r) := dropn n r
def taken : ℕ → list α → list α
| 0 a := []
| (succ n) [] := []
| (succ n) (x :: r) := x :: taken n r
definition foldl (f : α → β → α) : α → list β → α
| a [] := a
| a (b :: l) := foldl (f a b) l
definition foldr (f : α → β → β) : β → list α → β
| b [] := b
| b (a :: l) := f a (foldr b l)
definition any (l : list α) (p : α → bool) : bool :=
foldr (λ a r, p a || r) ff l
definition all (l : list α) (p : α → bool) : bool :=
foldr (λ a r, p a && r) tt l
def bor (l : list bool) : bool := any l id
def band (l : list bool) : bool := all l id
def zip_with (f : α → β → γ) : list α → list β → list γ
| (x::xs) (y::ys) := f x y :: zip_with xs ys
| _ _ := []
def zip : list α → list β → list (prod α β) :=
zip_with prod.mk
def repeat (a : α) : ℕ → list α
| 0 := []
| (succ n) := a :: repeat n
def range_core : ℕ → list ℕ → list ℕ
| 0 l := l
| (succ n) l := range_core n (n :: l)
def range (n : ℕ) : list ℕ :=
range_core n []
def iota_core : ℕ → list ℕ → list ℕ
| 0 l := reverse l
| (succ n) l := iota_core n (succ n :: l)
def iota : ℕ → list ℕ :=
λ n, iota_core n []
def sum [has_add α] [has_zero α] : list α → α :=
foldl add zero
end list
|
0877deddba092a91d59b806cfe0e2c47ba6a4a86 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/data/list/range.lean | 6a6faa4f2df14489b1c99a3627994b0766a03a80 | [
"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 | 8,262 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Kenny Lau, Scott Morrison
-/
import data.list.chain
import data.list.nodup
import data.list.of_fn
open nat
namespace list
/- iota and range(') -/
universe u
variables {α : Type u}
@[simp] theorem length_range' : ∀ (s n : ℕ), length (range' s n) = n
| s 0 := rfl
| s (n+1) := congr_arg succ (length_range' _ _)
@[simp] theorem mem_range' {m : ℕ} : ∀ {s n : ℕ}, m ∈ range' s n ↔ s ≤ m ∧ m < s + n
| s 0 := (false_iff _).2 $ λ ⟨H1, H2⟩, not_le_of_lt H2 H1
| s (succ n) :=
have m = s → m < s + n + 1,
from λ e, e ▸ lt_succ_of_le (le_add_right _ _),
have l : m = s ∨ s + 1 ≤ m ↔ s ≤ m,
by simpa only [eq_comm] using (@le_iff_eq_or_lt _ _ s m).symm,
(mem_cons_iff _ _ _).trans $ by simp only [mem_range',
or_and_distrib_left, or_iff_right_of_imp this, l, add_right_comm]; refl
theorem map_add_range' (a) : ∀ s n : ℕ, map ((+) a) (range' s n) = range' (a + s) n
| s 0 := rfl
| s (n+1) := congr_arg (cons _) (map_add_range' (s+1) n)
theorem map_sub_range' (a) : ∀ (s n : ℕ) (h : a ≤ s), map (λ x, x - a) (range' s n) = range' (s - a) n
| s 0 _ := rfl
| s (n+1) h :=
begin
convert congr_arg (cons (s-a)) (map_sub_range' (s+1) n (nat.le_succ_of_le h)),
rw nat.succ_sub h,
refl,
end
theorem chain_succ_range' : ∀ s n : ℕ, chain (λ a b, b = succ a) s (range' (s+1) n)
| s 0 := chain.nil
| s (n+1) := (chain_succ_range' (s+1) n).cons rfl
theorem chain_lt_range' (s n : ℕ) : chain (<) s (range' (s+1) n) :=
(chain_succ_range' s n).imp (λ a b e, e.symm ▸ lt_succ_self _)
theorem pairwise_lt_range' : ∀ s n : ℕ, pairwise (<) (range' s n)
| s 0 := pairwise.nil
| s (n+1) := (chain_iff_pairwise (by exact λ a b c, lt_trans)).1 (chain_lt_range' s n)
theorem nodup_range' (s n : ℕ) : nodup (range' s n) :=
(pairwise_lt_range' s n).imp (λ a b, ne_of_lt)
@[simp] theorem range'_append : ∀ s m n : ℕ, range' s m ++ range' (s+m) n = range' s (n+m)
| s 0 n := rfl
| s (m+1) n := show s :: (range' (s+1) m ++ range' (s+m+1) n) = s :: range' (s+1) (n+m),
by rw [add_right_comm, range'_append]
theorem range'_sublist_right {s m n : ℕ} : range' s m <+ range' s n ↔ m ≤ n :=
⟨λ h, by simpa only [length_range'] using length_le_of_sublist h,
λ h, by rw [← nat.sub_add_cancel h, ← range'_append]; apply sublist_append_left⟩
theorem range'_subset_right {s m n : ℕ} : range' s m ⊆ range' s n ↔ m ≤ n :=
⟨λ h, le_of_not_lt $ λ hn, lt_irrefl (s+n) $
(mem_range'.1 $ h $ mem_range'.2 ⟨le_add_right _ _, nat.add_lt_add_left hn s⟩).2,
λ h, subset_of_sublist (range'_sublist_right.2 h)⟩
theorem nth_range' : ∀ s {m n : ℕ}, m < n → nth (range' s n) m = some (s + m)
| s 0 (n+1) _ := rfl
| s (m+1) (n+1) h := (nth_range' (s+1) (lt_of_add_lt_add_right h)).trans $ by rw add_right_comm; refl
theorem range'_concat (s n : ℕ) : range' s (n + 1) = range' s n ++ [s+n] :=
by rw add_comm n 1; exact (range'_append s n 1).symm
theorem range_core_range' : ∀ s n : ℕ, range_core s (range' s n) = range' 0 (n + s)
| 0 n := rfl
| (s+1) n := by rw [show n+(s+1) = n+1+s, from add_right_comm n s 1]; exact range_core_range' s (n+1)
theorem range_eq_range' (n : ℕ) : range n = range' 0 n :=
(range_core_range' n 0).trans $ by rw zero_add
theorem range_succ_eq_map (n : ℕ) : range (n + 1) = 0 :: map succ (range n) :=
by rw [range_eq_range', range_eq_range', range',
add_comm, ← map_add_range'];
congr; exact funext one_add
theorem range'_eq_map_range (s n : ℕ) : range' s n = map ((+) s) (range n) :=
by rw [range_eq_range', map_add_range']; refl
@[simp] theorem length_range (n : ℕ) : length (range n) = n :=
by simp only [range_eq_range', length_range']
theorem pairwise_lt_range (n : ℕ) : pairwise (<) (range n) :=
by simp only [range_eq_range', pairwise_lt_range']
theorem nodup_range (n : ℕ) : nodup (range n) :=
by simp only [range_eq_range', nodup_range']
theorem range_sublist {m n : ℕ} : range m <+ range n ↔ m ≤ n :=
by simp only [range_eq_range', range'_sublist_right]
theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n :=
by simp only [range_eq_range', range'_subset_right]
@[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n :=
by simp only [range_eq_range', mem_range', nat.zero_le, true_and, zero_add]
@[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n :=
mt mem_range.1 $ lt_irrefl _
theorem nth_range {m n : ℕ} (h : m < n) : nth (range n) m = some m :=
by simp only [range_eq_range', nth_range' _ h, zero_add]
theorem range_concat (n : ℕ) : range (succ n) = range n ++ [n] :=
by simp only [range_eq_range', range'_concat, zero_add]
theorem iota_eq_reverse_range' : ∀ n : ℕ, iota n = reverse (range' 1 n)
| 0 := rfl
| (n+1) := by simp only [iota, range'_concat, iota_eq_reverse_range' n, reverse_append, add_comm]; refl
@[simp] theorem length_iota (n : ℕ) : length (iota n) = n :=
by simp only [iota_eq_reverse_range', length_reverse, length_range']
theorem pairwise_gt_iota (n : ℕ) : pairwise (>) (iota n) :=
by simp only [iota_eq_reverse_range', pairwise_reverse, pairwise_lt_range']
theorem nodup_iota (n : ℕ) : nodup (iota n) :=
by simp only [iota_eq_reverse_range', nodup_reverse, nodup_range']
theorem mem_iota {m n : ℕ} : m ∈ iota n ↔ 1 ≤ m ∧ m ≤ n :=
by simp only [iota_eq_reverse_range', mem_reverse, mem_range', add_comm, lt_succ_iff]
theorem reverse_range' : ∀ s n : ℕ,
reverse (range' s n) = map (λ i, s + n - 1 - i) (range n)
| s 0 := rfl
| s (n+1) := by rw [range'_concat, reverse_append, range_succ_eq_map];
simpa only [show s + (n + 1) - 1 = s + n, from rfl, (∘),
λ a i, show a - 1 - i = a - succ i, from pred_sub _ _,
reverse_singleton, map_cons, nat.sub_zero, cons_append,
nil_append, eq_self_iff_true, true_and, map_map]
using reverse_range' s n
/-- All elements of `fin n`, from `0` to `n-1`. -/
def fin_range (n : ℕ) : list (fin n) :=
(range n).pmap fin.mk (λ _, list.mem_range.1)
@[simp] lemma mem_fin_range {n : ℕ} (a : fin n) : a ∈ fin_range n :=
mem_pmap.2 ⟨a.1, mem_range.2 a.2, fin.eta _ _⟩
lemma nodup_fin_range (n : ℕ) : (fin_range n).nodup :=
nodup_pmap (λ _ _ _ _, fin.veq_of_eq) (nodup_range _)
@[simp] lemma length_fin_range (n : ℕ) : (fin_range n).length = n :=
by rw [fin_range, length_pmap, length_range]
@[to_additive]
theorem prod_range_succ {α : Type u} [monoid α] (f : ℕ → α) (n : ℕ) :
((range n.succ).map f).prod = ((range n).map f).prod * f n :=
by rw [range_concat, map_append, map_singleton,
prod_append, prod_cons, prod_nil, mul_one]
/-- A variant of `prod_range_succ` which pulls off the first
term in the product rather than the last.-/
@[to_additive "A variant of `sum_range_succ` which pulls off the first term in the sum
rather than the last."]
theorem prod_range_succ' {α : Type u} [monoid α] (f : ℕ → α) (n : ℕ) :
((range n.succ).map f).prod = f 0 * ((range n).map (λ i, f (succ i))).prod :=
nat.rec_on n
(show 1 * f 0 = f 0 * 1, by rw [one_mul, mul_one])
(λ _ hd, by rw [list.prod_range_succ, hd, mul_assoc, ←list.prod_range_succ])
@[simp] theorem enum_from_map_fst : ∀ n (l : list α),
map prod.fst (enum_from n l) = range' n l.length
| n [] := rfl
| n (a :: l) := congr_arg (cons _) (enum_from_map_fst _ _)
@[simp] theorem enum_map_fst (l : list α) :
map prod.fst (enum l) = range l.length :=
by simp only [enum, enum_from_map_fst, range_eq_range']
@[simp] lemma nth_le_range {n} (i) (H : i < (range n).length) :
nth_le (range n) i H = i :=
option.some.inj $ by rw [← nth_le_nth _, nth_range (by simpa using H)]
theorem of_fn_eq_pmap {α n} {f : fin n → α} :
of_fn f = pmap (λ i hi, f ⟨i, hi⟩) (range n) (λ _, mem_range.1) :=
by rw [pmap_eq_map_attach]; from ext_le (by simp)
(λ i hi1 hi2, by simp at hi1; simp [nth_le_of_fn f ⟨i, hi1⟩])
theorem nodup_of_fn {α n} {f : fin n → α} (hf : function.injective f) :
nodup (of_fn f) :=
by rw of_fn_eq_pmap; from nodup_pmap
(λ _ _ _ _ H, fin.veq_of_eq $ hf H) (nodup_range n)
end list
|
08fe87503d4e7bf5f5aa34e45a792f1b9b4b59f1 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/order/liminf_limsup.lean | fbc187f2a128357f35331f5e1c30d75ec94235ab | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 24,875 | lean | /-
Copyright (c) 2018 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel, Johannes Hölzl, Rémy Degenne
-/
import order.filter.partial
import order.filter.at_top_bot
/-!
# liminfs and limsups of functions and filters
Defines the Liminf/Limsup of a function taking values in a conditionally complete lattice, with
respect to an arbitrary filter.
We define `f.Limsup` (`f.Liminf`) where `f` is a filter taking values in a conditionally complete
lattice. `f.Limsup` is the smallest element `a` such that, eventually, `u ≤ a` (and vice versa for
`f.Liminf`). To work with the Limsup along a function `u` use `(f.map u).Limsup`.
Usually, one defines the Limsup as `Inf (Sup s)` where the Inf is taken over all sets in the filter.
For instance, in ℕ along a function `u`, this is `Inf_n (Sup_{k ≥ n} u k)` (and the latter quantity
decreases with `n`, so this is in fact a limit.). There is however a difficulty: it is well possible
that `u` is not bounded on the whole space, only eventually (think of `Limsup (λx, 1/x)` on ℝ. Then
there is no guarantee that the quantity above really decreases (the value of the `Sup` beforehand is
not really well defined, as one can not use ∞), so that the Inf could be anything. So one can not
use this `Inf Sup ...` definition in conditionally complete lattices, and one has to use a less
tractable definition.
In conditionally complete lattices, the definition is only useful for filters which are eventually
bounded above (otherwise, the Limsup would morally be +∞, which does not belong to the space) and
which are frequently bounded below (otherwise, the Limsup would morally be -∞, which is not in the
space either). We start with definitions of these concepts for arbitrary filters, before turning to
the definitions of Limsup and Liminf.
In complete lattices, however, it coincides with the `Inf Sup` definition.
-/
open filter set
open_locale filter
variables {α β ι : Type*}
namespace filter
section relation
/-- `f.is_bounded (≺)`: the filter `f` is eventually bounded w.r.t. the relation `≺`, i.e.
eventually, it is bounded by some uniform bound.
`r` will be usually instantiated with `≤` or `≥`. -/
def is_bounded (r : α → α → Prop) (f : filter α) := ∃ b, ∀ᶠ x in f, r x b
/-- `f.is_bounded_under (≺) u`: the image of the filter `f` under `u` is eventually bounded w.r.t.
the relation `≺`, i.e. eventually, it is bounded by some uniform bound. -/
def is_bounded_under (r : α → α → Prop) (f : filter β) (u : β → α) := (f.map u).is_bounded r
variables {r : α → α → Prop} {f g : filter α}
/-- `f` is eventually bounded if and only if, there exists an admissible set on which it is
bounded. -/
lemma is_bounded_iff : f.is_bounded r ↔ (∃s∈f.sets, ∃b, s ⊆ {x | r x b}) :=
iff.intro
(assume ⟨b, hb⟩, ⟨{a | r a b}, hb, b, subset.refl _⟩)
(assume ⟨s, hs, b, hb⟩, ⟨b, mem_of_superset hs hb⟩)
/-- A bounded function `u` is in particular eventually bounded. -/
lemma is_bounded_under_of {f : filter β} {u : β → α} :
(∃b, ∀x, r (u x) b) → f.is_bounded_under r u
| ⟨b, hb⟩ := ⟨b, show ∀ᶠ x in f, r (u x) b, from eventually_of_forall hb⟩
lemma is_bounded_bot : is_bounded r ⊥ ↔ nonempty α :=
by simp [is_bounded, exists_true_iff_nonempty]
lemma is_bounded_top : is_bounded r ⊤ ↔ (∃t, ∀x, r x t) :=
by simp [is_bounded, eq_univ_iff_forall]
lemma is_bounded_principal (s : set α) : is_bounded r (𝓟 s) ↔ (∃t, ∀x∈s, r x t) :=
by simp [is_bounded, subset_def]
lemma is_bounded_sup [is_trans α r] (hr : ∀b₁ b₂, ∃b, r b₁ b ∧ r b₂ b) :
is_bounded r f → is_bounded r g → is_bounded r (f ⊔ g)
| ⟨b₁, h₁⟩ ⟨b₂, h₂⟩ := let ⟨b, rb₁b, rb₂b⟩ := hr b₁ b₂ in
⟨b, eventually_sup.mpr ⟨h₁.mono (λ x h, trans h rb₁b), h₂.mono (λ x h, trans h rb₂b)⟩⟩
lemma is_bounded.mono (h : f ≤ g) : is_bounded r g → is_bounded r f
| ⟨b, hb⟩ := ⟨b, h hb⟩
lemma is_bounded_under.mono {f g : filter β} {u : β → α} (h : f ≤ g) :
g.is_bounded_under r u → f.is_bounded_under r u :=
λ hg, hg.mono (map_mono h)
lemma is_bounded.is_bounded_under {q : β → β → Prop} {u : α → β}
(hf : ∀a₀ a₁, r a₀ a₁ → q (u a₀) (u a₁)) : f.is_bounded r → f.is_bounded_under q u
| ⟨b, h⟩ := ⟨u b, show ∀ᶠ x in f, q (u x) (u b), from h.mono (λ x, hf x b)⟩
lemma not_is_bounded_under_of_tendsto_at_top [nonempty α] [semilattice_sup α]
[preorder β] [no_top_order β] {f : α → β} (hf : tendsto f at_top at_top) :
¬ is_bounded_under (≤) at_top f :=
begin
rintro ⟨b, hb⟩,
rw eventually_map at hb,
obtain ⟨b', h⟩ := no_top b,
have hb' := (tendsto_at_top.mp hf) b',
have : {x : α | f x ≤ b} ∩ {x : α | b' ≤ f x} = ∅ :=
eq_empty_of_subset_empty (λ x hx, (not_le_of_lt h) (le_trans hx.2 hx.1)),
exact at_top.empty_not_mem (this ▸ filter.inter_mem hb hb' : ∅ ∈ (at_top : filter α)),
end
lemma not_is_bounded_under_of_tendsto_at_bot [nonempty α] [semilattice_sup α]
[preorder β] [no_bot_order β] {f : α → β} (hf : tendsto f at_top at_bot) :
¬ is_bounded_under (≥) at_top f :=
begin
rintro ⟨b, hb⟩,
rw eventually_map at hb,
obtain ⟨b', h⟩ := no_bot b,
have hb' := (tendsto_at_bot.mp hf) b',
have : {x : α | b ≤ f x} ∩ {x : α | f x ≤ b'} = ∅ :=
eq_empty_of_subset_empty (λ x hx, (not_le_of_lt h) (le_trans hx.1 hx.2)),
exact at_top.empty_not_mem (this ▸ filter.inter_mem hb hb' : ∅ ∈ (at_top : filter α)),
end
/-- `is_cobounded (≺) f` states that the filter `f` does not tend to infinity w.r.t. `≺`. This is
also called frequently bounded. Will be usually instantiated with `≤` or `≥`.
There is a subtlety in this definition: we want `f.is_cobounded` to hold for any `f` in the case of
complete lattices. This will be relevant to deduce theorems on complete lattices from their
versions on conditionally complete lattices with additional assumptions. We have to be careful in
the edge case of the trivial filter containing the empty set: the other natural definition
`¬ ∀ a, ∀ᶠ n in f, a ≤ n`
would not work as well in this case.
-/
def is_cobounded (r : α → α → Prop) (f : filter α) := ∃b, ∀a, (∀ᶠ x in f, r x a) → r b a
/-- `is_cobounded_under (≺) f u` states that the image of the filter `f` under the map `u` does not
tend to infinity w.r.t. `≺`. This is also called frequently bounded. Will be usually instantiated
with `≤` or `≥`. -/
def is_cobounded_under (r : α → α → Prop) (f : filter β) (u : β → α) := (f.map u).is_cobounded r
/-- To check that a filter is frequently bounded, it suffices to have a witness
which bounds `f` at some point for every admissible set.
This is only an implication, as the other direction is wrong for the trivial filter.-/
lemma is_cobounded.mk [is_trans α r] (a : α) (h : ∀s∈f, ∃x∈s, r a x) : f.is_cobounded r :=
⟨a, assume y s, let ⟨x, h₁, h₂⟩ := h _ s in trans h₂ h₁⟩
/-- A filter which is eventually bounded is in particular frequently bounded (in the opposite
direction). At least if the filter is not trivial. -/
lemma is_bounded.is_cobounded_flip [is_trans α r] [ne_bot f] :
f.is_bounded r → f.is_cobounded (flip r)
| ⟨a, ha⟩ := ⟨a, assume b hb,
let ⟨x, rxa, rbx⟩ := (ha.and hb).exists in
show r b a, from trans rbx rxa⟩
lemma is_bounded.is_cobounded_ge [preorder α] [ne_bot f] (h : f.is_bounded (≤)) :
f.is_cobounded (≥) :=
h.is_cobounded_flip
lemma is_bounded.is_cobounded_le [preorder α] [ne_bot f] (h : f.is_bounded (≥)) :
f.is_cobounded (≤) :=
h.is_cobounded_flip
lemma is_cobounded_bot : is_cobounded r ⊥ ↔ (∃b, ∀x, r b x) :=
by simp [is_cobounded]
lemma is_cobounded_top : is_cobounded r ⊤ ↔ nonempty α :=
by simp [is_cobounded, eq_univ_iff_forall, exists_true_iff_nonempty] {contextual := tt}
lemma is_cobounded_principal (s : set α) :
(𝓟 s).is_cobounded r ↔ (∃b, ∀a, (∀x∈s, r x a) → r b a) :=
by simp [is_cobounded, subset_def]
lemma is_cobounded.mono (h : f ≤ g) : f.is_cobounded r → g.is_cobounded r
| ⟨b, hb⟩ := ⟨b, assume a ha, hb a (h ha)⟩
end relation
lemma is_cobounded_le_of_bot [preorder α] [order_bot α] {f : filter α} : f.is_cobounded (≤) :=
⟨⊥, assume a h, bot_le⟩
lemma is_cobounded_ge_of_top [preorder α] [order_top α] {f : filter α} : f.is_cobounded (≥) :=
⟨⊤, assume a h, le_top⟩
lemma is_bounded_le_of_top [preorder α] [order_top α] {f : filter α} : f.is_bounded (≤) :=
⟨⊤, eventually_of_forall $ λ _, le_top⟩
lemma is_bounded_ge_of_bot [preorder α] [order_bot α] {f : filter α} : f.is_bounded (≥) :=
⟨⊥, eventually_of_forall $ λ _, bot_le⟩
lemma is_bounded_under_sup [semilattice_sup α] {f : filter β} {u v : β → α} :
f.is_bounded_under (≤) u → f.is_bounded_under (≤) v → f.is_bounded_under (≤) (λa, u a ⊔ v a)
| ⟨bu, (hu : ∀ᶠ x in f, u x ≤ bu)⟩ ⟨bv, (hv : ∀ᶠ x in f, v x ≤ bv)⟩ :=
⟨bu ⊔ bv, show ∀ᶠ x in f, u x ⊔ v x ≤ bu ⊔ bv,
by filter_upwards [hu, hv] assume x, sup_le_sup⟩
lemma is_bounded_under_inf [semilattice_inf α] {f : filter β} {u v : β → α} :
f.is_bounded_under (≥) u → f.is_bounded_under (≥) v → f.is_bounded_under (≥) (λa, u a ⊓ v a)
| ⟨bu, (hu : ∀ᶠ x in f, u x ≥ bu)⟩ ⟨bv, (hv : ∀ᶠ x in f, v x ≥ bv)⟩ :=
⟨bu ⊓ bv, show ∀ᶠ x in f, u x ⊓ v x ≥ bu ⊓ bv,
by filter_upwards [hu, hv] assume x, inf_le_inf⟩
/-- Filters are automatically bounded or cobounded in complete lattices. To use the same statements
in complete and conditionally complete lattices but let automation fill automatically the
boundedness proofs in complete lattices, we use the tactic `is_bounded_default` in the statements,
in the form `(hf : f.is_bounded (≥) . is_bounded_default)`. -/
meta def is_bounded_default : tactic unit :=
tactic.applyc ``is_cobounded_le_of_bot <|>
tactic.applyc ``is_cobounded_ge_of_top <|>
tactic.applyc ``is_bounded_le_of_top <|>
tactic.applyc ``is_bounded_ge_of_bot
section conditionally_complete_lattice
variables [conditionally_complete_lattice α]
/-- The `Limsup` of a filter `f` is the infimum of the `a` such that, eventually for `f`,
holds `x ≤ a`. -/
def Limsup (f : filter α) : α := Inf { a | ∀ᶠ n in f, n ≤ a }
/-- The `Liminf` of a filter `f` is the supremum of the `a` such that, eventually for `f`,
holds `x ≥ a`. -/
def Liminf (f : filter α) : α := Sup { a | ∀ᶠ n in f, a ≤ n }
/-- The `limsup` of a function `u` along a filter `f` is the infimum of the `a` such that,
eventually for `f`, holds `u x ≤ a`. -/
def limsup (f : filter β) (u : β → α) : α := (f.map u).Limsup
/-- The `liminf` of a function `u` along a filter `f` is the supremum of the `a` such that,
eventually for `f`, holds `u x ≥ a`. -/
def liminf (f : filter β) (u : β → α) : α := (f.map u).Liminf
section
variables {f : filter β} {u : β → α}
theorem limsup_eq : f.limsup u = Inf { a | ∀ᶠ n in f, u n ≤ a } := rfl
theorem liminf_eq : f.liminf u = Sup { a | ∀ᶠ n in f, a ≤ u n } := rfl
end
theorem Limsup_le_of_le {f : filter α} {a}
(hf : f.is_cobounded (≤) . is_bounded_default) (h : ∀ᶠ n in f, n ≤ a) : f.Limsup ≤ a :=
cInf_le hf h
theorem le_Liminf_of_le {f : filter α} {a}
(hf : f.is_cobounded (≥) . is_bounded_default) (h : ∀ᶠ n in f, a ≤ n) : a ≤ f.Liminf :=
le_cSup hf h
theorem le_Limsup_of_le {f : filter α} {a}
(hf : f.is_bounded (≤) . is_bounded_default) (h : ∀ b, (∀ᶠ n in f, n ≤ b) → a ≤ b) :
a ≤ f.Limsup :=
le_cInf hf h
theorem Liminf_le_of_le {f : filter α} {a}
(hf : f.is_bounded (≥) . is_bounded_default) (h : ∀ b, (∀ᶠ n in f, b ≤ n) → b ≤ a) :
f.Liminf ≤ a :=
cSup_le hf h
theorem Liminf_le_Limsup {f : filter α} [ne_bot f]
(h₁ : f.is_bounded (≤) . is_bounded_default) (h₂ : f.is_bounded (≥) . is_bounded_default) :
f.Liminf ≤ f.Limsup :=
Liminf_le_of_le h₂ $ assume a₀ ha₀, le_Limsup_of_le h₁ $ assume a₁ ha₁,
show a₀ ≤ a₁, from let ⟨b, hb₀, hb₁⟩ := (ha₀.and ha₁).exists in le_trans hb₀ hb₁
lemma Liminf_le_Liminf {f g : filter α}
(hf : f.is_bounded (≥) . is_bounded_default) (hg : g.is_cobounded (≥) . is_bounded_default)
(h : ∀ a, (∀ᶠ n in f, a ≤ n) → ∀ᶠ n in g, a ≤ n) : f.Liminf ≤ g.Liminf :=
cSup_le_cSup hg hf h
lemma Limsup_le_Limsup {f g : filter α}
(hf : f.is_cobounded (≤) . is_bounded_default) (hg : g.is_bounded (≤) . is_bounded_default)
(h : ∀ a, (∀ᶠ n in g, n ≤ a) → ∀ᶠ n in f, n ≤ a) : f.Limsup ≤ g.Limsup :=
cInf_le_cInf hf hg h
lemma Limsup_le_Limsup_of_le {f g : filter α} (h : f ≤ g)
(hf : f.is_cobounded (≤) . is_bounded_default) (hg : g.is_bounded (≤) . is_bounded_default) :
f.Limsup ≤ g.Limsup :=
Limsup_le_Limsup hf hg (assume a ha, h ha)
lemma Liminf_le_Liminf_of_le {f g : filter α} (h : g ≤ f)
(hf : f.is_bounded (≥) . is_bounded_default) (hg : g.is_cobounded (≥) . is_bounded_default) :
f.Liminf ≤ g.Liminf :=
Liminf_le_Liminf hf hg (assume a ha, h ha)
lemma limsup_le_limsup {α : Type*} [conditionally_complete_lattice β] {f : filter α} {u v : α → β}
(h : u ≤ᶠ[f] v)
(hu : f.is_cobounded_under (≤) u . is_bounded_default)
(hv : f.is_bounded_under (≤) v . is_bounded_default) :
f.limsup u ≤ f.limsup v :=
Limsup_le_Limsup hu hv $ assume b, h.trans
lemma liminf_le_liminf {α : Type*} [conditionally_complete_lattice β] {f : filter α} {u v : α → β}
(h : ∀ᶠ a in f, u a ≤ v a)
(hu : f.is_bounded_under (≥) u . is_bounded_default)
(hv : f.is_cobounded_under (≥) v . is_bounded_default) :
f.liminf u ≤ f.liminf v :=
@limsup_le_limsup (order_dual β) α _ _ _ _ h hv hu
lemma limsup_le_limsup_of_le {α β} [conditionally_complete_lattice β] {f g : filter α} (h : f ≤ g)
{u : α → β} (hf : f.is_cobounded_under (≤) u . is_bounded_default)
(hg : g.is_bounded_under (≤) u . is_bounded_default) :
f.limsup u ≤ g.limsup u :=
Limsup_le_Limsup_of_le (map_mono h) hf hg
lemma liminf_le_liminf_of_le {α β} [conditionally_complete_lattice β] {f g : filter α} (h : g ≤ f)
{u : α → β} (hf : f.is_bounded_under (≥) u . is_bounded_default)
(hg : g.is_cobounded_under (≥) u . is_bounded_default) :
f.liminf u ≤ g.liminf u :=
Liminf_le_Liminf_of_le (map_mono h) hf hg
theorem Limsup_principal {s : set α} (h : bdd_above s) (hs : s.nonempty) :
(𝓟 s).Limsup = Sup s :=
by simp [Limsup]; exact cInf_upper_bounds_eq_cSup h hs
theorem Liminf_principal {s : set α} (h : bdd_below s) (hs : s.nonempty) :
(𝓟 s).Liminf = Inf s :=
@Limsup_principal (order_dual α) _ s h hs
lemma limsup_congr {α : Type*} [conditionally_complete_lattice β] {f : filter α} {u v : α → β}
(h : ∀ᶠ a in f, u a = v a) : limsup f u = limsup f v :=
begin
rw limsup_eq,
congr' with b,
exact eventually_congr (h.mono $ λ x hx, by simp [hx])
end
lemma liminf_congr {α : Type*} [conditionally_complete_lattice β] {f : filter α} {u v : α → β}
(h : ∀ᶠ a in f, u a = v a) : liminf f u = liminf f v :=
@limsup_congr (order_dual β) _ _ _ _ _ h
lemma limsup_const {α : Type*} [conditionally_complete_lattice β] {f : filter α} [ne_bot f]
(b : β) : limsup f (λ x, b) = b :=
by simpa only [limsup_eq, eventually_const] using cInf_Ici
lemma liminf_const {α : Type*} [conditionally_complete_lattice β] {f : filter α} [ne_bot f]
(b : β) : liminf f (λ x, b) = b :=
@limsup_const (order_dual β) α _ f _ b
lemma liminf_le_limsup {f : filter β} [ne_bot f] {u : β → α}
(h : f.is_bounded_under (≤) u . is_bounded_default)
(h' : f.is_bounded_under (≥) u . is_bounded_default) :
liminf f u ≤ limsup f u :=
Liminf_le_Limsup h h'
end conditionally_complete_lattice
section complete_lattice
variables [complete_lattice α]
@[simp] theorem Limsup_bot : (⊥ : filter α).Limsup = ⊥ :=
bot_unique $ Inf_le $ by simp
@[simp] theorem Liminf_bot : (⊥ : filter α).Liminf = ⊤ :=
top_unique $ le_Sup $ by simp
@[simp] theorem Limsup_top : (⊤ : filter α).Limsup = ⊤ :=
top_unique $ le_Inf $
by simp [eq_univ_iff_forall]; exact assume b hb, (top_unique $ hb _)
@[simp] theorem Liminf_top : (⊤ : filter α).Liminf = ⊥ :=
bot_unique $ Sup_le $
by simp [eq_univ_iff_forall]; exact assume b hb, (bot_unique $ hb _)
/-- Same as limsup_const applied to `⊥` but without the `ne_bot f` assumption -/
lemma limsup_const_bot {f : filter β} : limsup f (λ x : β, (⊥ : α)) = (⊥ : α) :=
begin
rw [limsup_eq, eq_bot_iff],
exact Inf_le (eventually_of_forall (λ x, le_refl _)),
end
/-- Same as limsup_const applied to `⊤` but without the `ne_bot f` assumption -/
lemma liminf_const_top {f : filter β} : liminf f (λ x : β, (⊤ : α)) = (⊤ : α) :=
@limsup_const_bot (order_dual α) β _ _
theorem has_basis.Limsup_eq_infi_Sup {ι} {p : ι → Prop} {s} {f : filter α} (h : f.has_basis p s) :
f.Limsup = ⨅ i (hi : p i), Sup (s i) :=
le_antisymm
(le_binfi $ λ i hi, Inf_le $ h.eventually_iff.2 ⟨i, hi, λ x, le_Sup⟩)
(le_Inf $ assume a ha, let ⟨i, hi, ha⟩ := h.eventually_iff.1 ha in
infi_le_of_le _ $ infi_le_of_le hi $ Sup_le ha)
theorem has_basis.Liminf_eq_supr_Inf {p : ι → Prop} {s : ι → set α} {f : filter α}
(h : f.has_basis p s) : f.Liminf = ⨆ i (hi : p i), Inf (s i) :=
@has_basis.Limsup_eq_infi_Sup (order_dual α) _ _ _ _ _ h
theorem Limsup_eq_infi_Sup {f : filter α} : f.Limsup = ⨅ s ∈ f, Sup s :=
f.basis_sets.Limsup_eq_infi_Sup
theorem Liminf_eq_supr_Inf {f : filter α} : f.Liminf = ⨆ s ∈ f, Inf s :=
@Limsup_eq_infi_Sup (order_dual α) _ _
/-- In a complete lattice, the limsup of a function is the infimum over sets `s` in the filter
of the supremum of the function over `s` -/
theorem limsup_eq_infi_supr {f : filter β} {u : β → α} : f.limsup u = ⨅ s ∈ f, ⨆ a ∈ s, u a :=
(f.basis_sets.map u).Limsup_eq_infi_Sup.trans $
by simp only [Sup_image, id]
lemma limsup_eq_infi_supr_of_nat {u : ℕ → α} : limsup at_top u = ⨅ n : ℕ, ⨆ i ≥ n, u i :=
(at_top_basis.map u).Limsup_eq_infi_Sup.trans $
by simp only [Sup_image, infi_const]; refl
lemma limsup_eq_infi_supr_of_nat' {u : ℕ → α} : limsup at_top u = ⨅ n : ℕ, ⨆ i : ℕ, u (i + n) :=
by simp only [limsup_eq_infi_supr_of_nat, supr_ge_eq_supr_nat_add]
theorem has_basis.limsup_eq_infi_supr {p : ι → Prop} {s : ι → set β} {f : filter β} {u : β → α}
(h : f.has_basis p s) : f.limsup u = ⨅ i (hi : p i), ⨆ a ∈ s i, u a :=
(h.map u).Limsup_eq_infi_Sup.trans $ by simp only [Sup_image, id]
/-- In a complete lattice, the liminf of a function is the infimum over sets `s` in the filter
of the supremum of the function over `s` -/
theorem liminf_eq_supr_infi {f : filter β} {u : β → α} : f.liminf u = ⨆ s ∈ f, ⨅ a ∈ s, u a :=
@limsup_eq_infi_supr (order_dual α) β _ _ _
lemma liminf_eq_supr_infi_of_nat {u : ℕ → α} : liminf at_top u = ⨆ n : ℕ, ⨅ i ≥ n, u i :=
@limsup_eq_infi_supr_of_nat (order_dual α) _ u
lemma liminf_eq_supr_infi_of_nat' {u : ℕ → α} : liminf at_top u = ⨆ n : ℕ, ⨅ i : ℕ, u (i + n) :=
@limsup_eq_infi_supr_of_nat' (order_dual α) _ _
theorem has_basis.liminf_eq_supr_infi {p : ι → Prop} {s : ι → set β} {f : filter β} {u : β → α}
(h : f.has_basis p s) : f.liminf u = ⨆ i (hi : p i), ⨅ a ∈ s i, u a :=
@has_basis.limsup_eq_infi_supr (order_dual α) _ _ _ _ _ _ _ h
@[simp] lemma liminf_nat_add (f : ℕ → α) (k : ℕ) :
at_top.liminf (λ i, f (i + k)) = at_top.liminf f :=
by { simp_rw liminf_eq_supr_infi_of_nat, exact supr_infi_ge_nat_add f k }
@[simp] lemma limsup_nat_add (f : ℕ → α) (k : ℕ) :
at_top.limsup (λ i, f (i + k)) = at_top.limsup f :=
@liminf_nat_add (order_dual α) _ f k
lemma liminf_le_of_frequently_le' {α β} [complete_lattice β]
{f : filter α} {u : α → β} {x : β} (h : ∃ᶠ a in f, u a ≤ x) :
f.liminf u ≤ x :=
begin
rw liminf_eq,
refine Sup_le (λ b hb, _),
have hbx : ∃ᶠ a in f, b ≤ x,
{ revert h,
rw [←not_imp_not, not_frequently, not_frequently],
exact λ h, hb.mp (h.mono (λ a hbx hba hax, hbx (hba.trans hax))), },
exact hbx.exists.some_spec,
end
lemma le_limsup_of_frequently_le' {α β} [complete_lattice β]
{f : filter α} {u : α → β} {x : β} (h : ∃ᶠ a in f, x ≤ u a) :
x ≤ f.limsup u :=
@liminf_le_of_frequently_le' _ (order_dual β) _ _ _ _ h
end complete_lattice
section conditionally_complete_linear_order
lemma eventually_lt_of_lt_liminf {f : filter α} [conditionally_complete_linear_order β]
{u : α → β} {b : β} (h : b < liminf f u) (hu : f.is_bounded_under (≥) u . is_bounded_default) :
∀ᶠ a in f, b < u a :=
begin
obtain ⟨c, hc, hbc⟩ : ∃ (c : β) (hc : c ∈ {c : β | ∀ᶠ (n : α) in f, c ≤ u n}), b < c :=
exists_lt_of_lt_cSup hu h,
exact hc.mono (λ x hx, lt_of_lt_of_le hbc hx)
end
lemma eventually_lt_of_limsup_lt {f : filter α} [conditionally_complete_linear_order β]
{u : α → β} {b : β} (h : limsup f u < b) (hu : f.is_bounded_under (≤) u . is_bounded_default) :
∀ᶠ a in f, u a < b :=
@eventually_lt_of_lt_liminf _ (order_dual β) _ _ _ _ h hu
lemma le_limsup_of_frequently_le {α β} [conditionally_complete_linear_order β] {f : filter α}
{u : α → β} {b : β} (hu_le : ∃ᶠ x in f, b ≤ u x)
(hu : f.is_bounded_under (≤) u . is_bounded_default) :
b ≤ f.limsup u :=
begin
revert hu_le,
rw [←not_imp_not, not_frequently],
simp_rw ←lt_iff_not_ge,
exact λ h, eventually_lt_of_limsup_lt h hu,
end
lemma liminf_le_of_frequently_le {α β} [conditionally_complete_linear_order β] {f : filter α}
{u : α → β} {b : β} (hu_le : ∃ᶠ x in f, u x ≤ b)
(hu : f.is_bounded_under (≥) u . is_bounded_default) :
f.liminf u ≤ b :=
@le_limsup_of_frequently_le _ (order_dual β) _ f u b hu_le hu
lemma frequently_lt_of_lt_limsup {α β} [conditionally_complete_linear_order β] {f : filter α}
{u : α → β} {b : β}
(hu : f.is_cobounded_under (≤) u . is_bounded_default) (h : b < f.limsup u) :
∃ᶠ x in f, b < u x :=
begin
contrapose! h,
apply Limsup_le_of_le hu,
simpa using h,
end
lemma frequently_lt_of_liminf_lt {α β} [conditionally_complete_linear_order β] {f : filter α}
{u : α → β} {b : β}
(hu : f.is_cobounded_under (≥) u . is_bounded_default) (h : f.liminf u < b) :
∃ᶠ x in f, u x < b :=
@frequently_lt_of_lt_limsup _ (order_dual β) _ f u b hu h
end conditionally_complete_linear_order
end filter
section order
open filter
lemma galois_connection.l_limsup_le {α β γ} [conditionally_complete_lattice β]
[conditionally_complete_lattice γ] {f : filter α} {v : α → β}
{l : β → γ} {u : γ → β} (gc : galois_connection l u)
(hlv : f.is_bounded_under (≤) (λ x, l (v x)) . is_bounded_default)
(hv_co : f.is_cobounded_under (≤) v . is_bounded_default) :
l (f.limsup v) ≤ f.limsup (λ x, l (v x)) :=
begin
refine le_Limsup_of_le hlv (λ c hc, _),
rw filter.eventually_map at hc,
simp_rw (gc _ _) at hc ⊢,
exact Limsup_le_of_le hv_co hc,
end
lemma order_iso.limsup_apply {γ} [conditionally_complete_lattice β]
[conditionally_complete_lattice γ] {f : filter α} {u : α → β} (g : β ≃o γ)
(hu : f.is_bounded_under (≤) u . is_bounded_default)
(hu_co : f.is_cobounded_under (≤) u . is_bounded_default)
(hgu : f.is_bounded_under (≤) (λ x, g (u x)) . is_bounded_default)
(hgu_co : f.is_cobounded_under (≤) (λ x, g (u x)) . is_bounded_default) :
g (f.limsup u) = f.limsup (λ x, g (u x)) :=
begin
refine le_antisymm (g.to_galois_connection.l_limsup_le hgu hu_co) _,
rw [←(g.symm.symm_apply_apply (f.limsup (λ (x : α), g (u x)))), g.symm_symm],
refine g.monotone _,
have hf : u = λ i, g.symm (g (u i)), from funext (λ i, (g.symm_apply_apply (u i)).symm),
nth_rewrite 0 hf,
refine g.symm.to_galois_connection.l_limsup_le _ hgu_co,
simp_rw g.symm_apply_apply,
exact hu,
end
lemma order_iso.liminf_apply {γ} [conditionally_complete_lattice β]
[conditionally_complete_lattice γ] {f : filter α} {u : α → β} (g : β ≃o γ)
(hu : f.is_bounded_under (≥) u . is_bounded_default)
(hu_co : f.is_cobounded_under (≥) u . is_bounded_default)
(hgu : f.is_bounded_under (≥) (λ x, g (u x)) . is_bounded_default)
(hgu_co : f.is_cobounded_under (≥) (λ x, g (u x)) . is_bounded_default) :
g (f.liminf u) = f.liminf (λ x, g (u x)) :=
@order_iso.limsup_apply α (order_dual β) (order_dual γ) _ _ f u g.dual hu hu_co hgu hgu_co
end order
|
4686781d73e30a472d5752842895ffede9568ccc | cf39355caa609c0f33405126beee2739aa3cb77e | /library/init/data/int/basic.lean | d5c56774975a8afeb65436890661c3438a1f38ab | [
"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 | 23,263 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
-/
prelude
import init.data.nat.lemmas init.data.nat.gcd
open nat
/-!
# The integers, with addition, multiplication, and subtraction.
the type, coercions, and notation -/
@[derive decidable_eq]
inductive int : Type
| of_nat : nat → int
| neg_succ_of_nat : nat → int
notation `ℤ` := int
instance : has_coe nat int := ⟨int.of_nat⟩
notation `-[1+ ` n `]` := int.neg_succ_of_nat n
protected def int.repr : int → string
| (int.of_nat n) := repr n
| (int.neg_succ_of_nat n) := "-" ++ repr (succ n)
instance : has_repr int :=
⟨int.repr⟩
instance : has_to_string int :=
⟨int.repr⟩
namespace int
protected lemma coe_nat_eq (n : ℕ) : ↑n = int.of_nat n := rfl
protected def zero : ℤ := of_nat 0
protected def one : ℤ := of_nat 1
instance : has_zero ℤ := ⟨int.zero⟩
instance : has_one ℤ := ⟨int.one⟩
lemma of_nat_zero : of_nat (0 : nat) = (0 : int) := rfl
lemma of_nat_one : of_nat (1 : nat) = (1 : int) := rfl
/-! definitions of basic functions -/
def neg_of_nat : ℕ → ℤ
| 0 := 0
| (succ m) := -[1+ m]
def 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
lemma sub_nat_nat_of_sub_eq_zero {m n : ℕ} (h : n - m = 0) :
sub_nat_nat m n = of_nat (m - n) :=
begin unfold sub_nat_nat, rw h, unfold sub_nat_nat._match_1 end
lemma sub_nat_nat_of_sub_eq_succ {m n k : ℕ} (h : n - m = succ k) :
sub_nat_nat m n = -[1+ k] :=
begin unfold sub_nat_nat, rw h, unfold sub_nat_nat._match_1 end
protected def neg : ℤ → ℤ
| (of_nat n) := neg_of_nat n
| -[1+ n] := succ n
protected def add : ℤ → ℤ → ℤ
| (of_nat m) (of_nat n) := of_nat (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] := -[1+ succ (m + n)]
protected def mul : ℤ → ℤ → ℤ
| (of_nat m) (of_nat n) := of_nat (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] := of_nat (succ m * succ n)
instance : has_neg ℤ := ⟨int.neg⟩
instance : has_add ℤ := ⟨int.add⟩
instance : has_mul ℤ := ⟨int.mul⟩
-- defeq to algebra.sub which gives subtraction for arbitrary `add_group`s
protected def sub : ℤ → ℤ → ℤ :=
λ m n, m + -n
instance : has_sub ℤ := ⟨int.sub⟩
protected lemma neg_zero : -(0:ℤ) = 0 := rfl
lemma of_nat_add (n m : ℕ) : of_nat (n + m) = of_nat n + of_nat m := rfl
lemma of_nat_mul (n m : ℕ) : of_nat (n * m) = of_nat n * of_nat m := rfl
lemma of_nat_succ (n : ℕ) : of_nat (succ n) = of_nat n + 1 := rfl
lemma neg_of_nat_zero : -(of_nat 0) = 0 := rfl
lemma neg_of_nat_of_succ (n : ℕ) : -(of_nat (succ n)) = -[1+ n] := rfl
lemma neg_neg_of_nat_succ (n : ℕ) : -(-[1+ n]) = of_nat (succ n) := rfl
lemma of_nat_eq_coe (n : ℕ) : of_nat n = ↑n := rfl
lemma neg_succ_of_nat_coe (n : ℕ) : -[1+ n] = -↑(n + 1) := rfl
protected lemma coe_nat_add (m n : ℕ) : (↑(m + n) : ℤ) = ↑m + ↑n := rfl
protected lemma coe_nat_mul (m n : ℕ) : (↑(m * n) : ℤ) = ↑m * ↑n := rfl
protected lemma coe_nat_zero : ↑(0 : ℕ) = (0 : ℤ) := rfl
protected lemma coe_nat_one : ↑(1 : ℕ) = (1 : ℤ) := rfl
protected lemma coe_nat_succ (n : ℕ) : (↑(succ n) : ℤ) = ↑n + 1 := rfl
protected lemma coe_nat_add_out (m n : ℕ) : ↑m + ↑n = (m + n : ℤ) := rfl
protected lemma coe_nat_mul_out (m n : ℕ) : ↑m * ↑n = (↑(m * n) : ℤ) := rfl
protected lemma coe_nat_add_one_out (n : ℕ) : ↑n + (1 : ℤ) = ↑(succ n) := rfl
/-! these are only for internal use -/
lemma of_nat_add_of_nat (m n : nat) : of_nat m + of_nat n = of_nat (m + n) := rfl
lemma of_nat_add_neg_succ_of_nat (m n : nat) :
of_nat m + -[1+ n] = sub_nat_nat m (succ n) := rfl
lemma neg_succ_of_nat_add_of_nat (m n : nat) :
-[1+ m] + of_nat n = sub_nat_nat n (succ m) := rfl
lemma neg_succ_of_nat_add_neg_succ_of_nat (m n : nat) :
-[1+ m] + -[1+ n] = -[1+ succ (m + n)] := rfl
lemma of_nat_mul_of_nat (m n : nat) : of_nat m * of_nat n = of_nat (m * n) := rfl
lemma of_nat_mul_neg_succ_of_nat (m n : nat) :
of_nat m * -[1+ n] = neg_of_nat (m * succ n) := rfl
lemma 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] = of_nat (succ m * succ n) := rfl
local attribute [simp] of_nat_add_of_nat of_nat_mul_of_nat neg_of_nat_zero neg_of_nat_of_succ
neg_neg_of_nat_succ of_nat_add_neg_succ_of_nat neg_succ_of_nat_add_of_nat
neg_succ_of_nat_add_neg_succ_of_nat of_nat_mul_neg_succ_of_nat neg_succ_of_nat_of_nat
mul_neg_succ_of_nat_neg_succ_of_nat
/-! some basic functions and properties -/
protected lemma coe_nat_inj {m n : ℕ} (h : (↑m : ℤ) = ↑n) : m = n :=
int.of_nat.inj h
lemma of_nat_eq_of_nat_iff (m n : ℕ) : of_nat m = of_nat n ↔ m = n :=
iff.intro int.of_nat.inj (congr_arg _)
protected lemma coe_nat_eq_coe_nat_iff (m n : ℕ) : (↑m : ℤ) = ↑n ↔ m = n :=
of_nat_eq_of_nat_iff m n
lemma neg_succ_of_nat_inj_iff {m n : ℕ} : neg_succ_of_nat m = neg_succ_of_nat n ↔ m = n :=
⟨neg_succ_of_nat.inj, assume H, by simp [H]⟩
lemma neg_succ_of_nat_eq (n : ℕ) : -[1+ n] = -(n + 1) := rfl
/-! neg -/
protected lemma neg_neg : ∀ a : ℤ, -(-a) = a
| (of_nat 0) := rfl
| (of_nat (n+1)) := rfl
| -[1+ n] := rfl
protected lemma neg_inj {a b : ℤ} (h : -a = -b) : a = b :=
by rw [← int.neg_neg a, ← int.neg_neg b, h]
protected lemma sub_eq_add_neg {a b : ℤ} : a - b = a + -b := rfl
/-! basic properties of sub_nat_nat -/
lemma sub_nat_nat_elim (m n : ℕ) (P : ℕ → ℕ → ℤ → Prop)
(hp : ∀i n, P (n + i) n (of_nat i))
(hn : ∀i m, P m (m + i + 1) (-[1+ i])) :
P m n (sub_nat_nat m n) :=
begin
have H : ∀k, n - m = k → P m n (nat.cases_on k (of_nat (m - n)) (λa, -[1+ a])),
{ intro k, cases k,
{ intro e,
cases (nat.le.dest (nat.le_of_sub_eq_zero e)) with k h,
rw [h.symm, nat.add_sub_cancel_left],
apply hp },
{ intro heq,
have h : m ≤ n,
{ exact nat.le_of_lt (nat.lt_of_sub_eq_succ heq) },
rw [nat.sub_eq_iff_eq_add h] at heq,
rw [heq, nat.add_comm],
apply hn } },
delta sub_nat_nat,
exact H _ rfl
end
lemma sub_nat_nat_add_left {m n : ℕ} :
sub_nat_nat (m + n) m = of_nat n :=
begin
dunfold sub_nat_nat,
rw [nat.sub_eq_zero_of_le],
dunfold sub_nat_nat._match_1,
rw [nat.add_sub_cancel_left],
apply nat.le_add_right
end
lemma sub_nat_nat_add_right {m n : ℕ} :
sub_nat_nat m (m + n + 1) = neg_succ_of_nat n :=
calc sub_nat_nat._match_1 m (m + n + 1) (m + n + 1 - m) =
sub_nat_nat._match_1 m (m + n + 1) (m + (n + 1) - m) : by rw [nat.add_assoc]
... = sub_nat_nat._match_1 m (m + n + 1) (n + 1) : by rw [nat.add_sub_cancel_left]
... = neg_succ_of_nat n : rfl
lemma sub_nat_nat_add_add (m n k : ℕ) : sub_nat_nat (m + k) (n + k) = sub_nat_nat m n :=
sub_nat_nat_elim m n (λm n i, sub_nat_nat (m + k) (n + k) = i)
(assume i n, have n + i + k = (n + k) + i, by simp [nat.add_comm, nat.add_left_comm],
begin rw [this], exact sub_nat_nat_add_left end)
(assume i m, have m + i + 1 + k = (m + k) + i + 1, by simp [nat.add_comm, nat.add_left_comm],
begin rw [this], exact sub_nat_nat_add_right end)
lemma sub_nat_nat_of_le {m n : ℕ} (h : n ≤ m) : sub_nat_nat m n = of_nat (m - n) :=
sub_nat_nat_of_sub_eq_zero (nat.sub_eq_zero_of_le h)
lemma sub_nat_nat_of_lt {m n : ℕ} (h : m < n) : sub_nat_nat m n = -[1+ pred (n - m)] :=
have n - m = succ (pred (n - m)), from eq.symm (succ_pred_eq_of_pos (nat.sub_pos_of_lt h)),
by rewrite sub_nat_nat_of_sub_eq_succ this
/-! nat_abs -/
@[simp] def nat_abs : ℤ → ℕ
| (of_nat m) := m
| -[1+ m] := succ m
lemma nat_abs_of_nat (n : ℕ) : nat_abs ↑n = n := rfl
lemma 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 _)
lemma nat_abs_pos_of_ne_zero {a : ℤ} (h : a ≠ 0) : 0 < nat_abs a :=
(nat.eq_zero_or_pos _).resolve_left $ mt eq_zero_of_nat_abs_eq_zero h
lemma nat_abs_zero : nat_abs (0 : int) = (0 : nat) := rfl
lemma nat_abs_one : nat_abs (1 : int) = (1 : nat) := rfl
lemma nat_abs_mul_self : Π {a : ℤ}, ↑(nat_abs a * nat_abs a) = a * a
| (of_nat m) := rfl
| -[1+ m'] := rfl
@[simp] lemma nat_abs_neg (a : ℤ) : nat_abs (-a) = nat_abs a :=
by {cases a with n n, cases n; refl, refl}
lemma nat_abs_eq : Π (a : ℤ), a = nat_abs a ∨ a = -(nat_abs a)
| (of_nat m) := or.inl rfl
| -[1+ m'] := or.inr rfl
lemma eq_coe_or_neg (a : ℤ) : ∃n : ℕ, a = n ∨ a = -n := ⟨_, nat_abs_eq a⟩
/-! sign -/
def sign : ℤ → ℤ
| (n+1:ℕ) := 1
| 0 := 0
| -[1+ n] := -1
@[simp] theorem sign_zero : sign 0 = 0 := rfl
@[simp] theorem sign_one : sign 1 = 1 := rfl
@[simp] theorem sign_neg_one : sign (-1) = -1 := rfl
/-! Quotient and remainder -/
-- There are three main conventions for integer division,
-- referred here as the E, F, T rounding conventions.
-- All three pairs satisfy the identity x % y + (x / y) * y = x
-- unconditionally.
-- E-rounding: This pair satisfies 0 ≤ mod x y < nat_abs y for y ≠ 0
protected def div : ℤ → ℤ → ℤ
| (m : ℕ) (n : ℕ) := of_nat (m / n)
| (m : ℕ) -[1+ n] := -of_nat (m / succ n)
| -[1+ m] 0 := 0
| -[1+ m] (n+1:ℕ) := -[1+ m / succ n]
| -[1+ m] -[1+ n] := of_nat (succ (m / succ n))
protected def mod : ℤ → ℤ → ℤ
| (m : ℕ) n := (m % nat_abs n : ℕ)
| -[1+ m] n := sub_nat_nat (nat_abs n) (succ (m % nat_abs n))
-- F-rounding: This pair satisfies fdiv x y = floor (x / y)
def fdiv : ℤ → ℤ → ℤ
| 0 _ := 0
| (m : ℕ) (n : ℕ) := of_nat (m / n)
| (m+1:ℕ) -[1+ n] := -[1+ m / succ n]
| -[1+ m] 0 := 0
| -[1+ m] (n+1:ℕ) := -[1+ m / succ n]
| -[1+ m] -[1+ n] := of_nat (succ m / succ n)
def fmod : ℤ → ℤ → ℤ
| 0 _ := 0
| (m : ℕ) (n : ℕ) := of_nat (m % n)
| (m+1:ℕ) -[1+ n] := sub_nat_nat (m % succ n) n
| -[1+ m] (n : ℕ) := sub_nat_nat n (succ (m % n))
| -[1+ m] -[1+ n] := -of_nat (succ m % succ n)
-- T-rounding: This pair satisfies quot x y = round_to_zero (x / y)
def quot : ℤ → ℤ → ℤ
| (of_nat m) (of_nat n) := of_nat (m / n)
| (of_nat m) -[1+ n] := -of_nat (m / succ n)
| -[1+ m] (of_nat n) := -of_nat (succ m / n)
| -[1+ m] -[1+ n] := of_nat (succ m / succ n)
def rem : ℤ → ℤ → ℤ
| (of_nat m) (of_nat n) := of_nat (m % n)
| (of_nat m) -[1+ n] := of_nat (m % succ n)
| -[1+ m] (of_nat n) := -of_nat (succ m % n)
| -[1+ m] -[1+ n] := -of_nat (succ m % succ n)
instance : has_div ℤ := ⟨int.div⟩
instance : has_mod ℤ := ⟨int.mod⟩
/-! gcd -/
def gcd (m n : ℤ) : ℕ := gcd (nat_abs m) (nat_abs n)
/-
int is a ring
-/
/-! addition -/
protected lemma add_comm : ∀ a b : ℤ, a + b = b + a
| (of_nat n) (of_nat m) := by simp [nat.add_comm]
| (of_nat n) -[1+ m] := rfl
| -[1+ n] (of_nat m) := rfl
| -[1+ n] -[1+m] := by simp [nat.add_comm]
protected lemma add_zero : ∀ a : ℤ, a + 0 = a
| (of_nat n) := rfl
| -[1+ n] := rfl
protected lemma zero_add (a : ℤ) : 0 + a = a :=
int.add_comm a 0 ▸ int.add_zero a
lemma sub_nat_nat_sub {m n : ℕ} (h : n ≤ m) (k : ℕ) :
sub_nat_nat (m - n) k = sub_nat_nat m (k + n) :=
calc
sub_nat_nat (m - n) k = sub_nat_nat (m - n + n) (k + n) : by rewrite [sub_nat_nat_add_add]
... = sub_nat_nat m (k + n) : by rewrite [nat.sub_add_cancel h]
lemma sub_nat_nat_add (m n k : ℕ) : sub_nat_nat (m + n) k = of_nat m + sub_nat_nat n k :=
begin
have h := le_or_lt k n,
cases h with h' h',
{ rw [sub_nat_nat_of_le h'],
have h₂ : k ≤ m + n, exact (le_trans h' (nat.le_add_left _ _)),
rw [sub_nat_nat_of_le h₂], simp,
rw nat.add_sub_assoc h' },
rw [sub_nat_nat_of_lt h'], simp, rw [succ_pred_eq_of_pos (nat.sub_pos_of_lt h')],
transitivity, rw [← nat.sub_add_cancel (le_of_lt h')],
apply sub_nat_nat_add_add
end
lemma sub_nat_nat_add_neg_succ_of_nat (m n k : ℕ) :
sub_nat_nat m n + -[1+ k] = sub_nat_nat m (n + succ k) :=
begin
have h := le_or_lt n m,
cases h with h' h',
{ rw [sub_nat_nat_of_le h'], simp, rw [sub_nat_nat_sub h', nat.add_comm] },
have h₂ : m < n + succ k, exact nat.lt_of_lt_of_le h' (nat.le_add_right _ _),
have h₃ : m ≤ n + k, exact le_of_succ_le_succ h₂,
rw [sub_nat_nat_of_lt h', sub_nat_nat_of_lt h₂], simp [nat.add_comm],
rw [← add_succ, succ_pred_eq_of_pos (nat.sub_pos_of_lt h'), add_succ, succ_sub h₃, pred_succ],
rw [nat.add_comm n, nat.add_sub_assoc (le_of_lt h')]
end
lemma add_assoc_aux1 (m n : ℕ) :
∀ c : ℤ, of_nat m + of_nat n + c = of_nat m + (of_nat n + c)
| (of_nat k) := by simp [nat.add_assoc]
| -[1+ k] := by simp [sub_nat_nat_add]
lemma add_assoc_aux2 (m n k : ℕ) :
-[1+ m] + -[1+ n] + of_nat k = -[1+ m] + (-[1+ n] + of_nat k) :=
begin
simp [add_succ], rw [int.add_comm, sub_nat_nat_add_neg_succ_of_nat], simp [add_succ, succ_add, nat.add_comm]
end
protected lemma add_assoc : ∀ a b c : ℤ, a + b + c = a + (b + c)
| (of_nat m) (of_nat n) c := add_assoc_aux1 _ _ _
| (of_nat m) b (of_nat k) := by rw [int.add_comm, ← add_assoc_aux1, int.add_comm (of_nat k),
add_assoc_aux1, int.add_comm b]
| a (of_nat n) (of_nat k) := by rw [int.add_comm, int.add_comm a, ← add_assoc_aux1,
int.add_comm a, int.add_comm (of_nat k)]
| -[1+ m] -[1+ n] (of_nat k) := add_assoc_aux2 _ _ _
| -[1+ m] (of_nat n) -[1+ k] := by rw [int.add_comm, ← add_assoc_aux2, int.add_comm (of_nat n),
← add_assoc_aux2, int.add_comm -[1+ m] ]
| (of_nat m) -[1+ n] -[1+ k] := by rw [int.add_comm, int.add_comm (of_nat m),
int.add_comm (of_nat m), ← add_assoc_aux2,
int.add_comm -[1+ k] ]
| -[1+ m] -[1+ n] -[1+ k] := by simp [add_succ, nat.add_comm, nat.add_left_comm, neg_of_nat_of_succ]
/-! negation -/
lemma sub_nat_self : ∀ n, sub_nat_nat n n = 0
| 0 := rfl
| (succ m) := begin rw [sub_nat_nat_of_sub_eq_zero, nat.sub_self, of_nat_zero], rw nat.sub_self end
local attribute [simp] sub_nat_self
protected lemma add_left_neg : ∀ a : ℤ, -a + a = 0
| (of_nat 0) := rfl
| (of_nat (succ m)) := by simp
| -[1+ m] := by simp
protected lemma add_right_neg (a : ℤ) : a + -a = 0 :=
by rw [int.add_comm, int.add_left_neg]
/-! multiplication -/
protected lemma mul_comm : ∀ a b : ℤ, a * b = b * a
| (of_nat m) (of_nat n) := by simp [nat.mul_comm]
| (of_nat m) -[1+ n] := by simp [nat.mul_comm]
| -[1+ m] (of_nat n) := by simp [nat.mul_comm]
| -[1+ m] -[1+ n] := by simp [nat.mul_comm]
lemma of_nat_mul_neg_of_nat (m : ℕ) :
∀ n, of_nat m * neg_of_nat n = neg_of_nat (m * n)
| 0 := rfl
| (succ n) := begin unfold neg_of_nat, simp end
lemma neg_of_nat_mul_of_nat (m n : ℕ) :
neg_of_nat m * of_nat n = neg_of_nat (m * n) :=
begin rw int.mul_comm, simp [of_nat_mul_neg_of_nat, nat.mul_comm] end
lemma neg_succ_of_nat_mul_neg_of_nat (m : ℕ) :
∀ n, -[1+ m] * neg_of_nat n = of_nat (succ m * n)
| 0 := rfl
| (succ n) := begin unfold neg_of_nat, simp end
lemma neg_of_nat_mul_neg_succ_of_nat (m n : ℕ) :
neg_of_nat n * -[1+ m] = of_nat (n * succ m) :=
begin rw int.mul_comm, simp [neg_succ_of_nat_mul_neg_of_nat, nat.mul_comm] end
local attribute [simp] of_nat_mul_neg_of_nat neg_of_nat_mul_of_nat
neg_succ_of_nat_mul_neg_of_nat neg_of_nat_mul_neg_succ_of_nat
protected lemma mul_assoc : ∀ a b c : ℤ, a * b * c = a * (b * c)
| (of_nat m) (of_nat n) (of_nat k) := by simp [nat.mul_assoc]
| (of_nat m) (of_nat n) -[1+ k] := by simp [nat.mul_assoc]
| (of_nat m) -[1+ n] (of_nat k) := by simp [nat.mul_assoc]
| (of_nat m) -[1+ n] -[1+ k] := by simp [nat.mul_assoc]
| -[1+ m] (of_nat n) (of_nat k) := by simp [nat.mul_assoc]
| -[1+ m] (of_nat n) -[1+ k] := by simp [nat.mul_assoc]
| -[1+ m] -[1+ n] (of_nat k) := by simp [nat.mul_assoc]
| -[1+ m] -[1+ n] -[1+ k] := by simp [nat.mul_assoc]
protected lemma mul_zero : ∀ (a : ℤ), a * 0 = 0
| (of_nat m) := rfl
| -[1+ m] := rfl
protected lemma zero_mul (a : ℤ) : 0 * a = 0 :=
int.mul_comm a 0 ▸ int.mul_zero a
lemma neg_of_nat_eq_sub_nat_nat_zero : ∀ n, neg_of_nat n = sub_nat_nat 0 n
| 0 := rfl
| (succ n) := rfl
lemma of_nat_mul_sub_nat_nat (m n k : ℕ) :
of_nat m * sub_nat_nat n k = sub_nat_nat (m * n) (m * k) :=
begin
have h₀ : m > 0 ∨ 0 = m,
exact decidable.lt_or_eq_of_le m.zero_le,
cases h₀ with h₀ h₀,
{ have h := nat.lt_or_ge n k,
cases h with h h,
{ have h' : m * n < m * k,
exact nat.mul_lt_mul_of_pos_left h h₀,
rw [sub_nat_nat_of_lt h, sub_nat_nat_of_lt h'],
simp, rw [succ_pred_eq_of_pos (nat.sub_pos_of_lt h)],
rw [← neg_of_nat_of_succ, nat.mul_sub_left_distrib],
rw [← succ_pred_eq_of_pos (nat.sub_pos_of_lt h')], reflexivity },
have h' : m * k ≤ m * n,
exact nat.mul_le_mul_left _ h,
rw [sub_nat_nat_of_le h, sub_nat_nat_of_le h'], simp,
rw [nat.mul_sub_left_distrib]
},
have h₂ : of_nat 0 = 0, exact rfl,
subst h₀, simp [h₂, int.zero_mul, nat.zero_mul]
end
lemma neg_of_nat_add (m n : ℕ) :
neg_of_nat m + neg_of_nat n = neg_of_nat (m + n) :=
begin
cases m,
{ cases n,
{ simp, reflexivity },
simp [nat.zero_add], reflexivity },
cases n,
{ simp, reflexivity },
simp [nat.succ_add], reflexivity
end
lemma neg_succ_of_nat_mul_sub_nat_nat (m n k : ℕ) :
-[1+ m] * sub_nat_nat n k = sub_nat_nat (succ m * k) (succ m * n) :=
begin
have h := nat.lt_or_ge n k,
cases h with h h,
{ have h' : succ m * n < succ m * k,
exact nat.mul_lt_mul_of_pos_left h (nat.succ_pos m),
rw [sub_nat_nat_of_lt h, sub_nat_nat_of_le (le_of_lt h')],
simp [succ_pred_eq_of_pos (nat.sub_pos_of_lt h), nat.mul_sub_left_distrib]},
have h' : n > k ∨ k = n,
exact decidable.lt_or_eq_of_le h,
cases h' with h' h',
{ have h₁ : succ m * n > succ m * k,
exact nat.mul_lt_mul_of_pos_left h' (nat.succ_pos m),
rw [sub_nat_nat_of_le h, sub_nat_nat_of_lt h₁], simp [nat.mul_sub_left_distrib, nat.mul_comm],
rw [nat.mul_comm k, nat.mul_comm n, ← succ_pred_eq_of_pos (nat.sub_pos_of_lt h₁),
← neg_of_nat_of_succ],
reflexivity },
subst h', simp, reflexivity
end
local attribute [simp] of_nat_mul_sub_nat_nat neg_of_nat_add neg_succ_of_nat_mul_sub_nat_nat
protected lemma distrib_left : ∀ a b c : ℤ, a * (b + c) = a * b + a * c
| (of_nat m) (of_nat n) (of_nat k) := by simp [nat.left_distrib]
| (of_nat m) (of_nat n) -[1+ k] := begin simp [neg_of_nat_eq_sub_nat_nat_zero],
rw ← sub_nat_nat_add, reflexivity end
| (of_nat m) -[1+ n] (of_nat k) := begin simp [neg_of_nat_eq_sub_nat_nat_zero],
rw [int.add_comm, ← sub_nat_nat_add], reflexivity end
| (of_nat m) -[1+ n] -[1+ k] := begin simp, rw [← nat.left_distrib, add_succ, succ_add] end
| -[1+ m] (of_nat n) (of_nat k) := begin simp [nat.mul_comm], rw [← nat.right_distrib, nat.mul_comm] end
| -[1+ m] (of_nat n) -[1+ k] := begin simp [neg_of_nat_eq_sub_nat_nat_zero],
rw [int.add_comm, ← sub_nat_nat_add], reflexivity end
| -[1+ m] -[1+ n] (of_nat k) := begin simp [neg_of_nat_eq_sub_nat_nat_zero],
rw [← sub_nat_nat_add], reflexivity end
| -[1+ m] -[1+ n] -[1+ k] := begin simp, rw [← nat.left_distrib, add_succ, succ_add] end
protected lemma distrib_right (a b c : ℤ) : (a + b) * c = a * c + b * c :=
begin rw [int.mul_comm, int.distrib_left], simp [int.mul_comm] end
protected lemma zero_ne_one : (0 : int) ≠ 1 :=
assume h : 0 = 1, succ_ne_zero _ (int.of_nat.inj h).symm
lemma of_nat_sub {n m : ℕ} (h : m ≤ n) : of_nat (n - m) = of_nat n - of_nat m :=
show of_nat (n - m) = of_nat n + neg_of_nat m, from match m, h with
| 0, h := rfl
| succ m, h := show of_nat (n - succ m) = sub_nat_nat n (succ m),
by delta sub_nat_nat; rw nat.sub_eq_zero_of_le h; refl
end
protected lemma add_left_comm (a b c : ℤ) : a + (b + c) = b + (a + c) :=
by rw [← int.add_assoc, int.add_comm a, int.add_assoc]
protected lemma add_left_cancel {a b c : ℤ} (h : a + b = a + c) : b = c :=
have -a + (a + b) = -a + (a + c), by rw h,
by rwa [← int.add_assoc, ← int.add_assoc, int.add_left_neg, int.zero_add, int.zero_add] at this
protected lemma neg_add {a b : ℤ} : - (a + b) = -a + -b :=
calc - (a + b) = -(a + b) + (a + b) + -a + -b :
begin
rw [int.add_assoc, int.add_comm (-a), int.add_assoc, int.add_assoc, ← int.add_assoc b],
rw [int.add_right_neg, int.zero_add, int.add_right_neg, int.add_zero],
end
... = -a + -b : by { rw [int.add_left_neg, int.zero_add] }
lemma neg_succ_of_nat_coe' (n : ℕ) : -[1+ n] = -↑n - 1 :=
by rw [int.sub_eq_add_neg, ← int.neg_add]; refl
protected lemma coe_nat_sub {n m : ℕ} : n ≤ m → (↑(m - n) : ℤ) = ↑m - ↑n := of_nat_sub
local attribute [simp] int.sub_eq_add_neg
protected lemma sub_nat_nat_eq_coe {m n : ℕ} : sub_nat_nat m n = ↑m - ↑n :=
sub_nat_nat_elim m n (λm n i, i = ↑m - ↑n)
(λi n, by { simp [int.coe_nat_add, int.add_left_comm, int.add_assoc, int.add_right_neg], refl })
(λi n, by { rw [int.coe_nat_add, int.coe_nat_add, int.coe_nat_one, int.neg_succ_of_nat_eq,
int.sub_eq_add_neg, int.neg_add, int.neg_add, int.neg_add, ← int.add_assoc,
← int.add_assoc, int.add_right_neg, int.zero_add] })
def to_nat : ℤ → ℕ
| (n : ℕ) := n
| -[1+ n] := 0
theorem to_nat_sub (m n : ℕ) : to_nat (m - n) = m - n :=
by rw [← int.sub_nat_nat_eq_coe]; exact sub_nat_nat_elim m n
(λm n i, to_nat i = m - n)
(λi n, by rw [nat.add_sub_cancel_left]; refl)
(λi n, by rw [nat.add_assoc, nat.sub_eq_zero_of_le (nat.le_add_right _ _)]; refl)
-- Since mod x y is always nonnegative when y ≠ 0, we can make a nat version of it
def nat_mod (m n : ℤ) : ℕ := (m % n).to_nat
protected lemma one_mul : ∀ (a : ℤ), (1 : ℤ) * a = a
| (of_nat n) := show of_nat (1 * n) = of_nat n, by rw nat.one_mul
| -[1+ n] := show -[1+ (1 * n)] = -[1+ n], by rw nat.one_mul
protected lemma mul_one (a : ℤ) : a * 1 = a :=
by rw [int.mul_comm, int.one_mul]
protected lemma neg_eq_neg_one_mul : ∀ a : ℤ, -a = -1 * a
| (of_nat 0) := rfl
| (of_nat (n+1)) := show _ = -[1+ (1*n)+0], by { rw nat.one_mul, refl }
| -[1+ n] := show _ = of_nat _, by { rw nat.one_mul, refl }
theorem sign_mul_nat_abs : ∀ (a : ℤ), sign a * nat_abs a = a
| (n+1:ℕ) := int.one_mul _
| 0 := rfl
| -[1+ n] := (int.neg_eq_neg_one_mul _).symm
end int
|
5600bce5647af01a690246717267b45228ae3545 | 1abd1ed12aa68b375cdef28959f39531c6e95b84 | /src/number_theory/bernoulli_polynomials.lean | e62d2e227dc136b9b1e3eda45f503f19d8528b48 | [
"Apache-2.0"
] | permissive | jumpy4/mathlib | d3829e75173012833e9f15ac16e481e17596de0f | af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13 | refs/heads/master | 1,693,508,842,818 | 1,636,203,271,000 | 1,636,203,271,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,099 | lean | /-
Copyright (c) 2021 Ashvni Narayanan. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Ashvni Narayanan
-/
import data.nat.choose.cast
import number_theory.bernoulli
/-!
# Bernoulli polynomials
The Bernoulli polynomials (defined here : https://en.wikipedia.org/wiki/Bernoulli_polynomials)
are an important tool obtained from Bernoulli numbers.
## Mathematical overview
The $n$-th Bernoulli polynomial is defined as
$$ B_n(X) = ∑_{k = 0}^n {n \choose k} (-1)^k * B_k * X^{n - k} $$
where $B_k$ is the $k$-th Bernoulli number. The Bernoulli polynomials are generating functions,
$$ t * e^{tX} / (e^t - 1) = ∑_{n = 0}^{\infty} B_n(X) * \frac{t^n}{n!} $$
## Implementation detail
Bernoulli polynomials are defined using `bernoulli`, the Bernoulli numbers.
## Main theorems
- `sum_bernoulli_poly`: The sum of the $k^\mathrm{th}$ Bernoulli polynomial with binomial
coefficients up to n is `(n + 1) * X^n`.
- `exp_bernoulli_poly`: The Bernoulli polynomials act as generating functions for the exponential.
## TODO
- `bernoulli_poly_eval_one_neg` : $$ B_n(1 - x) = (-1)^n*B_n(x) $$
- ``bernoulli_poly_eval_one` : Follows as a consequence of `bernoulli_poly_eval_one_neg`.
-/
noncomputable theory
open_locale big_operators
open_locale nat
open nat finset
/-- The Bernoulli polynomials are defined in terms of the negative Bernoulli numbers. -/
def bernoulli_poly (n : ℕ) : polynomial ℚ :=
∑ i in range (n + 1), polynomial.monomial (n - i) ((bernoulli i) * (choose n i))
lemma bernoulli_poly_def (n : ℕ) : bernoulli_poly n =
∑ i in range (n + 1), polynomial.monomial i ((bernoulli (n - i)) * (choose n i)) :=
begin
rw [←sum_range_reflect, add_succ_sub_one, add_zero, bernoulli_poly],
apply sum_congr rfl,
rintros x hx,
rw mem_range_succ_iff at hx, rw [choose_symm hx, tsub_tsub_cancel_of_le hx],
end
namespace bernoulli_poly
/-
### examples
-/
section examples
@[simp] lemma bernoulli_poly_zero : bernoulli_poly 0 = 1 :=
by simp [bernoulli_poly]
@[simp] lemma bernoulli_poly_eval_zero (n : ℕ) : (bernoulli_poly n).eval 0 = bernoulli n :=
begin
rw [bernoulli_poly, polynomial.eval_finset_sum, sum_range_succ],
have : ∑ (x : ℕ) in range n, bernoulli x * (n.choose x) * 0 ^ (n - x) = 0,
{ apply sum_eq_zero (λ x hx, _),
have h : 0 < n - x := tsub_pos_of_lt (mem_range.1 hx),
simp [h] },
simp [this],
end
@[simp] lemma bernoulli_poly_eval_one (n : ℕ) : (bernoulli_poly n).eval 1 = bernoulli' n :=
begin
simp only [bernoulli_poly, polynomial.eval_finset_sum],
simp only [←succ_eq_add_one, sum_range_succ, mul_one, cast_one, choose_self,
(bernoulli _).mul_comm, sum_bernoulli, one_pow, mul_one, polynomial.eval_C,
polynomial.eval_monomial],
by_cases h : n = 1,
{ norm_num [h], },
{ simp [h],
exact bernoulli_eq_bernoulli'_of_ne_one h, }
end
end examples
@[simp] theorem sum_bernoulli_poly (n : ℕ) :
∑ k in range (n + 1), ((n + 1).choose k : ℚ) • bernoulli_poly k =
polynomial.monomial n (n + 1 : ℚ) :=
begin
simp_rw [bernoulli_poly_def, finset.smul_sum, finset.range_eq_Ico, ←finset.sum_Ico_Ico_comm,
finset.sum_Ico_eq_sum_range],
simp only [cast_succ, add_tsub_cancel_left, tsub_zero, zero_add, linear_map.map_add],
simp_rw [polynomial.smul_monomial, mul_comm (bernoulli _) _, smul_eq_mul, ←mul_assoc],
conv_lhs { apply_congr, skip, conv
{ apply_congr, skip,
rw [← nat.cast_mul, choose_mul ((le_tsub_iff_left $ mem_range_le H).1
$ mem_range_le H_1) (le.intro rfl), nat.cast_mul, add_comm x x_1, add_tsub_cancel_right,
mul_assoc, mul_comm, ←smul_eq_mul, ←polynomial.smul_monomial] },
rw [←sum_smul], },
rw [sum_range_succ_comm],
simp only [add_right_eq_self, cast_succ, mul_one, cast_one, cast_add, add_tsub_cancel_left,
choose_succ_self_right, one_smul, bernoulli_zero, sum_singleton, zero_add,
linear_map.map_add, range_one],
apply sum_eq_zero (λ x hx, _),
have f : ∀ x ∈ range n, ¬ n + 1 - x = 1,
{ rintros x H, rw [mem_range] at H,
rw [eq_comm],
exact ne_of_lt (nat.lt_of_lt_of_le one_lt_two (le_tsub_of_add_le_left (succ_le_succ H))) },
rw [sum_bernoulli],
have g : (ite (n + 1 - x = 1) (1 : ℚ) 0) = 0,
{ simp only [ite_eq_right_iff, one_ne_zero],
intro h₁,
exact (f x hx) h₁, },
rw [g, zero_smul],
end
open power_series
open polynomial (aeval)
variables {A : Type*} [comm_ring A] [algebra ℚ A]
-- TODO: define exponential generating functions, and use them here
-- This name should probably be updated afterwards
/-- The theorem that `∑ Bₙ(t)X^n/n!)(e^X-1)=Xe^{tX}` -/
theorem exp_bernoulli_poly' (t : A) :
mk (λ n, aeval t ((1 / n! : ℚ) • bernoulli_poly n)) * (exp A - 1) = X * rescale t (exp A) :=
begin
-- check equality of power series by checking coefficients of X^n
ext n,
-- n = 0 case solved by `simp`
cases n, { simp },
-- n ≥ 1, the coefficients is a sum to n+2, so use `sum_range_succ` to write as
-- last term plus sum to n+1
rw [coeff_succ_X_mul, coeff_rescale, coeff_exp, coeff_mul,
nat.sum_antidiagonal_eq_sum_range_succ_mk, sum_range_succ],
-- last term is zero so kill with `add_zero`
simp only [ring_hom.map_sub, tsub_self, constant_coeff_one, constant_coeff_exp,
coeff_zero_eq_constant_coeff, mul_zero, sub_self, add_zero],
-- Let's multiply both sides by (n+1)! (OK because it's a unit)
set u : units ℚ := ⟨(n+1)!, (n+1)!⁻¹,
mul_inv_cancel (by exact_mod_cast factorial_ne_zero (n+1)),
inv_mul_cancel (by exact_mod_cast factorial_ne_zero (n+1))⟩ with hu,
rw ←units.mul_right_inj (units.map (algebra_map ℚ A).to_monoid_hom u),
-- now tidy up unit mess and generally do trivial rearrangements
-- to make RHS (n+1)*t^n
rw [units.coe_map, mul_left_comm, ring_hom.to_monoid_hom_eq_coe,
ring_hom.coe_monoid_hom, ←ring_hom.map_mul, hu, units.coe_mk],
change _ = t^n * algebra_map ℚ A (((n+1)*n! : ℕ)*(1/n!)),
rw [cast_mul, mul_assoc, mul_one_div_cancel
(show (n! : ℚ) ≠ 0, from cast_ne_zero.2 (factorial_ne_zero n)), mul_one, mul_comm (t^n),
← polynomial.aeval_monomial, cast_add, cast_one],
-- But this is the RHS of `sum_bernoulli_poly`
rw [← sum_bernoulli_poly, finset.mul_sum, alg_hom.map_sum],
-- and now we have to prove a sum is a sum, but all the terms are equal.
apply finset.sum_congr rfl,
-- The rest is just trivialities, hampered by the fact that we're coercing
-- factorials and binomial coefficients between ℕ and ℚ and A.
intros i hi,
-- deal with coefficients of e^X-1
simp only [nat.cast_choose ℚ (mem_range_le hi), coeff_mk,
if_neg (mem_range_sub_ne_zero hi), one_div, alg_hom.map_smul, coeff_one, units.coe_mk,
coeff_exp, sub_zero, linear_map.map_sub, algebra.smul_mul_assoc, algebra.smul_def,
mul_right_comm _ ((aeval t) _), ←mul_assoc, ← ring_hom.map_mul, succ_eq_add_one],
-- finally cancel the Bernoulli polynomial and the algebra_map
congr',
apply congr_arg,
rw [mul_assoc, div_eq_mul_inv, ← mul_inv₀],
end
end bernoulli_poly
|
615ad747b0d5e085bbb78e4660add2f26de4403e | c777c32c8e484e195053731103c5e52af26a25d1 | /src/ring_theory/ring_hom/finite.lean | 3959d106f125fcabdc0439ae38732323e894c0e6 | [
"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 | 1,075 | lean | /-
Copyright (c) 2021 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import ring_theory.ring_hom_properties
/-!
# The meta properties of finite ring homomorphisms.
-/
namespace ring_hom
open_locale tensor_product
open tensor_product algebra.tensor_product
lemma finite_stable_under_composition :
stable_under_composition @finite :=
by { introv R hf hg, exactI hg.comp hf }
lemma finite_respects_iso :
respects_iso @finite :=
begin
apply finite_stable_under_composition.respects_iso,
introsI,
exact finite.of_surjective _ e.to_equiv.surjective,
end
lemma finite_stable_under_base_change :
stable_under_base_change @finite :=
begin
refine stable_under_base_change.mk _ finite_respects_iso _,
classical,
introv h,
resetI,
replace h : module.finite R T := by { convert h, ext, rw algebra.smul_def, refl },
suffices : module.finite S (S ⊗[R] T),
{ change module.finite _ _, convert this, ext, rw algebra.smul_def, refl },
exactI infer_instance
end
end ring_hom
|
92cafcfadf9913b2d8d53315b2b90dfccc541e37 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/normed_space/banach.lean | e3aa13499386fbc6f4bc9a286f2e0cb334d8243c | [
"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 | 21,668 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import topology.metric_space.baire
import analysis.normed_space.operator_norm
import analysis.normed_space.affine_isometry
/-!
# Banach open mapping theorem
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file contains the Banach open mapping theorem, i.e., the fact that a bijective
bounded linear map between Banach spaces has a bounded inverse.
-/
open function metric set filter finset linear_map (range ker)
open_locale classical topology big_operators nnreal
variables {𝕜 : Type*} [nontrivially_normed_field 𝕜]
{E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E]
{F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F]
(f : E →L[𝕜] F)
include 𝕜
namespace continuous_linear_map
/-- A (possibly nonlinear) right inverse to a continuous linear map, which doesn't have to be
linear itself but which satisfies a bound `‖inverse x‖ ≤ C * ‖x‖`. A surjective continuous linear
map doesn't always have a continuous linear right inverse, but it always has a nonlinear inverse
in this sense, by Banach's open mapping theorem. -/
structure nonlinear_right_inverse :=
(to_fun : F → E)
(nnnorm : ℝ≥0)
(bound' : ∀ y, ‖to_fun y‖ ≤ nnnorm * ‖y‖)
(right_inv' : ∀ y, f (to_fun y) = y)
instance : has_coe_to_fun (nonlinear_right_inverse f) (λ _, F → E) := ⟨λ fsymm, fsymm.to_fun⟩
@[simp] lemma nonlinear_right_inverse.right_inv {f : E →L[𝕜] F} (fsymm : nonlinear_right_inverse f)
(y : F) : f (fsymm y) = y :=
fsymm.right_inv' y
lemma nonlinear_right_inverse.bound {f : E →L[𝕜] F} (fsymm : nonlinear_right_inverse f) (y : F) :
‖fsymm y‖ ≤ fsymm.nnnorm * ‖y‖ :=
fsymm.bound' y
end continuous_linear_map
/-- Given a continuous linear equivalence, the inverse is in particular an instance of
`nonlinear_right_inverse` (which turns out to be linear). -/
noncomputable def continuous_linear_equiv.to_nonlinear_right_inverse (f : E ≃L[𝕜] F) :
continuous_linear_map.nonlinear_right_inverse (f : E →L[𝕜] F) :=
{ to_fun := f.inv_fun,
nnnorm := ‖(f.symm : F →L[𝕜] E)‖₊,
bound' := λ y, continuous_linear_map.le_op_norm (f.symm : F →L[𝕜] E) _,
right_inv' := f.apply_symm_apply }
noncomputable instance (f : E ≃L[𝕜] F) :
inhabited (continuous_linear_map.nonlinear_right_inverse (f : E →L[𝕜] F)) :=
⟨f.to_nonlinear_right_inverse⟩
/-! ### Proof of the Banach open mapping theorem -/
variable [complete_space F]
namespace continuous_linear_map
/--
First step of the proof of the Banach open mapping theorem (using completeness of `F`):
by Baire's theorem, there exists a ball in `E` whose image closure has nonempty interior.
Rescaling everything, it follows that any `y ∈ F` is arbitrarily well approached by
images of elements of norm at most `C * ‖y‖`.
For further use, we will only need such an element whose image
is within distance `‖y‖/2` of `y`, to apply an iterative process. -/
lemma exists_approx_preimage_norm_le (surj : surjective f) :
∃C ≥ 0, ∀y, ∃x, dist (f x) y ≤ 1/2 * ‖y‖ ∧ ‖x‖ ≤ C * ‖y‖ :=
begin
have A : (⋃n:ℕ, closure (f '' (ball 0 n))) = univ,
{ refine subset.antisymm (subset_univ _) (λy hy, _),
rcases surj y with ⟨x, hx⟩,
rcases exists_nat_gt (‖x‖) with ⟨n, hn⟩,
refine mem_Union.2 ⟨n, subset_closure _⟩,
refine (mem_image _ _ _).2 ⟨x, ⟨_, hx⟩⟩,
rwa [mem_ball, dist_eq_norm, sub_zero] },
have : ∃ (n : ℕ) x, x ∈ interior (closure (f '' (ball 0 n))) :=
nonempty_interior_of_Union_of_closed (λn, is_closed_closure) A,
simp only [mem_interior_iff_mem_nhds, metric.mem_nhds_iff] at this,
rcases this with ⟨n, a, ε, ⟨εpos, H⟩⟩,
rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩,
refine ⟨(ε/2)⁻¹ * ‖c‖ * 2 * n, _, λy, _⟩,
{ refine mul_nonneg (mul_nonneg (mul_nonneg _ (norm_nonneg _)) (by norm_num)) _,
exacts [inv_nonneg.2 (div_nonneg (le_of_lt εpos) (by norm_num)), n.cast_nonneg] },
{ by_cases hy : y = 0,
{ use 0, simp [hy] },
{ rcases rescale_to_shell hc (half_pos εpos) hy with ⟨d, hd, ydlt, leyd, dinv⟩,
let δ := ‖d‖ * ‖y‖/4,
have δpos : 0 < δ :=
div_pos (mul_pos (norm_pos_iff.2 hd) (norm_pos_iff.2 hy)) (by norm_num),
have : a + d • y ∈ ball a ε,
by simp [dist_eq_norm, lt_of_le_of_lt ydlt.le (half_lt_self εpos)],
rcases metric.mem_closure_iff.1 (H this) _ δpos with ⟨z₁, z₁im, h₁⟩,
rcases (mem_image _ _ _).1 z₁im with ⟨x₁, hx₁, xz₁⟩,
rw ← xz₁ at h₁,
rw [mem_ball, dist_eq_norm, sub_zero] at hx₁,
have : a ∈ ball a ε, by { simp, exact εpos },
rcases metric.mem_closure_iff.1 (H this) _ δpos with ⟨z₂, z₂im, h₂⟩,
rcases (mem_image _ _ _).1 z₂im with ⟨x₂, hx₂, xz₂⟩,
rw ← xz₂ at h₂,
rw [mem_ball, dist_eq_norm, sub_zero] at hx₂,
let x := x₁ - x₂,
have I : ‖f x - d • y‖ ≤ 2 * δ := calc
‖f x - d • y‖ = ‖f x₁ - (a + d • y) - (f x₂ - a)‖ :
by { congr' 1, simp only [x, f.map_sub], abel }
... ≤ ‖f x₁ - (a + d • y)‖ + ‖f x₂ - a‖ :
norm_sub_le _ _
... ≤ δ + δ : begin
apply add_le_add,
{ rw [← dist_eq_norm, dist_comm], exact le_of_lt h₁ },
{ rw [← dist_eq_norm, dist_comm], exact le_of_lt h₂ }
end
... = 2 * δ : (two_mul _).symm,
have J : ‖f (d⁻¹ • x) - y‖ ≤ 1/2 * ‖y‖ := calc
‖f (d⁻¹ • x) - y‖ = ‖d⁻¹ • f x - (d⁻¹ * d) • y‖ :
by rwa [f.map_smul _, inv_mul_cancel, one_smul]
... = ‖d⁻¹ • (f x - d • y)‖ : by rw [mul_smul, smul_sub]
... = ‖d‖⁻¹ * ‖f x - d • y‖ : by rw [norm_smul, norm_inv]
... ≤ ‖d‖⁻¹ * (2 * δ) : begin
apply mul_le_mul_of_nonneg_left I,
rw inv_nonneg,
exact norm_nonneg _
end
... = (‖d‖⁻¹ * ‖d‖) * ‖y‖ /2 : by { simp only [δ], ring }
... = ‖y‖/2 : by { rw [inv_mul_cancel, one_mul], simp [norm_eq_zero, hd] }
... = (1/2) * ‖y‖ : by ring,
rw ← dist_eq_norm at J,
have K : ‖d⁻¹ • x‖ ≤ (ε / 2)⁻¹ * ‖c‖ * 2 * ↑n * ‖y‖ := calc
‖d⁻¹ • x‖ = ‖d‖⁻¹ * ‖x₁ - x₂‖ : by rw [norm_smul, norm_inv]
... ≤ ((ε / 2)⁻¹ * ‖c‖ * ‖y‖) * (n + n) : begin
refine mul_le_mul dinv _ (norm_nonneg _) _,
{ exact le_trans (norm_sub_le _ _) (add_le_add (le_of_lt hx₁) (le_of_lt hx₂)) },
{ apply mul_nonneg (mul_nonneg _ (norm_nonneg _)) (norm_nonneg _),
exact inv_nonneg.2 (le_of_lt (half_pos εpos)) }
end
... = (ε / 2)⁻¹ * ‖c‖ * 2 * ↑n * ‖y‖ : by ring,
exact ⟨d⁻¹ • x, J, K⟩ } },
end
variable [complete_space E]
/-- The Banach open mapping theorem: if a bounded linear map between Banach spaces is onto, then
any point has a preimage with controlled norm. -/
theorem exists_preimage_norm_le (surj : surjective f) :
∃C > 0, ∀y, ∃x, f x = y ∧ ‖x‖ ≤ C * ‖y‖ :=
begin
obtain ⟨C, C0, hC⟩ := exists_approx_preimage_norm_le f surj,
/- Second step of the proof: starting from `y`, we want an exact preimage of `y`. Let `g y` be
the approximate preimage of `y` given by the first step, and `h y = y - f(g y)` the part that
has no preimage yet. We will iterate this process, taking the approximate preimage of `h y`,
leaving only `h^2 y` without preimage yet, and so on. Let `u n` be the approximate preimage
of `h^n y`. Then `u` is a converging series, and by design the sum of the series is a
preimage of `y`. This uses completeness of `E`. -/
choose g hg using hC,
let h := λy, y - f (g y),
have hle : ∀y, ‖h y‖ ≤ (1/2) * ‖y‖,
{ assume y,
rw [← dist_eq_norm, dist_comm],
exact (hg y).1 },
refine ⟨2 * C + 1, by linarith, λy, _⟩,
have hnle : ∀n:ℕ, ‖(h^[n]) y‖ ≤ (1/2)^n * ‖y‖,
{ assume n,
induction n with n IH,
{ simp only [one_div, nat.nat_zero_eq_zero, one_mul, iterate_zero_apply,
pow_zero] },
{ rw [iterate_succ'],
apply le_trans (hle _) _,
rw [pow_succ, mul_assoc],
apply mul_le_mul_of_nonneg_left IH,
norm_num } },
let u := λn, g((h^[n]) y),
have ule : ∀n, ‖u n‖ ≤ (1/2)^n * (C * ‖y‖),
{ assume n,
apply le_trans (hg _).2 _,
calc C * ‖(h^[n]) y‖ ≤ C * ((1/2)^n * ‖y‖) : mul_le_mul_of_nonneg_left (hnle n) C0
... = (1 / 2) ^ n * (C * ‖y‖) : by ring },
have sNu : summable (λn, ‖u n‖),
{ refine summable_of_nonneg_of_le (λn, norm_nonneg _) ule _,
exact summable.mul_right _ (summable_geometric_of_lt_1 (by norm_num) (by norm_num)) },
have su : summable u := summable_of_summable_norm sNu,
let x := tsum u,
have x_ineq : ‖x‖ ≤ (2 * C + 1) * ‖y‖ := calc
‖x‖ ≤ ∑'n, ‖u n‖ : norm_tsum_le_tsum_norm sNu
... ≤ ∑'n, (1/2)^n * (C * ‖y‖) :
tsum_le_tsum ule sNu (summable.mul_right _ summable_geometric_two)
... = (∑'n, (1/2)^n) * (C * ‖y‖) : tsum_mul_right
... = 2 * C * ‖y‖ : by rw [tsum_geometric_two, mul_assoc]
... ≤ 2 * C * ‖y‖ + ‖y‖ : le_add_of_nonneg_right (norm_nonneg y)
... = (2 * C + 1) * ‖y‖ : by ring,
have fsumeq : ∀n:ℕ, f (∑ i in finset.range n, u i) = y - (h^[n]) y,
{ assume n,
induction n with n IH,
{ simp [f.map_zero] },
{ rw [sum_range_succ, f.map_add, IH, iterate_succ', sub_add] } },
have : tendsto (λn, ∑ i in finset.range n, u i) at_top (𝓝 x) :=
su.has_sum.tendsto_sum_nat,
have L₁ : tendsto (λn, f (∑ i in finset.range n, u i)) at_top (𝓝 (f x)) :=
(f.continuous.tendsto _).comp this,
simp only [fsumeq] at L₁,
have L₂ : tendsto (λn, y - (h^[n]) y) at_top (𝓝 (y - 0)),
{ refine tendsto_const_nhds.sub _,
rw tendsto_iff_norm_tendsto_zero,
simp only [sub_zero],
refine squeeze_zero (λ_, norm_nonneg _) hnle _,
rw [← zero_mul ‖y‖],
refine (tendsto_pow_at_top_nhds_0_of_lt_1 _ _).mul tendsto_const_nhds; norm_num },
have feq : f x = y - 0 := tendsto_nhds_unique L₁ L₂,
rw sub_zero at feq,
exact ⟨x, feq, x_ineq⟩
end
/-- The Banach open mapping theorem: a surjective bounded linear map between Banach spaces is
open. -/
protected theorem is_open_map (surj : surjective f) : is_open_map f :=
begin
assume s hs,
rcases exists_preimage_norm_le f surj with ⟨C, Cpos, hC⟩,
refine is_open_iff.2 (λy yfs, _),
rcases mem_image_iff_bex.1 yfs with ⟨x, xs, fxy⟩,
rcases is_open_iff.1 hs x xs with ⟨ε, εpos, hε⟩,
refine ⟨ε/C, div_pos εpos Cpos, λz hz, _⟩,
rcases hC (z-y) with ⟨w, wim, wnorm⟩,
have : f (x + w) = z, by { rw [f.map_add, wim, fxy, add_sub_cancel'_right] },
rw ← this,
have : x + w ∈ ball x ε := calc
dist (x+w) x = ‖w‖ : by { rw dist_eq_norm, simp }
... ≤ C * ‖z - y‖ : wnorm
... < C * (ε/C) : begin
apply mul_lt_mul_of_pos_left _ Cpos,
rwa [mem_ball, dist_eq_norm] at hz,
end
... = ε : mul_div_cancel' _ (ne_of_gt Cpos),
exact set.mem_image_of_mem _ (hε this)
end
protected theorem quotient_map (surj : surjective f) : quotient_map f :=
(f.is_open_map surj).to_quotient_map f.continuous surj
lemma _root_.affine_map.is_open_map {P Q : Type*}
[metric_space P] [normed_add_torsor E P] [metric_space Q] [normed_add_torsor F Q]
(f : P →ᵃ[𝕜] Q) (hf : continuous f) (surj : surjective f) :
is_open_map f :=
affine_map.is_open_map_linear_iff.mp $ continuous_linear_map.is_open_map
{ cont := affine_map.continuous_linear_iff.mpr hf, .. f.linear }
(f.linear_surjective_iff.mpr surj)
/-! ### Applications of the Banach open mapping theorem -/
lemma interior_preimage (hsurj : surjective f) (s : set F) :
interior (f ⁻¹' s) = f ⁻¹' (interior s) :=
((f.is_open_map hsurj).preimage_interior_eq_interior_preimage f.continuous s).symm
lemma closure_preimage (hsurj : surjective f) (s : set F) :
closure (f ⁻¹' s) = f ⁻¹' (closure s) :=
((f.is_open_map hsurj).preimage_closure_eq_closure_preimage f.continuous s).symm
lemma frontier_preimage (hsurj : surjective f) (s : set F) :
frontier (f ⁻¹' s) = f ⁻¹' (frontier s) :=
((f.is_open_map hsurj).preimage_frontier_eq_frontier_preimage f.continuous s).symm
lemma exists_nonlinear_right_inverse_of_surjective (f : E →L[𝕜] F)
(hsurj : linear_map.range f = ⊤) : ∃ (fsymm : nonlinear_right_inverse f), 0 < fsymm.nnnorm :=
begin
choose C hC fsymm h using exists_preimage_norm_le _ (linear_map.range_eq_top.mp hsurj),
use { to_fun := fsymm,
nnnorm := ⟨C, hC.lt.le⟩,
bound' := λ y, (h y).2,
right_inv' := λ y, (h y).1 },
exact hC
end
/-- A surjective continuous linear map between Banach spaces admits a (possibly nonlinear)
controlled right inverse. In general, it is not possible to ensure that such a right inverse
is linear (take for instance the map from `E` to `E/F` where `F` is a closed subspace of `E`
without a closed complement. Then it doesn't have a continuous linear right inverse.) -/
@[irreducible] noncomputable def nonlinear_right_inverse_of_surjective
(f : E →L[𝕜] F) (hsurj : linear_map.range f = ⊤) : nonlinear_right_inverse f :=
classical.some (exists_nonlinear_right_inverse_of_surjective f hsurj)
lemma nonlinear_right_inverse_of_surjective_nnnorm_pos (f : E →L[𝕜] F)
(hsurj : linear_map.range f = ⊤) : 0 < (nonlinear_right_inverse_of_surjective f hsurj).nnnorm :=
begin
rw nonlinear_right_inverse_of_surjective,
exact classical.some_spec (exists_nonlinear_right_inverse_of_surjective f hsurj)
end
end continuous_linear_map
namespace linear_equiv
variables [complete_space E]
/-- If a bounded linear map is a bijection, then its inverse is also a bounded linear map. -/
@[continuity]
theorem continuous_symm (e : E ≃ₗ[𝕜] F) (h : continuous e) :
continuous e.symm :=
begin
rw continuous_def,
intros s hs,
rw [← e.image_eq_preimage],
rw [← e.coe_coe] at h ⊢,
exact continuous_linear_map.is_open_map ⟨↑e, h⟩ e.surjective s hs
end
/-- Associating to a linear equivalence between Banach spaces a continuous linear equivalence when
the direct map is continuous, thanks to the Banach open mapping theorem that ensures that the
inverse map is also continuous. -/
def to_continuous_linear_equiv_of_continuous (e : E ≃ₗ[𝕜] F) (h : continuous e) :
E ≃L[𝕜] F :=
{ continuous_to_fun := h,
continuous_inv_fun := e.continuous_symm h,
..e }
@[simp] lemma coe_fn_to_continuous_linear_equiv_of_continuous (e : E ≃ₗ[𝕜] F) (h : continuous e) :
⇑(e.to_continuous_linear_equiv_of_continuous h) = e := rfl
@[simp] lemma coe_fn_to_continuous_linear_equiv_of_continuous_symm (e : E ≃ₗ[𝕜] F)
(h : continuous e) :
⇑(e.to_continuous_linear_equiv_of_continuous h).symm = e.symm := rfl
end linear_equiv
namespace continuous_linear_equiv
variables [complete_space E]
/-- Convert a bijective continuous linear map `f : E →L[𝕜] F` from a Banach space to a normed space
to a continuous linear equivalence. -/
noncomputable def of_bijective (f : E →L[𝕜] F) (hinj : ker f = ⊥)
(hsurj : linear_map.range f = ⊤) : E ≃L[𝕜] F :=
(linear_equiv.of_bijective ↑f ⟨linear_map.ker_eq_bot.mp hinj, linear_map.range_eq_top.mp hsurj⟩)
.to_continuous_linear_equiv_of_continuous f.continuous
@[simp] lemma coe_fn_of_bijective (f : E →L[𝕜] F) (hinj : ker f = ⊥)
(hsurj : linear_map.range f = ⊤) : ⇑(of_bijective f hinj hsurj) = f := rfl
lemma coe_of_bijective (f : E →L[𝕜] F) (hinj : ker f = ⊥) (hsurj : linear_map.range f = ⊤) :
↑(of_bijective f hinj hsurj) = f := by { ext, refl }
@[simp] lemma of_bijective_symm_apply_apply (f : E →L[𝕜] F) (hinj : ker f = ⊥)
(hsurj : linear_map.range f = ⊤) (x : E) :
(of_bijective f hinj hsurj).symm (f x) = x :=
(of_bijective f hinj hsurj).symm_apply_apply x
@[simp] lemma of_bijective_apply_symm_apply (f : E →L[𝕜] F) (hinj : ker f = ⊥)
(hsurj : linear_map.range f = ⊤) (y : F) :
f ((of_bijective f hinj hsurj).symm y) = y :=
(of_bijective f hinj hsurj).apply_symm_apply y
end continuous_linear_equiv
namespace continuous_linear_map
variables [complete_space E]
/-- Intermediate definition used to show
`continuous_linear_map.closed_complemented_range_of_is_compl_of_ker_eq_bot`.
This is `f.coprod G.subtypeL` as an `continuous_linear_equiv`. -/
noncomputable def coprod_subtypeL_equiv_of_is_compl
(f : E →L[𝕜] F) {G : submodule 𝕜 F}
(h : is_compl (linear_map.range f) G) [complete_space G] (hker : ker f = ⊥) : (E × G) ≃L[𝕜] F :=
continuous_linear_equiv.of_bijective (f.coprod G.subtypeL)
(begin
rw ker_coprod_of_disjoint_range,
{ rw [hker, submodule.ker_subtypeL, submodule.prod_bot] },
{ rw submodule.range_subtypeL,
exact h.disjoint }
end)
(by simp only [range_coprod, h.sup_eq_top, submodule.range_subtypeL])
lemma range_eq_map_coprod_subtypeL_equiv_of_is_compl
(f : E →L[𝕜] F) {G : submodule 𝕜 F}
(h : is_compl (linear_map.range f) G) [complete_space G] (hker : ker f = ⊥) :
linear_map.range f = ((⊤ : submodule 𝕜 E).prod (⊥ : submodule 𝕜 G)).map
(f.coprod_subtypeL_equiv_of_is_compl h hker : E × G →ₗ[𝕜] F) :=
begin
rw [coprod_subtypeL_equiv_of_is_compl, _root_.coe_coe, continuous_linear_equiv.coe_of_bijective,
coe_coprod, linear_map.coprod_map_prod, submodule.map_bot, sup_bot_eq, submodule.map_top],
refl
end
/- TODO: remove the assumption `f.ker = ⊥` in the next lemma, by using the map induced by `f` on
`E / f.ker`, once we have quotient normed spaces. -/
lemma closed_complemented_range_of_is_compl_of_ker_eq_bot (f : E →L[𝕜] F) (G : submodule 𝕜 F)
(h : is_compl (linear_map.range f) G) (hG : is_closed (G : set F)) (hker : ker f = ⊥) :
is_closed (linear_map.range f : set F) :=
begin
haveI : complete_space G := hG.complete_space_coe,
let g := coprod_subtypeL_equiv_of_is_compl f h hker,
rw congr_arg coe (range_eq_map_coprod_subtypeL_equiv_of_is_compl f h hker ),
apply g.to_homeomorph.is_closed_image.2,
exact is_closed_univ.prod is_closed_singleton,
end
end continuous_linear_map
section closed_graph_thm
variables [complete_space E] (g : E →ₗ[𝕜] F)
/-- The **closed graph theorem** : a linear map between two Banach spaces whose graph is closed
is continuous. -/
theorem linear_map.continuous_of_is_closed_graph (hg : is_closed (g.graph : set $ E × F)) :
continuous g :=
begin
letI : complete_space g.graph := complete_space_coe_iff_is_complete.mpr hg.is_complete,
let φ₀ : E →ₗ[𝕜] E × F := linear_map.id.prod g,
have : function.left_inverse prod.fst φ₀ := λ x, rfl,
let φ : E ≃ₗ[𝕜] g.graph :=
(linear_equiv.of_left_inverse this).trans
(linear_equiv.of_eq _ _ g.graph_eq_range_prod.symm),
let ψ : g.graph ≃L[𝕜] E := φ.symm.to_continuous_linear_equiv_of_continuous
continuous_subtype_coe.fst,
exact (continuous_subtype_coe.comp ψ.symm.continuous).snd
end
/-- A useful form of the **closed graph theorem** : let `f` be a linear map between two Banach
spaces. To show that `f` is continuous, it suffices to show that for any convergent sequence
`uₙ ⟶ x`, if `f(uₙ) ⟶ y` then `y = f(x)`. -/
theorem linear_map.continuous_of_seq_closed_graph
(hg : ∀ (u : ℕ → E) x y, tendsto u at_top (𝓝 x) → tendsto (g ∘ u) at_top (𝓝 y) → y = g x) :
continuous g :=
begin
refine g.continuous_of_is_closed_graph (is_seq_closed.is_closed _),
rintros φ ⟨x, y⟩ hφg hφ,
refine hg (prod.fst ∘ φ) x y ((continuous_fst.tendsto _).comp hφ) _,
have : g ∘ prod.fst ∘ φ = prod.snd ∘ φ,
{ ext n,
exact (hφg n).symm },
rw this,
exact (continuous_snd.tendsto _).comp hφ
end
variable {g}
namespace continuous_linear_map
/-- Upgrade a `linear_map` to a `continuous_linear_map` using the **closed graph theorem**. -/
def of_is_closed_graph (hg : is_closed (g.graph : set $ E × F)) :
E →L[𝕜] F :=
{ to_linear_map := g,
cont := g.continuous_of_is_closed_graph hg }
@[simp] lemma coe_fn_of_is_closed_graph (hg : is_closed (g.graph : set $ E × F)) :
⇑(continuous_linear_map.of_is_closed_graph hg) = g := rfl
lemma coe_of_is_closed_graph (hg : is_closed (g.graph : set $ E × F)) :
↑(continuous_linear_map.of_is_closed_graph hg) = g := by { ext, refl }
/-- Upgrade a `linear_map` to a `continuous_linear_map` using a variation on the
**closed graph theorem**. -/
def of_seq_closed_graph
(hg : ∀ (u : ℕ → E) x y, tendsto u at_top (𝓝 x) → tendsto (g ∘ u) at_top (𝓝 y) → y = g x) :
E →L[𝕜] F :=
{ to_linear_map := g,
cont := g.continuous_of_seq_closed_graph hg }
@[simp] lemma coe_fn_of_seq_closed_graph
(hg : ∀ (u : ℕ → E) x y, tendsto u at_top (𝓝 x) → tendsto (g ∘ u) at_top (𝓝 y) → y = g x) :
⇑(continuous_linear_map.of_seq_closed_graph hg) = g := rfl
lemma coe_of_seq_closed_graph
(hg : ∀ (u : ℕ → E) x y, tendsto u at_top (𝓝 x) → tendsto (g ∘ u) at_top (𝓝 y) → y = g x) :
↑(continuous_linear_map.of_seq_closed_graph hg) = g := by { ext, refl }
end continuous_linear_map
end closed_graph_thm
|
2791059601922511102e7a5da879aea97473721f | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/algebra/group/pi.lean | a6a336c19492fd637d6e31e8f9e590af47917706 | [
"Apache-2.0"
] | permissive | hikari0108/mathlib | b7ea2b7350497ab1a0b87a09d093ecc025a50dfa | a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901 | refs/heads/master | 1,690,483,608,260 | 1,631,541,580,000 | 1,631,541,580,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,974 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Patrick Massot
-/
import data.pi
import data.set.function
import tactic.pi_instances
import algebra.group.hom_instances
/-!
# Pi instances for groups and monoids
This file defines instances for group, monoid, semigroup and related structures on Pi types.
-/
universes u v w
variable {I : Type u} -- The indexing type
variable {f : I → Type v} -- The family of types already equipped with instances
variables (x y : Π i, f i) (i : I)
namespace pi
@[to_additive]
instance semigroup [∀ i, semigroup $ f i] : semigroup (Π i : I, f i) :=
by refine_struct { mul := (*), .. }; tactic.pi_instance_derive_field
instance semigroup_with_zero [∀ i, semigroup_with_zero $ f i] :
semigroup_with_zero (Π i : I, f i) :=
by refine_struct { zero := (0 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field
@[to_additive]
instance comm_semigroup [∀ i, comm_semigroup $ f i] : comm_semigroup (Π i : I, f i) :=
by refine_struct { mul := (*), .. }; tactic.pi_instance_derive_field
@[to_additive]
instance mul_one_class [∀ i, mul_one_class $ f i] : mul_one_class (Π i : I, f i) :=
by refine_struct { one := (1 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field
@[to_additive]
instance monoid [∀ i, monoid $ f i] : monoid (Π i : I, f i) :=
by refine_struct { one := (1 : Π i, f i), mul := (*), npow := λ n x i, npow n (x i) };
tactic.pi_instance_derive_field
@[simp]
lemma pow_apply [∀ i, monoid $ f i] (n : ℕ) : (x^n) i = (x i)^n :=
begin
induction n with n ih,
{ simp, },
{ simp [pow_succ, ih], },
end
@[to_additive]
instance comm_monoid [∀ i, comm_monoid $ f i] : comm_monoid (Π i : I, f i) :=
by refine_struct { one := (1 : Π i, f i), mul := (*), npow := λ n x i, npow n (x i) };
tactic.pi_instance_derive_field
@[to_additive]
instance div_inv_monoid [∀ i, div_inv_monoid $ f i] :
div_inv_monoid (Π i : I, f i) :=
{ div_eq_mul_inv := λ x y, funext (λ i, div_eq_mul_inv (x i) (y i)),
.. pi.monoid, .. pi.has_div, .. pi.has_inv }
@[to_additive]
instance group [∀ i, group $ f i] : group (Π i : I, f i) :=
by refine_struct { one := (1 : Π i, f i), mul := (*), inv := has_inv.inv, div := has_div.div,
npow := λ n x i, npow n (x i), gpow := λ n x i, gpow n (x i) }; tactic.pi_instance_derive_field
@[to_additive]
instance comm_group [∀ i, comm_group $ f i] : comm_group (Π i : I, f i) :=
by refine_struct { one := (1 : Π i, f i), mul := (*), inv := has_inv.inv, div := has_div.div,
npow := λ n x i, npow n (x i), gpow := λ n x i, gpow n (x i) }; tactic.pi_instance_derive_field
@[to_additive add_left_cancel_semigroup]
instance left_cancel_semigroup [∀ i, left_cancel_semigroup $ f i] :
left_cancel_semigroup (Π i : I, f i) :=
by refine_struct { mul := (*) }; tactic.pi_instance_derive_field
@[to_additive add_right_cancel_semigroup]
instance right_cancel_semigroup [∀ i, right_cancel_semigroup $ f i] :
right_cancel_semigroup (Π i : I, f i) :=
by refine_struct { mul := (*) }; tactic.pi_instance_derive_field
@[to_additive add_left_cancel_monoid]
instance left_cancel_monoid [∀ i, left_cancel_monoid $ f i] :
left_cancel_monoid (Π i : I, f i) :=
by refine_struct { one := (1 : Π i, f i), mul := (*), npow := λ n x i, npow n (x i) };
tactic.pi_instance_derive_field
@[to_additive add_right_cancel_monoid]
instance right_cancel_monoid [∀ i, right_cancel_monoid $ f i] :
right_cancel_monoid (Π i : I, f i) :=
by refine_struct { one := (1 : Π i, f i), mul := (*), npow := λ n x i, npow n (x i), .. };
tactic.pi_instance_derive_field
@[to_additive add_cancel_monoid]
instance cancel_monoid [∀ i, cancel_monoid $ f i] :
cancel_monoid (Π i : I, f i) :=
by refine_struct { one := (1 : Π i, f i), mul := (*), npow := λ n x i, npow n (x i) };
tactic.pi_instance_derive_field
@[to_additive add_cancel_comm_monoid]
instance cancel_comm_monoid [∀ i, cancel_comm_monoid $ f i] :
cancel_comm_monoid (Π i : I, f i) :=
by refine_struct { one := (1 : Π i, f i), mul := (*), npow := λ n x i, npow n (x i) };
tactic.pi_instance_derive_field
instance mul_zero_class [∀ i, mul_zero_class $ f i] :
mul_zero_class (Π i : I, f i) :=
by refine_struct { zero := (0 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field
instance mul_zero_one_class [∀ i, mul_zero_one_class $ f i] :
mul_zero_one_class (Π i : I, f i) :=
by refine_struct { zero := (0 : Π i, f i), one := (1 : Π i, f i), mul := (*), .. };
tactic.pi_instance_derive_field
instance monoid_with_zero [∀ i, monoid_with_zero $ f i] :
monoid_with_zero (Π i : I, f i) :=
by refine_struct { zero := (0 : Π i, f i), one := (1 : Π i, f i), mul := (*),
npow := λ n x i, npow n (x i) }; tactic.pi_instance_derive_field
instance comm_monoid_with_zero [∀ i, comm_monoid_with_zero $ f i] :
comm_monoid_with_zero (Π i : I, f i) :=
by refine_struct { zero := (0 : Π i, f i), one := (1 : Π i, f i), mul := (*),
npow := λ n x i, npow n (x i) }; tactic.pi_instance_derive_field
section instance_lemmas
open function
variables {α β γ : Type*}
@[simp, to_additive] lemma const_one [has_one β] : const α (1 : β) = 1 := rfl
@[simp, to_additive] lemma comp_one [has_one β] {f : β → γ} : f ∘ 1 = const α (f 1) := rfl
@[simp, to_additive] lemma one_comp [has_one γ] {f : α → β} : (1 : β → γ) ∘ f = 1 := rfl
end instance_lemmas
end pi
section monoid_hom
variables (f) [Π i, mul_one_class (f i)]
/-- Evaluation of functions into an indexed collection of monoids at a point is a monoid
homomorphism.
This is `function.eval i` as a `monoid_hom`. -/
@[to_additive "Evaluation of functions into an indexed collection of additive monoids at a
point is an additive monoid homomorphism.
This is `function.eval i` as an `add_monoid_hom`.", simps]
def pi.eval_monoid_hom (i : I) : (Π i, f i) →* f i :=
{ to_fun := λ g, g i,
map_one' := pi.one_apply i,
map_mul' := λ x y, pi.mul_apply _ _ i, }
/-- `function.const` as a `monoid_hom`. -/
@[to_additive "`function.const` as an `add_monoid_hom`.", simps]
def pi.const_monoid_hom (α β : Type*) [mul_one_class β] : β →* (α → β) :=
{ to_fun := function.const α,
map_one' := rfl,
map_mul' := λ _ _, rfl }
/-- Coercion of a `monoid_hom` into a function is itself a `monoid_hom`.
See also `monoid_hom.eval`. -/
@[to_additive "Coercion of an `add_monoid_hom` into a function is itself a `add_monoid_hom`.
See also `add_monoid_hom.eval`. ", simps]
def monoid_hom.coe_fn (α β : Type*) [mul_one_class α] [comm_monoid β] : (α →* β) →* (α → β) :=
{ to_fun := λ g, g,
map_one' := rfl,
map_mul' := λ x y, rfl, }
/-- Monoid homomorphism between the function spaces `I → α` and `I → β`, induced by a monoid
homomorphism `f` between `α` and `β`. -/
@[to_additive "Additive monoid homomorphism between the function spaces `I → α` and `I → β`,
induced by an additive monoid homomorphism `f` between `α` and `β`", simps]
protected def monoid_hom.comp_left {α β : Type*} [mul_one_class α] [mul_one_class β] (f : α →* β)
(I : Type*) :
(I → α) →* (I → β) :=
{ to_fun := λ h, f ∘ h,
map_one' := by ext; simp,
map_mul' := λ _ _, by ext; simp }
end monoid_hom
section single
variables [decidable_eq I]
open pi
variables (f)
/-- The zero-preserving homomorphism including a single value
into a dependent family of values, as functions supported at a point.
This is the `zero_hom` version of `pi.single`. -/
@[simps] def zero_hom.single [Π i, has_zero $ f i] (i : I) : zero_hom (f i) (Π i, f i) :=
{ to_fun := single i,
map_zero' := single_zero i }
/-- The additive monoid homomorphism including a single additive monoid
into a dependent family of additive monoids, as functions supported at a point.
This is the `add_monoid_hom` version of `pi.single`. -/
@[simps] def add_monoid_hom.single [Π i, add_zero_class $ f i] (i : I) : f i →+ Π i, f i :=
{ to_fun := single i,
map_add' := single_op₂ (λ _, (+)) (λ _, zero_add _) _,
.. (zero_hom.single f i) }
/-- The multiplicative homomorphism including a single `mul_zero_class`
into a dependent family of `mul_zero_class`es, as functions supported at a point.
This is the `mul_hom` version of `pi.single`. -/
@[simps] def mul_hom.single [Π i, mul_zero_class $ f i] (i : I) : mul_hom (f i) (Π i, f i) :=
{ to_fun := single i,
map_mul' := single_op₂ (λ _, (*)) (λ _, zero_mul _) _, }
variables {f}
lemma pi.single_add [Π i, add_zero_class $ f i] (i : I) (x y : f i) :
single i (x + y) = single i x + single i y :=
(add_monoid_hom.single f i).map_add x y
lemma pi.single_neg [Π i, add_group $ f i] (i : I) (x : f i) :
single i (-x) = -single i x :=
(add_monoid_hom.single f i).map_neg x
lemma pi.single_sub [Π i, add_group $ f i] (i : I) (x y : f i) :
single i (x - y) = single i x - single i y :=
(add_monoid_hom.single f i).map_sub x y
lemma pi.single_mul [Π i, mul_zero_class $ f i] (i : I) (x y : f i) :
single i (x * y) = single i x * single i y :=
(mul_hom.single f i).map_mul x y
end single
section piecewise
@[to_additive]
lemma set.piecewise_mul [Π i, has_mul (f i)] (s : set I) [Π i, decidable (i ∈ s)]
(f₁ f₂ g₁ g₂ : Π i, f i) :
s.piecewise (f₁ * f₂) (g₁ * g₂) = s.piecewise f₁ g₁ * s.piecewise f₂ g₂ :=
s.piecewise_op₂ _ _ _ _ (λ _, (*))
@[to_additive]
lemma pi.piecewise_inv [Π i, has_inv (f i)] (s : set I) [Π i, decidable (i ∈ s)]
(f₁ g₁ : Π i, f i) :
s.piecewise (f₁⁻¹) (g₁⁻¹) = (s.piecewise f₁ g₁)⁻¹ :=
s.piecewise_op f₁ g₁ (λ _ x, x⁻¹)
@[to_additive]
lemma pi.piecewise_div [Π i, has_div (f i)] (s : set I) [Π i, decidable (i ∈ s)]
(f₁ f₂ g₁ g₂ : Π i, f i) :
s.piecewise (f₁ / f₂) (g₁ / g₂) = s.piecewise f₁ g₁ / s.piecewise f₂ g₂ :=
s.piecewise_op₂ _ _ _ _ (λ _, (/))
end piecewise
|
0fde502fa36b91591b76cdc985301ec139ba9f34 | 947b78d97130d56365ae2ec264df196ce769371a | /tests/lean/run/DefEqAssignBug.lean | 85ded1d24191e941f5698afc97b1cccf12c4f133 | [
"Apache-2.0"
] | permissive | shyamalschandra/lean4 | 27044812be8698f0c79147615b1d5090b9f4b037 | 6e7a883b21eaf62831e8111b251dc9b18f40e604 | refs/heads/master | 1,671,417,126,371 | 1,601,859,995,000 | 1,601,860,020,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 617 | lean | import Lean.Meta
new_frontend
open Lean
open Lean.Meta
def checkM (x : MetaM Bool) : MetaM Unit :=
unlessM x $ throwError "check failed"
def tst1 : MetaM Unit := do
let nat := mkConst `Nat
let m1 ← mkFreshExprMVar nat
let m2 ← mkFreshExprMVar (← mkArrow nat nat)
withLocalDeclD `x nat fun x => do
let t := mkApp m2 x
checkM $ isDefEq t m1
def tst2 : MetaM Unit := do
let nat := mkConst `Nat
let m1 ← mkFreshExprMVar nat
let m2 ← mkFreshExprMVar (← mkArrow nat nat)
withLocalDeclD `x nat fun x => do
let t := mkApp m2 x
checkM $ isDefEq m1 t
set_option trace.Meta true
#eval tst1
#eval tst2
|
64baeb683796554a354e3cd77e7883c907ae70e2 | 3dd1b66af77106badae6edb1c4dea91a146ead30 | /tests/lean/run/cody1.lean | 9db70c9f252332c7e37747842c08f7d3cf52f01f | [
"Apache-2.0"
] | permissive | silky/lean | 79c20c15c93feef47bb659a2cc139b26f3614642 | df8b88dca2f8da1a422cb618cd476ef5be730546 | refs/heads/master | 1,610,737,587,697 | 1,406,574,534,000 | 1,406,574,534,000 | 22,362,176 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 495 | lean | import logic
abbreviation subsets (P : Type) := P → Prop.
section
hypothesis A : Type.
hypothesis r : A → subsets A.
hypothesis i : subsets A → A.
hypothesis retract {P : subsets A} {a : A} : r (i P) a = P a.
definition delta (a:A) : Prop := ¬ (r a a).
notation `δ` := delta.
-- Crashes unifier!
theorem false_aux : ¬ (δ (i delta))
:= assume H : δ (i delta),
have H' : r (i delta) (i delta),
from eq_rec H (symm retract),
H H'.
|
ca17be2f106ea273281fc16333e4b4626020c7c1 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/run/struct_inst_exprs2.lean | f636c997197130d683d74637caeacc84f886295c | [
"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 | 572 | lean | exit
-- import data.nat.basic
open nat
structure s1 (A : Type) :=
(x : A) (y : A) (h : x = y)
structure s2 (A : Type) :=
(mul : A → A → A) (one : A)
structure s3 (A : Type) extends s1 A, s2 A :=
(mul_one : ∀ a : A, mul a one = a)
definition v1 : s1 nat := {| s1, x := 10, y := 10, h := rfl |}
definition v2 : s2 nat := {| s2, mul := nat.add, one := zero |}
definition v3 : s3 nat := {| s3, mul_one := nat.add_zero, v1, v2 |}
example : s3.x v3 = 10 := rfl
example : s3.y v3 = 10 := rfl
example : s3.mul v3 = nat.add := rfl
example : s3.one v3 = nat.zero := rfl
|
fa90317466212a854e901172a84eeebe701b7cb1 | 592ee40978ac7604005a4e0d35bbc4b467389241 | /Library/generated/mathscheme-lean/LeftInverseMagma.lean | c5ef77efff4bdfc18fc86ee4e40282c074e870f6 | [] | 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 | 6,133 | 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 LeftInverseMagma
structure LeftInverseMagma (A : Type) : Type :=
(linv : (A → (A → A)))
open LeftInverseMagma
structure Sig (AS : Type) : Type :=
(linvS : (AS → (AS → AS)))
structure Product (A : Type) : Type :=
(linvP : ((Prod A A) → ((Prod A A) → (Prod A A))))
structure Hom {A1 : Type} {A2 : Type} (Le1 : (LeftInverseMagma A1)) (Le2 : (LeftInverseMagma A2)) : Type :=
(hom : (A1 → A2))
(pres_linv : (∀ {x1 x2 : A1} , (hom ((linv Le1) x1 x2)) = ((linv Le2) (hom x1) (hom x2))))
structure RelInterp {A1 : Type} {A2 : Type} (Le1 : (LeftInverseMagma A1)) (Le2 : (LeftInverseMagma A2)) : Type 1 :=
(interp : (A1 → (A2 → Type)))
(interp_linv : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((linv Le1) x1 x2) ((linv Le2) y1 y2))))))
inductive LeftInverseMagmaTerm : Type
| linvL : (LeftInverseMagmaTerm → (LeftInverseMagmaTerm → LeftInverseMagmaTerm))
open LeftInverseMagmaTerm
inductive ClLeftInverseMagmaTerm (A : Type) : Type
| sing : (A → ClLeftInverseMagmaTerm)
| linvCl : (ClLeftInverseMagmaTerm → (ClLeftInverseMagmaTerm → ClLeftInverseMagmaTerm))
open ClLeftInverseMagmaTerm
inductive OpLeftInverseMagmaTerm (n : ℕ) : Type
| v : ((fin n) → OpLeftInverseMagmaTerm)
| linvOL : (OpLeftInverseMagmaTerm → (OpLeftInverseMagmaTerm → OpLeftInverseMagmaTerm))
open OpLeftInverseMagmaTerm
inductive OpLeftInverseMagmaTerm2 (n : ℕ) (A : Type) : Type
| v2 : ((fin n) → OpLeftInverseMagmaTerm2)
| sing2 : (A → OpLeftInverseMagmaTerm2)
| linvOL2 : (OpLeftInverseMagmaTerm2 → (OpLeftInverseMagmaTerm2 → OpLeftInverseMagmaTerm2))
open OpLeftInverseMagmaTerm2
def simplifyCl {A : Type} : ((ClLeftInverseMagmaTerm A) → (ClLeftInverseMagmaTerm A))
| (linvCl x1 x2) := (linvCl (simplifyCl x1) (simplifyCl x2))
| (sing x1) := (sing x1)
def simplifyOpB {n : ℕ} : ((OpLeftInverseMagmaTerm n) → (OpLeftInverseMagmaTerm n))
| (linvOL x1 x2) := (linvOL (simplifyOpB x1) (simplifyOpB x2))
| (v x1) := (v x1)
def simplifyOp {n : ℕ} {A : Type} : ((OpLeftInverseMagmaTerm2 n A) → (OpLeftInverseMagmaTerm2 n A))
| (linvOL2 x1 x2) := (linvOL2 (simplifyOp x1) (simplifyOp x2))
| (v2 x1) := (v2 x1)
| (sing2 x1) := (sing2 x1)
def evalB {A : Type} : ((LeftInverseMagma A) → (LeftInverseMagmaTerm → A))
| Le (linvL x1 x2) := ((linv Le) (evalB Le x1) (evalB Le x2))
def evalCl {A : Type} : ((LeftInverseMagma A) → ((ClLeftInverseMagmaTerm A) → A))
| Le (sing x1) := x1
| Le (linvCl x1 x2) := ((linv Le) (evalCl Le x1) (evalCl Le x2))
def evalOpB {A : Type} {n : ℕ} : ((LeftInverseMagma A) → ((vector A n) → ((OpLeftInverseMagmaTerm n) → A)))
| Le vars (v x1) := (nth vars x1)
| Le vars (linvOL x1 x2) := ((linv Le) (evalOpB Le vars x1) (evalOpB Le vars x2))
def evalOp {A : Type} {n : ℕ} : ((LeftInverseMagma A) → ((vector A n) → ((OpLeftInverseMagmaTerm2 n A) → A)))
| Le vars (v2 x1) := (nth vars x1)
| Le vars (sing2 x1) := x1
| Le vars (linvOL2 x1 x2) := ((linv Le) (evalOp Le vars x1) (evalOp Le vars x2))
def inductionB {P : (LeftInverseMagmaTerm → Type)} : ((∀ (x1 x2 : LeftInverseMagmaTerm) , ((P x1) → ((P x2) → (P (linvL x1 x2))))) → (∀ (x : LeftInverseMagmaTerm) , (P x)))
| plinvl (linvL x1 x2) := (plinvl _ _ (inductionB plinvl x1) (inductionB plinvl x2))
def inductionCl {A : Type} {P : ((ClLeftInverseMagmaTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClLeftInverseMagmaTerm A)) , ((P x1) → ((P x2) → (P (linvCl x1 x2))))) → (∀ (x : (ClLeftInverseMagmaTerm A)) , (P x))))
| psing plinvcl (sing x1) := (psing x1)
| psing plinvcl (linvCl x1 x2) := (plinvcl _ _ (inductionCl psing plinvcl x1) (inductionCl psing plinvcl x2))
def inductionOpB {n : ℕ} {P : ((OpLeftInverseMagmaTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpLeftInverseMagmaTerm n)) , ((P x1) → ((P x2) → (P (linvOL x1 x2))))) → (∀ (x : (OpLeftInverseMagmaTerm n)) , (P x))))
| pv plinvol (v x1) := (pv x1)
| pv plinvol (linvOL x1 x2) := (plinvol _ _ (inductionOpB pv plinvol x1) (inductionOpB pv plinvol x2))
def inductionOp {n : ℕ} {A : Type} {P : ((OpLeftInverseMagmaTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpLeftInverseMagmaTerm2 n A)) , ((P x1) → ((P x2) → (P (linvOL2 x1 x2))))) → (∀ (x : (OpLeftInverseMagmaTerm2 n A)) , (P x)))))
| pv2 psing2 plinvol2 (v2 x1) := (pv2 x1)
| pv2 psing2 plinvol2 (sing2 x1) := (psing2 x1)
| pv2 psing2 plinvol2 (linvOL2 x1 x2) := (plinvol2 _ _ (inductionOp pv2 psing2 plinvol2 x1) (inductionOp pv2 psing2 plinvol2 x2))
def stageB : (LeftInverseMagmaTerm → (Staged LeftInverseMagmaTerm))
| (linvL x1 x2) := (stage2 linvL (codeLift2 linvL) (stageB x1) (stageB x2))
def stageCl {A : Type} : ((ClLeftInverseMagmaTerm A) → (Staged (ClLeftInverseMagmaTerm A)))
| (sing x1) := (Now (sing x1))
| (linvCl x1 x2) := (stage2 linvCl (codeLift2 linvCl) (stageCl x1) (stageCl x2))
def stageOpB {n : ℕ} : ((OpLeftInverseMagmaTerm n) → (Staged (OpLeftInverseMagmaTerm n)))
| (v x1) := (const (code (v x1)))
| (linvOL x1 x2) := (stage2 linvOL (codeLift2 linvOL) (stageOpB x1) (stageOpB x2))
def stageOp {n : ℕ} {A : Type} : ((OpLeftInverseMagmaTerm2 n A) → (Staged (OpLeftInverseMagmaTerm2 n A)))
| (sing2 x1) := (Now (sing2 x1))
| (v2 x1) := (const (code (v2 x1)))
| (linvOL2 x1 x2) := (stage2 linvOL2 (codeLift2 linvOL2) (stageOp x1) (stageOp x2))
structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type :=
(linvT : ((Repr A) → ((Repr A) → (Repr A))))
end LeftInverseMagma |
8584d000a0942513ce948b51bfe9415859c2c328 | 05b503addd423dd68145d68b8cde5cd595d74365 | /src/category_theory/core.lean | 2b47b318be0b422ae7eec4ec06c734a03a5f8a3b | [
"Apache-2.0"
] | permissive | aestriplex/mathlib | 77513ff2b176d74a3bec114f33b519069788811d | e2fa8b2b1b732d7c25119229e3cdfba8370cb00f | refs/heads/master | 1,621,969,960,692 | 1,586,279,279,000 | 1,586,279,279,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,366 | lean | /-
Copyright (c) 2019 Scott Morrison All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.groupoid
import category_theory.whiskering
import category.equiv_functor
import category_theory.types
namespace category_theory
universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation
/-- The core of a category C is the groupoid whose morphisms are all the
isomorphisms of C. -/
def core (C : Type u₁) := C
variables {C : Type u₁} [𝒞 : category.{v₁} C]
include 𝒞
instance core_category : groupoid.{v₁} (core C) :=
{ hom := λ X Y : C, X ≅ Y,
inv := λ X Y f, iso.symm f,
id := λ X, iso.refl X,
comp := λ X Y Z f g, iso.trans f g }
namespace core
@[simp] lemma id_hom (X : core C) : iso.hom (𝟙 X) = 𝟙 X := rfl
@[simp] lemma comp_hom {X Y Z : core C} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).hom = f.hom ≫ g.hom :=
rfl
/-- The core of a category is naturally included in the category. -/
def inclusion : core C ⥤ C :=
{ obj := id,
map := λ X Y f, f.hom }
variables {G : Type u₂} [𝒢 : groupoid.{v₂} G]
include 𝒢
/-- A functor from a groupoid to a category C factors through the core of C. -/
-- Note that this function is not functorial
-- (consider the two functors from [0] to [1], and the natural transformation between them).
def functor_to_core (F : G ⥤ C) : G ⥤ core C :=
{ obj := λ X, F.obj X,
map := λ X Y f, ⟨F.map f, F.map (inv f)⟩ }
def forget_functor_to_core : (G ⥤ core C) ⥤ (G ⥤ C) := (whiskering_right _ _ _).obj inclusion
end core
omit 𝒞
/--
`of_equiv_functor m` lifts a type-level `equiv_functor`
to a categorical functor `core (Type u₁) ⥤ core (Type u₂)`.
-/
def of_equiv_functor (m : Type u₁ → Type u₂) [equiv_functor m] :
core (Type u₁) ⥤ core (Type u₂) :=
{ obj := m,
map := λ α β f, (equiv_functor.map_equiv m f.to_equiv).to_iso,
-- These are not very pretty.
map_id' := λ α, begin ext, exact (congr_fun (equiv_functor.map_refl _ _) x), end,
map_comp' := λ α β γ f g,
begin
ext,
simp only [equiv_functor.map_equiv_apply, equiv.to_iso_hom,
function.comp_app, core.comp_hom, types_comp],
erw [iso.to_equiv_comp, equiv_functor.map_trans],
end, }
end category_theory
|
f698f23d4189e7e27cc892a39927d6ce42561c47 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/algebra/group/inj_surj.lean | 2535390f9b0c2d7e20cc5e4b94c939854457dfcb | [
"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 | 18,855 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import algebra.group.defs
import logic.function.basic
/-!
# Lifting algebraic data classes along injective/surjective maps
This file provides definitions that are meant to deal with
situations such as the following:
Suppose that `G` is a group, and `H` is a type endowed with
`has_one H`, `has_mul H`, and `has_inv H`.
Suppose furthermore, that `f : G → H` is a surjective map
that respects the multiplication, and the unit elements.
Then `H` satisfies the group axioms.
The relevant definition in this case is `function.surjective.group`.
Dually, there is also `function.injective.group`.
And there are versions for (additive) (commutative) semigroups/monoids.
-/
namespace function
/-!
### Injective
-/
namespace injective
variables {M₁ : Type*} {M₂ : Type*} [has_mul M₁]
/-- A type endowed with `*` is a semigroup,
if it admits an injective map that preserves `*` to a semigroup.
See note [reducible non-instances]. -/
@[reducible, to_additive
"A type endowed with `+` is an additive semigroup,
if it admits an injective map that preserves `+` to an additive semigroup."]
protected def semigroup [semigroup M₂] (f : M₁ → M₂) (hf : injective f)
(mul : ∀ x y, f (x * y) = f x * f y) :
semigroup M₁ :=
{ mul_assoc := λ x y z, hf $ by erw [mul, mul, mul, mul, mul_assoc],
..‹has_mul M₁› }
/-- A type endowed with `*` is a commutative semigroup,
if it admits an injective map that preserves `*` to a commutative semigroup.
See note [reducible non-instances]. -/
@[reducible, to_additive
"A type endowed with `+` is an additive commutative semigroup,
if it admits an injective map that preserves `+` to an additive commutative semigroup."]
protected def comm_semigroup [comm_semigroup M₂] (f : M₁ → M₂) (hf : injective f)
(mul : ∀ x y, f (x * y) = f x * f y) :
comm_semigroup M₁ :=
{ mul_comm := λ x y, hf $ by erw [mul, mul, mul_comm],
.. hf.semigroup f mul }
/-- A type endowed with `*` is a left cancel semigroup,
if it admits an injective map that preserves `*` to a left cancel semigroup.
See note [reducible non-instances]. -/
@[reducible, to_additive add_left_cancel_semigroup
"A type endowed with `+` is an additive left cancel semigroup,
if it admits an injective map that preserves `+` to an additive left cancel semigroup."]
protected def left_cancel_semigroup [left_cancel_semigroup M₂] (f : M₁ → M₂) (hf : injective f)
(mul : ∀ x y, f (x * y) = f x * f y) :
left_cancel_semigroup M₁ :=
{ mul := (*),
mul_left_cancel := λ x y z H, hf $ (mul_right_inj (f x)).1 $ by erw [← mul, ← mul, H]; refl,
.. hf.semigroup f mul }
/-- A type endowed with `*` is a right cancel semigroup,
if it admits an injective map that preserves `*` to a right cancel semigroup.
See note [reducible non-instances]. -/
@[reducible, to_additive add_right_cancel_semigroup
"A type endowed with `+` is an additive right cancel semigroup,
if it admits an injective map that preserves `+` to an additive right cancel semigroup."]
protected def right_cancel_semigroup [right_cancel_semigroup M₂] (f : M₁ → M₂) (hf : injective f)
(mul : ∀ x y, f (x * y) = f x * f y) :
right_cancel_semigroup M₁ :=
{ mul := (*),
mul_right_cancel := λ x y z H, hf $ (mul_left_inj (f y)).1 $ by erw [← mul, ← mul, H]; refl,
.. hf.semigroup f mul }
variables [has_one M₁]
/-- A type endowed with `1` and `*` is a mul_one_class,
if it admits an injective map that preserves `1` and `*` to a mul_one_class.
See note [reducible non-instances]. -/
@[reducible, to_additive
"A type endowed with `0` and `+` is an add_zero_class,
if it admits an injective map that preserves `0` and `+` to an add_zero_class."]
protected def mul_one_class [mul_one_class M₂] (f : M₁ → M₂) (hf : injective f)
(one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) :
mul_one_class M₁ :=
{ one_mul := λ x, hf $ by erw [mul, one, one_mul],
mul_one := λ x, hf $ by erw [mul, one, mul_one],
..‹has_one M₁›, ..‹has_mul M₁› }
/-- A type endowed with `1` and `*` is a monoid,
if it admits an injective map that preserves `1` and `*` to a monoid.
See note [reducible non-instances]. -/
@[reducible, to_additive
"A type endowed with `0` and `+` is an additive monoid,
if it admits an injective map that preserves `0` and `+` to an additive monoid."]
protected def monoid [monoid M₂] (f : M₁ → M₂) (hf : injective f)
(one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) :
monoid M₁ :=
{ .. hf.semigroup f mul, .. hf.mul_one_class f one mul }
/-- A type endowed with `1` and `*` is a monoid,
if it admits an injective map that preserves `1` and `*` to a monoid.
This version takes a custom `npow` as a `[has_pow M₁ ℕ]` argument.
See note [reducible non-instances]. -/
@[reducible, to_additive add_monoid_smul
"A type endowed with `0` and `+` is an additive monoid,
if it admits an injective map that preserves `0` and `+` to an additive monoid.
This version takes a custom `nsmul` as a `[has_scalar ℕ M₁]` argument."]
protected def monoid_pow [has_pow M₁ ℕ] [monoid M₂] (f : M₁ → M₂) (hf : injective f)
(one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) :
monoid M₁ :=
{ npow := λ n x, x ^ n,
npow_zero' := λ x, hf $ by erw [npow, one, pow_zero],
npow_succ' := λ n x, hf $ by erw [npow, pow_succ, mul, npow],
.. hf.monoid f one mul }
/-- A type endowed with `1` and `*` is a left cancel monoid,
if it admits an injective map that preserves `1` and `*` to a left cancel monoid.
See note [reducible non-instances]. -/
@[reducible, to_additive add_left_cancel_monoid
"A type endowed with `0` and `+` is an additive left cancel monoid,
if it admits an injective map that preserves `0` and `+` to an additive left cancel monoid."]
protected def left_cancel_monoid [left_cancel_monoid M₂] (f : M₁ → M₂) (hf : injective f)
(one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) :
left_cancel_monoid M₁ :=
{ .. hf.left_cancel_semigroup f mul, .. hf.monoid f one mul }
/-- A type endowed with `1` and `*` is a right cancel monoid,
if it admits an injective map that preserves `1` and `*` to a right cancel monoid.
See note [reducible non-instances]. -/
@[reducible, to_additive add_right_cancel_monoid
"A type endowed with `0` and `+` is an additive left cancel monoid,
if it admits an injective map that preserves `0` and `+` to an additive left cancel monoid."]
protected def right_cancel_monoid [right_cancel_monoid M₂] (f : M₁ → M₂) (hf : injective f)
(one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) :
right_cancel_monoid M₁ :=
{ .. hf.right_cancel_semigroup f mul, .. hf.monoid f one mul }
/-- A type endowed with `1` and `*` is a cancel monoid,
if it admits an injective map that preserves `1` and `*` to a cancel monoid.
See note [reducible non-instances]. -/
@[reducible, to_additive add_cancel_monoid
"A type endowed with `0` and `+` is an additive left cancel monoid,
if it admits an injective map that preserves `0` and `+` to an additive left cancel monoid."]
protected def cancel_monoid [cancel_monoid M₂] (f : M₁ → M₂) (hf : injective f)
(one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) :
cancel_monoid M₁ :=
{ .. hf.left_cancel_monoid f one mul, .. hf.right_cancel_monoid f one mul }
/-- A type endowed with `1` and `*` is a commutative monoid,
if it admits an injective map that preserves `1` and `*` to a commutative monoid.
See note [reducible non-instances]. -/
@[reducible, to_additive
"A type endowed with `0` and `+` is an additive commutative monoid,
if it admits an injective map that preserves `0` and `+` to an additive commutative monoid."]
protected def comm_monoid [comm_monoid M₂] (f : M₁ → M₂) (hf : injective f)
(one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) :
comm_monoid M₁ :=
{ .. hf.comm_semigroup f mul, .. hf.monoid f one mul }
/-- A type endowed with `1` and `*` is a cancel commutative monoid,
if it admits an injective map that preserves `1` and `*` to a cancel commutative monoid.
See note [reducible non-instances]. -/
@[reducible, to_additive add_cancel_comm_monoid
"A type endowed with `0` and `+` is an additive cancel commutative monoid,
if it admits an injective map that preserves `0` and `+` to an additive cancel commutative monoid."]
protected def cancel_comm_monoid [cancel_comm_monoid M₂] (f : M₁ → M₂) (hf : injective f)
(one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) :
cancel_comm_monoid M₁ :=
{ .. hf.left_cancel_semigroup f mul, .. hf.comm_monoid f one mul }
variables [has_inv M₁] [has_div M₁]
/-- A type endowed with `1`, `*`, `⁻¹`, and `/` is a `div_inv_monoid`
if it admits an injective map that preserves `1`, `*`, `⁻¹`, and `/` to a `div_inv_monoid`.
See note [reducible non-instances]. -/
@[reducible, to_additive sub_neg_monoid
"A type endowed with `0`, `+`, unary `-`, and binary `-` is a `sub_neg_monoid`
if it admits an injective map that preserves `0`, `+`, unary `-`, and binary `-` to
a `sub_neg_monoid`."]
protected def div_inv_monoid [div_inv_monoid M₂] (f : M₁ → M₂) (hf : injective f)
(one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹)
(div : ∀ x y, f (x / y) = f x / f y) :
div_inv_monoid M₁ :=
{ div_eq_mul_inv := λ x y, hf $ by erw [div, mul, inv, div_eq_mul_inv],
.. hf.monoid f one mul, .. ‹has_inv M₁›, .. ‹has_div M₁› }
/-- A type endowed with `1`, `*`, `⁻¹`, and `/` is a `div_inv_monoid`
if it admits an injective map that preserves `1`, `*`, `⁻¹`, and `/` to a `div_inv_monoid`.
This version takes custom `npow` and `zpow` as `[has_pow M₁ ℕ]` and `[has_pow M₁ ℤ]` arguments.
See note [reducible non-instances]. -/
@[reducible, to_additive sub_neg_monoid_smul
"A type endowed with `0`, `+`, unary `-`, and binary `-` is a `sub_neg_monoid`
if it admits an injective map that preserves `0`, `+`, unary `-`, and binary `-` to
a `sub_neg_monoid`.
This version takes custom `nsmul` and `zsmul` as `[has_scalar ℕ M₁]` and
`[has_scalar ℤ M₁]` arguments."]
protected def div_inv_monoid_pow [has_pow M₁ ℕ] [has_pow M₁ ℤ] [div_inv_monoid M₂]
(f : M₁ → M₂) (hf : injective f)
(one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹)
(div : ∀ x y, f (x / y) = f x / f y) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n)
(zpow : ∀ x (n : ℤ), f (x ^ n) = f x ^ n) :
div_inv_monoid M₁ :=
{ zpow := λ n x, x ^ n,
zpow_zero' := λ x, hf $ by erw [zpow, zpow_zero, one],
zpow_succ' := λ n x, hf $ by erw [zpow, mul, zpow_of_nat, pow_succ, zpow, zpow_of_nat],
zpow_neg' := λ n x, hf $ by erw [zpow, zpow_neg_succ_of_nat, inv, zpow, zpow_coe_nat],
.. hf.monoid_pow f one mul npow,
.. hf.div_inv_monoid f one mul inv div }
/-- A type endowed with `1`, `*` and `⁻¹` is a group,
if it admits an injective map that preserves `1`, `*` and `⁻¹` to a group.
See note [reducible non-instances]. -/
@[reducible, to_additive
"A type endowed with `0` and `+` is an additive group,
if it admits an injective map that preserves `0` and `+` to an additive group."]
protected def group [group M₂] (f : M₁ → M₂) (hf : injective f)
(one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹)
(div : ∀ x y, f (x / y) = f x / f y) :
group M₁ :=
{ mul_left_inv := λ x, hf $ by erw [mul, inv, mul_left_inv, one],
.. hf.div_inv_monoid f one mul inv div }
/-- A type endowed with `1`, `*` and `⁻¹` is a group,
if it admits an injective map that preserves `1`, `*` and `⁻¹` to a group.
This version takes custom `npow` and `zpow` as `[has_pow M₁ ℕ]` and `[has_pow M₁ ℤ]` arguments.
See note [reducible non-instances]. -/
@[reducible, to_additive add_group_smul
"A type endowed with `0` and `+` is an additive group,
if it admits an injective map that preserves `0` and `+` to an additive group.
This version takes custom `nsmul` and `zsmul` as `[has_scalar ℕ M₁]` and
`[has_scalar ℤ M₁]` arguments."]
protected def group_pow [has_pow M₁ ℕ] [has_pow M₁ ℤ] [group M₂] (f : M₁ → M₂) (hf : injective f)
(one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹)
(div : ∀ x y, f (x / y) = f x / f y) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n)
(zpow : ∀ x (n : ℤ), f (x ^ n) = f x ^ n) :
group M₁ :=
{ .. hf.div_inv_monoid_pow f one mul inv div npow zpow,
.. hf.group f one mul inv div }
/-- A type endowed with `1`, `*` and `⁻¹` is a commutative group,
if it admits an injective map that preserves `1`, `*` and `⁻¹` to a commutative group.
See note [reducible non-instances]. -/
@[reducible, to_additive
"A type endowed with `0` and `+` is an additive commutative group,
if it admits an injective map that preserves `0` and `+` to an additive commutative group."]
protected def comm_group [comm_group M₂] (f : M₁ → M₂) (hf : injective f)
(one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹)
(div : ∀ x y, f (x / y) = f x / f y) :
comm_group M₁ :=
{ .. hf.comm_monoid f one mul, .. hf.group f one mul inv div }
end injective
/-!
### Surjective
-/
namespace surjective
variables {M₁ : Type*} {M₂ : Type*} [has_mul M₂]
/-- A type endowed with `*` is a semigroup,
if it admits a surjective map that preserves `*` from a semigroup.
See note [reducible non-instances]. -/
@[reducible, to_additive
"A type endowed with `+` is an additive semigroup,
if it admits a surjective map that preserves `+` from an additive semigroup."]
protected def semigroup [semigroup M₁] (f : M₁ → M₂) (hf : surjective f)
(mul : ∀ x y, f (x * y) = f x * f y) :
semigroup M₂ :=
{ mul_assoc := hf.forall₃.2 $ λ x y z, by simp only [← mul, mul_assoc],
..‹has_mul M₂› }
/-- A type endowed with `*` is a commutative semigroup,
if it admits a surjective map that preserves `*` from a commutative semigroup.
See note [reducible non-instances]. -/
@[reducible, to_additive
"A type endowed with `+` is an additive commutative semigroup,
if it admits a surjective map that preserves `+` from an additive commutative semigroup."]
protected def comm_semigroup [comm_semigroup M₁] (f : M₁ → M₂) (hf : surjective f)
(mul : ∀ x y, f (x * y) = f x * f y) :
comm_semigroup M₂ :=
{ mul_comm := hf.forall₂.2 $ λ x y, by erw [← mul, ← mul, mul_comm],
.. hf.semigroup f mul }
variables [has_one M₂]
/-- A type endowed with `1` and `*` is a mul_one_class,
if it admits a surjective map that preserves `1` and `*` from a mul_one_class.
See note [reducible non-instances]. -/
@[reducible, to_additive
"A type endowed with `0` and `+` is an add_zero_class,
if it admits a surjective map that preserves `0` and `+` to an add_zero_class."]
protected def mul_one_class [mul_one_class M₁] (f : M₁ → M₂) (hf : surjective f)
(one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) :
mul_one_class M₂ :=
{ one_mul := hf.forall.2 $ λ x, by erw [← one, ← mul, one_mul],
mul_one := hf.forall.2 $ λ x, by erw [← one, ← mul, mul_one],
..‹has_one M₂›, ..‹has_mul M₂› }
/-- A type endowed with `1` and `*` is a monoid,
if it admits a surjective map that preserves `1` and `*` from a monoid.
See note [reducible non-instances]. -/
@[reducible, to_additive
"A type endowed with `0` and `+` is an additive monoid,
if it admits a surjective map that preserves `0` and `+` to an additive monoid."]
protected def monoid [monoid M₁] (f : M₁ → M₂) (hf : surjective f)
(one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) :
monoid M₂ :=
{ .. hf.semigroup f mul, .. hf.mul_one_class f one mul }
/-- A type endowed with `1` and `*` is a commutative monoid,
if it admits a surjective map that preserves `1` and `*` from a commutative monoid.
See note [reducible non-instances]. -/
@[reducible, to_additive
"A type endowed with `0` and `+` is an additive commutative monoid,
if it admits a surjective map that preserves `0` and `+` to an additive commutative monoid."]
protected def comm_monoid [comm_monoid M₁] (f : M₁ → M₂) (hf : surjective f)
(one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) :
comm_monoid M₂ :=
{ .. hf.comm_semigroup f mul, .. hf.monoid f one mul }
variables [has_inv M₂] [has_div M₂]
/-- A type endowed with `1`, `*`, `⁻¹`, and `/` is a `div_inv_monoid`,
if it admits a surjective map that preserves `1`, `*`, `⁻¹`, and `/` from a `div_inv_monoid`
See note [reducible non-instances]. -/
@[reducible, to_additive sub_neg_monoid
"A type endowed with `0`, `+`, and `-` (unary and binary) is an additive group,
if it admits a surjective map that preserves `0`, `+`, and `-` from a `sub_neg_monoid`"]
protected def div_inv_monoid [div_inv_monoid M₁] (f : M₁ → M₂) (hf : surjective f)
(one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹)
(div : ∀ x y, f (x / y) = f x / f y) :
div_inv_monoid M₂ :=
{ div_eq_mul_inv := hf.forall₂.2 $ λ x y, by erw [← inv, ← mul, ← div, div_eq_mul_inv],
.. hf.monoid f one mul, .. ‹has_div M₂›, .. ‹has_inv M₂› }
/-- A type endowed with `1`, `*`, `⁻¹`, and `/` is a group,
if it admits a surjective map that preserves `1`, `*`, `⁻¹`, and `/` from a group.
See note [reducible non-instances]. -/
@[reducible, to_additive
"A type endowed with `0`, `+`, and unary `-` is an additive group,
if it admits a surjective map that preserves `0`, `+`, and `-` from an additive group."]
protected def group [group M₁] (f : M₁ → M₂) (hf : surjective f)
(one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹)
(div : ∀ x y, f (x / y) = f x / f y) :
group M₂ :=
{ mul_left_inv := hf.forall.2 $ λ x, by erw [← inv, ← mul, mul_left_inv, one]; refl,
.. hf.div_inv_monoid f one mul inv div }
/-- A type endowed with `1`, `*`, `⁻¹`, and `/` is a commutative group,
if it admits a surjective map that preserves `1`, `*`, `⁻¹`, and `/` from a commutative group.
See note [reducible non-instances]. -/
@[reducible, to_additive
"A type endowed with `0` and `+` is an additive commutative group,
if it admits a surjective map that preserves `0` and `+` to an additive commutative group."]
protected def comm_group [comm_group M₁] (f : M₁ → M₂) (hf : surjective f)
(one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹)
(div : ∀ x y, f (x / y) = f x / f y) :
comm_group M₂ :=
{ .. hf.comm_monoid f one mul, .. hf.group f one mul inv div }
end surjective
end function
|
d3a858755f9391a529133e98fbfc3d6830c806b2 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/order/filter/lift.lean | 97fbee9aae907301e7268800e4f5ab08cfad81fe | [
"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 | 16,558 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
Lift filters along filter and set functions.
-/
import order.filter.basic
open set
open_locale classical
namespace filter
variables {α : Type*} {β : Type*} {γ : Type*} {ι : Sort*}
section lift
/-- A variant on `bind` using a function `g` taking a set instead of a member of `α`.
This is essentially a push-forward along a function mapping each set to a filter. -/
protected def lift (f : filter α) (g : set α → filter β) :=
⨅s ∈ f, g s
variables {f f₁ f₂ : filter α} {g g₁ g₂ : set α → filter β}
lemma mem_lift_sets (hg : monotone g) {s : set β} :
s ∈ f.lift g ↔ ∃t∈f, s ∈ g t :=
mem_binfi
(assume s hs t ht, ⟨s ∩ t, inter_mem_sets hs ht,
hg $ inter_subset_left s t, hg $ inter_subset_right s t⟩)
⟨univ, univ_mem_sets⟩
lemma mem_lift {s : set β} {t : set α} (ht : t ∈ f) (hs : s ∈ g t) :
s ∈ f.lift g :=
le_principal_iff.mp $ show f.lift g ≤ principal s,
from infi_le_of_le t $ infi_le_of_le ht $ le_principal_iff.mpr hs
lemma lift_le {f : filter α} {g : set α → filter β} {h : filter β} {s : set α}
(hs : s ∈ f) (hg : g s ≤ h) : f.lift g ≤ h :=
infi_le_of_le s $ infi_le_of_le hs $ hg
lemma le_lift {f : filter α} {g : set α → filter β} {h : filter β}
(hh : ∀s∈f, h ≤ g s) : h ≤ f.lift g :=
le_infi $ assume s, le_infi $ assume hs, hh s hs
lemma lift_mono (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.lift g₁ ≤ f₂.lift g₂ :=
infi_le_infi $ assume s, infi_le_infi2 $ assume hs, ⟨hf hs, hg s⟩
lemma lift_mono' (hg : ∀s∈f, g₁ s ≤ g₂ s) : f.lift g₁ ≤ f.lift g₂ :=
infi_le_infi $ assume s, infi_le_infi $ assume hs, hg s hs
lemma map_lift_eq {m : β → γ} (hg : monotone g) : map m (f.lift g) = f.lift (map m ∘ g) :=
have monotone (map m ∘ g),
from map_mono.comp hg,
filter_eq $ set.ext $
by simp only [mem_lift_sets hg, mem_lift_sets this, exists_prop, forall_const, mem_map, iff_self, function.comp_app]
lemma comap_lift_eq {m : γ → β} (hg : monotone g) : comap m (f.lift g) = f.lift (comap m ∘ g) :=
have monotone (comap m ∘ g),
from comap_mono.comp hg,
filter_eq $ set.ext begin
simp only [mem_lift_sets hg, mem_lift_sets this, comap, mem_lift_sets, mem_set_of_eq, exists_prop,
function.comp_apply],
exact λ s,
⟨λ ⟨b, ⟨a, ha, hb⟩, hs⟩, ⟨a, ha, b, hb, hs⟩,
λ ⟨a, ha, b, hb, hs⟩, ⟨b, ⟨a, ha, hb⟩, hs⟩⟩
end
theorem comap_lift_eq2 {m : β → α} {g : set β → filter γ} (hg : monotone g) :
(comap m f).lift g = f.lift (g ∘ preimage m) :=
le_antisymm
(le_infi $ assume s, le_infi $ assume hs,
infi_le_of_le (preimage m s) $ infi_le _ ⟨s, hs, subset.refl _⟩)
(le_infi $ assume s, le_infi $ assume ⟨s', hs', (h_sub : preimage m s' ⊆ s)⟩,
infi_le_of_le s' $ infi_le_of_le hs' $ hg h_sub)
lemma map_lift_eq2 {g : set β → filter γ} {m : α → β} (hg : monotone g) :
(map m f).lift g = f.lift (g ∘ image m) :=
le_antisymm
(infi_le_infi2 $ assume s, ⟨image m s,
infi_le_infi2 $ assume hs, ⟨
f.sets_of_superset hs $ assume a h, mem_image_of_mem _ h,
le_refl _⟩⟩)
(infi_le_infi2 $ assume t, ⟨preimage m t,
infi_le_infi2 $ assume ht, ⟨ht,
hg $ assume x, assume h : x ∈ m '' preimage m t,
let ⟨y, hy, h_eq⟩ := h in
show x ∈ t, from h_eq ▸ hy⟩⟩)
lemma lift_comm {g : filter β} {h : set α → set β → filter γ} :
f.lift (λs, g.lift (h s)) = g.lift (λt, f.lift (λs, h s t)) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume hi, le_infi $ assume j, le_infi $ assume hj,
infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi)
(le_infi $ assume i, le_infi $ assume hi, le_infi $ assume j, le_infi $ assume hj,
infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi)
lemma lift_assoc {h : set β → filter γ} (hg : monotone g) :
(f.lift g).lift h = f.lift (λs, (g s).lift h) :=
le_antisymm
(le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht,
infi_le_of_le t $ infi_le _ $ (mem_lift_sets hg).mpr ⟨_, hs, ht⟩)
(le_infi $ assume t, le_infi $ assume ht,
let ⟨s, hs, h'⟩ := (mem_lift_sets hg).mp ht in
infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le t $ infi_le _ h')
lemma lift_lift_same_le_lift {g : set α → set α → filter β} :
f.lift (λs, f.lift (g s)) ≤ f.lift (λs, g s s) :=
le_infi $ assume s, le_infi $ assume hs, infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le _ hs
lemma lift_lift_same_eq_lift {g : set α → set α → filter β}
(hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)) :
f.lift (λs, f.lift (g s)) = f.lift (λs, g s s) :=
le_antisymm
lift_lift_same_le_lift
(le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht,
infi_le_of_le (s ∩ t) $
infi_le_of_le (inter_mem_sets hs ht) $
calc g (s ∩ t) (s ∩ t) ≤ g s (s ∩ t) : hg₂ (s ∩ t) (inter_subset_left _ _)
... ≤ g s t : hg₁ s (inter_subset_right _ _))
lemma lift_principal {s : set α} (hg : monotone g) :
(principal s).lift g = g s :=
le_antisymm
(infi_le_of_le s $ infi_le _ $ subset.refl _)
(le_infi $ assume t, le_infi $ assume hi, hg hi)
theorem monotone_lift [preorder γ] {f : γ → filter α} {g : γ → set α → filter β}
(hf : monotone f) (hg : monotone g) : monotone (λc, (f c).lift (g c)) :=
assume a b h, lift_mono (hf h) (hg h)
lemma lift_ne_bot_iff (hm : monotone g) : (f.lift g ≠ ⊥) ↔ (∀s∈f, g s ≠ ⊥) :=
begin
rw [filter.lift, infi_subtype', infi_ne_bot_iff_of_directed', subtype.forall'],
{ exact ⟨⟨univ, univ_mem_sets⟩⟩ },
{ rintros ⟨s, hs⟩ ⟨t, ht⟩,
exact ⟨⟨s ∩ t, inter_mem_sets hs ht⟩, hm (inter_subset_left s t), hm (inter_subset_right s t)⟩ }
end
@[simp] lemma lift_const {f : filter α} {g : filter β} : f.lift (λx, g) = g :=
le_antisymm (lift_le univ_mem_sets $ le_refl g) (le_lift $ assume s hs, le_refl g)
@[simp] lemma lift_inf {f : filter α} {g h : set α → filter β} :
f.lift (λx, g x ⊓ h x) = f.lift g ⊓ f.lift h :=
by simp only [filter.lift, infi_inf_eq, eq_self_iff_true]
@[simp] lemma lift_principal2 {f : filter α} : f.lift principal = f :=
le_antisymm
(assume s hs, mem_lift hs (mem_principal_self s))
(le_infi $ assume s, le_infi $ assume hs, by simp only [hs, le_principal_iff])
lemma lift_infi {f : ι → filter α} {g : set α → filter β}
(hι : nonempty ι) (hg : ∀{s t}, g s ⊓ g t = g (s ∩ t)) : (infi f).lift g = (⨅i, (f i).lift g) :=
le_antisymm
(le_infi $ assume i, lift_mono (infi_le _ _) (le_refl _))
(assume s,
have g_mono : monotone g,
from assume s t h, le_of_inf_eq $ eq.trans hg $ congr_arg g $ inter_eq_self_of_subset_left h,
have ∀t∈(infi f), (⨅ (i : ι), filter.lift (f i) g) ≤ g t,
from assume t ht, infi_sets_induct ht
(let ⟨i⟩ := hι in infi_le_of_le i $ infi_le_of_le univ $ infi_le _ univ_mem_sets)
(assume i s₁ s₂ hs₁ hs₂,
@hg s₁ s₂ ▸ le_inf (infi_le_of_le i $ infi_le_of_le s₁ $ infi_le _ hs₁) hs₂)
(assume s₁ s₂ hs₁ hs₂, le_trans hs₂ $ g_mono hs₁),
begin
simp only [mem_lift_sets g_mono, exists_imp_distrib],
exact assume t ht hs, this t ht hs
end)
end lift
section lift'
/-- Specialize `lift` to functions `set α → set β`. This can be viewed as a generalization of `map`.
This is essentially a push-forward along a function mapping each set to a set. -/
protected def lift' (f : filter α) (h : set α → set β) :=
f.lift (principal ∘ h)
variables {f f₁ f₂ : filter α} {h h₁ h₂ : set α → set β}
lemma mem_lift' {t : set α} (ht : t ∈ f) : h t ∈ (f.lift' h) :=
le_principal_iff.mp $ show f.lift' h ≤ principal (h t),
from infi_le_of_le t $ infi_le_of_le ht $ le_refl _
lemma mem_lift'_sets (hh : monotone h) {s : set β} : s ∈ (f.lift' h) ↔ (∃t∈f, h t ⊆ s) :=
mem_lift_sets $ monotone_principal.comp hh
lemma lift'_le {f : filter α} {g : set α → set β} {h : filter β} {s : set α}
(hs : s ∈ f) (hg : principal (g s) ≤ h) : f.lift' g ≤ h :=
lift_le hs hg
lemma lift'_mono (hf : f₁ ≤ f₂) (hh : h₁ ≤ h₂) : f₁.lift' h₁ ≤ f₂.lift' h₂ :=
lift_mono hf $ assume s, principal_mono.mpr $ hh s
lemma lift'_mono' (hh : ∀s∈f, h₁ s ⊆ h₂ s) : f.lift' h₁ ≤ f.lift' h₂ :=
infi_le_infi $ assume s, infi_le_infi $ assume hs, principal_mono.mpr $ hh s hs
lemma lift'_cong (hh : ∀s∈f, h₁ s = h₂ s) : f.lift' h₁ = f.lift' h₂ :=
le_antisymm (lift'_mono' $ assume s hs, le_of_eq $ hh s hs) (lift'_mono' $ assume s hs, le_of_eq $ (hh s hs).symm)
lemma map_lift'_eq {m : β → γ} (hh : monotone h) : map m (f.lift' h) = f.lift' (image m ∘ h) :=
calc map m (f.lift' h) = f.lift (map m ∘ principal ∘ h) :
map_lift_eq $ monotone_principal.comp hh
... = f.lift' (image m ∘ h) : by simp only [(∘), filter.lift', map_principal, eq_self_iff_true]
lemma map_lift'_eq2 {g : set β → set γ} {m : α → β} (hg : monotone g) :
(map m f).lift' g = f.lift' (g ∘ image m) :=
map_lift_eq2 $ monotone_principal.comp hg
theorem comap_lift'_eq {m : γ → β} (hh : monotone h) :
comap m (f.lift' h) = f.lift' (preimage m ∘ h) :=
calc comap m (f.lift' h) = f.lift (comap m ∘ principal ∘ h) :
comap_lift_eq $ monotone_principal.comp hh
... = f.lift' (preimage m ∘ h) : by simp only [(∘), filter.lift', comap_principal, eq_self_iff_true]
theorem comap_lift'_eq2 {m : β → α} {g : set β → set γ} (hg : monotone g) :
(comap m f).lift' g = f.lift' (g ∘ preimage m) :=
comap_lift_eq2 $ monotone_principal.comp hg
lemma lift'_principal {s : set α} (hh : monotone h) :
(principal s).lift' h = principal (h s) :=
lift_principal $ monotone_principal.comp hh
lemma principal_le_lift' {t : set β} (hh : ∀s∈f, t ⊆ h s) :
principal t ≤ f.lift' h :=
le_infi $ assume s, le_infi $ assume hs, principal_mono.mpr (hh s hs)
theorem monotone_lift' [preorder γ] {f : γ → filter α} {g : γ → set α → set β}
(hf : monotone f) (hg : monotone g) : monotone (λc, (f c).lift' (g c)) :=
assume a b h, lift'_mono (hf h) (hg h)
lemma lift_lift'_assoc {g : set α → set β} {h : set β → filter γ}
(hg : monotone g) (hh : monotone h) :
(f.lift' g).lift h = f.lift (λs, h (g s)) :=
calc (f.lift' g).lift h = f.lift (λs, (principal (g s)).lift h) :
lift_assoc (monotone_principal.comp hg)
... = f.lift (λs, h (g s)) : by simp only [lift_principal, hh, eq_self_iff_true]
lemma lift'_lift'_assoc {g : set α → set β} {h : set β → set γ}
(hg : monotone g) (hh : monotone h) :
(f.lift' g).lift' h = f.lift' (λs, h (g s)) :=
lift_lift'_assoc hg (monotone_principal.comp hh)
lemma lift'_lift_assoc {g : set α → filter β} {h : set β → set γ}
(hg : monotone g) : (f.lift g).lift' h = f.lift (λs, (g s).lift' h) :=
lift_assoc hg
lemma lift_lift'_same_le_lift' {g : set α → set α → set β} :
f.lift (λs, f.lift' (g s)) ≤ f.lift' (λs, g s s) :=
lift_lift_same_le_lift
lemma lift_lift'_same_eq_lift' {g : set α → set α → set β}
(hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)) :
f.lift (λs, f.lift' (g s)) = f.lift' (λs, g s s) :=
lift_lift_same_eq_lift
(assume s, monotone_principal.comp (hg₁ s))
(assume t, monotone_principal.comp (hg₂ t))
lemma lift'_inf_principal_eq {h : set α → set β} {s : set β} :
f.lift' h ⊓ principal s = f.lift' (λt, h t ∩ s) :=
le_antisymm
(le_infi $ assume t, le_infi $ assume ht,
calc filter.lift' f h ⊓ principal s ≤ principal (h t) ⊓ principal s :
inf_le_inf (infi_le_of_le t $ infi_le _ ht) (le_refl _)
... = _ : by simp only [principal_eq_iff_eq, inf_principal, eq_self_iff_true, function.comp_app])
(le_inf
(le_infi $ assume t, le_infi $ assume ht,
infi_le_of_le t $ infi_le_of_le ht $
by simp only [le_principal_iff, inter_subset_left, mem_principal_sets, function.comp_app]; exact inter_subset_right _ _)
(infi_le_of_le univ $ infi_le_of_le univ_mem_sets $
by simp only [le_principal_iff, inter_subset_right, mem_principal_sets, function.comp_app]; exact inter_subset_left _ _))
lemma lift'_ne_bot_iff (hh : monotone h) : (f.lift' h ≠ ⊥) ↔ (∀s∈f, (h s).nonempty) :=
calc (f.lift' h ≠ ⊥) ↔ (∀s∈f, principal (h s) ≠ ⊥) :
lift_ne_bot_iff (monotone_principal.comp hh)
... ↔ (∀s∈f, (h s).nonempty) : by simp only [principal_ne_bot_iff]
@[simp] lemma lift'_id {f : filter α} : f.lift' id = f :=
lift_principal2
lemma le_lift' {f : filter α} {h : set α → set β} {g : filter β}
(h_le : ∀s∈f, h s ∈ g) : g ≤ f.lift' h :=
le_infi $ assume s, le_infi $ assume hs, by simp only [h_le, le_principal_iff, function.comp_app]; exact h_le s hs
lemma lift_infi' {f : ι → filter α} {g : set α → filter β}
(hι : nonempty ι) (hf : directed (≥) f) (hg : monotone g) : (infi f).lift g = (⨅i, (f i).lift g) :=
le_antisymm
(le_infi $ assume i, lift_mono (infi_le _ _) (le_refl _))
(assume s,
begin
rw mem_lift_sets hg,
simp only [exists_imp_distrib, mem_infi hf hι],
exact assume t i ht hs, mem_infi_sets i $ mem_lift ht hs
end)
lemma lift'_infi {f : ι → filter α} {g : set α → set β}
(hι : nonempty ι) (hg : ∀{s t}, g s ∩ g t = g (s ∩ t)) : (infi f).lift' g = (⨅i, (f i).lift' g) :=
lift_infi hι $ by simp only [principal_eq_iff_eq, inf_principal, function.comp_app]; apply assume s t, hg
theorem comap_eq_lift' {f : filter β} {m : α → β} :
comap m f = f.lift' (preimage m) :=
filter_eq $ set.ext $ by simp only [mem_lift'_sets, monotone_preimage, comap, exists_prop, forall_const, iff_self, mem_set_of_eq]
end lift'
section prod
variables {f : filter α}
lemma prod_def {f : filter α} {g : filter β} : f.prod g = (f.lift $ λs, g.lift' $ set.prod s) :=
have ∀(s:set α) (t : set β),
principal (set.prod s t) = (principal s).comap prod.fst ⊓ (principal t).comap prod.snd,
by simp only [principal_eq_iff_eq, comap_principal, inf_principal]; intros; refl,
begin
simp only [filter.lift', function.comp, this, -comap_principal, lift_inf, lift_const, lift_inf],
rw [← comap_lift_eq monotone_principal, ← comap_lift_eq monotone_principal],
simp only [filter.prod, lift_principal2, eq_self_iff_true]
end
lemma prod_same_eq : filter.prod f f = f.lift' (λt, set.prod t t) :=
by rw [prod_def];
from lift_lift'_same_eq_lift'
(assume s, set.monotone_prod monotone_const monotone_id)
(assume t, set.monotone_prod monotone_id monotone_const)
lemma mem_prod_same_iff {s : set (α×α)} :
s ∈ filter.prod f f ↔ (∃t∈f, set.prod t t ⊆ s) :=
by rw [prod_same_eq, mem_lift'_sets]; exact set.monotone_prod monotone_id monotone_id
lemma tendsto_prod_self_iff {f : α × α → β} {x : filter α} {y : filter β} :
filter.tendsto f (filter.prod x x) y ↔
∀ W ∈ y, ∃ U ∈ x, ∀ (x x' : α), x ∈ U → x' ∈ U → f (x, x') ∈ W :=
by simp only [tendsto_def, mem_prod_same_iff, prod_sub_preimage_iff, exists_prop, iff_self]
variables {α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*}
lemma prod_lift_lift
{f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → filter β₁} {g₂ : set α₂ → filter β₂}
(hg₁ : monotone g₁) (hg₂ : monotone g₂) :
filter.prod (f₁.lift g₁) (f₂.lift g₂) = f₁.lift (λs, f₂.lift (λt, filter.prod (g₁ s) (g₂ t))) :=
begin
simp only [prod_def],
rw [lift_assoc],
apply congr_arg, funext x,
rw [lift_comm],
apply congr_arg, funext y,
rw [lift'_lift_assoc],
exact hg₂,
exact hg₁
end
lemma prod_lift'_lift'
{f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → set β₁} {g₂ : set α₂ → set β₂}
(hg₁ : monotone g₁) (hg₂ : monotone g₂) :
filter.prod (f₁.lift' g₁) (f₂.lift' g₂) = f₁.lift (λs, f₂.lift' (λt, set.prod (g₁ s) (g₂ t))) :=
begin
rw [prod_def, lift_lift'_assoc],
apply congr_arg, funext x,
rw [lift'_lift'_assoc],
exact hg₂,
exact set.monotone_prod monotone_const monotone_id,
exact hg₁,
exact (monotone_lift' monotone_const $ monotone_lam $
assume x, set.monotone_prod monotone_id monotone_const)
end
end prod
end filter
|
37dde414f0cc33567cab1bb8d6636360f5bc01b1 | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/category_theory/limits/cones.lean | d1da732e501df4b44920c1a8742920beab07e664 | [
"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 | 14,704 | 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, Floris van Doorn
-/
import category_theory.const
import category_theory.yoneda
import category_theory.concrete_category.bundled_hom
import category_theory.equivalence
universes v u u' -- declare the `v`'s first; see `category_theory.category` for an explanation
open category_theory
-- There is an awkward difficulty with universes here.
-- If we allowed `J` to be a small category in `Prop`, we'd run into trouble
-- because `yoneda.obj (F : (J ⥤ C)ᵒᵖ)` will be a functor into `Sort (max v 1)`,
-- not into `Sort v`.
-- So we don't allow this case; it's not particularly useful anyway.
variables {J : Type v} [small_category J]
variables {C : Type u} [𝒞 : category.{v} C]
include 𝒞
open category_theory
open category_theory.category
open category_theory.functor
open opposite
namespace category_theory
namespace functor
variables {J C} (F : J ⥤ C)
/--
`F.cones` is the functor assigning to an object `X` the type of
natural transformations from the constant functor with value `X` to `F`.
An object representing this functor is a limit of `F`.
-/
def cones : Cᵒᵖ ⥤ Type v := (const J).op ⋙ (yoneda.obj F)
lemma cones_obj (X : Cᵒᵖ) : F.cones.obj X = ((const J).obj (unop X) ⟶ F) := rfl
@[simp] lemma cones_map_app {X₁ X₂ : Cᵒᵖ} (f : X₁ ⟶ X₂) (t : F.cones.obj X₁) (j : J) :
(F.cones.map f t).app j = f.unop ≫ t.app j := rfl
/--
`F.cocones` is the functor assigning to an object `X` the type of
natural transformations from `F` to the constant functor with value `X`.
An object corepresenting this functor is a colimit of `F`.
-/
def cocones : C ⥤ Type v := const J ⋙ coyoneda.obj (op F)
lemma cocones_obj (X : C) : F.cocones.obj X = (F ⟶ (const J).obj X) := rfl
@[simp] lemma cocones_map_app {X₁ X₂ : C} (f : X₁ ⟶ X₂) (t : F.cocones.obj X₁) (j : J) :
(F.cocones.map f t).app j = t.app j ≫ f := rfl
end functor
section
variables (J C)
/--
Functorially associated to each functor `J ⥤ C`, we have the `C`-presheaf consisting of
cones with a given cone point.
-/
@[simps] def cones : (J ⥤ C) ⥤ (Cᵒᵖ ⥤ Type v) :=
{ obj := functor.cones,
map := λ F G f, whisker_left (const J).op (yoneda.map f) }
/--
Contravariantly associated to each functor `J ⥤ C`, we have the `C`-copresheaf consisting of
cocones with a given cocone point.
-/
@[simps] def cocones : (J ⥤ C)ᵒᵖ ⥤ (C ⥤ Type v) :=
{ obj := λ F, functor.cocones (unop F),
map := λ F G f, whisker_left (const J) (coyoneda.map f) }
end
namespace limits
/--
A `c : cone F` is:
* an object `c.X` and
* a natural transformation `c.π : c.X ⟶ F` from the constant `c.X` functor to `F`.
`cone F` is equivalent, via `cone.equiv` below, to `Σ X, F.cones.obj X`.
-/
structure cone (F : J ⥤ C) :=
(X : C)
(π : (const J).obj X ⟶ F)
@[simp] lemma cone.w {F : J ⥤ C} (c : cone F) {j j' : J} (f : j ⟶ j') :
c.π.app j ≫ F.map f = c.π.app j' :=
by convert ←(c.π.naturality f).symm; apply id_comp
/--
A `c : cocone F` is
* an object `c.X` and
* a natural transformation `c.ι : F ⟶ c.X` from `F` to the constant `c.X` functor.
`cocone F` is equivalent, via `cone.equiv` below, to `Σ X, F.cocones.obj X`.
-/
structure cocone (F : J ⥤ C) :=
(X : C)
(ι : F ⟶ (const J).obj X)
@[simp] lemma cocone.w {F : J ⥤ C} (c : cocone F) {j j' : J} (f : j ⟶ j') :
F.map f ≫ c.ι.app j' = c.ι.app j :=
by convert ←(c.ι.naturality f); apply comp_id
variables {F : J ⥤ C}
namespace cone
def equiv (F : J ⥤ C) : cone F ≅ Σ X, F.cones.obj X :=
{ hom := λ c, ⟨op c.X, c.π⟩,
inv := λ c, { X := unop c.1, π := c.2 },
hom_inv_id' := begin ext, cases x, refl, end,
inv_hom_id' := begin ext, cases x, refl, end }
@[simp] def extensions (c : cone F) : yoneda.obj c.X ⟶ F.cones :=
{ app := λ X f, ((const J).map f) ≫ c.π }
/-- A map to the vertex of a cone induces a cone by composition. -/
@[simp] def extend (c : cone F) {X : C} (f : X ⟶ c.X) : cone F :=
{ X := X,
π := c.extensions.app (op X) f }
@[simp] lemma extend_π (c : cone F) {X : Cᵒᵖ} (f : unop X ⟶ c.X) :
(extend c f).π = c.extensions.app X f :=
rfl
@[simps] def whisker {K : Type v} [small_category K] (E : K ⥤ J) (c : cone F) : cone (E ⋙ F) :=
{ X := c.X,
π := whisker_left E c.π }
-- We now prove a lemma about naturality of cones over functors into bundled categories.
section
omit 𝒞
variables {J' : Type u} [small_category J']
variables {C' : Type (u+1)} [𝒞' : concrete_category C']
include 𝒞'
local attribute [instance] concrete_category.has_coe_to_sort
local attribute [instance] concrete_category.has_coe_to_fun
/-- Naturality of a cone over functors to a concrete category. -/
@[simp] lemma naturality_concrete {G : J' ⥤ C'} (s : cone G) {j j' : J'} (f : j ⟶ j') (x : s.X) :
(G.map f) ((s.π.app j) x) = (s.π.app j') x :=
begin
convert congr_fun (congr_arg (λ k : s.X ⟶ G.obj j', (k : s.X → G.obj j')) (s.π.naturality f).symm) x;
{ dsimp, simp },
end
end
end cone
namespace cocone
def equiv (F : J ⥤ C) : cocone F ≅ Σ X, F.cocones.obj X :=
{ hom := λ c, ⟨c.X, c.ι⟩,
inv := λ c, { X := c.1, ι := c.2 },
hom_inv_id' := begin ext, cases x, refl, end,
inv_hom_id' := begin ext, cases x, refl, end }
@[simp] def extensions (c : cocone F) : coyoneda.obj (op c.X) ⟶ F.cocones :=
{ app := λ X f, c.ι ≫ (const J).map f }
/-- A map from the vertex of a cocone induces a cocone by composition. -/
@[simp] def extend (c : cocone F) {X : C} (f : c.X ⟶ X) : cocone F :=
{ X := X,
ι := c.extensions.app X f }
@[simp] lemma extend_ι (c : cocone F) {X : C} (f : c.X ⟶ X) :
(extend c f).ι = c.extensions.app X f :=
rfl
@[simps] def whisker {K : Type v} [small_category K] (E : K ⥤ J) (c : cocone F) : cocone (E ⋙ F) :=
{ X := c.X,
ι := whisker_left E c.ι }
-- We now prove a lemma about naturality of cocones over functors into bundled categories.
section
omit 𝒞
variables {J' : Type u} [small_category J']
variables {C' : Type (u+1)} [𝒞' : concrete_category C']
include 𝒞'
local attribute [instance] concrete_category.has_coe_to_sort
local attribute [instance] concrete_category.has_coe_to_fun
/-- Naturality of a cocone over functors into a concrete category. -/
@[simp] lemma naturality_concrete {G : J' ⥤ C'} (s : cocone G) {j j' : J'} (f : j ⟶ j') (x : G.obj j) :
(s.ι.app j') ((G.map f) x) = (s.ι.app j) x :=
begin
convert congr_fun (congr_arg (λ k : G.obj j ⟶ s.X, (k : G.obj j → s.X)) (s.ι.naturality f)) x;
{ dsimp, simp },
end
end
end cocone
structure cone_morphism (A B : cone F) :=
(hom : A.X ⟶ B.X)
(w' : ∀ j : J, hom ≫ B.π.app j = A.π.app j . obviously)
restate_axiom cone_morphism.w'
attribute [simp] cone_morphism.w
@[ext] lemma cone_morphism.ext {A B : cone F} {f g : cone_morphism A B}
(w : f.hom = g.hom) : f = g :=
by cases f; cases g; simpa using w
@[simps] instance cone.category : category.{v} (cone F) :=
{ hom := λ A B, cone_morphism A B,
comp := λ X Y Z f g,
{ hom := f.hom ≫ g.hom,
w' := by intro j; rw [assoc, g.w, f.w] },
id := λ B, { hom := 𝟙 B.X } }
namespace cones
/-- To give an isomorphism between cones, it suffices to give an
isomorphism between their vertices which commutes with the cone
maps. -/
@[ext, simps] def ext {c c' : cone F}
(φ : c.X ≅ c'.X) (w : ∀ j, c.π.app j = φ.hom ≫ c'.π.app j) : c ≅ c' :=
{ hom := { hom := φ.hom },
inv := { hom := φ.inv, w' := λ j, φ.inv_comp_eq.mpr (w j) } }
@[simps] def postcompose {G : J ⥤ C} (α : F ⟶ G) : cone F ⥤ cone G :=
{ obj := λ c, { X := c.X, π := c.π ≫ α },
map := λ c₁ c₂ f, { hom := f.hom, w' :=
by intro; erw ← category.assoc; simp [-category.assoc] } }
def postcompose_comp {G H : J ⥤ C} (α : F ⟶ G) (β : G ⟶ H) :
postcompose (α ≫ β) ≅ postcompose α ⋙ postcompose β :=
by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously }
def postcompose_id : postcompose (𝟙 F) ≅ 𝟭 (cone F) :=
by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously }
def postcompose_equivalence {G : J ⥤ C} (α : F ≅ G) : cone F ≌ cone G :=
begin
refine equivalence.mk (postcompose α.hom) (postcompose α.inv) _ _,
{ symmetry,
refine (postcompose_comp _ _).symm.trans _, rw [iso.hom_inv_id], exact postcompose_id },
{ refine (postcompose_comp _ _).symm.trans _, rw [iso.inv_hom_id], exact postcompose_id }
end
@[simps] def forget : cone F ⥤ C :=
{ obj := λ t, t.X, map := λ s t f, f.hom }
section
variables {D : Type u'} [𝒟 : category.{v} D]
include 𝒟
@[simps] def functoriality (G : C ⥤ D) : cone F ⥤ cone (F ⋙ G) :=
{ obj := λ A,
{ X := G.obj A.X,
π := { app := λ j, G.map (A.π.app j), naturality' := by intros; erw ←G.map_comp; tidy } },
map := λ X Y f,
{ hom := G.map f.hom,
w' := by intros; rw [←functor.map_comp, f.w] } }
end
end cones
structure cocone_morphism (A B : cocone F) :=
(hom : A.X ⟶ B.X)
(w' : ∀ j : J, A.ι.app j ≫ hom = B.ι.app j . obviously)
restate_axiom cocone_morphism.w'
attribute [simp] cocone_morphism.w
@[ext] lemma cocone_morphism.ext
{A B : cocone F} {f g : cocone_morphism A B} (w : f.hom = g.hom) : f = g :=
by cases f; cases g; simpa using w
@[simps] instance cocone.category : category.{v} (cocone F) :=
{ hom := λ A B, cocone_morphism A B,
comp := λ _ _ _ f g,
{ hom := f.hom ≫ g.hom,
w' := by intro j; rw [←assoc, f.w, g.w] },
id := λ B, { hom := 𝟙 B.X } }
namespace cocones
/-- To give an isomorphism between cocones, it suffices to give an
isomorphism between their vertices which commutes with the cocone
maps. -/
@[ext, simps] def ext {c c' : cocone F}
(φ : c.X ≅ c'.X) (w : ∀ j, c.ι.app j ≫ φ.hom = c'.ι.app j) : c ≅ c' :=
{ hom := { hom := φ.hom },
inv := { hom := φ.inv, w' := λ j, φ.comp_inv_eq.mpr (w j).symm } }
@[simps] def precompose {G : J ⥤ C} (α : G ⟶ F) : cocone F ⥤ cocone G :=
{ obj := λ c, { X := c.X, ι := α ≫ c.ι },
map := λ c₁ c₂ f, { hom := f.hom } }
def precompose_comp {G H : J ⥤ C} (α : F ⟶ G) (β : G ⟶ H) :
precompose (α ≫ β) ≅ precompose β ⋙ precompose α :=
by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously }
def precompose_id : precompose (𝟙 F) ≅ 𝟭 (cocone F) :=
by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously }
def precompose_equivalence {G : J ⥤ C} (α : G ≅ F) : cocone F ≌ cocone G :=
begin
refine equivalence.mk (precompose α.hom) (precompose α.inv) _ _,
{ symmetry, refine (precompose_comp _ _).symm.trans _, rw [iso.inv_hom_id], exact precompose_id },
{ refine (precompose_comp _ _).symm.trans _, rw [iso.hom_inv_id], exact precompose_id }
end
@[simps] def forget : cocone F ⥤ C :=
{ obj := λ t, t.X, map := λ s t f, f.hom }
section
variables {D : Type u'} [𝒟 : category.{v} D]
include 𝒟
@[simps] def functoriality (G : C ⥤ D) : cocone F ⥤ cocone (F ⋙ G) :=
{ obj := λ A,
{ X := G.obj A.X,
ι := { app := λ j, G.map (A.ι.app j), naturality' := by intros; erw ←G.map_comp; tidy } },
map := λ _ _ f,
{ hom := G.map f.hom,
w' := by intros; rw [←functor.map_comp, cocone_morphism.w] } }
end
end cocones
end limits
namespace functor
variables {D : Type u'} [category.{v} D]
variables {F : J ⥤ C} {G : J ⥤ C} (H : C ⥤ D)
open category_theory.limits
/-- The image of a cone in C under a functor G : C ⥤ D is a cone in D. -/
def map_cone (c : cone F) : cone (F ⋙ H) := (cones.functoriality H).obj c
/-- The image of a cocone in C under a functor G : C ⥤ D is a cocone in D. -/
def map_cocone (c : cocone F) : cocone (F ⋙ H) := (cocones.functoriality H).obj c
@[simp] lemma map_cone_X (c : cone F) : (H.map_cone c).X = H.obj c.X := rfl
@[simp] lemma map_cocone_X (c : cocone F) : (H.map_cocone c).X = H.obj c.X := rfl
def map_cone_inv [is_equivalence H]
(c : cone (F ⋙ H)) : cone F :=
let t := (inv H).map_cone c in
let α : (F ⋙ H) ⋙ inv H ⟶ F :=
((whisker_left F (is_equivalence.unit_iso H).inv) : F ⋙ (H ⋙ inv H) ⟶ _) ≫ (functor.right_unitor _).hom in
{ X := t.X,
π := ((category_theory.cones J C).map α).app (op t.X) t.π }
@[simp] lemma map_cone_inv_X [is_equivalence H] (c : cone (F ⋙ H)) : (H.map_cone_inv c).X = (inv H).obj c.X := rfl
def map_cone_morphism {c c' : cone F} (f : cone_morphism c c') :
cone_morphism (H.map_cone c) (H.map_cone c') := (cones.functoriality H).map f
def map_cocone_morphism {c c' : cocone F} (f : cocone_morphism c c') :
cocone_morphism (H.map_cocone c) (H.map_cocone c') := (cocones.functoriality H).map f
@[simp] lemma map_cone_π (c : cone F) (j : J) :
(map_cone H c).π.app j = H.map (c.π.app j) := rfl
@[simp] lemma map_cocone_ι (c : cocone F) (j : J) :
(map_cocone H c).ι.app j = H.map (c.ι.app j) := rfl
end functor
end category_theory
namespace category_theory.limits
variables {F : J ⥤ Cᵒᵖ}
-- Here and below we only automatically generate the `@[simp]` lemma for the `X` field,
-- as we can be a simpler `rfl` lemma for the components of the natural transformation by hand.
@[simps X] def cone_of_cocone_left_op (c : cocone F.left_op) : cone F :=
{ X := op c.X,
π := nat_trans.right_op (c.ι ≫ (const.op_obj_unop (op c.X)).hom) }
@[simp] lemma cone_of_cocone_left_op_π_app (c : cocone F.left_op) (j) :
(cone_of_cocone_left_op c).π.app j = (c.ι.app (op j)).op :=
by { dsimp [cone_of_cocone_left_op], simp }
@[simps X] def cocone_left_op_of_cone (c : cone F) : cocone (F.left_op) :=
{ X := unop c.X,
ι := nat_trans.left_op c.π }
@[simp] lemma cocone_left_op_of_cone_ι_app (c : cone F) (j) :
(cocone_left_op_of_cone c).ι.app j = (c.π.app (unop j)).unop :=
by { dsimp [cocone_left_op_of_cone], simp }
@[simps X] def cocone_of_cone_left_op (c : cone F.left_op) : cocone F :=
{ X := op c.X,
ι := nat_trans.right_op ((const.op_obj_unop (op c.X)).hom ≫ c.π) }
@[simp] lemma cocone_of_cone_left_op_ι_app (c : cone F.left_op) (j) :
(cocone_of_cone_left_op c).ι.app j = (c.π.app (op j)).op :=
by { dsimp [cocone_of_cone_left_op], simp }
@[simps X] def cone_left_op_of_cocone (c : cocone F) : cone (F.left_op) :=
{ X := unop c.X,
π := nat_trans.left_op c.ι }
@[simp] lemma cone_left_op_of_cocone_π_app (c : cocone F) (j) :
(cone_left_op_of_cocone c).π.app j = (c.ι.app (unop j)).unop :=
by { dsimp [cone_left_op_of_cocone], simp }
end category_theory.limits
|
df1c3cb6ee4af3b9b1a29aa67ea8129793c03044 | 2c41ae31b2b771ad5646ad880201393f5269a7f0 | /Lean/Qualities/Versatile.lean | d91eb5e97dae4e3269c6b0f9bd60e4cf05674b5d | [] | no_license | kevinsullivan/Boehm | 926f25bc6f1a8b6bd47d333d936fdfc278228312 | 55208395bff20d48a598b7fa33a4d55a2447a9cf | refs/heads/master | 1,586,127,134,302 | 1,488,252,326,000 | 1,488,252,326,000 | 32,836,930 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 666 | lean | -- Versatile
/-
[Versatile] is parameterized by an instance of type [SystemType], and it's a sub-attribute to [MissionEffective].
An instance of type [SystemType] is deemed [Versatile] if and only if all the requirements are satisfied.
-/
import SystemModel.System
inductive Versatile (sys_type: SystemType): Prop
| intro : (exists versatile: sys_type ^.Contexts -> sys_type ^.Phases -> sys_type ^.Stakeholders -> @SystemInstance sys_type -> Prop,
forall c: sys_type ^.Contexts, forall p: sys_type ^.Phases,
forall s: sys_type ^.Stakeholders, forall st: @SystemInstance sys_type, versatile c p s st) ->
Versatile
|
e6c36fed3277e33365211dd04a0d1e78c8ccdb0b | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/order/group/defs.lean | 457a7e1d5470694fa07b144af28076f0c80329ec | [
"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 | 31,204 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl
-/
import order.hom.basic
import algebra.order.sub.defs
import algebra.order.monoid.defs
/-!
# Ordered groups
This file develops the basics of ordered groups.
## Implementation details
Unfortunately, the number of `'` appended to lemmas in this file
may differ between the multiplicative and the additive version of a lemma.
The reason is that we did not want to change existing names in the library.
-/
set_option old_structure_cmd true
open function
universe u
variable {α : Type u}
/-- An ordered additive commutative group is an additive commutative group
with a partial order in which addition is strictly monotone. -/
@[protect_proj, ancestor add_comm_group partial_order]
class ordered_add_comm_group (α : Type u) extends add_comm_group α, partial_order α :=
(add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b)
/-- An ordered commutative group is an commutative group
with a partial order in which multiplication is strictly monotone. -/
@[protect_proj, ancestor comm_group partial_order]
class ordered_comm_group (α : Type u) extends comm_group α, partial_order α :=
(mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b)
attribute [to_additive] ordered_comm_group
@[to_additive]
instance ordered_comm_group.to_covariant_class_left_le (α : Type u) [ordered_comm_group α] :
covariant_class α α (*) (≤) :=
{ elim := λ a b c bc, ordered_comm_group.mul_le_mul_left b c bc a }
example (α : Type u) [ordered_add_comm_group α] : covariant_class α α (swap (+)) (<) :=
add_right_cancel_semigroup.covariant_swap_add_lt_of_covariant_swap_add_le α
/-- A choice-free shortcut instance. -/
@[to_additive "A choice-free shortcut instance."]
instance ordered_comm_group.to_contravariant_class_left_le (α : Type u) [ordered_comm_group α] :
contravariant_class α α (*) (≤) :=
{ elim := λ a b c bc, by simpa using mul_le_mul_left' bc a⁻¹, }
/-- A choice-free shortcut instance. -/
@[to_additive "A choice-free shortcut instance."]
instance ordered_comm_group.to_contravariant_class_right_le (α : Type u) [ordered_comm_group α] :
contravariant_class α α (swap (*)) (≤) :=
{ elim := λ a b c bc, by simpa using mul_le_mul_right' bc a⁻¹, }
section group
variables [group α]
section typeclasses_left_le
variables [has_le α] [covariant_class α α (*) (≤)] {a b c d : α}
/-- Uses `left` co(ntra)variant. -/
@[simp, to_additive left.neg_nonpos_iff "Uses `left` co(ntra)variant."]
lemma left.inv_le_one_iff :
a⁻¹ ≤ 1 ↔ 1 ≤ a :=
by { rw [← mul_le_mul_iff_left a], simp }
/-- Uses `left` co(ntra)variant. -/
@[simp, to_additive left.nonneg_neg_iff "Uses `left` co(ntra)variant."]
lemma left.one_le_inv_iff :
1 ≤ a⁻¹ ↔ a ≤ 1 :=
by { rw [← mul_le_mul_iff_left a], simp }
@[simp, to_additive]
lemma le_inv_mul_iff_mul_le : b ≤ a⁻¹ * c ↔ a * b ≤ c :=
by { rw ← mul_le_mul_iff_left a, simp }
@[simp, to_additive]
lemma inv_mul_le_iff_le_mul : b⁻¹ * a ≤ c ↔ a ≤ b * c :=
by rw [← mul_le_mul_iff_left b, mul_inv_cancel_left]
@[to_additive neg_le_iff_add_nonneg']
lemma inv_le_iff_one_le_mul' : a⁻¹ ≤ b ↔ 1 ≤ a * b :=
(mul_le_mul_iff_left a).symm.trans $ by rw mul_inv_self
@[to_additive]
lemma le_inv_iff_mul_le_one_left : a ≤ b⁻¹ ↔ b * a ≤ 1 :=
(mul_le_mul_iff_left b).symm.trans $ by rw mul_inv_self
@[to_additive]
lemma le_inv_mul_iff_le : 1 ≤ b⁻¹ * a ↔ b ≤ a :=
by rw [← mul_le_mul_iff_left b, mul_one, mul_inv_cancel_left]
@[to_additive]
lemma inv_mul_le_one_iff : a⁻¹ * b ≤ 1 ↔ b ≤ a :=
trans (inv_mul_le_iff_le_mul) $ by rw mul_one
end typeclasses_left_le
section typeclasses_left_lt
variables [has_lt α] [covariant_class α α (*) (<)] {a b c : α}
/-- Uses `left` co(ntra)variant. -/
@[simp, to_additive left.neg_pos_iff "Uses `left` co(ntra)variant."]
lemma left.one_lt_inv_iff :
1 < a⁻¹ ↔ a < 1 :=
by rw [← mul_lt_mul_iff_left a, mul_inv_self, mul_one]
/-- Uses `left` co(ntra)variant. -/
@[simp, to_additive left.neg_neg_iff "Uses `left` co(ntra)variant."]
lemma left.inv_lt_one_iff :
a⁻¹ < 1 ↔ 1 < a :=
by rw [← mul_lt_mul_iff_left a, mul_inv_self, mul_one]
@[simp, to_additive]
lemma lt_inv_mul_iff_mul_lt : b < a⁻¹ * c ↔ a * b < c :=
by { rw [← mul_lt_mul_iff_left a], simp }
@[simp, to_additive]
lemma inv_mul_lt_iff_lt_mul : b⁻¹ * a < c ↔ a < b * c :=
by rw [← mul_lt_mul_iff_left b, mul_inv_cancel_left]
@[to_additive]
lemma inv_lt_iff_one_lt_mul' : a⁻¹ < b ↔ 1 < a * b :=
(mul_lt_mul_iff_left a).symm.trans $ by rw mul_inv_self
@[to_additive]
lemma lt_inv_iff_mul_lt_one' : a < b⁻¹ ↔ b * a < 1 :=
(mul_lt_mul_iff_left b).symm.trans $ by rw mul_inv_self
@[to_additive]
lemma lt_inv_mul_iff_lt : 1 < b⁻¹ * a ↔ b < a :=
by rw [← mul_lt_mul_iff_left b, mul_one, mul_inv_cancel_left]
@[to_additive]
lemma inv_mul_lt_one_iff : a⁻¹ * b < 1 ↔ b < a :=
trans (inv_mul_lt_iff_lt_mul) $ by rw mul_one
end typeclasses_left_lt
section typeclasses_right_le
variables [has_le α] [covariant_class α α (swap (*)) (≤)] {a b c : α}
/-- Uses `right` co(ntra)variant. -/
@[simp, to_additive right.neg_nonpos_iff "Uses `right` co(ntra)variant."]
lemma right.inv_le_one_iff :
a⁻¹ ≤ 1 ↔ 1 ≤ a :=
by { rw [← mul_le_mul_iff_right a], simp }
/-- Uses `right` co(ntra)variant. -/
@[simp, to_additive right.nonneg_neg_iff "Uses `right` co(ntra)variant."]
lemma right.one_le_inv_iff :
1 ≤ a⁻¹ ↔ a ≤ 1 :=
by { rw [← mul_le_mul_iff_right a], simp }
@[to_additive neg_le_iff_add_nonneg]
lemma inv_le_iff_one_le_mul : a⁻¹ ≤ b ↔ 1 ≤ b * a :=
(mul_le_mul_iff_right a).symm.trans $ by rw inv_mul_self
@[to_additive]
lemma le_inv_iff_mul_le_one_right : a ≤ b⁻¹ ↔ a * b ≤ 1 :=
(mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_self
@[simp, to_additive]
lemma mul_inv_le_iff_le_mul : a * b⁻¹ ≤ c ↔ a ≤ c * b :=
(mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_cancel_right
@[simp, to_additive]
lemma le_mul_inv_iff_mul_le : c ≤ a * b⁻¹ ↔ c * b ≤ a :=
(mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_cancel_right
@[simp, to_additive]
lemma mul_inv_le_one_iff_le : a * b⁻¹ ≤ 1 ↔ a ≤ b :=
mul_inv_le_iff_le_mul.trans $ by rw one_mul
@[to_additive]
lemma le_mul_inv_iff_le : 1 ≤ a * b⁻¹ ↔ b ≤ a :=
by rw [← mul_le_mul_iff_right b, one_mul, inv_mul_cancel_right]
@[to_additive]
lemma mul_inv_le_one_iff : b * a⁻¹ ≤ 1 ↔ b ≤ a :=
trans (mul_inv_le_iff_le_mul) $ by rw one_mul
end typeclasses_right_le
section typeclasses_right_lt
variables [has_lt α] [covariant_class α α (swap (*)) (<)] {a b c : α}
/-- Uses `right` co(ntra)variant. -/
@[simp, to_additive right.neg_neg_iff "Uses `right` co(ntra)variant."]
lemma right.inv_lt_one_iff :
a⁻¹ < 1 ↔ 1 < a :=
by rw [← mul_lt_mul_iff_right a, inv_mul_self, one_mul]
/-- Uses `right` co(ntra)variant. -/
@[simp, to_additive right.neg_pos_iff "Uses `right` co(ntra)variant."]
lemma right.one_lt_inv_iff :
1 < a⁻¹ ↔ a < 1 :=
by rw [← mul_lt_mul_iff_right a, inv_mul_self, one_mul]
@[to_additive]
lemma inv_lt_iff_one_lt_mul : a⁻¹ < b ↔ 1 < b * a :=
(mul_lt_mul_iff_right a).symm.trans $ by rw inv_mul_self
@[to_additive]
lemma lt_inv_iff_mul_lt_one : a < b⁻¹ ↔ a * b < 1 :=
(mul_lt_mul_iff_right b).symm.trans $ by rw inv_mul_self
@[simp, to_additive]
lemma mul_inv_lt_iff_lt_mul : a * b⁻¹ < c ↔ a < c * b :=
by rw [← mul_lt_mul_iff_right b, inv_mul_cancel_right]
@[simp, to_additive]
lemma lt_mul_inv_iff_mul_lt : c < a * b⁻¹ ↔ c * b < a :=
(mul_lt_mul_iff_right b).symm.trans $ by rw inv_mul_cancel_right
@[simp, to_additive]
lemma inv_mul_lt_one_iff_lt : a * b⁻¹ < 1 ↔ a < b :=
by rw [← mul_lt_mul_iff_right b, inv_mul_cancel_right, one_mul]
@[to_additive]
lemma lt_mul_inv_iff_lt : 1 < a * b⁻¹ ↔ b < a :=
by rw [← mul_lt_mul_iff_right b, one_mul, inv_mul_cancel_right]
@[to_additive]
lemma mul_inv_lt_one_iff : b * a⁻¹ < 1 ↔ b < a :=
trans (mul_inv_lt_iff_lt_mul) $ by rw one_mul
end typeclasses_right_lt
section typeclasses_left_right_le
variables [has_le α] [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)]
{a b c d : α}
@[simp, to_additive]
lemma inv_le_inv_iff : a⁻¹ ≤ b⁻¹ ↔ b ≤ a :=
by { rw [← mul_le_mul_iff_left a, ← mul_le_mul_iff_right b], simp }
alias neg_le_neg_iff ↔ le_of_neg_le_neg _
@[to_additive]
lemma mul_inv_le_inv_mul_iff : a * b⁻¹ ≤ d⁻¹ * c ↔ d * a ≤ c * b :=
by rw [← mul_le_mul_iff_left d, ← mul_le_mul_iff_right b, mul_inv_cancel_left, mul_assoc,
inv_mul_cancel_right]
@[simp, to_additive] lemma div_le_self_iff (a : α) {b : α} : a / b ≤ a ↔ 1 ≤ b :=
by simp [div_eq_mul_inv]
@[simp, to_additive] lemma le_div_self_iff (a : α) {b : α} : a ≤ a / b ↔ b ≤ 1 :=
by simp [div_eq_mul_inv]
alias sub_le_self_iff ↔ _ sub_le_self
end typeclasses_left_right_le
section typeclasses_left_right_lt
variables [has_lt α] [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)]
{a b c d : α}
@[simp, to_additive]
lemma inv_lt_inv_iff : a⁻¹ < b⁻¹ ↔ b < a :=
by { rw [← mul_lt_mul_iff_left a, ← mul_lt_mul_iff_right b], simp }
@[to_additive neg_lt]
lemma inv_lt' : a⁻¹ < b ↔ b⁻¹ < a :=
by rw [← inv_lt_inv_iff, inv_inv]
@[to_additive lt_neg]
lemma lt_inv' : a < b⁻¹ ↔ b < a⁻¹ :=
by rw [← inv_lt_inv_iff, inv_inv]
alias lt_inv' ↔ lt_inv_of_lt_inv _
attribute [to_additive] lt_inv_of_lt_inv
alias inv_lt' ↔ inv_lt_of_inv_lt' _
attribute [to_additive neg_lt_of_neg_lt] inv_lt_of_inv_lt'
@[to_additive]
lemma mul_inv_lt_inv_mul_iff : a * b⁻¹ < d⁻¹ * c ↔ d * a < c * b :=
by rw [← mul_lt_mul_iff_left d, ← mul_lt_mul_iff_right b, mul_inv_cancel_left, mul_assoc,
inv_mul_cancel_right]
@[simp, to_additive] lemma div_lt_self_iff (a : α) {b : α} : a / b < a ↔ 1 < b :=
by simp [div_eq_mul_inv]
alias sub_lt_self_iff ↔ _ sub_lt_self
end typeclasses_left_right_lt
section pre_order
variable [preorder α]
section left_le
variables [covariant_class α α (*) (≤)] {a : α}
@[to_additive]
lemma left.inv_le_self (h : 1 ≤ a) : a⁻¹ ≤ a :=
le_trans (left.inv_le_one_iff.mpr h) h
alias left.neg_le_self ← neg_le_self
@[to_additive]
lemma left.self_le_inv (h : a ≤ 1) : a ≤ a⁻¹ :=
le_trans h (left.one_le_inv_iff.mpr h)
end left_le
section left_lt
variables [covariant_class α α (*) (<)] {a : α}
@[to_additive]
lemma left.inv_lt_self (h : 1 < a) : a⁻¹ < a :=
(left.inv_lt_one_iff.mpr h).trans h
alias left.neg_lt_self ← neg_lt_self
@[to_additive]
lemma left.self_lt_inv (h : a < 1) : a < a⁻¹ :=
lt_trans h (left.one_lt_inv_iff.mpr h)
end left_lt
section right_le
variables [covariant_class α α (swap (*)) (≤)] {a : α}
@[to_additive]
lemma right.inv_le_self (h : 1 ≤ a) : a⁻¹ ≤ a :=
le_trans (right.inv_le_one_iff.mpr h) h
@[to_additive]
lemma right.self_le_inv (h : a ≤ 1) : a ≤ a⁻¹ :=
le_trans h (right.one_le_inv_iff.mpr h)
end right_le
section right_lt
variables [covariant_class α α (swap (*)) (<)] {a : α}
@[to_additive]
lemma right.inv_lt_self (h : 1 < a) : a⁻¹ < a :=
(right.inv_lt_one_iff.mpr h).trans h
@[to_additive]
lemma right.self_lt_inv (h : a < 1) : a < a⁻¹ :=
lt_trans h (right.one_lt_inv_iff.mpr h)
end right_lt
end pre_order
end group
section comm_group
variables [comm_group α]
section has_le
variables [has_le α] [covariant_class α α (*) (≤)] {a b c d : α}
@[to_additive]
lemma inv_mul_le_iff_le_mul' : c⁻¹ * a ≤ b ↔ a ≤ b * c :=
by rw [inv_mul_le_iff_le_mul, mul_comm]
@[simp, to_additive]
lemma mul_inv_le_iff_le_mul' : a * b⁻¹ ≤ c ↔ a ≤ b * c :=
by rw [← inv_mul_le_iff_le_mul, mul_comm]
@[to_additive add_neg_le_add_neg_iff]
lemma mul_inv_le_mul_inv_iff' : a * b⁻¹ ≤ c * d⁻¹ ↔ a * d ≤ c * b :=
by rw [mul_comm c, mul_inv_le_inv_mul_iff, mul_comm]
end has_le
section has_lt
variables [has_lt α] [covariant_class α α (*) (<)] {a b c d : α}
@[to_additive]
lemma inv_mul_lt_iff_lt_mul' : c⁻¹ * a < b ↔ a < b * c :=
by rw [inv_mul_lt_iff_lt_mul, mul_comm]
@[simp, to_additive]
lemma mul_inv_lt_iff_le_mul' : a * b⁻¹ < c ↔ a < b * c :=
by rw [← inv_mul_lt_iff_lt_mul, mul_comm]
@[to_additive add_neg_lt_add_neg_iff]
lemma mul_inv_lt_mul_inv_iff' : a * b⁻¹ < c * d⁻¹ ↔ a * d < c * b :=
by rw [mul_comm c, mul_inv_lt_inv_mul_iff, mul_comm]
end has_lt
end comm_group
alias left.inv_le_one_iff ↔ one_le_of_inv_le_one _
attribute [to_additive] one_le_of_inv_le_one
alias left.one_le_inv_iff ↔ le_one_of_one_le_inv _
attribute [to_additive nonpos_of_neg_nonneg] le_one_of_one_le_inv
alias inv_lt_inv_iff ↔ lt_of_inv_lt_inv _
attribute [to_additive] lt_of_inv_lt_inv
alias left.inv_lt_one_iff ↔ one_lt_of_inv_lt_one _
attribute [to_additive] one_lt_of_inv_lt_one
alias left.inv_lt_one_iff ← inv_lt_one_iff_one_lt
attribute [to_additive] inv_lt_one_iff_one_lt
alias left.inv_lt_one_iff ← inv_lt_one'
attribute [to_additive neg_lt_zero] inv_lt_one'
alias left.one_lt_inv_iff ↔ inv_of_one_lt_inv _
attribute [to_additive neg_of_neg_pos] inv_of_one_lt_inv
alias left.one_lt_inv_iff ↔ _ one_lt_inv_of_inv
attribute [to_additive neg_pos_of_neg] one_lt_inv_of_inv
alias le_inv_mul_iff_mul_le ↔ mul_le_of_le_inv_mul _
attribute [to_additive] mul_le_of_le_inv_mul
alias le_inv_mul_iff_mul_le ↔ _ le_inv_mul_of_mul_le
attribute [to_additive] le_inv_mul_of_mul_le
alias inv_mul_le_iff_le_mul ↔ _ inv_mul_le_of_le_mul
attribute [to_additive] inv_mul_le_iff_le_mul
alias lt_inv_mul_iff_mul_lt ↔ mul_lt_of_lt_inv_mul _
attribute [to_additive] mul_lt_of_lt_inv_mul
alias lt_inv_mul_iff_mul_lt ↔ _ lt_inv_mul_of_mul_lt
attribute [to_additive] lt_inv_mul_of_mul_lt
alias inv_mul_lt_iff_lt_mul ↔ lt_mul_of_inv_mul_lt inv_mul_lt_of_lt_mul
attribute [to_additive] lt_mul_of_inv_mul_lt
attribute [to_additive] inv_mul_lt_of_lt_mul
alias lt_mul_of_inv_mul_lt ← lt_mul_of_inv_mul_lt_left
attribute [to_additive] lt_mul_of_inv_mul_lt_left
alias left.inv_le_one_iff ← inv_le_one'
attribute [to_additive neg_nonpos] inv_le_one'
alias left.one_le_inv_iff ← one_le_inv'
attribute [to_additive neg_nonneg] one_le_inv'
alias left.one_lt_inv_iff ← one_lt_inv'
attribute [to_additive neg_pos] one_lt_inv'
alias mul_lt_mul_left' ← ordered_comm_group.mul_lt_mul_left'
attribute [to_additive ordered_add_comm_group.add_lt_add_left] ordered_comm_group.mul_lt_mul_left'
alias le_of_mul_le_mul_left' ← ordered_comm_group.le_of_mul_le_mul_left
attribute [to_additive ordered_add_comm_group.le_of_add_le_add_left]
ordered_comm_group.le_of_mul_le_mul_left
alias lt_of_mul_lt_mul_left' ← ordered_comm_group.lt_of_mul_lt_mul_left
attribute [to_additive ordered_add_comm_group.lt_of_add_lt_add_left]
ordered_comm_group.lt_of_mul_lt_mul_left
/- Most of the lemmas that are primed in this section appear in ordered_field. -/
/- I (DT) did not try to minimise the assumptions. -/
section group
variables [group α] [has_le α]
section right
variables [covariant_class α α (swap (*)) (≤)] {a b c d : α}
@[simp, to_additive]
lemma div_le_div_iff_right (c : α) : a / c ≤ b / c ↔ a ≤ b :=
by simpa only [div_eq_mul_inv] using mul_le_mul_iff_right _
@[to_additive sub_le_sub_right]
lemma div_le_div_right' (h : a ≤ b) (c : α) : a / c ≤ b / c :=
(div_le_div_iff_right c).2 h
@[simp, to_additive sub_nonneg]
lemma one_le_div' : 1 ≤ a / b ↔ b ≤ a :=
by rw [← mul_le_mul_iff_right b, one_mul, div_eq_mul_inv, inv_mul_cancel_right]
alias sub_nonneg ↔ le_of_sub_nonneg sub_nonneg_of_le
@[simp, to_additive sub_nonpos]
lemma div_le_one' : a / b ≤ 1 ↔ a ≤ b :=
by rw [← mul_le_mul_iff_right b, one_mul, div_eq_mul_inv, inv_mul_cancel_right]
alias sub_nonpos ↔ le_of_sub_nonpos sub_nonpos_of_le
@[to_additive]
lemma le_div_iff_mul_le : a ≤ c / b ↔ a * b ≤ c :=
by rw [← mul_le_mul_iff_right b, div_eq_mul_inv, inv_mul_cancel_right]
alias le_sub_iff_add_le ↔ add_le_of_le_sub_right le_sub_right_of_add_le
@[to_additive]
lemma div_le_iff_le_mul : a / c ≤ b ↔ a ≤ b * c :=
by rw [← mul_le_mul_iff_right c, div_eq_mul_inv, inv_mul_cancel_right]
-- TODO: Should we get rid of `sub_le_iff_le_add` in favor of
-- (a renamed version of) `tsub_le_iff_right`?
@[priority 100] -- see Note [lower instance priority]
instance add_group.to_has_ordered_sub {α : Type*} [add_group α] [has_le α]
[covariant_class α α (swap (+)) (≤)] : has_ordered_sub α :=
⟨λ a b c, sub_le_iff_le_add⟩
end right
section left
variables [covariant_class α α (*) (≤)]
variables [covariant_class α α (swap (*)) (≤)] {a b c : α}
@[simp, to_additive]
lemma div_le_div_iff_left (a : α) : a / b ≤ a / c ↔ c ≤ b :=
by rw [div_eq_mul_inv, div_eq_mul_inv, ← mul_le_mul_iff_left a⁻¹, inv_mul_cancel_left,
inv_mul_cancel_left, inv_le_inv_iff]
@[to_additive sub_le_sub_left]
lemma div_le_div_left' (h : a ≤ b) (c : α) : c / b ≤ c / a :=
(div_le_div_iff_left c).2 h
end left
end group
section comm_group
variables [comm_group α]
section has_le
variables [has_le α] [covariant_class α α (*) (≤)] {a b c d : α}
@[to_additive sub_le_sub_iff]
lemma div_le_div_iff' : a / b ≤ c / d ↔ a * d ≤ c * b :=
by simpa only [div_eq_mul_inv] using mul_inv_le_mul_inv_iff'
@[to_additive]
lemma le_div_iff_mul_le' : b ≤ c / a ↔ a * b ≤ c :=
by rw [le_div_iff_mul_le, mul_comm]
alias le_sub_iff_add_le' ↔ add_le_of_le_sub_left le_sub_left_of_add_le
@[to_additive]
lemma div_le_iff_le_mul' : a / b ≤ c ↔ a ≤ b * c :=
by rw [div_le_iff_le_mul, mul_comm]
alias sub_le_iff_le_add' ↔ le_add_of_sub_left_le sub_left_le_of_le_add
@[simp, to_additive]
lemma inv_le_div_iff_le_mul : b⁻¹ ≤ a / c ↔ c ≤ a * b :=
le_div_iff_mul_le.trans inv_mul_le_iff_le_mul'
@[to_additive]
lemma inv_le_div_iff_le_mul' : a⁻¹ ≤ b / c ↔ c ≤ a * b :=
by rw [inv_le_div_iff_le_mul, mul_comm]
@[to_additive]
lemma div_le_comm : a / b ≤ c ↔ a / c ≤ b := div_le_iff_le_mul'.trans div_le_iff_le_mul.symm
@[to_additive]
lemma le_div_comm : a ≤ b / c ↔ c ≤ b / a := le_div_iff_mul_le'.trans le_div_iff_mul_le.symm
end has_le
section preorder
variables [preorder α] [covariant_class α α (*) (≤)] {a b c d : α}
@[to_additive sub_le_sub]
lemma div_le_div'' (hab : a ≤ b) (hcd : c ≤ d) :
a / d ≤ b / c :=
begin
rw [div_eq_mul_inv, div_eq_mul_inv, mul_comm b, mul_inv_le_inv_mul_iff, mul_comm],
exact mul_le_mul' hab hcd
end
end preorder
end comm_group
/- Most of the lemmas that are primed in this section appear in ordered_field. -/
/- I (DT) did not try to minimise the assumptions. -/
section group
variables [group α] [has_lt α]
section right
variables [covariant_class α α (swap (*)) (<)] {a b c d : α}
@[simp, to_additive]
lemma div_lt_div_iff_right (c : α) : a / c < b / c ↔ a < b :=
by simpa only [div_eq_mul_inv] using mul_lt_mul_iff_right _
@[to_additive sub_lt_sub_right]
lemma div_lt_div_right' (h : a < b) (c : α) : a / c < b / c :=
(div_lt_div_iff_right c).2 h
@[simp, to_additive sub_pos]
lemma one_lt_div' : 1 < a / b ↔ b < a :=
by rw [← mul_lt_mul_iff_right b, one_mul, div_eq_mul_inv, inv_mul_cancel_right]
alias sub_pos ↔ lt_of_sub_pos sub_pos_of_lt
@[simp, to_additive sub_neg]
lemma div_lt_one' : a / b < 1 ↔ a < b :=
by rw [← mul_lt_mul_iff_right b, one_mul, div_eq_mul_inv, inv_mul_cancel_right]
alias sub_neg ↔ lt_of_sub_neg sub_neg_of_lt
alias sub_neg ← sub_lt_zero
@[to_additive]
lemma lt_div_iff_mul_lt : a < c / b ↔ a * b < c :=
by rw [← mul_lt_mul_iff_right b, div_eq_mul_inv, inv_mul_cancel_right]
alias lt_sub_iff_add_lt ↔ add_lt_of_lt_sub_right lt_sub_right_of_add_lt
@[to_additive]
lemma div_lt_iff_lt_mul : a / c < b ↔ a < b * c :=
by rw [← mul_lt_mul_iff_right c, div_eq_mul_inv, inv_mul_cancel_right]
alias sub_lt_iff_lt_add ↔ lt_add_of_sub_right_lt sub_right_lt_of_lt_add
end right
section left
variables [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)] {a b c : α}
@[simp, to_additive]
lemma div_lt_div_iff_left (a : α) : a / b < a / c ↔ c < b :=
by rw [div_eq_mul_inv, div_eq_mul_inv, ← mul_lt_mul_iff_left a⁻¹, inv_mul_cancel_left,
inv_mul_cancel_left, inv_lt_inv_iff]
@[simp, to_additive]
lemma inv_lt_div_iff_lt_mul : a⁻¹ < b / c ↔ c < a * b :=
by rw [div_eq_mul_inv, lt_mul_inv_iff_mul_lt, inv_mul_lt_iff_lt_mul]
@[to_additive sub_lt_sub_left]
lemma div_lt_div_left' (h : a < b) (c : α) : c / b < c / a :=
(div_lt_div_iff_left c).2 h
end left
end group
section comm_group
variables [comm_group α]
section has_lt
variables [has_lt α] [covariant_class α α (*) (<)] {a b c d : α}
@[to_additive sub_lt_sub_iff]
lemma div_lt_div_iff' : a / b < c / d ↔ a * d < c * b :=
by simpa only [div_eq_mul_inv] using mul_inv_lt_mul_inv_iff'
@[to_additive]
lemma lt_div_iff_mul_lt' : b < c / a ↔ a * b < c :=
by rw [lt_div_iff_mul_lt, mul_comm]
alias lt_sub_iff_add_lt' ↔ add_lt_of_lt_sub_left lt_sub_left_of_add_lt
@[to_additive]
lemma div_lt_iff_lt_mul' : a / b < c ↔ a < b * c :=
by rw [div_lt_iff_lt_mul, mul_comm]
alias sub_lt_iff_lt_add' ↔ lt_add_of_sub_left_lt sub_left_lt_of_lt_add
@[to_additive]
lemma inv_lt_div_iff_lt_mul' : b⁻¹ < a / c ↔ c < a * b :=
lt_div_iff_mul_lt.trans inv_mul_lt_iff_lt_mul'
@[to_additive]
lemma div_lt_comm : a / b < c ↔ a / c < b := div_lt_iff_lt_mul'.trans div_lt_iff_lt_mul.symm
@[to_additive]
lemma lt_div_comm : a < b / c ↔ c < b / a := lt_div_iff_mul_lt'.trans lt_div_iff_mul_lt.symm
end has_lt
section preorder
variables [preorder α] [covariant_class α α (*) (<)] {a b c d : α}
@[to_additive sub_lt_sub]
lemma div_lt_div'' (hab : a < b) (hcd : c < d) :
a / d < b / c :=
begin
rw [div_eq_mul_inv, div_eq_mul_inv, mul_comm b, mul_inv_lt_inv_mul_iff, mul_comm],
exact mul_lt_mul_of_lt_of_lt hab hcd
end
end preorder
end comm_group
section linear_order
variables [group α] [linear_order α]
@[simp, to_additive cmp_sub_zero]
lemma cmp_div_one' [covariant_class α α (swap (*)) (≤)] (a b : α) : cmp (a / b) 1 = cmp a b :=
by rw [← cmp_mul_right' _ _ b, one_mul, div_mul_cancel']
variables [covariant_class α α (*) (≤)]
section variable_names
variables {a b c : α}
@[to_additive]
lemma le_of_forall_one_lt_lt_mul (h : ∀ ε : α, 1 < ε → a < b * ε) : a ≤ b :=
le_of_not_lt (λ h₁, lt_irrefl a (by simpa using (h _ (lt_inv_mul_iff_lt.mpr h₁))))
@[to_additive]
lemma le_iff_forall_one_lt_lt_mul : a ≤ b ↔ ∀ ε, 1 < ε → a < b * ε :=
⟨λ h ε, lt_mul_of_le_of_one_lt h, le_of_forall_one_lt_lt_mul⟩
/- I (DT) introduced this lemma to prove (the additive version `sub_le_sub_flip` of)
`div_le_div_flip` below. Now I wonder what is the point of either of these lemmas... -/
@[to_additive]
lemma div_le_inv_mul_iff [covariant_class α α (swap (*)) (≤)] :
a / b ≤ a⁻¹ * b ↔ a ≤ b :=
begin
rw [div_eq_mul_inv, mul_inv_le_inv_mul_iff],
exact ⟨λ h, not_lt.mp (λ k, not_lt.mpr h (mul_lt_mul_of_lt_of_lt k k)), λ h, mul_le_mul' h h⟩,
end
/- What is the point of this lemma? See comment about `div_le_inv_mul_iff` above. -/
@[simp, to_additive]
lemma div_le_div_flip {α : Type*} [comm_group α] [linear_order α] [covariant_class α α (*) (≤)]
{a b : α}:
a / b ≤ b / a ↔ a ≤ b :=
begin
rw [div_eq_mul_inv b, mul_comm],
exact div_le_inv_mul_iff,
end
end variable_names
end linear_order
/-!
### Linearly ordered commutative groups
-/
/-- A linearly ordered additive commutative group is an
additive commutative group with a linear order in which
addition is monotone. -/
@[protect_proj, ancestor ordered_add_comm_group linear_order]
class linear_ordered_add_comm_group (α : Type u) extends ordered_add_comm_group α, linear_order α
/-- A linearly ordered commutative monoid with an additively absorbing `⊤` element.
Instances should include number systems with an infinite element adjoined.` -/
@[protect_proj, ancestor linear_ordered_add_comm_monoid_with_top sub_neg_monoid nontrivial]
class linear_ordered_add_comm_group_with_top (α : Type*)
extends linear_ordered_add_comm_monoid_with_top α, sub_neg_monoid α, nontrivial α :=
(neg_top : - (⊤ : α) = ⊤)
(add_neg_cancel : ∀ a:α, a ≠ ⊤ → a + (- a) = 0)
/-- A linearly ordered commutative group is a
commutative group with a linear order in which
multiplication is monotone. -/
@[protect_proj, ancestor ordered_comm_group linear_order, to_additive]
class linear_ordered_comm_group (α : Type u) extends ordered_comm_group α, linear_order α
section linear_ordered_comm_group
variables [linear_ordered_comm_group α] {a b c : α}
@[to_additive linear_ordered_add_comm_group.add_lt_add_left]
lemma linear_ordered_comm_group.mul_lt_mul_left'
(a b : α) (h : a < b) (c : α) : c * a < c * b :=
mul_lt_mul_left' h c
@[to_additive eq_zero_of_neg_eq]
lemma eq_one_of_inv_eq' (h : a⁻¹ = a) : a = 1 :=
match lt_trichotomy a 1 with
| or.inl h₁ :=
have 1 < a, from h ▸ one_lt_inv_of_inv h₁,
absurd h₁ this.asymm
| or.inr (or.inl h₁) := h₁
| or.inr (or.inr h₁) :=
have a < 1, from h ▸ inv_lt_one'.mpr h₁,
absurd h₁ this.asymm
end
@[to_additive exists_zero_lt]
lemma exists_one_lt' [nontrivial α] : ∃ (a:α), 1 < a :=
begin
obtain ⟨y, hy⟩ := decidable.exists_ne (1 : α),
cases hy.lt_or_lt,
{ exact ⟨y⁻¹, one_lt_inv'.mpr h⟩ },
{ exact ⟨y, h⟩ }
end
@[priority 100, to_additive] -- see Note [lower instance priority]
instance linear_ordered_comm_group.to_no_max_order [nontrivial α] :
no_max_order α :=
⟨ begin
obtain ⟨y, hy⟩ : ∃ (a:α), 1 < a := exists_one_lt',
exact λ a, ⟨a * y, lt_mul_of_one_lt_right' a hy⟩
end ⟩
@[priority 100, to_additive] -- see Note [lower instance priority]
instance linear_ordered_comm_group.to_no_min_order [nontrivial α] : no_min_order α :=
⟨ begin
obtain ⟨y, hy⟩ : ∃ (a:α), 1 < a := exists_one_lt',
exact λ a, ⟨a / y, (div_lt_self_iff a).mpr hy⟩
end ⟩
end linear_ordered_comm_group
namespace add_comm_group
/-- A collection of elements in an `add_comm_group` designated as "non-negative".
This is useful for constructing an `ordered_add_commm_group`
by choosing a positive cone in an exisiting `add_comm_group`. -/
@[nolint has_nonempty_instance]
structure positive_cone (α : Type*) [add_comm_group α] :=
(nonneg : α → Prop)
(pos : α → Prop := λ a, nonneg a ∧ ¬ nonneg (-a))
(pos_iff : ∀ a, pos a ↔ nonneg a ∧ ¬ nonneg (-a) . order_laws_tac)
(zero_nonneg : nonneg 0)
(add_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a + b))
(nonneg_antisymm : ∀ {a}, nonneg a → nonneg (-a) → a = 0)
/-- A positive cone in an `add_comm_group` induces a linear order if
for every `a`, either `a` or `-a` is non-negative. -/
@[nolint has_nonempty_instance]
structure total_positive_cone (α : Type*) [add_comm_group α] extends positive_cone α :=
(nonneg_decidable : decidable_pred nonneg)
(nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a))
/-- Forget that a `total_positive_cone` is total. -/
add_decl_doc total_positive_cone.to_positive_cone
end add_comm_group
namespace ordered_add_comm_group
open add_comm_group
/-- Construct an `ordered_add_comm_group` by
designating a positive cone in an existing `add_comm_group`. -/
def mk_of_positive_cone {α : Type*} [add_comm_group α] (C : positive_cone α) :
ordered_add_comm_group α :=
{ le := λ a b, C.nonneg (b - a),
lt := λ a b, C.pos (b - a),
lt_iff_le_not_le := λ a b, by simp; rw [C.pos_iff]; simp,
le_refl := λ a, by simp [C.zero_nonneg],
le_trans := λ a b c nab nbc, by simp [-sub_eq_add_neg];
rw ← sub_add_sub_cancel; exact C.add_nonneg nbc nab,
le_antisymm := λ a b nab nba, eq_of_sub_eq_zero $
C.nonneg_antisymm nba (by rw neg_sub; exact nab),
add_le_add_left := λ a b nab c, by simpa [(≤), preorder.le] using nab,
..‹add_comm_group α› }
end ordered_add_comm_group
namespace linear_ordered_add_comm_group
open add_comm_group
/-- Construct a `linear_ordered_add_comm_group` by
designating a positive cone in an existing `add_comm_group`
such that for every `a`, either `a` or `-a` is non-negative. -/
def mk_of_positive_cone {α : Type*} [add_comm_group α] (C : total_positive_cone α) :
linear_ordered_add_comm_group α :=
{ le_total := λ a b, by { convert C.nonneg_total (b - a), change C.nonneg _ = _, congr, simp, },
decidable_le := λ a b, C.nonneg_decidable _,
..ordered_add_comm_group.mk_of_positive_cone C.to_positive_cone }
end linear_ordered_add_comm_group
section norm_num_lemmas
/- The following lemmas are stated so that the `norm_num` tactic can use them with the
expected signatures. -/
variables [ordered_comm_group α] {a b : α}
@[to_additive neg_le_neg]
lemma inv_le_inv' : a ≤ b → b⁻¹ ≤ a⁻¹ :=
inv_le_inv_iff.mpr
@[to_additive neg_lt_neg]
lemma inv_lt_inv' : a < b → b⁻¹ < a⁻¹ :=
inv_lt_inv_iff.mpr
/- The additive version is also a `linarith` lemma. -/
@[to_additive]
theorem inv_lt_one_of_one_lt : 1 < a → a⁻¹ < 1 :=
inv_lt_one_iff_one_lt.mpr
/- The additive version is also a `linarith` lemma. -/
@[to_additive]
lemma inv_le_one_of_one_le : 1 ≤ a → a⁻¹ ≤ 1 :=
inv_le_one'.mpr
@[to_additive neg_nonneg_of_nonpos]
lemma one_le_inv_of_le_one : a ≤ 1 → 1 ≤ a⁻¹ :=
one_le_inv'.mpr
end norm_num_lemmas
section
variables {β : Type*}
[group α] [preorder α] [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)]
[preorder β] {f : β → α} {s : set β}
@[to_additive] lemma monotone.inv (hf : monotone f) : antitone (λ x, (f x)⁻¹) :=
λ x y hxy, inv_le_inv_iff.2 (hf hxy)
@[to_additive] lemma antitone.inv (hf : antitone f) : monotone (λ x, (f x)⁻¹) :=
λ x y hxy, inv_le_inv_iff.2 (hf hxy)
@[to_additive] lemma monotone_on.inv (hf : monotone_on f s) :
antitone_on (λ x, (f x)⁻¹) s :=
λ x hx y hy hxy, inv_le_inv_iff.2 (hf hx hy hxy)
@[to_additive] lemma antitone_on.inv (hf : antitone_on f s) :
monotone_on (λ x, (f x)⁻¹) s :=
λ x hx y hy hxy, inv_le_inv_iff.2 (hf hx hy hxy)
end
section
variables {β : Type*}
[group α] [preorder α] [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)]
[preorder β] {f : β → α} {s : set β}
@[to_additive] lemma strict_mono.inv (hf : strict_mono f) : strict_anti (λ x, (f x)⁻¹) :=
λ x y hxy, inv_lt_inv_iff.2 (hf hxy)
@[to_additive] lemma strict_anti.inv (hf : strict_anti f) : strict_mono (λ x, (f x)⁻¹) :=
λ x y hxy, inv_lt_inv_iff.2 (hf hxy)
@[to_additive] lemma strict_mono_on.inv (hf : strict_mono_on f s) :
strict_anti_on (λ x, (f x)⁻¹) s :=
λ x hx y hy hxy, inv_lt_inv_iff.2 (hf hx hy hxy)
@[to_additive] lemma strict_anti_on.inv (hf : strict_anti_on f s) :
strict_mono_on (λ x, (f x)⁻¹) s :=
λ x hx y hy hxy, inv_lt_inv_iff.2 (hf hx hy hxy)
end
|
a994646e7abf2dbdf59215db018ff9813867b25d | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/data/multiset/basic.lean | 27727ef87f96d5eeb79b268fde3ca2d405adc55a | [
"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 | 105,530 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.list.perm
import data.list.prod_monoid
/-!
# Multisets
These are implemented as the quotient of a list by permutations.
## Notation
We define the global infix notation `::ₘ` for `multiset.cons`.
-/
open list subtype nat
variables {α : Type*} {β : Type*} {γ : Type*}
/-- `multiset α` is the quotient of `list α` by list permutation. The result
is a type of finite sets with duplicates allowed. -/
def {u} multiset (α : Type u) : Type u :=
quotient (list.is_setoid α)
namespace multiset
instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩
@[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl
@[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl
@[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl
@[simp] theorem coe_eq_coe {l₁ l₂ : list α} : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq
instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α)
| s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂,
decidable_of_iff' _ quotient.eq
/-- defines a size for a multiset by referring to the size of the underlying list -/
protected def sizeof [has_sizeof α] (s : multiset α) : ℕ :=
quot.lift_on s sizeof $ λ l₁ l₂, perm.sizeof_eq_sizeof
instance has_sizeof [has_sizeof α] : has_sizeof (multiset α) := ⟨multiset.sizeof⟩
/-! ### Empty multiset -/
/-- `0 : multiset α` is the empty set -/
protected def zero : multiset α := @nil α
instance : has_zero (multiset α) := ⟨multiset.zero⟩
instance : has_emptyc (multiset α) := ⟨0⟩
instance inhabited_multiset : inhabited (multiset α) := ⟨0⟩
@[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl
@[simp] theorem empty_eq_zero : (∅ : multiset α) = 0 := rfl
theorem coe_eq_zero (l : list α) : (l : multiset α) = 0 ↔ l = [] :=
iff.trans coe_eq_coe perm_nil
/-! ### `multiset.cons` -/
/-- `cons a s` is the multiset which contains `s` plus one more
instance of `a`. -/
def cons (a : α) (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (a :: l : multiset α))
(λ l₁ l₂ p, quot.sound (p.cons a))
infixr ` ::ₘ `:67 := multiset.cons
instance : has_insert α (multiset α) := ⟨cons⟩
@[simp] theorem insert_eq_cons (a : α) (s : multiset α) :
insert a s = a ::ₘ s := rfl
@[simp] theorem cons_coe (a : α) (l : list α) :
(a ::ₘ l : multiset α) = (a::l : list α) := rfl
theorem singleton_coe (a : α) : (a ::ₘ 0 : multiset α) = ([a] : list α) := rfl
@[simp] theorem cons_inj_left {a b : α} (s : multiset α) :
a ::ₘ s = b ::ₘ s ↔ a = b :=
⟨quot.induction_on s $ λ l e,
have [a] ++ l ~ [b] ++ l, from quotient.exact e,
singleton_perm_singleton.1 $ (perm_append_right_iff _).1 this, congr_arg _⟩
@[simp] theorem cons_inj_right (a : α) : ∀{s t : multiset α}, a ::ₘ s = a ::ₘ t ↔ s = t :=
by rintros ⟨l₁⟩ ⟨l₂⟩; simp
@[recursor 5] protected theorem induction {p : multiset α → Prop}
(h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a ::ₘ s)) : ∀s, p s :=
by rintros ⟨l⟩; induction l with _ _ ih; [exact h₁, exact h₂ ih]
@[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop}
(s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a ::ₘ s)) : p s :=
multiset.induction h₁ h₂ s
theorem cons_swap (a b : α) (s : multiset α) : a ::ₘ b ::ₘ s = b ::ₘ a ::ₘ s :=
quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _
section rec
variables {C : multiset α → Sort*}
/-- Dependent recursor on multisets.
TODO: should be @[recursor 6], but then the definition of `multiset.pi` fails with a stack
overflow in `whnf`.
-/
protected def rec
(C_0 : C 0)
(C_cons : Πa m, C m → C (a ::ₘ m))
(C_cons_heq : ∀ a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) ==
C_cons a' (a ::ₘ m) (C_cons a m b))
(m : multiset α) : C m :=
quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $
assume l l' h,
h.rec_heq
(assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc)
(assume a a' l, C_cons_heq a a' ⟦l⟧)
/-- Companion to `multiset.rec` with more convenient argument order. -/
@[elab_as_eliminator]
protected def rec_on (m : multiset α)
(C_0 : C 0)
(C_cons : Πa m, C m → C (a ::ₘ m))
(C_cons_heq : ∀a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) ==
C_cons a' (a ::ₘ m) (C_cons a m b)) :
C m :=
multiset.rec C_0 C_cons C_cons_heq m
variables {C_0 : C 0} {C_cons : Πa m, C m → C (a ::ₘ m)}
{C_cons_heq : ∀a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) ==
C_cons a' (a ::ₘ m) (C_cons a m b)}
@[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 :=
rfl
@[simp] lemma rec_on_cons (a : α) (m : multiset α) :
(a ::ₘ m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) :=
quotient.induction_on m $ assume l, rfl
end rec
section mem
/-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/
def mem (a : α) (s : multiset α) : Prop :=
quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ e.mem_iff)
instance : has_mem α (multiset α) := ⟨mem⟩
@[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl
instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) :=
quot.rec_on_subsingleton s $ list.decidable_mem a
@[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b ::ₘ s ↔ a = b ∨ a ∈ s :=
quot.induction_on s $ λ l, iff.rfl
lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b ::ₘ s :=
mem_cons.2 $ or.inr h
@[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a ::ₘ s :=
mem_cons.2 (or.inl rfl)
theorem forall_mem_cons {p : α → Prop} {a : α} {s : multiset α} :
(∀ x ∈ (a ::ₘ s), p x) ↔ p a ∧ ∀ x ∈ s, p x :=
quotient.induction_on' s $ λ L, list.forall_mem_cons
theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a ::ₘ t :=
quot.induction_on s $ λ l (h : a ∈ l),
let ⟨l₁, l₂, e⟩ := mem_split h in
e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩
@[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id
theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 :=
quot.induction_on s $ λ l H, by rw eq_nil_iff_forall_not_mem.mpr H; refl
theorem eq_zero_iff_forall_not_mem {s : multiset α} : s = 0 ↔ ∀ a, a ∉ s :=
⟨λ h, h.symm ▸ λ _, not_false, eq_zero_of_forall_not_mem⟩
theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s :=
quot.induction_on s $ assume l hl,
match l, hl with
| [] := assume h, false.elim $ h rfl
| (a :: l) := assume _, ⟨a, by simp⟩
end
@[simp] lemma zero_ne_cons {a : α} {m : multiset α} : 0 ≠ a ::ₘ m :=
assume h, have a ∈ (0:multiset α), from h.symm ▸ mem_cons_self _ _, not_mem_zero _ this
@[simp] lemma cons_ne_zero {a : α} {m : multiset α} : a ::ₘ m ≠ 0 := zero_ne_cons.symm
lemma cons_eq_cons {a b : α} {as bs : multiset α} :
a ::ₘ as = b ::ₘ bs ↔ ((a = b ∧ as = bs) ∨ (a ≠ b ∧ ∃cs, as = b ::ₘ cs ∧ bs = a ::ₘ cs)) :=
begin
haveI : decidable_eq α := classical.dec_eq α,
split,
{ assume eq,
by_cases a = b,
{ subst h, simp * at * },
{ have : a ∈ b ::ₘ bs, from eq ▸ mem_cons_self _ _,
have : a ∈ bs, by simpa [h],
rcases exists_cons_of_mem this with ⟨cs, hcs⟩,
simp [h, hcs],
have : a ::ₘ as = b ::ₘ a ::ₘ cs, by simp [eq, hcs],
have : a ::ₘ as = a ::ₘ b ::ₘ cs, by rwa [cons_swap],
simpa using this } },
{ assume h,
rcases h with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩,
{ simp * },
{ simp [*, cons_swap a b] } }
end
end mem
/-! ### `multiset.subset` -/
section subset
/-- `s ⊆ t` is the lift of the list subset relation. It means that any
element with nonzero multiplicity in `s` has nonzero multiplicity in `t`,
but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`;
see `s ≤ t` for this relation. -/
protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t
instance : has_subset (multiset α) := ⟨multiset.subset⟩
@[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl
@[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h
theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u :=
λ h₁ h₂ a m, h₂ (h₁ m)
theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl
theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _
@[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s :=
λ a, (not_mem_nil a).elim
@[simp] theorem cons_subset {a : α} {s t : multiset α} : (a ::ₘ s) ⊆ t ↔ a ∈ t ∧ s ⊆ t :=
by simp [subset_iff, or_imp_distrib, forall_and_distrib]
theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 :=
eq_zero_of_forall_not_mem h
theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 :=
⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩
lemma induction_on' {p : multiset α → Prop} (S : multiset α)
(h₁ : p ∅) (h₂ : ∀ {a s}, a ∈ S → s ⊆ S → p s → p (insert a s)) : p S :=
@multiset.induction_on α (λ T, T ⊆ S → p T) S (λ _, h₁) (λ a s hps hs,
let ⟨hS, sS⟩ := cons_subset.1 hs in h₂ hS sS (hps sS)) (subset.refl S)
end subset
section to_list
/-- Produces a list of the elements in the multiset using choice. -/
@[reducible] noncomputable def to_list {α : Type*} (s : multiset α) :=
classical.some (quotient.exists_rep s)
@[simp] lemma to_list_zero {α : Type*} : (multiset.to_list 0 : list α) = [] :=
(multiset.coe_eq_zero _).1 (classical.some_spec (quotient.exists_rep multiset.zero))
@[simp, norm_cast]
lemma coe_to_list {α : Type*} (s : multiset α) : (s.to_list : multiset α) = s :=
classical.some_spec (quotient.exists_rep _)
@[simp]
lemma mem_to_list {α : Type*} (a : α) (s : multiset α) : a ∈ s.to_list ↔ a ∈ s :=
by rw [←multiset.mem_coe, multiset.coe_to_list]
end to_list
/-! ### Partial order on `multiset`s -/
/-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation).
Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/
protected def le (s t : multiset α) : Prop :=
quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
propext (p₂.subperm_left.trans p₁.subperm_right)
instance : partial_order (multiset α) :=
{ le := multiset.le,
le_refl := by rintros ⟨l⟩; exact subperm.refl _,
le_trans := by rintros ⟨l₁⟩ ⟨l₂⟩ ⟨l₃⟩; exact @subperm.trans _ _ _ _,
le_antisymm := by rintros ⟨l₁⟩ ⟨l₂⟩ h₁ h₂; exact quot.sound (subperm.antisymm h₁ h₂) }
theorem subset_of_le {s t : multiset α} : s ≤ t → s ⊆ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, subperm.subset
theorem mem_of_le {s t : multiset α} {a : α} (h : s ≤ t) : a ∈ s → a ∈ t :=
mem_of_subset (subset_of_le h)
@[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl
@[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop}
{s t : multiset α} (h : s ≤ t)
(H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t :=
quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩,
(show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h
theorem zero_le (s : multiset α) : 0 ≤ s :=
quot.induction_on s $ λ l, (nil_sublist l).subperm
theorem le_zero {s : multiset α} : s ≤ 0 ↔ s = 0 :=
⟨λ h, le_antisymm h (zero_le _), le_of_eq⟩
theorem lt_cons_self (s : multiset α) (a : α) : s < a ::ₘ s :=
quot.induction_on s $ λ l,
suffices l <+~ a :: l ∧ (¬l ~ a :: l),
by simpa [lt_iff_le_and_ne],
⟨(sublist_cons _ _).subperm,
λ p, ne_of_lt (lt_succ_self (length l)) p.length_eq⟩
theorem le_cons_self (s : multiset α) (a : α) : s ≤ a ::ₘ s :=
le_of_lt $ lt_cons_self _ _
theorem cons_le_cons_iff (a : α) {s t : multiset α} : a ::ₘ s ≤ a ::ₘ t ↔ s ≤ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a
theorem cons_le_cons (a : α) {s t : multiset α} : s ≤ t → a ::ₘ s ≤ a ::ₘ t :=
(cons_le_cons_iff a).2
theorem le_cons_of_not_mem {a : α} {s t : multiset α} (m : a ∉ s) : s ≤ a ::ₘ t ↔ s ≤ t :=
begin
refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩,
suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a ::ₘ s ≤ t',
{ exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) },
introv h, revert m, refine le_induction_on h _,
introv s m₁ m₂,
rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩,
exact perm_middle.subperm_left.2 ((subperm_cons _).2 $
((sublist_or_mem_of_sublist s).resolve_right m₁).subperm)
end
/-! ### Singleton -/
instance : has_singleton α (multiset α) := ⟨λ a, a ::ₘ 0⟩
instance : is_lawful_singleton α (multiset α) := ⟨λ a, rfl⟩
theorem singleton_eq_cons (a : α) : singleton a = a ::ₘ 0 := rfl
@[simp] theorem mem_singleton {a b : α} : b ∈ ({a} : multiset α) ↔ b = a :=
by simp only [singleton_eq_cons, mem_cons, iff_self, or_false, not_mem_zero]
theorem mem_singleton_self (a : α) : a ∈ ({a} : multiset α) :=
by { rw singleton_eq_cons, exact mem_cons_self _ _ }
theorem singleton_inj {a b : α} : ({a} : multiset α) = {b} ↔ a = b :=
by { simp_rw [singleton_eq_cons], exact cons_inj_left _ }
@[simp] theorem singleton_ne_zero (a : α) : ({a} : multiset α) ≠ 0 :=
ne_of_gt (lt_cons_self _ _)
@[simp] theorem singleton_le {a : α} {s : multiset α} : {a} ≤ s ↔ a ∈ s :=
⟨λ h, mem_of_le h (mem_singleton_self _),
λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩
/-! ### Additive monoid -/
/-- The sum of two multisets is the lift of the list append operation.
This adds the multiplicities of each element,
i.e. `count a (s + t) = count a s + count a t`. -/
protected def add (s₁ s₂ : multiset α) : multiset α :=
quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $
λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.append p₂
instance : has_add (multiset α) := ⟨multiset.add⟩
@[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl
protected theorem add_comm (s t : multiset α) : s + t = t + s :=
quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_append_comm
protected theorem zero_add (s : multiset α) : 0 + s = s :=
quot.induction_on s $ λ l, rfl
theorem singleton_add (a : α) (s : multiset α) : {a} + s = a ::ₘ s := rfl
protected theorem add_le_add_left (s) {t u : multiset α} : s + t ≤ s + u ↔ t ≤ u :=
quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_append_left _
protected theorem add_left_cancel (s) {t u : multiset α} (h : s + t = s + u) : t = u :=
le_antisymm ((multiset.add_le_add_left _).1 (le_of_eq h))
((multiset.add_le_add_left _).1 (le_of_eq h.symm))
instance : ordered_cancel_add_comm_monoid (multiset α) :=
{ zero := 0,
add := (+),
add_comm := multiset.add_comm,
add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃,
congr_arg coe $ append_assoc l₁ l₂ l₃,
zero_add := multiset.zero_add,
add_zero := λ s, by rw [multiset.add_comm, multiset.zero_add],
add_left_cancel := multiset.add_left_cancel,
add_le_add_left := λ s₁ s₂ h s₃, (multiset.add_le_add_left _).2 h,
le_of_add_le_add_left := λ s₁ s₂ s₃, (multiset.add_le_add_left _).1,
..@multiset.partial_order α }
theorem le_add_right (s t : multiset α) : s ≤ s + t :=
by simpa using add_le_add_left (zero_le t) s
theorem le_add_left (s t : multiset α) : s ≤ t + s :=
by simpa using add_le_add_right (zero_le t) s
theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u :=
⟨λ h, le_induction_on h $ λ l₁ l₂ s,
let ⟨l, p⟩ := s.exists_perm_append in ⟨l, quot.sound p⟩,
λ ⟨u, e⟩, e.symm ▸ le_add_right _ _⟩
instance : order_bot (multiset α) :=
{ bot := 0,
bot_le := multiset.zero_le }
instance : canonically_ordered_add_monoid (multiset α) :=
{ le_iff_exists_add := @le_iff_exists_add _,
..multiset.order_bot,
..multiset.ordered_cancel_add_comm_monoid }
@[simp] theorem cons_add (a : α) (s t : multiset α) : a ::ₘ s + t = a ::ₘ (s + t) :=
by rw [← singleton_add, ← singleton_add, add_assoc]
@[simp] theorem add_cons (a : α) (s t : multiset α) : s + a ::ₘ t = a ::ₘ (s + t) :=
by rw [add_comm, cons_add, add_comm]
@[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, mem_append
lemma mem_of_mem_nsmul {a : α} {s : multiset α} {n : ℕ} (h : a ∈ n • s) : a ∈ s :=
begin
induction n with n ih,
{ rw zero_nsmul at h,
exact absurd h (not_mem_zero _) },
{ rw [succ_nsmul, mem_add] at h,
exact h.elim id ih },
end
@[simp]
lemma mem_nsmul {a : α} {s : multiset α} {n : ℕ} (h0 : n ≠ 0) : a ∈ n • s ↔ a ∈ s :=
begin
refine ⟨mem_of_mem_nsmul, λ h, _⟩,
obtain ⟨n, rfl⟩ := exists_eq_succ_of_ne_zero h0,
rw [succ_nsmul, mem_add],
exact or.inl h
end
lemma nsmul_cons {s : multiset α} (n : ℕ) (a : α) : n • (a ::ₘ s) = n • {a} + n • s :=
by rw [←singleton_add, nsmul_add]
/-! ### Cardinality -/
/-- The cardinality of a multiset is the sum of the multiplicities
of all its elements, or simply the length of the underlying list. -/
def card : multiset α →+ ℕ :=
{ to_fun := λ s, quot.lift_on s length $ λ l₁ l₂, perm.length_eq,
map_zero' := rfl,
map_add' := λ s t, quotient.induction_on₂ s t length_append }
@[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl
@[simp] theorem card_zero : @card α 0 = 0 := rfl
theorem card_add (s t : multiset α) : card (s + t) = card s + card t :=
card.map_add s t
lemma card_nsmul (s : multiset α) (n : ℕ) :
(n • s).card = n * s.card :=
by rw [card.map_nsmul s n, nat.nsmul_eq_mul]
@[simp] theorem card_cons (a : α) (s : multiset α) : card (a ::ₘ s) = card s + 1 :=
quot.induction_on s $ λ l, rfl
@[simp] theorem card_singleton (a : α) : card ({a} : multiset α) = 1 :=
by simp only [singleton_eq_cons, card_zero, eq_self_iff_true, zero_add, card_cons]
theorem card_eq_one {s : multiset α} : card s = 1 ↔ ∃ a, s = {a} :=
⟨quot.induction_on s $ λ l h,
(list.length_eq_one.1 h).imp $ λ a, congr_arg coe,
λ ⟨a, e⟩, e.symm ▸ rfl⟩
theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t :=
le_induction_on h $ λ l₁ l₂, length_le_of_sublist
theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t :=
le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂
theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t :=
lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂
theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a ::ₘ s ≤ t :=
⟨quotient.induction_on₂ s t $ λ l₁ l₂ h,
subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h),
λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩
@[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 :=
⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩
theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 :=
pos_iff_ne_zero.trans $ not_congr card_eq_zero
theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s :=
quot.induction_on s $ λ l, length_pos_iff_exists_mem
/-- A strong induction principle for multisets:
If you construct a value for a particular multiset given values for all strictly smaller multisets,
you can construct a value for any multiset.
-/
@[elab_as_eliminator] def strong_induction_on {p : multiset α → Sort*} :
∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s
| s := λ ih, ih s $ λ t h,
have card t < card s, from card_lt_of_lt h,
strong_induction_on t ih
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]}
theorem strong_induction_eq {p : multiset α → Sort*}
(s : multiset α) (H) : @strong_induction_on _ p s H =
H s (λ t h, @strong_induction_on _ p t H) :=
by rw [strong_induction_on]
@[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop}
(s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a ::ₘ s)) : p s :=
multiset.strong_induction_on s $ assume s,
multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $
λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _
/-- Suppose that, given that `p t` can be defined on all supersets of `s` of cardinality less than
`n`, one knows how to define `p s`. Then one can inductively define `p s` for all multisets `s` of
cardinality less than `n`, starting from multisets of card `n` and iterating. This
can be used either to define data, or to prove properties. -/
def strong_downward_induction {p : multiset α → Sort*} {n : ℕ} (H : ∀ t₁, (∀ {t₂ : multiset α},
t₂.card ≤ n → t₁ < t₂ → p t₂) → t₁.card ≤ n → p t₁) :
∀ (s : multiset α), s.card ≤ n → p s
| s := H s (λ t ht h, have n - card t < n - card s,
from (tsub_lt_tsub_iff_left_of_le ht).2 (card_lt_of_lt h),
strong_downward_induction t ht)
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ (t : multiset α), n - t.card)⟩]}
lemma strong_downward_induction_eq {p : multiset α → Sort*} {n : ℕ} (H : ∀ t₁, (∀ {t₂ : multiset α},
t₂.card ≤ n → t₁ < t₂ → p t₂) → t₁.card ≤ n → p t₁) (s : multiset α) :
strong_downward_induction H s = H s (λ t ht hst, strong_downward_induction H t ht) :=
by rw strong_downward_induction
/-- Analogue of `strong_downward_induction` with order of arguments swapped. -/
@[elab_as_eliminator] def strong_downward_induction_on {p : multiset α → Sort*} {n : ℕ} :
∀ (s : multiset α), (∀ t₁, (∀ {t₂ : multiset α}, t₂.card ≤ n → t₁ < t₂ → p t₂) → t₁.card ≤ n →
p t₁) → s.card ≤ n → p s :=
λ s H, strong_downward_induction H s
lemma strong_downward_induction_on_eq {p : multiset α → Sort*} (s : multiset α) {n : ℕ} (H : ∀ t₁,
(∀ {t₂ : multiset α}, t₂.card ≤ n → t₁ < t₂ → p t₂) → t₁.card ≤ n → p t₁) :
s.strong_downward_induction_on H = H s (λ t ht h, t.strong_downward_induction_on H ht) :=
by { dunfold strong_downward_induction_on, rw strong_downward_induction }
/-- Another way of expressing `strong_induction_on`: the `(<)` relation is well-founded. -/
lemma well_founded_lt : well_founded ((<) : multiset α → multiset α → Prop) :=
subrelation.wf (λ _ _, multiset.card_lt_of_lt) (measure_wf multiset.card)
/-! ### `multiset.repeat` -/
/-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/
def repeat (a : α) (n : ℕ) : multiset α := repeat a n
@[simp] lemma repeat_zero (a : α) : repeat a 0 = 0 := rfl
@[simp] lemma repeat_succ (a : α) (n) : repeat a (n+1) = a ::ₘ repeat a n := by simp [repeat]
@[simp] lemma repeat_one (a : α) : repeat a 1 = {a} :=
by simp only [repeat_succ, singleton_eq_cons, eq_self_iff_true, repeat_zero, cons_inj_right]
@[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat
theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat
theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
(perm_repeat.1 $ (quotient.exact h)), congr_arg coe⟩ eq_repeat'
theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card :=
eq_repeat'.2
theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a :=
⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩,
λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩
theorem repeat_injective (a : α) : function.injective (repeat a) :=
λ m n h, by rw [← (eq_repeat.1 h).1, card_repeat]
theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ {a} := repeat_subset_singleton
theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l :=
⟨λ ⟨l', p, s⟩, (perm_repeat.1 p) ▸ s, sublist.subperm⟩
theorem nsmul_singleton (a : α) (n) : n • ({a} : multiset α) = repeat a n :=
begin
refine eq_repeat.mpr ⟨_, λ b hb, mem_singleton.mp (mem_of_mem_nsmul hb)⟩,
rw [card_nsmul, card_singleton, mul_one]
end
lemma nsmul_repeat {a : α} (n m : ℕ) : n • (repeat a m) = repeat a (n * m) :=
begin
rw eq_repeat,
split,
{ rw [card_nsmul, card_repeat] },
{ exact λ b hb, eq_of_mem_repeat (mem_of_mem_nsmul hb) },
end
/-! ### Erasing one copy of an element -/
section erase
variables [decidable_eq α] {s t : multiset α} {a b : α}
/-- `erase s a` is the multiset that subtracts 1 from the
multiplicity of `a`. -/
def erase (s : multiset α) (a : α) : multiset α :=
quot.lift_on s (λ l, (l.erase a : multiset α))
(λ l₁ l₂ p, quot.sound (p.erase a))
@[simp] theorem coe_erase (l : list α) (a : α) :
erase (l : multiset α) a = l.erase a := rfl
@[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl
@[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a ::ₘ s).erase a = s :=
quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l
@[simp, priority 990]
theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) :
(b ::ₘ s).erase a = b ::ₘ s.erase a :=
quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h
@[simp, priority 980]
theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s :=
quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h
@[simp, priority 980]
theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a ::ₘ s.erase a = s :=
quot.induction_on s $ λ l h, quot.sound (perm_cons_erase h).symm
theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a ::ₘ s.erase a :=
if h : a ∈ s then le_of_eq (cons_erase h).symm
else by rw erase_of_not_mem h; apply le_cons_self
theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t :=
quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h
theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) :
(s + t).erase a = s + t.erase a :=
by rw [add_comm, erase_add_left_pos s h, add_comm]
theorem erase_add_right_neg {a : α} {s : multiset α} (t) :
a ∉ s → (s + t).erase a = s + t.erase a :=
quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h
theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) :
(s + t).erase a = s.erase a + t :=
by rw [add_comm, erase_add_right_neg s h, add_comm]
theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s :=
quot.induction_on s $ λ l, (erase_sublist a l).subperm
@[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s :=
⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h),
λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩
theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s :=
subset_of_le (erase_le a s)
theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s :=
quot.induction_on s $ λ l, list.mem_erase_of_ne ab
theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s :=
mem_of_subset (erase_subset _ _)
theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a :=
quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b
theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a :=
le_induction_on h $ λ l₁ l₂ h, (h.erase _).subperm
theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a ::ₘ t :=
⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h),
λ h, if m : a ∈ s
then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h
else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩
@[simp] theorem card_erase_of_mem {a : α} {s : multiset α} :
a ∈ s → card (s.erase a) = pred (card s) :=
quot.induction_on s $ λ l, length_erase_of_mem
theorem card_erase_lt_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) < card s :=
λ h, card_lt_of_lt (erase_lt.mpr h)
theorem card_erase_le {a : α} {s : multiset α} : card (s.erase a) ≤ card s :=
card_le_of_le (erase_le a s)
theorem card_erase_eq_ite {a : α} {s : multiset α} :
card (s.erase a) = if a ∈ s then pred (card s) else card s :=
begin
by_cases h : a ∈ s,
{ rwa [card_erase_of_mem h, if_pos] },
{ rwa [erase_of_not_mem h, if_neg] }
end
end erase
@[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l :=
quot.sound $ reverse_perm _
/-! ### `multiset.map` -/
/-- `map f s` is the lift of the list `map` operation. The multiplicity
of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity)
such that `f a = b`. -/
def map (f : α → β) (s : multiset α) : multiset β :=
quot.lift_on s (λ l : list α, (l.map f : multiset β))
(λ l₁ l₂ p, quot.sound (p.map f))
theorem forall_mem_map_iff {f : α → β} {p : β → Prop} {s : multiset α} :
(∀ y ∈ s.map f, p y) ↔ (∀ x ∈ s, p (f x)) :=
quotient.induction_on' s $ λ L, list.forall_mem_map_iff
@[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl
@[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl
@[simp] theorem map_cons (f : α → β) (a s) : map f (a ::ₘ s) = f a ::ₘ map f s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl
theorem map_repeat (f : α → β) (a : α) (k : ℕ) : (repeat a k).map f = repeat (f a) k := by
{ induction k, simp, simpa }
@[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _
/-- If each element of `s : multiset α` can be lifted to `β`, then `s` can be lifted to
`multiset β`. -/
instance [can_lift α β] : can_lift (multiset α) (multiset β) :=
{ cond := λ s, ∀ x ∈ s, can_lift.cond β x,
coe := map can_lift.coe,
prf := by { rintro ⟨l⟩ hl, lift l to list β using hl, exact ⟨l, coe_map _ _⟩ } }
/-- `multiset.map` as an `add_monoid_hom`. -/
def map_add_monoid_hom (f : α → β) : multiset α →+ multiset β :=
{ to_fun := map f,
map_zero' := map_zero _,
map_add' := map_add _ }
@[simp] lemma coe_map_add_monoid_hom (f : α → β) :
(map_add_monoid_hom f : multiset α → multiset β) = map f := rfl
theorem map_nsmul (f : α → β) (n : ℕ) (s) : map f (n • s) = n • (map f s) :=
(map_add_monoid_hom f).map_nsmul _ _
@[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} :
b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b :=
quot.induction_on s $ λ l, mem_map
@[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s :=
quot.induction_on s $ λ l, length_map _ _
@[simp] theorem map_eq_zero {s : multiset α} {f : α → β} : s.map f = 0 ↔ s = 0 :=
by rw [← multiset.card_eq_zero, multiset.card_map, multiset.card_eq_zero]
theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s :=
mem_map.2 ⟨_, h, rfl⟩
lemma map_eq_singleton {f : α → β} {s : multiset α} {b : β} :
map f s = {b} ↔ ∃ a : α, s = {a} ∧ f a = b :=
begin
split,
{ intro h,
obtain ⟨a, ha⟩ : ∃ a, s = {a},
{ rw [←card_eq_one, ←card_map, h, card_singleton] },
refine ⟨a, ha, _⟩,
rw [←mem_singleton, ←h, ha, map_singleton, mem_singleton] },
{ rintro ⟨a, rfl, rfl⟩,
simp }
end
theorem mem_map_of_injective {f : α → β} (H : function.injective f) {a : α} {s : multiset α} :
f a ∈ map f s ↔ a ∈ s :=
quot.induction_on s $ λ l, mem_map_of_injective H
@[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) :
map g (map f s) = map (g ∘ f) s :=
quot.induction_on s $ λ l, congr_arg coe $ list.map_map _ _ _
theorem map_id (s : multiset α) : map id s = s :=
quot.induction_on s $ λ l, congr_arg coe $ map_id _
@[simp] lemma map_id' (s : multiset α) : map (λx, x) s = s := map_id s
@[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card :=
quot.induction_on s $ λ l, congr_arg coe $ map_const _ _
@[congr] theorem map_congr {f g : α → β} {s : multiset α} :
(∀ x ∈ s, f x = g x) → map f s = map g s :=
quot.induction_on s $ λ l H, congr_arg coe $ map_congr H
lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'}
(h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m :=
begin subst h, simp at hf, simp [map_congr hf] end
theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) :
b₁ = b₂ :=
eq_of_mem_repeat $ by rwa map_const at h
@[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t :=
le_induction_on h $ λ l₁ l₂ h, (h.map f).subperm
@[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t :=
λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩
lemma map_erase [decidable_eq α] [decidable_eq β]
(f : α → β) (hf : function.injective f) (x : α) (s : multiset α) :
(s.erase x).map f = (s.map f).erase (f x) :=
begin
induction s using multiset.induction_on with y s ih,
{ simp },
by_cases hxy : y = x,
{ cases hxy, simp },
{ rw [s.erase_cons_tail hxy, map_cons, map_cons, (s.map f).erase_cons_tail (hf.ne hxy), ih] }
end
/-! ### `multiset.fold` -/
/-- `foldl f H b s` is the lift of the list operation `foldl f b l`,
which folds `f` over the multiset. It is well defined when `f` is right-commutative,
that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/
def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β :=
quot.lift_on s (λ l, foldl f b l)
(λ l₁ l₂ p, p.foldl_eq H b)
@[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl
@[simp] theorem foldl_cons (f : β → α → β) (H b a s) :
foldl f H b (a ::ₘ s) = foldl f H (f b a) s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem foldl_add (f : β → α → β) (H b s t) :
foldl f H b (s + t) = foldl f H (foldl f H b s) t :=
quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _
/-- `foldr f H b s` is the lift of the list operation `foldr f b l`,
which folds `f` over the multiset. It is well defined when `f` is left-commutative,
that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/
def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β :=
quot.lift_on s (λ l, foldr f b l)
(λ l₁ l₂ p, p.foldr_eq H b)
@[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl
@[simp] theorem foldr_cons (f : α → β → β) (H b a s) :
foldr f H b (a ::ₘ s) = f a (foldr f H b s) :=
quot.induction_on s $ λ l, rfl
@[simp] theorem foldr_singleton (f : α → β → β) (H b a) :
foldr f H b ({a} : multiset α) = f a b :=
rfl
@[simp] theorem foldr_add (f : α → β → β) (H b s t) :
foldr f H b (s + t) = foldr f H (foldr f H b t) s :=
quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _
@[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) :
foldr f H b l = l.foldr f b := rfl
@[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) :
foldl f H b l = l.foldl f b := rfl
theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) :
foldr f H b l = l.foldl (λ x y, f y x) b :=
(congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _
theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) :
foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s :=
quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _
theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) :
foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s :=
(foldr_swap _ _ _ _).symm
lemma foldr_induction' (f : α → β → β) (H : left_commutative f) (x : β) (q : α → Prop)
(p : β → Prop) (s : multiset α) (hpqf : ∀ a b, q a → p b → p (f a b)) (px : p x)
(q_s : ∀ a ∈ s, q a) :
p (foldr f H x s) :=
begin
revert s,
refine multiset.induction (by simp [px]) _,
intros a s hs hsa,
rw foldr_cons,
have hps : ∀ (x : α), x ∈ s → q x, from λ x hxs, hsa x (mem_cons_of_mem hxs),
exact hpqf a (foldr f H x s) (hsa a (mem_cons_self a s)) (hs hps),
end
lemma foldr_induction (f : α → α → α) (H : left_commutative f) (x : α) (p : α → Prop)
(s : multiset α) (p_f : ∀ a b, p a → p b → p (f a b)) (px : p x) (p_s : ∀ a ∈ s, p a) :
p (foldr f H x s) :=
foldr_induction' f H x p p s p_f px p_s
lemma foldl_induction' (f : β → α → β) (H : right_commutative f) (x : β) (q : α → Prop)
(p : β → Prop) (s : multiset α) (hpqf : ∀ a b, q a → p b → p (f b a)) (px : p x)
(q_s : ∀ a ∈ s, q a) :
p (foldl f H x s) :=
begin
rw foldl_swap,
exact foldr_induction' (λ x y, f y x) (λ x y z, (H _ _ _).symm) x q p s hpqf px q_s,
end
lemma foldl_induction (f : α → α → α) (H : right_commutative f) (x : α) (p : α → Prop)
(s : multiset α) (p_f : ∀ a b, p a → p b → p (f b a)) (px : p x) (p_s : ∀ a ∈ s, p a) :
p (foldl f H x s) :=
foldl_induction' f H x p p s p_f px p_s
/-- Product of a multiset given a commutative monoid structure on `α`.
`prod {a, b, c} = a * b * c` -/
@[to_additive "Sum of a multiset given a commutative additive monoid structure on `α`.
`sum {a, b, c} = a + b + c`"]
def prod [comm_monoid α] : multiset α → α :=
foldr (*) (λ x y z, by simp [mul_left_comm]) 1
@[to_additive]
theorem prod_eq_foldr [comm_monoid α] (s : multiset α) :
prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl
@[to_additive]
theorem prod_eq_foldl [comm_monoid α] (s : multiset α) :
prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s :=
(foldr_swap _ _ _ _).trans (by simp [mul_comm])
@[simp, norm_cast, to_additive]
theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod :=
prod_eq_foldl _
@[simp, to_additive] theorem prod_to_list [comm_monoid α] (s : multiset α) :
s.to_list.prod = s.prod :=
begin
conv_rhs { rw ←coe_to_list s, },
rw coe_prod,
end
@[simp, to_additive]
theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl
@[simp, to_additive]
theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a ::ₘ s) = a * prod s :=
foldr_cons _ _ _ _ _
@[simp, to_additive]
theorem prod_singleton [comm_monoid α] (a : α) : prod {a} = a :=
by simp only [mul_one, prod_cons, singleton_eq_cons, eq_self_iff_true, prod_zero]
@[simp, to_additive]
theorem prod_add [comm_monoid α] (s t : multiset α) : prod (s + t) = prod s * prod t :=
quotient.induction_on₂ s t $ λ l₁ l₂, by simp
/-- `multiset.sum`, the sum of the elements of a multiset, promoted to a morphism of
`add_comm_monoid`s. -/
def sum_add_monoid_hom [add_comm_monoid α] : multiset α →+ α :=
{ to_fun := sum,
map_zero' := sum_zero,
map_add' := sum_add }
@[simp] lemma coe_sum_add_monoid_hom [add_comm_monoid α] :
(sum_add_monoid_hom : multiset α → α) = sum := rfl
lemma prod_nsmul {α : Type*} [comm_monoid α] (m : multiset α) :
∀ (n : ℕ), (n • m).prod = m.prod ^ n
| 0 := by { rw [zero_nsmul, pow_zero], refl }
| (n + 1) :=
by rw [add_nsmul, one_nsmul, pow_add, pow_one, prod_add, prod_nsmul n]
@[simp, to_additive] theorem prod_repeat [comm_monoid α] (a : α) (n : ℕ) :
prod (multiset.repeat a n) = a ^ n :=
by simp [repeat, list.prod_repeat]
@[to_additive]
lemma prod_map_one [comm_monoid γ] {m : multiset α} :
prod (m.map (λa, (1 : γ))) = (1 : γ) :=
by simp
@[simp, to_additive]
lemma prod_map_mul [comm_monoid γ] {m : multiset α} {f g : α → γ} :
prod (m.map $ λa, f a * g a) = prod (m.map f) * prod (m.map g) :=
multiset.induction_on m (by simp) (assume a m ih, by simp [ih]; cc)
@[to_additive]
lemma prod_map_prod_map [comm_monoid γ] (m : multiset α) (n : multiset β) {f : α → β → γ} :
prod (m.map $ λa, prod $ n.map $ λb, f a b) = prod (n.map $ λb, prod $ m.map $ λa, f a b) :=
multiset.induction_on m (by simp) (assume a m ih, by simp [ih])
lemma sum_map_mul_left [semiring β] {b : β} {s : multiset α} {f : α → β} :
sum (s.map (λa, b * f a)) = b * sum (s.map f) :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, mul_add])
lemma sum_map_mul_right [semiring β] {b : β} {s : multiset α} {f : α → β} :
sum (s.map (λa, f a * b)) = sum (s.map f) * b :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, add_mul])
lemma prod_eq_zero {M₀ : Type*} [comm_monoid_with_zero M₀] {s : multiset M₀} (h : (0 : M₀) ∈ s) :
multiset.prod s = 0 :=
begin
rcases multiset.exists_cons_of_mem h with ⟨s', hs'⟩,
simp [hs', multiset.prod_cons]
end
lemma prod_eq_zero_iff {M₀ : Type*} [comm_monoid_with_zero M₀] [no_zero_divisors M₀] [nontrivial M₀]
{s : multiset M₀} :
multiset.prod s = 0 ↔ (0 : M₀) ∈ s :=
by { rcases s with ⟨l⟩, simp }
theorem prod_ne_zero {M₀ : Type*} [comm_monoid_with_zero M₀] [no_zero_divisors M₀] [nontrivial M₀]
{m : multiset M₀} (h : (0 : M₀) ∉ m) : m.prod ≠ 0 :=
mt prod_eq_zero_iff.1 h
@[to_additive]
lemma prod_hom [comm_monoid α] [comm_monoid β] (s : multiset α) (f : α →* β) :
(s.map f).prod = f s.prod :=
quotient.induction_on s $ λ l, by simp only [l.prod_hom f, quot_mk_to_coe, coe_map, coe_prod]
@[to_additive]
theorem prod_hom_rel [comm_monoid β] [comm_monoid γ] (s : multiset α) {r : β → γ → Prop}
{f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) :
r (s.map f).prod (s.map g).prod :=
quotient.induction_on s $ λ l,
by simp only [l.prod_hom_rel h₁ h₂, quot_mk_to_coe, coe_map, coe_prod]
@[simp] lemma coe_inv_monoid_hom {G : Type*} [comm_group G] :
(comm_group.inv_monoid_hom : G → G) = has_inv.inv := rfl
@[simp, to_additive]
lemma prod_map_inv {G : Type*} [comm_group G] (m : multiset G) :
(m.map has_inv.inv).prod = m.prod⁻¹ :=
m.prod_hom comm_group.inv_monoid_hom
lemma dvd_prod [comm_monoid α] {a : α} {s : multiset α} : a ∈ s → a ∣ s.prod :=
quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a
lemma prod_dvd_prod [comm_monoid α] {s t : multiset α} (h : s ≤ t) :
s.prod ∣ t.prod :=
begin
rcases multiset.le_iff_exists_add.1 h with ⟨z, rfl⟩,
simp,
end
lemma prod_nonneg [ordered_comm_semiring α] {m : multiset α} (h : ∀ a ∈ m, (0 : α) ≤ a) :
0 ≤ m.prod :=
begin
revert h,
refine m.induction_on _ _,
{ rintro -, rw prod_zero, exact zero_le_one },
{ intros a s hs ih,
rw prod_cons,
apply mul_nonneg,
{ exact ih _ (mem_cons_self _ _) },
{ exact hs (λ a ha, ih _ (mem_cons_of_mem ha)) } }
end
@[to_additive sum_nonneg]
lemma one_le_prod_of_one_le [ordered_comm_monoid α] {m : multiset α} :
(∀ x ∈ m, (1 : α) ≤ x) → 1 ≤ m.prod :=
quotient.induction_on m $ λ l hl, by simpa using list.one_le_prod_of_one_le hl
@[to_additive]
lemma single_le_prod [ordered_comm_monoid α] {m : multiset α} :
(∀ x ∈ m, (1 : α) ≤ x) → ∀ x ∈ m, x ≤ m.prod :=
quotient.induction_on m $ λ l hl x hx, by simpa using list.single_le_prod hl x hx
@[to_additive]
lemma prod_le_of_forall_le [ordered_comm_monoid α] (l : multiset α) (n : α) (h : ∀ (x ∈ l), x ≤ n) :
l.prod ≤ n ^ l.card :=
begin
induction l using quotient.induction_on,
simpa using list.prod_le_of_forall_le _ _ h
end
@[to_additive all_zero_of_le_zero_le_of_sum_eq_zero]
lemma all_one_of_le_one_le_of_prod_eq_one [ordered_comm_monoid α] {m : multiset α} :
(∀ x ∈ m, (1 : α) ≤ x) → m.prod = 1 → (∀ x ∈ m, x = (1 : α)) :=
begin
apply quotient.induction_on m,
simp only [quot_mk_to_coe, coe_prod, mem_coe],
exact λ l, all_one_of_le_one_le_of_prod_eq_one,
end
lemma sum_eq_zero_iff [canonically_ordered_add_monoid α] {m : multiset α} :
m.sum = 0 ↔ ∀ x ∈ m, x = (0 : α) :=
quotient.induction_on m $ λ l, by simpa using list.sum_eq_zero_iff l
@[to_additive]
lemma prod_induction {M : Type*} [comm_monoid M] (p : M → Prop) (s : multiset M)
(p_mul : ∀ a b, p a → p b → p (a * b)) (p_one : p 1) (p_s : ∀ a ∈ s, p a) :
p s.prod :=
begin
rw prod_eq_foldr,
exact foldr_induction (*) (λ x y z, by simp [mul_left_comm]) 1 p s p_mul p_one p_s,
end
@[to_additive le_sum_of_subadditive_on_pred]
lemma le_prod_of_submultiplicative_on_pred [comm_monoid α] [ordered_comm_monoid β]
(f : α → β) (p : α → Prop) (h_one : f 1 = 1) (hp_one : p 1)
(h_mul : ∀ a b, p a → p b → f (a * b) ≤ f a * f b)
(hp_mul : ∀ a b, p a → p b → p (a * b)) (s : multiset α) (hps : ∀ a, a ∈ s → p a) :
f s.prod ≤ (s.map f).prod :=
begin
revert s,
refine multiset.induction _ _,
{ simp [le_of_eq h_one], },
intros a s hs hpsa,
have hps : ∀ x, x ∈ s → p x, from λ x hx, hpsa x (mem_cons_of_mem hx),
have hp_prod : p s.prod, from prod_induction p s hp_mul hp_one hps,
rw [prod_cons, map_cons, prod_cons],
exact (h_mul a s.prod (hpsa a (mem_cons_self a s)) hp_prod).trans (mul_le_mul_left' (hs hps) _),
end
@[to_additive le_sum_of_subadditive]
lemma le_prod_of_submultiplicative [comm_monoid α] [ordered_comm_monoid β]
(f : α → β) (h_one : f 1 = 1) (h_mul : ∀ a b, f (a * b) ≤ f a * f b) (s : multiset α) :
f s.prod ≤ (s.map f).prod :=
le_prod_of_submultiplicative_on_pred f (λ i, true) h_one trivial (λ x y _ _ , h_mul x y) (by simp)
s (by simp)
@[to_additive]
lemma prod_induction_nonempty {M : Type*} [comm_monoid M] (p : M → Prop)
(p_mul : ∀ a b, p a → p b → p (a * b)) {s : multiset M} (hs_nonempty : s ≠ ∅)
(p_s : ∀ a ∈ s, p a) :
p s.prod :=
begin
revert s,
refine multiset.induction _ _,
{ intro h,
exfalso,
simpa using h, },
intros a s hs hsa hpsa,
rw prod_cons,
by_cases hs_empty : s = ∅,
{ simp [hs_empty, hpsa a], },
have hps : ∀ (x : M), x ∈ s → p x, from λ x hxs, hpsa x (mem_cons_of_mem hxs),
exact p_mul a s.prod (hpsa a (mem_cons_self a s)) (hs hs_empty hps),
end
@[to_additive le_sum_nonempty_of_subadditive_on_pred]
lemma le_prod_nonempty_of_submultiplicative_on_pred [comm_monoid α] [ordered_comm_monoid β]
(f : α → β) (p : α → Prop) (h_mul : ∀ a b, p a → p b → f (a * b) ≤ f a * f b)
(hp_mul : ∀ a b, p a → p b → p (a * b)) (s : multiset α) (hs_nonempty : s ≠ ∅)
(hs : ∀ a, a ∈ s → p a) :
f s.prod ≤ (s.map f).prod :=
begin
revert s,
refine multiset.induction _ _,
{ intro h,
exfalso,
exact h rfl, },
rintros a s hs hsa_nonempty hsa_prop,
rw [prod_cons, map_cons, prod_cons],
by_cases hs_empty : s = ∅,
{ simp [hs_empty], },
have hsa_restrict : (∀ x, x ∈ s → p x), from λ x hx, hsa_prop x (mem_cons_of_mem hx),
have hp_sup : p s.prod,
from prod_induction_nonempty p hp_mul hs_empty hsa_restrict,
have hp_a : p a, from hsa_prop a (mem_cons_self a s),
exact (h_mul a _ hp_a hp_sup).trans (mul_le_mul_left' (hs hs_empty hsa_restrict) _),
end
@[to_additive le_sum_nonempty_of_subadditive]
lemma le_prod_nonempty_of_submultiplicative [comm_monoid α] [ordered_comm_monoid β]
(f : α → β) (h_mul : ∀ a b, f (a * b) ≤ f a * f b) (s : multiset α) (hs_nonempty : s ≠ ∅) :
f s.prod ≤ (s.map f).prod :=
le_prod_nonempty_of_submultiplicative_on_pred f (λ i, true) (by simp [h_mul]) (by simp) s
hs_nonempty (by simp)
theorem dvd_sum [comm_semiring α] {a : α} {s : multiset α} : (∀ x ∈ s, a ∣ x) → a ∣ s.sum :=
multiset.induction_on s (λ _, dvd_zero _)
(λ x s ih h, by rw sum_cons; exact dvd_add
(h _ (mem_cons_self _ _)) (ih (λ y hy, h _ (mem_cons.2 (or.inr hy)))))
@[simp] theorem sum_map_singleton (s : multiset α) : (s.map (λ a, ({a} : multiset α))).sum = s :=
multiset.induction_on s (by simp) (by simp [singleton_eq_cons])
theorem abs_sum_le_sum_abs [linear_ordered_add_comm_group α] {s : multiset α} :
abs s.sum ≤ (s.map abs).sum :=
le_sum_of_subadditive _ abs_zero abs_add s
/-! ### Join -/
/-- `join S`, where `S` is a multiset of multisets, is the lift of the list join
operation, that is, the union of all the sets.
join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/
def join : multiset (multiset α) → multiset α := sum
theorem coe_join : ∀ L : list (list α),
join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join
| [] := rfl
| (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L)
@[simp] theorem join_zero : @join α 0 = 0 := rfl
@[simp] theorem join_cons (s S) : @join α (s ::ₘ S) = s + join S :=
sum_cons _ _
@[simp] theorem join_add (S T) : @join α (S + T) = join S + join T :=
sum_add _ _
@[simp] theorem singleton_join (a) : join ({a} : multiset (multiset α)) = a :=
sum_singleton _
@[simp] theorem mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s :=
multiset.induction_on S (by simp) $
by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt}
@[simp] theorem card_join (S) : card (@join α S) = sum (map card S) :=
multiset.induction_on S (by simp) (by simp)
/-! ### `multiset.bind` -/
/-- `bind s f` is the monad bind operation, defined as `join (map f s)`.
It is the union of `f a` as `a` ranges over `s`. -/
def bind (s : multiset α) (f : α → multiset β) : multiset β :=
join (map f s)
@[simp] theorem coe_bind (l : list α) (f : α → list β) :
@bind α β l (λ a, f a) = l.bind f :=
by rw [list.bind, ← coe_join, list.map_map]; refl
@[simp] theorem zero_bind (f : α → multiset β) : bind 0 f = 0 := rfl
@[simp] theorem cons_bind (a s) (f : α → multiset β) : bind (a ::ₘ s) f = f a + bind s f :=
by simp [bind]
@[simp] theorem singleton_bind (a) (f : α → multiset β) : bind {a} f = f a :=
by simp [bind]
@[simp] theorem add_bind (s t) (f : α → multiset β) : bind (s + t) f = bind s f + bind t f :=
by simp [bind]
@[simp] theorem bind_zero (s : multiset α) : bind s (λa, 0 : α → multiset β) = 0 :=
by simp [bind, join, nsmul_zero]
@[simp] theorem bind_add (s : multiset α) (f g : α → multiset β) :
bind s (λa, f a + g a) = bind s f + bind s g :=
by simp [bind, join]
@[simp] theorem bind_cons (s : multiset α) (f : α → β) (g : α → multiset β) :
bind s (λa, f a ::ₘ g a) = map f s + bind s g :=
multiset.induction_on s (by simp) (by simp [add_comm, add_left_comm] {contextual := tt})
@[simp] theorem bind_singleton (s : multiset α) (f : α → β) :
bind s (λ x, ({f x} : multiset β)) = map f s :=
multiset.induction_on s (by rw [zero_bind, map_zero]) (by simp [singleton_add])
@[simp] theorem mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a :=
by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm];
rw exists_swap; simp [and_assoc]
@[simp] theorem card_bind (s) (f : α → multiset β) : card (bind s f) = sum (map (card ∘ f) s) :=
by simp [bind]
lemma bind_congr {f g : α → multiset β} {m : multiset α} :
(∀a∈m, f a = g a) → bind m f = bind m g :=
by simp [bind] {contextual := tt}
lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'}
(h : β = β') (hf : ∀a∈m, f a == f' a) : bind m f == bind m f' :=
begin subst h, simp at hf, simp [bind_congr hf] end
lemma map_bind (m : multiset α) (n : α → multiset β) (f : β → γ) :
map f (bind m n) = bind m (λa, map f (n a)) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_map (m : multiset α) (n : β → multiset γ) (f : α → β) :
bind (map f m) n = bind m (λa, n (f a)) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_assoc {s : multiset α} {f : α → multiset β} {g : β → multiset γ} :
(s.bind f).bind g = s.bind (λa, (f a).bind g) :=
multiset.induction_on s (by simp) (by simp {contextual := tt})
lemma bind_bind (m : multiset α) (n : multiset β) {f : α → β → multiset γ} :
(bind m $ λa, bind n $ λb, f a b) = (bind n $ λb, bind m $ λa, f a b) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_map_comm (m : multiset α) (n : multiset β) {f : α → β → γ} :
(bind m $ λa, n.map $ λb, f a b) = (bind n $ λb, m.map $ λa, f a b) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
@[simp, to_additive]
lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) :
prod (bind s t) = prod (s.map $ λa, prod (t a)) :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind])
/-! ### Product of two `multiset`s -/
/-- The multiplicity of `(a, b)` in `product s t` is
the product of the multiplicity of `a` in `s` and `b` in `t`. -/
def product (s : multiset α) (t : multiset β) : multiset (α × β) :=
s.bind $ λ a, t.map $ prod.mk a
@[simp] theorem coe_product (l₁ : list α) (l₂ : list β) :
@product α β l₁ l₂ = l₁.product l₂ :=
by rw [product, list.product, ← coe_bind]; simp
@[simp] theorem zero_product (t) : @product α β 0 t = 0 := rfl
@[simp] theorem cons_product (a : α) (s : multiset α) (t : multiset β) :
product (a ::ₘ s) t = map (prod.mk a) t + product s t :=
by simp [product]
@[simp] theorem product_singleton (a : α) (b : β) :
product ({a} : multiset α) ({b} : multiset β) = {(a,b)} :=
by simp only [product, bind_singleton, map_singleton]
@[simp] theorem add_product (s t : multiset α) (u : multiset β) :
product (s + t) u = product s u + product t u :=
by simp [product]
@[simp] theorem product_add (s : multiset α) : ∀ t u : multiset β,
product s (t + u) = product s t + product s u :=
multiset.induction_on s (λ t u, rfl) $ λ a s IH t u,
by rw [cons_product, IH]; simp; cc
@[simp] theorem mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t
| (a, b) := by simp [product, and.left_comm]
@[simp] theorem card_product (s : multiset α) (t : multiset β) :
card (product s t) = card s * card t :=
by simp [product, repeat, (∘), mul_comm]
/-! ### Sigma multiset -/
section
variable {σ : α → Type*}
/-- `sigma s t` is the dependent version of `product`. It is the sum of
`(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/
protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) :=
s.bind $ λ a, (t a).map $ sigma.mk a
@[simp] theorem coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) :
@multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ :=
by rw [multiset.sigma, list.sigma, ← coe_bind]; simp
@[simp] theorem zero_sigma (t) : @multiset.sigma α σ 0 t = 0 := rfl
@[simp] theorem cons_sigma (a : α) (s : multiset α) (t : Π a, multiset (σ a)) :
(a ::ₘ s).sigma t = map (sigma.mk a) (t a) + s.sigma t :=
by simp [multiset.sigma]
@[simp] theorem sigma_singleton (a : α) (b : α → β) :
({a} : multiset α).sigma (λ a, ({b a} : multiset β)) = {⟨a, b a⟩} := rfl
@[simp] theorem add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) :
(s + t).sigma u = s.sigma u + t.sigma u :=
by simp [multiset.sigma]
@[simp] theorem sigma_add (s : multiset α) : ∀ t u : Π a, multiset (σ a),
s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u :=
multiset.induction_on s (λ t u, rfl) $ λ a s IH t u,
by rw [cons_sigma, IH]; simp; cc
@[simp] theorem mem_sigma {s t} : ∀ {p : Σ a, σ a},
p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1
| ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm]
@[simp] theorem card_sigma (s : multiset α) (t : Π a, multiset (σ a)) :
card (s.sigma t) = sum (map (λ a, card (t a)) s) :=
by simp [multiset.sigma, (∘)]
end
/-! ### Map for partial functions -/
/-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset
`s` whose elements are all in the domain of `f`. -/
def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β :=
quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂),
funext $ λ (H₂ : ∀ a ∈ l₂, p a),
have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a (pp.subset h),
have ∀ {s₂ e H}, @eq.rec (multiset α) l₁
(λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁))
s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e,
this.trans $ quot.sound $ pp.pmap f
@[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β)
(l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl
@[simp] lemma pmap_zero {p : α → Prop} (f : Π a, p a → β) (h : ∀a∈(0:multiset α), p a) :
pmap f 0 h = 0 := rfl
@[simp] lemma pmap_cons {p : α → Prop} (f : Π a, p a → β) (a : α) (m : multiset α) :
∀(h : ∀b∈a ::ₘ m, p b), pmap f (a ::ₘ m) h =
f a (h a (mem_cons_self a m)) ::ₘ pmap f m (λa ha, h a $ mem_cons_of_mem ha) :=
quotient.induction_on m $ assume l h, rfl
/-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce
a multiset on `{x // x ∈ s}`. -/
def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id)
@[simp] theorem coe_attach (l : list α) :
@eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl
theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {s : multiset α} (hx : x ∈ s) :
sizeof x < sizeof s := by
{ induction s with l a b, exact list.sizeof_lt_sizeof_of_mem hx, refl }
theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) :
∀ H, @pmap _ _ p (λ a _, f a) s H = map f s :=
quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H
theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β}
(s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) :
pmap f s H₁ = pmap g s H₂ :=
quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂
theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β)
(s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H :=
quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H
theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β)
(s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) :=
quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H
theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s :=
quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l
@[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach :=
quot.induction_on s $ λ l, mem_attach _
@[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β}
{s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b :=
quot.induction_on s (λ l H, mem_pmap) H
@[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β)
(s H) : card (pmap f s H) = card s :=
quot.induction_on s (λ l H, length_pmap) H
@[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _
@[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl
lemma attach_cons (a : α) (m : multiset α) :
(a ::ₘ m).attach = ⟨a, mem_cons_self a m⟩ ::ₘ (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) :=
quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $
by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl)
section decidable_pi_exists
variables {m : multiset α}
/-- If `p` is a decidable predicate,
so is the predicate that all elements of a multiset satisfy `p`. -/
protected def decidable_forall_multiset {p : α → Prop} [hp : ∀a, decidable (p a)] :
decidable (∀a∈m, p a) :=
quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a∈l, p a) $ by simp)
instance decidable_dforall_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] :
decidable (∀a (h : a ∈ m), p a h) :=
decidable_of_decidable_of_iff
(@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _)
(iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _))
/-- decidable equality for functions whose domain is bounded by multisets -/
instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀a, decidable_eq (β a)] :
decidable_eq (Πa∈m, β a) :=
assume f g, decidable_of_iff (∀a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff])
/-- If `p` is a decidable predicate,
so is the existence of an element in a multiset satisfying `p`. -/
def decidable_exists_multiset {p : α → Prop} [decidable_pred p] :
decidable (∃ x ∈ m, p x) :=
quotient.rec_on_subsingleton m list.decidable_exists_mem
instance decidable_dexists_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] :
decidable (∃a (h : a ∈ m), p a h) :=
decidable_of_decidable_of_iff
(@multiset.decidable_exists_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _)
(iff.intro (λ ⟨⟨a, ha₁⟩, _, ha₂⟩, ⟨a, ha₁, ha₂⟩)
(λ ⟨a, ha₁, ha₂⟩, ⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩))
end decidable_pi_exists
/-! ### Subtraction -/
section
variables [decidable_eq α] {s t u : multiset α} {a b : α}
/-- `s - t` is the multiset such that `count a (s - t) = count a s - count a t` for all `a`
(note that it is truncated subtraction, so it is `0` if `count a t ≥ count a s`). -/
protected def sub (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ p₁.diff p₂
instance : has_sub (multiset α) := ⟨multiset.sub⟩
@[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl
/-- This is a special case of `tsub_zero`, which should be used instead of this.
This is needed to prove `has_ordered_sub (multiset α)`. -/
protected theorem sub_zero (s : multiset α) : s - 0 = s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a ::ₘ t = s.erase a - t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _
/-- This is a special case of `tsub_le_iff_right`, which should be used instead of this.
This is needed to prove `has_ordered_sub (multiset α)`. -/
protected theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t :=
by revert s; exact
multiset.induction_on t (by simp [multiset.sub_zero])
(λ a t IH s, by simp [IH, erase_le_iff_le_cons])
instance : has_ordered_sub (multiset α) :=
⟨λ n m k, multiset.sub_le_iff_le_add⟩
theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t :=
quotient.induction_on₂ s t $ λ l₁ l₂,
show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂,
by { rw diff_eq_foldl l₁ l₂, symmetry, exact foldl_hom _ _ _ _ _ (λ x y, rfl) }
@[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t :=
(tsub_eq_of_eq_add_rev $ by rw [add_comm, ← card_add, tsub_add_cancel_of_le h]).symm
/-! ### Union -/
/-- `s ∪ t` is the lattice join operation with respect to the
multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum
of the multiplicities in `s` and `t`. -/
def union (s t : multiset α) : multiset α := s - t + t
instance : has_union (multiset α) := ⟨union⟩
theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl
theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_tsub_add
theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _
theorem eq_union_left : t ≤ s → s ∪ t = s := tsub_add_cancel_of_le
theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u :=
add_le_add_right (tsub_le_tsub_right h _) u
theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u :=
by rw ← eq_union_left h₂; exact union_le_union_right h₁ t
@[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t :=
⟨λ h, (mem_add.1 h).imp_left (mem_of_le tsub_le_self),
or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩
@[simp] theorem map_union [decidable_eq β] {f : α → β} (finj : function.injective f)
{s t : multiset α} :
map f (s ∪ t) = map f s ∪ map f t :=
quotient.induction_on₂ s t $ λ l₁ l₂,
congr_arg coe (by rw [list.map_append f, list.map_diff finj])
/-! ### Intersection -/
/-- `s ∩ t` is the lattice meet operation with respect to the
multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum
of the multiplicities in `s` and `t`. -/
def inter (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ p₁.bag_inter p₂
instance : has_inter (multiset α) := ⟨inter⟩
@[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 :=
quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil
@[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 :=
quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter
@[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} :
a ∈ t → (a ::ₘ s) ∩ t = a ::ₘ s ∩ t.erase a :=
quotient.induction_on₂ s t $ λ l₁ l₂ h,
congr_arg coe $ cons_bag_inter_of_pos _ h
@[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} :
a ∉ t → (a ::ₘ s) ∩ t = s ∩ t :=
quotient.induction_on₂ s t $ λ l₁ l₂ h,
congr_arg coe $ cons_bag_inter_of_neg _ h
theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s :=
quotient.induction_on₂ s t $ λ l₁ l₂,
(bag_inter_sublist_left _ _).subperm
theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t :=
multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $
λ a s IH t, if h : a ∈ t
then by simpa [h] using cons_le_cons a (IH (t.erase a))
else by simp [h, IH]
theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u :=
begin
revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros,
{ simp [h₁] },
by_cases a ∈ u,
{ rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons],
exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) },
{ rw cons_inter_of_neg _ h,
exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ }
end
@[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t :=
⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩,
λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩
instance : lattice (multiset α) :=
{ sup := (∪),
sup_le := @union_le _ _,
le_sup_left := le_union_left,
le_sup_right := le_union_right,
inf := (∩),
le_inf := @le_inter _ _,
inf_le_left := inter_le_left,
inf_le_right := inter_le_right,
..@multiset.partial_order α }
@[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl
@[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl
@[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff
@[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff
instance : semilattice_inf_bot (multiset α) :=
{ bot := 0, bot_le := zero_le, ..multiset.lattice }
theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm
theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm
theorem eq_union_right (h : s ≤ t) : s ∪ t = t :=
by rw [union_comm, eq_union_left h]
theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t :=
sup_le_sup_left h _
theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t :=
union_le (le_add_right _ _) (le_add_left _ _)
theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) :=
by simpa [(∪), union, eq_comm, add_assoc] using show s + u - (t + u) = s - t,
by rw [add_comm t, tsub_add_eq_tsub_tsub, add_tsub_cancel_right]
theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) :=
by rw [add_comm, union_add_distrib, add_comm s, add_comm s]
theorem cons_union_distrib (a : α) (s t : multiset α) : a ::ₘ (s ∪ t) = (a ::ₘ s) ∪ (a ::ₘ t) :=
by simpa using add_union_distrib (a ::ₘ 0) s t
theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) :=
begin
by_contra h,
cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter
(add_le_add_right (inter_le_left s t) u)
(add_le_add_right (inter_le_right s t) u)) h) with a hl,
rw ← cons_add at hl,
exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter
(le_of_add_le_add_right (le_trans hl (inter_le_left _ _)))
(le_of_add_le_add_right (le_trans hl (inter_le_right _ _))))
end
theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) :=
by rw [add_comm, inter_add_distrib, add_comm s, add_comm s]
theorem cons_inter_distrib (a : α) (s t : multiset α) : a ::ₘ (s ∩ t) = (a ::ₘ s) ∩ (a ::ₘ t) :=
by simp
theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t :=
begin
apply le_antisymm,
{ rw union_add_distrib,
refine union_le (add_le_add_left (inter_le_right _ _) _) _,
rw add_comm, exact add_le_add_right (inter_le_left _ _) _ },
{ rw [add_comm, add_inter_distrib],
refine le_inter (add_le_add_right (le_union_right _ _) _) _,
rw add_comm, exact add_le_add_right (le_union_left _ _) _ }
end
theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s :=
begin
rw [inter_comm],
revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _),
by_cases a ∈ s,
{ rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] },
{ rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] }
end
theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t :=
add_right_cancel $ by rw [sub_add_inter s t, tsub_add_cancel_of_le (inter_le_left s t)]
end
/-! ### `multiset.filter` -/
section
variables (p : α → Prop) [decidable_pred p]
/-- `filter p s` returns the elements in `s` (with the same multiplicities)
which satisfy `p`, and removes the rest. -/
def filter (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (filter p l : multiset α))
(λ l₁ l₂ h, quot.sound $ h.filter p)
@[simp] theorem coe_filter (l : list α) : filter p (↑l) = l.filter p := rfl
@[simp] theorem filter_zero : filter p 0 = 0 := rfl
lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q]
{s : multiset α} : (∀ x ∈ s, p x ↔ q x) → filter p s = filter q s :=
quot.induction_on s $ λ l h, congr_arg coe $ filter_congr h
@[simp] theorem filter_add (s t : multiset α) : filter p (s + t) = filter p s + filter p t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _
@[simp] theorem filter_le (s : multiset α) : filter p s ≤ s :=
quot.induction_on s $ λ l, (filter_sublist _).subperm
@[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s :=
subset_of_le $ filter_le _ _
theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t :=
le_induction_on h $ λ l₁ l₂ h, (h.filter p).subperm
lemma monotone_filter_left :
monotone (filter p) :=
λ s t, filter_le_filter p
lemma monotone_filter_right (s : multiset α) ⦃p q : α → Prop⦄
[decidable_pred p] [decidable_pred q] (h : p ≤ q) :
s.filter p ≤ s.filter q :=
quotient.induction_on s (λ l, (l.monotone_filter_right h).subperm)
variable {p}
@[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a ::ₘ s) = a ::ₘ filter p s :=
quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h
@[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a ::ₘ s) = filter p s :=
quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h
@[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a :=
quot.induction_on s $ λ l, mem_filter
theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a :=
(mem_filter.1 h).2
theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s :=
(mem_filter.1 h).1
theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l :=
mem_filter.2 ⟨m, h⟩
theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h),
congr_arg coe⟩ filter_eq_self
theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h),
congr_arg coe⟩ filter_eq_nil
theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a :=
⟨λ h, ⟨le_trans h (filter_le _ _), λ a m, of_mem_filter (mem_of_le h m)⟩,
λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter p h⟩
theorem filter_cons {a : α} (s : multiset α) :
filter p (a ::ₘ s) = (if p a then {a} else 0) + filter p s :=
begin
split_ifs with h,
{ rw [filter_cons_of_pos _ h, singleton_add] },
{ rw [filter_cons_of_neg _ h, zero_add] },
end
lemma filter_nsmul (s : multiset α) (n : ℕ) :
filter p (n • s) = n • filter p s :=
begin
refine s.induction_on _ _,
{ simp only [filter_zero, nsmul_zero] },
{ intros a ha ih,
rw [nsmul_cons, filter_add, ih, filter_cons, nsmul_add],
congr,
split_ifs with hp;
{ simp only [filter_eq_self, nsmul_zero, filter_eq_nil],
intros b hb,
rwa (mem_singleton.mp (mem_of_mem_nsmul hb)) } }
end
variable (p)
@[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) :
filter p (s - t) = filter p s - filter p t :=
begin
revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _),
rw [sub_cons, IH],
by_cases p a,
{ rw [filter_cons_of_pos _ h, sub_cons], congr,
by_cases m : a ∈ s,
{ rw [← cons_inj_right a, ← filter_cons_of_pos _ h,
cons_erase (mem_filter_of_mem m h), cons_erase m] },
{ rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } },
{ rw [filter_cons_of_neg _ h],
by_cases m : a ∈ s,
{ rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a ::ₘ erase s a)),
cons_erase m] },
{ rw [erase_of_not_mem m] } }
end
@[simp] theorem filter_union [decidable_eq α] (s t : multiset α) :
filter p (s ∪ t) = filter p s ∪ filter p t :=
by simp [(∪), union]
@[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) :
filter p (s ∩ t) = filter p s ∩ filter p t :=
le_antisymm (le_inter
(filter_le_filter _ $ inter_le_left _ _)
(filter_le_filter _ $ inter_le_right _ _)) $ le_filter.2
⟨inf_le_inf (filter_le _ _) (filter_le _ _),
λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩
@[simp] theorem filter_filter (q) [decidable_pred q] (s : multiset α) :
filter p (filter q s) = filter (λ a, p a ∧ q a) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_filter p q l
theorem filter_add_filter (q) [decidable_pred q] (s : multiset α) :
filter p s + filter q s = filter (λ a, p a ∨ q a) s + filter (λ a, p a ∧ q a) s :=
multiset.induction_on s rfl $ λ a s IH,
by by_cases p a; by_cases q a; simp *
theorem filter_add_not (s : multiset α) :
filter p s + filter (λ a, ¬ p a) s = s :=
by rw [filter_add_filter, filter_eq_self.2, filter_eq_nil.2]; simp [decidable.em]
theorem map_filter (f : β → α) (s : multiset β) :
filter p (map f s) = map f (filter (p ∘ f) s) :=
quot.induction_on s (λ l, by simp [map_filter])
/-! ### Simultaneously filter and map elements of a multiset -/
/-- `filter_map f s` is a combination filter/map operation on `s`.
The function `f : α → option β` is applied to each element of `s`;
if `f a` is `some b` then `b` is added to the result, otherwise
`a` is removed from the resulting multiset. -/
def filter_map (f : α → option β) (s : multiset α) : multiset β :=
quot.lift_on s (λ l, (filter_map f l : multiset β))
(λ l₁ l₂ h, quot.sound $ h.filter_map f)
@[simp] theorem coe_filter_map (f : α → option β) (l : list α) :
filter_map f l = l.filter_map f := rfl
@[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl
@[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) :
filter_map f (a ::ₘ s) = filter_map f s :=
quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h
@[simp] theorem filter_map_cons_some (f : α → option β)
(a : α) (s : multiset α) {b : β} (h : f a = some b) :
filter_map f (a ::ₘ s) = b ::ₘ filter_map f s :=
quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h
theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f :=
funext $ λ s, quot.induction_on s $ λ l,
@congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l
theorem filter_map_eq_filter : filter_map (option.guard p) = filter p :=
funext $ λ s, quot.induction_on s $ λ l,
@congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l
theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) :
filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l
theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) :
map g (filter_map f s) = filter_map (λ x, (f x).map g) s :=
quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l
theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) :
filter_map g (map f s) = filter_map (g ∘ f) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l
theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) :
filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l
theorem filter_map_filter (f : α → option β) (s : multiset α) :
filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l
@[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l
@[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} :
b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b :=
quot.induction_on s $ λ l, mem_filter_map f l
theorem map_filter_map_of_inv (f : α → option β) (g : β → α)
(H : ∀ x : α, (f x).map g = some x) (s : multiset α) :
map g (filter_map f s) = s :=
quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l
theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α}
(h : s ≤ t) : filter_map f s ≤ filter_map f t :=
le_induction_on h $ λ l₁ l₂ h, (h.filter_map _).subperm
/-! ### countp -/
/-- `countp p s` counts the number of elements of `s` (with multiplicity) that
satisfy `p`. -/
def countp (s : multiset α) : ℕ :=
quot.lift_on s (countp p) (λ l₁ l₂, perm.countp_eq p)
@[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl
@[simp] theorem countp_zero : countp p 0 = 0 := rfl
variable {p}
@[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a ::ₘ s) = countp p s + 1 :=
quot.induction_on s $ countp_cons_of_pos p
@[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a ::ₘ s) = countp p s :=
quot.induction_on s $ countp_cons_of_neg p
variable (p)
theorem countp_cons (b : α) (s) : countp p (b ::ₘ s) = countp p s + (if p b then 1 else 0) :=
begin
split_ifs with h;
simp only [h, multiset.countp_cons_of_pos, add_zero, multiset.countp_cons_of_neg, not_false_iff],
end
theorem countp_eq_card_filter (s) : countp p s = card (filter p s) :=
quot.induction_on s $ λ l, countp_eq_length_filter _ _
@[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t :=
by simp [countp_eq_card_filter]
/-- `countp p`, the number of elements of a multiset satisfying `p`, promoted to an
`add_monoid_hom`. -/
def countp_add_monoid_hom : multiset α →+ ℕ :=
{ to_fun := countp p,
map_zero' := countp_zero _,
map_add' := countp_add _ }
@[simp] lemma coe_countp_add_monoid_hom :
(countp_add_monoid_hom p : multiset α → ℕ) = countp p := rfl
@[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) :
countp p (s - t) = countp p s - countp p t :=
by simp [countp_eq_card_filter, h, filter_le_filter]
theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t :=
by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter p h)
@[simp] theorem countp_filter (q) [decidable_pred q] (s : multiset α) :
countp p (filter q s) = countp (λ a, p a ∧ q a) s :=
by simp [countp_eq_card_filter]
theorem countp_map (f : α → β) (s : multiset α) (p : β → Prop) [decidable_pred p] :
countp p (map f s) = (s.filter (λ a, p (f a))).card :=
begin
refine multiset.induction_on s _ (λ a t IH, _),
{ rw [map_zero, countp_zero, filter_zero, card_zero] },
{ rw [map_cons, countp_cons, IH, filter_cons, card_add, apply_ite card, card_zero,
card_singleton, add_comm] },
end
variable {p}
theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a :=
by simp [countp_eq_card_filter, card_pos_iff_exists_mem]
theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s :=
countp_pos.2 ⟨_, h, pa⟩
end
/-! ### Multiplicity of an element -/
section
variable [decidable_eq α]
/-- `count a s` is the multiplicity of `a` in `s`. -/
def count (a : α) : multiset α → ℕ := countp (eq a)
@[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _ _
@[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl
@[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a ::ₘ s) = succ (count a s) :=
countp_cons_of_pos _ rfl
@[simp, priority 990]
theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b ::ₘ s) = count a s :=
countp_cons_of_neg _ h
theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t :=
countp_le_of_le _
theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b ::ₘ s) :=
count_le_of_le _ (le_cons_self _ _)
theorem count_cons (a b : α) (s : multiset α) :
count a (b ::ₘ s) = count a s + (if a = b then 1 else 0) :=
by by_cases h : a = b; simp [h]
theorem count_singleton_self (a : α) : count a ({a} : multiset α) = 1 :=
by simp only [count_cons_self, singleton_eq_cons, eq_self_iff_true, count_zero]
theorem count_singleton (a b : α) : count a ({b} : multiset α) = if a = b then 1 else 0 :=
by simp only [count_cons, singleton_eq_cons, count_zero, zero_add]
@[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t :=
countp_add _
/-- `count a`, the multiplicity of `a` in a multiset, promoted to an `add_monoid_hom`. -/
def count_add_monoid_hom (a : α) : multiset α →+ ℕ := countp_add_monoid_hom (eq a)
@[simp] lemma coe_count_add_monoid_hom {a : α} :
(count_add_monoid_hom a : multiset α → ℕ) = count a := rfl
@[simp] theorem count_nsmul (a : α) (n s) : count a (n • s) = n * count a s :=
by induction n; simp [*, succ_nsmul', succ_mul, zero_nsmul]
theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s :=
by simp [count, countp_pos]
@[simp, priority 980]
theorem count_eq_zero_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) : count a s = 0 :=
by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h')
@[simp] theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s :=
iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero
theorem count_ne_zero {a : α} {s : multiset α} : count a s ≠ 0 ↔ a ∈ s :=
by simp [ne.def, count_eq_zero]
@[simp] theorem count_repeat_self (a : α) (n : ℕ) : count a (repeat a n) = n :=
by simp [repeat]
theorem count_repeat (a b : α) (n : ℕ) :
count a (repeat b n) = if (a = b) then n else 0 :=
begin
split_ifs with h₁,
{ rw [h₁, count_repeat_self] },
{ rw [count_eq_zero],
apply mt eq_of_mem_repeat h₁ },
end
@[simp] theorem count_erase_self (a : α) (s : multiset α) :
count a (erase s a) = pred (count a s) :=
begin
by_cases a ∈ s,
{ rw [(by rw cons_erase h : count a s = count a (a ::ₘ erase s a)),
count_cons_self]; refl },
{ rw [erase_of_not_mem h, count_eq_zero.2 h]; refl }
end
@[simp, priority 980] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) :
count a (erase s b) = count a s :=
begin
by_cases b ∈ s,
{ rw [← count_cons_of_ne ab, cons_erase h] },
{ rw [erase_of_not_mem h] }
end
@[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t :=
begin
revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _),
rw [sub_cons, IH],
by_cases ab : a = b,
{ subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] },
{ rw [count_erase_of_ne ab, count_cons_of_ne ab] }
end
@[simp] theorem count_union (a : α) (s t : multiset α) :
count a (s ∪ t) = max (count a s) (count a t) :=
by simp [(∪), union, tsub_add_eq_max, -add_comm]
@[simp] theorem count_inter (a : α) (s t : multiset α) :
count a (s ∩ t) = min (count a s) (count a t) :=
begin
apply @nat.add_left_cancel (count a (s - t)),
rw [← count_add, sub_add_inter, count_sub, tsub_add_min],
end
lemma count_sum {m : multiset β} {f : β → multiset α} {a : α} :
count a (map f m).sum = sum (m.map $ λb, count a $ f b) :=
multiset.induction_on m (by simp) ( by simp)
lemma count_bind {m : multiset β} {f : β → multiset α} {a : α} :
count a (bind m f) = sum (m.map $ λb, count a $ f b) := count_sum
theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s :=
quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm
@[simp] theorem count_filter_of_pos {p} [decidable_pred p]
{a} {s : multiset α} (h : p a) : count a (filter p s) = count a s :=
quot.induction_on s $ λ l, count_filter h
@[simp] theorem count_filter_of_neg {p} [decidable_pred p]
{a} {s : multiset α} (h : ¬ p a) : count a (filter p s) = 0 :=
multiset.count_eq_zero_of_not_mem (λ t, h (of_mem_filter t))
theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t :=
quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count
@[ext]
theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t :=
ext.2
@[simp] theorem coe_inter (s t : list α) : (s ∩ t : multiset α) = (s.bag_inter t : list α) :=
by ext; simp
theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t :=
⟨λ h a, count_le_of_le a h, λ al,
by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t);
apply le_union_left⟩
instance : distrib_lattice (multiset α) :=
{ le_sup_inf := λ s t u, le_of_eq $ eq.symm $
ext.2 $ λ a, by simp only [max_min_distrib_left,
multiset.count_inter, multiset.sup_eq_union, multiset.count_union, multiset.inf_eq_inter],
..multiset.lattice }
instance : semilattice_sup_bot (multiset α) :=
{ bot := 0,
bot_le := zero_le,
..multiset.lattice }
theorem repeat_inf (s : multiset α) (a : α) (n : ℕ) :
(repeat a n) ⊓ s = repeat a (min (s.count a) n) :=
begin
ext x,
rw [inf_eq_inter, count_inter, count_repeat, count_repeat],
by_cases x = a,
simp only [min_comm, h, if_true, eq_self_iff_true],
simp only [h, if_false, zero_min],
end
/-- `multiset.map f` preserves `count` if `f` is injective on the set of elements contained in
the multiset -/
theorem count_map_eq_count [decidable_eq β] (f : α → β) (s : multiset α)
(hf : set.inj_on f {x : α | x ∈ s}) (x ∈ s) : (s.map f).count (f x) = s.count x :=
begin
suffices : (filter (λ (a : α), f x = f a) s).count x = card (filter (λ (a : α), f x = f a) s),
{ rw [count, countp_map, ← this],
exact count_filter_of_pos rfl },
{ rw eq_repeat.2 ⟨rfl, λ b hb, eq_comm.1 ((hf H (mem_filter.1 hb).left) (mem_filter.1 hb).right)⟩,
simp only [count_repeat, eq_self_iff_true, if_true, card_repeat]},
end
end
/-! ### Lift a relation to `multiset`s -/
section rel
/-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`,
s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/
@[mk_iff] inductive rel (r : α → β → Prop) : multiset α → multiset β → Prop
| zero : rel 0 0
| cons {a b as bs} : r a b → rel as bs → rel (a ::ₘ as) (b ::ₘ bs)
variables {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop}
private lemma rel_flip_aux {s t} (h : rel r s t) : rel (flip r) t s :=
rel.rec_on h rel.zero (assume _ _ _ _ h₀ h₁ ih, rel.cons h₀ ih)
lemma rel_flip {s t} : rel (flip r) s t ↔ rel r t s :=
⟨rel_flip_aux, rel_flip_aux⟩
lemma rel_refl_of_refl_on {m : multiset α} {r : α → α → Prop} :
(∀ x ∈ m, r x x) → rel r m m :=
begin
apply m.induction_on,
{ intros, apply rel.zero },
{ intros a m ih h,
exact rel.cons (h _ (mem_cons_self _ _)) (ih (λ _ ha, h _ (mem_cons_of_mem ha))) }
end
lemma rel_eq_refl {s : multiset α} : rel (=) s s :=
rel_refl_of_refl_on (λ x hx, rfl)
lemma rel_eq {s t : multiset α} : rel (=) s t ↔ s = t :=
begin
split,
{ assume h, induction h; simp * },
{ assume h, subst h, exact rel_eq_refl }
end
lemma rel.mono {r p : α → β → Prop} {s t} (hst : rel r s t) (h : ∀(a ∈ s) (b ∈ t), r a b → p a b) :
rel p s t :=
begin
induction hst,
case rel.zero { exact rel.zero },
case rel.cons : a b s t hab hst ih {
apply rel.cons (h a (mem_cons_self _ _) b (mem_cons_self _ _) hab),
exact ih (λ a' ha' b' hb' h', h a' (mem_cons_of_mem ha') b' (mem_cons_of_mem hb') h') }
end
lemma rel.add {s t u v} (hst : rel r s t) (huv : rel r u v) : rel r (s + u) (t + v) :=
begin
induction hst,
case rel.zero { simpa using huv },
case rel.cons : a b s t hab hst ih { simpa using ih.cons hab }
end
lemma rel_flip_eq {s t : multiset α} : rel (λa b, b = a) s t ↔ s = t :=
show rel (flip (=)) s t ↔ s = t, by rw [rel_flip, rel_eq, eq_comm]
@[simp] lemma rel_zero_left {b : multiset β} : rel r 0 b ↔ b = 0 :=
by rw [rel_iff]; simp
@[simp] lemma rel_zero_right {a : multiset α} : rel r a 0 ↔ a = 0 :=
by rw [rel_iff]; simp
lemma rel_cons_left {a as bs} :
rel r (a ::ₘ as) bs ↔ (∃b bs', r a b ∧ rel r as bs' ∧ bs = b ::ₘ bs') :=
begin
split,
{ generalize hm : a ::ₘ as = m,
assume h,
induction h generalizing as,
case rel.zero { simp at hm, contradiction },
case rel.cons : a' b as' bs ha'b h ih
{ rcases cons_eq_cons.1 hm with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩,
{ subst eq₁, subst eq₂, exact ⟨b, bs, ha'b, h, rfl⟩ },
{ rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩,
exact ⟨b', b ::ₘ bs', h₁, eq₁.symm ▸ rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩ } } },
{ exact assume ⟨b, bs', hab, h, eq⟩, eq.symm ▸ rel.cons hab h }
end
lemma rel_cons_right {as b bs} :
rel r as (b ::ₘ bs) ↔ (∃a as', r a b ∧ rel r as' bs ∧ as = a ::ₘ as') :=
begin
rw [← rel_flip, rel_cons_left],
apply exists_congr, assume a,
apply exists_congr, assume as',
rw [rel_flip, flip]
end
lemma rel_add_left {as₀ as₁} :
∀{bs}, rel r (as₀ + as₁) bs ↔ (∃bs₀ bs₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ bs = bs₀ + bs₁) :=
multiset.induction_on as₀ (by simp)
begin
assume a s ih bs,
simp only [ih, cons_add, rel_cons_left],
split,
{ assume h,
rcases h with ⟨b, bs', hab, h, rfl⟩,
rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩,
exact ⟨b ::ₘ bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩ },
{ assume h,
rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩,
rcases h with ⟨b, bs, hab, h₀, rfl⟩,
exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩ }
end
lemma rel_add_right {as bs₀ bs₁} :
rel r as (bs₀ + bs₁) ↔ (∃as₀ as₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ as = as₀ + as₁) :=
by rw [← rel_flip, rel_add_left]; simp [rel_flip]
lemma rel_map_left {s : multiset γ} {f : γ → α} :
∀{t}, rel r (s.map f) t ↔ rel (λa b, r (f a) b) s t :=
multiset.induction_on s (by simp) (by simp [rel_cons_left] {contextual := tt})
lemma rel_map_right {s : multiset α} {t : multiset γ} {f : γ → β} :
rel r s (t.map f) ↔ rel (λa b, r a (f b)) s t :=
by rw [← rel_flip, rel_map_left, ← rel_flip]; refl
lemma rel_join {s t} (h : rel (rel r) s t) : rel r s.join t.join :=
begin
induction h,
case rel.zero { simp },
case rel.cons : a b s t hab hst ih { simpa using hab.add ih }
end
lemma rel_map {s : multiset α} {t : multiset β} {f : α → γ} {g : β → δ} :
rel p (s.map f) (t.map g) ↔ rel (λa b, p (f a) (g b)) s t :=
rel_map_left.trans rel_map_right
lemma rel_bind {p : γ → δ → Prop} {s t} {f : α → multiset γ} {g : β → multiset δ}
(h : (r ⇒ rel p) f g) (hst : rel r s t) :
rel p (s.bind f) (t.bind g) :=
by { apply rel_join, rw rel_map, exact hst.mono (λ a ha b hb hr, h hr) }
lemma card_eq_card_of_rel {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) :
card s = card t :=
by induction h; simp [*]
lemma exists_mem_of_rel_of_mem {r : α → β → Prop} {s : multiset α} {t : multiset β}
(h : rel r s t) :
∀ {a : α} (ha : a ∈ s), ∃ b ∈ t, r a b :=
begin
induction h with x y s t hxy hst ih,
{ simp },
{ assume a ha,
cases mem_cons.1 ha with ha ha,
{ exact ⟨y, mem_cons_self _ _, ha.symm ▸ hxy⟩ },
{ rcases ih ha with ⟨b, hbt, hab⟩,
exact ⟨b, mem_cons.2 (or.inr hbt), hab⟩ } }
end
lemma rel_of_forall {m1 m2 : multiset α} {r : α → α → Prop} (h : ∀ a b, a ∈ m1 → b ∈ m2 → r a b)
(hc : card m1 = card m2) :
m1.rel r m2 :=
begin
revert m1,
apply m2.induction_on,
{ intros m h hc,
rw [rel_zero_right, ← card_eq_zero, hc, card_zero] },
{ intros a t ih m h hc,
rw card_cons at hc,
obtain ⟨b, hb⟩ := card_pos_iff_exists_mem.1 (show 0 < card m, from hc.symm ▸ (nat.succ_pos _)),
obtain ⟨m', rfl⟩ := exists_cons_of_mem hb,
refine rel_cons_right.mpr ⟨b, m', h _ _ hb (mem_cons_self _ _), ih _ _, rfl⟩,
{ exact λ _ _ ha hb, h _ _ (mem_cons_of_mem ha) (mem_cons_of_mem hb) },
{ simpa using hc } }
end
lemma rel_repeat_left {m : multiset α} {a : α} {r : α → α → Prop} {n : ℕ} :
(repeat a n).rel r m ↔ m.card = n ∧ ∀ x, x ∈ m → r a x :=
⟨λ h, ⟨(card_eq_card_of_rel h).symm.trans (card_repeat _ _), λ x hx, begin
obtain ⟨b, hb1, hb2⟩ := exists_mem_of_rel_of_mem (rel_flip.2 h) hx,
rwa eq_of_mem_repeat hb1 at hb2,
end⟩,
λ h, rel_of_forall (λ x y hx hy, (eq_of_mem_repeat hx).symm ▸ (h.2 _ hy))
(eq.trans (card_repeat _ _) h.1.symm)⟩
lemma rel_repeat_right {m : multiset α} {a : α} {r : α → α → Prop} {n : ℕ} :
m.rel r (repeat a n) ↔ m.card = n ∧ ∀ x, x ∈ m → r x a :=
by { rw [← rel_flip], exact rel_repeat_left }
lemma sum_le_sum_of_rel_le [ordered_add_comm_monoid α]
{m1 m2 : multiset α} (h : m1.rel (≤) m2) : m1.sum ≤ m2.sum :=
begin
induction h with _ _ _ _ rh _ rt,
{ refl },
{ rw [sum_cons, sum_cons],
exact add_le_add rh rt }
end
end rel
section sum_inequalities
lemma le_sum_of_mem [canonically_ordered_add_monoid α] {m : multiset α} {a : α}
(h : a ∈ m) : a ≤ m.sum :=
begin
obtain ⟨m', rfl⟩ := exists_cons_of_mem h,
rw [sum_cons],
exact _root_.le_add_right (le_refl a),
end
variables [ordered_add_comm_monoid α]
lemma sum_map_le_sum
{m : multiset α} (f : α → α) (h : ∀ x, x ∈ m → f x ≤ x) : (m.map f).sum ≤ m.sum :=
sum_le_sum_of_rel_le (rel_map_left.2 (rel_refl_of_refl_on h))
lemma sum_le_sum_map
{m : multiset α} (f : α → α) (h : ∀ x, x ∈ m → x ≤ f x) : m.sum ≤ (m.map f).sum :=
@sum_map_le_sum (order_dual α) _ _ f h
lemma card_nsmul_le_sum {b : α}
{m : multiset α} (h : ∀ x, x ∈ m → b ≤ x) : (card m) • b ≤ m.sum :=
begin
rw [←multiset.sum_repeat, ←multiset.map_const],
exact sum_map_le_sum _ h,
end
lemma sum_le_card_nsmul {b : α}
{m : multiset α} (h : ∀ x, x ∈ m → x ≤ b) : m.sum ≤ (card m) • b :=
begin
rw [←multiset.sum_repeat, ←multiset.map_const],
exact sum_le_sum_map _ h,
end
end sum_inequalities
section map
theorem map_eq_map {f : α → β} (hf : function.injective f) {s t : multiset α} :
s.map f = t.map f ↔ s = t :=
by { rw [← rel_eq, ← rel_eq, rel_map], simp only [hf.eq_iff] }
theorem map_injective {f : α → β} (hf : function.injective f) :
function.injective (multiset.map f) :=
assume x y, (map_eq_map hf).1
end map
section quot
theorem map_mk_eq_map_mk_of_rel {r : α → α → Prop} {s t : multiset α} (hst : s.rel r t) :
s.map (quot.mk r) = t.map (quot.mk r) :=
rel.rec_on hst rfl $ assume a b s t hab hst ih, by simp [ih, quot.sound hab]
theorem exists_multiset_eq_map_quot_mk {r : α → α → Prop} (s : multiset (quot r)) :
∃t:multiset α, s = t.map (quot.mk r) :=
multiset.induction_on s ⟨0, rfl⟩ $
assume a s ⟨t, ht⟩, quot.induction_on a $ assume a, ht.symm ▸ ⟨a ::ₘ t, (map_cons _ _ _).symm⟩
theorem induction_on_multiset_quot
{r : α → α → Prop} {p : multiset (quot r) → Prop} (s : multiset (quot r)) :
(∀s:multiset α, p (s.map (quot.mk r))) → p s :=
match s, exists_multiset_eq_map_quot_mk s with _, ⟨t, rfl⟩ := assume h, h _ end
end quot
/-! ### Disjoint multisets -/
/-- `disjoint s t` means that `s` and `t` have no elements in common. -/
def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false
@[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl
theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s
| a i₂ i₁ := d i₁ i₂
theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s :=
⟨disjoint.symm, disjoint.symm⟩
theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl
theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s :=
disjoint_comm
theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b :=
by simp [disjoint_left, imp_not_comm]
theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t
| x m₁ := d (h m₁)
theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t
| x m m₁ := d m (h m₁)
theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t :=
disjoint_of_subset_left (subset_of_le h)
theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t :=
disjoint_of_subset_right (subset_of_le h)
@[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l
| a := (not_mem_nil a).elim
@[simp, priority 1100]
theorem singleton_disjoint {l : multiset α} {a : α} : disjoint {a} l ↔ a ∉ l :=
by simp [disjoint]; refl
@[simp, priority 1100]
theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l {a} ↔ a ∉ l :=
by rw [disjoint_comm, singleton_disjoint]
@[simp] theorem disjoint_add_left {s t u : multiset α} :
disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_add_right {s t u : multiset α} :
disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u :=
by rw [disjoint_comm, disjoint_add_left]; tauto
@[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} :
disjoint (a ::ₘ s) t ↔ a ∉ t ∧ disjoint s t :=
(@disjoint_add_left _ {a} s t).trans $ by rw singleton_disjoint
@[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} :
disjoint s (a ::ₘ t) ↔ a ∉ s ∧ disjoint s t :=
by rw [disjoint_comm, disjoint_cons_left]; tauto
theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t :=
by rw ← subset_zero; simp [subset_iff, disjoint]
@[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} :
disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} :
disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
lemma add_eq_union_iff_disjoint [decidable_eq α] {s t : multiset α} :
s + t = s ∪ t ↔ disjoint s t :=
by simp_rw [←inter_eq_zero_iff_disjoint, ext, count_add, count_union, count_inter, count_zero,
nat.min_eq_zero_iff, nat.add_eq_max_iff]
lemma disjoint_map_map {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} :
disjoint (s.map f) (t.map g) ↔ (∀a∈s, ∀b∈t, f a ≠ g b) :=
by { simp [disjoint, @eq_comm _ (f _) (g _)], refl }
/-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this
list. -/
def pairwise (r : α → α → Prop) (m : multiset α) : Prop :=
∃l:list α, m = l ∧ l.pairwise r
lemma pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : symmetric r) {l : list α} :
multiset.pairwise r l ↔ l.pairwise r :=
iff.intro
(assume ⟨l', eq, h⟩, ((quotient.exact eq).pairwise_iff hr).2 h)
(assume h, ⟨l, rfl, h⟩)
end multiset
namespace multiset
section choose
variables (p : α → Prop) [decidable_pred p] (l : multiset α)
/-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `choose_x p l hp` returns
that `a` together with proofs of `a ∈ l` and `p a`. -/
def choose_x : Π hp : (∃! a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } :=
quotient.rec_on l (λ l' ex_unique, list.choose_x p l' (exists_of_exists_unique ex_unique)) begin
intros,
funext hp,
suffices all_equal : ∀ x y : { t // t ∈ b ∧ p t }, x = y,
{ apply all_equal },
{ rintros ⟨x, px⟩ ⟨y, py⟩,
rcases hp with ⟨z, ⟨z_mem_l, pz⟩, z_unique⟩,
congr,
calc x = z : z_unique x px
... = y : (z_unique y py).symm }
end
/-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `choose p l hp` returns
that `a`. -/
def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp
lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) :=
(choose_x p l hp).property
lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1
lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2
end choose
variable (α)
/-- The equivalence between lists and multisets of a subsingleton type. -/
def subsingleton_equiv [subsingleton α] : list α ≃ multiset α :=
{ to_fun := coe,
inv_fun := quot.lift id $ λ (a b : list α) (h : a ~ b),
list.ext_le h.length_eq $ λ n h₁ h₂, subsingleton.elim _ _,
left_inv := λ l, rfl,
right_inv := λ m, quot.induction_on m $ λ l, rfl }
variable {α}
@[simp]
lemma coe_subsingleton_equiv [subsingleton α] :
(subsingleton_equiv α : list α → multiset α) = coe :=
rfl
end multiset
@[to_additive]
theorem monoid_hom.map_multiset_prod [comm_monoid α] [comm_monoid β] (f : α →* β) (s : multiset α) :
f s.prod = (s.map f).prod :=
(s.prod_hom f).symm
|
1c71fdc7e93fa693c9501020565280f06a681913 | 64874bd1010548c7f5a6e3e8902efa63baaff785 | /hott/init/wf.hlean | 53073f42a2cfc171d72648cf614aa56b26763a10 | [
"Apache-2.0"
] | permissive | tjiaqi/lean | 4634d729795c164664d10d093f3545287c76628f | d0ce4cf62f4246b0600c07e074d86e51f2195e30 | refs/heads/master | 1,622,323,796,480 | 1,422,643,069,000 | 1,422,643,069,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,828 | hlean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import init.relation init.tactic
inductive acc.{l₁ l₂} {A : Type.{l₁}} (R : A → A → Type.{l₂}) : A → Type.{max l₁ l₂} :=
intro : ∀x, (∀ y, R y x → acc R y) → acc R x
namespace acc
variables {A : Type} {R : A → A → Type}
definition inv {x y : A} (H₁ : acc R x) (H₂ : R y x) : acc R y :=
rec_on H₁ (λ x₁ ac₁ iH H₂, ac₁ y H₂) H₂
end acc
inductive well_founded [class] {A : Type} (R : A → A → Type) : Type :=
intro : (∀ a, acc R a) → well_founded R
namespace well_founded
definition apply [coercion] {A : Type} {R : A → A → Type} (wf : well_founded R) : ∀a, acc R a :=
take a, well_founded.rec_on wf (λp, p) a
context
parameters {A : Type} {R : A → A → Type}
infix `≺`:50 := R
hypothesis [Hwf : well_founded R]
definition recursion {C : A → Type} (a : A) (H : Πx, (Πy, y ≺ x → C y) → C x) : C a :=
acc.rec_on (Hwf a) (λ x₁ ac₁ iH, H x₁ iH)
definition induction {C : A → Type} (a : A) (H : ∀x, (∀y, y ≺ x → C y) → C x) : C a :=
recursion a H
parameter {C : A → Type}
parameter F : Πx, (Πy, y ≺ x → C y) → C x
definition fix_F (x : A) (a : acc R x) : C x :=
acc.rec_on a (λ x₁ ac₁ iH, F x₁ iH)
definition fix_F_eq (x : A) (r : acc R x) :
fix_F x r = F x (λ (y : A) (p : y ≺ x), fix_F y (acc.inv r p)) :=
acc.rec_on r (λ x H ih, rfl)
-- Remark: after we prove function extensionality from univalence, we can drop this hypothesis
hypothesis F_ext : Π (x : A) (f g : Π y, y ≺ x → C y),
(Π (y : A) (p : y ≺ x), f y p = g y p) → F x f = F x g
lemma fix_F_inv (x : A) (r : acc R x) : Π (s : acc R x), fix_F x r = fix_F x s :=
acc.rec_on r (λ
(x₁ : A)
(h₁ : Π y, y ≺ x₁ → acc R y)
(ih₁ : Π y (hlt : y ≺ x₁) (s : acc R y), fix_F y (h₁ y hlt) = fix_F y s)
(s : acc R x₁),
have aux₁ : Π (s : acc R x₁) (h₁ : Π y, y ≺ x₁ → acc R y) (ih₁ : Π y (hlt : y ≺ x₁) (s : acc R y),
fix_F y (h₁ y hlt) = fix_F y s), fix_F x₁ (acc.intro x₁ h₁) = fix_F x₁ s, from
λ s, acc.rec_on s (λ
(x₂ : A)
(h₂ : Π y, y ≺ x₂ → acc R y)
(ih₂ : _)
(h₁ : Π y, y ≺ x₂ → acc R y)
(ih₁ : Π y (hlt : y ≺ x₂) (s : acc R y), fix_F y (h₁ y hlt) = fix_F y s),
calc fix_F x₂ (acc.intro x₂ h₁)
= F x₂ (λ (y : A) (p : y ≺ x₂), fix_F y (h₁ y p)) : rfl
... = F x₂ (λ (y : A) (p : y ≺ x₂), fix_F y (h₂ y p)) : F_ext x₂ _ _ (λ (y : A) (p : y ≺ x₂), ih₁ y p (h₂ y p))
... = fix_F x₂ (acc.intro x₂ h₂) : rfl),
show fix_F x₁ (acc.intro x₁ h₁) = fix_F x₁ s, from
aux₁ s h₁ ih₁)
-- Well-founded fixpoint
definition fix (x : A) : C x :=
fix_F x (Hwf x)
-- Well-founded fixpoint satisfies fixpoint equation
definition fix_eq (x : A) : fix x = F x (λy h, fix y) :=
calc
fix x
= fix_F x (Hwf x) : rfl
... = F x (λy h, fix_F y (acc.inv (Hwf x) h)) : fix_F_eq x (Hwf x)
... = F x (λy h, fix_F y (Hwf y)) : F_ext x _ _ (λ y h, fix_F_inv y _ _)
... = F x (λy h, fix y) : rfl
end
end well_founded
open well_founded
-- Empty relation is well-founded
definition empty.wf {A : Type} : well_founded empty_relation :=
well_founded.intro (λ (a : A),
acc.intro a (λ (b : A) (lt : empty), empty.rec _ lt))
-- Subrelation of a well-founded relation is well-founded
namespace subrelation
context
parameters {A : Type} {R Q : A → A → Type}
parameters (H₁ : subrelation Q R)
parameters (H₂ : well_founded R)
definition accessible {a : A} (ac : acc R a) : acc Q a :=
acc.rec_on ac
(λ (x : A) (ax : _) (iH : ∀ (y : A), R y x → acc Q y),
acc.intro x (λ (y : A) (lt : Q y x), iH y (H₁ lt)))
definition wf : well_founded Q :=
well_founded.intro (λ a, accessible (H₂ a))
end
end subrelation
-- The inverse image of a well-founded relation is well-founded
namespace inv_image
context
parameters {A B : Type} {R : B → B → Type}
parameters (f : A → B)
parameters (H : well_founded R)
definition accessible {a : A} (ac : acc R (f a)) : acc (inv_image R f) a :=
have gen : ∀x, f x = f a → acc (inv_image R f) x, from
acc.rec_on ac
(λx acx (iH : ∀y, R y x → (∀z, f z = y → acc (inv_image R f) z))
(z : A) (eq₁ : f z = x),
acc.intro z (λ (y : A) (lt : R (f y) (f z)),
iH (f y) (eq.rec_on eq₁ lt) y rfl)),
gen a rfl
definition wf : well_founded (inv_image R f) :=
well_founded.intro (λ a, accessible (H (f a)))
end
end inv_image
-- The transitive closure of a well-founded relation is well-founded
namespace tc
context
parameters {A : Type} {R : A → A → Type}
notation `R⁺` := tc R
definition accessible {z} (ac: acc R z) : acc R⁺ z :=
acc.rec_on ac
(λ x acx (iH : ∀y, R y x → acc R⁺ y),
acc.intro x (λ (y : A) (lt : R⁺ y x),
have gen : x = x → acc R⁺ y, from
tc.rec_on lt
(λa b (H : R a b) (Heq : b = x),
iH a (eq.rec_on Heq H))
(λa b c (H₁ : R⁺ a b) (H₂ : R⁺ b c)
(iH₁ : b = x → acc R⁺ a)
(iH₂ : c = x → acc R⁺ b)
(Heq : c = x),
acc.inv (iH₂ Heq) H₁),
gen rfl))
definition wf (H : well_founded R) : well_founded R⁺ :=
well_founded.intro (λ a, accessible (H a))
end
end tc
|
2ab08f797df320fc18892ffca64783ca5dd17ccf | d29d82a0af640c937e499f6be79fc552eae0aa13 | /src/algebra/group/hom.lean | 593e956bf2a3e704187f5e42cb33b4d720638356 | [
"Apache-2.0"
] | permissive | AbdulMajeedkhurasani/mathlib | 835f8a5c5cf3075b250b3737172043ab4fa1edf6 | 79bc7323b164aebd000524ebafd198eb0e17f956 | refs/heads/master | 1,688,003,895,660 | 1,627,788,521,000 | 1,627,788,521,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 36,488 | lean | /-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Kevin Buzzard, Scott Morrison, Johan Commelin, Chris Hughes,
Johannes Hölzl, Yury Kudryashov
-/
import algebra.group.commute
import algebra.group_with_zero.defs
/-!
# monoid and group homomorphisms
This file defines the bundled structures for monoid and group homomorphisms. Namely, we define
`monoid_hom` (resp., `add_monoid_hom`) to be bundled homomorphisms between multiplicative (resp.,
additive) monoids or groups.
We also define coercion to a function, and usual operations: composition, identity homomorphism,
pointwise multiplication and pointwise inversion.
This file also defines the lesser-used (and notation-less) homomorphism types which are used as
building blocks for other homomorphisms:
* `zero_hom`
* `one_hom`
* `add_hom`
* `mul_hom`
* `monoid_with_zero_hom`
## Notations
* `→*` for bundled monoid homs (also use for group homs)
* `→+` for bundled add_monoid homs (also use for add_group homs)
## implementation notes
There's a coercion from bundled homs to fun, and the canonical
notation is to use the bundled hom as a function via this coercion.
There is no `group_hom` -- the idea is that `monoid_hom` is used.
The constructor for `monoid_hom` needs a proof of `map_one` as well
as `map_mul`; a separate constructor `monoid_hom.mk'` will construct
group homs (i.e. monoid homs between groups) given only a proof
that multiplication is preserved,
Implicit `{}` brackets are often used instead of type class `[]` brackets. This is done when the
instances can be inferred because they are implicit arguments to the type `monoid_hom`. When they
can be inferred from the type it is faster to use this method than to use type class inference.
Historically this file also included definitions of unbundled homomorphism classes; they were
deprecated and moved to `deprecated/group`.
## Tags
monoid_hom, add_monoid_hom
-/
variables {M : Type*} {N : Type*} {P : Type*} -- monoids
{G : Type*} {H : Type*} -- groups
-- for easy multiple inheritance
set_option old_structure_cmd true
/-- Homomorphism that preserves zero -/
structure zero_hom (M : Type*) (N : Type*) [has_zero M] [has_zero N] :=
(to_fun : M → N)
(map_zero' : to_fun 0 = 0)
/-- Homomorphism that preserves addition -/
structure add_hom (M : Type*) (N : Type*) [has_add M] [has_add N] :=
(to_fun : M → N)
(map_add' : ∀ x y, to_fun (x + y) = to_fun x + to_fun y)
/-- Bundled add_monoid homomorphisms; use this for bundled add_group homomorphisms too. -/
@[ancestor zero_hom add_hom]
structure add_monoid_hom (M : Type*) (N : Type*) [add_zero_class M] [add_zero_class N]
extends zero_hom M N, add_hom M N
attribute [nolint doc_blame] add_monoid_hom.to_add_hom
attribute [nolint doc_blame] add_monoid_hom.to_zero_hom
infixr ` →+ `:25 := add_monoid_hom
/-- Homomorphism that preserves one -/
@[to_additive]
structure one_hom (M : Type*) (N : Type*) [has_one M] [has_one N] :=
(to_fun : M → N)
(map_one' : to_fun 1 = 1)
/-- Homomorphism that preserves multiplication -/
@[to_additive]
structure mul_hom (M : Type*) (N : Type*) [has_mul M] [has_mul N] :=
(to_fun : M → N)
(map_mul' : ∀ x y, to_fun (x * y) = to_fun x * to_fun y)
/-- Bundled monoid homomorphisms; use this for bundled group homomorphisms too. -/
@[ancestor one_hom mul_hom, to_additive]
structure monoid_hom (M : Type*) (N : Type*) [mul_one_class M] [mul_one_class N]
extends one_hom M N, mul_hom M N
/-- Bundled monoid with zero homomorphisms; use this for bundled group with zero homomorphisms
too. -/
@[ancestor zero_hom monoid_hom]
structure monoid_with_zero_hom (M : Type*) (N : Type*) [mul_zero_one_class M] [mul_zero_one_class N]
extends zero_hom M N, monoid_hom M N
attribute [nolint doc_blame] monoid_hom.to_mul_hom
attribute [nolint doc_blame] monoid_hom.to_one_hom
attribute [nolint doc_blame] monoid_with_zero_hom.to_monoid_hom
attribute [nolint doc_blame] monoid_with_zero_hom.to_zero_hom
infixr ` →* `:25 := monoid_hom
-- completely uninteresting lemmas about coercion to function, that all homs need
section coes
/-! Bundled morphisms can be down-cast to weaker bundlings -/
@[to_additive]
instance monoid_hom.has_coe_to_one_hom {mM : mul_one_class M} {mN : mul_one_class N} :
has_coe (M →* N) (one_hom M N) := ⟨monoid_hom.to_one_hom⟩
@[to_additive]
instance monoid_hom.has_coe_to_mul_hom {mM : mul_one_class M} {mN : mul_one_class N} :
has_coe (M →* N) (mul_hom M N) := ⟨monoid_hom.to_mul_hom⟩
instance monoid_with_zero_hom.has_coe_to_monoid_hom
{mM : mul_zero_one_class M} {mN : mul_zero_one_class N} :
has_coe (monoid_with_zero_hom M N) (M →* N) := ⟨monoid_with_zero_hom.to_monoid_hom⟩
instance monoid_with_zero_hom.has_coe_to_zero_hom
{mM : mul_zero_one_class M} {mN : mul_zero_one_class N} :
has_coe (monoid_with_zero_hom M N) (zero_hom M N) := ⟨monoid_with_zero_hom.to_zero_hom⟩
/-! The simp-normal form of morphism coercion is `f.to_..._hom`. This choice is primarily because
this is the way things were before the above coercions were introduced. Bundled morphisms defined
elsewhere in Mathlib may choose `↑f` as their simp-normal form instead. -/
@[simp, to_additive]
lemma monoid_hom.coe_eq_to_one_hom {mM : mul_one_class M} {mN : mul_one_class N} (f : M →* N) :
(f : one_hom M N) = f.to_one_hom := rfl
@[simp, to_additive]
lemma monoid_hom.coe_eq_to_mul_hom {mM : mul_one_class M} {mN : mul_one_class N} (f : M →* N) :
(f : mul_hom M N) = f.to_mul_hom := rfl
@[simp]
lemma monoid_with_zero_hom.coe_eq_to_monoid_hom
{mM : mul_zero_one_class M} {mN : mul_zero_one_class N} (f : monoid_with_zero_hom M N) :
(f : M →* N) = f.to_monoid_hom := rfl
@[simp]
lemma monoid_with_zero_hom.coe_eq_to_zero_hom
{mM : mul_zero_one_class M} {mN : mul_zero_one_class N} (f : monoid_with_zero_hom M N) :
(f : zero_hom M N) = f.to_zero_hom := rfl
@[to_additive]
instance {mM : has_one M} {mN : has_one N} : has_coe_to_fun (one_hom M N) :=
⟨_, one_hom.to_fun⟩
@[to_additive]
instance {mM : has_mul M} {mN : has_mul N} : has_coe_to_fun (mul_hom M N) :=
⟨_, mul_hom.to_fun⟩
@[to_additive]
instance {mM : mul_one_class M} {mN : mul_one_class N} : has_coe_to_fun (M →* N) :=
⟨_, monoid_hom.to_fun⟩
instance {mM : mul_zero_one_class M} {mN : mul_zero_one_class N} :
has_coe_to_fun (monoid_with_zero_hom M N) :=
⟨_, monoid_with_zero_hom.to_fun⟩
-- these must come after the coe_to_fun definitions
initialize_simps_projections zero_hom (to_fun → apply)
initialize_simps_projections add_hom (to_fun → apply)
initialize_simps_projections add_monoid_hom (to_fun → apply)
initialize_simps_projections one_hom (to_fun → apply)
initialize_simps_projections mul_hom (to_fun → apply)
initialize_simps_projections monoid_hom (to_fun → apply)
initialize_simps_projections monoid_with_zero_hom (to_fun → apply)
@[simp, to_additive]
lemma one_hom.to_fun_eq_coe [has_one M] [has_one N] (f : one_hom M N) : f.to_fun = f := rfl
@[simp, to_additive]
lemma mul_hom.to_fun_eq_coe [has_mul M] [has_mul N] (f : mul_hom M N) : f.to_fun = f := rfl
@[simp, to_additive]
lemma monoid_hom.to_fun_eq_coe [mul_one_class M] [mul_one_class N]
(f : M →* N) : f.to_fun = f := rfl
@[simp]
lemma monoid_with_zero_hom.to_fun_eq_coe [mul_zero_one_class M] [mul_zero_one_class N]
(f : monoid_with_zero_hom M N) : f.to_fun = f := rfl
@[simp, to_additive]
lemma one_hom.coe_mk [has_one M] [has_one N]
(f : M → N) (h1) : ⇑(one_hom.mk f h1) = f := rfl
@[simp, to_additive]
lemma mul_hom.coe_mk [has_mul M] [has_mul N]
(f : M → N) (hmul) : ⇑(mul_hom.mk f hmul) = f := rfl
@[simp, to_additive]
lemma monoid_hom.coe_mk [mul_one_class M] [mul_one_class N]
(f : M → N) (h1 hmul) : ⇑(monoid_hom.mk f h1 hmul) = f := rfl
@[simp]
lemma monoid_with_zero_hom.coe_mk [mul_zero_one_class M] [mul_zero_one_class N]
(f : M → N) (h0 h1 hmul) : ⇑(monoid_with_zero_hom.mk f h0 h1 hmul) = f := rfl
@[simp, to_additive]
lemma monoid_hom.to_one_hom_coe [mul_one_class M] [mul_one_class N] (f : M →* N) :
(f.to_one_hom : M → N) = f := rfl
@[simp, to_additive]
lemma monoid_hom.to_mul_hom_coe [mul_one_class M] [mul_one_class N] (f : M →* N) :
(f.to_mul_hom : M → N) = f := rfl
@[simp]
lemma monoid_with_zero_hom.to_zero_hom_coe [mul_zero_one_class M] [mul_zero_one_class N]
(f : monoid_with_zero_hom M N) :
(f.to_zero_hom : M → N) = f := rfl
@[simp]
lemma monoid_with_zero_hom.to_monoid_hom_coe [mul_zero_one_class M] [mul_zero_one_class N]
(f : monoid_with_zero_hom M N) :
(f.to_monoid_hom : M → N) = f := rfl
@[to_additive]
theorem one_hom.congr_fun [has_one M] [has_one N]
{f g : one_hom M N} (h : f = g) (x : M) : f x = g x :=
congr_arg (λ h : one_hom M N, h x) h
@[to_additive]
theorem mul_hom.congr_fun [has_mul M] [has_mul N]
{f g : mul_hom M N} (h : f = g) (x : M) : f x = g x :=
congr_arg (λ h : mul_hom M N, h x) h
@[to_additive]
theorem monoid_hom.congr_fun [mul_one_class M] [mul_one_class N]
{f g : M →* N} (h : f = g) (x : M) : f x = g x :=
congr_arg (λ h : M →* N, h x) h
theorem monoid_with_zero_hom.congr_fun [mul_zero_one_class M] [mul_zero_one_class N]
{f g : monoid_with_zero_hom M N} (h : f = g) (x : M) : f x = g x :=
congr_arg (λ h : monoid_with_zero_hom M N, h x) h
@[to_additive]
theorem one_hom.congr_arg [has_one M] [has_one N]
(f : one_hom M N) {x y : M} (h : x = y) : f x = f y :=
congr_arg (λ x : M, f x) h
@[to_additive]
theorem mul_hom.congr_arg [has_mul M] [has_mul N]
(f : mul_hom M N) {x y : M} (h : x = y) : f x = f y :=
congr_arg (λ x : M, f x) h
@[to_additive]
theorem monoid_hom.congr_arg [mul_one_class M] [mul_one_class N]
(f : M →* N) {x y : M} (h : x = y) : f x = f y :=
congr_arg (λ x : M, f x) h
theorem monoid_with_zero_hom.congr_arg [mul_zero_one_class M] [mul_zero_one_class N]
(f : monoid_with_zero_hom M N) {x y : M} (h : x = y) : f x = f y :=
congr_arg (λ x : M, f x) h
@[to_additive]
lemma one_hom.coe_inj [has_one M] [has_one N] ⦃f g : one_hom M N⦄ (h : (f : M → N) = g) : f = g :=
by cases f; cases g; cases h; refl
@[to_additive]
lemma mul_hom.coe_inj [has_mul M] [has_mul N] ⦃f g : mul_hom M N⦄ (h : (f : M → N) = g) : f = g :=
by cases f; cases g; cases h; refl
@[to_additive]
lemma monoid_hom.coe_inj [mul_one_class M] [mul_one_class N]
⦃f g : M →* N⦄ (h : (f : M → N) = g) : f = g :=
by cases f; cases g; cases h; refl
lemma monoid_with_zero_hom.coe_inj [mul_zero_one_class M] [mul_zero_one_class N]
⦃f g : monoid_with_zero_hom M N⦄ (h : (f : M → N) = g) : f = g :=
by cases f; cases g; cases h; refl
@[ext, to_additive]
lemma one_hom.ext [has_one M] [has_one N] ⦃f g : one_hom M N⦄ (h : ∀ x, f x = g x) : f = g :=
one_hom.coe_inj (funext h)
@[ext, to_additive]
lemma mul_hom.ext [has_mul M] [has_mul N] ⦃f g : mul_hom M N⦄ (h : ∀ x, f x = g x) : f = g :=
mul_hom.coe_inj (funext h)
@[ext, to_additive]
lemma monoid_hom.ext [mul_one_class M] [mul_one_class N]
⦃f g : M →* N⦄ (h : ∀ x, f x = g x) : f = g :=
monoid_hom.coe_inj (funext h)
@[ext]
lemma monoid_with_zero_hom.ext [mul_zero_one_class M] [mul_zero_one_class N]
⦃f g : monoid_with_zero_hom M N⦄ (h : ∀ x, f x = g x) : f = g :=
monoid_with_zero_hom.coe_inj (funext h)
attribute [ext] zero_hom.ext add_hom.ext add_monoid_hom.ext
@[to_additive]
lemma one_hom.ext_iff [has_one M] [has_one N] {f g : one_hom M N} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, λ h, one_hom.ext h⟩
@[to_additive]
lemma mul_hom.ext_iff [has_mul M] [has_mul N] {f g : mul_hom M N} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, λ h, mul_hom.ext h⟩
@[to_additive]
lemma monoid_hom.ext_iff [mul_one_class M] [mul_one_class N]
{f g : M →* N} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, λ h, monoid_hom.ext h⟩
lemma monoid_with_zero_hom.ext_iff [mul_zero_one_class M] [mul_zero_one_class N]
{f g : monoid_with_zero_hom M N} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, λ h, monoid_with_zero_hom.ext h⟩
@[simp, to_additive]
lemma one_hom.mk_coe [has_one M] [has_one N]
(f : one_hom M N) (h1) : one_hom.mk f h1 = f :=
one_hom.ext $ λ _, rfl
@[simp, to_additive]
lemma mul_hom.mk_coe [has_mul M] [has_mul N]
(f : mul_hom M N) (hmul) : mul_hom.mk f hmul = f :=
mul_hom.ext $ λ _, rfl
@[simp, to_additive]
lemma monoid_hom.mk_coe [mul_one_class M] [mul_one_class N]
(f : M →* N) (h1 hmul) : monoid_hom.mk f h1 hmul = f :=
monoid_hom.ext $ λ _, rfl
@[simp]
lemma monoid_with_zero_hom.mk_coe [mul_zero_one_class M] [mul_zero_one_class N]
(f : monoid_with_zero_hom M N) (h0 h1 hmul) : monoid_with_zero_hom.mk f h0 h1 hmul = f :=
monoid_with_zero_hom.ext $ λ _, rfl
end coes
@[simp, to_additive]
lemma one_hom.map_one [has_one M] [has_one N] (f : one_hom M N) : f 1 = 1 := f.map_one'
/-- If `f` is a monoid homomorphism then `f 1 = 1`. -/
@[simp, to_additive]
lemma monoid_hom.map_one [mul_one_class M] [mul_one_class N] (f : M →* N) : f 1 = 1 := f.map_one'
@[simp]
lemma monoid_with_zero_hom.map_one [mul_zero_one_class M] [mul_zero_one_class N]
(f : monoid_with_zero_hom M N) : f 1 = 1 := f.map_one'
/-- If `f` is an additive monoid homomorphism then `f 0 = 0`. -/
add_decl_doc add_monoid_hom.map_zero
@[simp]
lemma monoid_with_zero_hom.map_zero [mul_zero_one_class M] [mul_zero_one_class N]
(f : monoid_with_zero_hom M N) : f 0 = 0 := f.map_zero'
@[simp, to_additive]
lemma mul_hom.map_mul [has_mul M] [has_mul N]
(f : mul_hom M N) (a b : M) : f (a * b) = f a * f b := f.map_mul' a b
/-- If `f` is a monoid homomorphism then `f (a * b) = f a * f b`. -/
@[simp, to_additive]
lemma monoid_hom.map_mul [mul_one_class M] [mul_one_class N]
(f : M →* N) (a b : M) : f (a * b) = f a * f b := f.map_mul' a b
@[simp]
lemma monoid_with_zero_hom.map_mul [mul_zero_one_class M] [mul_zero_one_class N]
(f : monoid_with_zero_hom M N) (a b : M) : f (a * b) = f a * f b := f.map_mul' a b
/-- If `f` is an additive monoid homomorphism then `f (a + b) = f a + f b`. -/
add_decl_doc add_monoid_hom.map_add
namespace monoid_hom
variables {mM : mul_one_class M} {mN : mul_one_class N} {mP : mul_one_class P}
variables [group G] [comm_group H]
include mM mN
@[to_additive]
lemma map_mul_eq_one (f : M →* N) {a b : M} (h : a * b = 1) : f a * f b = 1 :=
by rw [← f.map_mul, h, f.map_one]
/-- Given a monoid homomorphism `f : M →* N` and an element `x : M`, if `x` has a right inverse,
then `f x` has a right inverse too. For elements invertible on both sides see `is_unit.map`. -/
@[to_additive "Given an add_monoid homomorphism `f : M →+ N` and an element `x : M`, if `x` has
a right inverse, then `f x` has a right inverse too."]
lemma map_exists_right_inv (f : M →* N) {x : M} (hx : ∃ y, x * y = 1) :
∃ y, f x * y = 1 :=
let ⟨y, hy⟩ := hx in ⟨f y, f.map_mul_eq_one hy⟩
/-- Given a monoid homomorphism `f : M →* N` and an element `x : M`, if `x` has a left inverse,
then `f x` has a left inverse too. For elements invertible on both sides see `is_unit.map`. -/
@[to_additive "Given an add_monoid homomorphism `f : M →+ N` and an element `x : M`, if `x` has
a left inverse, then `f x` has a left inverse too. For elements invertible on both sides see
`is_add_unit.map`."]
lemma map_exists_left_inv (f : M →* N) {x : M} (hx : ∃ y, y * x = 1) :
∃ y, y * f x = 1 :=
let ⟨y, hy⟩ := hx in ⟨f y, f.map_mul_eq_one hy⟩
end monoid_hom
/-- The identity map from a type with 1 to itself. -/
@[to_additive, simps]
def one_hom.id (M : Type*) [has_one M] : one_hom M M :=
{ to_fun := λ x, x, map_one' := rfl, }
/-- The identity map from a type with multiplication to itself. -/
@[to_additive, simps]
def mul_hom.id (M : Type*) [has_mul M] : mul_hom M M :=
{ to_fun := λ x, x, map_mul' := λ _ _, rfl, }
/-- The identity map from a monoid to itself. -/
@[to_additive, simps]
def monoid_hom.id (M : Type*) [mul_one_class M] : M →* M :=
{ to_fun := λ x, x, map_one' := rfl, map_mul' := λ _ _, rfl, }
/-- The identity map from a monoid_with_zero to itself. -/
@[simps]
def monoid_with_zero_hom.id (M : Type*) [mul_zero_one_class M] : monoid_with_zero_hom M M :=
{ to_fun := λ x, x, map_zero' := rfl, map_one' := rfl, map_mul' := λ _ _, rfl, }
/-- The identity map from an type with zero to itself. -/
add_decl_doc zero_hom.id
/-- The identity map from an type with addition to itself. -/
add_decl_doc add_hom.id
/-- The identity map from an additive monoid to itself. -/
add_decl_doc add_monoid_hom.id
/-- Composition of `one_hom`s as a `one_hom`. -/
@[to_additive]
def one_hom.comp [has_one M] [has_one N] [has_one P]
(hnp : one_hom N P) (hmn : one_hom M N) : one_hom M P :=
{ to_fun := hnp ∘ hmn, map_one' := by simp, }
/-- Composition of `mul_hom`s as a `mul_hom`. -/
@[to_additive]
def mul_hom.comp [has_mul M] [has_mul N] [has_mul P]
(hnp : mul_hom N P) (hmn : mul_hom M N) : mul_hom M P :=
{ to_fun := hnp ∘ hmn, map_mul' := by simp, }
/-- Composition of monoid morphisms as a monoid morphism. -/
@[to_additive]
def monoid_hom.comp [mul_one_class M] [mul_one_class N] [mul_one_class P]
(hnp : N →* P) (hmn : M →* N) : M →* P :=
{ to_fun := hnp ∘ hmn, map_one' := by simp, map_mul' := by simp, }
/-- Composition of `monoid_with_zero_hom`s as a `monoid_with_zero_hom`. -/
def monoid_with_zero_hom.comp [mul_zero_one_class M] [mul_zero_one_class N] [mul_zero_one_class P]
(hnp : monoid_with_zero_hom N P) (hmn : monoid_with_zero_hom M N) : monoid_with_zero_hom M P :=
{ to_fun := hnp ∘ hmn, map_zero' := by simp, map_one' := by simp, map_mul' := by simp, }
/-- Composition of `zero_hom`s as a `zero_hom`. -/
add_decl_doc zero_hom.comp
/-- Composition of `add_hom`s as a `add_hom`. -/
add_decl_doc add_hom.comp
/-- Composition of additive monoid morphisms as an additive monoid morphism. -/
add_decl_doc add_monoid_hom.comp
@[simp, to_additive] lemma one_hom.coe_comp [has_one M] [has_one N] [has_one P]
(g : one_hom N P) (f : one_hom M N) :
⇑(g.comp f) = g ∘ f := rfl
@[simp, to_additive] lemma mul_hom.coe_comp [has_mul M] [has_mul N] [has_mul P]
(g : mul_hom N P) (f : mul_hom M N) :
⇑(g.comp f) = g ∘ f := rfl
@[simp, to_additive] lemma monoid_hom.coe_comp [mul_one_class M] [mul_one_class N] [mul_one_class P]
(g : N →* P) (f : M →* N) :
⇑(g.comp f) = g ∘ f := rfl
@[simp] lemma monoid_with_zero_hom.coe_comp [mul_zero_one_class M] [mul_zero_one_class N]
[mul_zero_one_class P]
(g : monoid_with_zero_hom N P) (f : monoid_with_zero_hom M N) :
⇑(g.comp f) = g ∘ f := rfl
@[to_additive] lemma one_hom.comp_apply [has_one M] [has_one N] [has_one P]
(g : one_hom N P) (f : one_hom M N) (x : M) :
g.comp f x = g (f x) := rfl
@[to_additive] lemma mul_hom.comp_apply [has_mul M] [has_mul N] [has_mul P]
(g : mul_hom N P) (f : mul_hom M N) (x : M) :
g.comp f x = g (f x) := rfl
@[to_additive] lemma monoid_hom.comp_apply [mul_one_class M] [mul_one_class N] [mul_one_class P]
(g : N →* P) (f : M →* N) (x : M) :
g.comp f x = g (f x) := rfl
lemma monoid_with_zero_hom.comp_apply
[mul_zero_one_class M] [mul_zero_one_class N] [mul_zero_one_class P]
(g : monoid_with_zero_hom N P) (f : monoid_with_zero_hom M N) (x : M) :
g.comp f x = g (f x) := rfl
/-- Composition of monoid homomorphisms is associative. -/
@[to_additive] lemma one_hom.comp_assoc {Q : Type*} [has_one M] [has_one N] [has_one P] [has_one Q]
(f : one_hom M N) (g : one_hom N P) (h : one_hom P Q) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
@[to_additive] lemma mul_hom.comp_assoc {Q : Type*} [has_mul M] [has_mul N] [has_mul P] [has_mul Q]
(f : mul_hom M N) (g : mul_hom N P) (h : mul_hom P Q) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
@[to_additive] lemma monoid_hom.comp_assoc {Q : Type*}
[mul_one_class M] [mul_one_class N] [mul_one_class P] [mul_one_class Q]
(f : M →* N) (g : N →* P) (h : P →* Q) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
lemma monoid_with_zero_hom.comp_assoc {Q : Type*}
[mul_zero_one_class M] [mul_zero_one_class N] [mul_zero_one_class P] [mul_zero_one_class Q]
(f : monoid_with_zero_hom M N) (g : monoid_with_zero_hom N P) (h : monoid_with_zero_hom P Q) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
@[to_additive]
lemma one_hom.cancel_right [has_one M] [has_one N] [has_one P]
{g₁ g₂ : one_hom N P} {f : one_hom M N} (hf : function.surjective f) :
g₁.comp f = g₂.comp f ↔ g₁ = g₂ :=
⟨λ h, one_hom.ext $ (forall_iff_forall_surj hf).1 (one_hom.ext_iff.1 h), λ h, h ▸ rfl⟩
@[to_additive]
lemma mul_hom.cancel_right [has_mul M] [has_mul N] [has_mul P]
{g₁ g₂ : mul_hom N P} {f : mul_hom M N} (hf : function.surjective f) :
g₁.comp f = g₂.comp f ↔ g₁ = g₂ :=
⟨λ h, mul_hom.ext $ (forall_iff_forall_surj hf).1 (mul_hom.ext_iff.1 h), λ h, h ▸ rfl⟩
@[to_additive]
lemma monoid_hom.cancel_right
[mul_one_class M] [mul_one_class N] [mul_one_class P]
{g₁ g₂ : N →* P} {f : M →* N} (hf : function.surjective f) :
g₁.comp f = g₂.comp f ↔ g₁ = g₂ :=
⟨λ h, monoid_hom.ext $ (forall_iff_forall_surj hf).1 (monoid_hom.ext_iff.1 h), λ h, h ▸ rfl⟩
lemma monoid_with_zero_hom.cancel_right
[mul_zero_one_class M] [mul_zero_one_class N] [mul_zero_one_class P]
{g₁ g₂ : monoid_with_zero_hom N P} {f : monoid_with_zero_hom M N} (hf : function.surjective f) :
g₁.comp f = g₂.comp f ↔ g₁ = g₂ :=
⟨λ h, monoid_with_zero_hom.ext $ (forall_iff_forall_surj hf).1 (monoid_with_zero_hom.ext_iff.1 h),
λ h, h ▸ rfl⟩
@[to_additive]
lemma one_hom.cancel_left [has_one M] [has_one N] [has_one P]
{g : one_hom N P} {f₁ f₂ : one_hom M N} (hg : function.injective g) :
g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ :=
⟨λ h, one_hom.ext $ λ x, hg $ by rw [← one_hom.comp_apply, h, one_hom.comp_apply],
λ h, h ▸ rfl⟩
@[to_additive]
lemma mul_hom.cancel_left [has_one M] [has_one N] [has_one P]
{g : one_hom N P} {f₁ f₂ : one_hom M N} (hg : function.injective g) :
g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ :=
⟨λ h, one_hom.ext $ λ x, hg $ by rw [← one_hom.comp_apply, h, one_hom.comp_apply],
λ h, h ▸ rfl⟩
@[to_additive]
lemma monoid_hom.cancel_left [mul_one_class M] [mul_one_class N] [mul_one_class P]
{g : N →* P} {f₁ f₂ : M →* N} (hg : function.injective g) :
g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ :=
⟨λ h, monoid_hom.ext $ λ x, hg $ by rw [← monoid_hom.comp_apply, h, monoid_hom.comp_apply],
λ h, h ▸ rfl⟩
lemma monoid_with_zero_hom.cancel_left
[mul_zero_one_class M] [mul_zero_one_class N] [mul_zero_one_class P]
{g : monoid_with_zero_hom N P} {f₁ f₂ : monoid_with_zero_hom M N} (hg : function.injective g) :
g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ :=
⟨λ h, monoid_with_zero_hom.ext $ λ x, hg $ by rw [
← monoid_with_zero_hom.comp_apply, h, monoid_with_zero_hom.comp_apply],
λ h, h ▸ rfl⟩
@[to_additive]
lemma monoid_hom.to_one_hom_injective [mul_one_class M] [mul_one_class N] :
function.injective (monoid_hom.to_one_hom : (M →* N) → one_hom M N) :=
λ f g h, monoid_hom.ext $ one_hom.ext_iff.mp h
@[to_additive]
lemma monoid_hom.to_mul_hom_injective [mul_one_class M] [mul_one_class N] :
function.injective (monoid_hom.to_mul_hom : (M →* N) → mul_hom M N) :=
λ f g h, monoid_hom.ext $ mul_hom.ext_iff.mp h
lemma monoid_with_zero_hom.to_monoid_hom_injective [monoid_with_zero M] [monoid_with_zero N] :
function.injective (monoid_with_zero_hom.to_monoid_hom : monoid_with_zero_hom M N → M →* N) :=
λ f g h, monoid_with_zero_hom.ext $ monoid_hom.ext_iff.mp h
lemma monoid_with_zero_hom.to_zero_hom_injective [monoid_with_zero M] [monoid_with_zero N] :
function.injective (monoid_with_zero_hom.to_zero_hom : monoid_with_zero_hom M N → zero_hom M N) :=
λ f g h, monoid_with_zero_hom.ext $ zero_hom.ext_iff.mp h
@[simp, to_additive] lemma one_hom.comp_id [has_one M] [has_one N]
(f : one_hom M N) : f.comp (one_hom.id M) = f := one_hom.ext $ λ x, rfl
@[simp, to_additive] lemma mul_hom.comp_id [has_mul M] [has_mul N]
(f : mul_hom M N) : f.comp (mul_hom.id M) = f := mul_hom.ext $ λ x, rfl
@[simp, to_additive] lemma monoid_hom.comp_id [mul_one_class M] [mul_one_class N]
(f : M →* N) : f.comp (monoid_hom.id M) = f := monoid_hom.ext $ λ x, rfl
@[simp] lemma monoid_with_zero_hom.comp_id [mul_zero_one_class M] [mul_zero_one_class N]
(f : monoid_with_zero_hom M N) : f.comp (monoid_with_zero_hom.id M) = f :=
monoid_with_zero_hom.ext $ λ x, rfl
@[simp, to_additive] lemma one_hom.id_comp [has_one M] [has_one N]
(f : one_hom M N) : (one_hom.id N).comp f = f := one_hom.ext $ λ x, rfl
@[simp, to_additive] lemma mul_hom.id_comp [has_mul M] [has_mul N]
(f : mul_hom M N) : (mul_hom.id N).comp f = f := mul_hom.ext $ λ x, rfl
@[simp, to_additive] lemma monoid_hom.id_comp [mul_one_class M] [mul_one_class N]
(f : M →* N) : (monoid_hom.id N).comp f = f := monoid_hom.ext $ λ x, rfl
@[simp] lemma monoid_with_zero_hom.id_comp [mul_zero_one_class M] [mul_zero_one_class N]
(f : monoid_with_zero_hom M N) : (monoid_with_zero_hom.id N).comp f = f :=
monoid_with_zero_hom.ext $ λ x, rfl
section End
namespace monoid
variables (M) [mul_one_class M]
/-- The monoid of endomorphisms. -/
protected def End := M →* M
namespace End
instance : monoid (monoid.End M) :=
{ mul := monoid_hom.comp,
one := monoid_hom.id M,
mul_assoc := λ _ _ _, monoid_hom.comp_assoc _ _ _,
mul_one := monoid_hom.comp_id,
one_mul := monoid_hom.id_comp }
instance : inhabited (monoid.End M) := ⟨1⟩
instance : has_coe_to_fun (monoid.End M) := ⟨_, monoid_hom.to_fun⟩
end End
@[simp] lemma coe_one : ((1 : monoid.End M) : M → M) = id := rfl
@[simp] lemma coe_mul (f g) : ((f * g : monoid.End M) : M → M) = f ∘ g := rfl
end monoid
namespace add_monoid
variables (A : Type*) [add_zero_class A]
/-- The monoid of endomorphisms. -/
protected def End := A →+ A
namespace End
instance : monoid (add_monoid.End A) :=
{ mul := add_monoid_hom.comp,
one := add_monoid_hom.id A,
mul_assoc := λ _ _ _, add_monoid_hom.comp_assoc _ _ _,
mul_one := add_monoid_hom.comp_id,
one_mul := add_monoid_hom.id_comp }
instance : inhabited (add_monoid.End A) := ⟨1⟩
instance : has_coe_to_fun (add_monoid.End A) := ⟨_, add_monoid_hom.to_fun⟩
end End
@[simp] lemma coe_one : ((1 : add_monoid.End A) : A → A) = id := rfl
@[simp] lemma coe_mul (f g) : ((f * g : add_monoid.End A) : A → A) = f ∘ g := rfl
end add_monoid
end End
/-- `1` is the homomorphism sending all elements to `1`. -/
@[to_additive]
instance [has_one M] [has_one N] : has_one (one_hom M N) := ⟨⟨λ _, 1, rfl⟩⟩
/-- `1` is the multiplicative homomorphism sending all elements to `1`. -/
@[to_additive]
instance [has_mul M] [mul_one_class N] : has_one (mul_hom M N) :=
⟨⟨λ _, 1, λ _ _, (one_mul 1).symm⟩⟩
/-- `1` is the monoid homomorphism sending all elements to `1`. -/
@[to_additive]
instance [mul_one_class M] [mul_one_class N] : has_one (M →* N) :=
⟨⟨λ _, 1, rfl, λ _ _, (one_mul 1).symm⟩⟩
/-- `0` is the homomorphism sending all elements to `0`. -/
add_decl_doc zero_hom.has_zero
/-- `0` is the additive homomorphism sending all elements to `0`. -/
add_decl_doc add_hom.has_zero
/-- `0` is the additive monoid homomorphism sending all elements to `0`. -/
add_decl_doc add_monoid_hom.has_zero
@[simp, to_additive] lemma one_hom.one_apply [has_one M] [has_one N]
(x : M) : (1 : one_hom M N) x = 1 := rfl
@[simp, to_additive] lemma monoid_hom.one_apply [mul_one_class M] [mul_one_class N]
(x : M) : (1 : M →* N) x = 1 := rfl
@[simp, to_additive] lemma one_hom.one_comp [has_one M] [has_one N] [has_one P] (f : one_hom M N) :
(1 : one_hom N P).comp f = 1 := rfl
@[simp, to_additive] lemma one_hom.comp_one [has_one M] [has_one N] [has_one P] (f : one_hom N P) :
f.comp (1 : one_hom M N) = 1 :=
by { ext, simp only [one_hom.map_one, one_hom.coe_comp, function.comp_app, one_hom.one_apply] }
@[to_additive]
instance [has_one M] [has_one N] : inhabited (one_hom M N) := ⟨1⟩
@[to_additive]
instance [has_mul M] [mul_one_class N] : inhabited (mul_hom M N) := ⟨1⟩
@[to_additive]
instance [mul_one_class M] [mul_one_class N] : inhabited (M →* N) := ⟨1⟩
-- unlike the other homs, `monoid_with_zero_hom` does not have a `1` or `0`
instance [mul_zero_one_class M] : inhabited (monoid_with_zero_hom M M) :=
⟨monoid_with_zero_hom.id M⟩
namespace monoid_hom
variables [mM : mul_one_class M] [mN : mul_one_class N] [mP : mul_one_class P]
variables [group G] [comm_group H]
/-- Given two monoid morphisms `f`, `g` to a commutative monoid, `f * g` is the monoid morphism
sending `x` to `f x * g x`. -/
@[to_additive]
instance {M N} {mM : mul_one_class M} [comm_monoid N] : has_mul (M →* N) :=
⟨λ f g,
{ to_fun := λ m, f m * g m,
map_one' := show f 1 * g 1 = 1, by simp,
map_mul' := begin intros, show f (x * y) * g (x * y) = f x * g x * (f y * g y),
rw [f.map_mul, g.map_mul, ←mul_assoc, ←mul_assoc, mul_right_comm (f x)], end }⟩
/-- Given two additive monoid morphisms `f`, `g` to an additive commutative monoid, `f + g` is the
additive monoid morphism sending `x` to `f x + g x`. -/
add_decl_doc add_monoid_hom.has_add
@[simp, to_additive] lemma mul_apply {M N} {mM : mul_one_class M} {mN : comm_monoid N}
(f g : M →* N) (x : M) :
(f * g) x = f x * g x := rfl
@[simp, to_additive] lemma one_comp [mul_one_class M] [mul_one_class N] [mul_one_class P]
(f : M →* N) : (1 : N →* P).comp f = 1 := rfl
@[simp, to_additive] lemma comp_one [mul_one_class M] [mul_one_class N] [mul_one_class P]
(f : N →* P) : f.comp (1 : M →* N) = 1 :=
by { ext, simp only [map_one, coe_comp, function.comp_app, one_apply] }
@[to_additive] lemma mul_comp [mul_one_class M] [comm_monoid N] [comm_monoid P]
(g₁ g₂ : N →* P) (f : M →* N) :
(g₁ * g₂).comp f = g₁.comp f * g₂.comp f := rfl
@[to_additive] lemma comp_mul [mul_one_class M] [comm_monoid N] [comm_monoid P]
(g : N →* P) (f₁ f₂ : M →* N) :
g.comp (f₁ * f₂) = g.comp f₁ * g.comp f₂ :=
by { ext, simp only [mul_apply, function.comp_app, map_mul, coe_comp] }
/-- If two homomorphism from a group to a monoid are equal at `x`, then they are equal at `x⁻¹`. -/
@[to_additive "If two homomorphism from an additive group to an additive monoid are equal at `x`,
then they are equal at `-x`." ]
lemma eq_on_inv {G} [group G] [monoid M] {f g : G →* M} {x : G} (h : f x = g x) :
f x⁻¹ = g x⁻¹ :=
left_inv_eq_right_inv (f.map_mul_eq_one $ inv_mul_self x) $
h.symm ▸ g.map_mul_eq_one $ mul_inv_self x
/-- Group homomorphisms preserve inverse. -/
@[simp, to_additive]
theorem map_inv {G H} [group G] [group H] (f : G →* H) (g : G) : f g⁻¹ = (f g)⁻¹ :=
eq_inv_of_mul_eq_one $ f.map_mul_eq_one $ inv_mul_self g
/-- Group homomorphisms preserve division. -/
@[simp, to_additive]
theorem map_mul_inv {G H} [group G] [group H] (f : G →* H) (g h : G) :
f (g * h⁻¹) = (f g) * (f h)⁻¹ := by rw [f.map_mul, f.map_inv]
/-- A homomorphism from a group to a monoid is injective iff its kernel is trivial.
For the iff statement on the triviality of the kernel, see `monoid_hom.injective_iff'`. -/
@[to_additive /-" A homomorphism from an additive group to an additive monoid is injective iff
its kernel is trivial. For the iff statement on the triviality of the kernel,
see `add_monoid_hom.injective_iff'`. "-/]
lemma injective_iff {G H} [group G] [mul_one_class H] (f : G →* H) :
function.injective f ↔ (∀ a, f a = 1 → a = 1) :=
⟨λ h x hfx, h $ hfx.trans f.map_one.symm,
λ h x y hxy, mul_inv_eq_one.1 $ h _ $ by rw [f.map_mul, hxy, ← f.map_mul, mul_inv_self, f.map_one]⟩
/-- A homomorphism from a group to a monoid is injective iff its kernel is trivial,
stated as an iff on the triviality of the kernel.
For the implication, see `monoid_hom.injective_iff`. -/
@[to_additive /-" A homomorphism from an additive group to an additive monoid is injective iff
its kernel is trivial, stated as an iff on the triviality of the kernel. For the implication, see
`add_monoid_hom.injective_iff`. "-/]
lemma injective_iff' {G H} [group G] [mul_one_class H] (f : G →* H) :
function.injective f ↔ (∀ a, f a = 1 ↔ a = 1) :=
f.injective_iff.trans $ forall_congr $ λ a, ⟨λ h, ⟨h, λ H, H.symm ▸ f.map_one⟩, iff.mp⟩
include mM
/-- Makes a group homomorphism from a proof that the map preserves multiplication. -/
@[to_additive "Makes an additive group homomorphism from a proof that the map preserves addition.",
simps {fully_applied := ff}]
def mk' (f : M → G) (map_mul : ∀ a b : M, f (a * b) = f a * f b) : M →* G :=
{ to_fun := f,
map_mul' := map_mul,
map_one' := mul_left_eq_self.1 $ by rw [←map_mul, mul_one] }
omit mM
/-- Makes a group homomorphism from a proof that the map preserves right division `λ x y, x * y⁻¹`.
-/
@[to_additive "Makes an additive group homomorphism from a proof that the map preserves
the operation `λ a b, a + -b`. See also `add_monoid_hom.of_map_sub` for a version using
`λ a b, a - b`."]
def of_map_mul_inv {H : Type*} [group H] (f : G → H)
(map_div : ∀ a b : G, f (a * b⁻¹) = f a * (f b)⁻¹) :
G →* H :=
mk' f $ λ x y,
calc f (x * y) = f x * (f $ 1 * 1⁻¹ * y⁻¹)⁻¹ : by simp only [one_mul, one_inv, ← map_div, inv_inv]
... = f x * f y : by { simp only [map_div], simp only [mul_right_inv, one_mul, inv_inv] }
@[simp, to_additive] lemma coe_of_map_mul_inv {H : Type*} [group H] (f : G → H)
(map_div : ∀ a b : G, f (a * b⁻¹) = f a * (f b)⁻¹) :
⇑(of_map_mul_inv f map_div) = f :=
rfl
/-- If `f` is a monoid homomorphism to a commutative group, then `f⁻¹` is the homomorphism sending
`x` to `(f x)⁻¹`. -/
@[to_additive]
instance {M G} [mul_one_class M] [comm_group G] : has_inv (M →* G) :=
⟨λ f, mk' (λ g, (f g)⁻¹) $ λ a b, by rw [←mul_inv, f.map_mul]⟩
/-- If `f` is an additive monoid homomorphism to an additive commutative group, then `-f` is the
homomorphism sending `x` to `-(f x)`. -/
add_decl_doc add_monoid_hom.has_neg
@[simp, to_additive] lemma inv_apply {M G} {mM : mul_one_class M} {gG : comm_group G}
(f : M →* G) (x : M) :
f⁻¹ x = (f x)⁻¹ := rfl
@[simp, to_additive] lemma inv_comp {M N A} {mM : mul_one_class M} {gN : mul_one_class N}
{gA : comm_group A} (φ : N →* A) (ψ : M →* N) : φ⁻¹.comp ψ = (φ.comp ψ)⁻¹ :=
by { ext, simp only [function.comp_app, inv_apply, coe_comp] }
@[simp, to_additive] lemma comp_inv {M A B} {mM : mul_one_class M} {mA : comm_group A}
{mB : comm_group B} (φ : A →* B) (ψ : M →* A) : φ.comp ψ⁻¹ = (φ.comp ψ)⁻¹ :=
by { ext, simp only [function.comp_app, inv_apply, map_inv, coe_comp] }
/-- If `f` and `g` are monoid homomorphisms to a commutative group, then `f / g` is the homomorphism
sending `x` to `(f x) / (g x)`. -/
@[to_additive]
instance {M G} [mul_one_class M] [comm_group G] : has_div (M →* G) :=
⟨λ f g, mk' (λ x, f x / g x) $ λ a b,
by simp [div_eq_mul_inv, mul_assoc, mul_left_comm, mul_comm]⟩
/-- If `f` and `g` are monoid homomorphisms to an additive commutative group, then `f - g`
is the homomorphism sending `x` to `(f x) - (g x)`. -/
add_decl_doc add_monoid_hom.has_sub
@[simp, to_additive] lemma div_apply {M G} {mM : mul_one_class M} {gG : comm_group G}
(f g : M →* G) (x : M) :
(f / g) x = f x / g x := rfl
end monoid_hom
namespace add_monoid_hom
variables {A B : Type*} [add_zero_class A] [add_comm_group B] [add_group G] [add_group H]
/-- Additive group homomorphisms preserve subtraction. -/
@[simp] theorem map_sub (f : G →+ H) (g h : G) : f (g - h) = (f g) - (f h) :=
by rw [sub_eq_add_neg, sub_eq_add_neg, f.map_add_neg g h]
/-- Define a morphism of additive groups given a map which respects difference. -/
def of_map_sub (f : G → H) (hf : ∀ x y, f (x - y) = f x - f y) : G →+ H :=
of_map_add_neg f (by simpa only [sub_eq_add_neg] using hf)
@[simp] lemma coe_of_map_sub (f : G → H) (hf : ∀ x y, f (x - y) = f x - f y) :
⇑(of_map_sub f hf) = f :=
rfl
end add_monoid_hom
section commute
variables [mul_one_class M] [mul_one_class N] {a x y : M}
@[simp, to_additive]
protected lemma semiconj_by.map (h : semiconj_by a x y) (f : M →* N) :
semiconj_by (f a) (f x) (f y) :=
by simpa only [semiconj_by, f.map_mul] using congr_arg f h
@[simp, to_additive]
protected lemma commute.map (h : commute x y) (f : M →* N) : commute (f x) (f y) := h.map f
end commute
|
199a0a9ffb1e3770d7a9715dde4fc87dbd339541 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/tactic/itauto.lean | b396a36e779a8c2f1f9206a22111cbcfb56bab67 | [
"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 | 25,022 | lean | /-
Copyright (c) 2021 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import tactic.hint
/-!
# Intuitionistic tautology (`itauto`) decision procedure
The `itauto` tactic will prove any intuitionistic tautology. It implements the well known
`G4ip` algorithm:
[Dyckhoff, *Contraction-free sequent calculi for intuitionistic logic*][dyckhoff_1992].
All built in propositional connectives are supported: `true`, `false`, `and`, `or`, `implies`,
`not`, `iff`, `xor`, as well as `eq` and `ne` on propositions. Anything else, including definitions
and predicate logical connectives (`forall` and `exists`), are not supported, and will have to be
simplified or instantiated before calling this tactic.
The resulting proofs will never use any axioms except possibly `propext`, and `propext` is only
used if the input formula contains an equality of propositions `p = q`.
## Implementation notes
The core logic of the prover is in three functions:
* `prove : context → prop → state_t ℕ option proof`: The main entry point.
Gets a context and a goal, and returns a `proof` object or fails, using `state_t ℕ` for the name
generator.
* `search : context → prop → state_t ℕ option proof`: Same meaning as `proof`, called during the
search phase (see below).
* `context.add : prop → proof → context → except (prop → proof) context`: Adds a proposition with
its proof into the context, but it also does some simplifications on the spot while doing so.
It will either return the new context, or if it happens to notice a proof of false, it will
return a function to compute a proof of any proposition in the original context.
The intuitionistic logic rules are separated into three groups:
* level 1: No splitting, validity preserving: apply whenever you can.
Left rules in `context.add`, right rules in `prove`.
* `context.add`:
* simplify `Γ, ⊤ ⊢ B` to `Γ ⊢ B`
* `Γ, ⊥ ⊢ B` is true
* simplify `Γ, A ∧ B ⊢ C` to `Γ, A, B ⊢ C`
* simplify `Γ, ⊥ → A ⊢ B` to `Γ ⊢ B`
* simplify `Γ, ⊤ → A ⊢ B` to `Γ, A ⊢ B`
* simplify `Γ, A ∧ B → C ⊢ D` to `Γ, A → B → C ⊢ D`
* simplify `Γ, A ∨ B → C ⊢ D` to `Γ, A → C, B → C ⊢ D`
* `prove`:
* `Γ ⊢ ⊤` is true
* simplify `Γ ⊢ A → B` to `Γ, A ⊢ B`
* `search`:
* `Γ, P ⊢ P` is true
* simplify `Γ, P, P → A ⊢ B` to `Γ, P, A ⊢ B`
* level 2: Splitting rules, validity preserving: apply after level 1 rules. Done in `prove`
* simplify `Γ ⊢ A ∧ B` to `Γ ⊢ A` and `Γ ⊢ B`
* simplify `Γ, A ∨ B ⊢ C` to `Γ, A ⊢ C` and `Γ, B ⊢ C`
* level 3: Splitting rules, not validity preserving: apply only if nothing else applies.
Done in `search`
* `Γ ⊢ A ∨ B` follows from `Γ ⊢ A`
* `Γ ⊢ A ∨ B` follows from `Γ ⊢ B`
* `Γ, (A₁ → A₂) → C ⊢ B` follows from `Γ, A₂ → C, A₁ ⊢ A₂` and `Γ, C ⊢ B`
This covers the core algorithm, which only handles `true`, `false`, `and`, `or`, and `implies`.
For `iff` and `eq`, we treat them essentially the same as `(p → q) ∧ (q → p)`, although we use
a different `prop` representation because we have to remember to apply different theorems during
replay. For definitions like `not` and `xor`, we just eagerly unfold them. (This could potentially
cause a blowup issue for `xor`, but it isn't used very often anyway. We could add it to the `prop`
grammar if it matters.)
## Tags
propositional logic, intuitionistic logic, decision procedure
-/
namespace tactic
namespace itauto
/-- Different propositional constructors that are variants of "and" for the purposes of the
theorem prover. -/
@[derive [has_reflect, decidable_eq]]
inductive and_kind | and | iff | eq
instance : inhabited and_kind := ⟨and_kind.and⟩
/-- A reified inductive type for propositional logic. -/
@[derive [has_reflect, decidable_eq]]
inductive prop : Type
| var : ℕ → prop -- propositional atoms P_i
| true : prop -- ⊤
| false : prop -- ⊥
| and' : and_kind → prop → prop → prop -- p ∧ q, p ↔ q, p = q
| or : prop → prop → prop -- p ∨ q
| imp : prop → prop → prop -- p → q
/-- Constructor for `p ∧ q`. -/
@[pattern] def prop.and : prop → prop → prop := prop.and' and_kind.and
/-- Constructor for `p ↔ q`. -/
@[pattern] def prop.iff : prop → prop → prop := prop.and' and_kind.iff
/-- Constructor for `p = q`. -/
@[pattern] def prop.eq : prop → prop → prop := prop.and' and_kind.eq
/-- Constructor for `¬ p`. -/
@[pattern] def prop.not (a : prop) : prop := a.imp prop.false
/-- Constructor for `xor p q`. -/
@[pattern] def prop.xor (a b : prop) : prop := (a.and b.not).or (b.and a.not)
instance : inhabited prop := ⟨prop.true⟩
/-- Given the contents of an `and` variant, return the two conjuncts. -/
def and_kind.sides : and_kind → prop → prop → prop × prop
| and_kind.and A B := (A, B)
| _ A B := (A.imp B, B.imp A)
/-- Debugging printer for propositions. -/
meta def prop.to_format : prop → format
| (prop.var i) := format!"v{i}"
| prop.true := format!"⊤"
| prop.false := format!"⊥"
| (prop.and p q) := format!"({p.to_format} ∧ {q.to_format})"
| (prop.iff p q) := format!"({p.to_format} ↔ {q.to_format})"
| (prop.eq p q) := format!"({p.to_format} = {q.to_format})"
| (prop.or p q) := format!"({p.to_format} ∨ {q.to_format})"
| (prop.imp p q) := format!"({p.to_format} → {q.to_format})"
meta instance : has_to_format prop := ⟨prop.to_format⟩
section
open ordering
/-- A comparator for `and_kind`. (There should really be a derive handler for this.) -/
def and_kind.cmp (p q : and_kind) : ordering :=
by { cases p; cases q, exacts [eq, lt, lt, gt, eq, lt, gt, gt, eq] }
/-- A comparator for propositions. (There should really be a derive handler for this.) -/
def prop.cmp (p q : prop) : ordering :=
begin
induction p with _ ap _ _ p₁ p₂ _ _ p₁ p₂ _ _ p₁ p₂ _ _ p₁ p₂ generalizing q; cases q,
case var var { exact cmp p q },
case true true { exact eq },
case false false { exact eq },
case and' and' : aq q₁ q₂ { exact (ap.cmp aq).or_else ((p₁ q₁).or_else (p₂ q₂)) },
case or or : q₁ q₂ { exact (p₁ q₁).or_else (p₂ q₂) },
case imp imp : q₁ q₂ { exact (p₁ q₁).or_else (p₂ q₂) },
exacts [lt, lt, lt, lt, lt,
gt, lt, lt, lt, lt,
gt, gt, lt, lt, lt,
gt, gt, gt, lt, lt,
gt, gt, gt, gt, lt,
gt, gt, gt, gt, gt]
end
instance : has_lt prop := ⟨λ p q, p.cmp q = lt⟩
instance : decidable_rel (@has_lt.lt prop _) := λ _ _, ordering.decidable_eq _ _
end
/-- A reified inductive proof type for intuitionistic propositional logic. -/
@[derive has_reflect]
inductive proof
-- (n: A) ⊢ A
| hyp (n : name) : proof
-- ⊢ ⊤
| triv : proof
-- (p: ⊥) ⊢ A
| exfalso' (p : proof) : proof
-- (p: (x: A) ⊢ B) ⊢ A → B
| intro (x : name) (p : proof) : proof
-- ak = and: (p: A ∧ B) ⊢ A
-- ak = iff: (p: A ↔ B) ⊢ A → B
-- ak = eq: (p: A = B) ⊢ A → B
| and_left (ak : and_kind) (p : proof) : proof
-- ak = and: (p: A ∧ B) ⊢ B
-- ak = iff: (p: A ↔ B) ⊢ B → A
-- ak = eq: (p: A = B) ⊢ B → A
| and_right (ak : and_kind) (p : proof) : proof
-- ak = and: (p₁: A) (p₂: B) ⊢ A ∧ B
-- ak = iff: (p₁: A → B) (p₁: B → A) ⊢ A ↔ B
-- ak = eq: (p₁: A → B) (p₁: B → A) ⊢ A = B
| and_intro (ak : and_kind) (p₁ p₂ : proof) : proof
-- ak = and: (p: A ∧ B → C) ⊢ A → B → C
-- ak = iff: (p: (A ↔ B) → C) ⊢ (A → B) → (B → A) → C
-- ak = eq: (p: (A = B) → C) ⊢ (A → B) → (B → A) → C
| curry (ak : and_kind) (p : proof) : proof
-- This is a partial application of curry.
-- ak = and: (p: A ∧ B → C) (q : A) ⊢ B → C
-- ak = iff: (p: (A ↔ B) → C) (q: A → B) ⊢ (B → A) → C
-- ak = eq: (p: (A ↔ B) → C) (q: A → B) ⊢ (B → A) → C
| curry₂ (ak : and_kind) (p q : proof) : proof
-- (p: A → B) (q: A) ⊢ B
| app' : proof → proof → proof
-- (p: A ∨ B → C) ⊢ A → C
| or_imp_left (p : proof) : proof
-- (p: A ∨ B → C) ⊢ B → C
| or_imp_right (p : proof) : proof
-- (p: A) ⊢ A ∨ B
| or_inl (p : proof) : proof
-- (p: B) ⊢ A ∨ B
| or_inr (p : proof) : proof
-- (p: B) ⊢ A ∨ B
-- (p₁: A ∨ B) (p₂: (x: A) ⊢ C) (p₃: (x: B) ⊢ C) ⊢ C
| or_elim (p₁ : proof) (x : name) (p₂ p₃ : proof) : proof
-- The variable x here names the variable that will be used in the elaborated proof
-- (p: ((x:A) → B) → C) ⊢ B → C
| imp_imp_simp (x : name) (p : proof) : proof
instance : inhabited proof := ⟨proof.triv⟩
/-- Debugging printer for proof objects. -/
meta def proof.to_format : proof → format
| (proof.hyp i) := to_fmt i
| proof.triv := "triv"
| (proof.exfalso' p) := format!"(exfalso {p.to_format})"
| (proof.intro x p) := format!"(λ {x}, {p.to_format})"
| (proof.and_left _ p) := format!"{p.to_format} .1"
| (proof.and_right _ p) := format!"{p.to_format} .2"
| (proof.and_intro _ p q) := format!"⟨{p.to_format}, {q.to_format}⟩"
| (proof.curry _ p) := format!"(curry {p.to_format})"
| (proof.curry₂ _ p q) := format!"(curry {p.to_format} {q.to_format})"
| (proof.app' p q) := format!"({p.to_format} {q.to_format})"
| (proof.or_imp_left p) := format!"(or_imp_left {p.to_format})"
| (proof.or_imp_right p) := format!"(or_imp_right {p.to_format})"
| (proof.or_inl p) := format!"(or.inl {p.to_format})"
| (proof.or_inr p) := format!"(or.inr {p.to_format})"
| (proof.or_elim p x q r) :=
format!"({p.to_format}.elim (λ {x}, {q.to_format}) (λ {x}, {r.to_format})"
| (proof.imp_imp_simp _ p) := format!"(imp_imp_simp {p.to_format})"
meta instance : has_to_format proof := ⟨proof.to_format⟩
/-- A variant on `proof.exfalso'` that performs opportunistic simplification. -/
meta def proof.exfalso : prop → proof → proof
| prop.false p := p
| A p := proof.exfalso' p
/-- A variant on `proof.app'` that performs opportunistic simplification.
(This doesn't do full normalization because we don't want the proof size to blow up.) -/
meta def proof.app : proof → proof → proof
| (proof.curry ak p) q := proof.curry₂ ak p q
| (proof.curry₂ ak p q) r := p.app (q.and_intro ak r)
| (proof.or_imp_left p) q := p.app q.or_inl
| (proof.or_imp_right p) q := p.app q.or_inr
| (proof.imp_imp_simp x p) q := p.app (proof.intro x q)
| p q := p.app' q
-- Note(Mario): the typechecker is disabled because it requires proofs to carry around additional
-- props. These can be retrieved from the git history if you want to re-enable this.
/-
/-- A typechecker for the `proof` type. This is not used by the tactic but can be used for
debugging. -/
meta def proof.check : name_map prop → proof → option prop
| Γ (proof.hyp i) := Γ.find i
| Γ proof.triv := some prop.true
| Γ (proof.exfalso' A p) := guard (p.check Γ = some prop.false) $> A
| Γ (proof.intro x A p) := do B ← p.check (Γ.insert x A), pure (prop.imp A B)
| Γ (proof.and_left ak p) := do
prop.and' ak' A B ← p.check Γ | none,
guard (ak = ak') $> (ak.sides A B).1
| Γ (proof.and_right ak p) := do
prop.and' ak' A B ← p.check Γ | none,
guard (ak = ak') $> (ak.sides A B).2
| Γ (proof.and_intro and_kind.and p q) := do
A ← p.check Γ, B ← q.check Γ,
pure (A.and B)
| Γ (proof.and_intro ak p q) := do
prop.imp A B ← p.check Γ | none,
C ← q.check Γ, guard (C = prop.imp B A) $> (A.and' ak B)
| Γ (proof.curry ak p) := do
prop.imp (prop.and' ak' A B) C ← p.check Γ | none,
let (A', B') := ak.sides A B,
guard (ak = ak') $> (A'.imp $ B'.imp C)
| Γ (proof.curry₂ ak p q) := do
prop.imp (prop.and' ak' A B) C ← p.check Γ | none,
A₂ ← q.check Γ,
let (A', B') := ak.sides A B,
guard (ak = ak' ∧ A₂ = A') $> (B'.imp C)
| Γ (proof.app' p q) := do prop.imp A B ← p.check Γ | none, A' ← q.check Γ, guard (A = A') $> B
| Γ (proof.or_imp_left B p) := do
prop.imp (prop.or A B') C ← p.check Γ | none,
guard (B = B') $> (A.imp C)
| Γ (proof.or_imp_right A p) := do
prop.imp (prop.or A' B) C ← p.check Γ | none,
guard (A = A') $> (B.imp C)
| Γ (proof.or_inl B p) := do A ← p.check Γ | none, pure (A.or B)
| Γ (proof.or_inr A p) := do B ← p.check Γ | none, pure (A.or B)
| Γ (proof.or_elim p x q r) := do
prop.or A B ← p.check Γ | none,
C ← q.check (Γ.insert x A),
C' ← r.check (Γ.insert x B),
guard (C = C') $> C
| Γ (proof.imp_imp_simp x A p) := do
prop.imp (prop.imp A' B) C ← p.check Γ | none,
guard (A = A') $> (B.imp C)
-/
/-- Get a new name in the pattern `h0, h1, h2, ...` -/
@[inline] meta def fresh_name {m} [monad m] : state_t ℕ m name :=
⟨λ n, pure (mk_simple_name ("h" ++ to_string n), n+1)⟩
/-- The context during proof search is a map from propositions to proof values. -/
meta def context := native.rb_map prop proof
/-- Debug printer for the context. -/
meta def context.to_format (Γ : context) : format :=
Γ.fold "" $ λ P p f, P.to_format ++ " := " ++ p.to_format ++ ",\n" ++ f
meta instance : has_to_format context := ⟨context.to_format⟩
/-- Insert a proposition and its proof into the context, as in `have : A := p`. This will eagerly
apply all level 1 rules on the spot, which are rules that don't split the goal and are validity
preserving: specifically, we drop `⊤` and `A → ⊤` hypotheses, close the goal if we find a `⊥`
hypothesis, split all conjunctions, and also simplify `⊥ → A` (drop), `⊤ → A` (simplify to `A`),
`A ∧ B → C` (curry to `A → B → C`) and `A ∨ B → C` (rewrite to `(A → C) ∧ (B → C)` and split). -/
meta def context.add : prop → proof → context → except (prop → proof) context
| prop.true p Γ := pure Γ
| prop.false p Γ := except.error (λ A, proof.exfalso A p)
| (prop.and' ak A B) p Γ := do
let (A, B) := ak.sides A B,
Γ ← Γ.add A (p.and_left ak),
Γ.add B (p.and_right ak)
| (prop.imp prop.false A) p Γ := pure Γ
| (prop.imp prop.true A) p Γ := Γ.add A (p.app proof.triv)
| (prop.imp (prop.and' ak A B) C) p Γ :=
let (A, B) := ak.sides A B in
Γ.add (prop.imp A (B.imp C)) (p.curry ak)
| (prop.imp (prop.or A B) C) p Γ := do
Γ ← Γ.add (A.imp C) p.or_imp_left,
Γ.add (B.imp C) p.or_imp_right
| (prop.imp A prop.true) p Γ := pure Γ
| A p Γ := pure (Γ.insert A p)
/-- Add `A` to the context `Γ` with proof `p`. This version of `context.add` takes a continuation
and a target proposition `B`, so that in the case that `⊥` is found we can skip the continuation
and just prove `B` outright. -/
@[inline] meta def context.with_add {m} [monad m] (Γ : context) (A : prop) (p : proof)
(B : prop) (f : context → prop → m proof) : m proof :=
match Γ.add A p with
| except.ok Γ_A := f Γ_A B
| except.error p := pure (p B)
end
/-- The search phase, which deals with the level 3 rules, which are rules that are not validity
preserving and so require proof search. One obvious one is the or-introduction rule: we prove
`A ∨ B` by proving `A` or `B`, and we might have to try one and backtrack.
There are two rules dealing with implication in this category: `p, p -> C ⊢ B` where `p` is an
atom (which is safe if we can find it but often requires the right search to expose the `p`
assumption), and `(A₁ → A₂) → C ⊢ B`. We decompose the double implication into two subgoals: one to
prove `A₁ → A₂`, which can be written `A₂ → C, A₁ ⊢ A₂` (where we used `A₁` to simplify
`(A₁ → A₂) → C`), and one to use the consequent, `C ⊢ B`. The search here is that there are
potentially many implications to split like this, and we have to try all of them if we want to be
complete. -/
meta def search (prove : context → prop → state_t ℕ option proof) :
context → prop → state_t ℕ option proof
| Γ B := match Γ.find B with
| some p := pure p
| none := match B with
| prop.or B₁ B₂ := proof.or_inl <$> prove Γ B₁ <|> proof.or_inr <$> prove Γ B₂
| _ := ⟨λ n, Γ.fold none $ λ A p r, r <|> match A with
| prop.imp A' C := match Γ.find A' with
| some q := (context.with_add (Γ.erase A) C (p.app q) B prove).1 n
| none := match A' with
| prop.imp A₁ A₂ :=
(do {
let Γ : context := Γ.erase A,
a ← fresh_name,
p₁ ← Γ.with_add A₁ (proof.hyp a) A₂ $ λ Γ_A₁ A₂,
Γ_A₁.with_add (prop.imp A₂ C) (proof.imp_imp_simp a p) A₂ prove,
Γ.with_add C (p.app (proof.intro a p₁)) B prove } : state_t ℕ option proof).1 n
| _ := none
end
end
| _ := none
end⟩
end
end
/-- The main prover. This receives a context of proven or assumed lemmas and a target proposition,
and returns a proof or `none` (with state for the fresh variable generator).
The intuitionistic logic rules are separated into three groups:
* level 1: No splitting, validity preserving: apply whenever you can.
Left rules in `context.add`, right rules in `prove`
* level 2: Splitting rules, validity preserving: apply after level 1 rules. Done in `prove`
* level 3: Splitting rules, not validity preserving: apply only if nothing else applies.
Done in `search`
The level 1 rules on the right of the turnstile are `Γ ⊢ ⊤` and `Γ ⊢ A → B`, these are easy to
handle. The rule `Γ ⊢ A ∧ B` is a level 2 rule, also handled here. If none of these apply, we try
the level 2 rule `A ∨ B ⊢ C` by searching the context and splitting all ors we find. Finally, if
we don't make any more progress, we go to the search phase.
-/
meta def prove : context → prop → state_t ℕ option proof
| Γ prop.true := pure proof.triv
| Γ (prop.imp A B) := do
a ← fresh_name,
proof.intro a <$> Γ.with_add A (proof.hyp a) B prove
| Γ (prop.and' ak A B) := do
let (A, B) := ak.sides A B,
p ← prove Γ A,
q ← prove Γ B,
pure (p.and_intro ak q)
| Γ B := Γ.fold (λ b Γ, cond b prove (search prove) Γ B) (λ A p IH b Γ,
match A with
| prop.or A₁ A₂ := do
let Γ : context := Γ.erase A,
a ← fresh_name,
p₁ ← Γ.with_add A₁ (proof.hyp a) B (λ Γ _, IH tt Γ),
p₂ ← Γ.with_add A₂ (proof.hyp a) B (λ Γ _, IH tt Γ),
pure (proof.or_elim p a p₁ p₂)
| _ := IH b Γ
end) ff Γ
/-- Reifies an atomic or otherwise unrecognized proposition. If it is defeq to a proposition we
have already allocated, we reuse it, otherwise we name it with a new index. -/
meta def reify_atom (atoms : ref (buffer expr)) (e : expr) : tactic prop := do
vec ← read_ref atoms,
o ← try_core $ vec.iterate failure (λ i e' r,
r <|> (is_def_eq e e' >> pure i.1)),
match o with
| none := write_ref atoms (vec.push_back e) $> prop.var vec.size
| some i := pure $ prop.var i
end
/-- Reify an `expr` into a `prop`, allocating anything non-propositional as an atom in the
`atoms` list. -/
meta def reify (atoms : ref (buffer expr)) : expr → tactic prop
| `(true) := pure prop.true
| `(false) := pure prop.false
| `(¬ %%a) := prop.not <$> reify a
| `(%%a ∧ %%b) := prop.and <$> reify a <*> reify b
| `(%%a ∨ %%b) := prop.or <$> reify a <*> reify b
| `(%%a ↔ %%b) := prop.iff <$> reify a <*> reify b
| `(xor %%a %%b) := prop.xor <$> reify a <*> reify b
| `(@eq Prop %%a %%b) := prop.eq <$> reify a <*> reify b
| `(@ne Prop %%a %%b) := prop.not <$> (prop.eq <$> reify a <*> reify b)
| `(implies %%a %%b) := prop.imp <$> reify a <*> reify b
| e@`(%%a → %%b) :=
if b.has_var then reify_atom atoms e else prop.imp <$> reify a <*> reify b
| e := reify_atom atoms e
/-- Once we have a proof object, we have to apply it to the goal. (Some of these cases are a bit
annoying because `applyc` gets the arguments wrong sometimes so we have to use `to_expr` instead.)
-/
meta def apply_proof : name_map expr → proof → tactic unit
| Γ (proof.hyp n) := do e ← Γ.find n, exact e
| Γ proof.triv := triv
| Γ (proof.exfalso' p) := do
t ← mk_mvar, to_expr ``(false.elim %%t) tt ff >>= exact,
gs ← get_goals, set_goals (t::gs), apply_proof Γ p
| Γ (proof.intro x p) := do e ← intro_core x, apply_proof (Γ.insert x e) p
| Γ (proof.and_left and_kind.and p) := do
t ← mk_mvar, to_expr ``(and.left %%t) tt ff >>= exact,
gs ← get_goals, set_goals (t::gs), apply_proof Γ p
| Γ (proof.and_left and_kind.iff p) := do
t ← mk_mvar, to_expr ``(iff.mp %%t) tt ff >>= exact,
gs ← get_goals, set_goals (t::gs), apply_proof Γ p
| Γ (proof.and_left and_kind.eq p) := do
t ← mk_mvar, to_expr ``(cast %%t) tt ff >>= exact,
gs ← get_goals, set_goals (t::gs), apply_proof Γ p
| Γ (proof.and_right and_kind.and p) := do
t ← mk_mvar, to_expr ``(and.right %%t) tt ff >>= exact,
gs ← get_goals, set_goals (t::gs), apply_proof Γ p
| Γ (proof.and_right and_kind.iff p) := do
t ← mk_mvar, to_expr ``(iff.mpr %%t) tt ff >>= exact,
gs ← get_goals, set_goals (t::gs), apply_proof Γ p
| Γ (proof.and_right and_kind.eq p) := do
t ← mk_mvar, to_expr ``(cast (eq.symm %%t)) tt ff >>= exact,
gs ← get_goals, set_goals (t::gs), apply_proof Γ p
| Γ (proof.and_intro and_kind.and p q) := do
t₁ ← mk_mvar, t₂ ← mk_mvar, to_expr ``(and.intro %%t₁ %%t₂) tt ff >>= exact,
gs ← get_goals, set_goals (t₁::t₂::gs), apply_proof Γ p >> apply_proof Γ q
| Γ (proof.and_intro and_kind.iff p q) := do
t₁ ← mk_mvar, t₂ ← mk_mvar, to_expr ``(iff.intro %%t₁ %%t₂) tt ff >>= exact,
gs ← get_goals, set_goals (t₁::t₂::gs), apply_proof Γ p >> apply_proof Γ q
| Γ (proof.and_intro and_kind.eq p q) := do
t₁ ← mk_mvar, t₂ ← mk_mvar, to_expr ``(propext (iff.intro %%t₁ %%t₂)) tt ff >>= exact,
gs ← get_goals, set_goals (t₁::t₂::gs), apply_proof Γ p >> apply_proof Γ q
| Γ (proof.curry ak p) := do
e ← intro_core `_, let n := e.local_uniq_name,
apply_proof (Γ.insert n e) (proof.curry₂ ak p (proof.hyp n))
| Γ (proof.curry₂ ak p q) := do
e ← intro_core `_, let n := e.local_uniq_name,
apply_proof (Γ.insert n e) (p.app (q.and_intro ak (proof.hyp n)))
| Γ (proof.app' p q) := do
A ← mk_meta_var (expr.sort level.zero),
B ← mk_meta_var (expr.sort level.zero),
g₁ ← mk_meta_var `((%%A : Prop) → (%%B : Prop)),
g₂ ← mk_meta_var A,
g :: gs ← get_goals,
unify (g₁ g₂) g,
set_goals (g₁::g₂::gs) >> apply_proof Γ p >> apply_proof Γ q
| Γ (proof.or_imp_left p) := do
e ← intro_core `_, let n := e.local_uniq_name,
apply_proof (Γ.insert n e) (p.app (proof.hyp n).or_inl)
| Γ (proof.or_imp_right p) := do
e ← intro_core `_, let n := e.local_uniq_name,
apply_proof (Γ.insert n e) (p.app (proof.hyp n).or_inr)
| Γ (proof.or_inl p) := do
t ← mk_mvar, to_expr ``(or.inl %%t) tt ff >>= exact,
gs ← get_goals, set_goals (t::gs), apply_proof Γ p
| Γ (proof.or_inr p) := do
t ← mk_mvar, to_expr ``(or.inr %%t) tt ff >>= exact,
gs ← get_goals, set_goals (t::gs), apply_proof Γ p
| Γ (proof.or_elim p x p₁ p₂) := do
t₁ ← mk_mvar, t₂ ← mk_mvar, t₃ ← mk_mvar, to_expr ``(or.elim %%t₁ %%t₂ %%t₃) tt ff >>= exact,
gs ← get_goals, set_goals (t₁::t₂::t₃::gs), apply_proof Γ p,
e ← intro_core x, apply_proof (Γ.insert x e) p₁,
e ← intro_core x, apply_proof (Γ.insert x e) p₂
| Γ (proof.imp_imp_simp x p) := do
e ← intro_core `_, let n := e.local_uniq_name,
apply_proof (Γ.insert n e) (p.app (proof.intro x (proof.hyp n)))
end itauto
namespace interactive
open itauto
/-- A decision procedure for intuitionistic propositional logic. Unlike `finish` and `tauto!` this
tactic never uses the law of excluded middle, and the proof search is tailored for this use case.
```lean
example (p : Prop) : ¬ (p ↔ ¬ p) := by itauto
```
-/
meta def itauto : tactic unit :=
using_new_ref mk_buffer $ λ atoms,
using_new_ref mk_name_map $ λ hs, do
t ← target,
t ← mcond (is_prop t) (reify atoms t) (tactic.exfalso $> prop.false),
hyps ← local_context,
Γ ← hyps.mfoldl
(λ (Γ : except (prop → proof) context) h, do
e ← infer_type h,
mcond (is_prop e)
(do A ← reify atoms e,
let n := h.local_uniq_name,
read_ref hs >>= λ Γ, write_ref hs (Γ.insert n h),
pure (Γ >>= λ Γ', Γ'.add A (proof.hyp n)))
(pure Γ))
(except.ok (native.rb_map.mk _ _)),
let o := state_t.run (match Γ with
| except.ok Γ := prove Γ t
| except.error p := pure (p t)
end) 0,
match o with
| none := fail "itauto failed"
| some (p, _) := do hs ← read_ref hs, apply_proof hs p
end
add_hint_tactic "itauto"
add_tactic_doc
{ name := "itauto",
category := doc_category.tactic,
decl_names := [`tactic.interactive.itauto],
tags := ["logic", "propositional logic", "intuitionistic logic", "decision procedure"] }
end interactive
end tactic
|
a8af17c8c1d3884ac346566945860f2f122f2a3c | 367134ba5a65885e863bdc4507601606690974c1 | /src/topology/algebra/multilinear.lean | 5cbf883a08747770e831322e8b6bb1ea01e195f5 | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 15,105 | lean | /-
Copyright (c) 2020 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import topology.algebra.module
import linear_algebra.multilinear
/-!
# Continuous multilinear maps
We define continuous multilinear maps as maps from `Π(i : ι), M₁ i` to `M₂` which are multilinear
and continuous, by extending the space of multilinear maps with a continuity assumption.
Here, `M₁ i` and `M₂` are modules over a ring `R`, and `ι` is an arbitrary type, and all these
spaces are also topological spaces.
## Main definitions
* `continuous_multilinear_map R M₁ M₂` is the space of continuous multilinear maps from
`Π(i : ι), M₁ i` to `M₂`. We show that it is an `R`-module.
## Implementation notes
We mostly follow the API of multilinear maps.
## Notation
We introduce the notation `M [×n]→L[R] M'` for the space of continuous `n`-multilinear maps from
`M^n` to `M'`. This is a particular case of the general notion (where we allow varying dependent
types as the arguments of our continuous multilinear maps), but arguably the most important one,
especially when defining iterated derivatives.
-/
open function fin set
open_locale big_operators
universes u v w w₁ w₁' w₂ w₃ w₄
variables {R : Type u} {ι : Type v} {n : ℕ} {M : fin n.succ → Type w} {M₁ : ι → Type w₁}
{M₁' : ι → Type w₁'} {M₂ : Type w₂} {M₃ : Type w₃} {M₄ : Type w₄} [decidable_eq ι]
/-- Continuous multilinear maps over the ring `R`, from `Πi, M₁ i` to `M₂` where `M₁ i` and `M₂`
are modules over `R` with a topological structure. In applications, there will be compatibility
conditions between the algebraic and the topological structures, but this is not needed for the
definition. -/
structure continuous_multilinear_map (R : Type u) {ι : Type v} (M₁ : ι → Type w₁) (M₂ : Type w₂)
[decidable_eq ι] [semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂]
[∀i, semimodule R (M₁ i)] [semimodule R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂]
extends multilinear_map R M₁ M₂ :=
(cont : continuous to_fun)
notation M `[×`:25 n `]→L[`:25 R `] ` M' := continuous_multilinear_map R (λ (i : fin n), M) M'
namespace continuous_multilinear_map
section semiring
variables [semiring R]
[Πi, add_comm_monoid (M i)] [Πi, add_comm_monoid (M₁ i)] [Πi, add_comm_monoid (M₁' i)]
[add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] [Π i, semimodule R (M i)]
[Π i, semimodule R (M₁ i)] [Π i, semimodule R (M₁' i)] [semimodule R M₂]
[semimodule R M₃] [semimodule R M₄]
[Π i, topological_space (M i)] [Π i, topological_space (M₁ i)] [Π i, topological_space (M₁' i)]
[topological_space M₂] [topological_space M₃] [topological_space M₄]
(f f' : continuous_multilinear_map R M₁ M₂)
instance : has_coe_to_fun (continuous_multilinear_map R M₁ M₂) :=
⟨_, λ f, f.to_multilinear_map.to_fun⟩
@[continuity] lemma coe_continuous : continuous (f : (Π i, M₁ i) → M₂) := f.cont
@[simp] lemma coe_coe : (f.to_multilinear_map : (Π i, M₁ i) → M₂) = f := rfl
theorem to_multilinear_map_inj :
function.injective (continuous_multilinear_map.to_multilinear_map :
continuous_multilinear_map R M₁ M₂ → multilinear_map R M₁ M₂)
| ⟨f, hf⟩ ⟨g, hg⟩ rfl := rfl
@[ext] theorem ext {f f' : continuous_multilinear_map R M₁ M₂} (H : ∀ x, f x = f' x) : f = f' :=
to_multilinear_map_inj $ multilinear_map.ext H
@[simp] lemma map_add (m : Πi, M₁ i) (i : ι) (x y : M₁ i) :
f (update m i (x + y)) = f (update m i x) + f (update m i y) :=
f.map_add' m i x y
@[simp] lemma map_smul (m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i) :
f (update m i (c • x)) = c • f (update m i x) :=
f.map_smul' m i c x
lemma map_coord_zero {m : Πi, M₁ i} (i : ι) (h : m i = 0) : f m = 0 :=
f.to_multilinear_map.map_coord_zero i h
@[simp] lemma map_zero [nonempty ι] : f 0 = 0 :=
f.to_multilinear_map.map_zero
instance : has_zero (continuous_multilinear_map R M₁ M₂) :=
⟨{ cont := continuous_const, ..(0 : multilinear_map R M₁ M₂) }⟩
instance : inhabited (continuous_multilinear_map R M₁ M₂) := ⟨0⟩
@[simp] lemma zero_apply (m : Πi, M₁ i) : (0 : continuous_multilinear_map R M₁ M₂) m = 0 := rfl
section has_continuous_add
variable [has_continuous_add M₂]
instance : has_add (continuous_multilinear_map R M₁ M₂) :=
⟨λ f f', ⟨f.to_multilinear_map + f'.to_multilinear_map, f.cont.add f'.cont⟩⟩
@[simp] lemma add_apply (m : Πi, M₁ i) : (f + f') m = f m + f' m := rfl
@[simp] lemma to_multilinear_map_add (f g : continuous_multilinear_map R M₁ M₂) :
(f + g).to_multilinear_map = f.to_multilinear_map + g.to_multilinear_map :=
rfl
instance add_comm_monoid : add_comm_monoid (continuous_multilinear_map R M₁ M₂) :=
to_multilinear_map_inj.add_comm_monoid _ rfl (λ _ _, rfl)
/-- Evaluation of a `continuous_multilinear_map` at a vector as an `add_monoid_hom`. -/
def apply_add_hom (m : Π i, M₁ i) : continuous_multilinear_map R M₁ M₂ →+ M₂ :=
⟨λ f, f m, rfl, λ _ _, rfl⟩
@[simp] lemma sum_apply {α : Type*} (f : α → continuous_multilinear_map R M₁ M₂)
(m : Πi, M₁ i) {s : finset α} : (∑ a in s, f a) m = ∑ a in s, f a m :=
(apply_add_hom m).map_sum f s
end has_continuous_add
/-- If `f` is a continuous multilinear map, then `f.to_continuous_linear_map m i` is the continuous
linear map obtained by fixing all coordinates but `i` equal to those of `m`, and varying the
`i`-th coordinate. -/
def to_continuous_linear_map (m : Πi, M₁ i) (i : ι) : M₁ i →L[R] M₂ :=
{ cont := f.cont.comp continuous_update, ..(f.to_multilinear_map.to_linear_map m i) }
/-- The cartesian product of two continuous multilinear maps, as a continuous multilinear map. -/
def prod (f : continuous_multilinear_map R M₁ M₂) (g : continuous_multilinear_map R M₁ M₃) :
continuous_multilinear_map R M₁ (M₂ × M₃) :=
{ cont := f.cont.prod_mk g.cont,
.. f.to_multilinear_map.prod g.to_multilinear_map }
@[simp] lemma prod_apply
(f : continuous_multilinear_map R M₁ M₂) (g : continuous_multilinear_map R M₁ M₃) (m : Πi, M₁ i) :
(f.prod g) m = (f m, g m) := rfl
/-- If `g` is continuous multilinear and `f` is a collection of continuous linear maps,
then `g (f₁ m₁, ..., fₙ mₙ)` is again a continuous multilinear map, that we call
`g.comp_continuous_linear_map f`. -/
def comp_continuous_linear_map
(g : continuous_multilinear_map R M₁' M₄) (f : Π i : ι, M₁ i →L[R] M₁' i) :
continuous_multilinear_map R M₁ M₄ :=
{ cont := g.cont.comp $ continuous_pi $ λj, (f j).cont.comp $ continuous_apply _,
.. g.to_multilinear_map.comp_linear_map (λ i, (f i).to_linear_map) }
@[simp] lemma comp_continuous_linear_map_apply (g : continuous_multilinear_map R M₁' M₄)
(f : Π i : ι, M₁ i →L[R] M₁' i) (m : Π i, M₁ i) :
g.comp_continuous_linear_map f m = g (λ i, f i $ m i) :=
rfl
/-- In the specific case of continuous multilinear maps on spaces indexed by `fin (n+1)`, where one
can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the
additivity of a multilinear map along the first variable. -/
lemma cons_add (f : continuous_multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (x y : M 0) :
f (cons (x+y) m) = f (cons x m) + f (cons y m) :=
f.to_multilinear_map.cons_add m x y
/-- In the specific case of continuous multilinear maps on spaces indexed by `fin (n+1)`, where one
can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the
multiplicativity of a multilinear map along the first variable. -/
lemma cons_smul
(f : continuous_multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (c : R) (x : M 0) :
f (cons (c • x) m) = c • f (cons x m) :=
f.to_multilinear_map.cons_smul m c x
lemma map_piecewise_add (m m' : Πi, M₁ i) (t : finset ι) :
f (t.piecewise (m + m') m') = ∑ s in t.powerset, f (s.piecewise m m') :=
f.to_multilinear_map.map_piecewise_add _ _ _
/-- Additivity of a continuous multilinear map along all coordinates at the same time,
writing `f (m + m')` as the sum of `f (s.piecewise m m')` over all sets `s`. -/
lemma map_add_univ [fintype ι] (m m' : Πi, M₁ i) :
f (m + m') = ∑ s : finset ι, f (s.piecewise m m') :=
f.to_multilinear_map.map_add_univ _ _
section apply_sum
open fintype finset
variables {α : ι → Type*} [fintype ι] (g : Π i, α i → M₁ i) (A : Π i, finset (α i))
/-- If `f` is continuous multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the
sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ...,
`r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each
coordinate. -/
lemma map_sum_finset :
f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) :=
f.to_multilinear_map.map_sum_finset _ _
/-- If `f` is continuous multilinear, then `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` is the sum of
`f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions `r`. This follows from
multilinearity by expanding successively with respect to each coordinate. -/
lemma map_sum [∀ i, fintype (α i)] :
f (λ i, ∑ j, g i j) = ∑ r : Π i, α i, f (λ i, g i (r i)) :=
f.to_multilinear_map.map_sum _
end apply_sum
section restrict_scalar
variables (R) {A : Type*} [semiring A] [has_scalar R A] [Π (i : ι), semimodule A (M₁ i)]
[semimodule A M₂] [∀ i, is_scalar_tower R A (M₁ i)] [is_scalar_tower R A M₂]
/-- Reinterpret an `A`-multilinear map as an `R`-multilinear map, if `A` is an algebra over `R`
and their actions on all involved semimodules agree with the action of `R` on `A`. -/
def restrict_scalars (f : continuous_multilinear_map A M₁ M₂) :
continuous_multilinear_map R M₁ M₂ :=
{ to_multilinear_map := f.to_multilinear_map.restrict_scalars R,
cont := f.cont }
@[simp] lemma coe_restrict_scalars (f : continuous_multilinear_map A M₁ M₂) :
⇑(f.restrict_scalars R) = f := rfl
end restrict_scalar
end semiring
section ring
variables [ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂]
[∀i, semimodule R (M₁ i)] [semimodule R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂]
(f f' : continuous_multilinear_map R M₁ M₂)
@[simp] lemma map_sub (m : Πi, M₁ i) (i : ι) (x y : M₁ i) :
f (update m i (x - y)) = f (update m i x) - f (update m i y) :=
f.to_multilinear_map.map_sub _ _ _ _
section topological_add_group
variable [topological_add_group M₂]
instance : has_neg (continuous_multilinear_map R M₁ M₂) :=
⟨λ f, {cont := f.cont.neg, ..(-f.to_multilinear_map)}⟩
@[simp] lemma neg_apply (m : Πi, M₁ i) : (-f) m = - (f m) := rfl
instance : has_sub (continuous_multilinear_map R M₁ M₂) :=
⟨λ f g, { cont := f.cont.sub g.cont, .. (f.to_multilinear_map - g.to_multilinear_map) }⟩
@[simp] lemma sub_apply (m : Πi, M₁ i) : (f - f') m = f m - f' m := rfl
instance : add_comm_group (continuous_multilinear_map R M₁ M₂) :=
to_multilinear_map_inj.add_comm_group_sub _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl)
end topological_add_group
end ring
section comm_semiring
variables [comm_semiring R]
[∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂]
[∀i, semimodule R (M₁ i)] [semimodule R M₂]
[∀i, topological_space (M₁ i)] [topological_space M₂]
(f : continuous_multilinear_map R M₁ M₂)
lemma map_piecewise_smul (c : ι → R) (m : Πi, M₁ i) (s : finset ι) :
f (s.piecewise (λ i, c i • m i) m) = (∏ i in s, c i) • f m :=
f.to_multilinear_map.map_piecewise_smul _ _ _
/-- Multiplicativity of a continuous multilinear map along all coordinates at the same time,
writing `f (λ i, c i • m i)` as `(∏ i, c i) • f m`. -/
lemma map_smul_univ [fintype ι] (c : ι → R) (m : Πi, M₁ i) :
f (λ i, c i • m i) = (∏ i, c i) • f m :=
f.to_multilinear_map.map_smul_univ _ _
variables {R' A : Type*} [comm_semiring R'] [semiring A] [algebra R' A]
[Π i, semimodule A (M₁ i)] [semimodule R' M₂] [semimodule A M₂] [is_scalar_tower R' A M₂]
[topological_space R'] [topological_semimodule R' M₂]
instance : has_scalar R' (continuous_multilinear_map A M₁ M₂) :=
⟨λ c f, { cont := continuous_const.smul f.cont, .. c • f.to_multilinear_map }⟩
@[simp] lemma smul_apply (f : continuous_multilinear_map A M₁ M₂) (c : R') (m : Πi, M₁ i) :
(c • f) m = c • f m := rfl
@[simp] lemma to_multilinear_map_smul (c : R') (f : continuous_multilinear_map A M₁ M₂) :
(c • f).to_multilinear_map = c • f.to_multilinear_map :=
rfl
instance {R''} [comm_semiring R''] [has_scalar R' R''] [algebra R'' A]
[semimodule R'' M₂] [is_scalar_tower R'' A M₂] [is_scalar_tower R' R'' M₂]
[topological_space R''] [topological_semimodule R'' M₂]:
is_scalar_tower R' R'' (continuous_multilinear_map A M₁ M₂) :=
⟨λ c₁ c₂ f, ext $ λ x, smul_assoc _ _ _⟩
variable [has_continuous_add M₂]
/-- The space of continuous multilinear maps over an algebra over `R` is a module over `R`, for the
pointwise addition and scalar multiplication. -/
instance : semimodule R' (continuous_multilinear_map A M₁ M₂) :=
{ one_smul := λ f, ext $ λ x, one_smul _ _,
mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul _ _ _,
smul_zero := λ r, ext $ λ x, smul_zero _,
smul_add := λ r f₁ f₂, ext $ λ x, smul_add _ _ _,
add_smul := λ r₁ r₂ f, ext $ λ x, add_smul _ _ _,
zero_smul := λ f, ext $ λ x, zero_smul _ _ }
/-- Linear map version of the map `to_multilinear_map` associating to a continuous multilinear map
the corresponding multilinear map. -/
@[simps] def to_multilinear_map_linear :
(continuous_multilinear_map A M₁ M₂) →ₗ[R'] (multilinear_map A M₁ M₂) :=
{ to_fun := λ f, f.to_multilinear_map,
map_add' := λ f g, rfl,
map_smul' := λ c f, rfl }
end comm_semiring
end continuous_multilinear_map
namespace continuous_linear_map
variables [ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [add_comm_group M₃]
[∀i, module R (M₁ i)] [module R M₂] [module R M₃]
[∀i, topological_space (M₁ i)] [topological_space M₂] [topological_space M₃]
/-- Composing a continuous multilinear map with a continuous linear map gives again a
continuous multilinear map. -/
def comp_continuous_multilinear_map (g : M₂ →L[R] M₃) (f : continuous_multilinear_map R M₁ M₂) :
continuous_multilinear_map R M₁ M₃ :=
{ cont := g.cont.comp f.cont,
.. g.to_linear_map.comp_multilinear_map f.to_multilinear_map }
@[simp] lemma comp_continuous_multilinear_map_coe (g : M₂ →L[R] M₃)
(f : continuous_multilinear_map R M₁ M₂) :
((g.comp_continuous_multilinear_map f) : (Πi, M₁ i) → M₃) =
(g : M₂ → M₃) ∘ (f : (Πi, M₁ i) → M₂) :=
by { ext m, refl }
end continuous_linear_map
|
80dedfa1823543053dafe59987ed7aa340a43b83 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/data/pnat/basic.lean | 6badec1ee2c170bbbea4abb635f8dea4ded9aaf3 | [
"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 | 15,043 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Neil Strickland
-/
import algebra.group_power.basic
/-!
# The positive natural numbers
This file defines the type `ℕ+` or `pnat`, the subtype of natural numbers that are positive.
-/
/-- `ℕ+` is the type of positive natural numbers. It is defined as a subtype,
and the VM representation of `ℕ+` is the same as `ℕ` because the proof
is not stored. -/
def pnat := {n : ℕ // 0 < n}
notation `ℕ+` := pnat
instance coe_pnat_nat : has_coe ℕ+ ℕ := ⟨subtype.val⟩
instance : has_repr ℕ+ := ⟨λ n, repr n.1⟩
/-- Predecessor of a `ℕ+`, as a `ℕ`. -/
def pnat.nat_pred (i : ℕ+) : ℕ := i - 1
namespace nat
/-- Convert a natural number to a positive natural number. The
positivity assumption is inferred by `dec_trivial`. -/
def to_pnat (n : ℕ) (h : 0 < n . tactic.exact_dec_trivial) : ℕ+ := ⟨n, h⟩
/-- Write a successor as an element of `ℕ+`. -/
def succ_pnat (n : ℕ) : ℕ+ := ⟨succ n, succ_pos n⟩
@[simp] theorem succ_pnat_coe (n : ℕ) : (succ_pnat n : ℕ) = succ n := rfl
theorem succ_pnat_inj {n m : ℕ} : succ_pnat n = succ_pnat m → n = m :=
λ h, by { let h' := congr_arg (coe : ℕ+ → ℕ) h, exact nat.succ.inj h' }
/-- Convert a natural number to a pnat. `n+1` is mapped to itself,
and `0` becomes `1`. -/
def to_pnat' (n : ℕ) : ℕ+ := succ_pnat (pred n)
@[simp] theorem to_pnat'_coe : ∀ (n : ℕ),
((to_pnat' n) : ℕ) = ite (0 < n) n 1
| 0 := rfl
| (m + 1) := by {rw [if_pos (succ_pos m)], refl}
end nat
namespace pnat
open nat
/-- We now define a long list of structures on ℕ+ induced by
similar structures on ℕ. Most of these behave in a completely
obvious way, but there are a few things to be said about
subtraction, division and powers.
-/
instance : decidable_eq ℕ+ := λ (a b : ℕ+), by apply_instance
instance : linear_order ℕ+ :=
subtype.linear_order _
@[simp] lemma mk_le_mk (n k : ℕ) (hn : 0 < n) (hk : 0 < k) :
(⟨n, hn⟩ : ℕ+) ≤ ⟨k, hk⟩ ↔ n ≤ k := iff.rfl
@[simp] lemma mk_lt_mk (n k : ℕ) (hn : 0 < n) (hk : 0 < k) :
(⟨n, hn⟩ : ℕ+) < ⟨k, hk⟩ ↔ n < k := iff.rfl
@[simp, norm_cast] lemma coe_le_coe (n k : ℕ+) : (n : ℕ) ≤ k ↔ n ≤ k := iff.rfl
@[simp, norm_cast] lemma coe_lt_coe (n k : ℕ+) : (n : ℕ) < k ↔ n < k := iff.rfl
@[simp] theorem pos (n : ℕ+) : 0 < (n : ℕ) := n.2
theorem eq {m n : ℕ+} : (m : ℕ) = n → m = n := subtype.eq
@[simp] lemma coe_inj {m n : ℕ+} : (m : ℕ) = n ↔ m = n := set_coe.ext_iff
lemma coe_injective : function.injective (coe : ℕ+ → ℕ) := subtype.coe_injective
@[simp] theorem mk_coe (n h) : ((⟨n, h⟩ : ℕ+) : ℕ) = n := rfl
instance : has_add ℕ+ := ⟨λ a b, ⟨(a + b : ℕ), add_pos a.pos b.pos⟩⟩
instance : add_comm_semigroup ℕ+ := coe_injective.add_comm_semigroup coe (λ _ _, rfl)
@[simp] theorem add_coe (m n : ℕ+) : ((m + n : ℕ+) : ℕ) = m + n := rfl
/-- `pnat.coe` promoted to an `add_hom`, that is, a morphism which preserves addition. -/
def coe_add_hom : add_hom ℕ+ ℕ :=
{ to_fun := coe,
map_add' := add_coe }
instance : add_left_cancel_semigroup ℕ+ :=
coe_injective.add_left_cancel_semigroup coe (λ _ _, rfl)
instance : add_right_cancel_semigroup ℕ+ :=
coe_injective.add_right_cancel_semigroup coe (λ _ _, rfl)
@[simp] theorem ne_zero (n : ℕ+) : (n : ℕ) ≠ 0 := n.2.ne'
theorem to_pnat'_coe {n : ℕ} : 0 < n → (n.to_pnat' : ℕ) = n := succ_pred_eq_of_pos
@[simp] theorem coe_to_pnat' (n : ℕ+) : (n : ℕ).to_pnat' = n := eq (to_pnat'_coe n.pos)
instance : has_mul ℕ+ := ⟨λ m n, ⟨m.1 * n.1, mul_pos m.2 n.2⟩⟩
instance : has_one ℕ+ := ⟨succ_pnat 0⟩
instance : comm_monoid ℕ+ := coe_injective.comm_monoid coe rfl (λ _ _, rfl)
theorem lt_add_one_iff : ∀ {a b : ℕ+}, a < b + 1 ↔ a ≤ b :=
λ a b, nat.lt_add_one_iff
theorem add_one_le_iff : ∀ {a b : ℕ+}, a + 1 ≤ b ↔ a < b :=
λ a b, nat.add_one_le_iff
@[simp] lemma one_le (n : ℕ+) : (1 : ℕ+) ≤ n := n.2
instance : order_bot ℕ+ :=
{ bot := 1,
bot_le := λ a, a.property }
@[simp] lemma bot_eq_one : (⊥ : ℕ+) = 1 := rfl
instance : inhabited ℕ+ := ⟨1⟩
-- Some lemmas that rewrite `pnat.mk n h`, for `n` an explicit numeral, into explicit numerals.
@[simp] lemma mk_one {h} : (⟨1, h⟩ : ℕ+) = (1 : ℕ+) := rfl
@[simp] lemma mk_bit0 (n) {h} : (⟨bit0 n, h⟩ : ℕ+) = (bit0 ⟨n, pos_of_bit0_pos h⟩ : ℕ+) := rfl
@[simp] lemma mk_bit1 (n) {h} {k} : (⟨bit1 n, h⟩ : ℕ+) = (bit1 ⟨n, k⟩ : ℕ+) := rfl
-- Some lemmas that rewrite inequalities between explicit numerals in `ℕ+`
-- into the corresponding inequalities in `ℕ`.
-- TODO: perhaps this should not be attempted by `simp`,
-- and instead we should expect `norm_num` to take care of these directly?
-- TODO: these lemmas are perhaps incomplete:
-- * 1 is not represented as a bit0 or bit1
-- * strict inequalities?
@[simp] lemma bit0_le_bit0 (n m : ℕ+) : (bit0 n) ≤ (bit0 m) ↔ (bit0 (n : ℕ)) ≤ (bit0 (m : ℕ)) :=
iff.rfl
@[simp] lemma bit0_le_bit1 (n m : ℕ+) : (bit0 n) ≤ (bit1 m) ↔ (bit0 (n : ℕ)) ≤ (bit1 (m : ℕ)) :=
iff.rfl
@[simp] lemma bit1_le_bit0 (n m : ℕ+) : (bit1 n) ≤ (bit0 m) ↔ (bit1 (n : ℕ)) ≤ (bit0 (m : ℕ)) :=
iff.rfl
@[simp] lemma bit1_le_bit1 (n m : ℕ+) : (bit1 n) ≤ (bit1 m) ↔ (bit1 (n : ℕ)) ≤ (bit1 (m : ℕ)) :=
iff.rfl
@[simp] theorem one_coe : ((1 : ℕ+) : ℕ) = 1 := rfl
@[simp] theorem mul_coe (m n : ℕ+) : ((m * n : ℕ+) : ℕ) = m * n := rfl
/-- `pnat.coe` promoted to a `monoid_hom`. -/
def coe_monoid_hom : ℕ+ →* ℕ :=
{ to_fun := coe,
map_one' := one_coe,
map_mul' := mul_coe }
@[simp] lemma coe_coe_monoid_hom : (coe_monoid_hom : ℕ+ → ℕ) = coe := rfl
@[simp]
lemma coe_eq_one_iff {m : ℕ+} :
(m : ℕ) = 1 ↔ m = 1 := by { split; intro h; try { apply pnat.eq}; rw h; simp }
@[simp] lemma coe_bit0 (a : ℕ+) : ((bit0 a : ℕ+) : ℕ) = bit0 (a : ℕ) := rfl
@[simp] lemma coe_bit1 (a : ℕ+) : ((bit1 a : ℕ+) : ℕ) = bit1 (a : ℕ) := rfl
@[simp] theorem pow_coe (m : ℕ+) (n : ℕ) : ((m ^ n : ℕ+) : ℕ) = (m : ℕ) ^ n :=
by induction n with n ih;
[refl, rw [pow_succ', pow_succ, mul_coe, mul_comm, ih]]
instance : ordered_cancel_comm_monoid ℕ+ :=
{ mul_le_mul_left := by { intros, apply nat.mul_le_mul_left, assumption },
le_of_mul_le_mul_left := by { intros a b c h, apply nat.le_of_mul_le_mul_left h a.property, },
mul_left_cancel := λ a b c h, by {
replace h := congr_arg (coe : ℕ+ → ℕ) h,
exact eq ((nat.mul_right_inj a.pos).mp h)},
.. pnat.comm_monoid,
.. pnat.linear_order }
instance : distrib ℕ+ := coe_injective.distrib coe (λ _ _, rfl) (λ _ _, rfl)
/-- Subtraction a - b is defined in the obvious way when
a > b, and by a - b = 1 if a ≤ b.
-/
instance : has_sub ℕ+ := ⟨λ a b, to_pnat' (a - b : ℕ)⟩
theorem sub_coe (a b : ℕ+) : ((a - b : ℕ+) : ℕ) = ite (b < a) (a - b : ℕ) 1 :=
begin
change ((to_pnat' ((a : ℕ) - (b : ℕ)) : ℕ)) =
ite ((a : ℕ) > (b : ℕ)) ((a : ℕ) - (b : ℕ)) 1,
split_ifs with h,
{ exact to_pnat'_coe (tsub_pos_of_lt h) },
{ rw [tsub_eq_zero_iff_le.mpr (le_of_not_gt h)], refl }
end
theorem add_sub_of_lt {a b : ℕ+} : a < b → a + (b - a) = b :=
λ h, eq $ by { rw [add_coe, sub_coe, if_pos h],
exact add_tsub_cancel_of_le h.le }
instance : has_well_founded ℕ+ := ⟨(<), measure_wf coe⟩
/-- Strong induction on `ℕ+`. -/
def strong_induction_on {p : ℕ+ → Sort*} : ∀ (n : ℕ+) (h : ∀ k, (∀ m, m < k → p m) → p k), p n
| n := λ IH, IH _ (λ a h, strong_induction_on a IH)
using_well_founded { dec_tac := `[assumption] }
/-- If `n : ℕ+` is different from `1`, then it is the successor of some `k : ℕ+`. -/
lemma exists_eq_succ_of_ne_one : ∀ {n : ℕ+} (h1 : n ≠ 1), ∃ (k : ℕ+), n = k + 1
| ⟨1, _⟩ h1 := false.elim $ h1 rfl
| ⟨n+2, _⟩ _ := ⟨⟨n+1, by simp⟩, rfl⟩
/-- Strong induction on `ℕ+`, with `n = 1` treated separately. -/
def case_strong_induction_on {p : ℕ+ → Sort*} (a : ℕ+) (hz : p 1)
(hi : ∀ n, (∀ m, m ≤ n → p m) → p (n + 1)) : p a :=
begin
apply strong_induction_on a,
rintro ⟨k, kprop⟩ hk,
cases k with k,
{ exact (lt_irrefl 0 kprop).elim },
cases k with k,
{ exact hz },
exact hi ⟨k.succ, nat.succ_pos _⟩ (λ m hm, hk _ (lt_succ_iff.2 hm)),
end
/-- An induction principle for `ℕ+`: it takes values in `Sort*`, so it applies also to Types,
not only to `Prop`. -/
@[elab_as_eliminator]
def rec_on (n : ℕ+) {p : ℕ+ → Sort*} (p1 : p 1) (hp : ∀ n, p n → p (n + 1)) : p n :=
begin
rcases n with ⟨n, h⟩,
induction n with n IH,
{ exact absurd h dec_trivial },
{ cases n with n,
{ exact p1 },
{ exact hp _ (IH n.succ_pos) } }
end
@[simp] theorem rec_on_one {p} (p1 hp) : @pnat.rec_on 1 p p1 hp = p1 := rfl
@[simp] theorem rec_on_succ (n : ℕ+) {p : ℕ+ → Sort*} (p1 hp) :
@pnat.rec_on (n + 1) p p1 hp = hp n (@pnat.rec_on n p p1 hp) :=
by { cases n with n h, cases n; [exact absurd h dec_trivial, refl] }
/-- We define `m % k` and `m / k` in the same way as for `ℕ`
except that when `m = n * k` we take `m % k = k` and
`m / k = n - 1`. This ensures that `m % k` is always positive
and `m = (m % k) + k * (m / k)` in all cases. Later we
define a function `div_exact` which gives the usual `m / k`
in the case where `k` divides `m`.
-/
def mod_div_aux : ℕ+ → ℕ → ℕ → ℕ+ × ℕ
| k 0 q := ⟨k, q.pred⟩
| k (r + 1) q := ⟨⟨r + 1, nat.succ_pos r⟩, q⟩
lemma mod_div_aux_spec : ∀ (k : ℕ+) (r q : ℕ) (h : ¬ (r = 0 ∧ q = 0)),
(((mod_div_aux k r q).1 : ℕ) + k * (mod_div_aux k r q).2 = (r + k * q))
| k 0 0 h := (h ⟨rfl, rfl⟩).elim
| k 0 (q + 1) h := by {
change (k : ℕ) + (k : ℕ) * (q + 1).pred = 0 + (k : ℕ) * (q + 1),
rw [nat.pred_succ, nat.mul_succ, zero_add, add_comm]}
| k (r + 1) q h := rfl
/-- `mod_div m k = (m % k, m / k)`.
We define `m % k` and `m / k` in the same way as for `ℕ`
except that when `m = n * k` we take `m % k = k` and
`m / k = n - 1`. This ensures that `m % k` is always positive
and `m = (m % k) + k * (m / k)` in all cases. Later we
define a function `div_exact` which gives the usual `m / k`
in the case where `k` divides `m`.
-/
def mod_div (m k : ℕ+) : ℕ+ × ℕ := mod_div_aux k ((m : ℕ) % (k : ℕ)) ((m : ℕ) / (k : ℕ))
/-- We define `m % k` in the same way as for `ℕ`
except that when `m = n * k` we take `m % k = k` This ensures that `m % k` is always positive.
-/
def mod (m k : ℕ+) : ℕ+ := (mod_div m k).1
/-- We define `m / k` in the same way as for `ℕ` except that when `m = n * k` we take
`m / k = n - 1`. This ensures that `m = (m % k) + k * (m / k)` in all cases. Later we
define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`.
-/
def div (m k : ℕ+) : ℕ := (mod_div m k).2
theorem mod_add_div (m k : ℕ+) : ((mod m k) + k * (div m k) : ℕ) = m :=
begin
let h₀ := nat.mod_add_div (m : ℕ) (k : ℕ),
have : ¬ ((m : ℕ) % (k : ℕ) = 0 ∧ (m : ℕ) / (k : ℕ) = 0),
by { rintro ⟨hr, hq⟩, rw [hr, hq, mul_zero, zero_add] at h₀,
exact (m.ne_zero h₀.symm).elim },
have := mod_div_aux_spec k ((m : ℕ) % (k : ℕ)) ((m : ℕ) / (k : ℕ)) this,
exact (this.trans h₀),
end
theorem div_add_mod (m k : ℕ+) : (k * (div m k) + mod m k : ℕ) = m :=
(add_comm _ _).trans (mod_add_div _ _)
lemma mod_add_div' (m k : ℕ+) : ((mod m k) + (div m k) * k : ℕ) = m :=
by { rw mul_comm, exact mod_add_div _ _ }
lemma div_add_mod' (m k : ℕ+) : ((div m k) * k + mod m k : ℕ) = m :=
by { rw mul_comm, exact div_add_mod _ _ }
theorem mod_coe (m k : ℕ+) :
((mod m k) : ℕ) = ite ((m : ℕ) % (k : ℕ) = 0) (k : ℕ) ((m : ℕ) % (k : ℕ)) :=
begin
dsimp [mod, mod_div],
cases (m : ℕ) % (k : ℕ),
{ rw [if_pos rfl], refl },
{ rw [if_neg n.succ_ne_zero], refl }
end
theorem div_coe (m k : ℕ+) :
((div m k) : ℕ) = ite ((m : ℕ) % (k : ℕ) = 0) ((m : ℕ) / (k : ℕ)).pred ((m : ℕ) / (k : ℕ)) :=
begin
dsimp [div, mod_div],
cases (m : ℕ) % (k : ℕ),
{ rw [if_pos rfl], refl },
{ rw [if_neg n.succ_ne_zero], refl }
end
theorem mod_le (m k : ℕ+) : mod m k ≤ m ∧ mod m k ≤ k :=
begin
change ((mod m k) : ℕ) ≤ (m : ℕ) ∧ ((mod m k) : ℕ) ≤ (k : ℕ),
rw [mod_coe], split_ifs,
{ have hm : (m : ℕ) > 0 := m.pos,
rw [← nat.mod_add_div (m : ℕ) (k : ℕ), h, zero_add] at hm ⊢,
by_cases h' : ((m : ℕ) / (k : ℕ)) = 0,
{ rw [h', mul_zero] at hm, exact (lt_irrefl _ hm).elim},
{ let h' := nat.mul_le_mul_left (k : ℕ)
(nat.succ_le_of_lt (nat.pos_of_ne_zero h')),
rw [mul_one] at h', exact ⟨h', le_refl (k : ℕ)⟩ } },
{ exact ⟨nat.mod_le (m : ℕ) (k : ℕ), (nat.mod_lt (m : ℕ) k.pos).le⟩ }
end
theorem dvd_iff {k m : ℕ+} : k ∣ m ↔ (k : ℕ) ∣ (m : ℕ) :=
begin
split; intro h, rcases h with ⟨_, rfl⟩, apply dvd_mul_right,
rcases h with ⟨a, h⟩, cases a, { contrapose h, apply ne_zero, },
use a.succ, apply nat.succ_pos, rw [← coe_inj, h, mul_coe, mk_coe],
end
theorem dvd_iff' {k m : ℕ+} : k ∣ m ↔ mod m k = k :=
begin
rw dvd_iff,
rw [nat.dvd_iff_mod_eq_zero], split,
{ intro h, apply eq, rw [mod_coe, if_pos h] },
{ intro h, by_cases h' : (m : ℕ) % (k : ℕ) = 0,
{ exact h'},
{ replace h : ((mod m k) : ℕ) = (k : ℕ) := congr_arg _ h,
rw [mod_coe, if_neg h'] at h,
exact ((nat.mod_lt (m : ℕ) k.pos).ne h).elim } }
end
lemma le_of_dvd {m n : ℕ+} : m ∣ n → m ≤ n :=
by { rw dvd_iff', intro h, rw ← h, apply (mod_le n m).left }
/-- If `h : k | m`, then `k * (div_exact m k) = m`. Note that this is not equal to `m / k`. -/
def div_exact (m k : ℕ+) : ℕ+ :=
⟨(div m k).succ, nat.succ_pos _⟩
theorem mul_div_exact {m k : ℕ+} (h : k ∣ m) : k * (div_exact m k) = m :=
begin
apply eq, rw [mul_coe],
change (k : ℕ) * (div m k).succ = m,
rw [← div_add_mod m k, dvd_iff'.mp h, nat.mul_succ]
end
theorem dvd_antisymm {m n : ℕ+} : m ∣ n → n ∣ m → m = n :=
λ hmn hnm, (le_of_dvd hmn).antisymm (le_of_dvd hnm)
theorem dvd_one_iff (n : ℕ+) : n ∣ 1 ↔ n = 1 :=
⟨λ h, dvd_antisymm h (one_dvd n), λ h, h.symm ▸ (dvd_refl 1)⟩
lemma pos_of_div_pos {n : ℕ+} {a : ℕ} (h : a ∣ n) : 0 < a :=
begin
apply pos_iff_ne_zero.2,
intro hzero,
rw hzero at h,
exact pnat.ne_zero n (eq_zero_of_zero_dvd h)
end
end pnat
section can_lift
instance nat.can_lift_pnat : can_lift ℕ ℕ+ :=
⟨coe, λ n, 0 < n, λ n hn, ⟨nat.to_pnat' n, pnat.to_pnat'_coe hn⟩⟩
instance int.can_lift_pnat : can_lift ℤ ℕ+ :=
⟨coe, λ n, 0 < n, λ n hn, ⟨nat.to_pnat' (int.nat_abs n),
by rw [coe_coe, nat.to_pnat'_coe, if_pos (int.nat_abs_pos_of_ne_zero hn.ne'),
int.nat_abs_of_nonneg hn.le]⟩⟩
end can_lift
|
95b178e9161af124a434fb9fea96a1646475f939 | aa101d73b1a3173c7ec56de02b96baa8ca64c42e | /src/my_exercises/08_limits_negation.lean | d9c2da215d4d5d8f9cedae6477af047d34dab2d7 | [
"Apache-2.0"
] | permissive | gihanmarasingha/tutorials | b554d4d53866c493c4341dc13e914b01444e95a6 | 56617114ef0f9f7b808476faffd11e22e4380918 | refs/heads/master | 1,671,141,758,153 | 1,599,173,318,000 | 1,599,173,318,000 | 282,405,870 | 0 | 0 | Apache-2.0 | 1,595,666,751,000 | 1,595,666,750,000 | null | UTF-8 | Lean | false | false | 5,223 | lean | import tuto_lib
section
/-
The first part of this file makes sure you can negate quantified statements
in your head without the help of `push_neg`.
You need to complete the statement and then use the `check_me` tactic
to check your answer. This tactic exists only for those exercises,
it mostly calls `push_neg` and then cleans up a bit.
def seq_limit (u : ℕ → ℝ) (l : ℝ) : Prop :=
∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| ≤ ε
-/
-- In this section, u denotes a sequence of real numbers
-- f is a function from ℝ to ℝ
-- x₀ and l are real numbers
variables (u : ℕ → ℝ) (f : ℝ → ℝ) (x₀ l : ℝ)
/- Negation of "u tends to l" -/
-- 0062
example : ¬ (∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| ≤ ε) ↔
∃ ε > 0, ∀ N, ∃ n ≥ N, |u n - l| > ε
:=
begin
check_me,
end
/- Negation of "f is continuous at x₀" -/
-- 0063
example : ¬ (∀ ε > 0, ∃ δ > 0, ∀ x, |x - x₀| ≤ δ → |f x - f x₀| ≤ ε) ↔
∃ ε > 0, ∀ δ > 0, ∃ x, |x - x₀| ≤ δ ∧ |f x - f x₀| > ε
:=
begin
check_me,
end
/-
In the next exercise, we need to keep in mind that
`∀ x x', ...` is the abbreviation of
`∀ x, ∀ x', ... `.
Also, `∃ x x', ...` is the abbreviation of `∃ x, ∃ x', ...`.
-/
/- Negation of "f is uniformly continuous on ℝ" -/
-- 0064
example : ¬ (∀ ε > 0, ∃ δ > 0, ∀ x x', |x' - x| ≤ δ → |f x' - f x| ≤ ε) ↔
∃ ε > 0, ∀ δ > 0, ∃ x x', |x' - x| ≤ δ ∧ |f x' - f x| > ε
:=
begin
check_me,
end
/- Negation of "f is sequentially continuous at x₀" -/
-- 0065
example : ¬ (∀ u : ℕ → ℝ, (∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - x₀| ≤ ε) → (∀ ε > 0, ∃ N, ∀ n ≥ N, |(f ∘ u) n - f x₀| ≤ ε)) ↔
∃ u : ℕ → ℝ, (∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - x₀| ≤ ε) ∧
(∃ ε > 0, ∀ N, ∃ n ≥ N, |(f ∘ u) n - f x₀| > ε)
:=
begin
check_me,
end
end -- end of section
/-
We now turn to elementary applications of negations to limits of sequences.
Remember that `linarith` can find easy numerical contradictions.
Also recall the following lemmas:
abs_le (x y : ℝ) : |x| ≤ y ↔ -y ≤ x ∧ x ≤ y
ge_max_iff (p q r) : r ≥ max p q ↔ r ≥ p ∧ r ≥ q
le_max_left p q : p ≤ max p q
le_max_right p q : q ≤ max p q
/-- The sequence `u` tends to `+∞`. -/
def tendsto_infinity (u : ℕ → ℝ) := ∀ A, ∃ N, ∀ n ≥ N, u n ≥ A
-/
-- 0066
/- My comment: the model solutions do not use push_neg or proof by contradiction-/
example {u : ℕ → ℝ} : tendsto_infinity u → ∀ l, ¬ seq_limit u l :=
begin
intros htinf l,
unfold seq_limit,
push_neg,
cases htinf (2+l) with M hn,
use [1, (by linarith)],
intro N,
use (max N M),
split, {
exact le_max_left N M,
}, {
by_contradiction H,
simp [abs_le] at H,
cases H,
have : 2 +l < 2 + l,
calc 2 + l ≤ u (max N M) : hn (max N M) (le_max_right N M)
... < 2 + l : by linarith,
linarith,
}
end
def nondecreasing_seq (u : ℕ → ℝ) := ∀ n m, n ≤ m → u n ≤ u m
-- 0067
example (u : ℕ → ℝ) (l : ℝ) (h : seq_limit u l) (h' : nondecreasing_seq u) :
∀ n, u n ≤ l :=
begin
intro k,
by_contradiction H,
cases h ((u k -l)/2) (by linarith) with N hN,
let p := max k N,
specialize hN p (le_max_right k N),
specialize h' k p (le_max_left k N),
rw abs_le at hN,
linarith,
end
/-
In the following exercises, `A : set ℝ` means that A is a set of real numbers.
We can use the usual notation x ∈ A.
The notation `∀ x ∈ A, ...` is the abbreviation of `∀ x, x ∈ A → ... `
The notation `∃ x ∈ A, ...` is the abbreviation of `∃ x, x ∈ A ∧ ... `.
More precisely it is the abbreviation of `∃ x (H : x ∈ A), ...`
which is Lean's strange way of saying `∃ x, x ∈ A ∧ ... `.
You can convert between these forms using the lemma
exists_prop {p q : Prop} : (∃ (h : p), q) ↔ p ∧ q
We'll work with upper bounds and supremums.
Again we'll introduce specialized definitions for the sake of exercises, but mathlib
has more general versions.
def upper_bound (A : set ℝ) (x : ℝ) := ∀ a ∈ A, a ≤ x
def is_sup (A : set ℝ) (x : ℝ) := upper_bound A x ∧ ∀ y, upper_bound A y → x ≤ y
Remark: one can easily show that a set of real numbers has at most one sup,
but we won't need this.
-/
-- 0068
/- My comment: the model solution is much shorter and uses contrapose! -/
example {A : set ℝ} {x : ℝ} (hx : is_sup A x) :
∀ y, y < x → ∃ a ∈ A, y < a :=
begin
intros y hy,
by_contradiction H,
push_neg at H,
cases hx with _ hsup,
specialize hsup y H,
linarith,
end
/-
Let's do a variation on an example from file 07 that will be useful in the last
exercise below.
-/
-- 0069
lemma le_of_le_add_all' {x y : ℝ} :
(∀ ε > 0, y ≤ x + ε) → y ≤ x :=
begin
contrapose!,
intro hxy,
use ((y-x)/2),
split;
linarith,
end
-- 0070
example {x y : ℝ} {u : ℕ → ℝ} (hu : seq_limit u x)
(ineg : ∀ n, u n ≤ y) : x ≤ y :=
begin
apply le_of_le_add_all',
intros ε ε_pos,
cases hu ε ε_pos with N hN,
specialize hN N (by linarith),
specialize ineg N,
rw abs_le at hN,
cases hN with h _,
linarith,
end
|
5d1c7101c44a00e4af6d849906338d7f40ae9ffe | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/finsupp/pointwise.lean | 219f0bdabf84a67ba09cf8f9ae219162de132894 | [
"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,776 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import data.finsupp.defs
import algebra.ring.pi
/-!
# The pointwise product on `finsupp`.
For the convolution product on `finsupp` when the domain has a binary operation,
see the type synonyms `add_monoid_algebra`
(which is in turn used to define `polynomial` and `mv_polynomial`)
and `monoid_algebra`.
-/
noncomputable theory
open finset
universes u₁ u₂ u₃ u₄ u₅
variables {α : Type u₁} {β : Type u₂} {γ : Type u₃} {δ : Type u₄} {ι : Type u₅}
namespace finsupp
/-! ### Declarations about the pointwise product on `finsupp`s -/
section
variables [mul_zero_class β]
/-- The product of `f g : α →₀ β` is the finitely supported function
whose value at `a` is `f a * g a`. -/
instance : has_mul (α →₀ β) := ⟨zip_with (*) (mul_zero 0)⟩
lemma coe_mul (g₁ g₂ : α →₀ β) : ⇑(g₁ * g₂) = g₁ * g₂ := rfl
@[simp] lemma mul_apply {g₁ g₂ : α →₀ β} {a : α} : (g₁ * g₂) a = g₁ a * g₂ a :=
rfl
lemma support_mul [decidable_eq α] {g₁ g₂ : α →₀ β} : (g₁ * g₂).support ⊆ g₁.support ∩ g₂.support :=
begin
intros a h,
simp only [mul_apply, mem_support_iff] at h,
simp only [mem_support_iff, mem_inter, ne.def],
rw ←not_or_distrib,
intro w,
apply h,
cases w; { rw w, simp },
end
instance : mul_zero_class (α →₀ β) :=
finsupp.coe_fn_injective.mul_zero_class _ coe_zero coe_mul
end
instance [semigroup_with_zero β] : semigroup_with_zero (α →₀ β) :=
finsupp.coe_fn_injective.semigroup_with_zero _ coe_zero coe_mul
instance [non_unital_non_assoc_semiring β] : non_unital_non_assoc_semiring (α →₀ β) :=
finsupp.coe_fn_injective.non_unital_non_assoc_semiring _ coe_zero coe_add coe_mul (λ _ _, rfl)
instance [non_unital_semiring β] : non_unital_semiring (α →₀ β) :=
finsupp.coe_fn_injective.non_unital_semiring _ coe_zero coe_add coe_mul (λ _ _, rfl)
instance [non_unital_comm_semiring β] : non_unital_comm_semiring (α →₀ β) :=
finsupp.coe_fn_injective.non_unital_comm_semiring _ coe_zero coe_add coe_mul (λ _ _, rfl)
instance [non_unital_non_assoc_ring β] : non_unital_non_assoc_ring (α →₀ β) :=
finsupp.coe_fn_injective.non_unital_non_assoc_ring _
coe_zero coe_add coe_mul coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl)
instance [non_unital_ring β] : non_unital_ring (α →₀ β) :=
finsupp.coe_fn_injective.non_unital_ring _
coe_zero coe_add coe_mul coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl)
instance [non_unital_comm_ring β] : non_unital_comm_ring (α →₀ β) :=
finsupp.coe_fn_injective.non_unital_comm_ring _
coe_zero coe_add coe_mul coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl)
-- TODO can this be generalized in the direction of `pi.has_smul'`
-- (i.e. dependent functions and finsupps)
-- TODO in theory this could be generalised, we only really need `smul_zero` for the definition
instance pointwise_scalar [semiring β] : has_smul (α → β) (α →₀ β) :=
{ smul := λ f g, finsupp.of_support_finite (λ a, f a • g a) begin
apply set.finite.subset g.finite_support,
simp only [function.support_subset_iff, finsupp.mem_support_iff, ne.def,
finsupp.fun_support_eq, finset.mem_coe],
intros x hx h,
apply hx,
rw [h, smul_zero],
end }
@[simp]
lemma coe_pointwise_smul [semiring β] (f : α → β) (g : α →₀ β) :
⇑(f • g) = f • g := rfl
/-- The pointwise multiplicative action of functions on finitely supported functions -/
instance pointwise_module [semiring β] : module (α → β) (α →₀ β) :=
function.injective.module _ coe_fn_add_hom coe_fn_injective coe_pointwise_smul
end finsupp
|
3ae2f8e0a9ac0aa48b051ae125a7dee6320edfab | 4950bf76e5ae40ba9f8491647d0b6f228ddce173 | /src/analysis/specific_limits.lean | e0ea0d7d8ef486b8e7e062ad0c6152995cca1a75 | [
"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 | 24,957 | 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 analysis.normed_space.basic
import algebra.geom_sum
import order.filter.archimedean
import topology.instances.ennreal
import tactic.ring_exp
/-!
# A collection of specific limit computations
-/
noncomputable theory
open classical function filter finset metric
open_locale classical topological_space nat big_operators uniformity
variables {α : Type*} {β : Type*} {ι : Type*}
lemma tendsto_norm_at_top_at_top : tendsto (norm : ℝ → ℝ) at_top at_top :=
tendsto_abs_at_top_at_top
lemma summable_of_absolute_convergence_real {f : ℕ → ℝ} :
(∃r, tendsto (λn, (∑ i in range n, abs (f i))) at_top (𝓝 r)) → summable f
| ⟨r, hr⟩ :=
begin
refine summable_of_summable_norm ⟨r, (has_sum_iff_tendsto_nat_of_nonneg _ _).2 _⟩,
exact assume i, norm_nonneg _,
simpa only using hr
end
lemma tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ)⁻¹) at_top (𝓝 0) :=
tendsto_inv_at_top_zero.comp tendsto_coe_nat_at_top_at_top
lemma tendsto_const_div_at_top_nhds_0_nat (C : ℝ) : tendsto (λ n : ℕ, C / n) at_top (𝓝 0) :=
by simpa only [mul_zero] using tendsto_const_nhds.mul tendsto_inverse_at_top_nhds_0_nat
lemma nnreal.tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : nnreal)⁻¹) at_top (𝓝 0) :=
by { rw ← nnreal.tendsto_coe, convert tendsto_inverse_at_top_nhds_0_nat, simp }
lemma nnreal.tendsto_const_div_at_top_nhds_0_nat (C : nnreal) :
tendsto (λ n : ℕ, C / n) at_top (𝓝 0) :=
by simpa using tendsto_const_nhds.mul nnreal.tendsto_inverse_at_top_nhds_0_nat
lemma tendsto_one_div_add_at_top_nhds_0_nat :
tendsto (λ n : ℕ, 1 / ((n : ℝ) + 1)) at_top (𝓝 0) :=
suffices tendsto (λ n : ℕ, 1 / (↑(n + 1) : ℝ)) at_top (𝓝 0), by simpa,
(tendsto_add_at_top_iff_nat 1).2 (tendsto_const_div_at_top_nhds_0_nat 1)
/-! ### Powers -/
lemma tendsto_add_one_pow_at_top_at_top_of_pos [linear_ordered_semiring α] [archimedean α] {r : α}
(h : 0 < r) :
tendsto (λ n:ℕ, (r + 1)^n) at_top at_top :=
tendsto_at_top_at_top_of_monotone' (λ n m, pow_le_pow (le_add_of_nonneg_left (le_of_lt h))) $
not_bdd_above_iff.2 $ λ x, set.exists_range_iff.2 $ add_one_pow_unbounded_of_pos _ h
lemma tendsto_pow_at_top_at_top_of_one_lt [linear_ordered_ring α] [archimedean α]
{r : α} (h : 1 < r) :
tendsto (λn:ℕ, r ^ n) at_top at_top :=
sub_add_cancel r 1 ▸ tendsto_add_one_pow_at_top_at_top_of_pos (sub_pos.2 h)
lemma nat.tendsto_pow_at_top_at_top_of_one_lt {m : ℕ} (h : 1 < m) :
tendsto (λn:ℕ, m ^ n) at_top at_top :=
nat.sub_add_cancel (le_of_lt h) ▸
tendsto_add_one_pow_at_top_at_top_of_pos (nat.sub_pos_of_lt h)
lemma lim_norm_zero' {𝕜 : Type*} [normed_group 𝕜] :
tendsto (norm : 𝕜 → ℝ) (𝓝[{x | x ≠ 0}] 0) (𝓝[set.Ioi 0] 0) :=
lim_norm_zero.inf $ tendsto_principal_principal.2 $ λ x hx, norm_pos_iff.2 hx
lemma normed_field.tendsto_norm_inverse_nhds_within_0_at_top {𝕜 : Type*} [normed_field 𝕜] :
tendsto (λ x:𝕜, ∥x⁻¹∥) (𝓝[{x | x ≠ 0}] 0) at_top :=
(tendsto_inv_zero_at_top.comp lim_norm_zero').congr $ λ x, (normed_field.norm_inv x).symm
lemma tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) :
tendsto (λn:ℕ, r^n) at_top (𝓝 0) :=
by_cases
(assume : r = 0, (tendsto_add_at_top_iff_nat 1).mp $ by simp [pow_succ, this, tendsto_const_nhds])
(assume : r ≠ 0,
have tendsto (λn, (r⁻¹ ^ n)⁻¹) at_top (𝓝 0),
from tendsto_inv_at_top_zero.comp
(tendsto_pow_at_top_at_top_of_one_lt $ one_lt_inv (lt_of_le_of_ne h₁ this.symm) h₂),
tendsto.congr' (univ_mem_sets' $ by simp *) this)
lemma uniformity_basis_dist_pow_of_lt_1 {α : Type*} [metric_space α]
{r : ℝ} (h₀ : 0 < r) (h₁ : r < 1) :
(𝓤 α).has_basis (λ k : ℕ, true) (λ k, {p : α × α | dist p.1 p.2 < r ^ k}) :=
metric.mk_uniformity_basis (λ i _, pow_pos h₀ _) $ λ ε ε0,
(exists_pow_lt_of_lt_one ε0 h₁).imp $ λ k hk, ⟨trivial, hk.le⟩
lemma geom_lt {u : ℕ → ℝ} {k : ℝ} (hk : 0 < k) {n : ℕ} (h : ∀ m ≤ n, k*u m < u (m + 1)) :
k^(n + 1) *u 0 < u (n + 1) :=
begin
induction n with n ih,
{ simpa using h 0 (le_refl _) },
have : (∀ (m : ℕ), m ≤ n → k * u m < u (m + 1)),
intros m hm, apply h, exact nat.le_succ_of_le hm,
specialize ih this,
change k ^ (n + 2) * u 0 < u (n + 2),
replace h : k * u (n + 1) < u (n + 2) := h (n+1) (le_refl _),
calc k ^ (n + 2) * u 0 = k*(k ^ (n + 1) * u 0) : by ring_exp
... < k*(u (n + 1)) : mul_lt_mul_of_pos_left ih hk
... < u (n + 2) : h,
end
/-- If a sequence `v` of real numbers satisfies `k*v n < v (n+1)` with `1 < k`,
then it goes to +∞. -/
lemma tendsto_at_top_of_geom_lt {v : ℕ → ℝ} {k : ℝ} (h₀ : 0 < v 0) (hk : 1 < k)
(hu : ∀ n, k*v n < v (n+1)) : tendsto v at_top at_top :=
begin
apply tendsto_at_top_mono,
show ∀ n, k^n*v 0 ≤ v n,
{ intro n,
induction n with n ih,
{ simp },
calc
k ^ (n + 1) * v 0 = k*(k^n*v 0) : by ring_exp
... ≤ k*v n : mul_le_mul_of_nonneg_left ih (by linarith)
... ≤ v (n + 1) : le_of_lt (hu n) },
apply tendsto_at_top_mul_right h₀,
exact tendsto_pow_at_top_at_top_of_one_lt hk,
end
lemma nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : nnreal} (hr : r < 1) :
tendsto (λ n:ℕ, r^n) at_top (𝓝 0) :=
nnreal.tendsto_coe.1 $ by simp only [nnreal.coe_pow, nnreal.coe_zero,
tendsto_pow_at_top_nhds_0_of_lt_1 r.coe_nonneg hr]
lemma ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : ennreal} (hr : r < 1) :
tendsto (λ n:ℕ, r^n) at_top (𝓝 0) :=
begin
rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩,
rw [← ennreal.coe_zero],
norm_cast at *,
apply nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 hr
end
/-- In a normed ring, the powers of an element x with `∥x∥ < 1` tend to zero. -/
lemma tendsto_pow_at_top_nhds_0_of_norm_lt_1 {R : Type*} [normed_ring R] {x : R}
(h : ∥x∥ < 1) : tendsto (λ (n : ℕ), x ^ n) at_top (𝓝 0) :=
begin
apply squeeze_zero_norm' (eventually_norm_pow_le x),
exact tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg _) h,
end
lemma tendsto_pow_at_top_nhds_0_of_abs_lt_1 {r : ℝ} (h : abs r < 1) :
tendsto (λn:ℕ, r^n) at_top (𝓝 0) :=
tendsto_pow_at_top_nhds_0_of_norm_lt_1 h
/-! ### Geometric series-/
section geometric
lemma has_sum_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) :
has_sum (λn:ℕ, r ^ n) (1 - r)⁻¹ :=
have r ≠ 1, from ne_of_lt h₂,
have tendsto (λn, (r ^ n - 1) * (r - 1)⁻¹) at_top (𝓝 ((0 - 1) * (r - 1)⁻¹)),
from ((tendsto_pow_at_top_nhds_0_of_lt_1 h₁ h₂).sub tendsto_const_nhds).mul tendsto_const_nhds,
have (λ n, (∑ i in range n, r ^ i)) = (λ n, geom_series r n) := rfl,
(has_sum_iff_tendsto_nat_of_nonneg (pow_nonneg h₁) _).mpr $
by simp [neg_inv, geom_sum, div_eq_mul_inv, *] at *
lemma summable_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : summable (λn:ℕ, r ^ n) :=
⟨_, has_sum_geometric_of_lt_1 h₁ h₂⟩
lemma tsum_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : (∑'n:ℕ, r ^ n) = (1 - r)⁻¹ :=
(has_sum_geometric_of_lt_1 h₁ h₂).tsum_eq
lemma has_sum_geometric_two : has_sum (λn:ℕ, ((1:ℝ)/2) ^ n) 2 :=
by convert has_sum_geometric_of_lt_1 _ _; norm_num
lemma summable_geometric_two : summable (λn:ℕ, ((1:ℝ)/2) ^ n) :=
⟨_, has_sum_geometric_two⟩
lemma tsum_geometric_two : (∑'n:ℕ, ((1:ℝ)/2) ^ n) = 2 :=
has_sum_geometric_two.tsum_eq
lemma sum_geometric_two_le (n : ℕ) : ∑ (i : ℕ) in range n, (1 / (2 : ℝ)) ^ i ≤ 2 :=
begin
have : ∀ i, 0 ≤ (1 / (2 : ℝ)) ^ i,
{ intro i, apply pow_nonneg, norm_num },
convert sum_le_tsum (range n) (λ i _, this i) summable_geometric_two,
exact tsum_geometric_two.symm
end
lemma has_sum_geometric_two' (a : ℝ) : has_sum (λn:ℕ, (a / 2) / 2 ^ n) a :=
begin
convert has_sum.mul_left (a / 2) (has_sum_geometric_of_lt_1
(le_of_lt one_half_pos) one_half_lt_one),
{ funext n, simp, refl, },
{ norm_num }
end
lemma summable_geometric_two' (a : ℝ) : summable (λ n:ℕ, (a / 2) / 2 ^ n) :=
⟨a, has_sum_geometric_two' a⟩
lemma tsum_geometric_two' (a : ℝ) : (∑' n:ℕ, (a / 2) / 2^n) = a :=
(has_sum_geometric_two' a).tsum_eq
lemma nnreal.has_sum_geometric {r : nnreal} (hr : r < 1) :
has_sum (λ n : ℕ, r ^ n) (1 - r)⁻¹ :=
begin
apply nnreal.has_sum_coe.1,
push_cast,
rw [nnreal.coe_sub (le_of_lt hr)],
exact has_sum_geometric_of_lt_1 r.coe_nonneg hr
end
lemma nnreal.summable_geometric {r : nnreal} (hr : r < 1) : summable (λn:ℕ, r ^ n) :=
⟨_, nnreal.has_sum_geometric hr⟩
lemma tsum_geometric_nnreal {r : nnreal} (hr : r < 1) : (∑'n:ℕ, r ^ n) = (1 - r)⁻¹ :=
(nnreal.has_sum_geometric hr).tsum_eq
/-- The series `pow r` converges to `(1-r)⁻¹`. For `r < 1` the RHS is a finite number,
and for `1 ≤ r` the RHS equals `∞`. -/
lemma ennreal.tsum_geometric (r : ennreal) : (∑'n:ℕ, r ^ n) = (1 - r)⁻¹ :=
begin
cases lt_or_le r 1 with hr hr,
{ rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩,
norm_cast at *,
convert ennreal.tsum_coe_eq (nnreal.has_sum_geometric hr),
rw [ennreal.coe_inv $ ne_of_gt $ nnreal.sub_pos.2 hr] },
{ rw [ennreal.sub_eq_zero_of_le hr, ennreal.inv_zero, ennreal.tsum_eq_supr_nat, supr_eq_top],
refine λ a ha, (ennreal.exists_nat_gt (lt_top_iff_ne_top.1 ha)).imp
(λ n hn, lt_of_lt_of_le hn _),
have : ∀ k:ℕ, 1 ≤ r^k, by simpa using canonically_ordered_semiring.pow_le_pow_of_le_left hr,
calc (n:ennreal) = (∑ i in range n, 1) : by rw [sum_const, nsmul_one, card_range]
... ≤ ∑ i in range n, r ^ i : sum_le_sum (λ k _, this k) }
end
variables {K : Type*} [normed_field K] {ξ : K}
lemma has_sum_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : has_sum (λn:ℕ, ξ ^ n) (1 - ξ)⁻¹ :=
begin
have xi_ne_one : ξ ≠ 1, by { contrapose! h, simp [h] },
have A : tendsto (λn, (ξ ^ n - 1) * (ξ - 1)⁻¹) at_top (𝓝 ((0 - 1) * (ξ - 1)⁻¹)),
from ((tendsto_pow_at_top_nhds_0_of_norm_lt_1 h).sub tendsto_const_nhds).mul tendsto_const_nhds,
have B : (λ n, (∑ i in range n, ξ ^ i)) = (λ n, geom_series ξ n) := rfl,
rw [has_sum_iff_tendsto_nat_of_summable_norm, B],
{ simpa [geom_sum, xi_ne_one, neg_inv] using A },
{ simp [normed_field.norm_pow, summable_geometric_of_lt_1 (norm_nonneg _) h] }
end
lemma summable_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : summable (λn:ℕ, ξ ^ n) :=
⟨_, has_sum_geometric_of_norm_lt_1 h⟩
lemma tsum_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : (∑'n:ℕ, ξ ^ n) = (1 - ξ)⁻¹ :=
(has_sum_geometric_of_norm_lt_1 h).tsum_eq
lemma has_sum_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : has_sum (λn:ℕ, r ^ n) (1 - r)⁻¹ :=
has_sum_geometric_of_norm_lt_1 h
lemma summable_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : summable (λn:ℕ, r ^ n) :=
summable_geometric_of_norm_lt_1 h
lemma tsum_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : (∑'n:ℕ, r ^ n) = (1 - r)⁻¹ :=
tsum_geometric_of_norm_lt_1 h
/-- A geometric series in a normed field is summable iff the norm of the common ratio is less than
one. -/
@[simp] lemma summable_geometric_iff_norm_lt_1 : summable (λ n : ℕ, ξ ^ n) ↔ ∥ξ∥ < 1 :=
begin
refine ⟨λ h, _, summable_geometric_of_norm_lt_1⟩,
obtain ⟨k : ℕ, hk : dist (ξ ^ k) 0 < 1⟩ :=
(h.tendsto_cofinite_zero.eventually (ball_mem_nhds _ zero_lt_one)).exists,
simp only [normed_field.norm_pow, dist_zero_right] at hk,
rw [← one_pow k] at hk,
exact lt_of_pow_lt_pow _ zero_le_one hk
end
end geometric
/-!
### Sequences with geometrically decaying distance in metric spaces
In this paragraph, we discuss sequences in metric spaces or emetric spaces for which the distance
between two consecutive terms decays geometrically. We show that such sequences are Cauchy
sequences, and bound their distances to the limit. We also discuss series with geometrically
decaying terms.
-/
section edist_le_geometric
variables [emetric_space α] (r C : ennreal) (hr : r < 1) (hC : C ≠ ⊤) {f : ℕ → α}
(hu : ∀n, edist (f n) (f (n+1)) ≤ C * r^n)
include hr hC hu
/-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, `C ≠ ∞`, `r < 1`,
then `f` is a Cauchy sequence.-/
lemma cauchy_seq_of_edist_le_geometric : cauchy_seq f :=
begin
refine cauchy_seq_of_edist_le_of_tsum_ne_top _ hu _,
rw [ennreal.tsum_mul_left, ennreal.tsum_geometric],
refine ennreal.mul_ne_top hC (ennreal.inv_ne_top.2 _),
exact ne_of_gt (ennreal.zero_lt_sub_iff_lt.2 hr)
end
omit hr hC
/-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from
`f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/
lemma edist_le_of_edist_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) :
edist (f n) a ≤ (C * r^n) / (1 - r) :=
begin
convert edist_le_tsum_of_edist_le_of_tendsto _ hu ha _,
simp only [pow_add, ennreal.tsum_mul_left, ennreal.tsum_geometric, ennreal.div_def, mul_assoc]
end
/-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from
`f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/
lemma edist_le_of_edist_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) :
edist (f 0) a ≤ C / (1 - r) :=
by simpa only [pow_zero, mul_one] using edist_le_of_edist_le_geometric_of_tendsto r C hu ha 0
end edist_le_geometric
section edist_le_geometric_two
variables [emetric_space α] (C : ennreal) (hC : C ≠ ⊤) {f : ℕ → α}
(hu : ∀n, edist (f n) (f (n+1)) ≤ C / 2^n) {a : α} (ha : tendsto f at_top (𝓝 a))
include hC hu
/-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then `f` is a Cauchy sequence.-/
lemma cauchy_seq_of_edist_le_geometric_two : cauchy_seq f :=
begin
simp only [ennreal.div_def, ennreal.inv_pow] at hu,
refine cauchy_seq_of_edist_le_geometric 2⁻¹ C _ hC hu,
simp [ennreal.one_lt_two]
end
omit hC
include ha
/-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from
`f n` to the limit of `f` is bounded above by `2 * C * 2^-n`. -/
lemma edist_le_of_edist_le_geometric_two_of_tendsto (n : ℕ) :
edist (f n) a ≤ 2 * C / 2^n :=
begin
simp only [ennreal.div_def, ennreal.inv_pow] at hu,
rw [ennreal.div_def, mul_assoc, mul_comm, ennreal.inv_pow],
convert edist_le_of_edist_le_geometric_of_tendsto 2⁻¹ C hu ha n,
rw [ennreal.one_sub_inv_two, ennreal.inv_inv]
end
/-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from
`f 0` to the limit of `f` is bounded above by `2 * C`. -/
lemma edist_le_of_edist_le_geometric_two_of_tendsto₀: edist (f 0) a ≤ 2 * C :=
by simpa only [pow_zero, ennreal.div_def, ennreal.inv_one, mul_one]
using edist_le_of_edist_le_geometric_two_of_tendsto C hu ha 0
end edist_le_geometric_two
section le_geometric
variables [metric_space α] {r C : ℝ} (hr : r < 1) {f : ℕ → α}
(hu : ∀n, dist (f n) (f (n+1)) ≤ C * r^n)
include hr hu
lemma aux_has_sum_of_le_geometric : has_sum (λ n : ℕ, C * r^n) (C / (1 - r)) :=
begin
have h0 : 0 ≤ C,
by simpa using le_trans dist_nonneg (hu 0),
rcases eq_or_lt_of_le h0 with rfl | Cpos,
{ simp [has_sum_zero] },
{ have rnonneg: r ≥ 0, from nonneg_of_mul_nonneg_left
(by simpa only [pow_one] using le_trans dist_nonneg (hu 1)) Cpos,
refine has_sum.mul_left C _,
by simpa using has_sum_geometric_of_lt_1 rnonneg hr }
end
variables (r C)
/-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then `f` is a Cauchy sequence.
Note that this lemma does not assume `0 ≤ C` or `0 ≤ r`. -/
lemma cauchy_seq_of_le_geometric : cauchy_seq f :=
cauchy_seq_of_dist_le_of_summable _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩
/-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from
`f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/
lemma dist_le_of_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) :
dist (f 0) a ≤ C / (1 - r) :=
(aux_has_sum_of_le_geometric hr hu).tsum_eq ▸
dist_le_tsum_of_dist_le_of_tendsto₀ _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩ ha
/-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from
`f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/
lemma dist_le_of_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) :
dist (f n) a ≤ (C * r^n) / (1 - r) :=
begin
have := aux_has_sum_of_le_geometric hr hu,
convert dist_le_tsum_of_dist_le_of_tendsto _ hu ⟨_, this⟩ ha n,
simp only [pow_add, mul_left_comm C, mul_div_right_comm],
rw [mul_comm],
exact (this.mul_left _).tsum_eq.symm
end
omit hr hu
variable (hu₂ : ∀ n, dist (f n) (f (n+1)) ≤ (C / 2) / 2^n)
/-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then `f` is a Cauchy sequence. -/
lemma cauchy_seq_of_le_geometric_two : cauchy_seq f :=
cauchy_seq_of_dist_le_of_summable _ hu₂ $ ⟨_, has_sum_geometric_two' C⟩
/-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from
`f 0` to the limit of `f` is bounded above by `C`. -/
lemma dist_le_of_le_geometric_two_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) :
dist (f 0) a ≤ C :=
(tsum_geometric_two' C) ▸ dist_le_tsum_of_dist_le_of_tendsto₀ _ hu₂ (summable_geometric_two' C) ha
include hu₂
/-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from
`f n` to the limit of `f` is bounded above by `C / 2^n`. -/
lemma dist_le_of_le_geometric_two_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) :
dist (f n) a ≤ C / 2^n :=
begin
convert dist_le_tsum_of_dist_le_of_tendsto _ hu₂ (summable_geometric_two' C) ha n,
simp only [add_comm n, pow_add, (div_div_eq_div_mul _ _ _).symm],
symmetry,
exact ((has_sum_geometric_two' C).mul_right _).tsum_eq
end
end le_geometric
section summable_le_geometric
variables [normed_group α] {r C : ℝ} {f : ℕ → α}
lemma dist_partial_sum_le_of_le_geometric (hf : ∀n, ∥f n∥ ≤ C * r^n) (n : ℕ) :
dist (∑ i in range n, f i) (∑ i in range (n+1), f i) ≤ C * r ^ n :=
begin
rw [sum_range_succ, dist_eq_norm, ← norm_neg],
convert hf n,
rw [neg_sub, add_sub_cancel]
end
/-- If `∥f n∥ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` form a
Cauchy sequence. This lemma does not assume `0 ≤ r` or `0 ≤ C`. -/
lemma cauchy_seq_finset_of_geometric_bound (hr : r < 1) (hf : ∀n, ∥f n∥ ≤ C * r^n) :
cauchy_seq (λ s : finset (ℕ), ∑ x in s, f x) :=
cauchy_seq_finset_of_norm_bounded _
(aux_has_sum_of_le_geometric hr (dist_partial_sum_le_of_le_geometric hf)).summable hf
/-- If `∥f n∥ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` are within
distance `C * r ^ n / (1 - r)` of the sum of the series. This lemma does not assume `0 ≤ r` or
`0 ≤ C`. -/
lemma norm_sub_le_of_geometric_bound_of_has_sum (hr : r < 1) (hf : ∀n, ∥f n∥ ≤ C * r^n)
{a : α} (ha : has_sum f a) (n : ℕ) :
∥(∑ x in finset.range n, f x) - a∥ ≤ (C * r ^ n) / (1 - r) :=
begin
rw ← dist_eq_norm,
apply dist_le_of_le_geometric_of_tendsto r C hr (dist_partial_sum_le_of_le_geometric hf),
exact ha.tendsto_sum_nat
end
end summable_le_geometric
section normed_ring_geometric
variables {R : Type*} [normed_ring R] [complete_space R]
open normed_space
/-- A geometric series in a complete normed ring is summable.
Proved above (same name, different namespace) for not-necessarily-complete normed fields. -/
lemma normed_ring.summable_geometric_of_norm_lt_1
(x : R) (h : ∥x∥ < 1) : summable (λ (n:ℕ), x ^ n) :=
begin
have h1 : summable (λ (n:ℕ), ∥x∥ ^ n) := summable_geometric_of_lt_1 (norm_nonneg _) h,
refine summable_of_norm_bounded_eventually _ h1 _,
rw nat.cofinite_eq_at_top,
exact eventually_norm_pow_le x,
end
/-- Bound for the sum of a geometric series in a normed ring. This formula does not assume that the
normed ring satisfies the axiom `∥1∥ = 1`. -/
lemma normed_ring.tsum_geometric_of_norm_lt_1
(x : R) (h : ∥x∥ < 1) : ∥(∑' (n:ℕ), x ^ n)∥ ≤ ∥(1:R)∥ - 1 + (1 - ∥x∥)⁻¹ :=
begin
rw tsum_eq_zero_add (normed_ring.summable_geometric_of_norm_lt_1 x h),
simp only [pow_zero],
refine le_trans (norm_add_le _ _) _,
have : ∥(∑' (b : ℕ), (λ n, x ^ (n + 1)) b)∥ ≤ (1 - ∥x∥)⁻¹ - 1,
{ refine tsum_of_norm_bounded _ (λ b, norm_pow_le' _ (nat.succ_pos b)),
convert (has_sum_nat_add_iff' 1).mpr (has_sum_geometric_of_lt_1 (norm_nonneg x) h),
simp },
linarith
end
lemma geom_series_mul_neg (x : R) (h : ∥x∥ < 1) :
(∑' (i:ℕ), x ^ i) * (1 - x) = 1 :=
begin
have := ((normed_ring.summable_geometric_of_norm_lt_1 x h).has_sum.mul_right (1 - x)),
refine tendsto_nhds_unique this.tendsto_sum_nat _,
have : tendsto (λ (n : ℕ), 1 - x ^ n) at_top (𝓝 1),
{ simpa using tendsto_const_nhds.sub (tendsto_pow_at_top_nhds_0_of_norm_lt_1 h) },
convert ← this,
ext n,
rw [←geom_sum_mul_neg, geom_series_def, finset.sum_mul],
end
lemma mul_neg_geom_series (x : R) (h : ∥x∥ < 1) :
(1 - x) * (∑' (i:ℕ), x ^ i) = 1 :=
begin
have := (normed_ring.summable_geometric_of_norm_lt_1 x h).has_sum.mul_left (1 - x),
refine tendsto_nhds_unique this.tendsto_sum_nat _,
have : tendsto (λ (n : ℕ), 1 - x ^ n) at_top (nhds 1),
{ simpa using tendsto_const_nhds.sub
(tendsto_pow_at_top_nhds_0_of_norm_lt_1 h) },
convert ← this,
ext n,
rw [←mul_neg_geom_sum, geom_series_def, finset.mul_sum]
end
end normed_ring_geometric
/-! ### Positive sequences with small sums on encodable types -/
/-- For any positive `ε`, define on an encodable type a positive sequence with sum less than `ε` -/
def pos_sum_of_encodable {ε : ℝ} (hε : 0 < ε)
(ι) [encodable ι] : {ε' : ι → ℝ // (∀ i, 0 < ε' i) ∧ ∃ c, has_sum ε' c ∧ c ≤ ε} :=
begin
let f := λ n, (ε / 2) / 2 ^ n,
have hf : has_sum f ε := has_sum_geometric_two' _,
have f0 : ∀ n, 0 < f n := λ n, div_pos (half_pos hε) (pow_pos zero_lt_two _),
refine ⟨f ∘ encodable.encode, λ i, f0 _, _⟩,
rcases hf.summable.comp_injective (@encodable.encode_injective ι _) with ⟨c, hg⟩,
refine ⟨c, hg, has_sum_le_inj _ (@encodable.encode_injective ι _) _ _ hg hf⟩,
{ assume i _, exact le_of_lt (f0 _) },
{ assume n, exact le_refl _ }
end
namespace nnreal
theorem exists_pos_sum_of_encodable {ε : nnreal} (hε : 0 < ε) (ι) [encodable ι] :
∃ ε' : ι → nnreal, (∀ i, 0 < ε' i) ∧ ∃c, has_sum ε' c ∧ c < ε :=
let ⟨a, a0, aε⟩ := exists_between hε in
let ⟨ε', hε', c, hc, hcε⟩ := pos_sum_of_encodable a0 ι in
⟨ λi, ⟨ε' i, le_of_lt $ hε' i⟩, assume i, nnreal.coe_lt_coe.2 $ hε' i,
⟨c, has_sum_le (assume i, le_of_lt $ hε' i) has_sum_zero hc ⟩, nnreal.has_sum_coe.1 hc,
lt_of_le_of_lt (nnreal.coe_le_coe.1 hcε) aε ⟩
end nnreal
namespace ennreal
theorem exists_pos_sum_of_encodable {ε : ennreal} (hε : 0 < ε) (ι) [encodable ι] :
∃ ε' : ι → nnreal, (∀ i, 0 < ε' i) ∧ (∑' i, (ε' i : ennreal)) < ε :=
begin
rcases exists_between hε with ⟨r, h0r, hrε⟩,
rcases lt_iff_exists_coe.1 hrε with ⟨x, rfl, hx⟩,
rcases nnreal.exists_pos_sum_of_encodable (coe_lt_coe.1 h0r) ι with ⟨ε', hp, c, hc, hcr⟩,
exact ⟨ε', hp, (ennreal.tsum_coe_eq hc).symm ▸ lt_trans (coe_lt_coe.2 hcr) hrε⟩
end
end ennreal
/-!
### Factorial
-/
lemma factorial_tendsto_at_top : tendsto nat.factorial at_top at_top :=
tendsto_at_top_at_top_of_monotone nat.monotone_factorial (λ n, ⟨n, n.self_le_factorial⟩)
lemma tendsto_factorial_div_pow_self_at_top : tendsto (λ n, n! / n^n : ℕ → ℝ) at_top (𝓝 0) :=
tendsto_of_tendsto_of_tendsto_of_le_of_le'
tendsto_const_nhds
(tendsto_const_div_at_top_nhds_0_nat 1)
(eventually_of_forall $ λ n, div_nonneg (by exact_mod_cast n.factorial_pos.le)
(pow_nonneg (by exact_mod_cast n.zero_le) _))
begin
rw eventually_iff_exists_mem,
use [set.Ioi 0, Ioi_mem_at_top 0],
rintros n (hn : 0 < n),
rcases nat.exists_eq_succ_of_ne_zero hn.ne.symm with ⟨k, rfl⟩,
rw [← prod_range_add_one_eq_factorial, pow_eq_prod_const, div_eq_mul_inv, ← inv_eq_one_div, prod_nat_cast,
nat.cast_succ, ← prod_inv_distrib', ← prod_mul_distrib, finset.prod_range_succ'],
simp only [prod_range_succ', one_mul, nat.cast_add, zero_add, nat.cast_one],
refine mul_le_of_le_one_left (inv_nonneg.mpr $ by exact_mod_cast hn.le) (prod_le_one _ _);
intros x hx;
rw finset.mem_range at hx,
{ refine mul_nonneg _ (inv_nonneg.mpr _); norm_cast; linarith },
{ refine (div_le_one $ by exact_mod_cast hn).mpr _, norm_cast, linarith }
end
|
ff232077357e16164994bf7d007af15cea4786ea | 37a833c924892ee3ecb911484775a6d6ebb8984d | /src/category_theory/cancellation.lean | 9268b4edf8f19a5a2997aeb837c21fcf314c454a | [] | no_license | silky/lean-category-theory | 28126e80564a1f99e9c322d86b3f7d750da0afa1 | 0f029a2364975f56ac727d31d867a18c95c22fd8 | refs/heads/master | 1,589,555,811,646 | 1,554,673,665,000 | 1,554,673,665,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,375 | lean | -- Copyright (c) 2018 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
import category_theory.category
import category_theory.tactics.obviously
namespace category_theory
universes u v
variables {C : Type u} {X Y Z : C} [𝒞 : category.{u v} C]
include 𝒞
@[forward] def cancel_left (f g : X ⟶ Y) (h : ∀ {Z : C} (h : Y ⟶ Z), f ≫ h = g ≫ h) : f = g :=
begin
convert h (𝟙 Y), tidy
end
@[forward] def cancel_right (f g : Y ⟶ Z) (h : ∀ {X : C} (h : X ⟶ Y), h ≫ f = h ≫ g) : f = g :=
begin
convert h (𝟙 Y), tidy
end
@[forward] def cancel_left' (f g : X ⟶ Y) (w : (λ {Z : C} (h : Y ⟶ Z), f ≫ h) = (λ {Z : C} (h : Y ⟶ Z), g ≫ h)) : f = g :=
begin
convert (congr_fun (congr_fun w Y) (𝟙 Y)), tidy
end
@[forward] def cancel_right' (f g : Y ⟶ Z) (w : (λ {X : C} (h : X ⟶ Y), h ≫ f) = (λ {X : C} (h : X ⟶ Y), h ≫ g)) : f = g :=
begin
convert (congr_fun (congr_fun w Y) (𝟙 Y)), tidy
end
@[forward] def identity_if_it_quacks_left (f : X ⟶ X) (h : ∀ {Y : C} (g : X ⟶ Y), f ≫ g = g) : f = 𝟙 X :=
begin
convert h (𝟙 X), tidy
end
@[forward] def identity_if_it_quacks_right (f : X ⟶ X) (h : ∀ {Y : C} (g : Y ⟶ X), g ≫ f = g) : f = 𝟙 X :=
begin
convert h (𝟙 X), tidy
end
end category_theory |
becaf508603f0110d86ff775ff62d60b3fd10885 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/algebra/opposites.lean | 8ed49d0dff8209e407d49a74bf129a71fa3416ac | [
"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 | 8,893 | 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 algebra.group.defs
import logic.equiv.basic
import logic.nontrivial
/-!
# Multiplicative opposite and algebraic operations on it
In this file we define `mul_opposite α = αᵐᵒᵖ` to be the multiplicative opposite of `α`. It inherits
all additive algebraic structures on `α` (in other files), and reverses the order of multipliers in
multiplicative structures, i.e., `op (x * y) = op y * op x`, where `mul_opposite.op` is the
canonical map from `α` to `αᵐᵒᵖ`.
We also define `add_opposite α = αᵃᵒᵖ` to be the additive opposite of `α`. It inherits all
multiplicative algebraic structures on `α` (in other files), and reverses the order of summands in
additive structures, i.e. `op (x + y) = op y + op x`, where `add_opposite.op` is the canonical map
from `α` to `αᵃᵒᵖ`.
## Notation
* `αᵐᵒᵖ = mul_opposite α`
* `αᵃᵒᵖ = add_opposite α`
## Tags
multiplicative opposite, additive opposite
-/
universes u v
open function
/-- Multiplicative opposite of a type. This type inherits all additive structures on `α` and
reverses left and right in multiplication.-/
@[to_additive "Additive opposite of a type. This type inherits all multiplicative structures on
`α` and reverses left and right in addition."]
def mul_opposite (α : Type u) : Type u := α
postfix `ᵐᵒᵖ`:std.prec.max_plus := mul_opposite
postfix `ᵃᵒᵖ`:std.prec.max_plus := add_opposite
variables {α : Type u}
namespace mul_opposite
/-- The element of `mul_opposite α` that represents `x : α`. -/
@[pp_nodot, to_additive "The element of `αᵃᵒᵖ` that represents `x : α`."]
def op : α → αᵐᵒᵖ := id
/-- The element of `α` represented by `x : αᵐᵒᵖ`. -/
@[pp_nodot, to_additive "The element of `α` represented by `x : αᵃᵒᵖ`."]
def unop : αᵐᵒᵖ → α := id
attribute [pp_nodot] add_opposite.op add_opposite.unop
@[simp, to_additive] lemma unop_op (x : α) : unop (op x) = x := rfl
@[simp, to_additive] lemma op_unop (x : αᵐᵒᵖ) : op (unop x) = x := rfl
@[simp, to_additive] lemma op_comp_unop : (op : α → αᵐᵒᵖ) ∘ unop = id := rfl
@[simp, to_additive] lemma unop_comp_op : (unop : αᵐᵒᵖ → α) ∘ op = id := rfl
attribute [irreducible] mul_opposite
/-- A recursor for `mul_opposite`. Use as `induction x using mul_opposite.rec`. -/
@[simp, to_additive "A recursor for `add_opposite`. Use as `induction x using add_opposite.rec`."]
protected def rec {F : Π (X : αᵐᵒᵖ), Sort v} (h : Π X, F (op X)) : Π X, F X :=
λ X, h (unop X)
/-- The canonical bijection between `α` and `αᵐᵒᵖ`. -/
@[to_additive "The canonical bijection between `α` and `αᵃᵒᵖ`.",
simps apply symm_apply { fully_applied := ff }]
def op_equiv : α ≃ αᵐᵒᵖ := ⟨op, unop, unop_op, op_unop⟩
@[to_additive] lemma op_bijective : bijective (op : α → αᵐᵒᵖ) := op_equiv.bijective
@[to_additive] lemma unop_bijective : bijective (unop : αᵐᵒᵖ → α) := op_equiv.symm.bijective
@[to_additive] lemma op_injective : injective (op : α → αᵐᵒᵖ) := op_bijective.injective
@[to_additive] lemma op_surjective : surjective (op : α → αᵐᵒᵖ) := op_bijective.surjective
@[to_additive] lemma unop_injective : injective (unop : αᵐᵒᵖ → α) := unop_bijective.injective
@[to_additive] lemma unop_surjective : surjective (unop : αᵐᵒᵖ → α) := unop_bijective.surjective
@[simp, to_additive] lemma op_inj {x y : α} : op x = op y ↔ x = y := op_injective.eq_iff
@[simp, to_additive] lemma unop_inj {x y : αᵐᵒᵖ} : unop x = unop y ↔ x = y := unop_injective.eq_iff
variable (α)
@[to_additive] instance [nontrivial α] : nontrivial αᵐᵒᵖ := op_injective.nontrivial
@[to_additive] instance [inhabited α] : inhabited αᵐᵒᵖ := ⟨op default⟩
@[to_additive] instance [subsingleton α] : subsingleton αᵐᵒᵖ := unop_injective.subsingleton
@[to_additive] instance [unique α] : unique αᵐᵒᵖ := unique.mk' _
@[to_additive] instance [is_empty α] : is_empty αᵐᵒᵖ := function.is_empty unop
instance [has_zero α] : has_zero αᵐᵒᵖ := { zero := op 0 }
@[to_additive] instance [has_one α] : has_one αᵐᵒᵖ := { one := op 1 }
instance [has_add α] : has_add αᵐᵒᵖ :=
{ add := λ x y, op (unop x + unop y) }
instance [has_sub α] : has_sub αᵐᵒᵖ :=
{ sub := λ x y, op (unop x - unop y) }
instance [has_neg α] : has_neg αᵐᵒᵖ :=
{ neg := λ x, op $ -(unop x) }
instance [has_involutive_neg α] : has_involutive_neg αᵐᵒᵖ :=
{ neg_neg := λ a, unop_injective $ neg_neg _,
..mul_opposite.has_neg α }
@[to_additive] instance [has_mul α] : has_mul αᵐᵒᵖ :=
{ mul := λ x y, op (unop y * unop x) }
@[to_additive] instance [has_inv α] : has_inv αᵐᵒᵖ :=
{ inv := λ x, op $ (unop x)⁻¹ }
@[to_additive] instance [has_involutive_inv α] : has_involutive_inv αᵐᵒᵖ :=
{ inv_inv := λ a, unop_injective $ inv_inv _,
..mul_opposite.has_inv α }
@[to_additive] instance (R : Type*) [has_smul R α] : has_smul R αᵐᵒᵖ :=
{ smul := λ c x, op (c • unop x) }
section
variables (α)
@[simp] lemma op_zero [has_zero α] : op (0 : α) = 0 := rfl
@[simp] lemma unop_zero [has_zero α] : unop (0 : αᵐᵒᵖ) = 0 := rfl
@[simp, to_additive] lemma op_one [has_one α] : op (1 : α) = 1 := rfl
@[simp, to_additive] lemma unop_one [has_one α] : unop (1 : αᵐᵒᵖ) = 1 := rfl
variable {α}
@[simp] lemma op_add [has_add α] (x y : α) : op (x + y) = op x + op y := rfl
@[simp] lemma unop_add [has_add α] (x y : αᵐᵒᵖ) : unop (x + y) = unop x + unop y := rfl
@[simp] lemma op_neg [has_neg α] (x : α) : op (-x) = -op x := rfl
@[simp] lemma unop_neg [has_neg α] (x : αᵐᵒᵖ) : unop (-x) = -unop x := rfl
@[simp, to_additive] lemma op_mul [has_mul α] (x y : α) : op (x * y) = op y * op x := rfl
@[simp, to_additive] lemma unop_mul [has_mul α] (x y : αᵐᵒᵖ) : unop (x * y) = unop y * unop x := rfl
@[simp, to_additive] lemma op_inv [has_inv α] (x : α) : op (x⁻¹) = (op x)⁻¹ := rfl
@[simp, to_additive] lemma unop_inv [has_inv α] (x : αᵐᵒᵖ) : unop (x⁻¹) = (unop x)⁻¹ := rfl
@[simp] lemma op_sub [has_sub α] (x y : α) : op (x - y) = op x - op y := rfl
@[simp] lemma unop_sub [has_sub α] (x y : αᵐᵒᵖ) : unop (x - y) = unop x - unop y := rfl
@[simp, to_additive] lemma op_smul {R : Type*} [has_smul R α] (c : R) (a : α) :
op (c • a) = c • op a := rfl
@[simp, to_additive] lemma unop_smul {R : Type*} [has_smul R α] (c : R) (a : αᵐᵒᵖ) :
unop (c • a) = c • unop a := rfl
end
variable {α}
@[simp] lemma unop_eq_zero_iff [has_zero α] (a : αᵐᵒᵖ) : a.unop = (0 : α) ↔ a = (0 : αᵐᵒᵖ) :=
unop_injective.eq_iff' rfl
@[simp] lemma op_eq_zero_iff [has_zero α] (a : α) : op a = (0 : αᵐᵒᵖ) ↔ a = (0 : α) :=
op_injective.eq_iff' rfl
lemma unop_ne_zero_iff [has_zero α] (a : αᵐᵒᵖ) : a.unop ≠ (0 : α) ↔ a ≠ (0 : αᵐᵒᵖ) :=
not_congr $ unop_eq_zero_iff a
lemma op_ne_zero_iff [has_zero α] (a : α) : op a ≠ (0 : αᵐᵒᵖ) ↔ a ≠ (0 : α) :=
not_congr $ op_eq_zero_iff a
@[simp, to_additive] lemma unop_eq_one_iff [has_one α] (a : αᵐᵒᵖ) : a.unop = 1 ↔ a = 1 :=
unop_injective.eq_iff' rfl
@[simp, to_additive] lemma op_eq_one_iff [has_one α] (a : α) : op a = 1 ↔ a = 1 :=
op_injective.eq_iff' rfl
end mul_opposite
namespace add_opposite
instance [has_one α] : has_one αᵃᵒᵖ := { one := op 1 }
@[simp] lemma op_one [has_one α] : op (1 : α) = 1 := rfl
@[simp] lemma unop_one [has_one α] : unop 1 = (1 : α) := rfl
@[simp] lemma op_eq_one_iff [has_one α] {a : α} : op a = 1 ↔ a = 1 := op_injective.eq_iff' op_one
@[simp] lemma unop_eq_one_iff [has_one α] {a : αᵃᵒᵖ} : unop a = 1 ↔ a = 1 :=
unop_injective.eq_iff' unop_one
instance [has_mul α] : has_mul αᵃᵒᵖ := { mul := λ a b, op (unop a * unop b) }
@[simp] lemma op_mul [has_mul α] (a b : α) : op (a * b) = op a * op b := rfl
@[simp] lemma unop_mul [has_mul α] (a b : αᵃᵒᵖ) : unop (a * b) = unop a * unop b := rfl
instance [has_inv α] : has_inv αᵃᵒᵖ := { inv := λ a, op (unop a)⁻¹ }
instance [has_involutive_inv α] : has_involutive_inv αᵃᵒᵖ :=
{ inv_inv := λ a, unop_injective $ inv_inv _,
..add_opposite.has_inv }
@[simp] lemma op_inv [has_inv α] (a : α) : op a⁻¹ = (op a)⁻¹ := rfl
@[simp] lemma unop_inv [has_inv α] (a : αᵃᵒᵖ) : unop a⁻¹ = (unop a)⁻¹ := rfl
instance [has_div α] : has_div αᵃᵒᵖ := { div := λ a b, op (unop a / unop b) }
@[simp] lemma op_div [has_div α] (a b : α) : op (a / b) = op a / op b := rfl
@[simp] lemma unop_div [has_div α] (a b : α) : unop (a / b) = unop a / unop b := rfl
end add_opposite
|
7bebd17b5c5ed03bbaa1abd2107b9f333efa1758 | 5fbbd711f9bfc21ee168f46a4be146603ece8835 | /lean/principia_mathematica/peano.lean | 14f81b7cd2ed3249bf695657dd1c50a2fdc3beb7 | [] | no_license | goedel-gang/maths | 22596f71e3fde9c088e59931f128a3b5efb73a2c | a20a6f6a8ce800427afd595c598a5ad43da1408d | refs/heads/master | 1,623,055,941,960 | 1,621,599,441,000 | 1,621,599,441,000 | 169,335,840 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,027 | lean | open nat
--1.a.
example : ∀ m n k : nat, m * (n + k) = m * n + m * k :=
begin
intros m n k,
induction m with n hn,
repeat {rw zero_mul},
repeat {rw succ_mul},
rw hn,
simp,
end
--1.b.
example : ∀ n : nat, 0 * n = 0 :=
begin
intro n,
rw zero_mul,
end
--1.c.
example : ∀ n : nat, 1 * n = n :=
begin
intro n,
induction n with m hm,
rw mul_zero,
rw mul_succ,
rw hm,
end
--1.d.
example : ∀ m n k : nat, (m * n) * k = m * (n * k) :=
begin
intros m n k,
rw mul_assoc,
end
--1.e.
example : ∀ m n : nat, m * n= n * m :=
begin
intros m n,
rw mul_comm,
end
--2.a.
example : ∀ m n k : nat, n ≤ m → n + k ≤ m + k :=
begin
intros m n k h,
sorry,
end
--2.b.
example : ∀ m n k : nat, n + k ≤ m + k → n ≤ m :=
begin
intros m n k h,
end
--2.c.
example : ∀ m n k : nat, n ≤ m → n * k ≤ m * k := sorry
--2.d.
example : ∀ m n : nat, m ≥ n → m = n ∨ m ≥ n+1 := sorry
--2.e.
example : ∀ n : nat, 0 ≤ n := sorry |
b0e67fe55dc8dc8e887637f4547c894348508fa6 | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/data/polynomial/derivative.lean | d02ec976a594018fe1d9602f75d3807d5105de70 | [
"Apache-2.0"
] | permissive | agjftucker/mathlib | d634cd0d5256b6325e3c55bb7fb2403548371707 | 87fe50de17b00af533f72a102d0adefe4a2285e8 | refs/heads/master | 1,625,378,131,941 | 1,599,166,526,000 | 1,599,166,526,000 | 160,748,509 | 0 | 0 | Apache-2.0 | 1,544,141,789,000 | 1,544,141,789,000 | null | UTF-8 | Lean | false | false | 9,583 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker
-/
import data.polynomial.eval
/-!
# Theory of univariate polynomials
-/
noncomputable theory
local attribute [instance, priority 100] classical.prop_decidable
open finsupp finset
open_locale big_operators
namespace polynomial
universes u v w y z
variables {R : Type u} {S : Type v} {T : Type w} {ι : Type y} {A : Type z} {a b : R} {n : ℕ}
section derivative
section semiring
variables [semiring R]
/-- `derivative p` is the formal derivative of the polynomial `p` -/
def derivative (p : polynomial R) : polynomial R := p.sum (λn a, C (a * n) * X^(n - 1))
lemma coeff_derivative (p : polynomial R) (n : ℕ) :
coeff (derivative p) n = coeff p (n + 1) * (n + 1) :=
begin
rw [derivative],
simp only [coeff_X_pow, coeff_sum, coeff_C_mul],
rw [finsupp.sum, finset.sum_eq_single (n + 1)],
simp only [nat.add_succ_sub_one, add_zero, mul_one, if_true, eq_self_iff_true], norm_cast,
swap, { rw [if_pos (nat.add_sub_cancel _ _).symm, mul_one, nat.cast_add, nat.cast_one, mem_support_iff],
intro h, push_neg at h, simp [h], },
{ assume b, cases b,
{ intros, rw [nat.cast_zero, mul_zero, zero_mul], },
{ intros _ H, rw [nat.succ_sub_one b, if_neg (mt (congr_arg nat.succ) H.symm), mul_zero] } }
end
@[simp] lemma derivative_zero : derivative (0 : polynomial R) = 0 :=
finsupp.sum_zero_index
lemma derivative_monomial (a : R) (n : ℕ) : derivative (C a * X ^ n) = C (a * n) * X^(n - 1) :=
begin
rw [← single_eq_C_mul_X, ← single_eq_C_mul_X, derivative, monomial,
sum_single_index, single_eq_C_mul_X],
simp only [zero_mul, C_0],
end
@[simp] lemma derivative_C {a : R} : derivative (C a) = 0 :=
suffices derivative (C a * X^0) = C (a * 0:R) * X ^ 0,
by simpa only [mul_one, zero_mul, C_0, mul_zero, pow_zero],
derivative_monomial a 0
@[simp] lemma derivative_X : derivative (X : polynomial R) = 1 :=
by simpa only [mul_one, one_mul, C_1, pow_one, nat.cast_one, pow_zero]
using derivative_monomial (1:R) 1
@[simp] lemma derivative_one : derivative (1 : polynomial R) = 0 :=
derivative_C
@[simp] lemma derivative_add {f g : polynomial R} :
derivative (f + g) = derivative f + derivative g :=
by refine finsupp.sum_add_index _ _; intros;
simp only [add_mul, zero_mul, C_0, C_add, C_mul]
/-- The formal derivative of polynomials, as additive homomorphism. -/
def derivative_hom (R : Type*) [semiring R] : polynomial R →+ polynomial R :=
{ to_fun := derivative,
map_zero' := derivative_zero,
map_add' := λ p q, derivative_add }
@[simp] lemma derivative_neg {R : Type*} [ring R] (f : polynomial R) :
derivative (-f) = -derivative f :=
(derivative_hom R).map_neg f
@[simp] lemma derivative_sub {R : Type*} [ring R] (f g : polynomial R) :
derivative (f - g) = derivative f - derivative g :=
(derivative_hom R).map_sub f g
instance : is_add_monoid_hom (derivative : polynomial R → polynomial R) :=
(derivative_hom R).is_add_monoid_hom
@[simp] lemma derivative_sum {s : finset ι} {f : ι → polynomial R} :
derivative (∑ b in s, f b) = ∑ b in s, derivative (f b) :=
(derivative_hom R).map_sum f s
@[simp] lemma derivative_smul (r : R) (p : polynomial R) : derivative (r • p) = r • derivative p :=
by { ext, simp only [coeff_derivative, mul_assoc, coeff_smul], }
end semiring
section comm_semiring
variables [comm_semiring R]
@[simp] lemma derivative_mul {f g : polynomial R} :
derivative (f * g) = derivative f * g + f * derivative g :=
calc derivative (f * g) = f.sum (λn a, g.sum (λm b, C ((a * b) * (n + m : ℕ)) * X^((n + m) - 1))) :
begin
transitivity, exact derivative_sum,
transitivity, { apply finset.sum_congr rfl, assume x hx, exact derivative_sum },
apply finset.sum_congr rfl, assume n hn, apply finset.sum_congr rfl, assume m hm,
transitivity,
{ apply congr_arg, exact single_eq_C_mul_X },
exact derivative_monomial _ _
end
... = f.sum (λn a, g.sum (λm b,
(C (a * n) * X^(n - 1)) * (C b * X^m) + (C a * X^n) * (C (b * m) * X^(m - 1)))) :
sum_congr rfl $ assume n hn, sum_congr rfl $ assume m hm,
by simp only [nat.cast_add, mul_add, add_mul, C_add, C_mul];
cases n; simp only [nat.succ_sub_succ, pow_zero];
cases m; simp only [nat.cast_zero, C_0, nat.succ_sub_succ, zero_mul, mul_zero,
nat.sub_zero, pow_zero, pow_add, one_mul, pow_succ, mul_comm, mul_left_comm]
... = derivative f * g + f * derivative g :
begin
conv { to_rhs, congr,
{ rw [← sum_C_mul_X_eq g] },
{ rw [← sum_C_mul_X_eq f] } },
unfold derivative finsupp.sum,
simp only [sum_add_distrib, finset.mul_sum, finset.sum_mul]
end
theorem derivative_pow_succ (p : polynomial R) (n : ℕ) :
(p ^ (n + 1)).derivative = (n + 1) * (p ^ n) * p.derivative :=
nat.rec_on n (by rw [pow_one, nat.cast_zero, zero_add, one_mul, pow_zero, one_mul]) $ λ n ih,
by rw [pow_succ', derivative_mul, ih, mul_right_comm, ← add_mul,
add_mul (n.succ : polynomial R), one_mul, pow_succ', mul_assoc, n.cast_succ]
theorem derivative_pow (p : polynomial R) (n : ℕ) :
(p ^ n).derivative = n * (p ^ (n - 1)) * p.derivative :=
nat.cases_on n (by rw [pow_zero, derivative_one, nat.cast_zero, zero_mul, zero_mul]) $ λ n,
by rw [p.derivative_pow_succ n, n.succ_sub_one, n.cast_succ]
theorem derivative_map [comm_semiring S] (p : polynomial R) (f : R →+* S) :
(p.map f).derivative = p.derivative.map f :=
polynomial.induction_on p
(λ r, by rw [map_C, derivative_C, derivative_C, map_zero])
(λ p q ihp ihq, by rw [map_add, derivative_add, ihp, ihq, derivative_add, map_add])
(λ n r ih, by rw [map_mul, map_C, map_pow, map_X,
derivative_mul, derivative_pow_succ, derivative_C, zero_mul, zero_add, derivative_X, mul_one,
derivative_mul, derivative_pow_succ, derivative_C, zero_mul, zero_add, derivative_X, mul_one,
map_mul, map_C, map_mul, map_pow, map_add, map_nat_cast, map_one, map_X])
/-- Chain rule for formal derivative of polynomials. -/
theorem derivative_eval₂_C (p q : polynomial R) :
(p.eval₂ C q).derivative = p.derivative.eval₂ C q * q.derivative :=
polynomial.induction_on p
(λ r, by rw [eval₂_C, derivative_C, eval₂_zero, zero_mul])
(λ p₁ p₂ ih₁ ih₂, by rw [eval₂_add, derivative_add, ih₁, ih₂, derivative_add, eval₂_add, add_mul])
(λ n r ih, by rw [pow_succ', ← mul_assoc, eval₂_mul, eval₂_X, derivative_mul, ih,
@derivative_mul _ _ _ X, derivative_X, mul_one, eval₂_add, @eval₂_mul _ _ _ _ X, eval₂_X,
add_mul, mul_right_comm])
theorem of_mem_support_derivative {p : polynomial R} {n : ℕ} (h : n ∈ p.derivative.support) :
n + 1 ∈ p.support :=
finsupp.mem_support_iff.2 $ λ (h1 : p.coeff (n+1) = 0), finsupp.mem_support_iff.1 h $
show p.derivative.coeff n = 0, by rw [coeff_derivative, h1, zero_mul]
theorem degree_derivative_lt {p : polynomial R} (hp : p ≠ 0) : p.derivative.degree < p.degree :=
(finset.sup_lt_iff $ bot_lt_iff_ne_bot.2 $ mt degree_eq_bot.1 hp).2 $ λ n hp, lt_of_lt_of_le
(with_bot.some_lt_some.2 n.lt_succ_self) $ finset.le_sup $ of_mem_support_derivative hp
theorem nat_degree_derivative_lt {p : polynomial R} (hp : p.derivative ≠ 0) :
p.derivative.nat_degree < p.nat_degree :=
have hp1 : p ≠ 0, from λ h, hp $ by rw [h, derivative_zero],
with_bot.some_lt_some.1 $ by { rw [nat_degree, option.get_or_else_of_ne_none $ mt degree_eq_bot.1 hp,
nat_degree, option.get_or_else_of_ne_none $ mt degree_eq_bot.1 hp1], exact degree_derivative_lt hp1 }
theorem degree_derivative_le {p : polynomial R} : p.derivative.degree ≤ p.degree :=
if H : p = 0 then le_of_eq $ by rw [H, derivative_zero] else le_of_lt $ degree_derivative_lt H
/-- The formal derivative of polynomials, as linear homomorphism. -/
def derivative_lhom (R : Type*) [comm_ring R] : polynomial R →ₗ[R] polynomial R :=
{ to_fun := derivative,
map_add' := λ p q, derivative_add,
map_smul' := λ r p, derivative_smul r p }
end comm_semiring
section domain
variables [integral_domain R]
-- TODO: golf this, dunno how i broke it so bad
lemma mem_support_derivative [char_zero R] (p : polynomial R) (n : ℕ) :
n ∈ (derivative p).support ↔ n + 1 ∈ p.support :=
begin
rw finsupp.mem_support_iff, split; intro h,
suffices h1 : p.coeff (n+1) ≠ 0, simp; tauto, contrapose! h,
convert coeff_derivative _ _, simp [h],
contrapose! h, simp,
suffices : p.to_fun (n + 1) * (n + 1) = 0, simp only [mul_eq_zero] at this, cases this,
{ exact this }, { norm_cast at this },
erw ← h, symmetry, convert coeff_derivative _ _,
end
@[simp] lemma degree_derivative_eq [char_zero R] (p : polynomial R) (hp : 0 < nat_degree p) :
degree (derivative p) = (nat_degree p - 1 : ℕ) :=
le_antisymm
(le_trans (degree_sum_le _ _) $ sup_le $ assume n hn,
have n ≤ nat_degree p, begin
rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree],
{ refine le_degree_of_ne_zero _, simpa only [mem_support_iff] using hn },
{ assume h, simpa only [h, support_zero] using hn }
end,
le_trans (degree_monomial_le _ _) $ with_bot.coe_le_coe.2 $ nat.sub_le_sub_right this _)
begin
refine le_sup _,
rw [mem_support_derivative, nat.sub_add_cancel, mem_support_iff],
{ show ¬ leading_coeff p = 0,
rw [leading_coeff_eq_zero],
assume h, rw [h, nat_degree_zero] at hp,
exact lt_irrefl 0 (lt_of_le_of_lt (zero_le _) hp), },
exact hp
end
end domain
end derivative
end polynomial
|
ac627eafb144bd70b534c7904753d0cb975a040c | ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5 | /src/Lean/Elab/Match.lean | 6fe8ab9b2b5a95296c154a3d4c98a0040d986898 | [
"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 | 38,301 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Match.MatchPatternAttr
import Lean.Meta.Match.Match
import Lean.Elab.SyntheticMVars
import Lean.Elab.App
import Lean.Parser.Term
namespace Lean.Elab.Term
open Meta
open Lean.Parser.Term
/- This modules assumes "match"-expressions use the following syntax.
```lean
def matchDiscr := parser! optional (try (ident >> checkNoWsBefore "no space before ':'" >> ":")) >> termParser
def «match» := parser!:leadPrec "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> matchAlts
```
-/
structure MatchAltView where
ref : Syntax
patterns : Array Syntax
rhs : Syntax
deriving Inhabited
private def expandSimpleMatch (stx discr lhsVar rhs : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do
let newStx ← `(let $lhsVar := $discr; $rhs)
withMacroExpansion stx newStx $ elabTerm newStx expectedType?
private def expandSimpleMatchWithType (stx discr lhsVar type rhs : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do
let newStx ← `(let $lhsVar : $type := $discr; $rhs)
withMacroExpansion stx newStx $ elabTerm newStx expectedType?
private def elabDiscrsWitMatchType (discrStxs : Array Syntax) (matchType : Expr) (expectedType : Expr) : TermElabM (Array Expr) := do
let mut discrs := #[]
let mut i := 0
let mut matchType := matchType
for discrStx in discrStxs do
i := i + 1
matchType ← whnf matchType
match matchType with
| Expr.forallE _ d b _ =>
let discr ← fullApproxDefEq $ elabTermEnsuringType discrStx[1] d
trace[Elab.match]! "discr #{i} {discr} : {d}"
matchType ← b.instantiate1 discr
discrs := discrs.push discr
| _ =>
throwError! "invalid type provided to match-expression, function type with arity #{discrStxs.size} expected"
pure discrs
private def mkUserNameFor (e : Expr) : TermElabM Name :=
match e with
| Expr.fvar fvarId _ => do pure (← getLocalDecl fvarId).userName
| _ => mkFreshBinderName
-- `expandNonAtomicDiscrs?` create auxiliary variables with base name `_discr`
private def isAuxDiscrName (n : Name) : Bool :=
n.eraseMacroScopes == `_discr
-- See expandNonAtomicDiscrs?
private def elabAtomicDiscr (discr : Syntax) : TermElabM Expr := do
let term := discr[1]
match (← isLocalIdent? term) with
| some e@(Expr.fvar fvarId _) =>
let localDecl ← getLocalDecl fvarId
if !isAuxDiscrName localDecl.userName then
pure e -- it is not an auxiliary local created by `expandNonAtomicDiscrs?`
else
pure localDecl.value
| _ => throwErrorAt discr "unexpected discriminant"
private def elabMatchTypeAndDiscrs (discrStxs : Array Syntax) (matchOptType : Syntax) (matchAltViews : Array MatchAltView) (expectedType : Expr)
: TermElabM (Array Expr × Expr × Array MatchAltView) := do
let numDiscrs := discrStxs.size
if matchOptType.isNone then
let rec loop (i : Nat) (discrs : Array Expr) (matchType : Expr) (matchAltViews : Array MatchAltView) := do
match i with
| 0 => pure (discrs.reverse, matchType, matchAltViews)
| i+1 =>
let discrStx := discrStxs[i]
let discr ← elabAtomicDiscr discrStx
let discr ← instantiateMVars discr
let discrType ← inferType discr
let discrType ← instantiateMVars discrType
let matchTypeBody ← kabstract matchType discr
let userName ← mkUserNameFor discr
if discrStx[0].isNone then
loop i (discrs.push discr) (Lean.mkForall userName BinderInfo.default discrType matchTypeBody) matchAltViews
else
let identStx := discrStx[0][0]
withLocalDeclD userName discrType fun x => do
let eqType ← mkEq discr x
withLocalDeclD identStx.getId eqType fun h => do
let matchTypeBody := matchTypeBody.instantiate1 x
let matchType ← mkForallFVars #[x, h] matchTypeBody
let refl ← mkEqRefl discr
let discrs := (discrs.push refl).push discr
let matchAltViews := matchAltViews.map fun altView =>
{ altView with patterns := altView.patterns.insertAt (i+1) identStx }
loop i discrs matchType matchAltViews
loop discrStxs.size #[] expectedType matchAltViews
else
let matchTypeStx := matchOptType[0][1]
let matchType ← elabType matchTypeStx
let discrs ← elabDiscrsWitMatchType discrStxs matchType expectedType
pure (discrs, matchType, matchAltViews)
def expandMacrosInPatterns (matchAlts : Array MatchAltView) : MacroM (Array MatchAltView) := do
matchAlts.mapM fun matchAlt => do
let patterns ← matchAlt.patterns.mapM expandMacros
pure { matchAlt with patterns := patterns }
/- Given `stx` a match-expression, return its alternatives. -/
private def getMatchAlts : Syntax → Array MatchAltView
| `(match $discrs,* $[: $ty?]? with $alts:matchAlt*) =>
alts.map fun alt => match alt with
| `(matchAltExpr| | $patterns,* => $rhs) => {
ref := alt,
patterns := patterns,
rhs := rhs
}
| _ => unreachable!
| _ => unreachable!
/--
Auxiliary annotation used to mark terms marked with the "inaccessible" annotation `.(t)` and
`_` in patterns. -/
def mkInaccessible (e : Expr) : Expr :=
mkAnnotation `_inaccessible e
def inaccessible? (e : Expr) : Option Expr :=
annotation? `_inaccessible e
inductive PatternVar where
| localVar (userName : Name)
-- anonymous variables (`_`) are encoded using metavariables
| anonymousVar (mvarId : MVarId)
instance : ToString PatternVar := ⟨fun
| PatternVar.localVar x => toString x
| PatternVar.anonymousVar mvarId => s!"?m{mvarId}"⟩
builtin_initialize Parser.registerBuiltinNodeKind `MVarWithIdKind
/--
Create an auxiliary Syntax node wrapping a fresh metavariable id.
We use this kind of Syntax for representing `_` occurring in patterns.
The metavariables are created before we elaborate the patterns into `Expr`s. -/
private def mkMVarSyntax : TermElabM Syntax := do
let mvarId ← mkFreshId
pure $ Syntax.node `MVarWithIdKind #[Syntax.node mvarId #[]]
/-- Given a syntax node constructed using `mkMVarSyntax`, return its MVarId -/
private def getMVarSyntaxMVarId (stx : Syntax) : MVarId :=
stx[0].getKind
/--
The elaboration function for `Syntax` created using `mkMVarSyntax`.
It just converts the metavariable id wrapped by the Syntax into an `Expr`. -/
@[builtinTermElab MVarWithIdKind] def elabMVarWithIdKind : TermElab := fun stx expectedType? =>
pure $ mkInaccessible $ mkMVar (getMVarSyntaxMVarId stx)
@[builtinTermElab inaccessible] def elabInaccessible : TermElab := fun stx expectedType? => do
let e ← elabTerm stx[1] expectedType?
pure $ mkInaccessible e
/-
Patterns define new local variables.
This module collect them and preprocess `_` occurring in patterns.
Recall that an `_` may represent anonymous variables or inaccessible terms
that are implied by typing constraints. Thus, we represent them with fresh named holes `?x`.
After we elaborate the pattern, if the metavariable remains unassigned, we transform it into
a regular pattern variable. Otherwise, it becomes an inaccessible term.
Macros occurring in patterns are expanded before the `collectPatternVars` method is executed.
The following kinds of Syntax are handled by this module
- Constructor applications
- Applications of functions tagged with the `[matchPattern]` attribute
- Identifiers
- Anonymous constructors
- Structure instances
- Inaccessible terms
- Named patterns
- Tuple literals
- Type ascriptions
- Literals: num, string and char
-/
namespace CollectPatternVars
structure State where
found : NameSet := {}
vars : Array PatternVar := #[]
abbrev M := StateRefT State TermElabM
private def throwCtorExpected {α} : M α :=
throwError "invalid pattern, constructor or constant marked with '[matchPattern]' expected"
private def getNumExplicitCtorParams (ctorVal : ConstructorVal) : TermElabM Nat :=
forallBoundedTelescope ctorVal.type ctorVal.nparams fun ps _ => do
let mut result := 0
for p in ps do
let localDecl ← getLocalDecl p.fvarId!
if localDecl.binderInfo.isExplicit then
result := result+1
pure result
private def throwInvalidPattern {α} : M α :=
throwError "invalid pattern"
namespace CtorApp
/-
An application in a pattern can be
1- A constructor application
The elaborator assumes fields are accessible and inductive parameters are not accessible.
2- A regular application `(f ...)` where `f` is tagged with `[matchPattern]`.
The elaborator assumes implicit arguments are not accessible and explicit ones are accessible.
-/
structure Context where
funId : Syntax
ctorVal? : Option ConstructorVal -- It is `some`, if constructor application
explicit : Bool
ellipsis : Bool
paramDecls : Array LocalDecl
paramDeclIdx : Nat := 0
namedArgs : Array NamedArg
args : List Arg
newArgs : Array Syntax := #[]
deriving Inhabited
private def isDone (ctx : Context) : Bool :=
ctx.paramDeclIdx ≥ ctx.paramDecls.size
private def finalize (ctx : Context) : M Syntax := do
if ctx.namedArgs.isEmpty && ctx.args.isEmpty then
let fStx ← `(@$(ctx.funId):ident)
pure $ Syntax.mkApp fStx ctx.newArgs
else
throwError "too many arguments"
private def isNextArgAccessible (ctx : Context) : Bool :=
let i := ctx.paramDeclIdx
match ctx.ctorVal? with
| some ctorVal => i ≥ ctorVal.nparams -- For constructor applications only fields are accessible
| none =>
if h : i < ctx.paramDecls.size then
-- For `[matchPattern]` applications, only explicit parameters are accessible.
let d := ctx.paramDecls.get ⟨i, h⟩
d.binderInfo.isExplicit
else
false
private def getNextParam (ctx : Context) : LocalDecl × Context :=
let i := ctx.paramDeclIdx
let d := ctx.paramDecls[i]
(d, { ctx with paramDeclIdx := ctx.paramDeclIdx + 1 })
private def pushNewArg (collect : Syntax → M Syntax) (accessible : Bool) (ctx : Context) (arg : Arg) : M Context :=
match arg with
| Arg.stx stx => do
let stx ← if accessible then collect stx else pure stx
pure { ctx with newArgs := ctx.newArgs.push stx }
| _ => unreachable!
private def processExplicitArg (collect : Syntax → M Syntax) (accessible : Bool) (ctx : Context) : M Context :=
match ctx.args with
| [] =>
if ctx.ellipsis then do
let hole ← `(_)
pushNewArg collect accessible ctx (Arg.stx hole)
else
throwError! "explicit parameter is missing, unused named arguments {ctx.namedArgs.map fun narg => narg.name}"
| arg::args => do
let ctx := { ctx with args := args }
pushNewArg collect accessible ctx arg
private def processImplicitArg (collect : Syntax → M Syntax) (accessible : Bool) (ctx : Context) : M Context :=
if ctx.explicit then
processExplicitArg collect accessible ctx
else do
let hole ← `(_)
pushNewArg collect accessible ctx (Arg.stx hole)
private partial def processCtorAppAux (collect : Syntax → M Syntax) (ctx : Context) : M Syntax := do
if isDone ctx then
finalize ctx
else
let accessible := isNextArgAccessible ctx
let (d, ctx) := getNextParam ctx
match ctx.namedArgs.findIdx? fun namedArg => namedArg.name == d.userName with
| some idx =>
let arg := ctx.namedArgs[idx]
let ctx := { ctx with namedArgs := ctx.namedArgs.eraseIdx idx }
let ctx ← pushNewArg collect accessible ctx arg.val
processCtorAppAux collect ctx
| none =>
let ctx ← match d.binderInfo with
| BinderInfo.implicit => processImplicitArg collect accessible ctx
| BinderInfo.instImplicit => processImplicitArg collect accessible ctx
| _ => processExplicitArg collect accessible ctx
processCtorAppAux collect ctx
def processCtorApp (collect : Syntax → M Syntax) (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (ellipsis : Bool) : M Syntax := do
let args := args.toList
let (fId, explicit) ← match f with
| `($fId:ident) => pure (fId, false)
| `(@$fId:ident) => pure (fId, true)
| _ => throwError "identifier expected"
let some (Expr.const fName _ _) ← resolveId? fId "pattern" | throwCtorExpected
let fInfo ← getConstInfo fName
forallTelescopeReducing fInfo.type fun xs _ => do
let paramDecls ← xs.mapM (getFVarLocalDecl ·)
match fInfo with
| ConstantInfo.ctorInfo val =>
processCtorAppAux collect
{ funId := fId, explicit := explicit, ctorVal? := val, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis }
| _ =>
let env ← getEnv
if hasMatchPatternAttribute env fName then
processCtorAppAux collect
{ funId := fId, explicit := explicit, ctorVal? := none, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis }
else
throwCtorExpected
end CtorApp
def processCtorApp (collect : Syntax → M Syntax) (stx : Syntax) : M Syntax := do
let (f, namedArgs, args, ellipsis) ← liftM $ expandApp stx true
CtorApp.processCtorApp collect f namedArgs args ellipsis
def processCtor (collect : Syntax → M Syntax) (stx : Syntax) : M Syntax := do
CtorApp.processCtorApp collect stx #[] #[] false
private def processVar (idStx : Syntax) : M Syntax := do
unless idStx.isIdent do
throwErrorAt idStx "identifier expected"
let id := idStx.getId
unless id.eraseMacroScopes.isAtomic do throwError "invalid pattern variable, must be atomic"
let s ← get
if s.found.contains id then throwError! "invalid pattern, variable '{id}' occurred more than once"
modify fun s => { s with vars := s.vars.push (PatternVar.localVar id), found := s.found.insert id }
pure idStx
/- Check whether `stx` is a pattern variable or constructor-like (i.e., constructor or constant tagged with `[matchPattern]` attribute) -/
private def processId (collect : Syntax → M Syntax) (stx : Syntax) : M Syntax := do
let env ← getEnv
match (← resolveId? stx "pattern") with
| none => processVar stx
| some f => match f with
| Expr.const fName _ _ =>
match env.find? fName with
| some (ConstantInfo.ctorInfo _) => processCtor collect stx
| some _ =>
if hasMatchPatternAttribute env fName then
processCtor collect stx
else
processVar stx
| none => throwCtorExpected
| _ => processVar stx
private def nameToPattern : Name → TermElabM Syntax
| Name.anonymous => `(Name.anonymous)
| Name.str p s _ => do let p ← nameToPattern p; `(Name.str $p $(quote s) _)
| Name.num p n _ => do let p ← nameToPattern p; `(Name.num $p $(quote n) _)
private def quotedNameToPattern (stx : Syntax) : TermElabM Syntax :=
match stx[0].isNameLit? with
| some val => nameToPattern val
| none => throwIllFormedSyntax
partial def collect : Syntax → M Syntax
| stx@(Syntax.node k args) => withRef stx $ withFreshMacroScope do
if k == `Lean.Parser.Term.app then
processCtorApp collect stx
else if k == `Lean.Parser.Term.anonymousCtor then
let elems ← args[1].getArgs.mapSepElemsM collect
pure $ Syntax.node k (args.set! 1 $ mkNullNode elems)
else if k == `Lean.Parser.Term.structInst then
/-
```
parser! "{" >> optional (atomic (termParser >> " with "))
>> manyIndent (group (structInstField >> optional ", "))
>> optional ".."
>> optional (" : " >> termParser)
>> " }"
``` -/
let withMod := args[1]
unless withMod.isNone do
throwErrorAt withMod "invalid struct instance pattern, 'with' is not allowed in patterns"
let fields ← args[2].getArgs.mapM fun p => do
-- p is of the form (group (structInstField >> optional ", "))
let field := p[0]
-- parser! structInstLVal >> " := " >> termParser
let newVal ← collect field[2]
let field := field.setArg 2 newVal
pure <| field.setArg 0 field
pure <| Syntax.node k (args.set! 2 <| mkNullNode fields)
else if k == `Lean.Parser.Term.hole then
let r ← mkMVarSyntax
modify fun s => { s with vars := s.vars.push $ PatternVar.anonymousVar $ getMVarSyntaxMVarId r }
pure r
else if k == `Lean.Parser.Term.paren then
let arg := args[1]
if arg.isNone then
pure stx -- `()`
else
let t := arg[0]
let s := arg[1]
if s.isNone || s[0].getKind == `Lean.Parser.Term.typeAscription then
-- Ignore `s`, since it empty or it is a type ascription
let t ← collect t
let arg := arg.setArg 0 t
pure $ Syntax.node k (args.set! 1 arg)
else
-- Tuple literal is a constructor
let t ← collect t
let arg := arg.setArg 0 t
let tupleTail := s[0]
let tupleTailElems := tupleTail[1].getArgs
let tupleTailElems ← tupleTailElems.mapSepElemsM collect
let tupleTail := tupleTail.setArg 1 $ mkNullNode tupleTailElems
let s := s.setArg 0 tupleTail
let arg := arg.setArg 1 s
pure $ Syntax.node k (args.set! 1 arg)
else if k == `Lean.Parser.Term.explicitUniv then
processCtor collect stx[0]
else if k == `Lean.Parser.Term.namedPattern then
/- Recall that
def namedPattern := check... >> tparser! "@" >> termParser -/
let id := stx[0]
discard <| processVar id
let pat := stx[2]
let pat ← collect pat
`(_root_.namedPattern $id $pat)
else if k == `Lean.Parser.Term.inaccessible then
pure stx
else if k == strLitKind then
pure stx
else if k == numLitKind then
pure stx
else if k == scientificLitKind then
pure stx
else if k == charLitKind then
pure stx
else if k == `Lean.Parser.Term.quotedName then
/- Quoted names have an elaboration function associated with them, and they will not be macro expanded.
Note that macro expansion is not a good option since it produces a term using the smart constructors `Name.mkStr`, `Name.mkNum`
instead of the constructors `Name.str` and `Name.num` -/
quotedNameToPattern stx
else if k == choiceKind then
throwError "invalid pattern, notation is ambiguous"
else
throwInvalidPattern
| stx@(Syntax.ident _ _ _ _) =>
processId collect stx
| stx =>
throwInvalidPattern
def main (alt : MatchAltView) : M MatchAltView := do
let patterns ← alt.patterns.mapM fun p => do
trace[Elab.match]! "collecting variables at pattern: {p}"
collect p
pure { alt with patterns := patterns }
end CollectPatternVars
private def collectPatternVars (alt : MatchAltView) : TermElabM (Array PatternVar × MatchAltView) := do
let (alt, s) ← (CollectPatternVars.main alt).run {}
pure (s.vars, alt)
/- Return the pattern variables in the given pattern.
Remark: this method is not used here, but in other macros (e.g., at `Do.lean`). -/
def getPatternVars (patternStx : Syntax) : TermElabM (Array PatternVar) := do
let patternStx ← liftMacroM $ expandMacros patternStx
let (_, s) ← (CollectPatternVars.collect patternStx).run {}
pure s.vars
def getPatternsVars (patterns : Array Syntax) : TermElabM (Array PatternVar) := do
let collect : CollectPatternVars.M Unit := do
for pattern in patterns do
discard <| CollectPatternVars.collect (← liftMacroM $ expandMacros pattern)
let (_, s) ← collect.run {}
pure s.vars
/- We convert the collected `PatternVar`s intro `PatternVarDecl` -/
inductive PatternVarDecl where
/- For `anonymousVar`, we create both a metavariable and a free variable. The free variable is used as an assignment for the metavariable
when it is not assigned during pattern elaboration. -/
| anonymousVar (mvarId : MVarId) (fvarId : FVarId)
| localVar (fvarId : FVarId)
private partial def withPatternVars {α} (pVars : Array PatternVar) (k : Array PatternVarDecl → TermElabM α) : TermElabM α :=
let rec loop (i : Nat) (decls : Array PatternVarDecl) := do
if h : i < pVars.size then
match pVars.get ⟨i, h⟩ with
| PatternVar.anonymousVar mvarId =>
let type ← mkFreshTypeMVar
let userName ← mkFreshBinderName
withLocalDecl userName BinderInfo.default type fun x =>
loop (i+1) (decls.push (PatternVarDecl.anonymousVar mvarId x.fvarId!))
| PatternVar.localVar userName =>
let type ← mkFreshTypeMVar
withLocalDecl userName BinderInfo.default type fun x =>
loop (i+1) (decls.push (PatternVarDecl.localVar x.fvarId!))
else
/- We must create the metavariables for `PatternVar.anonymousVar` AFTER we create the new local decls using `withLocalDecl`.
Reason: their scope must include the new local decls since some of them are assigned by typing constraints. -/
decls.forM fun decl => match decl with
| PatternVarDecl.anonymousVar mvarId fvarId => do
let type ← inferType (mkFVar fvarId)
discard <| mkFreshExprMVarWithId mvarId type
| _ => pure ()
k decls
loop 0 #[]
private def elabPatterns (patternStxs : Array Syntax) (matchType : Expr) : TermElabM (Array Expr × Expr) := do
let mut patterns := #[]
let mut matchType := matchType
for patternStx in patternStxs do
matchType ← whnf matchType
match matchType with
| Expr.forallE _ d b _ =>
let pattern ← elabTermEnsuringType patternStx d
matchType := b.instantiate1 pattern
patterns := patterns.push pattern
| _ => throwError "unexpected match type"
pure (patterns, matchType)
def finalizePatternDecls (patternVarDecls : Array PatternVarDecl) : TermElabM (Array LocalDecl) := do
let mut decls := #[]
for pdecl in patternVarDecls do
match pdecl with
| PatternVarDecl.localVar fvarId =>
let decl ← getLocalDecl fvarId
let decl ← instantiateLocalDeclMVars decl
decls := decls.push decl
| PatternVarDecl.anonymousVar mvarId fvarId =>
let e ← instantiateMVars (mkMVar mvarId);
trace[Elab.match]! "finalizePatternDecls: mvarId: {mvarId} := {e}, fvar: {mkFVar fvarId}"
match e with
| Expr.mvar newMVarId _ =>
/- Metavariable was not assigned, or assigned to another metavariable. So,
we assign to the auxiliary free variable we created at `withPatternVars` to `newMVarId`. -/
assignExprMVar newMVarId (mkFVar fvarId)
trace[Elab.match]! "finalizePatternDecls: {mkMVar newMVarId} := {mkFVar fvarId}"
let decl ← getLocalDecl fvarId
let decl ← instantiateLocalDeclMVars decl
decls := decls.push decl
| _ => pure ()
pure decls
open Meta.Match (Pattern Pattern.var Pattern.inaccessible Pattern.ctor Pattern.as Pattern.val Pattern.arrayLit AltLHS MatcherResult)
namespace ToDepElimPattern
structure State where
found : NameSet := {}
localDecls : Array LocalDecl
newLocals : NameSet := {}
abbrev M := StateRefT State TermElabM
private def alreadyVisited (fvarId : FVarId) : M Bool := do
let s ← get
pure $ s.found.contains fvarId
private def markAsVisited (fvarId : FVarId) : M Unit :=
modify fun s => { s with found := s.found.insert fvarId }
private def throwInvalidPattern {α} (e : Expr) : M α :=
throwError! "invalid pattern {indentExpr e}"
/- Create a new LocalDecl `x` for the metavariable `mvar`, and return `Pattern.var x` -/
private def mkLocalDeclFor (mvar : Expr) : M Pattern := do
let mvarId := mvar.mvarId!
let s ← get
match (← getExprMVarAssignment? mvarId) with
| some val => pure $ Pattern.inaccessible val
| none =>
let fvarId ← mkFreshId
let type ← inferType mvar
/- HACK: `fvarId` is not in the scope of `mvarId`
If this generates problems in the future, we should update the metavariable declarations. -/
assignExprMVar mvarId (mkFVar fvarId)
let userName ← liftM $ mkFreshBinderName
let newDecl := LocalDecl.cdecl arbitrary fvarId userName type BinderInfo.default;
modify fun s =>
{ s with
newLocals := s.newLocals.insert fvarId,
localDecls :=
match s.localDecls.findIdx? fun decl => mvar.occurs decl.type with
| none => s.localDecls.push newDecl -- None of the existing declarations depend on `mvar`
| some i => s.localDecls.insertAt i newDecl }
pure $ Pattern.var fvarId
partial def main (e : Expr) : M Pattern := do
let isLocalDecl (fvarId : FVarId) : M Bool := do
let s ← get
pure $ s.localDecls.any fun d => d.fvarId == fvarId
let mkPatternVar (fvarId : FVarId) (e : Expr) : M Pattern := do
if (← alreadyVisited fvarId) then
pure $ Pattern.inaccessible e
else
markAsVisited fvarId
pure $ Pattern.var e.fvarId!
let mkInaccessible (e : Expr) : M Pattern := do
match e with
| Expr.fvar fvarId _ =>
if (← isLocalDecl fvarId) then
mkPatternVar fvarId e
else
pure $ Pattern.inaccessible e
| _ =>
pure $ Pattern.inaccessible e
match inaccessible? e with
| some t => mkInaccessible t
| none =>
match e.arrayLit? with
| some (α, lits) =>
let ps ← lits.mapM main;
pure $ Pattern.arrayLit α ps
| none =>
if e.isAppOfArity `namedPattern 3 then
let p ← main $ e.getArg! 2;
match e.getArg! 1 with
| Expr.fvar fvarId _ => pure $ Pattern.as fvarId p
| _ => throwError "unexpected occurrence of auxiliary declaration 'namedPattern'"
else if e.isNatLit || e.isStringLit || e.isCharLit then
pure $ Pattern.val e
else if e.isFVar then
let fvarId := e.fvarId!
unless(← isLocalDecl fvarId) do throwInvalidPattern e
mkPatternVar fvarId e
else if e.isMVar then
mkLocalDeclFor e
else
let newE ← whnf e
if newE != e then
main newE
else matchConstCtor e.getAppFn (fun _ => throwInvalidPattern e) fun v us => do
let args := e.getAppArgs
unless args.size == v.nparams + v.nfields do
throwInvalidPattern e
let params := args.extract 0 v.nparams
let fields := args.extract v.nparams args.size
let fields ← fields.mapM main
pure $ Pattern.ctor v.name us params.toList fields.toList
end ToDepElimPattern
def withDepElimPatterns {α} (localDecls : Array LocalDecl) (ps : Array Expr) (k : Array LocalDecl → Array Pattern → TermElabM α) : TermElabM α := do
let (patterns, s) ← (ps.mapM ToDepElimPattern.main).run { localDecls := localDecls }
let localDecls ← s.localDecls.mapM fun d => instantiateLocalDeclMVars d
/- toDepElimPatterns may have added new localDecls. Thus, we must update the local context before we execute `k` -/
let lctx ← getLCtx
let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.erase d.fvarId) lctx
let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.addDecl d) lctx
withTheReader Meta.Context (fun ctx => { ctx with lctx := lctx }) $ k localDecls patterns
private def withElaboratedLHS {α} (ref : Syntax) (patternVarDecls : Array PatternVarDecl) (patternStxs : Array Syntax) (matchType : Expr)
(k : AltLHS → Expr → TermElabM α) : TermElabM α := do
let (patterns, matchType) ← withSynthesize $ elabPatterns patternStxs matchType
let localDecls ← finalizePatternDecls patternVarDecls
let patterns ← patterns.mapM (instantiateMVars ·)
withDepElimPatterns localDecls patterns fun localDecls patterns =>
k { ref := ref, fvarDecls := localDecls.toList, patterns := patterns.toList } matchType
def elabMatchAltView (alt : MatchAltView) (matchType : Expr) : TermElabM (AltLHS × Expr) := withRef alt.ref do
let (patternVars, alt) ← collectPatternVars alt
trace[Elab.match]! "patternVars: {patternVars}"
withPatternVars patternVars fun patternVarDecls => do
withElaboratedLHS alt.ref patternVarDecls alt.patterns matchType fun altLHS matchType => do
let rhs ← elabTermEnsuringType alt.rhs matchType
let xs := altLHS.fvarDecls.toArray.map LocalDecl.toExpr
let rhs ← if xs.isEmpty then pure $ mkSimpleThunk rhs else mkLambdaFVars xs rhs
trace[Elab.match]! "rhs: {rhs}"
pure (altLHS, rhs)
def mkMatcher (elimName : Name) (matchType : Expr) (numDiscrs : Nat) (lhss : List AltLHS) : TermElabM MatcherResult :=
liftMetaM $ Meta.Match.mkMatcher elimName matchType numDiscrs lhss
builtin_initialize
registerOption `match.ignoreUnusedAlts { defValue := false, group := "", descr := "if true, do not generate error if an alternative is not used" }
def ignoreUnusedAlts (opts : Options) : Bool :=
opts.get `match.ignoreUnusedAlts false
def reportMatcherResultErrors (altLHSS : List AltLHS) (result : MatcherResult) : TermElabM Unit := do
unless result.counterExamples.isEmpty do
withHeadRefOnly <| throwError! "missing cases:\n{Meta.Match.counterExamplesToMessageData result.counterExamples}"
unless ignoreUnusedAlts (← getOptions) || result.unusedAltIdxs.isEmpty do
let mut i := 0
for alt in altLHSS do
if result.unusedAltIdxs.contains i then
withRef alt.ref do
logError "redundant alternative"
i := i + 1
private def elabMatchAux (discrStxs : Array Syntax) (altViews : Array MatchAltView) (matchOptType : Syntax) (expectedType : Expr)
: TermElabM Expr := do
let (discrs, matchType, altViews) ← elabMatchTypeAndDiscrs discrStxs matchOptType altViews expectedType
let matchAlts ← liftMacroM $ expandMacrosInPatterns altViews
trace[Elab.match]! "matchType: {matchType}"
let alts ← matchAlts.mapM $ fun alt => elabMatchAltView alt matchType
/-
We should not use `synthesizeSyntheticMVarsNoPostponing` here. Otherwise, we will not be
able to elaborate examples such as:
```
def f (x : Nat) : Option Nat := none
def g (xs : List (Nat × Nat)) : IO Unit :=
xs.forM fun x =>
match f x.fst with
| _ => pure ()
```
If `synthesizeSyntheticMVarsNoPostponing`, the example above fails at `x.fst` because
the type of `x` is only available after we proces the last argument of `List.forM`.
We apply pending default types to make sure we can process examples such as
```
let (a, b) := (0, 0)
```
-/
synthesizeSyntheticMVarsUsingDefault
let rhss := alts.map Prod.snd
let matchType ← instantiateMVars matchType
let altLHSS ← alts.toList.mapM fun alt => do
let altLHS ← Match.instantiateAltLHSMVars alt.1
withRef altLHS.ref do
for d in altLHS.fvarDecls do
if d.hasExprMVar then
withExistingLocalDecls altLHS.fvarDecls do
throwMVarError m!"invalid match-expression, type of pattern variable '{d.toExpr}' contains metavariables{indentExpr d.type}"
for p in altLHS.patterns do
if p.hasExprMVar then
withExistingLocalDecls altLHS.fvarDecls do
throwMVarError m!"invalid match-expression, pattern contains metavariables{indentExpr (← p.toExpr)}"
pure altLHS
let numDiscrs := discrs.size
let matcherName ← mkAuxName `match
let matcherResult ← mkMatcher matcherName matchType numDiscrs altLHSS
let motive ← forallBoundedTelescope matchType numDiscrs fun xs matchType => mkLambdaFVars xs matchType
reportMatcherResultErrors altLHSS matcherResult
let r := mkApp matcherResult.matcher motive
let r := mkAppN r discrs
let r := mkAppN r rhss
trace[Elab.match]! "result: {r}"
pure r
private def getDiscrs (matchStx : Syntax) : Array Syntax :=
matchStx[1].getSepArgs
private def getMatchOptType (matchStx : Syntax) : Syntax :=
matchStx[2]
private def expandNonAtomicDiscrs? (matchStx : Syntax) : TermElabM (Option Syntax) :=
let matchOptType := getMatchOptType matchStx;
if matchOptType.isNone then do
let discrs := getDiscrs matchStx;
let allLocal ← discrs.allM fun discr => Option.isSome <$> isLocalIdent? discr[1]
if allLocal then
pure none
else
let rec loop (discrs : List Syntax) (discrsNew : Array Syntax) := do
match discrs with
| [] =>
let discrs := Syntax.mkSep discrsNew (mkAtomFrom matchStx ", ");
pure (matchStx.setArg 1 discrs)
| discr :: discrs =>
-- Recall that
-- matchDiscr := parser! optional (ident >> ":") >> termParser
let term := discr[1]
match (← isLocalIdent? term) with
| some _ => loop discrs (discrsNew.push discr)
| none => withFreshMacroScope do
let d ← `(_discr);
unless isAuxDiscrName d.getId do -- Use assertion?
throwError "unexpected internal auxiliary discriminant name"
let discrNew := discr.setArg 1 d;
let r ← loop discrs (discrsNew.push discrNew)
`(let _discr := $term; $r)
pure (some (← loop discrs.toList #[]))
else
-- We do not pull non atomic discriminants when match type is provided explicitly by the user
pure none
private def waitExpectedType (expectedType? : Option Expr) : TermElabM Expr := do
tryPostponeIfNoneOrMVar expectedType?
match expectedType? with
| some expectedType => pure expectedType
| none => mkFreshTypeMVar
private def tryPostponeIfDiscrTypeIsMVar (matchStx : Syntax) : TermElabM Unit := do
-- We don't wait for the discriminants types when match type is provided by user
if getMatchOptType matchStx |>.isNone then
let discrs := getDiscrs matchStx
for discr in discrs do
let term := discr[1]
match (← isLocalIdent? term) with
| none => throwErrorAt discr "unexpected discriminant" -- see `expandNonAtomicDiscrs?
| some d =>
let dType ← inferType d
trace[Elab.match]! "discr {d} : {dType}"
tryPostponeIfMVar dType
/-
We (try to) elaborate a `match` only when the expected type is available.
If the `matchType` has not been provided by the user, we also try to postpone elaboration if the type
of a discriminant is not available. That is, it is of the form `(?m ...)`.
We use `expandNonAtomicDiscrs?` to make sure all discriminants are local variables.
This is a standard trick we use in the elaborator, and it is also used to elaborate structure instances.
Suppose, we are trying to elaborate
```
match g x with
| ... => ...
```
`expandNonAtomicDiscrs?` converts it intro
```
let _discr := g x
match _discr with
| ... => ...
```
Thus, at `tryPostponeIfDiscrTypeIsMVar` we only need to check whether the type of `_discr` is not of the form `(?m ...)`.
Note that, the auxiliary variable `_discr` is expanded at `elabAtomicDiscr`.
This elaboration technique is needed to elaborate terms such as:
```lean
xs.filter fun (a, b) => a > b
```
which are syntax sugar for
```lean
List.filter (fun p => match p with | (a, b) => a > b) xs
```
When we visit `match p with | (a, b) => a > b`, we don't know the type of `p` yet.
-/
private def waitExpectedTypeAndDiscrs (matchStx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do
tryPostponeIfNoneOrMVar expectedType?
tryPostponeIfDiscrTypeIsMVar matchStx
match expectedType? with
| some expectedType => pure expectedType
| none => mkFreshTypeMVar
/-
```
parser!:leadPrec "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> matchAlts
```
Remark the `optIdent` must be `none` at `matchDiscr`. They are expanded by `expandMatchDiscr?`.
-/
private def elabMatchCore (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do
let expectedType ← waitExpectedTypeAndDiscrs stx expectedType?
let discrStxs := (getDiscrs stx).map fun d => d
let altViews := getMatchAlts stx
let matchOptType := getMatchOptType stx
elabMatchAux discrStxs altViews matchOptType expectedType
private def isPatternVar (stx : Syntax) : TermElabM Bool := do
match (← resolveId? stx "pattern") with
| none => isAtomicIdent stx
| some f => match f with
| Expr.const fName _ _ =>
match (← getEnv).find? fName with
| some (ConstantInfo.ctorInfo _) => return false
| _ => isAtomicIdent stx
| _ => isAtomicIdent stx
where
isAtomicIdent (stx : Syntax) : Bool :=
stx.isIdent && stx.getId.eraseMacroScopes.isAtomic
-- parser! "match " >> sepBy1 termParser ", " >> optType >> " with " >> matchAlts
@[builtinTermElab «match»] def elabMatch : TermElab := fun stx expectedType? => do
match stx with
| `(match $discr:term with | $y:ident => $rhs:term) =>
if (← isPatternVar y) then expandSimpleMatch stx discr y rhs expectedType? else elabMatchDefault stx expectedType?
| `(match $discr:term : $type with | $y:ident => $rhs:term) =>
if (← isPatternVar y) then expandSimpleMatchWithType stx discr y type rhs expectedType? else elabMatchDefault stx expectedType?
| _ => elabMatchDefault stx expectedType?
where
elabMatchDefault (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do
match (← expandNonAtomicDiscrs? stx) with
| some stxNew => withMacroExpansion stx stxNew $ elabTerm stxNew expectedType?
| none =>
let discrs := getDiscrs stx;
let matchOptType := getMatchOptType stx;
if !matchOptType.isNone && discrs.any fun d => !d[0].isNone then
throwErrorAt matchOptType "match expected type should not be provided when discriminants with equality proofs are used"
elabMatchCore stx expectedType?
@[builtinInit] private def regTraceClasses : IO Unit := do
registerTraceClass `Elab.match;
pure ()
-- parser!:leadPrec "nomatch " >> termParser
@[builtinTermElab «nomatch»] def elabNoMatch : TermElab := fun stx expectedType? =>
match stx with
| `(nomatch $discrExpr) => do
let expectedType ← waitExpectedType expectedType?
let discr := Syntax.node `Lean.Parser.Term.matchDiscr #[mkNullNode, discrExpr]
elabMatchAux #[discr] #[] mkNullNode expectedType
| _ => throwUnsupportedSyntax
end Term
end Elab
end Lean
|
ab4013604a386877b6d6e067c1f54e4a96d36de8 | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/algebra/big_operators/order.lean | 8a1280d278565600717b5f1c20bccc6d5e410c71 | [
"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 | 14,464 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import algebra.big_operators.basic
/-!
# Results about big operators with values in an ordered algebraic structure.
Mostly monotonicity results for the `∑` operation.
-/
universes u v w
open_locale big_operators
variables {α : Type u} {β : Type v} {γ : Type w}
namespace finset
variables {s s₁ s₂ : finset α} {a : α} {f g : α → β}
lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_add_comm_monoid β]
(f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : finset γ) (g : γ → α) :
f (∑ x in s, g x) ≤ ∑ x in s, f (g x) :=
begin
refine le_trans (multiset.le_sum_of_subadditive f h_zero h_add _) _,
rw [multiset.map_map],
refl
end
lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {f : β → α} {s : finset β} :
abs (∑ x in s, f x) ≤ ∑ x in s, abs (f x) :=
le_sum_of_subadditive _ abs_zero abs_add s f
section ordered_add_comm_monoid
variables [ordered_add_comm_monoid β]
lemma sum_le_sum : (∀x∈s, f x ≤ g x) → (∑ x in s, f x) ≤ (∑ x in s, g x) :=
begin
classical,
apply finset.induction_on s,
exact (λ _, le_refl _),
assume a s ha ih h,
have : f a + (∑ x in s, f x) ≤ g a + (∑ x in s, g x),
from add_le_add (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx),
by simpa only [sum_insert ha]
end
theorem card_le_mul_card_image_of_maps_to [decidable_eq γ] {f : α → γ} {s : finset α} {t : finset γ}
(Hf : ∀ a ∈ s, f a ∈ t) (n : ℕ) (hn : ∀ a ∈ t, (s.filter (λ x, f x = a)).card ≤ n) :
s.card ≤ n * t.card :=
calc s.card = (∑ a in t, (s.filter (λ x, f x = a)).card) : card_eq_sum_card_fiberwise Hf
... ≤ (∑ _ in t, n) : sum_le_sum hn
... = _ : by simp [mul_comm]
theorem card_le_mul_card_image [decidable_eq γ] {f : α → γ} (s : finset α)
(n : ℕ) (hn : ∀ a ∈ s.image f, (s.filter (λ x, f x = a)).card ≤ n) :
s.card ≤ n * (s.image f).card :=
card_le_mul_card_image_of_maps_to (λ x, mem_image_of_mem _) n hn
theorem mul_card_image_le_card_of_maps_to [decidable_eq γ] {f : α → γ} {s : finset α} {t : finset γ}
(Hf : ∀ a ∈ s, f a ∈ t) (n : ℕ) (hn : ∀ a ∈ t, n ≤ (s.filter (λ x, f x = a)).card) :
n * t.card ≤ s.card :=
calc n * t.card = (∑ _ in t, n) : by simp [mul_comm]
... ≤ (∑ a in t, (s.filter (λ x, f x = a)).card) : sum_le_sum hn
... = s.card : by rw ← card_eq_sum_card_fiberwise Hf
theorem mul_card_image_le_card [decidable_eq γ] {f : α → γ} (s : finset α)
(n : ℕ) (hn : ∀ a ∈ s.image f, n ≤ (s.filter (λ x, f x = a)).card) :
n * (s.image f).card ≤ s.card :=
mul_card_image_le_card_of_maps_to (λ x, mem_image_of_mem _) n hn
lemma sum_nonneg (h : ∀x∈s, 0 ≤ f x) : 0 ≤ (∑ x in s, f x) :=
le_trans (by rw [sum_const_zero]) (sum_le_sum h)
lemma sum_nonpos (h : ∀x∈s, f x ≤ 0) : (∑ x in s, f x) ≤ 0 :=
le_trans (sum_le_sum h) (by rw [sum_const_zero])
lemma sum_le_sum_of_subset_of_nonneg
(h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → 0 ≤ f x) : (∑ x in s₁, f x) ≤ (∑ x in s₂, f x) :=
by classical;
calc (∑ x in s₁, f x) ≤ (∑ x in s₂ \ s₁, f x) + (∑ x in s₁, f x) :
le_add_of_nonneg_left $ sum_nonneg $ by simpa only [mem_sdiff, and_imp]
... = ∑ x in s₂ \ s₁ ∪ s₁, f x : (sum_union sdiff_disjoint).symm
... = (∑ x in s₂, f x) : by rw [sdiff_union_of_subset h]
lemma sum_mono_set_of_nonneg (hf : ∀ x, 0 ≤ f x) : monotone (λ s, ∑ x in s, f x) :=
λ s₁ s₂ hs, sum_le_sum_of_subset_of_nonneg hs $ λ x _ _, hf x
lemma sum_fiberwise_le_sum_of_sum_fiber_nonneg [decidable_eq γ] {s : finset α} {t : finset γ}
{g : α → γ} {f : α → β} (h : ∀ y ∉ t, (0 : β) ≤ ∑ x in s.filter (λ x, g x = y), f x) :
(∑ y in t, ∑ x in s.filter (λ x, g x = y), f x) ≤ ∑ x in s, f x :=
calc (∑ y in t, ∑ x in s.filter (λ x, g x = y), f x) ≤
(∑ y in t ∪ s.image g, ∑ x in s.filter (λ x, g x = y), f x) :
sum_le_sum_of_subset_of_nonneg (subset_union_left _ _) $ λ y hyts, h y
... = ∑ x in s, f x :
sum_fiberwise_of_maps_to (λ x hx, mem_union.2 $ or.inr $ mem_image_of_mem _ hx) _
lemma sum_le_sum_fiberwise_of_sum_fiber_nonpos [decidable_eq γ] {s : finset α} {t : finset γ}
{g : α → γ} {f : α → β} (h : ∀ y ∉ t, (∑ x in s.filter (λ x, g x = y), f x) ≤ 0) :
(∑ x in s, f x) ≤ ∑ y in t, ∑ x in s.filter (λ x, g x = y), f x :=
@sum_fiberwise_le_sum_of_sum_fiber_nonneg α (order_dual β) _ _ _ _ _ _ _ h
lemma sum_eq_zero_iff_of_nonneg : (∀x∈s, 0 ≤ f x) → ((∑ x in s, f x) = 0 ↔ ∀x∈s, f x = 0) :=
begin
classical,
apply finset.induction_on s,
exact λ _, ⟨λ _ _, false.elim, λ _, rfl⟩,
assume a s ha ih H,
have : ∀ x ∈ s, 0 ≤ f x, from λ _, H _ ∘ mem_insert_of_mem,
rw [sum_insert ha, add_eq_zero_iff' (H _ $ mem_insert_self _ _) (sum_nonneg this),
forall_mem_insert, ih this]
end
lemma sum_eq_zero_iff_of_nonpos : (∀x∈s, f x ≤ 0) → ((∑ x in s, f x) = 0 ↔ ∀x∈s, f x = 0) :=
@sum_eq_zero_iff_of_nonneg _ (order_dual β) _ _ _
lemma single_le_sum (hf : ∀x∈s, 0 ≤ f x) {a} (h : a ∈ s) : f a ≤ (∑ x in s, f x) :=
have ∑ x in {a}, f x ≤ (∑ x in s, f x),
from sum_le_sum_of_subset_of_nonneg
(λ x e, (mem_singleton.1 e).symm ▸ h) (λ x h _, hf x h),
by rwa sum_singleton at this
end ordered_add_comm_monoid
section canonically_ordered_add_monoid
variables [canonically_ordered_add_monoid β]
@[simp] lemma sum_eq_zero_iff : ∑ x in s, f x = 0 ↔ ∀ x ∈ s, f x = 0 :=
sum_eq_zero_iff_of_nonneg $ λ x hx, zero_le (f x)
lemma sum_le_sum_of_subset (h : s₁ ⊆ s₂) : (∑ x in s₁, f x) ≤ (∑ x in s₂, f x) :=
sum_le_sum_of_subset_of_nonneg h $ assume x h₁ h₂, zero_le _
lemma sum_mono_set (f : α → β) : monotone (λ s, ∑ x in s, f x) :=
λ s₁ s₂ hs, sum_le_sum_of_subset hs
lemma sum_le_sum_of_ne_zero (h : ∀x∈s₁, f x ≠ 0 → x ∈ s₂) :
(∑ x in s₁, f x) ≤ (∑ x in s₂, f x) :=
by classical;
calc (∑ x in s₁, f x) = ∑ x in s₁.filter (λx, f x = 0), f x + ∑ x in s₁.filter (λx, f x ≠ 0), f x :
by rw [←sum_union, filter_union_filter_neg_eq];
exact disjoint_filter.2 (assume _ _ h n_h, n_h h)
... ≤ (∑ x in s₂, f x) : add_le_of_nonpos_of_le'
(sum_nonpos $ by simp only [mem_filter, and_imp]; exact λ _ _, le_of_eq)
(sum_le_sum_of_subset $ by simpa only [subset_iff, mem_filter, and_imp])
end canonically_ordered_add_monoid
section ordered_cancel_comm_monoid
variables [ordered_cancel_add_comm_monoid β]
theorem sum_lt_sum (Hle : ∀ i ∈ s, f i ≤ g i) (Hlt : ∃ i ∈ s, f i < g i) :
(∑ x in s, f x) < (∑ x in s, g x) :=
begin
classical,
rcases Hlt with ⟨i, hi, hlt⟩,
rw [← insert_erase hi, sum_insert (not_mem_erase _ _), sum_insert (not_mem_erase _ _)],
exact add_lt_add_of_lt_of_le hlt (sum_le_sum $ λ j hj, Hle j $ mem_of_mem_erase hj)
end
lemma sum_lt_sum_of_nonempty (hs : s.nonempty) (Hlt : ∀ x ∈ s, f x < g x) :
(∑ x in s, f x) < (∑ x in s, g x) :=
begin
apply sum_lt_sum,
{ intros i hi, apply le_of_lt (Hlt i hi) },
cases hs with i hi,
exact ⟨i, hi, Hlt i hi⟩,
end
lemma sum_lt_sum_of_subset [decidable_eq α]
(h : s₁ ⊆ s₂) {i : α} (hi : i ∈ s₂ \ s₁) (hpos : 0 < f i) (hnonneg : ∀ j ∈ s₂ \ s₁, 0 ≤ f j) :
(∑ x in s₁, f x) < (∑ x in s₂, f x) :=
calc (∑ x in s₁, f x) < (∑ x in insert i s₁, f x) :
begin
simp only [mem_sdiff] at hi,
rw sum_insert hi.2,
exact lt_add_of_pos_left (∑ x in s₁, f x) hpos,
end
... ≤ (∑ x in s₂, f x) :
begin
simp only [mem_sdiff] at hi,
apply sum_le_sum_of_subset_of_nonneg,
{ simp [finset.insert_subset, h, hi.1] },
{ assume x hx h'x,
apply hnonneg x,
simp [mem_insert, not_or_distrib] at h'x,
rw mem_sdiff,
simp [hx, h'x] }
end
end ordered_cancel_comm_monoid
section decidable_linear_ordered_cancel_comm_monoid
variables [decidable_linear_ordered_cancel_add_comm_monoid β]
theorem exists_lt_of_sum_lt (Hlt : (∑ x in s, f x) < ∑ x in s, g x) :
∃ i ∈ s, f i < g i :=
begin
contrapose! Hlt with Hle,
exact sum_le_sum Hle
end
theorem exists_le_of_sum_le (hs : s.nonempty) (Hle : (∑ x in s, f x) ≤ ∑ x in s, g x) :
∃ i ∈ s, f i ≤ g i :=
begin
contrapose! Hle with Hlt,
rcases hs with ⟨i, hi⟩,
exact sum_lt_sum (λ i hi, le_of_lt (Hlt i hi)) ⟨i, hi, Hlt i hi⟩
end
lemma exists_pos_of_sum_zero_of_exists_nonzero (f : α → β)
(h₁ : ∑ e in s, f e = 0) (h₂ : ∃ x ∈ s, f x ≠ 0) :
∃ x ∈ s, 0 < f x :=
begin
contrapose! h₁,
obtain ⟨x, m, x_nz⟩ : ∃ x ∈ s, f x ≠ 0 := h₂,
apply ne_of_lt,
calc ∑ e in s, f e < ∑ e in s, 0 : sum_lt_sum h₁ ⟨x, m, lt_of_le_of_ne (h₁ x m) x_nz⟩
... = 0 : by rw [finset.sum_const, nsmul_zero],
end
end decidable_linear_ordered_cancel_comm_monoid
section linear_ordered_comm_ring
variables [linear_ordered_comm_ring β]
open_locale classical
/- this is also true for a ordered commutative multiplicative monoid -/
lemma prod_nonneg {s : finset α} {f : α → β}
(h0 : ∀(x ∈ s), 0 ≤ f x) : 0 ≤ (∏ x in s, f x) :=
prod_induction f (λ x, 0 ≤ x) (λ _ _ ha hb, mul_nonneg ha hb) zero_le_one h0
/- this is also true for a ordered commutative multiplicative monoid -/
lemma prod_pos {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 < f x) : 0 < (∏ x in s, f x) :=
prod_induction f (λ x, 0 < x) (λ _ _ ha hb, mul_pos ha hb) zero_lt_one h0
/- this is also true for a ordered commutative multiplicative monoid -/
lemma prod_le_prod {s : finset α} {f g : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x)
(h1 : ∀(x ∈ s), f x ≤ g x) : (∏ x in s, f x) ≤ (∏ x in s, g x) :=
begin
induction s using finset.induction with a s has ih h,
{ simp },
{ simp [has], apply mul_le_mul,
exact h1 a (mem_insert_self a s),
apply ih (λ x H, h0 _ _) (λ x H, h1 _ _); exact (mem_insert_of_mem H),
apply prod_nonneg (λ x H, h0 x (mem_insert_of_mem H)),
apply le_trans (h0 a (mem_insert_self a s)) (h1 a (mem_insert_self a s)) }
end
lemma prod_le_one {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x)
(h1 : ∀(x ∈ s), f x ≤ 1) : (∏ x in s, f x) ≤ 1 :=
begin
convert ← prod_le_prod h0 h1,
exact finset.prod_const_one
end
/-- If `g, h ≤ f` and `g i + h i ≤ f i`, then the product of `f` over `s` is at least the
sum of the products of `g` and `h`. This is the version for `linear_ordered_comm_ring`. -/
lemma prod_add_prod_le {s : finset α} {i : α} {f g h : α → β}
(hi : i ∈ s) (h2i : g i + h i ≤ f i) (hgf : ∀ j ∈ s, j ≠ i → g j ≤ f j)
(hhf : ∀ j ∈ s, j ≠ i → h j ≤ f j) (hg : ∀ i ∈ s, 0 ≤ g i) (hh : ∀ i ∈ s, 0 ≤ h i) :
∏ i in s, g i + ∏ i in s, h i ≤ ∏ i in s, f i :=
begin
simp_rw [← mul_prod_diff_singleton hi],
refine le_trans _ (mul_le_mul_of_nonneg_right h2i _),
{ rw [right_distrib],
apply add_le_add; apply mul_le_mul_of_nonneg_left; try { apply prod_le_prod };
simp only [and_imp, mem_sdiff, mem_singleton]; intros; apply_assumption; assumption },
{ apply prod_nonneg, simp only [and_imp, mem_sdiff, mem_singleton],
intros j h1j h2j, refine le_trans (hg j h1j) (hgf j h1j h2j) }
end
end linear_ordered_comm_ring
section canonically_ordered_comm_semiring
variables [canonically_ordered_comm_semiring β]
lemma prod_le_prod' {s : finset α} {f g : α → β} (h : ∀ i ∈ s, f i ≤ g i) :
(∏ x in s, f x) ≤ (∏ x in s, g x) :=
begin
classical,
induction s using finset.induction with a s has ih h,
{ simp },
{ rw [finset.prod_insert has, finset.prod_insert has],
apply canonically_ordered_semiring.mul_le_mul,
{ exact h _ (finset.mem_insert_self a s) },
{ exact ih (λ i hi, h _ (finset.mem_insert_of_mem hi)) } }
end
/-- If `g, h ≤ f` and `g i + h i ≤ f i`, then the product of `f` over `s` is at least the
sum of the products of `g` and `h`. This is the version for `canonically_ordered_comm_semiring`.
-/
lemma prod_add_prod_le' {s : finset α} {i : α} {f g h : α → β} (hi : i ∈ s) (h2i : g i + h i ≤ f i)
(hgf : ∀ j ∈ s, j ≠ i → g j ≤ f j) (hhf : ∀ j ∈ s, j ≠ i → h j ≤ f j) :
∏ i in s, g i + ∏ i in s, h i ≤ ∏ i in s, f i :=
begin
classical, simp_rw [← mul_prod_diff_singleton hi],
refine le_trans _ (canonically_ordered_semiring.mul_le_mul_right' h2i _),
rw [right_distrib],
apply add_le_add; apply canonically_ordered_semiring.mul_le_mul_left'; apply prod_le_prod';
simp only [and_imp, mem_sdiff, mem_singleton]; intros; apply_assumption; assumption
end
end canonically_ordered_comm_semiring
end finset
namespace with_top
open finset
open_locale classical
/-- A sum of finite numbers is still finite -/
lemma sum_lt_top [ordered_add_comm_monoid β] {s : finset α} {f : α → with_top β} :
(∀a∈s, f a < ⊤) → (∑ x in s, f x) < ⊤ :=
λ h, sum_induction f (λ a, a < ⊤) (by { simp_rw add_lt_top, tauto }) zero_lt_top h
/-- A sum of finite numbers is still finite -/
lemma sum_lt_top_iff [canonically_ordered_add_monoid β] {s : finset α} {f : α → with_top β} :
(∑ x in s, f x) < ⊤ ↔ (∀a∈s, f a < ⊤) :=
iff.intro (λh a ha, lt_of_le_of_lt (single_le_sum (λa ha, zero_le _) ha) h) sum_lt_top
/-- A sum of numbers is infinite iff one of them is infinite -/
lemma sum_eq_top_iff [canonically_ordered_add_monoid β] {s : finset α} {f : α → with_top β} :
(∑ x in s, f x) = ⊤ ↔ (∃a∈s, f a = ⊤) :=
begin
rw ← not_iff_not,
push_neg,
simp only [← lt_top_iff_ne_top],
exact sum_lt_top_iff
end
open opposite
/-- Moving to the opposite additive commutative monoid commutes with summing. -/
@[simp] lemma op_sum [add_comm_monoid β] {s : finset α} (f : α → β) :
op (∑ x in s, f x) = ∑ x in s, op (f x) :=
(@op_add_hom β _).map_sum _ _
@[simp] lemma unop_sum [add_comm_monoid β] {s : finset α} (f : α → βᵒᵖ) :
unop (∑ x in s, f x) = ∑ x in s, unop (f x) :=
(@unop_add_hom β _).map_sum _ _
end with_top
|
00bc8aaab124f6e5c800af5ae4df90ae33ea2153 | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /tests/lean/run/basic_monitor1.lean | 300a4517cfd930d98cb71b1efca23688b83fc81a | [
"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 | 279 | lean | meta def basic_monitor : vm_monitor nat :=
{ init := 0, step := λ s, return (trace ("step " ++ s^.to_string) (s+1)) >> failure }
run_command vm_monitor.register `basic_monitor
set_option debugger true
def f : nat → nat
| 0 := 0
| (a+1) := f a
vm_eval trace "a" (f 4)
|
4a6a1c97047f8603cde0077d8f04aab05495fd67 | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/topology/algebra/ordered.lean | 5b74d2a11f78f384a89fb3e1eaac9bc9f11ebfd2 | [
"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 | 131,568 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Yury Kudryashov
-/
import tactic.linarith
import tactic.tfae
import algebra.archimedean
import algebra.group.pi
import algebra.ordered_ring
import order.liminf_limsup
import data.set.intervals.image_preimage
import data.set.intervals.ord_connected
import data.set.intervals.surj_on
import topology.algebra.group
import topology.extend_from_subset
import order.filter.interval
/-!
# Theory of topology on ordered spaces
## Main definitions
The order topology on an ordered space is the topology generated by all open intervals (or
equivalently by those of the form `(-∞, a)` and `(b, +∞)`). We define it as `preorder.topology α`.
However, we do *not* register it as an instance (as many existing ordered types already have
topologies, which would be equal but not definitionally equal to `preorder.topology α`). Instead,
we introduce a class `order_topology α`(which is a `Prop`, also known as a mixin) saying that on
the type `α` having already a topological space structure and a preorder structure, the topological
structure is equal to the order topology.
We also introduce another (mixin) class `order_closed_topology α` saying that the set of points
`(x, y)` with `x ≤ y` is closed in the product space. This is automatically satisfied on a linear
order with the order topology.
We prove many basic properties of such topologies.
## Main statements
This file contains the proofs of the following facts. For exact requirements (`order_closed_topology`
vs `order_topology`, `preorder` vs `partial_order` vs `linear_order` etc) see their statements.
### Open / closed sets
* `is_open_lt` : if `f` and `g` are continuous functions, then `{x | f x < g x}` is open;
* `is_open_Iio`, `is_open_Ioi`, `is_open_Ioo` : open intervals are open;
* `is_closed_le` : if `f` and `g` are continuous functions, then `{x | f x ≤ g x}` is closed;
* `is_closed_Iic`, `is_closed_Ici`, `is_closed_Icc` : closed intervals are closed;
* `frontier_le_subset_eq`, `frontier_lt_subset_eq` : frontiers of both `{x | f x ≤ g x}`
and `{x | f x < g x}` are included by `{x | f x = g x}`;
* `exists_Ioc_subset_of_mem_nhds`, `exists_Ico_subset_of_mem_nhds` : if `x < y`, then any
neighborhood of `x` includes an interval `[x, z)` for some `z ∈ (x, y]`, and any neighborhood
of `y` includes an interval `(z, y]` for some `z ∈ [x, y)`.
### Convergence and inequalities
* `le_of_tendsto_of_tendsto` : if `f` converges to `a`, `g` converges to `b`, and eventually
`f x ≤ g x`, then `a ≤ b`
* `le_of_tendsto`, `ge_of_tendsto` : if `f` converges to `a` and eventually `f x ≤ b`
(resp., `b ≤ f x`), then `a ≤ b` (resp., `b ≤ a); we also provide primed versions
that assume the inequalities to hold for all `x`.
### Min, max, `Sup` and `Inf`
* `continuous.min`, `continuous.max`: pointwise `min`/`max` of two continuous functions is
continuous.
* `tendsto.min`, `tendsto.max` : if `f` tends to `a` and `g` tends to `b`, then their pointwise
`min`/`max` tend to `min a b` and `max a b`, respectively.
* `tendsto_of_tendsto_of_tendsto_of_le_of_le` : theorem known as squeeze theorem,
sandwich theorem, theorem of Carabinieri, and two policemen (and a drunk) theorem; if `g` and `h`
both converge to `a`, and eventually `g x ≤ f x ≤ h x`, then `f` converges to `a`.
### Connected sets and Intermediate Value Theorem
* `is_preconnected_I??` : all intervals `I??` are preconnected,
* `is_preconnected.intermediate_value`, `intermediate_value_univ` : Intermediate Value Theorem for
connected sets and connected spaces, respectively;
* `intermediate_value_Icc`, `intermediate_value_Icc'`: Intermediate Value Theorem for functions
on closed intervals.
### Miscellaneous facts
* `is_compact.exists_forall_le`, `is_compact.exists_forall_ge` : extreme value theorem, a continuous
function on a compact set takes its minimum and maximum values.
* `is_closed.Icc_subset_of_forall_mem_nhds_within` : “Continuous induction” principle;
if `s ∩ [a, b]` is closed, `a ∈ s`, and for each `x ∈ [a, b) ∩ s` some of its right neighborhoods
is included `s`, then `[a, b] ⊆ s`.
* `is_closed.Icc_subset_of_forall_exists_gt`, `is_closed.mem_of_ge_of_forall_exists_gt` : two
other versions of the “continuous induction” principle.
## Implementation
We do _not_ register the order topology as an instance on a preorder (or even on a linear order).
Indeed, on many such spaces, a topology has already been constructed in a different way (think
of the discrete spaces `ℕ` or `ℤ`, or `ℝ` that could inherit a topology as the completion of `ℚ`),
and is in general not defeq to the one generated by the intervals. We make it available as a
definition `preorder.topology α` though, that can be registered as an instance when necessary, or
for specific types.
-/
open classical set filter topological_space
open function (curry uncurry)
open_locale topological_space classical filter
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
/-- A topology on a set which is both a topological space and a preorder is _order-closed_ if the
set of points `(x, y)` with `x ≤ y` is closed in the product space. We introduce this as a mixin.
This property is satisfied for the order topology on a linear order, but it can be satisfied more
generally, and suffices to derive many interesting properties relating order and topology. -/
class order_closed_topology (α : Type*) [topological_space α] [preorder α] : Prop :=
(is_closed_le' : is_closed {p:α×α | p.1 ≤ p.2})
instance : Π [topological_space α], topological_space (order_dual α) := id
section order_closed_topology
section preorder
variables [topological_space α] [preorder α] [t : order_closed_topology α]
include t
lemma is_closed_le_prod : is_closed {p : α × α | p.1 ≤ p.2} :=
t.is_closed_le'
lemma is_closed_le [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) :
is_closed {b | f b ≤ g b} :=
continuous_iff_is_closed.mp (hf.prod_mk hg) _ is_closed_le_prod
lemma is_closed_le' (a : α) : is_closed {b | b ≤ a} :=
is_closed_le continuous_id continuous_const
lemma is_closed_Iic {a : α} : is_closed (Iic a) :=
is_closed_le' a
lemma is_closed_ge' (a : α) : is_closed {b | a ≤ b} :=
is_closed_le continuous_const continuous_id
lemma is_closed_Ici {a : α} : is_closed (Ici a) :=
is_closed_ge' a
instance : order_closed_topology (order_dual α) :=
⟨continuous_swap _ (@order_closed_topology.is_closed_le' α _ _ _)⟩
lemma is_closed_Icc {a b : α} : is_closed (Icc a b) :=
is_closed_inter is_closed_Ici is_closed_Iic
@[simp] lemma closure_Icc (a b : α) : closure (Icc a b) = Icc a b :=
is_closed_Icc.closure_eq
@[simp] lemma closure_Iic (a : α) : closure (Iic a) = Iic a :=
is_closed_Iic.closure_eq
@[simp] lemma closure_Ici (a : α) : closure (Ici a) = Ici a :=
is_closed_Ici.closure_eq
lemma le_of_tendsto_of_tendsto {f g : β → α} {b : filter β} {a₁ a₂ : α} [ne_bot b]
(hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) (h : f ≤ᶠ[b] g) :
a₁ ≤ a₂ :=
have tendsto (λb, (f b, g b)) b (𝓝 (a₁, a₂)),
by rw [nhds_prod_eq]; exact hf.prod_mk hg,
show (a₁, a₂) ∈ {p:α×α | p.1 ≤ p.2},
from t.is_closed_le'.mem_of_tendsto this h
lemma le_of_tendsto_of_tendsto' {f g : β → α} {b : filter β} {a₁ a₂ : α} [ne_bot b]
(hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) (h : ∀ x, f x ≤ g x) :
a₁ ≤ a₂ :=
le_of_tendsto_of_tendsto hf hg (eventually_of_forall h)
lemma le_of_tendsto {f : β → α} {a b : α} {x : filter β}
[ne_bot x] (lim : tendsto f x (𝓝 a)) (h : ∀ᶠ c in x, f c ≤ b) : a ≤ b :=
le_of_tendsto_of_tendsto lim tendsto_const_nhds h
lemma le_of_tendsto' {f : β → α} {a b : α} {x : filter β}
[ne_bot x] (lim : tendsto f x (𝓝 a)) (h : ∀ c, f c ≤ b) : a ≤ b :=
le_of_tendsto lim (eventually_of_forall h)
lemma ge_of_tendsto {f : β → α} {a b : α} {x : filter β} [ne_bot x]
(lim : tendsto f x (𝓝 a)) (h : ∀ᶠ c in x, b ≤ f c) : b ≤ a :=
le_of_tendsto_of_tendsto tendsto_const_nhds lim h
lemma ge_of_tendsto' {f : β → α} {a b : α} {x : filter β} [ne_bot x]
(lim : tendsto f x (𝓝 a)) (h : ∀ c, b ≤ f c) : b ≤ a :=
ge_of_tendsto lim (eventually_of_forall h)
@[simp]
lemma closure_le_eq [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) :
closure {b | f b ≤ g b} = {b | f b ≤ g b} :=
(is_closed_le hf hg).closure_eq
lemma closure_lt_subset_le [topological_space β] {f g : β → α} (hf : continuous f)
(hg : continuous g) :
closure {b | f b < g b} ⊆ {b | f b ≤ g b} :=
by { rw [←closure_le_eq hf hg], exact closure_mono (λ b, le_of_lt) }
lemma continuous_within_at.closure_le [topological_space β]
{f g : β → α} {s : set β} {x : β} (hx : x ∈ closure s)
(hf : continuous_within_at f s x)
(hg : continuous_within_at g s x)
(h : ∀ y ∈ s, f y ≤ g y) : f x ≤ g x :=
show (f x, g x) ∈ {p : α × α | p.1 ≤ p.2},
from order_closed_topology.is_closed_le'.closure_subset ((hf.prod hg).mem_closure hx h)
/-- If `s` is a closed set and two functions `f` and `g` are continuous on `s`,
then the set `{x ∈ s | f x ≤ g x}` is a closed set. -/
lemma is_closed.is_closed_le [topological_space β] {f g : β → α} {s : set β} (hs : is_closed s)
(hf : continuous_on f s) (hg : continuous_on g s) :
is_closed {x ∈ s | f x ≤ g x} :=
(hf.prod hg).preimage_closed_of_closed hs order_closed_topology.is_closed_le'
omit t
lemma nhds_within_Ici_ne_bot {a b : α} (H₂ : a ≤ b) :
𝓝[Ici a] b ≠ ⊥ :=
nhds_within_ne_bot_of_mem H₂
lemma nhds_within_Ici_self_ne_bot (a : α) :
𝓝[Ici a] a ≠ ⊥ :=
nhds_within_Ici_ne_bot (le_refl a)
lemma nhds_within_Iic_ne_bot {a b : α} (H : a ≤ b) :
𝓝[Iic b] a ≠ ⊥ :=
nhds_within_ne_bot_of_mem H
lemma nhds_within_Iic_self_ne_bot (a : α) :
𝓝[Iic a] a ≠ ⊥ :=
nhds_within_Iic_ne_bot (le_refl a)
end preorder
section partial_order
variables [topological_space α] [partial_order α] [t : order_closed_topology α]
include t
private lemma is_closed_eq : is_closed {p : α × α | p.1 = p.2} :=
by simp only [le_antisymm_iff];
exact is_closed_inter t.is_closed_le' (is_closed_le continuous_snd continuous_fst)
@[priority 90] -- see Note [lower instance priority]
instance order_closed_topology.to_t2_space : t2_space α :=
{ t2 :=
have is_open {p : α × α | p.1 ≠ p.2}, from is_closed_eq,
assume a b h,
let ⟨u, v, hu, hv, ha, hb, h⟩ := is_open_prod_iff.mp this a b h in
⟨u, v, hu, hv, ha, hb,
set.eq_empty_iff_forall_not_mem.2 $ assume a ⟨h₁, h₂⟩,
have a ≠ a, from @h (a, a) ⟨h₁, h₂⟩,
this rfl⟩ }
end partial_order
section linear_order
variables [topological_space α] [linear_order α] [order_closed_topology α]
lemma is_open_lt_prod : is_open {p : α × α | p.1 < p.2} :=
by { simp_rw [← is_closed_compl_iff, compl_set_of, not_lt],
exact is_closed_le continuous_snd continuous_fst }
lemma is_open_lt [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) :
is_open {b | f b < g b} :=
by simp [lt_iff_not_ge, -not_le]; exact is_closed_le hg hf
variables {a b : α}
lemma is_open_Iio : is_open (Iio a) :=
is_open_lt continuous_id continuous_const
lemma is_open_Ioi : is_open (Ioi a) :=
is_open_lt continuous_const continuous_id
lemma is_open_Ioo : is_open (Ioo a b) :=
is_open_inter is_open_Ioi is_open_Iio
@[simp] lemma interior_Ioi : interior (Ioi a) = Ioi a :=
is_open_Ioi.interior_eq
@[simp] lemma interior_Iio : interior (Iio a) = Iio a :=
is_open_Iio.interior_eq
@[simp] lemma interior_Ioo : interior (Ioo a b) = Ioo a b :=
is_open_Ioo.interior_eq
/-- Intermediate value theorem for two functions: if `f` and `g` are two continuous functions
on a preconnected space and `f a ≤ g a` and `g b ≤ f b`, then for some `x` we have `f x = g x`. -/
lemma intermediate_value_univ₂ {γ : Type*} [topological_space γ] [preconnected_space γ] {a b : γ}
{f g : γ → α} (hf : continuous f) (hg : continuous g) (ha : f a ≤ g a) (hb : g b ≤ f b) :
∃ x, f x = g x :=
begin
obtain ⟨x, h, hfg, hgf⟩ : (univ ∩ {x | f x ≤ g x ∧ g x ≤ f x}).nonempty,
from is_preconnected_closed_iff.1 preconnected_space.is_preconnected_univ _ _
(is_closed_le hf hg) (is_closed_le hg hf) (λ x hx, le_total _ _) ⟨a, trivial, ha⟩
⟨b, trivial, hb⟩,
exact ⟨x, le_antisymm hfg hgf⟩
end
/-- Intermediate value theorem for two functions: if `f` and `g` are two functions continuous
on a preconnected set `s` and for some `a b ∈ s` we have `f a ≤ g a` and `g b ≤ f b`,
then for some `x ∈ s` we have `f x = g x`. -/
lemma is_preconnected.intermediate_value₂ {γ : Type*} [topological_space γ] {s : set γ}
(hs : is_preconnected s) {a b : γ} (ha : a ∈ s) (hb : b ∈ s) {f g : γ → α}
(hf : continuous_on f s) (hg : continuous_on g s) (ha' : f a ≤ g a) (hb' : g b ≤ f b) :
∃ x ∈ s, f x = g x :=
let ⟨x, hx⟩ := @intermediate_value_univ₂ α _ _ _ s _ (subtype.preconnected_space hs) ⟨a, ha⟩ ⟨b, hb⟩
_ _ (continuous_on_iff_continuous_restrict.1 hf) (continuous_on_iff_continuous_restrict.1 hg)
ha' hb'
in ⟨x, x.2, hx⟩
/-- Intermediate Value Theorem for continuous functions on connected sets. -/
lemma is_preconnected.intermediate_value {γ : Type*} [topological_space γ] {s : set γ}
(hs : is_preconnected s) {a b : γ} (ha : a ∈ s) (hb : b ∈ s) {f : γ → α}
(hf : continuous_on f s) :
Icc (f a) (f b) ⊆ f '' s :=
λ x hx, mem_image_iff_bex.2 $ hs.intermediate_value₂ ha hb hf continuous_on_const hx.1 hx.2
/-- Intermediate Value Theorem for continuous functions on connected spaces. -/
lemma intermediate_value_univ {γ : Type*} [topological_space γ] [preconnected_space γ]
(a b : γ) {f : γ → α} (hf : continuous f) :
Icc (f a) (f b) ⊆ range f :=
λ x hx, intermediate_value_univ₂ hf continuous_const hx.1 hx.2
/-- If a preconnected set contains endpoints of an interval, then it includes the whole interval. -/
lemma is_preconnected.Icc_subset {s : set α} (hs : is_preconnected s)
{a b : α} (ha : a ∈ s) (hb : b ∈ s) :
Icc a b ⊆ s :=
by simpa only [image_id] using hs.intermediate_value ha hb continuous_on_id
/-- If a preconnected set contains endpoints of an interval, then it includes the whole interval. -/
lemma is_connected.Icc_subset {s : set α} (hs : is_connected s)
{a b : α} (ha : a ∈ s) (hb : b ∈ s) :
Icc a b ⊆ s :=
hs.2.Icc_subset ha hb
/-- If preconnected set in a linear order space is unbounded below and above, then it is the whole
space. -/
lemma is_preconnected.eq_univ_of_unbounded {s : set α} (hs : is_preconnected s) (hb : ¬bdd_below s)
(ha : ¬bdd_above s) :
s = univ :=
begin
refine eq_univ_of_forall (λ x, _),
obtain ⟨y, ys, hy⟩ : ∃ y ∈ s, y < x := not_bdd_below_iff.1 hb x,
obtain ⟨z, zs, hz⟩ : ∃ z ∈ s, x < z := not_bdd_above_iff.1 ha x,
exact hs.Icc_subset ys zs ⟨le_of_lt hy, le_of_lt hz⟩
end
/-!
### Neighborhoods to the left and to the right on an `order_closed_topology`
Limits to the left and to the right of real functions are defined in terms of neighborhoods to
the left and to the right, either open or closed, i.e., members of `𝓝[Ioi a] a` and
`𝓝[Ici a] a` on the right, and similarly on the left. Here we simply prove that all
right-neighborhoods of a point are equal, and we'll prove later other useful characterizations which
require the stronger hypothesis `order_topology α` -/
/-!
#### Right neighborhoods, point excluded
-/
lemma Ioo_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) :
Ioo a c ∈ 𝓝[Ioi b] b :=
mem_nhds_within.2 ⟨Iio c, is_open_Iio, H.2,
by rw [inter_comm, Ioi_inter_Iio]; exact Ioo_subset_Ioo_left H.1⟩
lemma Ioc_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) :
Ioc a c ∈ 𝓝[Ioi b] b :=
mem_sets_of_superset (Ioo_mem_nhds_within_Ioi H) Ioo_subset_Ioc_self
lemma Ico_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) :
Ico a c ∈ 𝓝[Ioi b] b :=
mem_sets_of_superset (Ioo_mem_nhds_within_Ioi H) Ioo_subset_Ico_self
lemma Icc_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) :
Icc a c ∈ 𝓝[Ioi b] b :=
mem_sets_of_superset (Ioo_mem_nhds_within_Ioi H) Ioo_subset_Icc_self
@[simp] lemma nhds_within_Ioc_eq_nhds_within_Ioi {a b : α} (h : a < b) :
𝓝[Ioc a b] a = 𝓝[Ioi a] a :=
le_antisymm (nhds_within_mono _ Ioc_subset_Ioi_self) $
nhds_within_le_of_mem $ Ioc_mem_nhds_within_Ioi $ left_mem_Ico.2 h
@[simp] lemma nhds_within_Ioo_eq_nhds_within_Ioi {a b : α} (h : a < b) :
𝓝[Ioo a b] a = 𝓝[Ioi a] a :=
le_antisymm (nhds_within_mono _ Ioo_subset_Ioi_self) $
nhds_within_le_of_mem $ Ioo_mem_nhds_within_Ioi $ left_mem_Ico.2 h
@[simp]
lemma continuous_within_at_Ioc_iff_Ioi [topological_space β] {a b : α} {f : α → β} (h : a < b) :
continuous_within_at f (Ioc a b) a ↔ continuous_within_at f (Ioi a) a :=
by simp only [continuous_within_at, nhds_within_Ioc_eq_nhds_within_Ioi h]
@[simp]
lemma continuous_within_at_Ioo_iff_Ioi [topological_space β] {a b : α} {f : α → β} (h : a < b) :
continuous_within_at f (Ioo a b) a ↔ continuous_within_at f (Ioi a) a :=
by simp only [continuous_within_at, nhds_within_Ioo_eq_nhds_within_Ioi h]
/-!
#### Left neighborhoods, point excluded
-/
lemma Ioo_mem_nhds_within_Iio {a b c : α} (H : b ∈ Ioc a c) :
Ioo a c ∈ 𝓝[Iio b] b :=
by simpa only [dual_Ioo] using @Ioo_mem_nhds_within_Ioi (order_dual α) _ _ _ _ _ _ ⟨H.2, H.1⟩
lemma Ico_mem_nhds_within_Iio {a b c : α} (H : b ∈ Ioc a c) :
Ico a c ∈ 𝓝[Iio b] b :=
mem_sets_of_superset (Ioo_mem_nhds_within_Iio H) Ioo_subset_Ico_self
lemma Ioc_mem_nhds_within_Iio {a b c : α} (H : b ∈ Ioc a c) :
Ioc a c ∈ 𝓝[Iio b] b :=
mem_sets_of_superset (Ioo_mem_nhds_within_Iio H) Ioo_subset_Ioc_self
lemma Icc_mem_nhds_within_Iio {a b c : α} (H : b ∈ Ioc a c) :
Icc a c ∈ 𝓝[Iio b] b :=
mem_sets_of_superset (Ioo_mem_nhds_within_Iio H) Ioo_subset_Icc_self
@[simp] lemma nhds_within_Ico_eq_nhds_within_Iio {a b : α} (h : a < b) :
𝓝[Ico a b] b = 𝓝[Iio b] b :=
by simpa only [dual_Ioc] using @nhds_within_Ioc_eq_nhds_within_Ioi (order_dual α) _ _ _ _ _ h
@[simp] lemma nhds_within_Ioo_eq_nhds_within_Iio {a b : α} (h : a < b) :
𝓝[Ioo a b] b = 𝓝[Iio b] b :=
by simpa only [dual_Ioo] using @nhds_within_Ioo_eq_nhds_within_Ioi (order_dual α) _ _ _ _ _ h
@[simp] lemma continuous_within_at_Ico_iff_Iio [topological_space β] {a b : α} {f : α → β} (h : a < b) :
continuous_within_at f (Ico a b) b ↔ continuous_within_at f (Iio b) b :=
by simp only [continuous_within_at, nhds_within_Ico_eq_nhds_within_Iio h]
@[simp] lemma continuous_within_at_Ioo_iff_Iio [topological_space β] {a b : α} {f : α → β} (h : a < b) :
continuous_within_at f (Ioo a b) b ↔ continuous_within_at f (Iio b) b :=
by simp only [continuous_within_at, nhds_within_Ioo_eq_nhds_within_Iio h]
/-!
#### Right neighborhoods, point included
-/
lemma Ioo_mem_nhds_within_Ici {a b c : α} (H : b ∈ Ioo a c) :
Ioo a c ∈ 𝓝[Ici b] b :=
mem_nhds_within_of_mem_nhds $ mem_nhds_sets is_open_Ioo H
lemma Ioc_mem_nhds_within_Ici {a b c : α} (H : b ∈ Ioo a c) :
Ioc a c ∈ 𝓝[Ici b] b :=
mem_sets_of_superset (Ioo_mem_nhds_within_Ici H) Ioo_subset_Ioc_self
lemma Ico_mem_nhds_within_Ici {a b c : α} (H : b ∈ Ico a c) :
Ico a c ∈ 𝓝[Ici b] b :=
mem_nhds_within.2 ⟨Iio c, is_open_Iio, H.2,
by simp only [inter_comm, Ici_inter_Iio, Ico_subset_Ico_left H.1]⟩
lemma Icc_mem_nhds_within_Ici {a b c : α} (H : b ∈ Ico a c) :
Icc a c ∈ 𝓝[Ici b] b :=
mem_sets_of_superset (Ico_mem_nhds_within_Ici H) Ico_subset_Icc_self
@[simp] lemma nhds_within_Icc_eq_nhds_within_Ici {a b : α} (h : a < b) :
𝓝[Icc a b] a = 𝓝[Ici a] a :=
le_antisymm (nhds_within_mono _ Icc_subset_Ici_self) $
nhds_within_le_of_mem $ Icc_mem_nhds_within_Ici $ left_mem_Ico.2 h
@[simp] lemma nhds_within_Ico_eq_nhds_within_Ici {a b : α} (h : a < b) :
𝓝[Ico a b] a = 𝓝[Ici a] a :=
le_antisymm (nhds_within_mono _ (λ x, and.left)) $
nhds_within_le_of_mem $ Ico_mem_nhds_within_Ici $ left_mem_Ico.2 h
@[simp]
lemma continuous_within_at_Icc_iff_Ici [topological_space β] {a b : α} {f : α → β} (h : a < b) :
continuous_within_at f (Icc a b) a ↔ continuous_within_at f (Ici a) a :=
by simp only [continuous_within_at, nhds_within_Icc_eq_nhds_within_Ici h]
@[simp]
lemma continuous_within_at_Ico_iff_Ici [topological_space β] {a b : α} {f : α → β} (h : a < b) :
continuous_within_at f (Ico a b) a ↔ continuous_within_at f (Ici a) a :=
by simp only [continuous_within_at, nhds_within_Ico_eq_nhds_within_Ici h]
/-!
#### Left neighborhoods, point included
-/
lemma Ioo_mem_nhds_within_Iic {a b c : α} (H : b ∈ Ioo a c) :
Ioo a c ∈ 𝓝[Iic b] b :=
mem_nhds_within_of_mem_nhds $ mem_nhds_sets is_open_Ioo H
lemma Ico_mem_nhds_within_Iic {a b c : α} (H : b ∈ Ioo a c) :
Ico a c ∈ 𝓝[Iic b] b :=
mem_sets_of_superset (Ioo_mem_nhds_within_Iic H) Ioo_subset_Ico_self
lemma Ioc_mem_nhds_within_Iic {a b c : α} (H : b ∈ Ioc a c) :
Ioc a c ∈ 𝓝[Iic b] b :=
by simpa only [dual_Ico] using @Ico_mem_nhds_within_Ici (order_dual α) _ _ _ _ _ _ ⟨H.2, H.1⟩
lemma Icc_mem_nhds_within_Iic {a b c : α} (H : b ∈ Ioc a c) :
Icc a c ∈ 𝓝[Iic b] b :=
mem_sets_of_superset (Ioc_mem_nhds_within_Iic H) Ioc_subset_Icc_self
@[simp] lemma nhds_within_Icc_eq_nhds_within_Iic {a b : α} (h : a < b) :
𝓝[Icc a b] b = 𝓝[Iic b] b :=
by simpa only [dual_Icc] using @nhds_within_Icc_eq_nhds_within_Ici (order_dual α) _ _ _ _ _ h
@[simp] lemma nhds_within_Ioc_eq_nhds_within_Iic {a b : α} (h : a < b) :
𝓝[Ioc a b] b = 𝓝[Iic b] b :=
by simpa only [dual_Ico] using @nhds_within_Ico_eq_nhds_within_Ici (order_dual α) _ _ _ _ _ h
@[simp]
lemma continuous_within_at_Icc_iff_Iic [topological_space β] {a b : α} {f : α → β} (h : a < b) :
continuous_within_at f (Icc a b) b ↔ continuous_within_at f (Iic b) b :=
by simp only [continuous_within_at, nhds_within_Icc_eq_nhds_within_Iic h]
@[simp]
lemma continuous_within_at_Ioc_iff_Iic [topological_space β] {a b : α} {f : α → β} (h : a < b) :
continuous_within_at f (Ioc a b) b ↔ continuous_within_at f (Iic b) b :=
by simp only [continuous_within_at, nhds_within_Ioc_eq_nhds_within_Iic h]
end linear_order
section decidable_linear_order
variables [topological_space α] [decidable_linear_order α] [order_closed_topology α] {f g : β → α}
section
variables [topological_space β] (hf : continuous f) (hg : continuous g)
include hf hg
lemma frontier_le_subset_eq : frontier {b | f b ≤ g b} ⊆ {b | f b = g b} :=
begin
rw [frontier_eq_closure_inter_closure, closure_le_eq hf hg],
rintros b ⟨hb₁, hb₂⟩,
refine le_antisymm hb₁ (closure_lt_subset_le hg hf _),
convert hb₂ using 2, simp only [not_le.symm], refl
end
lemma frontier_lt_subset_eq : frontier {b | f b < g b} ⊆ {b | f b = g b} :=
by rw ← frontier_compl;
convert frontier_le_subset_eq hg hf; simp [ext_iff, eq_comm]
@[continuity] lemma continuous.min : continuous (λb, min (f b) (g b)) :=
have ∀b∈frontier {b | f b ≤ g b}, f b = g b, from assume b hb, frontier_le_subset_eq hf hg hb,
continuous_if this hf hg
@[continuity] lemma continuous.max : continuous (λb, max (f b) (g b)) :=
@continuous.min (order_dual α) _ _ _ _ _ _ _ hf hg
end
lemma tendsto.max {b : filter β} {a₁ a₂ : α} (hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) :
tendsto (λb, max (f b) (g b)) b (𝓝 (max a₁ a₂)) :=
show tendsto ((λp:α×α, max p.1 p.2) ∘ (λb, (f b, g b))) b (𝓝 (max a₁ a₂)),
from tendsto.comp
begin
rw [←nhds_prod_eq],
from continuous_iff_continuous_at.mp (continuous_fst.max continuous_snd) _
end
(hf.prod_mk hg)
lemma tendsto.min {b : filter β} {a₁ a₂ : α} (hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) :
tendsto (λb, min (f b) (g b)) b (𝓝 (min a₁ a₂)) :=
show tendsto ((λp:α×α, min p.1 p.2) ∘ (λb, (f b, g b))) b (𝓝 (min a₁ a₂)),
from tendsto.comp
begin
rw [←nhds_prod_eq],
from continuous_iff_continuous_at.mp (continuous_fst.min continuous_snd) _
end
(hf.prod_mk hg)
end decidable_linear_order
end order_closed_topology
/-- The order topology on an ordered type is the topology generated by open intervals. We register
it on a preorder, but it is mostly interesting in linear orders, where it is also order-closed.
We define it as a mixin. If you want to introduce the order topology on a preorder, use
`preorder.topology`. -/
class order_topology (α : Type*) [t : topological_space α] [preorder α] : Prop :=
(topology_eq_generate_intervals : t = generate_from {s | ∃a, s = Ioi a ∨ s = Iio a})
/-- (Order) topology on a partial order `α` generated by the subbase of open intervals
`(a, ∞) = { x ∣ a < x }, (-∞ , b) = {x ∣ x < b}` for all `a, b` in `α`. We do not register it as an
instance as many ordered sets are already endowed with the same topology, most often in a non-defeq
way though. Register as a local instance when necessary. -/
def preorder.topology (α : Type*) [preorder α] : topological_space α :=
generate_from {s : set α | ∃ (a : α), s = {b : α | a < b} ∨ s = {b : α | b < a}}
section order_topology
instance {α : Type*} [topological_space α] [partial_order α] [order_topology α] :
order_topology (order_dual α) :=
⟨by convert @order_topology.topology_eq_generate_intervals α _ _ _;
conv in (_ ∨ _) { rw or.comm }; refl⟩
section partial_order
variables [topological_space α] [partial_order α] [t : order_topology α]
include t
lemma is_open_iff_generate_intervals {s : set α} :
is_open s ↔ generate_open {s | ∃a, s = Ioi a ∨ s = Iio a} s :=
by rw [t.topology_eq_generate_intervals]; refl
lemma is_open_lt' (a : α) : is_open {b:α | a < b} :=
by rw [@is_open_iff_generate_intervals α _ _ t]; exact generate_open.basic _ ⟨a, or.inl rfl⟩
lemma is_open_gt' (a : α) : is_open {b:α | b < a} :=
by rw [@is_open_iff_generate_intervals α _ _ t]; exact generate_open.basic _ ⟨a, or.inr rfl⟩
lemma lt_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 b, a < x :=
mem_nhds_sets (is_open_lt' _) h
lemma le_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 b, a ≤ x :=
(𝓝 b).sets_of_superset (lt_mem_nhds h) $ assume b hb, le_of_lt hb
lemma gt_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 a, x < b :=
mem_nhds_sets (is_open_gt' _) h
lemma ge_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 a, x ≤ b :=
(𝓝 a).sets_of_superset (gt_mem_nhds h) $ assume b hb, le_of_lt hb
lemma nhds_eq_order (a : α) :
𝓝 a = (⨅b ∈ Iio a, 𝓟 (Ioi b)) ⊓ (⨅b ∈ Ioi a, 𝓟 (Iio b)) :=
by rw [t.topology_eq_generate_intervals, nhds_generate_from];
from le_antisymm
(le_inf
(le_infi $ assume b, le_infi $ assume hb,
infi_le_of_le {c : α | b < c} $ infi_le _ ⟨hb, b, or.inl rfl⟩)
(le_infi $ assume b, le_infi $ assume hb,
infi_le_of_le {c : α | c < b} $ infi_le _ ⟨hb, b, or.inr rfl⟩))
(le_infi $ assume s, le_infi $ assume ⟨ha, b, hs⟩,
match s, ha, hs with
| _, h, (or.inl rfl) := inf_le_left_of_le $ infi_le_of_le b $ infi_le _ h
| _, h, (or.inr rfl) := inf_le_right_of_le $ infi_le_of_le b $ infi_le _ h
end)
lemma tendsto_order {f : β → α} {a : α} {x : filter β} :
tendsto f x (𝓝 a) ↔ (∀ a' < a, ∀ᶠ b in x, a' < f b) ∧ (∀ a' > a, ∀ᶠ b in x, f b < a') :=
by simp [nhds_eq_order a, tendsto_inf, tendsto_infi, tendsto_principal]
instance tendsto_Icc_class_nhds (a : α) : tendsto_Ixx_class Icc (𝓝 a) (𝓝 a) :=
begin
simp only [nhds_eq_order, infi_subtype'],
refine ((has_basis_infi_principal_finite _).inf
(has_basis_infi_principal_finite _)).tendsto_Ixx_class (λ s hs, _),
refine (ord_connected_bInter _).inter (ord_connected_bInter _); intros _ _,
exacts [ord_connected_Ioi, ord_connected_Iio]
end
instance tendsto_Ico_class_nhds (a : α) : tendsto_Ixx_class Ico (𝓝 a) (𝓝 a) :=
tendsto_Ixx_class_of_subset (λ _ _, Ico_subset_Icc_self)
instance tendsto_Ioc_class_nhds (a : α) : tendsto_Ixx_class Ioc (𝓝 a) (𝓝 a) :=
tendsto_Ixx_class_of_subset (λ _ _, Ioc_subset_Icc_self)
instance tendsto_Ioo_class_nhds (a : α) : tendsto_Ixx_class Ioo (𝓝 a) (𝓝 a) :=
tendsto_Ixx_class_of_subset (λ _ _, Ioo_subset_Icc_self)
instance tendsto_Ixx_nhds_within (a : α) {s t : set α} {Ixx}
[tendsto_Ixx_class Ixx (𝓝 a) (𝓝 a)] [tendsto_Ixx_class Ixx (𝓟 s) (𝓟 t)]:
tendsto_Ixx_class Ixx (𝓝[s] a) (𝓝[t] a) :=
filter.tendsto_Ixx_class_inf
/-- Also known as squeeze or sandwich theorem. This version assumes that inequalities hold
eventually for the filter. -/
lemma tendsto_of_tendsto_of_tendsto_of_le_of_le' {f g h : β → α} {b : filter β} {a : α}
(hg : tendsto g b (𝓝 a)) (hh : tendsto h b (𝓝 a))
(hgf : ∀ᶠ b in b, g b ≤ f b) (hfh : ∀ᶠ b in b, f b ≤ h b) :
tendsto f b (𝓝 a) :=
tendsto_order.2
⟨assume a' h',
have ∀ᶠ b in b, a' < g b, from (tendsto_order.1 hg).left a' h',
by filter_upwards [this, hgf] assume a, lt_of_lt_of_le,
assume a' h',
have ∀ᶠ b in b, h b < a', from (tendsto_order.1 hh).right a' h',
by filter_upwards [this, hfh] assume a h₁ h₂, lt_of_le_of_lt h₂ h₁⟩
/-- Also known as squeeze or sandwich theorem. This version assumes that inequalities hold
everywhere. -/
lemma tendsto_of_tendsto_of_tendsto_of_le_of_le {f g h : β → α} {b : filter β} {a : α}
(hg : tendsto g b (𝓝 a)) (hh : tendsto h b (𝓝 a)) (hgf : g ≤ f) (hfh : f ≤ h) :
tendsto f b (𝓝 a) :=
tendsto_of_tendsto_of_tendsto_of_le_of_le' hg hh
(eventually_of_forall hgf) (eventually_of_forall hfh)
lemma nhds_order_unbounded {a : α} (hu : ∃u, a < u) (hl : ∃l, l < a) :
𝓝 a = (⨅l (h₂ : l < a) u (h₂ : a < u), 𝓟 (Ioo l u)) :=
calc 𝓝 a = (⨅b<a, 𝓟 {c | b < c}) ⊓ (⨅b>a, 𝓟 {c | c < b}) : nhds_eq_order a
... = (⨅b<a, 𝓟 {c | b < c} ⊓ (⨅b>a, 𝓟 {c | c < b})) : binfi_inf hl
... = (⨅l<a, (⨅u>a, 𝓟 {c | c < u} ⊓ 𝓟 {c | l < c})) :
begin
congr, funext x,
congr, funext hx,
rw [inf_comm],
apply binfi_inf hu
end
... = _ : by simp [inter_comm]; refl
lemma tendsto_order_unbounded {f : β → α} {a : α} {x : filter β}
(hu : ∃u, a < u) (hl : ∃l, l < a) (h : ∀l u, l < a → a < u → ∀ᶠ b in x, l < f b ∧ f b < u) :
tendsto f x (𝓝 a) :=
by rw [nhds_order_unbounded hu hl];
from (tendsto_infi.2 $ assume l, tendsto_infi.2 $ assume hl,
tendsto_infi.2 $ assume u, tendsto_infi.2 $ assume hu, tendsto_principal.2 $ h l u hl hu)
end partial_order
theorem induced_order_topology' {α : Type u} {β : Type v}
[partial_order α] [ta : topological_space β] [partial_order β] [order_topology β]
(f : α → β) (hf : ∀ {x y}, f x < f y ↔ x < y)
(H₁ : ∀ {a x}, x < f a → ∃ b < a, x ≤ f b)
(H₂ : ∀ {a x}, f a < x → ∃ b > a, f b ≤ x) :
@order_topology _ (induced f ta) _ :=
begin
letI := induced f ta,
refine ⟨eq_of_nhds_eq_nhds (λ a, _)⟩,
rw [nhds_induced, nhds_generate_from, nhds_eq_order (f a)],
apply le_antisymm,
{ refine le_infi (λ s, le_infi $ λ hs, le_principal_iff.2 _),
rcases hs with ⟨ab, b, rfl|rfl⟩,
{ exact mem_comap_sets.2 ⟨{x | f b < x},
mem_inf_sets_of_left $ mem_infi_sets _ $ mem_infi_sets (hf.2 ab) $ mem_principal_self _,
λ x, hf.1⟩ },
{ exact mem_comap_sets.2 ⟨{x | x < f b},
mem_inf_sets_of_right $ mem_infi_sets _ $ mem_infi_sets (hf.2 ab) $ mem_principal_self _,
λ x, hf.1⟩ } },
{ rw [← map_le_iff_le_comap],
refine le_inf _ _; refine le_infi (λ x, le_infi $ λ h, le_principal_iff.2 _); simp,
{ rcases H₁ h with ⟨b, ab, xb⟩,
refine mem_infi_sets _ (mem_infi_sets ⟨ab, b, or.inl rfl⟩ (mem_principal_sets.2 _)),
exact λ c hc, lt_of_le_of_lt xb (hf.2 hc) },
{ rcases H₂ h with ⟨b, ab, xb⟩,
refine mem_infi_sets _ (mem_infi_sets ⟨ab, b, or.inr rfl⟩ (mem_principal_sets.2 _)),
exact λ c hc, lt_of_lt_of_le (hf.2 hc) xb } },
end
theorem induced_order_topology {α : Type u} {β : Type v}
[partial_order α] [ta : topological_space β] [partial_order β] [order_topology β]
(f : α → β) (hf : ∀ {x y}, f x < f y ↔ x < y)
(H : ∀ {x y}, x < y → ∃ a, x < f a ∧ f a < y) :
@order_topology _ (induced f ta) _ :=
induced_order_topology' f @hf
(λ a x xa, let ⟨b, xb, ba⟩ := H xa in ⟨b, hf.1 ba, le_of_lt xb⟩)
(λ a x ax, let ⟨b, ab, bx⟩ := H ax in ⟨b, hf.1 ab, le_of_lt bx⟩)
/-- On an `ord_connected` subset of a linear order, the order topology for the restriction of the
order is the same as the restriction to the subset of the order topology. -/
instance order_topology_of_ord_connected {α : Type u}
[ta : topological_space α] [decidable_linear_order α] [order_topology α]
{t : set α} [ht : ord_connected t] :
order_topology t :=
begin
letI := induced (coe : t → α) ta,
refine ⟨eq_of_nhds_eq_nhds (λ a, _)⟩,
rw [nhds_induced, nhds_generate_from, nhds_eq_order (a : α)],
apply le_antisymm,
{ refine le_infi (λ s, le_infi $ λ hs, le_principal_iff.2 _),
rcases hs with ⟨ab, b, rfl|rfl⟩,
{ refine ⟨Ioi b, _, λ _, id⟩,
refine mem_inf_sets_of_left (mem_infi_sets b _),
exact mem_infi_sets ab (mem_principal_self (Ioi ↑b)) },
{ refine ⟨Iio b, _, λ _, id⟩,
refine mem_inf_sets_of_right (mem_infi_sets b _),
exact mem_infi_sets ab (mem_principal_self (Iio b)) } },
{ rw [← map_le_iff_le_comap],
refine le_inf _ _,
{ refine le_infi (λ x, le_infi $ λ h, le_principal_iff.2 _),
by_cases hx : x ∈ t,
{ refine mem_infi_sets (Ioi ⟨x, hx⟩) (mem_infi_sets ⟨h, ⟨⟨x, hx⟩, or.inl rfl⟩⟩ _),
exact λ _, id },
simp only [set_coe.exists, mem_set_of_eq, mem_map],
convert univ_sets _,
suffices hx' : ∀ (y : t), ↑y ∈ Ioi x,
{ simp [hx'] },
intros y,
revert hx,
contrapose!,
-- here we use the `ord_connected` hypothesis
exact λ hx, ht y.2 a.2 ⟨le_of_not_gt hx, le_of_lt h⟩ },
{ refine le_infi (λ x, le_infi $ λ h, le_principal_iff.2 _),
by_cases hx : x ∈ t,
{ refine mem_infi_sets (Iio ⟨x, hx⟩) (mem_infi_sets ⟨h, ⟨⟨x, hx⟩, or.inr rfl⟩⟩ _),
exact λ _, id },
simp only [set_coe.exists, mem_set_of_eq, mem_map],
convert univ_sets _,
suffices hx' : ∀ (y : t), ↑y ∈ Iio x,
{ simp [hx'] },
intros y,
revert hx,
contrapose!,
-- here we use the `ord_connected` hypothesis
exact λ hx, ht a.2 y.2 ⟨le_of_lt h, le_of_not_gt hx⟩ } }
end
lemma nhds_top_order [topological_space α] [order_top α] [order_topology α] :
𝓝 (⊤:α) = (⨅l (h₂ : l < ⊤), 𝓟 (Ioi l)) :=
by simp [nhds_eq_order (⊤:α)]
lemma nhds_bot_order [topological_space α] [order_bot α] [order_topology α] :
𝓝 (⊥:α) = (⨅l (h₂ : ⊥ < l), 𝓟 (Iio l)) :=
by simp [nhds_eq_order (⊥:α)]
section linear_order
variables [topological_space α] [linear_order α] [order_topology α]
lemma exists_Ioc_subset_of_mem_nhds' {a : α} {s : set α} (hs : s ∈ 𝓝 a) {l : α} (hl : l < a) :
∃ l' ∈ Ico l a, Ioc l' a ⊆ s :=
begin
rw [nhds_eq_order a] at hs,
rcases hs with ⟨t₁, ht₁, t₂, ht₂, hts⟩,
-- First we show that `t₂` includes `(-∞, a]`, so it suffices to show `(l', ∞) ⊆ t₁`
suffices : ∃ l' ∈ Ico l a, Ioi l' ⊆ t₁,
{ have A : 𝓟 (Iic a) ≤ ⨅ b ∈ Ioi a, 𝓟 (Iio b),
from (le_infi $ λ b, le_infi $ λ hb, principal_mono.2 $ Iic_subset_Iio.2 hb),
have B : t₁ ∩ Iic a ⊆ s,
from subset.trans (inter_subset_inter_right _ (A ht₂)) hts,
from this.imp (λ l', Exists.imp $ λ hl' hl x hx, B ⟨hl hx.1, hx.2⟩) },
clear hts ht₂ t₂,
-- Now we find `l` such that `(l', ∞) ⊆ t₁`
letI := classical.DLO α,
rw [mem_binfi] at ht₁,
{ rcases ht₁ with ⟨b, hb, hb'⟩,
exact ⟨max b l, ⟨le_max_right _ _, max_lt hb hl⟩,
λ x hx, hb' $ Ioi_subset_Ioi (le_max_left _ _) hx⟩ },
{ intros b hb b' hb', simp only [mem_Iio] at hb hb',
use [max b b', max_lt hb hb'],
simp [le_refl] },
exact ⟨l, hl⟩
end
lemma exists_Ico_subset_of_mem_nhds' {a : α} {s : set α} (hs : s ∈ 𝓝 a) {u : α} (hu : a < u) :
∃ u' ∈ Ioc a u, Ico a u' ⊆ s :=
begin
convert @exists_Ioc_subset_of_mem_nhds' (order_dual α) _ _ _ _ _ hs _ hu,
ext, rw [dual_Ico, dual_Ioc]
end
lemma exists_Ioc_subset_of_mem_nhds {a : α} {s : set α} (hs : s ∈ 𝓝 a) (h : ∃ l, l < a) :
∃ l < a, Ioc l a ⊆ s :=
let ⟨l', hl'⟩ := h in let ⟨l, hl⟩ := exists_Ioc_subset_of_mem_nhds' hs hl' in ⟨l, hl.fst.2, hl.snd⟩
lemma exists_Ico_subset_of_mem_nhds {a : α} {s : set α} (hs : s ∈ 𝓝 a) (h : ∃ u, a < u) :
∃ u (_ : a < u), Ico a u ⊆ s :=
let ⟨l', hl'⟩ := h in let ⟨l, hl⟩ := exists_Ico_subset_of_mem_nhds' hs hl' in ⟨l, hl.fst.1, hl.snd⟩
lemma mem_nhds_unbounded {a : α} {s : set α} (hu : ∃u, a < u) (hl : ∃l, l < a) :
s ∈ 𝓝 a ↔ (∃l u, l < a ∧ a < u ∧ ∀b, l < b → b < u → b ∈ s) :=
let ⟨l, hl'⟩ := hl, ⟨u, hu'⟩ := hu in
have 𝓝 a = (⨅p : {l // l < a} × {u // a < u}, 𝓟 (Ioo p.1.val p.2.val)),
by simp [nhds_order_unbounded hu hl, infi_subtype, infi_prod],
iff.intro
(assume hs, by rw [this] at hs; from infi_sets_induct hs
⟨l, u, hl', hu', by simp⟩
begin
intro p, rcases p with ⟨⟨l, hl⟩, ⟨u, hu⟩⟩,
simp [set.subset_def],
intros s₁ s₂ hs₁ l' hl' u' hu' hs₂,
letI := classical.DLO α,
refine ⟨max l l', _, min u u', _⟩;
simp [*, lt_min_iff, max_lt_iff] {contextual := tt}
end
(assume s₁ s₂ h ⟨l, u, h₁, h₂, h₃⟩, ⟨l, u, h₁, h₂, assume b hu hl, h $ h₃ _ hu hl⟩))
(assume ⟨l, u, hl, hu, h⟩,
by rw [this]; exact mem_infi_sets ⟨⟨l, hl⟩, ⟨u, hu⟩⟩ (assume b ⟨h₁, h₂⟩, h b h₁ h₂))
lemma order_separated {a₁ a₂ : α} (h : a₁ < a₂) :
∃u v : set α, is_open u ∧ is_open v ∧ a₁ ∈ u ∧ a₂ ∈ v ∧ (∀b₁∈u, ∀b₂∈v, b₁ < b₂) :=
match dense_or_discrete a₁ a₂ with
| or.inl ⟨a, ha₁, ha₂⟩ := ⟨{a' | a' < a}, {a' | a < a'}, is_open_gt' a, is_open_lt' a, ha₁, ha₂,
assume b₁ h₁ b₂ h₂, lt_trans h₁ h₂⟩
| or.inr ⟨h₁, h₂⟩ := ⟨{a | a < a₂}, {a | a₁ < a}, is_open_gt' a₂, is_open_lt' a₁, h, h,
assume b₁ hb₁ b₂ hb₂,
calc b₁ ≤ a₁ : h₂ _ hb₁
... < a₂ : h
... ≤ b₂ : h₁ _ hb₂⟩
end
@[priority 100] -- see Note [lower instance priority]
instance order_topology.to_order_closed_topology : order_closed_topology α :=
{ is_closed_le' :=
is_open_prod_iff.mpr $ assume a₁ a₂ (h : ¬ a₁ ≤ a₂),
have h : a₂ < a₁, from lt_of_not_ge h,
let ⟨u, v, hu, hv, ha₁, ha₂, h⟩ := order_separated h in
⟨v, u, hv, hu, ha₂, ha₁, assume ⟨b₁, b₂⟩ ⟨h₁, h₂⟩, not_le_of_gt $ h b₂ h₂ b₁ h₁⟩ }
lemma order_topology.t2_space : t2_space α := by apply_instance
@[priority 100] -- see Note [lower instance priority]
instance order_topology.regular_space : regular_space α :=
{ regular := assume s a hs ha,
have hs' : sᶜ ∈ 𝓝 a, from mem_nhds_sets hs ha,
have ∃t:set α, is_open t ∧ (∀l∈ s, l < a → l ∈ t) ∧ 𝓝[t] a = ⊥,
from by_cases
(assume h : ∃l, l < a,
let ⟨l, hl, h⟩ := exists_Ioc_subset_of_mem_nhds hs' h in
match dense_or_discrete l a with
| or.inl ⟨b, hb₁, hb₂⟩ := ⟨{a | a < b}, is_open_gt' _,
assume c hcs hca, show c < b,
from lt_of_not_ge $ assume hbc, h ⟨lt_of_lt_of_le hb₁ hbc, le_of_lt hca⟩ hcs,
inf_principal_eq_bot $ (𝓝 a).sets_of_superset (mem_nhds_sets (is_open_lt' _) hb₂) $
assume x (hx : b < x), show ¬ x < b, from not_lt.2 $ le_of_lt hx⟩
| or.inr ⟨h₁, h₂⟩ := ⟨{a' | a' < a}, is_open_gt' _, assume b hbs hba, hba,
inf_principal_eq_bot $ (𝓝 a).sets_of_superset (mem_nhds_sets (is_open_lt' _) hl) $
assume x (hx : l < x), show ¬ x < a, from not_lt.2 $ h₁ _ hx⟩
end)
(assume : ¬ ∃l, l < a, ⟨∅, is_open_empty, assume l _ hl, (this ⟨l, hl⟩).elim,
nhds_within_empty _⟩),
let ⟨t₁, ht₁o, ht₁s, ht₁a⟩ := this in
have ∃t:set α, is_open t ∧ (∀u∈ s, u>a → u ∈ t) ∧ 𝓝[t] a = ⊥,
from by_cases
(assume h : ∃u, u > a,
let ⟨u, hu, h⟩ := exists_Ico_subset_of_mem_nhds hs' h in
match dense_or_discrete a u with
| or.inl ⟨b, hb₁, hb₂⟩ := ⟨{a | b < a}, is_open_lt' _,
assume c hcs hca, show c > b,
from lt_of_not_ge $ assume hbc, h ⟨le_of_lt hca, lt_of_le_of_lt hbc hb₂⟩ hcs,
inf_principal_eq_bot $ (𝓝 a).sets_of_superset (mem_nhds_sets (is_open_gt' _) hb₁) $
assume x (hx : b > x), show ¬ x > b, from not_lt.2 $ le_of_lt hx⟩
| or.inr ⟨h₁, h₂⟩ := ⟨{a' | a' > a}, is_open_lt' _, assume b hbs hba, hba,
inf_principal_eq_bot $ (𝓝 a).sets_of_superset (mem_nhds_sets (is_open_gt' _) hu) $
assume x (hx : u > x), show ¬ x > a, from not_lt.2 $ h₂ _ hx⟩
end)
(assume : ¬ ∃u, u > a, ⟨∅, is_open_empty, assume l _ hl, (this ⟨l, hl⟩).elim,
nhds_within_empty _⟩),
let ⟨t₂, ht₂o, ht₂s, ht₂a⟩ := this in
⟨t₁ ∪ t₂, is_open_union ht₁o ht₂o,
assume x hx,
have x ≠ a, from assume eq, ha $ eq ▸ hx,
(ne_iff_lt_or_gt.mp this).imp (ht₁s _ hx) (ht₂s _ hx),
by rw [nhds_within_union, ht₁a, ht₂a, bot_sup_eq]⟩,
..order_topology.t2_space }
/-- A set is a neighborhood of `a` if and only if it contains an interval `(l, u)` containing `a`,
provided `a` is neither a bottom element nor a top element. -/
lemma mem_nhds_iff_exists_Ioo_subset' {a l' u' : α} {s : set α}
(hl' : l' < a) (hu' : a < u') :
s ∈ 𝓝 a ↔ ∃l u, a ∈ Ioo l u ∧ Ioo l u ⊆ s :=
begin
split,
{ assume h,
rcases exists_Ico_subset_of_mem_nhds' h hu' with ⟨u, au, hu⟩,
rcases exists_Ioc_subset_of_mem_nhds' h hl' with ⟨l, la, hl⟩,
refine ⟨l, u, ⟨la.2, au.1⟩, λx hx, _⟩,
cases le_total a x with hax hax,
{ exact hu ⟨hax, hx.2⟩ },
{ exact hl ⟨hx.1, hax⟩ } },
{ rintros ⟨l, u, ha, h⟩,
apply mem_sets_of_superset (mem_nhds_sets is_open_Ioo ha) h }
end
/-- A set is a neighborhood of `a` if and only if it contains an interval `(l, u)` containing `a`.
-/
lemma mem_nhds_iff_exists_Ioo_subset [no_top_order α] [no_bot_order α] {a : α} {s : set α} :
s ∈ 𝓝 a ↔ ∃l u, a ∈ Ioo l u ∧ Ioo l u ⊆ s :=
let ⟨l', hl'⟩ := no_bot a in let ⟨u', hu'⟩ := no_top a in mem_nhds_iff_exists_Ioo_subset' hl' hu'
lemma filter.eventually.exists_Ioo_subset [no_top_order α] [no_bot_order α] {a : α} {p : α → Prop}
(hp : ∀ᶠ x in 𝓝 a, p x) :
∃ l u, a ∈ Ioo l u ∧ Ioo l u ⊆ {x | p x} :=
mem_nhds_iff_exists_Ioo_subset.1 hp
lemma Iio_mem_nhds {a b : α} (h : a < b) : Iio b ∈ 𝓝 a :=
mem_nhds_sets is_open_Iio h
lemma Ioi_mem_nhds {a b : α} (h : a < b) : Ioi a ∈ 𝓝 b :=
mem_nhds_sets is_open_Ioi h
lemma Ioo_mem_nhds {a b x : α} (ha : a < x) (hb : x < b) : Ioo a b ∈ 𝓝 x :=
mem_nhds_sets is_open_Ioo ⟨ha, hb⟩
lemma disjoint_nhds_at_top [no_top_order α] (x : α) :
disjoint (𝓝 x) at_top :=
begin
rw filter.disjoint_iff,
cases no_top x with a ha,
use [Iio a, Ici a, Iio_mem_nhds ha, mem_at_top a],
rw [inter_comm, Ici_inter_Iio, Ico_self]
end
@[simp] lemma inf_nhds_at_top [no_top_order α] (x : α) :
𝓝 x ⊓ at_top = ⊥ :=
disjoint_iff.1 (disjoint_nhds_at_top x)
lemma disjoint_nhds_at_bot [no_bot_order α] (x : α) :
disjoint (𝓝 x) at_bot :=
@disjoint_nhds_at_top (order_dual α) _ _ _ _ x
@[simp] lemma inf_nhds_at_bot [no_bot_order α] (x : α) :
𝓝 x ⊓ at_bot = ⊥ :=
@inf_nhds_at_top (order_dual α) _ _ _ _ x
lemma not_tendsto_nhds_of_tendsto_at_top [no_top_order α]
{F : filter β} [ne_bot F] {f : β → α} (hf : tendsto f F at_top) (x : α) :
¬ tendsto f F (𝓝 x) :=
hf.not_tendsto (disjoint_nhds_at_top x).symm
lemma not_tendsto_at_top_of_tendsto_nhds [no_top_order α]
{F : filter β} [ne_bot F] {f : β → α} {x : α} (hf : tendsto f F (𝓝 x)) :
¬ tendsto f F at_top :=
hf.not_tendsto (disjoint_nhds_at_top x)
lemma not_tendsto_nhds_of_tendsto_at_bot [no_bot_order α]
{F : filter β} [ne_bot F] {f : β → α} (hf : tendsto f F at_bot) (x : α) :
¬ tendsto f F (𝓝 x) :=
hf.not_tendsto (disjoint_nhds_at_bot x).symm
lemma not_tendsto_at_bot_of_tendsto_nhds [no_bot_order α]
{F : filter β} [ne_bot F] {f : β → α} {x : α} (hf : tendsto f F (𝓝 x)) :
¬ tendsto f F at_bot :=
hf.not_tendsto (disjoint_nhds_at_bot x)
/-!
### Neighborhoods to the left and to the right on an `order_topology`
We've seen some properties of left and right neighborhood of a point in an `order_closed_topology`.
In an `order_topology`, such neighborhoods can be characterized as the sets containing suitable
intervals to the right or to the left of `a`. We give now these characterizations. -/
-- NB: If you extend the list, append to the end please to avoid breaking the API
/-- The following statements are equivalent:
0. `s` is a neighborhood of `a` within `(a, +∞)`
1. `s` is a neighborhood of `a` within `(a, b]`
2. `s` is a neighborhood of `a` within `(a, b)`
3. `s` includes `(a, u)` for some `u ∈ (a, b]`
4. `s` includes `(a, u)` for some `u > a` -/
lemma tfae_mem_nhds_within_Ioi {a b : α} (hab : a < b) (s : set α) :
tfae [s ∈ 𝓝[Ioi a] a, -- 0 : `s` is a neighborhood of `a` within `(a, +∞)`
s ∈ 𝓝[Ioc a b] a, -- 1 : `s` is a neighborhood of `a` within `(a, b]`
s ∈ 𝓝[Ioo a b] a, -- 2 : `s` is a neighborhood of `a` within `(a, b)`
∃ u ∈ Ioc a b, Ioo a u ⊆ s, -- 3 : `s` includes `(a, u)` for some `u ∈ (a, b]`
∃ u ∈ Ioi a, Ioo a u ⊆ s] := -- 4 : `s` includes `(a, u)` for some `u > a`
begin
tfae_have : 1 ↔ 2, by rw [nhds_within_Ioc_eq_nhds_within_Ioi hab],
tfae_have : 1 ↔ 3, by rw [nhds_within_Ioo_eq_nhds_within_Ioi hab],
tfae_have : 4 → 5, from λ ⟨u, umem, hu⟩, ⟨u, umem.1, hu⟩,
tfae_have : 5 → 1,
{ rintros ⟨u, hau, hu⟩,
exact mem_sets_of_superset (Ioo_mem_nhds_within_Ioi ⟨le_refl a, hau⟩) hu },
tfae_have : 1 → 4,
{ assume h,
rcases mem_nhds_within_iff_exists_mem_nhds_inter.1 h with ⟨v, va, hv⟩,
rcases exists_Ico_subset_of_mem_nhds' va hab with ⟨u, au, hu⟩,
refine ⟨u, au, λx hx, _⟩,
refine hv ⟨hu ⟨le_of_lt hx.1, hx.2⟩, _⟩,
exact hx.1 },
tfae_finish
end
lemma mem_nhds_within_Ioi_iff_exists_mem_Ioc_Ioo_subset {a u' : α} {s : set α} (hu' : a < u') :
s ∈ 𝓝[Ioi a] a ↔ ∃u ∈ Ioc a u', Ioo a u ⊆ s :=
(tfae_mem_nhds_within_Ioi hu' s).out 0 3
/-- A set is a neighborhood of `a` within `(a, +∞)` if and only if it contains an interval `(a, u)`
with `a < u < u'`, provided `a` is not a top element. -/
lemma mem_nhds_within_Ioi_iff_exists_Ioo_subset' {a u' : α} {s : set α} (hu' : a < u') :
s ∈ 𝓝[Ioi a] a ↔ ∃u ∈ Ioi a, Ioo a u ⊆ s :=
(tfae_mem_nhds_within_Ioi hu' s).out 0 4
/-- A set is a neighborhood of `a` within `(a, +∞)` if and only if it contains an interval `(a, u)`
with `a < u`. -/
lemma mem_nhds_within_Ioi_iff_exists_Ioo_subset [no_top_order α] {a : α} {s : set α} :
s ∈ 𝓝[Ioi a] a ↔ ∃u ∈ Ioi a, Ioo a u ⊆ s :=
let ⟨u', hu'⟩ := no_top a in mem_nhds_within_Ioi_iff_exists_Ioo_subset' hu'
/-- A set is a neighborhood of `a` within `(a, +∞)` if and only if it contains an interval `(a, u]`
with `a < u`. -/
lemma mem_nhds_within_Ioi_iff_exists_Ioc_subset [no_top_order α] [densely_ordered α]
{a : α} {s : set α} : s ∈ 𝓝[Ioi a] a ↔ ∃u ∈ Ioi a, Ioc a u ⊆ s :=
begin
rw mem_nhds_within_Ioi_iff_exists_Ioo_subset,
split,
{ rintros ⟨u, au, as⟩,
rcases exists_between au with ⟨v, hv⟩,
exact ⟨v, hv.1, λx hx, as ⟨hx.1, lt_of_le_of_lt hx.2 hv.2⟩⟩ },
{ rintros ⟨u, au, as⟩,
exact ⟨u, au, subset.trans Ioo_subset_Ioc_self as⟩ }
end
/-- The following statements are equivalent:
0. `s` is a neighborhood of `b` within `(-∞, b)`
1. `s` is a neighborhood of `b` within `[a, b)`
2. `s` is a neighborhood of `b` within `(a, b)`
3. `s` includes `(l, b)` for some `l ∈ [a, b)`
4. `s` includes `(l, b)` for some `l < b` -/
lemma tfae_mem_nhds_within_Iio {a b : α} (h : a < b) (s : set α) :
tfae [s ∈ 𝓝[Iio b] b, -- 0 : `s` is a neighborhood of `b` within `(-∞, b)`
s ∈ 𝓝[Ico a b] b, -- 1 : `s` is a neighborhood of `b` within `[a, b)`
s ∈ 𝓝[Ioo a b] b, -- 2 : `s` is a neighborhood of `b` within `(a, b)`
∃ l ∈ Ico a b, Ioo l b ⊆ s, -- 3 : `s` includes `(l, b)` for some `l ∈ [a, b)`
∃ l ∈ Iio b, Ioo l b ⊆ s] := -- 4 : `s` includes `(l, b)` for some `l < b`
begin
have := @tfae_mem_nhds_within_Ioi (order_dual α) _ _ _ _ _ h s,
-- If we call `convert` here, it generates wrong equations, so we need to simplify first
simp only [exists_prop] at this ⊢,
rw [dual_Ioi, dual_Ioc, dual_Ioo] at this,
convert this; ext l; rw [dual_Ioo]
end
lemma mem_nhds_within_Iio_iff_exists_mem_Ico_Ioo_subset {a l' : α} {s : set α} (hl' : l' < a) :
s ∈ 𝓝[Iio a] a ↔ ∃l ∈ Ico l' a, Ioo l a ⊆ s :=
(tfae_mem_nhds_within_Iio hl' s).out 0 3
/-- A set is a neighborhood of `a` within `(-∞, a)` if and only if it contains an interval `(l, a)`
with `l < a`, provided `a` is not a bottom element. -/
lemma mem_nhds_within_Iio_iff_exists_Ioo_subset' {a l' : α} {s : set α} (hl' : l' < a) :
s ∈ 𝓝[Iio a] a ↔ ∃l ∈ Iio a, Ioo l a ⊆ s :=
(tfae_mem_nhds_within_Iio hl' s).out 0 4
/-- A set is a neighborhood of `a` within `(-∞, a)` if and only if it contains an interval `(l, a)`
with `l < a`. -/
lemma mem_nhds_within_Iio_iff_exists_Ioo_subset [no_bot_order α] {a : α} {s : set α} :
s ∈ 𝓝[Iio a] a ↔ ∃l ∈ Iio a, Ioo l a ⊆ s :=
let ⟨l', hl'⟩ := no_bot a in mem_nhds_within_Iio_iff_exists_Ioo_subset' hl'
/-- A set is a neighborhood of `a` within `(-∞, a)` if and only if it contains an interval `[l, a)`
with `l < a`. -/
lemma mem_nhds_within_Iio_iff_exists_Ico_subset [no_bot_order α] [densely_ordered α]
{a : α} {s : set α} : s ∈ 𝓝[Iio a] a ↔ ∃l ∈ Iio a, Ico l a ⊆ s :=
begin
convert @mem_nhds_within_Ioi_iff_exists_Ioc_subset (order_dual α) _ _ _ _ _ _ _,
simp only [dual_Ioc], refl
end
/-- The following statements are equivalent:
0. `s` is a neighborhood of `a` within `[a, +∞)`
1. `s` is a neighborhood of `a` within `[a, b]`
2. `s` is a neighborhood of `a` within `[a, b)`
3. `s` includes `[a, u)` for some `u ∈ (a, b]`
4. `s` includes `[a, u)` for some `u > a` -/
lemma tfae_mem_nhds_within_Ici {a b : α} (hab : a < b) (s : set α) :
tfae [s ∈ 𝓝[Ici a] a, -- 0 : `s` is a neighborhood of `a` within `[a, +∞)`
s ∈ 𝓝[Icc a b] a, -- 1 : `s` is a neighborhood of `a` within `[a, b]`
s ∈ 𝓝[Ico a b] a, -- 2 : `s` is a neighborhood of `a` within `[a, b)`
∃ u ∈ Ioc a b, Ico a u ⊆ s, -- 3 : `s` includes `[a, u)` for some `u ∈ (a, b]`
∃ u ∈ Ioi a, Ico a u ⊆ s] := -- 4 : `s` includes `[a, u)` for some `u > a`
begin
tfae_have : 1 ↔ 2, by rw [nhds_within_Icc_eq_nhds_within_Ici hab],
tfae_have : 1 ↔ 3, by rw [nhds_within_Ico_eq_nhds_within_Ici hab],
tfae_have : 4 → 5, from λ ⟨u, umem, hu⟩, ⟨u, umem.1, hu⟩,
tfae_have : 5 → 1,
{ rintros ⟨u, hau, hu⟩,
exact mem_sets_of_superset (Ico_mem_nhds_within_Ici ⟨le_refl a, hau⟩) hu },
tfae_have : 1 → 4,
{ assume h,
rcases mem_nhds_within_iff_exists_mem_nhds_inter.1 h with ⟨v, va, hv⟩,
rcases exists_Ico_subset_of_mem_nhds' va hab with ⟨u, au, hu⟩,
refine ⟨u, au, λx hx, _⟩,
refine hv ⟨hu ⟨hx.1, hx.2⟩, _⟩,
exact hx.1 },
tfae_finish
end
lemma mem_nhds_within_Ici_iff_exists_mem_Ioc_Ico_subset {a u' : α} {s : set α} (hu' : a < u') :
s ∈ 𝓝[Ici a] a ↔ ∃u ∈ Ioc a u', Ico a u ⊆ s :=
(tfae_mem_nhds_within_Ici hu' s).out 0 3 (by norm_num) (by norm_num)
/-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u)`
with `a < u < u'`, provided `a` is not a top element. -/
lemma mem_nhds_within_Ici_iff_exists_Ico_subset' {a u' : α} {s : set α} (hu' : a < u') :
s ∈ 𝓝[Ici a] a ↔ ∃u ∈ Ioi a, Ico a u ⊆ s :=
(tfae_mem_nhds_within_Ici hu' s).out 0 4 (by norm_num) (by norm_num)
/-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u)`
with `a < u`. -/
lemma mem_nhds_within_Ici_iff_exists_Ico_subset [no_top_order α] {a : α} {s : set α} :
s ∈ 𝓝[Ici a] a ↔ ∃u ∈ Ioi a, Ico a u ⊆ s :=
let ⟨u', hu'⟩ := no_top a in mem_nhds_within_Ici_iff_exists_Ico_subset' hu'
/-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u]`
with `a < u`. -/
lemma mem_nhds_within_Ici_iff_exists_Icc_subset' [no_top_order α] [densely_ordered α]
{a : α} {s : set α} : s ∈ 𝓝[Ici a] a ↔ ∃u ∈ Ioi a, Icc a u ⊆ s :=
begin
rw mem_nhds_within_Ici_iff_exists_Ico_subset,
split,
{ rintros ⟨u, au, as⟩,
rcases exists_between au with ⟨v, hv⟩,
exact ⟨v, hv.1, λx hx, as ⟨hx.1, lt_of_le_of_lt hx.2 hv.2⟩⟩ },
{ rintros ⟨u, au, as⟩,
exact ⟨u, au, subset.trans Ico_subset_Icc_self as⟩ }
end
/-- The following statements are equivalent:
0. `s` is a neighborhood of `b` within `(-∞, b]`
1. `s` is a neighborhood of `b` within `[a, b]`
2. `s` is a neighborhood of `b` within `(a, b]`
3. `s` includes `(l, b]` for some `l ∈ [a, b)`
4. `s` includes `(l, b]` for some `l < b` -/
lemma tfae_mem_nhds_within_Iic {a b : α} (h : a < b) (s : set α) :
tfae [s ∈ 𝓝[Iic b] b, -- 0 : `s` is a neighborhood of `b` within `(-∞, b]`
s ∈ 𝓝[Icc a b] b, -- 1 : `s` is a neighborhood of `b` within `[a, b]`
s ∈ 𝓝[Ioc a b] b, -- 2 : `s` is a neighborhood of `b` within `(a, b]`
∃ l ∈ Ico a b, Ioc l b ⊆ s, -- 3 : `s` includes `(l, b]` for some `l ∈ [a, b)`
∃ l ∈ Iio b, Ioc l b ⊆ s] := -- 4 : `s` includes `(l, b]` for some `l < b`
begin
have := @tfae_mem_nhds_within_Ici (order_dual α) _ _ _ _ _ h s,
-- If we call `convert` here, it generates wrong equations, so we need to simplify first
simp only [exists_prop] at this ⊢,
rw [dual_Icc, dual_Ioc, dual_Ioi] at this,
convert this; ext l; rw [dual_Ico]
end
lemma mem_nhds_within_Iic_iff_exists_mem_Ico_Ioc_subset {a l' : α} {s : set α} (hl' : l' < a) :
s ∈ 𝓝[Iic a] a ↔ ∃l ∈ Ico l' a, Ioc l a ⊆ s :=
(tfae_mem_nhds_within_Iic hl' s).out 0 3 (by norm_num) (by norm_num)
/-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `(l, a]`
with `l < a`, provided `a` is not a bottom element. -/
lemma mem_nhds_within_Iic_iff_exists_Ioc_subset' {a l' : α} {s : set α} (hl' : l' < a) :
s ∈ 𝓝[Iic a] a ↔ ∃l ∈ Iio a, Ioc l a ⊆ s :=
(tfae_mem_nhds_within_Iic hl' s).out 0 4 (by norm_num) (by norm_num)
/-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `(l, a]`
with `l < a`. -/
lemma mem_nhds_within_Iic_iff_exists_Ioc_subset [no_bot_order α] {a : α} {s : set α} :
s ∈ 𝓝[Iic a] a ↔ ∃l ∈ Iio a, Ioc l a ⊆ s :=
let ⟨l', hl'⟩ := no_bot a in mem_nhds_within_Iic_iff_exists_Ioc_subset' hl'
/-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `[l, a]`
with `l < a`. -/
lemma mem_nhds_within_Iic_iff_exists_Icc_subset' [no_bot_order α] [densely_ordered α]
{a : α} {s : set α} : s ∈ 𝓝[Iic a] a ↔ ∃l ∈ Iio a, Icc l a ⊆ s :=
begin
convert @mem_nhds_within_Ici_iff_exists_Icc_subset' (order_dual α) _ _ _ _ _ _ _,
simp_rw (show ∀ u : order_dual α, @Icc (order_dual α) _ a u = @Icc α _ u a, from λ u, dual_Icc),
refl,
end
/-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u]`
with `a < u`. -/
lemma mem_nhds_within_Ici_iff_exists_Icc_subset [no_top_order α] [densely_ordered α]
{a : α} {s : set α} : s ∈ 𝓝[Ici a] a ↔ ∃u, a < u ∧ Icc a u ⊆ s :=
begin
rw mem_nhds_within_Ici_iff_exists_Ico_subset,
split,
{ rintros ⟨u, au, as⟩,
rcases exists_between au with ⟨v, hv⟩,
exact ⟨v, hv.1, λx hx, as ⟨hx.1, lt_of_le_of_lt hx.2 hv.2⟩⟩ },
{ rintros ⟨u, au, as⟩,
exact ⟨u, au, subset.trans Ico_subset_Icc_self as⟩ }
end
/-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `[l, a]`
with `l < a`. -/
lemma mem_nhds_within_Iic_iff_exists_Icc_subset [no_bot_order α] [densely_ordered α]
{a : α} {s : set α} : s ∈ 𝓝[Iic a] a ↔ ∃l, l < a ∧ Icc l a ⊆ s :=
begin
rw mem_nhds_within_Iic_iff_exists_Ioc_subset,
split,
{ rintros ⟨l, la, as⟩,
rcases exists_between la with ⟨v, hv⟩,
refine ⟨v, hv.2, λx hx, as ⟨lt_of_lt_of_le hv.1 hx.1, hx.2⟩⟩, },
{ rintros ⟨l, la, as⟩,
exact ⟨l, la, subset.trans Ioc_subset_Icc_self as⟩ }
end
section functions
variables [topological_space β] [linear_order β] [order_topology β]
/-- If `f : α → β` is strictly monotone and surjective, it is everywhere right-continuous. Superseded
later in this file by `continuous_of_strict_mono_surjective` (same assumptions). -/
lemma continuous_right_of_strict_mono_surjective
{f : α → β} (h_mono : strict_mono f) (h_surj : function.surjective f) (a : α) :
continuous_within_at f (Ici a) a :=
begin
have ha : a ∈ Ici a := left_mem_Ici,
intros s hs,
by_cases hfa_top : ∃ p, f a < p,
{ obtain ⟨q, hq, hqs⟩ : ∃ q ∈ Ioi (f a), Ico (f a) q ⊆ s :=
exists_Ico_subset_of_mem_nhds hs hfa_top,
refine mem_sets_of_superset (mem_map.2 _) hqs,
have h_surj_on := surj_on_Ici_of_monotone_surjective h_mono.monotone h_surj a,
rcases h_surj_on (Ioi_subset_Ici_self hq) with ⟨x, hx, rfl⟩,
rcases eq_or_lt_of_le hx with rfl|hax, { exact (lt_irrefl _ hq).elim },
refine mem_sets_of_superset (Ico_mem_nhds_within_Ici (left_mem_Ico.2 hax)) _,
intros z hz,
exact ⟨h_mono.monotone hz.1, h_mono hz.2⟩ },
{ push_neg at hfa_top,
have ha_top : ∀ x : α, x ≤ a := strict_mono.top_preimage_top h_mono hfa_top,
rw [Ici_singleton_of_top ha_top, nhds_within_eq_map_subtype_coe (mem_singleton a),
nhds_discrete {x : α // x ∈ {a}}],
{ exact mem_pure_sets.mpr (mem_of_nhds hs) },
{ apply_instance } }
end
/-- If `f : α → β` is strictly monotone and surjective, it is everywhere left-continuous. Superseded
later in this file by `continuous_of_strict_mono_surjective` (same assumptions). -/
lemma continuous_left_of_strict_mono_surjective
{f : α → β} (h_mono : strict_mono f) (h_surj : function.surjective f) (a : α) :
continuous_within_at f (Iic a) a :=
begin
apply @continuous_right_of_strict_mono_surjective (order_dual α) (order_dual β),
{ exact λ x y hxy, h_mono hxy },
{ simpa only [dual_Icc] }
end
end functions
end linear_order
section linear_ordered_ring
variables [topological_space α] [linear_ordered_ring α] [order_topology α]
variables {l : filter β} {f g : β → α}
/- TODO The theorems in this section ought to be written in the context of linearly ordered
(additive) commutative groups rather than linearly ordered rings; however, the former concept does
not currently exist in mathlib. -/
/-- In a linearly ordered ring with the order topology, if `f` tends to `C` and `g` tends to
`at_top` then `f + g` tends to `at_top`. -/
lemma tendsto_at_top_add_tendsto_left
{C : α} (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_top) :
tendsto (λ x, f x + g x) l at_top :=
begin
obtain ⟨C', hC'⟩ : ∃ C', C' < C := no_bot C,
refine tendsto_at_top_add_left_of_le' _ C' _ hg,
rw tendsto_order at hf,
exact (hf.1 C' hC').mp (eventually_of_forall (λ x hx, le_of_lt hx))
end
/-- In a linearly ordered ring with the order topology, if `f` tends to `C` and `g` tends to
`at_bot` then `f + g` tends to `at_bot`. -/
lemma tendsto_at_bot_add_tendsto_left
{C : α} (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_bot) :
tendsto (λ x, f x + g x) l at_bot :=
begin
obtain ⟨C', hC'⟩ : ∃ C', C < C' := no_top C,
refine tendsto_at_bot_add_left_of_ge' _ C' _ hg,
rw tendsto_order at hf,
exact (hf.2 C' hC').mp (eventually_of_forall (λ x hx, le_of_lt hx))
end
/-- In a linearly ordered ring with the order topology, if `f` tends to `at_top` and `g` tends to
`C` then `f + g` tends to `at_top`. -/
lemma tendsto_at_top_add_tendsto_right
{C : α} (hf : tendsto f l at_top) (hg : tendsto g l (𝓝 C)) :
tendsto (λ x, f x + g x) l at_top :=
begin
convert tendsto_at_top_add_tendsto_left hg hf,
ext,
exact add_comm _ _,
end
/-- In a linearly ordered ring with the order topology, if `f` tends to `at_bot` and `g` tends to
`C` then `f + g` tends to `at_bot`. -/
lemma tendsto_at_bot_add_tendsto_right
{C : α} (hf : tendsto f l at_bot) (hg : tendsto g l (𝓝 C)) :
tendsto (λ x, f x + g x) l at_bot :=
begin
convert tendsto_at_bot_add_tendsto_left hg hf,
ext,
exact add_comm _ _,
end
end linear_ordered_ring
section decidable_linear_ordered_semiring
variables [decidable_linear_ordered_semiring α] [archimedean α]
variables {l : filter β} {f : β → α}
/-- If a function tends to infinity along a filter, then this function multiplied by a positive
constant (on the left) also tends to infinity. The archimedean assumption is convenient to get a
statement that works on `ℕ`, `ℤ` and `ℝ`, although not necessary (a version in ordered fields is
given in `tendsto_at_top_mul_left'`). -/
lemma tendsto_at_top_mul_left {r : α} (hr : 0 < r) (hf : tendsto f l at_top) :
tendsto (λx, r * f x) l at_top :=
begin
apply (tendsto_at_top _ _).2 (λb, _),
obtain ⟨n : ℕ, hn : 1 ≤ n •ℕ r⟩ := archimedean.arch 1 hr,
have hn' : 1 ≤ r * n, by rwa nsmul_eq_mul' at hn,
filter_upwards [(tendsto_at_top _ _).1 hf (n * max b 0)],
assume x hx,
calc b ≤ 1 * max b 0 : by { rw [one_mul], exact le_max_left _ _ }
... ≤ (r * n) * max b 0 : mul_le_mul_of_nonneg_right hn' (le_max_right _ _)
... = r * (n * max b 0) : by rw [mul_assoc]
... ≤ r * f x : mul_le_mul_of_nonneg_left hx (le_of_lt hr)
end
/-- If a function tends to infinity along a filter, then this function multiplied by a positive
constant (on the right) also tends to infinity. The archimedean assumption is convenient to get a
statement that works on `ℕ`, `ℤ` and `ℝ`, although not necessary (a version in ordered fields is
given in `tendsto_at_top_mul_right'`). -/
lemma tendsto_at_top_mul_right {r : α} (hr : 0 < r) (hf : tendsto f l at_top) :
tendsto (λx, f x * r) l at_top :=
begin
apply (tendsto_at_top _ _).2 (λb, _),
obtain ⟨n : ℕ, hn : 1 ≤ n •ℕ r⟩ := archimedean.arch 1 hr,
have hn' : 1 ≤ (n : α) * r, by rwa nsmul_eq_mul at hn,
filter_upwards [(tendsto_at_top _ _).1 hf (max b 0 * n)],
assume x hx,
calc b ≤ max b 0 * 1 : by { rw [mul_one], exact le_max_left _ _ }
... ≤ max b 0 * (n * r) : mul_le_mul_of_nonneg_left hn' (le_max_right _ _)
... = (max b 0 * n) * r : by rw [mul_assoc]
... ≤ f x * r : mul_le_mul_of_nonneg_right hx (le_of_lt hr)
end
end decidable_linear_ordered_semiring
section linear_ordered_field
variables [linear_ordered_field α]
variables {l : filter β} {f g : β → α}
/-- If a function tends to infinity along a filter, then this function multiplied by a positive
constant (on the left) also tends to infinity. For a version working in `ℕ` or `ℤ`, use
`tendsto_at_top_mul_left` instead. -/
lemma tendsto_at_top_mul_left' {r : α} (hr : 0 < r) (hf : tendsto f l at_top) :
tendsto (λx, r * f x) l at_top :=
begin
apply (tendsto_at_top _ _).2 (λb, _),
filter_upwards [(tendsto_at_top _ _).1 hf (b/r)],
assume x hx,
simpa [div_le_iff' hr] using hx
end
/-- If a function tends to infinity along a filter, then this function multiplied by a positive
constant (on the right) also tends to infinity. For a version working in `ℕ` or `ℤ`, use
`tendsto_at_top_mul_right` instead. -/
lemma tendsto_at_top_mul_right' {r : α} (hr : 0 < r) (hf : tendsto f l at_top) :
tendsto (λx, f x * r) l at_top :=
by simpa [mul_comm] using tendsto_at_top_mul_left' hr hf
/-- If a function tends to infinity along a filter, then this function divided by a positive
constant also tends to infinity. -/
lemma tendsto_at_top_div {r : α} (hr : 0 < r) (hf : tendsto f l at_top) :
tendsto (λx, f x / r) l at_top :=
tendsto_at_top_mul_right' (inv_pos.2 hr) hf
variables [topological_space α] [order_topology α]
/-- In a linearly ordered field with the order topology, if `f` tends to `at_top` and `g` tends to
a positive constant `C` then `f * g` tends to `at_top`. -/
lemma tendsto_mul_at_top {C : α} (hC : 0 < C) (hf : tendsto f l at_top) (hg : tendsto g l (𝓝 C)) :
tendsto (λ x, (f x * g x)) l at_top :=
begin
rw tendsto_at_top at hf ⊢,
rw tendsto_order at hg,
intro b,
refine (hf (b/(C/2))).mp ((hg.1 (C/2) (half_lt_self hC)).mp ((hf 1).mp (eventually_of_forall _))),
intros x hx hltg hlef,
nlinarith [(div_le_iff' (half_pos hC)).mp hlef],
end
/-- In a linearly ordered field with the order topology, if `f` tends to `at_top` and `g` tends to
a negative constant `C` then `f * g` tends to `at_bot`. -/
lemma tendsto_mul_at_bot {C : α} (hC : C < 0) (hf : tendsto f l at_top) (hg : tendsto g l (𝓝 C)) :
tendsto (λ x, (f x * g x)) l at_bot :=
begin
rw tendsto_at_bot,
rw tendsto_at_top at hf,
rw tendsto_order at hg,
intro b,
refine (hf (b/(C/2))).mp ((hg.2 (C/2) (by linarith)).mp ((hf 1).mp (eventually_of_forall _))),
intros x hx hltg hlef,
nlinarith [(div_le_iff_of_neg (div_neg_of_neg_of_pos hC zero_lt_two)).mp hlef],
end
end linear_ordered_field
section discrete_linear_ordered_field
variables [discrete_linear_ordered_field α] [topological_space α] [order_topology α]
/-- The function `x ↦ x⁻¹` tends to `+∞` on the right of `0`. -/
lemma tendsto_inv_zero_at_top : tendsto (λx:α, x⁻¹) (𝓝[set.Ioi (0:α)] 0) at_top :=
begin
apply (tendsto_at_top _ _).2 (λb, _),
refine mem_nhds_within_Ioi_iff_exists_Ioo_subset.2 ⟨(max b 1)⁻¹, by simp [zero_lt_one], λx hx, _⟩,
calc b ≤ max b 1 : le_max_left _ _
... ≤ x⁻¹ : begin
apply (le_inv _ hx.1).2 (le_of_lt hx.2),
exact lt_of_lt_of_le zero_lt_one (le_max_right _ _)
end
end
/-- The function `r ↦ r⁻¹` tends to `0` on the right as `r → +∞`. -/
lemma tendsto_inv_at_top_zero' : tendsto (λr:α, r⁻¹) at_top (𝓝[set.Ioi (0:α)] 0) :=
begin
assume s hs,
rw mem_nhds_within_Ioi_iff_exists_Ioc_subset at hs,
rcases hs with ⟨C, C0, hC⟩,
change 0 < C at C0,
refine filter.mem_map.2 (mem_sets_of_superset (mem_at_top C⁻¹) (λ x hx, hC _)),
have : 0 < x, from lt_of_lt_of_le (inv_pos.2 C0) hx,
exact ⟨inv_pos.2 this, (inv_le C0 this).1 hx⟩
end
lemma tendsto_inv_at_top_zero : tendsto (λr:α, r⁻¹) at_top (𝓝 0) :=
tendsto_inv_at_top_zero'.mono_right inf_le_left
variables {l : filter β} {f : β → α}
lemma tendsto.inv_tendsto_at_top (h : tendsto f l at_top) : tendsto (f⁻¹) l (𝓝 0) :=
tendsto_inv_at_top_zero.comp h
lemma tendsto.inv_tendsto_zero (h : tendsto f l (𝓝[set.Ioi 0] 0)) : tendsto (f⁻¹) l at_top :=
tendsto_inv_zero_at_top.comp h
end discrete_linear_ordered_field
lemma preimage_neg [add_group α] : preimage (has_neg.neg : α → α) = image (has_neg.neg : α → α) :=
(image_eq_preimage_of_inverse neg_neg neg_neg).symm
lemma filter.map_neg [add_group α] : map (has_neg.neg : α → α) = comap (has_neg.neg : α → α) :=
funext $ assume f, map_eq_comap_of_inverse (funext neg_neg) (funext neg_neg)
section topological_add_group
variables [topological_space α] [ordered_add_comm_group α] [topological_add_group α]
lemma neg_preimage_closure {s : set α} : (λr:α, -r) ⁻¹' closure s = closure ((λr:α, -r) '' s) :=
have (λr:α, -r) ∘ (λr:α, -r) = id, from funext neg_neg,
by rw [preimage_neg]; exact
(subset.antisymm (image_closure_subset_closure_image continuous_neg) $
calc closure ((λ (r : α), -r) '' s) = (λr, -r) '' ((λr, -r) '' closure ((λ (r : α), -r) '' s)) :
by rw [←image_comp, this, image_id]
... ⊆ (λr, -r) '' closure ((λr, -r) '' ((λ (r : α), -r) '' s)) :
monotone_image $ image_closure_subset_closure_image continuous_neg
... = _ : by rw [←image_comp, this, image_id])
end topological_add_group
section order_topology
variables [topological_space α] [topological_space β]
[linear_order α] [linear_order β] [order_topology α] [order_topology β]
lemma is_lub.nhds_within_ne_bot {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) :
ne_bot (𝓝[s] a) :=
let ⟨a', ha'⟩ := hs in
forall_sets_nonempty_iff_ne_bot.mp $ assume t ht,
let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := mem_inf_sets.mp ht in
by_cases
(assume h : a = a',
have a ∈ t₁, from mem_of_nhds ht₁,
have a ∈ t₂, from ht₂ $ by rwa [h],
⟨a, ht ⟨‹a ∈ t₁›, ‹a ∈ t₂›⟩⟩)
(assume : a ≠ a',
have a' < a, from lt_of_le_of_ne (ha.left ‹a' ∈ s›) this.symm,
let ⟨l, hl, hlt₁⟩ := exists_Ioc_subset_of_mem_nhds ht₁ ⟨a', this⟩ in
have ∃a'∈s, l < a',
from classical.by_contradiction $ assume : ¬ ∃a'∈s, l < a',
have ∀a'∈s, a' ≤ l, from assume a ha, not_lt.1 $ assume ha', this ⟨a, ha, ha'⟩,
have ¬ l < a, from not_lt.2 $ ha.right this,
this ‹l < a›,
let ⟨a', ha', ha'l⟩ := this in
have a' ∈ t₁, from hlt₁ ⟨‹l < a'›, ha.left ha'⟩,
⟨a', ht ⟨‹a' ∈ t₁›, ht₂ ‹a' ∈ s›⟩⟩)
lemma is_glb.nhds_within_ne_bot : ∀ {a : α} {s : set α}, is_glb s a → s.nonempty →
ne_bot (𝓝[s] a) :=
@is_lub.nhds_within_ne_bot (order_dual α) _ _ _
lemma is_lub_of_mem_nhds {s : set α} {a : α} {f : filter α}
(hsa : a ∈ upper_bounds s) (hsf : s ∈ f) [ne_bot (f ⊓ 𝓝 a)] : is_lub s a :=
⟨hsa, assume b hb,
not_lt.1 $ assume hba,
have s ∩ {a | b < a} ∈ f ⊓ 𝓝 a,
from inter_mem_inf_sets hsf (mem_nhds_sets (is_open_lt' _) hba),
let ⟨x, ⟨hxs, hxb⟩⟩ := nonempty_of_mem_sets this in
have b < b, from lt_of_lt_of_le hxb $ hb hxs,
lt_irrefl b this⟩
lemma is_glb_of_mem_nhds : ∀ {s : set α} {a : α} {f : filter α},
a ∈ lower_bounds s → s ∈ f → ne_bot (f ⊓ 𝓝 a) → is_glb s a :=
@is_lub_of_mem_nhds (order_dual α) _ _ _
lemma is_lub_of_is_lub_of_tendsto {f : α → β} {s : set α} {a : α} {b : β}
(hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) (ha : is_lub s a) (hs : s.nonempty)
(hb : tendsto f (𝓝[s] a) (𝓝 b)) : is_lub (f '' s) b :=
have hnbot : ne_bot (𝓝[s] a), from ha.nhds_within_ne_bot hs,
have ∀a'∈s, ¬ b < f a',
from assume a' ha' h,
have ∀ᶠ x in 𝓝 b, x < f a', from mem_nhds_sets (is_open_gt' _) h,
let ⟨t₁, ht₁, t₂, ht₂, hs⟩ := mem_inf_sets.mp (hb this) in
by_cases
(assume h : a = a',
have a ∈ t₁ ∩ t₂, from ⟨mem_of_nhds ht₁, ht₂ $ by rwa [h]⟩,
have f a < f a', from hs this,
lt_irrefl (f a') $ by rwa [h] at this)
(assume h : a ≠ a',
have a' < a, from lt_of_le_of_ne (ha.left ha') h.symm,
have {x | a' < x} ∈ 𝓝 a, from mem_nhds_sets (is_open_lt' _) this,
have {x | a' < x} ∩ t₁ ∈ 𝓝 a, from inter_mem_sets this ht₁,
have ({x | a' < x} ∩ t₁) ∩ s ∈ 𝓝[s] a,
from inter_mem_inf_sets this (subset.refl s),
let ⟨x, ⟨hx₁, hx₂⟩, hx₃⟩ := hnbot.nonempty_of_mem this in
have hxa' : f x < f a', from hs ⟨hx₂, ht₂ hx₃⟩,
have ha'x : f a' ≤ f x, from hf _ ha' _ hx₃ $ le_of_lt hx₁,
lt_irrefl _ (lt_of_le_of_lt ha'x hxa')),
and.intro
(assume b' ⟨a', ha', h_eq⟩, h_eq ▸ not_lt.1 $ this _ ha')
(assume b' hb', by exactI (le_of_tendsto hb $
mem_inf_sets_of_right $ assume x hx, hb' $ mem_image_of_mem _ hx))
lemma is_glb_of_is_glb_of_tendsto {f : α → β} {s : set α} {a : α} {b : β}
(hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) : is_glb s a → s.nonempty →
tendsto f (𝓝[s] a) (𝓝 b) → is_glb (f '' s) b :=
@is_lub_of_is_lub_of_tendsto (order_dual α) (order_dual β) _ _ _ _ _ _ f s a b
(λ x hx y hy, hf y hy x hx)
lemma is_glb_of_is_lub_of_tendsto : ∀ {f : α → β} {s : set α} {a : α} {b : β},
(∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) → is_lub s a → s.nonempty →
tendsto f (𝓝[s] a) (𝓝 b) → is_glb (f '' s) b :=
@is_lub_of_is_lub_of_tendsto α (order_dual β) _ _ _ _ _ _
lemma is_lub_of_is_glb_of_tendsto : ∀ {f : α → β} {s : set α} {a : α} {b : β},
(∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) → is_glb s a → s.nonempty →
tendsto f (𝓝[s] a) (𝓝 b) → is_lub (f '' s) b :=
@is_glb_of_is_glb_of_tendsto α (order_dual β) _ _ _ _ _ _
lemma mem_closure_of_is_lub {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) :
a ∈ closure s :=
by rw closure_eq_cluster_pts; exact ha.nhds_within_ne_bot hs
lemma mem_of_is_lub_of_is_closed {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty)
(sc : is_closed s) : a ∈ s :=
by rw ←sc.closure_eq; exact mem_closure_of_is_lub ha hs
lemma mem_closure_of_is_glb {a : α} {s : set α} (ha : is_glb s a) (hs : s.nonempty) :
a ∈ closure s :=
by rw closure_eq_cluster_pts; exact ha.nhds_within_ne_bot hs
lemma mem_of_is_glb_of_is_closed {a : α} {s : set α} (ha : is_glb s a) (hs : s.nonempty)
(sc : is_closed s) : a ∈ s :=
by rw ←sc.closure_eq; exact mem_closure_of_is_glb ha hs
/-- A compact set is bounded below -/
lemma is_compact.bdd_below {α : Type u} [topological_space α] [linear_order α]
[order_closed_topology α] [nonempty α] {s : set α} (hs : is_compact s) : bdd_below s :=
begin
by_contra H,
letI := classical.DLO α,
rcases hs.elim_finite_subcover_image (λ x (_ : x ∈ s), @is_open_Ioi _ _ _ _ x) _
with ⟨t, st, ft, ht⟩,
{ refine H (ft.bdd_below.imp $ λ C hC y hy, _),
rcases mem_bUnion_iff.1 (ht hy) with ⟨x, hx, xy⟩,
exact le_trans (hC hx) (le_of_lt xy) },
{ refine λ x hx, mem_bUnion_iff.2 (not_imp_comm.1 _ H),
exact λ h, ⟨x, λ y hy, le_of_not_lt (h.imp $ λ ys, ⟨_, hy, ys⟩)⟩ }
end
/-- A compact set is bounded above -/
lemma is_compact.bdd_above {α : Type u} [topological_space α] [linear_order α]
[order_topology α] : Π [nonempty α] {s : set α}, is_compact s → bdd_above s :=
@is_compact.bdd_below (order_dual α) _ _ _
end order_topology
section linear_order
variables [topological_space α] [linear_order α] [order_topology α] [densely_ordered α]
/-- The closure of the interval `(a, +∞)` is the closed interval `[a, +∞)`, unless `a` is a top
element. -/
lemma closure_Ioi' {a b : α} (hab : a < b) :
closure (Ioi a) = Ici a :=
begin
apply subset.antisymm,
{ exact closure_minimal Ioi_subset_Ici_self is_closed_Ici },
{ assume x hx,
by_cases h : x = a,
{ rw h, exact mem_closure_of_is_glb is_glb_Ioi ⟨_, hab⟩ },
{ exact subset_closure (lt_of_le_of_ne hx (ne.symm h)) } }
end
/-- The closure of the interval `(a, +∞)` is the closed interval `[a, +∞)`. -/
@[simp] lemma closure_Ioi (a : α) [no_top_order α] :
closure (Ioi a) = Ici a :=
let ⟨b, hb⟩ := no_top a in closure_Ioi' hb
/-- The closure of the interval `(-∞, a)` is the closed interval `(-∞, a]`, unless `a` is a bottom
element. -/
lemma closure_Iio' {a b : α} (hab : b < a) :
closure (Iio a) = Iic a :=
begin
apply subset.antisymm,
{ exact closure_minimal Iio_subset_Iic_self is_closed_Iic },
{ assume x hx,
by_cases h : x = a,
{ rw h, exact mem_closure_of_is_lub is_lub_Iio ⟨_, hab⟩ },
{ apply subset_closure, by simpa [h] using lt_or_eq_of_le hx } }
end
/-- The closure of the interval `(-∞, a)` is the interval `(-∞, a]`. -/
@[simp] lemma closure_Iio (a : α) [no_bot_order α] :
closure (Iio a) = Iic a :=
let ⟨b, hb⟩ := no_bot a in closure_Iio' hb
/-- The closure of the open interval `(a, b)` is the closed interval `[a, b]`. -/
@[simp] lemma closure_Ioo {a b : α} (hab : a < b) :
closure (Ioo a b) = Icc a b :=
begin
apply subset.antisymm,
{ exact closure_minimal Ioo_subset_Icc_self is_closed_Icc },
{ have hab' : (Ioo a b).nonempty, from nonempty_Ioo.2 hab,
assume x hx,
by_cases h : x = a,
{ rw h, exact mem_closure_of_is_glb (is_glb_Ioo hab) hab' },
by_cases h' : x = b,
{ rw h', refine mem_closure_of_is_lub (is_lub_Ioo hab) hab' },
exact subset_closure ⟨lt_of_le_of_ne hx.1 (ne.symm h), by simpa [h'] using lt_or_eq_of_le hx.2⟩ }
end
/-- The closure of the interval `(a, b]` is the closed interval `[a, b]`. -/
@[simp] lemma closure_Ioc {a b : α} (hab : a < b) :
closure (Ioc a b) = Icc a b :=
begin
apply subset.antisymm,
{ exact closure_minimal Ioc_subset_Icc_self is_closed_Icc },
{ apply subset.trans _ (closure_mono Ioo_subset_Ioc_self),
rw closure_Ioo hab }
end
/-- The closure of the interval `[a, b)` is the closed interval `[a, b]`. -/
@[simp] lemma closure_Ico {a b : α} (hab : a < b) :
closure (Ico a b) = Icc a b :=
begin
apply subset.antisymm,
{ exact closure_minimal Ico_subset_Icc_self is_closed_Icc },
{ apply subset.trans _ (closure_mono Ioo_subset_Ico_self),
rw closure_Ioo hab }
end
@[simp] lemma interior_Ici [no_bot_order α] {a : α} : interior (Ici a) = Ioi a :=
by rw [← compl_Iio, interior_compl, closure_Iio, compl_Iic]
@[simp] lemma interior_Iic [no_top_order α] {a : α} : interior (Iic a) = Iio a :=
by rw [← compl_Ioi, interior_compl, closure_Ioi, compl_Ici]
@[simp] lemma interior_Icc [no_bot_order α] [no_top_order α] {a b : α}:
interior (Icc a b) = Ioo a b :=
by rw [← Ici_inter_Iic, interior_inter, interior_Ici, interior_Iic, Ioi_inter_Iio]
@[simp] lemma interior_Ico [no_bot_order α] {a b : α} : interior (Ico a b) = Ioo a b :=
by rw [← Ici_inter_Iio, interior_inter, interior_Ici, interior_Iio, Ioi_inter_Iio]
@[simp] lemma interior_Ioc [no_top_order α] {a b : α} : interior (Ioc a b) = Ioo a b :=
by rw [← Ioi_inter_Iic, interior_inter, interior_Ioi, interior_Iic, Ioi_inter_Iio]
@[simp] lemma frontier_Ici [no_bot_order α] {a : α} : frontier (Ici a) = {a} :=
by simp [frontier]
@[simp] lemma frontier_Iic [no_top_order α] {a : α} : frontier (Iic a) = {a} :=
by simp [frontier]
@[simp] lemma frontier_Ioi [no_top_order α] {a : α} : frontier (Ioi a) = {a} :=
by simp [frontier]
@[simp] lemma frontier_Iio [no_bot_order α] {a : α} : frontier (Iio a) = {a} :=
by simp [frontier]
@[simp] lemma frontier_Icc [no_bot_order α] [no_top_order α] {a b : α} (h : a < b) :
frontier (Icc a b) = {a, b} :=
by simp [frontier, le_of_lt h, Icc_diff_Ioo_same]
@[simp] lemma frontier_Ioo {a b : α} (h : a < b) : frontier (Ioo a b) = {a, b} :=
by simp [frontier, h, le_of_lt h, Icc_diff_Ioo_same]
@[simp] lemma frontier_Ico [no_bot_order α] {a b : α} (h : a < b) : frontier (Ico a b) = {a, b} :=
by simp [frontier, h, le_of_lt h, Icc_diff_Ioo_same]
@[simp] lemma frontier_Ioc [no_top_order α] {a b : α} (h : a < b) : frontier (Ioc a b) = {a, b} :=
by simp [frontier, h, le_of_lt h, Icc_diff_Ioo_same]
lemma nhds_within_Ioi_ne_bot' {a b c : α} (H₁ : a < c) (H₂ : a ≤ b) :
ne_bot (𝓝[Ioi a] b) :=
mem_closure_iff_nhds_within_ne_bot.1 $ by { rw [closure_Ioi' H₁], exact H₂ }
lemma nhds_within_Ioi_ne_bot [no_top_order α] {a b : α} (H : a ≤ b) :
ne_bot (𝓝[Ioi a] b) :=
let ⟨c, hc⟩ := no_top a in nhds_within_Ioi_ne_bot' hc H
lemma nhds_within_Ioi_self_ne_bot' {a b : α} (H : a < b) :
ne_bot (𝓝[Ioi a] a) :=
nhds_within_Ioi_ne_bot' H (le_refl a)
@[instance]
lemma nhds_within_Ioi_self_ne_bot [no_top_order α] (a : α) :
ne_bot (𝓝[Ioi a] a) :=
nhds_within_Ioi_ne_bot (le_refl a)
lemma nhds_within_Iio_ne_bot' {a b c : α} (H₁ : a < c) (H₂ : b ≤ c) :
ne_bot (𝓝[Iio c] b) :=
mem_closure_iff_nhds_within_ne_bot.1 $ by { rw [closure_Iio' H₁], exact H₂ }
lemma nhds_within_Iio_ne_bot [no_bot_order α] {a b : α} (H : a ≤ b) :
ne_bot (𝓝[Iio b] a) :=
let ⟨c, hc⟩ := no_bot b in nhds_within_Iio_ne_bot' hc H
lemma nhds_within_Iio_self_ne_bot' {a b : α} (H : a < b) :
ne_bot (𝓝[Iio b] b) :=
nhds_within_Iio_ne_bot' H (le_refl b)
@[instance]
lemma nhds_within_Iio_self_ne_bot [no_bot_order α] (a : α) :
ne_bot (𝓝[Iio a] a) :=
nhds_within_Iio_ne_bot (le_refl a)
end linear_order
section decidable_linear_order
variables [topological_space α] [decidable_linear_order α] [order_topology α] [densely_ordered α]
/-- The `at_top` filter for an open interval `Ioo a b` comes from the left-neighbourhoods filter at
the right endpoint in the ambient order. -/
lemma Ioo_at_top_eq_nhds_within {a b : α} (h : a < b) :
(at_top : filter (Ioo a b)) = comap (coe : Ioo a b → α) (𝓝[Iio b] b) :=
begin
haveI : nonempty (Ioo a b) := nonempty_Ioo_subtype h,
ext,
split,
{ intros hs,
obtain ⟨x, hx⟩ : ∃ x : (Ioo a b), ∀ z : (Ioo a b), z ≥ x → z ∈ s := mem_at_top_sets.mp hs,
refine ⟨Ioo x b, Ioo_mem_nhds_within_Iio (right_mem_Ioc.mpr x.2.2), _⟩,
intros z hz,
simpa using hx z (le_of_lt hz.1) },
{ rintros ⟨t, ht, hts⟩,
obtain ⟨x, hx, hxt⟩ : ∃ x ∈ Iio b, Ioo x b ⊆ t := (mem_nhds_within_Iio_iff_exists_Ioo_subset' h).mp ht,
obtain ⟨y, hay, hyb⟩ : ∃ y, max a x < y ∧ y < b := exists_between (max_lt_iff.mpr ⟨h, hx⟩),
refine mem_at_top_sets.mpr ⟨⟨y, (max_lt_iff.mp hay).1, hyb⟩, _⟩,
intros z hz,
exact hts (hxt ⟨lt_of_lt_of_le (lt_of_le_of_lt (le_max_right a x) hay) hz, z.2.2⟩) }
end
/-- The `at_bot` filter for an open interval `Ioo a b` comes from the right-neighbourhoods filter at
the left endpoint in the ambient order. -/
lemma Ioo_at_bot_eq_nhds_within {a b : α} (h : a < b) :
(at_bot : filter (Ioo a b)) = comap (coe : Ioo a b → α) (𝓝[Ioi a] a) :=
begin
haveI : nonempty (Ioo a b) := nonempty_Ioo_subtype h,
ext,
split,
{ intros hs,
obtain ⟨x, hx⟩ : ∃ x : (Ioo a b), ∀ z : (Ioo a b), z ≤ x → z ∈ s := mem_at_bot_sets.mp hs,
refine ⟨Ioo a x, Ioo_mem_nhds_within_Ioi (left_mem_Ico.mpr x.2.1), _⟩,
intros z hz,
simpa using hx z (le_of_lt hz.2) },
{ rintros ⟨t, ht, hts⟩,
obtain ⟨x, hx, hxt⟩ : ∃ x ∈ Ioi a, Ioo a x ⊆ t := (mem_nhds_within_Ioi_iff_exists_Ioo_subset' h).mp ht,
obtain ⟨y, hay, hyb⟩ : ∃ y, a < y ∧ y < min b x := exists_between (lt_min_iff.mpr ⟨h, hx⟩),
refine mem_at_bot_sets.mpr ⟨⟨y, hay, (lt_min_iff.mp hyb).1⟩, _⟩,
intros z hz,
exact hts (hxt ⟨z.2.1, lt_of_le_of_lt hz (lt_of_lt_of_le hyb (min_le_right b x))⟩) }
end
end decidable_linear_order
section complete_linear_order
variables [complete_linear_order α] [topological_space α] [order_topology α]
[complete_linear_order β] [topological_space β] [order_topology β] [nonempty γ]
lemma Sup_mem_closure {α : Type u} [topological_space α] [complete_linear_order α]
[order_topology α] {s : set α} (hs : s.nonempty) :
Sup s ∈ closure s :=
mem_closure_of_is_lub (is_lub_Sup _) hs
lemma Inf_mem_closure {α : Type u} [topological_space α] [complete_linear_order α]
[order_topology α] {s : set α} (hs : s.nonempty) :
Inf s ∈ closure s :=
mem_closure_of_is_glb (is_glb_Inf _) hs
lemma is_closed.Sup_mem {α : Type u} [topological_space α] [complete_linear_order α]
[order_topology α] {s : set α} (hs : s.nonempty) (hc : is_closed s) :
Sup s ∈ s :=
mem_of_is_lub_of_is_closed (is_lub_Sup _) hs hc
lemma is_closed.Inf_mem {α : Type u} [topological_space α] [complete_linear_order α]
[order_topology α] {s : set α} (hs : s.nonempty) (hc : is_closed s) :
Inf s ∈ s :=
mem_of_is_glb_of_is_closed (is_glb_Inf _) hs hc
/-- A monotone function continuous at the supremum of a nonempty set sends this supremum to
the supremum of the image of this set. -/
lemma map_Sup_of_continuous_at_of_monotone' {f : α → β} {s : set α} (Cf : continuous_at f (Sup s))
(Mf : monotone f) (hs : s.nonempty) :
f (Sup s) = Sup (f '' s) :=
--This is a particular case of the more general is_lub_of_is_lub_of_tendsto
(is_lub_of_is_lub_of_tendsto (λ x hx y hy xy, Mf xy) (is_lub_Sup _) hs $
Cf.mono_left inf_le_left).Sup_eq.symm
/-- A monotone function `s` sending `bot` to `bot` and continuous at the supremum of a set sends
this supremum to the supremum of the image of this set. -/
lemma map_Sup_of_continuous_at_of_monotone {f : α → β} {s : set α} (Cf : continuous_at f (Sup s))
(Mf : monotone f) (fbot : f ⊥ = ⊥) :
f (Sup s) = Sup (f '' s) :=
begin
cases s.eq_empty_or_nonempty with h h,
{ simp [h, fbot] },
{ exact map_Sup_of_continuous_at_of_monotone' Cf Mf h }
end
/-- A monotone function continuous at the indexed supremum over a nonempty `Sort` sends this indexed
supremum to the indexed supremum of the composition. -/
lemma map_supr_of_continuous_at_of_monotone' {ι : Sort*} [nonempty ι] {f : α → β} {g : ι → α}
(Cf : continuous_at f (supr g)) (Mf : monotone f) :
f (⨆ i, g i) = ⨆ i, f (g i) :=
by rw [supr, map_Sup_of_continuous_at_of_monotone' Cf Mf (range_nonempty g), ← range_comp, supr]
/-- If a monotone function sending `bot` to `bot` is continuous at the indexed supremum over
a `Sort`, then it sends this indexed supremum to the indexed supremum of the composition. -/
lemma map_supr_of_continuous_at_of_monotone {ι : Sort*} {f : α → β} {g : ι → α}
(Cf : continuous_at f (supr g)) (Mf : monotone f) (fbot : f ⊥ = ⊥) :
f (⨆ i, g i) = ⨆ i, f (g i) :=
by rw [supr, map_Sup_of_continuous_at_of_monotone Cf Mf fbot, ← range_comp, supr]
/-- A monotone function continuous at the infimum of a nonempty set sends this infimum to
the infimum of the image of this set. -/
lemma map_Inf_of_continuous_at_of_monotone' {f : α → β} {s : set α} (Cf : continuous_at f (Inf s))
(Mf : monotone f) (hs : s.nonempty) :
f (Inf s) = Inf (f '' s) :=
@map_Sup_of_continuous_at_of_monotone' (order_dual α) (order_dual β) _ _ _ _ _ _ f s Cf
Mf.order_dual hs
/-- A monotone function `s` sending `top` to `top` and continuous at the infimum of a set sends
this infimum to the infimum of the image of this set. -/
lemma map_Inf_of_continuous_at_of_monotone {f : α → β} {s : set α} (Cf : continuous_at f (Inf s))
(Mf : monotone f) (ftop : f ⊤ = ⊤) :
f (Inf s) = Inf (f '' s) :=
@map_Sup_of_continuous_at_of_monotone (order_dual α) (order_dual β) _ _ _ _ _ _ f s Cf
Mf.order_dual ftop
/-- A monotone function continuous at the indexed infimum over a nonempty `Sort` sends this indexed
infimum to the indexed infimum of the composition. -/
lemma map_infi_of_continuous_at_of_monotone' {ι : Sort*} [nonempty ι] {f : α → β} {g : ι → α}
(Cf : continuous_at f (infi g)) (Mf : monotone f) :
f (⨅ i, g i) = ⨅ i, f (g i) :=
@map_supr_of_continuous_at_of_monotone' (order_dual α) (order_dual β) _ _ _ _ _ _ ι _ f g Cf
Mf.order_dual
/-- If a monotone function sending `top` to `top` is continuous at the indexed infimum over
a `Sort`, then it sends this indexed infimum to the indexed infimum of the composition. -/
lemma map_infi_of_continuous_at_of_monotone {ι : Sort*} {f : α → β} {g : ι → α}
(Cf : continuous_at f (infi g)) (Mf : monotone f) (ftop : f ⊤ = ⊤) :
f (infi g) = infi (f ∘ g) :=
@map_supr_of_continuous_at_of_monotone (order_dual α) (order_dual β) _ _ _ _ _ _ ι f g Cf
Mf.order_dual ftop
end complete_linear_order
section conditionally_complete_linear_order
variables [conditionally_complete_linear_order α] [topological_space α] [order_topology α]
[conditionally_complete_linear_order β] [topological_space β] [order_topology β] [nonempty γ]
lemma cSup_mem_closure {s : set α} (hs : s.nonempty) (B : bdd_above s) : Sup s ∈ closure s :=
mem_closure_of_is_lub (is_lub_cSup hs B) hs
lemma cInf_mem_closure {s : set α} (hs : s.nonempty) (B : bdd_below s) : Inf s ∈ closure s :=
mem_closure_of_is_glb (is_glb_cInf hs B) hs
lemma is_closed.cSup_mem {s : set α} (hc : is_closed s) (hs : s.nonempty) (B : bdd_above s) :
Sup s ∈ s :=
mem_of_is_lub_of_is_closed (is_lub_cSup hs B) hs hc
lemma is_closed.cInf_mem {s : set α} (hc : is_closed s) (hs : s.nonempty) (B : bdd_below s) :
Inf s ∈ s :=
mem_of_is_glb_of_is_closed (is_glb_cInf hs B) hs hc
/-- If a monotone function is continuous at the supremum of a nonempty bounded above set `s`,
then it sends this supremum to the supremum of the image of `s`. -/
lemma map_cSup_of_continuous_at_of_monotone {f : α → β} {s : set α} (Cf : continuous_at f (Sup s))
(Mf : monotone f) (ne : s.nonempty) (H : bdd_above s) :
f (Sup s) = Sup (f '' s) :=
begin
refine ((is_lub_cSup (ne.image f) (Mf.map_bdd_above H)).unique _).symm,
refine is_lub_of_is_lub_of_tendsto (λx hx y hy xy, Mf xy) (is_lub_cSup ne H) ne _,
exact Cf.mono_left inf_le_left
end
/-- If a monotone function is continuous at the indexed supremum of a bounded function on
a nonempty `Sort`, then it sends this supremum to the supremum of the composition. -/
lemma map_csupr_of_continuous_at_of_monotone {f : α → β} {g : γ → α}
(Cf : continuous_at f (⨆ i, g i)) (Mf : monotone f) (H : bdd_above (range g)) :
f (⨆ i, g i) = ⨆ i, f (g i) :=
by rw [supr, map_cSup_of_continuous_at_of_monotone Cf Mf (range_nonempty _) H, ← range_comp, supr]
/-- If a monotone function is continuous at the infimum of a nonempty bounded below set `s`,
then it sends this infimum to the infimum of the image of `s`. -/
lemma map_cInf_of_continuous_at_of_monotone {f : α → β} {s : set α} (Cf : continuous_at f (Inf s))
(Mf : monotone f) (ne : s.nonempty) (H : bdd_below s) :
f (Inf s) = Inf (f '' s) :=
@map_cSup_of_continuous_at_of_monotone (order_dual α) (order_dual β) _ _ _ _ _ _ f s Cf
Mf.order_dual ne H
/-- A continuous monotone function sends indexed infimum to indexed infimum in conditionally
complete linear order, under a boundedness assumption. -/
lemma map_cinfi_of_continuous_at_of_monotone {f : α → β} {g : γ → α}
(Cf : continuous_at f (⨅ i, g i)) (Mf : monotone f) (H : bdd_below (range g)) :
f (⨅ i, g i) = ⨅ i, f (g i) :=
@map_csupr_of_continuous_at_of_monotone (order_dual α) (order_dual β) _ _ _ _ _ _ _ _ _ _
Cf Mf.order_dual H
/-- A bounded connected subset of a conditionally complete linear order includes the open interval
`(Inf s, Sup s)`. -/
lemma is_connected.Ioo_cInf_cSup_subset {s : set α} (hs : is_connected s) (hb : bdd_below s)
(ha : bdd_above s) :
Ioo (Inf s) (Sup s) ⊆ s :=
λ x hx, let ⟨y, ys, hy⟩ := (is_glb_lt_iff (is_glb_cInf hs.nonempty hb)).1 hx.1 in
let ⟨z, zs, hz⟩ := (lt_is_lub_iff (is_lub_cSup hs.nonempty ha)).1 hx.2 in
hs.Icc_subset ys zs ⟨le_of_lt hy, le_of_lt hz⟩
lemma eq_Icc_cInf_cSup_of_connected_bdd_closed {s : set α} (hc : is_connected s) (hb : bdd_below s)
(ha : bdd_above s) (hcl : is_closed s) :
s = Icc (Inf s) (Sup s) :=
subset.antisymm (subset_Icc_cInf_cSup hb ha) $
hc.Icc_subset (hcl.cInf_mem hc.nonempty hb) (hcl.cSup_mem hc.nonempty ha)
lemma is_preconnected.Ioi_cInf_subset {s : set α} (hs : is_preconnected s) (hb : bdd_below s)
(ha : ¬bdd_above s) :
Ioi (Inf s) ⊆ s :=
begin
have sne : s.nonempty := @nonempty_of_not_bdd_above α _ s ⟨Inf ∅⟩ ha,
intros x hx,
obtain ⟨y, ys, hy⟩ : ∃ y ∈ s, y < x := (is_glb_lt_iff (is_glb_cInf sne hb)).1 hx,
obtain ⟨z, zs, hz⟩ : ∃ z ∈ s, x < z := not_bdd_above_iff.1 ha x,
exact hs.Icc_subset ys zs ⟨le_of_lt hy, le_of_lt hz⟩
end
lemma is_preconnected.Iio_cSup_subset {s : set α} (hs : is_preconnected s) (hb : ¬bdd_below s)
(ha : bdd_above s) :
Iio (Sup s) ⊆ s :=
@is_preconnected.Ioi_cInf_subset (order_dual α) _ _ _ s hs ha hb
/-- A preconnected set in a conditionally complete linear order is either one of the intervals
`[Inf s, Sup s]`, `[Inf s, Sup s)`, `(Inf s, Sup s]`, `(Inf s, Sup s)`, `[Inf s, +∞)`,
`(Inf s, +∞)`, `(-∞, Sup s]`, `(-∞, Sup s)`, `(-∞, +∞)`, or `∅`. The converse statement requires
`α` to be densely ordererd. -/
lemma is_preconnected.mem_intervals {s : set α} (hs : is_preconnected s) :
s ∈ ({Icc (Inf s) (Sup s), Ico (Inf s) (Sup s), Ioc (Inf s) (Sup s), Ioo (Inf s) (Sup s),
Ici (Inf s), Ioi (Inf s), Iic (Sup s), Iio (Sup s), univ, ∅} : set (set α)) :=
begin
rcases s.eq_empty_or_nonempty with rfl|hne,
{ apply_rules [or.inr, mem_singleton] },
have hs' : is_connected s := ⟨hne, hs⟩,
by_cases hb : bdd_below s; by_cases ha : bdd_above s,
{ rcases mem_Icc_Ico_Ioc_Ioo_of_subset_of_subset (hs'.Ioo_cInf_cSup_subset hb ha)
(subset_Icc_cInf_cSup hb ha) with hs|hs|hs|hs,
{ exact (or.inl hs) },
{ exact (or.inr $ or.inl hs) },
{ exact (or.inr $ or.inr $ or.inl hs) },
{ exact (or.inr $ or.inr $ or.inr $ or.inl hs) } },
{ refine (or.inr $ or.inr $ or.inr $ or.inr _),
cases mem_Ici_Ioi_of_subset_of_subset (hs.Ioi_cInf_subset hb ha) (λ x hx, cInf_le hb hx)
with hs hs,
{ exact or.inl hs },
{ exact or.inr (or.inl hs) } },
{ iterate 6 { apply or.inr },
cases mem_Iic_Iio_of_subset_of_subset (hs.Iio_cSup_subset hb ha) (λ x hx, le_cSup ha hx)
with hs hs,
{ exact or.inl hs },
{ exact or.inr (or.inl hs) } },
{ iterate 8 { apply or.inr },
exact or.inl (hs.eq_univ_of_unbounded hb ha) }
end
/-- A preconnected set is either one of the intervals `Icc`, `Ico`, `Ioc`, `Ioo`, `Ici`, `Ioi`,
`Iic`, `Iio`, or `univ`, or `∅`. The converse statement requires `α` to be densely ordererd. Though
one can represent `∅` as `(Inf s, Inf s)`, we include it into the list of possible cases to improve
readability. -/
lemma set_of_is_preconnected_subset_of_ordered :
{s : set α | is_preconnected s} ⊆
-- bounded intervals
(range (uncurry Icc) ∪ range (uncurry Ico) ∪ range (uncurry Ioc) ∪ range (uncurry Ioo)) ∪
-- unbounded intervals and `univ`
(range Ici ∪ range Ioi ∪ range Iic ∪ range Iio ∪ {univ, ∅}) :=
begin
intros s hs,
rcases hs.mem_intervals with hs|hs|hs|hs|hs|hs|hs|hs|hs|hs,
{ exact (or.inl $ or.inl $ or.inl $ or.inl ⟨(Inf s, Sup s), hs.symm⟩) },
{ exact (or.inl $ or.inl $ or.inl $ or.inr ⟨(Inf s, Sup s), hs.symm⟩) },
{ exact (or.inl $ or.inl $ or.inr ⟨(Inf s, Sup s), hs.symm⟩) },
{ exact (or.inl $ or.inr ⟨(Inf s, Sup s), hs.symm⟩) },
{ exact (or.inr $ or.inl $ or.inl $ or.inl $ or.inl ⟨Inf s, hs.symm⟩) },
{ exact (or.inr $ or.inl $ or.inl $ or.inl $ or.inr ⟨Inf s, hs.symm⟩) },
{ exact (or.inr $ or.inl $ or.inl $ or.inr ⟨Sup s, hs.symm⟩) },
{ exact (or.inr $ or.inl $ or.inr ⟨Sup s, hs.symm⟩) },
{ exact (or.inr $ or.inr $ or.inl hs) },
{ exact (or.inr $ or.inr $ or.inr hs) }
end
/-- A "continuous induction principle" for a closed interval: if a set `s` meets `[a, b]`
on a closed subset, contains `a`, and the set `s ∩ [a, b)` has no maximal point, then `b ∈ s`. -/
lemma is_closed.mem_of_ge_of_forall_exists_gt {a b : α} {s : set α} (hs : is_closed (s ∩ Icc a b))
(ha : a ∈ s) (hab : a ≤ b) (hgt : ∀ x ∈ s ∩ Ico a b, (s ∩ Ioc x b).nonempty) :
b ∈ s :=
begin
let S := s ∩ Icc a b,
replace ha : a ∈ S, from ⟨ha, left_mem_Icc.2 hab⟩,
have Sbd : bdd_above S, from ⟨b, λ z hz, hz.2.2⟩,
let c := Sup (s ∩ Icc a b),
have c_mem : c ∈ S, from hs.cSup_mem ⟨_, ha⟩ Sbd,
have c_le : c ≤ b, from cSup_le ⟨_, ha⟩ (λ x hx, hx.2.2),
cases eq_or_lt_of_le c_le with hc hc, from hc ▸ c_mem.1,
exfalso,
rcases hgt c ⟨c_mem.1, c_mem.2.1, hc⟩ with ⟨x, xs, cx, xb⟩,
exact not_lt_of_le (le_cSup Sbd ⟨xs, le_trans (le_cSup Sbd ha) (le_of_lt cx), xb⟩) cx
end
/-- A "continuous induction principle" for a closed interval: if a set `s` meets `[a, b]`
on a closed subset, contains `a`, and for any `a ≤ x < y ≤ b`, `x ∈ s`, the set `s ∩ (x, y]`
is not empty, then `[a, b] ⊆ s`. -/
lemma is_closed.Icc_subset_of_forall_exists_gt {a b : α} {s : set α} (hs : is_closed (s ∩ Icc a b))
(ha : a ∈ s) (hgt : ∀ x ∈ s ∩ Ico a b, ∀ y ∈ Ioi x, (s ∩ Ioc x y).nonempty) :
Icc a b ⊆ s :=
begin
assume y hy,
have : is_closed (s ∩ Icc a y),
{ suffices : s ∩ Icc a y = s ∩ Icc a b ∩ Icc a y,
{ rw this, exact is_closed_inter hs is_closed_Icc },
rw [inter_assoc],
congr,
exact (inter_eq_self_of_subset_right $ Icc_subset_Icc_right hy.2).symm },
exact is_closed.mem_of_ge_of_forall_exists_gt this ha hy.1
(λ x hx, hgt x ⟨hx.1, Ico_subset_Ico_right hy.2 hx.2⟩ y hx.2.2)
end
section densely_ordered
variables [densely_ordered α] {a b : α}
/-- A "continuous induction principle" for a closed interval: if a set `s` meets `[a, b]`
on a closed subset, contains `a`, and for any `x ∈ s ∩ [a, b)` the set `s` includes some open
neighborhood of `x` within `(x, +∞)`, then `[a, b] ⊆ s`. -/
lemma is_closed.Icc_subset_of_forall_mem_nhds_within {a b : α} {s : set α}
(hs : is_closed (s ∩ Icc a b)) (ha : a ∈ s)
(hgt : ∀ x ∈ s ∩ Ico a b, s ∈ 𝓝[Ioi x] x) :
Icc a b ⊆ s :=
begin
apply hs.Icc_subset_of_forall_exists_gt ha,
rintros x ⟨hxs, hxab⟩ y hyxb,
have : s ∩ Ioc x y ∈ 𝓝[Ioi x] x,
from inter_mem_sets (hgt x ⟨hxs, hxab⟩) (Ioc_mem_nhds_within_Ioi ⟨le_refl _, hyxb⟩),
exact (nhds_within_Ioi_self_ne_bot' hxab.2).nonempty_of_mem this
end
/-- A closed interval in a densely ordered conditionally complete linear order is preconnected. -/
lemma is_preconnected_Icc : is_preconnected (Icc a b) :=
is_preconnected_closed_iff.2
begin
rintros s t hs ht hab ⟨x, hx⟩ ⟨y, hy⟩,
wlog hxy : x ≤ y := le_total x y using [x y s t, y x t s],
have xyab : Icc x y ⊆ Icc a b := Icc_subset_Icc hx.1.1 hy.1.2,
by_contradiction hst,
suffices : Icc x y ⊆ s,
from hst ⟨y, xyab $ right_mem_Icc.2 hxy, this $ right_mem_Icc.2 hxy, hy.2⟩,
apply (is_closed_inter hs is_closed_Icc).Icc_subset_of_forall_mem_nhds_within hx.2,
rintros z ⟨zs, hz⟩,
have zt : z ∈ tᶜ, from λ zt, hst ⟨z, xyab $ Ico_subset_Icc_self hz, zs, zt⟩,
have : tᶜ ∩ Ioc z y ∈ 𝓝[Ioi z] z,
{ rw [← nhds_within_Ioc_eq_nhds_within_Ioi hz.2],
exact mem_nhds_within.2 ⟨tᶜ, ht, zt, subset.refl _⟩},
apply mem_sets_of_superset this,
have : Ioc z y ⊆ s ∪ t, from λ w hw, hab (xyab ⟨le_trans hz.1 (le_of_lt hw.1), hw.2⟩),
exact λ w ⟨wt, wzy⟩, (this wzy).elim id (λ h, (wt h).elim)
end
lemma is_preconnected_interval : is_preconnected (interval a b) := is_preconnected_Icc
lemma is_preconnected_iff_ord_connected {s : set α} :
is_preconnected s ↔ ord_connected s :=
⟨λ h x hx y hy, h.Icc_subset hx hy, λ h, is_preconnected_of_forall_pair $ λ x y hx hy,
⟨interval x y, h.interval_subset hx hy, left_mem_interval, right_mem_interval,
is_preconnected_interval⟩⟩
alias is_preconnected_iff_ord_connected ↔
is_preconnected.ord_connected set.ord_connected.is_preconnected
lemma is_preconnected_Ici : is_preconnected (Ici a) := ord_connected_Ici.is_preconnected
lemma is_preconnected_Iic : is_preconnected (Iic a) := ord_connected_Iic.is_preconnected
lemma is_preconnected_Iio : is_preconnected (Iio a) := ord_connected_Iio.is_preconnected
lemma is_preconnected_Ioi : is_preconnected (Ioi a) := ord_connected_Ioi.is_preconnected
lemma is_preconnected_Ioo : is_preconnected (Ioo a b) := ord_connected_Ioo.is_preconnected
lemma is_preconnected_Ioc : is_preconnected (Ioc a b) := ord_connected_Ioc.is_preconnected
lemma is_preconnected_Ico : is_preconnected (Ico a b) := ord_connected_Ico.is_preconnected
@[priority 100]
instance ordered_connected_space : preconnected_space α :=
⟨ord_connected_univ.is_preconnected⟩
/-- In a dense conditionally complete linear order, the set of preconnected sets is exactly
the set of the intervals `Icc`, `Ico`, `Ioc`, `Ioo`, `Ici`, `Ioi`, `Iic`, `Iio`, `(-∞, +∞)`,
or `∅`. Though one can represent `∅` as `(Inf s, Inf s)`, we include it into the list of
possible cases to improve readability. -/
lemma set_of_is_preconnected_eq_of_ordered :
{s : set α | is_preconnected s} =
-- bounded intervals
(range (uncurry Icc) ∪ range (uncurry Ico) ∪ range (uncurry Ioc) ∪ range (uncurry Ioo)) ∪
-- unbounded intervals and `univ`
(range Ici ∪ range Ioi ∪ range Iic ∪ range Iio ∪ {univ, ∅}) :=
begin
refine subset.antisymm set_of_is_preconnected_subset_of_ordered _,
simp only [subset_def, -mem_range, forall_range_iff, uncurry, or_imp_distrib, forall_and_distrib,
mem_union, mem_set_of_eq, insert_eq, mem_singleton_iff, forall_eq, forall_true_iff, and_true,
is_preconnected_Icc, is_preconnected_Ico, is_preconnected_Ioc,
is_preconnected_Ioo, is_preconnected_Ioi, is_preconnected_Iio, is_preconnected_Ici,
is_preconnected_Iic, is_preconnected_univ, is_preconnected_empty],
end
/--Intermediate Value Theorem for continuous functions on closed intervals, case `f a ≤ t ≤ f b`.-/
lemma intermediate_value_Icc {a b : α} (hab : a ≤ b) {f : α → β} (hf : continuous_on f (Icc a b)) :
Icc (f a) (f b) ⊆ f '' (Icc a b) :=
is_preconnected_Icc.intermediate_value (left_mem_Icc.2 hab) (right_mem_Icc.2 hab) hf
/--Intermediate Value Theorem for continuous functions on closed intervals, case `f a ≥ t ≥ f b`.-/
lemma intermediate_value_Icc' {a b : α} (hab : a ≤ b) {f : α → β} (hf : continuous_on f (Icc a b)) :
Icc (f b) (f a) ⊆ f '' (Icc a b) :=
is_preconnected_Icc.intermediate_value (right_mem_Icc.2 hab) (left_mem_Icc.2 hab) hf
/-- A continuous function which tendsto `at_top` `at_top` and to `at_bot` `at_bot` is surjective. -/
lemma surjective_of_continuous {f : α → β} (hf : continuous f) (h_top : tendsto f at_top at_top)
(h_bot : tendsto f at_bot at_bot) :
function.surjective f :=
begin
intros p,
obtain ⟨b, hb⟩ : ∃ b, p ≤ f b,
{ rcases ((tendsto_at_top_at_top _).mp h_top) p with ⟨b, hb⟩,
exact ⟨b, hb b rfl.ge⟩ },
obtain ⟨a, hab, ha⟩ : ∃ a, a ≤ b ∧ f a ≤ p,
{ rcases ((tendsto_at_bot_at_bot _).mp h_bot) p with ⟨x, hx⟩,
exact ⟨min x b, min_le_right x b, hx (min x b) (min_le_left x b)⟩ },
rcases intermediate_value_Icc hab hf.continuous_on ⟨ha, hb⟩ with ⟨x, _, hx⟩,
exact ⟨x, hx⟩
end
/-- A continuous function which tendsto `at_bot` `at_top` and to `at_top` `at_bot` is surjective. -/
lemma surjective_of_continuous' {f : α → β} (hf : continuous f) (h_top : tendsto f at_bot at_top)
(h_bot : tendsto f at_top at_bot) :
function.surjective f :=
@surjective_of_continuous (order_dual α) β _ _ _ _ _ _ _ _ hf h_top h_bot
end densely_ordered
lemma is_compact.Inf_mem {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
Inf s ∈ s :=
hs.is_closed.cInf_mem ne_s hs.bdd_below
lemma is_compact.Sup_mem {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
Sup s ∈ s :=
@is_compact.Inf_mem (order_dual α) _ _ _ _ hs ne_s
lemma is_compact.is_glb_Inf {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
is_glb s (Inf s) :=
is_glb_cInf ne_s hs.bdd_below
lemma is_compact.is_lub_Sup {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
is_lub s (Sup s) :=
@is_compact.is_glb_Inf (order_dual α) _ _ _ _ hs ne_s
lemma is_compact.is_least_Inf {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
is_least s (Inf s) :=
⟨hs.Inf_mem ne_s, (hs.is_glb_Inf ne_s).1⟩
lemma is_compact.is_greatest_Sup {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
is_greatest s (Sup s) :=
@is_compact.is_least_Inf (order_dual α) _ _ _ _ hs ne_s
lemma is_compact.exists_is_least {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
∃ x, is_least s x :=
⟨_, hs.is_least_Inf ne_s⟩
lemma is_compact.exists_is_greatest {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
∃ x, is_greatest s x :=
⟨_, hs.is_greatest_Sup ne_s⟩
lemma is_compact.exists_is_glb {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
∃ x ∈ s, is_glb s x :=
⟨_, hs.Inf_mem ne_s, hs.is_glb_Inf ne_s⟩
lemma is_compact.exists_is_lub {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
∃ x ∈ s, is_lub s x :=
⟨_, hs.Sup_mem ne_s, hs.is_lub_Sup ne_s⟩
lemma is_compact.exists_Inf_image_eq {α : Type u} [topological_space α]
{s : set α} (hs : is_compact s) (ne_s : s.nonempty) {f : α → β} (hf : continuous_on f s) :
∃ x ∈ s, Inf (f '' s) = f x :=
let ⟨x, hxs, hx⟩ := (hs.image_of_continuous_on hf).Inf_mem (ne_s.image f)
in ⟨x, hxs, hx.symm⟩
/-- The extreme value theorem: a continuous function realizes its minimum on a compact set -/
lemma is_compact.exists_forall_le {α : Type u} [topological_space α]
{s : set α} (hs : is_compact s) (ne_s : s.nonempty) {f : α → β} (hf : continuous_on f s) :
∃x∈s, ∀y∈s, f x ≤ f y :=
begin
rcases hs.exists_Inf_image_eq ne_s hf with ⟨x, hxs, hx⟩,
refine ⟨x, hxs, λ y hy, _⟩,
rw ← hx,
exact ((hs.image_of_continuous_on hf).is_glb_Inf (ne_s.image f)).1 (mem_image_of_mem _ hy)
end
/-- The extreme value theorem: a continuous function realizes its maximum on a compact set -/
lemma is_compact.exists_forall_ge {α : Type u} [topological_space α]:
∀ {s : set α}, is_compact s → s.nonempty → ∀ {f : α → β}, continuous_on f s →
∃x∈s, ∀y∈s, f y ≤ f x :=
@is_compact.exists_forall_le (order_dual β) _ _ _ _ _
lemma is_compact.exists_Sup_image_eq {α : Type u} [topological_space α]:
∀ {s : set α}, is_compact s → s.nonempty → ∀ {f : α → β}, continuous_on f s →
∃ x ∈ s, Sup (f '' s) = f x :=
@is_compact.exists_Inf_image_eq (order_dual β) _ _ _ _ _
lemma eq_Icc_of_connected_compact {s : set α} (h₁ : is_connected s) (h₂ : is_compact s) :
s = Icc (Inf s) (Sup s) :=
eq_Icc_cInf_cSup_of_connected_bdd_closed h₁ h₂.bdd_below h₂.bdd_above
h₂.is_closed
end conditionally_complete_linear_order
section liminf_limsup
section order_closed_topology
variables [semilattice_sup α] [topological_space α] [order_topology α]
lemma is_bounded_le_nhds (a : α) : (𝓝 a).is_bounded (≤) :=
match forall_le_or_exists_lt_sup a with
| or.inl h := ⟨a, eventually_of_forall h⟩
| or.inr ⟨b, hb⟩ := ⟨b, ge_mem_nhds hb⟩
end
lemma filter.tendsto.is_bounded_under_le {f : filter β} {u : β → α} {a : α}
(h : tendsto u f (𝓝 a)) : f.is_bounded_under (≤) u :=
(is_bounded_le_nhds a).mono h
lemma is_cobounded_ge_nhds (a : α) : (𝓝 a).is_cobounded (≥) :=
(is_bounded_le_nhds a).is_cobounded_flip
lemma filter.tendsto.is_cobounded_under_ge {f : filter β} {u : β → α} {a : α}
[ne_bot f] (h : tendsto u f (𝓝 a)) : f.is_cobounded_under (≥) u :=
h.is_bounded_under_le.is_cobounded_flip
end order_closed_topology
section order_closed_topology
variables [semilattice_inf α] [topological_space α] [order_topology α]
lemma is_bounded_ge_nhds (a : α) : (𝓝 a).is_bounded (≥) :=
@is_bounded_le_nhds (order_dual α) _ _ _ a
lemma filter.tendsto.is_bounded_under_ge {f : filter β} {u : β → α} {a : α}
(h : tendsto u f (𝓝 a)) : f.is_bounded_under (≥) u :=
(is_bounded_ge_nhds a).mono h
lemma is_cobounded_le_nhds (a : α) : (𝓝 a).is_cobounded (≤) :=
(is_bounded_ge_nhds a).is_cobounded_flip
lemma filter.tendsto.is_cobounded_under_le {f : filter β} {u : β → α} {a : α}
[ne_bot f] (h : tendsto u f (𝓝 a)) : f.is_cobounded_under (≤) u :=
h.is_bounded_under_ge.is_cobounded_flip
end order_closed_topology
section conditionally_complete_linear_order
variables [conditionally_complete_linear_order α]
theorem lt_mem_sets_of_Limsup_lt {f : filter α} {b} (h : f.is_bounded (≤)) (l : f.Limsup < b) :
∀ᶠ a in f, a < b :=
let ⟨c, (h : ∀ᶠ a in f, a ≤ c), hcb⟩ := exists_lt_of_cInf_lt h l in
mem_sets_of_superset h $ assume a hac, lt_of_le_of_lt hac hcb
theorem gt_mem_sets_of_Liminf_gt : ∀ {f : filter α} {b}, f.is_bounded (≥) → b < f.Liminf →
∀ᶠ a in f, b < a :=
@lt_mem_sets_of_Limsup_lt (order_dual α) _
variables [topological_space α] [order_topology α]
/-- If the liminf and the limsup of a filter coincide, then this filter converges to
their common value, at least if the filter is eventually bounded above and below. -/
theorem le_nhds_of_Limsup_eq_Liminf {f : filter α} {a : α}
(hl : f.is_bounded (≤)) (hg : f.is_bounded (≥)) (hs : f.Limsup = a) (hi : f.Liminf = a) :
f ≤ 𝓝 a :=
tendsto_order.2 $ and.intro
(assume b hb, gt_mem_sets_of_Liminf_gt hg $ hi.symm ▸ hb)
(assume b hb, lt_mem_sets_of_Limsup_lt hl $ hs.symm ▸ hb)
theorem Limsup_nhds (a : α) : Limsup (𝓝 a) = a :=
cInf_intro (is_bounded_le_nhds a)
(assume a' (h : {n : α | n ≤ a'} ∈ 𝓝 a), show a ≤ a', from @mem_of_nhds α _ a _ h)
(assume b (hba : a < b), show ∃c (h : {n : α | n ≤ c} ∈ 𝓝 a), c < b, from
match dense_or_discrete a b with
| or.inl ⟨c, hac, hcb⟩ := ⟨c, ge_mem_nhds hac, hcb⟩
| or.inr ⟨_, h⟩ := ⟨a, (𝓝 a).sets_of_superset (gt_mem_nhds hba) h, hba⟩
end)
theorem Liminf_nhds : ∀ (a : α), Liminf (𝓝 a) = a :=
@Limsup_nhds (order_dual α) _ _ _
/-- If a filter is converging, its limsup coincides with its limit. -/
theorem Liminf_eq_of_le_nhds {f : filter α} {a : α} [ne_bot f] (h : f ≤ 𝓝 a) : f.Liminf = a :=
have hb_ge : is_bounded (≥) f, from (is_bounded_ge_nhds a).mono h,
have hb_le : is_bounded (≤) f, from (is_bounded_le_nhds a).mono h,
le_antisymm
(calc f.Liminf ≤ f.Limsup : Liminf_le_Limsup hb_le hb_ge
... ≤ (𝓝 a).Limsup :
Limsup_le_Limsup_of_le h hb_ge.is_cobounded_flip (is_bounded_le_nhds a)
... = a : Limsup_nhds a)
(calc a = (𝓝 a).Liminf : (Liminf_nhds a).symm
... ≤ f.Liminf :
Liminf_le_Liminf_of_le h (is_bounded_ge_nhds a) hb_le.is_cobounded_flip)
/-- If a filter is converging, its liminf coincides with its limit. -/
theorem Limsup_eq_of_le_nhds : ∀ {f : filter α} {a : α} [ne_bot f], f ≤ 𝓝 a → f.Limsup = a :=
@Liminf_eq_of_le_nhds (order_dual α) _ _ _
/-- If a function has a limit, then its limsup coincides with its limit. -/
theorem filter.tendsto.limsup_eq {f : filter β} {u : β → α} {a : α} [ne_bot f]
(h : tendsto u f (𝓝 a)) : limsup f u = a :=
Limsup_eq_of_le_nhds h
/-- If a function has a limit, then its liminf coincides with its limit. -/
theorem filter.tendsto.liminf_eq {f : filter β} {u : β → α} {a : α} [ne_bot f]
(h : tendsto u f (𝓝 a)) : liminf f u = a :=
Liminf_eq_of_le_nhds h
end conditionally_complete_linear_order
section complete_linear_order
variables [complete_linear_order α] [topological_space α] [order_topology α]
-- In complete_linear_order, the above theorems take a simpler form
/-- If the liminf and the limsup of a function coincide, then the limit of the function
exists and has the same value -/
theorem tendsto_of_liminf_eq_limsup {f : filter β} {u : β → α} {a : α}
(hinf : liminf f u = a) (hsup : limsup f u = a) : tendsto u f (𝓝 a) :=
le_nhds_of_Limsup_eq_Liminf is_bounded_le_of_top is_bounded_ge_of_bot hsup hinf
/-- If a number `a` is less than or equal to the `liminf` of a function `f` at some filter
and is greater than or equal to the `limsup` of `f`, then `f` tends to `a` along this filter. -/
theorem tendsto_of_le_liminf_of_limsup_le {f : filter β} {u : β → α} {a : α}
(hinf : a ≤ liminf f u) (hsup : limsup f u ≤ a) :
tendsto u f (𝓝 a) :=
if hf : f = ⊥ then hf.symm ▸ tendsto_bot
else by haveI : ne_bot f := hf; exact tendsto_of_liminf_eq_limsup
(le_antisymm (le_trans liminf_le_limsup hsup) hinf)
(le_antisymm hsup (le_trans hinf liminf_le_limsup))
end complete_linear_order
end liminf_limsup
end order_topology
lemma order_topology_of_nhds_abs
{α : Type*} [decidable_linear_ordered_add_comm_group α] [topological_space α]
(h_nhds : ∀a:α, 𝓝 a = (⨅r>0, 𝓟 {b | abs (a - b) < r})) : order_topology α :=
order_topology.mk $ eq_of_nhds_eq_nhds $ assume a:α, le_antisymm_iff.mpr
begin
simp [infi_and, topological_space.nhds_generate_from,
h_nhds, le_infi_iff, -le_principal_iff, and_comm],
refine ⟨λ s ha b hs, _, λ r hr, _⟩,
{ rcases hs with rfl | rfl,
{ refine infi_le_of_le (a - b)
(infi_le_of_le (lt_sub_left_of_add_lt $ by simpa using ha) $
principal_mono.mpr $ assume c (hc : abs (a - c) < a - b), _),
have : a - c < a - b := lt_of_le_of_lt (le_abs_self _) hc,
exact lt_of_neg_lt_neg (lt_of_add_lt_add_left this) },
{ refine infi_le_of_le (b - a)
(infi_le_of_le (lt_sub_left_of_add_lt $ by simpa using ha) $
principal_mono.mpr $ assume c (hc : abs (a - c) < b - a), _),
have : abs (c - a) < b - a, {rw abs_sub; simpa using hc},
have : c - a < b - a := lt_of_le_of_lt (le_abs_self _) this,
exact lt_of_add_lt_add_right this } },
{ have h : {b | abs (a - b) < r} = {b | a - r < b} ∩ {b | b < a + r},
from set.ext (assume b,
by simp [abs_lt, sub_lt, lt_sub_iff_add_lt, sub_lt_iff_lt_add']; cc),
rw [h, ← inf_principal],
apply le_inf _ _,
{ exact infi_le_of_le {b : α | a - r < b} (infi_le_of_le (sub_lt_self a hr) $
infi_le_of_le (a - r) $ infi_le _ (or.inl rfl)) },
{ exact infi_le_of_le {b : α | b < a + r} (infi_le_of_le (lt_add_of_pos_right _ hr) $
infi_le_of_le (a + r) $ infi_le _ (or.inr rfl)) } }
end
/-- $\lim_{x\to+\infty}|x|=+\infty$ -/
lemma tendsto_abs_at_top_at_top [decidable_linear_ordered_add_comm_group α] :
tendsto (abs : α → α) at_top at_top :=
tendsto_at_top_mono (λ n, le_abs_self _) tendsto_id
local notation `|` x `|` := abs x
lemma decidable_linear_ordered_add_comm_group.tendsto_nhds
[decidable_linear_ordered_add_comm_group α] [topological_space α] [order_topology α] {β : Type*}
(f : β → α) (x : filter β) (a : α) :
filter.tendsto f x (nhds a) ↔ ∀ ε > (0 : α), ∀ᶠ b in x, |f b - a| < ε :=
begin
rw (show _, from @tendsto_order α), -- does not work without `show` for some reason
split,
{ rintros ⟨hyp_lt_a, hyp_gt_a⟩ ε ε_pos,
suffices : {b : β | f b - a < ε ∧ a - f b < ε} ∈ x, by simpa only [abs_sub_lt_iff],
have set1 : {b : β | a - f b < ε} ∈ x,
{ have : {b : β | a - ε < f b} ∈ x, from hyp_lt_a (a - ε) (sub_lt_self a ε_pos),
have : ∀ b, a - f b < ε ↔ a - ε < f b, by { intro _, exact sub_lt },
simpa only [this] },
have set2 : {b : β | f b - a < ε} ∈ x,
{ have : {b : β | a + ε > f b} ∈ x, from hyp_gt_a (a + ε) (lt_add_of_pos_right a ε_pos),
have : ∀ b, f b - a < ε ↔ a + ε > f b, by { intro _, exact sub_lt_iff_lt_add' },
simpa only [this] },
exact (x.inter_sets set2 set1) },
{ assume hyp_ε_pos,
split,
{ assume a' a'_lt_a,
let ε := a - a',
have : {b : β | |f b - a| < ε} ∈ x, from hyp_ε_pos ε (sub_pos.elim_right a'_lt_a),
have : {b : β | f b - a < ε ∧ a - f b < ε} ∈ x, by simpa only [abs_sub_lt_iff] using this,
have : {b : β | a - f b < ε} ∈ x, from x.sets_of_superset this (set.inter_subset_right _ _),
have : ∀ b, a' < f b ↔ a - f b < ε, by {intro b, rw [sub_lt, sub_sub_self] },
simpa only [this] },
{ assume a' a'_gt_a,
let ε := a' - a,
have : {b : β | |f b - a| < ε} ∈ x, from hyp_ε_pos ε (sub_pos.elim_right a'_gt_a),
have : {b : β | f b - a < ε ∧ a - f b < ε} ∈ x, by simpa only [abs_sub_lt_iff] using this,
have : {b : β | f b - a < ε} ∈ x, from x.sets_of_superset this (set.inter_subset_left _ _),
have : ∀ b, f b < a' ↔ f b - a < ε, by { intro b, simp [lt_sub_iff_add_lt] },
simpa only [this] }}
end
/-!
Here is a counter-example to a version of the following with `conditionally_complete_lattice α`.
Take `α = [0, 1) → ℝ` with the natural lattice structure, `ι = ℕ`. Put `f n x = -x^n`. Then
`⨆ n, f n = 0` while none of `f n` is strictly greater than the constant function `-0.5`.
-/
lemma tendsto_at_top_csupr {ι α : Type*} [preorder ι] [topological_space α]
[conditionally_complete_linear_order α] [order_topology α]
{f : ι → α} (h_mono : monotone f) (hbdd : bdd_above $ range f) :
tendsto f at_top (𝓝 (⨆i, f i)) :=
begin
by_cases hi : nonempty ι,
{ resetI,
rw tendsto_order,
split,
{ intros a h,
cases exists_lt_of_lt_csupr h with N hN,
apply eventually.mono (mem_at_top N),
exact λ i hi, lt_of_lt_of_le hN (h_mono hi) },
{ exact λ a h, eventually_of_forall (λ n, lt_of_le_of_lt (le_csupr hbdd n) h) } },
{ exact tendsto_of_not_nonempty hi }
end
lemma tendsto_at_top_cinfi {ι α : Type*} [preorder ι] [topological_space α]
[conditionally_complete_linear_order α] [order_topology α]
{f : ι → α} (h_mono : ∀ ⦃i j⦄, i ≤ j → f j ≤ f i) (hbdd : bdd_below $ range f) :
tendsto f at_top (𝓝 (⨅i, f i)) :=
@tendsto_at_top_csupr _ (order_dual α) _ _ _ _ _ @h_mono hbdd
lemma tendsto_at_top_supr {ι α : Type*} [preorder ι] [topological_space α]
[complete_linear_order α] [order_topology α] {f : ι → α} (h_mono : monotone f) :
tendsto f at_top (𝓝 (⨆i, f i)) :=
tendsto_at_top_csupr h_mono (order_top.bdd_above _)
lemma tendsto_at_top_infi {ι α : Type*} [preorder ι] [topological_space α]
[complete_linear_order α] [order_topology α] {f : ι → α} (h_mono : ∀ ⦃i j⦄, i ≤ j → f j ≤ f i) :
tendsto f at_top (𝓝 (⨅i, f i)) :=
tendsto_at_top_cinfi @h_mono (order_bot.bdd_below _)
lemma tendsto_of_monotone {ι α : Type*} [preorder ι] [topological_space α]
[conditionally_complete_linear_order α] [order_topology α] {f : ι → α} (h_mono : monotone f) :
tendsto f at_top at_top ∨ (∃ l, tendsto f at_top (𝓝 l)) :=
if H : bdd_above (range f) then or.inr ⟨_, tendsto_at_top_csupr h_mono H⟩
else or.inl $ tendsto_at_top_at_top_of_monotone' h_mono H
lemma supr_eq_of_tendsto {α β} [topological_space α] [complete_linear_order α] [order_topology α]
[nonempty β] [semilattice_sup β] {f : β → α} {a : α} (hf : monotone f) :
tendsto f at_top (𝓝 a) → supr f = a :=
tendsto_nhds_unique (tendsto_at_top_supr hf)
lemma infi_eq_of_tendsto {α} [topological_space α] [complete_linear_order α] [order_topology α]
[nonempty β] [semilattice_sup β] {f : β → α} {a : α} (hf : ∀n m, n ≤ m → f m ≤ f n) :
tendsto f at_top (𝓝 a) → infi f = a :=
tendsto_nhds_unique (tendsto_at_top_infi hf)
@[to_additive] lemma tendsto_inv_nhds_within_Ioi [ordered_comm_group α]
[topological_space α] [topological_group α] {a : α} :
tendsto has_inv.inv (𝓝[Ioi a] a) (𝓝[Iio (a⁻¹)] (a⁻¹)) :=
(continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal]
@[to_additive] lemma tendsto_inv_nhds_within_Iio [ordered_comm_group α]
[topological_space α] [topological_group α] {a : α} :
tendsto has_inv.inv (𝓝[Iio a] a) (𝓝[Ioi (a⁻¹)] (a⁻¹)) :=
(continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal]
@[to_additive] lemma tendsto_inv_nhds_within_Ioi_inv [ordered_comm_group α]
[topological_space α] [topological_group α] {a : α} :
tendsto has_inv.inv (𝓝[Ioi (a⁻¹)] (a⁻¹)) (𝓝[Iio a] a) :=
by simpa only [inv_inv] using @tendsto_inv_nhds_within_Ioi _ _ _ _ (a⁻¹)
@[to_additive] lemma tendsto_inv_nhds_within_Iio_inv [ordered_comm_group α]
[topological_space α] [topological_group α] {a : α} :
tendsto has_inv.inv (𝓝[Iio (a⁻¹)] (a⁻¹)) (𝓝[Ioi a] a) :=
by simpa only [inv_inv] using @tendsto_inv_nhds_within_Iio _ _ _ _ (a⁻¹)
@[to_additive] lemma tendsto_inv_nhds_within_Ici [ordered_comm_group α]
[topological_space α] [topological_group α] {a : α} :
tendsto has_inv.inv (𝓝[Ici a] a) (𝓝[Iic (a⁻¹)] (a⁻¹)) :=
(continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal]
@[to_additive] lemma tendsto_inv_nhds_within_Iic [ordered_comm_group α]
[topological_space α] [topological_group α] {a : α} :
tendsto has_inv.inv (𝓝[Iic a] a) (𝓝[Ici (a⁻¹)] (a⁻¹)) :=
(continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal]
@[to_additive] lemma tendsto_inv_nhds_within_Ici_inv [ordered_comm_group α]
[topological_space α] [topological_group α] {a : α} :
tendsto has_inv.inv (𝓝[Ici (a⁻¹)] (a⁻¹)) (𝓝[Iic a] a) :=
by simpa only [inv_inv] using @tendsto_inv_nhds_within_Ici _ _ _ _ (a⁻¹)
@[to_additive] lemma tendsto_inv_nhds_within_Iic_inv [ordered_comm_group α]
[topological_space α] [topological_group α] {a : α} :
tendsto has_inv.inv (𝓝[Iic (a⁻¹)] (a⁻¹)) (𝓝[Ici a] a) :=
by simpa only [inv_inv] using @tendsto_inv_nhds_within_Iic _ _ _ _ (a⁻¹)
lemma nhds_left_sup_nhds_right (a : α) [topological_space α] [linear_order α] :
nhds_within a (Iic a) ⊔ nhds_within a (Ici a) = 𝓝 a :=
by rw [← nhds_within_union, Iic_union_Ici, nhds_within_univ]
lemma nhds_left'_sup_nhds_right (a : α) [topological_space α] [linear_order α] :
nhds_within a (Iio a) ⊔ nhds_within a (Ici a) = 𝓝 a :=
by rw [← nhds_within_union, Iio_union_Ici, nhds_within_univ]
lemma nhds_left_sup_nhds_right' (a : α) [topological_space α] [linear_order α] :
nhds_within a (Iic a) ⊔ nhds_within a (Ioi a) = 𝓝 a :=
by rw [← nhds_within_union, Iic_union_Ioi, nhds_within_univ]
lemma continuous_at_iff_continuous_left_right [topological_space α] [linear_order α]
[topological_space β] {a : α} {f : α → β} :
continuous_at f a ↔ continuous_within_at f (Iic a) a ∧ continuous_within_at f (Ici a) a :=
by simp only [continuous_within_at, continuous_at, ← tendsto_sup, nhds_left_sup_nhds_right]
lemma continuous_on_Icc_extend_from_Ioo [topological_space α] [linear_order α] [densely_ordered α]
[order_topology α] [topological_space β] [regular_space β] {f : α → β} {a b : α}
{la lb : β} (hab : a < b) (hf : continuous_on f (Ioo a b))
(ha : tendsto f (nhds_within a $ Ioi a) (𝓝 la))
(hb : tendsto f (nhds_within b $ Iio b) (𝓝 lb)) :
continuous_on (extend_from (Ioo a b) f) (Icc a b) :=
begin
apply continuous_on_extend_from,
{ rw closure_Ioo hab, },
{ intros x x_in,
rcases mem_Ioo_or_eq_endpoints_of_mem_Icc x_in with rfl | rfl | h,
{ use la,
simpa [hab] },
{ use lb,
simpa [hab] },
{ use [f x, hf x h] } }
end
lemma eq_lim_at_left_extend_from_Ioo [topological_space α] [linear_order α] [densely_ordered α]
[order_topology α] [topological_space β] [t2_space β] {f : α → β} {a b : α}
{la : β} (hab : a < b) (ha : tendsto f (nhds_within a $ Ioi a) (𝓝 la)) :
extend_from (Ioo a b) f a = la :=
begin
apply extend_from_eq,
{ rw closure_Ioo hab,
simp only [le_of_lt hab, left_mem_Icc, right_mem_Icc] },
{ simpa [hab] }
end
lemma eq_lim_at_right_extend_from_Ioo [topological_space α] [linear_order α] [densely_ordered α]
[order_topology α] [topological_space β] [t2_space β] {f : α → β} {a b : α}
{lb : β} (hab : a < b) (hb : tendsto f (nhds_within b $ Iio b) (𝓝 lb)) :
extend_from (Ioo a b) f b = lb :=
begin
apply extend_from_eq,
{ rw closure_Ioo hab,
simp only [le_of_lt hab, left_mem_Icc, right_mem_Icc] },
{ simpa [hab] }
end
lemma continuous_on_Ico_extend_from_Ioo [topological_space α]
[linear_order α] [densely_ordered α] [order_topology α] [topological_space β]
[regular_space β] {f : α → β} {a b : α} {la : β} (hab : a < b) (hf : continuous_on f (Ioo a b))
(ha : tendsto f (nhds_within a $ Ioi a) (𝓝 la)) :
continuous_on (extend_from (Ioo a b) f) (Ico a b) :=
begin
apply continuous_on_extend_from,
{ rw [closure_Ioo hab], exact Ico_subset_Icc_self, },
{ intros x x_in,
rcases mem_Ioo_or_eq_left_of_mem_Ico x_in with rfl | h,
{ use la,
simpa [hab] },
{ use [f x, hf x h] } }
end
lemma continuous_on_Ioc_extend_from_Ioo [topological_space α]
[linear_order α] [densely_ordered α] [order_topology α] [topological_space β]
[regular_space β] {f : α → β} {a b : α} {lb : β} (hab : a < b) (hf : continuous_on f (Ioo a b))
(hb : tendsto f (nhds_within b $ Iio b) (𝓝 lb)) :
continuous_on (extend_from (Ioo a b) f) (Ioc a b) :=
begin
have := @continuous_on_Ico_extend_from_Ioo (order_dual α) _ _ _ _ _ _ _ f _ _ _ hab,
erw [dual_Ico, dual_Ioi, dual_Ioo] at this,
exact this hf hb
end
lemma continuous_within_at_Ioi_iff_Ici {α β : Type*} [topological_space α] [partial_order α]
[topological_space β] {a : α} {f : α → β} :
continuous_within_at f (Ioi a) a ↔ continuous_within_at f (Ici a) a :=
by simp only [← Ici_diff_left, continuous_within_at_diff_self]
lemma continuous_within_at_Iio_iff_Iic
{α β : Type*} [topological_space α] [linear_order α] [topological_space β] {a : α} {f : α → β} :
continuous_within_at f (Iio a) a ↔ continuous_within_at f (Iic a) a :=
begin
have := @continuous_within_at_Ioi_iff_Ici (order_dual α) _ _ _ _ _ f,
erw [dual_Ici, dual_Ioi] at this,
exact this,
end
lemma continuous_at_iff_continuous_left'_right' [topological_space α] [linear_order α]
[topological_space β] {a : α} {f : α → β} :
continuous_at f a ↔ continuous_within_at f (Iio a) a ∧ continuous_within_at f (Ioi a) a :=
by rw [continuous_within_at_Ioi_iff_Ici, continuous_within_at_Iio_iff_Iic,
continuous_at_iff_continuous_left_right]
section homeomorphisms
variables [topological_space α] [topological_space β]
section linear_order
variables [linear_order α] [order_topology α]
variables [linear_order β] [order_topology β]
/-- If `f : α → β` is strictly monotone and surjective, it is everywhere continuous. -/
lemma continuous_at_of_strict_mono_surjective
{f : α → β} (h_mono : strict_mono f) (h_surj : function.surjective f) (a : α) :
continuous_at f a :=
continuous_at_iff_continuous_left_right.mpr
⟨continuous_left_of_strict_mono_surjective h_mono h_surj a,
continuous_right_of_strict_mono_surjective h_mono h_surj a⟩
/-- If `f : α → β` is strictly monotone and surjective, it is continuous. -/
lemma continuous_of_strict_mono_surjective
{f : α → β} (h_mono : strict_mono f) (h_surj : function.surjective f) :
continuous f :=
continuous_iff_continuous_at.mpr (continuous_at_of_strict_mono_surjective h_mono h_surj)
/-- If `f : α ≃ β` is strictly monotone, its inverse is continuous. -/
lemma continuous_inv_of_strict_mono_equiv (e : α ≃ β) (h_mono : strict_mono e.to_fun) :
continuous e.inv_fun :=
begin
have hinv_mono : strict_mono e.inv_fun,
{ intros x y hxy,
rw [← h_mono.lt_iff_lt, e.right_inv, e.right_inv],
exact hxy },
have hinv_surj : function.surjective e.inv_fun,
{ intros x,
exact ⟨e.to_fun x, e.left_inv x⟩ },
exact continuous_of_strict_mono_surjective hinv_mono hinv_surj
end
/-- If `f : α → β` is strictly monotone and surjective, it is a homeomorphism. -/
noncomputable def homeomorph_of_strict_mono_surjective
(f : α → β) (h_mono : strict_mono f) (h_surj : function.surjective f) :
homeomorph α β :=
{ to_equiv := equiv.of_bijective f ⟨strict_mono.injective h_mono, h_surj⟩,
continuous_to_fun := continuous_of_strict_mono_surjective h_mono h_surj,
continuous_inv_fun := continuous_inv_of_strict_mono_equiv
(equiv.of_bijective f ⟨strict_mono.injective h_mono, h_surj⟩) h_mono }
@[simp] lemma coe_homeomorph_of_strict_mono_surjective
(f : α → β) (h_mono : strict_mono f) (h_surj : function.surjective f) :
(homeomorph_of_strict_mono_surjective f h_mono h_surj : α → β) = f := rfl
end linear_order
section conditionally_complete_linear_order
variables [conditionally_complete_linear_order α] [densely_ordered α] [order_topology α]
variables [conditionally_complete_linear_order β] [order_topology β]
/-- If `f : α → β` is strictly monotone and continuous, and tendsto `at_top` `at_top` and to
`at_bot` `at_bot`, then it is a homeomorphism. -/
noncomputable def homeomorph_of_strict_mono_continuous
(f : α → β) (h_mono : strict_mono f) (h_cont : continuous f) (h_top : tendsto f at_top at_top)
(h_bot : tendsto f at_bot at_bot) :
homeomorph α β :=
homeomorph_of_strict_mono_surjective f h_mono (surjective_of_continuous h_cont h_top h_bot)
@[simp] lemma coe_homeomorph_of_strict_mono_continuous
(f : α → β) (h_mono : strict_mono f) (h_cont : continuous f) (h_top : tendsto f at_top at_top)
(h_bot : tendsto f at_bot at_bot) :
(homeomorph_of_strict_mono_continuous f h_mono h_cont h_top h_bot : α → β) = f := rfl
/- Now we prove a relative version of the above result. This (`Ioo` to `univ`) is provided as a
sample; there are at least 16 possible variations with open intervals (`univ` to `Ioo`, `Ioi` to
`univ`, ...), not to mention the possibilities with closed or half-closed intervals. -/
variables {a b : α}
/-- If `f : α → β` is strictly monotone and continuous on the interval `Ioo a b` of `α`, and tends
to `at_top` within `𝓝[Iio b] b` and to `at_bot` within `𝓝[Ioi a] a`, then it restricts to a
homeomorphism from `Ioo a b` to `β`. -/
noncomputable def homeomorph_of_strict_mono_continuous_Ioo
(f : α → β) (h : a < b)
(h_mono : ∀ ⦃x y : α⦄, a < x → y < b → x < y → f x < f y)
(h_cont : continuous_on f (Ioo a b))
(h_top : tendsto f (𝓝[Iio b] b) at_top)
(h_bot : tendsto f (𝓝[Ioi a] a) at_bot) :
homeomorph (Ioo a b) β :=
@homeomorph_of_strict_mono_continuous _ _ _ _
(@ord_connected_subset_conditionally_complete_linear_order α (Ioo a b) _
⟨classical.choice (nonempty_Ioo_subtype h)⟩ _)
_ _ _ _
(restrict f (Ioo a b))
(λ x y, h_mono x.2.1 y.2.2)
(continuous_on_iff_continuous_restrict.mp h_cont)
begin
rw [restrict_eq f (Ioo a b), Ioo_at_top_eq_nhds_within h],
exact h_top.comp tendsto_comap
end
begin
rw [restrict_eq f (Ioo a b), Ioo_at_bot_eq_nhds_within h],
exact h_bot.comp tendsto_comap
end
@[simp] lemma coe_homeomorph_of_strict_mono_continuous_Ioo
(f : α → β) (h : a < b)
(h_mono : ∀ ⦃x y : α⦄, a < x → y < b → x < y → f x < f y)
(h_cont : continuous_on f (Ioo a b))
(h_top : tendsto f (𝓝[Iio b] b) at_top)
(h_bot : tendsto f (𝓝[Ioi a] a) at_bot) :
(homeomorph_of_strict_mono_continuous_Ioo f h h_mono h_cont h_top h_bot : Ioo a b → β)
= restrict f (Ioo a b) :=
rfl
end conditionally_complete_linear_order
end homeomorphisms
|
f563a7630b46fc7fad31fe8aafb53f84e7121603 | 38bf3fd2bb651ab70511408fcf70e2029e2ba310 | /src/data/multiset.lean | ed634a9f0c2b7047d4809aa15056fc596785ac11 | [
"Apache-2.0"
] | permissive | JaredCorduan/mathlib | 130392594844f15dad65a9308c242551bae6cd2e | d5de80376088954d592a59326c14404f538050a1 | refs/heads/master | 1,595,862,206,333 | 1,570,816,457,000 | 1,570,816,457,000 | 209,134,499 | 0 | 0 | Apache-2.0 | 1,568,746,811,000 | 1,568,746,811,000 | null | UTF-8 | Lean | false | false | 133,547 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Multisets.
-/
import logic.function order.boolean_algebra
data.equiv.basic data.list.basic data.list.perm data.list.sort data.quot data.string
algebra.order_functions algebra.group_power algebra.ordered_group
category.traversable.lemmas tactic.interactive
category.traversable.instances category.basic
open list subtype nat lattice
variables {α : Type*} {β : Type*} {γ : Type*}
open_locale add_monoid
/-- `multiset α` is the quotient of `list α` by list permutation. The result
is a type of finite sets with duplicates allowed. -/
def {u} multiset (α : Type u) : Type u :=
quotient (list.is_setoid α)
namespace multiset
instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩
@[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl
@[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl
@[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl
@[simp] theorem coe_eq_coe {l₁ l₂ : list α} : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq
instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α)
| s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂,
decidable_of_iff' _ quotient.eq
/- empty multiset -/
/-- `0 : multiset α` is the empty set -/
protected def zero : multiset α := @nil α
instance : has_zero (multiset α) := ⟨multiset.zero⟩
instance : has_emptyc (multiset α) := ⟨0⟩
instance : inhabited (multiset α) := ⟨0⟩
@[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl
@[simp] theorem empty_eq_zero : (∅ : multiset α) = 0 := rfl
theorem coe_eq_zero (l : list α) : (l : multiset α) = 0 ↔ l = [] :=
iff.trans coe_eq_coe perm_nil
/- cons -/
/-- `cons a s` is the multiset which contains `s` plus one more
instance of `a`. -/
def cons (a : α) (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (a :: l : multiset α))
(λ l₁ l₂ p, quot.sound ((perm_cons a).2 p))
notation a :: b := cons a b
instance : has_insert α (multiset α) := ⟨cons⟩
@[simp] theorem insert_eq_cons (a : α) (s : multiset α) :
insert a s = a::s := rfl
@[simp] theorem cons_coe (a : α) (l : list α) :
(a::l : multiset α) = (a::l : list α) := rfl
theorem singleton_coe (a : α) : (a::0 : multiset α) = ([a] : list α) := rfl
@[simp] theorem cons_inj_left {a b : α} (s : multiset α) :
a::s = b::s ↔ a = b :=
⟨quot.induction_on s $ λ l e,
have [a] ++ l ~ [b] ++ l, from quotient.exact e,
eq_singleton_of_perm $ (perm_app_right_iff _).1 this, congr_arg _⟩
@[simp] theorem cons_inj_right (a : α) : ∀{s t : multiset α}, a::s = a::t ↔ s = t :=
by rintros ⟨l₁⟩ ⟨l₂⟩; simp [perm_cons]
@[recursor 5] protected theorem induction {p : multiset α → Prop}
(h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : ∀s, p s :=
by rintros ⟨l⟩; induction l with _ _ ih; [exact h₁, exact h₂ ih]
@[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop}
(s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : p s :=
multiset.induction h₁ h₂ s
theorem cons_swap (a b : α) (s : multiset α) : a :: b :: s = b :: a :: s :=
quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _
section rec
variables {C : multiset α → Sort*}
/-- Dependent recursor on multisets.
TODO: should be @[recursor 6], but then the definition of `multiset.pi` failes with a stack
overflow in `whnf`.
-/
protected def rec
(C_0 : C 0)
(C_cons : Πa m, C m → C (a::m))
(C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b))
(m : multiset α) : C m :=
quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $
assume l l' h,
list.rec_heq_of_perm h
(assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc)
(assume a a' l, C_cons_heq a a' ⟦l⟧)
@[elab_as_eliminator]
protected def rec_on (m : multiset α)
(C_0 : C 0)
(C_cons : Πa m, C m → C (a::m))
(C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) :
C m :=
multiset.rec C_0 C_cons C_cons_heq m
variables {C_0 : C 0} {C_cons : Πa m, C m → C (a::m)}
{C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)}
@[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 :=
rfl
@[simp] lemma rec_on_cons (a : α) (m : multiset α) :
(a :: m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) :=
quotient.induction_on m $ assume l, rfl
end rec
section mem
/-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/
def mem (a : α) (s : multiset α) : Prop :=
quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ mem_of_perm e)
instance : has_mem α (multiset α) := ⟨mem⟩
@[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl
instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) :=
quot.rec_on_subsingleton s $ list.decidable_mem a
@[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b :: s ↔ a = b ∨ a ∈ s :=
quot.induction_on s $ λ l, iff.rfl
lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b :: s :=
mem_cons.2 $ or.inr h
@[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a :: s :=
mem_cons.2 (or.inl rfl)
theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a :: t :=
quot.induction_on s $ λ l (h : a ∈ l),
let ⟨l₁, l₂, e⟩ := mem_split h in
e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩
@[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id
theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 :=
quot.induction_on s $ λ l H, by rw eq_nil_iff_forall_not_mem.mpr H; refl
theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s :=
quot.induction_on s $ assume l hl,
match l, hl with
| [] := assume h, false.elim $ h rfl
| (a :: l) := assume _, ⟨a, by simp⟩
end
@[simp] lemma zero_ne_cons {a : α} {m : multiset α} : 0 ≠ a :: m :=
assume h, have a ∈ (0:multiset α), from h.symm ▸ mem_cons_self _ _, not_mem_zero _ this
@[simp] lemma cons_ne_zero {a : α} {m : multiset α} : a :: m ≠ 0 := zero_ne_cons.symm
lemma cons_eq_cons {a b : α} {as bs : multiset α} :
a :: as = b :: bs ↔ ((a = b ∧ as = bs) ∨ (a ≠ b ∧ ∃cs, as = b :: cs ∧ bs = a :: cs)) :=
begin
haveI : decidable_eq α := classical.dec_eq α,
split,
{ assume eq,
by_cases a = b,
{ subst h, simp * at * },
{ have : a ∈ b :: bs, from eq ▸ mem_cons_self _ _,
have : a ∈ bs, by simpa [h],
rcases exists_cons_of_mem this with ⟨cs, hcs⟩,
simp [h, hcs],
have : a :: as = b :: a :: cs, by simp [eq, hcs],
have : a :: as = a :: b :: cs, by rwa [cons_swap],
simpa using this } },
{ assume h,
rcases h with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩,
{ simp * },
{ simp [*, cons_swap a b] } }
end
end mem
/- subset -/
section subset
/-- `s ⊆ t` is the lift of the list subset relation. It means that any
element with nonzero multiplicity in `s` has nonzero multiplicity in `t`,
but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`;
see `s ≤ t` for this relation. -/
protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t
instance : has_subset (multiset α) := ⟨multiset.subset⟩
@[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl
@[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h
theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u :=
λ h₁ h₂ a m, h₂ (h₁ m)
theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl
theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _
@[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s :=
λ a, (not_mem_nil a).elim
@[simp] theorem cons_subset {a : α} {s t : multiset α} : (a :: s) ⊆ t ↔ a ∈ t ∧ s ⊆ t :=
by simp [subset_iff, or_imp_distrib, forall_and_distrib]
theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 :=
eq_zero_of_forall_not_mem h
theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 :=
⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩
end subset
/- multiset order -/
/-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation).
Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/
protected def le (s t : multiset α) : Prop :=
quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
propext (p₂.subperm_left.trans p₁.subperm_right)
instance : partial_order (multiset α) :=
{ le := multiset.le,
le_refl := by rintros ⟨l⟩; exact subperm.refl _,
le_trans := by rintros ⟨l₁⟩ ⟨l₂⟩ ⟨l₃⟩; exact @subperm.trans _ _ _ _,
le_antisymm := by rintros ⟨l₁⟩ ⟨l₂⟩ h₁ h₂; exact quot.sound (subperm.antisymm h₁ h₂) }
theorem subset_of_le {s t : multiset α} : s ≤ t → s ⊆ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, subset_of_subperm
theorem mem_of_le {s t : multiset α} {a : α} (h : s ≤ t) : a ∈ s → a ∈ t :=
mem_of_subset (subset_of_le h)
@[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl
@[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop}
{s t : multiset α} (h : s ≤ t)
(H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t :=
quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩,
(show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h
theorem zero_le (s : multiset α) : 0 ≤ s :=
quot.induction_on s $ λ l, subperm_of_sublist $ nil_sublist l
theorem le_zero {s : multiset α} : s ≤ 0 ↔ s = 0 :=
⟨λ h, le_antisymm h (zero_le _), le_of_eq⟩
theorem lt_cons_self (s : multiset α) (a : α) : s < a :: s :=
quot.induction_on s $ λ l,
suffices l <+~ a :: l ∧ (¬l ~ a :: l),
by simpa [lt_iff_le_and_ne],
⟨subperm_of_sublist (sublist_cons _ _),
λ p, ne_of_lt (lt_succ_self (length l)) (perm_length p)⟩
theorem le_cons_self (s : multiset α) (a : α) : s ≤ a :: s :=
le_of_lt $ lt_cons_self _ _
theorem cons_le_cons_iff (a : α) {s t : multiset α} : a :: s ≤ a :: t ↔ s ≤ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a
theorem cons_le_cons (a : α) {s t : multiset α} : s ≤ t → a :: s ≤ a :: t :=
(cons_le_cons_iff a).2
theorem le_cons_of_not_mem {a : α} {s t : multiset α} (m : a ∉ s) : s ≤ a :: t ↔ s ≤ t :=
begin
refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩,
suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a :: s ≤ t',
{ exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) },
introv h, revert m, refine le_induction_on h _,
introv s m₁ m₂,
rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩,
exact perm_middle.subperm_left.2 ((subperm_cons _).2 $ subperm_of_sublist $
(sublist_or_mem_of_sublist s).resolve_right m₁)
end
/- cardinality -/
/-- The cardinality of a multiset is the sum of the multiplicities
of all its elements, or simply the length of the underlying list. -/
def card (s : multiset α) : ℕ :=
quot.lift_on s length $ λ l₁ l₂, perm_length
@[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl
@[simp] theorem card_zero : @card α 0 = 0 := rfl
@[simp] theorem card_cons (a : α) (s : multiset α) : card (a :: s) = card s + 1 :=
quot.induction_on s $ λ l, rfl
@[simp] theorem card_singleton (a : α) : card (a::0) = 1 := by simp
theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t :=
le_induction_on h $ λ l₁ l₂, length_le_of_sublist
theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t :=
le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂
theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t :=
lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂
theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a :: s ≤ t :=
⟨quotient.induction_on₂ s t $ λ l₁ l₂ h,
subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h),
λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩
@[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 :=
⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩
theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 :=
pos_iff_ne_zero.trans $ not_congr card_eq_zero
theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s :=
quot.induction_on s $ λ l, length_pos_iff_exists_mem
@[elab_as_eliminator] def strong_induction_on {p : multiset α → Sort*} :
∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s
| s := λ ih, ih s $ λ t h,
have card t < card s, from card_lt_of_lt h,
strong_induction_on t ih
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]}
theorem strong_induction_eq {p : multiset α → Sort*}
(s : multiset α) (H) : @strong_induction_on _ p s H =
H s (λ t h, @strong_induction_on _ p t H) :=
by rw [strong_induction_on]
@[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop}
(s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a :: s)) : p s :=
multiset.strong_induction_on s $ assume s,
multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $
λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _
/- singleton -/
@[simp] theorem singleton_eq_singleton (a : α) : singleton a = a::0 := rfl
@[simp] theorem mem_singleton {a b : α} : b ∈ a::0 ↔ b = a := by simp
theorem mem_singleton_self (a : α) : a ∈ (a::0 : multiset α) := mem_cons_self _ _
theorem singleton_inj {a b : α} : a::0 = b::0 ↔ a = b := cons_inj_left _
@[simp] theorem singleton_ne_zero (a : α) : a::0 ≠ 0 :=
ne_of_gt (lt_cons_self _ _)
@[simp] theorem singleton_le {a : α} {s : multiset α} : a::0 ≤ s ↔ a ∈ s :=
⟨λ h, mem_of_le h (mem_singleton_self _),
λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩
theorem card_eq_one {s : multiset α} : card s = 1 ↔ ∃ a, s = a::0 :=
⟨quot.induction_on s $ λ l h,
(list.length_eq_one.1 h).imp $ λ a, congr_arg coe,
λ ⟨a, e⟩, e.symm ▸ rfl⟩
/- add -/
/-- The sum of two multisets is the lift of the list append operation.
This adds the multiplicities of each element,
i.e. `count a (s + t) = count a s + count a t`. -/
protected def add (s₁ s₂ : multiset α) : multiset α :=
quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $
λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_app p₁ p₂
instance : has_add (multiset α) := ⟨multiset.add⟩
@[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl
protected theorem add_comm (s t : multiset α) : s + t = t + s :=
quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_app_comm
protected theorem zero_add (s : multiset α) : 0 + s = s :=
quot.induction_on s $ λ l, rfl
theorem singleton_add (a : α) (s : multiset α) : ↑[a] + s = a::s := rfl
protected theorem add_le_add_left (s) {t u : multiset α} : s + t ≤ s + u ↔ t ≤ u :=
quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_app_left _
protected theorem add_left_cancel (s) {t u : multiset α} (h : s + t = s + u) : t = u :=
le_antisymm ((multiset.add_le_add_left _).1 (le_of_eq h))
((multiset.add_le_add_left _).1 (le_of_eq h.symm))
instance : ordered_cancel_comm_monoid (multiset α) :=
{ zero := 0,
add := (+),
add_comm := multiset.add_comm,
add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃,
congr_arg coe $ append_assoc l₁ l₂ l₃,
zero_add := multiset.zero_add,
add_zero := λ s, by rw [multiset.add_comm, multiset.zero_add],
add_left_cancel := multiset.add_left_cancel,
add_right_cancel := λ s₁ s₂ s₃ h, multiset.add_left_cancel s₂ $
by simpa [multiset.add_comm] using h,
add_le_add_left := λ s₁ s₂ h s₃, (multiset.add_le_add_left _).2 h,
le_of_add_le_add_left := λ s₁ s₂ s₃, (multiset.add_le_add_left _).1,
..@multiset.partial_order α }
@[simp] theorem cons_add (a : α) (s t : multiset α) : a :: s + t = a :: (s + t) :=
by rw [← singleton_add, ← singleton_add, add_assoc]
@[simp] theorem add_cons (a : α) (s t : multiset α) : s + a :: t = a :: (s + t) :=
by rw [add_comm, cons_add, add_comm]
theorem le_add_right (s t : multiset α) : s ≤ s + t :=
by simpa using add_le_add_left (zero_le t) s
theorem le_add_left (s t : multiset α) : s ≤ t + s :=
by simpa using add_le_add_right (zero_le t) s
@[simp] theorem card_add (s t : multiset α) : card (s + t) = card s + card t :=
quotient.induction_on₂ s t length_append
lemma card_smul (s : multiset α) (n : ℕ) :
(n • s).card = n * s.card :=
by induction n; simp [succ_smul, *, nat.succ_mul]
@[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, mem_append
theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u :=
⟨λ h, le_induction_on h $ λ l₁ l₂ s,
let ⟨l, p⟩ := exists_perm_append_of_sublist s in ⟨l, quot.sound p⟩,
λ⟨u, e⟩, e.symm ▸ le_add_right s u⟩
instance : canonically_ordered_monoid (multiset α) :=
{ lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _,
le_iff_exists_add := @le_iff_exists_add _,
bot := 0,
bot_le := multiset.zero_le,
..multiset.ordered_cancel_comm_monoid }
/- repeat -/
/-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/
def repeat (a : α) (n : ℕ) : multiset α := repeat a n
@[simp] lemma repeat_zero (a : α) : repeat a 0 = 0 := rfl
@[simp] lemma repeat_succ (a : α) (n) : repeat a (n+1) = a :: repeat a n := by simp [repeat]
@[simp] lemma repeat_one (a : α) : repeat a 1 = a :: 0 := by simp
@[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat
theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat
theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
(perm_repeat.1 $ (quotient.exact h).symm).symm, congr_arg coe⟩ eq_repeat'
theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card :=
eq_repeat'.2
theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a :=
⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩,
λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩
theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ a::0 := repeat_subset_singleton
theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l :=
⟨λ ⟨l', p, s⟩, (perm_repeat.1 p.symm).symm ▸ s, subperm_of_sublist⟩
/- range -/
/-- `range n` is the multiset lifted from the list `range n`,
that is, the set `{0, 1, ..., n-1}`. -/
def range (n : ℕ) : multiset ℕ := range n
@[simp] theorem range_zero : range 0 = 0 := rfl
@[simp] theorem range_succ (n : ℕ) : range (succ n) = n :: range n :=
by rw [range, range_concat, ← coe_add, add_comm]; refl
@[simp] theorem card_range (n : ℕ) : card (range n) = n := length_range _
theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := range_subset
@[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := mem_range
@[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := not_mem_range_self
/- erase -/
section erase
variables [decidable_eq α] {s t : multiset α} {a b : α}
/-- `erase s a` is the multiset that subtracts 1 from the
multiplicity of `a`. -/
def erase (s : multiset α) (a : α) : multiset α :=
quot.lift_on s (λ l, (l.erase a : multiset α))
(λ l₁ l₂ p, quot.sound (erase_perm_erase a p))
@[simp] theorem coe_erase (l : list α) (a : α) :
erase (l : multiset α) a = l.erase a := rfl
@[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl
@[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a :: s).erase a = s :=
quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l
@[simp] theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) : (b::s).erase a = b :: s.erase a :=
quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h
@[simp] theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s :=
quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h
@[simp] theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a :: s.erase a = s :=
quot.induction_on s $ λ l h, quot.sound (perm_erase h).symm
theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a :: s.erase a :=
if h : a ∈ s then le_of_eq (cons_erase h).symm
else by rw erase_of_not_mem h; apply le_cons_self
theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t :=
quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h
theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) : (s + t).erase a = s + t.erase a :=
by rw [add_comm, erase_add_left_pos s h, add_comm]
theorem erase_add_right_neg {a : α} {s : multiset α} (t) : a ∉ s → (s + t).erase a = s + t.erase a :=
quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h
theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) : (s + t).erase a = s.erase a + t :=
by rw [add_comm, erase_add_right_neg s h, add_comm]
theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s :=
quot.induction_on s $ λ l, subperm_of_sublist (erase_sublist a l)
@[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s :=
⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h),
λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩
theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s :=
subset_of_le (erase_le a s)
theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s :=
quot.induction_on s $ λ l, list.mem_erase_of_ne ab
theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s :=
mem_of_subset (erase_subset _ _)
theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a :=
quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b
theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a :=
le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist (erase_sublist_erase _ h)
theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a :: t :=
⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h),
λ h, if m : a ∈ s
then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h
else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩
@[simp] theorem card_erase_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) = pred (card s) :=
quot.induction_on s $ λ l, length_erase_of_mem
theorem card_erase_lt_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) < card s :=
λ h, card_lt_of_lt (erase_lt.mpr h)
theorem card_erase_le {a : α} {s : multiset α} : card (s.erase a) ≤ card s :=
card_le_of_le (erase_le a s)
end erase
@[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l :=
quot.sound $ reverse_perm _
/- map -/
/-- `map f s` is the lift of the list `map` operation. The multiplicity
of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity)
such that `f a = b`. -/
def map (f : α → β) (s : multiset α) : multiset β :=
quot.lift_on s (λ l : list α, (l.map f : multiset β))
(λ l₁ l₂ p, quot.sound (perm_map f p))
@[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl
@[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl
@[simp] theorem map_cons (f : α → β) (a s) : map f (a::s) = f a :: map f s :=
quot.induction_on s $ λ l, rfl
@[simp] lemma map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl
@[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _
instance (f : α → β) : is_add_monoid_hom (map f) :=
{ map_add := map_add _, map_zero := map_zero _ }
@[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} :
b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b :=
quot.induction_on s $ λ l, mem_map
@[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s :=
quot.induction_on s $ λ l, length_map _ _
@[simp] theorem map_eq_zero {s : multiset α} {f : α → β} : s.map f = 0 ↔ s = 0 :=
by rw [← multiset.card_eq_zero, multiset.card_map, multiset.card_eq_zero]
theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s :=
mem_map.2 ⟨_, h, rfl⟩
@[simp] theorem mem_map_of_inj {f : α → β} (H : function.injective f) {a : α} {s : multiset α} :
f a ∈ map f s ↔ a ∈ s :=
quot.induction_on s $ λ l, mem_map_of_inj H
@[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s :=
quot.induction_on s $ λ l, congr_arg coe $ list.map_map _ _ _
@[simp] theorem map_id (s : multiset α) : map id s = s :=
quot.induction_on s $ λ l, congr_arg coe $ map_id _
@[simp] lemma map_id' (s : multiset α) : map (λx, x) s = s := map_id s
@[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card :=
quot.induction_on s $ λ l, congr_arg coe $ map_const _ _
@[congr] theorem map_congr {f g : α → β} {s : multiset α} : (∀ x ∈ s, f x = g x) → map f s = map g s :=
quot.induction_on s $ λ l H, congr_arg coe $ map_congr H
lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'}
(h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m :=
begin subst h, simp at hf, simp [map_congr hf] end
theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ :=
eq_of_mem_repeat $ by rwa map_const at h
@[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t :=
le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ map_sublist_map f h
@[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t :=
λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩
/- fold -/
/-- `foldl f H b s` is the lift of the list operation `foldl f b l`,
which folds `f` over the multiset. It is well defined when `f` is right-commutative,
that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/
def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β :=
quot.lift_on s (λ l, foldl f b l)
(λ l₁ l₂ p, foldl_eq_of_perm H p b)
@[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl
@[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a :: s) = foldl f H (f b a) s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t :=
quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _
/-- `foldr f H b s` is the lift of the list operation `foldr f b l`,
which folds `f` over the multiset. It is well defined when `f` is left-commutative,
that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/
def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β :=
quot.lift_on s (λ l, foldr f b l)
(λ l₁ l₂ p, foldr_eq_of_perm H p b)
@[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl
@[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a :: s) = f a (foldr f H b s) :=
quot.induction_on s $ λ l, rfl
@[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s :=
quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _
@[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) :
foldr f H b l = l.foldr f b := rfl
@[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) :
foldl f H b l = l.foldl f b := rfl
theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) :
foldr f H b l = l.foldl (λ x y, f y x) b :=
(congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _
theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) :
foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s :=
quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _
theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) :
foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s :=
(foldr_swap _ _ _ _).symm
/-- Product of a multiset given a commutative monoid structure on `α`.
`prod {a, b, c} = a * b * c` -/
@[to_additive]
def prod [comm_monoid α] : multiset α → α :=
foldr (*) (λ x y z, by simp [mul_left_comm]) 1
@[to_additive]
theorem prod_eq_foldr [comm_monoid α] (s : multiset α) :
prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl
@[to_additive]
theorem prod_eq_foldl [comm_monoid α] (s : multiset α) :
prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s :=
(foldr_swap _ _ _ _).trans (by simp [mul_comm])
@[simp, to_additive]
theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod :=
prod_eq_foldl _
@[simp, to_additive]
theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl
@[simp, to_additive]
theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a :: s) = a * prod s :=
foldr_cons _ _ _ _ _
@[to_additive]
theorem prod_singleton [comm_monoid α] (a : α) : prod (a :: 0) = a := by simp
@[simp, to_additive]
theorem prod_add [comm_monoid α] (s t : multiset α) : prod (s + t) = prod s * prod t :=
quotient.induction_on₂ s t $ λ l₁ l₂, by simp
instance sum.is_add_monoid_hom [add_comm_monoid α] : is_add_monoid_hom (sum : multiset α → α) :=
{ map_add := sum_add, map_zero := sum_zero }
lemma prod_smul {α : Type*} [comm_monoid α] (m : multiset α) :
∀n, (add_monoid.smul n m).prod = m.prod ^ n
| 0 := rfl
| (n + 1) :=
by rw [add_monoid.add_smul, add_monoid.one_smul, _root_.pow_add, _root_.pow_one, prod_add, prod_smul n]
@[simp] theorem prod_repeat [comm_monoid α] (a : α) (n : ℕ) : prod (multiset.repeat a n) = a ^ n :=
by simp [repeat, list.prod_repeat]
@[simp] theorem sum_repeat [add_comm_monoid α] : ∀ (a : α) (n : ℕ), sum (multiset.repeat a n) = n • a :=
@prod_repeat (multiplicative α) _
attribute [to_additive] prod_repeat
@[simp] lemma prod_map_one [comm_monoid γ] {m : multiset α} :
prod (m.map (λa, (1 : γ))) = (1 : γ) :=
multiset.induction_on m (by simp) (by simp)
@[simp] lemma sum_map_zero [add_comm_monoid γ] {m : multiset α} :
sum (m.map (λa, (0 : γ))) = (0 : γ) :=
multiset.induction_on m (by simp) (by simp)
attribute [to_additive] prod_map_one
@[simp, to_additive]
lemma prod_map_mul [comm_monoid γ] {m : multiset α} {f g : α → γ} :
prod (m.map $ λa, f a * g a) = prod (m.map f) * prod (m.map g) :=
multiset.induction_on m (by simp) (assume a m ih, by simp [ih]; cc)
lemma prod_map_prod_map [comm_monoid γ] (m : multiset α) (n : multiset β) {f : α → β → γ} :
prod (m.map $ λa, prod $ n.map $ λb, f a b) = prod (n.map $ λb, prod $ m.map $ λa, f a b) :=
multiset.induction_on m (by simp) (assume a m ih, by simp [ih])
lemma sum_map_sum_map [add_comm_monoid γ] : ∀ (m : multiset α) (n : multiset β) {f : α → β → γ},
sum (m.map $ λa, sum $ n.map $ λb, f a b) = sum (n.map $ λb, sum $ m.map $ λa, f a b) :=
@prod_map_prod_map _ _ (multiplicative γ) _
attribute [to_additive] prod_map_prod_map
lemma sum_map_mul_left [semiring β] {b : β} {s : multiset α} {f : α → β} :
sum (s.map (λa, b * f a)) = b * sum (s.map f) :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, mul_add])
lemma sum_map_mul_right [semiring β] {b : β} {s : multiset α} {f : α → β} :
sum (s.map (λa, f a * b)) = sum (s.map f) * b :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, add_mul])
lemma prod_hom [comm_monoid α] [comm_monoid β] (f : α → β) [is_monoid_hom f] (s : multiset α) :
(s.map f).prod = f s.prod :=
multiset.induction_on s (by simp [is_monoid_hom.map_one f])
(by simp [is_monoid_hom.map_mul f] {contextual := tt})
lemma dvd_prod [comm_semiring α] {a : α} {s : multiset α} : a ∈ s → a ∣ s.prod :=
quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a
lemma sum_hom [add_comm_monoid α] [add_comm_monoid β] (f : α → β) [is_add_monoid_hom f] (s : multiset α) :
(s.map f).sum = f s.sum :=
multiset.induction_on s (by simp [is_add_monoid_hom.map_zero f])
(by simp [is_add_monoid_hom.map_add f] {contextual := tt})
attribute [to_additive] multiset.prod_hom
lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_comm_monoid β]
(f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : multiset α) :
f s.sum ≤ (s.map f).sum :=
multiset.induction_on s (le_of_eq h_zero) $
assume a s ih, by rw [sum_cons, map_cons, sum_cons];
from le_trans (h_add a s.sum) (add_le_add_left' ih)
lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {s : multiset α} :
abs s.sum ≤ (s.map abs).sum :=
le_sum_of_subadditive _ abs_zero abs_add s
/- join -/
/-- `join S`, where `S` is a multiset of multisets, is the lift of the list join
operation, that is, the union of all the sets.
join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/
def join : multiset (multiset α) → multiset α := sum
theorem coe_join : ∀ L : list (list α),
join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join
| [] := rfl
| (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L)
@[simp] theorem join_zero : @join α 0 = 0 := rfl
@[simp] theorem join_cons (s S) : @join α (s :: S) = s + join S :=
sum_cons _ _
@[simp] theorem join_add (S T) : @join α (S + T) = join S + join T :=
sum_add _ _
@[simp] theorem mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s :=
multiset.induction_on S (by simp) $
by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt}
@[simp] theorem card_join (S) : card (@join α S) = sum (map card S) :=
multiset.induction_on S (by simp) (by simp)
/- bind -/
/-- `bind s f` is the monad bind operation, defined as `join (map f s)`.
It is the union of `f a` as `a` ranges over `s`. -/
def bind (s : multiset α) (f : α → multiset β) : multiset β :=
join (map f s)
@[simp] theorem coe_bind (l : list α) (f : α → list β) :
@bind α β l (λ a, f a) = l.bind f :=
by rw [list.bind, ← coe_join, list.map_map]; refl
@[simp] theorem zero_bind (f : α → multiset β) : bind 0 f = 0 := rfl
@[simp] theorem cons_bind (a s) (f : α → multiset β) : bind (a::s) f = f a + bind s f :=
by simp [bind]
@[simp] theorem add_bind (s t) (f : α → multiset β) : bind (s + t) f = bind s f + bind t f :=
by simp [bind]
@[simp] theorem bind_zero (s : multiset α) : bind s (λa, 0 : α → multiset β) = 0 :=
by simp [bind, -map_const, join]
@[simp] theorem bind_add (s : multiset α) (f g : α → multiset β) :
bind s (λa, f a + g a) = bind s f + bind s g :=
by simp [bind, join]
@[simp] theorem bind_cons (s : multiset α) (f : α → β) (g : α → multiset β) :
bind s (λa, f a :: g a) = map f s + bind s g :=
multiset.induction_on s (by simp) (by simp {contextual := tt})
@[simp] theorem mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a :=
by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm];
rw exists_swap; simp [and_assoc]
@[simp] theorem card_bind (s) (f : α → multiset β) : card (bind s f) = sum (map (card ∘ f) s) :=
by simp [bind]
lemma bind_congr {f g : α → multiset β} {m : multiset α} : (∀a∈m, f a = g a) → bind m f = bind m g :=
by simp [bind] {contextual := tt}
lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'}
(h : β = β') (hf : ∀a∈m, f a == f' a) : bind m f == bind m f' :=
begin subst h, simp at hf, simp [bind_congr hf] end
lemma map_bind (m : multiset α) (n : α → multiset β) (f : β → γ) :
map f (bind m n) = bind m (λa, map f (n a)) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_map (m : multiset α) (n : β → multiset γ) (f : α → β) :
bind (map f m) n = bind m (λa, n (f a)) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_assoc {s : multiset α} {f : α → multiset β} {g : β → multiset γ} :
(s.bind f).bind g = s.bind (λa, (f a).bind g) :=
multiset.induction_on s (by simp) (by simp {contextual := tt})
lemma bind_bind (m : multiset α) (n : multiset β) {f : α → β → multiset γ} :
(bind m $ λa, bind n $ λb, f a b) = (bind n $ λb, bind m $ λa, f a b) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_map_comm (m : multiset α) (n : multiset β) {f : α → β → γ} :
(bind m $ λa, n.map $ λb, f a b) = (bind n $ λb, m.map $ λa, f a b) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
@[simp, to_additive]
lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) :
prod (bind s t) = prod (s.map $ λa, prod (t a)) :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind])
/- product -/
/-- The multiplicity of `(a, b)` in `product s t` is
the product of the multiplicity of `a` in `s` and `b` in `t`. -/
def product (s : multiset α) (t : multiset β) : multiset (α × β) :=
s.bind $ λ a, t.map $ prod.mk a
@[simp] theorem coe_product (l₁ : list α) (l₂ : list β) :
@product α β l₁ l₂ = l₁.product l₂ :=
by rw [product, list.product, ← coe_bind]; simp
@[simp] theorem zero_product (t) : @product α β 0 t = 0 := rfl
@[simp] theorem cons_product (a : α) (s : multiset α) (t : multiset β) :
product (a :: s) t = map (prod.mk a) t + product s t :=
by simp [product]
@[simp] theorem product_singleton (a : α) (b : β) : product (a::0) (b::0) = (a,b)::0 := rfl
@[simp] theorem add_product (s t : multiset α) (u : multiset β) :
product (s + t) u = product s u + product t u :=
by simp [product]
@[simp] theorem product_add (s : multiset α) : ∀ t u : multiset β,
product s (t + u) = product s t + product s u :=
multiset.induction_on s (λ t u, rfl) $ λ a s IH t u,
by rw [cons_product, IH]; simp
@[simp] theorem mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t
| (a, b) := by simp [product, and.left_comm]
@[simp] theorem card_product (s : multiset α) (t : multiset β) : card (product s t) = card s * card t :=
by simp [product, repeat, (∘), mul_comm]
/- sigma -/
section
variable {σ : α → Type*}
/-- `sigma s t` is the dependent version of `product`. It is the sum of
`(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/
protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) :=
s.bind $ λ a, (t a).map $ sigma.mk a
@[simp] theorem coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) :
@multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ :=
by rw [multiset.sigma, list.sigma, ← coe_bind]; simp
@[simp] theorem zero_sigma (t) : @multiset.sigma α σ 0 t = 0 := rfl
@[simp] theorem cons_sigma (a : α) (s : multiset α) (t : Π a, multiset (σ a)) :
(a :: s).sigma t = map (sigma.mk a) (t a) + s.sigma t :=
by simp [multiset.sigma]
@[simp] theorem sigma_singleton (a : α) (b : α → β) :
(a::0).sigma (λ a, b a::0) = ⟨a, b a⟩::0 := rfl
@[simp] theorem add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) :
(s + t).sigma u = s.sigma u + t.sigma u :=
by simp [multiset.sigma]
@[simp] theorem sigma_add (s : multiset α) : ∀ t u : Π a, multiset (σ a),
s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u :=
multiset.induction_on s (λ t u, rfl) $ λ a s IH t u,
by rw [cons_sigma, IH]; simp
@[simp] theorem mem_sigma {s t} : ∀ {p : Σ a, σ a},
p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1
| ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm]
@[simp] theorem card_sigma (s : multiset α) (t : Π a, multiset (σ a)) :
card (s.sigma t) = sum (map (λ a, card (t a)) s) :=
by simp [multiset.sigma, (∘)]
end
/- map for partial functions -/
/-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset
`s` whose elements are all in the domain of `f`. -/
def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β :=
quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂),
funext $ λ (H₂ : ∀ a ∈ l₂, p a),
have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a ((mem_of_perm pp).1 h),
have ∀ {s₂ e H}, @eq.rec (multiset α) l₁
(λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁))
s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e,
this.trans $ quot.sound $ perm_pmap f pp
@[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β)
(l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl
@[simp] lemma pmap_zero {p : α → Prop} (f : Π a, p a → β) (h : ∀a∈(0:multiset α), p a) :
pmap f 0 h = 0 := rfl
@[simp] lemma pmap_cons {p : α → Prop} (f : Π a, p a → β) (a : α) (m : multiset α) :
∀(h : ∀b∈a::m, p b), pmap f (a :: m) h =
f a (h a (mem_cons_self a m)) :: pmap f m (λa ha, h a $ mem_cons_of_mem ha) :=
quotient.induction_on m $ assume l h, rfl
/-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce
a multiset on `{x // x ∈ s}`. -/
def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id)
@[simp] theorem coe_attach (l : list α) :
@eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl
theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) :
∀ H, @pmap _ _ p (λ a _, f a) s H = map f s :=
quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H
theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β}
(s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) :
pmap f s H₁ = pmap g s H₂ :=
quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂
theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β)
(s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H :=
quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H
theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β)
(s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) :=
quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H
theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s :=
quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l
@[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach :=
quot.induction_on s $ λ l, mem_attach _
@[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β}
{s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b :=
quot.induction_on s (λ l H, mem_pmap) H
@[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β)
(s H) : card (pmap f s H) = card s :=
quot.induction_on s (λ l H, length_pmap) H
@[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _
@[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl
lemma attach_cons (a : α) (m : multiset α) :
(a :: m).attach = ⟨a, mem_cons_self a m⟩ :: (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) :=
quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $
by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl)
section decidable_pi_exists
variables {m : multiset α}
protected def decidable_forall_multiset {p : α → Prop} [hp : ∀a, decidable (p a)] :
decidable (∀a∈m, p a) :=
quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a∈l, p a) $ by simp)
instance decidable_dforall_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] :
decidable (∀a (h : a ∈ m), p a h) :=
decidable_of_decidable_of_iff
(@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _)
(iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _))
/-- decidable equality for functions whose domain is bounded by multisets -/
instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀a, decidable_eq (β a)] :
decidable_eq (Πa∈m, β a) :=
assume f g, decidable_of_iff (∀a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff])
def decidable_exists_multiset {p : α → Prop} [decidable_pred p] :
decidable (∃ x ∈ m, p x) :=
quotient.rec_on_subsingleton m list.decidable_exists_mem
instance decidable_dexists_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] :
decidable (∃a (h : a ∈ m), p a h) :=
decidable_of_decidable_of_iff
(@multiset.decidable_exists_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _)
(iff.intro (λ ⟨⟨a, ha₁⟩, _, ha₂⟩, ⟨a, ha₁, ha₂⟩)
(λ ⟨a, ha₁, ha₂⟩, ⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩))
end decidable_pi_exists
/- subtraction -/
section
variables [decidable_eq α] {s t u : multiset α} {a b : α}
/-- `s - t` is the multiset such that
`count a (s - t) = count a s - count a t` for all `a`. -/
protected def sub (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ perm_diff_right w₁ p₂ ▸ perm_diff_left _ p₁
instance : has_sub (multiset α) := ⟨multiset.sub⟩
@[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl
theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t :=
quotient.induction_on₂ s t $ λ l₁ l₂,
show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂,
by rw diff_eq_foldl l₁ l₂; exact foldl_hom _ _ _ _ (λ x y, rfl) _
@[simp] theorem sub_zero (s : multiset α) : s - 0 = s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a::t = s.erase a - t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _
theorem add_sub_of_le (h : s ≤ t) : s + (t - s) = t :=
begin
revert t,
refine multiset.induction_on s (by simp) (λ a s IH t h, _),
have := cons_erase (mem_of_le h (mem_cons_self _ _)),
rw [cons_add, sub_cons, IH, this],
exact (cons_le_cons_iff a).1 (this.symm ▸ h)
end
theorem sub_add' : s - (t + u) = s - t - u :=
quotient.induction_on₃ s t u $
λ l₁ l₂ l₃, congr_arg coe $ diff_append _ _ _
theorem sub_add_cancel (h : t ≤ s) : s - t + t = s :=
by rw [add_comm, add_sub_of_le h]
@[simp] theorem add_sub_cancel_left (s : multiset α) : ∀ t, s + t - s = t :=
multiset.induction_on s (by simp)
(λ a s IH t, by rw [cons_add, sub_cons, erase_cons_head, IH])
@[simp] theorem add_sub_cancel (s t : multiset α) : s + t - t = s :=
by rw [add_comm, add_sub_cancel_left]
theorem sub_le_sub_right (h : s ≤ t) (u) : s - u ≤ t - u :=
by revert s t h; exact
multiset.induction_on u (by simp {contextual := tt})
(λ a u IH s t h, by simp [IH, erase_le_erase a h])
theorem sub_le_sub_left (h : s ≤ t) : ∀ u, u - t ≤ u - s :=
le_induction_on h $ λ l₁ l₂ h, begin
induction h with l₁ l₂ a s IH l₁ l₂ a s IH; intro u,
{ refl },
{ rw [← cons_coe, sub_cons],
exact le_trans (sub_le_sub_right (erase_le _ _) _) (IH u) },
{ rw [← cons_coe, sub_cons, ← cons_coe, sub_cons],
exact IH _ }
end
theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t :=
by revert s; exact
multiset.induction_on t (by simp)
(λ a t IH s, by simp [IH, erase_le_iff_le_cons])
theorem le_sub_add (s t : multiset α) : s ≤ s - t + t :=
sub_le_iff_le_add.1 (le_refl _)
theorem sub_le_self (s t : multiset α) : s - t ≤ s :=
sub_le_iff_le_add.2 (le_add_right _ _)
@[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t :=
(nat.sub_eq_of_eq_add $ by rw [add_comm, ← card_add, sub_add_cancel h]).symm
/- union -/
/-- `s ∪ t` is the lattice join operation with respect to the
multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum
of the multiplicities in `s` and `t`. -/
def union (s t : multiset α) : multiset α := s - t + t
instance : has_union (multiset α) := ⟨union⟩
theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl
theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_sub_add _ _
theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _
theorem eq_union_left : t ≤ s → s ∪ t = s := sub_add_cancel
theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u :=
add_le_add_right (sub_le_sub_right h _) u
theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u :=
by rw ← eq_union_left h₂; exact union_le_union_right h₁ t
@[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t :=
⟨λ h, (mem_add.1 h).imp_left (mem_of_le $ sub_le_self _ _),
or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩
@[simp] theorem map_union [decidable_eq β] {f : α → β} (finj : function.injective f) {s t : multiset α} :
map f (s ∪ t) = map f s ∪ map f t :=
quotient.induction_on₂ s t $ λ l₁ l₂,
congr_arg coe (by rw [list.map_append f, list.map_diff finj])
/- inter -/
/-- `s ∩ t` is the lattice meet operation with respect to the
multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum
of the multiplicities in `s` and `t`. -/
def inter (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ perm_bag_inter_right w₁ p₂ ▸ perm_bag_inter_left _ p₁
instance : has_inter (multiset α) := ⟨inter⟩
@[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 :=
quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil
@[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 :=
quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter
@[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} :
a ∈ t → (a :: s) ∩ t = a :: s ∩ t.erase a :=
quotient.induction_on₂ s t $ λ l₁ l₂ h,
congr_arg coe $ cons_bag_inter_of_pos _ h
@[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} :
a ∉ t → (a :: s) ∩ t = s ∩ t :=
quotient.induction_on₂ s t $ λ l₁ l₂ h,
congr_arg coe $ cons_bag_inter_of_neg _ h
theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s :=
quotient.induction_on₂ s t $ λ l₁ l₂,
subperm_of_sublist $ bag_inter_sublist_left _ _
theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t :=
multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $
λ a s IH t, if h : a ∈ t
then by simpa [h] using cons_le_cons a (IH (t.erase a))
else by simp [h, IH]
theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u :=
begin
revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros,
{ simp [h₁] },
by_cases a ∈ u,
{ rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons],
exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) },
{ rw cons_inter_of_neg _ h,
exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ }
end
@[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t :=
⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩,
λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩
instance : lattice (multiset α) :=
{ sup := (∪),
sup_le := @union_le _ _,
le_sup_left := le_union_left,
le_sup_right := le_union_right,
inf := (∩),
le_inf := @le_inter _ _,
inf_le_left := inter_le_left,
inf_le_right := inter_le_right,
..@multiset.partial_order α }
@[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl
@[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl
@[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff
@[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff
instance : semilattice_inf_bot (multiset α) :=
{ bot := 0, bot_le := zero_le, ..multiset.lattice.lattice }
theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm
theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm
theorem eq_union_right (h : s ≤ t) : s ∪ t = t :=
by rw [union_comm, eq_union_left h]
theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t :=
sup_le_sup_left h _
theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t :=
union_le (le_add_right _ _) (le_add_left _ _)
theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) :=
by simpa [(∪), union, eq_comm] using show s + u - (t + u) = s - t,
by rw [add_comm t, sub_add', add_sub_cancel]
theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) :=
by rw [add_comm, union_add_distrib, add_comm s, add_comm s]
theorem cons_union_distrib (a : α) (s t : multiset α) : a :: (s ∪ t) = (a :: s) ∪ (a :: t) :=
by simpa using add_union_distrib (a::0) s t
theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) :=
begin
by_contra h,
cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter
(add_le_add_right (inter_le_left s t) u)
(add_le_add_right (inter_le_right s t) u)) h) with a hl,
rw ← cons_add at hl,
exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter
(le_of_add_le_add_right (le_trans hl (inter_le_left _ _)))
(le_of_add_le_add_right (le_trans hl (inter_le_right _ _))))
end
theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) :=
by rw [add_comm, inter_add_distrib, add_comm s, add_comm s]
theorem cons_inter_distrib (a : α) (s t : multiset α) : a :: (s ∩ t) = (a :: s) ∩ (a :: t) :=
by simp
theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t :=
begin
apply le_antisymm,
{ rw union_add_distrib,
refine union_le (add_le_add_left (inter_le_right _ _) _) _,
rw add_comm, exact add_le_add_right (inter_le_left _ _) _ },
{ rw [add_comm, add_inter_distrib],
refine le_inter (add_le_add_right (le_union_right _ _) _) _,
rw add_comm, exact add_le_add_right (le_union_left _ _) _ }
end
theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s :=
begin
rw [inter_comm],
revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _),
by_cases a ∈ s,
{ rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] },
{ rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] }
end
theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t :=
add_right_cancel $
by rw [sub_add_inter s t, sub_add_cancel (inter_le_left _ _)]
end
/- filter -/
section
variables {p : α → Prop} [decidable_pred p]
/-- `filter p s` returns the elements in `s` (with the same multiplicities)
which satisfy `p`, and removes the rest. -/
def filter (p : α → Prop) [h : decidable_pred p] (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (filter p l : multiset α))
(λ l₁ l₂ h, quot.sound $ perm_filter p h)
@[simp] theorem coe_filter (p : α → Prop) [h : decidable_pred p]
(l : list α) : filter p (↑l) = l.filter p := rfl
@[simp] theorem filter_zero (p : α → Prop) [h : decidable_pred p] : filter p 0 = 0 := rfl
@[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a::s) = a :: filter p s :=
quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h
@[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a::s) = filter p s :=
quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h
lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q]
{s : multiset α} : (∀ x ∈ s, p x ↔ q x) → filter p s = filter q s :=
quot.induction_on s $ λ l h, congr_arg coe $ filter_congr h
@[simp] theorem filter_add (s t : multiset α) :
filter p (s + t) = filter p s + filter p t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _
@[simp] theorem filter_le (s : multiset α) : filter p s ≤ s :=
quot.induction_on s $ λ l, subperm_of_sublist $ filter_sublist _
@[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s :=
subset_of_le $ filter_le _
@[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a :=
quot.induction_on s $ λ l, mem_filter
theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a :=
(mem_filter.1 h).2
theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s :=
(mem_filter.1 h).1
theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l :=
mem_filter.2 ⟨m, h⟩
theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h),
congr_arg coe⟩ filter_eq_self
theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h),
congr_arg coe⟩ filter_eq_nil
theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t :=
le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ filter_sublist_filter h
theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a :=
⟨λ h, ⟨le_trans h (filter_le _), λ a m, of_mem_filter (mem_of_le h m)⟩,
λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter h⟩
@[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) :
filter p (s - t) = filter p s - filter p t :=
begin
revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _),
rw [sub_cons, IH],
by_cases p a,
{ rw [filter_cons_of_pos _ h, sub_cons], congr,
by_cases m : a ∈ s,
{ rw [← cons_inj_right a, ← filter_cons_of_pos _ h,
cons_erase (mem_filter_of_mem m h), cons_erase m] },
{ rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } },
{ rw [filter_cons_of_neg _ h],
by_cases m : a ∈ s,
{ rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a :: erase s a)),
cons_erase m] },
{ rw [erase_of_not_mem m] } }
end
@[simp] theorem filter_union [decidable_eq α] (s t : multiset α) :
filter p (s ∪ t) = filter p s ∪ filter p t :=
by simp [(∪), union]
@[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) :
filter p (s ∩ t) = filter p s ∩ filter p t :=
le_antisymm (le_inter
(filter_le_filter $ inter_le_left _ _)
(filter_le_filter $ inter_le_right _ _)) $ le_filter.2
⟨inf_le_inf (filter_le _) (filter_le _),
λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩
@[simp] theorem filter_filter {q} [decidable_pred q] (s : multiset α) :
filter p (filter q s) = filter (λ a, p a ∧ q a) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_filter l
theorem filter_add_filter {q} [decidable_pred q] (s : multiset α) :
filter p s + filter q s = filter (λ a, p a ∨ q a) s + filter (λ a, p a ∧ q a) s :=
multiset.induction_on s rfl $ λ a s IH,
by by_cases p a; by_cases q a; simp *
theorem filter_add_not (s : multiset α) :
filter p s + filter (λ a, ¬ p a) s = s :=
by rw [filter_add_filter, filter_eq_self.2, filter_eq_nil.2]; simp [decidable.em]
/- filter_map -/
/-- `filter_map f s` is a combination filter/map operation on `s`.
The function `f : α → option β` is applied to each element of `s`;
if `f a` is `some b` then `b` is added to the result, otherwise
`a` is removed from the resulting multiset. -/
def filter_map (f : α → option β) (s : multiset α) : multiset β :=
quot.lift_on s (λ l, (filter_map f l : multiset β))
(λ l₁ l₂ h, quot.sound $perm_filter_map f h)
@[simp] theorem coe_filter_map (f : α → option β) (l : list α) : filter_map f l = l.filter_map f := rfl
@[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl
@[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) :
filter_map f (a :: s) = filter_map f s :=
quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h
@[simp] theorem filter_map_cons_some (f : α → option β)
(a : α) (s : multiset α) {b : β} (h : f a = some b) :
filter_map f (a :: s) = b :: filter_map f s :=
quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h
theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f :=
funext $ λ s, quot.induction_on s $ λ l,
@congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l
theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] :
filter_map (option.guard p) = filter p :=
funext $ λ s, quot.induction_on s $ λ l,
@congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l
theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) :
filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l
theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) :
map g (filter_map f s) = filter_map (λ x, (f x).map g) s :=
quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l
theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) :
filter_map g (map f s) = filter_map (g ∘ f) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l
theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) :
filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l
theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (s : multiset α) :
filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l
@[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l
@[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} :
b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b :=
quot.induction_on s $ λ l, mem_filter_map f l
theorem map_filter_map_of_inv (f : α → option β) (g : β → α)
(H : ∀ x : α, (f x).map g = some x) (s : multiset α) :
map g (filter_map f s) = s :=
quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l
theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α}
(h : s ≤ t) : filter_map f s ≤ filter_map f t :=
le_induction_on h $ λ l₁ l₂ h,
subperm_of_sublist $ filter_map_sublist_filter_map _ h
/- powerset -/
def powerset_aux (l : list α) : list (multiset α) :=
0 :: sublists_aux l (λ x y, x :: y)
theorem powerset_aux_eq_map_coe {l : list α} :
powerset_aux l = (sublists l).map coe :=
by simp [powerset_aux, sublists];
rw [← show @sublists_aux₁ α (multiset α) l (λ x, [↑x]) =
sublists_aux l (λ x, list.cons ↑x),
from sublists_aux₁_eq_sublists_aux _ _,
sublists_aux_cons_eq_sublists_aux₁,
← bind_ret_eq_map, sublists_aux₁_bind]; refl
@[simp] theorem mem_powerset_aux {l : list α} {s} :
s ∈ powerset_aux l ↔ s ≤ ↑l :=
quotient.induction_on s $
by simp [powerset_aux_eq_map_coe, subperm, and.comm]
def powerset_aux' (l : list α) : list (multiset α) := (sublists' l).map coe
theorem powerset_aux_perm_powerset_aux' {l : list α} :
powerset_aux l ~ powerset_aux' l :=
by rw powerset_aux_eq_map_coe; exact
perm_map _ (sublists_perm_sublists' _)
@[simp] theorem powerset_aux'_nil : powerset_aux' (@nil α) = [0] := rfl
@[simp] theorem powerset_aux'_cons (a : α) (l : list α) :
powerset_aux' (a::l) = powerset_aux' l ++ list.map (cons a) (powerset_aux' l) :=
by simp [powerset_aux']; refl
theorem powerset_aux'_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) :
powerset_aux' l₁ ~ powerset_aux' l₂ :=
begin
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp},
{ simp, exact perm_app IH (perm_map _ IH) },
{ simp, apply perm_app_right,
rw [← append_assoc, ← append_assoc,
(by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)],
exact perm_app_left _ perm_app_comm },
{ exact IH₁.trans IH₂ }
end
theorem powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) :
powerset_aux l₁ ~ powerset_aux l₂ :=
powerset_aux_perm_powerset_aux'.trans $
(powerset_aux'_perm p).trans powerset_aux_perm_powerset_aux'.symm
def powerset (s : multiset α) : multiset (multiset α) :=
quot.lift_on s
(λ l, (powerset_aux l : multiset (multiset α)))
(λ l₁ l₂ h, quot.sound (powerset_aux_perm h))
theorem powerset_coe (l : list α) :
@powerset α l = ((sublists l).map coe : list (multiset α)) :=
congr_arg coe powerset_aux_eq_map_coe
@[simp] theorem powerset_coe' (l : list α) :
@powerset α l = ((sublists' l).map coe : list (multiset α)) :=
quot.sound powerset_aux_perm_powerset_aux'
@[simp] theorem powerset_zero : @powerset α 0 = 0::0 := rfl
@[simp] theorem powerset_cons (a : α) (s) :
powerset (a::s) = powerset s + map (cons a) (powerset s) :=
quotient.induction_on s $ λ l, by simp; refl
@[simp] theorem mem_powerset {s t : multiset α} :
s ∈ powerset t ↔ s ≤ t :=
quotient.induction_on₂ s t $ by simp [subperm, and.comm]
theorem map_single_le_powerset (s : multiset α) :
s.map (λ a, a::0) ≤ powerset s :=
quotient.induction_on s $ λ l, begin
simp [powerset_coe],
show l.map (coe ∘ list.ret) <+~ (sublists l).map coe,
rw ← list.map_map,
exact subperm_of_sublist
(map_sublist_map _ (map_ret_sublist_sublists _))
end
@[simp] theorem card_powerset (s : multiset α) :
card (powerset s) = 2 ^ card s :=
quotient.induction_on s $ by simp
/- antidiagonal -/
theorem revzip_powerset_aux {l : list α} ⦃x⦄
(h : x ∈ revzip (powerset_aux l)) : x.1 + x.2 = ↑l :=
begin
rw [revzip, powerset_aux_eq_map_coe, ← map_reverse, zip_map, ← revzip] at h,
simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩,
exact quot.sound (revzip_sublists _ _ _ h)
end
theorem revzip_powerset_aux' {l : list α} ⦃x⦄
(h : x ∈ revzip (powerset_aux' l)) : x.1 + x.2 = ↑l :=
begin
rw [revzip, powerset_aux', ← map_reverse, zip_map, ← revzip] at h,
simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩,
exact quot.sound (revzip_sublists' _ _ _ h)
end
theorem revzip_powerset_aux_lemma [decidable_eq α] (l : list α)
{l' : list (multiset α)} (H : ∀ ⦃x : _ × _⦄, x ∈ revzip l' → x.1 + x.2 = ↑l) :
revzip l' = l'.map (λ x, (x, ↑l - x)) :=
begin
have : forall₂ (λ (p : multiset α × multiset α) (s : multiset α), p = (s, ↑l - s))
(revzip l') ((revzip l').map prod.fst),
{ rw forall₂_map_right_iff,
apply forall₂_same, rintro ⟨s, t⟩ h,
dsimp, rw [← H h, add_sub_cancel_left] },
rw [← forall₂_eq_eq_eq, forall₂_map_right_iff], simpa
end
theorem revzip_powerset_aux_perm_aux' {l : list α} :
revzip (powerset_aux l) ~ revzip (powerset_aux' l) :=
begin
haveI := classical.dec_eq α,
rw [revzip_powerset_aux_lemma l revzip_powerset_aux,
revzip_powerset_aux_lemma l revzip_powerset_aux'],
exact perm_map _ powerset_aux_perm_powerset_aux',
end
theorem revzip_powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) :
revzip (powerset_aux l₁) ~ revzip (powerset_aux l₂) :=
begin
haveI := classical.dec_eq α,
simp [λ l:list α, revzip_powerset_aux_lemma l revzip_powerset_aux, coe_eq_coe.2 p],
exact perm_map _ (powerset_aux_perm p)
end
/-- The antidiagonal of a multiset `s` consists of all pairs `(t₁, t₂)`
such that `t₁ + t₂ = s`. These pairs are counted with multiplicities. -/
def antidiagonal (s : multiset α) : multiset (multiset α × multiset α) :=
quot.lift_on s
(λ l, (revzip (powerset_aux l) : multiset (multiset α × multiset α)))
(λ l₁ l₂ h, quot.sound (revzip_powerset_aux_perm h))
theorem antidiagonal_coe (l : list α) :
@antidiagonal α l = revzip (powerset_aux l) := rfl
@[simp] theorem antidiagonal_coe' (l : list α) :
@antidiagonal α l = revzip (powerset_aux' l) :=
quot.sound revzip_powerset_aux_perm_aux'
/-- A pair `(t₁, t₂)` of multisets is contained in `antidiagonal s`
if and only if `t₁ + t₂ = s`. -/
@[simp] theorem mem_antidiagonal {s : multiset α} {x : multiset α × multiset α} :
x ∈ antidiagonal s ↔ x.1 + x.2 = s :=
quotient.induction_on s $ λ l, begin
simp [antidiagonal_coe], refine ⟨λ h, revzip_powerset_aux h, λ h, _⟩,
haveI := classical.dec_eq α,
simp [revzip_powerset_aux_lemma l revzip_powerset_aux, h.symm],
cases x with x₁ x₂,
exact ⟨_, le_add_right _ _, by rw add_sub_cancel_left _ _⟩
end
@[simp] theorem antidiagonal_map_fst (s : multiset α) :
(antidiagonal s).map prod.fst = powerset s :=
quotient.induction_on s $ λ l,
by simp [powerset_aux']
@[simp] theorem antidiagonal_map_snd (s : multiset α) :
(antidiagonal s).map prod.snd = powerset s :=
quotient.induction_on s $ λ l,
by simp [powerset_aux']
@[simp] theorem antidiagonal_zero : @antidiagonal α 0 = (0, 0)::0 := rfl
@[simp] theorem antidiagonal_cons (a : α) (s) : antidiagonal (a::s) =
map (prod.map id (cons a)) (antidiagonal s) +
map (prod.map (cons a) id) (antidiagonal s) :=
quotient.induction_on s $ λ l, begin
simp [revzip, reverse_append],
rw [← zip_map, ← zip_map, zip_append, (_ : _++_=_)],
{congr; simp}, {simp}
end
@[simp] theorem card_antidiagonal (s : multiset α) :
card (antidiagonal s) = 2 ^ card s :=
by have := card_powerset s;
rwa [← antidiagonal_map_fst, card_map] at this
lemma prod_map_add [comm_semiring β] {s : multiset α} {f g : α → β} :
prod (s.map (λa, f a + g a)) =
sum ((antidiagonal s).map (λp, (p.1.map f).prod * (p.2.map g).prod)) :=
begin
refine s.induction_on _ _,
{ simp },
{ assume a s ih, simp [ih, add_mul, mul_comm, mul_left_comm, mul_assoc, sum_map_mul_left.symm] },
end
/- powerset_len -/
def powerset_len_aux (n : ℕ) (l : list α) : list (multiset α) :=
sublists_len_aux n l coe []
theorem powerset_len_aux_eq_map_coe {n} {l : list α} :
powerset_len_aux n l = (sublists_len n l).map coe :=
by rw [powerset_len_aux, sublists_len_aux_eq, append_nil]
@[simp] theorem mem_powerset_len_aux {n} {l : list α} {s} :
s ∈ powerset_len_aux n l ↔ s ≤ ↑l ∧ card s = n :=
quotient.induction_on s $
by simp [powerset_len_aux_eq_map_coe, subperm]; exact
λ l₁, ⟨λ ⟨l₂, ⟨s, e⟩, p⟩, ⟨⟨_, p, s⟩, (perm_length p.symm).trans e⟩,
λ ⟨⟨l₂, p, s⟩, e⟩, ⟨_, ⟨s, (perm_length p).trans e⟩, p⟩⟩
@[simp] theorem powerset_len_aux_zero (l : list α) :
powerset_len_aux 0 l = [0] :=
by simp [powerset_len_aux_eq_map_coe]
@[simp] theorem powerset_len_aux_nil (n : ℕ) :
powerset_len_aux (n+1) (@nil α) = [] := rfl
@[simp] theorem powerset_len_aux_cons (n : ℕ) (a : α) (l : list α) :
powerset_len_aux (n+1) (a::l) =
powerset_len_aux (n+1) l ++ list.map (cons a) (powerset_len_aux n l) :=
by simp [powerset_len_aux_eq_map_coe]; refl
theorem powerset_len_aux_perm {n} {l₁ l₂ : list α} (p : l₁ ~ l₂) :
powerset_len_aux n l₁ ~ powerset_len_aux n l₂ :=
begin
induction n with n IHn generalizing l₁ l₂, {simp},
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {refl},
{ simp, exact perm_app IH (perm_map _ (IHn p)) },
{ simp, apply perm_app_right,
cases n, {simp, apply perm.swap},
simp,
rw [← append_assoc, ← append_assoc,
(by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)],
exact perm_app_left _ perm_app_comm },
{ exact IH₁.trans IH₂ }
end
def powerset_len (n : ℕ) (s : multiset α) : multiset (multiset α) :=
quot.lift_on s
(λ l, (powerset_len_aux n l : multiset (multiset α)))
(λ l₁ l₂ h, quot.sound (powerset_len_aux_perm h))
theorem powerset_len_coe' (n) (l : list α) :
@powerset_len α n l = powerset_len_aux n l := rfl
theorem powerset_len_coe (n) (l : list α) :
@powerset_len α n l = ((sublists_len n l).map coe : list (multiset α)) :=
congr_arg coe powerset_len_aux_eq_map_coe
@[simp] theorem powerset_len_zero_left (s : multiset α) :
powerset_len 0 s = 0::0 :=
quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl
@[simp] theorem powerset_len_zero_right (n : ℕ) :
@powerset_len α (n + 1) 0 = 0 := rfl
@[simp] theorem powerset_len_cons (n : ℕ) (a : α) (s) :
powerset_len (n + 1) (a::s) =
powerset_len (n + 1) s + map (cons a) (powerset_len n s) :=
quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl
@[simp] theorem mem_powerset_len {n : ℕ} {s t : multiset α} :
s ∈ powerset_len n t ↔ s ≤ t ∧ card s = n :=
quotient.induction_on t $ λ l, by simp [powerset_len_coe']
@[simp] theorem card_powerset_len (n : ℕ) (s : multiset α) :
card (powerset_len n s) = nat.choose (card s) n :=
quotient.induction_on s $ by simp [powerset_len_coe]
theorem powerset_len_le_powerset (n : ℕ) (s : multiset α) :
powerset_len n s ≤ powerset s :=
quotient.induction_on s $ λ l, by simp [powerset_len_coe]; exact
subperm_of_sublist (map_sublist_map _ (sublists_len_sublist_sublists' _ _))
theorem powerset_len_mono (n : ℕ) {s t : multiset α} (h : s ≤ t) :
powerset_len n s ≤ powerset_len n t :=
le_induction_on h $ λ l₁ l₂ h, by simp [powerset_len_coe]; exact
subperm_of_sublist (map_sublist_map _ (sublists_len_sublist_of_sublist _ h))
/- countp -/
/-- `countp p s` counts the number of elements of `s` (with multiplicity) that
satisfy `p`. -/
def countp (p : α → Prop) [decidable_pred p] (s : multiset α) : ℕ :=
quot.lift_on s (countp p) (λ l₁ l₂, perm_countp p)
@[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl
@[simp] theorem countp_zero (p : α → Prop) [decidable_pred p] : countp p 0 = 0 := rfl
@[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a::s) = countp p s + 1 :=
quot.induction_on s countp_cons_of_pos
@[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a::s) = countp p s :=
quot.induction_on s countp_cons_of_neg
theorem countp_eq_card_filter (s) : countp p s = card (filter p s) :=
quot.induction_on s $ λ l, countp_eq_length_filter _
@[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t :=
by simp [countp_eq_card_filter]
instance countp.is_add_monoid_hom : is_add_monoid_hom (countp p : multiset α → ℕ) :=
{ map_add := countp_add, map_zero := countp_zero _ }
theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a :=
by simp [countp_eq_card_filter, card_pos_iff_exists_mem]
@[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) :
countp p (s - t) = countp p s - countp p t :=
by simp [countp_eq_card_filter, h, filter_le_filter]
theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s :=
countp_pos.2 ⟨_, h, pa⟩
theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t :=
by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter h)
@[simp] theorem countp_filter {q} [decidable_pred q] (s : multiset α) :
countp p (filter q s) = countp (λ a, p a ∧ q a) s :=
by simp [countp_eq_card_filter]
end
/- count -/
section
variable [decidable_eq α]
/-- `count a s` is the multiplicity of `a` in `s`. -/
def count (a : α) : multiset α → ℕ := countp (eq a)
@[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _
@[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl
@[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a::s) = succ (count a s) :=
countp_cons_of_pos _ rfl
@[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b::s) = count a s :=
countp_cons_of_neg _ h
theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t :=
countp_le_of_le
theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b :: s) :=
count_le_of_le _ (le_cons_self _ _)
theorem count_singleton (a : α) : count a (a::0) = 1 :=
by simp
@[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t :=
countp_add
instance count.is_add_monoid_hom (a : α) : is_add_monoid_hom (count a : multiset α → ℕ) :=
countp.is_add_monoid_hom
@[simp] theorem count_smul (a : α) (n s) : count a (n • s) = n * count a s :=
by induction n; simp [*, succ_smul', succ_mul]
theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s :=
by simp [count, countp_pos]
@[simp] theorem count_eq_zero_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) : count a s = 0 :=
by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h')
theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s :=
iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero
@[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n :=
by simp [repeat]
@[simp] theorem count_erase_self (a : α) (s : multiset α) : count a (erase s a) = pred (count a s) :=
begin
by_cases a ∈ s,
{ rw [(by rw cons_erase h : count a s = count a (a::erase s a)),
count_cons_self]; refl },
{ rw [erase_of_not_mem h, count_eq_zero.2 h]; refl }
end
@[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s :=
begin
by_cases b ∈ s,
{ rw [← count_cons_of_ne ab, cons_erase h] },
{ rw [erase_of_not_mem h] }
end
@[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t :=
begin
revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _),
rw [sub_cons, IH],
by_cases ab : a = b,
{ subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] },
{ rw [count_erase_of_ne ab, count_cons_of_ne ab] }
end
@[simp] theorem count_union (a : α) (s t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) :=
by simp [(∪), union, sub_add_eq_max, -add_comm]
@[simp] theorem count_inter (a : α) (s t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) :=
begin
apply @nat.add_left_cancel (count a (s - t)),
rw [← count_add, sub_add_inter, count_sub, sub_add_min],
end
lemma count_bind {m : multiset β} {f : β → multiset α} {a : α} :
count a (bind m f) = sum (m.map $ λb, count a $ f b) :=
multiset.induction_on m (by simp) (by simp)
theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s :=
quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm
@[simp] theorem count_filter {p} [decidable_pred p]
{a} {s : multiset α} (h : p a) : count a (filter p s) = count a s :=
quot.induction_on s $ λ l, count_filter h
theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t :=
quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count
@[extensionality]
theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t :=
ext.2
@[simp] theorem coe_inter (s t : list α) : (s ∩ t : multiset α) = (s.bag_inter t : list α) :=
by ext; simp
theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t :=
⟨λ h a, count_le_of_le a h, λ al,
by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t);
apply le_union_left⟩
instance : distrib_lattice (multiset α) :=
{ le_sup_inf := λ s t u, le_of_eq $ eq.symm $
ext.2 $ λ a, by simp only [max_min_distrib_left,
multiset.count_inter, multiset.sup_eq_union, multiset.count_union, multiset.inf_eq_inter],
..multiset.lattice.lattice }
instance : semilattice_sup_bot (multiset α) :=
{ bot := 0,
bot_le := zero_le,
..multiset.lattice.lattice }
end
/- relator -/
section rel
/-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`,
s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/
inductive rel (r : α → β → Prop) : multiset α → multiset β → Prop
| zero {} : rel 0 0
| cons {a b as bs} : r a b → rel as bs → rel (a :: as) (b :: bs)
run_cmd tactic.mk_iff_of_inductive_prop `multiset.rel `multiset.rel_iff
variables {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop}
private lemma rel_flip_aux {s t} (h : rel r s t) : rel (flip r) t s :=
rel.rec_on h rel.zero (assume _ _ _ _ h₀ h₁ ih, rel.cons h₀ ih)
lemma rel_flip {s t} : rel (flip r) s t ↔ rel r t s :=
⟨rel_flip_aux, rel_flip_aux⟩
lemma rel_eq_refl {s : multiset α} : rel (=) s s :=
multiset.induction_on s rel.zero (assume a s, rel.cons rfl)
lemma rel_eq {s t : multiset α} : rel (=) s t ↔ s = t :=
begin
split,
{ assume h, induction h; simp * },
{ assume h, subst h, exact rel_eq_refl }
end
lemma rel.mono {p : α → β → Prop} {s t} (h : ∀a b, r a b → p a b) (hst : rel r s t) : rel p s t :=
begin
induction hst,
case rel.zero { exact rel.zero },
case rel.cons : a b s t hab hst ih { exact ih.cons (h a b hab) }
end
lemma rel.add {s t u v} (hst : rel r s t) (huv : rel r u v) : rel r (s + u) (t + v) :=
begin
induction hst,
case rel.zero { simpa using huv },
case rel.cons : a b s t hab hst ih { simpa using ih.cons hab }
end
lemma rel_flip_eq {s t : multiset α} : rel (λa b, b = a) s t ↔ s = t :=
show rel (flip (=)) s t ↔ s = t, by rw [rel_flip, rel_eq, eq_comm]
@[simp] lemma rel_zero_left {b : multiset β} : rel r 0 b ↔ b = 0 :=
by rw [rel_iff]; simp
@[simp] lemma rel_zero_right {a : multiset α} : rel r a 0 ↔ a = 0 :=
by rw [rel_iff]; simp
lemma rel_cons_left {a as bs} :
rel r (a :: as) bs ↔ (∃b bs', r a b ∧ rel r as bs' ∧ bs = b :: bs') :=
begin
split,
{ generalize hm : a :: as = m,
assume h,
induction h generalizing as,
case rel.zero { simp at hm, contradiction },
case rel.cons : a' b as' bs ha'b h ih {
rcases cons_eq_cons.1 hm with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩,
{ subst eq₁, subst eq₂, exact ⟨b, bs, ha'b, h, rfl⟩ },
{ rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩,
exact ⟨b', b::bs', h₁, eq₁.symm ▸ rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩ }
} },
{ exact assume ⟨b, bs', hab, h, eq⟩, eq.symm ▸ rel.cons hab h }
end
lemma rel_cons_right {as b bs} :
rel r as (b :: bs) ↔ (∃a as', r a b ∧ rel r as' bs ∧ as = a :: as') :=
begin
rw [← rel_flip, rel_cons_left],
apply exists_congr, assume a,
apply exists_congr, assume as',
rw [rel_flip, flip]
end
lemma rel_add_left {as₀ as₁} :
∀{bs}, rel r (as₀ + as₁) bs ↔ (∃bs₀ bs₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ bs = bs₀ + bs₁) :=
multiset.induction_on as₀ (by simp)
begin
assume a s ih bs,
simp only [ih, cons_add, rel_cons_left],
split,
{ assume h,
rcases h with ⟨b, bs', hab, h, rfl⟩,
rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩,
exact ⟨b :: bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩ },
{ assume h,
rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩,
rcases h with ⟨b, bs, hab, h₀, rfl⟩,
exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩ }
end
lemma rel_add_right {as bs₀ bs₁} :
rel r as (bs₀ + bs₁) ↔ (∃as₀ as₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ as = as₀ + as₁) :=
by rw [← rel_flip, rel_add_left]; simp [rel_flip]
lemma rel_map_left {s : multiset γ} {f : γ → α} :
∀{t}, rel r (s.map f) t ↔ rel (λa b, r (f a) b) s t :=
multiset.induction_on s (by simp) (by simp [rel_cons_left] {contextual := tt})
lemma rel_map_right {s : multiset α} {t : multiset γ} {f : γ → β} :
rel r s (t.map f) ↔ rel (λa b, r a (f b)) s t :=
by rw [← rel_flip, rel_map_left, ← rel_flip]; refl
lemma rel_join {s t} (h : rel (rel r) s t) : rel r s.join t.join :=
begin
induction h,
case rel.zero { simp },
case rel.cons : a b s t hab hst ih { simpa using hab.add ih }
end
lemma rel_map {p : γ → δ → Prop} {s t} {f : α → γ} {g : β → δ} (h : (r ⇒ p) f g) (hst : rel r s t) :
rel p (s.map f) (t.map g) :=
by rw [rel_map_left, rel_map_right]; exact hst.mono h
lemma rel_bind {p : γ → δ → Prop} {s t} {f : α → multiset γ} {g : β → multiset δ}
(h : (r ⇒ rel p) f g) (hst : rel r s t) :
rel p (s.bind f) (t.bind g) :=
by apply rel_join; apply rel_map; assumption
lemma card_eq_card_of_rel {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) :
card s = card t :=
by induction h; simp [*]
lemma exists_mem_of_rel_of_mem {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) :
∀ {a : α} (ha : a ∈ s), ∃ b ∈ t, r a b :=
begin
induction h with x y s t hxy hst ih,
{ simp },
{ assume a ha,
cases mem_cons.1 ha with ha ha,
{ exact ⟨y, mem_cons_self _ _, ha.symm ▸ hxy⟩ },
{ rcases ih ha with ⟨b, hbt, hab⟩,
exact ⟨b, mem_cons.2 (or.inr hbt), hab⟩ } }
end
end rel
section map
theorem map_eq_map {f : α → β} (hf : function.injective f) {s t : multiset α} :
s.map f = t.map f ↔ s = t :=
by rw [← rel_eq, ← rel_eq, rel_map_left, rel_map_right]; simp [hf.eq_iff]
theorem injective_map {f : α → β} (hf : function.injective f) :
function.injective (multiset.map f) :=
assume x y, (map_eq_map hf).1
end map
section quot
theorem map_mk_eq_map_mk_of_rel {r : α → α → Prop} {s t : multiset α} (hst : s.rel r t) :
s.map (quot.mk r) = t.map (quot.mk r) :=
rel.rec_on hst rfl $ assume a b s t hab hst ih, by simp [ih, quot.sound hab]
theorem exists_multiset_eq_map_quot_mk {r : α → α → Prop} (s : multiset (quot r)) :
∃t:multiset α, s = t.map (quot.mk r) :=
multiset.induction_on s ⟨0, rfl⟩ $
assume a s ⟨t, ht⟩, quot.induction_on a $ assume a, ht.symm ▸ ⟨a::t, (map_cons _ _ _).symm⟩
theorem induction_on_multiset_quot
{r : α → α → Prop} {p : multiset (quot r) → Prop} (s : multiset (quot r)) :
(∀s:multiset α, p (s.map (quot.mk r))) → p s :=
match s, exists_multiset_eq_map_quot_mk s with _, ⟨t, rfl⟩ := assume h, h _ end
end quot
/- disjoint -/
/-- `disjoint s t` means that `s` and `t` have no elements in common. -/
def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false
@[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl
theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s
| a i₂ i₁ := d i₁ i₂
@[simp] theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s :=
⟨disjoint.symm, disjoint.symm⟩
theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl
theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s :=
disjoint_comm
theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b :=
by simp [disjoint_left, imp_not_comm]
theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t
| x m₁ := d (h m₁)
theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t
| x m m₁ := d m (h m₁)
theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t :=
disjoint_of_subset_left (subset_of_le h)
theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t :=
disjoint_of_subset_right (subset_of_le h)
@[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l
| a := (not_mem_nil a).elim
@[simp] theorem singleton_disjoint {l : multiset α} {a : α} : disjoint (a::0) l ↔ a ∉ l :=
by simp [disjoint]; refl
@[simp] theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l (a::0) ↔ a ∉ l :=
by rw disjoint_comm; simp
@[simp] theorem disjoint_add_left {s t u : multiset α} :
disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_add_right {s t u : multiset α} :
disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u :=
disjoint_comm.trans $ by simp [disjoint_append_left]
@[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} :
disjoint (a::s) t ↔ a ∉ t ∧ disjoint s t :=
(@disjoint_add_left _ (a::0) s t).trans $ by simp
@[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} :
disjoint s (a::t) ↔ a ∉ s ∧ disjoint s t :=
disjoint_comm.trans $ by simp [disjoint_cons_left]
theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t :=
by rw ← subset_zero; simp [subset_iff, disjoint]
@[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} :
disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} :
disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
lemma disjoint_map_map {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} :
disjoint (s.map f) (t.map g) ↔ (∀a∈s, ∀b∈t, f a ≠ g b) :=
begin
simp [disjoint],
split,
from assume h a ha b hb eq, h _ ha rfl _ hb eq.symm,
from assume h c a ha eq₁ b hb eq₂, h _ ha _ hb (eq₂.symm ▸ eq₁)
end
/-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/
def pairwise (r : α → α → Prop) (m : multiset α) : Prop :=
∃l:list α, m = l ∧ l.pairwise r
lemma pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : symmetric r) {l : list α} :
multiset.pairwise r l ↔ l.pairwise r :=
iff.intro
(assume ⟨l', eq, h⟩, (list.perm_pairwise hr (quotient.exact eq)).2 h)
(assume h, ⟨l, rfl, h⟩)
/- nodup -/
/-- `nodup s` means that `s` has no duplicates, i.e. the multiplicity of
any element is at most 1. -/
def nodup (s : multiset α) : Prop :=
quot.lift_on s nodup (λ s t p, propext $ perm_nodup p)
@[simp] theorem coe_nodup {l : list α} : @nodup α l ↔ l.nodup := iff.rfl
@[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l :=
⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩
@[simp] theorem nodup_zero : @nodup α 0 := pairwise.nil
@[simp] theorem nodup_cons {a : α} {s : multiset α} : nodup (a::s) ↔ a ∉ s ∧ nodup s :=
quot.induction_on s $ λ l, nodup_cons
theorem nodup_cons_of_nodup {a : α} {s : multiset α} (m : a ∉ s) (n : nodup s) : nodup (a::s) :=
nodup_cons.2 ⟨m, n⟩
theorem nodup_singleton : ∀ a : α, nodup (a::0) := nodup_singleton
theorem nodup_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : nodup s :=
(nodup_cons.1 h).2
theorem not_mem_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : a ∉ s :=
(nodup_cons.1 h).1
theorem nodup_of_le {s t : multiset α} (h : s ≤ t) : nodup t → nodup s :=
le_induction_on h $ λ l₁ l₂, nodup_of_sublist
theorem not_nodup_pair : ∀ a : α, ¬ nodup (a::a::0) := not_nodup_pair
theorem nodup_iff_le {s : multiset α} : nodup s ↔ ∀ a : α, ¬ a::a::0 ≤ s :=
quot.induction_on s $ λ l, nodup_iff_sublist.trans $ forall_congr $ λ a,
not_congr (@repeat_le_coe _ a 2 _).symm
theorem nodup_iff_count_le_one [decidable_eq α] {s : multiset α} : nodup s ↔ ∀ a, count a s ≤ 1 :=
quot.induction_on s $ λ l, nodup_iff_count_le_one
@[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {s : multiset α}
(d : nodup s) (h : a ∈ s) : count a s = 1 :=
le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h)
lemma pairwise_of_nodup {r : α → α → Prop} {s : multiset α} :
(∀a∈s, ∀b∈s, a ≠ b → r a b) → nodup s → pairwise r s :=
quotient.induction_on s $ assume l h hl, ⟨l, rfl, hl.imp_of_mem $ assume a b ha hb, h a ha b hb⟩
lemma forall_of_pairwise {r : α → α → Prop} (H : symmetric r) {s : multiset α}
(hs : pairwise r s) : (∀a∈s, ∀b∈s, a ≠ b → r a b) :=
let ⟨l, hl₁, hl₂⟩ := hs in hl₁.symm ▸ list.forall_of_pairwise H hl₂
theorem nodup_add {s t : multiset α} : nodup (s + t) ↔ nodup s ∧ nodup t ∧ disjoint s t :=
quotient.induction_on₂ s t $ λ l₁ l₂, nodup_append
theorem disjoint_of_nodup_add {s t : multiset α} (d : nodup (s + t)) : disjoint s t :=
(nodup_add.1 d).2.2
theorem nodup_add_of_nodup {s t : multiset α} (d₁ : nodup s) (d₂ : nodup t) : nodup (s + t) ↔ disjoint s t :=
by simp [nodup_add, d₁, d₂]
theorem nodup_of_nodup_map (f : α → β) {s : multiset α} : nodup (map f s) → nodup s :=
quot.induction_on s $ λ l, nodup_of_nodup_map f
theorem nodup_map_on {f : α → β} {s : multiset α} : (∀x∈s, ∀y∈s, f x = f y → x = y) →
nodup s → nodup (map f s) :=
quot.induction_on s $ λ l, nodup_map_on
theorem nodup_map {f : α → β} {s : multiset α} (hf : function.injective f) : nodup s → nodup (map f s) :=
nodup_map_on (λ x _ y _ h, hf h)
theorem nodup_filter (p : α → Prop) [decidable_pred p] {s} : nodup s → nodup (filter p s) :=
quot.induction_on s $ λ l, nodup_filter p
@[simp] theorem nodup_attach {s : multiset α} : nodup (attach s) ↔ nodup s :=
quot.induction_on s $ λ l, nodup_attach
theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {s : multiset α} {H}
(hf : ∀ a ha b hb, f a ha = f b hb → a = b) : nodup s → nodup (pmap f s H) :=
quot.induction_on s (λ l H, nodup_pmap hf) H
instance nodup_decidable [decidable_eq α] (s : multiset α) : decidable (nodup s) :=
quotient.rec_on_subsingleton s $ λ l, l.nodup_decidable
theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {s} : nodup s → s.erase a = filter (≠ a) s :=
quot.induction_on s $ λ l d, congr_arg coe $ nodup_erase_eq_filter a d
theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) :=
nodup_of_le (erase_le _ _)
theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) :
a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l :=
by rw nodup_erase_eq_filter b d; simp [and_comm]
theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a :=
by rw mem_erase_iff_of_nodup h; simp
theorem nodup_product {s : multiset α} {t : multiset β} : nodup s → nodup t → nodup (product s t) :=
quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, by simp [nodup_product d₁ d₂]
theorem nodup_sigma {σ : α → Type*} {s : multiset α} {t : Π a, multiset (σ a)} :
nodup s → (∀ a, nodup (t a)) → nodup (s.sigma t) :=
quot.induction_on s $ assume l₁,
begin
choose f hf using assume a, quotient.exists_rep (t a),
rw show t = λ a, f a, from (eq.symm $ funext $ λ a, hf a),
simpa using nodup_sigma
end
theorem nodup_filter_map (f : α → option β) {s : multiset α}
(H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') :
nodup s → nodup (filter_map f s) :=
quot.induction_on s $ λ l, nodup_filter_map H
theorem nodup_range (n : ℕ) : nodup (range n) := nodup_range _
theorem nodup_inter_left [decidable_eq α] {s : multiset α} (t) : nodup s → nodup (s ∩ t) :=
nodup_of_le $ inter_le_left _ _
theorem nodup_inter_right [decidable_eq α] (s) {t : multiset α} : nodup t → nodup (s ∩ t) :=
nodup_of_le $ inter_le_right _ _
@[simp] theorem nodup_union [decidable_eq α] {s t : multiset α} : nodup (s ∪ t) ↔ nodup s ∧ nodup t :=
⟨λ h, ⟨nodup_of_le (le_union_left _ _) h, nodup_of_le (le_union_right _ _) h⟩,
λ ⟨h₁, h₂⟩, nodup_iff_count_le_one.2 $ λ a, by rw [count_union]; exact
max_le (nodup_iff_count_le_one.1 h₁ a) (nodup_iff_count_le_one.1 h₂ a)⟩
@[simp] theorem nodup_powerset {s : multiset α} : nodup (powerset s) ↔ nodup s :=
⟨λ h, nodup_of_nodup_map _ (nodup_of_le (map_single_le_powerset _) h),
quotient.induction_on s $ λ l h,
by simp; refine list.nodup_map_on _ (nodup_sublists'.2 h); exact
λ x sx y sy e,
(perm_ext_sublist_nodup h (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1
(quotient.exact e)⟩
theorem nodup_powerset_len {n : ℕ} {s : multiset α}
(h : nodup s) : nodup (powerset_len n s) :=
nodup_of_le (powerset_len_le_powerset _ _) (nodup_powerset.2 h)
@[simp] lemma nodup_bind {s : multiset α} {t : α → multiset β} :
nodup (bind s t) ↔ ((∀a∈s, nodup (t a)) ∧ (s.pairwise (λa b, disjoint (t a) (t b)))) :=
have h₁ : ∀a, ∃l:list β, t a = l, from
assume a, quot.induction_on (t a) $ assume l, ⟨l, rfl⟩,
let ⟨t', h'⟩ := classical.axiom_of_choice h₁ in
have t = λa, t' a, from funext h',
have hd : symmetric (λa b, list.disjoint (t' a) (t' b)), from assume a b h, h.symm,
quot.induction_on s $ by simp [this, list.nodup_bind, pairwise_coe_iff_pairwise hd]
theorem nodup_ext {s t : multiset α} : nodup s → nodup t → (s = t ↔ ∀ a, a ∈ s ↔ a ∈ t) :=
quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, quotient.eq.trans $ perm_ext d₁ d₂
theorem le_iff_subset {s t : multiset α} : nodup s → (s ≤ t ↔ s ⊆ t) :=
quotient.induction_on₂ s t $ λ l₁ l₂ d, ⟨subset_of_le, subperm_of_subset_nodup d⟩
theorem range_le {m n : ℕ} : range m ≤ range n ↔ m ≤ n :=
(le_iff_subset (nodup_range _)).trans range_subset
theorem mem_sub_of_nodup [decidable_eq α] {a : α} {s t : multiset α} (d : nodup s) :
a ∈ s - t ↔ a ∈ s ∧ a ∉ t :=
⟨λ h, ⟨mem_of_le (sub_le_self _ _) h, λ h',
by refine count_eq_zero.1 _ h; rw [count_sub a s t, nat.sub_eq_zero_iff_le];
exact le_trans (nodup_iff_count_le_one.1 d _) (count_pos.2 h')⟩,
λ ⟨h₁, h₂⟩, or.resolve_right (mem_add.1 $ mem_of_le (le_sub_add _ _) h₁) h₂⟩
section
variable [decidable_eq α]
/- erase_dup -/
/-- `erase_dup s` removes duplicates from `s`, yielding a `nodup` multiset. -/
def erase_dup (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (l.erase_dup : multiset α))
(λ s t p, quot.sound (perm_erase_dup_of_perm p))
@[simp] theorem coe_erase_dup (l : list α) : @erase_dup α _ l = l.erase_dup := rfl
@[simp] theorem erase_dup_zero : @erase_dup α _ 0 = 0 := rfl
@[simp] theorem mem_erase_dup {a : α} {s : multiset α} : a ∈ erase_dup s ↔ a ∈ s :=
quot.induction_on s $ λ l, mem_erase_dup
@[simp] theorem erase_dup_cons_of_mem {a : α} {s : multiset α} : a ∈ s →
erase_dup (a::s) = erase_dup s :=
quot.induction_on s $ λ l m, @congr_arg _ _ _ _ coe $ erase_dup_cons_of_mem m
@[simp] theorem erase_dup_cons_of_not_mem {a : α} {s : multiset α} : a ∉ s →
erase_dup (a::s) = a :: erase_dup s :=
quot.induction_on s $ λ l m, congr_arg coe $ erase_dup_cons_of_not_mem m
theorem erase_dup_le (s : multiset α) : erase_dup s ≤ s :=
quot.induction_on s $ λ l, subperm_of_sublist $ erase_dup_sublist _
theorem erase_dup_subset (s : multiset α) : erase_dup s ⊆ s :=
subset_of_le $ erase_dup_le _
theorem subset_erase_dup (s : multiset α) : s ⊆ erase_dup s :=
λ a, mem_erase_dup.2
@[simp] theorem erase_dup_subset' {s t : multiset α} : erase_dup s ⊆ t ↔ s ⊆ t :=
⟨subset.trans (subset_erase_dup _), subset.trans (erase_dup_subset _)⟩
@[simp] theorem subset_erase_dup' {s t : multiset α} : s ⊆ erase_dup t ↔ s ⊆ t :=
⟨λ h, subset.trans h (erase_dup_subset _), λ h, subset.trans h (subset_erase_dup _)⟩
@[simp] theorem nodup_erase_dup (s : multiset α) : nodup (erase_dup s) :=
quot.induction_on s nodup_erase_dup
theorem erase_dup_eq_self {s : multiset α} : erase_dup s = s ↔ nodup s :=
⟨λ e, e ▸ nodup_erase_dup s,
quot.induction_on s $ λ l h, congr_arg coe $ erase_dup_eq_self.2 h⟩
theorem erase_dup_eq_zero {s : multiset α} : erase_dup s = 0 ↔ s = 0 :=
⟨λ h, eq_zero_of_subset_zero $ h ▸ subset_erase_dup _,
λ h, h.symm ▸ erase_dup_zero⟩
@[simp] theorem erase_dup_singleton {a : α} : erase_dup (a :: 0) = a :: 0 :=
erase_dup_eq_self.2 $ nodup_singleton _
theorem le_erase_dup {s t : multiset α} : s ≤ erase_dup t ↔ s ≤ t ∧ nodup s :=
⟨λ h, ⟨le_trans h (erase_dup_le _), nodup_of_le h (nodup_erase_dup _)⟩,
λ ⟨l, d⟩, (le_iff_subset d).2 $ subset.trans (subset_of_le l) (subset_erase_dup _)⟩
theorem erase_dup_ext {s t : multiset α} : erase_dup s = erase_dup t ↔ ∀ a, a ∈ s ↔ a ∈ t :=
by simp [nodup_ext]
theorem erase_dup_map_erase_dup_eq [decidable_eq β] (f : α → β) (s : multiset α) :
erase_dup (map f (erase_dup s)) = erase_dup (map f s) := by simp [erase_dup_ext]
/- finset insert -/
/-- `ndinsert a s` is the lift of the list `insert` operation. This operation
does not respect multiplicities, unlike `cons`, but it is suitable as
an insert operation on `finset`. -/
def ndinsert (a : α) (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (l.insert a : multiset α))
(λ s t p, quot.sound (perm_insert a p))
@[simp] theorem coe_ndinsert (a : α) (l : list α) : ndinsert a l = (insert a l : list α) := rfl
@[simp] theorem ndinsert_zero (a : α) : ndinsert a 0 = a::0 := rfl
@[simp] theorem ndinsert_of_mem {a : α} {s : multiset α} : a ∈ s → ndinsert a s = s :=
quot.induction_on s $ λ l h, congr_arg coe $ insert_of_mem h
@[simp] theorem ndinsert_of_not_mem {a : α} {s : multiset α} : a ∉ s → ndinsert a s = a :: s :=
quot.induction_on s $ λ l h, congr_arg coe $ insert_of_not_mem h
@[simp] theorem mem_ndinsert {a b : α} {s : multiset α} : a ∈ ndinsert b s ↔ a = b ∨ a ∈ s :=
quot.induction_on s $ λ l, mem_insert_iff
@[simp] theorem le_ndinsert_self (a : α) (s : multiset α) : s ≤ ndinsert a s :=
quot.induction_on s $ λ l, subperm_of_sublist $ sublist_of_suffix $ suffix_insert _ _
@[simp] theorem mem_ndinsert_self (a : α) (s : multiset α) : a ∈ ndinsert a s :=
mem_ndinsert.2 (or.inl rfl)
@[simp] theorem mem_ndinsert_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ ndinsert b s :=
mem_ndinsert.2 (or.inr h)
@[simp] theorem length_ndinsert_of_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∈ s) :
card (ndinsert a s) = card s :=
by simp [h]
@[simp] theorem length_ndinsert_of_not_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∉ s) :
card (ndinsert a s) = card s + 1 :=
by simp [h]
theorem erase_dup_cons {a : α} {s : multiset α} :
erase_dup (a::s) = ndinsert a (erase_dup s) :=
by by_cases a ∈ s; simp [h]
theorem nodup_ndinsert (a : α) {s : multiset α} : nodup s → nodup (ndinsert a s) :=
quot.induction_on s $ λ l, nodup_insert
theorem ndinsert_le {a : α} {s t : multiset α} : ndinsert a s ≤ t ↔ s ≤ t ∧ a ∈ t :=
⟨λ h, ⟨le_trans (le_ndinsert_self _ _) h, mem_of_le h (mem_ndinsert_self _ _)⟩,
λ ⟨l, m⟩, if h : a ∈ s then by simp [h, l] else
by rw [ndinsert_of_not_mem h, ← cons_erase m, cons_le_cons_iff,
← le_cons_of_not_mem h, cons_erase m]; exact l⟩
lemma attach_ndinsert (a : α) (s : multiset α) :
(s.ndinsert a).attach =
ndinsert ⟨a, mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, mem_ndinsert_of_mem p.2⟩) :=
have eq : ∀h : ∀(p : {x // x ∈ s}), p.1 ∈ s,
(λ (p : {x // x ∈ s}), ⟨p.val, h p⟩ : {x // x ∈ s} → {x // x ∈ s}) = id, from
assume h, funext $ assume p, subtype.eq rfl,
have ∀t (eq : s.ndinsert a = t), t.attach = ndinsert ⟨a, eq ▸ mem_ndinsert_self a s⟩
(s.attach.map $ λp, ⟨p.1, eq ▸ mem_ndinsert_of_mem p.2⟩),
begin
intros t ht,
by_cases a ∈ s,
{ rw [ndinsert_of_mem h] at ht,
subst ht,
rw [eq, map_id, ndinsert_of_mem (mem_attach _ _)] },
{ rw [ndinsert_of_not_mem h] at ht,
subst ht,
simp [attach_cons, h] }
end,
this _ rfl
@[simp] theorem disjoint_ndinsert_left {a : α} {s t : multiset α} :
disjoint (ndinsert a s) t ↔ a ∉ t ∧ disjoint s t :=
iff.trans (by simp [disjoint]) disjoint_cons_left
@[simp] theorem disjoint_ndinsert_right {a : α} {s t : multiset α} :
disjoint s (ndinsert a t) ↔ a ∉ s ∧ disjoint s t :=
disjoint_comm.trans $ by simp
/- finset union -/
/-- `ndunion s t` is the lift of the list `union` operation. This operation
does not respect multiplicities, unlike `s ∪ t`, but it is suitable as
a union operation on `finset`. (`s ∪ t` would also work as a union operation
on finset, but this is more efficient.) -/
def ndunion (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.union l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ perm_union p₁ p₂
@[simp] theorem coe_ndunion (l₁ l₂ : list α) : @ndunion α _ l₁ l₂ = (l₁ ∪ l₂ : list α) := rfl
@[simp] theorem zero_ndunion (s : multiset α) : ndunion 0 s = s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem cons_ndunion (s t : multiset α) (a : α) : ndunion (a :: s) t = ndinsert a (ndunion s t) :=
quotient.induction_on₂ s t $ λ l₁ l₂, rfl
@[simp] theorem mem_ndunion {s t : multiset α} {a : α} : a ∈ ndunion s t ↔ a ∈ s ∨ a ∈ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, list.mem_union
theorem le_ndunion_right (s t : multiset α) : t ≤ ndunion s t :=
quotient.induction_on₂ s t $ λ l₁ l₂,
subperm_of_sublist $ sublist_of_suffix $ suffix_union_right _ _
theorem ndunion_le_add (s t : multiset α) : ndunion s t ≤ s + t :=
quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ union_sublist_append _ _
theorem ndunion_le {s t u : multiset α} : ndunion s t ≤ u ↔ s ⊆ u ∧ t ≤ u :=
multiset.induction_on s (by simp) (by simp [ndinsert_le, and_comm, and.left_comm] {contextual := tt})
theorem subset_ndunion_left (s t : multiset α) : s ⊆ ndunion s t :=
λ a h, mem_ndunion.2 $ or.inl h
theorem le_ndunion_left {s} (t : multiset α) (d : nodup s) : s ≤ ndunion s t :=
(le_iff_subset d).2 $ subset_ndunion_left _ _
theorem ndunion_le_union (s t : multiset α) : ndunion s t ≤ s ∪ t :=
ndunion_le.2 ⟨subset_of_le (le_union_left _ _), le_union_right _ _⟩
theorem nodup_ndunion (s : multiset α) {t : multiset α} : nodup t → nodup (ndunion s t) :=
quotient.induction_on₂ s t $ λ l₁ l₂, list.nodup_union _
@[simp] theorem ndunion_eq_union {s t : multiset α} (d : nodup s) : ndunion s t = s ∪ t :=
le_antisymm (ndunion_le_union _ _) $ union_le (le_ndunion_left _ d) (le_ndunion_right _ _)
theorem erase_dup_add (s t : multiset α) : erase_dup (s + t) = ndunion s (erase_dup t) :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ erase_dup_append _ _
/- finset inter -/
/-- `ndinter s t` is the lift of the list `∩` operation. This operation
does not respect multiplicities, unlike `s ∩ t`, but it is suitable as
an intersection operation on `finset`. (`s ∩ t` would also work as a union operation
on finset, but this is more efficient.) -/
def ndinter (s t : multiset α) : multiset α := filter (∈ t) s
@[simp] theorem coe_ndinter (l₁ l₂ : list α) : @ndinter α _ l₁ l₂ = (l₁ ∩ l₂ : list α) := rfl
@[simp] theorem zero_ndinter (s : multiset α) : ndinter 0 s = 0 := rfl
@[simp] theorem cons_ndinter_of_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∈ t) :
ndinter (a::s) t = a :: (ndinter s t) := by simp [ndinter, h]
@[simp] theorem ndinter_cons_of_not_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∉ t) :
ndinter (a::s) t = ndinter s t := by simp [ndinter, h]
@[simp] theorem mem_ndinter {s t : multiset α} {a : α} : a ∈ ndinter s t ↔ a ∈ s ∧ a ∈ t :=
mem_filter
theorem nodup_ndinter {s : multiset α} (t : multiset α) : nodup s → nodup (ndinter s t) :=
nodup_filter _
theorem le_ndinter {s t u : multiset α} : s ≤ ndinter t u ↔ s ≤ t ∧ s ⊆ u :=
by simp [ndinter, le_filter, subset_iff]
theorem ndinter_le_left (s t : multiset α) : ndinter s t ≤ s :=
(le_ndinter.1 (le_refl _)).1
theorem ndinter_subset_right (s t : multiset α) : ndinter s t ⊆ t :=
(le_ndinter.1 (le_refl _)).2
theorem ndinter_le_right {s} (t : multiset α) (d : nodup s) : ndinter s t ≤ t :=
(le_iff_subset $ nodup_ndinter _ d).2 (ndinter_subset_right _ _)
theorem inter_le_ndinter (s t : multiset α) : s ∩ t ≤ ndinter s t :=
le_ndinter.2 ⟨inter_le_left _ _, subset_of_le $ inter_le_right _ _⟩
@[simp] theorem ndinter_eq_inter {s t : multiset α} (d : nodup s) : ndinter s t = s ∩ t :=
le_antisymm (le_inter (ndinter_le_left _ _) (ndinter_le_right _ d)) (inter_le_ndinter _ _)
theorem ndinter_eq_zero_iff_disjoint {s t : multiset α} : ndinter s t = 0 ↔ disjoint s t :=
by rw ← subset_zero; simp [subset_iff, disjoint]
end
/- fold -/
section fold
variables (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op]
local notation a * b := op a b
include hc ha
/-- `fold op b s` folds a commutative associative operation `op` over
the multiset `s`. -/
def fold : α → multiset α → α := foldr op (left_comm _ hc.comm ha.assoc)
theorem fold_eq_foldr (b : α) (s : multiset α) : fold op b s = foldr op (left_comm _ hc.comm ha.assoc) b s := rfl
@[simp] theorem coe_fold_r (b : α) (l : list α) : fold op b l = l.foldr op b := rfl
theorem coe_fold_l (b : α) (l : list α) : fold op b l = l.foldl op b :=
(coe_foldr_swap op _ b l).trans $ by simp [hc.comm]
theorem fold_eq_foldl (b : α) (s : multiset α) : fold op b s = foldl op (right_comm _ hc.comm ha.assoc) b s :=
quot.induction_on s $ λ l, coe_fold_l _ _ _
@[simp] theorem fold_zero (b : α) : (0 : multiset α).fold op b = b := rfl
@[simp] theorem fold_cons_left : ∀ (b a : α) (s : multiset α),
(a :: s).fold op b = a * s.fold op b := foldr_cons _ _
theorem fold_cons_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op b * a :=
by simp [hc.comm]
theorem fold_cons'_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (b * a) :=
by rw [fold_eq_foldl, foldl_cons, ← fold_eq_foldl]
theorem fold_cons'_left (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (a * b) :=
by rw [fold_cons'_right, hc.comm]
theorem fold_add (b₁ b₂ : α) (s₁ s₂ : multiset α) : (s₁ + s₂).fold op (b₁ * b₂) = s₁.fold op b₁ * s₂.fold op b₂ :=
multiset.induction_on s₂
(by rw [add_zero, fold_zero, ← fold_cons'_right, ← fold_cons_right op])
(by simp {contextual := tt}; cc)
theorem fold_singleton (b a : α) : (a::0 : multiset α).fold op b = a * b := by simp
theorem fold_distrib {f g : β → α} (u₁ u₂ : α) (s : multiset β) :
(s.map (λx, f x * g x)).fold op (u₁ * u₂) = (s.map f).fold op u₁ * (s.map g).fold op u₂ :=
multiset.induction_on s (by simp) (by simp {contextual := tt}; cc)
theorem fold_hom {op' : β → β → β} [is_commutative β op'] [is_associative β op']
{m : α → β} (hm : ∀x y, m (op x y) = op' (m x) (m y)) (b : α) (s : multiset α) :
(s.map m).fold op' (m b) = m (s.fold op b) :=
multiset.induction_on s (by simp) (by simp [hm] {contextual := tt})
theorem fold_union_inter [decidable_eq α] (s₁ s₂ : multiset α) (b₁ b₂ : α) :
(s₁ ∪ s₂).fold op b₁ * (s₁ ∩ s₂).fold op b₂ = s₁.fold op b₁ * s₂.fold op b₂ :=
by rw [← fold_add op, union_add_inter, fold_add op]
@[simp] theorem fold_erase_dup_idem [decidable_eq α] [hi : is_idempotent α op] (s : multiset α) (b : α) :
(erase_dup s).fold op b = s.fold op b :=
multiset.induction_on s (by simp) $ λ a s IH, begin
by_cases a ∈ s; simp [IH, h],
show fold op b s = op a (fold op b s),
rw [← cons_erase h, fold_cons_left, ← ha.assoc, hi.idempotent],
end
end fold
theorem le_smul_erase_dup [decidable_eq α] (s : multiset α) :
∃ n : ℕ, s ≤ n • erase_dup s :=
⟨(s.map (λ a, count a s)).fold max 0, le_iff_count.2 $ λ a, begin
rw count_smul, by_cases a ∈ s,
{ refine le_trans _ (mul_le_mul_left _ $ count_pos.2 $ mem_erase_dup.2 h),
have : count a s ≤ fold max 0 (map (λ a, count a s) (a :: erase s a));
[simp [le_max_left], simpa [cons_erase h]] },
{ simp [count_eq_zero.2 h, nat.zero_le] }
end⟩
section sup
variables [semilattice_sup_bot α]
/-- Supremum of a multiset: `sup {a, b, c} = a ⊔ b ⊔ c` -/
def sup (s : multiset α) : α := s.fold (⊔) ⊥
@[simp] lemma sup_zero : (0 : multiset α).sup = ⊥ :=
fold_zero _ _
@[simp] lemma sup_cons (a : α) (s : multiset α) :
(a :: s).sup = a ⊔ s.sup :=
fold_cons_left _ _ _ _
@[simp] lemma sup_singleton {a : α} : (a::0).sup = a := by simp
@[simp] lemma sup_add (s₁ s₂ : multiset α) : (s₁ + s₂).sup = s₁.sup ⊔ s₂.sup :=
eq.trans (by simp [sup]) (fold_add _ _ _ _ _)
variables [decidable_eq α]
@[simp] lemma sup_erase_dup (s : multiset α) : (erase_dup s).sup = s.sup :=
fold_erase_dup_idem _ _ _
@[simp] lemma sup_ndunion (s₁ s₂ : multiset α) :
(ndunion s₁ s₂).sup = s₁.sup ⊔ s₂.sup :=
by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp
@[simp] lemma sup_union (s₁ s₂ : multiset α) :
(s₁ ∪ s₂).sup = s₁.sup ⊔ s₂.sup :=
by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp
@[simp] lemma sup_ndinsert (a : α) (s : multiset α) :
(ndinsert a s).sup = a ⊔ s.sup :=
by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_cons]; simp
lemma sup_le {s : multiset α} {a : α} : s.sup ≤ a ↔ (∀b ∈ s, b ≤ a) :=
multiset.induction_on s (by simp)
(by simp [or_imp_distrib, forall_and_distrib] {contextual := tt})
lemma le_sup {s : multiset α} {a : α} (h : a ∈ s) : a ≤ s.sup :=
sup_le.1 (le_refl _) _ h
lemma sup_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₁.sup ≤ s₂.sup :=
sup_le.2 $ assume b hb, le_sup (h hb)
end sup
section inf
variables [semilattice_inf_top α]
/-- Infimum of a multiset: `inf {a, b, c} = a ⊓ b ⊓ c` -/
def inf (s : multiset α) : α := s.fold (⊓) ⊤
@[simp] lemma inf_zero : (0 : multiset α).inf = ⊤ :=
fold_zero _ _
@[simp] lemma inf_cons (a : α) (s : multiset α) :
(a :: s).inf = a ⊓ s.inf :=
fold_cons_left _ _ _ _
@[simp] lemma inf_singleton {a : α} : (a::0).inf = a := by simp
@[simp] lemma inf_add (s₁ s₂ : multiset α) : (s₁ + s₂).inf = s₁.inf ⊓ s₂.inf :=
eq.trans (by simp [inf]) (fold_add _ _ _ _ _)
variables [decidable_eq α]
@[simp] lemma inf_erase_dup (s : multiset α) : (erase_dup s).inf = s.inf :=
fold_erase_dup_idem _ _ _
@[simp] lemma inf_ndunion (s₁ s₂ : multiset α) :
(ndunion s₁ s₂).inf = s₁.inf ⊓ s₂.inf :=
by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp
@[simp] lemma inf_union (s₁ s₂ : multiset α) :
(s₁ ∪ s₂).inf = s₁.inf ⊓ s₂.inf :=
by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp
@[simp] lemma inf_ndinsert (a : α) (s : multiset α) :
(ndinsert a s).inf = a ⊓ s.inf :=
by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_cons]; simp
lemma le_inf {s : multiset α} {a : α} : a ≤ s.inf ↔ (∀b ∈ s, a ≤ b) :=
multiset.induction_on s (by simp)
(by simp [or_imp_distrib, forall_and_distrib] {contextual := tt})
lemma inf_le {s : multiset α} {a : α} (h : a ∈ s) : s.inf ≤ a :=
le_inf.1 (le_refl _) _ h
lemma inf_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₂.inf ≤ s₁.inf :=
le_inf.2 $ assume b hb, inf_le (h hb)
end inf
section sort
variables (r : α → α → Prop) [decidable_rel r]
[is_trans α r] [is_antisymm α r] [is_total α r]
/-- `sort s` constructs a sorted list from the multiset `s`.
(Uses merge sort algorithm.) -/
def sort (s : multiset α) : list α :=
quot.lift_on s (merge_sort r) $ λ a b h,
eq_of_sorted_of_perm
((perm_merge_sort _ _).trans $ h.trans (perm_merge_sort _ _).symm)
(sorted_merge_sort r _)
(sorted_merge_sort r _)
@[simp] theorem coe_sort (l : list α) : sort r l = merge_sort r l := rfl
@[simp] theorem sort_sorted (s : multiset α) : sorted r (sort r s) :=
quot.induction_on s $ λ l, sorted_merge_sort r _
@[simp] theorem sort_eq (s : multiset α) : ↑(sort r s) = s :=
quot.induction_on s $ λ l, quot.sound $ perm_merge_sort _ _
@[simp] theorem mem_sort {s : multiset α} {a : α} : a ∈ sort r s ↔ a ∈ s :=
by rw [← mem_coe, sort_eq]
@[simp] theorem length_sort {s : multiset α} : (sort r s).length = s.card :=
quot.induction_on s $ length_merge_sort _
end sort
instance [has_repr α] : has_repr (multiset α) :=
⟨λ s, "{" ++ string.intercalate ", " ((s.map repr).sort (≤)) ++ "}"⟩
section sections
def sections (s : multiset (multiset α)) : multiset (multiset α) :=
multiset.rec_on s {0} (λs _ c, s.bind $ λa, c.map ((::) a))
(assume a₀ a₁ s pi, by simp [map_bind, bind_bind a₀ a₁, cons_swap])
@[simp] lemma sections_zero : sections (0 : multiset (multiset α)) = 0::0 :=
rfl
@[simp] lemma sections_cons (s : multiset (multiset α)) (m : multiset α) :
sections (m :: s) = m.bind (λa, (sections s).map ((::) a)) :=
rec_on_cons m s
lemma coe_sections : ∀(l : list (list α)),
sections ((l.map (λl:list α, (l : multiset α))) : multiset (multiset α)) =
((l.sections.map (λl:list α, (l : multiset α))) : multiset (multiset α))
| [] := rfl
| (a :: l) :=
begin
simp,
rw [← cons_coe, sections_cons, bind_map_comm, coe_sections l],
simp [list.sections, (∘), list.bind]
end
@[simp] lemma sections_add (s t : multiset (multiset α)) :
sections (s + t) = (sections s).bind (λm, (sections t).map ((+) m)) :=
multiset.induction_on s (by simp)
(assume a s ih, by simp [ih, bind_assoc, map_bind, bind_map, -add_comm])
lemma mem_sections {s : multiset (multiset α)} :
∀{a}, a ∈ sections s ↔ s.rel (λs a, a ∈ s) a :=
multiset.induction_on s (by simp)
(assume a s ih a',
by simp [ih, rel_cons_left, -exists_and_distrib_left, exists_and_distrib_left.symm, eq_comm])
lemma card_sections {s : multiset (multiset α)} : card (sections s) = prod (s.map card) :=
multiset.induction_on s (by simp) (by simp {contextual := tt})
lemma prod_map_sum [comm_semiring α] {s : multiset (multiset α)} :
prod (s.map sum) = sum ((sections s).map prod) :=
multiset.induction_on s (by simp)
(assume a s ih, by simp [ih, map_bind, sum_map_mul_left, sum_map_mul_right])
end sections
section pi
variables [decidable_eq α] {δ : α → Type*}
open function
def pi.cons (m : multiset α) (a : α) (b : δ a) (f : Πa∈m, δ a) : Πa'∈a::m, δ a' :=
λa' ha', if h : a' = a then eq.rec b h.symm else f a' $ (mem_cons.1 ha').resolve_left h
def pi.empty (δ : α → Type*) : (Πa∈(0:multiset α), δ a) .
lemma pi.cons_same {m : multiset α} {a : α} {b : δ a} {f : Πa∈m, δ a} (h : a ∈ a :: m) :
pi.cons m a b f a h = b :=
dif_pos rfl
lemma pi.cons_ne {m : multiset α} {a a' : α} {b : δ a} {f : Πa∈m, δ a} (h' : a' ∈ a :: m) (h : a' ≠ a) :
pi.cons m a b f a' h' = f a' ((mem_cons.1 h').resolve_left h) :=
dif_neg h
lemma pi.cons_swap {a a' : α} {b : δ a} {b' : δ a'} {m : multiset α} {f : Πa∈m, δ a} (h : a ≠ a') :
pi.cons (a' :: m) a b (pi.cons m a' b' f) == pi.cons (a :: m) a' b' (pi.cons m a b f) :=
begin
apply hfunext, { refl }, intros a'' _ h, subst h,
apply hfunext, { rw [cons_swap] }, intros ha₁ ha₂ h,
by_cases h₁ : a'' = a; by_cases h₂ : a'' = a';
simp [*, pi.cons_same, pi.cons_ne] at *,
{ subst h₁, rw [pi.cons_same, pi.cons_same] },
{ subst h₂, rw [pi.cons_same, pi.cons_same] }
end
/-- `pi m t` constructs the Cartesian product over `t` indexed by `m`. -/
def pi (m : multiset α) (t : Πa, multiset (δ a)) : multiset (Πa∈m, δ a) :=
m.rec_on {pi.empty δ} (λa m (p : multiset (Πa∈m, δ a)), (t a).bind $ λb, p.map $ pi.cons m a b)
begin
intros a a' m n,
by_cases eq : a = a',
{ subst eq },
{ simp [map_bind, bind_bind (t a') (t a)],
apply bind_hcongr, { rw [cons_swap a a'] },
intros b hb,
apply bind_hcongr, { rw [cons_swap a a'] },
intros b' hb',
apply map_hcongr, { rw [cons_swap a a'] },
intros f hf,
exact pi.cons_swap eq }
end
@[simp] lemma pi_zero (t : Πa, multiset (δ a)) : pi 0 t = pi.empty δ :: 0 := rfl
@[simp] lemma pi_cons (m : multiset α) (t : Πa, multiset (δ a)) (a : α) :
pi (a :: m) t = ((t a).bind $ λb, (pi m t).map $ pi.cons m a b) :=
rec_on_cons a m
lemma injective_pi_cons {a : α} {b : δ a} {s : multiset α} (hs : a ∉ s) :
function.injective (pi.cons s a b) :=
assume f₁ f₂ eq, funext $ assume a', funext $ assume h',
have ne : a ≠ a', from assume h, hs $ h.symm ▸ h',
have a' ∈ a :: s, from mem_cons_of_mem h',
calc f₁ a' h' = pi.cons s a b f₁ a' this : by rw [pi.cons_ne this ne.symm]
... = pi.cons s a b f₂ a' this : by rw [eq]
... = f₂ a' h' : by rw [pi.cons_ne this ne.symm]
lemma card_pi (m : multiset α) (t : Πa, multiset (δ a)) :
card (pi m t) = prod (m.map $ λa, card (t a)) :=
multiset.induction_on m (by simp) (by simp [mul_comm] {contextual := tt})
lemma nodup_pi {s : multiset α} {t : Πa, multiset (δ a)} :
nodup s → (∀a∈s, nodup (t a)) → nodup (pi s t) :=
multiset.induction_on s (assume _ _, nodup_singleton _)
begin
assume a s ih hs ht,
have has : a ∉ s, by simp at hs; exact hs.1,
have hs : nodup s, by simp at hs; exact hs.2,
simp,
split,
{ assume b hb,
from nodup_map (injective_pi_cons has) (ih hs $ assume a' h', ht a' $ mem_cons_of_mem h') },
{ apply pairwise_of_nodup _ (ht a $ mem_cons_self _ _),
from assume b₁ hb₁ b₂ hb₂ neb, disjoint_map_map.2 (assume f hf g hg eq,
have pi.cons s a b₁ f a (mem_cons_self _ _) = pi.cons s a b₂ g a (mem_cons_self _ _),
by rw [eq],
neb $ show b₁ = b₂, by rwa [pi.cons_same, pi.cons_same] at this) }
end
lemma mem_pi (m : multiset α) (t : Πa, multiset (δ a)) :
∀f:Πa∈m, δ a, (f ∈ pi m t) ↔ (∀a (h : a ∈ m), f a h ∈ t a) :=
begin
refine multiset.induction_on m (λ f, _) (λ a m ih f, _),
{ simpa using show f = pi.empty δ, by funext a ha; exact ha.elim },
simp, split,
{ rintro ⟨b, hb, f', hf', rfl⟩ a' ha',
rw [ih] at hf',
by_cases a' = a,
{ subst h, rwa [pi.cons_same] },
{ rw [pi.cons_ne _ h], apply hf' } },
{ intro hf,
refine ⟨_, hf a (mem_cons_self a _), λa ha, f a (mem_cons_of_mem ha),
(ih _).2 (λ a' h', hf _ _), _⟩,
funext a' h',
by_cases a' = a,
{ subst h, rw [pi.cons_same] },
{ rw [pi.cons_ne _ h] } }
end
end pi
end multiset
namespace multiset
instance : functor multiset :=
{ map := @map }
instance : is_lawful_functor multiset :=
by refine { .. }; intros; simp
open is_lawful_traversable is_comm_applicative
variables {F : Type u_1 → Type u_1} [applicative F] [is_comm_applicative F]
variables {α' β' : Type u_1} (f : α' → F β')
def traverse : multiset α' → F (multiset β') :=
quotient.lift (functor.map coe ∘ traversable.traverse f)
begin
introv p, unfold function.comp,
induction p,
case perm.nil { refl },
case perm.skip {
have : multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₁) =
multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₂),
{ rw [p_ih] },
simpa with functor_norm },
case perm.swap {
have : (λa b (l:list β'), (↑(a :: b :: l) : multiset β')) <$> f p_y <*> f p_x =
(λa b l, ↑(a :: b :: l)) <$> f p_x <*> f p_y,
{ rw [is_comm_applicative.commutative_map],
congr, funext a b l, simpa [flip] using perm.swap b a l },
simp [(∘), this] with functor_norm },
case perm.trans { simp [*] }
end
instance : monad multiset :=
{ pure := λ α x, x::0,
bind := @bind,
.. multiset.functor }
instance : is_lawful_monad multiset :=
{ bind_pure_comp_eq_map := λ α β f s, multiset.induction_on s rfl $ λ a s ih,
by rw [bind_cons, map_cons, bind_zero, add_zero],
pure_bind := λ α β x f, by simp only [cons_bind, zero_bind, add_zero],
bind_assoc := @bind_assoc }
open functor
open traversable is_lawful_traversable
@[simp]
lemma lift_beta {α β : Type*} (x : list α) (f : list α → β)
(h : ∀ a b : list α, a ≈ b → f a = f b) :
quotient.lift f h (x : multiset α) = f x :=
quotient.lift_beta _ _ _
@[simp]
lemma map_comp_coe {α β} (h : α → β) :
functor.map h ∘ coe = (coe ∘ functor.map h : list α → multiset β) :=
by funext; simp [functor.map]
lemma id_traverse {α : Type*} (x : multiset α) :
traverse id.mk x = x :=
quotient.induction_on x
(by { intro, rw [traverse,quotient.lift_beta,function.comp],
simp, congr })
lemma comp_traverse {G H : Type* → Type*}
[applicative G] [applicative H]
[is_comm_applicative G] [is_comm_applicative H]
{α β γ : Type*}
(g : α → G β) (h : β → H γ) (x : multiset α) :
traverse (comp.mk ∘ functor.map h ∘ g) x =
comp.mk (functor.map (traverse h) (traverse g x)) :=
quotient.induction_on x
(by intro;
simp [traverse,comp_traverse] with functor_norm;
simp [(<$>),(∘)] with functor_norm)
lemma map_traverse {G : Type* → Type*}
[applicative G] [is_comm_applicative G]
{α β γ : Type*}
(g : α → G β) (h : β → γ)
(x : multiset α) :
functor.map (functor.map h) (traverse g x) =
traverse (functor.map h ∘ g) x :=
quotient.induction_on x
(by intro; simp [traverse] with functor_norm;
rw [comp_map,map_traverse])
lemma traverse_map {G : Type* → Type*}
[applicative G] [is_comm_applicative G]
{α β γ : Type*}
(g : α → β) (h : β → G γ)
(x : multiset α) :
traverse h (map g x) =
traverse (h ∘ g) x :=
quotient.induction_on x
(by intro; simp [traverse];
rw [← traversable.traverse_map h g];
[ refl, apply_instance ])
lemma naturality {G H : Type* → Type*}
[applicative G] [applicative H]
[is_comm_applicative G] [is_comm_applicative H]
(eta : applicative_transformation G H)
{α β : Type*} (f : α → G β) (x : multiset α) :
eta (traverse f x) = traverse (@eta _ ∘ f) x :=
quotient.induction_on x
(by intro; simp [traverse,is_lawful_traversable.naturality] with functor_norm)
section choose
variables (p : α → Prop) [decidable_pred p] (l : multiset α)
def choose_x : Π hp : (∃! a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } :=
quotient.rec_on l (λ l' ex_unique, list.choose_x p l' (exists_of_exists_unique ex_unique)) begin
intros,
funext hp,
suffices all_equal : ∀ x y : { t // t ∈ b ∧ p t }, x = y,
{ apply all_equal },
{ rintros ⟨x, px⟩ ⟨y, py⟩,
rcases hp with ⟨z, ⟨z_mem_l, pz⟩, z_unique⟩,
congr,
calc x = z : z_unique x px
... = y : (z_unique y py).symm }
end
def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp
lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) :=
(choose_x p l hp).property
lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1
lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2
end choose
/- Ico -/
/-- `Ico n m` is the multiset lifted from the list `Ico n m`, e.g. the set `{n, n+1, ..., m-1}`. -/
def Ico (n m : ℕ) : multiset ℕ := Ico n m
namespace Ico
theorem map_add (n m k : ℕ) : (Ico n m).map ((+) k) = Ico (n + k) (m + k) :=
congr_arg coe $ list.Ico.map_add _ _ _
theorem map_sub (n m k : ℕ) (h : k ≤ n) : (Ico n m).map (λ x, x - k) = Ico (n - k) (m - k) :=
congr_arg coe $ list.Ico.map_sub _ _ _ h
theorem zero_bot (n : ℕ) : Ico 0 n = range n :=
congr_arg coe $ list.Ico.zero_bot _
@[simp] theorem card (n m : ℕ) : (Ico n m).card = m - n :=
list.Ico.length _ _
theorem nodup (n m : ℕ) : nodup (Ico n m) := Ico.nodup _ _
@[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m :=
list.Ico.mem
theorem eq_zero_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = 0 :=
congr_arg coe $ list.Ico.eq_nil_of_le h
@[simp] theorem self_eq_zero {n : ℕ} : Ico n n = 0 :=
eq_zero_of_le $ le_refl n
@[simp] theorem eq_zero_iff {n m : ℕ} : Ico n m = 0 ↔ m ≤ n :=
iff.trans (coe_eq_zero _) list.Ico.eq_empty_iff
lemma add_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) :
Ico n m + Ico m l = Ico n l :=
congr_arg coe $ list.Ico.append_consecutive hnm hml
@[simp] lemma inter_consecutive (n m l : ℕ) : Ico n m ∩ Ico m l = 0 :=
congr_arg coe $ list.Ico.bag_inter_consecutive n m l
@[simp] theorem succ_singleton {n : ℕ} : Ico n (n+1) = {n} :=
congr_arg coe $ list.Ico.succ_singleton
theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = m :: Ico n m :=
by rw [Ico, list.Ico.succ_top h, ← coe_add, add_comm]; refl
theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = n :: Ico (n + 1) m :=
congr_arg coe $ list.Ico.eq_cons h
@[simp] theorem pred_singleton {m : ℕ} (h : 0 < m) : Ico (m - 1) m = {m - 1} :=
congr_arg coe $ list.Ico.pred_singleton h
@[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m :=
list.Ico.not_mem_top
lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m :=
congr_arg coe $ list.Ico.filter_lt_of_top_le hml
lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = ∅ :=
congr_arg coe $ list.Ico.filter_lt_of_le_bot hln
lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l :=
congr_arg coe $ list.Ico.filter_lt_of_ge hlm
@[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) :=
congr_arg coe $ list.Ico.filter_lt n m l
lemma filter_le_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, l ≤ x) = Ico n m :=
congr_arg coe $ list.Ico.filter_le_of_le_bot hln
lemma filter_le_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, l ≤ x) = ∅ :=
congr_arg coe $ list.Ico.filter_le_of_top_le hml
lemma filter_le_of_le {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, l ≤ x) = Ico l m :=
congr_arg coe $ list.Ico.filter_le_of_le hnl
@[simp] lemma filter_le (n m l : ℕ) : (Ico n m).filter (λ x, l ≤ x) = Ico (max n l) m :=
congr_arg coe $ list.Ico.filter_le n m l
end Ico
variable (α)
def subsingleton_equiv [subsingleton α] : list α ≃ multiset α :=
{ to_fun := coe,
inv_fun := quot.lift id $ λ (a b : list α) (h : a ~ b),
list.ext_le (perm_length h) $ λ n h₁ h₂, subsingleton.elim _ _,
left_inv := λ l, rfl,
right_inv := λ m, quot.induction_on m $ λ l, rfl }
namespace nat
/-- The antidiagonal of a natural number `n` is
the multiset of pairs `(i,j)` such that `i+j = n`. -/
def antidiagonal (n : ℕ) : multiset (ℕ × ℕ) :=
list.nat.antidiagonal n
/-- A pair (i,j) is contained in the antidiagonal of `n` if and only if `i+j=n`. -/
@[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} :
x ∈ antidiagonal n ↔ x.1 + x.2 = n :=
by rw [antidiagonal, mem_coe, list.nat.mem_antidiagonal]
/-- The cardinality of the antidiagonal of `n` is `n+1`. -/
@[simp] lemma card_antidiagonal (n : ℕ) : (antidiagonal n).card = n+1 :=
by rw [antidiagonal, coe_card, list.nat.length_antidiagonal]
/-- The antidiagonal of `0` is the list `[(0,0)]` -/
@[simp] lemma antidiagonal_zero : antidiagonal 0 = {(0, 0)} :=
by { rw [antidiagonal, list.nat.antidiagonal_zero], refl }
/-- The antidiagonal of `n` does not contain duplicate entries. -/
lemma nodup_antidiagonal (n : ℕ) : nodup (antidiagonal n) :=
coe_nodup.2 $ list.nat.nodup_antidiagonal n
end nat
end multiset
|
6340c984d0b72e00fea64d667b13fe102550b529 | cf39355caa609c0f33405126beee2739aa3cb77e | /library/init/meta/default.lean | 92b6397ff246bb69dbcbb5cc75373eda86fc1aa3 | [
"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 | 1,113 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta.name init.meta.options init.meta.format init.meta.rb_map
import init.meta.level init.meta.expr init.meta.environment init.meta.attribute
import init.meta.tactic init.meta.contradiction_tactic init.meta.constructor_tactic
import init.meta.injection_tactic init.meta.relation_tactics init.meta.fun_info
import init.meta.congr_lemma init.meta.match_tactic init.meta.ac_tactics
import init.meta.backward init.meta.rewrite_tactic
import init.meta.derive init.meta.mk_dec_eq_instance
import init.meta.simp_tactic init.meta.set_get_option_tactics
import init.meta.interactive init.meta.converter init.meta.vm
import init.meta.comp_value_tactics init.meta.smt
import init.meta.async_tactic init.meta.ref
import init.meta.hole_command init.meta.congr_tactic
import init.meta.local_context init.meta.type_context
import init.meta.instance_cache
import init.meta.module_info
import init.meta.expr_address
import init.meta.tagged_format |
67ad55db07331a18b5e9d9e89d6f37463416fdf3 | e00ea76a720126cf9f6d732ad6216b5b824d20a7 | /src/tactic/omega/main.lean | 323d2e6a4276d9e95e930914a2267cd4a1a5ad3c | [
"Apache-2.0"
] | permissive | vaibhavkarve/mathlib | a574aaf68c0a431a47fa82ce0637f0f769826bfe | 17f8340912468f49bdc30acdb9a9fa02eeb0473a | refs/heads/master | 1,621,263,802,637 | 1,585,399,588,000 | 1,585,399,588,000 | 250,833,447 | 0 | 0 | Apache-2.0 | 1,585,410,341,000 | 1,585,410,341,000 | null | UTF-8 | Lean | false | false | 5,585 | lean | /- Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Seul Baek
A tactic for discharging linear integer & natural
number arithmetic goals using the Omega test. -/
import tactic.omega.int.main
import tactic.omega.nat.main
import tactic.doc_commands
namespace omega
open tactic
meta def select_domain (t s : tactic (option bool)) : tactic (option bool) :=
do a ← t, b ← s,
match a, b with
| a, none := return a
| none, b := return b
| (some tt), (some tt) := return (some tt)
| (some ff), (some ff) := return (some ff)
| _, _ := failed
end
meta def type_domain (x : expr) : tactic (option bool) :=
if x = `(int)
then return (some tt)
else if x = `(nat)
then return (some ff)
else failed
/-- Detects domain of a formula from its expr.
* Returns none, if domain can be either ℤ or ℕ
* Returns some tt, if domain is exclusively ℤ
* Returns some ff, if domain is exclusively ℕ
* Fails, if domain is neither ℤ nor ℕ -/
meta def form_domain : expr → tactic (option bool)
| `(¬ %%px) := form_domain px
| `(%%px ∨ %%qx) := select_domain (form_domain px) (form_domain qx)
| `(%%px ∧ %%qx) := select_domain (form_domain px) (form_domain qx)
| `(%%px ↔ %%qx) := select_domain (form_domain px) (form_domain qx)
| `(%%(expr.pi _ _ px qx)) :=
monad.cond
(if expr.has_var px then return tt else is_prop px)
(select_domain (form_domain px) (form_domain qx))
(select_domain (type_domain px) (form_domain qx))
| `(@has_lt.lt %%dx %%h _ _) := type_domain dx
| `(@has_le.le %%dx %%h _ _) := type_domain dx
| `(@eq %%dx _ _) := type_domain dx
| `(@ge %%dx %%h _ _) := type_domain dx
| `(@gt %%dx %%h _ _) := type_domain dx
| `(@ne %%dx _ _) := type_domain dx
| `(true) := return none
| `(false) := return none
| x := failed
meta def goal_domain_aux (x : expr) : tactic bool :=
(omega.int.wff x >> return tt) <|> (omega.nat.wff x >> return ff)
/-- Use the current goal to determine.
Return tt if the domain is ℤ, and return ff if it is ℕ -/
meta def goal_domain : tactic bool :=
do gx ← target,
hxs ← local_context >>= monad.mapm infer_type,
app_first goal_domain_aux (gx::hxs)
/-- Return tt if the domain is ℤ, and return ff if it is ℕ -/
meta def determine_domain (opt : list name) : tactic bool :=
if `int ∈ opt
then return tt
else if `nat ∈ opt
then return ff
else goal_domain
end omega
open lean.parser interactive omega
/-- Attempts to discharge goals in the quantifier-free fragment of
linear integer and natural number arithmetic using the Omega test.
Guesses the correct domain by looking at the goal and hypotheses,
and then reverts all relevant hypotheses and variables.
Use `omega manual` to disable automatic reverts, and `omega int` or
`omega nat` to specify the domain.
---
`omega` attempts to discharge goals in the quantifier-free fragment of linear integer and natural number arithmetic using the Omega test. In other words, the core procedure of `omega` works with goals of the form
```lean
∀ x₁, ... ∀ xₖ, P
```
where `x₁, ... xₖ` are integer (resp. natural number) variables, and `P` is a quantifier-free formula of linear integer (resp. natural number) arithmetic. For instance:
```lean
example : ∀ (x y : int), (x ≤ 5 ∧ y ≤ 3) → x + y ≤ 8 := by omega
```
By default, `omega` tries to guess the correct domain by looking at the goal and hypotheses, and then reverts all relevant hypotheses and variables (e.g., all variables of type `nat` and `Prop`s in linear natural number arithmetic, if the domain was determined to be `nat`) to universally close the goal before calling the main procedure. Therefore, `omega` will often work even if the goal is not in the above form:
```lean
example (x y : nat) (h : 2 * x + 1 = 2 * y) : false := by omega
```
But this behaviour is not always optimal, since it may revert irrelevant hypotheses or incorrectly guess the domain. Use `omega manual` to disable automatic reverts, and `omega int` or `omega nat` to specify the domain.
```lean
example (x y z w : int) (h1 : 3 * y ≥ x) (h2 : z > 19 * w) : 3 * x ≤ 9 * y :=
by {revert h1 x y, omega manual}
example (i : int) (n : nat) (h1 : i = 0) (h2 : n < n) : false := by omega nat
example (n : nat) (h1 : n < 34) (i : int) (h2 : i * 9 = -72) : i = -8 :=
by {revert h2 i, omega manual int}
```
`omega` handles `nat` subtraction by repeatedly rewriting goals of the form `P[t-s]` into `P[x] ∧ (t = s + x ∨ (t ≤ s ∧ x = 0))`, where `x` is fresh. This means that each (distinct) occurrence of subtraction will cause the goal size to double during DNF transformation.
`omega` implements the real shadow step of the Omega test, but not the dark and gray shadows. Therefore, it should (in principle) succeed whenever the negation of the goal has no real solution, but it may fail if a real solution exists, even if there is no integer/natural number solution.
-/
meta def tactic.interactive.omega (opt : parse (many ident)) : tactic unit :=
do is_int ← determine_domain opt,
let is_manual : bool := if `manual ∈ opt then tt else ff,
if is_int
then omega_int is_manual
else omega_nat is_manual
add_hint_tactic "omega"
add_tactic_doc
{ name := "omega",
category := doc_category.tactic,
decl_names := [`tactic.interactive.omega],
tags := ["finishing", "arithmetic", "decision procedure"] }
|
e9e639c8e9497833fdeff329c048318630c7a9b0 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/topology/sheaves/presheaf_of_functions.lean | 216bb9f08f765d2d6b04b0860f0c7fd417bcf754 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 5,742 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.yoneda
import topology.sheaves.presheaf
import topology.category.TopCommRing
import topology.continuous_function.algebra
/-!
# Presheaves of functions
We construct some simple examples of presheaves of functions on a topological space.
* `presheaf_to_Types X T`, where `T : X → Type`,
is the presheaf of dependently-typed (not-necessarily continuous) functions
* `presheaf_to_Type X T`, where `T : Type`,
is the presheaf of (not-necessarily-continuous) functions to a fixed target type `T`
* `presheaf_to_Top X T`, where `T : Top`,
is the presheaf of continuous functions into a topological space `T`
* `presheaf_To_TopCommRing X R`, where `R : TopCommRing`
is the presheaf valued in `CommRing` of functions functions into a topological ring `R`
* as an example of the previous construction,
`presheaf_to_TopCommRing X (TopCommRing.of ℂ)`
is the presheaf of rings of continuous complex-valued functions on `X`.
-/
universes v u
open category_theory
open topological_space
open opposite
namespace Top
variables (X : Top.{v})
/--
The presheaf of dependently typed functions on `X`, with fibres given by a type family `T`.
There is no requirement that the functions are continuous, here.
-/
def presheaf_to_Types (T : X → Type v) : X.presheaf (Type v) :=
{ obj := λ U, Π x : (unop U), T x,
map := λ U V i g, λ (x : unop V), g (i.unop x),
map_id' := λ U, by { ext g ⟨x, hx⟩, refl },
map_comp' := λ U V W i j, rfl }
@[simp] lemma presheaf_to_Types_obj
{T : X → Type v} {U : (opens X)ᵒᵖ} :
(presheaf_to_Types X T).obj U = Π x : (unop U), T x :=
rfl
@[simp] lemma presheaf_to_Types_map
{T : X → Type v} {U V : (opens X)ᵒᵖ} {i : U ⟶ V} {f} :
(presheaf_to_Types X T).map i f = λ x, f (i.unop x) :=
rfl
/--
The presheaf of functions on `X` with values in a type `T`.
There is no requirement that the functions are continuous, here.
-/
-- We don't just define this in terms of `presheaf_to_Types`,
-- as it's helpful later to see (at a syntactic level) that `(presheaf_to_Type X T).obj U`
-- is a non-dependent function.
-- We don't use `@[simps]` to generate the projection lemmas here,
-- as it turns out to be useful to have `presheaf_to_Type_map`
-- written as an equality of functions (rather than being applied to some argument).
def presheaf_to_Type (T : Type v) : X.presheaf (Type v) :=
{ obj := λ U, (unop U) → T,
map := λ U V i g, g ∘ i.unop,
map_id' := λ U, by { ext g ⟨x, hx⟩, refl },
map_comp' := λ U V W i j, rfl }
@[simp] lemma presheaf_to_Type_obj
{T : Type v} {U : (opens X)ᵒᵖ} :
(presheaf_to_Type X T).obj U = ((unop U) → T) :=
rfl
@[simp] lemma presheaf_to_Type_map
{T : Type v} {U V : (opens X)ᵒᵖ} {i : U ⟶ V} {f} :
(presheaf_to_Type X T).map i f = f ∘ i.unop :=
rfl
/-- The presheaf of continuous functions on `X` with values in fixed target topological space
`T`. -/
def presheaf_to_Top (T : Top.{v}) : X.presheaf (Type v) :=
(opens.to_Top X).op ⋙ (yoneda.obj T)
@[simp] lemma presheaf_to_Top_obj (T : Top.{v}) (U : (opens X)ᵒᵖ) :
(presheaf_to_Top X T).obj U = ((opens.to_Top X).obj (unop U) ⟶ T) :=
rfl
/-- The (bundled) commutative ring of continuous functions from a topological space
to a topological commutative ring, with pointwise multiplication. -/
-- TODO upgrade the result to TopCommRing?
def continuous_functions (X : Top.{v}ᵒᵖ) (R : TopCommRing.{v}) : CommRing.{v} :=
CommRing.of (unop X ⟶ (forget₂ TopCommRing Top).obj R)
namespace continuous_functions
/-- Pulling back functions into a topological ring along a continuous map is a ring homomorphism. -/
def pullback {X Y : Topᵒᵖ} (f : X ⟶ Y) (R : TopCommRing) :
continuous_functions X R ⟶ continuous_functions Y R :=
{ to_fun := λ g, f.unop ≫ g,
map_one' := rfl,
map_zero' := rfl,
map_add' := by tidy,
map_mul' := by tidy }
/-- A homomorphism of topological rings can be postcomposed with functions from a source space `X`;
this is a ring homomorphism (with respect to the pointwise ring operations on functions). -/
def map (X : Top.{u}ᵒᵖ) {R S : TopCommRing.{u}} (φ : R ⟶ S) :
continuous_functions X R ⟶ continuous_functions X S :=
{ to_fun := λ g, g ≫ ((forget₂ TopCommRing Top).map φ),
map_one' := by ext; exact φ.1.map_one,
map_zero' := by ext; exact φ.1.map_zero,
map_add' := by intros; ext; apply φ.1.map_add,
map_mul' := by intros; ext; apply φ.1.map_mul }
end continuous_functions
/-- An upgraded version of the Yoneda embedding, observing that the continuous maps
from `X : Top` to `R : TopCommRing` form a commutative ring, functorial in both `X` and `R`. -/
def CommRing_yoneda : TopCommRing.{u} ⥤ (Top.{u}ᵒᵖ ⥤ CommRing.{u}) :=
{ obj := λ R,
{ obj := λ X, continuous_functions X R,
map := λ X Y f, continuous_functions.pullback f R,
map_id' := λ X, by { ext, refl },
map_comp' := λ X Y Z f g, rfl },
map := λ R S φ,
{ app := λ X, continuous_functions.map X φ,
naturality' := λ X Y f, rfl },
map_id' := λ X, by { ext, refl },
map_comp' := λ X Y Z f g, rfl }
/--
The presheaf (of commutative rings), consisting of functions on an open set `U ⊆ X` with
values in some topological commutative ring `T`.
For example, we could construct the presheaf of continuous complex valued functions of `X` as
```
presheaf_to_TopCommRing X (TopCommRing.of ℂ)
```
(this requires `import topology.instances.complex`).
-/
def presheaf_to_TopCommRing (T : TopCommRing.{v}) :
X.presheaf CommRing.{v} :=
(opens.to_Top X).op ⋙ (CommRing_yoneda.obj T)
end Top
|
d9629be16f265fa3e83153b52df15b2e103c2dfd | 02fbe05a45fda5abde7583464416db4366eedfbf | /library/init/control/monad_fail.lean | 4a9ac5bd98db7fd3cc0d17be846d445e82d56b29 | [
"Apache-2.0"
] | permissive | jasonrute/lean | cc12807e11f9ac6b01b8951a8bfb9c2eb35a0154 | 4be962c167ca442a0ec5e84472d7ff9f5302788f | refs/heads/master | 1,672,036,664,637 | 1,601,642,826,000 | 1,601,642,826,000 | 260,777,966 | 0 | 0 | Apache-2.0 | 1,588,454,819,000 | 1,588,454,818,000 | null | UTF-8 | Lean | false | false | 599 | 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.control.lift init.data.string.basic
universes u v
class monad_fail (m : Type u → Type v) :=
(fail : Π {a}, string → m a)
def match_failed {α : Type u} {m : Type u → Type v} [monad_fail m] : m α :=
monad_fail.fail "match failed"
instance monad_fail_lift (m n : Type u → Type v) [monad n] [monad_fail m] [has_monad_lift m n] : monad_fail n :=
{ fail := λ α s, monad_lift (monad_fail.fail s : m α) }
|
97cdadaa9f1f612761816c6606c06520c61d07bf | d1a52c3f208fa42c41df8278c3d280f075eb020c | /tests/lean/run/Reparen.lean | 2098c8499ee8cb809f2edf9194adc9fe6745ddc7 | [
"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 | 2,156 | lean | import Lean.Parser
/-! Reprint file after removing all parentheses and then passing it through the parenthesizer -/
open Lean
open Std.Format open Std
def unparenAux (parens body : Syntax) : Syntax :=
match parens.getHeadInfo, body.getHeadInfo, body.getTailInfo, parens.getTailInfo with
| SourceInfo.original lead _ _ _, SourceInfo.original _ pos trail pos',
SourceInfo.original endLead endPos _ endPos', SourceInfo.original _ _ endTrail _ =>
body.setHeadInfo (SourceInfo.original lead pos trail pos') |>.setTailInfo (SourceInfo.original endLead endPos endTrail endPos')
| _, _, _, _ => body
partial def unparen : Syntax → Syntax
-- don't remove parentheses in syntax quotations, they might be semantically significant
| stx => if stx.isOfKind `Lean.Parser.Term.stxQuot then stx
else match stx with
| `(($stx')) => unparenAux stx $ unparen stx'
| `(level|($stx')) => unparenAux stx $ unparen stx'
| _ => stx.modifyArgs $ Array.map unparen
unsafe def main (args : List String) : IO Unit := do
let (debug, f) : Bool × String := match args with
| [f, "-d"] => (true, f)
| [f] => (false, f)
| _ => panic! "usage: file [-d]";
let env ← mkEmptyEnvironment;
let stx ← Lean.Parser.testParseFile env args.head!;
let header := stx.getArg 0;
let some s ← pure header.reprint | throw $ IO.userError "header reprint failed";
IO.print s;
let cmds := (stx.getArg 1).getArgs;
cmds.forM $ fun cmd => do
let cmd := unparen cmd;
let (cmd, _) ← (tryFinally (PrettyPrinter.parenthesizeCommand cmd) printTraces).toIO { options := Options.empty.setBool `trace.PrettyPrinter.parenthesize debug } { env := env };
let some s ← pure cmd.reprint | throw $ IO.userError "cmd reprint failed";
IO.print s
#eval main ["../../../src/Init/Prelude.lean"]
def check (stx : Syntax) : CoreM Unit := do
let stx' := unparen stx;
let stx' ← PrettyPrinter.parenthesizeTerm stx';
let f ← PrettyPrinter.formatTerm stx';
IO.println f;
if (stx != stx') then
throwError "reparenthesization failed"
open Lean
syntax:80 term " ^~ " term:80 : term
syntax:70 term " *~ " term:71 : term
#eval check $ Unhygienic.run `(((1 + 2) *~ 3) ^~ 4)
|
5921376a9c4d346d5b390151f068086fe98e7961 | 4f643cce24b2d005aeeb5004c2316a8d6cc7f3b1 | /omin/def_choice/order.lean | 35a5dd9a40e5d206f7674b6eb5631f9b1074c0fb | [] | no_license | rwbarton/lean-omin | da209ed061d64db65a8f7f71f198064986f30eb9 | fd733c6d95ef6f4743aae97de5e15df79877c00e | refs/heads/master | 1,674,408,673,325 | 1,607,343,535,000 | 1,607,343,535,000 | 285,150,399 | 9 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 701 | lean | import o_minimal.sheaf.yoneda
import o_minimal.order
namespace o_minimal
variables {R : Type*} [preorder R] {S : struc R} [is_definable_le S R]
lemma definable_Ioo : definable S (set.Ioo : R → R → set R) :=
begin [defin]
intro a,
intro b,
intro x,
app, app, exact definable.and.definable _,
{ app, app, exact (definable_iff_def_rel₂.mpr definable_lt').definable _,
var, var },
{ app, app, exact (definable_iff_def_rel₂.mpr definable_lt').definable _,
var, var }
end
lemma definable_Iio : definable S (set.Iio : R → set R) :=
begin [defin]
intro b,
intro x,
app, app, exact (definable_iff_def_rel₂.mpr definable_lt').definable _,
var, var
end
end o_minimal
|
eb14a0e306f7c5259c7609ed10f0e539926b29d9 | 80746c6dba6a866de5431094bf9f8f841b043d77 | /src/order/lattice.lean | 692acad2d0e39c47c258b7be801c59a6dda39ef5 | [
"Apache-2.0"
] | permissive | leanprover-fork/mathlib-backup | 8b5c95c535b148fca858f7e8db75a76252e32987 | 0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0 | refs/heads/master | 1,585,156,056,139 | 1,548,864,430,000 | 1,548,864,438,000 | 143,964,213 | 0 | 0 | Apache-2.0 | 1,550,795,966,000 | 1,533,705,322,000 | Lean | UTF-8 | Lean | false | false | 14,775 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
Defines the inf/sup (semi)-lattice with optionally top/bot type class hierarchy.
-/
import order.basic
set_option old_structure_cmd true
universes u v w
-- TODO: move this eventually, if we decide to use them
attribute [ematch] le_trans lt_of_le_of_lt lt_of_lt_of_le lt_trans
section
variable {α : Type u}
-- TODO: this seems crazy, but it also seems to work reasonably well
@[ematch] theorem le_antisymm' [partial_order α] : ∀ {a b : α}, (: a ≤ b :) → b ≤ a → a = b :=
@le_antisymm _ _
end
/- TODO: automatic construction of dual definitions / theorems -/
namespace lattice
reserve infixl ` ⊓ `:70
reserve infixl ` ⊔ `:65
/-- Typeclass for the `⊔` (`\lub`) notation -/
class has_sup (α : Type u) := (sup : α → α → α)
/-- Typeclass for the `⊓` (`\glb`) notation -/
class has_inf (α : Type u) := (inf : α → α → α)
infix ⊔ := has_sup.sup
infix ⊓ := has_inf.inf
/-- A `semilattice_sup` is a join-semilattice, that is, a partial order
with a join (a.k.a. lub / least upper bound, sup / supremum) operation
`⊔` which is the least element larger than both factors. -/
class semilattice_sup (α : Type u) extends has_sup α, partial_order α :=
(le_sup_left : ∀ a b : α, a ≤ a ⊔ b)
(le_sup_right : ∀ a b : α, b ≤ a ⊔ b)
(sup_le : ∀ a b c : α, a ≤ c → b ≤ c → a ⊔ b ≤ c)
section semilattice_sup
variables {α : Type u} [semilattice_sup α] {a b c d : α}
@[simp] theorem le_sup_left : a ≤ a ⊔ b :=
semilattice_sup.le_sup_left a b
@[ematch] theorem le_sup_left' : a ≤ (: a ⊔ b :) :=
semilattice_sup.le_sup_left a b
@[simp] theorem le_sup_right : b ≤ a ⊔ b :=
semilattice_sup.le_sup_right a b
@[ematch] theorem le_sup_right' : b ≤ (: a ⊔ b :) :=
semilattice_sup.le_sup_right a b
theorem le_sup_left_of_le (h : c ≤ a) : c ≤ a ⊔ b :=
by finish
theorem le_sup_right_of_le (h : c ≤ b) : c ≤ a ⊔ b :=
by finish
theorem sup_le : a ≤ c → b ≤ c → a ⊔ b ≤ c :=
semilattice_sup.sup_le a b c
@[simp] theorem sup_le_iff : a ⊔ b ≤ c ↔ a ≤ c ∧ b ≤ c :=
⟨assume h : a ⊔ b ≤ c, ⟨le_trans le_sup_left h, le_trans le_sup_right h⟩,
assume ⟨h₁, h₂⟩, sup_le h₁ h₂⟩
-- TODO: if we just write le_antisymm, Lean doesn't know which ≤ we want to use
-- Can we do anything about that?
theorem sup_of_le_left (h : b ≤ a) : a ⊔ b = a :=
by apply le_antisymm; finish
theorem sup_of_le_right (h : a ≤ b) : a ⊔ b = b :=
by apply le_antisymm; finish
theorem sup_le_sup (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊔ c ≤ b ⊔ d :=
by finish
theorem sup_le_sup_left (h₁ : a ≤ b) (c) : c ⊔ a ≤ c ⊔ b :=
by finish
theorem sup_le_sup_right (h₁ : a ≤ b) (c) : a ⊔ c ≤ b ⊔ c :=
by finish
theorem le_of_sup_eq (h : a ⊔ b = b) : a ≤ b :=
by finish
@[simp] lemma sup_lt_iff [is_total α (≤)] {a b c : α} : b ⊔ c < a ↔ b < a ∧ c < a :=
begin
cases (is_total.total (≤) b c) with h,
{ simp [sup_of_le_right h], exact ⟨λI, ⟨lt_of_le_of_lt h I, I⟩, λH, H.2⟩ },
{ simp [sup_of_le_left h], exact ⟨λI, ⟨I, lt_of_le_of_lt h I⟩, λH, H.1⟩ }
end
@[simp] theorem sup_idem : a ⊔ a = a :=
by apply le_antisymm; finish
instance sup_is_idempotent : is_idempotent α (⊔) := ⟨@sup_idem _ _⟩
theorem sup_comm : a ⊔ b = b ⊔ a :=
by apply le_antisymm; finish
instance sup_is_commutative : is_commutative α (⊔) := ⟨@sup_comm _ _⟩
theorem sup_assoc : a ⊔ b ⊔ c = a ⊔ (b ⊔ c) :=
by apply le_antisymm; finish
instance sup_is_associative : is_associative α (⊔) := ⟨@sup_assoc _ _⟩
lemma forall_le_or_exists_lt_sup (a : α) : (∀b, b ≤ a) ∨ (∃b, a < b) :=
suffices (∃b, ¬b ≤ a) → (∃b, a < b),
by rwa [classical.or_iff_not_imp_left, classical.not_forall],
assume ⟨b, hb⟩,
have a ≠ a ⊔ b, from assume eq, hb $ eq.symm ▸ le_sup_right,
⟨a ⊔ b, lt_of_le_of_ne le_sup_left ‹a ≠ a ⊔ b›⟩
theorem semilattice_sup.ext_sup {α} {A B : semilattice_sup α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y)
(x y : α) : (by haveI := A; exact (x ⊔ y)) = x ⊔ y :=
eq_of_forall_ge_iff $ λ c,
by simp only [sup_le_iff]; rw [← H, @sup_le_iff α A, H, H]
theorem semilattice_sup.ext {α} {A B : semilattice_sup α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
haveI this := partial_order.ext H,
have ss := funext (λ x, funext $ semilattice_sup.ext_sup H x),
cases A; cases B; injection this; congr'
end
end semilattice_sup
/-- A `semilattice_inf` is a meet-semilattice, that is, a partial order
with a meet (a.k.a. glb / greatest lower bound, inf / infimum) operation
`⊓` which is the greatest element smaller than both factors. -/
class semilattice_inf (α : Type u) extends has_inf α, partial_order α :=
(inf_le_left : ∀ a b : α, a ⊓ b ≤ a)
(inf_le_right : ∀ a b : α, a ⊓ b ≤ b)
(le_inf : ∀ a b c : α, a ≤ b → a ≤ c → a ≤ b ⊓ c)
section semilattice_inf
variables {α : Type u} [semilattice_inf α] {a b c d : α}
@[simp] theorem inf_le_left : a ⊓ b ≤ a :=
semilattice_inf.inf_le_left a b
@[ematch] theorem inf_le_left' : (: a ⊓ b :) ≤ a :=
semilattice_inf.inf_le_left a b
@[simp] theorem inf_le_right : a ⊓ b ≤ b :=
semilattice_inf.inf_le_right a b
@[ematch] theorem inf_le_right' : (: a ⊓ b :) ≤ b :=
semilattice_inf.inf_le_right a b
theorem le_inf : a ≤ b → a ≤ c → a ≤ b ⊓ c :=
semilattice_inf.le_inf a b c
theorem inf_le_left_of_le (h : a ≤ c) : a ⊓ b ≤ c :=
le_trans inf_le_left h
theorem inf_le_right_of_le (h : b ≤ c) : a ⊓ b ≤ c :=
le_trans inf_le_right h
@[simp] theorem le_inf_iff : a ≤ b ⊓ c ↔ a ≤ b ∧ a ≤ c :=
⟨assume h : a ≤ b ⊓ c, ⟨le_trans h inf_le_left, le_trans h inf_le_right⟩,
assume ⟨h₁, h₂⟩, le_inf h₁ h₂⟩
theorem inf_of_le_left (h : a ≤ b) : a ⊓ b = a :=
by apply le_antisymm; finish
theorem inf_of_le_right (h : b ≤ a) : a ⊓ b = b :=
by apply le_antisymm; finish
theorem inf_le_inf (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊓ c ≤ b ⊓ d :=
by finish
theorem le_of_inf_eq (h : a ⊓ b = a) : a ≤ b :=
by finish
@[simp] lemma lt_inf_iff [is_total α (≤)] {a b c : α} : a < b ⊓ c ↔ a < b ∧ a < c :=
begin
cases (is_total.total (≤) b c) with h,
{ simp [inf_of_le_left h], exact ⟨λI, ⟨I, lt_of_lt_of_le I h⟩, λH, H.1⟩ },
{ simp [inf_of_le_right h], exact ⟨λI, ⟨lt_of_lt_of_le I h, I⟩, λH, H.2⟩ }
end
@[simp] theorem inf_idem : a ⊓ a = a :=
by apply le_antisymm; finish
instance inf_is_idempotent : is_idempotent α (⊓) := ⟨@inf_idem _ _⟩
theorem inf_comm : a ⊓ b = b ⊓ a :=
by apply le_antisymm; finish
instance inf_is_commutative : is_commutative α (⊓) := ⟨@inf_comm _ _⟩
theorem inf_assoc : a ⊓ b ⊓ c = a ⊓ (b ⊓ c) :=
by apply le_antisymm; finish
instance inf_is_associative : is_associative α (⊓) := ⟨@inf_assoc _ _⟩
lemma forall_le_or_exists_lt_inf (a : α) : (∀b, a ≤ b) ∨ (∃b, b < a) :=
suffices (∃b, ¬a ≤ b) → (∃b, b < a),
by rwa [classical.or_iff_not_imp_left, classical.not_forall],
assume ⟨b, hb⟩,
have a ⊓ b ≠ a, from assume eq, hb $ eq ▸ inf_le_right,
⟨a ⊓ b, lt_of_le_of_ne inf_le_left ‹a ⊓ b ≠ a›⟩
theorem semilattice_inf.ext_inf {α} {A B : semilattice_inf α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y)
(x y : α) : (by haveI := A; exact (x ⊓ y)) = x ⊓ y :=
eq_of_forall_le_iff $ λ c,
by simp only [le_inf_iff]; rw [← H, @le_inf_iff α A, H, H]
theorem semilattice_inf.ext {α} {A B : semilattice_inf α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
haveI this := partial_order.ext H,
have ss := funext (λ x, funext $ semilattice_inf.ext_inf H x),
cases A; cases B; injection this; congr'
end
end semilattice_inf
/- Lattices -/
/-- A lattice is a join-semilattice which is also a meet-semilattice. -/
class lattice (α : Type u) extends semilattice_sup α, semilattice_inf α
section lattice
variables {α : Type u} [lattice α] {a b c d : α}
/- Distributivity laws -/
/- TODO: better names? -/
theorem sup_inf_le : a ⊔ (b ⊓ c) ≤ (a ⊔ b) ⊓ (a ⊔ c) :=
by finish
theorem le_inf_sup : (a ⊓ b) ⊔ (a ⊓ c) ≤ a ⊓ (b ⊔ c) :=
by finish
theorem inf_sup_self : a ⊓ (a ⊔ b) = a :=
le_antisymm (by finish) (by finish)
theorem sup_inf_self : a ⊔ (a ⊓ b) = a :=
le_antisymm (by finish) (by finish)
theorem lattice.ext {α} {A B : lattice α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have SS : @lattice.to_semilattice_sup α A =
@lattice.to_semilattice_sup α B := semilattice_sup.ext H,
have II := semilattice_inf.ext H,
resetI, cases A; cases B; injection SS; injection II; congr'
end
end lattice
variables {α : Type u} {x y z w : α}
/-- A distributive lattice is a lattice that satisfies any of four
equivalent distribution properties (of sup over inf or inf over sup,
on the left or right). A classic example of a distributive lattice
is the lattice of subsets of a set, and in fact this example is
generic in the sense that every distributive lattice is realizable
as a sublattice of a powerset lattice. -/
class distrib_lattice α extends lattice α :=
(le_sup_inf : ∀x y z : α, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z))
section distrib_lattice
variables [distrib_lattice α]
theorem le_sup_inf : ∀{x y z : α}, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z) :=
distrib_lattice.le_sup_inf
theorem sup_inf_left : x ⊔ (y ⊓ z) = (x ⊔ y) ⊓ (x ⊔ z) :=
le_antisymm sup_inf_le le_sup_inf
theorem sup_inf_right : (y ⊓ z) ⊔ x = (y ⊔ x) ⊓ (z ⊔ x) :=
by simp only [sup_inf_left, λy:α, @sup_comm α _ y x, eq_self_iff_true]
theorem inf_sup_left : x ⊓ (y ⊔ z) = (x ⊓ y) ⊔ (x ⊓ z) :=
calc x ⊓ (y ⊔ z) = (x ⊓ (x ⊔ z)) ⊓ (y ⊔ z) : by rw [inf_sup_self]
... = x ⊓ ((x ⊓ y) ⊔ z) : by simp only [inf_assoc, sup_inf_right, eq_self_iff_true]
... = (x ⊔ (x ⊓ y)) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_inf_self]
... = ((x ⊓ y) ⊔ x) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_comm]
... = (x ⊓ y) ⊔ (x ⊓ z) : by rw [sup_inf_left]
theorem inf_sup_right : (y ⊔ z) ⊓ x = (y ⊓ x) ⊔ (z ⊓ x) :=
by simp only [inf_sup_left, λy:α, @inf_comm α _ y x, eq_self_iff_true]
lemma eq_of_sup_eq_inf_eq {α : Type u} [distrib_lattice α] {a b c : α}
(h₁ : b ⊓ a = c ⊓ a) (h₂ : b ⊔ a = c ⊔ a) : b = c :=
le_antisymm
(calc b ≤ (c ⊓ a) ⊔ b : le_sup_right
... = (c ⊔ b) ⊓ (a ⊔ b) : sup_inf_right
... = c ⊔ (c ⊓ a) : by rw [←h₁, sup_inf_left, ←h₂]; simp only [sup_comm, eq_self_iff_true]
... = c : sup_inf_self)
(calc c ≤ (b ⊓ a) ⊔ c : le_sup_right
... = (b ⊔ c) ⊓ (a ⊔ c) : sup_inf_right
... = b ⊔ (b ⊓ a) : by rw [h₁, sup_inf_left, h₂]; simp only [sup_comm, eq_self_iff_true]
... = b : sup_inf_self)
end distrib_lattice
/- Lattices derived from linear orders -/
instance lattice_of_decidable_linear_order {α : Type u} [o : decidable_linear_order α] : lattice α :=
{ sup := max,
le_sup_left := le_max_left,
le_sup_right := le_max_right,
sup_le := assume a b c, max_le,
inf := min,
inf_le_left := min_le_left,
inf_le_right := min_le_right,
le_inf := assume a b c, le_min,
..o }
theorem sup_eq_max [decidable_linear_order α] : x ⊔ y = max x y := rfl
theorem inf_eq_min [decidable_linear_order α] : x ⊓ y = min x y := rfl
instance distrib_lattice_of_decidable_linear_order {α : Type u} [o : decidable_linear_order α] : distrib_lattice α :=
{ le_sup_inf := assume a b c,
match le_total b c with
| or.inl h := inf_le_left_of_le $ sup_le_sup_left (le_inf (le_refl b) h) _
| or.inr h := inf_le_right_of_le $ sup_le_sup_left (le_inf h (le_refl c)) _
end,
..lattice.lattice_of_decidable_linear_order }
instance nat.distrib_lattice : distrib_lattice ℕ :=
by apply_instance
end lattice
namespace order_dual
open lattice
variable (α : Type*)
instance [has_inf α] : has_sup (order_dual α) := ⟨((⊓) : α → α → α)⟩
instance [has_sup α] : has_inf (order_dual α) := ⟨((⊔) : α → α → α)⟩
instance [semilattice_inf α] : semilattice_sup (order_dual α) :=
{ le_sup_left := @inf_le_left α _,
le_sup_right := @inf_le_right α _,
sup_le := assume a b c hca hcb, @le_inf α _ _ _ _ hca hcb,
.. order_dual.partial_order α, .. order_dual.lattice.has_sup α }
instance [semilattice_sup α] : semilattice_inf (order_dual α) :=
{ inf_le_left := @le_sup_left α _,
inf_le_right := @le_sup_right α _,
le_inf := assume a b c hca hcb, @sup_le α _ _ _ _ hca hcb,
.. order_dual.partial_order α, .. order_dual.lattice.has_inf α }
instance [lattice α] : lattice (order_dual α) :=
{ .. order_dual.lattice.semilattice_sup α, .. order_dual.lattice.semilattice_inf α }
instance [distrib_lattice α] : distrib_lattice (order_dual α) :=
{ le_sup_inf := assume x y z, le_of_eq inf_sup_left.symm,
.. order_dual.lattice.lattice α }
end order_dual
namespace prod
open lattice
variables (α : Type u) (β : Type v)
instance [has_sup α] [has_sup β] : has_sup (α × β) := ⟨λp q, ⟨p.1 ⊔ q.1, p.2 ⊔ q.2⟩⟩
instance [has_inf α] [has_inf β] : has_inf (α × β) := ⟨λp q, ⟨p.1 ⊓ q.1, p.2 ⊓ q.2⟩⟩
instance [semilattice_sup α] [semilattice_sup β] : semilattice_sup (α × β) :=
{ sup_le := assume a b c h₁ h₂, ⟨sup_le h₁.1 h₂.1, sup_le h₁.2 h₂.2⟩,
le_sup_left := assume a b, ⟨le_sup_left, le_sup_left⟩,
le_sup_right := assume a b, ⟨le_sup_right, le_sup_right⟩,
.. prod.partial_order α β, .. prod.lattice.has_sup α β }
instance [semilattice_inf α] [semilattice_inf β] : semilattice_inf (α × β) :=
{ le_inf := assume a b c h₁ h₂, ⟨le_inf h₁.1 h₂.1, le_inf h₁.2 h₂.2⟩,
inf_le_left := assume a b, ⟨inf_le_left, inf_le_left⟩,
inf_le_right := assume a b, ⟨inf_le_right, inf_le_right⟩,
.. prod.partial_order α β, .. prod.lattice.has_inf α β }
instance [lattice α] [lattice β] : lattice (α × β) :=
{ .. prod.lattice.semilattice_inf α β, .. prod.lattice.semilattice_sup α β }
instance [distrib_lattice α] [distrib_lattice β] : distrib_lattice (α × β) :=
{ le_sup_inf := assume a b c, ⟨le_sup_inf, le_sup_inf⟩,
.. prod.lattice.lattice α β }
end prod
|
8585b3315601f7df59aba2a95667fce88458da22 | 36938939954e91f23dec66a02728db08a7acfcf9 | /lean4/tests/Hex.lean | 19025dd7f0222987fd06f348bdc8612502a5b494 | [] | no_license | pnwamk/reopt-vcg | f8b56dd0279392a5e1c6aee721be8138e6b558d3 | c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d | refs/heads/master | 1,631,145,017,772 | 1,593,549,019,000 | 1,593,549,143,000 | 254,191,418 | 0 | 0 | null | 1,586,377,077,000 | 1,586,377,077,000 | null | UTF-8 | Lean | false | false | 957 | lean |
import Galois.Init.Nat
namespace Test
namespace Hex
def test : IO UInt32 := do
-- Printing hex at the minimal width
IO.println $ Nat.ppHex 0;
IO.println $ Nat.ppHex 15;
IO.println $ Nat.ppHex 42;
-- Printing hex at specified widths
IO.println $ Nat.ppHexAtWidth 0 1;
IO.println $ Nat.ppHexAtWidth 15 1;
IO.println $ Nat.ppHexAtWidth 42 1;
IO.println $ Nat.ppHexAtWidth 0 10;
IO.println $ Nat.ppHexAtWidth 15 10;
IO.println $ Nat.ppHexAtWidth 42 10;
-- Parsing Hex
IO.println $ repr $ Nat.fromHexString "0x";
IO.println $ repr $ Nat.fromHexString "0xabcdefg";
IO.println $ repr $ Nat.fromHexString "0x0";
IO.println $ repr $ Nat.fromHexString "0x00";
IO.println $ repr $ Nat.fromHexString "0xf";
IO.println $ repr $ Nat.fromHexString "0xF";
IO.println $ repr $ Nat.fromHexString "0x0f";
IO.println $ repr $ Nat.fromHexString "0x2a";
IO.println $ repr $ Nat.fromHexString "0x02a";
IO.println $ repr $ Nat.fromHexString "0x02A";
pure 0
end Hex
end Test
|
e5d56a1e0076f7618a8a0e17e56994cd7346f999 | ebf7140a9ea507409ff4c994124fa36e79b4ae35 | /src/solutions/thursday/category_theory/exercise6.lean | fe538e529217732d633aecb7d97888b5584938fb | [] | no_license | fundou/lftcm2020 | 3e88d58a92755ea5dd49f19c36239c35286ecf5e | 99d11bf3bcd71ffeaef0250caa08ecc46e69b55b | refs/heads/master | 1,685,610,799,304 | 1,624,070,416,000 | 1,624,070,416,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,045 | lean | import category_theory.limits.shapes.pullbacks
/-!
Thanks to Markus Himmel for suggesting this question.
-/
open category_theory
open category_theory.limits
/-!
Let C be a category, X and Y be objects and f : X ⟶ Y be a morphism. Show that f is an epimorphism
if and only if the diagram
X --f--→ Y
| |
f 𝟙
| |
↓ ↓
Y --𝟙--→ Y
is a pushout.
-/
variables {C : Type*} [category C]
def pushout_of_epi {X Y : C} (f : X ⟶ Y) [epi f] :
is_colimit (pushout_cocone.mk (𝟙 Y) (𝟙 Y) rfl : pushout_cocone f f) :=
-- Hint: you can start a proof with `fapply pushout_cocone.is_colimit.mk`
-- to save a little bit of work over just building a `is_colimit` structure directly.
-- sorry
begin
fapply pushout_cocone.is_colimit.mk,
{ intro s,
apply s.ι.app walking_span.left, },
{ tidy, },
{ tidy,
apply (cancel_epi f).1,
have fst := s.ι.naturality walking_span.hom.fst,
simp at fst,
rw fst,
have snd := s.ι.naturality walking_span.hom.snd,
simp at snd,
rw snd, },
{ tidy, }
end
-- sorry
theorem epi_of_pushout {X Y : C} (f : X ⟶ Y)
(is_colim : is_colimit (pushout_cocone.mk (𝟙 Y) (𝟙 Y) rfl : pushout_cocone f f)) : epi f :=
-- Hint: You can use `pushout_cocone.mk` to conveniently construct a cocone over a cospan.
-- Hint: use `is_colim.desc` to construct the map from a colimit cocone to any other cocone.
-- Hint: use `is_colim.fac` to show that this map gives a factorisation of the cocone maps through the colimit cocone.
-- Hint: if `simp` won't correctly simplify `𝟙 X ≫ f`, try `dsimp, simp`.
-- sorry
{ left_cancellation := λ Z g h hf,
begin
let a := pushout_cocone.mk _ _ hf,
have hg : is_colim.desc a = g, {
convert is_colim.fac a walking_span.left,
simp, dsimp, simp,
},
have hh : is_colim.desc a = h, {
convert is_colim.fac a walking_span.right,
simp, dsimp, simp,
},
rw [←hg, ←hh],
end }
-- sorry
/-!
There are some further hints in
`hints/category_theory/exercise6/`
-/
|
ed79b4ec6c7f2cd58a00c157d9e8843e17516570 | 5756a081670ba9c1d1d3fca7bd47cb4e31beae66 | /Mathport/Util/Parse.lean | 06613ea1107cd92800eb3d9c0e1d5f6c2a123369 | [
"Apache-2.0"
] | permissive | leanprover-community/mathport | 2c9bdc8292168febf59799efdc5451dbf0450d4a | 13051f68064f7638970d39a8fecaede68ffbf9e1 | refs/heads/master | 1,693,841,364,079 | 1,693,813,111,000 | 1,693,813,111,000 | 379,357,010 | 27 | 10 | Apache-2.0 | 1,691,309,132,000 | 1,624,384,521,000 | Lean | UTF-8 | Lean | false | false | 1,497 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Daniel Selsam
-/
import Lean
import Mathport.Util.Name
open Lean
open System (FilePath)
def parseNat (s : String) : IO Nat :=
match s.toNat? with
| some k => pure k
| none => throw $ IO.userError s!"String '{s}' cannot be converted to Nat"
def parseBool (s : String) : IO Bool :=
match s.toNat? with
| some 1 => pure true
| some 0 => pure false
| _ => throw $ IO.userError s!"String '{s}' cannot be converted to Bool"
open Lean.Json in
def parseJsonFile (α : Type) [FromJson α] (filePath : FilePath) : IO α := do
let s ← IO.FS.readFile filePath
match Json.parse s with
| Except.error err => throw $ IO.userError s!"Error parsing JSON: {err}"
| Except.ok json =>
match fromJson? json with
| Except.error err => throw $ IO.userError s!"Error decoding JSON: {err}"
| Except.ok x => pure x
def parseTLeanImports (tlean : FilePath) (mod : Name) : IO (Array Name) := do
let line ← IO.FS.withFile tlean IO.FS.Mode.read fun h => h.getLine
let tokens := line.trim.splitOn " " |>.toArray
let nImports := tokens[1]!.toNat!
let mut paths := #[]
for i in [:nImports] do
let mod2 := tokens[2+2*i]!.toName'
let mod2 ← match tokens[2+2*i+1]! with
| "-1" => pure mod2
| n => pure <| ((← parseNat n) + 1).repeat Name.getPrefix mod ++ mod2
paths := paths.push mod2
return paths
|
06492bb3ba5265a380ffc8edcbddb57c9f1161e3 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/algebra/algebra/subalgebra.lean | 68ef6408a8d706f042472828b51064babf454704 | [
"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 | 30,032 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Yury Kudryashov
-/
import algebra.algebra.operations
/-!
# Subalgebras over Commutative Semiring
In this file we define `subalgebra`s and the usual operations on them (`map`, `comap'`).
More lemmas about `adjoin` can be found in `ring_theory.adjoin`.
-/
universes u v w
open_locale tensor_product big_operators
set_option old_structure_cmd true
/-- A subalgebra is a sub(semi)ring that includes the range of `algebra_map`. -/
structure subalgebra (R : Type u) (A : Type v)
[comm_semiring R] [semiring A] [algebra R A] extends subsemiring A : Type v :=
(algebra_map_mem' : ∀ r, algebra_map R A r ∈ carrier)
(zero_mem' := (algebra_map R A).map_zero ▸ algebra_map_mem' 0)
(one_mem' := (algebra_map R A).map_one ▸ algebra_map_mem' 1)
/-- Reinterpret a `subalgebra` as a `subsemiring`. -/
add_decl_doc subalgebra.to_subsemiring
namespace subalgebra
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B]
include R
instance : set_like (subalgebra R A) A :=
⟨subalgebra.carrier, λ p q h, by cases p; cases q; congr'⟩
@[simp]
lemma mem_carrier {s : subalgebra R A} {x : A} : x ∈ s.carrier ↔ x ∈ s := iff.rfl
@[ext] theorem ext {S T : subalgebra R A} (h : ∀ x : A, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h
@[simp] lemma mem_to_subsemiring {S : subalgebra R A} {x} : x ∈ S.to_subsemiring ↔ x ∈ S := iff.rfl
@[simp] lemma coe_to_subsemiring (S : subalgebra R A) : (↑S.to_subsemiring : set A) = S := rfl
/-- Copy of a subalgebra with a new `carrier` equal to the old one. Useful to fix definitional
equalities. -/
protected def copy (S : subalgebra R A) (s : set A) (hs : s = ↑S) : subalgebra R A :=
{ carrier := s,
add_mem' := hs.symm ▸ S.add_mem',
mul_mem' := hs.symm ▸ S.mul_mem',
algebra_map_mem' := hs.symm ▸ S.algebra_map_mem' }
variables (S : subalgebra R A)
theorem algebra_map_mem (r : R) : algebra_map R A r ∈ S :=
S.algebra_map_mem' r
theorem srange_le : (algebra_map R A).srange ≤ S.to_subsemiring :=
λ x ⟨r, hr⟩, hr ▸ S.algebra_map_mem r
theorem range_subset : set.range (algebra_map R A) ⊆ S :=
λ x ⟨r, hr⟩, hr ▸ S.algebra_map_mem r
theorem range_le : set.range (algebra_map R A) ≤ S :=
S.range_subset
theorem one_mem : (1 : A) ∈ S :=
S.to_subsemiring.one_mem
theorem mul_mem {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x * y ∈ S :=
S.to_subsemiring.mul_mem hx hy
theorem smul_mem {x : A} (hx : x ∈ S) (r : R) : r • x ∈ S :=
(algebra.smul_def r x).symm ▸ S.mul_mem (S.algebra_map_mem r) hx
theorem pow_mem {x : A} (hx : x ∈ S) (n : ℕ) : x ^ n ∈ S :=
S.to_subsemiring.pow_mem hx n
theorem zero_mem : (0 : A) ∈ S :=
S.to_subsemiring.zero_mem
theorem add_mem {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x + y ∈ S :=
S.to_subsemiring.add_mem hx hy
theorem neg_mem {R : Type u} {A : Type v} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) {x : A} (hx : x ∈ S) : -x ∈ S :=
neg_one_smul R x ▸ S.smul_mem hx _
theorem sub_mem {R : Type u} {A : Type v} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x - y ∈ S :=
by simpa only [sub_eq_add_neg] using S.add_mem hx (S.neg_mem hy)
theorem nsmul_mem {x : A} (hx : x ∈ S) (n : ℕ) : n • x ∈ S :=
S.to_subsemiring.nsmul_mem hx n
theorem gsmul_mem {R : Type u} {A : Type v} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) {x : A} (hx : x ∈ S) : ∀ (n : ℤ), n • x ∈ S
| (n : ℕ) := by { rw [gsmul_coe_nat], exact S.nsmul_mem hx n }
| -[1+ n] := by { rw [gsmul_neg_succ_of_nat], exact S.neg_mem (S.nsmul_mem hx _) }
theorem coe_nat_mem (n : ℕ) : (n : A) ∈ S :=
S.to_subsemiring.coe_nat_mem n
theorem coe_int_mem {R : Type u} {A : Type v} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) (n : ℤ) : (n : A) ∈ S :=
int.cases_on n (λ i, S.coe_nat_mem i) (λ i, S.neg_mem $ S.coe_nat_mem $ i + 1)
theorem list_prod_mem {L : list A} (h : ∀ x ∈ L, x ∈ S) : L.prod ∈ S :=
S.to_subsemiring.list_prod_mem h
theorem list_sum_mem {L : list A} (h : ∀ x ∈ L, x ∈ S) : L.sum ∈ S :=
S.to_subsemiring.list_sum_mem h
theorem multiset_prod_mem {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A]
[algebra R A] (S : subalgebra R A) {m : multiset A} (h : ∀ x ∈ m, x ∈ S) : m.prod ∈ S :=
S.to_subsemiring.multiset_prod_mem m h
theorem multiset_sum_mem {m : multiset A} (h : ∀ x ∈ m, x ∈ S) : m.sum ∈ S :=
S.to_subsemiring.multiset_sum_mem m h
theorem prod_mem {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A]
[algebra R A] (S : subalgebra R A) {ι : Type w} {t : finset ι} {f : ι → A}
(h : ∀ x ∈ t, f x ∈ S) : ∏ x in t, f x ∈ S :=
S.to_subsemiring.prod_mem h
theorem sum_mem {ι : Type w} {t : finset ι} {f : ι → A}
(h : ∀ x ∈ t, f x ∈ S) : ∑ x in t, f x ∈ S :=
S.to_subsemiring.sum_mem h
/-- The projection from a subalgebra of `A` to an additive submonoid of `A`. -/
def to_add_submonoid {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A]
(S : subalgebra R A) : add_submonoid A :=
S.to_subsemiring.to_add_submonoid
/-- The projection from a subalgebra of `A` to a submonoid of `A`. -/
def to_submonoid {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A]
(S : subalgebra R A) : submonoid A :=
S.to_subsemiring.to_submonoid
/-- A subalgebra over a ring is also a `subring`. -/
def to_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) :
subring A :=
{ neg_mem' := λ _, S.neg_mem,
.. S.to_subsemiring }
@[simp] lemma mem_to_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A]
{S : subalgebra R A} {x} : x ∈ S.to_subring ↔ x ∈ S := iff.rfl
@[simp] lemma coe_to_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A]
(S : subalgebra R A) : (↑S.to_subring : set A) = S := rfl
instance : inhabited S := ⟨(0 : S.to_subsemiring)⟩
section
/-! `subalgebra`s inherit structure from their `subsemiring` / `semiring` coercions. -/
instance to_semiring {R A}
[comm_semiring R] [semiring A] [algebra R A] (S : subalgebra R A) :
semiring S := S.to_subsemiring.to_semiring
instance to_comm_semiring {R A}
[comm_semiring R] [comm_semiring A] [algebra R A] (S : subalgebra R A) :
comm_semiring S := S.to_subsemiring.to_comm_semiring
instance to_ring {R A}
[comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) :
ring S := S.to_subring.to_ring
instance to_comm_ring {R A}
[comm_ring R] [comm_ring A] [algebra R A] (S : subalgebra R A) :
comm_ring S := S.to_subring.to_comm_ring
instance to_ordered_semiring {R A}
[comm_semiring R] [ordered_semiring A] [algebra R A] (S : subalgebra R A) :
ordered_semiring S := S.to_subsemiring.to_ordered_semiring
instance to_ordered_comm_semiring {R A}
[comm_semiring R] [ordered_comm_semiring A] [algebra R A] (S : subalgebra R A) :
ordered_comm_semiring S := S.to_subsemiring.to_ordered_comm_semiring
instance to_ordered_ring {R A}
[comm_ring R] [ordered_ring A] [algebra R A] (S : subalgebra R A) :
ordered_ring S := S.to_subring.to_ordered_ring
instance to_ordered_comm_ring {R A}
[comm_ring R] [ordered_comm_ring A] [algebra R A] (S : subalgebra R A) :
ordered_comm_ring S := S.to_subring.to_ordered_comm_ring
instance to_linear_ordered_semiring {R A}
[comm_semiring R] [linear_ordered_semiring A] [algebra R A] (S : subalgebra R A) :
linear_ordered_semiring S := S.to_subsemiring.to_linear_ordered_semiring
/-! There is no `linear_ordered_comm_semiring`. -/
instance to_linear_ordered_ring {R A}
[comm_ring R] [linear_ordered_ring A] [algebra R A] (S : subalgebra R A) :
linear_ordered_ring S := S.to_subring.to_linear_ordered_ring
instance to_linear_ordered_comm_ring {R A}
[comm_ring R] [linear_ordered_comm_ring A] [algebra R A] (S : subalgebra R A) :
linear_ordered_comm_ring S := S.to_subring.to_linear_ordered_comm_ring
end
instance algebra : algebra R S :=
{ smul := λ (c:R) x, ⟨c • x.1, S.smul_mem x.2 c⟩,
commutes' := λ c x, subtype.eq $ algebra.commutes _ _,
smul_def' := λ c x, subtype.eq $ algebra.smul_def _ _,
.. (algebra_map R A).cod_srestrict S.to_subsemiring $ λ x, S.range_le ⟨x, rfl⟩ }
instance to_algebra {R A B : Type*} [comm_semiring R] [comm_semiring A] [semiring B]
[algebra R A] [algebra A B] (A₀ : subalgebra R A) : algebra A₀ B :=
algebra.of_subsemiring A₀.to_subsemiring
instance nontrivial [nontrivial A] : nontrivial S :=
S.to_subsemiring.nontrivial
instance no_zero_smul_divisors_bot [no_zero_smul_divisors R A] : no_zero_smul_divisors R S :=
⟨λ c x h,
have c = 0 ∨ (x : A) = 0,
from eq_zero_or_eq_zero_of_smul_eq_zero (congr_arg coe h),
this.imp_right (@subtype.ext_iff _ _ x 0).mpr⟩
@[simp, norm_cast] lemma coe_add (x y : S) : (↑(x + y) : A) = ↑x + ↑y := rfl
@[simp, norm_cast] lemma coe_mul (x y : S) : (↑(x * y) : A) = ↑x * ↑y := rfl
@[simp, norm_cast] lemma coe_zero : ((0 : S) : A) = 0 := rfl
@[simp, norm_cast] lemma coe_one : ((1 : S) : A) = 1 := rfl
@[simp, norm_cast] lemma coe_neg {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A]
{S : subalgebra R A} (x : S) : (↑(-x) : A) = -↑x := rfl
@[simp, norm_cast] lemma coe_sub {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A]
{S : subalgebra R A} (x y : S) : (↑(x - y) : A) = ↑x - ↑y := rfl
@[simp, norm_cast] lemma coe_smul (r : R) (x : S) : (↑(r • x) : A) = r • ↑x := rfl
@[simp, norm_cast] lemma coe_algebra_map (r : R) : ↑(algebra_map R S r) = algebra_map R A r :=
rfl
@[simp, norm_cast] lemma coe_pow (x : S) (n : ℕ) : (↑(x^n) : A) = (↑x)^n :=
begin
induction n with n ih,
{ simp, },
{ simp [pow_succ, ih], },
end
@[simp, norm_cast] lemma coe_eq_zero {x : S} : (x : A) = 0 ↔ x = 0 :=
(subtype.ext_iff.symm : (x : A) = (0 : S) ↔ x = 0)
@[simp, norm_cast] lemma coe_eq_one {x : S} : (x : A) = 1 ↔ x = 1 :=
(subtype.ext_iff.symm : (x : A) = (1 : S) ↔ x = 1)
-- todo: standardize on the names these morphisms
-- compare with submodule.subtype
/-- Embedding of a subalgebra into the algebra. -/
def val : S →ₐ[R] A :=
by refine_struct { to_fun := (coe : S → A) }; intros; refl
@[simp] lemma coe_val : (S.val : S → A) = coe := rfl
lemma val_apply (x : S) : S.val x = (x : A) := rfl
/-- Convert a `subalgebra` to `submodule` -/
def to_submodule : submodule R A :=
{ carrier := S,
zero_mem' := (0:S).2,
add_mem' := λ x y hx hy, (⟨x, hx⟩ + ⟨y, hy⟩ : S).2,
smul_mem' := λ c x hx, (algebra.smul_def c x).symm ▸
(⟨algebra_map R A c, S.range_le ⟨c, rfl⟩⟩ * ⟨x, hx⟩:S).2 }
@[simp] lemma mem_to_submodule {x} : x ∈ S.to_submodule ↔ x ∈ S := iff.rfl
@[simp] lemma coe_to_submodule (S : subalgebra R A) : (↑S.to_submodule : set A) = S := rfl
theorem to_submodule_injective :
function.injective (to_submodule : subalgebra R A → submodule R A) :=
λ S T h, ext $ λ x, by rw [← mem_to_submodule, ← mem_to_submodule, h]
theorem to_submodule_inj {S U : subalgebra R A} : S.to_submodule = U.to_submodule ↔ S = U :=
to_submodule_injective.eq_iff
/-- As submodules, subalgebras are idempotent. -/
@[simp] theorem mul_self : S.to_submodule * S.to_submodule = S.to_submodule :=
begin
apply le_antisymm,
{ rw submodule.mul_le,
intros y hy z hz,
exact mul_mem S hy hz },
{ intros x hx1,
rw ← mul_one x,
exact submodule.mul_mem_mul hx1 (one_mem S) }
end
/-- Linear equivalence between `S : submodule R A` and `S`. Though these types are equal,
we define it as a `linear_equiv` to avoid type equalities. -/
def to_submodule_equiv (S : subalgebra R A) : S.to_submodule ≃ₗ[R] S :=
linear_equiv.of_eq _ _ rfl
/-- If `S` is an `R`-subalgebra of `A` and `T` is an `S`-subalgebra of `A`,
then `T` is an `R`-subalgebra of `A`. -/
def under {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A]
{i : algebra R A} (S : subalgebra R A)
(T : subalgebra S A) : subalgebra R A :=
{ algebra_map_mem' := λ r, T.algebra_map_mem ⟨algebra_map R A r, S.algebra_map_mem r⟩,
.. T }
/-- Transport a subalgebra via an algebra homomorphism. -/
def map (S : subalgebra R A) (f : A →ₐ[R] B) : subalgebra R B :=
{ algebra_map_mem' := λ r, f.commutes r ▸ set.mem_image_of_mem _ (S.algebra_map_mem r),
.. S.to_subsemiring.map (f : A →+* B) }
lemma map_mono {S₁ S₂ : subalgebra R A} {f : A →ₐ[R] B} :
S₁ ≤ S₂ → S₁.map f ≤ S₂.map f :=
set.image_subset f
lemma map_injective {S₁ S₂ : subalgebra R A} (f : A →ₐ[R] B)
(hf : function.injective f) (ih : S₁.map f = S₂.map f) : S₁ = S₂ :=
ext $ set.ext_iff.1 $ set.image_injective.2 hf $ set.ext $ set_like.ext_iff.mp ih
lemma mem_map {S : subalgebra R A} {f : A →ₐ[R] B} {y : B} :
y ∈ map S f ↔ ∃ x ∈ S, f x = y :=
subsemiring.mem_map
/-- Preimage of a subalgebra under an algebra homomorphism. -/
def comap' (S : subalgebra R B) (f : A →ₐ[R] B) : subalgebra R A :=
{ algebra_map_mem' := λ r, show f (algebra_map R A r) ∈ S,
from (f.commutes r).symm ▸ S.algebra_map_mem r,
.. S.to_subsemiring.comap (f : A →+* B) }
theorem map_le {S : subalgebra R A} {f : A →ₐ[R] B} {U : subalgebra R B} :
map S f ≤ U ↔ S ≤ comap' U f :=
set.image_subset_iff
@[simp] lemma mem_comap (S : subalgebra R B) (f : A →ₐ[R] B) (x : A) :
x ∈ S.comap' f ↔ f x ∈ S :=
iff.rfl
@[simp, norm_cast] lemma coe_comap (S : subalgebra R B) (f : A →ₐ[R] B) :
(S.comap' f : set A) = f ⁻¹' (S : set B) :=
by { ext, simp, }
instance no_zero_divisors {R A : Type*} [comm_ring R] [semiring A] [no_zero_divisors A]
[algebra R A] (S : subalgebra R A) : no_zero_divisors S :=
S.to_subsemiring.no_zero_divisors
instance no_zero_smul_divisors_top {R A : Type*} [comm_semiring R] [comm_semiring A] [algebra R A]
[no_zero_divisors A] (S : subalgebra R A) : no_zero_smul_divisors S A :=
⟨λ c x h,
have (c : A) = 0 ∨ x = 0,
from eq_zero_or_eq_zero_of_mul_eq_zero h,
this.imp_left (@subtype.ext_iff _ _ c 0).mpr⟩
instance integral_domain {R A : Type*} [comm_ring R] [integral_domain A] [algebra R A]
(S : subalgebra R A) : integral_domain S :=
subring.integral_domain S.to_subring
end subalgebra
namespace alg_hom
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B]
variables (φ : A →ₐ[R] B)
/-- Range of an `alg_hom` as a subalgebra. -/
protected def range (φ : A →ₐ[R] B) : subalgebra R B :=
{ algebra_map_mem' := λ r, ⟨algebra_map R A r, φ.commutes r⟩,
.. φ.to_ring_hom.srange }
@[simp] lemma mem_range (φ : A →ₐ[R] B) {y : B} :
y ∈ φ.range ↔ ∃ x, φ x = y := ring_hom.mem_srange
theorem mem_range_self (φ : A →ₐ[R] B) (x : A) : φ x ∈ φ.range := φ.mem_range.2 ⟨x, rfl⟩
@[simp] lemma coe_range (φ : A →ₐ[R] B) : (φ.range : set B) = set.range φ :=
by { ext, rw [set_like.mem_coe, mem_range], refl }
/-- Restrict the codomain of an algebra homomorphism. -/
def cod_restrict (f : A →ₐ[R] B) (S : subalgebra R B) (hf : ∀ x, f x ∈ S) : A →ₐ[R] S :=
{ commutes' := λ r, subtype.eq $ f.commutes r,
.. ring_hom.cod_srestrict (f : A →+* B) S.to_subsemiring hf }
@[simp] lemma val_comp_cod_restrict (f : A →ₐ[R] B) (S : subalgebra R B) (hf : ∀ x, f x ∈ S) :
S.val.comp (f.cod_restrict S hf) = f :=
alg_hom.ext $ λ _, rfl
@[simp] lemma coe_cod_restrict (f : A →ₐ[R] B) (S : subalgebra R B) (hf : ∀ x, f x ∈ S) (x : A) :
↑(f.cod_restrict S hf x) = f x := rfl
theorem injective_cod_restrict (f : A →ₐ[R] B) (S : subalgebra R B) (hf : ∀ x, f x ∈ S) :
function.injective (f.cod_restrict S hf) ↔ function.injective f :=
⟨λ H x y hxy, H $ subtype.eq hxy, λ H x y hxy, H (congr_arg subtype.val hxy : _)⟩
/-- Restrict the codomain of a alg_hom `f` to `f.range`.
This is the bundled version of `set.range_factorization`. -/
@[reducible] def range_restrict (f : A →ₐ[R] B) : A →ₐ[R] f.range :=
f.cod_restrict f.range f.mem_range_self
/-- The equalizer of two R-algebra homomorphisms -/
def equalizer (ϕ ψ : A →ₐ[R] B) : subalgebra R A :=
{ carrier := {a | ϕ a = ψ a},
add_mem' := λ x y hx hy, by
{ change ϕ x = ψ x at hx,
change ϕ y = ψ y at hy,
change ϕ (x + y) = ψ (x + y),
rw [alg_hom.map_add, alg_hom.map_add, hx, hy] },
mul_mem' := λ x y hx hy, by
{ change ϕ x = ψ x at hx,
change ϕ y = ψ y at hy,
change ϕ (x * y) = ψ (x * y),
rw [alg_hom.map_mul, alg_hom.map_mul, hx, hy] },
algebra_map_mem' := λ x, by
{ change ϕ (algebra_map R A x) = ψ (algebra_map R A x),
rw [alg_hom.commutes, alg_hom.commutes] } }
@[simp] lemma mem_equalizer (ϕ ψ : A →ₐ[R] B) (x : A) :
x ∈ ϕ.equalizer ψ ↔ ϕ x = ψ x := iff.rfl
/-- The range of a morphism of algebras is a fintype, if the domain is a fintype.
Note that this instance can cause a diamond with `subtype.fintype` if `B` is also a fintype. -/
instance fintype_range [fintype A] [decidable_eq B] (φ : A →ₐ[R] B) : fintype φ.range :=
set.fintype_range φ
end alg_hom
namespace alg_equiv
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B]
/-- Restrict an algebra homomorphism with a left inverse to an algebra isomorphism to its range.
This is a computable alternative to `alg_equiv.of_injective`. -/
def of_left_inverse
{g : B → A} {f : A →ₐ[R] B} (h : function.left_inverse g f) :
A ≃ₐ[R] f.range :=
{ to_fun := f.range_restrict,
inv_fun := g ∘ f.range.val,
left_inv := h,
right_inv := λ x, subtype.ext $
let ⟨x', hx'⟩ := f.mem_range.mp x.prop in
show f (g x) = x, by rw [←hx', h x'],
..f.range_restrict }
@[simp] lemma of_left_inverse_apply
{g : B → A} {f : A →ₐ[R] B} (h : function.left_inverse g f) (x : A) :
↑(of_left_inverse h x) = f x := rfl
@[simp] lemma of_left_inverse_symm_apply
{g : B → A} {f : A →ₐ[R] B} (h : function.left_inverse g f) (x : f.range) :
(of_left_inverse h).symm x = g x := rfl
/-- Restrict an injective algebra homomorphism to an algebra isomorphism -/
noncomputable def of_injective (f : A →ₐ[R] B) (hf : function.injective f) :
A ≃ₐ[R] f.range :=
of_left_inverse (classical.some_spec hf.has_left_inverse)
@[simp] lemma of_injective_apply (f : A →ₐ[R] B) (hf : function.injective f) (x : A) :
↑(of_injective f hf x) = f x := rfl
/-- Restrict an algebra homomorphism between fields to an algebra isomorphism -/
noncomputable def of_injective_field {E F : Type*} [division_ring E] [semiring F]
[nontrivial F] [algebra R E] [algebra R F] (f : E →ₐ[R] F) : E ≃ₐ[R] f.range :=
of_injective f f.to_ring_hom.injective
end alg_equiv
namespace algebra
variables (R : Type u) {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B]
/-- The minimal subalgebra that includes `s`. -/
def adjoin (s : set A) : subalgebra R A :=
{ algebra_map_mem' := λ r, subsemiring.subset_closure $ or.inl ⟨r, rfl⟩,
.. subsemiring.closure (set.range (algebra_map R A) ∪ s) }
variables {R}
protected lemma gc : galois_connection (adjoin R : set A → subalgebra R A) coe :=
λ s S, ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) subsemiring.subset_closure) H,
λ H, show subsemiring.closure (set.range (algebra_map R A) ∪ s) ≤ S.to_subsemiring,
from subsemiring.closure_le.2 $ set.union_subset S.range_subset H⟩
/-- Galois insertion between `adjoin` and `coe`. -/
protected def gi : galois_insertion (adjoin R : set A → subalgebra R A) coe :=
{ choice := λ s hs, (adjoin R s).copy s $ le_antisymm (algebra.gc.le_u_l s) hs,
gc := algebra.gc,
le_l_u := λ S, (algebra.gc (S : set A) (adjoin R S)).1 $ le_refl _,
choice_eq := λ _ _, set_like.coe_injective $ by { generalize_proofs h, exact h } }
instance : complete_lattice (subalgebra R A) :=
galois_insertion.lift_complete_lattice algebra.gi
@[simp]
lemma coe_top : (↑(⊤ : subalgebra R A) : set A) = set.univ := rfl
@[simp] lemma mem_top {x : A} : x ∈ (⊤ : subalgebra R A) :=
set.mem_univ x
@[simp] lemma top_to_submodule : (⊤ : subalgebra R A).to_submodule = ⊤ := rfl
@[simp] lemma top_to_subsemiring : (⊤ : subalgebra R A).to_subsemiring = ⊤ := rfl
@[simp, norm_cast]
lemma coe_inf (S T : subalgebra R A) : (↑(S ⊓ T) : set A) = S ∩ T := rfl
@[simp]
lemma mem_inf {S T : subalgebra R A} {x : A} : x ∈ S ⊓ T ↔ x ∈ S ∧ x ∈ T := iff.rfl
@[simp] lemma inf_to_submodule (S T : subalgebra R A) :
(S ⊓ T).to_submodule = S.to_submodule ⊓ T.to_submodule := rfl
@[simp] lemma inf_to_subsemiring (S T : subalgebra R A) :
(S ⊓ T).to_subsemiring = S.to_subsemiring ⊓ T.to_subsemiring := rfl
@[simp, norm_cast]
lemma coe_Inf (S : set (subalgebra R A)) : (↑(Inf S) : set A) = ⋂ s ∈ S, ↑s := rfl
lemma mem_Inf {S : set (subalgebra R A)} {x : A} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff
@[simp] lemma Inf_to_submodule (S : set (subalgebra R A)) :
(Inf S).to_submodule = Inf (subalgebra.to_submodule '' S) :=
set_like.coe_injective $ by simp
@[simp] lemma Inf_to_subsemiring (S : set (subalgebra R A)) :
(Inf S).to_subsemiring = Inf (subalgebra.to_subsemiring '' S) :=
set_like.coe_injective $ by simp
@[simp, norm_cast]
lemma coe_infi {ι : Sort*} {S : ι → subalgebra R A} : (↑(⨅ i, S i) : set A) = ⋂ i, S i :=
set.bInter_range
lemma mem_infi {ι : Sort*} {S : ι → subalgebra R A} {x : A} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i :=
by simp only [infi, mem_Inf, set.forall_range_iff]
@[simp] lemma infi_to_submodule {ι : Sort*} (S : ι → subalgebra R A) :
(⨅ i, S i).to_submodule = ⨅ i, (S i).to_submodule :=
set_like.coe_injective $ by simp
instance : inhabited (subalgebra R A) := ⟨⊥⟩
theorem mem_bot {x : A} : x ∈ (⊥ : subalgebra R A) ↔ x ∈ set.range (algebra_map R A) :=
suffices (of_id R A).range = (⊥ : subalgebra R A),
by { rw [← this, ←set_like.mem_coe, alg_hom.coe_range], refl },
le_bot_iff.mp (λ x hx, subalgebra.range_le _ ((of_id R A).coe_range ▸ hx))
theorem to_submodule_bot : (⊥ : subalgebra R A).to_submodule = R ∙ 1 :=
by { ext x, simp [mem_bot, -set.singleton_one, submodule.mem_span_singleton, algebra.smul_def] }
@[simp] theorem coe_bot : ((⊥ : subalgebra R A) : set A) = set.range (algebra_map R A) :=
by simp [set.ext_iff, algebra.mem_bot]
theorem eq_top_iff {S : subalgebra R A} :
S = ⊤ ↔ ∀ x : A, x ∈ S :=
⟨λ h x, by rw h; exact mem_top, λ h, by ext x; exact ⟨λ _, mem_top, λ _, h x⟩⟩
@[simp] theorem map_top (f : A →ₐ[R] B) : subalgebra.map (⊤ : subalgebra R A) f = f.range :=
subalgebra.ext $ λ x,
⟨λ ⟨y, _, hy⟩, ⟨y, hy⟩, λ ⟨y, hy⟩, ⟨y, algebra.mem_top, hy⟩⟩
@[simp] theorem map_bot (f : A →ₐ[R] B) : subalgebra.map (⊥ : subalgebra R A) f = ⊥ :=
eq_bot_iff.2 $ λ x ⟨y, hy, hfy⟩, let ⟨r, hr⟩ := mem_bot.1 hy in subalgebra.range_le _
⟨r, by rwa [← f.commutes, hr]⟩
@[simp] theorem comap_top (f : A →ₐ[R] B) : subalgebra.comap' (⊤ : subalgebra R B) f = ⊤ :=
eq_top_iff.2 $ λ x, mem_top
/-- `alg_hom` to `⊤ : subalgebra R A`. -/
def to_top : A →ₐ[R] (⊤ : subalgebra R A) :=
by refine_struct { to_fun := λ x, (⟨x, mem_top⟩ : (⊤ : subalgebra R A)) }; intros; refl
theorem surjective_algebra_map_iff :
function.surjective (algebra_map R A) ↔ (⊤ : subalgebra R A) = ⊥ :=
⟨λ h, eq_bot_iff.2 $ λ y _, let ⟨x, hx⟩ := h y in hx ▸ subalgebra.algebra_map_mem _ _,
λ h y, algebra.mem_bot.1 $ eq_bot_iff.1 h (algebra.mem_top : y ∈ _)⟩
theorem bijective_algebra_map_iff {R A : Type*} [field R] [semiring A] [nontrivial A]
[algebra R A] :
function.bijective (algebra_map R A) ↔ (⊤ : subalgebra R A) = ⊥ :=
⟨λ h, surjective_algebra_map_iff.1 h.2,
λ h, ⟨(algebra_map R A).injective, surjective_algebra_map_iff.2 h⟩⟩
/-- The bottom subalgebra is isomorphic to the base ring. -/
noncomputable def bot_equiv_of_injective (h : function.injective (algebra_map R A)) :
(⊥ : subalgebra R A) ≃ₐ[R] R :=
alg_equiv.symm $ alg_equiv.of_bijective (algebra.of_id R _)
⟨λ x y hxy, h (congr_arg subtype.val hxy : _),
λ ⟨y, hy⟩, let ⟨x, hx⟩ := algebra.mem_bot.1 hy in ⟨x, subtype.eq hx⟩⟩
/-- The bottom subalgebra is isomorphic to the field. -/
noncomputable def bot_equiv (F R : Type*) [field F] [semiring R] [nontrivial R] [algebra F R] :
(⊥ : subalgebra F R) ≃ₐ[F] F :=
bot_equiv_of_injective (ring_hom.injective _)
/-- The top subalgebra is isomorphic to the field. -/
noncomputable def top_equiv : (⊤ : subalgebra R A) ≃ₐ[R] A :=
(alg_equiv.of_bijective to_top ⟨λ _ _, subtype.mk.inj,
λ x, ⟨x.val, by { ext, refl }⟩⟩ : A ≃ₐ[R] (⊤ : subalgebra R A)).symm
end algebra
namespace subalgebra
open algebra
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B]
variables (S : subalgebra R A)
-- TODO[gh-6025]: make this an instance once safe to do so
lemma subsingleton_of_subsingleton [subsingleton A] : subsingleton (subalgebra R A) :=
⟨λ B C, ext (λ x, by { simp only [subsingleton.elim x 0, zero_mem] })⟩
/--
For performance reasons this is not an instance. If you need this instance, add
```
local attribute [instance] alg_hom.subsingleton subalgebra.subsingleton_of_subsingleton
```
in the section that needs it.
-/
-- TODO[gh-6025]: make this an instance once safe to do so
lemma _root_.alg_hom.subsingleton [subsingleton (subalgebra R A)] : subsingleton (A →ₐ[R] B) :=
⟨λ f g, alg_hom.ext $ λ a,
have a ∈ (⊥ : subalgebra R A) := subsingleton.elim (⊤ : subalgebra R A) ⊥ ▸ mem_top,
let ⟨x, hx⟩ := set.mem_range.mp (mem_bot.mp this) in
hx ▸ (f.commutes _).trans (g.commutes _).symm⟩
-- TODO[gh-6025]: make this an instance once safe to do so
lemma _root_.alg_equiv.subsingleton_left [subsingleton (subalgebra R A)] :
subsingleton (A ≃ₐ[R] B) :=
begin
haveI : subsingleton (A →ₐ[R] B) := alg_hom.subsingleton,
exact ⟨λ f g, alg_equiv.ext
(λ x, alg_hom.ext_iff.mp (subsingleton.elim f.to_alg_hom g.to_alg_hom) x)⟩,
end
-- TODO[gh-6025]: make this an instance once safe to do so
lemma _root_.alg_equiv.subsingleton_right [subsingleton (subalgebra R B)] :
subsingleton (A ≃ₐ[R] B) :=
begin
haveI : subsingleton (B ≃ₐ[R] A) := alg_equiv.subsingleton_left,
exact ⟨λ f g, eq.trans (alg_equiv.symm_symm _).symm
(by rw [subsingleton.elim f.symm g.symm, alg_equiv.symm_symm])⟩
end
lemma range_val : S.val.range = S :=
ext $ set.ext_iff.1 $ S.val.coe_range.trans subtype.range_val
instance : unique (subalgebra R R) :=
{ uniq :=
begin
intro S,
refine le_antisymm (λ r hr, _) bot_le,
simp only [set.mem_range, mem_bot, id.map_eq_self, exists_apply_eq_apply, default],
end
.. algebra.subalgebra.inhabited }
/-- Two subalgebras that are equal are also equivalent as algebras.
This is the `subalgebra` version of `linear_equiv.of_eq` and `equiv.set.of_eq`. -/
@[simps apply]
def equiv_of_eq (S T : subalgebra R A) (h : S = T) : S ≃ₐ[R] T :=
{ to_fun := λ x, ⟨x, h ▸ x.2⟩,
inv_fun := λ x, ⟨x, h.symm ▸ x.2⟩,
map_mul' := λ _ _, rfl,
commutes' := λ _, rfl,
.. linear_equiv.of_eq _ _ (congr_arg to_submodule h) }
@[simp] lemma equiv_of_eq_symm (S T : subalgebra R A) (h : S = T) :
(equiv_of_eq S T h).symm = equiv_of_eq T S h.symm :=
rfl
@[simp] lemma equiv_of_eq_rfl (S : subalgebra R A) :
equiv_of_eq S S rfl = alg_equiv.refl :=
by { ext, refl }
@[simp] lemma equiv_of_eq_trans (S T U : subalgebra R A) (hST : S = T) (hTU : T = U) :
(equiv_of_eq S T hST).trans (equiv_of_eq T U hTU) = equiv_of_eq S U (trans hST hTU) :=
rfl
section prod
variables (S₁ : subalgebra R B)
/-- The product of two subalgebras is a subalgebra. -/
def prod : subalgebra R (A × B) :=
{ carrier := set.prod S S₁,
algebra_map_mem' := λ r, ⟨algebra_map_mem _ _, algebra_map_mem _ _⟩,
.. S.to_subsemiring.prod S₁.to_subsemiring }
@[simp] lemma coe_prod :
(prod S S₁ : set (A × B)) = set.prod S S₁ := rfl
lemma prod_to_submodule :
(S.prod S₁).to_submodule = S.to_submodule.prod S₁.to_submodule := rfl
@[simp] lemma mem_prod {S : subalgebra R A} {S₁ : subalgebra R B} {x : A × B} :
x ∈ prod S S₁ ↔ x.1 ∈ S ∧ x.2 ∈ S₁ := set.mem_prod
@[simp] lemma prod_top : (prod ⊤ ⊤ : subalgebra R (A × B)) = ⊤ :=
by ext; simp
lemma prod_mono {S T : subalgebra R A} {S₁ T₁ : subalgebra R B} :
S ≤ T → S₁ ≤ T₁ → prod S S₁ ≤ prod T T₁ := set.prod_mono
@[simp] lemma prod_inf_prod {S T : subalgebra R A} {S₁ T₁ : subalgebra R B} :
S.prod S₁ ⊓ T.prod T₁ = (S ⊓ T).prod (S₁ ⊓ T₁) :=
set_like.coe_injective set.prod_inter_prod
end prod
end subalgebra
section nat
variables {R : Type*} [semiring R]
/-- A subsemiring is a `ℕ`-subalgebra. -/
def subalgebra_of_subsemiring (S : subsemiring R) : subalgebra ℕ R :=
{ algebra_map_mem' := λ i, S.coe_nat_mem i,
.. S }
@[simp] lemma mem_subalgebra_of_subsemiring {x : R} {S : subsemiring R} :
x ∈ subalgebra_of_subsemiring S ↔ x ∈ S :=
iff.rfl
end nat
section int
variables {R : Type*} [ring R]
/-- A subring is a `ℤ`-subalgebra. -/
def subalgebra_of_subring (S : subring R) : subalgebra ℤ R :=
{ algebra_map_mem' := λ i, int.induction_on i S.zero_mem
(λ i ih, S.add_mem ih S.one_mem)
(λ i ih, show ((-i - 1 : ℤ) : R) ∈ S, by { rw [int.cast_sub, int.cast_one],
exact S.sub_mem ih S.one_mem }),
.. S }
variables {S : Type*} [semiring S]
@[simp] lemma mem_subalgebra_of_subring {x : R} {S : subring R} :
x ∈ subalgebra_of_subring S ↔ x ∈ S :=
iff.rfl
end int
|
a967b36c0941cb64cb6d385eec38cab67d121751 | bb31430994044506fa42fd667e2d556327e18dfe | /src/data/set/prod.lean | 1a5ec550b1712490e65d6992a434b4628a9ab54c | [
"Apache-2.0"
] | permissive | sgouezel/mathlib | 0cb4e5335a2ba189fa7af96d83a377f83270e503 | 00638177efd1b2534fc5269363ebf42a7871df9a | refs/heads/master | 1,674,527,483,042 | 1,673,665,568,000 | 1,673,665,568,000 | 119,598,202 | 0 | 0 | null | 1,517,348,647,000 | 1,517,348,646,000 | null | UTF-8 | Lean | false | false | 26,007 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Johannes Hölzl, Patrick Massot
-/
import data.set.image
/-!
# Sets in product and pi types
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines the product of sets in `α × β` and in `Π i, α i` along with the diagonal of a
type.
## Main declarations
* `set.prod`: Binary product of sets. For `s : set α`, `t : set β`, we have
`s.prod t : set (α × β)`.
* `set.diagonal`: Diagonal of a type. `set.diagonal α = {(x, x) | x : α}`.
* `set.off_diag`: Off-diagonal. `s ×ˢ s` without the diagonal.
* `set.pi`: Arbitrary product of sets.
-/
open function
namespace set
/-! ### Cartesian binary product of sets -/
section prod
variables {α β γ δ : Type*} {s s₁ s₂ : set α} {t t₁ t₂ : set β} {a : α} {b : β}
/-- The cartesian product `prod s t` is the set of `(a, b)` such that `a ∈ s` and `b ∈ t`. -/
def prod (s : set α) (t : set β) : set (α × β) := {p | p.1 ∈ s ∧ p.2 ∈ t}
/- This notation binds more strongly than (pre)images, unions and intersections. -/
infixr (name := set.prod) ` ×ˢ `:82 := set.prod
lemma prod_eq (s : set α) (t : set β) : s ×ˢ t = prod.fst ⁻¹' s ∩ prod.snd ⁻¹' t := rfl
lemma mem_prod_eq {p : α × β} : p ∈ s ×ˢ t = (p.1 ∈ s ∧ p.2 ∈ t) := rfl
@[simp] lemma mem_prod {p : α × β} : p ∈ s ×ˢ t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl
@[simp] lemma prod_mk_mem_set_prod_eq : (a, b) ∈ s ×ˢ t = (a ∈ s ∧ b ∈ t) := rfl
lemma mk_mem_prod (ha : a ∈ s) (hb : b ∈ t) : (a, b) ∈ s ×ˢ t := ⟨ha, hb⟩
instance decidable_mem_prod [hs : decidable_pred (∈ s)] [ht : decidable_pred (∈ t)] :
decidable_pred (∈ (s ×ˢ t)) :=
λ _, and.decidable
lemma prod_mono (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : s₁ ×ˢ t₁ ⊆ s₂ ×ˢ t₂ :=
λ x ⟨h₁, h₂⟩, ⟨hs h₁, ht h₂⟩
lemma prod_mono_left (hs : s₁ ⊆ s₂) : s₁ ×ˢ t ⊆ s₂ ×ˢ t := prod_mono hs subset.rfl
lemma prod_mono_right (ht : t₁ ⊆ t₂) : s ×ˢ t₁ ⊆ s ×ˢ t₂ := prod_mono subset.rfl ht
@[simp] lemma prod_self_subset_prod_self : s₁ ×ˢ s₁ ⊆ s₂ ×ˢ s₂ ↔ s₁ ⊆ s₂ :=
⟨λ h x hx, (h (mk_mem_prod hx hx)).1, λ h x hx, ⟨h hx.1, h hx.2⟩⟩
@[simp] lemma prod_self_ssubset_prod_self : s₁ ×ˢ s₁ ⊂ s₂ ×ˢ s₂ ↔ s₁ ⊂ s₂ :=
and_congr prod_self_subset_prod_self $ not_congr prod_self_subset_prod_self
lemma prod_subset_iff {P : set (α × β)} : s ×ˢ t ⊆ P ↔ ∀ (x ∈ s) (y ∈ t), (x, y) ∈ P :=
⟨λ h _ hx _ hy, h (mk_mem_prod hx hy), λ h ⟨_, _⟩ hp, h _ hp.1 _ hp.2⟩
lemma forall_prod_set {p : α × β → Prop} : (∀ x ∈ s ×ˢ t, p x) ↔ ∀ (x ∈ s) (y ∈ t), p (x, y) :=
prod_subset_iff
lemma exists_prod_set {p : α × β → Prop} : (∃ x ∈ s ×ˢ t, p x) ↔ ∃ (x ∈ s) (y ∈ t), p (x, y) :=
by simp [and_assoc]
@[simp] lemma prod_empty : s ×ˢ (∅ : set β) = ∅ := by { ext, exact and_false _ }
@[simp] lemma empty_prod : (∅ : set α) ×ˢ t = ∅ := by { ext, exact false_and _ }
@[simp] lemma univ_prod_univ : @univ α ×ˢ @univ β = univ := by { ext, exact true_and _ }
lemma univ_prod {t : set β} : (univ : set α) ×ˢ t = prod.snd ⁻¹' t := by simp [prod_eq]
lemma prod_univ {s : set α} : s ×ˢ (univ : set β) = prod.fst ⁻¹' s := by simp [prod_eq]
@[simp] lemma singleton_prod : ({a} : set α) ×ˢ t = prod.mk a '' t :=
by { ext ⟨x, y⟩, simp [and.left_comm, eq_comm] }
@[simp] lemma prod_singleton : s ×ˢ ({b} : set β) = (λ a, (a, b)) '' s :=
by { ext ⟨x, y⟩, simp [and.left_comm, eq_comm] }
lemma singleton_prod_singleton : ({a} : set α) ×ˢ ({b} : set β) = {(a, b)} :=by simp
@[simp] lemma union_prod : (s₁ ∪ s₂) ×ˢ t = s₁ ×ˢ t ∪ s₂ ×ˢ t :=
by { ext ⟨x, y⟩, simp [or_and_distrib_right] }
@[simp] lemma prod_union : s ×ˢ (t₁ ∪ t₂) = s ×ˢ t₁ ∪ s ×ˢ t₂ :=
by { ext ⟨x, y⟩, simp [and_or_distrib_left] }
lemma inter_prod : (s₁ ∩ s₂) ×ˢ t = s₁ ×ˢ t ∩ s₂ ×ˢ t :=
by { ext ⟨x, y⟩, simp only [←and_and_distrib_right, mem_inter_iff, mem_prod] }
lemma prod_inter : s ×ˢ (t₁ ∩ t₂) = s ×ˢ t₁ ∩ s ×ˢ t₂ :=
by { ext ⟨x, y⟩, simp only [←and_and_distrib_left, mem_inter_iff, mem_prod] }
lemma prod_inter_prod : s₁ ×ˢ t₁ ∩ s₂ ×ˢ t₂ = (s₁ ∩ s₂) ×ˢ (t₁ ∩ t₂) :=
by { ext ⟨x, y⟩, simp [and_assoc, and.left_comm] }
lemma disjoint_prod : disjoint (s₁ ×ˢ t₁) (s₂ ×ˢ t₂) ↔ disjoint s₁ s₂ ∨ disjoint t₁ t₂ :=
begin
simp_rw [disjoint_left, mem_prod, not_and_distrib, prod.forall, and_imp,
←@forall_or_distrib_right α, ←@forall_or_distrib_left β,
←@forall_or_distrib_right (_ ∈ s₁), ←@forall_or_distrib_left (_ ∈ t₁)],
end
lemma insert_prod : insert a s ×ˢ t = (prod.mk a '' t) ∪ s ×ˢ t :=
by { ext ⟨x, y⟩, simp [image, iff_def, or_imp_distrib, imp.swap] {contextual := tt} }
lemma prod_insert : s ×ˢ (insert b t) = ((λa, (a, b)) '' s) ∪ s ×ˢ t :=
by { ext ⟨x, y⟩, simp [image, iff_def, or_imp_distrib, imp.swap] {contextual := tt} }
lemma prod_preimage_eq {f : γ → α} {g : δ → β} :
(f ⁻¹' s) ×ˢ (g ⁻¹' t) = (λ p : γ × δ, (f p.1, g p.2)) ⁻¹' s ×ˢ t := rfl
lemma prod_preimage_left {f : γ → α} :
(f ⁻¹' s) ×ˢ t = (λ p : γ × β, (f p.1, p.2)) ⁻¹' s ×ˢ t := rfl
lemma prod_preimage_right {g : δ → β} :
s ×ˢ (g ⁻¹' t) = (λ p : α × δ, (p.1, g p.2)) ⁻¹' s ×ˢ t := rfl
lemma preimage_prod_map_prod (f : α → β) (g : γ → δ) (s : set β) (t : set δ) :
prod.map f g ⁻¹' s ×ˢ t = (f ⁻¹' s) ×ˢ (g ⁻¹' t) :=
rfl
lemma mk_preimage_prod (f : γ → α) (g : γ → β) :
(λ x, (f x, g x)) ⁻¹' s ×ˢ t = f ⁻¹' s ∩ g ⁻¹' t := rfl
@[simp] lemma mk_preimage_prod_left (hb : b ∈ t) : (λ a, (a, b)) ⁻¹' s ×ˢ t = s :=
by { ext a, simp [hb] }
@[simp] lemma mk_preimage_prod_right (ha : a ∈ s) : prod.mk a ⁻¹' s ×ˢ t = t :=
by { ext b, simp [ha] }
@[simp] lemma mk_preimage_prod_left_eq_empty (hb : b ∉ t) : (λ a, (a, b)) ⁻¹' s ×ˢ t = ∅ :=
by { ext a, simp [hb] }
@[simp] lemma mk_preimage_prod_right_eq_empty (ha : a ∉ s) : prod.mk a ⁻¹' s ×ˢ t = ∅ :=
by { ext b, simp [ha] }
lemma mk_preimage_prod_left_eq_if [decidable_pred (∈ t)] :
(λ a, (a, b)) ⁻¹' s ×ˢ t = if b ∈ t then s else ∅ :=
by split_ifs; simp [h]
lemma mk_preimage_prod_right_eq_if [decidable_pred (∈ s)] :
prod.mk a ⁻¹' s ×ˢ t = if a ∈ s then t else ∅ :=
by split_ifs; simp [h]
lemma mk_preimage_prod_left_fn_eq_if [decidable_pred (∈ t)] (f : γ → α) :
(λ a, (f a, b)) ⁻¹' s ×ˢ t = if b ∈ t then f ⁻¹' s else ∅ :=
by rw [← mk_preimage_prod_left_eq_if, prod_preimage_left, preimage_preimage]
lemma mk_preimage_prod_right_fn_eq_if [decidable_pred (∈ s)] (g : δ → β) :
(λ b, (a, g b)) ⁻¹' s ×ˢ t = if a ∈ s then g ⁻¹' t else ∅ :=
by rw [← mk_preimage_prod_right_eq_if, prod_preimage_right, preimage_preimage]
@[simp] lemma preimage_swap_prod (s : set α) (t : set β) : prod.swap ⁻¹' s ×ˢ t = t ×ˢ s :=
by { ext ⟨x, y⟩, simp [and_comm] }
@[simp] lemma image_swap_prod (s : set α) (t : set β) : prod.swap '' s ×ˢ t = t ×ˢ s :=
by rw [image_swap_eq_preimage_swap, preimage_swap_prod]
lemma prod_image_image_eq {m₁ : α → γ} {m₂ : β → δ} :
(m₁ '' s) ×ˢ (m₂ '' t) = (λ p : α × β, (m₁ p.1, m₂ p.2)) '' s ×ˢ t :=
ext $ by simp [-exists_and_distrib_right, exists_and_distrib_right.symm, and.left_comm,
and.assoc, and.comm]
lemma prod_range_range_eq {m₁ : α → γ} {m₂ : β → δ} :
(range m₁) ×ˢ (range m₂) = range (λ p : α × β, (m₁ p.1, m₂ p.2)) :=
ext $ by simp [range]
@[simp] lemma range_prod_map {m₁ : α → γ} {m₂ : β → δ} :
range (prod.map m₁ m₂) = (range m₁) ×ˢ (range m₂) :=
prod_range_range_eq.symm
lemma prod_range_univ_eq {m₁ : α → γ} :
(range m₁) ×ˢ (univ : set β) = range (λ p : α × β, (m₁ p.1, p.2)) :=
ext $ by simp [range]
lemma prod_univ_range_eq {m₂ : β → δ} :
(univ : set α) ×ˢ (range m₂) = range (λ p : α × β, (p.1, m₂ p.2)) :=
ext $ by simp [range]
lemma range_pair_subset (f : α → β) (g : α → γ) :
range (λ x, (f x, g x)) ⊆ (range f) ×ˢ (range g) :=
have (λ x, (f x, g x)) = prod.map f g ∘ (λ x, (x, x)), from funext (λ x, rfl),
by { rw [this, ← range_prod_map], apply range_comp_subset_range }
lemma nonempty.prod : s.nonempty → t.nonempty → (s ×ˢ t).nonempty :=
λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨(x, y), ⟨hx, hy⟩⟩
lemma nonempty.fst : (s ×ˢ t).nonempty → s.nonempty := λ ⟨x, hx⟩, ⟨x.1, hx.1⟩
lemma nonempty.snd : (s ×ˢ t).nonempty → t.nonempty := λ ⟨x, hx⟩, ⟨x.2, hx.2⟩
lemma prod_nonempty_iff : (s ×ˢ t).nonempty ↔ s.nonempty ∧ t.nonempty :=
⟨λ h, ⟨h.fst, h.snd⟩, λ h, h.1.prod h.2⟩
lemma prod_eq_empty_iff : s ×ˢ 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 ×ˢ t ⊆ f ⁻¹' W ↔ ∀ a b, a ∈ s → b ∈ t → f (a, b) ∈ W :=
by simp [subset_def]
lemma image_prod_mk_subset_prod {f : α → β} {g : α → γ} {s : set α} :
(λ x, (f x, g x)) '' s ⊆ (f '' s) ×ˢ (g '' s) :=
by { rintros _ ⟨x, hx, rfl⟩, exact mk_mem_prod (mem_image_of_mem f hx) (mem_image_of_mem g hx) }
lemma image_prod_mk_subset_prod_left (hb : b ∈ t) : (λ a, (a, b)) '' s ⊆ s ×ˢ t :=
by { rintro _ ⟨a, ha, rfl⟩, exact ⟨ha, hb⟩ }
lemma image_prod_mk_subset_prod_right (ha : a ∈ s) : prod.mk a '' t ⊆ s ×ˢ t :=
by { rintro _ ⟨b, hb, rfl⟩, exact ⟨ha, hb⟩ }
lemma prod_subset_preimage_fst (s : set α) (t : set β) : s ×ˢ t ⊆ prod.fst ⁻¹' s :=
inter_subset_left _ _
lemma fst_image_prod_subset (s : set α) (t : set β) : prod.fst '' s ×ˢ t ⊆ s :=
image_subset_iff.2 $ prod_subset_preimage_fst s t
lemma fst_image_prod (s : set β) {t : set α} (ht : t.nonempty) : prod.fst '' s ×ˢ t = s :=
(fst_image_prod_subset _ _).antisymm $ λ y hy, let ⟨x, hx⟩ := ht in ⟨(y, x), ⟨hy, hx⟩, rfl⟩
lemma prod_subset_preimage_snd (s : set α) (t : set β) : s ×ˢ t ⊆ prod.snd ⁻¹' t :=
inter_subset_right _ _
lemma snd_image_prod_subset (s : set α) (t : set β) : prod.snd '' s ×ˢ t ⊆ t :=
image_subset_iff.2 $ prod_subset_preimage_snd s t
lemma snd_image_prod {s : set α} (hs : s.nonempty) (t : set β) : prod.snd '' s ×ˢ t = t :=
(snd_image_prod_subset _ _).antisymm $ λ y y_in, let ⟨x, x_in⟩ := hs in ⟨(x, y), ⟨x_in, y_in⟩, rfl⟩
lemma prod_diff_prod : s ×ˢ t \ s₁ ×ˢ t₁ = s ×ˢ (t \ t₁) ∪ (s \ s₁) ×ˢ t :=
by { ext x, by_cases h₁ : x.1 ∈ s₁; by_cases h₂ : x.2 ∈ t₁; simp * }
/-- 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 ×ˢ t ⊆ s₁ ×ˢ t₁ ↔ s ⊆ s₁ ∧ t ⊆ t₁ ∨ s = ∅ ∨ t = ∅ :=
begin
cases (s ×ˢ 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,
refine ⟨λ H, or.inl ⟨_, _⟩, _⟩,
{ have := image_subset (prod.fst : α × β → α) H,
rwa [fst_image_prod _ st.2, fst_image_prod _ (h.mono H).snd] at this },
{ have := image_subset (prod.snd : α × β → β) H,
rwa [snd_image_prod st.1, snd_image_prod (h.mono H).fst] at this },
{ intro H,
simp only [st.1.ne_empty, st.2.ne_empty, or_false] at H,
exact prod_mono H.1 H.2 }
end
lemma prod_eq_prod_iff_of_nonempty (h : (s ×ˢ t).nonempty) :
s ×ˢ t = s₁ ×ˢ t₁ ↔ s = s₁ ∧ t = t₁ :=
begin
split,
{ intro heq,
have h₁ : (s₁ ×ˢ t₁ : set _).nonempty, { rwa [← heq] },
rw [prod_nonempty_iff] at h h₁,
rw [← fst_image_prod s h.2, ← fst_image_prod s₁ h₁.2, heq, eq_self_iff_true, true_and,
← snd_image_prod h.1 t, ← snd_image_prod h₁.1 t₁, heq] },
{ rintro ⟨rfl, rfl⟩, refl }
end
lemma prod_eq_prod_iff : s ×ˢ t = s₁ ×ˢ t₁ ↔ s = s₁ ∧ t = t₁ ∨ (s = ∅ ∨ t = ∅) ∧
(s₁ = ∅ ∨ t₁ = ∅) :=
begin
symmetry,
cases eq_empty_or_nonempty (s ×ˢ t) with h h,
{ simp_rw [h, @eq_comm _ ∅, prod_eq_empty_iff, prod_eq_empty_iff.mp h, true_and,
or_iff_right_iff_imp],
rintro ⟨rfl, rfl⟩, exact prod_eq_empty_iff.mp h },
rw [prod_eq_prod_iff_of_nonempty h],
rw [nonempty_iff_ne_empty, ne.def, prod_eq_empty_iff] at h,
simp_rw [h, false_and, or_false],
end
@[simp] lemma prod_eq_iff_eq (ht : t.nonempty) : s ×ˢ t = s₁ ×ˢ t ↔ s = s₁ :=
begin
simp_rw [prod_eq_prod_iff, ht.ne_empty, eq_self_iff_true, and_true, or_iff_left_iff_imp,
or_false],
rintro ⟨rfl, rfl⟩,
refl,
end
section mono
variables [preorder α] {f : α → set β} {g : α → set γ}
theorem _root_.monotone.set_prod (hf : monotone f) (hg : monotone g) : monotone (λ x, f x ×ˢ g x) :=
λ a b h, prod_mono (hf h) (hg h)
theorem _root_.antitone.set_prod (hf : antitone f) (hg : antitone g) : antitone (λ x, f x ×ˢ g x) :=
λ a b h, prod_mono (hf h) (hg h)
theorem _root_.monotone_on.set_prod (hf : monotone_on f s) (hg : monotone_on g s) :
monotone_on (λ x, f x ×ˢ g x) s :=
λ a ha b hb h, prod_mono (hf ha hb h) (hg ha hb h)
theorem _root_.antitone_on.set_prod (hf : antitone_on f s) (hg : antitone_on g s) :
antitone_on (λ x, f x ×ˢ g x) s :=
λ a ha b hb h, prod_mono (hf ha hb h) (hg ha hb h)
end mono
end prod
/-! ### Diagonal
In this section we prove some lemmas about the diagonal set `{p | p.1 = p.2}` and the diagonal map
`λ x, (x, x)`.
-/
section diagonal
variables {α : Type*} {s t : set α}
/-- `diagonal α` is the set of `α × α` consisting of all pairs of the form `(a, a)`. -/
def diagonal (α : Type*) : set (α × α) := {p | p.1 = p.2}
lemma mem_diagonal (x : α) : (x, x) ∈ diagonal α := by simp [diagonal]
@[simp] lemma mem_diagonal_iff {x : α × α} : x ∈ diagonal α ↔ x.1 = x.2 := iff.rfl
instance decidable_mem_diagonal [h : decidable_eq α] (x : α × α) : decidable (x ∈ diagonal α) :=
h x.1 x.2
lemma preimage_coe_coe_diagonal (s : set α) : (prod.map coe coe) ⁻¹' (diagonal α) = diagonal s :=
by { ext ⟨⟨x, hx⟩, ⟨y, hy⟩⟩, simp [set.diagonal] }
@[simp] lemma range_diag : range (λ x, (x, x)) = diagonal α :=
by { ext ⟨x, y⟩, simp [diagonal, eq_comm] }
@[simp] lemma prod_subset_compl_diagonal_iff_disjoint : s ×ˢ t ⊆ (diagonal α)ᶜ ↔ disjoint s t :=
subset_compl_comm.trans $ by simp_rw [← range_diag, range_subset_iff,
disjoint_left, mem_compl_iff, prod_mk_mem_set_prod_eq, not_and]
@[simp] lemma diag_preimage_prod (s t : set α) : (λ x, (x, x)) ⁻¹' (s ×ˢ t) = s ∩ t := rfl
lemma diag_preimage_prod_self (s : set α) : (λ x, (x, x)) ⁻¹' (s ×ˢ s) = s := inter_self s
end diagonal
section off_diag
variables {α : Type*} {s t : set α} {x : α × α} {a : α}
/-- The off-diagonal of a set `s` is the set of pairs `(a, b)` with `a, b ∈ s` and `a ≠ b`. -/
def off_diag (s : set α) : set (α × α) := {x | x.1 ∈ s ∧ x.2 ∈ s ∧ x.1 ≠ x.2}
@[simp] lemma mem_off_diag : x ∈ s.off_diag ↔ x.1 ∈ s ∧ x.2 ∈ s ∧ x.1 ≠ x.2 := iff.rfl
lemma off_diag_mono : monotone (off_diag : set α → set (α × α)) :=
λ s t h x, and.imp (@h _) $ and.imp_left $ @h _
@[simp] lemma off_diag_nonempty : s.off_diag.nonempty ↔ s.nontrivial :=
by simp [off_diag, set.nonempty, set.nontrivial]
@[simp] lemma off_diag_eq_empty : s.off_diag = ∅ ↔ s.subsingleton :=
by rw [←not_nonempty_iff_eq_empty, ←not_nontrivial_iff, off_diag_nonempty.not]
alias off_diag_nonempty ↔ _ nontrivial.off_diag_nonempty
alias off_diag_nonempty ↔ _ subsingleton.off_diag_eq_empty
variables (s t)
lemma off_diag_subset_prod : s.off_diag ⊆ s ×ˢ s := λ x hx, ⟨hx.1, hx.2.1⟩
lemma off_diag_eq_sep_prod : s.off_diag = {x ∈ s ×ˢ s | x.1 ≠ x.2} := ext $ λ _, and.assoc.symm
@[simp] lemma off_diag_empty : (∅ : set α).off_diag = ∅ := by simp
@[simp] lemma off_diag_singleton (a : α) : ({a} : set α).off_diag = ∅ := by simp
@[simp] lemma off_diag_univ : (univ : set α).off_diag = (diagonal α)ᶜ := ext $ by simp
@[simp] lemma prod_sdiff_diagonal : s ×ˢ s \ diagonal α = s.off_diag := ext $ λ _, and.assoc
@[simp] lemma disjoint_diagonal_off_diag : disjoint (diagonal α) s.off_diag :=
disjoint_left.mpr $ λ x hd ho, ho.2.2 hd
lemma off_diag_inter : (s ∩ t).off_diag = s.off_diag ∩ t.off_diag :=
ext $ λ x, by { simp only [mem_off_diag, mem_inter_iff], tauto }
variables {s t}
lemma off_diag_union (h : disjoint s t) :
(s ∪ t).off_diag = s.off_diag ∪ t.off_diag ∪ s ×ˢ t ∪ t ×ˢ s :=
begin
rw [off_diag_eq_sep_prod, union_prod, prod_union, prod_union, union_comm _ (t ×ˢ t), union_assoc,
union_left_comm (s ×ˢ t), ←union_assoc, sep_union, sep_union, ←off_diag_eq_sep_prod,
←off_diag_eq_sep_prod, sep_eq_self_iff_mem_true.2, ←union_assoc],
simp only [mem_union, mem_prod, ne.def, prod.forall],
rintro i j (⟨hi, hj⟩ | ⟨hi, hj⟩) rfl; exact h.le_bot ⟨‹_›, ‹_›⟩,
end
lemma off_diag_insert (ha : a ∉ s) : (insert a s).off_diag = s.off_diag ∪ {a} ×ˢ s ∪ s ×ˢ {a} :=
begin
rw [insert_eq, union_comm, off_diag_union, off_diag_singleton, union_empty, union_right_comm],
rw disjoint_left,
rintro b hb (rfl : b = a),
exact ha hb
end
end off_diag
/-! ### Cartesian set-indexed product of sets -/
section pi
variables {ι : Type*} {α β : ι → Type*} {s s₁ s₂ : set ι} {t t₁ t₂ : Π i, set (α i)} {i : ι}
/-- Given an index set `ι` and a family of sets `t : Π i, set (α i)`, `pi s t`
is the set of dependent functions `f : Πa, π a` such that `f a` belongs to `t a`
whenever `a ∈ s`. -/
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 := iff.rfl
@[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] }
@[simp] lemma pi_univ (s : set ι) : pi s (λ i, (univ : set (α i))) = univ :=
eq_univ_of_forall $ λ f i hi, mem_univ _
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_inter_distrib : s.pi (λ i, t i ∩ t₁ i) = s.pi t ∩ s.pi t₁ :=
ext $ λ x, by simp only [forall_and_distrib, mem_pi, mem_inter_iff]
lemma pi_congr (h : s₁ = s₂) (h' : ∀ i ∈ s₁, t₁ i = t₂ i) : s₁.pi t₁ = s₂.pi t₂ :=
h ▸ (ext $ λ x, forall₂_congr $ λ i hi, h' i hi ▸ iff.rfl)
lemma pi_eq_empty (hs : i ∈ s) (ht : t i = ∅) : s.pi t = ∅ :=
by { ext f, simp only [mem_empty_iff_false, not_forall, iff_false, mem_pi, not_imp],
exact ⟨i, hs, by simp [ht]⟩ }
lemma univ_pi_eq_empty (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, is_empty (α i) ∨ i ∈ s ∧ t i = ∅ :=
begin
rw [← not_nonempty_iff_eq_empty, pi_nonempty_iff],
push_neg,
refine exists_congr (λ i, _),
casesI is_empty_or_nonempty (α i); simp [*, forall_and_distrib, eq_empty_iff_forall_not_mem],
end
@[simp] 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 univ_pi_empty [h : nonempty ι] : pi univ (λ i, ∅ : Π i, set (α i)) = ∅ :=
univ_pi_eq_empty_iff.2 $ h.elim $ λ x, ⟨x, rfl⟩
@[simp] lemma disjoint_univ_pi : disjoint (pi univ t₁) (pi univ t₂) ↔ ∃ i, disjoint (t₁ i) (t₂ i) :=
by simp only [disjoint_iff_inter_eq_empty, ← pi_inter_distrib, univ_pi_eq_empty_iff]
@[simp] lemma range_dcomp (f : Π i, α i → β i) :
range (λ (g : Π i, α i), (λ i, f i (g i))) = pi univ (λ i, range (f i)) :=
begin
apply subset.antisymm _ (λ x hx, _),
{ rintro _ ⟨x, rfl⟩ i -,
exact ⟨x i, rfl⟩ },
{ choose y hy using hx,
exact ⟨λ i, y i trivial, funext $ λ i, hy i trivial⟩ }
end
@[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 singleton_pi' (i : ι) (t : Π i, set (α i)) : pi {i} t = {x | x i ∈ t i} := singleton_pi i t
lemma univ_pi_singleton (f : Π i, α i) : pi univ (λ i, {f i}) = ({f} : set (Π i, α i)) :=
ext $ λ g, by simp [funext_iff]
lemma preimage_pi (s : set ι) (t : Π i, set (β i)) (f : Π i, α i → β i) :
(λ (g : Π i, α i) i, f _ (g i)) ⁻¹' s.pi t = s.pi (λ i, f i ⁻¹' t i) := rfl
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,
refine ⟨λ h, _, _⟩,
{ split; { rintro i ⟨his, hpi⟩, simpa [*] using h i } },
{ rintro ⟨ht₁, ht₂⟩ i his,
by_cases p i; simp * at * }
end
lemma union_pi : (s₁ ∪ s₂).pi t = s₁.pi t ∩ s₂.pi t :=
by simp [pi, or_imp_distrib, forall_and_distrib, set_of_and]
@[simp] lemma pi_inter_compl (s : set ι) : pi s t ∩ pi sᶜ t = pi univ t :=
by rw [← union_pi, union_compl_self]
lemma pi_update_of_not_mem [decidable_eq ι] (hi : i ∉ s) (f : Π j, α j) (a : α i)
(t : Π j, α j → set (β j)) :
s.pi (λ j, t j (update f i a j)) = s.pi (λ j, t j (f j)) :=
pi_congr rfl $ λ j hj, by { rw update_noteq, exact λ h, hi (h ▸ hj) }
lemma pi_update_of_mem [decidable_eq ι] (hi : i ∈ s) (f : Π j, α j) (a : α i)
(t : Π j, α j → set (β j)) :
s.pi (λ j, t j (update f i a j)) = {x | x i ∈ t i a} ∩ (s \ {i}).pi (λ j, t j (f j)) :=
calc s.pi (λ j, t j (update f i a j)) = ({i} ∪ s \ {i}).pi (λ j, t j (update f i a j)) :
by rw [union_diff_self, union_eq_self_of_subset_left (singleton_subset_iff.2 hi)]
... = {x | x i ∈ t i a} ∩ (s \ {i}).pi (λ j, t j (f j)) :
by { rw [union_pi, singleton_pi', update_same, pi_update_of_not_mem], simp }
lemma univ_pi_update [decidable_eq ι] {β : Π i, Type*} (i : ι) (f : Π j, α j) (a : α i)
(t : Π j, α j → set (β j)) :
pi univ (λ j, t j (update f i a j)) = {x | x i ∈ t i a} ∩ pi {i}ᶜ (λ j, t j (f j)) :=
by rw [compl_eq_univ_diff, ← pi_update_of_mem (mem_univ _)]
lemma univ_pi_update_univ [decidable_eq ι] (i : ι) (s : set (α i)) :
pi univ (update (λ j : ι, (univ : set (α j))) i s) = eval i ⁻¹' s :=
by rw [univ_pi_update i (λ j, (univ : set (α j))) s (λ j t, t), pi_univ, inter_univ, preimage]
lemma eval_image_pi_subset (hs : i ∈ s) : eval i '' s.pi t ⊆ t i :=
image_subset_iff.2 $ λ f hf, hf i hs
lemma eval_image_univ_pi_subset : eval i '' pi univ t ⊆ t i :=
eval_image_pi_subset (mem_univ i)
lemma subset_eval_image_pi (ht : (s.pi t).nonempty) (i : ι) : t i ⊆ eval i '' s.pi t :=
begin
classical,
obtain ⟨f, hf⟩ := ht,
refine λ y hy, ⟨update f i y, λ j hj, _, update_same _ _ _⟩,
obtain rfl | hji := eq_or_ne j i; simp [*, hf _ hj]
end
lemma eval_image_pi (hs : i ∈ s) (ht : (s.pi t).nonempty) : eval i '' s.pi t = t i :=
(eval_image_pi_subset hs).antisymm (subset_eval_image_pi ht i)
@[simp] lemma eval_image_univ_pi (ht : (pi univ t).nonempty) :
(λ f : Π i, α i, f i) '' pi univ t = t i :=
eval_image_pi (mem_univ i) ht
lemma pi_subset_pi_iff : pi s t₁ ⊆ pi s t₂ ↔ (∀ i ∈ s, t₁ i ⊆ t₂ i) ∨ pi s t₁ = ∅ :=
begin
refine ⟨λ h, or_iff_not_imp_right.2 _, λ h, h.elim pi_mono (λ h', h'.symm ▸ empty_subset _)⟩,
rw [← ne.def, ←nonempty_iff_ne_empty],
intros hne i hi,
simpa only [eval_image_pi hi hne, eval_image_pi hi (hne.mono h)]
using image_subset (λ f : Π i, α i, f i) h
end
lemma univ_pi_subset_univ_pi_iff : pi univ t₁ ⊆ pi univ t₂ ↔ (∀ i, t₁ i ⊆ t₂ i) ∨ ∃ i, t₁ i = ∅ :=
by simp [pi_subset_pi_iff]
lemma eval_preimage [decidable_eq ι] {s : set (α i)} :
eval i ⁻¹' s = pi univ (update (λ i, univ) i s) :=
by { ext x, simp [@forall_update_iff _ (λ i, set (α i)) _ _ _ _ (λ i' y, x i' ∈ y)] }
lemma eval_preimage' [decidable_eq ι] {s : set (α i)} :
eval i ⁻¹' s = pi {i} (update (λ i, univ) i s) :=
by { ext, simp }
lemma update_preimage_pi [decidable_eq ι] {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,
refine ⟨λ h, _, λ hx j hj, _⟩,
{ convert h i hi,
simp },
{ obtain rfl | h := eq_or_ne j i,
{ simpa },
{ rw update_noteq h,
exact hf j hj h } }
end
lemma update_preimage_univ_pi [decidable_eq ι] {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⟩
lemma univ_pi_ite (s : set ι) [decidable_pred (∈ s)] (t : Π i, set (α i)) :
pi univ (λ i, if i ∈ s then t i else univ) = s.pi t :=
by { ext, simp_rw [mem_univ_pi], refine forall_congr (λ i, _), split_ifs; simp [h] }
end pi
end set
|
5577231f7a84416e35379e754a0380a70968d396 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/measure_theory/function/ae_measurable_order.lean | 2c5766576668d98e328d6c2b25975ce2af8b987d | [
"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 | 6,234 | lean | /-
Copyright (c) 2021 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import measure_theory.constructions.borel_space
/-!
# Measurability criterion for ennreal-valued functions
Consider a function `f : α → ℝ≥0∞`. If the level sets `{f < p}` and `{q < f}` have measurable
supersets which are disjoint up to measure zero when `p` and `q` are finite numbers satisfying
`p < q`, then `f` is almost-everywhere measurable. This is proved in
`ennreal.ae_measurable_of_exist_almost_disjoint_supersets`, and deduced from an analogous statement
for any target space which is a complete linear dense order, called
`measure_theory.ae_measurable_of_exist_almost_disjoint_supersets`.
Note that it should be enough to assume that the space is a conditionally complete linear order,
but the proof would be more painful. Since our only use for now is for `ℝ≥0∞`, we keep it as simple
as possible.
-/
open measure_theory set topological_space
open_locale classical ennreal nnreal
/-- If a function `f : α → β` is such that the level sets `{f < p}` and `{q < f}` have measurable
supersets which are disjoint up to measure zero when `p < q`, then `f` is almost-everywhere
measurable. It is even enough to have this for `p` and `q` in a countable dense set. -/
theorem measure_theory.ae_measurable_of_exist_almost_disjoint_supersets
{α : Type*} {m : measurable_space α} (μ : measure α)
{β : Type*} [complete_linear_order β] [densely_ordered β] [topological_space β]
[order_topology β] [second_countable_topology β] [measurable_space β] [borel_space β]
(s : set β) (s_count : s.countable) (s_dense : dense s) (f : α → β)
(h : ∀ (p ∈ s) (q ∈ s), p < q → ∃ u v, measurable_set u ∧ measurable_set v ∧
{x | f x < p} ⊆ u ∧ {x | q < f x} ⊆ v ∧ μ (u ∩ v) = 0) :
ae_measurable f μ :=
begin
haveI : encodable s := s_count.to_encodable,
have h' : ∀ p q, ∃ u v, measurable_set u ∧ measurable_set v ∧
{x | f x < p} ⊆ u ∧ {x | q < f x} ⊆ v ∧ (p ∈ s → q ∈ s → p < q → μ (u ∩ v) = 0),
{ assume p q,
by_cases H : p ∈ s ∧ q ∈ s ∧ p < q,
{ rcases h p H.1 q H.2.1 H.2.2 with ⟨u, v, hu, hv, h'u, h'v, hμ⟩,
exact ⟨u, v, hu, hv, h'u, h'v, λ ps qs pq, hμ⟩ },
{ refine ⟨univ, univ, measurable_set.univ, measurable_set.univ, subset_univ _, subset_univ _,
λ ps qs pq, _⟩,
simp only [not_and] at H,
exact (H ps qs pq).elim } },
choose! u v huv using h',
let u' : β → set α := λ p, ⋂ (q ∈ s ∩ Ioi p), u p q,
have u'_meas : ∀ i, measurable_set (u' i),
{ assume i,
exact measurable_set.bInter (s_count.mono (inter_subset_left _ _)) (λ b hb, (huv i b).1) },
let f' : α → β := λ x, ⨅ (i : s), piecewise (u' i) (λ x, (i : β)) (λ x, (⊤ : β)) x,
have f'_meas : measurable f',
{ apply measurable_infi,
exact λ i, measurable.piecewise (u'_meas i) measurable_const measurable_const },
let t := ⋃ (p : s) (q : s ∩ Ioi p), u' p ∩ v p q,
have μt : μ t ≤ 0 := calc
μ t ≤ ∑' (p : s) (q : s ∩ Ioi p), μ (u' p ∩ v p q) : begin
refine (measure_Union_le _).trans _,
apply ennreal.tsum_le_tsum (λ p, _),
apply measure_Union_le _,
exact (s_count.mono (inter_subset_left _ _)).to_subtype,
end
... ≤ ∑' (p : s) (q : s ∩ Ioi p), μ (u p q ∩ v p q) : begin
apply ennreal.tsum_le_tsum (λ p, _),
refine ennreal.tsum_le_tsum (λ q, measure_mono _),
exact inter_subset_inter_left _ (bInter_subset_of_mem q.2)
end
... = ∑' (p : s) (q : s ∩ Ioi p), (0 : ℝ≥0∞) :
by { congr, ext1 p, congr, ext1 q, exact (huv p q).2.2.2.2 p.2 q.2.1 q.2.2 }
... = 0 : by simp only [tsum_zero],
have ff' : ∀ᵐ x ∂μ, f x = f' x,
{ have : ∀ᵐ x ∂μ, x ∉ t,
{ have : μ t = 0 := le_antisymm μt bot_le,
change μ _ = 0,
convert this,
ext y,
simp only [not_exists, exists_prop, mem_set_of_eq, mem_compl_iff, not_not_mem] },
filter_upwards [this] with x hx,
apply (infi_eq_of_forall_ge_of_forall_gt_exists_lt _ _).symm,
{ assume i,
by_cases H : x ∈ u' i,
swap, { simp only [H, le_top, not_false_iff, piecewise_eq_of_not_mem] },
simp only [H, piecewise_eq_of_mem],
contrapose! hx,
obtain ⟨r, ⟨xr, rq⟩, rs⟩ : ∃ r, r ∈ Ioo (i : β) (f x) ∩ s :=
dense_iff_inter_open.1 s_dense (Ioo i (f x)) is_open_Ioo (nonempty_Ioo.2 hx),
have A : x ∈ v i r := (huv i r).2.2.2.1 rq,
apply mem_Union.2 ⟨i, _⟩,
refine mem_Union.2 ⟨⟨r, ⟨rs, xr⟩⟩, _⟩,
exact ⟨H, A⟩ },
{ assume q hq,
obtain ⟨r, ⟨xr, rq⟩, rs⟩ : ∃ r, r ∈ Ioo (f x) q ∩ s :=
dense_iff_inter_open.1 s_dense (Ioo (f x) q) is_open_Ioo (nonempty_Ioo.2 hq),
refine ⟨⟨r, rs⟩, _⟩,
have A : x ∈ u' r := mem_bInter (λ i hi, (huv r i).2.2.1 xr),
simp only [A, rq, piecewise_eq_of_mem, subtype.coe_mk] } },
exact ⟨f', f'_meas, ff'⟩,
end
/-- If a function `f : α → ℝ≥0∞` is such that the level sets `{f < p}` and `{q < f}` have measurable
supersets which are disjoint up to measure zero when `p` and `q` are finite numbers satisfying
`p < q`, then `f` is almost-everywhere measurable. -/
theorem ennreal.ae_measurable_of_exist_almost_disjoint_supersets
{α : Type*} {m : measurable_space α} (μ : measure α) (f : α → ℝ≥0∞)
(h : ∀ (p : ℝ≥0) (q : ℝ≥0), p < q → ∃ u v, measurable_set u ∧ measurable_set v ∧
{x | f x < p} ⊆ u ∧ {x | (q : ℝ≥0∞) < f x} ⊆ v ∧ μ (u ∩ v) = 0) :
ae_measurable f μ :=
begin
obtain ⟨s, s_count, s_dense, s_zero, s_top⟩ : ∃ s : set ℝ≥0∞, s.countable ∧ dense s ∧
0 ∉ s ∧ ∞ ∉ s := ennreal.exists_countable_dense_no_zero_top,
have I : ∀ x ∈ s, x ≠ ∞ := λ x xs hx, s_top (hx ▸ xs),
apply measure_theory.ae_measurable_of_exist_almost_disjoint_supersets μ s s_count s_dense _,
rintros p hp q hq hpq,
lift p to ℝ≥0 using I p hp,
lift q to ℝ≥0 using I q hq,
exact h p q (ennreal.coe_lt_coe.1 hpq),
end
|
d744e6bcde3d63336be176ef7bf32dc38ef09a36 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/injHEq.lean | 4bd6bfb20ebecee45125ed9a2f754227a82f3ca8 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 75 | lean | example (h : HEq Nat.zero (Nat.succ Nat.zero)) : False := by
injection h
|
e3313714a4df2959623af816101f88704bd995a6 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/data/array/default.lean | 8aa97ce100b2247dbd7bd09a133e2847faaf6352 | [] | 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 | 297 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.data.array.basic
import Mathlib.Lean3Lib.init.data.array.slice
namespace Mathlib
|
da900552fb91cc771e26eba6006b34063aed86af | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/analysis/box_integral/partition/split.lean | bddac898baa726c5576453258ebef64ccaba5582 | [
"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,631 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import analysis.box_integral.partition.basic
/-!
# Split a box along one or more hyperplanes
## Main definitions
A hyperplane `{x : ι → ℝ | x i = a}` splits a rectangular box `I : box_integral.box ι` into two
smaller boxes. If `a ∉ Ioo (I.lower i, I.upper i)`, then one of these boxes is empty, so it is not a
box in the sense of `box_integral.box`.
We introduce the following definitions.
* `box_integral.box.split_lower I i a` and `box_integral.box.split_upper I i a` are these boxes (as
`with_bot (box_integral.box ι)`);
* `box_integral.prepartition.split I i a` is the partition of `I` made of these two boxes (or of one
box `I` if one of these boxes is empty);
* `box_integral.prepartition.split_many I s`, where `s : finset (ι × ℝ)` is a finite set of
hyperplanes `{x : ι → ℝ | x i = a}` encoded as pairs `(i, a)`, is the partition of `I` made by
cutting it along all the hyperplanes in `s`.
## Main results
The main result `box_integral.prepartition.exists_Union_eq_diff` says that any prepartition `π` of
`I` admits a prepartition `π'` of `I` that covers exactly `I \ π.Union`. One of these prepartitions
is available as `box_integral.prepartition.compl`.
## Tags
rectangular box, partition, hyperplane
-/
noncomputable theory
open_locale classical big_operators filter
open function set filter
namespace box_integral
variables {ι M : Type*} {n : ℕ}
namespace box
variables {I : box ι} {i : ι} {x : ℝ} {y : ι → ℝ}
/-- Given a box `I` and `x ∈ (I.lower i, I.upper i)`, the hyperplane `{y : ι → ℝ | y i = x}` splits
`I` into two boxes. `box_integral.box.split_lower I i x` is the box `I ∩ {y | y i ≤ x}`
(if it is nonempty). As usual, we represent a box that may be empty as
`with_bot (box_integral.box ι)`. -/
def split_lower (I : box ι) (i : ι) (x : ℝ) : with_bot (box ι) :=
mk' I.lower (update I.upper i (min x (I.upper i)))
@[simp] lemma coe_split_lower : (split_lower I i x : set (ι → ℝ)) = I ∩ {y | y i ≤ x} :=
begin
rw [split_lower, coe_mk'],
ext y,
simp only [mem_univ_pi, mem_Ioc, mem_inter_eq, mem_coe, mem_set_of_eq, forall_and_distrib,
← pi.le_def, le_update_iff, le_min_iff, and_assoc, and_forall_ne i, mem_def],
rw [and_comm (y i ≤ x), pi.le_def]
end
lemma split_lower_le : I.split_lower i x ≤ I := with_bot_coe_subset_iff.1 $ by simp
@[simp] lemma split_lower_eq_bot {i x} : I.split_lower i x = ⊥ ↔ x ≤ I.lower i :=
begin
rw [split_lower, mk'_eq_bot, exists_update_iff I.upper (λ j y, y ≤ I.lower j)],
simp [(I.lower_lt_upper _).not_le]
end
@[simp] lemma split_lower_eq_self : I.split_lower i x = I ↔ I.upper i ≤ x :=
by simp [split_lower, update_eq_iff]
lemma split_lower_def [decidable_eq ι] {i x} (h : x ∈ Ioo (I.lower i) (I.upper i))
(h' : ∀ j, I.lower j < update I.upper i x j :=
(forall_update_iff I.upper (λ j y, I.lower j < y)).2 ⟨h.1, λ j hne, I.lower_lt_upper _⟩) :
I.split_lower i x = (⟨I.lower, update I.upper i x, h'⟩ : box ι) :=
by { simp only [split_lower, mk'_eq_coe, min_eq_left h.2.le], use rfl, congr }
/-- Given a box `I` and `x ∈ (I.lower i, I.upper i)`, the hyperplane `{y : ι → ℝ | y i = x}` splits
`I` into two boxes. `box_integral.box.split_upper I i x` is the box `I ∩ {y | x < y i}`
(if it is nonempty). As usual, we represent a box that may be empty as
`with_bot (box_integral.box ι)`. -/
def split_upper (I : box ι) (i : ι) (x : ℝ) : with_bot (box ι) :=
mk' (update I.lower i (max x (I.lower i))) I.upper
@[simp] lemma coe_split_upper : (split_upper I i x : set (ι → ℝ)) = I ∩ {y | x < y i} :=
begin
rw [split_upper, coe_mk'],
ext y,
simp only [mem_univ_pi, mem_Ioc, mem_inter_eq, mem_coe, mem_set_of_eq, forall_and_distrib,
forall_update_iff I.lower (λ j z, z < y j), max_lt_iff, and_assoc (x < y i),
and_forall_ne i, mem_def],
exact and_comm _ _
end
lemma split_upper_le : I.split_upper i x ≤ I := with_bot_coe_subset_iff.1 $ by simp
@[simp] lemma split_upper_eq_bot {i x} : I.split_upper i x = ⊥ ↔ I.upper i ≤ x :=
begin
rw [split_upper, mk'_eq_bot, exists_update_iff I.lower (λ j y, I.upper j ≤ y)],
simp [(I.lower_lt_upper _).not_le]
end
@[simp] lemma split_upper_eq_self : I.split_upper i x = I ↔ x ≤ I.lower i :=
by simp [split_upper, update_eq_iff]
lemma split_upper_def [decidable_eq ι] {i x} (h : x ∈ Ioo (I.lower i) (I.upper i))
(h' : ∀ j, update I.lower i x j < I.upper j :=
(forall_update_iff I.lower (λ j y, y < I.upper j)).2 ⟨h.2, λ j hne, I.lower_lt_upper _⟩) :
I.split_upper i x = (⟨update I.lower i x, I.upper, h'⟩ : box ι) :=
by { simp only [split_upper, mk'_eq_coe, max_eq_left h.1.le], refine ⟨_, rfl⟩, congr }
lemma disjoint_split_lower_split_upper (I : box ι) (i : ι) (x : ℝ) :
disjoint (I.split_lower i x) (I.split_upper i x) :=
begin
rw [← disjoint_with_bot_coe, coe_split_lower, coe_split_upper],
refine (disjoint.inf_left' _ _).inf_right' _,
exact λ y (hy : y i ≤ x ∧ x < y i), not_lt_of_le hy.1 hy.2
end
lemma split_lower_ne_split_upper (I : box ι) (i : ι) (x : ℝ) :
I.split_lower i x ≠ I.split_upper i x :=
begin
cases le_or_lt x (I.lower i),
{ rw [split_upper_eq_self.2 h, split_lower_eq_bot.2 h], exact with_bot.bot_ne_coe _ },
{ refine (disjoint_split_lower_split_upper I i x).ne _,
rwa [ne.def, split_lower_eq_bot, not_le] }
end
end box
namespace prepartition
variables {I J : box ι} {i : ι} {x : ℝ}
/-- The partition of `I : box ι` into the boxes `I ∩ {y | y ≤ x i}` and `I ∩ {y | x i < y}`.
One of these boxes can be empty, then this partition is just the single-box partition `⊤`. -/
def split (I : box ι) (i : ι) (x : ℝ) : prepartition I :=
of_with_bot {I.split_lower i x, I.split_upper i x}
begin
simp only [finset.mem_insert, finset.mem_singleton],
rintro J (rfl|rfl),
exacts [box.split_lower_le, box.split_upper_le]
end
begin
simp only [finset.coe_insert, finset.coe_singleton, true_and, set.mem_singleton_iff,
pairwise_insert_of_symmetric symmetric_disjoint, pairwise_singleton],
rintro J rfl -,
exact I.disjoint_split_lower_split_upper i x
end
@[simp] lemma mem_split_iff : J ∈ split I i x ↔ ↑J = I.split_lower i x ∨ ↑J = I.split_upper i x :=
by simp [split]
lemma mem_split_iff' : J ∈ split I i x ↔
(J : set (ι → ℝ)) = I ∩ {y | y i ≤ x} ∨ (J : set (ι → ℝ)) = I ∩ {y | x < y i} :=
by simp [mem_split_iff, ← box.with_bot_coe_inj]
@[simp] lemma Union_split (I : box ι) (i : ι) (x : ℝ) : (split I i x).Union = I :=
by simp [split, ← inter_union_distrib_left, ← set_of_or, le_or_lt]
lemma is_partition_split (I : box ι) (i : ι) (x : ℝ) : is_partition (split I i x) :=
is_partition_iff_Union_eq.2 $ Union_split I i x
lemma sum_split_boxes {M : Type*} [add_comm_monoid M] (I : box ι) (i : ι) (x : ℝ) (f : box ι → M) :
∑ J in (split I i x).boxes, f J = (I.split_lower i x).elim 0 f + (I.split_upper i x).elim 0 f :=
by rw [split, sum_of_with_bot, finset.sum_pair (I.split_lower_ne_split_upper i x)]
/-- If `x ∉ (I.lower i, I.upper i)`, then the hyperplane `{y | y i = x}` does not split `I`. -/
lemma split_of_not_mem_Ioo (h : x ∉ Ioo (I.lower i) (I.upper i)) : split I i x = ⊤ :=
begin
refine ((is_partition_top I).eq_of_boxes_subset (λ J hJ, _)).symm,
rcases mem_top.1 hJ with rfl, clear hJ,
rw [mem_boxes, mem_split_iff],
rw [mem_Ioo, not_and_distrib, not_lt, not_lt] at h,
cases h; [right, left],
{ rwa [eq_comm, box.split_upper_eq_self] },
{ rwa [eq_comm, box.split_lower_eq_self] }
end
lemma coe_eq_of_mem_split_of_mem_le {y : ι → ℝ} (h₁ : J ∈ split I i x) (h₂ : y ∈ J) (h₃ : y i ≤ x) :
(J : set (ι → ℝ)) = I ∩ {y | y i ≤ x} :=
(mem_split_iff'.1 h₁).resolve_right $ λ H,
by { rw [← box.mem_coe, H] at h₂, exact h₃.not_lt h₂.2 }
lemma coe_eq_of_mem_split_of_lt_mem {y : ι → ℝ} (h₁ : J ∈ split I i x) (h₂ : y ∈ J) (h₃ : x < y i) :
(J : set (ι → ℝ)) = I ∩ {y | x < y i} :=
(mem_split_iff'.1 h₁).resolve_left $ λ H,
by { rw [← box.mem_coe, H] at h₂, exact h₃.not_le h₂.2 }
@[simp] lemma restrict_split (h : I ≤ J) (i : ι) (x : ℝ) : (split J i x).restrict I = split I i x :=
begin
refine ((is_partition_split J i x).restrict h).eq_of_boxes_subset _,
simp only [finset.subset_iff, mem_boxes, mem_restrict', exists_prop, mem_split_iff'],
have : ∀ s, (I ∩ s : set (ι → ℝ)) ⊆ J, from λ s, (inter_subset_left _ _).trans h,
rintro J₁ ⟨J₂, (H₂|H₂), H₁⟩; [left, right]; simp [H₁, H₂, inter_left_comm ↑I, this],
end
lemma inf_split (π : prepartition I) (i : ι) (x : ℝ) :
π ⊓ split I i x = π.bUnion (λ J, split J i x) :=
bUnion_congr_of_le rfl $ λ J hJ, restrict_split hJ i x
/-- Split a box along many hyperplanes `{y | y i = x}`; each hyperplane is given by the pair
`(i x)`. -/
def split_many (I : box ι) (s : finset (ι × ℝ)) : prepartition I :=
s.inf (λ p, split I p.1 p.2)
@[simp] lemma split_many_empty (I : box ι) : split_many I ∅ = ⊤ := finset.inf_empty
@[simp] lemma split_many_insert (I : box ι) (s : finset (ι × ℝ)) (p : ι × ℝ) :
split_many I (insert p s) = split_many I s ⊓ split I p.1 p.2 :=
by rw [split_many, finset.inf_insert, inf_comm, split_many]
lemma split_many_le_split (I : box ι) {s : finset (ι × ℝ)} {p : ι × ℝ} (hp : p ∈ s) :
split_many I s ≤ split I p.1 p.2 :=
finset.inf_le hp
lemma is_partition_split_many (I : box ι) (s : finset (ι × ℝ)) :
is_partition (split_many I s) :=
finset.induction_on s (by simp only [split_many_empty, is_partition_top]) $
λ a s ha hs, by simpa only [split_many_insert, inf_split]
using hs.bUnion (λ J hJ, is_partition_split _ _ _)
@[simp] lemma Union_split_many (I : box ι) (s : finset (ι × ℝ)) : (split_many I s).Union = I :=
(is_partition_split_many I s).Union_eq
lemma inf_split_many {I : box ι} (π : prepartition I) (s : finset (ι × ℝ)) :
π ⊓ split_many I s = π.bUnion (λ J, split_many J s) :=
begin
induction s using finset.induction_on with p s hp ihp,
{ simp },
{ simp_rw [split_many_insert, ← inf_assoc, ihp, inf_split, bUnion_assoc] }
end
/-- Let `s : finset (ι × ℝ)` be a set of hyperplanes `{x : ι → ℝ | x i = r}` in `ι → ℝ` encoded as
pairs `(i, r)`. Suppose that this set contains all faces of a box `J`. The hyperplanes of `s` split
a box `I` into subboxes. Let `Js` be one of them. If `J` and `Js` have nonempty intersection, then
`Js` is a subbox of `J`. -/
lemma not_disjoint_imp_le_of_subset_of_mem_split_many {I J Js : box ι} {s : finset (ι × ℝ)}
(H : ∀ i, {(i, J.lower i), (i, J.upper i)} ⊆ s) (HJs : Js ∈ split_many I s)
(Hn : ¬disjoint (J : with_bot (box ι)) Js) : Js ≤ J :=
begin
simp only [finset.insert_subset, finset.singleton_subset_iff] at H,
rcases box.not_disjoint_coe_iff_nonempty_inter.mp Hn with ⟨x, hx, hxs⟩,
refine λ y hy i, ⟨_, _⟩,
{ rcases split_many_le_split I (H i).1 HJs with ⟨Jl, Hmem : Jl ∈ split I i (J.lower i), Hle⟩,
have := Hle hxs,
rw [← box.coe_subset_coe, coe_eq_of_mem_split_of_lt_mem Hmem this (hx i).1] at Hle,
exact (Hle hy).2 },
{ rcases split_many_le_split I (H i).2 HJs with ⟨Jl, Hmem : Jl ∈ split I i (J.upper i), Hle⟩,
have := Hle hxs,
rw [← box.coe_subset_coe, coe_eq_of_mem_split_of_mem_le Hmem this (hx i).2] at Hle,
exact (Hle hy).2 }
end
section fintype
variable [fintype ι]
/-- Let `s` be a finite set of boxes in `ℝⁿ = ι → ℝ`. Then there exists a finite set `t₀` of
hyperplanes (namely, the set of all hyperfaces of boxes in `s`) such that for any `t ⊇ t₀`
and any box `I` in `ℝⁿ` the following holds. The hyperplanes from `t` split `I` into subboxes.
Let `J'` be one of them, and let `J` be one of the boxes in `s`. If these boxes have a nonempty
intersection, then `J' ≤ J`. -/
lemma eventually_not_disjoint_imp_le_of_mem_split_many (s : finset (box ι)) :
∀ᶠ t : finset (ι × ℝ) in at_top, ∀ (I : box ι) (J ∈ s) (J' ∈ split_many I t),
¬disjoint (J : with_bot (box ι)) J' → J' ≤ J :=
begin
refine eventually_at_top.2
⟨s.bUnion (λ J, finset.univ.bUnion (λ i, {(i, J.lower i), (i, J.upper i)})),
λ t ht I J hJ J' hJ', not_disjoint_imp_le_of_subset_of_mem_split_many (λ i, _) hJ'⟩,
exact λ p hp, ht (finset.mem_bUnion.2 ⟨J, hJ, finset.mem_bUnion.2 ⟨i, finset.mem_univ _, hp⟩⟩)
end
lemma eventually_split_many_inf_eq_filter (π : prepartition I) :
∀ᶠ t : finset (ι × ℝ) in at_top,
π ⊓ (split_many I t) = (split_many I t).filter (λ J, ↑J ⊆ π.Union) :=
begin
refine (eventually_not_disjoint_imp_le_of_mem_split_many π.boxes).mono (λ t ht, _),
refine le_antisymm ((bUnion_le_iff _).2 $ λ J hJ, _) (le_inf (λ J hJ, _) (filter_le _ _)),
{ refine of_with_bot_mono _,
simp only [finset.mem_image, exists_prop, mem_boxes, mem_filter],
rintro _ ⟨J₁, h₁, rfl⟩ hne,
refine ⟨_, ⟨J₁, ⟨h₁, subset.trans _ (π.subset_Union hJ)⟩, rfl⟩, le_rfl⟩,
exact ht I J hJ J₁ h₁ (mt disjoint_iff.1 hne) },
{ rw mem_filter at hJ,
rcases set.mem_Union₂.1 (hJ.2 J.upper_mem) with ⟨J', hJ', hmem⟩,
refine ⟨J', hJ', ht I _ hJ' _ hJ.1 $ box.not_disjoint_coe_iff_nonempty_inter.2 _⟩,
exact ⟨J.upper, hmem, J.upper_mem⟩ }
end
lemma exists_split_many_inf_eq_filter_of_finite (s : set (prepartition I)) (hs : s.finite) :
∃ t : finset (ι × ℝ), ∀ π ∈ s,
π ⊓ (split_many I t) = (split_many I t).filter (λ J, ↑J ⊆ π.Union) :=
begin
have := λ π (hπ : π ∈ s), eventually_split_many_inf_eq_filter π,
exact (hs.eventually_all.2 this).exists
end
/-- If `π` is a partition of `I`, then there exists a finite set `s` of hyperplanes such that
`split_many I s ≤ π`. -/
lemma is_partition.exists_split_many_le {I : box ι} {π : prepartition I}
(h : is_partition π) : ∃ s, split_many I s ≤ π :=
(eventually_split_many_inf_eq_filter π).exists.imp $ λ s hs,
by { rwa [h.Union_eq, filter_of_true, inf_eq_right] at hs, exact λ J hJ, le_of_mem _ hJ }
/-- For every prepartition `π` of `I` there exists a prepartition that covers exactly
`I \ π.Union`. -/
lemma exists_Union_eq_diff (π : prepartition I) :
∃ π' : prepartition I, π'.Union = I \ π.Union :=
begin
rcases π.eventually_split_many_inf_eq_filter.exists with ⟨s, hs⟩,
use (split_many I s).filter (λ J, ¬(J : set (ι → ℝ)) ⊆ π.Union),
simp [← hs]
end
/-- If `π` is a prepartition of `I`, then `π.compl` is a prepartition of `I`
such that `π.compl.Union = I \ π.Union`. -/
def compl (π : prepartition I) : prepartition I := π.exists_Union_eq_diff.some
@[simp] lemma Union_compl (π : prepartition I) : π.compl.Union = I \ π.Union :=
π.exists_Union_eq_diff.some_spec
/-- Since the definition of `box_integral.prepartition.compl` uses `Exists.some`,
the result depends only on `π.Union`. -/
lemma compl_congr {π₁ π₂ : prepartition I} (h : π₁.Union = π₂.Union) :
π₁.compl = π₂.compl :=
by { dunfold compl, congr' 1, rw h }
lemma is_partition.compl_eq_bot {π : prepartition I} (h : is_partition π) : π.compl = ⊥ :=
by rw [← Union_eq_empty, Union_compl, h.Union_eq, diff_self]
@[simp] lemma compl_top : (⊤ : prepartition I).compl = ⊥ := (is_partition_top I).compl_eq_bot
end fintype
end prepartition
end box_integral
|
95b7af5c1e5fd14699d2c0b607dd70f6a0a3f54c | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/set_theory/cofinality_auto.lean | 309138df246c3df991d67c77c3123decf92c11c4 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,643 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.set_theory.cardinal_ordinal
import Mathlib.PostPort
universes u_1 u v u_2
namespace Mathlib
/-!
# Cofinality on ordinals, regular cardinals
-/
namespace order
/-- Cofinality of a reflexive order `≼`. This is the smallest cardinality
of a subset `S : set α` such that `∀ a, ∃ b ∈ S, a ≼ b`. -/
def cof {α : Type u_1} (r : α → α → Prop) [is_refl α r] : cardinal :=
cardinal.min sorry
fun (S : Subtype fun (S : set α) => ∀ (a : α), ∃ (b : α), ∃ (H : b ∈ S), r a b) =>
cardinal.mk ↥S
theorem cof_le {α : Type u_1} (r : α → α → Prop) [is_refl α r] {S : set α}
(h : ∀ (a : α), ∃ (b : α), ∃ (H : b ∈ S), r a b) : cof r ≤ cardinal.mk ↥S :=
sorry
theorem le_cof {α : Type u_1} {r : α → α → Prop} [is_refl α r] (c : cardinal) :
c ≤ cof r ↔ ∀ {S : set α}, (∀ (a : α), ∃ (b : α), ∃ (H : b ∈ S), r a b) → c ≤ cardinal.mk ↥S :=
sorry
end order
theorem rel_iso.cof.aux {α : Type u} {β : Type v} {r : α → α → Prop} {s : β → β → Prop}
[is_refl α r] [is_refl β s] (f : r ≃r s) :
cardinal.lift (order.cof r) ≤ cardinal.lift (order.cof s) :=
sorry
theorem rel_iso.cof {α : Type u} {β : Type v} {r : α → α → Prop} {s : β → β → Prop} [is_refl α r]
[is_refl β s] (f : r ≃r s) : cardinal.lift (order.cof r) = cardinal.lift (order.cof s) :=
le_antisymm sorry sorry
def strict_order.cof {α : Type u_1} (r : α → α → Prop) [h : is_irrefl α r] : cardinal :=
order.cof fun (x y : α) => ¬r y x
namespace ordinal
/-- Cofinality of an ordinal. This is the smallest cardinal of a
subset `S` of the ordinal which is unbounded, in the sense
`∀ a, ∃ b ∈ S, ¬(b > a)`. It is defined for all ordinals, but
`cof 0 = 0` and `cof (succ o) = 1`, so it is only really
interesting on limit ordinals (when it is an infinite cardinal). -/
def cof (o : ordinal) : cardinal := quot.lift_on o (fun (_x : Well_order) => sorry) sorry
theorem cof_type {α : Type u_1} (r : α → α → Prop) [is_well_order α r] :
cof (type r) = strict_order.cof r :=
rfl
theorem le_cof_type {α : Type u_1} {r : α → α → Prop} [is_well_order α r] {c : cardinal} :
c ≤ cof (type r) ↔
∀ (S : set α), (∀ (a : α), ∃ (b : α), ∃ (H : b ∈ S), ¬r b a) → c ≤ cardinal.mk ↥S :=
sorry
theorem cof_type_le {α : Type u_1} {r : α → α → Prop} [is_well_order α r] (S : set α)
(h : ∀ (a : α), ∃ (b : α), ∃ (H : b ∈ S), ¬r b a) : cof (type r) ≤ cardinal.mk ↥S :=
iff.mp le_cof_type (le_refl (cof (type r))) S h
theorem lt_cof_type {α : Type u_1} {r : α → α → Prop} [is_well_order α r] (S : set α)
(hl : cardinal.mk ↥S < cof (type r)) : ∃ (a : α), ∀ (b : α), b ∈ S → r b a :=
iff.mp not_forall_not
fun (h : ∀ (x : α), ¬∀ (b : α), b ∈ S → r b x) =>
not_le_of_lt hl (cof_type_le S fun (a : α) => iff.mp not_ball (h a))
theorem cof_eq {α : Type u_1} (r : α → α → Prop) [is_well_order α r] :
∃ (S : set α), (∀ (a : α), ∃ (b : α), ∃ (H : b ∈ S), ¬r b a) ∧ cardinal.mk ↥S = cof (type r) :=
sorry
theorem ord_cof_eq {α : Type u_1} (r : α → α → Prop) [is_well_order α r] :
∃ (S : set α),
(∀ (a : α), ∃ (b : α), ∃ (H : b ∈ S), ¬r b a) ∧
type (subrel r S) = cardinal.ord (cof (type r)) :=
sorry
theorem lift_cof (o : ordinal) : cardinal.lift (cof o) = cof (lift o) := sorry
theorem cof_le_card (o : ordinal) : cof o ≤ card o := sorry
theorem cof_ord_le (c : cardinal) : cof (cardinal.ord c) ≤ c := sorry
@[simp] theorem cof_zero : cof 0 = 0 := sorry
@[simp] theorem cof_eq_zero {o : ordinal} : cof o = 0 ↔ o = 0 := sorry
@[simp] theorem cof_succ (o : ordinal) : cof (succ o) = 1 := sorry
@[simp] theorem cof_eq_one_iff_is_succ {o : ordinal} : cof o = 1 ↔ ∃ (a : ordinal), o = succ a :=
sorry
@[simp] theorem cof_add (a : ordinal) (b : ordinal) : b ≠ 0 → cof (a + b) = cof b := sorry
@[simp] theorem cof_cof (o : ordinal) : cof (cardinal.ord (cof o)) = cof o := sorry
theorem omega_le_cof {o : ordinal} : cardinal.omega ≤ cof o ↔ is_limit o := sorry
@[simp] theorem cof_omega : cof omega = cardinal.omega :=
le_antisymm
(eq.mpr (id (Eq._oldrec (Eq.refl (cof omega ≤ cardinal.omega)) (Eq.symm card_omega)))
(cof_le_card omega))
(iff.mpr omega_le_cof omega_is_limit)
theorem cof_eq' {α : Type u_1} (r : α → α → Prop) [is_well_order α r] (h : is_limit (type r)) :
∃ (S : set α), (∀ (a : α), ∃ (b : α), ∃ (H : b ∈ S), r a b) ∧ cardinal.mk ↥S = cof (type r) :=
sorry
theorem cof_sup_le_lift {ι : Type u_1} (f : ι → ordinal) (H : ∀ (i : ι), f i < sup f) :
cof (sup f) ≤ cardinal.lift (cardinal.mk ι) :=
sorry
theorem cof_sup_le {ι : Type u} (f : ι → ordinal) (H : ∀ (i : ι), f i < sup f) :
cof (sup f) ≤ cardinal.mk ι :=
sorry
theorem cof_bsup_le_lift {o : ordinal} (f : (a : ordinal) → a < o → ordinal) :
(∀ (i : ordinal) (h : i < o), f i h < bsup o f) → cof (bsup o f) ≤ cardinal.lift (card o) :=
sorry
theorem cof_bsup_le {o : ordinal} (f : (a : ordinal) → a < o → ordinal) :
(∀ (i : ordinal) (h : i < o), f i h < bsup o f) → cof (bsup o f) ≤ card o :=
sorry
@[simp] theorem cof_univ : cof univ = cardinal.univ := sorry
theorem sup_lt_ord {ι : Type u} (f : ι → ordinal) {c : ordinal} (H1 : cardinal.mk ι < cof c)
(H2 : ∀ (i : ι), f i < c) : sup f < c :=
sorry
theorem sup_lt {ι : Type u} (f : ι → cardinal) {c : cardinal}
(H1 : cardinal.mk ι < cof (cardinal.ord c)) (H2 : ∀ (i : ι), f i < c) : cardinal.sup f < c :=
sorry
/-- If the union of s is unbounded and s is smaller than the cofinality, then s has an unbounded member -/
theorem unbounded_of_unbounded_sUnion {α : Type u_1} (r : α → α → Prop) [wo : is_well_order α r]
{s : set (set α)} (h₁ : unbounded r (⋃₀s)) (h₂ : cardinal.mk ↥s < strict_order.cof r) :
∃ (x : set α), ∃ (H : x ∈ s), unbounded r x :=
sorry
/-- If the union of s is unbounded and s is smaller than the cofinality, then s has an unbounded member -/
theorem unbounded_of_unbounded_Union {α : Type u} {β : Type u} (r : α → α → Prop)
[wo : is_well_order α r] (s : β → set α) (h₁ : unbounded r (set.Union fun (x : β) => s x))
(h₂ : cardinal.mk β < strict_order.cof r) : ∃ (x : β), unbounded r (s x) :=
sorry
/-- The infinite pigeonhole principle-/
theorem infinite_pigeonhole {β : Type u} {α : Type u} (f : β → α)
(h₁ : cardinal.omega ≤ cardinal.mk β)
(h₂ : cardinal.mk α < cof (cardinal.ord (cardinal.mk β))) :
∃ (a : α), cardinal.mk ↥(f ⁻¹' singleton a) = cardinal.mk β :=
sorry
/-- pigeonhole principle for a cardinality below the cardinality of the domain -/
theorem infinite_pigeonhole_card {β : Type u} {α : Type u} (f : β → α) (θ : cardinal)
(hθ : θ ≤ cardinal.mk β) (h₁ : cardinal.omega ≤ θ) (h₂ : cardinal.mk α < cof (cardinal.ord θ)) :
∃ (a : α), θ ≤ cardinal.mk ↥(f ⁻¹' singleton a) :=
sorry
theorem infinite_pigeonhole_set {β : Type u} {α : Type u} {s : set β} (f : ↥s → α) (θ : cardinal)
(hθ : θ ≤ cardinal.mk ↥s) (h₁ : cardinal.omega ≤ θ)
(h₂ : cardinal.mk α < cof (cardinal.ord θ)) :
∃ (a : α),
∃ (t : set β),
∃ (h : t ⊆ s),
θ ≤ cardinal.mk ↥t ∧ ∀ {x : β} (hx : x ∈ t), f { val := x, property := h hx } = a :=
sorry
end ordinal
namespace cardinal
/-- A cardinal is a limit if it is not zero or a successor
cardinal. Note that `ω` is a limit cardinal by this definition. -/
def is_limit (c : cardinal) := c ≠ 0 ∧ ∀ (x : cardinal), x < c → succ x < c
/-- A cardinal is a strong limit if it is not zero and it is
closed under powersets. Note that `ω` is a strong limit by this definition. -/
def is_strong_limit (c : cardinal) := c ≠ 0 ∧ ∀ (x : cardinal), x < c → bit0 1 ^ x < c
theorem is_strong_limit.is_limit {c : cardinal} (H : is_strong_limit c) : is_limit c :=
{ left := and.left H,
right :=
fun (x : cardinal) (h : x < c) =>
lt_of_le_of_lt (iff.mpr succ_le (cantor x)) (and.right H x h) }
/-- A cardinal is regular if it is infinite and it equals its own cofinality. -/
def is_regular (c : cardinal) := omega ≤ c ∧ ordinal.cof (ord c) = c
theorem cof_is_regular {o : ordinal} (h : ordinal.is_limit o) : is_regular (ordinal.cof o) :=
{ left := iff.mpr ordinal.omega_le_cof h, right := ordinal.cof_cof o }
theorem omega_is_regular : is_regular omega := sorry
theorem succ_is_regular {c : cardinal} (h : omega ≤ c) : is_regular (succ c) := sorry
theorem sup_lt_ord_of_is_regular {ι : Type u} (f : ι → ordinal) {c : cardinal} (hc : is_regular c)
(H1 : mk ι < c) (H2 : ∀ (i : ι), f i < ord c) : ordinal.sup f < ord c :=
ordinal.sup_lt_ord (fun (i : ι) => f i)
(eq.mpr (id (Eq._oldrec (Eq.refl (mk ι < ordinal.cof (ord c))) (and.right hc))) H1) H2
theorem sup_lt_of_is_regular {ι : Type u} (f : ι → cardinal) {c : cardinal} (hc : is_regular c)
(H1 : mk ι < c) (H2 : ∀ (i : ι), f i < c) : sup f < c :=
ordinal.sup_lt (fun (i : ι) => f i)
(eq.mpr (id (Eq._oldrec (Eq.refl (mk ι < ordinal.cof (ord c))) (and.right hc))) H1) H2
theorem sum_lt_of_is_regular {ι : Type u} (f : ι → cardinal) {c : cardinal} (hc : is_regular c)
(H1 : mk ι < c) (H2 : ∀ (i : ι), f i < c) : sum f < c :=
lt_of_le_of_lt (sum_le_sup f) (mul_lt_of_lt (and.left hc) H1 (sup_lt_of_is_regular f hc H1 H2))
/-- A cardinal is inaccessible if it is an
uncountable regular strong limit cardinal. -/
def is_inaccessible (c : cardinal) := omega < c ∧ is_regular c ∧ is_strong_limit c
theorem is_inaccessible.mk {c : cardinal} (h₁ : omega < c) (h₂ : c ≤ ordinal.cof (ord c))
(h₃ : ∀ (x : cardinal), x < c → bit0 1 ^ x < c) : is_inaccessible c :=
sorry
/- Lean's foundations prove the existence of ω many inaccessible
cardinals -/
theorem univ_inaccessible : is_inaccessible univ := sorry
theorem lt_power_cof {c : cardinal} : omega ≤ c → c < c ^ ordinal.cof (ord c) := sorry
theorem lt_cof_power {a : cardinal} {b : cardinal} (ha : omega ≤ a) (b1 : 1 < b) :
a < ordinal.cof (ord (b ^ a)) :=
sorry
end Mathlib |
bd10e8ccc56d49dadaed007f068cc9b14083a445 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /src/Lean/Compiler/IR/ElimDeadVars.lean | 9974bdde9ca922199f906c67a6e18eefd2f61c71 | [
"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,613 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Compiler.IR.Basic
import Lean.Compiler.IR.FreeVars
namespace Lean.IR
partial def reshapeWithoutDead (bs : Array FnBody) (term : FnBody) : FnBody :=
let rec reshape (bs : Array FnBody) (b : FnBody) (used : IndexSet) :=
if bs.isEmpty then b
else
let curr := bs.back
let bs := bs.pop
let keep (_ : Unit) :=
let used := curr.collectFreeIndices used
let b := curr.setBody b
reshape bs b used
let keepIfUsed (vidx : Index) :=
if used.contains vidx then keep ()
else reshape bs b used
match curr with
| FnBody.vdecl x _ _ _ => keepIfUsed x.idx
-- TODO: we should keep all struct/union projections because they are used to ensure struct/union values are fully consumed.
| FnBody.jdecl j _ _ _ => keepIfUsed j.idx
| _ => keep ()
reshape bs term term.freeIndices
partial def FnBody.elimDead (b : FnBody) : FnBody :=
let (bs, term) := b.flatten
let bs := modifyJPs bs elimDead
let term := match term with
| FnBody.case tid x xType alts =>
let alts := alts.map $ fun alt => alt.modifyBody elimDead
FnBody.case tid x xType alts
| other => other
reshapeWithoutDead bs term
/-- Eliminate dead let-declarations and join points -/
def Decl.elimDead (d : Decl) : Decl :=
match d with
| Decl.fdecl (body := b) .. => d.updateBody! b.elimDead
| other => other
end Lean.IR
|
923d3e7a0d65e210bfa4a65f259ff53c0269ad0e | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/testing/slim_check/testable.lean | c7a79b43a48603e0e048482aa4cc49923ea0190f | [
"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 | 28,298 | lean | /-
Copyright (c) 2020 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import testing.slim_check.sampleable
/-!
# `testable` Class
Testable propositions have a procedure that can generate counter-examples
together with a proof that they invalidate the proposition.
This is a port of the Haskell QuickCheck library.
## Creating Customized Instances
The type classes `testable` and `sampleable` are the means by which
`slim_check` creates samples and tests them. For instance, the proposition
`∀ i j : ℕ, i ≤ j` has a `testable` instance because `ℕ` is sampleable
and `i ≤ j` is decidable. Once `slim_check` finds the `testable`
instance, it can start using the instance to repeatedly creating samples
and checking whether they satisfy the property. This allows the
user to create new instances and apply `slim_check` to new situations.
### Polymorphism
The property `testable.check (∀ (α : Type) (xs ys : list α), xs ++ ys
= ys ++ xs)` shows us that type-polymorphic properties can be
tested. `α` is instantiated with `ℤ` first and then tested as normal
monomorphic properties.
The monomorphisation limits the applicability of `slim_check` to
polymorphic properties that can be stated about integers. The
limitation may be lifted in the future but, for now, if
one wishes to use a different type than `ℤ`, one has to refer to
the desired type.
### What do I do if I'm testing a property about my newly defined type?
Let us consider a type made for a new formalization:
```lean
structure my_type :=
(x y : ℕ)
(h : x ≤ y)
```
How do we test a property about `my_type`? For instance, let us consider
`testable.check $ ∀ a b : my_type, a.y ≤ b.x → a.x ≤ b.y`. Writing this
property as is will give us an error because we do not have an instance
of `sampleable my_type`. We can define one as follows:
```lean
instance : sampleable my_type :=
{ sample := do
x ← sample ℕ,
xy_diff ← sample ℕ,
return { x := x, y := x + xy_diff, h := /- some proof -/ } }
```
We can see that the instance is very simple because our type is built
up from other type that have `sampleable` instances. `sampleable` also
has a `shrink` method but it is optional. We may want to implement one
for ease of testing as:
```lean
/- ... -/
shrink := λ ⟨x,y,h⟩, (λ ⟨x,y⟩, { x := x, y := x + y, h := /- proof -/}) <$> shrink (x, y - x)
}
```
Again, we take advantage of the fact that other types have useful
`shrink` implementations, in this case `prod`.
### Optimizing the sampling
Some properties are guarded by a proposition. For instance, recall this
example:
```lean
#eval testable.check (∀ x : ℕ, 2 ∣ x → x < 100)
```
When testing the above example, we generate a natural number, we check
that it is even and test it if it is even or throw it away and start
over otherwise. Statistically, we can expect half of our samples to be
thrown away by such a filter. Sometimes, the filter is more
restrictive. For instance we might need `x` to be a `prime`
number. This would cause most of our samples to be discarded.
We can help `slim_check` find good samples by providing specialized
sampleable instances. Below, we show an instance for the subtype
of even natural numbers. This means that, when producing
a sample, it is forced to produce a proof that it is even.
```lean
instance {k : ℕ} [fact (0 < k)] : sampleable { x : ℕ // k ∣ x } :=
{ sample := do { n ← sample ℕ, pure ⟨k*n, dvd_mul_right _ _⟩ },
shrink := λ ⟨x,h⟩, (λ y, ⟨k*y, dvd_mul_right _ _⟩) <$> shrink x }
```
Such instance will be preferred when testing a proposition of the shape
`∀ x : T, p x → q`
We can observe the effect by enabling tracing:
```lean
/- no specialized sampling -/
#eval testable.check (∀ x : ℕ, 2 ∣ x → x < 100) { trace_discarded := tt }
-- discard
-- x := 1
-- discard
-- x := 41
-- discard
-- x := 3
-- discard
-- x := 5
-- discard
-- x := 5
-- discard
-- x := 197
-- discard
-- x := 469
-- discard
-- x := 9
-- discard
-- ===================
-- Found problems!
-- x := 552
-- -------------------
/- let us define a specialized sampling instance -/
instance {k : ℕ} : sampleable { x : ℕ // k ∣ x } :=
{ sample := do { n ← sample ℕ, pure ⟨k*n, dvd_mul_right _ _⟩ },
shrink := λ ⟨x,h⟩, (λ y, ⟨k*y, dvd_mul_right _ _⟩) <$> shrink x }
#eval testable.check (∀ x : ℕ, 2 ∣ x → x < 100) { enable_tracing := tt }
-- ===================
-- Found problems!
-- x := 358
-- -------------------
```
Similarly, it is common to write properties of the form: `∀ i j, i ≤ j → ...`
as the following example show:
```lean
#eval check (∀ i j k : ℕ, j < k → i - k < i - j)
```
Without subtype instances, the above property discards many samples
because `j < k` does not hold. Fortunately, we have appropriate
instance to choose `k` intelligently.
## Main definitions
* `testable` class
* `testable.check`: a way to test a proposition using random examples
## Tags
random testing
## References
* https://hackage.haskell.org/package/QuickCheck
-/
universes u v
variables var var' : string
variable α : Type u
variable β : α → Prop
variable f : Type → Prop
namespace slim_check
/-- Result of trying to disprove `p`
The constructors are:
* `success : (psum unit p) → test_result`
succeed when we find another example satisfying `p`
In `success h`, `h` is an optional proof of the proposition.
Without the proof, all we know is that we found one example
where `p` holds. With a proof, the one test was sufficient to
prove that `p` holds and we do not need to keep finding examples.
* `gave_up {} : ℕ → test_result`
give up when a well-formed example cannot be generated.
`gave_up n` tells us that `n` invalid examples were tried.
Above 100, we give up on the proposition and report that we
did not find a way to properly test it.
* `failure : ¬ p → (list string) → ℕ → test_result`
a counter-example to `p`; the strings specify values for the relevant variables.
`failure h vs n` also carries a proof that `p` does not hold. This way, we can
guarantee that there will be no false positive. The last component, `n`,
is the number of times that the counter-example was shrunk.
-/
@[derive inhabited]
inductive test_result (p : Prop)
| success : (psum unit p) → test_result
| gave_up {} : ℕ → test_result
| failure : ¬ p → (list string) → ℕ → test_result
/-- format a `test_result` as a string. -/
protected def test_result.to_string {p} : test_result p → string
| (test_result.success (psum.inl ())) := "success (without proof)"
| (test_result.success (psum.inr h)) := "success (with proof)"
| (test_result.gave_up n) := sformat!"gave up {n} times"
| (test_result.failure a vs _) := sformat!"failed {vs}"
/-- configuration for testing a property -/
@[derive [has_reflect, inhabited]]
structure slim_check_cfg :=
(num_inst : ℕ := 100) -- number of examples
(max_size : ℕ := 100) -- final size argument
(trace_discarded : bool := ff) -- enable the printing out of discarded samples
(trace_success : bool := ff) -- enable the printing out of successful tests
(trace_shrink : bool := ff) -- enable the printing out of shrinking steps
(trace_shrink_candidates : bool := ff) -- enable the printing out of shrinking candidates
(random_seed : option ℕ := none) -- specify a seed to the random number generator to
-- obtain a deterministic behavior
(quiet : bool := ff) -- suppress success message when running `slim_check`
instance {p} : has_to_string (test_result p) := ⟨ test_result.to_string ⟩
/--
`printable_prop p` allows one to print a proposition so that
`slim_check` can indicate how values relate to each other.
-/
class printable_prop (p : Prop) :=
(print_prop : option string)
@[priority 100] -- see [note priority]
instance default_printable_prop {p} : printable_prop p :=
⟨ none ⟩
/-- `testable p` uses random examples to try to disprove `p`. -/
class testable (p : Prop) :=
(run [] (cfg : slim_check_cfg) (minimize : bool) : gen (test_result p))
open _root_.list
open test_result
/-- applicative combinator proof carrying test results -/
def combine {p q : Prop} : psum unit (p → q) → psum unit p → psum unit q
| (psum.inr f) (psum.inr x) := psum.inr (f x)
| _ _ := psum.inl ()
/-- Combine the test result for properties `p` and `q` to create a test for their conjunction. -/
def and_counter_example {p q : Prop} :
test_result p →
test_result q →
test_result (p ∧ q)
| (failure Hce xs n) _ := failure (λ h, Hce h.1) xs n
| _ (failure Hce xs n) := failure (λ h, Hce h.2) xs n
| (success xs) (success ys) := success $ combine (combine (psum.inr and.intro) xs) ys
| (gave_up n) (gave_up m) := gave_up $ n + m
| (gave_up n) _ := gave_up n
| _ (gave_up n) := gave_up n
/-- Combine the test result for properties `p` and `q` to create a test for their disjunction -/
def or_counter_example {p q : Prop} :
test_result p →
test_result q →
test_result (p ∨ q)
| (failure Hce xs n) (failure Hce' ys n') := failure (λ h, or_iff_not_and_not.1 h ⟨Hce, Hce'⟩)
(xs ++ ys) (n + n')
| (success xs) _ := success $ combine (psum.inr or.inl) xs
| _ (success ys) := success $ combine (psum.inr or.inr) ys
| (gave_up n) (gave_up m) := gave_up $ n + m
| (gave_up n) _ := gave_up n
| _ (gave_up n) := gave_up n
/-- If `q → p`, then `¬ p → ¬ q` which means that testing `p` can allow us
to find counter-examples to `q`. -/
def convert_counter_example {p q : Prop}
(h : q → p) :
test_result p →
opt_param (psum unit (p → q)) (psum.inl ()) →
test_result q
| (failure Hce xs n) _ := failure (mt h Hce) xs n
| (success Hp) Hpq := success (combine Hpq Hp)
| (gave_up n) _ := gave_up n
/-- Test `q` by testing `p` and proving the equivalence between the two. -/
def convert_counter_example' {p q : Prop}
(h : p ↔ q) (r : test_result p) :
test_result q :=
convert_counter_example h.2 r (psum.inr h.1)
/-- When we assign a value to a universally quantified variable,
we record that value using this function so that our counter-examples
can be informative. -/
def add_to_counter_example (x : string) {p q : Prop}
(h : q → p) :
test_result p →
opt_param (psum unit (p → q)) (psum.inl ()) →
test_result q
| (failure Hce xs n) _ := failure (mt h Hce) (x :: xs) n
| r hpq := convert_counter_example h r hpq
/-- Add some formatting to the information recorded by `add_to_counter_example`. -/
def add_var_to_counter_example {γ : Type v} [has_repr γ]
(var : string) (x : γ) {p q : Prop}
(h : q → p) : test_result p →
opt_param (psum unit (p → q)) (psum.inl ()) →
test_result q :=
@add_to_counter_example (var ++ " := " ++ repr x) _ _ h
/-- Gadget used to introspect the name of bound variables.
It is used with the `testable` typeclass so that
`testable (named_binder "x" (∀ x, p x))` can use the variable name
of `x` in error messages displayed to the user. If we find that instantiating
the above quantifier with 3 falsifies it, we can print:
```
==============
Problem found!
==============
x := 3
```
-/
@[simp, nolint unused_arguments]
def named_binder (n : string) (p : Prop) : Prop := p
/-- Is the given test result a failure? -/
def is_failure {p} : test_result p → bool
| (test_result.failure _ _ _) := tt
| _ := ff
instance and_testable (p q : Prop) [testable p] [testable q] :
testable (p ∧ q) :=
⟨ λ cfg min, do
xp ← testable.run p cfg min,
xq ← testable.run q cfg min,
pure $ and_counter_example xp xq ⟩
instance or_testable (p q : Prop) [testable p] [testable q] :
testable (p ∨ q) :=
⟨ λ cfg min, do
xp ← testable.run p cfg min,
match xp with
| success (psum.inl h) := pure $ success (psum.inl h)
| success (psum.inr h) := pure $ success (psum.inr $ or.inl h)
| _ := do
xq ← testable.run q cfg min,
pure $ or_counter_example xp xq
end ⟩
instance iff_testable (p q : Prop) [testable ((p ∧ q) ∨ (¬ p ∧ ¬ q))] :
testable (p ↔ q) :=
⟨ λ cfg min, do
xp ← testable.run ((p ∧ q) ∨ (¬ p ∧ ¬ q)) cfg min,
return $ convert_counter_example' (by tauto!) xp ⟩
open printable_prop
@[priority 1000]
instance dec_guard_testable (p : Prop) [printable_prop p] [decidable p] (β : p → Prop)
[∀ h, testable (β h)] : testable (named_binder var $ Π h, β h) :=
⟨ λ cfg min, do
if h : p
then
match print_prop p with
| none := (λ r, convert_counter_example ($ h) r (psum.inr $ λ q _, q)) <$>
testable.run (β h) cfg min
| some str := (λ r, add_to_counter_example (sformat!"guard: {str}") ($ h) r
(psum.inr $ λ q _, q)) <$> testable.run (β h) cfg min
end
else if cfg.trace_discarded ∨ cfg.trace_success then
match print_prop p with
| none := trace "discard" $ return $ gave_up 1
| some str := trace sformat!"discard: {str} does not hold" $ return $ gave_up 1
end
else return $ gave_up 1 ⟩
/-- Type tag that replaces a type's `has_repr` instance with its `has_to_string` instance. -/
def use_has_to_string (α : Type*) := α
instance use_has_to_string.inhabited [I : inhabited α] : inhabited (use_has_to_string α) := I
/-- Add the type tag `use_has_to_string` to an expression's type. -/
def use_has_to_string.mk {α} (x : α) : use_has_to_string α := x
instance [has_to_string α] : has_repr (use_has_to_string α) :=
⟨ @to_string α _ ⟩
@[priority 2000]
instance all_types_testable [testable (f ℤ)] : testable (named_binder var $ Π x, f x) :=
⟨ λ cfg min, do
r ← testable.run (f ℤ) cfg min,
return $ add_var_to_counter_example var (use_has_to_string.mk "ℤ") ($ ℤ) r ⟩
/-- Trace the value of sampled variables if the sample is discarded. -/
def trace_if_giveup {p α β} [has_repr α] (tracing_enabled : bool) (var : string) (val : α) :
test_result p → thunk β → β
| (test_result.gave_up _) :=
if tracing_enabled then trace (sformat!" {var} := {repr val}")
else ($ ())
| _ := ($ ())
/-- testable instance for a property iterating over the element of a list -/
@[priority 5000]
instance test_forall_in_list
[∀ x, testable (β x)] [has_repr α] :
Π xs : list α, testable (named_binder var $ ∀ x, named_binder var' $ x ∈ xs → β x)
| [] := ⟨ λ tracing min, return $ success $ psum.inr (by { introv x h, cases h} ) ⟩
| (x :: xs) :=
⟨ λ cfg min, do
r ← testable.run (β x) cfg min,
trace_if_giveup cfg.trace_discarded var x r $
match r with
| failure _ _ _ := return $ add_var_to_counter_example var x
(by { intro h, apply h, left, refl }) r
| success hp := do
rs ← @testable.run _ (test_forall_in_list xs) cfg min,
return $ convert_counter_example
(by { intros h i h',
apply h,
right, apply h' })
rs
(combine (psum.inr
$ by { intros j h, simp only [ball_cons, named_binder],
split ; assumption, } ) hp)
| gave_up n := do
rs ← @testable.run _ (test_forall_in_list xs) cfg min,
match rs with
| (success _) := return $ gave_up n
| (failure Hce xs n) := return $ failure
(by { simp only [ball_cons, named_binder],
apply not_and_of_not_right _ Hce, }) xs n
| (gave_up n') := return $ gave_up (n + n')
end
end ⟩
/-- Test proposition `p` by randomly selecting one of the provided
testable instances. -/
def combine_testable (p : Prop)
(t : list $ testable p) (h : 0 < t.length) : testable p :=
⟨ λ cfg min, have 0 < length (map (λ t, @testable.run _ t cfg min) t),
by { rw [length_map], apply h },
gen.one_of (list.map (λ t, @testable.run _ t cfg min) t) this ⟩
open sampleable_ext
/--
Format the counter-examples found in a test failure.
-/
def format_failure (s : string) (xs : list string) (n : ℕ) : string :=
let counter_ex := string.intercalate "\n" xs in
sformat!"
===================
{s}
{counter_ex}
({n} shrinks)
-------------------
"
/--
Format the counter-examples found in a test failure.
-/
def format_failure' (s : string) {p} : test_result p → string
| (success a) := ""
| (gave_up a) := ""
| (test_result.failure _ xs n) := format_failure s xs n
/--
Increase the number of shrinking steps in a test result.
-/
def add_shrinks {p} (n : ℕ) : test_result p → test_result p
| r@(success a) := r
| r@(gave_up a) := r
| (test_result.failure h vs n') := test_result.failure h vs $ n + n'
/-- Shrink a counter-example `x` by using `shrink x`, picking the first
candidate that falsifies a property and recursively shrinking that one.
The process is guaranteed to terminate because `shrink x` produces
a proof that all the values it produces are smaller (according to `sizeof`)
than `x`. -/
def minimize_aux [sampleable_ext α] [∀ x, testable (β x)] (cfg : slim_check_cfg) (var : string) :
proxy_repr α → ℕ → option_t gen (Σ x, test_result (β (interp α x))) :=
well_founded.fix has_well_founded.wf $ λ x f_rec n, do
if cfg.trace_shrink_candidates
then return $ trace sformat!
"candidates for {var} :=\n{repr (sampleable_ext.shrink x).to_list}\n" ()
else pure (),
⟨y,r,⟨h₁⟩⟩ ← (sampleable_ext.shrink x).mfirst (λ ⟨a,h⟩, do
⟨r⟩ ← monad_lift (uliftable.up $ testable.run (β (interp α a)) cfg tt
: gen (ulift $ test_result $ β $ interp α a)),
if is_failure r
then pure (⟨a, r, ⟨h⟩⟩ : (Σ a, test_result (β (interp α a)) × plift (sizeof_lt a x)))
else failure),
if cfg.trace_shrink then return $
trace (sformat!"{var} := {repr y}" ++ format_failure' "Shrink counter-example:" r) ()
else pure (),
f_rec y h₁ (n+1) <|> pure ⟨y,add_shrinks (n+1) r⟩
/-- Once a property fails to hold on an example, look for smaller counter-examples
to show the user. -/
def minimize [sampleable_ext α] [∀ x, testable (β x)] (cfg : slim_check_cfg) (var : string)
(x : proxy_repr α) (r : test_result (β (interp α x))) :
gen (Σ x, test_result (β (interp α x))) := do
if cfg.trace_shrink then return $
trace (sformat!"{var} := {repr x}" ++ format_failure' "Shrink counter-example:" r) ()
else pure (),
x' ← option_t.run $ minimize_aux α _ cfg var x 0,
pure $ x'.get_or_else ⟨x, r⟩
@[priority 2000]
instance exists_testable (p : Prop)
[testable (named_binder var (∀ x, named_binder var' $ β x → p))] :
testable (named_binder var' (named_binder var (∃ x, β x) → p)) :=
⟨ λ cfg min, do
x ← testable.run (named_binder var (∀ x, named_binder var' $ β x → p)) cfg min,
pure $ convert_counter_example' exists_imp_distrib.symm x ⟩
/-- Test a universal property by creating a sample of the right type and instantiating the
bound variable with it -/
instance var_testable [sampleable_ext α] [∀ x, testable (β x)] :
testable (named_binder var $ Π x : α, β x) :=
⟨ λ cfg min, do
uliftable.adapt_down (sampleable_ext.sample α) $
λ x, do
r ← testable.run (β (sampleable_ext.interp α x)) cfg ff,
uliftable.adapt_down (if is_failure r ∧ min
then minimize _ _ cfg var x r
else if cfg.trace_success
then trace (sformat!" {var} := {repr x}") $ pure ⟨x,r⟩
else pure ⟨x,r⟩) $
λ ⟨x,r⟩, return $ trace_if_giveup cfg.trace_discarded var x r (add_var_to_counter_example var x
($ sampleable_ext.interp α x) r) ⟩
/-- Test a universal property about propositions -/
instance prop_var_testable (β : Prop → Prop) [I : ∀ b : bool, testable (β b)] :
testable (named_binder var $ Π p : Prop, β p) :=
⟨λ cfg min, do
convert_counter_example (λ h (b : bool), h b) <$> @testable.run
(named_binder var $ Π b : bool, β b) _ cfg min⟩
@[priority 3000]
instance unused_var_testable (β) [inhabited α] [testable β] : testable (named_binder var $ Π x : α, β) :=
⟨ λ cfg min, do
r ← testable.run β cfg min,
pure $ convert_counter_example ($ default _) r (psum.inr $ λ x _, x) ⟩
@[priority 2000]
instance subtype_var_testable {p : α → Prop}
[∀ x, printable_prop (p x)]
[∀ x, testable (β x)]
[I : sampleable_ext (subtype p)] :
testable (named_binder var $ Π x : α, named_binder var' $ p x → β x) :=
⟨ λ cfg min,
do let test (x : subtype p) : testable (β x) :=
⟨ λ cfg min, do
r ← testable.run (β x.val) cfg min,
match print_prop (p x) with
| none := pure r
| some str := pure $ add_to_counter_example sformat!"guard: {str} (by construction)"
id r (psum.inr id)
end ⟩,
r ← @testable.run (∀ x : subtype p, β x.val) (@slim_check.var_testable var _ _ I test) cfg
min,
pure $ convert_counter_example'
⟨λ (h : ∀ x : subtype p, β x) x h', h ⟨x,h'⟩,
λ h ⟨x,h'⟩, h x h'⟩
r ⟩
@[priority 100]
instance decidable_testable (p : Prop) [printable_prop p] [decidable p] : testable p :=
⟨ λ cfg min, return $
if h : p then success (psum.inr h)
else
match print_prop p with
| none := failure h [] 0
| some str := failure h [sformat!"issue: {str} does not hold"] 0
end ⟩
instance eq.printable_prop {α} [has_repr α] (x y : α) : printable_prop (x = y) :=
⟨ some sformat!"{repr x} = {repr y}" ⟩
instance ne.printable_prop {α} [has_repr α] (x y : α) : printable_prop (x ≠ y) :=
⟨ some sformat!"{repr x} ≠ {repr y}" ⟩
instance le.printable_prop {α} [has_le α] [has_repr α] (x y : α) : printable_prop (x ≤ y) :=
⟨ some sformat!"{repr x} ≤ {repr y}" ⟩
instance lt.printable_prop {α} [has_lt α] [has_repr α] (x y : α) : printable_prop (x < y) :=
⟨ some sformat!"{repr x} < {repr y}" ⟩
instance perm.printable_prop {α} [has_repr α] (xs ys : list α) : printable_prop (xs ~ ys) :=
⟨ some sformat!"{repr xs} ~ {repr ys}" ⟩
instance and.printable_prop (x y : Prop) [printable_prop x] [printable_prop y] :
printable_prop (x ∧ y) :=
⟨ do x' ← print_prop x,
y' ← print_prop y,
some sformat!"({x'} ∧ {y'})" ⟩
instance or.printable_prop (x y : Prop) [printable_prop x] [printable_prop y] :
printable_prop (x ∨ y) :=
⟨ do x' ← print_prop x,
y' ← print_prop y,
some sformat!"({x'} ∨ {y'})" ⟩
instance iff.printable_prop (x y : Prop) [printable_prop x] [printable_prop y] :
printable_prop (x ↔ y) :=
⟨ do x' ← print_prop x,
y' ← print_prop y,
some sformat!"({x'} ↔ {y'})" ⟩
instance imp.printable_prop (x y : Prop) [printable_prop x] [printable_prop y] :
printable_prop (x → y) :=
⟨ do x' ← print_prop x,
y' ← print_prop y,
some sformat!"({x'} → {y'})" ⟩
instance not.printable_prop (x : Prop) [printable_prop x] : printable_prop (¬ x) :=
⟨ do x' ← print_prop x,
some sformat!"¬ {x'}" ⟩
instance true.printable_prop : printable_prop true :=
⟨ some "true" ⟩
instance false.printable_prop : printable_prop false :=
⟨ some "false" ⟩
instance bool.printable_prop (b : bool) : printable_prop b :=
⟨ some $ if b then "true" else "false" ⟩
section io
open _root_.nat
variable {p : Prop}
/-- Execute `cmd` and repeat every time the result is `gave_up` (at most
`n` times). -/
def retry (cmd : rand (test_result p)) : ℕ → rand (test_result p)
| 0 := return $ gave_up 1
| (succ n) := do
r ← cmd,
match r with
| success hp := return $ success hp
| (failure Hce xs n) := return (failure Hce xs n)
| (gave_up _) := retry n
end
/-- Count the number of times the test procedure gave up. -/
def give_up (x : ℕ) : test_result p → test_result p
| (success (psum.inl ())) := gave_up x
| (success (psum.inr p)) := success (psum.inr p)
| (gave_up n) := gave_up (n+x)
| (failure Hce xs n) := failure Hce xs n
variable (p)
variable [testable p]
/-- Try `n` times to find a counter-example for `p`. -/
def testable.run_suite_aux (cfg : slim_check_cfg) : test_result p → ℕ → rand (test_result p)
| r 0 := return r
| r (succ n) :=
do let size := (cfg.num_inst - n - 1) * cfg.max_size / cfg.num_inst,
when cfg.trace_success $ return $ trace sformat!"[slim_check: sample]" (),
x ← retry ( (testable.run p cfg tt).run ⟨ size ⟩) 10,
match x with
| (success (psum.inl ())) := testable.run_suite_aux r n
| (success (psum.inr Hp)) := return $ success (psum.inr Hp)
| (failure Hce xs n) := return (failure Hce xs n)
| (gave_up g) := testable.run_suite_aux (give_up g r) n
end
/-- Try to find a counter-example of `p`. -/
def testable.run_suite (cfg : slim_check_cfg := {}) : rand (test_result p) :=
testable.run_suite_aux p cfg (success $ psum.inl ()) cfg.num_inst
/-- Run a test suite for `p` in `io`. -/
def testable.check' (cfg : slim_check_cfg := {}) : io (test_result p) :=
match cfg.random_seed with
| some seed := io.run_rand_with seed (testable.run_suite p cfg)
| none := io.run_rand (testable.run_suite p cfg)
end
namespace tactic
open _root_.tactic expr
/-!
## Decorations
Instances of `testable` use `named_binder` as a decoration on
propositions in order to access the name of bound variables, as in
`named_binder "x" (forall x, x < y)`. This helps the
`testable` instances create useful error messages where variables
are matched with values that falsify a given proposition.
The following functions help support the gadget so that the user does
not have to put them in themselves.
-/
/-- `add_existential_decorations p` adds `a `named_binder` annotation at the
root of `p` if `p` is an existential quantification. -/
meta def add_existential_decorations : expr → expr
| e@`(@Exists %%α %%(lam n bi d b)) :=
let n := to_string n in
const ``named_binder [] (`(n) : expr) e
| e := e
/-- Traverse the syntax of a proposition to find universal quantifiers
and existential quantifiers and add `named_binder` annotations next to
them. -/
meta def add_decorations : expr → expr | e :=
e.replace $ λ e _,
match e with
| (pi n bi d b) :=
let n := to_string n in
some $ const ``named_binder [] (`(n) : expr)
(pi n bi (add_existential_decorations d) (add_decorations b))
| e := none
end
/-- `decorations_of p` is used as a hint to `mk_decorations` to specify
that the goal should be satisfied with a proposition equivalent to `p`
with added annotations. -/
@[reducible, nolint unused_arguments]
def decorations_of (p : Prop) := Prop
/-- In a goal of the shape `⊢ tactic.decorations_of p`, `mk_decoration` examines
the syntax of `p` and add `named_binder` around universal quantifications and
existential quantifications to improve error messages.
This tool can be used in the declaration of a function as follows:
```lean
def foo (p : Prop) (p' : tactic.decorations_of p . mk_decorations) [testable p'] : ...
```
`p` is the parameter given by the user, `p'` is an equivalent proposition where
the quantifiers are annotated with `named_binder`.
-/
meta def mk_decorations : tactic unit := do
`(tactic.decorations_of %%p) ← target,
exact $ add_decorations p
end tactic
/-- Run a test suite for `p` and return true or false: should we believe that `p` holds? -/
def testable.check (p : Prop) (cfg : slim_check_cfg := {})
(p' : tactic.decorations_of p . tactic.mk_decorations) [testable p'] : io punit := do
x ← match cfg.random_seed with
| some seed := io.run_rand_with seed (testable.run_suite p' cfg)
| none := io.run_rand (testable.run_suite p' cfg)
end,
match x with
| (success _) := when (¬ cfg.quiet) $ io.put_str_ln "Success"
| (gave_up n) := io.fail sformat!"Gave up {repr n} times"
| (failure _ xs n) := do
io.fail $ format_failure "Found problems!" xs n
end
end io
end slim_check
|
1f7f3608f513109fed947f082303778b65fe87c9 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/solve_by_elim.lean | 0a2804b8181f9f30d2ddf1d84e606ed126bbb68d | [] | 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 | 9,486 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Scott Morrison
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.core
import Mathlib.PostPort
namespace Mathlib
/-!
# solve_by_elim
A depth-first search backwards reasoner.
`solve_by_elim` takes a list of lemmas, and repeating tries to `apply` these against
the goals, recursively acting on any generated subgoals.
It accepts a variety of configuration options described below, enabling
* backtracking across multiple goals,
* pruning the search tree, and
* invoking other tactics before or after trying to apply lemmas.
At present it has no "premise selection", and simply tries the supplied lemmas in order
at each step of the search.
-/
namespace tactic
namespace solve_by_elim
/--
`mk_assumption_set` builds a collection of lemmas for use in
the backtracking search in `solve_by_elim`.
* By default, it includes all local hypotheses, along with `rfl`, `trivial`, `congr_fun` and
`congr_arg`.
* The flag `no_dflt` removes these.
* The argument `hs` is a list of `simp_arg_type`s,
and can be used to add, or remove, lemmas or expressions from the set.
* The argument `attr : list name` adds all lemmas tagged with one of a specified list of attributes.
`mk_assumption_set` returns not a `list expr`, but a `list (tactic expr) × tactic (list expr)`.
There are two separate problems that need to be solved.
### Relevant local hypotheses
`solve_by_elim*` works with multiple goals,
and we need to use separate sets of local hypotheses for each goal.
The second component of the returned value provides these local hypotheses.
(Essentially using `local_context`, along with some filtering to remove hypotheses
that have been explicitly removed via `only` or `[-h]`.)
### Stuck metavariables
Lemmas with implicit arguments would be filled in with metavariables if we created the
`expr` objects immediately, so instead we return thunks that generate the expressions
on demand. This is the first component, with type `list (tactic expr)`.
As an example, we have `def rfl : ∀ {α : Sort u} {a : α}, a = a`, which on elaboration will become
`@rfl ?m_1 ?m_2`.
Because `solve_by_elim` works by repeated application of lemmas against subgoals,
the first time such a lemma is successfully applied,
those metavariables will be unified, and thereafter have fixed values.
This would make it impossible to apply the lemma
a second time with different values of the metavariables.
See https://github.com/leanprover-community/mathlib/issues/2269
As an optimisation, after we build the list of `tactic expr`s, we actually run them, and replace any
that do not in fact produce metavariables with a simple `return` tactic.
-/
-- We lock the tactic state so that any spurious goals generated during
-- elaboration of pre-expressions are discarded
/--
Configuration options for `solve_by_elim`.
* `accept : list expr → tactic unit` determines whether the current branch should be explored.
At each step, before the lemmas are applied,
`accept` is passed the proof terms for the original goals,
as reported by `get_goals` when `solve_by_elim` started.
These proof terms may be metavariables (if no progress has been made on that goal)
or may contain metavariables at some leaf nodes
(if the goal has been partially solved by previous `apply` steps).
If the `accept` tactic fails `solve_by_elim` aborts searching this branch and backtracks.
By default `accept := λ _, skip` always succeeds.
(There is an example usage in `tests/solve_by_elim.lean`.)
* `pre_apply : tactic unit` specifies an additional tactic to run before each round of `apply`.
* `discharger : tactic unit` specifies an additional tactic to apply on subgoals
for which no lemma applies.
If that tactic succeeds, `solve_by_elim` will continue applying lemmas on resulting goals.
-/
/--
A helper function for trace messages, prepending '....' depending on the current search depth.
-/
/-- A helper function to generate trace messages on successful applications. -/
/-- A helper function to generate trace messages on unsuccessful applications. -/
/--
A helper function to generate the tactic that print trace messages.
This function exists to ensure the target is pretty printed only as necessary.
-/
/--
The internal implementation of `solve_by_elim`, with a limiting counter.
-/
/--
Arguments for `solve_by_elim`:
* By default `solve_by_elim` operates only on the first goal,
but with `backtrack_all_goals := true`, it operates on all goals at once,
backtracking across goals as needed,
and only succeeds if it discharges all goals.
* `lemmas` specifies the list of lemmas to use in the backtracking search.
If `none`, `solve_by_elim` uses the local hypotheses,
along with `rfl`, `trivial`, `congr_arg`, and `congr_fun`.
* `lemma_thunks` provides the lemmas as a list of `tactic expr`,
which are used to regenerate the `expr` objects to avoid binding metavariables.
It should not usually be specified by the user.
(If both `lemmas` and `lemma_thunks` are specified, only `lemma_thunks` is used.)
* `ctx_thunk` is for internal use only: it returns the local hypotheses which will be used.
* `max_depth` bounds the depth of the search.
-/
/--
If no lemmas have been specified, generate the default set
(local hypotheses, along with `rfl`, `trivial`, `congr_arg`, and `congr_fun`).
-/
end solve_by_elim
/--
`solve_by_elim` repeatedly tries `apply`ing a lemma
from the list of assumptions (passed via the `opt` argument),
recursively operating on any generated subgoals, backtracking as necessary.
`solve_by_elim` succeeds only if it discharges the goal.
(By default, `solve_by_elim` focuses on the first goal, and only attempts to solve that.
With the option `backtrack_all_goals := tt`,
it attempts to solve all goals, and only succeeds if it does so.
With `backtrack_all_goals := tt`, `solve_by_elim` will backtrack a solution it has found for
one goal if it then can't discharge other goals.)
If passed an empty list of assumptions, `solve_by_elim` builds a default set
as per the interactive tactic, using the `local_context` along with
`rfl`, `trivial`, `congr_arg`, and `congr_fun`.
To pass a particular list of assumptions, use the `lemmas` field
in the configuration argument. This expects an
`option (list expr)`. In certain situations it may be necessary to instead use the
`lemma_thunks` field, which expects a `option (list (tactic expr))`.
This allows for regenerating metavariables
for each application, which might otherwise get stuck.
See also the simpler tactic `apply_rules`, which does not perform backtracking.
-/
namespace interactive
/--
`apply_assumption` looks for an assumption of the form `... → ∀ _, ... → head`
where `head` matches the current goal.
If this fails, `apply_assumption` will call `symmetry` and try again.
If this also fails, `apply_assumption` will call `exfalso` and try again,
so that if there is an assumption of the form `P → ¬ Q`, the new tactic state
will have two goals, `P` and `Q`.
Optional arguments:
- `lemmas`: a list of expressions to apply, instead of the local constants
- `tac`: a tactic to run on each subgoal after applying an assumption; if
this tactic fails, the corresponding assumption will be rejected and
the next one will be attempted.
-/
/--
`solve_by_elim` calls `apply` on the main goal to find an assumption whose head matches
and then repeatedly calls `apply` on the generated subgoals until no subgoals remain,
performing at most `max_depth` recursive steps.
`solve_by_elim` discharges the current goal or fails.
`solve_by_elim` performs back-tracking if subgoals can not be solved.
By default, the assumptions passed to `apply` are the local context, `rfl`, `trivial`,
`congr_fun` and `congr_arg`.
The assumptions can be modified with similar syntax as for `simp`:
* `solve_by_elim [h₁, h₂, ..., hᵣ]` also applies the named lemmas.
* `solve_by_elim with attr₁ ... attrᵣ` also applies all lemmas tagged with the specified attributes.
* `solve_by_elim only [h₁, h₂, ..., hᵣ]` does not include the local context,
`rfl`, `trivial`, `congr_fun`, or `congr_arg` unless they are explicitly included.
* `solve_by_elim [-id_1, ... -id_n]` uses the default assumptions, removing the specified ones.
`solve_by_elim*` tries to solve all goals together, using backtracking if a solution for one goal
makes other goals impossible.
optional arguments passed via a configuration argument as `solve_by_elim { ... }`
- max_depth: number of attempts at discharging generated sub-goals
- discharger: a subsidiary tactic to try at each step when no lemmas apply
(e.g. `cc` may be helpful).
- pre_apply: a subsidiary tactic to run at each step before applying lemmas (e.g. `intros`).
- accept: a subsidiary tactic `list expr → tactic unit` that at each step,
before any lemmas are applied, is passed the original proof terms
as reported by `get_goals` when `solve_by_elim` started
(but which may by now have been partially solved by previous `apply` steps).
If the `accept` tactic fails,
`solve_by_elim` will abort searching the current branch and backtrack.
This may be used to filter results, either at every step of the search,
or filtering complete results
(by testing for the absence of metavariables, and then the filtering condition).
-/
|
69c8c980ee83a7117c14d17df2f3406df3ad5d97 | a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7 | /src/ring_theory/algebra.lean | 7a7856c4e341fd6ff1603a7a7de665863952c732 | [
"Apache-2.0"
] | permissive | kmill/mathlib | ea5a007b67ae4e9e18dd50d31d8aa60f650425ee | 1a419a9fea7b959317eddd556e1bb9639f4dcc05 | refs/heads/master | 1,668,578,197,719 | 1,593,629,163,000 | 1,593,629,163,000 | 276,482,939 | 0 | 0 | null | 1,593,637,960,000 | 1,593,637,959,000 | null | UTF-8 | Lean | false | false | 35,020 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Yury Kudryashov
-/
import data.matrix.basic
import linear_algebra.tensor_product
import data.equiv.ring
/-!
# Algebra over Commutative Semiring (under category)
In this file we define algebra over commutative (semi)rings, algebra homomorphisms `alg_hom`,
algebra equivalences `alg_equiv`, and `subalgebra`s. We also define usual operations on `alg_hom`s
(`id`, `comp`) and subalgebras (`map`, `comap`).
## Notations
* `A →ₐ[R] B` : `R`-algebra homomorphism from `A` to `B`.
* `A ≃ₐ[R] B` : `R`-algebra equivalence from `A` to `B`.
-/
noncomputable theory
universes u v w u₁ v₁
open_locale tensor_product big_operators
section prio
-- We set this priority to 0 later in this file
set_option default_priority 200 -- see Note [default priority]
/-- The category of R-algebras where R is a commutative
ring is the under category R ↓ CRing. In the categorical
setting we have a forgetful functor R-Alg ⥤ R-Mod.
However here it extends module in order to preserve
definitional equality in certain cases. -/
@[nolint has_inhabited_instance]
class algebra (R : Type u) (A : Type v) [comm_semiring R] [semiring A]
extends has_scalar R A, R →+* A :=
(commutes' : ∀ r x, to_fun r * x = x * to_fun r)
(smul_def' : ∀ r x, r • x = to_fun r * x)
end prio
/-- Embedding `R →+* A` given by `algebra` structure. -/
def algebra_map (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] : R →+* A :=
algebra.to_ring_hom
/-- Creating an algebra from a morphism to the center of a semiring. -/
def ring_hom.to_algebra' {R S} [comm_semiring R] [semiring S] (i : R →+* S)
(h : ∀ c x, i c * x = x * i c) :
algebra R S :=
{ smul := λ c x, i c * x,
commutes' := h,
smul_def' := λ c x, rfl,
.. i}
/-- Creating an algebra from a morphism to a commutative semiring. -/
def ring_hom.to_algebra {R S} [comm_semiring R] [comm_semiring S] (i : R →+* S) :
algebra R S :=
i.to_algebra' $ λ _, mul_comm _
namespace algebra
variables {R : Type u} {S : Type v} {A : Type w}
/-- Let `R` be a commutative semiring, let `A` be a semiring with a `semimodule R` structure.
If `(r • 1) * x = x * (r • 1) = r • x` for all `r : R` and `x : A`, then `A` is an `algebra`
over `R`. -/
def of_semimodule' [comm_semiring R] [semiring A] [semimodule R A]
(h₁ : ∀ (r : R) (x : A), (r • 1) * x = r • x)
(h₂ : ∀ (r : R) (x : A), x * (r • 1) = r • x) : algebra R A :=
{ to_fun := λ r, r • 1,
map_one' := one_smul _ _,
map_mul' := λ r₁ r₂, by rw [h₁, mul_smul],
map_zero' := zero_smul _ _,
map_add' := λ r₁ r₂, add_smul r₁ r₂ 1,
commutes' := λ r x, by simp only [h₁, h₂],
smul_def' := λ r x, by simp only [h₁] }
/-- Let `R` be a commutative semiring, let `A` be a semiring with a `semimodule R` structure.
If `(r • x) * y = x * (r • y) = r • (x * y)` for all `r : R` and `x y : A`, then `A`
is an `algebra` over `R`. -/
def of_semimodule [comm_semiring R] [semiring A] [semimodule R A]
(h₁ : ∀ (r : R) (x y : A), (r • x) * y = r • (x * y))
(h₂ : ∀ (r : R) (x y : A), x * (r • y) = r • (x * y)) : algebra R A :=
of_semimodule' (λ r x, by rw [h₁, one_mul]) (λ r x, by rw [h₂, mul_one])
section semiring
variables [comm_semiring R] [comm_semiring S] [semiring A] [algebra R A]
lemma smul_def'' (r : R) (x : A) : r • x = algebra_map R A r * x :=
algebra.smul_def' r x
@[priority 200] -- see Note [lower instance priority]
instance to_semimodule : semimodule R A :=
{ one_smul := by simp [smul_def''],
mul_smul := by simp [smul_def'', mul_assoc],
smul_add := by simp [smul_def'', mul_add],
smul_zero := by simp [smul_def''],
add_smul := by simp [smul_def'', add_mul],
zero_smul := by simp [smul_def''] }
-- from now on, we don't want to use the following instance anymore
attribute [instance, priority 0] algebra.to_has_scalar
lemma smul_def (r : R) (x : A) : r • x = algebra_map R A r * x :=
algebra.smul_def' r x
lemma algebra_map_eq_smul_one (r : R) : algebra_map R A r = r • 1 :=
calc algebra_map R A r = algebra_map R A r * 1 : (mul_one _).symm
... = r • 1 : (algebra.smul_def r 1).symm
theorem commutes (r : R) (x : A) : algebra_map R A r * x = x * algebra_map R A r :=
algebra.commutes' r x
theorem left_comm (r : R) (x y : A) : x * (algebra_map R A r * y) = algebra_map R A r * (x * y) :=
by rw [← mul_assoc, ← commutes, mul_assoc]
@[simp] lemma mul_smul_comm (s : R) (x y : A) :
x * (s • y) = s • (x * y) :=
by rw [smul_def, smul_def, left_comm]
@[simp] lemma smul_mul_assoc (r : R) (x y : A) :
(r • x) * y = r • (x * y) :=
by rw [smul_def, smul_def, mul_assoc]
end semiring
-- TODO (semimodule linear maps): once we have them, port next section to semirings
section ring
variables [comm_ring R] [ring A] [algebra R A]
/-- Creating an algebra from a subring. This is the dual of ring extension. -/
instance of_subring (S : set R) [is_subring S] : algebra S R :=
ring_hom.to_algebra ⟨coe, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩
variables (R A)
/-- The multiplication in an algebra is a bilinear map. -/
def lmul : A →ₗ A →ₗ A :=
linear_map.mk₂ R (*)
(λ x y z, add_mul x y z)
(λ c x y, by rw [smul_def, smul_def, mul_assoc _ x y])
(λ x y z, mul_add x y z)
(λ c x y, by rw [smul_def, smul_def, left_comm])
/-- The multiplication on the left in an algebra is a linear map. -/
def lmul_left (r : A) : A →ₗ A :=
lmul R A r
/-- The multiplication on the right in an algebra is a linear map. -/
def lmul_right (r : A) : A →ₗ A :=
(lmul R A).flip r
variables {R A}
@[simp] lemma lmul_apply (p q : A) : lmul R A p q = p * q := rfl
@[simp] lemma lmul_left_apply (p q : A) : lmul_left R A p q = p * q := rfl
@[simp] lemma lmul_right_apply (p q : A) : lmul_right R A p q = q * p := rfl
end ring
end algebra
instance module.endomorphism_algebra (R : Type u) (M : Type v)
[comm_ring R] [add_comm_group M] [module R M] : algebra R (M →ₗ[R] M) :=
{ to_fun := λ r, r • linear_map.id,
map_one' := one_smul _ _,
map_zero' := zero_smul _ _,
map_add' := λ r₁ r₂, add_smul _ _ _,
map_mul' := λ r₁ r₂, by { ext x, simp [mul_smul] },
commutes' := by { intros, ext, simp },
smul_def' := by { intros, ext, simp } }
instance matrix_algebra (n : Type u) (R : Type v)
[fintype n] [decidable_eq n] [comm_semiring R] : algebra R (matrix n n R) :=
{ commutes' := by { intros, simp [matrix.scalar], },
smul_def' := by { intros, simp [matrix.scalar], },
..(matrix.scalar n) }
set_option old_structure_cmd true
/-- Defining the homomorphism in the category R-Alg. -/
@[nolint has_inhabited_instance]
structure alg_hom (R : Type u) (A : Type v) (B : Type w)
[comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends ring_hom A B :=
(commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r)
run_cmd tactic.add_doc_string `alg_hom.to_ring_hom "Reinterpret an `alg_hom` as a `ring_hom`"
infixr ` →ₐ `:25 := alg_hom _
notation A ` →ₐ[`:25 R `] ` B := alg_hom R A B
namespace alg_hom
variables {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} {D : Type v₁}
section semiring
variables [comm_semiring R] [semiring A] [semiring B] [semiring C] [semiring D]
variables [algebra R A] [algebra R B] [algebra R C] [algebra R D]
instance : has_coe_to_fun (A →ₐ[R] B) := ⟨_, λ f, f.to_fun⟩
instance coe_ring_hom : has_coe (A →ₐ[R] B) (A →+* B) := ⟨alg_hom.to_ring_hom⟩
instance coe_monoid_hom : has_coe (A →ₐ[R] B) (A →* B) := ⟨λ f, ↑(f : A →+* B)⟩
instance coe_add_monoid_hom : has_coe (A →ₐ[R] B) (A →+ B) := ⟨λ f, ↑(f : A →+* B)⟩
@[simp, norm_cast] lemma coe_mk {f : A → B} (h₁ h₂ h₃ h₄ h₅) :
⇑(⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →ₐ[R] B) = f := rfl
@[simp, norm_cast] lemma coe_to_ring_hom (f : A →ₐ[R] B) : ⇑(f : A →+* B) = f := rfl
-- as `simp` can already prove this lemma, it is not tagged with the `simp` attribute.
@[norm_cast] lemma coe_to_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →* B) = f := rfl
-- as `simp` can already prove this lemma, it is not tagged with the `simp` attribute.
@[norm_cast] lemma coe_to_add_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →+ B) = f := rfl
variables (φ : A →ₐ[R] B)
theorem coe_fn_inj ⦃φ₁ φ₂ : A →ₐ[R] B⦄ (H : ⇑φ₁ = φ₂) : φ₁ = φ₂ :=
by { cases φ₁, cases φ₂, congr, exact H }
theorem coe_ring_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+* B)) :=
λ φ₁ φ₂ H, coe_fn_inj $ show ((φ₁ : (A →+* B)) : A → B) = ((φ₂ : (A →+* B)) : A → B),
from congr_arg _ H
theorem coe_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →* B)) :=
ring_hom.coe_monoid_hom_injective.comp coe_ring_hom_injective
theorem coe_add_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+ B)) :=
ring_hom.coe_add_monoid_hom_injective.comp coe_ring_hom_injective
@[ext]
theorem ext {φ₁ φ₂ : A →ₐ[R] B} (H : ∀ x, φ₁ x = φ₂ x) : φ₁ = φ₂ :=
coe_fn_inj $ funext H
theorem ext_iff {φ₁ φ₂ : A →ₐ[R] B} : φ₁ = φ₂ ↔ ∀ x, φ₁ x = φ₂ x :=
⟨by { rintro rfl x, refl }, ext⟩
@[simp]
theorem commutes (r : R) : φ (algebra_map R A r) = algebra_map R B r := φ.commutes' r
theorem comp_algebra_map : φ.to_ring_hom.comp (algebra_map R A) = algebra_map R B :=
ring_hom.ext $ φ.commutes
@[simp] lemma map_add (r s : A) : φ (r + s) = φ r + φ s :=
φ.to_ring_hom.map_add r s
@[simp] lemma map_zero : φ 0 = 0 :=
φ.to_ring_hom.map_zero
@[simp] lemma map_mul (x y) : φ (x * y) = φ x * φ y :=
φ.to_ring_hom.map_mul x y
@[simp] lemma map_one : φ 1 = 1 :=
φ.to_ring_hom.map_one
@[simp] lemma map_smul (r : R) (x : A) : φ (r • x) = r • φ x :=
by simp only [algebra.smul_def, map_mul, commutes]
@[simp] lemma map_pow (x : A) (n : ℕ) : φ (x ^ n) = (φ x) ^ n :=
φ.to_ring_hom.map_pow x n
lemma map_sum {ι : Type*} (f : ι → A) (s : finset ι) :
φ (∑ x in s, f x) = ∑ x in s, φ (f x) :=
φ.to_ring_hom.map_sum f s
@[simp] lemma map_nat_cast (n : ℕ) : φ n = n :=
φ.to_ring_hom.map_nat_cast n
section
variables (R A)
/-- Identity map as an `alg_hom`. -/
protected def id : A →ₐ[R] A :=
{ commutes' := λ _, rfl,
..ring_hom.id A }
end
@[simp] lemma id_apply (p : A) : alg_hom.id R A p = p := rfl
/-- Composition of algebra homeomorphisms. -/
def comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : A →ₐ[R] C :=
{ commutes' := λ r : R, by rw [← φ₁.commutes, ← φ₂.commutes]; refl,
.. φ₁.to_ring_hom.comp ↑φ₂ }
@[simp] lemma comp_apply (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) (p : A) :
φ₁.comp φ₂ p = φ₁ (φ₂ p) := rfl
@[simp] theorem comp_id : φ.comp (alg_hom.id R A) = φ :=
ext $ λ x, rfl
@[simp] theorem id_comp : (alg_hom.id R B).comp φ = φ :=
ext $ λ x, rfl
theorem comp_assoc (φ₁ : C →ₐ[R] D) (φ₂ : B →ₐ[R] C) (φ₃ : A →ₐ[R] B) :
(φ₁.comp φ₂).comp φ₃ = φ₁.comp (φ₂.comp φ₃) :=
ext $ λ x, rfl
end semiring
section comm_semiring
variables [comm_semiring R] [comm_semiring A] [comm_semiring B]
variables [algebra R A] [algebra R B]
variables (φ : A →ₐ[R] B)
lemma map_prod {ι : Type*} (f : ι → A) (s : finset ι) :
φ (∏ x in s, f x) = ∏ x in s, φ (f x) :=
φ.to_ring_hom.map_prod f s
end comm_semiring
variables [comm_ring R] [ring A] [ring B] [ring C]
variables [algebra R A] [algebra R B] [algebra R C] (φ : A →ₐ[R] B)
@[simp] lemma map_neg (x) : φ (-x) = -φ x :=
φ.to_ring_hom.map_neg x
@[simp] lemma map_sub (x y) : φ (x - y) = φ x - φ y :=
φ.to_ring_hom.map_sub x y
/-- R-Alg ⥤ R-Mod -/
def to_linear_map : A →ₗ B :=
{ to_fun := φ,
map_add' := φ.map_add,
map_smul' := φ.map_smul }
@[simp] lemma to_linear_map_apply (p : A) : φ.to_linear_map p = φ p := rfl
theorem to_linear_map_inj {φ₁ φ₂ : A →ₐ[R] B} (H : φ₁.to_linear_map = φ₂.to_linear_map) : φ₁ = φ₂ :=
ext $ λ x, show φ₁.to_linear_map x = φ₂.to_linear_map x, by rw H
@[simp] lemma comp_to_linear_map (f : A →ₐ[R] B) (g : B →ₐ[R] C) :
(g.comp f).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl
end alg_hom
set_option old_structure_cmd true
/-- An equivalence of algebras is an equivalence of rings commuting with the actions of scalars. -/
structure alg_equiv (R : Type u) (A : Type v) (B : Type w)
[comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B]
extends A ≃ B, A ≃* B, A ≃+ B, A ≃+* B :=
(commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r)
attribute [nolint doc_blame] alg_equiv.to_ring_equiv
attribute [nolint doc_blame] alg_equiv.to_equiv
attribute [nolint doc_blame] alg_equiv.to_add_equiv
attribute [nolint doc_blame] alg_equiv.to_mul_equiv
notation A ` ≃ₐ[`:50 R `] ` A' := alg_equiv R A A'
namespace alg_equiv
variables {R : Type u} {A₁ : Type v} {A₂ : Type w} {A₃ : Type u₁}
variables [comm_semiring R] [semiring A₁] [semiring A₂] [semiring A₃]
variables [algebra R A₁] [algebra R A₂] [algebra R A₃]
instance : has_coe_to_fun (A₁ ≃ₐ[R] A₂) := ⟨_, alg_equiv.to_fun⟩
@[ext]
lemma ext {f g : A₁ ≃ₐ[R] A₂} (h : ∀ a, f a = g a) : f = g :=
begin
have h₁ : f.to_equiv = g.to_equiv := equiv.ext h,
cases f, cases g, congr,
{ exact (funext h) },
{ exact congr_arg equiv.inv_fun h₁ }
end
lemma coe_fun_injective : @function.injective (A₁ ≃ₐ[R] A₂) (A₁ → A₂) (λ e, (e : A₁ → A₂)) :=
begin
intros f g w,
ext,
exact congr_fun w a,
end
instance has_coe_to_ring_equiv : has_coe (A₁ ≃ₐ[R] A₂) (A₁ ≃+* A₂) := ⟨alg_equiv.to_ring_equiv⟩
@[simp] lemma mk_apply {to_fun inv_fun left_inv right_inv map_mul map_add commutes a} :
(⟨to_fun, inv_fun, left_inv, right_inv, map_mul, map_add, commutes⟩ : A₁ ≃ₐ[R] A₂) a = to_fun a :=
rfl
@[simp] lemma to_fun_apply {e : A₁ ≃ₐ[R] A₂} {a : A₁} : e.to_fun a = e a := rfl
@[simp, norm_cast] lemma coe_ring_equiv (e : A₁ ≃ₐ[R] A₂) : ((e : A₁ ≃+* A₂) : A₁ → A₂) = e := rfl
lemma coe_ring_equiv_injective : function.injective (λ e : A₁ ≃ₐ[R] A₂, (e : A₁ ≃+* A₂)) :=
begin
intros f g w,
ext,
replace w : ((f : A₁ ≃+* A₂) : A₁ → A₂) = ((g : A₁ ≃+* A₂) : A₁ → A₂) :=
congr_arg (λ e : A₁ ≃+* A₂, (e : A₁ → A₂)) w,
exact congr_fun w a,
end
@[simp] lemma map_add (e : A₁ ≃ₐ[R] A₂) : ∀ x y, e (x + y) = e x + e y := e.to_add_equiv.map_add
@[simp] lemma map_zero (e : A₁ ≃ₐ[R] A₂) : e 0 = 0 := e.to_add_equiv.map_zero
@[simp] lemma map_mul (e : A₁ ≃ₐ[R] A₂) : ∀ x y, e (x * y) = (e x) * (e y) := e.to_mul_equiv.map_mul
@[simp] lemma map_one (e : A₁ ≃ₐ[R] A₂) : e 1 = 1 := e.to_mul_equiv.map_one
@[simp] lemma commutes (e : A₁ ≃ₐ[R] A₂) : ∀ (r : R), e (algebra_map R A₁ r) = algebra_map R A₂ r :=
e.commutes'
@[simp] lemma map_neg {A₁ : Type v} {A₂ : Type w}
[ring A₁] [ring A₂] [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) :
∀ x, e (-x) = -(e x) := e.to_add_equiv.map_neg
@[simp] lemma map_sub {A₁ : Type v} {A₂ : Type w}
[ring A₁] [ring A₂] [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) :
∀ x y, e (x - y) = e x - e y := e.to_add_equiv.map_sub
lemma map_sum (e : A₁ ≃ₐ[R] A₂) {ι : Type*} (f : ι → A₁) (s : finset ι) :
e (∑ x in s, f x) = ∑ x in s, e (f x) :=
e.to_add_equiv.map_sum f s
instance has_coe_to_alg_hom : has_coe (A₁ ≃ₐ[R] A₂) (A₁ →ₐ[R] A₂) :=
⟨λ e, { map_one' := e.map_one, map_zero' := e.map_zero, ..e }⟩
@[simp, norm_cast] lemma coe_alg_hom (e : A₁ ≃ₐ[R] A₂) : ((e : A₁ →ₐ[R] A₂) : A₁ → A₂) = e :=
rfl
lemma injective (e : A₁ ≃ₐ[R] A₂) : function.injective e := e.to_equiv.injective
lemma surjective (e : A₁ ≃ₐ[R] A₂) : function.surjective e := e.to_equiv.surjective
lemma bijective (e : A₁ ≃ₐ[R] A₂) : function.bijective e := e.to_equiv.bijective
instance : has_one (A₁ ≃ₐ[R] A₁) := ⟨{commutes' := λ r, rfl, ..(1 : A₁ ≃+* A₁)}⟩
instance : inhabited (A₁ ≃ₐ[R] A₁) := ⟨1⟩
/-- Algebra equivalences are reflexive. -/
@[refl]
def refl : A₁ ≃ₐ[R] A₁ := 1
@[simp] lemma coe_refl : (@refl R A₁ _ _ _ : A₁ →ₐ[R] A₁) = alg_hom.id R A₁ :=
alg_hom.ext (λ x, rfl)
/-- Algebra equivalences are symmetric. -/
@[symm]
def symm (e : A₁ ≃ₐ[R] A₂) : A₂ ≃ₐ[R] A₁ :=
{ commutes' := λ r, by { rw ←e.to_ring_equiv.symm_apply_apply (algebra_map R A₁ r), congr,
change _ = e _, rw e.commutes, },
..e.to_ring_equiv.symm, }
@[simp] lemma inv_fun_apply {e : A₁ ≃ₐ[R] A₂} {a : A₂} : e.inv_fun a = e.symm a := rfl
@[simp] lemma symm_symm {e : A₁ ≃ₐ[R] A₂} : e.symm.symm = e :=
by { ext, refl, }
/-- Algebra equivalences are transitive. -/
@[trans]
def trans (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) : A₁ ≃ₐ[R] A₃ :=
{ commutes' := λ r, show e₂.to_fun (e₁.to_fun _) = _, by rw [e₁.commutes', e₂.commutes'],
..(e₁.to_ring_equiv.trans e₂.to_ring_equiv), }
@[simp] lemma apply_symm_apply (e : A₁ ≃ₐ[R] A₂) : ∀ x, e (e.symm x) = x :=
e.to_equiv.apply_symm_apply
@[simp] lemma symm_apply_apply (e : A₁ ≃ₐ[R] A₂) : ∀ x, e.symm (e x) = x :=
e.to_equiv.symm_apply_apply
@[simp] lemma trans_apply (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) (x : A₁) :
(e₁.trans e₂) x = e₂ (e₁ x) := rfl
@[simp] lemma comp_symm (e : A₁ ≃ₐ[R] A₂) :
alg_hom.comp (e : A₁ →ₐ[R] A₂) ↑e.symm = alg_hom.id R A₂ :=
by { ext, simp }
@[simp] lemma symm_comp (e : A₁ ≃ₐ[R] A₂) :
alg_hom.comp ↑e.symm (e : A₁ →ₐ[R] A₂) = alg_hom.id R A₁ :=
by { ext, simp }
/-- If an algebra morphism has an inverse, it is a algebra isomorphism. -/
def of_alg_hom (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ : f.comp g = alg_hom.id R A₂) (h₂ : g.comp f = alg_hom.id R A₁) : A₁ ≃ₐ[R] A₂ :=
{ inv_fun := g,
left_inv := alg_hom.ext_iff.1 h₂,
right_inv := alg_hom.ext_iff.1 h₁,
..f }
end alg_equiv
namespace algebra
variables (R : Type u) (S : Type v) (A : Type w)
include R S A
/-- `comap R S A` is a type alias for `A`, and has an R-algebra structure defined on it
when `algebra R S` and `algebra S A`. -/
/- This is done to avoid a type class search with meta-variables `algebra R ?m_1` and
`algebra ?m_1 A -/
/- The `nolint` attribute is added because it has unused arguments `R` and `S`, but these are necessary for synthesizing the
appropriate type classes -/
@[nolint unused_arguments]
def comap : Type w := A
instance comap.inhabited [h : inhabited A] : inhabited (comap R S A) := h
instance comap.semiring [h : semiring A] : semiring (comap R S A) := h
instance comap.ring [h : ring A] : ring (comap R S A) := h
instance comap.comm_semiring [h : comm_semiring A] : comm_semiring (comap R S A) := h
instance comap.comm_ring [h : comm_ring A] : comm_ring (comap R S A) := h
instance comap.algebra' [comm_semiring S] [semiring A] [h : algebra S A] :
algebra S (comap R S A) := h
/-- Identity homomorphism `A →ₐ[S] comap R S A`. -/
def comap.to_comap [comm_semiring S] [semiring A] [algebra S A] :
A →ₐ[S] comap R S A := alg_hom.id S A
/-- Identity homomorphism `comap R S A →ₐ[S] A`. -/
def comap.of_comap [comm_semiring S] [semiring A] [algebra S A] :
comap R S A →ₐ[S] A := alg_hom.id S A
variables [comm_semiring R] [comm_semiring S] [semiring A] [algebra R S] [algebra S A]
/-- `R ⟶ S` induces `S-Alg ⥤ R-Alg` -/
instance comap.algebra : algebra R (comap R S A) :=
{ smul := λ r x, (algebra_map R S r • x : A),
commutes' := λ r x, algebra.commutes _ _,
smul_def' := λ _ _, algebra.smul_def _ _,
.. (algebra_map S A).comp (algebra_map R S) }
/-- Embedding of `S` into `comap R S A`. -/
def to_comap : S →ₐ[R] comap R S A :=
{ commutes' := λ r, rfl,
.. algebra_map S A }
theorem to_comap_apply (x) : to_comap R S A x = algebra_map S A x := rfl
end algebra
namespace alg_hom
variables {R : Type u} {S : Type v} {A : Type w} {B : Type u₁}
variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B]
variables [algebra R S] [algebra S A] [algebra S B] (φ : A →ₐ[S] B)
include R
/-- R ⟶ S induces S-Alg ⥤ R-Alg -/
def comap : algebra.comap R S A →ₐ[R] algebra.comap R S B :=
{ commutes' := λ r, φ.commutes (algebra_map R S r)
..φ }
end alg_hom
namespace rat
instance algebra_rat {α} [division_ring α] [char_zero α] : algebra ℚ α :=
(rat.cast_hom α).to_algebra' $ λ r x, r.cast_commute x
end rat
/-- A subalgebra is a subring that includes the range of `algebra_map`. -/
structure subalgebra (R : Type u) (A : Type v)
[comm_ring R] [ring A] [algebra R A] : Type v :=
(carrier : set A) [subring : is_subring carrier]
(range_le' : set.range (algebra_map R A) ≤ carrier)
namespace subalgebra
variables {R : Type u} {A : Type v}
variables [comm_ring R] [ring A] [algebra R A]
include R
instance : has_coe (subalgebra R A) (set A) :=
⟨λ S, S.carrier⟩
lemma range_le (S : subalgebra R A) : set.range (algebra_map R A) ≤ S := S.range_le'
instance : has_mem A (subalgebra R A) :=
⟨λ x S, x ∈ (S : set A)⟩
variables {A}
theorem mem_coe {x : A} {s : subalgebra R A} : x ∈ (s : set A) ↔ x ∈ s :=
iff.rfl
@[ext] theorem ext {S T : subalgebra R A}
(h : ∀ x : A, x ∈ S ↔ x ∈ T) : S = T :=
by cases S; cases T; congr; ext x; exact h x
theorem ext_iff {S T : subalgebra R A} : S = T ↔ ∀ x : A, x ∈ S ↔ x ∈ T :=
⟨λ h x, by rw h, ext⟩
variables (S : subalgebra R A)
instance : is_subring (S : set A) := S.subring
instance : ring S := @@subtype.ring _ S.is_subring
instance : inhabited S := ⟨0⟩
instance (R : Type u) (A : Type v) [comm_ring R] [comm_ring A]
[algebra R A] (S : subalgebra R A) : comm_ring S := @@subtype.comm_ring _ S.is_subring
instance algebra : algebra R S :=
{ smul := λ (c:R) x, ⟨c • x.1,
by rw algebra.smul_def; exact @@is_submonoid.mul_mem _ S.2.2 (S.3 ⟨c, rfl⟩) x.2⟩,
commutes' := λ c x, subtype.eq $ algebra.commutes _ _,
smul_def' := λ c x, subtype.eq $ algebra.smul_def _ _,
.. (algebra_map R A).cod_restrict S $ λ x, S.range_le ⟨x, rfl⟩ }
instance to_algebra (R : Type u) (A : Type v) [comm_ring R] [comm_ring A]
[algebra R A] (S : subalgebra R A) : algebra S A :=
algebra.of_subring _
/-- Embedding of a subalgebra into the algebra. -/
def val : S →ₐ[R] A :=
by refine_struct { to_fun := subtype.val }; intros; refl
/-- Convert a `subalgebra` to `submodule` -/
def to_submodule : submodule R A :=
{ carrier := S,
zero_mem' := (0:S).2,
add_mem' := λ x y hx hy, (⟨x, hx⟩ + ⟨y, hy⟩ : S).2,
smul_mem' := λ c x hx, (algebra.smul_def c x).symm ▸
(⟨algebra_map R A c, S.range_le ⟨c, rfl⟩⟩ * ⟨x, hx⟩:S).2 }
instance coe_to_submodule : has_coe (subalgebra R A) (submodule R A) :=
⟨to_submodule⟩
instance to_submodule.is_subring : is_subring ((S : submodule R A) : set A) := S.2
instance : partial_order (subalgebra R A) :=
{ le := λ S T, (S : set A) ≤ (T : set A),
le_refl := λ _, le_refl _,
le_trans := λ _ _ _, le_trans,
le_antisymm := λ S T hst hts, ext $ λ x, ⟨@hst x, @hts x⟩ }
/-- Reinterpret an `S`-subalgebra as an `R`-subalgebra in `comap R S A`. -/
def comap {R : Type u} {S : Type v} {A : Type w}
[comm_ring R] [comm_ring S] [ring A] [algebra R S] [algebra S A]
(iSB : subalgebra S A) : subalgebra R (algebra.comap R S A) :=
{ carrier := (iSB : set A),
subring := iSB.is_subring,
range_le' := λ a ⟨r, hr⟩, hr ▸ iSB.range_le ⟨_, rfl⟩ }
/-- If `S` is an `R`-subalgebra of `A` and `T` is an `S`-subalgebra of `A`,
then `T` is an `R`-subalgebra of `A`. -/
def under {R : Type u} {A : Type v} [comm_ring R] [comm_ring A]
{i : algebra R A} (S : subalgebra R A)
(T : subalgebra S A) : subalgebra R A :=
{ carrier := T,
range_le' := (λ a ⟨r, hr⟩, hr ▸ T.range_le ⟨⟨algebra_map R A r, S.range_le ⟨r, rfl⟩⟩, rfl⟩) }
lemma mul_mem (A' : subalgebra R A) (x y : A) :
x ∈ A' → y ∈ A' → x * y ∈ A' := @is_submonoid.mul_mem A _ A' _ x y
end subalgebra
namespace alg_hom
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_ring R] [ring A] [ring B] [algebra R A] [algebra R B]
variables (φ : A →ₐ[R] B)
/-- Range of an `alg_hom` as a subalgebra. -/
protected def range (φ : A →ₐ[R] B) : subalgebra R B :=
begin
haveI : is_subring (set.range φ) := show is_subring (set.range φ.to_ring_hom), by apply_instance,
exact ⟨set.range φ, λ y ⟨r, hr⟩, ⟨algebra_map R A r, hr ▸ φ.commutes r⟩⟩
end
end alg_hom
namespace algebra
variables (R : Type u) (A : Type v)
variables [comm_semiring R] [semiring A] [algebra R A]
instance id : algebra R R := (ring_hom.id R).to_algebra
namespace id
@[simp] lemma map_eq_self (x : R) : algebra_map R R x = x := rfl
@[simp] lemma smul_eq_mul (x y : R) : x • y = x * y := rfl
end id
/-- `algebra_map` as an `alg_hom`. -/
def of_id : R →ₐ[R] A :=
{ commutes' := λ _, rfl, .. algebra_map R A }
variables {R}
theorem of_id_apply (r) : of_id R A r = algebra_map R A r := rfl
end algebra
namespace algebra
variables (R : Type u) {A : Type v} [comm_ring R] [ring A] [algebra R A]
/-- The minimal subalgebra that includes `s`. -/
def adjoin (s : set A) : subalgebra R A :=
{ carrier := ring.closure (set.range (algebra_map R A) ∪ s),
range_le' := le_trans (set.subset_union_left _ _) ring.subset_closure }
variables {R}
protected lemma gc : galois_connection (adjoin R : set A → subalgebra R A) coe :=
λ s S, ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) ring.subset_closure) H,
λ H, ring.closure_subset $ set.union_subset S.range_le H⟩
/-- Galois insertion between `adjoin` and `coe`. -/
protected def gi : galois_insertion (adjoin R : set A → subalgebra R A) coe :=
{ choice := λ s hs, adjoin R s,
gc := algebra.gc,
le_l_u := λ S, (algebra.gc (S : set A) (adjoin R S)).1 $ le_refl _,
choice_eq := λ _ _, rfl }
instance : complete_lattice (subalgebra R A) :=
galois_insertion.lift_complete_lattice algebra.gi
instance : inhabited (subalgebra R A) := ⟨⊥⟩
theorem mem_bot {x : A} : x ∈ (⊥ : subalgebra R A) ↔ x ∈ set.range (algebra_map R A) :=
suffices (⊥ : subalgebra R A) = (of_id R A).range, by rw this; refl,
le_antisymm bot_le $ subalgebra.range_le _
theorem mem_top {x : A} : x ∈ (⊤ : subalgebra R A) :=
ring.mem_closure $ or.inr trivial
theorem eq_top_iff {S : subalgebra R A} :
S = ⊤ ↔ ∀ x : A, x ∈ S :=
⟨λ h x, by rw h; exact mem_top, λ h, by ext x; exact ⟨λ _, mem_top, λ _, h x⟩⟩
/-- `alg_hom` to `⊤ : subalgebra R A`. -/
def to_top : A →ₐ[R] (⊤ : subalgebra R A) :=
by refine_struct { to_fun := λ x, (⟨x, mem_top⟩ : (⊤ : subalgebra R A)) }; intros; refl
end algebra
section int
variables (R : Type*) [ring R]
/-- Reinterpret a `ring_hom` as a `ℤ`-algebra homomorphism. -/
def alg_hom_int
{R : Type u} [comm_ring R] [algebra ℤ R]
{S : Type v} [comm_ring S] [algebra ℤ S]
(f : R →+* S) : R →ₐ[ℤ] S :=
{ commutes' := λ i, show f _ = _, by simp, .. f }
/-- CRing ⥤ ℤ-Alg -/
instance algebra_int : algebra ℤ R :=
{ commutes' := int.cast_commute,
smul_def' := λ _ _, gsmul_eq_mul _ _,
.. int.cast_ring_hom R }
variables {R}
/-- A subring is a `ℤ`-subalgebra. -/
def subalgebra_of_subring (S : set R) [is_subring S] : subalgebra ℤ R :=
{ carrier := S,
range_le' := by { rintros _ ⟨i, rfl⟩, rw [ring_hom.eq_int_cast, ← gsmul_one],
exact is_add_subgroup.gsmul_mem is_submonoid.one_mem } }
@[simp] lemma mem_subalgebra_of_subring {x : R} {S : set R} [is_subring S] :
x ∈ subalgebra_of_subring S ↔ x ∈ S :=
iff.rfl
section span_int
open submodule
lemma span_int_eq_add_group_closure (s : set R) :
(span ℤ s).to_add_subgroup = add_subgroup.closure s :=
eq.symm $ add_subgroup.closure_eq_of_le _ subset_span $ λ x hx, span_induction hx
(λ x hx, add_subgroup.subset_closure hx) (add_subgroup.zero_mem _)
(λ _ _, add_subgroup.add_mem _) (λ _ _ _, add_subgroup.gsmul_mem _ ‹_› _)
@[simp] lemma span_int_eq (s : add_subgroup R) : (span ℤ (s : set R)).to_add_subgroup = s :=
by rw [span_int_eq_add_group_closure, s.closure_eq]
end span_int
end int
section restrict_scalars
/- In this section, we describe restriction of scalars: if `S` is an algebra over `R`, then
`S`-modules are also `R`-modules. -/
variables (R : Type*) [comm_ring R] (S : Type*) [ring S] [algebra R S]
variables (E : Type*) [add_comm_group E] [module S E] {F : Type*} [add_comm_group F] [module S F]
/--
When `E` is a module over a ring `S`, and `S` is an algebra over `R`, then `E` inherits a
module structure over `R`, called `module.restrict_scalars' R S E`.
We do not register this as an instance as `S` can not be inferred.
-/
def module.restrict_scalars' : module R E :=
{ smul := λ c x, (algebra_map R S c) • x,
one_smul := by simp,
mul_smul := by simp [mul_smul],
smul_add := by simp [smul_add],
smul_zero := by simp [smul_zero],
add_smul := by simp [add_smul],
zero_smul := by simp [zero_smul] }
/--
When `E` is a module over a ring `S`, and `S` is an algebra over `R`, then `E` inherits a
module structure over `R`, provided as a type synonym `module.restrict_scalars R S E := E`.
-/
@[nolint unused_arguments]
def module.restrict_scalars (R : Type*) (S : Type*) (E : Type*) : Type* := E
instance (R : Type*) (S : Type*) (E : Type*) [I : inhabited E] :
inhabited (module.restrict_scalars R S E) := I
instance (R : Type*) (S : Type*) (E : Type*) [I : add_comm_group E] :
add_comm_group (module.restrict_scalars R S E) := I
instance : module R (module.restrict_scalars R S E) :=
(module.restrict_scalars' R S E : module R E)
lemma module.restrict_scalars_smul_def (c : R) (x : module.restrict_scalars R S E) :
c • x = ((algebra_map R S c) • x : E) := rfl
/--
`module.restrict_scalars R S S` is `R`-linearly equivalent to the original algebra `S`.
Unfortunately these structures are not generally definitionally equal:
the `R`-module structure on `S` is part of the data of `S`,
while the `R`-module structure on `module.restrict_scalars R S S`
comes from the ring homomorphism `R →+* S`, which is a separate part of the data of `S`.
The field `algebra.smul_def'` gives the equation we need here.
-/
def algebra.restrict_scalars_equiv :
(module.restrict_scalars R S S) ≃ₗ[R] S :=
{ to_fun := λ s, s,
inv_fun := λ s, s,
left_inv := λ s, rfl,
right_inv := λ s, rfl,
map_add' := λ x y, rfl,
map_smul' := λ c x, (algebra.smul_def' _ _).symm, }
@[simp]
lemma algebra.restrict_scalars_equiv_apply (s : S) :
algebra.restrict_scalars_equiv R S s = s := rfl
@[simp]
lemma algebra.restrict_scalars_equiv_symm_apply (s : S) :
(algebra.restrict_scalars_equiv R S).symm s = s := rfl
variables {S E}
open module
/--
`V.restrict_scalars R` is the `R`-submodule of the `R`-module given by restriction of scalars,
corresponding to `V`, an `S`-submodule of the original `S`-module.
-/
@[simps]
def submodule.restrict_scalars (V : submodule S E) : submodule R (restrict_scalars R S E) :=
{ carrier := V.carrier,
zero_mem' := V.zero_mem,
smul_mem' := λ c e h, V.smul_mem _ h,
add_mem' := λ x y hx hy, V.add_mem hx hy, }
@[simp]
lemma submodule.restrict_scalars_mem (V : submodule S E) (e : E) :
e ∈ V.restrict_scalars R ↔ e ∈ V :=
iff.refl _
@[simp]
lemma submodule.restrict_scalars_bot :
submodule.restrict_scalars R (⊥ : submodule S E) = ⊥ :=
rfl
@[simp]
lemma submodule.restrict_scalars_top :
submodule.restrict_scalars R (⊤ : submodule S E) = ⊤ :=
rfl
/-- The `R`-linear map induced by an `S`-linear map when `S` is an algebra over `R`. -/
def linear_map.restrict_scalars (f : E →ₗ[S] F) :
(restrict_scalars R S E) →ₗ[R] (restrict_scalars R S F) :=
{ to_fun := f.to_fun,
map_add' := λx y, f.map_add x y,
map_smul' := λc x, f.map_smul (algebra_map R S c) x }
@[simp, norm_cast squash] lemma linear_map.coe_restrict_scalars_eq_coe (f : E →ₗ[S] F) :
(f.restrict_scalars R : E → F) = f := rfl
@[simp]
lemma restrict_scalars_ker (f : E →ₗ[S] F) :
(f.restrict_scalars R).ker = submodule.restrict_scalars R f.ker :=
rfl
variables (𝕜 : Type*) [field 𝕜] (𝕜' : Type*) [field 𝕜'] [algebra 𝕜 𝕜']
variables (W : Type*) [add_comm_group W] [vector_space 𝕜' W]
/--
`V.restrict_scalars 𝕜` is the `𝕜`-subspace of the `𝕜`-vector space given by restriction of scalars,
corresponding to `V`, a `𝕜'`-subspace of the original `𝕜'`-vector space.
-/
def subspace.restrict_scalars (V : subspace 𝕜' W) : subspace 𝕜 (restrict_scalars 𝕜 𝕜' W) :=
{ ..submodule.restrict_scalars 𝕜 (V : submodule 𝕜' W) }
end restrict_scalars
/-!
When `V` and `W` are `S`-modules, for some `R`-algebra `S`,
the collection of `S`-linear maps from `V` to `W` forms an `R`-module.
(But not generally an `S`-module, because `S` may be non-commutative.)
-/
section module_of_linear_maps
variables (R : Type*) [comm_ring R] (S : Type*) [ring S] [algebra R S]
(V : Type*) [add_comm_group V] [module S V]
(W : Type*) [add_comm_group W] [module S W]
/--
For `r : R`, and `f : V →ₗ[S] W` (where `S` is an `R`-algebra) we define
`(r • f) v = f (r • v)`.
-/
def linear_map_algebra_has_scalar : has_scalar R (V →ₗ[S] W) :=
{ smul := λ r f,
{ to_fun := λ v, f ((algebra_map R S r) • v),
map_add' := λ x y, by simp [smul_add],
map_smul' := λ s v, by simp [smul_smul, algebra.commutes], } }
local attribute [instance] linear_map_algebra_has_scalar
/-- The `R`-module structure on `S`-linear maps, for `S` an `R`-algebra. -/
def linear_map_algebra_module : module R (V →ₗ[S] W) :=
{ one_smul := λ f, begin ext v, dsimp [(•)], simp, end,
mul_smul := λ r r' f,
begin
ext v, dsimp [(•)],
rw [linear_map.map_smul, linear_map.map_smul, linear_map.map_smul, ring_hom.map_mul,
smul_smul, algebra.commutes],
end,
smul_zero := λ r, by { ext v, dsimp [(•)], refl, },
smul_add := λ r f g, by { ext v, dsimp [(•)], simp [linear_map.map_add], },
zero_smul := λ f, by { ext v, dsimp [(•)], simp, },
add_smul := λ r r' f, by { ext v, dsimp [(•)], simp [add_smul], }, }
local attribute [instance] linear_map_algebra_module
variables {R S V W}
@[simp]
lemma linear_map_algebra_module.smul_apply (c : R) (f : V →ₗ[S] W) (v : V) :
(c • f) v = (c • (f v) : module.restrict_scalars R S W) :=
begin
erw [linear_map.map_smul],
refl,
end
end module_of_linear_maps
|
df5f4fa0d2dd41d948c3dc734fe97658ec338067 | e39f04f6ff425fe3b3f5e26a8998b817d1dba80f | /category_theory/full_subcategory.lean | 1bd115a8065c220a57fe22cb4074062e2a0b4aa4 | [
"Apache-2.0"
] | permissive | kristychoi/mathlib | c504b5e8f84e272ea1d8966693c42de7523bf0ec | 257fd84fe98927ff4a5ffe044f68c4e9d235cc75 | refs/heads/master | 1,586,520,722,896 | 1,544,030,145,000 | 1,544,031,933,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 759 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
import category_theory.fully_faithful
namespace category_theory
universes u v
section
variables {C : Type u} [𝒞 : category.{u v} C]
include 𝒞
instance full_subcategory (Z : C → Prop) : category.{u v} {X : C // Z X} :=
{ hom := λ X Y, X.1 ⟶ Y.1,
id := λ X, 𝟙 X.1,
comp := λ _ _ _ f g, f ≫ g }
def full_subcategory_inclusion (Z : C → Prop) : {X : C // Z X} ⥤ C :=
{ obj := λ X, X.1,
map := λ _ _ f, f }
instance full_subcategory_fully_faithful (Z : C → Prop) : fully_faithful (full_subcategory_inclusion Z) :=
{ preimage := λ X Y f, f }
end
end category_theory
|
80a8b221a16fc49d4c7d5880f22f9b7142445bd6 | 957a80ea22c5abb4f4670b250d55534d9db99108 | /library/init/native/procedure.lean | c72715dc7f37629499b2645e7ba2d3e5247f15a1 | [
"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 | 577 | lean | /-
Copyright (c) 2016 Jared Roesch. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jared Roesch
-/
prelude
import init.meta.name
import init.meta.expr
meta def procedure :=
name × expr
meta def procedure.repr : procedure → string
| (n, e) := "def " ++ to_string n ++ " := \n" ++ to_string e -- to_string for expr does not produce string that can be parsed by Lean
meta def procedure.map_body (f : expr → expr) : procedure → procedure
| (n, e) := (n, f e)
meta instance : has_repr procedure :=
⟨procedure.repr⟩
|
ed16428c4d92ef6fb02c57d348092f71de1c4606 | cf39355caa609c0f33405126beee2739aa3cb77e | /library/init/meta/converter/default.lean | b478a8358c358cf328478433c73cc6b70d6681de | [
"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 | 279 | 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
Converter monad for building simplifiers.
-/
prelude
import init.meta.converter.conv init.meta.converter.interactive
|
54d6e5b77e722bbb9abc1b31e91d7873330f7b3b | e151e9053bfd6d71740066474fc500a087837323 | /src/hott/types/fiber.lean | c5364af84edf4fd6b2880bf139f57757b4cb8cd5 | [
"Apache-2.0"
] | permissive | daniel-carranza/hott3 | 15bac2d90589dbb952ef15e74b2837722491963d | 913811e8a1371d3a5751d7d32ff9dec8aa6815d9 | refs/heads/master | 1,610,091,349,670 | 1,596,222,336,000 | 1,596,222,336,000 | 241,957,822 | 0 | 0 | Apache-2.0 | 1,582,222,839,000 | 1,582,222,838,000 | null | UTF-8 | Lean | false | false | 22,791 | lean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Mike Shulman
Ported from Coq HoTT
Theorems about fibers
-/
import .eq .arrow ..cubical.squareover .pointed ..eq2
universes u v w
hott_theory
namespace hott
open hott.equiv hott.sigma hott.eq hott.pi hott.pointed hott.is_equiv
structure fiber {A B : Type _} (f : A → B) (b : B) :=
(point : A)
(point_eq : f point = b)
namespace fiber
variables {A : Type _} {B : Type _} {f : A → B} {b : B}
@[hott] protected def sigma_char
(f : A → B) (b : B) : fiber f b ≃ (Σ(a : A), f a = b) :=
begin
fapply equiv.MK,
{intro x, exact ⟨point x, point_eq x⟩},
{intro x, exact (fiber.mk x.1 x.2)},
{intro x, cases x, apply idp },
{intro x, cases x, apply idp },
end
@[hott, hsimp] def sigma_char_mk_pair {A B : Type*} (f : A → B) (a : A) (b : B) (p : f a = b)
: fiber.sigma_char f b ⟨ a , p ⟩ = ⟨a, p⟩ :=
rfl
-- @[hott, hsimp] def sigma_char_mk_snd {A B : Type*} (f : A → B) (a : A) (b : B) (p : f a = b)
-- : ((fiber.sigma_char f b) ⟨ a , p ⟩).snd = p :=
-- begin dsimp, end --refl _
-- @[hott, hsimp] def sigma_char_mk_fst {A B : Type*} (f : A → B) (a : A) (b : B) (p : f a = b)
-- : ((fiber.sigma_char f b) ⟨ a , p ⟩).fst = a :=
-- begin dsimp, end --refl _
@[hott] def fiber_eq_equiv (x y : fiber f b)
: (x = y) ≃ (Σ(p : point x = point y), point_eq x = ap f p ⬝ point_eq y) :=
begin
apply equiv.trans,
apply eq_equiv_fn_eq_of_equiv, apply fiber.sigma_char,
apply equiv.trans,
apply sigma_eq_equiv,
apply sigma_equiv_sigma_right,
intro p,
apply eq_pathover_equiv_Fl,
end
@[hott] def fiber_eq {x y : fiber f b} (p : point x = point y)
(q : point_eq x = ap f p ⬝ point_eq y) : x = y :=
to_inv (fiber_eq_equiv _ _) ⟨p, q⟩
@[hott] def fiber_pathover {X : Type _} {A B : X → Type _} {x₁ x₂ : X} {p : x₁ = x₂}
{f : Πx, A x → B x} {b : Πx, B x} {v₁ : fiber (f x₁) (b x₁)} {v₂ : fiber (f x₂) (b x₂)}
(q : point v₁ =[p] point v₂)
(r : squareover B hrfl (pathover_idp_of_eq _ (point_eq v₁)) (pathover_idp_of_eq _ (point_eq v₂))
(apo f q) (apd b p))
: v₁ =[p; λ x, fiber (f x) (b x)] v₂ :=
begin
apply (pathover_of_fn_pathover_fn (λ (x : X), @fiber.sigma_char (A x) (B x) (f x) (b x))), dsimp,
fapply sigma_pathover; dsimp,
{ exact q},
{ induction v₁ with a₁ p₁, induction v₂ with a₂ p₂, dsimp at *, induction q,
apply pathover_idp_of_eq, apply eq_of_vdeg_square,
dsimp[hrfl] at r,
dsimp[apo, apd] at r,
exact (square_of_squareover_ids B r)}
end
open is_trunc
@[hott] def π₁ {B : A → Type _} : (Σa, B a) → A := sigma.fst
@[hott] def fiber_pr1 (B : A → Type _) (a : A) : fiber (π₁ : (Σa, B a) → A) a ≃ B a :=
calc
fiber π₁ a ≃ Σ(u : Σ a, B a), (π₁ u) = a : fiber.sigma_char _ _
... ≃ Σ (a' : A) (b : B a'), a' = a : (sigma_assoc_equiv (λ (u : Σ a, B a), (π₁ u) = a) ) ⁻¹ᵉ
... ≃ Σa' (p : a' = a), B a' : sigma_equiv_sigma_right (λa', comm_equiv_nondep _ _)
... ≃ Σ(w : Σ a', a'=a), B (π₁ w) : sigma_assoc_equiv (λ (w : Σ a', a'=a), B (π₁ w))
... ≃ B a : sigma_equiv_of_is_contr_left (λ (w : Σ a', a'=a), B (π₁ w))
@[hott] def sigma_fiber_equiv (f : A → B) : (Σb, fiber f b) ≃ A :=
calc
(Σb, fiber f b) ≃ Σb a, f a = b : sigma_equiv_sigma_right (λb, fiber.sigma_char _ b)
... ≃ Σa b, f a = b : sigma_comm_equiv _
... ≃ A : sigma_equiv_of_is_contr_right _
@[hott, instance] def is_pointed_fiber (f : A → B) (a : A)
: pointed (fiber f (f a)) :=
pointed.mk (fiber.mk a idp)
@[hott] def pointed_fiber (f : A → B) (a : A) : Type* :=
pointed.Mk (fiber.mk a (idpath (f a)))
@[hott, reducible] def is_trunc_fun (n : ℕ₋₂) (f : A → B) :=
Π(b : B), is_trunc n (fiber f b)
@[hott, reducible] def is_contr_fun (f : A → B) := is_trunc_fun -2 f
-- pre and post composition with equivalences
open function
variable (f)
@[hott] protected def equiv_postcompose {B' : Type _} (g : B ≃ B') --[H : is_equiv g]
(b : B) : fiber (g ∘ f) (g b) ≃ fiber f b :=
calc
fiber (g ∘ f) (g b) ≃ Σa : A, g (f a) = g b : fiber.sigma_char _ _
... ≃ Σa : A, f a = b : begin
apply sigma_equiv_sigma_right,
intro a,
apply equiv.symm,
apply eq_equiv_fn_eq
end
... ≃ fiber f b : (fiber.sigma_char _ _) ⁻¹ᵉ
@[hott] protected def equiv_precompose {A' : Type _} (g : A' ≃ A) --[H : is_equiv g]
(b : B) : fiber (f ∘ g) b ≃ fiber f b :=
calc
fiber (f ∘ g) b ≃ Σa' : A', f (g a') = b : fiber.sigma_char _ _
... ≃ Σa : A, f a = b : begin
apply sigma_equiv_sigma g,
intro a', apply erfl
end
... ≃ fiber f b : (fiber.sigma_char _ _) ⁻¹ᵉ
end fiber
open unit is_trunc pointed
namespace fiber
@[hott] def fiber_star_equiv (A : Type _) : fiber (λx : A, star) star ≃ A :=
begin
fapply equiv.MK,
{ intro f, cases f with a H, exact a },
{ intro a, apply fiber.mk a, reflexivity },
{ intro a, reflexivity },
{ intro f, cases f with a H, change fiber.mk a (refl star) = fiber.mk a H,
rwr [is_set.elim H (refl star)] }
end
@[hott] def fiber_const_equiv (A : Type _) (a₀ : A) (a : A)
: fiber (λz : unit, a₀) a ≃ a₀ = a :=
calc
fiber (λz : unit, a₀) a ≃ Σz : unit, a₀ = a : fiber.sigma_char _ _
... ≃ a₀ = a : sigma_unit_left _
-- the pointed fiber of a pointed map, which is the fiber over the basepoint
open pointed
@[hott] def pfiber {X Y : Type*} (f : X →* Y) : Type* :=
pointed.MK (fiber f pt) (fiber.mk pt (respect_pt _))
@[hott] def ppoint {X Y : Type*} (f : X →* Y) : pfiber f →* X :=
pmap.mk point idp
@[hott] def pfiber.sigma_char {A B : Type*} (f : A →* B)
: pfiber f ≃* pointed.MK (Σa, f a = pt) ⟨pt, respect_pt f⟩ :=
pequiv_of_equiv (fiber.sigma_char f pt) idp
@[hott, hsimp] def pfiber.sigma_char_mk_snd {A B : Type*} (f : A →* B) (a : A) (p : f a = pt)
: ((pfiber.sigma_char f).to_pmap ⟨ a , p ⟩).snd = p :=
refl _
@[hott] def pointed_fst {A : Type*} (B : A → Type) (pt_B : B pt) :
pointed.MK (Σa, B a) ⟨pt, pt_B⟩ →* A :=
pmap.mk π₁ (refl _)
@[hott] def ppoint_sigma_char {A B : Type*} (f : A →* B)
: ppoint f ~* (pointed_fst _ _) ∘* (pfiber.sigma_char f).to_pmap :=
phomotopy.refl _
@[hott] def pfiber_pequiv_of_phomotopy {A B : Type*} {f g : A →* B} (h : f ~* g)
: pfiber f ≃* pfiber g :=
begin
fapply pequiv_of_equiv,
{ refine (fiber.sigma_char f pt ⬝e _ ⬝e (fiber.sigma_char g pt)⁻¹ᵉ),
apply sigma_equiv_sigma_right, intros a,
apply equiv_eq_closed_left, apply (to_homotopy h) },
{ refine (fiber_eq rfl _),
change (h pt)⁻¹ ⬝ respect_pt f = idp ⬝ respect_pt g,
rwr idp_con, apply inv_con_eq_of_eq_con, symmetry, exact (to_homotopy_pt h) }
end
@[hott] def transport_fiber_equiv {A B : Type _} (f : A → B) {b1 b2 : B} (p : b1 = b2)
: fiber f b1 ≃ fiber f b2 :=
calc fiber f b1 ≃ Σa, f a = b1 : fiber.sigma_char _ _
... ≃ Σa, f a = b2 : sigma_equiv_sigma_right (λa, equiv_eq_closed_right (f a) p)
... ≃ fiber f b2 : (fiber.sigma_char _ _) ⁻¹ᵉ
@[hott,hsimp] def transport_fiber_equiv_mk {A B : Type _}
(f : A → B) {b1 b2 : B} (p : b1 = b2) (a : A) (q : f a = b1) :
(transport_fiber_equiv f p) ⟨ a , q ⟩ = ⟨ a , q ⬝ p ⟩ :=
begin
induction p, induction q, refl
end
@[hott, hsimp] def snd_point_pfiber_eq_respect_pt {A B : Type*} (f : A →* B) :
(pfiber f).Point = ⟨ pt , respect_pt f ⟩ :=
by refl
@[hott] def pequiv_postcompose {A B B' : Type*} (f : A →* B) (g : B ≃* B')
: pfiber (g.to_pmap ∘* f) ≃* pfiber f :=
begin
fapply pequiv_of_equiv,
refine
transport_fiber_equiv (g.to_pmap ∘* f) (respect_pt g.to_pmap)⁻¹ ⬝e
fiber.equiv_postcompose f (equiv_of_pequiv g) (Point B),
apply ap (fiber.mk (Point A)), refine con.assoc _ _ _ ⬝ _,
apply inv_con_eq_of_eq_con,
dsimp [fiber.sigma_char],
rwr [con.assoc, eq.con.right_inv, con_idp, ← ap_compose],
exact ap_con_eq_con
(λ x, ap g⁻¹ᵉ*.to_pmap (ap g.to_pmap (pleft_inv' g x)⁻¹) ⬝ ap g⁻¹ᵉ*.to_pmap
(pright_inv g (g.to_pmap x)) ⬝
pleft_inv' g x) (respect_pt f)
end
@[hott] def pequiv_precompose {A A' B : Type*} (f : A →* B) (g : A' ≃* A)
: pfiber (f ∘* g.to_pmap) ≃* pfiber f :=
begin
fapply pequiv_of_equiv,
refine fiber.equiv_precompose f (equiv_of_pequiv g) (Point B),
apply (eq_of_fn_eq_fn (fiber.sigma_char _ _)), fapply sigma_eq,
{ apply respect_pt g.to_pmap },
{ apply eq_pathover_Fl' }
end
@[hott] def pfiber_pequiv_of_square {A B C D : Type*} {f : A →* B} {g : C →* D} (h : A ≃* C)
(k : B ≃* D) (s : k.to_pmap ∘* f ~* g ∘* h.to_pmap) : pfiber f ≃* pfiber g :=
calc pfiber f ≃* pfiber (k.to_pmap ∘* f) : (pequiv_postcompose f k) ⁻¹ᵉ*
... ≃* pfiber (g ∘* h.to_pmap) : pfiber_pequiv_of_phomotopy s
... ≃* pfiber g : (pequiv_precompose _ _)
@[hott] def pcompose_ppoint {A B : Type*} (f : A →* B) : f ∘* ppoint f ~* pconst (pfiber f) B :=
begin
fapply phomotopy.mk,
{ exact point_eq },
{ exact (idp_con _)⁻¹ }
end
@[hott] def point_fiber_eq {A B : Type _} {f : A → B} {b : B} {x y : fiber f b}
(p : point x = point y) (q : point_eq x = ap f p ⬝ point_eq y) :
ap point (fiber_eq p q) = p :=
begin
induction x with a γ, induction y with a' γ', dsimp at p q,
induction p, induction γ', dsimp at q,
hinduction q using eq.rec_symm, reflexivity
end
@[hott] def fiber_eq_equiv_fiber {A B : Type _} {f : A → B} {b : B} (x y : fiber f b) :
x = y ≃ fiber (ap1_gen f (point_eq x) (point_eq y)) (idpath b) :=
calc
x = y ≃ fiber.sigma_char f b x = fiber.sigma_char f b y :
eq_equiv_fn_eq_of_equiv (fiber.sigma_char f b) x y
... ≃ Σ(p : point x = point y), point_eq x =[p; λ z, f z = b] point_eq y : sigma_eq_equiv _ _
... ≃ Σ(p : point x = point y), (point_eq x)⁻¹ ⬝ ap f p ⬝ point_eq y = idp :
sigma_equiv_sigma_right (λp,
calc
point_eq x =[p; λ z, f z = b] point_eq y ≃ point_eq x = ap f p ⬝ point_eq y : eq_pathover_equiv_Fl _ _ _
... ≃ ap f p ⬝ point_eq y = point_eq x : eq_equiv_eq_symm _ _
... ≃ (point_eq x)⁻¹ ⬝ (ap f p ⬝ point_eq y) = idp : eq_equiv_inv_con_eq_idp _ _
... ≃ (point_eq x)⁻¹ ⬝ ap f p ⬝ point_eq y = idp : equiv_eq_closed_left _ (con.assoc _ _ _) ⁻¹)
... ≃ fiber (ap1_gen f (point_eq x) (point_eq y)) (idpath b) : (fiber.sigma_char _ _) ⁻¹ᵉ
@[hott] def loop_pfiber {A B : Type*} (f : A →* B) : Ω (pfiber f) ≃* pfiber (Ω→ f) :=
pequiv_of_equiv (fiber_eq_equiv_fiber (Point (pfiber f)) (Point (pfiber f)))
begin
induction f with f f₀, induction B with B b₀, dsimp at f f₀, induction f₀, reflexivity
end
@[hott] def pfiber_loop_space {A B : Type*} (f : A →* B) : pfiber (Ω→ f) ≃* Ω (pfiber f) :=
(loop_pfiber f)⁻¹ᵉ*
@[hott] def point_fiber_eq_equiv_fiber {A B : Type _} {f : A → B} {b : B} {x y : fiber f b}
(p : x = y) : point (fiber_eq_equiv_fiber x y p) = ap1_gen point idp idp p :=
by induction p; reflexivity
@[hott] lemma ppoint_loop_pfiber {A B : Type*} (f : A →* B) :
ppoint (Ω→ f) ∘* (loop_pfiber f).to_pmap ~* Ω→ (ppoint f) :=
phomotopy.mk (point_fiber_eq_equiv_fiber)
begin
induction f with f f₀, induction B with B b₀, dsimp at f f₀, induction f₀, reflexivity
end
@[hott] lemma ppoint_loop_pfiber_inv {A B : Type*} (f : A →* B) :
Ω→ (ppoint f) ∘* ((loop_pfiber f)⁻¹ᵉ*).to_pmap ~* ppoint (Ω→ f) :=
(phomotopy_pinv_right_of_phomotopy (ppoint_loop_pfiber f))⁻¹*
@[hott] def pfiber_pequiv_of_phomotopy_ppoint {A B : Type*} {f g : A →* B} (h : f ~* g)
: ppoint g ∘* (pfiber_pequiv_of_phomotopy h).to_pmap ~* ppoint f :=
begin
induction f with f f₀, induction g with g g₀, induction h with h h₀,
induction B with B b₀, induction A with A a₀,
dsimp at *,
induction g₀,
dsimp [respect_pt] at h₀,
induction h₀,
dsimp [ppoint],
fapply phomotopy.mk,
{ reflexivity },
{ refine idp_con _ ⬝ _, symmetry, apply point_fiber_eq }
end
@[hott] def pequiv_postcompose_ppoint {A B B' : Type*} (f : A →* B) (g : B ≃* B')
: ppoint f ∘* (fiber.pequiv_postcompose f g).to_pmap ~* ppoint (g.to_pmap ∘* f) :=
begin
induction f with f f₀, induction g with g hg g₀, induction B with B b₀,
induction B' with B' b₀', dsimp at *, induction g₀, induction f₀,
fapply phomotopy.mk,
{ reflexivity },
{ refine idp_con _ ⬝ _, symmetry, dsimp [ppoint],
refine (ap_compose' _ _ _) ⬝ _, apply ap_constant }
end
@[hott] def pequiv_precompose_ppoint {A A' B : Type*} (f : A →* B) (g : A' ≃* A)
: ppoint f ∘* (fiber.pequiv_precompose f g).to_pmap ~* g.to_pmap ∘* ppoint (f ∘* g.to_pmap) :=
begin
induction f with f f₀, induction g with g h₁ h₂ p₁ p₂, induction B with B b₀,
induction g with g g₀, induction A with A a₀', dsimp at *, induction g₀, induction f₀,
reflexivity
end
@[hott] def pfiber_pequiv_of_square_ppoint {A B C D : Type*} {f : A →* B} {g : C →* D}
(h : A ≃* C) (k : B ≃* D) (s : k.to_pmap ∘* f ~* g ∘* h.to_pmap)
: ppoint g ∘* (pfiber_pequiv_of_square h k s).to_pmap ~* h.to_pmap ∘* ppoint f :=
begin
refine (passoc _ _ _) ⁻¹* ⬝* _,
refine pwhisker_right _ (pequiv_precompose_ppoint _ _) ⬝* _,
refine (passoc _ _ _) ⬝* _,
apply pwhisker_left,
refine (passoc _ _ _) ⁻¹* ⬝* _,
refine pwhisker_right _ (pfiber_pequiv_of_phomotopy_ppoint _) ⬝* _,
apply pinv_right_phomotopy_of_phomotopy,
refine (pequiv_postcompose_ppoint _ _)⁻¹*,
end
-- this breaks certain proofs if it is an instance
@[hott] def is_trunc_fiber (n : ℕ₋₂) {A B : Type _} (f : A → B) (b : B)
[is_trunc n A] [is_trunc (n.+1) B] : is_trunc n (fiber f b) :=
is_trunc_equiv_closed_rev n (fiber.sigma_char _ _) (is_trunc_sigma _ n)
@[hott] def is_trunc_pfiber (n : ℕ₋₂) {A B : Type*} (f : A →* B)
[is_trunc n A] [is_trunc (n.+1) B] : is_trunc n (pfiber f) :=
is_trunc_fiber n f pt
@[hott] def fiber_equiv_of_is_contr {A B : Type _} (f : A → B) (b : B) [is_contr B] :
fiber f b ≃ A :=
(fiber.sigma_char _ _) ⬝e sigma_equiv_of_is_contr_right _
@[hott] def pfiber_pequiv_of_is_contr {A B : Type*} (f : A →* B) [is_contr B] :
pfiber f ≃* A :=
pequiv_of_equiv (fiber_equiv_of_is_contr f pt) idp
@[hott] def pfiber_ppoint_equiv {A B : Type*} (f : A →* B) : pfiber (ppoint f) ≃ Ω B :=
calc
pfiber (ppoint f) ≃ Σ(x : pfiber f), ppoint f x = pt : fiber.sigma_char _ _
... ≃ Σ(x : Σa, f a = pt), x.1 = pt :
by exact sigma_equiv_sigma (fiber.sigma_char _ _) (λ a, erfl)
... ≃ Σ(x : Σa, a = pt), f x.1 = pt : sigma_assoc_comm_equiv (λa, f a = pt) (λa, a = pt)
... ≃ f pt = pt : sigma_equiv_of_is_contr_left _ ⬝e by refl
... ≃ Ω B : equiv_eq_closed_left _ (respect_pt _)
@[hott] def pfiber_ppoint_pequiv {A B : Type*} (f : A →* B) : pfiber (ppoint f) ≃* Ω B :=
pequiv_of_equiv (pfiber_ppoint_equiv f) (con.left_inv _)
@[hott] def pfiber_ppoint_equiv_eq {A B : Type*} (f : A →* B) {a : A} (p : f a = pt)
(q : ppoint f (fiber.mk a p) = pt) :
(pfiber_ppoint_equiv f).to_fun (fiber.mk (fiber.mk a p) q) = (respect_pt f)⁻¹ ⬝ ap f q⁻¹ ⬝ p :=
begin
refine _ ⬝ (con.assoc _ _ _) ⁻¹,
apply whisker_left,
dsimp [sigma_equiv_of_is_contr_left],
refine eq_transport_Fl _ _ ⬝ _,
apply whisker_right,
refine inverse2 (ap_inv _ _) ⬝ (inv_inv _) ⬝ _,
refine ap_compose f sigma.fst _ ⬝ ap02 f _, apply ap_fst_center_eq_sigma_eq'
end
@[hott] def pfiber_ppoint_equiv_inv_eq {A B : Type*} (f : A →* B) (p : Ω B) :
(pfiber_ppoint_equiv f)⁻¹ᵉ p = fiber.mk (fiber.mk pt (respect_pt f ⬝ p)) idp :=
begin
apply inv_eq_of_eq,
refine _ ⬝ (pfiber_ppoint_equiv_eq _ _ _)⁻¹,
exact (inv_con_cancel_left _ _)⁻¹
end
@[hott] def fiber_functor {A A' B B' : Type} {f : A → B} {f' : A' → B'} {b : B} {b' : B'}
(g : A → A') (h : B → B') (H : hsquare g h f f') (p : h b = b') (x : fiber f b) : fiber f' b' :=
fiber.mk (g (point x)) (H (point x) ⬝ ap h (point_eq x) ⬝ p)
@[hott] def pfiber_functor {A A' B B' : Type*} {f : A →* B} {f' : A' →* B'}
(g : A →* A') (h : B →* B') (H : psquare g h f f') : pfiber f →* pfiber f' :=
pmap.mk (fiber_functor g h H (respect_pt h))
begin
fapply fiber_eq,
exact respect_pt g,
exact con.assoc _ _ _ ⬝ to_homotopy_pt H
end
@[hott] def ppoint_natural {A A' B B' : Type*} {f : A →* B} {f' : A' →* B'}
(g : A →* A') (h : B →* B') (H : psquare g h f f') :
psquare (ppoint f) (ppoint f') (pfiber_functor g h H) g :=
begin
fapply phomotopy.mk,
{ intro x, reflexivity },
{ refine idp_con _ ⬝ _ ⬝ (idp_con _)⁻¹ᵖ, apply point_fiber_eq }
end
-- @[hott] def pfiber_ppoint_pequiv_natural {A A' B B' : Type*} {f : A →* B} {f' : A' →* B'}
-- (g : A →* A') (h : B →* B') (H : psquare g h f f') :
-- psquare (pfiber_ppoint_pequiv f).to_pmap (pfiber_ppoint_pequiv f').to_pmap
-- (pfiber_functor (pfiber_functor g h H) g (ptranspose (ppoint_natural g h H))) (Ω→ h) :=
-- begin
-- induction A' with A' a₀', induction B with B b₀, induction B' with B' b₀',
-- induction f with f f₀, induction f' with f' f₀', induction g with g g₀,
-- dsimp at *, induction f₀, induction f₀', induction g₀,
-- fapply phomotopy.mk,
-- { intro x,
-- induction x with x q, induction x with a p, dsimp [ppoint] at *,
-- dsimp [pfiber_ppoint_pequiv, pcompose, pequiv_of_equiv, pequiv.mk, pequiv_of_pmap,
-- pfiber_functor, fiber_functor],
-- refine ap (Ω→ h) (pfiber_ppoint_equiv_eq _ _ _) ⬝ _ ⬝ (pfiber_ppoint_equiv_eq _ _ _)⁻¹ᵖ,
-- dsimp [ppoint_natural, phomotopy.symm],
-- hinduction q using eq.rec_symm, refine ap (Ω→ h) (idp_con _) ⬝ _ ⬝ (idp_con _)⁻¹ᵖ,
-- apply whisker_right, apply whisker_right,
-- apply inv_eq_of_idp_eq_con,
-- exact (to_homotopy_pt H)⁻¹ ⬝ whisker_left _ (idp_con _) },
-- { sorry } -- this is easier if we redefine pfiber_ppoint_equiv after porting stuff about psigma_gen etc.
-- end
@[hott] def pfiber_ppoint_pequiv_ppoint_homotopy {A B : Type*} (f : A →* B) (p : Ω A) :
(pfiber_ppoint_pequiv f).to_pmap ((ppoint (ppoint (ppoint f)))
((pfiber_ppoint_pequiv (ppoint f))⁻¹ᵉ*.to_pmap p)) = Ω→ f p⁻¹ᵖ :=
begin
refine ap (λ(x : pfiber (ppoint (ppoint f))), (pfiber_ppoint_pequiv f).to_pmap
(ppoint (ppoint (ppoint f)) x))
(pfiber_ppoint_equiv_inv_eq (ppoint f) p) ⬝ _,
dsimp [ppoint],
refine pfiber_ppoint_equiv_eq f f.resp_pt _ ⬝ _,
exact ap (Ω→ f) (idp_con p)⁻²
end
@[hott] def pfiber_ppoint_equiv_eq_idp {A B : Type*} (f : A →* B) :
pfiber_ppoint_equiv_eq f (respect_pt f) idp = idp :=
begin
apply con_inv_eq_idp,
refine ap (whisker_left _) (whisker_left _ _) ⬝ _,
{ reflexivity },
{ reflexivity },
refine ap (whisker_left _) (eq_transport_Fl_idp_left f (respect_pt f)) ⬝ _,
apply whisker_left_idp_con_eq_assoc
end
@[hott] def pfiber_ppoint_pequiv_ppoint {A B : Type*} (f : A →* B) :
psquare (ppoint (ppoint (ppoint f))) (Ω→ f ∘* pinverse A)
(pfiber_ppoint_pequiv (ppoint f)).to_pmap (pfiber_ppoint_pequiv f).to_pmap :=
begin
apply phomotopy_of_pinv_right_phomotopy,
fapply phomotopy.mk,
{ exact pfiber_ppoint_pequiv_ppoint_homotopy f },
{ dsimp [pcompose, pinverse],
apply whisker_right, refine idp_con _ ⬝ con_idp _ ⬝ _,
exact pfiber_ppoint_equiv_eq_idp f }
end
end fiber
open function is_equiv
namespace fiber
/- @[hott] theorem 4.7.6 -/
variables {A : Type _} {P : A → Type _ } {Q : A → Type _}
variable (f : Πa, P a → Q a)
@[hott] def fiber_total_equiv {a : A} (q : Q a)
: fiber (total f) ⟨a , q⟩ ≃ fiber (f a) q :=
calc
fiber (total f) ⟨a , q⟩
≃ Σ(w : Σx, P x), (⟨w.1 , f w.1 w.2 ⟩ : Σ x, _) = ⟨a , q⟩
: fiber.sigma_char _ _
... ≃ Σ(x : A), Σ(p : P x), (⟨x , f x p⟩ : Σx, _) = ⟨a , q⟩
: (@sigma_assoc_equiv A P (λ(w : Σx, P x), (⟨w.1 , f w.1 w.2 ⟩ : Σ x, _) = ⟨a , q⟩))⁻¹ᵉ
... ≃ Σ(x : A), Σ(p : P x), Σ(H : x = a), f x p =[H] q
:
begin
apply sigma_equiv_sigma_right, intro x,
apply sigma_equiv_sigma_right, intro p,
apply sigma_eq_equiv
end
... ≃ Σ(x : A), Σ(H : x = a), Σ(p : P x), f x p =[H] q
:
begin
apply sigma_equiv_sigma_right, intro x,
apply sigma_comm_equiv
end
... ≃ Σ(w : Σx, x = a), Σ(p : P w.1), f w.1 p =[w.2] q
: sigma_assoc_equiv (λ(w : Σx, x = a), Σ(p : P w.1), f w.1 p =[w.2] q)
... ≃ Σ(p : P (center (Σx, x=a)).1), f (center (Σx, x=a)).1 p =[(center (Σx, x=a)).2] q
: sigma_equiv_of_is_contr_left _
... ≃ Σ(p : P a), f a p =[idpath a] q
: equiv_of_eq idp
... ≃ Σ(p : P a), f a p = q
:
begin
apply sigma_equiv_sigma_right, intro p,
apply pathover_idp
end
... ≃ fiber (f a) q
: (fiber.sigma_char _ _)⁻¹ᵉ
end fiber
end hott |
059a67d56732865dca5b6d4a57968f33df007be1 | 761fea1362b10b4c588c2dfc0ae90c70b119e35d | /src/provers/utils.lean | 0feaac276fd66a9ebac35c867ab35f13f47726ec | [] | no_license | holtzermann17/mm-lean | 382a29fca5245f97cf488c525ed0c9594917f73b | a9130d71ed448f62df28d4128043b707bad85ccd | refs/heads/master | 1,588,477,413,982 | 1,553,885,046,000 | 1,553,885,046,000 | 178,404,617 | 0 | 0 | null | 1,553,863,829,000 | 1,553,863,828,000 | null | UTF-8 | Lean | false | false | 6,708 | lean | import mathematica data.real.basic tactic.ring tactic.linarith
open expr tactic classical
section logical_equivalences
local attribute [instance] prop_decidable
variables {a b : Prop}
theorem not_not_iff (a : Prop) : ¬¬a ↔ a :=
iff.intro classical.by_contradiction not_not_intro
theorem implies_iff_not_or (a b : Prop) : (a → b) ↔ (¬ a ∨ b) :=
iff.intro
(λ h, if ha : a then or.inr (h ha) else or.inl ha)
(λ h, or.elim h (λ hna ha, absurd ha hna) (λ hb ha, hb))
theorem not_and_iff (a b : Prop) : ¬ (a ∧ b) ↔ ¬a ∨ ¬b :=
iff.intro
(λ h, if ha : a then or.inr (λ hb, h ⟨ha, hb⟩) else or.inl ha)
(λ h, λ ⟨ha, hb⟩, or.elim h (λ hna, hna ha) (λ hnb, hnb hb))
theorem not_or_of_not_and_not (h : ¬ a ∧ ¬ b) : ¬ (a ∨ b) :=
assume h₁, or.elim h₁ (assume ha, h^.left ha) (assume hb, h^.right hb)
theorem not_and_not_of_not_or (h : ¬ (a ∨ b)) : ¬ a ∧ ¬ b :=
and.intro (assume ha, h (or.inl ha)) (assume hb, h (or.inr hb))
theorem not_or_iff (a b : Prop) : (¬ (a ∨ b)) = (¬ a ∧ ¬ b) :=
propext (iff.intro not_and_not_of_not_or not_or_of_not_and_not)
theorem and_or_distrib (a b c : Prop) : a ∧ (b ∨ c) ↔ (a ∧ b) ∨ (a ∧ c) :=
iff.intro
(λ ⟨ha, hbc⟩, or.elim hbc (λ hb, or.inl ⟨ha, hb⟩) (λ hc, or.inr ⟨ha, hc⟩))
(λ h, or.elim h (λ ⟨ha, hb⟩, ⟨ha, or.inl hb⟩) (λ ⟨ha, hc⟩, ⟨ha, or.inr hc⟩))
theorem and_or_distrib₂ (a b c : Prop) : (b ∨ c) ∧ a ↔ (b ∧ a) ∨ (c ∧ a) :=
by rw [and.comm, and_or_distrib, @and.comm a, @and.comm a]
theorem or_and_distrib (a b c : Prop) : a ∨ (b ∧ c) ↔ (a ∨ b) ∧ (a ∨ c) :=
begin
apply iff.intro,
{ intro h, cases h with h₁ h₂, split; left; assumption, cases h₂, split; right; assumption },
intro h, cases h with h₁ h₂, cases h₁, left, assumption, cases h₂, left, assumption,
right, split; assumption
end
theorem or_and_distrib₂ (a b c : Prop) : (b ∧ c) ∨ a ↔ (b ∨ a) ∧ (c ∨ a) :=
by rw [or.comm, or_and_distrib, @or.comm a, @or.comm a]
end logical_equivalences
/- the necessary logical principles for ljt-/
theorem imp_of_or_imp_left {p q r : Prop} (h : p ∨ q → r) : p → r :=
λ hp, h (or.inl hp)
theorem imp_of_or_imp_right {p q r : Prop} (h : p ∨ q → r) : q → r :=
λ hq, h (or.inr hq)
theorem uncurry {p q r : Prop} (h : p ∧ q → r) : p → q → r :=
λ hp hq, h ⟨hp, hq⟩
theorem imp_false_of_not {p : Prop} (h : ¬ p) : p → false := h
theorem nested_imp_elim {a b c d : Prop}
(h : (c → d) → b) (h₀ : (d → b) → c → d) (h₁ : b → a) : a :=
begin
apply h₁,
apply h,
apply h₀,
intro h₂,
apply h,
intro h₃,
apply h₂
end
def ljt_lemmas := [`imp_of_or_imp_left,
`imp_of_or_imp_right,
`uncurry,
`imp_false_of_not,
`nested_imp_elim,
`id_locked,
`absurd]
/- some generally useful things -/
namespace util
def {u} list.first {α : Type u} (l : list α) (p : α → Prop) [decidable_pred p] : option α :=
list.rec_on l none (λ h hs recval, if p h then some h else recval)
meta def assertv_fresh (t : expr) (v : expr) : tactic unit :=
do n ← get_unused_name `h none,
assertv n t v >> return ()
meta def intro_fresh : tactic expr :=
get_unused_name `h none >>= intro
meta def deny_conclusion : tactic unit :=
do apply `(@classical.by_contradiction),
n ← get_unused_name `h none,
intro n >> return ()
meta def simplify_goal (S : simp_lemmas) (cfg : simp_config := {}) : tactic unit :=
do t ← target,
(new_t, pr) ← simplify S [] t cfg,
replace_target new_t pr
meta def simp (cfg : simp_config := {}) : tactic unit :=
do S ← simp_lemmas.mk_default,
simplify_goal S cfg >> try triv >> try (reflexivity reducible)
meta def simp_only (hs : list expr) (cfg : simp_config := {}) : tactic unit :=
do S ← simp_lemmas.mk.append hs,
simplify_goal S cfg >> try triv
meta def simp_only_at (h : expr) (hs : list expr := []) (cfg : simp_config := {}) :
tactic expr :=
do when (expr.is_local_constant h = ff)
(fail "tactic simp_only_at failed, the given expression is not a hypothesis"),
htype ← infer_type h,
S ← simp_lemmas.mk^.append hs,
(new_htype, heq) ← simplify S [] htype cfg,
newh ← assert (expr.local_pp_name h) new_htype,
mk_eq_mp heq h >>= exact,
try $ clear h,
return newh
meta def simph (cfg : simp_config := {}) : tactic unit :=
collect_ctx_simps >>= simp_only >> simp
meta def finish : tactic unit :=
assumption <|> contradiction <|> triv <|> `[linarith] <|> `[ring1]
/- negation normal form, disjunctive normal form, and conjunctive normal form -/
meta def elim_imp_lemmas : tactic (list expr) :=
monad.mapm to_expr [``(iff_iff_implies_and_implies), ``(implies_iff_not_or)]
meta def nnf_lemmas : tactic (list expr) :=
monad.mapm to_expr [``(not_and_iff), ``(not_or_iff), ``(not_not_iff), ``(not_true_iff),
``(not_false_iff), ``(true_and), ``(and_true), ``(false_and),
``(and_false), ``(true_or), ``(or_true), ``(false_or),
``(or_false), ``(not_false_iff), ``(not_true_iff)]
meta def dnf_lemmas : tactic (list expr) :=
monad.mapm to_expr [``(and_or_distrib), ``(and_or_distrib₂)]
meta def cnf_lemmas : tactic (list expr) :=
monad.mapm to_expr [``(or_and_distrib), ``(or_and_distrib₂)]
meta def and_or_assoc : tactic (list expr) :=
monad.mapm to_expr [``(@and_comm), ``(@and_assoc), ``(@or_comm), ``(@or_assoc)]
meta def nnf : tactic unit :=
do hs ← elim_imp_lemmas,
try $ simp_only hs,
hs ← nnf_lemmas,
try $ simp_only hs
meta def cnf : tactic unit :=
do nnf,
hs ← cnf_lemmas,
try $ simp_only hs,
hs ← and_or_assoc,
try $ simp_only hs
meta def dnf : tactic unit :=
do nnf,
hs ← dnf_lemmas,
try $ simp_only hs,
hs ← and_or_assoc,
try $ simp_only hs
meta def nnf_at (h : expr) : tactic expr :=
do hs ← elim_imp_lemmas,
h₁ ← (simp_only_at h hs <|> return h),
hs ← nnf_lemmas,
(simp_only_at h₁ hs <|> return h₁)
meta def cnf_at (h : expr) : tactic expr :=
do h₁ ← nnf_at h,
hs ← cnf_lemmas,
h₂ ← (simp_only_at h₁ hs <|> return h₁),
hs ← and_or_assoc,
(simp_only_at h₂ hs <|> return h₂)
meta def dnf_at (h : expr) : tactic expr :=
do h₁ ← nnf_at h,
hs ← dnf_lemmas,
h₂ ← (simp_only_at h₁ hs <|> return h₁),
hs ← and_or_assoc,
(simp_only_at h₂ hs <|> return h₂)
meta def nnf_hyps : tactic unit :=
do hyps ← local_context,
list.mmap nnf_at hyps >> return ()
end util
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.