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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5fba7d25df410af7e367e2b67db99e3f7847b406 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/linear_algebra/span.lean | 1b35892df4ab64043a1a6c709961e7f6586dccf1 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 33,880 | 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, Frédéric Dupuis,
Heather Macbeth
-/
import linear_algebra.basic
import order.omega_complete_partial_order
/-!
# The span of a set of vectors, as a submodule
* `submodule.span s` is defined to be the smallest submodule containing the set `s`.
## Notations
* We introduce the notation `R ∙ v` for the span of a singleton, `submodule.span R {v}`. This is
`\.`, not the same as the scalar multiplication `•`/`\bub`.
-/
variables {R R₂ K M M₂ V S : Type*}
namespace submodule
open function set
open_locale pointwise
section add_comm_monoid
variables [semiring R] [add_comm_monoid M] [module R M]
variables {x : M} (p p' : submodule R M)
variables [semiring R₂] {σ₁₂ : R →+* R₂}
variables [add_comm_monoid M₂] [module R₂ M₂]
section
variables (R)
/-- The span of a set `s ⊆ M` is the smallest submodule of M that contains `s`. -/
def span (s : set M) : submodule R M := Inf {p | s ⊆ p}
end
variables {s t : set M}
lemma mem_span : x ∈ span R s ↔ ∀ p : submodule R M, s ⊆ p → x ∈ p := mem_Inter₂
lemma subset_span : s ⊆ span R s :=
λ x h, mem_span.2 $ λ p hp, hp h
lemma span_le {p} : span R s ≤ p ↔ s ⊆ p :=
⟨subset.trans subset_span, λ ss x h, mem_span.1 h _ ss⟩
lemma span_mono (h : s ⊆ t) : span R s ≤ span R t :=
span_le.2 $ subset.trans h subset_span
lemma span_eq_of_le (h₁ : s ⊆ p) (h₂ : p ≤ span R s) : span R s = p :=
le_antisymm (span_le.2 h₁) h₂
lemma span_eq : span R (p : set M) = p :=
span_eq_of_le _ (subset.refl _) subset_span
/-- A version of `submodule.span_eq` for when the span is by a smaller ring. -/
@[simp] lemma span_coe_eq_restrict_scalars
[semiring S] [has_scalar S R] [module S M] [is_scalar_tower S R M] :
span S (p : set M) = p.restrict_scalars S :=
span_eq (p.restrict_scalars S)
lemma map_span [ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) (s : set M) :
(span R s).map f = span R₂ (f '' s) :=
eq.symm $ span_eq_of_le _ (set.image_subset f subset_span) $
map_le_iff_le_comap.2 $ span_le.2 $ λ x hx, subset_span ⟨x, hx, rfl⟩
alias submodule.map_span ← linear_map.map_span
lemma map_span_le [ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) (s : set M)
(N : submodule R₂ M₂) : map f (span R s) ≤ N ↔ ∀ m ∈ s, f m ∈ N :=
begin
rw [f.map_span, span_le, set.image_subset_iff],
exact iff.rfl
end
alias submodule.map_span_le ← linear_map.map_span_le
@[simp] lemma span_insert_zero : span R (insert (0 : M) s) = span R s :=
begin
refine le_antisymm _ (submodule.span_mono (set.subset_insert 0 s)),
rw [span_le, set.insert_subset],
exact ⟨by simp only [set_like.mem_coe, submodule.zero_mem], submodule.subset_span⟩,
end
/- See also `span_preimage_eq` below. -/
lemma span_preimage_le (f : M →ₛₗ[σ₁₂] M₂) (s : set M₂) :
span R (f ⁻¹' s) ≤ (span R₂ s).comap f :=
by { rw [span_le, comap_coe], exact preimage_mono (subset_span), }
alias submodule.span_preimage_le ← linear_map.span_preimage_le
/-- An induction principle for span membership. If `p` holds for 0 and all elements of `s`, and is
preserved under addition and scalar multiplication, then `p` holds for all elements of the span of
`s`. -/
@[elab_as_eliminator] lemma span_induction {p : M → Prop} (h : x ∈ span R s)
(Hs : ∀ x ∈ s, p x) (H0 : p 0)
(H1 : ∀ x y, p x → p y → p (x + y))
(H2 : ∀ (a:R) x, p x → p (a • x)) : p x :=
(@span_le _ _ _ _ _ _ ⟨p, H1, H0, H2⟩).2 Hs h
/-- A dependent version of `submodule.span_induction`. -/
lemma span_induction' {p : Π x, x ∈ span R s → Prop}
(Hs : ∀ x (h : x ∈ s), p x (subset_span h))
(H0 : p 0 (submodule.zero_mem _))
(H1 : ∀ x hx y hy, p x hx → p y hy → p (x + y) (submodule.add_mem _ ‹_› ‹_›))
(H2 : ∀ (a : R) x hx, p x hx → p (a • x) (submodule.smul_mem _ _ ‹_›)) {x} (hx : x ∈ span R s) :
p x hx :=
begin
refine exists.elim _ (λ (hx : x ∈ span R s) (hc : p x hx), hc),
refine span_induction hx (λ m hm, ⟨subset_span hm, Hs m hm⟩) ⟨zero_mem _, H0⟩
(λ x y hx hy, exists.elim hx $ λ hx' hx, exists.elim hy $ λ hy' hy,
⟨add_mem hx' hy', H1 _ _ _ _ hx hy⟩) (λ r x hx, exists.elim hx $ λ hx' hx,
⟨smul_mem _ _ hx', H2 r _ _ hx⟩)
end
@[simp] lemma span_span_coe_preimage : span R ((coe : span R s → M) ⁻¹' s) = ⊤ :=
eq_top_iff.2 $ λ x, subtype.rec_on x $ λ x hx _, begin
refine span_induction' (λ x hx, _) _ (λ x y _ _, _) (λ r x _, _) hx,
{ exact subset_span hx },
{ exact zero_mem _ },
{ exact add_mem },
{ exact smul_mem _ _ }
end
lemma span_nat_eq_add_submonoid_closure (s : set M) :
(span ℕ s).to_add_submonoid = add_submonoid.closure s :=
begin
refine eq.symm (add_submonoid.closure_eq_of_le subset_span _),
apply add_submonoid.to_nat_submodule.symm.to_galois_connection.l_le _,
rw span_le,
exact add_submonoid.subset_closure,
end
@[simp] lemma span_nat_eq (s : add_submonoid M) : (span ℕ (s : set M)).to_add_submonoid = s :=
by rw [span_nat_eq_add_submonoid_closure, s.closure_eq]
lemma span_int_eq_add_subgroup_closure {M : Type*} [add_comm_group M] (s : set M) :
(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.zsmul_mem _ ‹_› _)
@[simp] lemma span_int_eq {M : Type*} [add_comm_group M] (s : add_subgroup M) :
(span ℤ (s : set M)).to_add_subgroup = s :=
by rw [span_int_eq_add_subgroup_closure, s.closure_eq]
section
variables (R M)
/-- `span` forms a Galois insertion with the coercion from submodule to set. -/
protected def gi : galois_insertion (@span R M _ _ _) coe :=
{ choice := λ s _, span R s,
gc := λ s t, span_le,
le_l_u := λ s, subset_span,
choice_eq := λ s h, rfl }
end
@[simp] lemma span_empty : span R (∅ : set M) = ⊥ :=
(submodule.gi R M).gc.l_bot
@[simp] lemma span_univ : span R (univ : set M) = ⊤ :=
eq_top_iff.2 $ set_like.le_def.2 $ subset_span
lemma span_union (s t : set M) : span R (s ∪ t) = span R s ⊔ span R t :=
(submodule.gi R M).gc.l_sup
lemma span_Union {ι} (s : ι → set M) : span R (⋃ i, s i) = ⨆ i, span R (s i) :=
(submodule.gi R M).gc.l_supr
lemma span_Union₂ {ι} {κ : ι → Sort*} (s : Π i, κ i → set M) :
span R (⋃ i j, s i j) = ⨆ i j, span R (s i j) :=
(submodule.gi R M).gc.l_supr₂
lemma span_attach_bUnion [decidable_eq M] {α : Type*} (s : finset α) (f : s → finset M) :
span R (s.attach.bUnion f : set M) = ⨆ x, span R (f x) :=
by simpa [span_Union]
lemma sup_span : p ⊔ span R s = span R (p ∪ s) :=
by rw [submodule.span_union, p.span_eq]
lemma span_sup : span R s ⊔ p = span R (s ∪ p) :=
by rw [submodule.span_union, p.span_eq]
lemma span_eq_supr_of_singleton_spans (s : set M) : span R s = ⨆ x ∈ s, span R {x} :=
by simp only [←span_Union, set.bUnion_of_singleton s]
lemma span_smul_le (s : set M) (r : R) :
span R (r • s) ≤ span R s :=
begin
rw span_le,
rintros _ ⟨x, hx, rfl⟩,
exact smul_mem (span R s) r (subset_span hx),
end
lemma subset_span_trans {U V W : set M} (hUV : U ⊆ submodule.span R V)
(hVW : V ⊆ submodule.span R W) :
U ⊆ submodule.span R W :=
(submodule.gi R M).gc.le_u_l_trans hUV hVW
/-- See `submodule.span_smul_eq` (in `ring_theory.ideal.operations`) for
`span R (r • s) = r • span R s` that holds for arbitrary `r` in a `comm_semiring`. -/
lemma span_smul_eq_of_is_unit (s : set M) (r : R) (hr : is_unit r) :
span R (r • s) = span R s :=
begin
apply le_antisymm,
{ apply span_smul_le },
{ convert span_smul_le (r • s) ((hr.unit ⁻¹ : _) : R),
rw smul_smul,
erw hr.unit.inv_val,
rw one_smul }
end
@[simp] theorem coe_supr_of_directed {ι} [hι : nonempty ι]
(S : ι → submodule R M) (H : directed (≤) S) :
((supr S : submodule R M) : set M) = ⋃ i, S i :=
begin
refine subset.antisymm _ (Union_subset $ le_supr S),
suffices : (span R (⋃ i, (S i : set M)) : set M) ⊆ ⋃ (i : ι), ↑(S i),
by simpa only [span_Union, span_eq] using this,
refine (λ x hx, span_induction hx (λ _, id) _ _ _);
simp only [mem_Union, exists_imp_distrib],
{ exact hι.elim (λ i, ⟨i, (S i).zero_mem⟩) },
{ intros x y i hi j hj,
rcases H i j with ⟨k, ik, jk⟩,
exact ⟨k, add_mem (ik hi) (jk hj)⟩ },
{ exact λ a x i hi, ⟨i, smul_mem _ a hi⟩ },
end
@[simp] theorem mem_supr_of_directed {ι} [nonempty ι]
(S : ι → submodule R M) (H : directed (≤) S) {x} :
x ∈ supr S ↔ ∃ i, x ∈ S i :=
by { rw [← set_like.mem_coe, coe_supr_of_directed S H, mem_Union], refl }
theorem mem_Sup_of_directed {s : set (submodule R M)}
{z} (hs : s.nonempty) (hdir : directed_on (≤) s) :
z ∈ Sup s ↔ ∃ y ∈ s, z ∈ y :=
begin
haveI : nonempty s := hs.to_subtype,
simp only [Sup_eq_supr', mem_supr_of_directed _ hdir.directed_coe, set_coe.exists, subtype.coe_mk]
end
@[norm_cast, simp] lemma coe_supr_of_chain (a : ℕ →o submodule R M) :
(↑(⨆ k, a k) : set M) = ⋃ k, (a k : set M) :=
coe_supr_of_directed a a.monotone.directed_le
/-- We can regard `coe_supr_of_chain` as the statement that `coe : (submodule R M) → set M` is
Scott continuous for the ω-complete partial order induced by the complete lattice structures. -/
lemma coe_scott_continuous : omega_complete_partial_order.continuous'
(coe : submodule R M → set M) :=
⟨set_like.coe_mono, coe_supr_of_chain⟩
@[simp] lemma mem_supr_of_chain (a : ℕ →o submodule R M) (m : M) :
m ∈ (⨆ k, a k) ↔ ∃ k, m ∈ a k :=
mem_supr_of_directed a a.monotone.directed_le
section
variables {p p'}
lemma mem_sup : x ∈ p ⊔ p' ↔ ∃ (y ∈ p) (z ∈ p'), y + z = x :=
⟨λ h, begin
rw [← span_eq p, ← span_eq p', ← span_union] at h,
apply span_induction h,
{ rintro y (h | h),
{ exact ⟨y, h, 0, by simp, by simp⟩ },
{ exact ⟨0, by simp, y, h, by simp⟩ } },
{ exact ⟨0, by simp, 0, by simp⟩ },
{ rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩,
exact ⟨_, add_mem hy₁ hy₂, _, add_mem hz₁ hz₂, by simp [add_assoc]; cc⟩ },
{ rintro a _ ⟨y, hy, z, hz, rfl⟩,
exact ⟨_, smul_mem _ a hy, _, smul_mem _ a hz, by simp [smul_add]⟩ }
end,
by rintro ⟨y, hy, z, hz, rfl⟩; exact add_mem
((le_sup_left : p ≤ p ⊔ p') hy)
((le_sup_right : p' ≤ p ⊔ p') hz)⟩
lemma mem_sup' : x ∈ p ⊔ p' ↔ ∃ (y : p) (z : p'), (y:M) + z = x :=
mem_sup.trans $ by simp only [set_like.exists, coe_mk]
variables (p p')
lemma coe_sup : ↑(p ⊔ p') = (p + p' : set M) :=
by { ext, rw [set_like.mem_coe, mem_sup, set.mem_add], simp, }
lemma sup_to_add_submonoid :
(p ⊔ p').to_add_submonoid = p.to_add_submonoid ⊔ p'.to_add_submonoid :=
begin
ext x,
rw [mem_to_add_submonoid, mem_sup, add_submonoid.mem_sup],
refl,
end
lemma sup_to_add_subgroup {R M : Type*} [ring R] [add_comm_group M] [module R M]
(p p' : submodule R M) :
(p ⊔ p').to_add_subgroup = p.to_add_subgroup ⊔ p'.to_add_subgroup :=
begin
ext x,
rw [mem_to_add_subgroup, mem_sup, add_subgroup.mem_sup],
refl,
end
end
/- This is the character `∙`, with escape sequence `\.`, and is thus different from the scalar
multiplication character `•`, with escape sequence `\bub`. -/
notation R`∙`:1000 x := span R (@singleton _ _ set.has_singleton x)
lemma mem_span_singleton_self (x : M) : x ∈ R ∙ x := subset_span rfl
lemma nontrivial_span_singleton {x : M} (h : x ≠ 0) : nontrivial (R ∙ x) :=
⟨begin
use [0, x, submodule.mem_span_singleton_self x],
intros H,
rw [eq_comm, submodule.mk_eq_zero] at H,
exact h H
end⟩
lemma mem_span_singleton {y : M} : x ∈ (R ∙ y) ↔ ∃ a:R, a • y = x :=
⟨λ h, begin
apply span_induction h,
{ rintro y (rfl|⟨⟨⟩⟩), exact ⟨1, by simp⟩ },
{ exact ⟨0, by simp⟩ },
{ rintro _ _ ⟨a, rfl⟩ ⟨b, rfl⟩,
exact ⟨a + b, by simp [add_smul]⟩ },
{ rintro a _ ⟨b, rfl⟩,
exact ⟨a * b, by simp [smul_smul]⟩ }
end,
by rintro ⟨a, y, rfl⟩; exact
smul_mem _ _ (subset_span $ by simp)⟩
lemma le_span_singleton_iff {s : submodule R M} {v₀ : M} :
s ≤ (R ∙ v₀) ↔ ∀ v ∈ s, ∃ r : R, r • v₀ = v :=
by simp_rw [set_like.le_def, mem_span_singleton]
variables (R)
lemma span_singleton_eq_top_iff (x : M) : (R ∙ x) = ⊤ ↔ ∀ v, ∃ r : R, r • x = v :=
by { rw [eq_top_iff, le_span_singleton_iff], tauto }
@[simp] lemma span_zero_singleton : (R ∙ (0:M)) = ⊥ :=
by { ext, simp [mem_span_singleton, eq_comm] }
lemma span_singleton_eq_range (y : M) : ↑(R ∙ y) = range ((• y) : R → M) :=
set.ext $ λ x, mem_span_singleton
lemma span_singleton_smul_le {S} [monoid S] [has_scalar S R] [mul_action S M]
[is_scalar_tower S R M] (r : S) (x : M) : (R ∙ (r • x)) ≤ R ∙ x :=
begin
rw [span_le, set.singleton_subset_iff, set_like.mem_coe],
exact smul_of_tower_mem _ _ (mem_span_singleton_self _)
end
lemma span_singleton_group_smul_eq {G} [group G] [has_scalar G R] [mul_action G M]
[is_scalar_tower G R M] (g : G) (x : M) : (R ∙ (g • x)) = R ∙ x :=
begin
refine le_antisymm (span_singleton_smul_le R g x) _,
convert span_singleton_smul_le R (g⁻¹) (g • x),
exact (inv_smul_smul g x).symm
end
variables {R}
lemma span_singleton_smul_eq {r : R} (hr : is_unit r) (x : M) : (R ∙ (r • x)) = R ∙ x :=
begin
lift r to Rˣ using hr,
rw ←units.smul_def,
exact span_singleton_group_smul_eq R r x,
end
lemma disjoint_span_singleton {K E : Type*} [division_ring K] [add_comm_group E] [module K E]
{s : submodule K E} {x : E} :
disjoint s (K ∙ x) ↔ (x ∈ s → x = 0) :=
begin
refine disjoint_def.trans ⟨λ H hx, H x hx $ subset_span $ mem_singleton x, _⟩,
assume H y hy hyx,
obtain ⟨c, rfl⟩ := mem_span_singleton.1 hyx,
by_cases hc : c = 0,
{ rw [hc, zero_smul] },
{ rw [s.smul_mem_iff hc] at hy,
rw [H hy, smul_zero] }
end
lemma disjoint_span_singleton' {K E : Type*} [division_ring K] [add_comm_group E] [module K E]
{p : submodule K E} {x : E} (x0 : x ≠ 0) :
disjoint p (K ∙ x) ↔ x ∉ p :=
disjoint_span_singleton.trans ⟨λ h₁ h₂, x0 (h₁ h₂), λ h₁ h₂, (h₁ h₂).elim⟩
lemma mem_span_singleton_trans {x y z : M} (hxy : x ∈ R ∙ y) (hyz : y ∈ R ∙ z) :
x ∈ R ∙ z :=
begin
rw [← set_like.mem_coe, ← singleton_subset_iff] at *,
exact submodule.subset_span_trans hxy hyz
end
lemma mem_span_insert {y} : x ∈ span R (insert y s) ↔ ∃ (a:R) (z ∈ span R s), x = a • y + z :=
begin
simp only [← union_singleton, span_union, mem_sup, mem_span_singleton, exists_prop,
exists_exists_eq_and],
rw [exists_comm],
simp only [eq_comm, add_comm, exists_and_distrib_left]
end
lemma span_insert (x) (s : set M) : span R (insert x s) = span R ({x} : set M) ⊔ span R s :=
by rw [insert_eq, span_union]
lemma span_insert_eq_span (h : x ∈ span R s) : span R (insert x s) = span R s :=
span_eq_of_le _ (set.insert_subset.mpr ⟨h, subset_span⟩) (span_mono $ subset_insert _ _)
lemma span_span : span R (span R s : set M) = span R s := span_eq _
variables (R S s)
/-- If `R` is "smaller" ring than `S` then the span by `R` is smaller than the span by `S`. -/
lemma span_le_restrict_scalars [semiring S] [has_scalar R S] [module S M] [is_scalar_tower R S M] :
span R s ≤ (span S s).restrict_scalars R :=
submodule.span_le.2 submodule.subset_span
/-- A version of `submodule.span_le_restrict_scalars` with coercions. -/
@[simp] lemma span_subset_span [semiring S] [has_scalar R S] [module S M] [is_scalar_tower R S M] :
↑(span R s) ⊆ (span S s : set M) :=
span_le_restrict_scalars R S s
/-- Taking the span by a large ring of the span by the small ring is the same as taking the span
by just the large ring. -/
lemma span_span_of_tower [semiring S] [has_scalar R S] [module S M] [is_scalar_tower R S M] :
span S (span R s : set M) = span S s :=
le_antisymm (span_le.2 $ span_subset_span R S s) (span_mono subset_span)
variables {R S s}
lemma span_eq_bot : span R (s : set M) = ⊥ ↔ ∀ x ∈ s, (x:M) = 0 :=
eq_bot_iff.trans ⟨
λ H x h, (mem_bot R).1 $ H $ subset_span h,
λ H, span_le.2 (λ x h, (mem_bot R).2 $ H x h)⟩
@[simp] lemma span_singleton_eq_bot : (R ∙ x) = ⊥ ↔ x = 0 :=
span_eq_bot.trans $ by simp
@[simp] lemma span_zero : span R (0 : set M) = ⊥ := by rw [←singleton_zero, span_singleton_eq_bot]
lemma span_singleton_eq_span_singleton {R M : Type*} [ring R] [add_comm_group M] [module R M]
[no_zero_smul_divisors R M] {x y : M} : (R ∙ x) = (R ∙ y) ↔ ∃ z : Rˣ, z • x = y :=
begin
by_cases hx : x = 0,
{ rw [hx, span_zero_singleton, eq_comm, span_singleton_eq_bot],
exact ⟨λ hy, ⟨1, by rw [hy, smul_zero]⟩, λ ⟨_, hz⟩, by rw [← hz, smul_zero]⟩ },
by_cases hy : y = 0,
{ rw [hy, span_zero_singleton, span_singleton_eq_bot],
exact ⟨λ hx, ⟨1, by rw [hx, smul_zero]⟩, λ ⟨z, hz⟩, (smul_eq_zero_iff_eq z).mp hz⟩ },
split,
{ intro hxy,
cases mem_span_singleton.mp (by { rw [hxy], apply mem_span_singleton_self }) with v hv,
cases mem_span_singleton.mp (by { rw [← hxy], apply mem_span_singleton_self }) with i hi,
have vi : v * i = 1 :=
by { rw [← one_smul R y, ← hi, smul_smul] at hv, exact smul_left_injective R hy hv },
have iv : i * v = 1 :=
by { rw [← one_smul R x, ← hv, smul_smul] at hi, exact smul_left_injective R hx hi },
exact ⟨⟨v, i, vi, iv⟩, hv⟩ },
{ rintro ⟨v, rfl⟩,
rw span_singleton_group_smul_eq }
end
@[simp] lemma span_image [ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) :
span R₂ (f '' s) = map f (span R s) :=
(map_span f s).symm
lemma apply_mem_span_image_of_mem_span
[ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) {x : M} {s : set M} (h : x ∈ submodule.span R s) :
f x ∈ submodule.span R₂ (f '' s) :=
begin
rw submodule.span_image,
exact submodule.mem_map_of_mem h
end
@[simp] lemma map_subtype_span_singleton {p : submodule R M} (x : p) :
map p.subtype (R ∙ x) = R ∙ (x : M) :=
by simp [← span_image]
/-- `f` is an explicit argument so we can `apply` this theorem and obtain `h` as a new goal. -/
lemma not_mem_span_of_apply_not_mem_span_image
[ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) {x : M} {s : set M}
(h : f x ∉ submodule.span R₂ (f '' s)) :
x ∉ submodule.span R s :=
h.imp (apply_mem_span_image_of_mem_span f)
lemma supr_eq_span {ι : Sort*} (p : ι → submodule R M) :
(⨆ (i : ι), p i) = submodule.span R (⋃ (i : ι), ↑(p i)) :=
le_antisymm
(supr_le $ assume i, subset.trans (assume m hm, set.mem_Union.mpr ⟨i, hm⟩) subset_span)
(span_le.mpr $ Union_subset_iff.mpr $ assume i m hm, mem_supr_of_mem i hm)
lemma supr_to_add_submonoid {ι : Sort*} (p : ι → submodule R M) :
(⨆ i, p i).to_add_submonoid = ⨆ i, (p i).to_add_submonoid :=
begin
refine le_antisymm (λ x, _) (supr_le $ λ i, to_add_submonoid_mono $ le_supr _ i),
simp_rw [supr_eq_span, add_submonoid.supr_eq_closure, mem_to_add_submonoid, coe_to_add_submonoid],
intros hx,
refine submodule.span_induction hx (λ x hx, _) _ (λ x y hx hy, _) (λ r x hx, _),
{ exact add_submonoid.subset_closure hx },
{ exact add_submonoid.zero_mem _ },
{ exact add_submonoid.add_mem _ hx hy },
{ apply add_submonoid.closure_induction hx,
{ rintros x ⟨_, ⟨i, rfl⟩, hix : x ∈ p i⟩,
apply add_submonoid.subset_closure (set.mem_Union.mpr ⟨i, _⟩),
exact smul_mem _ r hix },
{ rw smul_zero,
exact add_submonoid.zero_mem _ },
{ intros x y hx hy,
rw smul_add,
exact add_submonoid.add_mem _ hx hy, } }
end
/-- An induction principle for elements of `⨆ i, p i`.
If `C` holds for `0` and all elements of `p i` for all `i`, and is preserved under addition,
then it holds for all elements of the supremum of `p`. -/
@[elab_as_eliminator]
lemma supr_induction {ι : Sort*} (p : ι → submodule R M) {C : M → Prop} {x : M} (hx : x ∈ ⨆ i, p i)
(hp : ∀ i (x ∈ p i), C x)
(h0 : C 0)
(hadd : ∀ x y, C x → C y → C (x + y)) : C x :=
begin
rw [←mem_to_add_submonoid, supr_to_add_submonoid] at hx,
exact add_submonoid.supr_induction _ hx hp h0 hadd,
end
/-- A dependent version of `submodule.supr_induction`. -/
@[elab_as_eliminator]
lemma supr_induction' {ι : Sort*} (p : ι → submodule R M) {C : Π x, (x ∈ ⨆ i, p i) → Prop}
(hp : ∀ i (x ∈ p i), C x (mem_supr_of_mem i ‹_›))
(h0 : C 0 (zero_mem _))
(hadd : ∀ x y hx hy, C x hx → C y hy → C (x + y) (add_mem ‹_› ‹_›))
{x : M} (hx : x ∈ ⨆ i, p i) : C x hx :=
begin
refine exists.elim _ (λ (hx : x ∈ ⨆ i, p i) (hc : C x hx), hc),
refine supr_induction p hx (λ i x hx, _) _ (λ x y, _),
{ exact ⟨_, hp _ _ hx⟩ },
{ exact ⟨_, h0⟩ },
{ rintro ⟨_, Cx⟩ ⟨_, Cy⟩,
refine ⟨_, hadd _ _ _ _ Cx Cy⟩ },
end
@[simp] lemma span_singleton_le_iff_mem (m : M) (p : submodule R M) : (R ∙ m) ≤ p ↔ m ∈ p :=
by rw [span_le, singleton_subset_iff, set_like.mem_coe]
lemma singleton_span_is_compact_element (x : M) :
complete_lattice.is_compact_element (span R {x} : submodule R M) :=
begin
rw complete_lattice.is_compact_element_iff_le_of_directed_Sup_le,
intros d hemp hdir hsup,
have : x ∈ Sup d, from (set_like.le_def.mp hsup) (mem_span_singleton_self x),
obtain ⟨y, ⟨hyd, hxy⟩⟩ := (mem_Sup_of_directed hemp hdir).mp this,
exact ⟨y, ⟨hyd, by simpa only [span_le, singleton_subset_iff]⟩⟩,
end
/-- The span of a finite subset is compact in the lattice of submodules. -/
lemma finset_span_is_compact_element (S : finset M) :
complete_lattice.is_compact_element (span R S : submodule R M) :=
begin
rw span_eq_supr_of_singleton_spans,
simp only [finset.mem_coe],
rw ←finset.sup_eq_supr,
exact complete_lattice.finset_sup_compact_of_compact S
(λ x _, singleton_span_is_compact_element x),
end
/-- The span of a finite subset is compact in the lattice of submodules. -/
lemma finite_span_is_compact_element (S : set M) (h : S.finite) :
complete_lattice.is_compact_element (span R S : submodule R M) :=
finite.coe_to_finset h ▸ (finset_span_is_compact_element h.to_finset)
instance : is_compactly_generated (submodule R M) :=
⟨λ s, ⟨(λ x, span R {x}) '' s, ⟨λ t ht, begin
rcases (set.mem_image _ _ _).1 ht with ⟨x, hx, rfl⟩,
apply singleton_span_is_compact_element,
end, by rw [Sup_eq_supr, supr_image, ←span_eq_supr_of_singleton_spans, span_eq]⟩⟩⟩
lemma lt_sup_iff_not_mem {I : submodule R M} {a : M} : I < I ⊔ (R ∙ a) ↔ a ∉ I :=
begin
split,
{ intro h,
by_contra akey,
have h1 : I ⊔ (R ∙ a) ≤ I,
{ simp only [sup_le_iff],
split,
{ exact le_refl I, },
{ exact (span_singleton_le_iff_mem a I).mpr akey, } },
have h2 := gt_of_ge_of_gt h1 h,
exact lt_irrefl I h2, },
{ intro h,
apply set_like.lt_iff_le_and_exists.mpr, split,
simp only [le_sup_left],
use a,
split, swap, { assumption, },
{ have : (R ∙ a) ≤ I ⊔ (R ∙ a) := le_sup_right,
exact this (mem_span_singleton_self a), } },
end
lemma mem_supr {ι : Sort*} (p : ι → submodule R M) {m : M} :
(m ∈ ⨆ i, p i) ↔ (∀ N, (∀ i, p i ≤ N) → m ∈ N) :=
begin
rw [← span_singleton_le_iff_mem, le_supr_iff],
simp only [span_singleton_le_iff_mem],
end
section
open_locale classical
/-- For every element in the span of a set, there exists a finite subset of the set
such that the element is contained in the span of the subset. -/
lemma mem_span_finite_of_mem_span {S : set M} {x : M} (hx : x ∈ span R S) :
∃ T : finset M, ↑T ⊆ S ∧ x ∈ span R (T : set M) :=
begin
refine span_induction hx (λ x hx, _) _ _ _,
{ refine ⟨{x}, _, _⟩,
{ rwa [finset.coe_singleton, set.singleton_subset_iff] },
{ rw finset.coe_singleton,
exact submodule.mem_span_singleton_self x } },
{ use ∅, simp },
{ rintros x y ⟨X, hX, hxX⟩ ⟨Y, hY, hyY⟩,
refine ⟨X ∪ Y, _, _⟩,
{ rw finset.coe_union,
exact set.union_subset hX hY },
rw [finset.coe_union, span_union, mem_sup],
exact ⟨x, hxX, y, hyY, rfl⟩, },
{ rintros a x ⟨T, hT, h2⟩,
exact ⟨T, hT, smul_mem _ _ h2⟩ }
end
end
variables {M' : Type*} [add_comm_monoid M'] [module R M'] (q₁ q₁' : submodule R M')
/-- The product of two submodules is a submodule. -/
def prod : submodule R (M × M') :=
{ carrier := (p : set M) ×ˢ (q₁ : set M'),
smul_mem' := by rintro a ⟨x, y⟩ ⟨hx, hy⟩; exact ⟨smul_mem _ a hx, smul_mem _ a hy⟩,
.. p.to_add_submonoid.prod q₁.to_add_submonoid }
@[simp] lemma prod_coe :
(prod p q₁ : set (M × M')) = (p : set M) ×ˢ (q₁ : set M') := rfl
@[simp] lemma mem_prod {p : submodule R M} {q : submodule R M'} {x : M × M'} :
x ∈ prod p q ↔ x.1 ∈ p ∧ x.2 ∈ q := set.mem_prod
lemma span_prod_le (s : set M) (t : set M') :
span R (s ×ˢ t) ≤ prod (span R s) (span R t) :=
span_le.2 $ set.prod_mono subset_span subset_span
@[simp] lemma prod_top : (prod ⊤ ⊤ : submodule R (M × M')) = ⊤ :=
by ext; simp
@[simp] lemma prod_bot : (prod ⊥ ⊥ : submodule R (M × M')) = ⊥ :=
by ext ⟨x, y⟩; simp [prod.zero_eq_mk]
lemma prod_mono {p p' : submodule R M} {q q' : submodule R M'} :
p ≤ p' → q ≤ q' → prod p q ≤ prod p' q' := prod_mono
@[simp] lemma prod_inf_prod : prod p q₁ ⊓ prod p' q₁' = prod (p ⊓ p') (q₁ ⊓ q₁') :=
set_like.coe_injective set.prod_inter_prod
@[simp] lemma prod_sup_prod : prod p q₁ ⊔ prod p' q₁' = prod (p ⊔ p') (q₁ ⊔ q₁') :=
begin
refine le_antisymm (sup_le
(prod_mono le_sup_left le_sup_left)
(prod_mono le_sup_right le_sup_right)) _,
simp [set_like.le_def], intros xx yy hxx hyy,
rcases mem_sup.1 hxx with ⟨x, hx, x', hx', rfl⟩,
rcases mem_sup.1 hyy with ⟨y, hy, y', hy', rfl⟩,
refine mem_sup.2 ⟨(x, y), ⟨hx, hy⟩, (x', y'), ⟨hx', hy'⟩, rfl⟩
end
end add_comm_monoid
section add_comm_group
variables [ring R] [add_comm_group M] [module R M]
@[simp] lemma span_neg (s : set M) : span R (-s) = span R s :=
calc span R (-s) = span R ((-linear_map.id : M →ₗ[R] M) '' s) : by simp
... = map (-linear_map.id) (span R s) : ((-linear_map.id).map_span _).symm
... = span R s : by simp
lemma mem_span_insert' {x y} {s : set M} : x ∈ span R (insert y s) ↔ ∃(a:R), x + a • y ∈ span R s :=
begin
rw mem_span_insert, split,
{ rintro ⟨a, z, hz, rfl⟩, exact ⟨-a, by simp [hz, add_assoc]⟩ },
{ rintro ⟨a, h⟩, exact ⟨-a, _, h, by simp [add_comm, add_left_comm]⟩ }
end
instance : is_modular_lattice (submodule R M) :=
⟨λ x y z xz a ha, begin
rw [mem_inf, mem_sup] at ha,
rcases ha with ⟨⟨b, hb, c, hc, rfl⟩, haz⟩,
rw mem_sup,
refine ⟨b, hb, c, mem_inf.2 ⟨hc, _⟩, rfl⟩,
rw [← add_sub_cancel c b, add_comm],
apply z.sub_mem haz (xz hb),
end⟩
end add_comm_group
section add_comm_group
variables [semiring R] [semiring R₂]
variables [add_comm_group M] [module R M] [add_comm_group M₂] [module R₂ M₂]
variables {τ₁₂ : R →+* R₂} [ring_hom_surjective τ₁₂]
lemma comap_map_eq (f : M →ₛₗ[τ₁₂] M₂) (p : submodule R M) :
comap f (map f p) = p ⊔ f.ker :=
begin
refine le_antisymm _ (sup_le (le_comap_map _ _) (comap_mono bot_le)),
rintro x ⟨y, hy, e⟩,
exact mem_sup.2 ⟨y, hy, x - y, by simpa using sub_eq_zero.2 e.symm, by simp⟩
end
lemma comap_map_eq_self {f : M →ₛₗ[τ₁₂] M₂} {p : submodule R M} (h : f.ker ≤ p) :
comap f (map f p) = p :=
by rw [submodule.comap_map_eq, sup_of_le_left h]
end add_comm_group
end submodule
namespace linear_map
open submodule function
section add_comm_group
variables [semiring R] [semiring R₂]
variables [add_comm_group M] [add_comm_group M₂]
variables [module R M] [module R₂ M₂]
variables {τ₁₂ : R →+* R₂} [ring_hom_surjective τ₁₂]
include R
protected lemma map_le_map_iff (f : M →ₛₗ[τ₁₂] M₂) {p p'} : map f p ≤ map f p' ↔ p ≤ p' ⊔ ker f :=
by rw [map_le_iff_le_comap, submodule.comap_map_eq]
theorem map_le_map_iff' {f : M →ₛₗ[τ₁₂] M₂} (hf : ker f = ⊥) {p p'} :
map f p ≤ map f p' ↔ p ≤ p' :=
by rw [linear_map.map_le_map_iff, hf, sup_bot_eq]
theorem map_injective {f : M →ₛₗ[τ₁₂] M₂} (hf : ker f = ⊥) : injective (map f) :=
λ p p' h, le_antisymm ((map_le_map_iff' hf).1 (le_of_eq h)) ((map_le_map_iff' hf).1 (ge_of_eq h))
theorem map_eq_top_iff {f : M →ₛₗ[τ₁₂] M₂} (hf : range f = ⊤) {p : submodule R M} :
p.map f = ⊤ ↔ p ⊔ f.ker = ⊤ :=
by simp_rw [← top_le_iff, ← hf, range_eq_map, linear_map.map_le_map_iff]
end add_comm_group
section
variables (R) (M) [semiring R] [add_comm_monoid M] [module R M]
/-- Given an element `x` of a module `M` over `R`, the natural map from
`R` to scalar multiples of `x`.-/
@[simps] def to_span_singleton (x : M) : R →ₗ[R] M := linear_map.id.smul_right x
/-- The range of `to_span_singleton x` is the span of `x`.-/
lemma span_singleton_eq_range (x : M) : (R ∙ x) = (to_span_singleton R M x).range :=
submodule.ext $ λ y, by {refine iff.trans _ linear_map.mem_range.symm, exact mem_span_singleton }
lemma to_span_singleton_one (x : M) : to_span_singleton R M x 1 = x := one_smul _ _
end
section add_comm_monoid
variables [semiring R] [add_comm_monoid M] [module R M]
variables [semiring R₂] [add_comm_monoid M₂] [module R₂ M₂]
variables {σ₁₂ : R →+* R₂}
/-- If two linear maps are equal on a set `s`, then they are equal on `submodule.span s`.
See also `linear_map.eq_on_span'` for a version using `set.eq_on`. -/
lemma eq_on_span {s : set M} {f g : M →ₛₗ[σ₁₂] M₂} (H : set.eq_on f g s) ⦃x⦄ (h : x ∈ span R s) :
f x = g x :=
by apply span_induction h H; simp {contextual := tt}
/-- If two linear maps are equal on a set `s`, then they are equal on `submodule.span s`.
This version uses `set.eq_on`, and the hidden argument will expand to `h : x ∈ (span R s : set M)`.
See `linear_map.eq_on_span` for a version that takes `h : x ∈ span R s` as an argument. -/
lemma eq_on_span' {s : set M} {f g : M →ₛₗ[σ₁₂] M₂} (H : set.eq_on f g s) :
set.eq_on f g (span R s : set M) :=
eq_on_span H
/-- If `s` generates the whole module and linear maps `f`, `g` are equal on `s`, then they are
equal. -/
lemma ext_on {s : set M} {f g : M →ₛₗ[σ₁₂] M₂} (hv : span R s = ⊤) (h : set.eq_on f g s) :
f = g :=
linear_map.ext (λ x, eq_on_span h (eq_top_iff'.1 hv _))
/-- If the range of `v : ι → M` generates the whole module and linear maps `f`, `g` are equal at
each `v i`, then they are equal. -/
lemma ext_on_range {ι : Type*} {v : ι → M} {f g : M →ₛₗ[σ₁₂] M₂} (hv : span R (set.range v) = ⊤)
(h : ∀i, f (v i) = g (v i)) : f = g :=
ext_on hv (set.forall_range_iff.2 h)
end add_comm_monoid
section field
variables {K V} [field K] [add_comm_group V] [module K V]
noncomputable theory
open_locale classical
lemma span_singleton_sup_ker_eq_top (f : V →ₗ[K] K) {x : V} (hx : f x ≠ 0) :
(K ∙ x) ⊔ f.ker = ⊤ :=
eq_top_iff.2 (λ y hy, submodule.mem_sup.2 ⟨(f y * (f x)⁻¹) • x,
submodule.mem_span_singleton.2 ⟨f y * (f x)⁻¹, rfl⟩,
⟨y - (f y * (f x)⁻¹) • x,
by rw [linear_map.mem_ker, f.map_sub, f.map_smul, smul_eq_mul, mul_assoc,
inv_mul_cancel hx, mul_one, sub_self],
by simp only [add_sub_cancel'_right]⟩⟩)
variables (K V)
lemma ker_to_span_singleton {x : V} (h : x ≠ 0) : (to_span_singleton K V x).ker = ⊥ :=
begin
ext c, split,
{ intros hc, rw submodule.mem_bot, rw mem_ker at hc, by_contra hc',
have : x = 0,
calc x = c⁻¹ • (c • x) : by rw [← mul_smul, inv_mul_cancel hc', one_smul]
... = c⁻¹ • ((to_span_singleton K V x) c) : rfl
... = 0 : by rw [hc, smul_zero],
tauto },
{ rw [mem_ker, submodule.mem_bot], intros h, rw h, simp }
end
end field
end linear_map
open linear_map
namespace linear_equiv
section field
variables (K V) [field K] [add_comm_group V] [module K V]
/-- Given a nonzero element `x` of a vector space `V` over a field `K`, the natural
map from `K` to the span of `x`, with invertibility check to consider it as an
isomorphism.-/
def to_span_nonzero_singleton (x : V) (h : x ≠ 0) : K ≃ₗ[K] (K ∙ x) :=
linear_equiv.trans
(linear_equiv.of_injective
(linear_map.to_span_singleton K V x) (ker_eq_bot.1 $ linear_map.ker_to_span_singleton K V h))
(linear_equiv.of_eq (to_span_singleton K V x).range (K ∙ x)
(span_singleton_eq_range K V x).symm)
lemma to_span_nonzero_singleton_one (x : V) (h : x ≠ 0) :
linear_equiv.to_span_nonzero_singleton K V x h 1 =
(⟨x, submodule.mem_span_singleton_self x⟩ : K ∙ x) :=
begin
apply set_like.coe_eq_coe.mp,
have : ↑(to_span_nonzero_singleton K V x h 1) = to_span_singleton K V x 1 := rfl,
rw [this, to_span_singleton_one, submodule.coe_mk],
end
/-- Given a nonzero element `x` of a vector space `V` over a field `K`, the natural map
from the span of `x` to `K`.-/
abbreviation coord (x : V) (h : x ≠ 0) : (K ∙ x) ≃ₗ[K] K :=
(to_span_nonzero_singleton K V x h).symm
lemma coord_self (x : V) (h : x ≠ 0) :
(coord K V x h) (⟨x, submodule.mem_span_singleton_self x⟩ : K ∙ x) = 1 :=
by rw [← to_span_nonzero_singleton_one K V x h, linear_equiv.symm_apply_apply]
end field
end linear_equiv
|
70ff15d52a91351d487f0e79c694fbd65410c855 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/run/pattern3.lean | e239df386089514bcec7bd93dea3932a0956a437 | [
"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 | 126 | lean | constant Sum : (nat → nat) → nat → nat
attribute [forward]
lemma l1 (f : nat → nat) : Sum f 0 = 0 :=
sorry
print l1
|
28501af5e96560242bb2b029ce8506b284f5514f | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/data/finsupp.lean | 40b9e7485d56bf5f4ec2599957e35b3921c1b9d9 | [
"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 | 61,653 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
Type of functions with finite support.
Functions with finite support provide the basis for the following concrete instances:
* ℕ →₀ α: Polynomials (where α is a ring)
* (σ →₀ ℕ) →₀ α: Multivariate Polynomials (again α is a ring, and σ are variable names)
* α →₀ ℕ: Multisets
* α →₀ ℤ: Abelian groups freely generated by α
* β →₀ α: Linear combinations over β where α is the scalar ring
Most of the theory assumes that the range is a commutative monoid. This gives us the big sum
operator as a powerful way to construct `finsupp` elements.
A general advice is to not use α →₀ β directly, as the type class setup might not be fitting.
The best is to define a copy and select the instances best suited.
-/
import data.finset data.set.finite algebra.big_operators algebra.module
noncomputable theory
open_locale classical
open finset
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Type*}
{α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*}
/-- `finsupp α β`, denoted `α →₀ β`, is the type of functions `f : α → β` such that
`f x = 0` for all but finitely many `x`. -/
structure finsupp (α : Type*) (β : Type*) [has_zero β] :=
(support : finset α)
(to_fun : α → β)
(mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0)
infixr ` →₀ `:25 := finsupp
namespace finsupp
section basic
variable [has_zero β]
instance : has_coe_to_fun (α →₀ β) := ⟨λ_, α → β, finsupp.to_fun⟩
instance : has_zero (α →₀ β) := ⟨⟨∅, (λ_, 0), λ _, ⟨false.elim, λ H, H rfl⟩⟩⟩
@[simp] lemma zero_apply {a : α} : (0 : α →₀ β) a = 0 := rfl
@[simp] lemma support_zero : (0 : α →₀ β).support = ∅ := rfl
instance : inhabited (α →₀ β) := ⟨0⟩
@[simp] lemma mem_support_iff {f : α →₀ β} : ∀{a:α}, a ∈ f.support ↔ f a ≠ 0 :=
f.mem_support_to_fun
lemma not_mem_support_iff {f : α →₀ β} {a} : a ∉ f.support ↔ f a = 0 :=
not_iff_comm.1 mem_support_iff.symm
@[ext]
lemma ext : ∀{f g : α →₀ β}, (∀a, f a = g a) → f = g
| ⟨s, f, hf⟩ ⟨t, g, hg⟩ h :=
begin
have : f = g, { funext a, exact h a },
subst this,
have : s = t, { ext a, exact (hf a).trans (hg a).symm },
subst this
end
lemma ext_iff {f g : α →₀ β} : f = g ↔ (∀a:α, f a = g a) :=
⟨by rintros rfl a; refl, ext⟩
@[simp] lemma support_eq_empty {f : α →₀ β} : f.support = ∅ ↔ f = 0 :=
⟨assume h, ext $ assume a, by_contradiction $ λ H, (finset.ext.1 h a).1 $
mem_support_iff.2 H, by rintro rfl; refl⟩
instance finsupp.decidable_eq [decidable_eq α] [decidable_eq β] : decidable_eq (α →₀ β) :=
assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a))
⟨assume ⟨h₁, h₂⟩, ext $ assume a,
if h : a ∈ f.support then h₂ a h else
have hf : f a = 0, by rwa [mem_support_iff, not_not] at h,
have hg : g a = 0, by rwa [h₁, mem_support_iff, not_not] at h,
by rw [hf, hg],
by rintro rfl; exact ⟨rfl, λ _ _, rfl⟩⟩
lemma finite_supp (f : α →₀ β) : set.finite {a | f a ≠ 0} :=
⟨fintype.of_finset f.support (λ _, mem_support_iff)⟩
lemma support_subset_iff {s : set α} {f : α →₀ β} :
↑f.support ⊆ s ↔ (∀a∉s, f a = 0) :=
by simp only [set.subset_def, mem_coe, mem_support_iff];
exact forall_congr (assume a, @not_imp_comm _ _ (classical.dec _) (classical.dec _))
def equiv_fun_on_fintype [fintype α] : (α →₀ β) ≃ (α → β) :=
⟨λf a, f a, λf, mk (finset.univ.filter $ λa, f a ≠ 0) f (by simp),
begin intro f, ext a, refl end,
begin intro f, ext a, refl end⟩
end basic
section single
variables [has_zero β] {a a' : α} {b : β}
/-- `single a b` is the finitely supported function which has
value `b` at `a` and zero otherwise. -/
def single (a : α) (b : β) : α →₀ β :=
⟨if b = 0 then ∅ else finset.singleton a, λ a', if a = a' then b else 0, λ a', begin
by_cases hb : b = 0; by_cases a = a';
simp only [hb, h, if_pos, if_false, mem_singleton],
{ exact ⟨false.elim, λ H, H rfl⟩ },
{ exact ⟨false.elim, λ H, H rfl⟩ },
{ exact ⟨λ _, hb, λ _, rfl⟩ },
{ exact ⟨λ H _, h H.symm, λ H, (H rfl).elim⟩ }
end⟩
lemma single_apply : (single a b : α →₀ β) a' = if a = a' then b else 0 := rfl
@[simp] lemma single_eq_same : (single a b : α →₀ β) a = b := if_pos rfl
@[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ β) a' = 0 := if_neg h
@[simp] lemma single_zero : (single a 0 : α →₀ β) = 0 :=
ext $ assume a',
begin
by_cases h : a = a',
{ rw [h, single_eq_same, zero_apply] },
{ rw [single_eq_of_ne h, zero_apply] }
end
lemma support_single_ne_zero (hb : b ≠ 0) : (single a b).support = {a} :=
if_neg hb
lemma support_single_subset : (single a b).support ⊆ {a} :=
show ite _ _ _ ⊆ _, by split_ifs; [exact empty_subset _, exact subset.refl _]
lemma injective_single (a : α) : function.injective (single a : β → α →₀ β) :=
assume b₁ b₂ eq,
have (single a b₁ : α →₀ β) a = (single a b₂ : α →₀ β) a, by rw eq,
by rwa [single_eq_same, single_eq_same] at this
lemma single_eq_single_iff (a₁ a₂ : α) (b₁ b₂ : β) :
single a₁ b₁ = single a₂ b₂ ↔ ((a₁ = a₂ ∧ b₁ = b₂) ∨ (b₁ = 0 ∧ b₂ = 0)) :=
begin
split,
{ assume eq,
by_cases a₁ = a₂,
{ refine or.inl ⟨h, _⟩,
rwa [h, (injective_single a₂).eq_iff] at eq },
{ rw [finsupp.ext_iff] at eq,
have h₁ := eq a₁,
have h₂ := eq a₂,
simp only [single_eq_same, single_eq_of_ne h, single_eq_of_ne (ne.symm h)] at h₁ h₂,
exact or.inr ⟨h₁, h₂.symm⟩ } },
{ rintros (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩),
{ refl },
{ rw [single_zero, single_zero] } }
end
lemma single_right_inj (h : b ≠ 0) :
single a b = single a' b ↔ a = a' :=
⟨λ H, by simpa [h, single_eq_single_iff] using H, λ H, by rw [H]⟩
lemma single_eq_zero : single a b = 0 ↔ b = 0 :=
⟨λ h, by { rw ext_iff at h, simpa only [finsupp.single_eq_same, finsupp.zero_apply] using h a },
λ h, by rw [h, single_zero]⟩
lemma single_swap {α β : Type*} [has_zero β] (a₁ a₂ : α) (b : β) :
(single a₁ b : α → β) a₂ = (single a₂ b : α → β) a₁ :=
by simp [single_apply]; ac_refl
lemma unique_single [unique α] (x : α →₀ β) : x = single (default α) (x (default α)) :=
by ext i; simp [unique.eq_default i]
@[simp] lemma unique_single_eq_iff [unique α] {b' : β} :
single a b = single a' b' ↔ b = b' :=
begin
rw [single_eq_single_iff],
split,
{ rintros (⟨_, rfl⟩ | ⟨rfl, rfl⟩); refl },
{ intro h, left, exact ⟨subsingleton.elim _ _, h⟩ }
end
end single
section on_finset
variables [has_zero β]
/-- `on_finset s f hf` is the finsupp function representing `f` restricted to the set `s`.
The function needs to be 0 outside of `s`. Use this when the set needs filtered anyway, otherwise
often better set representation is available. -/
def on_finset (s : finset α) (f : α → β) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ β :=
⟨s.filter (λa, f a ≠ 0), f,
assume a, classical.by_cases
(assume h : f a = 0, by rw mem_filter; exact ⟨and.right, λ H, (H h).elim⟩)
(assume h : f a ≠ 0, by rw mem_filter; simp only [iff_true_intro h, hf a h, true_and])⟩
@[simp] lemma on_finset_apply {s : finset α} {f : α → β} {hf a} :
(on_finset s f hf : α →₀ β) a = f a :=
rfl
@[simp] lemma support_on_finset_subset {s : finset α} {f : α → β} {hf} :
(on_finset s f hf).support ⊆ s := filter_subset _
end on_finset
section map_range
variables [has_zero β₁] [has_zero β₂]
/-- The composition of `f : β₁ → β₂` and `g : α →₀ β₁` is
`map_range f hf g : α →₀ β₂`, well defined when `f 0 = 0`. -/
def map_range (f : β₁ → β₂) (hf : f 0 = 0) (g : α →₀ β₁) : α →₀ β₂ :=
on_finset g.support (f ∘ g) $
assume a, by rw [mem_support_iff, not_imp_not]; exact λ H, (congr_arg f H).trans hf
@[simp] lemma map_range_apply {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {a : α} :
map_range f hf g a = f (g a) :=
rfl
@[simp] lemma map_range_zero {f : β₁ → β₂} {hf : f 0 = 0} : map_range f hf (0 : α →₀ β₁) = 0 :=
finsupp.ext $ λ a, by simp [hf]
lemma support_map_range {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} :
(map_range f hf g).support ⊆ g.support :=
support_on_finset_subset
@[simp] lemma map_range_single {f : β₁ → β₂} {hf : f 0 = 0} {a : α} {b : β₁} :
map_range f hf (single a b) = single a (f b) :=
finsupp.ext $ λ a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf]
end map_range
section emb_domain
variables [has_zero β]
/-- Given `f : α₁ ↪ α₂` and `v : α₁ →₀ β`, `emb_domain f v : α₂ →₀ β` is the finitely supported
function whose value at `f a : α₂` is `v a`. For a `b : α₂` outside the range of `f` it is zero. -/
def emb_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) : α₂ →₀ β :=
begin
refine ⟨v.support.map f, λa₂,
if h : a₂ ∈ v.support.map f then v (v.support.choose (λa₁, f a₁ = a₂) _) else 0, _⟩,
{ rcases finset.mem_map.1 h with ⟨a, ha, rfl⟩,
exact exists_unique.intro a ⟨ha, rfl⟩ (assume b ⟨_, hb⟩, f.inj hb) },
{ assume a₂,
split_ifs,
{ simp [h],
rw [← finsupp.not_mem_support_iff, not_not],
apply finset.choose_mem },
{ simp [h] } }
end
lemma support_emb_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) :
(emb_domain f v).support = v.support.map f :=
rfl
lemma emb_domain_zero (f : α₁ ↪ α₂) : (emb_domain f 0 : α₂ →₀ β) = 0 :=
rfl
lemma emb_domain_apply (f : α₁ ↪ α₂) (v : α₁ →₀ β) (a : α₁) :
emb_domain f v (f a) = v a :=
begin
change dite _ _ _ = _,
split_ifs; rw [finset.mem_map' f] at h,
{ refine congr_arg (v : α₁ → β) (f.inj' _),
exact finset.choose_property (λa₁, f a₁ = f a) _ _ },
{ exact (finsupp.not_mem_support_iff.1 h).symm }
end
lemma emb_domain_notin_range (f : α₁ ↪ α₂) (v : α₁ →₀ β) (a : α₂) (h : a ∉ set.range f) :
emb_domain f v a = 0 :=
begin
refine dif_neg (mt (assume h, _) h),
rcases finset.mem_map.1 h with ⟨a, h, rfl⟩,
exact set.mem_range_self a
end
lemma emb_domain_inj {f : α₁ ↪ α₂} {l₁ l₂ : α₁ →₀ β} :
emb_domain f l₁ = emb_domain f l₂ ↔ l₁ = l₂ :=
⟨λ h, finsupp.ext $ λ a, by simpa [emb_domain_apply] using finsupp.ext_iff.1 h (f a),
λ h, by rw h⟩
lemma emb_domain_map_range
{β₁ β₂ : Type*} [has_zero β₁] [has_zero β₂]
(f : α₁ ↪ α₂) (g : β₁ → β₂) (p : α₁ →₀ β₁) (hg : g 0 = 0) :
emb_domain f (map_range g hg p) = map_range g hg (emb_domain f p) :=
begin
ext a,
by_cases a ∈ set.range f,
{ rcases h with ⟨a', rfl⟩,
rw [map_range_apply, emb_domain_apply, emb_domain_apply, map_range_apply] },
{ rw [map_range_apply, emb_domain_notin_range, emb_domain_notin_range, ← hg]; assumption }
end
lemma single_of_emb_domain_single
(l : α₁ →₀ β) (f : α₁ ↪ α₂) (a : α₂) (b : β) (hb : b ≠ 0)
(h : l.emb_domain f = finsupp.single a b) :
∃ x, l = finsupp.single x b ∧ f x = a :=
begin
have h_map_support : finset.map f (l.support) = finset.singleton a,
by rw [←finsupp.support_emb_domain, h, finsupp.support_single_ne_zero hb]; refl,
have ha : a ∈ finset.map f (l.support),
by simp [h_map_support],
rcases finset.mem_map.1 ha with ⟨c, hc₁, hc₂⟩,
use c,
split,
{ ext d,
rw [← finsupp.emb_domain_apply f l, h],
by_cases h_cases : c = d,
{ simp [h_cases.symm, hc₂] },
{ rw [finsupp.single_apply, finsupp.single_apply, if_neg, if_neg h_cases],
by_contra hfd,
exact h_cases (f.inj (hc₂.trans hfd)) } },
{ exact hc₂ }
end
end emb_domain
section zip_with
variables [has_zero β] [has_zero β₁] [has_zero β₂]
/-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying
`zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and well defined when `f 0 0 = 0`. -/
def zip_with (f : β₁ → β₂ → β) (hf : f 0 0 = 0) (g₁ : α →₀ β₁) (g₂ : α →₀ β₂) : (α →₀ β) :=
on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ λ a H, begin
simp only [mem_union, mem_support_iff, ne], rw [← not_and_distrib],
rintro ⟨h₁, h₂⟩, rw [h₁, h₂] at H, exact H hf
end
@[simp] lemma zip_with_apply
{f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} {a : α} :
zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) := rfl
lemma support_zip_with {f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} :
(zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support :=
support_on_finset_subset
end zip_with
section erase
def erase [has_zero β] (a : α) (f : α →₀ β) : α →₀ β :=
⟨f.support.erase a, (λa', if a' = a then 0 else f a'),
assume a', by rw [mem_erase, mem_support_iff]; split_ifs;
[exact ⟨λ H _, H.1 h, λ H, (H rfl).elim⟩,
exact and_iff_right h]⟩
@[simp] lemma support_erase [has_zero β] {a : α} {f : α →₀ β} :
(f.erase a).support = f.support.erase a :=
rfl
@[simp] lemma erase_same [has_zero β] {a : α} {f : α →₀ β} : (f.erase a) a = 0 :=
if_pos rfl
@[simp] lemma erase_ne [has_zero β] {a a' : α} {f : α →₀ β} (h : a' ≠ a) : (f.erase a) a' = f a' :=
if_neg h
end erase
-- [to_additive sum] for finsupp.prod doesn't work, the equation lemmas are not generated
/-- `sum f g` is the sum of `g a (f a)` over the support of `f`. -/
def sum [has_zero β] [add_comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ :=
f.support.sum (λa, g a (f a))
/-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/
@[to_additive]
def prod [has_zero β] [comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ :=
f.support.prod (λa, g a (f a))
@[to_additive]
lemma prod_map_range_index [has_zero β₁] [has_zero β₂] [comm_monoid γ]
{f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {h : α → β₂ → γ} (h0 : ∀a, h a 0 = 1) :
(map_range f hf g).prod h = g.prod (λa b, h a (f b)) :=
finset.prod_subset support_map_range $ λ _ _ H,
by rw [not_mem_support_iff.1 H, h0]
@[to_additive]
lemma prod_zero_index [add_comm_monoid β] [comm_monoid γ] {h : α → β → γ} :
(0 : α →₀ β).prod h = 1 := rfl
section nat_sub
instance nat_sub : has_sub (α →₀ ℕ) := ⟨zip_with (λ m n, m - n) (nat.sub_zero 0)⟩
@[simp] lemma nat_sub_apply {g₁ g₂ : α →₀ ℕ} {a : α} :
(g₁ - g₂) a = g₁ a - g₂ a := rfl
end nat_sub
section add_monoid
variables [add_monoid β]
@[to_additive]
lemma prod_single_index [comm_monoid γ] {a : α} {b : β} {h : α → β → γ} (h_zero : h a 0 = 1) :
(single a b).prod h = h a b :=
begin
by_cases h : b = 0,
{ simp only [h, h_zero, single_zero]; refl },
{ simp only [finsupp.prod, support_single_ne_zero h, insert_empty_eq_singleton,
prod_singleton, single_eq_same] }
end
instance : has_add (α →₀ β) := ⟨zip_with (+) (add_zero 0)⟩
@[simp] lemma add_apply {g₁ g₂ : α →₀ β} {a : α} : (g₁ + g₂) a = g₁ a + g₂ a :=
rfl
lemma support_add {g₁ g₂ : α →₀ β} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support :=
support_zip_with
lemma support_add_eq {g₁ g₂ : α →₀ β} (h : disjoint g₁.support g₂.support) :
(g₁ + g₂).support = g₁.support ∪ g₂.support :=
le_antisymm support_zip_with $ assume a ha,
(finset.mem_union.1 ha).elim
(assume ha, have a ∉ g₂.support, from disjoint_left.1 h ha,
by simp only [mem_support_iff, not_not] at *;
simpa only [add_apply, this, add_zero])
(assume ha, have a ∉ g₁.support, from disjoint_right.1 h ha,
by simp only [mem_support_iff, not_not] at *;
simpa only [add_apply, this, zero_add])
@[simp] lemma single_add {a : α} {b₁ b₂ : β} : single a (b₁ + b₂) = single a b₁ + single a b₂ :=
ext $ assume a',
begin
by_cases h : a = a',
{ rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] },
{ rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] }
end
instance : add_monoid (α →₀ β) :=
{ add_monoid .
zero := 0,
add := (+),
add_assoc := assume ⟨s, f, hf⟩ ⟨t, g, hg⟩ ⟨u, h, hh⟩, ext $ assume a, add_assoc _ _ _,
zero_add := assume ⟨s, f, hf⟩, ext $ assume a, zero_add _,
add_zero := assume ⟨s, f, hf⟩, ext $ assume a, add_zero _ }
instance (a : α) : is_add_monoid_hom (λ g : α →₀ β, g a) :=
{ map_add := λ _ _, add_apply, map_zero := zero_apply }
lemma single_add_erase {a : α} {f : α →₀ β} : single a (f a) + f.erase a = f :=
ext $ λ a',
if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, add_zero]
else by simp only [add_apply, single_eq_of_ne h, zero_add, erase_ne (ne.symm h)]
lemma erase_add_single {a : α} {f : α →₀ β} : f.erase a + single a (f a) = f :=
ext $ λ a',
if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, zero_add]
else by simp only [add_apply, single_eq_of_ne h, add_zero, erase_ne (ne.symm h)]
@[elab_as_eliminator]
protected theorem induction {p : (α →₀ β) → Prop} (f : α →₀ β)
(h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) :
p f :=
suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl,
assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $
assume a s has ih f hf,
suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this,
begin
apply ha,
{ rw [support_erase, mem_erase], exact λ H, H.1 rfl },
{ rw [← mem_support_iff, hf], exact mem_insert_self _ _ },
{ apply ih _ _,
rw [support_erase, hf, finset.erase_insert has] }
end
lemma induction₂ {p : (α →₀ β) → Prop} (f : α →₀ β)
(h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) :
p f :=
suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl,
assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $
assume a s has ih f hf,
suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this,
begin
apply ha,
{ rw [support_erase, mem_erase], exact λ H, H.1 rfl },
{ rw [← mem_support_iff, hf], exact mem_insert_self _ _ },
{ apply ih _ _,
rw [support_erase, hf, finset.erase_insert has] }
end
lemma map_range_add [add_monoid β₁] [add_monoid β₂]
{f : β₁ → β₂} {hf : f 0 = 0} (hf' : ∀ x y, f (x + y) = f x + f y) (v₁ v₂ : α →₀ β₁) :
map_range f hf (v₁ + v₂) = map_range f hf v₁ + map_range f hf v₂ :=
finsupp.ext $ λ a, by simp [hf']
end add_monoid
instance [add_comm_monoid β] : add_comm_monoid (α →₀ β) :=
{ add_comm := assume ⟨s, f, _⟩ ⟨t, g, _⟩, ext $ assume a, add_comm _ _,
.. finsupp.add_monoid }
instance [add_group β] : add_group (α →₀ β) :=
{ neg := map_range (has_neg.neg) neg_zero,
add_left_neg := assume ⟨s, f, _⟩, ext $ assume x, add_left_neg _,
.. finsupp.add_monoid }
lemma single_multiset_sum [add_comm_monoid β] (s : multiset β) (a : α) :
single a s.sum = (s.map (single a)).sum :=
multiset.induction_on s single_zero $ λ a s ih,
by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons]
lemma single_finset_sum [add_comm_monoid β] (s : finset γ) (f : γ → β) (a : α) :
single a (s.sum f) = s.sum (λb, single a (f b)) :=
begin
transitivity,
apply single_multiset_sum,
rw [multiset.map_map],
refl
end
lemma single_sum [has_zero γ] [add_comm_monoid β] (s : δ →₀ γ) (f : δ → γ → β) (a : α) :
single a (s.sum f) = s.sum (λd c, single a (f d c)) :=
single_finset_sum _ _ _
@[to_additive]
lemma prod_neg_index [add_group β] [comm_monoid γ]
{g : α →₀ β} {h : α → β → γ} (h0 : ∀a, h a 0 = 1) :
(-g).prod h = g.prod (λa b, h a (- b)) :=
prod_map_range_index h0
@[simp] lemma neg_apply [add_group β] {g : α →₀ β} {a : α} : (- g) a = - g a := rfl
@[simp] lemma sub_apply [add_group β] {g₁ g₂ : α →₀ β} {a : α} : (g₁ - g₂) a = g₁ a - g₂ a := rfl
@[simp] lemma support_neg [add_group β] {f : α →₀ β} : support (-f) = support f :=
finset.subset.antisymm
support_map_range
(calc support f = support (- (- f)) : congr_arg support (neg_neg _).symm
... ⊆ support (- f) : support_map_range)
instance [add_comm_group β] : add_comm_group (α →₀ β) :=
{ add_comm := add_comm, ..finsupp.add_group }
@[simp] lemma sum_apply [has_zero β₁] [add_comm_monoid β]
{f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β} {a₂ : α} :
(f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) :=
(finset.sum_hom (λf : α →₀ β, f a₂)).symm
lemma support_sum [has_zero β₁] [add_comm_monoid β]
{f : α₁ →₀ β₁} {g : α₁ → β₁ → (α →₀ β)} :
(f.sum g).support ⊆ f.support.bind (λa, (g a (f a)).support) :=
have ∀a₁ : α, f.sum (λ (a : α₁) (b : β₁), (g a b) a₁) ≠ 0 →
(∃ (a : α₁), f a ≠ 0 ∧ ¬ (g a (f a)) a₁ = 0),
from assume a₁ h,
let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in
⟨a, mem_support_iff.mp ha, ne⟩,
by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply, exists_prop] using this
@[simp] lemma sum_zero [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β} :
f.sum (λa b, (0 : γ)) = 0 :=
finset.sum_const_zero
@[simp] lemma sum_add [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β}
{h₁ h₂ : α → β → γ} :
f.sum (λa b, h₁ a b + h₂ a b) = f.sum h₁ + f.sum h₂ :=
finset.sum_add_distrib
@[simp] lemma sum_neg [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β}
{h : α → β → γ} : f.sum (λa b, - h a b) = - f.sum h :=
finset.sum_hom (@has_neg.neg γ _)
@[simp] lemma sum_sub [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β}
{h₁ h₂ : α → β → γ} :
f.sum (λa b, h₁ a b - h₂ a b) = f.sum h₁ - f.sum h₂ :=
by rw [sub_eq_add_neg, ←sum_neg, ←sum_add]; refl
@[simp] lemma sum_single [add_comm_monoid β] (f : α →₀ β) :
f.sum single = f :=
have ∀a:α, f.sum (λa' b, ite (a' = a) b 0) =
({a} : finset α).sum (λa', ite (a' = a) (f a') 0),
begin
intro a,
by_cases h : a ∈ f.support,
{ have : (finset.singleton a : finset α) ⊆ f.support,
{ simpa only [finset.subset_iff, mem_singleton, forall_eq] },
refine (finset.sum_subset this (λ _ _ H, _)).symm,
exact if_neg (mt mem_singleton.2 H) },
{ transitivity (f.support.sum (λa, (0 : β))),
{ refine (finset.sum_congr rfl $ λ a' ha', if_neg _),
rintro rfl, exact h ha' },
{ rw [sum_const_zero, insert_empty_eq_singleton, sum_singleton,
if_pos rfl, not_mem_support_iff.1 h] } }
end,
ext $ assume a, by simp only [sum_apply, single_apply, this,
insert_empty_eq_singleton, sum_singleton, if_pos]
@[to_additive]
lemma prod_add_index [add_comm_monoid β] [comm_monoid γ] {f g : α →₀ β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(f + g).prod h = f.prod h * g.prod h :=
have f_eq : (f.support ∪ g.support).prod (λa, h a (f a)) = f.prod h,
from (finset.prod_subset (finset.subset_union_left _ _) $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm,
have g_eq : (f.support ∪ g.support).prod (λa, h a (g a)) = g.prod h,
from (finset.prod_subset (finset.subset_union_right _ _) $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm,
calc (f + g).support.prod (λa, h a ((f + g) a)) =
(f.support ∪ g.support).prod (λa, h a ((f + g) a)) :
finset.prod_subset support_add $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]
... = (f.support ∪ g.support).prod (λa, h a (f a)) *
(f.support ∪ g.support).prod (λa, h a (g a)) :
by simp only [add_apply, h_add, finset.prod_mul_distrib]
... = _ : by rw [f_eq, g_eq]
lemma sum_sub_index [add_comm_group β] [add_comm_group γ] {f g : α →₀ β}
{h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) :
(f - g).sum h = f.sum h - g.sum h :=
have h_zero : ∀a, h a 0 = 0,
from assume a,
have h a (0 - 0) = h a 0 - h a 0, from h_sub a 0 0,
by simpa only [sub_self] using this,
have h_neg : ∀a b, h a (- b) = - h a b,
from assume a b,
have h a (0 - b) = h a 0 - h a b, from h_sub a 0 b,
by simpa only [h_zero, zero_sub] using this,
have h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ + h a b₂,
from assume a b₁ b₂,
have h a (b₁ - (- b₂)) = h a b₁ - h a (- b₂), from h_sub a b₁ (-b₂),
by simpa only [h_neg, sub_neg_eq_add] using this,
calc (f - g).sum h = (f + - g).sum h : rfl
... = f.sum h + - g.sum h : by simp only [sum_add_index h_zero h_add, sum_neg_index h_zero, h_neg, sum_neg]
... = f.sum h - g.sum h : rfl
@[to_additive]
lemma prod_finset_sum_index [add_comm_monoid β] [comm_monoid γ]
{s : finset ι} {g : ι → α →₀ β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
s.prod (λi, (g i).prod h) = (s.sum g).prod h :=
finset.induction_on s rfl $ λ a s has ih,
by rw [prod_insert has, ih, sum_insert has, prod_add_index h_zero h_add]
@[to_additive]
lemma prod_sum_index
[add_comm_monoid β₁] [add_comm_monoid β] [comm_monoid γ]
{f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(f.sum g).prod h = f.prod (λa b, (g a b).prod h) :=
(prod_finset_sum_index h_zero h_add).symm
lemma multiset_sum_sum_index
[add_comm_monoid β] [add_comm_monoid γ]
(f : multiset (α →₀ β)) (h : α → β → γ)
(h₀ : ∀a, h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : β), h a (b₁ + b₂) = h a b₁ + h a b₂) :
(f.sum.sum h) = (f.map $ λg:α →₀ β, g.sum h).sum :=
multiset.induction_on f rfl $ assume a s ih,
by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index h₀ h₁, ih]
lemma multiset_map_sum [has_zero β] {f : α →₀ β} {m : γ → δ} {h : α → β → multiset γ} :
multiset.map m (f.sum h) = f.sum (λa b, (h a b).map m) :=
(finset.sum_hom _).symm
lemma multiset_sum_sum [has_zero β] [add_comm_monoid γ] {f : α →₀ β} {h : α → β → multiset γ} :
multiset.sum (f.sum h) = f.sum (λa b, multiset.sum (h a b)) :=
(finset.sum_hom multiset.sum).symm
section map_range
variables
[add_comm_monoid β₁] [add_comm_monoid β₂]
(f : β₁ → β₂) [hf : is_add_monoid_hom f]
instance is_add_monoid_hom_map_range :
is_add_monoid_hom (map_range f hf.map_zero : (α →₀ β₁) → (α →₀ β₂)) :=
{ map_zero := map_range_zero, map_add := λ a b, map_range_add hf.map_add _ _ }
lemma map_range_multiset_sum (m : multiset (α →₀ β₁)) :
map_range f hf.map_zero m.sum = (m.map $ λx, map_range f hf.map_zero x).sum :=
(m.sum_hom (map_range f hf.map_zero)).symm
lemma map_range_finset_sum {ι : Type*} (s : finset ι) (g : ι → (α →₀ β₁)) :
map_range f hf.map_zero (s.sum g) = s.sum (λx, map_range f hf.map_zero (g x)) :=
by rw [finset.sum.equations._eqn_1, map_range_multiset_sum, multiset.map_map]; refl
end map_range
section map_domain
variables [add_comm_monoid β] {v v₁ v₂ : α →₀ β}
/-- Given `f : α₁ → α₂` and `v : α₁ →₀ β`, `map_domain f v : α₂ →₀ β`
is the finitely supported function whose value at `a : α₂` is the sum
of `v x` over all `x` such that `f x = a`. -/
def map_domain (f : α₁ → α₂) (v : α₁ →₀ β) : α₂ →₀ β :=
v.sum $ λa, single (f a)
lemma map_domain_apply {f : α₁ → α₂} (hf : function.injective f) (x : α₁ →₀ β) (a : α₁) :
map_domain f x (f a) = x a :=
begin
rw [map_domain, sum_apply, sum, finset.sum_eq_single a, single_eq_same],
{ assume b _ hba, exact single_eq_of_ne (hf.ne hba) },
{ simp only [(∉), (≠), not_not, mem_support_iff],
assume h,
rw [h, single_zero],
refl }
end
lemma map_domain_notin_range {f : α₁ → α₂} (x : α₁ →₀ β) (a : α₂) (h : a ∉ set.range f) :
map_domain f x a = 0 :=
begin
rw [map_domain, sum_apply, sum],
exact finset.sum_eq_zero
(assume a' h', single_eq_of_ne $ assume eq, h $ eq ▸ set.mem_range_self _)
end
lemma map_domain_id : map_domain id v = v := sum_single _
lemma map_domain_comp {f : α → α₁} {g : α₁ → α₂} :
map_domain (g ∘ f) v = map_domain g (map_domain f v) :=
begin
refine ((sum_sum_index _ _).trans _).symm,
{ intros, exact single_zero },
{ intros, exact single_add },
refine sum_congr rfl (λ _ _, sum_single_index _),
{ exact single_zero }
end
lemma map_domain_single {f : α → α₁} {a : α} {b : β} : map_domain f (single a b) = single (f a) b :=
sum_single_index single_zero
@[simp] lemma map_domain_zero {f : α → α₂} : map_domain f 0 = (0 : α₂ →₀ β) :=
sum_zero_index
lemma map_domain_congr {f g : α → α₂} (h : ∀x∈v.support, f x = g x) :
v.map_domain f = v.map_domain g :=
finset.sum_congr rfl $ λ _ H, by simp only [h _ H]
lemma map_domain_add {f : α → α₂} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ :=
sum_add_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_finset_sum {f : α → α₂} {s : finset ι} {v : ι → α →₀ β} :
map_domain f (s.sum v) = s.sum (λi, map_domain f (v i)) :=
eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_sum [has_zero β₁] {f : α → α₂} {s : α →₀ β₁} {v : α → β₁ → α →₀ β} :
map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) :=
eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_support {f : α → α₂} {s : α →₀ β} :
(s.map_domain f).support ⊆ s.support.image f :=
finset.subset.trans support_sum $
finset.subset.trans (finset.bind_mono $ assume a ha, support_single_subset) $
by rw [finset.bind_singleton]; exact subset.refl _
@[to_additive]
lemma prod_map_domain_index [comm_monoid γ] {f : α → α₂} {s : α →₀ β}
{h : α₂ → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(s.map_domain f).prod h = s.prod (λa b, h (f a) b) :=
(prod_sum_index h_zero h_add).trans $ prod_congr rfl $ λ _ _, prod_single_index (h_zero _)
lemma emb_domain_eq_map_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) :
emb_domain f v = map_domain f v :=
begin
ext a,
by_cases a ∈ set.range f,
{ rcases h with ⟨a, rfl⟩,
rw [map_domain_apply (function.embedding.inj' _), emb_domain_apply] },
{ rw [map_domain_notin_range, emb_domain_notin_range]; assumption }
end
lemma injective_map_domain {f : α₁ → α₂} (hf : function.injective f) :
function.injective (map_domain f : (α₁ →₀ β) → (α₂ →₀ β)) :=
begin
assume v₁ v₂ eq, ext a,
have : map_domain f v₁ (f a) = map_domain f v₂ (f a), { rw eq },
rwa [map_domain_apply hf, map_domain_apply hf] at this,
end
end map_domain
section comap_domain
noncomputable def comap_domain {α₁ α₂ γ : Type*} [has_zero γ]
(f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.inj_on f (f ⁻¹' l.support.to_set)) : α₁ →₀ γ :=
{ support := l.support.preimage hf,
to_fun := (λ a, l (f a)),
mem_support_to_fun :=
begin
intros a,
simp only [finset.mem_def.symm, finset.mem_preimage],
exact l.mem_support_to_fun (f a),
end }
lemma comap_domain_apply {α₁ α₂ γ : Type*} [has_zero γ]
(f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.inj_on f (f ⁻¹' l.support.to_set)) (a : α₁) :
comap_domain f l hf a = l (f a) :=
begin
unfold_coes,
unfold comap_domain,
simp,
refl
end
lemma sum_comap_domain {α₁ α₂ β γ : Type*} [has_zero β] [add_comm_monoid γ]
(f : α₁ → α₂) (l : α₂ →₀ β) (g : α₂ → β → γ) (hf : set.bij_on f (f ⁻¹' l.support.to_set) l.support.to_set):
(comap_domain f l (set.inj_on_of_bij_on hf)).sum (g ∘ f) = l.sum g :=
begin
unfold sum,
haveI := classical.dec_eq α₂,
simp only [comap_domain, comap_domain_apply, finset.sum_preimage f _ _ (λ (x : α₂), g x (l x))],
end
lemma eq_zero_of_comap_domain_eq_zero {α₁ α₂ γ : Type*} [add_comm_monoid γ]
(f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.bij_on f (f ⁻¹' l.support.to_set) l.support.to_set) :
comap_domain f l (set.inj_on_of_bij_on hf) = 0 → l = 0 :=
begin
rw [← support_eq_empty, ← support_eq_empty, comap_domain],
simp only [finset.ext, finset.not_mem_empty, iff_false, mem_preimage],
assume h a ha,
cases hf.2.2 ha with b hb,
exact h b (hb.2.symm ▸ ha)
end
lemma map_domain_comap_domain {α₁ α₂ γ : Type*} [add_comm_monoid γ]
(f : α₁ → α₂) (l : α₂ →₀ γ)
(hf : function.injective f) (hl : ↑l.support ⊆ set.range f):
map_domain f (comap_domain f l (set.inj_on_of_injective _ hf)) = l :=
begin
ext a,
haveI := classical.dec (a ∈ set.range f),
by_cases h_cases: a ∈ set.range f,
{ rcases set.mem_range.1 h_cases with ⟨b, hb⟩,
rw [hb.symm, map_domain_apply hf, comap_domain_apply] },
{ rw map_domain_notin_range _ _ h_cases,
by_contra h_contr,
apply h_cases (hl (finset.mem_coe.2 (mem_support_iff.2 (λ h, h_contr h.symm)))) }
end
end comap_domain
/-- The product of `f g : α →₀ β` is the finitely supported function
whose value at `a` is the sum of `f x * g y` over all pairs `x, y`
such that `x + y = a`. (Think of the product of multivariate
polynomials where `α` is the monoid of monomial exponents.) -/
instance [has_add α] [semiring β] : has_mul (α →₀ β) :=
⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)⟩
lemma mul_def [has_add α] [semiring β] {f g : α →₀ β} :
f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) := rfl
lemma support_mul [has_add α] [semiring β] (a b : α →₀ β) :
(a * b).support ⊆ a.support.bind (λa₁, b.support.bind $ λa₂, {a₁ + a₂}) :=
subset.trans support_sum $ bind_mono $ assume a₁ _,
subset.trans support_sum $ bind_mono $ assume a₂ _, support_single_subset
/-- The unit of the multiplication is `single 0 1`, i.e. the function
that is 1 at 0 and zero elsewhere. -/
instance [has_zero α] [has_zero β] [has_one β] : has_one (α →₀ β) :=
⟨single 0 1⟩
lemma one_def [has_zero α] [has_zero β] [has_one β] : 1 = (single 0 1 : α →₀ β) := rfl
section filter
section has_zero
variables [has_zero β] (p : α → Prop) (f : α →₀ β)
/-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/
def filter (p : α → Prop) (f : α →₀ β) : α →₀ β :=
on_finset f.support (λa, if p a then f a else 0) $ λ a H,
mem_support_iff.2 $ λ h, by rw [h, if_t_t] at H; exact H rfl
@[simp] lemma filter_apply_pos {a : α} (h : p a) : f.filter p a = f a :=
if_pos h
@[simp] lemma filter_apply_neg {a : α} (h : ¬ p a) : f.filter p a = 0 :=
if_neg h
@[simp] lemma support_filter : (f.filter p).support = f.support.filter p :=
finset.ext.mpr $ assume a, if H : p a
then by simp only [mem_support_iff, filter_apply_pos _ _ H, mem_filter, H, and_true]
else by simp only [mem_support_iff, filter_apply_neg _ _ H, mem_filter, H, and_false, ne.def, ne_self_iff_false]
lemma filter_zero : (0 : α →₀ β).filter p = 0 :=
by rw [← support_eq_empty, support_filter, support_zero, finset.filter_empty]
@[simp] lemma filter_single_of_pos
{a : α} {b : β} (h : p a) : (single a b).filter p = single a b :=
finsupp.ext $ λ x, begin
by_cases h' : p x; simp [h'],
rw single_eq_of_ne, rintro rfl, exact h' h
end
@[simp] lemma filter_single_of_neg
{a : α} {b : β} (h : ¬ p a) : (single a b).filter p = 0 :=
finsupp.ext $ λ x, begin
by_cases h' : p x; simp [h'],
rw single_eq_of_ne, rintro rfl, exact h h'
end
end has_zero
lemma filter_pos_add_filter_neg [add_monoid β] (f : α →₀ β) (p : α → Prop) :
f.filter p + f.filter (λa, ¬ p a) = f :=
finsupp.ext $ assume a, if H : p a
then by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_not, add_zero]
else by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_false_iff, zero_add]
end filter
section frange
variables [has_zero β]
def frange (f : α →₀ β) : finset β :=
finset.image f f.support
theorem mem_frange {f : α →₀ β} {y : β} :
y ∈ f.frange ↔ y ≠ 0 ∧ ∃ x, f x = y :=
finset.mem_image.trans
⟨λ ⟨x, hx1, hx2⟩, ⟨hx2 ▸ mem_support_iff.1 hx1, x, hx2⟩,
λ ⟨hy, x, hx⟩, ⟨x, mem_support_iff.2 (hx.symm ▸ hy), hx⟩⟩
theorem zero_not_mem_frange {f : α →₀ β} : (0:β) ∉ f.frange :=
λ H, (mem_frange.1 H).1 rfl
theorem frange_single {x : α} {y : β} : frange (single x y) ⊆ {y} :=
λ r hr, let ⟨t, ht1, ht2⟩ := mem_frange.1 hr in ht2 ▸
(by rw single_apply at ht2 ⊢; split_ifs at ht2 ⊢; [exact finset.mem_singleton_self _, cc])
end frange
section subtype_domain
variables {α' : Type*} [has_zero δ] {p : α → Prop}
section zero
variables [has_zero β] {v v' : α' →₀ β}
/-- `subtype_domain p f` is the restriction of the finitely supported function
`f` to the subtype `p`. -/
def subtype_domain (p : α → Prop) (f : α →₀ β) : (subtype p →₀ β) :=
⟨f.support.subtype p, f ∘ subtype.val, λ a, by simp only [mem_subtype, mem_support_iff]⟩
@[simp] lemma support_subtype_domain {f : α →₀ β} :
(subtype_domain p f).support = f.support.subtype p :=
rfl
@[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ β} :
(subtype_domain p v) a = v (a.val) :=
rfl
@[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ β) = 0 :=
rfl
@[to_additive]
lemma prod_subtype_domain_index [comm_monoid γ] {v : α →₀ β}
{h : α → β → γ} (hp : ∀x∈v.support, p x) :
(v.subtype_domain p).prod (λa b, h a.1 b) = v.prod h :=
prod_bij (λp _, p.val)
(λ _, mem_subtype.1)
(λ _ _, rfl)
(λ _ _ _ _, subtype.eq)
(λ b hb, ⟨⟨b, hp b hb⟩, mem_subtype.2 hb, rfl⟩)
end zero
section monoid
variables [add_monoid β] {v v' : α' →₀ β}
@[simp] lemma subtype_domain_add {v v' : α →₀ β} :
(v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p :=
ext $ λ _, rfl
instance subtype_domain.is_add_monoid_hom :
is_add_monoid_hom (subtype_domain p : (α →₀ β) → subtype p →₀ β) :=
{ map_add := λ _ _, subtype_domain_add, map_zero := subtype_domain_zero }
@[simp] lemma filter_add {v v' : α →₀ β} :
(v + v').filter p = v.filter p + v'.filter p :=
ext $ λ a, by by_cases p a; simp [h]
instance filter.is_add_monoid_hom (p : α → Prop) :
is_add_monoid_hom (filter p : (α →₀ β) → (α →₀ β)) :=
{ map_zero := filter_zero p, map_add := λ x y, filter_add }
end monoid
section comm_monoid
variables [add_comm_monoid β]
lemma subtype_domain_sum {s : finset γ} {h : γ → α →₀ β} :
(s.sum h).subtype_domain p = s.sum (λc, (h c).subtype_domain p) :=
eq.symm (finset.sum_hom _)
lemma subtype_domain_finsupp_sum {s : γ →₀ δ} {h : γ → δ → α →₀ β} :
(s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) :=
subtype_domain_sum
lemma filter_sum (s : finset γ) (f : γ → α →₀ β) :
(s.sum f).filter p = s.sum (λa, filter p (f a)) :=
(finset.sum_hom (filter p)).symm
end comm_monoid
section group
variables [add_group β] {v v' : α' →₀ β}
@[simp] lemma subtype_domain_neg {v : α →₀ β} :
(- v).subtype_domain p = - v.subtype_domain p :=
ext $ λ _, rfl
@[simp] lemma subtype_domain_sub {v v' : α →₀ β} :
(v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p :=
ext $ λ _, rfl
end group
end subtype_domain
section multiset
def to_multiset (f : α →₀ ℕ) : multiset α :=
f.sum (λa n, add_monoid.smul n {a})
lemma to_multiset_zero : (0 : α →₀ ℕ).to_multiset = 0 :=
rfl
lemma to_multiset_add (m n : α →₀ ℕ) :
(m + n).to_multiset = m.to_multiset + n.to_multiset :=
sum_add_index (assume a, add_monoid.zero_smul _) (assume a b₁ b₂, add_monoid.add_smul _ _ _)
lemma to_multiset_single (a : α) (n : ℕ) : to_multiset (single a n) = add_monoid.smul n {a} :=
by rw [to_multiset, sum_single_index]; apply add_monoid.zero_smul
instance is_add_monoid_hom.to_multiset : is_add_monoid_hom (to_multiset : _ → multiset α) :=
{ map_zero := to_multiset_zero, map_add := to_multiset_add }
lemma card_to_multiset (f : α →₀ ℕ) : f.to_multiset.card = f.sum (λa, id) :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.card_zero, sum_zero_index] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.card_add, ih, sum_add_index, to_multiset_single,
sum_single_index, multiset.card_smul, multiset.singleton_eq_singleton,
multiset.card_singleton, mul_one]; intros; refl }
end
lemma to_multiset_map (f : α →₀ ℕ) (g : α → β) :
f.to_multiset.map g = (f.map_domain g).to_multiset :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.map_zero, map_domain_zero, to_multiset_zero] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.map_add, ih, map_domain_add, map_domain_single,
to_multiset_single, to_multiset_add, to_multiset_single,
is_add_monoid_hom.map_smul (multiset.map g)],
refl }
end
lemma prod_to_multiset [comm_monoid α] (f : α →₀ ℕ) :
f.to_multiset.prod = f.prod (λa n, a ^ n) :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.prod_zero, finsupp.prod_zero_index] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.prod_add, ih, to_multiset_single, finsupp.prod_add_index,
finsupp.prod_single_index, multiset.prod_smul, multiset.singleton_eq_singleton,
multiset.prod_singleton],
{ exact pow_zero a },
{ exact pow_zero },
{ exact pow_add } }
end
lemma to_finset_to_multiset (f : α →₀ ℕ) : f.to_multiset.to_finset = f.support :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.to_finset_zero, support_zero] },
{ assume a n f ha hn ih,
rw [to_multiset_add, multiset.to_finset_add, ih, to_multiset_single, support_add_eq,
support_single_ne_zero hn, multiset.to_finset_smul _ _ hn,
multiset.singleton_eq_singleton, multiset.to_finset_cons, multiset.to_finset_zero],
refl,
refine disjoint_mono support_single_subset (subset.refl _) _,
rwa [finset.singleton_eq_singleton, finset.singleton_disjoint] }
end
@[simp] lemma count_to_multiset (f : α →₀ ℕ) (a : α) :
f.to_multiset.count a = f a :=
calc f.to_multiset.count a = f.sum (λx n, (add_monoid.smul n {x} : multiset α).count a) :
(finset.sum_hom _).symm
... = f.sum (λx n, n * ({x} : multiset α).count a) : by simp only [multiset.count_smul]
... = f.sum (λx n, n * (x :: 0 : multiset α).count a) : rfl
... = f a * (a :: 0 : multiset α).count a : sum_eq_single _
(λ a' _ H, by simp only [multiset.count_cons_of_ne (ne.symm H), multiset.count_zero, mul_zero])
(λ H, by simp only [not_mem_support_iff.1 H, zero_mul])
... = f a : by simp only [multiset.count_singleton, mul_one]
def of_multiset (m : multiset α) : α →₀ ℕ :=
on_finset m.to_finset (λa, m.count a) $ λ a H, multiset.mem_to_finset.2 $
by_contradiction (mt multiset.count_eq_zero.2 H)
@[simp] lemma of_multiset_apply (m : multiset α) (a : α) :
of_multiset m a = m.count a :=
rfl
def equiv_multiset : (α →₀ ℕ) ≃ (multiset α) :=
⟨ to_multiset, of_multiset,
assume f, finsupp.ext $ λ a, by rw [of_multiset_apply, count_to_multiset],
assume m, multiset.ext.2 $ λ a, by rw [count_to_multiset, of_multiset_apply] ⟩
lemma mem_support_multiset_sum [add_comm_monoid β]
{s : multiset (α →₀ β)} (a : α) :
a ∈ s.sum.support → ∃f∈s, a ∈ (f : α →₀ β).support :=
multiset.induction_on s false.elim
begin
assume f s ih ha,
by_cases a ∈ f.support,
{ exact ⟨f, multiset.mem_cons_self _ _, h⟩ },
{ simp only [multiset.sum_cons, mem_support_iff, add_apply,
not_mem_support_iff.1 h, zero_add] at ha,
rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩,
exact ⟨f', multiset.mem_cons_of_mem h₀, h₁⟩ }
end
lemma mem_support_finset_sum [add_comm_monoid β]
{s : finset γ} {h : γ → α →₀ β} (a : α) (ha : a ∈ (s.sum h).support) : ∃c∈s, a ∈ (h c).support :=
let ⟨f, hf, hfa⟩ := mem_support_multiset_sum a ha in
let ⟨c, hc, eq⟩ := multiset.mem_map.1 hf in
⟨c, hc, eq.symm ▸ hfa⟩
lemma mem_support_single [has_zero β] (a a' : α) (b : β) :
a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 :=
⟨λ H : (a ∈ ite _ _ _), if h : b = 0
then by rw if_pos h at H; exact H.elim
else ⟨by rw if_neg h at H; exact mem_singleton.1 H, h⟩,
λ ⟨h1, h2⟩, show a ∈ ite _ _ _, by rw [if_neg h2]; exact mem_singleton.2 h1⟩
end multiset
section curry_uncurry
protected def curry [add_comm_monoid γ]
(f : (α × β) →₀ γ) : α →₀ (β →₀ γ) :=
f.sum $ λp c, single p.1 (single p.2 c)
lemma sum_curry_index
[add_comm_monoid γ] [add_comm_monoid δ]
(f : (α × β) →₀ γ) (g : α → β → γ → δ)
(hg₀ : ∀ a b, g a b 0 = 0) (hg₁ : ∀a b c₀ c₁, g a b (c₀ + c₁) = g a b c₀ + g a b c₁) :
f.curry.sum (λa f, f.sum (g a)) = f.sum (λp c, g p.1 p.2 c) :=
begin
rw [finsupp.curry],
transitivity,
{ exact sum_sum_index (assume a, sum_zero_index)
(assume a b₀ b₁, sum_add_index (assume a, hg₀ _ _) (assume c d₀ d₁, hg₁ _ _ _ _)) },
congr, funext p c,
transitivity,
{ exact sum_single_index sum_zero_index },
exact sum_single_index (hg₀ _ _)
end
protected def uncurry [add_comm_monoid γ] (f : α →₀ (β →₀ γ)) : (α × β) →₀ γ :=
f.sum $ λa g, g.sum $ λb c, single (a, b) c
def finsupp_prod_equiv [add_comm_monoid γ] : ((α × β) →₀ γ) ≃ (α →₀ (β →₀ γ)) :=
by refine ⟨finsupp.curry, finsupp.uncurry, λ f, _, λ f, _⟩; simp only [
finsupp.curry, finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index,
sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff,
forall_3_true_iff, prod.mk.eta, (single_sum _ _ _).symm, sum_single]
lemma filter_curry [add_comm_monoid β] (f : α₁ × α₂ →₀ β) (p : α₁ → Prop) :
(f.filter (λa:α₁×α₂, p a.1)).curry = f.curry.filter p :=
begin
rw [finsupp.curry, finsupp.curry, finsupp.sum, finsupp.sum,
@filter_sum _ (α₂ →₀ β) _ p _ f.support _],
rw [support_filter, sum_filter],
refine finset.sum_congr rfl _,
rintros ⟨a₁, a₂⟩ ha,
dsimp only,
split_ifs,
{ rw [filter_apply_pos, filter_single_of_pos]; exact h },
{ rwa [filter_single_of_neg] }
end
lemma support_curry [add_comm_monoid β] (f : α₁ × α₂ →₀ β) :
f.curry.support ⊆ f.support.image prod.fst :=
begin
rw ← finset.bind_singleton,
refine finset.subset.trans support_sum _,
refine finset.bind_mono (assume a _, support_single_subset)
end
end curry_uncurry
section
variables [add_monoid α] [semiring β]
-- TODO: the simplifier unfolds 0 in the instance proof!
private lemma zero_mul (f : α →₀ β) : 0 * f = 0 := by simp only [mul_def, sum_zero_index]
private lemma mul_zero (f : α →₀ β) : f * 0 = 0 := by simp only [mul_def, sum_zero_index, sum_zero]
private lemma left_distrib (a b c : α →₀ β) : a * (b + c) = a * b + a * c :=
by simp only [mul_def, sum_add_index, mul_add, _root_.mul_zero, single_zero, single_add,
eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add]
private lemma right_distrib (a b c : α →₀ β) : (a + b) * c = a * c + b * c :=
by simp only [mul_def, sum_add_index, add_mul, _root_.mul_zero, _root_.zero_mul, single_zero, single_add,
eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add]
instance : semiring (α →₀ β) :=
{ one := 1,
mul := (*),
one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, _root_.zero_mul, single_zero, sum_zero,
zero_add, one_mul, sum_single],
mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, _root_.mul_zero, single_zero, sum_zero,
add_zero, mul_one, sum_single],
zero_mul := zero_mul,
mul_zero := mul_zero,
mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index,
single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff,
add_mul, mul_add, add_assoc, mul_assoc, _root_.zero_mul, _root_.mul_zero, sum_zero, sum_add],
left_distrib := left_distrib,
right_distrib := right_distrib,
.. finsupp.add_comm_monoid }
end
instance [add_comm_monoid α] [comm_semiring β] : comm_semiring (α →₀ β) :=
{ mul_comm := assume f g,
begin
simp only [mul_def, finsupp.sum, mul_comm],
rw [finset.sum_comm],
simp only [add_comm]
end,
.. finsupp.semiring }
instance [add_monoid α] [ring β] : ring (α →₀ β) :=
{ neg := has_neg.neg,
add_left_neg := add_left_neg,
.. finsupp.semiring }
instance [add_comm_monoid α] [comm_ring β] : comm_ring (α →₀ β) :=
{ mul_comm := mul_comm, .. finsupp.ring}
lemma single_mul_single [has_add α] [semiring β] {a₁ a₂ : α} {b₁ b₂ : β}:
single a₁ b₁ * single a₂ b₂ = single (a₁ + a₂) (b₁ * b₂) :=
(sum_single_index (by simp only [_root_.zero_mul, single_zero, sum_zero])).trans
(sum_single_index (by rw [_root_.mul_zero, single_zero]))
lemma prod_single [add_comm_monoid α] [comm_semiring β]
{s : finset ι} {a : ι → α} {b : ι → β} :
s.prod (λi, single (a i) (b i)) = single (s.sum a) (s.prod b) :=
finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih,
single_mul_single, sum_insert has, prod_insert has]
section
instance [semiring γ] [add_comm_monoid β] [semimodule γ β] : has_scalar γ (α →₀ β) := ⟨λa v, v.map_range ((•) a) (smul_zero _)⟩
variables (α β)
@[simp] lemma smul_apply' {R:semiring γ} [add_comm_monoid β] [semimodule γ β] {a : α} {b : γ} {v : α →₀ β} :
(b • v) a = b • (v a) := rfl
instance [semiring γ] [add_comm_monoid β] [semimodule γ β] : semimodule γ (α →₀ β) :=
{ smul := (•),
smul_add := λ a x y, finsupp.ext $ λ _, smul_add _ _ _,
add_smul := λ a x y, finsupp.ext $ λ _, add_smul _ _ _,
one_smul := λ x, finsupp.ext $ λ _, one_smul _ _,
mul_smul := λ r s x, finsupp.ext $ λ _, mul_smul _ _ _,
zero_smul := λ x, finsupp.ext $ λ _, zero_smul _ _,
smul_zero := λ x, finsupp.ext $ λ _, smul_zero _ }
instance [ring γ] [add_comm_group β] [module γ β] : module γ (α →₀ β) :=
{ ..finsupp.semimodule α β }
instance [discrete_field γ] [add_comm_group β] [vector_space γ β] : vector_space γ (α →₀ β) :=
{ ..finsupp.module α β }
variables {α β}
lemma support_smul {R:semiring γ} [add_comm_monoid β] [semimodule γ β] {b : γ} {g : α →₀ β} :
(b • g).support ⊆ g.support :=
λ a, by simp; exact mt (λ h, h.symm ▸ smul_zero _)
section
variables {α' : Type*} [has_zero δ] {p : α → Prop}
@[simp] lemma filter_smul {R : semiring γ} [add_comm_monoid β] [semimodule γ β]
{b : γ} {v : α →₀ β} : (b • v).filter p = b • v.filter p :=
ext $ λ a, by by_cases p a; simp [h]
end
lemma map_domain_smul {α'} {R : semiring γ} [add_comm_monoid β] [semimodule γ β]
{f : α → α'} (b : γ) (v : α →₀ β) : map_domain f (b • v) = b • map_domain f v :=
begin
change map_domain f (map_range _ _ _) = map_range _ _ _,
apply finsupp.induction v, {simp},
intros a b v' hv₁ hv₂ IH,
rw [map_range_add, map_domain_add, IH, map_domain_add, map_range_add,
map_range_single, map_domain_single, map_domain_single, map_range_single];
apply smul_add
end
@[simp] lemma smul_single {R : semiring γ} [add_comm_monoid β] [semimodule γ β]
(c : γ) (a : α) (b : β) : c • finsupp.single a b = finsupp.single a (c • b) :=
ext $ λ a', by by_cases a = a'; [{subst h, simp}, simp [h]]
end
@[simp] lemma smul_apply [ring β] {a : α} {b : β} {v : α →₀ β} :
(b • v) a = b • (v a) := rfl
lemma sum_smul_index [ring β] [add_comm_monoid γ] {g : α →₀ β} {b : β} {h : α → β → γ}
(h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi a, h i (b * a)) :=
finsupp.sum_map_range_index h0
section
variables [semiring β] [semiring γ]
lemma sum_mul (b : γ) (s : α →₀ β) {f : α → β → γ} :
(s.sum f) * b = s.sum (λ a c, (f a (s a)) * b) :=
by simp only [finsupp.sum, finset.sum_mul]
lemma mul_sum (b : γ) (s : α →₀ β) {f : α → β → γ} :
b * (s.sum f) = s.sum (λ a c, b * (f a (s a))) :=
by simp only [finsupp.sum, finset.mul_sum]
protected lemma eq_zero_of_zero_eq_one
(zero_eq_one : (0 : β) = 1) (l : α →₀ β) : l = 0 :=
by ext i; simp [eq_zero_of_zero_eq_one β zero_eq_one (l i)]
end
def restrict_support_equiv [add_comm_monoid β] (s : set α) :
{f : α →₀ β // ↑f.support ⊆ s } ≃ (s →₀ β):=
begin
refine ⟨λf, subtype_domain (λx, x ∈ s) f.1, λ f, ⟨f.map_domain subtype.val, _⟩, _, _⟩,
{ refine set.subset.trans (finset.coe_subset.2 map_domain_support) _,
rw [finset.coe_image, set.image_subset_iff],
exact assume x hx, x.2 },
{ rintros ⟨f, hf⟩,
apply subtype.eq,
ext a,
dsimp only,
refine classical.by_cases (assume h : a ∈ set.range (subtype.val : s → α), _) (assume h, _),
{ rcases h with ⟨x, rfl⟩,
rw [map_domain_apply subtype.val_injective, subtype_domain_apply] },
{ convert map_domain_notin_range _ _ h,
rw [← not_mem_support_iff],
refine mt _ h,
exact assume ha, ⟨⟨a, hf ha⟩, rfl⟩ } },
{ assume f,
ext ⟨a, ha⟩,
dsimp only,
rw [subtype_domain_apply, map_domain_apply subtype.val_injective] }
end
protected def dom_congr [add_comm_monoid β] (e : α₁ ≃ α₂) : (α₁ →₀ β) ≃ (α₂ →₀ β) :=
⟨map_domain e, map_domain e.symm,
begin
assume v,
simp only [map_domain_comp.symm, (∘), equiv.symm_apply_apply],
exact map_domain_id
end,
begin
assume v,
simp only [map_domain_comp.symm, (∘), equiv.apply_symm_apply],
exact map_domain_id
end⟩
section sigma
variables {αs : ι → Type*} [has_zero β] (l : (Σ i, αs i) →₀ β)
noncomputable def split (i : ι) : αs i →₀ β :=
l.comap_domain (sigma.mk i) (λ x1 x2 _ _ hx, heq_iff_eq.1 (sigma.mk.inj hx).2)
lemma split_apply (i : ι) (x : αs i) : split l i x = l ⟨i, x⟩ :=
begin
dunfold split,
rw comap_domain_apply
end
def split_support : finset ι := finset.image (sigma.fst) l.support
lemma mem_split_support_iff_nonzero (i : ι) :
i ∈ split_support l ↔ split l i ≠ 0 :=
begin
classical,
rw [split_support, mem_image, ne.def, ← support_eq_empty,
← exists_mem_iff_ne_empty, split, comap_domain],
simp
end
noncomputable def split_comp [has_zero γ] (g : Π i, (αs i →₀ β) → γ)
(hg : ∀ i x, x = 0 ↔ g i x = 0) : ι →₀ γ :=
{ support := split_support l,
to_fun := λ i, g i (split l i),
mem_support_to_fun :=
begin
intros i,
rw mem_split_support_iff_nonzero,
haveI := classical.dec,
rwa not_iff_not,
exact hg _ _,
end }
lemma sigma_support : l.support = l.split_support.sigma (λ i, (l.split i).support) :=
by simp [finset.ext, split_support, split, comap_domain]; tauto
lemma sigma_sum [add_comm_monoid γ] (f : (Σ (i : ι), αs i) → β → γ) :
l.sum f = (split_support l).sum (λ (i : ι), (split l i).sum (λ (a : αs i) b, f ⟨i, a⟩ b)) :=
by simp [sum, sigma_support, sum_sigma,split_apply]
end sigma
end finsupp
namespace multiset
def to_finsupp (s : multiset α) : α →₀ ℕ :=
{ support := s.to_finset,
to_fun := λ a, s.count a,
mem_support_to_fun := λ a,
begin
rw mem_to_finset,
convert not_iff_not_of_iff (count_eq_zero.symm),
rw not_not
end }
@[simp] lemma to_finsupp_support (s : multiset α) :
s.to_finsupp.support = s.to_finset := rfl
@[simp] lemma to_finsupp_apply (s : multiset α) (a : α) :
s.to_finsupp a = s.count a := rfl
@[simp] lemma to_finsupp_zero :
to_finsupp (0 : multiset α) = 0 :=
finsupp.ext $ λ a, count_zero a
@[simp] lemma to_finsupp_add (s t : multiset α) :
to_finsupp (s + t) = to_finsupp s + to_finsupp t :=
finsupp.ext $ λ a, count_add a s t
lemma to_finsupp_singleton (a : α) :
to_finsupp {a} = finsupp.single a 1 :=
finsupp.ext $ λ b,
if h : a = b then by simp [finsupp.single_apply, h] else
begin
rw [to_finsupp_apply, finsupp.single_apply, if_neg h, count_eq_zero,
singleton_eq_singleton, mem_singleton],
rintro rfl, exact h rfl
end
namespace to_finsupp
instance : is_add_monoid_hom (to_finsupp : multiset α → α →₀ ℕ) :=
{ map_zero := to_finsupp_zero,
map_add := to_finsupp_add }
end to_finsupp
@[simp] lemma to_finsupp_to_multiset (s : multiset α) :
s.to_finsupp.to_multiset = s :=
ext.2 $ λ a, by rw [finsupp.count_to_multiset, to_finsupp_apply]
end multiset
namespace finsupp
variables {σ : Type*}
instance [preorder α] [has_zero α] : preorder (σ →₀ α) :=
{ le := λ f g, ∀ s, f s ≤ g s,
le_refl := λ f s, le_refl _,
le_trans := λ f g h Hfg Hgh s, le_trans (Hfg s) (Hgh s) }
instance [partial_order α] [has_zero α] : partial_order (σ →₀ α) :=
{ le_antisymm := λ f g hfg hgf, finsupp.ext $ λ s, le_antisymm (hfg s) (hgf s),
.. finsupp.preorder }
instance [ordered_cancel_comm_monoid α] :
add_left_cancel_semigroup (σ →₀ α) :=
{ add_left_cancel := λ a b c h, finsupp.ext $ λ s,
by { rw finsupp.ext_iff at h, exact add_left_cancel (h s) },
.. finsupp.add_monoid }
instance [ordered_cancel_comm_monoid α] :
add_right_cancel_semigroup (σ →₀ α) :=
{ add_right_cancel := λ a b c h, finsupp.ext $ λ s,
by { rw finsupp.ext_iff at h, exact add_right_cancel (h s) },
.. finsupp.add_monoid }
instance [ordered_cancel_comm_monoid α] :
ordered_cancel_comm_monoid (σ →₀ α) :=
{ add_le_add_left := λ a b h c s, add_le_add_left (h s) (c s),
le_of_add_le_add_left := λ a b c h s, le_of_add_le_add_left (h s),
.. finsupp.add_comm_monoid, .. finsupp.partial_order,
.. finsupp.add_left_cancel_semigroup, .. finsupp.add_right_cancel_semigroup }
lemma le_iff [canonically_ordered_monoid α] (f g : σ →₀ α) :
f ≤ g ↔ ∀ s ∈ f.support, f s ≤ g s :=
⟨λ h s hs, h s,
λ h s, if H : s ∈ f.support then h s H else (not_mem_support_iff.1 H).symm ▸ zero_le (g s)⟩
attribute [simp] to_multiset_zero to_multiset_add
@[simp] lemma to_multiset_to_finsupp (f : σ →₀ ℕ) :
f.to_multiset.to_finsupp = f :=
ext $ λ s, by rw [multiset.to_finsupp_apply, count_to_multiset]
lemma to_multiset_strict_mono : strict_mono (@to_multiset σ) :=
λ m n h,
begin
rw lt_iff_le_and_ne at h ⊢, cases h with h₁ h₂,
split,
{ rw multiset.le_iff_count, intro s, erw [count_to_multiset m s, count_to_multiset], exact h₁ s },
{ intro H, apply h₂, replace H := congr_arg multiset.to_finsupp H, simpa using H }
end
lemma sum_id_lt_of_lt (m n : σ →₀ ℕ) (h : m < n) :
m.sum (λ _, id) < n.sum (λ _, id) :=
begin
rw [← card_to_multiset, ← card_to_multiset],
apply multiset.card_lt_of_lt,
exact to_multiset_strict_mono h
end
variable (σ)
/-- The order on σ →₀ ℕ is well-founded.-/
lemma lt_wf : well_founded (@has_lt.lt (σ →₀ ℕ) _) :=
subrelation.wf (sum_id_lt_of_lt) $ inv_image.wf _ nat.lt_wf
instance decidable_le : decidable_rel (@has_le.le (σ →₀ ℕ) _) :=
λ m n, by rw le_iff; apply_instance
variable {σ}
def antidiagonal (f : σ →₀ ℕ) : ((σ →₀ ℕ) × (σ →₀ ℕ)) →₀ ℕ :=
(f.to_multiset.antidiagonal.map (prod.map multiset.to_finsupp multiset.to_finsupp)).to_finsupp
lemma mem_antidiagonal_support {f : σ →₀ ℕ} {p : (σ →₀ ℕ) × (σ →₀ ℕ)} :
p ∈ (antidiagonal f).support ↔ p.1 + p.2 = f :=
begin
erw [multiset.mem_to_finset, multiset.mem_map],
split,
{ rintros ⟨⟨a, b⟩, h, rfl⟩,
rw multiset.mem_antidiagonal at h,
simpa using congr_arg multiset.to_finsupp h },
{ intro h,
refine ⟨⟨p.1.to_multiset, p.2.to_multiset⟩, _, _⟩,
{ simpa using congr_arg to_multiset h },
{ rw [prod.map, to_multiset_to_finsupp, to_multiset_to_finsupp, prod.mk.eta] } }
end
@[simp] lemma antidiagonal_zero : antidiagonal (0 : σ →₀ ℕ) = single (0,0) 1 :=
by rw [← multiset.to_finsupp_singleton]; refl
lemma swap_mem_antidiagonal_support {n : σ →₀ ℕ} {f} (hf : f ∈ (antidiagonal n).support) :
f.swap ∈ (antidiagonal n).support :=
by simpa [mem_antidiagonal_support, add_comm] using hf
end finsupp
|
70c0d12f7e3c0e62b9e12de30725c563f71c099e | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/playground/patcheqnspace.lean | e860113cd260336520c995e81e9c676a4dd162b1 | [
"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,755 | lean | import init.lean.parser
import init.lean.parser.transform
open Lean
open Lean.Parser
def getAtomTrailingSpace : Syntax → Nat
| Syntax.atom (some info) _ => info.trailing.stopPos - info.trailing.startPos
| _ => 0
def getMinTrailingSpace (ps : Array Syntax) (i : Nat) : Nat :=
ps.foldl (fun acc (p : Syntax) =>
let space := getAtomTrailingSpace (p.getArg i);
if space < acc then space else acc)
100000
def reduceTrailingSpace : Syntax → Nat → Syntax
| Syntax.atom (some info) val, delta => Syntax.atom (some { trailing := { stopPos := info.trailing.stopPos - delta, .. info.trailing }, .. info }) val
| stx, _ => stx
partial def fixPats : Array Syntax → Nat → Nat → Array Syntax
| ps, i, sz =>
if i < sz then
let minSpace := getMinTrailingSpace ps i;
if minSpace <= 1 then
fixPats ps (i+2) sz
else
let ps := ps.map $ fun p => p.modifyArg i $ fun comma => reduceTrailingSpace comma (minSpace - 1);
fixPats ps (i+2) sz
else
ps
def fixEqnSyntax (stx : Syntax) : Syntax :=
stx.rewriteBottomUp $ fun stx =>
stx.ifNodeKind `Lean.Parser.Command.declValEqns
(fun stx =>
stx.val.modifyArg 0 $ fun altsStx =>
altsStx.modifyArgs $ fun alts =>
let pats := alts.map $ fun alt => alt.getArg 1;
let patSize := (pats.get 0).getArgs.size;
let pats := fixPats pats 1 patSize;
alts.mapIdx $ fun i alt => alt.setArg 1 (pats.get i))
(fun _ => stx)
def main (xs : List String) : IO Unit :=
do
[fname] ← pure xs | throw (IO.userError "usage `patch <file-name>`");
env ← mkEmptyEnvironment;
stx ← parseFile env fname;
let stx := fixEqnSyntax stx;
match stx.reprint with
| some out => IO.print out
| none => throw (IO.userError "failed to reprint")
|
b6d9842682c534bd4115a46bc1dfb44e1c8ab9c2 | f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58 | /data/prod.lean | cacfaaf616d73ae1e282b59a36a12e419e93948f | [
"Apache-2.0"
] | permissive | semorrison/mathlib | 1be6f11086e0d24180fec4b9696d3ec58b439d10 | 20b4143976dad48e664c4847b75a85237dca0a89 | refs/heads/master | 1,583,799,212,170 | 1,535,634,130,000 | 1,535,730,505,000 | 129,076,205 | 0 | 0 | Apache-2.0 | 1,551,697,998,000 | 1,523,442,265,000 | Lean | UTF-8 | Lean | false | false | 2,222 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
Extends theory on products
-/
import tactic.ext
universes u v
variables {α : Type u} {β : Type v}
@[simp] theorem prod.forall {p : α × β → Prop} : (∀ x, p x) ↔ (∀ a b, p (a, b)) :=
⟨assume h a b, h (a, b), assume h ⟨a, b⟩, h a b⟩
@[simp] theorem prod.exists {p : α × β → Prop} : (∃ x, p x) ↔ (∃ a b, p (a, b)) :=
⟨assume ⟨⟨a, b⟩, h⟩, ⟨a, b, h⟩, assume ⟨a, b, h⟩, ⟨⟨a, b⟩, h⟩⟩
namespace prod
attribute [simp] prod.map
@[simp] theorem mk.inj_iff {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) = (a₂, b₂) ↔ (a₁ = a₂ ∧ b₁ = b₂) :=
⟨prod.mk.inj, by cc⟩
lemma ext_iff {p q : α × β} : p = q ↔ p.1 = q.1 ∧ p.2 = q.2 :=
by rw [← @mk.eta _ _ p, ← @mk.eta _ _ q, mk.inj_iff]
@[extensionality]
lemma ext {α β} {p q : α × β} : p.1 = q.1 → p.2 = q.2 → p = q :=
by rw [ext_iff] ; intros ; split ; assumption
/-- Swap the factors of a product. `swap (a, b) = (b, a)` -/
def swap : α × β → β × α := λp, (p.2, p.1)
@[simp] lemma swap_swap : ∀ x : α × β, swap (swap x) = x
| ⟨a, b⟩ := rfl
@[simp] lemma fst_swap {p : α × β} : (swap p).1 = p.2 := rfl
@[simp] lemma snd_swap {p : α × β} : (swap p).2 = p.1 := rfl
@[simp] lemma swap_prod_mk {a : α} {b : β} : swap (a, b) = (b, a) := rfl
@[simp] lemma swap_swap_eq : swap ∘ swap = @id (α × β) :=
funext swap_swap
@[simp] lemma swap_left_inverse : function.left_inverse (@swap α β) swap :=
swap_swap
@[simp] lemma swap_right_inverse : function.right_inverse (@swap α β) swap :=
swap_swap
lemma eq_iff_fst_eq_snd_eq : ∀{p q : α × β}, p = q ↔ (p.1 = q.1 ∧ p.2 = q.2)
| ⟨p₁, p₂⟩ ⟨q₁, q₂⟩ := by simp
theorem lex_def (r : α → α → Prop) (s : β → β → Prop)
{p q : α × β} : prod.lex r s p q ↔ r p.1 q.1 ∨ p.1 = q.1 ∧ s p.2 q.2 :=
⟨λ h, by cases h; simp *,
λ h, match p, q, h with
| (a, b), (c, d), or.inl h := lex.left _ _ _ h
| (a, b), (c, d), or.inr ⟨e, h⟩ :=
by change a = c at e; subst e; exact lex.right _ _ h
end⟩
end prod
|
5ab244171f8b476cbe442576bd4d5aa82b05a8a3 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/continued_fractions/computation/basic.lean | a7d533da3b7d24955d691d3ed363729e2341d96c | [
"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,034 | lean | /-
Copyright (c) 2020 Kevin Kappelmann. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Kappelmann
-/
import algebra.order.floor
import algebra.continued_fractions.basic
/-!
# Computable Continued Fractions
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
## Summary
We formalise the standard computation of (regular) continued fractions for linear ordered floor
fields. The algorithm is rather simple. Here is an outline of the procedure adapted from Wikipedia:
Take a value `v`. We call `⌊v⌋` the *integer part* of `v` and `v - ⌊v⌋` the *fractional part* of
`v`. A continued fraction representation of `v` can then be given by `[⌊v⌋; b₀, b₁, b₂,...]`, where
`[b₀; b₁, b₂,...]` recursively is the continued fraction representation of `1 / (v - ⌊v⌋)`. This
process stops when the fractional part hits 0.
In other words: to calculate a continued fraction representation of a number `v`, write down the
integer part (i.e. the floor) of `v`. Subtract this integer part from `v`. If the difference is 0,
stop; otherwise find the reciprocal of the difference and repeat. The procedure will terminate if
and only if `v` is rational.
For an example, refer to `int_fract_pair.stream`.
## Main definitions
- `generalized_continued_fraction.int_fract_pair.stream`: computes the stream of integer and
fractional parts of a given value as described in the summary.
- `generalized_continued_fraction.of`: computes the generalised continued fraction of a value `v`.
In fact, it computes a regular continued fraction that terminates if and only if `v` is rational.
## Implementation Notes
There is an intermediate definition `generalized_continued_fraction.int_fract_pair.seq1` between
`generalized_continued_fraction.int_fract_pair.stream` and `generalized_continued_fraction.of`
to wire up things. User should not (need to) directly interact with it.
The computation of the integer and fractional pairs of a value can elegantly be
captured by a recursive computation of a stream of option pairs. This is done in
`int_fract_pair.stream`. However, the type then does not guarantee the first pair to always be
`some` value, as expected by a continued fraction.
To separate concerns, we first compute a single head term that always exists in
`generalized_continued_fraction.int_fract_pair.seq1` followed by the remaining stream of option
pairs. This sequence with a head term (`seq1`) is then transformed to a generalized continued
fraction in `generalized_continued_fraction.of` by extracting the wanted integer parts of the
head term and the stream.
## References
- https://en.wikipedia.org/wiki/Continued_fraction
## Tags
numerics, number theory, approximations, fractions
-/
namespace generalized_continued_fraction
-- Fix a carrier `K`.
variable (K : Type*)
/--
We collect an integer part `b = ⌊v⌋` and fractional part `fr = v - ⌊v⌋` of a value `v` in a pair
`⟨b, fr⟩`.
-/
structure int_fract_pair := (b : ℤ) (fr : K)
variable {K}
/-! Interlude: define some expected coercions and instances. -/
namespace int_fract_pair
/-- Make an `int_fract_pair` printable. -/
instance [has_repr K] : has_repr (int_fract_pair K) :=
⟨λ p, "(b : " ++ (repr p.b) ++ ", fract : " ++ (repr p.fr) ++ ")"⟩
instance inhabited [inhabited K] : inhabited (int_fract_pair K) := ⟨⟨0, default⟩⟩
/--
Maps a function `f` on the fractional components of a given pair.
-/
def mapFr {β : Type*} (f : K → β) (gp : int_fract_pair K) : int_fract_pair β :=
⟨gp.b, f gp.fr⟩
section coe
/-! Interlude: define some expected coercions. -/
/- Fix another type `β` which we will convert to. -/
variables {β : Type*} [has_coe K β]
/-- Coerce a pair by coercing the fractional component. -/
instance has_coe_to_int_fract_pair : has_coe (int_fract_pair K) (int_fract_pair β) :=
⟨mapFr coe⟩
@[simp, norm_cast]
lemma coe_to_int_fract_pair {b : ℤ} {fr : K} :
(↑(int_fract_pair.mk b fr) : int_fract_pair β) = int_fract_pair.mk b (↑fr : β) :=
rfl
end coe
-- Note: this could be relaxed to something like `linear_ordered_division_ring` in the
-- future.
/- Fix a discrete linear ordered field with `floor` function. -/
variables [linear_ordered_field K] [floor_ring K]
/-- Creates the integer and fractional part of a value `v`, i.e. `⟨⌊v⌋, v - ⌊v⌋⟩`. -/
protected def of (v : K) : int_fract_pair K := ⟨⌊v⌋, int.fract v⟩
/--
Creates the stream of integer and fractional parts of a value `v` needed to obtain the continued
fraction representation of `v` in `generalized_continued_fraction.of`. More precisely, given a value
`v : K`, it recursively computes a stream of option `ℤ × K` pairs as follows:
- `stream v 0 = some ⟨⌊v⌋, v - ⌊v⌋⟩`
- `stream v (n + 1) = some ⟨⌊frₙ⁻¹⌋, frₙ⁻¹ - ⌊frₙ⁻¹⌋⟩`,
if `stream v n = some ⟨_, frₙ⟩` and `frₙ ≠ 0`
- `stream v (n + 1) = none`, otherwise
For example, let `(v : ℚ) := 3.4`. The process goes as follows:
- `stream v 0 = some ⟨⌊v⌋, v - ⌊v⌋⟩ = some ⟨3, 0.4⟩`
- `stream v 1 = some ⟨⌊0.4⁻¹⌋, 0.4⁻¹ - ⌊0.4⁻¹⌋⟩ = some ⟨⌊2.5⌋, 2.5 - ⌊2.5⌋⟩ = some ⟨2, 0.5⟩`
- `stream v 2 = some ⟨⌊0.5⁻¹⌋, 0.5⁻¹ - ⌊0.5⁻¹⌋⟩ = some ⟨⌊2⌋, 2 - ⌊2⌋⟩ = some ⟨2, 0⟩`
- `stream v n = none`, for `n ≥ 3`
-/
protected def stream (v : K) : stream $ option (int_fract_pair K)
| 0 := some (int_fract_pair.of v)
| (n + 1) := (stream n).bind $ λ ap_n,
if ap_n.fr = 0 then none else some (int_fract_pair.of ap_n.fr⁻¹)
/--
Shows that `int_fract_pair.stream` has the sequence property, that is once we return `none` at
position `n`, we also return `none` at `n + 1`.
-/
lemma stream_is_seq (v : K) : (int_fract_pair.stream v).is_seq :=
by { assume _ hyp, simp [int_fract_pair.stream, hyp] }
/--
Uses `int_fract_pair.stream` to create a sequence with head (i.e. `seq1`) of integer and fractional
parts of a value `v`. The first value of `int_fract_pair.stream` is never `none`, so we can safely
extract it and put the tail of the stream in the sequence part.
This is just an intermediate representation and users should not (need to) directly interact with
it. The setup of rewriting/simplification lemmas that make the definitions easy to use is done in
`algebra.continued_fractions.computation.translations`.
-/
protected def seq1 (v : K) : stream.seq1 $ int_fract_pair K :=
⟨ int_fract_pair.of v,--the head
stream.seq.tail -- take the tail of `int_fract_pair.stream` since the first element is already in
-- the head
-- create a sequence from `int_fract_pair.stream`
⟨ int_fract_pair.stream v, -- the underlying stream
@stream_is_seq _ _ _ v ⟩ ⟩ -- the proof that the stream is a sequence
end int_fract_pair
/--
Returns the `generalized_continued_fraction` of a value. In fact, the returned gcf is also
a `continued_fraction` that terminates if and only if `v` is rational (those proofs will be
added in a future commit).
The continued fraction representation of `v` is given by `[⌊v⌋; b₀, b₁, b₂,...]`, where
`[b₀; b₁, b₂,...]` recursively is the continued fraction representation of `1 / (v - ⌊v⌋)`. This
process stops when the fractional part `v - ⌊v⌋` hits 0 at some step.
The implementation uses `int_fract_pair.stream` to obtain the partial denominators of the continued
fraction. Refer to said function for more details about the computation process.
-/
protected def of [linear_ordered_field K] [floor_ring K] (v : K) :
generalized_continued_fraction K :=
let ⟨h, s⟩ := int_fract_pair.seq1 v in -- get the sequence of integer and fractional parts.
⟨ h.b, -- the head is just the first integer part
s.map (λ p, ⟨1, p.b⟩) ⟩ -- the sequence consists of the remaining integer parts as the partial
-- denominators; all partial numerators are simply 1
end generalized_continued_fraction
|
3b07202d4bcce9c3376cc1c3e2bce67846c0c265 | efa51dd2edbbbbd6c34bd0ce436415eb405832e7 | /20161026_ICTAC_Tutorial/ex41.lean | bc532b3b96cac02e9e8583672f4988e8e832082e | [
"Apache-2.0"
] | permissive | leanprover/presentations | dd031a05bcb12c8855676c77e52ed84246bd889a | 3ce2d132d299409f1de269fa8e95afa1333d644e | refs/heads/master | 1,688,703,388,796 | 1,686,838,383,000 | 1,687,465,742,000 | 29,750,158 | 12 | 9 | Apache-2.0 | 1,540,211,670,000 | 1,422,042,683,000 | Lean | UTF-8 | Lean | false | false | 303 | lean | variables (A : Type) (r : A → A → Prop)
variable trans_r : ∀ x y z, r x y → r y z → r x z
variables (a b c : A)
variables (hab : r a b) (hbc : r b c)
check trans_r -- ∀ (x y z : A), r x y → r y z → r x z
check trans_r a b c
check trans_r a b c hab
check trans_r a b c hab hbc
|
f6689aeeb1550bac825bb7cdd9dfe1792bd2117d | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/structPrivateFieldBug.lean | 790f1fa48b2dc796dd350bc89029f57bd30d2ade | [
"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 | 247 | lean | structure A where
private x : Nat := 10
def g (a : Nat) : A :=
{}
theorem ex1 (a : Nat) : (g a |>.x) = 10 :=
rfl
structure B extends A where
y : Nat
def f (a : Nat) : B :=
{ y := a }
theorem ex2 (a : Nat) : (f a |>.x) = 10 :=
rfl
|
407c02f6a233436ff0425ba6070b91d21022bd6d | 94e33a31faa76775069b071adea97e86e218a8ee | /src/topology/homeomorph.lean | 8dbee1460d6d002e5e27e5d62a3433fe99ffa402 | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 20,202 | lean | /-
Copyright (c) 2019 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Patrick Massot, Sébastien Gouëzel, Zhouhang Zhou, Reid Barton
-/
import logic.equiv.fin
import topology.dense_embedding
import topology.support
/-!
# Homeomorphisms
This file defines homeomorphisms between two topological spaces. They are bijections with both
directions continuous. We denote homeomorphisms with the notation `≃ₜ`.
# Main definitions
* `homeomorph α β`: The type of homeomorphisms from `α` to `β`.
This type can be denoted using the following notation: `α ≃ₜ β`.
# Main results
* Pretty much every topological property is preserved under homeomorphisms.
* `homeomorph.homeomorph_of_continuous_open`: A continuous bijection that is
an open map is a homeomorphism.
-/
open set filter
open_locale topological_space
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
/-- Homeomorphism between `α` and `β`, also called topological isomorphism -/
@[nolint has_inhabited_instance] -- not all spaces are homeomorphic to each other
structure homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β]
extends α ≃ β :=
(continuous_to_fun : continuous to_fun . tactic.interactive.continuity')
(continuous_inv_fun : continuous inv_fun . tactic.interactive.continuity')
infix ` ≃ₜ `:25 := homeomorph
namespace homeomorph
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
instance : has_coe_to_fun (α ≃ₜ β) (λ _, α → β) := ⟨λe, e.to_equiv⟩
@[simp] lemma homeomorph_mk_coe (a : equiv α β) (b c) :
((homeomorph.mk a b c) : α → β) = a :=
rfl
/-- Inverse of a homeomorphism. -/
protected def symm (h : α ≃ₜ β) : β ≃ₜ α :=
{ continuous_to_fun := h.continuous_inv_fun,
continuous_inv_fun := h.continuous_to_fun,
to_equiv := h.to_equiv.symm }
/-- See Note [custom simps projection]. We need to specify this projection explicitly in this case,
because it is a composition of multiple projections. -/
def simps.apply (h : α ≃ₜ β) : α → β := h
/-- See Note [custom simps projection] -/
def simps.symm_apply (h : α ≃ₜ β) : β → α := h.symm
initialize_simps_projections homeomorph
(to_equiv_to_fun → apply, to_equiv_inv_fun → symm_apply, -to_equiv)
@[simp] lemma coe_to_equiv (h : α ≃ₜ β) : ⇑h.to_equiv = h := rfl
@[simp] lemma coe_symm_to_equiv (h : α ≃ₜ β) : ⇑h.to_equiv.symm = h.symm := rfl
lemma to_equiv_injective : function.injective (to_equiv : α ≃ₜ β → α ≃ β)
| ⟨e, h₁, h₂⟩ ⟨e', h₁', h₂'⟩ rfl := rfl
@[ext] lemma ext {h h' : α ≃ₜ β} (H : ∀ x, h x = h' x) : h = h' :=
to_equiv_injective $ equiv.ext H
/-- Identity map as a homeomorphism. -/
@[simps apply {fully_applied := ff}]
protected def refl (α : Type*) [topological_space α] : α ≃ₜ α :=
{ continuous_to_fun := continuous_id,
continuous_inv_fun := continuous_id,
to_equiv := equiv.refl α }
/-- Composition of two homeomorphisms. -/
protected def trans (h₁ : α ≃ₜ β) (h₂ : β ≃ₜ γ) : α ≃ₜ γ :=
{ continuous_to_fun := h₂.continuous_to_fun.comp h₁.continuous_to_fun,
continuous_inv_fun := h₁.continuous_inv_fun.comp h₂.continuous_inv_fun,
to_equiv := equiv.trans h₁.to_equiv h₂.to_equiv }
@[simp] lemma trans_apply (h₁ : α ≃ₜ β) (h₂ : β ≃ₜ γ) (a : α) : h₁.trans h₂ a = h₂ (h₁ a) := rfl
@[simp] lemma homeomorph_mk_coe_symm (a : equiv α β) (b c) :
((homeomorph.mk a b c).symm : β → α) = a.symm :=
rfl
@[simp] lemma refl_symm : (homeomorph.refl α).symm = homeomorph.refl α := rfl
@[continuity]
protected lemma continuous (h : α ≃ₜ β) : continuous h := h.continuous_to_fun
@[continuity] -- otherwise `by continuity` can't prove continuity of `h.to_equiv.symm`
protected lemma continuous_symm (h : α ≃ₜ β) : continuous (h.symm) := h.continuous_inv_fun
@[simp] lemma apply_symm_apply (h : α ≃ₜ β) (x : β) : h (h.symm x) = x :=
h.to_equiv.apply_symm_apply x
@[simp] lemma symm_apply_apply (h : α ≃ₜ β) (x : α) : h.symm (h x) = x :=
h.to_equiv.symm_apply_apply x
protected lemma bijective (h : α ≃ₜ β) : function.bijective h := h.to_equiv.bijective
protected lemma injective (h : α ≃ₜ β) : function.injective h := h.to_equiv.injective
protected lemma surjective (h : α ≃ₜ β) : function.surjective h := h.to_equiv.surjective
/-- Change the homeomorphism `f` to make the inverse function definitionally equal to `g`. -/
def change_inv (f : α ≃ₜ β) (g : β → α) (hg : function.right_inverse g f) : α ≃ₜ β :=
have g = f.symm, from funext (λ x, calc g x = f.symm (f (g x)) : (f.left_inv (g x)).symm
... = f.symm x : by rw hg x),
{ to_fun := f,
inv_fun := g,
left_inv := by convert f.left_inv,
right_inv := by convert f.right_inv,
continuous_to_fun := f.continuous,
continuous_inv_fun := by convert f.symm.continuous }
@[simp] lemma symm_comp_self (h : α ≃ₜ β) : ⇑h.symm ∘ ⇑h = id :=
funext h.symm_apply_apply
@[simp] lemma self_comp_symm (h : α ≃ₜ β) : ⇑h ∘ ⇑h.symm = id :=
funext h.apply_symm_apply
@[simp] lemma range_coe (h : α ≃ₜ β) : range h = univ :=
h.surjective.range_eq
lemma image_symm (h : α ≃ₜ β) : image h.symm = preimage h :=
funext h.symm.to_equiv.image_eq_preimage
lemma preimage_symm (h : α ≃ₜ β) : preimage h.symm = image h :=
(funext h.to_equiv.image_eq_preimage).symm
@[simp] lemma image_preimage (h : α ≃ₜ β) (s : set β) : h '' (h ⁻¹' s) = s :=
h.to_equiv.image_preimage s
@[simp] lemma preimage_image (h : α ≃ₜ β) (s : set α) : h ⁻¹' (h '' s) = s :=
h.to_equiv.preimage_image s
protected lemma inducing (h : α ≃ₜ β) : inducing h :=
inducing_of_inducing_compose h.continuous h.symm.continuous $
by simp only [symm_comp_self, inducing_id]
lemma induced_eq (h : α ≃ₜ β) : topological_space.induced h ‹_› = ‹_› := h.inducing.1.symm
protected lemma quotient_map (h : α ≃ₜ β) : quotient_map h :=
quotient_map.of_quotient_map_compose h.symm.continuous h.continuous $
by simp only [self_comp_symm, quotient_map.id]
lemma coinduced_eq (h : α ≃ₜ β) : topological_space.coinduced h ‹_› = ‹_› :=
h.quotient_map.2.symm
protected lemma embedding (h : α ≃ₜ β) : embedding h :=
⟨h.inducing, h.injective⟩
/-- Homeomorphism given an embedding. -/
noncomputable def of_embedding (f : α → β) (hf : embedding f) : α ≃ₜ (set.range f) :=
{ continuous_to_fun := continuous_subtype_mk _ hf.continuous,
continuous_inv_fun := by simp [hf.continuous_iff, continuous_subtype_coe],
.. equiv.of_injective f hf.inj }
protected lemma second_countable_topology [topological_space.second_countable_topology β]
(h : α ≃ₜ β) :
topological_space.second_countable_topology α :=
h.inducing.second_countable_topology
lemma compact_image {s : set α} (h : α ≃ₜ β) : is_compact (h '' s) ↔ is_compact s :=
h.embedding.is_compact_iff_is_compact_image.symm
lemma compact_preimage {s : set β} (h : α ≃ₜ β) : is_compact (h ⁻¹' s) ↔ is_compact s :=
by rw ← image_symm; exact h.symm.compact_image
@[simp] lemma comap_cocompact (h : α ≃ₜ β) : comap h (cocompact β) = cocompact α :=
(comap_cocompact_le h.continuous).antisymm $
(has_basis_cocompact.le_basis_iff (has_basis_cocompact.comap h)).2 $ λ K hK,
⟨h ⁻¹' K, h.compact_preimage.2 hK, subset.rfl⟩
@[simp] lemma map_cocompact (h : α ≃ₜ β) : map h (cocompact α) = cocompact β :=
by rw [← h.comap_cocompact, map_comap_of_surjective h.surjective]
protected lemma compact_space [compact_space α] (h : α ≃ₜ β) : compact_space β :=
{ compact_univ := by { rw [← image_univ_of_surjective h.surjective, h.compact_image],
apply compact_space.compact_univ } }
protected lemma t0_space [t0_space α] (h : α ≃ₜ β) : t0_space β :=
h.symm.embedding.t0_space
protected lemma t1_space [t1_space α] (h : α ≃ₜ β) : t1_space β :=
h.symm.embedding.t1_space
protected lemma t2_space [t2_space α] (h : α ≃ₜ β) : t2_space β :=
h.symm.embedding.t2_space
protected lemma t3_space [t3_space α] (h : α ≃ₜ β) : t3_space β :=
h.symm.embedding.t3_space
protected lemma dense_embedding (h : α ≃ₜ β) : dense_embedding h :=
{ dense := h.surjective.dense_range,
.. h.embedding }
@[simp] lemma is_open_preimage (h : α ≃ₜ β) {s : set β} : is_open (h ⁻¹' s) ↔ is_open s :=
h.quotient_map.is_open_preimage
@[simp] lemma is_open_image (h : α ≃ₜ β) {s : set α} : is_open (h '' s) ↔ is_open s :=
by rw [← preimage_symm, is_open_preimage]
protected lemma is_open_map (h : α ≃ₜ β) : is_open_map h := λ s, h.is_open_image.2
@[simp] lemma is_closed_preimage (h : α ≃ₜ β) {s : set β} : is_closed (h ⁻¹' s) ↔ is_closed s :=
by simp only [← is_open_compl_iff, ← preimage_compl, is_open_preimage]
@[simp] lemma is_closed_image (h : α ≃ₜ β) {s : set α} : is_closed (h '' s) ↔ is_closed s :=
by rw [← preimage_symm, is_closed_preimage]
protected lemma is_closed_map (h : α ≃ₜ β) : is_closed_map h := λ s, h.is_closed_image.2
protected lemma open_embedding (h : α ≃ₜ β) : open_embedding h :=
open_embedding_of_embedding_open h.embedding h.is_open_map
protected lemma closed_embedding (h : α ≃ₜ β) : closed_embedding h :=
closed_embedding_of_embedding_closed h.embedding h.is_closed_map
protected lemma normal_space [normal_space α] (h : α ≃ₜ β) : normal_space β :=
h.symm.closed_embedding.normal_space
lemma preimage_closure (h : α ≃ₜ β) (s : set β) : h ⁻¹' (closure s) = closure (h ⁻¹' s) :=
h.is_open_map.preimage_closure_eq_closure_preimage h.continuous _
lemma image_closure (h : α ≃ₜ β) (s : set α) : h '' (closure s) = closure (h '' s) :=
by rw [← preimage_symm, preimage_closure]
lemma preimage_interior (h : α ≃ₜ β) (s : set β) : h⁻¹' (interior s) = interior (h ⁻¹' s) :=
h.is_open_map.preimage_interior_eq_interior_preimage h.continuous _
lemma image_interior (h : α ≃ₜ β) (s : set α) : h '' (interior s) = interior (h '' s) :=
by rw [← preimage_symm, preimage_interior]
lemma preimage_frontier (h : α ≃ₜ β) (s : set β) : h ⁻¹' (frontier s) = frontier (h ⁻¹' s) :=
h.is_open_map.preimage_frontier_eq_frontier_preimage h.continuous _
@[to_additive]
lemma _root_.has_compact_mul_support.comp_homeomorph {M} [has_one M] {f : β → M}
(hf : has_compact_mul_support f) (φ : α ≃ₜ β) : has_compact_mul_support (f ∘ φ) :=
hf.comp_closed_embedding φ.closed_embedding
@[simp] lemma map_nhds_eq (h : α ≃ₜ β) (x : α) : map h (𝓝 x) = 𝓝 (h x) :=
h.embedding.map_nhds_of_mem _ (by simp)
lemma symm_map_nhds_eq (h : α ≃ₜ β) (x : α) : map h.symm (𝓝 (h x)) = 𝓝 x :=
by rw [h.symm.map_nhds_eq, h.symm_apply_apply]
lemma nhds_eq_comap (h : α ≃ₜ β) (x : α) : 𝓝 x = comap h (𝓝 (h x)) :=
h.embedding.to_inducing.nhds_eq_comap x
@[simp] lemma comap_nhds_eq (h : α ≃ₜ β) (y : β) : comap h (𝓝 y) = 𝓝 (h.symm y) :=
by rw [h.nhds_eq_comap, h.apply_symm_apply]
/-- If an bijective map `e : α ≃ β` is continuous and open, then it is a homeomorphism. -/
def homeomorph_of_continuous_open (e : α ≃ β) (h₁ : continuous e) (h₂ : is_open_map e) :
α ≃ₜ β :=
{ continuous_to_fun := h₁,
continuous_inv_fun := begin
rw continuous_def,
intros s hs,
convert ← h₂ s hs using 1,
apply e.image_eq_preimage
end,
to_equiv := e }
@[simp] lemma comp_continuous_on_iff (h : α ≃ₜ β) (f : γ → α) (s : set γ) :
continuous_on (h ∘ f) s ↔ continuous_on f s :=
h.inducing.continuous_on_iff.symm
@[simp] lemma comp_continuous_iff (h : α ≃ₜ β) {f : γ → α} :
continuous (h ∘ f) ↔ continuous f :=
h.inducing.continuous_iff.symm
@[simp] lemma comp_continuous_iff' (h : α ≃ₜ β) {f : β → γ} :
continuous (f ∘ h) ↔ continuous f :=
h.quotient_map.continuous_iff.symm
lemma comp_continuous_at_iff (h : α ≃ₜ β) (f : γ → α) (x : γ) :
continuous_at (h ∘ f) x ↔ continuous_at f x :=
h.inducing.continuous_at_iff.symm
lemma comp_continuous_at_iff' (h : α ≃ₜ β) (f : β → γ) (x : α) :
continuous_at (f ∘ h) x ↔ continuous_at f (h x) :=
h.inducing.continuous_at_iff' (by simp)
lemma comp_continuous_within_at_iff (h : α ≃ₜ β) (f : γ → α) (s : set γ) (x : γ) :
continuous_within_at f s x ↔ continuous_within_at (h ∘ f) s x :=
h.inducing.continuous_within_at_iff
@[simp] lemma comp_is_open_map_iff (h : α ≃ₜ β) {f : γ → α} :
is_open_map (h ∘ f) ↔ is_open_map f :=
begin
refine ⟨_, λ hf, h.is_open_map.comp hf⟩,
intros hf,
rw [← function.comp.left_id f, ← h.symm_comp_self, function.comp.assoc],
exact h.symm.is_open_map.comp hf,
end
@[simp] lemma comp_is_open_map_iff' (h : α ≃ₜ β) {f : β → γ} :
is_open_map (f ∘ h) ↔ is_open_map f :=
begin
refine ⟨_, λ hf, hf.comp h.is_open_map⟩,
intros hf,
rw [← function.comp.right_id f, ← h.self_comp_symm, ← function.comp.assoc],
exact hf.comp h.symm.is_open_map,
end
/-- If two sets are equal, then they are homeomorphic. -/
def set_congr {s t : set α} (h : s = t) : s ≃ₜ t :=
{ continuous_to_fun := continuous_subtype_mk _ continuous_subtype_val,
continuous_inv_fun := continuous_subtype_mk _ continuous_subtype_val,
to_equiv := equiv.set_congr h }
/-- Sum of two homeomorphisms. -/
def sum_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α ⊕ γ ≃ₜ β ⊕ δ :=
{ continuous_to_fun := h₁.continuous.sum_map h₂.continuous,
continuous_inv_fun := h₁.symm.continuous.sum_map h₂.symm.continuous,
to_equiv := h₁.to_equiv.sum_congr h₂.to_equiv }
/-- Product of two homeomorphisms. -/
def prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α × γ ≃ₜ β × δ :=
{ continuous_to_fun := (h₁.continuous.comp continuous_fst).prod_mk
(h₂.continuous.comp continuous_snd),
continuous_inv_fun := (h₁.symm.continuous.comp continuous_fst).prod_mk
(h₂.symm.continuous.comp continuous_snd),
to_equiv := h₁.to_equiv.prod_congr h₂.to_equiv }
@[simp] lemma prod_congr_symm (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) :
(h₁.prod_congr h₂).symm = h₁.symm.prod_congr h₂.symm := rfl
@[simp] lemma coe_prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) :
⇑(h₁.prod_congr h₂) = prod.map h₁ h₂ := rfl
section
variables (α β γ)
/-- `α × β` is homeomorphic to `β × α`. -/
def prod_comm : α × β ≃ₜ β × α :=
{ continuous_to_fun := continuous_snd.prod_mk continuous_fst,
continuous_inv_fun := continuous_snd.prod_mk continuous_fst,
to_equiv := equiv.prod_comm α β }
@[simp] lemma prod_comm_symm : (prod_comm α β).symm = prod_comm β α := rfl
@[simp] lemma coe_prod_comm : ⇑(prod_comm α β) = prod.swap := rfl
/-- `(α × β) × γ` is homeomorphic to `α × (β × γ)`. -/
def prod_assoc : (α × β) × γ ≃ₜ α × (β × γ) :=
{ continuous_to_fun := (continuous_fst.comp continuous_fst).prod_mk
((continuous_snd.comp continuous_fst).prod_mk continuous_snd),
continuous_inv_fun := (continuous_fst.prod_mk (continuous_fst.comp continuous_snd)).prod_mk
(continuous_snd.comp continuous_snd),
to_equiv := equiv.prod_assoc α β γ }
/-- `α × {*}` is homeomorphic to `α`. -/
@[simps apply {fully_applied := ff}]
def prod_punit : α × punit ≃ₜ α :=
{ to_equiv := equiv.prod_punit α,
continuous_to_fun := continuous_fst,
continuous_inv_fun := continuous_id.prod_mk continuous_const }
/-- `{*} × α` is homeomorphic to `α`. -/
def punit_prod : punit × α ≃ₜ α :=
(prod_comm _ _).trans (prod_punit _)
@[simp] lemma coe_punit_prod : ⇑(punit_prod α) = prod.snd := rfl
end
/-- `ulift α` is homeomorphic to `α`. -/
def {u v} ulift {α : Type u} [topological_space α] : ulift.{v u} α ≃ₜ α :=
{ continuous_to_fun := continuous_ulift_down,
continuous_inv_fun := continuous_ulift_up,
to_equiv := equiv.ulift }
section distrib
/-- `(α ⊕ β) × γ` is homeomorphic to `α × γ ⊕ β × γ`. -/
def sum_prod_distrib : (α ⊕ β) × γ ≃ₜ α × γ ⊕ β × γ :=
homeomorph.symm $ homeomorph_of_continuous_open (equiv.sum_prod_distrib α β γ).symm
((continuous_inl.prod_map continuous_id).sum_elim (continuous_inr.prod_map continuous_id)) $
is_open_map_sum (open_embedding_inl.is_open_map.prod is_open_map.id)
(open_embedding_inr.is_open_map.prod is_open_map.id)
/-- `α × (β ⊕ γ)` is homeomorphic to `α × β ⊕ α × γ`. -/
def prod_sum_distrib : α × (β ⊕ γ) ≃ₜ α × β ⊕ α × γ :=
(prod_comm _ _).trans $
sum_prod_distrib.trans $
sum_congr (prod_comm _ _) (prod_comm _ _)
variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)]
/-- `(Σ i, σ i) × β` is homeomorphic to `Σ i, (σ i × β)`. -/
def sigma_prod_distrib : ((Σ i, σ i) × β) ≃ₜ (Σ i, (σ i × β)) :=
homeomorph.symm $
homeomorph_of_continuous_open (equiv.sigma_prod_distrib σ β).symm
(continuous_sigma $ λ i,
(continuous_sigma_mk.comp continuous_fst).prod_mk continuous_snd)
(is_open_map_sigma $ λ i,
(open_embedding_sigma_mk.prod open_embedding_id).is_open_map)
end distrib
/-- If `ι` has a unique element, then `ι → α` is homeomorphic to `α`. -/
@[simps { fully_applied := ff }]
def fun_unique (ι α : Type*) [unique ι] [topological_space α] : (ι → α) ≃ₜ α :=
{ to_equiv := equiv.fun_unique ι α,
continuous_to_fun := continuous_apply _,
continuous_inv_fun := continuous_pi (λ _, continuous_id) }
/-- Homeomorphism between dependent functions `Π i : fin 2, α i` and `α 0 × α 1`. -/
@[simps { fully_applied := ff }]
def {u} pi_fin_two (α : fin 2 → Type u) [Π i, topological_space (α i)] : (Π i, α i) ≃ₜ α 0 × α 1 :=
{ to_equiv := pi_fin_two_equiv α,
continuous_to_fun := (continuous_apply 0).prod_mk (continuous_apply 1),
continuous_inv_fun := continuous_pi $ fin.forall_fin_two.2 ⟨continuous_fst, continuous_snd⟩ }
/-- Homeomorphism between `α² = fin 2 → α` and `α × α`. -/
@[simps { fully_applied := ff }] def fin_two_arrow : (fin 2 → α) ≃ₜ α × α :=
{ to_equiv := fin_two_arrow_equiv α, .. pi_fin_two (λ _, α) }
/--
A subset of a topological space is homeomorphic to its image under a homeomorphism.
-/
@[simps] def image (e : α ≃ₜ β) (s : set α) : s ≃ₜ e '' s :=
{ continuous_to_fun := by continuity!,
continuous_inv_fun := by continuity!,
to_equiv := e.to_equiv.image s, }
/-- `set.univ α` is homeomorphic to `α`. -/
@[simps { fully_applied := ff }]
def set.univ (α : Type*) [topological_space α] : (univ : set α) ≃ₜ α :=
{ to_equiv := equiv.set.univ α,
continuous_to_fun := continuous_subtype_coe,
continuous_inv_fun := continuous_subtype_mk _ continuous_id }
end homeomorph
/-- An inducing equiv between topological spaces is a homeomorphism. -/
@[simps] def equiv.to_homeomorph_of_inducing [topological_space α] [topological_space β] (f : α ≃ β)
(hf : inducing f) :
α ≃ₜ β :=
{ continuous_to_fun := hf.continuous,
continuous_inv_fun := hf.continuous_iff.2 $ by simpa using continuous_id,
.. f }
namespace continuous
variables [topological_space α] [topological_space β]
lemma continuous_symm_of_equiv_compact_to_t2 [compact_space α] [t2_space β]
{f : α ≃ β} (hf : continuous f) : continuous f.symm :=
begin
rw continuous_iff_is_closed,
intros C hC,
have hC' : is_closed (f '' C) := (hC.is_compact.image hf).is_closed,
rwa equiv.image_eq_preimage at hC',
end
/-- Continuous equivalences from a compact space to a T2 space are homeomorphisms.
This is not true when T2 is weakened to T1
(see `continuous.homeo_of_equiv_compact_to_t2.t1_counterexample`). -/
@[simps]
def homeo_of_equiv_compact_to_t2 [compact_space α] [t2_space β]
{f : α ≃ β} (hf : continuous f) : α ≃ₜ β :=
{ continuous_to_fun := hf,
continuous_inv_fun := hf.continuous_symm_of_equiv_compact_to_t2,
..f }
end continuous
|
cb83355b0a3cde0f6de330526aba3f47d1da217f | 5df84495ec6c281df6d26411cc20aac5c941e745 | /src/formal_ml/cardinal_set.lean | bf83aa037d38991490e0e16e225e752896ba3a0d | [
"Apache-2.0"
] | permissive | eric-wieser/formal-ml | e278df5a8df78aa3947bc8376650419e1b2b0a14 | 630011d19fdd9539c8d6493a69fe70af5d193590 | refs/heads/master | 1,681,491,589,256 | 1,612,642,743,000 | 1,612,642,743,000 | 360,114,136 | 0 | 0 | Apache-2.0 | 1,618,998,189,000 | 1,618,998,188,000 | null | UTF-8 | Lean | false | false | 16,995 | lean | /-
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-/
import data.finset
import topology.metric_space.basic
import formal_ml.finset
import set_theory.cardinal_ordinal
namespace set
def prod_equiv_mul {α β:Type*} (s:set α) (t:set β):
(s.prod t) ≃ s × t := {
to_fun := (λ p, (subtype.mk p.val.fst p.property.left, subtype.mk p.val.snd p.property.right) ),
inv_fun := (λ p, subtype.mk (p.fst.val, p.snd.val) (set.mk_mem_prod p.fst.property
p.snd.property)) ,
left_inv :=
begin
simp [function.left_inverse],
end,
right_inv :=
begin
simp [function.right_inverse, function.left_inverse],
end,
}
lemma mem_of_mem_union_of_not_mem_left {α:Type*} {s:set α} {t:set α} {a:α} (h : a ∉ s)
(hu : a ∈ s ∪ t) : (a ∈ t) :=
begin
simp [h] at hu,
apply hu,
end
noncomputable def disjoint_union_equiv_add {α:Type*} (s:set α) (t:set α) (h:disjoint s t):
(s ∪ t:set α) ≃ s ⊕ t := {
to_fun := (λ a, (@dite (a.val ∈ s) (classical.prop_decidable _) (s ⊕ t)
(λ h, sum.inl (subtype.mk a.val h) ) (λ h, sum.inr (subtype.mk a.val
(set.mem_of_mem_union_of_not_mem_left h a.property))))),
inv_fun := (λ a, match a with
| sum.inl b := subtype.mk b.val (set.mem_union_left t b.property)
| sum.inr b := subtype.mk b.val (set.mem_union_right s b.property)
end),
left_inv :=
begin
simp [function.left_inverse],
intros x h2,
cases h2,
simp [h2],
refl,
have h3 : x ∉ s := (set.disjoint_right.mp h) h2,
simp [h3],
refl,
end,
right_inv :=
begin
simp [function.right_inverse, function.left_inverse],
split,
intros x h2,
have A1:(disjoint_union_equiv_add._match_1 s t (sum.inl (subtype.mk x h2))).val = x,
{ refl },
simp [A1,h2], refl,
intros x h2,
have A2:(disjoint_union_equiv_add._match_1 s t (sum.inr (subtype.mk x h2))).val = x := rfl,
have A3:(disjoint_union_equiv_add._match_1 s t (sum.inr (subtype.mk x h2))).val ∉ s,
{ rw A2, apply (set.disjoint_right.mp h) h2},
simp [A2, A3, h2],
refl,
end,
}
def card {α:Type*} (s:set α):cardinal :=
cardinal.mk s
lemma card_def {α:Type*} (s:set α):s.card = cardinal.mk s := rfl
lemma card_prod {α β:Type*} (s:set α) (t:set β):
(s.prod t).card = s.card * t.card :=
begin
unfold set.card,
rw cardinal.mul_def,
rw cardinal.eq,
apply nonempty.intro,
apply set.prod_equiv_mul,
end
lemma card_union {α:Type*} (s:set α) (t:set α) (h:disjoint s t):
((s ∪ t).card) = (s.card + t.card) :=
begin
have A1:(s.card + t.card) = (cardinal.mk (s ⊕ t)),
{ unfold set.card, refl },
rw A1,
unfold set.card,
rw cardinal.eq,
apply nonempty.intro,
apply disjoint_union_equiv_add s t h,
end
@[simp]
lemma card_empty (α:Type*):
(∅:set α).card = 0 :=
begin
unfold set.card,
simp,
end
@[simp]
lemma card_singleton' (α:Type*) {a:α}:
({a}:set α).card = 1 :=
begin
unfold set.card,
simp,
end
lemma card_insert' {α:Type*} (s:set α) (a:α) (h:a∉ s):
(insert a s).card = s.card + 1 :=
begin
rw set.insert_eq,
rw card_union,
rw card_singleton',
rw add_comm,
rw set.disjoint_left,
intros b h2,
simp at h2,
subst b,
apply h,
end
lemma disjoint_inter_diff {α : Type*} {s t : set α} : disjoint (t ∩ s) (t \ s) :=
begin
rw set.disjoint_left, simp, intros a A2 A3 A4, apply A3
end
lemma card_add_card_diff {α : Type*} (s t : set α) : s.card + (t \ s).card = (s ∪ t).card :=
begin
rw ← card_union,
rw set.union_diff_self,
apply set.disjoint_diff
end
lemma card_diff_add_card_inter {α : Type*} (s t : set α) : t.card = (t ∩ s).card + (t \ s).card :=
begin
rw ← card_union,
rw set.inter_union_diff,
apply set.disjoint_inter_diff,
end
lemma card_union_inter {α : Type*} {s t : set α} :
s.card + t.card = (s ∪ t).card + (s ∩ t).card :=
begin
have A1 := card_diff_add_card_inter s t,
rw add_comm at A1,
rw A1,
rw ← add_assoc,
have A2 := card_add_card_diff s t,
rw A2,
rw set.inter_comm,
end
lemma card_subset {α:Type*} {s t : set α} (h : s ⊆ t) : s.card ≤ t.card :=
begin
rw card_diff_add_card_inter s t,
rw set.inter_eq_self_of_subset_right h,
have A2 : s.card + 0 ≤ s.card + (t \ s).card,
{ apply add_le_add, apply le_refl _, apply zero_le },
rw add_zero at A2,
apply A2
end
end set
lemma nat.Iio_zero_eq_empty:set.Iio 0 = ∅ :=
begin
ext; split; simp
end
lemma nat.Iio_succ_eq_insert (n : ℕ) : set.Iio (n.succ) = insert n (set.Iio n) :=
begin
ext; split; simp,
{ intros A1,
have A2:= nat.le_of_lt_succ A1,
rw le_iff_lt_or_eq at A2,
cases A2,
{ apply set.mem_insert_of_mem, apply A2 },
cases A2,
{ apply set.mem_insert } },
{ intros A1,
have A3 : n < nat.succ n := nat.lt_succ_of_le (le_refl _),
cases A1,
subst x, apply A3, apply lt_trans A1 A3, },
end
lemma nat.plus_one_eq_succ {n:ℕ} : (n:cardinal) + 1 = (n:cardinal).succ :=
begin
apply le_antisymm,
apply cardinal.add_one_le_succ,
rw cardinal.succ_le,
have A1:(1:cardinal) = ((1:ℕ):cardinal),
{ simp },
rw A1,
rw ← nat.cast_add,
rw cardinal.nat_cast_lt,
simp,
end
lemma nat.card_Iio (n : ℕ) : (set.Iio n).card = n :=
begin
induction n,
{ rw nat.Iio_zero_eq_empty, simp },
{ rw nat.Iio_succ_eq_insert,
have A1 : n_n ∉ (set.Iio n_n),
{ simp },
rw set.card_insert' (set.Iio n_n) n_n A1, rw n_ih, simp,--rw ← nat.cast_succ,
rw nat.plus_one_eq_succ },
end
lemma cardinal_eq_of_bijective {α β:Type*} (f:α → β) (h:function.bijective f) : (cardinal.mk α = cardinal.mk β) :=
begin
haveI E := equiv.of_bijective f h,
rw cardinal.eq,
apply nonempty.intro E,
end
lemma card_eq_of_bijective {α β : Type*} {s : set α} {t : set β} (f : s → t) (h : function.bijective f) :
(s.card = t.card) :=
begin
unfold set.card,
apply cardinal_eq_of_bijective f h
end
lemma map_card {α β:Type*} {f:α → β} {s:set α} (h_inj : function.injective f):
(f '' s).card = s.card :=
begin
let g:s → (f '' s) := (λ (x:s), subtype.mk (f x.val) begin
simp,
apply exists.intro (x.val),
apply and.intro (x.property),
refl
end),
begin
symmetry,
apply card_eq_of_bijective g,
{ simp [g, function.bijective],
split,
intros a₁ a₂ A1A,
simp at A1A,
apply subtype.eq,
apply h_inj,
-- rw A0,
apply A1A,
intros x, have A1B := x.property,
simp at A1B,
cases A1B with y A1B, existsi (subtype.mk y (A1B.left)),
simp, apply subtype.eq, apply A1B.right, },
end
end
@[simp]
lemma not_lt_refl (c:cardinal) :¬ (c < c) :=
begin
simp,
end
lemma equiv_inj {α β : Type*} {s : set α} {t : set β} : s.card = t.card → 0 < t.card →
∃ f:α → β, f '' s = t :=
begin
intros A1 A2,
have A3 : t ≠ ∅,
{ intro contra, rw contra at A2, simp at A2, apply A2 },
unfold set.card at A1,
rw cardinal.eq at A1,
have A4 := classical.choice A1,
rw set.ne_empty_iff_nonempty at A3,
rw set.nonempty_def at A3,
cases A3 with b A3,
existsi (λ (a:α), @dite (a ∈ s) (classical.prop_decidable _) β
(λ h, A4.to_fun (subtype.mk a h))
(λ h, b) ),
simp,
ext,split; intros B1,
simp at B1,
cases B1 with a B1,
cases B1 with B1 B2,
subst x,
rw dif_pos,
simp,
apply B1,
simp,
have B3 := (A4.inv_fun (subtype.mk x B1)).property,
apply exists.intro (A4.inv_fun (subtype.mk x B1)).val,
apply and.intro B3,
rw dif_pos,
simp,
apply B3,
end
inductive set.finite' {α:Type*} : set α → Prop
| empty : set.finite' ∅
| insert (a:α) (s:set α) (hs:set.finite' s) : set.finite' (insert a s)
lemma finite'_of_eq_finset {α:Type*} (f : finset α) : ∀ (s:set α), (s = ↑f) → (s.finite') :=
begin
haveI := classical.decidable_eq α,
apply finset.induction_on f,
{ intros s A1, simp at A1, subst s,
apply set.finite'.empty },
{ intros a s B1 B2 t B4, simp at B4,
subst t,
apply set.finite'.insert a (↑s), apply B2, refl },
end
lemma finite'_of_finite {α:Type*} (s : set α) (h:s.finite) : (s.finite') :=
begin
haveI := classical.decidable_eq α,
unfold set.finite at h,
haveI A1 := classical.choice h,
have A2:s = ↑(finset.image subtype.val A1.elems),
{ ext; split; intros A2A,
{ simp, apply exists.intro A2A, apply A1.complete },
{ simp at A2A, cases A2A with A2A A2B, apply A2A } },
apply finite'_of_eq_finset _ s A2
end
def finset.attach' {α : Type*} [decidable_eq α] (s : finset α) (t : set α) (h : ↑s ⊆ t) :
finset t := (finset.image (λ (x : {x // x∈ s}), subtype.mk (x.val)
(set.subset_def.mp h (x.val) x.property)) s.attach)
noncomputable def fintype_of_insert {α: Type*} [decidable_eq α] (s : set α) (h : s.finite)
(a : α) : fintype (insert a s:set α) := {
elems := (insert a h.to_finset).attach' (insert a s) begin
rw set.subset_def,
intros x A1,
simp at A1,
simp,
apply A1,
end,
complete :=
begin
intros x,
simp [finset.attach', finset.attach],
existsi x.val,
split,
apply subtype.eq,
refl,
have A1 := x.property,
simp at A1,
simp [A1],
end
}
lemma finite_of_finite' {α:Type*} (s : set α) (h:s.finite') : (s.finite) :=
begin
haveI := classical.decidable_eq α,
induction h,
{ simp },
{ unfold set.finite, apply nonempty.intro,
apply fintype_of_insert h_s h_ih h_a },
end
lemma nat_cardinal_of_finite' {α : Type*} (s : set α) (h : s.finite') : ∃ (n:ℕ), s.card = n :=
begin
induction h,
existsi 0,
simp,
cases h_ih with n h_ih,
cases (classical.em (h_a ∈ h_s)) with A1 A1,
apply exists.intro n,
rw set.insert_eq_of_mem A1,
apply h_ih,
apply exists.intro n.succ,
rw set.card_insert' _ _ A1,
rw h_ih,
rw nat.plus_one_eq_succ,
simp,
end
lemma nat_cardinal_of_finite {α : Type*} (s : set α) (h : s.finite) : ∃ (n:ℕ), s.card = n :=
begin
apply nat_cardinal_of_finite' s (finite'_of_finite s h)
end
lemma empty_iff_card_eq_zero {α : Type*} (s : set α) : (s.card = 0) ↔ s = ∅ :=
begin
split; intros A1,
{ have A2 : (∅:set α).card = 0,
{ simp },
rw ← A1 at A2,
unfold set.card at A2,
rw cardinal.eq at A2,
have A3 := classical.choice A2,
rw ← set.subset_empty_iff,
rw set.subset_def,
intros x A4,
have A5 := (A3.inv_fun (subtype.mk x A4)).property,
exfalso,
simp at A5,
apply A5,
},
{ subst s, simp }
end
def set.special_image {α β : Type*} (s : set α) (f : Π (a:α) , (a ∈ s) → β) : set β :=
{ b | ∃ (a:α) (h:a ∈ s), b = f a h }
lemma set.mem_special_image {α β : Type*} (s : set α) (f : Π (a : α), (a ∈ s) → β) (a : α) (h : a ∈ s) :
f a h ∈ (s.special_image f) :=
begin
unfold set.special_image,
rw set.mem_set_of_eq,
existsi [a, h],
refl,
end
lemma set.special_image_card {α β : Type*} (s : set α) (f : Π (a:α) , (a ∈ s) → β)
(h_inj : ∀ (a₁ a₂ : α) (h1 : a₁ ∈ s) (h2 : a₂ ∈ s), (f a₁ h1 = f a₂ h2) → (a₁ = a₂)) :
(s.special_image f).card = s.card :=
begin
unfold set.special_image,
let g : s → (s.special_image f) := (λ (a:s), subtype.mk (f a.val a.property) (set.mem_special_image s f a.val a.property)),
begin
symmetry,
apply card_eq_of_bijective g,
split,
{ intros a₁ a₂ A1,
simp [g] at A1,
apply subtype.eq,
apply h_inj a₁ a₂ a₁.property a₂.property A1 },
{ intros b,
have B1 := b.property,
simp [set.special_image] at B1,
cases B1 with a B1,
cases B1 with h B1,
existsi (subtype.mk a h),
apply subtype.eq,
simp [g, set.special_image],
rw B1,
}
end
end
def set.attach {α : Type*} (s : set α) : (set s) :=
s.special_image subtype.mk
lemma set.attach_complete {α : Type*} (s : set α) (a : s) :
a ∈ (set.attach s) :=
begin
simp [set.attach, set.special_image],
existsi [a.val, a.property],
apply subtype.eq,
simp,
end
lemma subtype.val_eq_val {α :Type*} {P : α → Prop} {a b : subtype P} (h : a = b) : a.val = b.val :=
begin
rw h,
end
lemma set.attach_card {α : Type*} (s : set α) : (s.attach.card = s.card) :=
begin
unfold set.attach,
apply set.special_image_card,
intros a₁ a₂ h1 h2 A1,
apply subtype.val_eq_val A1,
end
lemma le_cardinal {α : Type*} {s:set α} {c:cardinal} :
(c ≤ s.card) ↔ (∃ t:set α, t ⊆ s ∧ t.card = c) :=
begin
rw set.card_def s,
rw cardinal.le_mk_iff_exists_set,
--have A2:(∃ (p : set ↥s), cardinal.mk ↥p = c) ↔
split; intros A1; cases A1 with t A1,
apply exists.intro ((λ (x:s), (x:α)) '' t),
split,
rw set.subset_def,
intros x B1,
simp at B1,
cases B1 with B1 B2,
apply B1,
rw map_card,
simp [set.card, A1],
intros i j C1,
apply subtype.eq,
simp at C1,
apply C1,
apply exists.intro (t.special_image (λ (a:α) (h:a ∈ t),
@subtype.mk α (λ a, a ∈ s) a ((@set.subset_def α t s).mp A1.left a h))),
cases A1 with A1 A2,
subst c,
rw ← set.card_def,
rw set.special_image_card,
intros a₁ a₂ h1 h2 h3,
have h4 := subtype.val_eq_val h3,
simp at h4,
apply h4,
end
lemma not_is_some {α : Type*} {a : option α} : (¬(option.is_some a)) ↔ (a = none) :=
begin
cases a;simp [option.is_some],
end
lemma card_finite_add_one {α β : Type*} {s : set α} {t : set β} (h_finite : s.finite)
(h_card : t.card = s.card + 1) :
(∃ (a : β) (s' : set β), t = insert a s' ∧ (a ∉ s') ∧ s'.card = s.card) :=
begin
have A1 : cardinal.mk (option s) = t.card,
{ rw h_card, rw cardinal.mk_option, refl },
unfold set.card at A1,
rw cardinal.eq at A1,
have A2 := classical.choice A1,
existsi [(A2.to_fun option.none).val, ((λ (a:s), (A2.to_fun (option.some a)).val) '' (s.attach))],
split,
ext, split; intros A3,
simp,
have A4 := A2.right_inv (subtype.mk x A3),
cases (classical.em (option.is_some (A2.inv_fun (subtype.mk x A3)))) with A5 A5,
{ right, existsi [(option.get A5).val, (option.get A5).property], split, apply set.attach_complete,
simp },
{ left, rw not_is_some at A5, rw A5 at A4, have A6 := subtype.val_eq_val A4, simp at A6, rw A6 },
simp at A3,
cases A3,
{ subst x, apply (A2 none).property },
{ cases A3 with y A3, cases A3 with A3 A4, cases A4 with A4 A5,
subst x, apply (A2 (some (subtype.mk y A3))).property, },
simp,
split,
intros x D1 D2,
cases D2 with D2 D3,
have D4 := A2.injective,
have D5 := subtype.eq D3,
have D6 := A2.injective (subtype.eq D3),
simp at D6,
apply D6,
rw map_card,
apply set.attach_card,
intros a₁ a₂ E1,
simp at E1,
have E2 := A2.injective (subtype.eq E1),
simp at E2,
apply E2,
end
lemma finite'_of_nat_cardinal {α : Type*} (n : ℕ) : ∀ (s : set α), (s.card = n) →
(s.finite') :=
begin
induction n,
{ intros s A1,
simp at A1, rw empty_iff_card_eq_zero at A1, subst s, apply finite'.empty },
{ intros t B1, simp at B1, rw ← nat.plus_one_eq_succ at B1,
have B2 : ↑n_n ≤ t.card,
{ rw B1,
have B2A : (n_n:cardinal) + 0 ≤ (n_n:cardinal) + 1,
{ apply add_le_add (le_refl _), simp },
rw add_zero at B2A,
apply B2A },
rw le_cardinal at B2,
cases B2 with u B2,
cases B2 with B2 B3,
have B4 := n_ih u B3,
have B5 := finite_of_finite' u B4,
rw ← B3 at B1,
have B6 := card_finite_add_one B5 B1,
--have B6 := card_finite_add_one B2 B5 B1,
cases B6 with a B6,
cases B6 with s' B6,
cases B6 with B6 B7,
cases B7 with B7 B8,
rw B3 at B8,
have B9 := n_ih s' B8,
subst t,
apply finite'.insert a s' B9 },
end
lemma finite_of_nat_cardinal {α : Type*} (n : ℕ) (s : set α) (h : s.card = n) :
(s.finite) :=
begin
have A1 := finite'_of_nat_cardinal n s h,
apply finite_of_finite' s A1,
end
lemma set.finite_insert {α:Type*} {s:set α} (a:α) (h:s.finite) : (insert a s).finite :=
begin
haveI D : decidable_eq α := classical.decidable_eq α,
cases (classical.em (a ∈ s)) with A1 A1,
{ have A2 : insert a s = s := set.insert_eq_of_mem A1, rw A2,
apply h },
{ haveI Fs : fintype s := classical.choice h,
haveI Fas : fintype (insert a s:set α) := set.fintype_insert' s A1,
apply nonempty.intro Fas },
end
/-
lemma card_add_one {α : Type*} {β : Type*} {s : set α} {t : set β}
(h : t.card = s.card + 1) :
(∃ (b : β) (f : s → (t \ {b} : set β)), function.bijective f) :=
begin
sorry
end
-/
|
bfa6ee297005e8abbcb30ce1189eeea7730b1201 | 86f6f4f8d827a196a32bfc646234b73328aeb306 | /examples/logic/unnamed_1703.lean | bdb6421c115c5166a0bc177f4a64cb5a4d5a837b | [] | no_license | jamescheuk91/mathematics_in_lean | 09f1f87d2b0dce53464ff0cbe592c568ff59cf5e | 4452499264e2975bca2f42565c0925506ba5dda3 | refs/heads/master | 1,679,716,410,967 | 1,613,957,947,000 | 1,613,957,947,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 117 | lean | import data.real.basic
-- BEGIN
example {x y : ℝ} : x ≤ y ∧ ¬ y ≤ x ↔ x ≤ y ∧ x ≠ y :=
sorry
-- END |
59bd2492756b0428483e8994636128b4bec57dda | 92b50235facfbc08dfe7f334827d47281471333b | /library/data/encodable.lean | f148461fdcaadcc48e9c1b2a3d6e60834fdef4c7 | [
"Apache-2.0"
] | permissive | htzh/lean | 24f6ed7510ab637379ec31af406d12584d31792c | d70c79f4e30aafecdfc4a60b5d3512199200ab6e | refs/heads/master | 1,607,677,731,270 | 1,437,089,952,000 | 1,437,089,952,000 | 37,078,816 | 0 | 0 | null | 1,433,780,956,000 | 1,433,780,955,000 | null | UTF-8 | Lean | false | false | 9,938 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
Type class for encodable types.
Note that every encodable type is countable.
-/
import data.fintype data.list data.sum data.nat data.subtype data.countable data.equiv
open option list nat function
structure encodable [class] (A : Type) :=
(encode : A → nat) (decode : nat → option A) (encodek : ∀ a, decode (encode a) = some a)
open encodable
definition countable_of_encodable {A : Type} : encodable A → countable A :=
assume e : encodable A,
have inj_encode : injective encode, from
λ (a₁ a₂ : A) (h : encode a₁ = encode a₂),
assert aux : decode A (encode a₁) = decode A (encode a₂), by rewrite h,
by rewrite [*encodek at aux]; injection aux; assumption,
exists.intro encode inj_encode
definition encodable_fintype [instance] {A : Type} [h₁ : fintype A] [h₂ : decidable_eq A] : encodable A :=
encodable.mk
(λ a, find a (elements_of A))
(λ n, nth (elements_of A) n)
(λ a, find_nth (fintype.complete a))
definition encodable_nat [instance] : encodable nat :=
encodable.mk (λ a, a) (λ n, some n) (λ a, rfl)
definition encodable_option [instance] {A : Type} [h : encodable A] : encodable (option A) :=
encodable.mk
(λ o, match o with
| some a := succ (encode a)
| none := 0
end)
(λ n, if n = 0 then some none else some (decode A (pred n)))
(λ o,
begin
cases o with a,
begin esimp end,
begin esimp, rewrite [if_neg !succ_ne_zero, encodable.encodek] end
end)
section sum
variables {A B : Type}
variables [h₁ : encodable A] [h₂ : encodable B]
include h₁ h₂
definition encode_sum : sum A B → nat
| (sum.inl a) := 2 * encode a
| (sum.inr b) := 2 * encode b + 1
definition decode_sum (n : nat) : option (sum A B) :=
if n mod 2 = 0 then
match decode A (n div 2) with
| some a := some (sum.inl a)
| none := none
end
else
match decode B ((n - 1) div 2) with
| some b := some (sum.inr b)
| none := none
end
open decidable
theorem decode_encode_sum : ∀ s : sum A B, decode_sum (encode_sum s) = some s
| (sum.inl a) :=
assert aux : 2 > 0, from dec_trivial,
begin
esimp [encode_sum, decode_sum],
rewrite [mul_mod_right, if_pos (eq.refl 0), mul_div_cancel_left _ aux, encodable.encodek]
end
| (sum.inr b) :=
assert aux₁ : 2 > 0, from dec_trivial,
assert aux₂ : 1 mod 2 = 1, by rewrite [nat.modulo_def],
assert aux₃ : 1 ≠ 0, from dec_trivial,
begin
esimp [encode_sum, decode_sum],
rewrite [add.comm, add_mul_mod_self_left, aux₂, if_neg aux₃, add_sub_cancel_left,
mul_div_cancel_left _ aux₁, encodable.encodek]
end
definition encodable_sum [instance] : encodable (sum A B) :=
encodable.mk
(λ s, encode_sum s)
(λ n, decode_sum n)
(λ s, decode_encode_sum s)
end sum
section prod
variables {A B : Type}
variables [h₁ : encodable A] [h₂ : encodable B]
include h₁ h₂
definition encode_prod : A × B → nat
| (a, b) := mkpair (encode a) (encode b)
definition decode_prod (n : nat) : option (A × B) :=
match unpair n with
| (n₁, n₂) :=
match decode A n₁ with
| some a :=
match decode B n₂ with
| some b := some (a, b)
| none := none
end
| none := none
end
end
theorem decode_encode_prod : ∀ p : A × B, decode_prod (encode_prod p) = some p
| (a, b) :=
begin
esimp [encode_prod, decode_prod, prod.cases_on],
rewrite [unpair_mkpair],
esimp,
rewrite [*encodable.encodek]
end
definition encodable_product [instance] : encodable (A × B) :=
encodable.mk
encode_prod
decode_prod
decode_encode_prod
end prod
section list
variables {A : Type}
variables [h : encodable A]
include h
definition encode_list_core : list A → nat
| [] := 0
| (a::l) := mkpair (encode a) (encode_list_core l)
theorem encode_list_core_cons (a : A) (l : list A) : encode_list_core (a::l) = mkpair (encode a) (encode_list_core l) :=
rfl
definition encode_list (l : list A) : nat :=
mkpair (length l) (encode_list_core l)
definition decode_list_core : nat → nat → option (list A)
| 0 v := some []
| (succ n) v :=
match unpair v with
| (v₁, v₂) :=
match decode A v₁ with
| some a :=
match decode_list_core n v₂ with
| some l := some (a::l)
| none := none
end
| none := none
end
end
theorem decode_list_core_succ (n v : nat) :
decode_list_core (succ n) v =
match unpair v with
| (v₁, v₂) :=
match decode A v₁ with
| some a :=
match decode_list_core n v₂ with
| some l := some (a::l)
| none := none
end
| none := none
end
end
:= rfl
definition decode_list (n : nat) : option (list A) :=
match unpair n with
| (l, v) := decode_list_core l v
end
theorem decode_encode_list_core : ∀ l : list A, decode_list_core (length l) (encode_list_core l) = some l
| [] := rfl
| (a::l) :=
begin
rewrite [encode_list_core_cons, length_cons, add_one (length l), decode_list_core_succ],
rewrite [unpair_mkpair],
esimp [prod.cases_on],
rewrite [decode_encode_list_core l],
rewrite [encodable.encodek],
end
theorem decode_encode_list (l : list A) : decode_list (encode_list l) = some l :=
begin
esimp [encode_list, decode_list],
rewrite [unpair_mkpair],
esimp [prod.cases_on],
apply decode_encode_list_core
end
definition encodable_list [instance] : encodable (list A) :=
encodable.mk
encode_list
decode_list
decode_encode_list
end list
definition encodable_of_left_injection
{A B : Type} [h₁ : encodable A]
(f : B → A) (finv : A → option B) (linv : ∀ b, finv (f b) = some b) : encodable B :=
encodable.mk
(λ b, encode (f b))
(λ n,
match decode A n with
| some a := finv a
| none := none
end)
(λ b,
begin
esimp,
rewrite [encodable.encodek],
esimp [option.cases_on],
rewrite [linv]
end)
section
open equiv
definition encodable_of_equiv {A B : Type} [h : encodable A] : A ≃ B → encodable B
| (mk f g l r) :=
encodable_of_left_injection g (λ a, some (f a))
(λ b, by rewrite r; reflexivity)
end
/-
Choice function for encodable types and decidable predicates.
We provide the following API
choose {A : Type} {p : A → Prop} [c : encodable A] [d : decidable_pred p] : (∃ x, p x) → A :=
choose_spec {A : Type} {p : A → Prop} [c : encodable A] [d : decidable_pred p] (ex : ∃ x, p x) : p (choose ex) :=
-/
section find_a
parameters {A : Type} {p : A → Prop} [c : encodable A] [d : decidable_pred p]
include c
include d
private definition pn (n : nat) : Prop :=
match decode A n with
| some a := p a
| none := false
end
private definition decidable_pn : decidable_pred pn :=
λ n,
match decode A n with
| some a := λ e : decode A n = some a,
match d a with
| decidable.inl t :=
begin
unfold pn, rewrite e, esimp [option.cases_on],
exact (decidable.inl t)
end
| decidable.inr f :=
begin
unfold pn, rewrite e, esimp [option.cases_on],
exact (decidable.inr f)
end
end
| none := λ e : decode A n = none,
begin
unfold pn, rewrite e, esimp [option.cases_on],
exact decidable_false
end
end (eq.refl (decode A n))
private definition ex_pn_of_ex : (∃ x, p x) → (∃ x, pn x) :=
assume ex,
obtain (w : A) (pw : p w), from ex,
exists.intro (encode w)
begin
unfold pn, rewrite [encodek], esimp, exact pw
end
private lemma decode_ne_none_of_pn {n : nat} : pn n → decode A n ≠ none :=
assume pnn e,
begin
rewrite [▸ (match decode A n with | some a := p a | none := false end) at pnn],
rewrite [e at pnn], esimp [option.cases_on] at pnn,
exact (false.elim pnn)
end
open subtype
private definition of_nat (n : nat) : pn n → { a : A | p a } :=
match decode A n with
| some a := λ (e : decode A n = some a),
begin
unfold pn, rewrite e, esimp [option.cases_on], intro pa,
exact (tag a pa)
end
| none := λ (e : decode A n = none) h, absurd e (decode_ne_none_of_pn h)
end (eq.refl (decode A n))
private definition find_a : (∃ x, p x) → {a : A | p a} :=
assume ex : ∃ x, p x,
have exn : ∃ x, pn x, from ex_pn_of_ex ex,
let r : nat := @nat.choose pn decidable_pn exn in
have pnr : pn r, from @nat.choose_spec pn decidable_pn exn,
of_nat r pnr
end find_a
namespace encodable
open subtype
definition choose {A : Type} {p : A → Prop} [c : encodable A] [d : decidable_pred p] : (∃ x, p x) → A :=
assume ex, elt_of (find_a ex)
theorem choose_spec {A : Type} {p : A → Prop} [c : encodable A] [d : decidable_pred p] (ex : ∃ x, p x) : p (choose ex) :=
has_property (find_a ex)
theorem axiom_of_choice {A : Type} {B : A → Type} {R : Π x, B x → Prop} [c : Π a, encodable (B a)] [d : ∀ x y, decidable (R x y)]
: (∀x, ∃y, R x y) → ∃f, ∀x, R x (f x) :=
assume H,
have H₁ : ∀x, R x (choose (H x)), from take x, choose_spec (H x),
exists.intro _ H₁
theorem skolem {A : Type} {B : A → Type} {P : Π x, B x → Prop} [c : Π a, encodable (B a)] [d : ∀ x y, decidable (P x y)]
: (∀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))
end encodable
namespace quot
section
open setoid encodable
parameter {A : Type}
parameter {s : setoid A}
parameter [decR : ∀ a b : A, decidable (a ≈ b)]
parameter [encA : encodable A]
include decR
include encA
-- Choose equivalence class representative
definition rep (q : quot s) : A :=
choose (exists_rep q)
theorem rep_spec (q : quot s) : ⟦rep q⟧ = q :=
choose_spec (exists_rep q)
end
end quot
|
b7c4945892dd6a1c4cbe95572380f326e26bc43d | 969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb | /src/algebraic_topology/simplicial_object.lean | d09440094311bba7fdcf2ce333df84571cf84342 | [
"Apache-2.0"
] | permissive | SAAluthwela/mathlib | 62044349d72dd63983a8500214736aa7779634d3 | 83a4b8b990907291421de54a78988c024dc8a552 | refs/heads/master | 1,679,433,873,417 | 1,615,998,031,000 | 1,615,998,031,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,575 | lean | /-
Copyright (c) 2021 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Scott Morrison
-/
import algebraic_topology.simplex_category
import category_theory.category.ulift
import category_theory.limits.functor_category
import category_theory.opposites
import category_theory.adjunction.limits
/-!
# Simplicial objects in a category.
A simplicial object in a category `C` is a `C`-valued presheaf on `simplex_category`.
-/
open opposite
open category_theory
open category_theory.limits
universes v u
namespace category_theory
variables (C : Type u) [category.{v} C]
/-- The category of simplicial objects valued in a category `C`.
This is the category of contravariant functors from `simplex_category` to `C`. -/
@[derive category, nolint has_inhabited_instance]
def simplicial_object := simplex_categoryᵒᵖ ⥤ C
namespace simplicial_object
instance {J : Type v} [small_category J] [has_limits_of_shape J C] :
has_limits_of_shape J (simplicial_object C) :=
let E : (simplex_categoryᵒᵖ ⥤ C) ≌ (ulift.{v} simplex_category)ᵒᵖ ⥤ C :=
ulift.equivalence.op.congr_left in
adjunction.has_limits_of_shape_of_equivalence E.functor
instance [has_limits C] : has_limits (simplicial_object C) := ⟨infer_instance⟩
instance {J : Type v} [small_category J] [has_colimits_of_shape J C] :
has_colimits_of_shape J (simplicial_object C) :=
let E : (simplex_categoryᵒᵖ ⥤ C) ≌ (ulift.{v} simplex_category)ᵒᵖ ⥤ C :=
ulift.equivalence.op.congr_left in
adjunction.has_colimits_of_shape_of_equivalence E.functor
instance [has_colimits C] : has_colimits (simplicial_object C) := ⟨infer_instance⟩
variables {C} (X : simplicial_object C)
/-- Face maps for a simplicial object. -/
def δ {n} (i : fin (n+2)) : X.obj (op (n+1 : ℕ)) ⟶ X.obj (op n) :=
X.map (simplex_category.δ i).op
/-- Degeneracy maps for a simplicial object. -/
def σ {n} (i : fin (n+1)) : X.obj (op n) ⟶ X.obj (op (n+1 : ℕ)) :=
X.map (simplex_category.σ i).op
/-- Isomorphisms from identities in ℕ. -/
def eq_to_iso {n m : ℕ} (h : n = m) : X.obj (op n) ≅ X.obj (op m) :=
X.map_iso (eq_to_iso (by rw h))
@[simp] lemma eq_to_iso_refl {n : ℕ} (h : n = n) : X.eq_to_iso h = iso.refl _ :=
by { ext, simp [eq_to_iso], }
/-- The generic case of the first simplicial identity -/
lemma δ_comp_δ {n} {i j : fin (n+2)} (H : i ≤ j) :
X.δ j.succ ≫ X.δ i = X.δ i.cast_succ ≫ X.δ j :=
by { dsimp [δ], simp only [←X.map_comp, ←op_comp, simplex_category.δ_comp_δ H] }
/-- The special case of the first simplicial identity -/
lemma δ_comp_δ_self {n} {i : fin (n+2)} : X.δ i.cast_succ ≫ X.δ i = X.δ i.succ ≫ X.δ i :=
by { dsimp [δ], simp only [←X.map_comp, ←op_comp, simplex_category.δ_comp_δ_self] }
/-- The second simplicial identity -/
lemma δ_comp_σ_of_le {n} {i : fin (n+2)} {j : fin (n+1)} (H : i ≤ j.cast_succ) :
X.σ j.succ ≫ X.δ i.cast_succ = X.δ i ≫ X.σ j :=
by { dsimp [δ, σ], simp only [←X.map_comp, ←op_comp, simplex_category.δ_comp_σ_of_le H] }
/-- The first part of the third simplicial identity -/
lemma δ_comp_σ_self {n} {i : fin (n+1)} :
X.σ i ≫ X.δ i.cast_succ = 𝟙 _ :=
begin
dsimp [δ, σ],
simp only [←X.map_comp, ←op_comp, simplex_category.δ_comp_σ_self, op_id, X.map_id],
end
/-- The second part of the third simplicial identity -/
lemma δ_comp_σ_succ {n} {i : fin (n+1)} :
X.σ i ≫ X.δ i.succ = 𝟙 _ :=
begin
dsimp [δ, σ],
simp only [←X.map_comp, ←op_comp, simplex_category.δ_comp_σ_succ, op_id, X.map_id],
end
/-- The fourth simplicial identity -/
lemma δ_comp_σ_of_gt {n} {i : fin (n+2)} {j : fin (n+1)} (H : j.cast_succ < i) :
X.σ j.cast_succ ≫ X.δ i.succ = X.δ i ≫ X.σ j :=
by { dsimp [δ, σ], simp only [←X.map_comp, ←op_comp, simplex_category.δ_comp_σ_of_gt H] }
/-- The fifth simplicial identity -/
lemma σ_comp_σ {n} {i j : fin (n+1)} (H : i ≤ j) :
X.σ j ≫ X.σ i.cast_succ = X.σ i ≫ X.σ j.succ :=
by { dsimp [δ, σ], simp only [←X.map_comp, ←op_comp, simplex_category.σ_comp_σ H] }
variable (C)
/-- Truncated simplicial objects. -/
@[derive category, nolint has_inhabited_instance]
def truncated (n : ℕ) := (simplex_category.truncated n)ᵒᵖ ⥤ C
variable {C}
namespace truncated
instance {n} {J : Type v} [small_category J] [has_limits_of_shape J C] :
has_limits_of_shape J (simplicial_object.truncated C n) :=
let E : (simplex_category.truncated n)ᵒᵖ ⥤ C ≌ (ulift.{v} (simplex_category.truncated n))ᵒᵖ ⥤ C :=
ulift.equivalence.op.congr_left in
adjunction.has_limits_of_shape_of_equivalence E.functor
instance {n} [has_limits C] : has_limits (simplicial_object.truncated C n) := ⟨infer_instance⟩
instance {n} {J : Type v} [small_category J] [has_colimits_of_shape J C] :
has_colimits_of_shape J (simplicial_object.truncated C n) :=
let E : (simplex_category.truncated n)ᵒᵖ ⥤ C ≌ (ulift.{v} (simplex_category.truncated n))ᵒᵖ ⥤ C :=
ulift.equivalence.op.congr_left in
adjunction.has_colimits_of_shape_of_equivalence E.functor
instance {n} [has_colimits C] : has_colimits (simplicial_object.truncated C n) := ⟨infer_instance⟩
end truncated
section skeleton
/-- The skeleton functor from simplicial objects to truncated simplicial objects. -/
def sk (n : ℕ) : simplicial_object C ⥤ simplicial_object.truncated C n :=
(whiskering_left _ _ _).obj (simplex_category.truncated.inclusion).op
end skeleton
end simplicial_object
end category_theory
|
790ec61066f23f26e126489bc957798ab4e91dc3 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/pkg/frontend/Frontend/Main.lean | 2a4f622de8eb89979c36337796f7754290b905e1 | [
"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 | 370 | lean | import Frontend.Compile
open Lean
unsafe def main (args : List String) : IO UInt32 := do
initSearchPath (← findSysroot)
let mut count : UInt32 := 0
for mod in args do
IO.println s!"Compiling {mod}"
let (_env, msgs) ← compileModule mod.toName true
for m in msgs do IO.println (← m.toString)
if msgs.length > 0 then count := 1
return count
|
fd76a5686dd5311f3117ffb61d4fe8b602822bbe | 8eeb99d0fdf8125f5d39a0ce8631653f588ee817 | /src/topology/constructions.lean | 027ccd5076a1d2909f93ae704a919e8afddb7247 | [
"Apache-2.0"
] | permissive | jesse-michael-han/mathlib | a15c58378846011b003669354cbab7062b893cfe | fa6312e4dc971985e6b7708d99a5bc3062485c89 | refs/heads/master | 1,625,200,760,912 | 1,602,081,753,000 | 1,602,081,753,000 | 181,787,230 | 0 | 0 | null | 1,555,460,682,000 | 1,555,460,682,000 | null | UTF-8 | Lean | false | false | 34,487 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot
-/
import topology.maps
/-!
# Constructions of new topological spaces from old ones
This file constructs products, sums, subtypes and quotients of topological spaces
and sets up their basic theory, such as criteria for maps into or out of these
constructions to be continuous; descriptions of the open sets, neighborhood filters,
and generators of these constructions; and their behavior with respect to embeddings
and other specific classes of maps.
## Implementation note
The constructed topologies are defined using induced and coinduced topologies
along with the complete lattice structure on topologies. Their universal properties
(for example, a map `X → Y × Z` is continuous if and only if both projections
`X → Y`, `X → Z` are) follow easily using order-theoretic descriptions of
continuity. With more work we can also extract descriptions of the open sets,
neighborhood filters and so on.
## Tags
product, sum, disjoint union, subspace, quotient space
-/
noncomputable theory
open topological_space set filter
open_locale classical topological_space filter
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
section constructions
instance {p : α → Prop} [t : topological_space α] : topological_space (subtype p) :=
induced coe t
instance {r : α → α → Prop} [t : topological_space α] : topological_space (quot r) :=
coinduced (quot.mk r) t
instance {s : setoid α} [t : topological_space α] : topological_space (quotient s) :=
coinduced quotient.mk t
instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α × β) :=
induced prod.fst t₁ ⊓ induced prod.snd t₂
instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α ⊕ β) :=
coinduced sum.inl t₁ ⊔ coinduced sum.inr t₂
instance {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (sigma β) :=
⨆a, coinduced (sigma.mk a) (t₂ a)
instance Pi.topological_space {β : α → Type v} [t₂ : Πa, topological_space (β a)] :
topological_space (Πa, β a) :=
⨅a, induced (λf, f a) (t₂ a)
instance ulift.topological_space [t : topological_space α] : topological_space (ulift.{v u} α) :=
t.induced ulift.down
lemma quotient_dense_of_dense [setoid α] [topological_space α] {s : set α} (H : ∀ x, x ∈ closure s) :
closure (quotient.mk '' s) = univ :=
eq_univ_of_forall $ λ x, begin
rw mem_closure_iff,
intros U U_op x_in_U,
let V := quotient.mk ⁻¹' U,
cases quotient.exists_rep x with y y_x,
have y_in_V : y ∈ V, by simp only [mem_preimage, y_x, x_in_U],
have V_op : is_open V := U_op,
obtain ⟨w, w_in_V, w_in_range⟩ : (V ∩ s).nonempty := mem_closure_iff.1 (H y) V V_op y_in_V,
exact ⟨_, w_in_V, mem_image_of_mem quotient.mk w_in_range⟩
end
instance {p : α → Prop} [topological_space α] [discrete_topology α] :
discrete_topology (subtype p) :=
⟨bot_unique $ assume s hs,
⟨coe '' s, is_open_discrete _, (set.preimage_image_eq _ subtype.coe_injective)⟩⟩
instance sum.discrete_topology [topological_space α] [topological_space β]
[hα : discrete_topology α] [hβ : discrete_topology β] : discrete_topology (α ⊕ β) :=
⟨by unfold sum.topological_space; simp [hα.eq_bot, hβ.eq_bot]⟩
instance sigma.discrete_topology {β : α → Type v} [Πa, topological_space (β a)]
[h : Πa, discrete_topology (β a)] : discrete_topology (sigma β) :=
⟨by { unfold sigma.topological_space, simp [λ a, (h a).eq_bot] }⟩
section topα
variable [topological_space α]
/-
The 𝓝 filter and the subspace topology.
-/
theorem mem_nhds_subtype (s : set α) (a : {x // x ∈ s}) (t : set {x // x ∈ s}) :
t ∈ 𝓝 a ↔ ∃ u ∈ 𝓝 (a : α), coe ⁻¹' u ⊆ t :=
mem_nhds_induced coe a t
theorem nhds_subtype (s : set α) (a : {x // x ∈ s}) :
𝓝 a = comap coe (𝓝 (a : α)) :=
nhds_induced coe a
end topα
end constructions
section prod
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
@[continuity] lemma continuous_fst : continuous (@prod.fst α β) :=
continuous_inf_dom_left continuous_induced_dom
lemma continuous_at_fst {p : α × β} : continuous_at prod.fst p :=
continuous_fst.continuous_at
@[continuity] lemma continuous_snd : continuous (@prod.snd α β) :=
continuous_inf_dom_right continuous_induced_dom
lemma continuous_at_snd {p : α × β} : continuous_at prod.snd p :=
continuous_snd.continuous_at
@[continuity] lemma continuous.prod_mk {f : γ → α} {g : γ → β}
(hf : continuous f) (hg : continuous g) : continuous (λx, (f x, g x)) :=
continuous_inf_rng (continuous_induced_rng hf) (continuous_induced_rng hg)
lemma continuous.prod_map {f : γ → α} {g : δ → β} (hf : continuous f) (hg : continuous g) :
continuous (λ x : γ × δ, (f x.1, g x.2)) :=
(hf.comp continuous_fst).prod_mk (hg.comp continuous_snd)
lemma filter.eventually.prod_inl_nhds {p : α → Prop} {a : α} (h : ∀ᶠ x in 𝓝 a, p x) (b : β) :
∀ᶠ x in 𝓝 (a, b), p (x : α × β).1 :=
continuous_at_fst h
lemma filter.eventually.prod_inr_nhds {p : β → Prop} {b : β} (h : ∀ᶠ x in 𝓝 b, p x) (a : α) :
∀ᶠ x in 𝓝 (a, b), p (x : α × β).2 :=
continuous_at_snd h
lemma filter.eventually.prod_mk_nhds {pa : α → Prop} {a} (ha : ∀ᶠ x in 𝓝 a, pa x)
{pb : β → Prop} {b} (hb : ∀ᶠ y in 𝓝 b, pb y) :
∀ᶠ p in 𝓝 (a, b), pa (p : α × β).1 ∧ pb p.2 :=
(ha.prod_inl_nhds b).and (hb.prod_inr_nhds a)
lemma continuous_swap : continuous (prod.swap : α × β → β × α) :=
continuous.prod_mk continuous_snd continuous_fst
lemma is_open_prod {s : set α} {t : set β} (hs : is_open s) (ht : is_open t) :
is_open (set.prod s t) :=
is_open_inter (continuous_fst s hs) (continuous_snd t ht)
lemma nhds_prod_eq {a : α} {b : β} : 𝓝 (a, b) = 𝓝 a ×ᶠ 𝓝 b :=
by rw [filter.prod, prod.topological_space, nhds_inf, nhds_induced, nhds_induced]
instance [discrete_topology α] [discrete_topology β] : discrete_topology (α × β) :=
⟨eq_of_nhds_eq_nhds $ assume ⟨a, b⟩,
by rw [nhds_prod_eq, nhds_discrete α, nhds_discrete β, nhds_bot, filter.prod_pure_pure]⟩
lemma prod_mem_nhds_sets {s : set α} {t : set β} {a : α} {b : β}
(ha : s ∈ 𝓝 a) (hb : t ∈ 𝓝 b) : set.prod s t ∈ 𝓝 (a, b) :=
by rw [nhds_prod_eq]; exact prod_mem_prod ha hb
lemma nhds_swap (a : α) (b : β) : 𝓝 (a, b) = (𝓝 (b, a)).map prod.swap :=
by rw [nhds_prod_eq, filter.prod_comm, nhds_prod_eq]; refl
lemma filter.tendsto.prod_mk_nhds {γ} {a : α} {b : β} {f : filter γ} {ma : γ → α} {mb : γ → β}
(ha : tendsto ma f (𝓝 a)) (hb : tendsto mb f (𝓝 b)) :
tendsto (λc, (ma c, mb c)) f (𝓝 (a, b)) :=
by rw [nhds_prod_eq]; exact filter.tendsto.prod_mk ha hb
lemma filter.eventually.curry_nhds {p : α × β → Prop} {x : α} {y : β} (h : ∀ᶠ x in 𝓝 (x, y), p x) :
∀ᶠ x' in 𝓝 x, ∀ᶠ y' in 𝓝 y, p (x', y') :=
by { rw [nhds_prod_eq] at h, exact h.curry }
lemma continuous_at.prod {f : α → β} {g : α → γ} {x : α}
(hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, (f x, g x)) x :=
hf.prod_mk_nhds hg
lemma continuous_at.prod_map {f : α → γ} {g : β → δ} {p : α × β}
(hf : continuous_at f p.fst) (hg : continuous_at g p.snd) :
continuous_at (λ p : α × β, (f p.1, g p.2)) p :=
(hf.comp continuous_fst.continuous_at).prod (hg.comp continuous_snd.continuous_at)
lemma continuous_at.prod_map' {f : α → γ} {g : β → δ} {x : α} {y : β}
(hf : continuous_at f x) (hg : continuous_at g y) :
continuous_at (λ p : α × β, (f p.1, g p.2)) (x, y) :=
have hf : continuous_at f (x, y).fst, from hf,
have hg : continuous_at g (x, y).snd, from hg,
hf.prod_map hg
lemma prod_generate_from_generate_from_eq {α : Type*} {β : Type*} {s : set (set α)} {t : set (set β)}
(hs : ⋃₀ s = univ) (ht : ⋃₀ t = univ) :
@prod.topological_space α β (generate_from s) (generate_from t) =
generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} :=
let G := generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} in
le_antisymm
(le_generate_from $ assume g ⟨u, hu, v, hv, g_eq⟩, g_eq.symm ▸
@is_open_prod _ _ (generate_from s) (generate_from t) _ _
(generate_open.basic _ hu) (generate_open.basic _ hv))
(le_inf
(coinduced_le_iff_le_induced.mp $ le_generate_from $ assume u hu,
have (⋃v∈t, set.prod u v) = prod.fst ⁻¹' u,
from calc (⋃v∈t, set.prod u v) = set.prod u univ :
set.ext $ assume ⟨a, b⟩, by rw ← ht; simp [and.left_comm] {contextual:=tt}
... = prod.fst ⁻¹' u : by simp [set.prod, preimage],
show G.is_open (prod.fst ⁻¹' u),
from this ▸ @is_open_Union _ _ G _ $ assume v, @is_open_Union _ _ G _ $ assume hv,
generate_open.basic _ ⟨_, hu, _, hv, rfl⟩)
(coinduced_le_iff_le_induced.mp $ le_generate_from $ assume v hv,
have (⋃u∈s, set.prod u v) = prod.snd ⁻¹' v,
from calc (⋃u∈s, set.prod u v) = set.prod univ v:
set.ext $ assume ⟨a, b⟩, by rw [←hs]; by_cases b ∈ v; simp [h] {contextual:=tt}
... = prod.snd ⁻¹' v : by simp [set.prod, preimage],
show G.is_open (prod.snd ⁻¹' v),
from this ▸ @is_open_Union _ _ G _ $ assume u, @is_open_Union _ _ G _ $ assume hu,
generate_open.basic _ ⟨_, hu, _, hv, rfl⟩))
lemma prod_eq_generate_from :
prod.topological_space =
generate_from {g | ∃(s:set α) (t:set β), is_open s ∧ is_open t ∧ g = set.prod s t} :=
le_antisymm
(le_generate_from $ assume g ⟨s, t, hs, ht, g_eq⟩, g_eq.symm ▸ is_open_prod hs ht)
(le_inf
(ball_image_of_ball $ λt ht, generate_open.basic _ ⟨t, univ, by simpa [set.prod_eq] using ht⟩)
(ball_image_of_ball $ λt ht, generate_open.basic _ ⟨univ, t, by simpa [set.prod_eq] using ht⟩))
lemma is_open_prod_iff {s : set (α×β)} : is_open s ↔
(∀a b, (a, b) ∈ s → ∃u v, is_open u ∧ is_open v ∧ a ∈ u ∧ b ∈ v ∧ set.prod u v ⊆ s) :=
begin
rw [is_open_iff_nhds],
simp [nhds_prod_eq, mem_prod_iff],
simp [mem_nhds_sets_iff],
exact forall_congr (assume a, ball_congr $ assume b h,
⟨assume ⟨u', ⟨u, us, uo, au⟩, v', ⟨v, vs, vo, bv⟩, h⟩,
⟨u, uo, v, vo, au, bv, subset.trans (set.prod_mono us vs) h⟩,
assume ⟨u, uo, v, vo, au, bv, h⟩,
⟨u, ⟨u, subset.refl u, uo, au⟩, v, ⟨v, subset.refl v, vo, bv⟩, h⟩⟩)
end
/-- Given an open neighborhood `s` of `(x, x)`, then `(x, x)` has a square open neighborhood
that is a subset of `s`. -/
lemma exists_nhds_square {s : set (α × α)} (hs : is_open s) {x : α} (hx : (x, x) ∈ s) :
∃U, is_open U ∧ x ∈ U ∧ set.prod U U ⊆ s :=
begin
rcases is_open_prod_iff.mp hs x x hx with ⟨u, v, hu, hv, h1x, h2x, h2s⟩,
refine ⟨u ∩ v, is_open_inter hu hv, ⟨h1x, h2x⟩, subset.trans _ h2s⟩,
simp only [prod_subset_prod_iff, inter_subset_left, true_or, inter_subset_right, and_self],
end
/-- The first projection in a product of topological spaces sends open sets to open sets. -/
lemma is_open_map_fst : is_open_map (@prod.fst α β) :=
begin
assume s hs,
rw is_open_iff_forall_mem_open,
assume x xs,
rw mem_image_eq at xs,
rcases xs with ⟨⟨y₁, y₂⟩, ys, yx⟩,
rcases is_open_prod_iff.1 hs _ _ ys with ⟨o₁, o₂, o₁_open, o₂_open, yo₁, yo₂, ho⟩,
simp at yx,
rw yx at yo₁,
refine ⟨o₁, _, o₁_open, yo₁⟩,
assume z zs,
rw mem_image_eq,
exact ⟨(z, y₂), ho (by simp [zs, yo₂]), rfl⟩
end
/-- The second projection in a product of topological spaces sends open sets to open sets. -/
lemma is_open_map_snd : is_open_map (@prod.snd α β) :=
begin
/- This lemma could be proved by composing the fact that the first projection is open, and
exchanging coordinates is a homeomorphism, hence open. As the `prod_comm` homeomorphism is defined
later, we rather go for the direct proof, copy-pasting the proof for the first projection. -/
assume s hs,
rw is_open_iff_forall_mem_open,
assume x xs,
rw mem_image_eq at xs,
rcases xs with ⟨⟨y₁, y₂⟩, ys, yx⟩,
rcases is_open_prod_iff.1 hs _ _ ys with ⟨o₁, o₂, o₁_open, o₂_open, yo₁, yo₂, ho⟩,
simp at yx,
rw yx at yo₂,
refine ⟨o₂, _, o₂_open, yo₂⟩,
assume z zs,
rw mem_image_eq,
exact ⟨(y₁, z), ho (by simp [zs, yo₁]), rfl⟩
end
/-- A product set is open in a product space if and only if each factor is open, or one of them is
empty -/
lemma is_open_prod_iff' {s : set α} {t : set β} :
is_open (set.prod s t) ↔ (is_open s ∧ is_open t) ∨ (s = ∅) ∨ (t = ∅) :=
begin
cases (set.prod s t).eq_empty_or_nonempty with h h,
{ simp [h, prod_eq_empty_iff.1 h] },
{ have st : s.nonempty ∧ t.nonempty, from prod_nonempty_iff.1 h,
split,
{ assume H : is_open (set.prod s t),
refine or.inl ⟨_, _⟩,
show is_open s,
{ rw ← fst_image_prod s st.2,
exact is_open_map_fst _ H },
show is_open t,
{ rw ← snd_image_prod st.1 t,
exact is_open_map_snd _ H } },
{ assume H,
simp [st.1.ne_empty, st.2.ne_empty] at H,
exact is_open_prod H.1 H.2 } }
end
lemma closure_prod_eq {s : set α} {t : set β} :
closure (set.prod s t) = set.prod (closure s) (closure t) :=
set.ext $ assume ⟨a, b⟩,
have (𝓝 a ×ᶠ 𝓝 b) ⊓ 𝓟 (set.prod s t) = (𝓝 a ⊓ 𝓟 s) ×ᶠ (𝓝 b ⊓ 𝓟 t),
by rw [←prod_inf_prod, prod_principal_principal],
by simp [closure_eq_cluster_pts, cluster_pt, nhds_prod_eq, this]; exact prod_ne_bot
lemma mem_closure2 {s : set α} {t : set β} {u : set γ} {f : α → β → γ} {a : α} {b : β}
(hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t)
(hu : ∀a b, a ∈ s → b ∈ t → f a b ∈ u) :
f a b ∈ closure u :=
have (a, b) ∈ closure (set.prod s t), by rw [closure_prod_eq]; from ⟨ha, hb⟩,
show (λp:α×β, f p.1 p.2) (a, b) ∈ closure u, from
mem_closure hf this $ assume ⟨a, b⟩ ⟨ha, hb⟩, hu a b ha hb
lemma is_closed_prod {s₁ : set α} {s₂ : set β} (h₁ : is_closed s₁) (h₂ : is_closed s₂) :
is_closed (set.prod s₁ s₂) :=
closure_eq_iff_is_closed.mp $ by simp only [h₁.closure_eq, h₂.closure_eq, closure_prod_eq]
lemma dense_range.prod {ι : Type*} {κ : Type*} {f : ι → β} {g : κ → γ}
(hf : dense_range f) (hg : dense_range g) : dense_range (λ p : ι × κ, (f p.1, g p.2)) :=
have closure (range $ λ p : ι×κ, (f p.1, g p.2)) = set.prod (closure $ range f) (closure $ range g),
by rw [←closure_prod_eq, prod_range_range_eq],
assume ⟨b, d⟩, this.symm ▸ mem_prod.2 ⟨hf _, hg _⟩
lemma inducing.prod_mk {f : α → β} {g : γ → δ} (hf : inducing f) (hg : inducing g) :
inducing (λx:α×γ, (f x.1, g x.2)) :=
⟨by rw [prod.topological_space, prod.topological_space, hf.induced, hg.induced,
induced_compose, induced_compose, induced_inf, induced_compose, induced_compose]⟩
lemma embedding.prod_mk {f : α → β} {g : γ → δ} (hf : embedding f) (hg : embedding g) :
embedding (λx:α×γ, (f x.1, g x.2)) :=
{ inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨hf.inj h₁, hg.inj h₂⟩,
..hf.to_inducing.prod_mk hg.to_inducing }
protected lemma is_open_map.prod {f : α → β} {g : γ → δ} (hf : is_open_map f) (hg : is_open_map g) :
is_open_map (λ p : α × γ, (f p.1, g p.2)) :=
begin
rw [is_open_map_iff_nhds_le],
rintros ⟨a, b⟩,
rw [nhds_prod_eq, nhds_prod_eq, ← filter.prod_map_map_eq],
exact filter.prod_mono (is_open_map_iff_nhds_le.1 hf a) (is_open_map_iff_nhds_le.1 hg b)
end
protected lemma open_embedding.prod {f : α → β} {g : γ → δ}
(hf : open_embedding f) (hg : open_embedding g) : open_embedding (λx:α×γ, (f x.1, g x.2)) :=
open_embedding_of_embedding_open (hf.1.prod_mk hg.1)
(hf.is_open_map.prod hg.is_open_map)
lemma embedding_graph {f : α → β} (hf : continuous f) : embedding (λx, (x, f x)) :=
embedding_of_embedding_compose (continuous_id.prod_mk hf) continuous_fst embedding_id
end prod
section sum
open sum
variables [topological_space α] [topological_space β] [topological_space γ]
@[continuity] lemma continuous_inl : continuous (@inl α β) :=
continuous_sup_rng_left continuous_coinduced_rng
@[continuity] lemma continuous_inr : continuous (@inr α β) :=
continuous_sup_rng_right continuous_coinduced_rng
@[continuity] lemma continuous_sum_rec {f : α → γ} {g : β → γ}
(hf : continuous f) (hg : continuous g) : @continuous (α ⊕ β) γ _ _ (@sum.rec α β (λ_, γ) f g) :=
continuous_sup_dom hf hg
lemma is_open_sum_iff {s : set (α ⊕ β)} :
is_open s ↔ is_open (inl ⁻¹' s) ∧ is_open (inr ⁻¹' s) :=
iff.rfl
lemma is_open_map_sum {f : α ⊕ β → γ}
(h₁ : is_open_map (λ a, f (inl a))) (h₂ : is_open_map (λ b, f (inr b))) :
is_open_map f :=
begin
intros u hu,
rw is_open_sum_iff at hu,
cases hu with hu₁ hu₂,
have : u = inl '' (inl ⁻¹' u) ∪ inr '' (inr ⁻¹' u),
{ ext (_|_); simp },
rw [this, set.image_union, set.image_image, set.image_image],
exact is_open_union (h₁ _ hu₁) (h₂ _ hu₂)
end
lemma embedding_inl : embedding (@inl α β) :=
{ induced := begin
unfold sum.topological_space,
apply le_antisymm,
{ rw ← coinduced_le_iff_le_induced, exact le_sup_left },
{ intros u hu, existsi (inl '' u),
change
(is_open (inl ⁻¹' (@inl α β '' u)) ∧
is_open (inr ⁻¹' (@inl α β '' u))) ∧
inl ⁻¹' (inl '' u) = u,
have : inl ⁻¹' (@inl α β '' u) = u :=
preimage_image_eq u (λ _ _, inl.inj_iff.mp), rw this,
have : inr ⁻¹' (@inl α β '' u) = ∅ :=
eq_empty_iff_forall_not_mem.mpr (assume a ⟨b, _, h⟩, inl_ne_inr h), rw this,
exact ⟨⟨hu, is_open_empty⟩, rfl⟩ }
end,
inj := λ _ _, inl.inj_iff.mp }
lemma embedding_inr : embedding (@inr α β) :=
{ induced := begin
unfold sum.topological_space,
apply le_antisymm,
{ rw ← coinduced_le_iff_le_induced, exact le_sup_right },
{ intros u hu, existsi (inr '' u),
change
(is_open (inl ⁻¹' (@inr α β '' u)) ∧
is_open (inr ⁻¹' (@inr α β '' u))) ∧
inr ⁻¹' (inr '' u) = u,
have : inl ⁻¹' (@inr α β '' u) = ∅ :=
eq_empty_iff_forall_not_mem.mpr (assume b ⟨a, _, h⟩, inr_ne_inl h), rw this,
have : inr ⁻¹' (@inr α β '' u) = u :=
preimage_image_eq u (λ _ _, inr.inj_iff.mp), rw this,
exact ⟨⟨is_open_empty, hu⟩, rfl⟩ }
end,
inj := λ _ _, inr.inj_iff.mp }
lemma open_embedding_inl : open_embedding (inl : α → α ⊕ β) :=
{ open_range := begin
rw is_open_sum_iff,
convert and.intro is_open_univ is_open_empty;
{ ext, simp }
end,
.. embedding_inl }
lemma open_embedding_inr : open_embedding (inr : β → α ⊕ β) :=
{ open_range := begin
rw is_open_sum_iff,
convert and.intro is_open_empty is_open_univ;
{ ext, simp }
end,
.. embedding_inr }
end sum
section subtype
variables [topological_space α] [topological_space β] [topological_space γ] {p : α → Prop}
lemma embedding_subtype_coe : embedding (coe : subtype p → α) :=
⟨⟨rfl⟩, subtype.coe_injective⟩
@[continuity] lemma continuous_subtype_val : continuous (@subtype.val α p) :=
continuous_induced_dom
lemma continuous_subtype_coe : continuous (coe : subtype p → α) :=
continuous_subtype_val
lemma is_open.open_embedding_subtype_coe {s : set α} (hs : is_open s) :
open_embedding (coe : s → α) :=
{ induced := rfl,
inj := subtype.coe_injective,
open_range := (subtype.range_coe : range coe = s).symm ▸ hs }
lemma is_open.is_open_map_subtype_coe {s : set α} (hs : is_open s) :
is_open_map (coe : s → α) :=
hs.open_embedding_subtype_coe.is_open_map
lemma is_open_map.restrict {f : α → β} (hf : is_open_map f) {s : set α} (hs : is_open s) :
is_open_map (s.restrict f) :=
hf.comp hs.is_open_map_subtype_coe
lemma is_closed.closed_embedding_subtype_coe {s : set α} (hs : is_closed s) :
closed_embedding (coe : {x // x ∈ s} → α) :=
{ induced := rfl,
inj := subtype.coe_injective,
closed_range := (subtype.range_coe : range coe = s).symm ▸ hs }
@[continuity] lemma continuous_subtype_mk {f : β → α}
(hp : ∀x, p (f x)) (h : continuous f) : continuous (λx, (⟨f x, hp x⟩ : subtype p)) :=
continuous_induced_rng h
lemma continuous_inclusion {s t : set α} (h : s ⊆ t) : continuous (inclusion h) :=
continuous_subtype_mk _ continuous_subtype_coe
lemma continuous_at_subtype_coe {p : α → Prop} {a : subtype p} :
continuous_at (coe : subtype p → α) a :=
continuous_iff_continuous_at.mp continuous_subtype_coe _
lemma map_nhds_subtype_coe_eq {a : α} (ha : p a) (h : {a | p a} ∈ 𝓝 a) :
map (coe : subtype p → α) (𝓝 ⟨a, ha⟩) = 𝓝 a :=
map_nhds_induced_eq $ by simpa only [subtype.coe_mk, subtype.range_coe] using h
lemma nhds_subtype_eq_comap {a : α} {h : p a} :
𝓝 (⟨a, h⟩ : subtype p) = comap coe (𝓝 a) :=
nhds_induced _ _
lemma tendsto_subtype_rng {β : Type*} {p : α → Prop} {b : filter β} {f : β → subtype p} :
∀{a:subtype p}, tendsto f b (𝓝 a) ↔ tendsto (λx, (f x : α)) b (𝓝 (a : α))
| ⟨a, ha⟩ := by rw [nhds_subtype_eq_comap, tendsto_comap_iff, subtype.coe_mk]
lemma continuous_subtype_nhds_cover {ι : Sort*} {f : α → β} {c : ι → α → Prop}
(c_cover : ∀x:α, ∃i, {x | c i x} ∈ 𝓝 x)
(f_cont : ∀i, continuous (λ(x : subtype (c i)), f x)) :
continuous f :=
continuous_iff_continuous_at.mpr $ assume x,
let ⟨i, (c_sets : {x | c i x} ∈ 𝓝 x)⟩ := c_cover x in
let x' : subtype (c i) := ⟨x, mem_of_nhds c_sets⟩ in
calc map f (𝓝 x) = map f (map coe (𝓝 x')) :
congr_arg (map f) (map_nhds_subtype_coe_eq _ $ c_sets).symm
... = map (λx:subtype (c i), f x) (𝓝 x') : rfl
... ≤ 𝓝 (f x) : continuous_iff_continuous_at.mp (f_cont i) x'
lemma continuous_subtype_is_closed_cover {ι : Sort*} {f : α → β} (c : ι → α → Prop)
(h_lf : locally_finite (λi, {x | c i x}))
(h_is_closed : ∀i, is_closed {x | c i x})
(h_cover : ∀x, ∃i, c i x)
(f_cont : ∀i, continuous (λ(x : subtype (c i)), f x)) :
continuous f :=
continuous_iff_is_closed.mpr $
assume s hs,
have ∀i, is_closed ((coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)),
from assume i,
embedding_is_closed embedding_subtype_coe
(by simp [subtype.range_coe]; exact h_is_closed i)
(continuous_iff_is_closed.mp (f_cont i) _ hs),
have is_closed (⋃i, (coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)),
from is_closed_Union_of_locally_finite
(locally_finite_subset h_lf $ assume i x ⟨⟨x', hx'⟩, _, heq⟩, heq ▸ hx')
this,
have f ⁻¹' s = (⋃i, (coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)),
begin
apply set.ext,
have : ∀ (x : α), f x ∈ s ↔ ∃ (i : ι), c i x ∧ f x ∈ s :=
λ x, ⟨λ hx, let ⟨i, hi⟩ := h_cover x in ⟨i, hi, hx⟩,
λ ⟨i, hi, hx⟩, hx⟩,
simpa [and.comm, @and.left_comm (c _ _), ← exists_and_distrib_right],
end,
by rwa [this]
lemma closure_subtype {x : {a // p a}} {s : set {a // p a}}:
x ∈ closure s ↔ (x : α) ∈ closure ((coe : _ → α) '' s) :=
closure_induced $ assume x y, subtype.eq
end subtype
section quotient
variables [topological_space α] [topological_space β] [topological_space γ]
variables {r : α → α → Prop} {s : setoid α}
lemma quotient_map_quot_mk : quotient_map (@quot.mk α r) :=
⟨quot.exists_rep, rfl⟩
@[continuity] lemma continuous_quot_mk : continuous (@quot.mk α r) :=
continuous_coinduced_rng
@[continuity] lemma continuous_quot_lift {f : α → β} (hr : ∀ a b, r a b → f a = f b)
(h : continuous f) : continuous (quot.lift f hr : quot r → β) :=
continuous_coinduced_dom h
lemma quotient_map_quotient_mk : quotient_map (@quotient.mk α s) :=
quotient_map_quot_mk
lemma continuous_quotient_mk : continuous (@quotient.mk α s) :=
continuous_coinduced_rng
lemma continuous_quotient_lift {f : α → β} (hs : ∀ a b, a ≈ b → f a = f b)
(h : continuous f) : continuous (quotient.lift f hs : quotient s → β) :=
continuous_coinduced_dom h
end quotient
section pi
variables {ι : Type*} {π : ι → Type*}
@[continuity]
lemma continuous_pi [topological_space α] [∀i, topological_space (π i)] {f : α → Πi:ι, π i}
(h : ∀i, continuous (λa, f a i)) : continuous f :=
continuous_infi_rng $ assume i, continuous_induced_rng $ h i
@[continuity]
lemma continuous_apply [∀i, topological_space (π i)] (i : ι) :
continuous (λp:Πi, π i, p i) :=
continuous_infi_dom continuous_induced_dom
/-- Embedding a factor into a product space (by fixing arbitrarily all the other coordinates) is
continuous. -/
@[continuity]
lemma continuous_update [decidable_eq ι] [∀i, topological_space (π i)] {i : ι} {f : Πi:ι, π i} :
continuous (λ x : π i, function.update f i x) :=
begin
refine continuous_pi (λj, _),
by_cases h : j = i,
{ rw h,
simpa using continuous_id },
{ simpa [h] using continuous_const }
end
lemma nhds_pi [t : ∀i, topological_space (π i)] {a : Πi, π i} :
𝓝 a = (⨅i, comap (λx, x i) (𝓝 (a i))) :=
calc 𝓝 a = (⨅i, @nhds _ (@topological_space.induced _ _ (λx:Πi, π i, x i) (t i)) a) : nhds_infi
... = (⨅i, comap (λx, x i) (𝓝 (a i))) : by simp [nhds_induced]
lemma tendsto_pi [t : ∀i, topological_space (π i)] {f : α → Πi, π i} {g : Πi, π i} {u : filter α} :
tendsto f u (𝓝 g) ↔ ∀ x, tendsto (λ i, f i x) u (𝓝 (g x)) :=
by simp [nhds_pi, filter.tendsto_comap_iff]
lemma is_open_set_pi [∀a, topological_space (π a)] {i : set ι} {s : Πa, set (π a)}
(hi : finite i) (hs : ∀a∈i, is_open (s a)) : is_open (pi i s) :=
by rw [pi_def]; exact (is_open_bInter hi $ assume a ha, continuous_apply a _ $ hs a ha)
lemma pi_eq_generate_from [∀a, topological_space (π a)] :
Pi.topological_space =
generate_from {g | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, is_open (s a)) ∧ g = pi ↑i s} :=
le_antisymm
(le_generate_from $ assume g ⟨s, i, hi, eq⟩, eq.symm ▸ is_open_set_pi (finset.finite_to_set _) hi)
(le_infi $ assume a s ⟨t, ht, s_eq⟩, generate_open.basic _ $
⟨function.update (λa, univ) a t, {a}, by simpa using ht, by ext f; simp [s_eq.symm, pi]⟩)
lemma pi_generate_from_eq {g : Πa, set (set (π a))} :
@Pi.topological_space ι π (λa, generate_from (g a)) =
generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} :=
let G := {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} in
begin
rw [pi_eq_generate_from],
refine le_antisymm (generate_from_mono _) (le_generate_from _),
exact assume s ⟨t, i, ht, eq⟩, ⟨t, i, assume a ha, generate_open.basic _ (ht a ha), eq⟩,
{ rintros s ⟨t, i, hi, rfl⟩,
rw [pi_def],
apply is_open_bInter (finset.finite_to_set _),
assume a ha, show ((generate_from G).coinduced (λf:Πa, π a, f a)).is_open (t a),
refine le_generate_from _ _ (hi a ha),
exact assume s hs, generate_open.basic _ ⟨function.update (λa, univ) a s, {a}, by simp [hs]⟩ }
end
lemma pi_generate_from_eq_fintype {g : Πa, set (set (π a))} [fintype ι] (hg : ∀a, ⋃₀ g a = univ) :
@Pi.topological_space ι π (λa, generate_from (g a)) =
generate_from {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} :=
let G := {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} in
begin
rw [pi_generate_from_eq],
refine le_antisymm (generate_from_mono _) (le_generate_from _),
exact assume s ⟨t, ht, eq⟩, ⟨t, finset.univ, by simp [ht, eq]⟩,
{ rintros s ⟨t, i, ht, rfl⟩,
apply is_open_iff_forall_mem_open.2 _,
assume f hf,
choose c hc using show ∀a, ∃s, s ∈ g a ∧ f a ∈ s,
{ assume a, have : f a ∈ ⋃₀ g a, { rw [hg], apply mem_univ }, simpa },
refine ⟨pi univ (λa, if a ∈ i then t a else (c : Πa, set (π a)) a), _, _, _⟩,
{ simp [pi_if] },
{ refine generate_open.basic _ ⟨_, assume a, _, rfl⟩,
by_cases a ∈ i; simp [*, pi] at * },
{ have : f ∈ pi {a | a ∉ i} c, { simp [*, pi] at * },
simpa [pi_if, hf] } }
end
end pi
section sigma
variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)]
@[continuity]
lemma continuous_sigma_mk {i : ι} : continuous (@sigma.mk ι σ i) :=
continuous_supr_rng continuous_coinduced_rng
lemma is_open_sigma_iff {s : set (sigma σ)} : is_open s ↔ ∀ i, is_open (sigma.mk i ⁻¹' s) :=
by simp only [is_open_supr_iff, is_open_coinduced]
lemma is_closed_sigma_iff {s : set (sigma σ)} : is_closed s ↔ ∀ i, is_closed (sigma.mk i ⁻¹' s) :=
is_open_sigma_iff
lemma is_open_map_sigma_mk {i : ι} : is_open_map (@sigma.mk ι σ i) :=
begin
intros s hs,
rw is_open_sigma_iff,
intro j,
classical,
by_cases h : i = j,
{ subst j,
convert hs,
exact set.preimage_image_eq _ sigma_mk_injective },
{ convert is_open_empty,
apply set.eq_empty_of_subset_empty,
rintro x ⟨y, _, hy⟩,
have : i = j, by cc,
contradiction }
end
lemma is_open_range_sigma_mk {i : ι} : is_open (set.range (@sigma.mk ι σ i)) :=
by { rw ←set.image_univ, exact is_open_map_sigma_mk _ is_open_univ }
lemma is_closed_map_sigma_mk {i : ι} : is_closed_map (@sigma.mk ι σ i) :=
begin
intros s hs,
rw is_closed_sigma_iff,
intro j,
classical,
by_cases h : i = j,
{ subst j,
convert hs,
exact set.preimage_image_eq _ sigma_mk_injective },
{ convert is_closed_empty,
apply set.eq_empty_of_subset_empty,
rintro x ⟨y, _, hy⟩,
have : i = j, by cc,
contradiction }
end
lemma is_closed_sigma_mk {i : ι} : is_closed (set.range (@sigma.mk ι σ i)) :=
by { rw ←set.image_univ, exact is_closed_map_sigma_mk _ is_closed_univ }
lemma open_embedding_sigma_mk {i : ι} : open_embedding (@sigma.mk ι σ i) :=
open_embedding_of_continuous_injective_open
continuous_sigma_mk sigma_mk_injective is_open_map_sigma_mk
lemma closed_embedding_sigma_mk {i : ι} : closed_embedding (@sigma.mk ι σ i) :=
closed_embedding_of_continuous_injective_closed
continuous_sigma_mk sigma_mk_injective is_closed_map_sigma_mk
lemma embedding_sigma_mk {i : ι} : embedding (@sigma.mk ι σ i) :=
closed_embedding_sigma_mk.1
/-- A map out of a sum type is continuous if its restriction to each summand is. -/
@[continuity]
lemma continuous_sigma [topological_space β] {f : sigma σ → β}
(h : ∀ i, continuous (λ a, f ⟨i, a⟩)) : continuous f :=
continuous_supr_dom (λ i, continuous_coinduced_dom (h i))
@[continuity]
lemma continuous_sigma_map {κ : Type*} {τ : κ → Type*} [Π k, topological_space (τ k)]
{f₁ : ι → κ} {f₂ : Π i, σ i → τ (f₁ i)} (hf : ∀ i, continuous (f₂ i)) :
continuous (sigma.map f₁ f₂) :=
continuous_sigma $ λ i,
show continuous (λ a, sigma.mk (f₁ i) (f₂ i a)),
from continuous_sigma_mk.comp (hf i)
lemma is_open_map_sigma [topological_space β] {f : sigma σ → β}
(h : ∀ i, is_open_map (λ a, f ⟨i, a⟩)) : is_open_map f :=
begin
intros s hs,
rw is_open_sigma_iff at hs,
have : s = ⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s),
{ rw Union_image_preimage_sigma_mk_eq_self },
rw this,
rw [image_Union],
apply is_open_Union,
intro i,
rw [image_image],
exact h i _ (hs i)
end
/-- The sum of embeddings is an embedding. -/
lemma embedding_sigma_map {τ : ι → Type*} [Π i, topological_space (τ i)]
{f : Π i, σ i → τ i} (hf : ∀ i, embedding (f i)) : embedding (sigma.map id f) :=
begin
refine ⟨⟨_⟩, function.injective_id.sigma_map (λ i, (hf i).inj)⟩,
refine le_antisymm
(continuous_iff_le_induced.mp (continuous_sigma_map (λ i, (hf i).continuous))) _,
intros s hs,
replace hs := is_open_sigma_iff.mp hs,
have : ∀ i, ∃ t, is_open t ∧ f i ⁻¹' t = sigma.mk i ⁻¹' s,
{ intro i,
apply is_open_induced_iff.mp,
convert hs i,
exact (hf i).induced.symm },
choose t ht using this,
apply is_open_induced_iff.mpr,
refine ⟨⋃ i, sigma.mk i '' t i, is_open_Union (λ i, is_open_map_sigma_mk _ (ht i).1), _⟩,
ext ⟨i, x⟩,
change (sigma.mk i (f i x) ∈ ⋃ (i : ι), sigma.mk i '' t i) ↔ x ∈ sigma.mk i ⁻¹' s,
rw [←(ht i).2, mem_Union],
split,
{ rintro ⟨j, hj⟩,
rw mem_image at hj,
rcases hj with ⟨y, hy₁, hy₂⟩,
rcases sigma.mk.inj_iff.mp hy₂ with ⟨rfl, hy⟩,
replace hy := eq_of_heq hy,
subst y,
exact hy₁ },
{ intro hx,
use i,
rw mem_image,
exact ⟨f i x, hx, rfl⟩ }
end
end sigma
section ulift
@[continuity] lemma continuous_ulift_down [topological_space α] :
continuous (ulift.down : ulift.{v u} α → α) :=
continuous_induced_dom
@[continuity] lemma continuous_ulift_up [topological_space α] :
continuous (ulift.up : α → ulift.{v u} α) :=
continuous_induced_rng continuous_id
end ulift
lemma mem_closure_of_continuous [topological_space α] [topological_space β]
{f : α → β} {a : α} {s : set α} {t : set β}
(hf : continuous f) (ha : a ∈ closure s) (h : maps_to f s (closure t)) :
f a ∈ closure t :=
calc f a ∈ f '' closure s : mem_image_of_mem _ ha
... ⊆ closure (f '' s) : image_closure_subset_closure_image hf
... ⊆ closure t : closure_minimal h.image_subset is_closed_closure
lemma mem_closure_of_continuous2 [topological_space α] [topological_space β] [topological_space γ]
{f : α → β → γ} {a : α} {b : β} {s : set α} {t : set β} {u : set γ}
(hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t)
(h : ∀a∈s, ∀b∈t, f a b ∈ closure u) :
f a b ∈ closure u :=
have (a,b) ∈ closure (set.prod s t),
by simp [closure_prod_eq, ha, hb],
show f (a, b).1 (a, b).2 ∈ closure u,
from @mem_closure_of_continuous (α×β) _ _ _ (λp:α×β, f p.1 p.2) (a,b) _ u hf this $
assume ⟨p₁, p₂⟩ ⟨h₁, h₂⟩, h p₁ h₁ p₂ h₂
|
f8a7f2fae60db1cf6813cb603242523f4c0619ea | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/simp_match_reducibility_issue.lean | 32c67e8f520d801db16a8a182ae2fb4d912d1821 | [
"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 | 292 | lean | import data.vector namespace test
universes u v
section
open vector
variable α : Type u
variables m n k : ℕ
variable v : vector α m
variable w : vector α n
theorem append_nil : append v nil = v :=
by cases v; simp [vector.append, vector.nil]; reflexivity
end
end test
|
c6be753cb9ced7067348cb186ef0d7cd7de61ea3 | ecdf4e083eb363cd3a0d6880399f86e2cd7f5adb | /src/algebraic_geometry/affine_variety.lean | af119c929e219d70fcbbe5143f7fcbb284bef19d | [] | no_license | fpvandoorn/formalabstracts | 29aa71772da418f18994c38379e2192a6ef361f7 | cea2f9f96d89ee1187d1b01e33f22305cdfe4d59 | refs/heads/master | 1,609,476,761,601 | 1,558,130,287,000 | 1,558,130,287,000 | 97,261,457 | 0 | 2 | null | 1,550,879,230,000 | 1,500,056,313,000 | Lean | UTF-8 | Lean | false | false | 17,536 | lean | import ring_theory.basic
..category_theory.group_object
..category_theory.limits2
tactic.omitted
category_theory.limits.opposites
topology.opens
open category_theory ideal set topological_space
noncomputable theory
universes u v w
-- we set some priorities of instances very low, because they cause problems in this file
local attribute [instance, priority 1] limits.category_theory.limits.has_limit
limits.category_theory.limits.has_colimit limits.category_theory.limits.has_colimits
limits.category_theory.limits.has_limits limits.category_theory.limits.has_limits_of_shape
limits.category_theory.limits.has_colimits_of_shape
def has_coe_ideal {α : Type u} [comm_ring α] : has_coe (ideal α) (set α) := by apply_instance
local attribute [instance] has_coe_ideal
/-- An algebraically closed field is a field where every polynomial with positive degree has a root -/
class algebraically_closed_field (α : Type u) extends discrete_field α :=
(closed : is_algebraically_closed α)
local attribute [instance, priority 0] classical.prop_decidable
/-- A finitely generated reduced algebra -/
class finitely_generated_reduced_algebra (R : Type u) (A : Type v)
[comm_ring R] [comm_ring A] extends algebra R A :=
(finitely_generated : is_finitely_generated R A)
(reduced : is_reduced A)
variables (K : Type u) [discrete_field K]
(R : Type v) [comm_ring R] (S : Type w) [comm_ring S]
[finitely_generated_reduced_algebra K R] [finitely_generated_reduced_algebra K S]
{σ : Type w} [decidable_eq σ]
open finitely_generated_reduced_algebra category_theory tensor_product
namespace algebraic_geometry
/-- The spectrum `Specm(R)` of a `K`-algebra `R` is the set of homomorphisms from `R` to `K`. -/
@[reducible] def spectrum : Type* := R →ₐ[K] K
variables {R K}
/-- The quotient of R by a maximal ideal is isomorphic to K -/
def quotient_maximal_ideal (I : maximal_ideal R) :
{ f : I.val.quotient ≃ K // is_ring_hom f.to_fun } :=
classical.choice omitted
/-- The spectrum of R is equivalent to the set of maximal ideals on R -/
def spectrum_equiv_maximal_ideal : spectrum K R ≃ maximal_ideal R :=
let f : maximal_ideal R → R → K :=
λ I, (quotient_maximal_ideal I).val.to_fun ∘ ideal.quotient.mk I.val in
by { haveI h : ∀ I : maximal_ideal R, is_ring_hom (f I) := omitted,
exact ⟨λ ϕ, ⟨ideal.ker ⇑ϕ, omitted⟩, λ I, ⟨f I, omitted⟩, omitted, omitted⟩ }
variables (K) {R}
/-- `Z(S)` is the set of homomorphisms in `Spec(R)` that vanish on `S`. -/
def Z (S : set R) : set (spectrum K R) := { f | ∀ x ∈ S, f.to_fun x = 0 }
/--`I(X)` consists of all points in `R` that are send to `0` by all `ϕ ∈ X`-/
def I (X : set (spectrum K R)) : set R :=
{ x : R | ∀ϕ : X, ϕ.val x = 0 }
/-- `Z(S)` is equal to `Z` of the radical of the span of `S`. -/
lemma Z_radical_span (S : set R) : Z K ((ideal.span S).radical.carrier) = Z K S :=
omitted
variables (K R)
/-- The Zariski topology is the topology where the closed sets are of the form `Z(S)` for some `S ⊆ R` -/
instance Zariski_topology : topological_space (spectrum K R) :=
⟨set.range (λ S : set R, - Z K S), omitted, omitted, omitted⟩
variables {K R}
/-- A radical ideal gives rise to a closed set in the Zariski topology -/
def closeds_of_radical_ideal (I : radical_ideal R) : closeds (spectrum K R) :=
⟨Z K I.val, mem_range_self I.val⟩
/-- A closed set in the Zariski topology gives rise to a radical ideal -/
def radical_ideal_of_closeds (X : closeds (spectrum K R)) : radical_ideal R :=
⟨⟨ I K X.val, omitted, omitted, omitted⟩, omitted⟩
/-- Hilbert's Nullstellensatz: there is a correspondence between radical ideals in R and
closed sets in the spectrum of R. -/
def Nullstellensatz : radical_ideal R ≃ closeds (spectrum K R) :=
⟨closeds_of_radical_ideal, radical_ideal_of_closeds, omitted, omitted⟩
instance base.finitely_generated_reduced_algebra :
finitely_generated_reduced_algebra K K :=
{ finitely_generated := is_finitely_generated_base K,
reduced := is_reduced_integral_domain,
.._inst_1 }
instance quotient.finitely_generated_reduced_algebra (I : radical_ideal R) :
finitely_generated_reduced_algebra K I.val.quotient :=
{ finitely_generated := is_finitely_generated_quotient (finitely_generated K R) I.val,
reduced := is_reduced_quotient I.2,
..quotient.algebra I.val }
variables (R S)
instance tensor.finitely_generated_reduced_algebra :
finitely_generated_reduced_algebra K (R ⊗[K] S) :=
{ finitely_generated := is_finitely_generated_tensor
(finitely_generated K R) (finitely_generated K S),
reduced := is_reduced_tensor (reduced K R) (reduced K S),
..tensor_product.algebra }
/-- For a closed subset `Z` the quotient `K[X]/I(Z)` is an algebra over `K` -/
example (Z : closeds (spectrum K R)) : algebra K (radical_ideal_of_closeds Z).val.quotient :=
infer_instance
/-- The spectrum of `K[X]/I(Z)` is Z for a closed subset `Z` -/
def spectrum_quotient (Z : closeds (spectrum K R)) :
spectrum K (radical_ideal_of_closeds Z).val.quotient ≃ₜ Z.val :=
{ to_fun := λ x, ⟨x.comp $ algebra.quotient.mk _, omitted⟩,
inv_fun := λ y, algebra.quotient.lift y omitted,
left_inv := omitted,
right_inv := omitted,
continuous_to_fun := omitted,
continuous_inv_fun := omitted }
variables {R S}
/-- The type of finitely generated reduced algebras over a fixed commutative ring. -/
structure FRAlgebra (R : Type u) [comm_ring R] : Type (u+1) :=
(β : Type u)
[ring : comm_ring β]
[algebra : finitely_generated_reduced_algebra R β]
attribute [instance] FRAlgebra.ring FRAlgebra.algebra
instance (R : Type v) [comm_ring R] : has_coe_to_sort (FRAlgebra R) :=
{ S := Type v, coe := FRAlgebra.β }
/-- The category of finitely generated reduced (f.g.r.) algebras over a fixed commutative ring. -/
instance FRAlgebra.category (R : Type u) [comm_ring R] : large_category (FRAlgebra R) :=
{ hom := λ a b, a.β →ₐ[R] b.β,
id := λ a, alg_hom.id R a,
comp := λ a b c f g, alg_hom.comp g f }
/-- Quotients in the category of f.g.r. algebras -/
def FRAlgebra.quotient (R : FRAlgebra K) (Z : closeds (spectrum K R)) : FRAlgebra K :=
⟨K, (radical_ideal_of_closeds Z).val.quotient⟩
/-- The quotient map in the category of f.g.r. algebras -/
def FRAlgebra.quotient_map (R : FRAlgebra K) (Z : closeds (spectrum K R)) :
R ⟶ R.quotient Z :=
algebra.quotient.mk _
/-- The tensor product of two finitely generated reduced algebras over `K` -/
def FRAlgebra_tensor (R S : FRAlgebra K) : FRAlgebra K :=
{ β := R ⊗[K] S,
ring := _,
algebra := tensor.finitely_generated_reduced_algebra R S }
variables (K)
/-- `K` forms a finitely generated reduced algebras over `K` -/
def FRAlgebra_id : FRAlgebra K := ⟨K, K⟩
example (R : FRAlgebra K) : (R ⟶ FRAlgebra_id K) = (R.β →ₐ[K] K) := by refl
example (R : FRAlgebra K) : (R ⟶ FRAlgebra_id K) = spectrum K R.β := rfl
/-- The category of finitely generated reduced algebras over `K` has binary coproducts -/
def FRAlgebra.has_binary_coproducts : limits.has_binary_coproducts (FRAlgebra K) :=
begin
fapply limits.has_binary_coproducts.mk FRAlgebra_tensor,
exact λ X Y, tensor_inl,
exact λ X Y, tensor_inr,
exact λ X Y Z, tensor_lift,
omit_proofs
end
/-- The category of finitely generated reduced algebras over `K` has an initial object -/
def FRAlgebra.has_initial_object : limits.has_initial_object (FRAlgebra K) :=
begin
fapply limits.has_initial_object.mk (FRAlgebra_id K),
intro X, exact algebra.of_id K X,
omitted
end
/-- In algebraic geometry, the categories of algebra's over `K` and affine varieties are opposite of each other. In this development we take a shortcut, and *define* affine varieties as the opposite of algebra's over K. -/
@[reducible] def affine_variety : Type* := opposite (FRAlgebra K)
example : large_category (affine_variety K) := by apply_instance
/-- The category of affine varieties has binary products -/
@[instance, priority 1200] def affine_variety.has_binary_products :
limits.has_binary_products (affine_variety K) :=
by { haveI : limits.has_colimits_of_shape.{u} (discrete limits.two) (FRAlgebra K) :=
FRAlgebra.has_binary_coproducts K, exact limits.has_products_opposite _ }
/-- The category of affine varieties has a terminal object -/
@[instance, priority 1200] def affine_variety.has_terminal_object :
limits.has_terminal_object (affine_variety K) :=
by { haveI : limits.has_colimits_of_shape.{u} (discrete pempty) (FRAlgebra K) :=
FRAlgebra.has_initial_object K, exact limits.has_products_opposite _ }
-- @[instance] lemma affine_variety.complete : limits.has_limits.{u} (affine_variety K) := _
/- The underlying type of an affine variety G = Rᵒᵖ is Spec(R), equivalently the global points
of G in the category of affine varieties. -/
def affine_variety.type_functor : affine_variety K ⥤ Type u :=
yoneda.obj (FRAlgebra_id K)
/- to do: affine_variety.type_functor preserves finite products (is just left-exact) -/
variables {K R}
/-- The object part of the functor `affine_variety.type_functor` -/
def affine_variety.type (X : affine_variety K) : Type u :=
(affine_variety.type_functor K).obj X
/-- The type of `X` is the spectrum of `X` viewed as an object in the opposite category -/
lemma affine_variety.type_eq (X : affine_variety K) :
affine_variety.type X = spectrum K (unop X).β := rfl
/-- We tell Lean that the Zariski topology gives a topology on the type of an affine variety -/
instance (X : affine_variety K) : topological_space X.type :=
algebraic_geometry.Zariski_topology _ _
/-- A subobject of an affine variety given by a closed set on its type -/
def affine_variety.subobject (X : affine_variety K) (Z : closeds X.type) : affine_variety K :=
op ((unop X).quotient Z)
/-- A subobject of an affine variety given by a closed set on its type -/
def affine_variety.incl (X : affine_variety K) (Z : closeds X.type) :
X.subobject Z ⟶ X :=
(FRAlgebra.quotient_map _ _).op
variable (K)
/-- An affine group is a group object in the category of affine varieties -/
def affine_group : Type* := group_object (affine_variety K)
instance : category (affine_group K) := group_object.category
end algebraic_geometry
open algebraic_geometry
variables variables {K} {G G' G₁ G₂ G₃ H : affine_group K}
/-- A morphism between affine groups induces a map between the types -/
def group_hom.type (f : G ⟶ G') : G.obj.type → G'.obj.type :=
(affine_variety.type_functor K).map f.map
namespace algebraic_geometry
-- Given an algebraic group, we get a group structure on its type
section
set_option class.instance_max_depth 80
/-- The multiplication on the type of an affine group -/
def group_type_mul (f g : G.obj.type) : G.obj.type := (tensor_lift f g).comp G.mul.unop
end
/-- The inversion on the type of an affine group -/
def group_type_inv (f : G.obj.type) : G.obj.type := f.comp G.inv.unop
/-- The unit in the type of an affine group -/
def group_type_one : G.obj.type := G.one.unop
/-- Given an algebraic group, we get a group structure on its type -/
instance group_type (G : affine_group K) : group G.obj.type :=
{ mul := group_type_mul,
mul_assoc := omitted,
one := group_type_one,
one_mul := omitted,
mul_one := omitted,
inv := group_type_inv,
mul_left_inv := omitted }
/-- A morphism between affine groups induces a group homomorphism between the types -/
instance (f : G ⟶ G') : is_group_hom f.type := omitted
/-- A closed subgroup of G is a subset of its type that is closed and a subgroup -/
class is_closed_subgroup (s : set G.obj.type) extends is_subgroup s : Prop :=
(closed : is_closed s)
instance is_closed_subgroup_univ (G : affine_group K) :
is_closed_subgroup (univ : set G.obj.type) :=
omitted
def to_closeds (s : set G.obj.type) [is_closed_subgroup s] : closeds G.obj.type :=
⟨s, is_closed_subgroup.closed s⟩
def mul_op (s : set G.obj.type) [is_closed_subgroup s] : (unop G.obj).quotient (to_closeds s) ⟶
FRAlgebra_tensor ((unop G.obj).quotient (to_closeds s)) ((unop G.obj).quotient (to_closeds s)) :=
algebra.quotient.lift
begin
refine alg_hom.comp _ G.mul.unop,
exact tensor_functor (algebra.quotient.mk _) (algebra.quotient.mk _)
end
omitted
/-- From a closed subgroup we can construct an affine group -/
def sub (s : set G.obj.type) [is_closed_subgroup s] : affine_group K :=
{ obj := G.obj.subobject (to_closeds s),
mul := (mul_op s).op,
mul_assoc := omitted,
one := (show (unop G.obj).quotient (to_closeds s) ⟶ FRAlgebra_id K,
from algebra.quotient.lift G.one.unop omitted).op,
one_mul := omitted,
mul_one := omitted,
inv := (show (unop G.obj).quotient (to_closeds s) ⟶ (unop G.obj).quotient (to_closeds s),
from algebra.quotient.functor G.inv.unop omitted).op,
mul_left_inv := omitted }
def affine_group.incl (G : affine_group K) (s : set G.obj.type) [is_closed_subgroup s] :
sub s ⟶ G :=
by exact ⟨affine_variety.incl _ _, omitted⟩
/-- The kernel of a morphism between affine groups is given by the preimage of 1.
More precisely, we can view `f : G ⟶ G'` as a map between the type of `G` and the type of `G'`,
and then take the preimage of `1 : type G'`, using the group structure induced on the type of `G'` -/
def kernel (f : G ⟶ G') : set G.obj.type :=
is_group_hom.ker f.type
/-- The kernel of a morphism is a closed subgroup -/
instance (f : G ⟶ G') : is_closed_subgroup (kernel f) := omitted
/-- A subset of the type of `G` is a normal subgroup if it the kernel of a morphism between
affine groups -/
def is_normal_subgroup (s : set G.obj.type) : Prop :=
∃(G' : affine_group K) (f : G ⟶ G'), kernel f = s
/-- The structure of being a normal subgroup -/
def normal_subgroup_structure (s : set G.obj.type) : Type* :=
Σ(G' : affine_group K), {f : G ⟶ G' // kernel f = s }
/-- An affine group `G` is solvable if it is abelian or inductively if there is a morphism
`ψ : G ⟶ H` such that both `ker(ψ)` and `H` are solvable. -/
-- For some reason this inductive type is very slow to compile if we make this into a `Type`,
-- probably, during the definition of auxilliary declarations. For now, let's have it a Prop,
-- we can turn it into a type later
inductive solvable : affine_group K → Prop
| base {{G : affine_group K}} : G.is_abelian → solvable G
| step {{G H : affine_group K}} (ψ : G ⟶ H) :
solvable H → solvable (sub (kernel ψ)) → solvable G
/-- A Borel subgroup is a maximal closed connected solvable subgroup of `G` -/
def is_Borel_subgroup (s : set G.obj.type) : Prop :=
is_maximal { t : set G.obj.type |
∃(h : is_closed_subgroup t), is_connected t ∧ by exactI solvable (sub t) } s
/-- There is a unique maximal closed subgroup of `G` that is a kernel of a morphism `ψ : G ⟶ A`
for an abelian group `A` -/
theorem closed_derived_subgroup_unique (G : affine_group K) :
∃!(s : set G.obj.type), is_maximal { t : set G.obj.type |
∃(A : affine_group K) (ψ : G ⟶ A), A.is_abelian ∧ t = kernel ψ } s :=
omitted
/-- The closed derived subgroup of `G` is the unique maximal subgroup of `G` that is a kernel of a
morphism `ψ : G ⟶ A` for an abelian group `A` -/
def closed_derived_subgroup (G : affine_group K) : set G.obj.type :=
classical.some (closed_derived_subgroup_unique G)
open category_theory.limits.binary_product
local infix ` × `:60 := limits.binary_product
local infix ` ×.map `:90 := binary_product.map
/-- The conjugation map `H₁ × H₂⟶ G` given by `(h₁,h₂) ↦ h₁*h₂*h₁⁻¹`-/
def conjugation (H₁ H₂ : set G.obj.type) [is_closed_subgroup H₁] [is_closed_subgroup H₂] :
(sub H₁).obj × (sub H₂).obj ⟶ G.obj :=
(((G.incl H₁).map ≫ diag) ×.map (G.incl H₂).map) ≫
product_assoc.hom ≫ (𝟙 G.obj ×.map (product_comm.hom ≫ G.mul)) ≫ G.mul
-- calc
-- H₁ × H₂ ⟶ (G × G) × G : ((G.incl H₁).map ≫ diag) ×.map (G.incl H₂).map
-- ... ⟶ G × (G × G) : product_assoc.hom
-- ... ⟶ G × G : 𝟙 G.obj ×.map (product_comm.hom ≫ G.mul)
-- ... ⟶ G : G.mul
/-- `C` centralizes `H` if `C × H ⟶ G` given by `(c,h) ↦ c*h*c⁻¹` is equal to the inclusion
`H ⟶ G`.
In the notes H is not assumed to be closed, but an arbitrary subgroup.
In that case does `H` represent an affine variety? -/
def centralizes (C H : set G.obj.type) [is_closed_subgroup C] [is_closed_subgroup H] : Prop :=
conjugation C H = π₂ ≫ (G.incl H).map
/-- There is a unique maximal closed subgroup of `G` that centralizes `H` -/
theorem centralizer_unique (H : set G.obj.type) [is_closed_subgroup H] :
∃!(C : set G.obj.type), is_maximal { C' : set G.obj.type |
∃(h : is_closed_subgroup C'), by exactI centralizes C' H } C :=
omitted
/-- The centralizer of `H` is the unique maximal closed subgroup of `G` that centralizes `H` -/
-- typo in notes: G -> H
def centralizer (H : set G.obj.type) [is_closed_subgroup H] : set G.obj.type :=
classical.some (centralizer_unique H)
/-- The center of `G` is the centralizer of `G` as closed subgroup of `G` -/
def center (G : affine_group K) : set G.obj.type :=
centralizer set.univ
/-- `N` normalizes `H` if the conjugation map `N × H ⟶ G` factors through `H` -/
-- this is a slightly different formulation than in the notes
def normalizes (N H : set G.obj.type) [is_closed_subgroup N] [is_closed_subgroup H] : Prop :=
∃(f : (sub N).obj × (sub H).obj ⟶ (sub H).obj), conjugation N H = f ≫ (G.incl H).map
end algebraic_geometry
|
883a9ad52a31427ed6a901c783191783201638e9 | bb31430994044506fa42fd667e2d556327e18dfe | /src/algebra/lie/subalgebra.lean | db9b94416b12079558a23dd6d4d70b41348800a2 | [
"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 | 23,376 | lean | /-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import algebra.lie.basic
import ring_theory.noetherian
/-!
# Lie subalgebras
This file defines Lie subalgebras of a Lie algebra and provides basic related definitions and
results.
## Main definitions
* `lie_subalgebra`
* `lie_subalgebra.incl`
* `lie_subalgebra.map`
* `lie_hom.range`
* `lie_equiv.of_injective`
* `lie_equiv.of_eq`
* `lie_equiv.of_subalgebra`
* `lie_equiv.of_subalgebras`
## Tags
lie algebra, lie subalgebra
-/
universes u v w w₁ w₂
section lie_subalgebra
variables (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L]
/-- A Lie subalgebra of a Lie algebra is submodule that is closed under the Lie bracket.
This is a sufficient condition for the subset itself to form a Lie algebra. -/
structure lie_subalgebra extends submodule R L :=
(lie_mem' : ∀ {x y}, x ∈ carrier → y ∈ carrier → ⁅x, y⁆ ∈ carrier)
attribute [nolint doc_blame] lie_subalgebra.to_submodule
/-- The zero algebra is a subalgebra of any Lie algebra. -/
instance : has_zero (lie_subalgebra R L) :=
⟨{ lie_mem' := λ x y hx hy, by { rw [((submodule.mem_bot R).1 hx), zero_lie],
exact submodule.zero_mem (0 : submodule R L), },
..(0 : submodule R L) }⟩
instance : inhabited (lie_subalgebra R L) := ⟨0⟩
instance : has_coe (lie_subalgebra R L) (submodule R L) := ⟨lie_subalgebra.to_submodule⟩
namespace lie_subalgebra
instance : set_like (lie_subalgebra R L) L :=
{ coe := λ L', L',
coe_injective' := λ L' L'' h, by { rcases L' with ⟨⟨⟩⟩, rcases L'' with ⟨⟨⟩⟩, congr' } }
instance : add_subgroup_class (lie_subalgebra R L) L :=
{ add_mem := λ L' _ _, L'.add_mem',
zero_mem := λ L', L'.zero_mem',
neg_mem := λ L' x hx, show -x ∈ (L' : submodule R L), from neg_mem hx }
/-- A Lie subalgebra forms a new Lie ring. -/
instance (L' : lie_subalgebra R L) : lie_ring L' :=
{ bracket := λ x y, ⟨⁅x.val, y.val⁆, L'.lie_mem' x.property y.property⟩,
lie_add := by { intros, apply set_coe.ext, apply lie_add, },
add_lie := by { intros, apply set_coe.ext, apply add_lie, },
lie_self := by { intros, apply set_coe.ext, apply lie_self, },
leibniz_lie := by { intros, apply set_coe.ext, apply leibniz_lie, } }
section
variables {R₁ : Type*} [semiring R₁]
/-- A Lie subalgebra inherits module structures from `L`. -/
instance [has_smul R₁ R] [module R₁ L] [is_scalar_tower R₁ R L]
(L' : lie_subalgebra R L) : module R₁ L' :=
L'.to_submodule.module'
instance [has_smul R₁ R] [has_smul R₁ᵐᵒᵖ R] [module R₁ L] [module R₁ᵐᵒᵖ L]
[is_scalar_tower R₁ R L] [is_scalar_tower R₁ᵐᵒᵖ R L] [is_central_scalar R₁ L]
(L' : lie_subalgebra R L) : is_central_scalar R₁ L' :=
L'.to_submodule.is_central_scalar
instance [has_smul R₁ R] [module R₁ L] [is_scalar_tower R₁ R L]
(L' : lie_subalgebra R L) : is_scalar_tower R₁ R L' :=
L'.to_submodule.is_scalar_tower
instance (L' : lie_subalgebra R L) [is_noetherian R L] : is_noetherian R L' :=
is_noetherian_submodule' ↑L'
end
/-- A Lie subalgebra forms a new Lie algebra. -/
instance (L' : lie_subalgebra R L) : lie_algebra R L' :=
{ lie_smul := by { intros, apply set_coe.ext, apply lie_smul } }
variables {R L} (L' : lie_subalgebra R L)
@[simp] protected lemma zero_mem : (0 : L) ∈ L' := zero_mem L'
protected lemma add_mem {x y : L} : x ∈ L' → y ∈ L' → (x + y : L) ∈ L' := add_mem
protected lemma sub_mem {x y : L} : x ∈ L' → y ∈ L' → (x - y : L) ∈ L' := sub_mem
lemma smul_mem (t : R) {x : L} (h : x ∈ L') : t • x ∈ L' := (L' : submodule R L).smul_mem t h
lemma lie_mem {x y : L} (hx : x ∈ L') (hy : y ∈ L') : (⁅x, y⁆ : L) ∈ L' := L'.lie_mem' hx hy
@[simp] lemma mem_carrier {x : L} : x ∈ L'.carrier ↔ x ∈ (L' : set L) := iff.rfl
@[simp] lemma mem_mk_iff (S : set L) (h₁ h₂ h₃ h₄) {x : L} :
x ∈ (⟨⟨S, h₁, h₂, h₃⟩, h₄⟩ : lie_subalgebra R L) ↔ x ∈ S :=
iff.rfl
@[simp] lemma mem_coe_submodule {x : L} : x ∈ (L' : submodule R L) ↔ x ∈ L' := iff.rfl
lemma mem_coe {x : L} : x ∈ (L' : set L) ↔ x ∈ L' := iff.rfl
@[simp, norm_cast] lemma coe_bracket (x y : L') : (↑⁅x, y⁆ : L) = ⁅(↑x : L), ↑y⁆ := rfl
lemma ext_iff (x y : L') : x = y ↔ (x : L) = y := subtype.ext_iff
lemma coe_zero_iff_zero (x : L') : (x : L) = 0 ↔ x = 0 := (ext_iff L' x 0).symm
@[ext] lemma ext (L₁' L₂' : lie_subalgebra R L) (h : ∀ x, x ∈ L₁' ↔ x ∈ L₂') :
L₁' = L₂' :=
set_like.ext h
lemma ext_iff' (L₁' L₂' : lie_subalgebra R L) : L₁' = L₂' ↔ ∀ x, x ∈ L₁' ↔ x ∈ L₂' :=
set_like.ext_iff
@[simp] lemma mk_coe (S : set L) (h₁ h₂ h₃ h₄) :
((⟨⟨S, h₁, h₂, h₃⟩, h₄⟩ : lie_subalgebra R L) : set L) = S := rfl
@[simp] lemma coe_to_submodule_mk (p : submodule R L) (h) :
(({lie_mem' := h, ..p} : lie_subalgebra R L) : submodule R L) = p :=
by { cases p, refl, }
lemma coe_injective : function.injective (coe : lie_subalgebra R L → set L) :=
set_like.coe_injective
@[norm_cast] theorem coe_set_eq (L₁' L₂' : lie_subalgebra R L) :
(L₁' : set L) = L₂' ↔ L₁' = L₂' := set_like.coe_set_eq
lemma to_submodule_injective :
function.injective (coe : lie_subalgebra R L → submodule R L) :=
λ L₁' L₂' h, by { rw set_like.ext'_iff at h, rw ← coe_set_eq, exact h, }
@[simp] lemma coe_to_submodule_eq_iff (L₁' L₂' : lie_subalgebra R L) :
(L₁' : submodule R L) = (L₂' : submodule R L) ↔ L₁' = L₂' :=
to_submodule_injective.eq_iff
@[norm_cast]
lemma coe_to_submodule : ((L' : submodule R L) : set L) = L' := rfl
section lie_module
variables {M : Type w} [add_comm_group M] [lie_ring_module L M]
variables {N : Type w₁} [add_comm_group N] [lie_ring_module L N] [module R N] [lie_module R L N]
/-- Given a Lie algebra `L` containing a Lie subalgebra `L' ⊆ L`, together with a Lie ring module
`M` of `L`, we may regard `M` as a Lie ring module of `L'` by restriction. -/
instance : lie_ring_module L' M :=
{ bracket := λ x m, ⁅(x : L), m⁆,
add_lie := λ x y m, add_lie x y m,
lie_add := λ x y m, lie_add x y m,
leibniz_lie := λ x y m, leibniz_lie x y m, }
@[simp] lemma coe_bracket_of_module (x : L') (m : M) : ⁅x, m⁆ = ⁅(x : L), m⁆ := rfl
variables [module R M] [lie_module R L M]
/-- Given a Lie algebra `L` containing a Lie subalgebra `L' ⊆ L`, together with a Lie module `M` of
`L`, we may regard `M` as a Lie module of `L'` by restriction. -/
instance : lie_module R L' M :=
{ smul_lie := λ t x m, by simp only [coe_bracket_of_module, smul_lie, submodule.coe_smul_of_tower],
lie_smul := λ t x m, by simp only [coe_bracket_of_module, lie_smul], }
/-- An `L`-equivariant map of Lie modules `M → N` is `L'`-equivariant for any Lie subalgebra
`L' ⊆ L`. -/
def _root_.lie_module_hom.restrict_lie (f : M →ₗ⁅R,L⁆ N) (L' : lie_subalgebra R L) : M →ₗ⁅R,L'⁆ N :=
{ map_lie' := λ x m, f.map_lie ↑x m,
.. (f : M →ₗ[R] N)}
@[simp] lemma _root_.lie_module_hom.coe_restrict_lie (f : M →ₗ⁅R,L⁆ N) :
⇑(f.restrict_lie L') = f :=
rfl
end lie_module
/-- The embedding of a Lie subalgebra into the ambient space as a morphism of Lie algebras. -/
def incl : L' →ₗ⁅R⁆ L :=
{ map_lie' := λ x y, by { simp only [linear_map.to_fun_eq_coe, submodule.subtype_apply], refl, },
.. (L' : submodule R L).subtype, }
@[simp] lemma coe_incl : ⇑L'.incl = coe := rfl
/-- The embedding of a Lie subalgebra into the ambient space as a morphism of Lie modules. -/
def incl' : L' →ₗ⁅R,L'⁆ L :=
{ map_lie' := λ x y, by simp only [coe_bracket_of_module, linear_map.to_fun_eq_coe,
submodule.subtype_apply, coe_bracket],
.. (L' : submodule R L).subtype, }
@[simp] lemma coe_incl' : ⇑L'.incl' = coe := rfl
end lie_subalgebra
variables {R L} {L₂ : Type w} [lie_ring L₂] [lie_algebra R L₂]
variables (f : L →ₗ⁅R⁆ L₂)
namespace lie_hom
/-- The range of a morphism of Lie algebras is a Lie subalgebra. -/
def range : lie_subalgebra R L₂ :=
{ lie_mem' := λ x y,
show x ∈ f.to_linear_map.range → y ∈ f.to_linear_map.range → ⁅x, y⁆ ∈ f.to_linear_map.range,
by { repeat { rw linear_map.mem_range }, rintros ⟨x', hx⟩ ⟨y', hy⟩, refine ⟨⁅x', y'⁆, _⟩,
rw [←hx, ←hy], change f ⁅x', y'⁆ = ⁅f x', f y'⁆, rw map_lie, },
..(f : L →ₗ[R] L₂).range }
@[simp] lemma range_coe : (f.range : set L₂) = set.range f :=
linear_map.range_coe ↑f
@[simp] lemma mem_range (x : L₂) : x ∈ f.range ↔ ∃ (y : L), f y = x := linear_map.mem_range
lemma mem_range_self (x : L) : f x ∈ f.range := linear_map.mem_range_self f x
/-- We can restrict a morphism to a (surjective) map to its range. -/
def range_restrict : L →ₗ⁅R⁆ f.range :=
{ map_lie' := λ x y, by { apply subtype.ext, exact f.map_lie x y, },
..(f : L →ₗ[R] L₂).range_restrict, }
@[simp] lemma range_restrict_apply (x : L) : f.range_restrict x = ⟨f x, f.mem_range_self x⟩ := rfl
lemma surjective_range_restrict : function.surjective (f.range_restrict) :=
begin
rintros ⟨y, hy⟩,
erw mem_range at hy, obtain ⟨x, rfl⟩ := hy,
use x,
simp only [subtype.mk_eq_mk, range_restrict_apply],
end
/-- A Lie algebra is equivalent to its range under an injective Lie algebra morphism. -/
noncomputable def equiv_range_of_injective (h : function.injective f) : L ≃ₗ⁅R⁆ f.range :=
lie_equiv.of_bijective f.range_restrict ⟨λ x y hxy,
begin
simp only [subtype.mk_eq_mk, range_restrict_apply] at hxy,
exact h hxy,
end, f.surjective_range_restrict⟩
@[simp] lemma equiv_range_of_injective_apply (h : function.injective f) (x : L) :
f.equiv_range_of_injective h x = ⟨f x, mem_range_self f x⟩ :=
rfl
end lie_hom
lemma submodule.exists_lie_subalgebra_coe_eq_iff (p : submodule R L) :
(∃ (K : lie_subalgebra R L), ↑K = p) ↔ ∀ (x y : L), x ∈ p → y ∈ p → ⁅x, y⁆ ∈ p :=
begin
split,
{ rintros ⟨K, rfl⟩ _ _, exact K.lie_mem', },
{ intros h, use { lie_mem' := h, ..p }, exact lie_subalgebra.coe_to_submodule_mk p _, },
end
namespace lie_subalgebra
variables (K K' : lie_subalgebra R L) (K₂ : lie_subalgebra R L₂)
@[simp] lemma incl_range : K.incl.range = K :=
by { rw ← coe_to_submodule_eq_iff, exact (K : submodule R L).range_subtype, }
/-- The image of a Lie subalgebra under a Lie algebra morphism is a Lie subalgebra of the
codomain. -/
def map : lie_subalgebra R L₂ :=
{ lie_mem' := λ x y hx hy, by
{ erw submodule.mem_map at hx, rcases hx with ⟨x', hx', hx⟩, rw ←hx,
erw submodule.mem_map at hy, rcases hy with ⟨y', hy', hy⟩, rw ←hy,
erw submodule.mem_map,
exact ⟨⁅x', y'⁆, K.lie_mem hx' hy', f.map_lie x' y'⟩, },
..((K : submodule R L).map (f : L →ₗ[R] L₂)) }
@[simp] lemma mem_map (x : L₂) : x ∈ K.map f ↔ ∃ (y : L), y ∈ K ∧ f y = x := submodule.mem_map
-- TODO Rename and state for homs instead of equivs.
@[simp] lemma mem_map_submodule (e : L ≃ₗ⁅R⁆ L₂) (x : L₂) :
x ∈ K.map (e : L →ₗ⁅R⁆ L₂) ↔ x ∈ (K : submodule R L).map (e : L →ₗ[R] L₂) :=
iff.rfl
/-- The preimage of a Lie subalgebra under a Lie algebra morphism is a Lie subalgebra of the
domain. -/
def comap : lie_subalgebra R L :=
{ lie_mem' := λ x y hx hy, by
{ suffices : ⁅f x, f y⁆ ∈ K₂, by { simp [this], }, exact K₂.lie_mem hx hy, },
..((K₂ : submodule R L₂).comap (f : L →ₗ[R] L₂)), }
section lattice_structure
open set
instance : partial_order (lie_subalgebra R L) :=
{ le := λ N N', ∀ ⦃x⦄, x ∈ N → x ∈ N', -- Overriding `le` like this gives a better defeq.
..partial_order.lift (coe : lie_subalgebra R L → set L) coe_injective }
lemma le_def : K ≤ K' ↔ (K : set L) ⊆ K' := iff.rfl
@[simp, norm_cast] lemma coe_submodule_le_coe_submodule : (K : submodule R L) ≤ K' ↔ K ≤ K' :=
iff.rfl
instance : has_bot (lie_subalgebra R L) := ⟨0⟩
@[simp] lemma bot_coe : ((⊥ : lie_subalgebra R L) : set L) = {0} := rfl
@[simp] lemma bot_coe_submodule : ((⊥ : lie_subalgebra R L) : submodule R L) = ⊥ := rfl
@[simp] lemma mem_bot (x : L) : x ∈ (⊥ : lie_subalgebra R L) ↔ x = 0 := mem_singleton_iff
instance : has_top (lie_subalgebra R L) :=
⟨{ lie_mem' := λ x y hx hy, mem_univ ⁅x, y⁆,
..(⊤ : submodule R L) }⟩
@[simp] lemma top_coe : ((⊤ : lie_subalgebra R L) : set L) = univ := rfl
@[simp] lemma top_coe_submodule : ((⊤ : lie_subalgebra R L) : submodule R L) = ⊤ := rfl
@[simp] lemma mem_top (x : L) : x ∈ (⊤ : lie_subalgebra R L) := mem_univ x
lemma _root_.lie_hom.range_eq_map : f.range = map f ⊤ :=
by { ext, simp }
instance : has_inf (lie_subalgebra R L) :=
⟨λ K K', { lie_mem' := λ x y hx hy, mem_inter (K.lie_mem hx.1 hy.1) (K'.lie_mem hx.2 hy.2),
..(K ⊓ K' : submodule R L) }⟩
instance : has_Inf (lie_subalgebra R L) :=
⟨λ S, { lie_mem' := λ x y hx hy, by
{ simp only [submodule.mem_carrier, mem_Inter, submodule.Inf_coe, mem_set_of_eq,
forall_apply_eq_imp_iff₂, exists_imp_distrib] at *,
intros K hK, exact K.lie_mem (hx K hK) (hy K hK), },
..Inf {(s : submodule R L) | s ∈ S} }⟩
@[simp] theorem inf_coe : (↑(K ⊓ K') : set L) = K ∩ K' := rfl
@[simp] lemma Inf_coe_to_submodule (S : set (lie_subalgebra R L)) :
(↑(Inf S) : submodule R L) = Inf {(s : submodule R L) | s ∈ S} := rfl
@[simp] lemma Inf_coe (S : set (lie_subalgebra R L)) : (↑(Inf S) : set L) = ⋂ s ∈ S, (s : set L) :=
begin
rw [← coe_to_submodule, Inf_coe_to_submodule, submodule.Inf_coe],
ext x,
simpa only [mem_Inter, mem_set_of_eq, forall_apply_eq_imp_iff₂, exists_imp_distrib],
end
lemma Inf_glb (S : set (lie_subalgebra R L)) : is_glb S (Inf S) :=
begin
have h : ∀ (K K' : lie_subalgebra R L), (K : set L) ≤ K' ↔ K ≤ K', { intros, exact iff.rfl, },
apply is_glb.of_image h,
simp only [Inf_coe],
exact is_glb_binfi
end
/-- The set of Lie subalgebras of a Lie algebra form a complete lattice.
We provide explicit values for the fields `bot`, `top`, `inf` to get more convenient definitions
than we would otherwise obtain from `complete_lattice_of_Inf`. -/
instance : complete_lattice (lie_subalgebra R L) :=
{ bot := ⊥,
bot_le := λ N _ h, by { rw mem_bot at h, rw h, exact N.zero_mem', },
top := ⊤,
le_top := λ _ _ _, trivial,
inf := (⊓),
le_inf := λ N₁ N₂ N₃ h₁₂ h₁₃ m hm, ⟨h₁₂ hm, h₁₃ hm⟩,
inf_le_left := λ _ _ _, and.left,
inf_le_right := λ _ _ _, and.right,
..complete_lattice_of_Inf _ Inf_glb }
instance : add_comm_monoid (lie_subalgebra R L) :=
{ add := (⊔),
add_assoc := λ _ _ _, sup_assoc,
zero := ⊥,
zero_add := λ _, bot_sup_eq,
add_zero := λ _, sup_bot_eq,
add_comm := λ _ _, sup_comm, }
instance : canonically_ordered_add_monoid (lie_subalgebra R L) :=
{ add_le_add_left := λ a b, sup_le_sup_left,
exists_add_of_le := λ a b h, ⟨b, (sup_eq_right.2 h).symm⟩,
le_self_add := λ a b, le_sup_left,
..lie_subalgebra.add_comm_monoid,
..lie_subalgebra.complete_lattice }
@[simp] lemma add_eq_sup : K + K' = K ⊔ K' := rfl
@[norm_cast, simp] lemma inf_coe_to_submodule :
(↑(K ⊓ K') : submodule R L) = (K : submodule R L) ⊓ (K' : submodule R L) := rfl
@[simp] lemma mem_inf (x : L) : x ∈ K ⊓ K' ↔ x ∈ K ∧ x ∈ K' :=
by rw [← mem_coe_submodule, ← mem_coe_submodule, ← mem_coe_submodule, inf_coe_to_submodule,
submodule.mem_inf]
lemma eq_bot_iff : K = ⊥ ↔ ∀ (x : L), x ∈ K → x = 0 :=
by { rw eq_bot_iff, exact iff.rfl, }
instance subsingleton_of_bot : subsingleton (lie_subalgebra R ↥(⊥ : lie_subalgebra R L)) :=
begin
apply subsingleton_of_bot_eq_top,
ext ⟨x, hx⟩, change x ∈ ⊥ at hx, rw lie_subalgebra.mem_bot at hx, subst hx,
simp only [true_iff, eq_self_iff_true, submodule.mk_eq_zero, mem_bot],
end
lemma subsingleton_bot : subsingleton ↥(⊥ : lie_subalgebra R L) :=
show subsingleton ((⊥ : lie_subalgebra R L) : set L), by simp
variables (R L)
lemma well_founded_of_noetherian [is_noetherian R L] :
well_founded ((>) : lie_subalgebra R L → lie_subalgebra R L → Prop) :=
let f : ((>) : lie_subalgebra R L → lie_subalgebra R L → Prop) →r
((>) : submodule R L → submodule R L → Prop) :=
{ to_fun := coe,
map_rel' := λ N N' h, h, }
in rel_hom_class.well_founded f (is_noetherian_iff_well_founded.mp infer_instance)
variables {R L K K' f}
section nested_subalgebras
variables (h : K ≤ K')
/-- Given two nested Lie subalgebras `K ⊆ K'`, the inclusion `K ↪ K'` is a morphism of Lie
algebras. -/
def hom_of_le : K →ₗ⁅R⁆ K' :=
{ map_lie' := λ x y, rfl,
..submodule.of_le h }
@[simp] lemma coe_hom_of_le (x : K) : (hom_of_le h x : L) = x := rfl
lemma hom_of_le_apply (x : K) : hom_of_le h x = ⟨x.1, h x.2⟩ := rfl
lemma hom_of_le_injective : function.injective (hom_of_le h) :=
λ x y, by simp only [hom_of_le_apply, imp_self, subtype.mk_eq_mk, set_like.coe_eq_coe,
subtype.val_eq_coe]
/-- Given two nested Lie subalgebras `K ⊆ K'`, we can view `K` as a Lie subalgebra of `K'`,
regarded as Lie algebra in its own right. -/
def of_le : lie_subalgebra R K' := (hom_of_le h).range
@[simp] lemma mem_of_le (x : K') : x ∈ of_le h ↔ (x : L) ∈ K :=
begin
simp only [of_le, hom_of_le_apply, lie_hom.mem_range],
split,
{ rintros ⟨y, rfl⟩, exact y.property, },
{ intros h, use ⟨(x : L), h⟩, simp, },
end
lemma of_le_eq_comap_incl : of_le h = K.comap K'.incl :=
by { ext, rw mem_of_le, refl, }
@[simp] lemma coe_of_le : (of_le h : submodule R K') = (submodule.of_le h).range := rfl
/-- Given nested Lie subalgebras `K ⊆ K'`, there is a natural equivalence from `K` to its image in
`K'`. -/
noncomputable def equiv_of_le : K ≃ₗ⁅R⁆ of_le h :=
(hom_of_le h).equiv_range_of_injective (hom_of_le_injective h)
@[simp] lemma equiv_of_le_apply (x : K) :
equiv_of_le h x = ⟨hom_of_le h x, (hom_of_le h).mem_range_self x⟩ :=
rfl
end nested_subalgebras
lemma map_le_iff_le_comap {K : lie_subalgebra R L} {K' : lie_subalgebra R L₂} :
map f K ≤ K' ↔ K ≤ comap f K' := set.image_subset_iff
lemma gc_map_comap : galois_connection (map f) (comap f) := λ K K', map_le_iff_le_comap
end lattice_structure
section lie_span
variables (R L) (s : set L)
/-- The Lie subalgebra of a Lie algebra `L` generated by a subset `s ⊆ L`. -/
def lie_span : lie_subalgebra R L := Inf {N | s ⊆ N}
variables {R L s}
lemma mem_lie_span {x : L} : x ∈ lie_span R L s ↔ ∀ K : lie_subalgebra R L, s ⊆ K → x ∈ K :=
by { change x ∈ (lie_span R L s : set L) ↔ _, erw Inf_coe, exact set.mem_Inter₂, }
lemma subset_lie_span : s ⊆ lie_span R L s :=
by { intros m hm, erw mem_lie_span, intros K hK, exact hK hm, }
lemma submodule_span_le_lie_span : submodule.span R s ≤ lie_span R L s :=
by { rw submodule.span_le, apply subset_lie_span, }
lemma lie_span_le {K} : lie_span R L s ≤ K ↔ s ⊆ K :=
begin
split,
{ exact set.subset.trans subset_lie_span, },
{ intros hs m hm, rw mem_lie_span at hm, exact hm _ hs, },
end
lemma lie_span_mono {t : set L} (h : s ⊆ t) : lie_span R L s ≤ lie_span R L t :=
by { rw lie_span_le, exact set.subset.trans h subset_lie_span, }
lemma lie_span_eq : lie_span R L (K : set L) = K :=
le_antisymm (lie_span_le.mpr rfl.subset) subset_lie_span
lemma coe_lie_span_submodule_eq_iff {p : submodule R L} :
(lie_span R L (p : set L) : submodule R L) = p ↔ ∃ (K : lie_subalgebra R L), ↑K = p :=
begin
rw p.exists_lie_subalgebra_coe_eq_iff, split; intros h,
{ intros x m hm, rw [← h, mem_coe_submodule], exact lie_mem _ (subset_lie_span hm), },
{ rw [← coe_to_submodule_mk p h, coe_to_submodule, coe_to_submodule_eq_iff, lie_span_eq], },
end
variables (R L)
/-- `lie_span` forms a Galois insertion with the coercion from `lie_subalgebra` to `set`. -/
protected def gi : galois_insertion (lie_span R L : set L → lie_subalgebra R L) coe :=
{ choice := λ s _, lie_span R L s,
gc := λ s t, lie_span_le,
le_l_u := λ s, subset_lie_span,
choice_eq := λ s h, rfl }
@[simp] lemma span_empty : lie_span R L (∅ : set L) = ⊥ :=
(lie_subalgebra.gi R L).gc.l_bot
@[simp] lemma span_univ : lie_span R L (set.univ : set L) = ⊤ :=
eq_top_iff.2 $ set_like.le_def.2 $ subset_lie_span
variables {L}
lemma span_union (s t : set L) : lie_span R L (s ∪ t) = lie_span R L s ⊔ lie_span R L t :=
(lie_subalgebra.gi R L).gc.l_sup
lemma span_Union {ι} (s : ι → set L) : lie_span R L (⋃ i, s i) = ⨆ i, lie_span R L (s i) :=
(lie_subalgebra.gi R L).gc.l_supr
end lie_span
end lie_subalgebra
end lie_subalgebra
namespace lie_equiv
variables {R : Type u} {L₁ : Type v} {L₂ : Type w}
variables [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂]
/-- An injective Lie algebra morphism is an equivalence onto its range. -/
noncomputable def of_injective (f : L₁ →ₗ⁅R⁆ L₂) (h : function.injective f) :
L₁ ≃ₗ⁅R⁆ f.range :=
{ map_lie' := λ x y, by { apply set_coe.ext, simpa },
.. linear_equiv.of_injective (f : L₁ →ₗ[R] L₂) $ by rwa [lie_hom.coe_to_linear_map] }
@[simp] lemma of_injective_apply (f : L₁ →ₗ⁅R⁆ L₂) (h : function.injective f) (x : L₁) :
↑(of_injective f h x) = f x := rfl
variables (L₁' L₁'' : lie_subalgebra R L₁) (L₂' : lie_subalgebra R L₂)
/-- Lie subalgebras that are equal as sets are equivalent as Lie algebras. -/
def of_eq (h : (L₁' : set L₁) = L₁'') : L₁' ≃ₗ⁅R⁆ L₁'' :=
{ map_lie' := λ x y, by { apply set_coe.ext, simp, },
..(linear_equiv.of_eq ↑L₁' ↑L₁''
(by {ext x, change x ∈ (L₁' : set L₁) ↔ x ∈ (L₁'' : set L₁), rw h, } )) }
@[simp] lemma of_eq_apply (L L' : lie_subalgebra R L₁) (h : (L : set L₁) = L') (x : L) :
(↑(of_eq L L' h x) : L₁) = x := rfl
variables (e : L₁ ≃ₗ⁅R⁆ L₂)
/-- An equivalence of Lie algebras restricts to an equivalence from any Lie subalgebra onto its
image. -/
def lie_subalgebra_map : L₁'' ≃ₗ⁅R⁆ (L₁''.map e : lie_subalgebra R L₂) :=
{ map_lie' := λ x y, by { apply set_coe.ext, exact lie_hom.map_lie (↑e : L₁ →ₗ⁅R⁆ L₂) ↑x ↑y, }
..(linear_equiv.submodule_map (e : L₁ ≃ₗ[R] L₂) ↑L₁'') }
@[simp] lemma lie_subalgebra_map_apply (x : L₁'') : ↑(e.lie_subalgebra_map _ x) = e x := rfl
/-- An equivalence of Lie algebras restricts to an equivalence from any Lie subalgebra onto its
image. -/
def of_subalgebras (h : L₁'.map ↑e = L₂') : L₁' ≃ₗ⁅R⁆ L₂' :=
{ map_lie' := λ x y, by { apply set_coe.ext, exact lie_hom.map_lie (↑e : L₁ →ₗ⁅R⁆ L₂) ↑x ↑y, },
..(linear_equiv.of_submodules (e : L₁ ≃ₗ[R] L₂) ↑L₁' ↑L₂' (by { rw ←h, refl, })) }
@[simp] lemma of_subalgebras_apply (h : L₁'.map ↑e = L₂') (x : L₁') :
↑(e.of_subalgebras _ _ h x) = e x := rfl
@[simp] lemma of_subalgebras_symm_apply (h : L₁'.map ↑e = L₂') (x : L₂') :
↑((e.of_subalgebras _ _ h).symm x) = e.symm x := rfl
end lie_equiv
|
cfa0727425b01c8980dfd9982c9d8223e48510bc | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/PPInstances.lean | c4ffea177705f89342020c5bfe61cd8eeeaac244 | [
"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,527 | lean | class Semiring (α : Type) where add : α → α → α
class Ring (α : Type) where add : α → α → α
class AddCommMonoid (α : Type) where
class AddCommGroup (α : Type) where
class Module (α β : Type) [Semiring α] [AddCommMonoid β] where
class NormedField (α : Type) where
add : α → α → α
add_comm : ∀ (x y : α), @Add.add _ ⟨add⟩ x y = @Add.add _ ⟨add⟩ y x
class SemiNormedGroup (α : Type) where
class SemiNormedSpace (α β : Type) [NormedField α] [SemiNormedGroup β] where
instance SemiNormedGroup.toAddCommMonoid [SemiNormedGroup α] : AddCommMonoid α := {}
instance Ring.toSemiring [instR : Ring α] : Semiring α := { add := instR.add }
instance NormedField.toRing [instNF : NormedField α] : Ring α := { add := instNF.add }
instance SemiNormedSpace.toModule [NormedField α] [SemiNormedGroup β] [SemiNormedSpace α β] : Module α β := {}
opaque R : Type := Unit
opaque foo (a b : R) : R := a
instance R.NormedField : NormedField R := { add := foo, add_comm := sorry }
instance R.Ring : Ring R := { add := foo }
variable {E : Type} [instSNG : SemiNormedGroup E] [instSNS : SemiNormedSpace R E]
set_option pp.all true
set_option pp.instances false in
set_option pp.instanceTypes false in
#check Module R E
set_option pp.instances false in
set_option pp.instanceTypes true in
#check Module R E
set_option pp.instances true in
set_option pp.instanceTypes false in
#check Module R E
set_option pp.instances true in
set_option pp.instanceTypes true in
#check Module R E
|
810f422321abed7f120110035d2b0e435bd9c06a | 618003631150032a5676f229d13a079ac875ff77 | /src/tactic/mk_iff_of_inductive_prop.lean | b81291c65d0c467aa68046c18c4a1e9eaa38cfbc | [
"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 | 8,155 | lean | /-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
Generation function for iff rules for inductives, like for `list.chain`:
∀{α : Type*} (R : α → α → Prop) (a : α) (l : list α),
chain R a l ↔ l = [] ∨ ∃{b : α} {l' : list α}, R a b ∧ chain R b l ∧ l = b :: l'
-/
import tactic.core
namespace tactic
open tactic expr
meta def mk_iff (e₀ : expr) (e₁ : expr) : expr := `(%%e₀ ↔ %%e₁)
meta def select : ℕ → ℕ → tactic unit
| 0 0 := skip
| 0 (n + 1) := left >> skip
| (m + 1) (n + 1) := right >> select m n
| (n + 1) 0 := failure
/-- `compact_relation bs as_ps`: Produce a relation of the form:
R as := ∃ bs, Λ_i a_i = p_i[bs]
This relation is user visible, so we compact it by removing each `b_j` where a `p_i = b_j`, and
hence `a_i = b_j`. We need to take care when there are `p_i` and `p_j` with `p_i = p_j = b_k`.
TODO: this is copied from Lean's `coinductive_predicates.lean`, export it there.
-/
private meta def compact_relation :
list expr → list (expr × expr) → list (option expr) × list (expr × expr)
| [] ps := ([], ps)
| (b :: bs) ps :=
match ps.span (λap:expr × expr, ¬ ap.2 =ₐ b) with
| (_, []) := let (bs, ps) := compact_relation bs ps in (b::bs, ps)
| (ps₁, list.cons (a, _) ps₂) :=
let
i := a.instantiate_local b.local_uniq_name,
(bs, ps) := compact_relation (bs.map i) ((ps₁ ++ ps₂).map (λ⟨a, p⟩, (a, i p)))
in (none :: bs, ps)
end
meta def constr_to_prop (univs : list level) (g : list expr) (idxs : list expr) (c : name) :
tactic ((list (option expr) × (expr ⊕ ℕ)) × expr) := do
e ← get_env,
decl ← get_decl c,
some type' ← return $ decl.instantiate_type_univ_params univs,
type ← drop_pis g type',
(args, res) ← mk_local_pis type,
let idxs_inst := res.get_app_args.drop g.length,
let (bs, eqs) := compact_relation args (idxs.zip idxs_inst),
let bs' := bs.filter_map id,
eqs ← eqs.mmap (λ⟨idx, inst⟩, do
let ty := idx.local_type,
inst_ty ← infer_type inst,
sort u ← infer_type ty,
(is_def_eq ty inst_ty >> return ((const `eq [u] : expr) ty idx inst)) <|>
return ((const `heq [u] : expr) ty idx inst_ty inst)),
(n, r) ← match bs', eqs with
| [], [] := return (sum.inr 0, mk_true)
| _, [] := do
let t : expr := bs'.ilast.local_type,
sort l ← infer_type t,
if l = level.zero then do
r ← mk_exists_lst bs'.init t,
return (sum.inl bs'.ilast, r)
else do
r ← mk_exists_lst bs' mk_true,
return (sum.inr 0, r)
| _, _ := do
r ← mk_exists_lst bs' (mk_and_lst eqs),
return (sum.inr eqs.length, r)
end,
return ((bs, n), r)
private meta def to_cases (s : list $ list (option expr) × (expr ⊕ ℕ)) : tactic unit := do
h ← intro1,
i ← induction h,
focus ((s.zip i).enum.map $ λ⟨p, (shape, t), _, vars, _⟩, do
let si := (shape.zip vars).filter_map (λ⟨c, v⟩, c >>= λ _, some v),
select p (s.length - 1),
match t with
| sum.inl e := do
si.init.mmap' existsi,
some v ← return $ vars.nth (shape.length - 1),
exact v
| sum.inr n := do
si.mmap' existsi,
iterate_exactly (n - 1) (split >> constructor >> skip) >> constructor >> skip
end,
done),
done
private def list_option_merge {α : Type*} {β : Type*} : list (option α) → list β → list (option β)
| [] _ := []
| (none :: xs) ys := none :: list_option_merge xs ys
| (some a :: xs) (y :: ys) := some y :: list_option_merge xs ys
| (some a :: xs) [] := []
private meta def to_inductive
(cs : list name) (gs : list expr) (s : list (list (option expr) × (expr ⊕ ℕ))) (h : expr) :
tactic unit :=
match s.length with
| 0 := induction h >> skip
| (n + 1) := do
r ← elim_gen_sum n h,
focus ((cs.zip (r.zip s)).map $ λ⟨constr_name, h, bs, e⟩, do
let n := (bs.filter_map id).length,
match e with
| sum.inl e := elim_gen_prod (n - 1) h [] [] >> skip
| sum.inr 0 := do
(hs, h, _) ← elim_gen_prod n h [] [],
clear h
| sum.inr (e + 1) := do
(hs, h, _) ← elim_gen_prod n h [] [],
(es, eq, _) ← elim_gen_prod e h [] [],
let es := es ++ [eq],
/- `es.mmap' subst`: fails when we have dependent equalities (heq). `subst will change the
dependent hypotheses, so that the uniq local names in `es` are wrong afterwards. Instead
we revert them and pull them out one by one -/
revert_lst es,
es.mmap' (λ_, intro1 >>= subst)
end,
ctxt ← local_context,
let gs := ctxt.take gs.length,
let hs := (ctxt.reverse.take n).reverse,
let m := gs.map some ++ list_option_merge bs hs,
args ← m.mmap (λa, match a with some v := return v | none := mk_mvar end),
c ← mk_const constr_name,
exact (c.mk_app args),
done),
done
end
/--
`mk_iff_of_inductive_prop i r` makes an iff rule for the inductively defined proposition `i`.
The new rule `r` has the shape `∀ps is, i as ↔ ⋁_j, ∃cs, is = cs`, where `ps` are the type
parameters, `is` are the indices, `j` ranges over all possible constructors, the `cs` are the
parameters for each constructors, the equalities `is = cs` are the instantiations for each
constructor for each of the indices to the inductive type `i`.
In each case, we remove constructor parameters (i.e. `cs`) when the corresponding equality would
be just `c = i` for some index `i`.
For example: `mk_iff_of_inductive_prop` on `list.chain` produces:
```lean
∀ {α : Type*} (R : α → α → Prop) (a : α) (l : list α),
chain R a l ↔ l = [] ∨ ∃{b : α} {l' : list α}, R a b ∧ chain R b l ∧ l = b :: l'
```
-/
meta def mk_iff_of_inductive_prop (i : name) (r : name) : tactic unit := do
e ← get_env,
guard (e.is_inductive i),
let constrs := e.constructors_of i,
let params := e.inductive_num_params i,
let indices := e.inductive_num_indices i,
let rec := match e.recursor_of i with some rec := rec | none := i.append `rec end,
decl ← get_decl i,
let type := decl.type,
let univ_names := decl.univ_params,
let univs := univ_names.map level.param,
/- we use these names for our universe parameters, maybe we should construct a copy of them using uniq_name -/
(g, `(Prop)) ← mk_local_pis type | fail "Inductive type is not a proposition",
let lhs := (const i univs).mk_app g,
shape_rhss ← constrs.mmap (constr_to_prop univs (g.take params) (g.drop params)),
let shape := shape_rhss.map prod.fst,
let rhss := shape_rhss.map prod.snd,
add_theorem_by r univ_names ((mk_iff lhs (mk_or_lst rhss)).pis g) (do
gs ← intro_lst (g.map local_pp_name),
split,
focus' [to_cases shape, intro1 >>= to_inductive constrs (gs.take params) shape]),
skip
end tactic
section
setup_tactic_parser
/--
`mk_iff_of_inductive_prop i r` makes an iff rule for the inductively defined proposition `i`.
The new rule `r` has the shape `∀ps is, i as ↔ ⋁_j, ∃cs, is = cs`, where `ps` are the type
parameters, `is` are the indices, `j` ranges over all possible constructors, the `cs` are the
parameters for each constructors, the equalities `is = cs` are the instantiations for each
constructor for each of the indices to the inductive type `i`.
In each case, we remove constructor parameters (i.e. `cs`) when the corresponding equality would
be just `c = i` for some index `i`.
For example: `mk_iff_of_inductive_prop` on `list.chain` produces:
```lean
∀ {α : Type*} (R : α → α → Prop) (a : α) (l : list α),
chain R a l ↔ l = [] ∨ ∃{b : α} {l' : list α}, R a b ∧ chain R b l ∧ l = b :: l'
```
-/
@[user_command] meta def mk_iff_of_inductive_prop_cmd (_ : parse (tk "mk_iff_of_inductive_prop")) :
parser unit :=
do i ← ident, r ← ident, tactic.mk_iff_of_inductive_prop i r
add_tactic_doc
{ name := "mk_iff_of_inductive_prop",
category := doc_category.cmd,
decl_names := [``mk_iff_of_inductive_prop_cmd],
tags := ["logic", "environment"] }
end
|
e7cc21399ab5c1c480dd9f5e49fc2cc60df58821 | 856e2e1615a12f95b551ed48fa5b03b245abba44 | /src/data/matrix/basic.lean | 77341b243035183737b610f59cf6d9fcc7436140 | [
"Apache-2.0"
] | permissive | pimsp/mathlib | 8b77e1ccfab21703ba8fbe65988c7de7765aa0e5 | 913318ca9d6979686996e8d9b5ebf7e74aae1c63 | refs/heads/master | 1,669,812,465,182 | 1,597,133,610,000 | 1,597,133,610,000 | 281,890,685 | 1 | 0 | null | 1,595,491,577,000 | 1,595,491,576,000 | null | UTF-8 | Lean | false | false | 28,168 | lean | /-
Copyright (c) 2018 Ellen Arlt. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Ellen Arlt, Blair Shi, Sean Leather, Mario Carneiro, Johan Commelin
-/
import algebra.pi_instances
import algebra.big_operators.ring
/-!
# Matrices
-/
universes u v w
open_locale big_operators
@[nolint unused_arguments]
def matrix (m n : Type u) [fintype m] [fintype n] (α : Type v) : Type (max u v) :=
m → n → α
variables {l m n o : Type u} [fintype l] [fintype m] [fintype n] [fintype o]
variables {α : Type v}
namespace matrix
section ext
variables {M N : matrix m n α}
theorem ext_iff : (∀ i j, M i j = N i j) ↔ M = N :=
⟨λ h, funext $ λ i, funext $ h i, λ h, by simp [h]⟩
@[ext] theorem ext : (∀ i j, M i j = N i j) → M = N :=
ext_iff.mp
end ext
/-- Apply a function to each matrix entry. -/
def map (M : matrix m n α) {β : Type w} (f : α → β) : matrix m n β := λ i j, f (M i j)
@[simp]
lemma map_apply {M : matrix m n α} {β : Type w} {f : α → β} {i : m} {j : n} :
M.map f i j = f (M i j) := rfl
def transpose (M : matrix m n α) : matrix n m α
| x y := M y x
localized "postfix `ᵀ`:1500 := matrix.transpose" in matrix
def col (w : m → α) : matrix m punit α
| x y := w x
def row (v : n → α) : matrix punit n α
| x y := v y
instance [inhabited α] : inhabited (matrix m n α) := pi.inhabited _
instance [has_add α] : has_add (matrix m n α) := pi.has_add
instance [add_semigroup α] : add_semigroup (matrix m n α) := pi.add_semigroup
instance [add_comm_semigroup α] : add_comm_semigroup (matrix m n α) := pi.add_comm_semigroup
instance [has_zero α] : has_zero (matrix m n α) := pi.has_zero
instance [add_monoid α] : add_monoid (matrix m n α) := pi.add_monoid
instance [add_comm_monoid α] : add_comm_monoid (matrix m n α) := pi.add_comm_monoid
instance [has_neg α] : has_neg (matrix m n α) := pi.has_neg
instance [add_group α] : add_group (matrix m n α) := pi.add_group
instance [add_comm_group α] : add_comm_group (matrix m n α) := pi.add_comm_group
@[simp] theorem zero_val [has_zero α] (i j) : (0 : matrix m n α) i j = 0 := rfl
@[simp] theorem neg_val [has_neg α] (M : matrix m n α) (i j) : (- M) i j = - M i j := rfl
@[simp] theorem add_val [has_add α] (M N : matrix m n α) (i j) : (M + N) i j = M i j + N i j := rfl
@[simp] lemma map_zero [has_zero α] {β : Type w} [has_zero β] {f : α → β} (h : f 0 = 0) :
(0 : matrix m n α).map f = 0 :=
by { ext, simp [h], }
lemma map_add [add_monoid α] {β : Type w} [add_monoid β] (f : α →+ β)
(M N : matrix m n α) : (M + N).map f = M.map f + N.map f :=
by { ext, simp, }
end matrix
/-- The `add_monoid_hom` between spaces of matrices induced by an `add_monoid_hom` between their
coefficients. -/
def add_monoid_hom.map_matrix [add_monoid α] {β : Type w} [add_monoid β] (f : α →+ β) :
matrix m n α →+ matrix m n β :=
{ to_fun := λ M, M.map f,
map_zero' := by simp,
map_add' := matrix.map_add f, }
@[simp] lemma add_monoid_hom.map_matrix_apply [add_monoid α] {β : Type w} [add_monoid β]
(f : α →+ β) (M : matrix m n α) : f.map_matrix M = M.map f := rfl
open_locale matrix
namespace matrix
section diagonal
variables [decidable_eq n]
/-- `diagonal d` is the square matrix such that `(diagonal d) i i = d i` and `(diagonal d) i j = 0`
if `i ≠ j`. -/
def diagonal [has_zero α] (d : n → α) : matrix n n α := λ i j, if i = j then d i else 0
@[simp] theorem diagonal_val_eq [has_zero α] {d : n → α} (i : n) : (diagonal d) i i = d i :=
by simp [diagonal]
@[simp] theorem diagonal_val_ne [has_zero α] {d : n → α} {i j : n} (h : i ≠ j) :
(diagonal d) i j = 0 := by simp [diagonal, h]
theorem diagonal_val_ne' [has_zero α] {d : n → α} {i j : n} (h : j ≠ i) :
(diagonal d) i j = 0 := diagonal_val_ne h.symm
@[simp] theorem diagonal_zero [has_zero α] : (diagonal (λ _, 0) : matrix n n α) = 0 :=
by simp [diagonal]; refl
@[simp] lemma diagonal_transpose [has_zero α] (v : n → α) :
(diagonal v)ᵀ = diagonal v :=
begin
ext i j,
by_cases h : i = j,
{ simp [h, transpose] },
{ simp [h, transpose, diagonal_val_ne' h] }
end
@[simp] theorem diagonal_add [add_monoid α] (d₁ d₂ : n → α) :
diagonal d₁ + diagonal d₂ = diagonal (λ i, d₁ i + d₂ i) :=
by ext i j; by_cases h : i = j; simp [h]
@[simp] lemma diagonal_map {β : Type w} [has_zero α] [has_zero β]
{f : α → β} (h : f 0 = 0) {d : n → α} :
(diagonal d).map f = diagonal (λ m, f (d m)) :=
by { ext, simp only [diagonal, map_apply], split_ifs; simp [h], }
section one
variables [has_zero α] [has_one α]
instance : has_one (matrix n n α) := ⟨diagonal (λ _, 1)⟩
@[simp] theorem diagonal_one : (diagonal (λ _, 1) : matrix n n α) = 1 := rfl
theorem one_val {i j} : (1 : matrix n n α) i j = if i = j then 1 else 0 := rfl
@[simp] theorem one_val_eq (i) : (1 : matrix n n α) i i = 1 := diagonal_val_eq i
@[simp] theorem one_val_ne {i j} : i ≠ j → (1 : matrix n n α) i j = 0 :=
diagonal_val_ne
theorem one_val_ne' {i j} : j ≠ i → (1 : matrix n n α) i j = 0 :=
diagonal_val_ne'
@[simp] lemma one_map {β : Type w} [has_zero β] [has_one β]
{f : α → β} (h₀ : f 0 = 0) (h₁ : f 1 = 1) :
(1 : matrix n n α).map f = (1 : matrix n n β) :=
by { ext, simp only [one_val, map_apply], split_ifs; simp [h₀, h₁], }
end one
section numeral
@[simp] lemma bit0_val [has_add α] (M : matrix m m α) (i : m) (j : m) :
(bit0 M) i j = bit0 (M i j) := rfl
variables [add_monoid α] [has_one α]
lemma bit1_val (M : matrix n n α) (i : n) (j : n) :
(bit1 M) i j = if i = j then bit1 (M i j) else bit0 (M i j) :=
by dsimp [bit1]; by_cases h : i = j; simp [h]
@[simp]
lemma bit1_val_eq (M : matrix n n α) (i : n) :
(bit1 M) i i = bit1 (M i i) :=
by simp [bit1_val]
@[simp]
lemma bit1_val_ne (M : matrix n n α) {i j : n} (h : i ≠ j) :
(bit1 M) i j = bit0 (M i j) :=
by simp [bit1_val, h]
end numeral
end diagonal
section dot_product
/-- `dot_product v w` is the sum of the entrywise products `v i * w i` -/
def dot_product [has_mul α] [add_comm_monoid α] (v w : m → α) : α :=
∑ i, v i * w i
lemma dot_product_assoc [semiring α] (u : m → α) (v : m → n → α) (w : n → α) :
dot_product (λ j, dot_product u (λ i, v i j)) w = dot_product u (λ i, dot_product (v i) w) :=
by simpa [dot_product, finset.mul_sum, finset.sum_mul, mul_assoc] using finset.sum_comm
lemma dot_product_comm [comm_semiring α] (v w : m → α) :
dot_product v w = dot_product w v :=
by simp_rw [dot_product, mul_comm]
@[simp] lemma dot_product_punit [add_comm_monoid α] [has_mul α] (v w : punit → α) :
dot_product v w = v ⟨⟩ * w ⟨⟩ :=
by simp [dot_product]
@[simp] lemma dot_product_zero [semiring α] (v : m → α) : dot_product v 0 = 0 :=
by simp [dot_product]
@[simp] lemma dot_product_zero' [semiring α] (v : m → α) : dot_product v (λ _, 0) = 0 :=
dot_product_zero v
@[simp] lemma zero_dot_product [semiring α] (v : m → α) : dot_product 0 v = 0 :=
by simp [dot_product]
@[simp] lemma zero_dot_product' [semiring α] (v : m → α) : dot_product (λ _, (0 : α)) v = 0 :=
zero_dot_product v
@[simp] lemma add_dot_product [semiring α] (u v w : m → α) :
dot_product (u + v) w = dot_product u w + dot_product v w :=
by simp [dot_product, add_mul, finset.sum_add_distrib]
@[simp] lemma dot_product_add [semiring α] (u v w : m → α) :
dot_product u (v + w) = dot_product u v + dot_product u w :=
by simp [dot_product, mul_add, finset.sum_add_distrib]
@[simp] lemma diagonal_dot_product [decidable_eq m] [semiring α] (v w : m → α) (i : m) :
dot_product (diagonal v i) w = v i * w i :=
have ∀ j ≠ i, diagonal v i j * w j = 0 := λ j hij, by simp [diagonal_val_ne' hij],
by convert finset.sum_eq_single i (λ j _, this j) _; simp
@[simp] lemma dot_product_diagonal [decidable_eq m] [semiring α] (v w : m → α) (i : m) :
dot_product v (diagonal w i) = v i * w i :=
have ∀ j ≠ i, v j * diagonal w i j = 0 := λ j hij, by simp [diagonal_val_ne' hij],
by convert finset.sum_eq_single i (λ j _, this j) _; simp
@[simp] lemma dot_product_diagonal' [decidable_eq m] [semiring α] (v w : m → α) (i : m) :
dot_product v (λ j, diagonal w j i) = v i * w i :=
have ∀ j ≠ i, v j * diagonal w j i = 0 := λ j hij, by simp [diagonal_val_ne hij],
by convert finset.sum_eq_single i (λ j _, this j) _; simp
@[simp] lemma neg_dot_product [ring α] (v w : m → α) : dot_product (-v) w = - dot_product v w :=
by simp [dot_product]
@[simp] lemma dot_product_neg [ring α] (v w : m → α) : dot_product v (-w) = - dot_product v w :=
by simp [dot_product]
@[simp] lemma smul_dot_product [semiring α] (x : α) (v w : m → α) :
dot_product (x • v) w = x * dot_product v w :=
by simp [dot_product, finset.mul_sum, mul_assoc]
@[simp] lemma dot_product_smul [comm_semiring α] (x : α) (v w : m → α) :
dot_product v (x • w) = x * dot_product v w :=
by simp [dot_product, finset.mul_sum, mul_assoc, mul_comm, mul_left_comm]
end dot_product
protected def mul [has_mul α] [add_comm_monoid α] (M : matrix l m α) (N : matrix m n α) :
matrix l n α :=
λ i k, dot_product (λ j, M i j) (λ j, N j k)
localized "infixl ` ⬝ `:75 := matrix.mul" in matrix
theorem mul_val [has_mul α] [add_comm_monoid α] {M : matrix l m α} {N : matrix m n α} {i k} :
(M ⬝ N) i k = ∑ j, M i j * N j k := rfl
instance [has_mul α] [add_comm_monoid α] : has_mul (matrix n n α) := ⟨matrix.mul⟩
@[simp] theorem mul_eq_mul [has_mul α] [add_comm_monoid α] (M N : matrix n n α) :
M * N = M ⬝ N := rfl
theorem mul_val' [has_mul α] [add_comm_monoid α] {M N : matrix n n α} {i k} :
(M ⬝ N) i k = dot_product (λ j, M i j) (λ j, N j k) := rfl
section semigroup
variables [semiring α]
protected theorem mul_assoc (L : matrix l m α) (M : matrix m n α) (N : matrix n o α) :
(L ⬝ M) ⬝ N = L ⬝ (M ⬝ N) :=
by { ext, apply dot_product_assoc }
instance : semigroup (matrix n n α) :=
{ mul_assoc := matrix.mul_assoc, ..matrix.has_mul }
end semigroup
@[simp] theorem diagonal_neg [decidable_eq n] [add_group α] (d : n → α) :
-diagonal d = diagonal (λ i, -d i) :=
by ext i j; by_cases i = j; simp [h]
section semiring
variables [semiring α]
@[simp] protected theorem mul_zero (M : matrix m n α) : M ⬝ (0 : matrix n o α) = 0 :=
by { ext i j, apply dot_product_zero }
@[simp] protected theorem zero_mul (M : matrix m n α) : (0 : matrix l m α) ⬝ M = 0 :=
by { ext i j, apply zero_dot_product }
protected theorem mul_add (L : matrix m n α) (M N : matrix n o α) : L ⬝ (M + N) = L ⬝ M + L ⬝ N :=
by { ext i j, apply dot_product_add }
protected theorem add_mul (L M : matrix l m α) (N : matrix m n α) : (L + M) ⬝ N = L ⬝ N + M ⬝ N :=
by { ext i j, apply add_dot_product }
@[simp] theorem diagonal_mul [decidable_eq m]
(d : m → α) (M : matrix m n α) (i j) : (diagonal d).mul M i j = d i * M i j :=
diagonal_dot_product _ _ _
@[simp] theorem mul_diagonal [decidable_eq n]
(d : n → α) (M : matrix m n α) (i j) : (M ⬝ diagonal d) i j = M i j * d j :=
by { rw ← diagonal_transpose, apply dot_product_diagonal }
@[simp] protected theorem one_mul [decidable_eq m] (M : matrix m n α) : (1 : matrix m m α) ⬝ M = M :=
by ext i j; rw [← diagonal_one, diagonal_mul, one_mul]
@[simp] protected theorem mul_one [decidable_eq n] (M : matrix m n α) : M ⬝ (1 : matrix n n α) = M :=
by ext i j; rw [← diagonal_one, mul_diagonal, mul_one]
instance [decidable_eq n] : monoid (matrix n n α) :=
{ one_mul := matrix.one_mul,
mul_one := matrix.mul_one,
..matrix.has_one, ..matrix.semigroup }
instance [decidable_eq n] : semiring (matrix n n α) :=
{ mul_zero := matrix.mul_zero,
zero_mul := matrix.zero_mul,
left_distrib := matrix.mul_add,
right_distrib := matrix.add_mul,
..matrix.add_comm_monoid,
..matrix.monoid }
@[simp] theorem diagonal_mul_diagonal [decidable_eq n] (d₁ d₂ : n → α) :
(diagonal d₁) ⬝ (diagonal d₂) = diagonal (λ i, d₁ i * d₂ i) :=
by ext i j; by_cases i = j; simp [h]
theorem diagonal_mul_diagonal' [decidable_eq n] (d₁ d₂ : n → α) :
diagonal d₁ * diagonal d₂ = diagonal (λ i, d₁ i * d₂ i) :=
diagonal_mul_diagonal _ _
lemma map_mul {L : matrix m n α} {M : matrix n o α}
{β : Type w} [semiring β] {f : α →+* β} :
(L ⬝ M).map f = L.map f ⬝ M.map f :=
by { ext, simp [mul_val, ring_hom.map_sum], }
lemma is_add_monoid_hom_mul_left (M : matrix l m α) :
is_add_monoid_hom (λ x : matrix m n α, M ⬝ x) :=
{ to_is_add_hom := ⟨matrix.mul_add _⟩, map_zero := matrix.mul_zero _ }
lemma is_add_monoid_hom_mul_right (M : matrix m n α) :
is_add_monoid_hom (λ x : matrix l m α, x ⬝ M) :=
{ to_is_add_hom := ⟨λ _ _, matrix.add_mul _ _ _⟩, map_zero := matrix.zero_mul _ }
protected lemma sum_mul {β : Type*} (s : finset β) (f : β → matrix l m α)
(M : matrix m n α) : (∑ a in s, f a) ⬝ M = ∑ a in s, f a ⬝ M :=
(@finset.sum_hom _ _ _ _ _ s f (λ x, x ⬝ M)
/- This line does not type-check without `id` and `: _`. Lean did not recognize that two different
`add_monoid` instances were def-eq -/
(id (@is_add_monoid_hom_mul_right l _ _ _ _ _ _ _ M) : _)).symm
protected lemma mul_sum {β : Type*} (s : finset β) (f : β → matrix m n α)
(M : matrix l m α) : M ⬝ ∑ a in s, f a = ∑ a in s, M ⬝ f a :=
(@finset.sum_hom _ _ _ _ _ s f (λ x, M ⬝ x)
/- This line does not type-check without `id` and `: _`. Lean did not recognize that two different
`add_monoid` instances were def-eq -/
(id (@is_add_monoid_hom_mul_left _ _ n _ _ _ _ _ M) : _)).symm
@[simp]
lemma row_mul_col_val (v w : m → α) (i j) : (row v ⬝ col w) i j = dot_product v w :=
rfl
end semiring
end matrix
/-- The `ring_hom` between spaces of square matrices induced by a `ring_hom` between their
coefficients. -/
def ring_hom.map_matrix [decidable_eq m] [semiring α] {β : Type w} [semiring β] (f : α →+* β) :
matrix m m α →+* matrix m m β :=
{ to_fun := λ M, M.map f,
map_one' := by simp,
map_mul' := λ L M, matrix.map_mul,
..(f.to_add_monoid_hom).map_matrix }
@[simp] lemma ring_hom.map_matrix_apply [decidable_eq m] [semiring α] {β : Type w} [semiring β]
(f : α →+* β) (M : matrix m m α) : f.map_matrix M = M.map f := rfl
open_locale matrix
namespace matrix
section ring
variables [ring α]
@[simp] theorem neg_mul (M : matrix m n α) (N : matrix n o α) :
(-M) ⬝ N = -(M ⬝ N) :=
by { ext, apply neg_dot_product }
@[simp] theorem mul_neg (M : matrix m n α) (N : matrix n o α) :
M ⬝ (-N) = -(M ⬝ N) :=
by { ext, apply dot_product_neg }
end ring
instance [decidable_eq n] [ring α] : ring (matrix n n α) :=
{ ..matrix.semiring, ..matrix.add_comm_group }
instance [semiring α] : has_scalar α (matrix m n α) := pi.has_scalar
instance {β : Type w} [semiring α] [add_comm_monoid β] [semimodule α β] :
semimodule α (matrix m n β) := pi.semimodule _ _ _
@[simp] lemma smul_val [semiring α] (a : α) (A : matrix m n α) (i : m) (j : n) : (a • A) i j = a * A i j := rfl
section semiring
variables [semiring α]
lemma smul_eq_diagonal_mul [decidable_eq m] (M : matrix m n α) (a : α) :
a • M = diagonal (λ _, a) ⬝ M :=
by { ext, simp }
@[simp] lemma smul_mul (M : matrix m n α) (a : α) (N : matrix n l α) : (a • M) ⬝ N = a • M ⬝ N :=
by { ext, apply smul_dot_product }
@[simp] lemma mul_mul_left (M : matrix m n α) (N : matrix n o α) (a : α) :
(λ i j, a * M i j) ⬝ N = a • (M ⬝ N) :=
begin
simp only [←smul_val],
simp,
end
/--
The ring homomorphism `α →+* matrix n n α`
sending `a` to the diagonal matrix with `a` on the diagonal.
-/
def scalar (n : Type u) [fintype n] [decidable_eq n] : α →+* matrix n n α :=
{ to_fun := λ a, a • 1,
map_zero' := by simp,
map_add' := by { intros, ext, simp [add_mul], },
map_one' := by simp,
map_mul' := by { intros, ext, simp [mul_assoc], }, }
section scalar
variable [decidable_eq n]
@[simp] lemma coe_scalar : (scalar n : α → matrix n n α) = λ a, a • 1 := rfl
lemma scalar_apply_eq (a : α) (i : n) :
scalar n a i i = a :=
by simp only [coe_scalar, mul_one, one_val_eq, smul_val]
lemma scalar_apply_ne (a : α) (i j : n) (h : i ≠ j) :
scalar n a i j = 0 :=
by simp only [h, coe_scalar, one_val_ne, ne.def, not_false_iff, smul_val, mul_zero]
end scalar
end semiring
section comm_semiring
variables [comm_semiring α]
lemma smul_eq_mul_diagonal [decidable_eq n] (M : matrix m n α) (a : α) :
a • M = M ⬝ diagonal (λ _, a) :=
by { ext, simp [mul_comm] }
@[simp] lemma mul_smul (M : matrix m n α) (a : α) (N : matrix n l α) : M ⬝ (a • N) = a • M ⬝ N :=
by { ext, apply dot_product_smul }
@[simp] lemma mul_mul_right (M : matrix m n α) (N : matrix n o α) (a : α) :
M ⬝ (λ i j, a * N i j) = a • (M ⬝ N) :=
begin
simp only [←smul_val],
simp,
end
end comm_semiring
section semiring
variables [semiring α]
def vec_mul_vec (w : m → α) (v : n → α) : matrix m n α
| x y := w x * v y
def mul_vec (M : matrix m n α) (v : n → α) : m → α
| i := dot_product (λ j, M i j) v
def vec_mul (v : m → α) (M : matrix m n α) : n → α
| j := dot_product v (λ i, M i j)
instance mul_vec.is_add_monoid_hom_left (v : n → α) :
is_add_monoid_hom (λM:matrix m n α, mul_vec M v) :=
{ map_zero := by ext; simp [mul_vec]; refl,
map_add :=
begin
intros x y,
ext m,
apply add_dot_product
end }
lemma mul_vec_diagonal [decidable_eq m] (v w : m → α) (x : m) :
mul_vec (diagonal v) w x = v x * w x :=
diagonal_dot_product v w x
lemma vec_mul_diagonal [decidable_eq m] (v w : m → α) (x : m) :
vec_mul v (diagonal w) x = v x * w x :=
dot_product_diagonal' v w x
@[simp] lemma mul_vec_one [decidable_eq m] (v : m → α) : mul_vec 1 v = v :=
by { ext, rw [←diagonal_one, mul_vec_diagonal, one_mul] }
@[simp] lemma vec_mul_one [decidable_eq m] (v : m → α) : vec_mul v 1 = v :=
by { ext, rw [←diagonal_one, vec_mul_diagonal, mul_one] }
@[simp] lemma mul_vec_zero (A : matrix m n α) : mul_vec A 0 = 0 :=
by { ext, simp [mul_vec] }
@[simp] lemma vec_mul_zero (A : matrix m n α) : vec_mul 0 A = 0 :=
by { ext, simp [vec_mul] }
@[simp] lemma vec_mul_vec_mul (v : m → α) (M : matrix m n α) (N : matrix n o α) :
vec_mul (vec_mul v M) N = vec_mul v (M ⬝ N) :=
by { ext, apply dot_product_assoc }
@[simp] lemma mul_vec_mul_vec (v : o → α) (M : matrix m n α) (N : matrix n o α) :
mul_vec M (mul_vec N v) = mul_vec (M ⬝ N) v :=
by { ext, symmetry, apply dot_product_assoc }
lemma vec_mul_vec_eq (w : m → α) (v : n → α) :
vec_mul_vec w v = (col w) ⬝ (row v) :=
by { ext i j, simp [vec_mul_vec, mul_val], refl }
variables [decidable_eq m] [decidable_eq n]
/--
`std_basis_matrix i j a` is the matrix with `a` in the `i`-th row, `j`-th column,
and zeroes elsewhere.
-/
def std_basis_matrix (i : m) (j : n) (a : α) : matrix m n α :=
(λ i' j', if i' = i ∧ j' = j then a else 0)
@[simp] lemma smul_std_basis_matrix (i : m) (j : n) (a b : α) :
b • std_basis_matrix i j a = std_basis_matrix i j (b • a) :=
by { unfold std_basis_matrix, ext, dsimp, simp }
@[simp] lemma std_basis_matrix_zero (i : m) (j : n) :
std_basis_matrix i j (0 : α) = 0 :=
by { unfold std_basis_matrix, ext, simp }
lemma std_basis_matrix_add (i : m) (j : n) (a b : α) :
std_basis_matrix i j (a + b) = std_basis_matrix i j a + std_basis_matrix i j b :=
begin
unfold std_basis_matrix, ext,
split_ifs with h; simp [h],
end
lemma matrix_eq_sum_std_basis (x : matrix n m α) :
x = ∑ (i : n) (j : m), std_basis_matrix i j (x i j) :=
begin
ext, iterate 2 {rw finset.sum_apply},
rw ← finset.sum_subset, swap 4, exact {i},
{ norm_num [std_basis_matrix] },
{ simp },
intros, norm_num at a, norm_num,
convert finset.sum_const_zero,
ext, norm_num [std_basis_matrix],
rw if_neg, tauto!,
end
-- TODO: tie this up with the `basis` machinery of linear algebra
-- this is not completely trivial because we are indexing by two types, instead of one
-- TODO: add `std_basis_vec`
lemma std_basis_eq_basis_mul_basis (i : m) (j : n) :
std_basis_matrix i j 1 = vec_mul_vec (λ i', ite (i = i') 1 0) (λ j', ite (j = j') 1 0) :=
begin
ext, norm_num [std_basis_matrix, vec_mul_vec],
split_ifs; tauto,
end
@[elab_as_eliminator] protected lemma induction_on'
{X : Type*} [semiring X] {M : matrix n n X → Prop} (m : matrix n n X)
(h_zero : M 0)
(h_add : ∀p q, M p → M q → M (p + q))
(h_std_basis : ∀ i j x, M (std_basis_matrix i j x)) :
M m :=
begin
rw [matrix_eq_sum_std_basis m, ← finset.sum_product'],
apply finset.sum_induction _ _ h_add h_zero,
{ intros, apply h_std_basis, }
end
@[elab_as_eliminator] protected lemma induction_on
[nonempty n] {X : Type*} [semiring X] {M : matrix n n X → Prop} (m : matrix n n X)
(h_add : ∀p q, M p → M q → M (p + q))
(h_std_basis : ∀ i j x, M (std_basis_matrix i j x)) :
M m :=
matrix.induction_on' m
begin
have i : n := classical.choice (by assumption),
simpa using h_std_basis i i 0,
end
h_add h_std_basis
end semiring
section ring
variables [ring α]
lemma neg_vec_mul (v : m → α) (A : matrix m n α) : vec_mul (-v) A = - vec_mul v A :=
by { ext, apply neg_dot_product }
lemma vec_mul_neg (v : m → α) (A : matrix m n α) : vec_mul v (-A) = - vec_mul v A :=
by { ext, apply dot_product_neg }
lemma neg_mul_vec (v : n → α) (A : matrix m n α) : mul_vec (-A) v = - mul_vec A v :=
by { ext, apply neg_dot_product }
lemma mul_vec_neg (v : n → α) (A : matrix m n α) : mul_vec A (-v) = - mul_vec A v :=
by { ext, apply dot_product_neg }
end ring
section transpose
open_locale matrix
/--
Tell `simp` what the entries are in a transposed matrix.
Compare with `mul_val`, `diagonal_val_eq`, etc.
-/
@[simp] lemma transpose_val (M : matrix m n α) (i j) : M.transpose j i = M i j := rfl
@[simp] lemma transpose_transpose (M : matrix m n α) :
Mᵀᵀ = M :=
by ext; refl
@[simp] lemma transpose_zero [has_zero α] : (0 : matrix m n α)ᵀ = 0 :=
by ext i j; refl
@[simp] lemma transpose_one [decidable_eq n] [has_zero α] [has_one α] : (1 : matrix n n α)ᵀ = 1 :=
begin
ext i j,
unfold has_one.one transpose,
by_cases i = j,
{ simp only [h, diagonal_val_eq] },
{ simp only [diagonal_val_ne h, diagonal_val_ne (λ p, h (symm p))] }
end
@[simp] lemma transpose_add [has_add α] (M : matrix m n α) (N : matrix m n α) :
(M + N)ᵀ = Mᵀ + Nᵀ :=
by { ext i j, simp }
@[simp] lemma transpose_sub [add_group α] (M : matrix m n α) (N : matrix m n α) :
(M - N)ᵀ = Mᵀ - Nᵀ :=
by { ext i j, simp }
@[simp] lemma transpose_mul [comm_semiring α] (M : matrix m n α) (N : matrix n l α) :
(M ⬝ N)ᵀ = Nᵀ ⬝ Mᵀ :=
begin
ext i j,
apply dot_product_comm
end
@[simp] lemma transpose_smul [semiring α] (c : α) (M : matrix m n α) :
(c • M)ᵀ = c • Mᵀ :=
by { ext i j, refl }
@[simp] lemma transpose_neg [has_neg α] (M : matrix m n α) :
(- M)ᵀ = - Mᵀ :=
by ext i j; refl
lemma transpose_map {β : Type w} {f : α → β} {M : matrix m n α} : Mᵀ.map f = (M.map f)ᵀ :=
by { ext, refl }
end transpose
def minor (A : matrix m n α) (row : l → m) (col : o → n) : matrix l o α :=
λ i j, A (row i) (col j)
@[reducible]
def sub_left {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin l) α :=
minor A id (fin.cast_add r)
@[reducible]
def sub_right {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin r) α :=
minor A id (fin.nat_add l)
@[reducible]
def sub_up {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin u) (fin n) α :=
minor A (fin.cast_add d) id
@[reducible]
def sub_down {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin d) (fin n) α :=
minor A (fin.nat_add u) id
@[reducible]
def sub_up_right {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) :
matrix (fin u) (fin r) α :=
sub_up (sub_right A)
@[reducible]
def sub_down_right {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) :
matrix (fin d) (fin r) α :=
sub_down (sub_right A)
@[reducible]
def sub_up_left {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) :
matrix (fin u) (fin (l)) α :=
sub_up (sub_left A)
@[reducible]
def sub_down_left {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) :
matrix (fin d) (fin (l)) α :=
sub_down (sub_left A)
section row_col
/-!
### `row_col` section
Simplification lemmas for `matrix.row` and `matrix.col`.
-/
open_locale matrix
@[simp] lemma col_add [semiring α] (v w : m → α) : col (v + w) = col v + col w := by { ext, refl }
@[simp] lemma col_smul [semiring α] (x : α) (v : m → α) : col (x • v) = x • col v := by { ext, refl }
@[simp] lemma row_add [semiring α] (v w : m → α) : row (v + w) = row v + row w := by { ext, refl }
@[simp] lemma row_smul [semiring α] (x : α) (v : m → α) : row (x • v) = x • row v := by { ext, refl }
@[simp] lemma col_val (v : m → α) (i j) : matrix.col v i j = v i := rfl
@[simp] lemma row_val (v : m → α) (i j) : matrix.row v i j = v j := rfl
@[simp]
lemma transpose_col (v : m → α) : (matrix.col v).transpose = matrix.row v := by {ext, refl}
@[simp]
lemma transpose_row (v : m → α) : (matrix.row v).transpose = matrix.col v := by {ext, refl}
lemma row_vec_mul [semiring α] (M : matrix m n α) (v : m → α) :
matrix.row (matrix.vec_mul v M) = matrix.row v ⬝ M := by {ext, refl}
lemma col_vec_mul [semiring α] (M : matrix m n α) (v : m → α) :
matrix.col (matrix.vec_mul v M) = (matrix.row v ⬝ M)ᵀ := by {ext, refl}
lemma col_mul_vec [semiring α] (M : matrix m n α) (v : n → α) :
matrix.col (matrix.mul_vec M v) = M ⬝ matrix.col v := by {ext, refl}
lemma row_mul_vec [semiring α] (M : matrix m n α) (v : n → α) :
matrix.row (matrix.mul_vec M v) = (M ⬝ matrix.col v)ᵀ := by {ext, refl}
end row_col
section update
/-- Update, i.e. replace the `i`th row of matrix `A` with the values in `b`. -/
def update_row [decidable_eq n] (M : matrix n m α) (i : n) (b : m → α) : matrix n m α :=
function.update M i b
/-- Update, i.e. replace the `i`th column of matrix `A` with the values in `b`. -/
def update_column [decidable_eq m] (M : matrix n m α) (j : m) (b : n → α) : matrix n m α :=
λ i, function.update (M i) j (b i)
variables {M : matrix n m α} {i : n} {j : m} {b : m → α} {c : n → α}
@[simp] lemma update_row_self [decidable_eq n] : update_row M i b i = b :=
function.update_same i b M
@[simp] lemma update_column_self [decidable_eq m] : update_column M j c i j = c i :=
function.update_same j (c i) (M i)
@[simp] lemma update_row_ne [decidable_eq n] {i' : n} (i_ne : i' ≠ i) :
update_row M i b i' = M i' := function.update_noteq i_ne b M
@[simp] lemma update_column_ne [decidable_eq m] {j' : m} (j_ne : j' ≠ j) :
update_column M j c i j' = M i j' := function.update_noteq j_ne (c i) (M i)
lemma update_row_val [decidable_eq n] {i' : n} :
update_row M i b i' j = if i' = i then b j else M i' j :=
begin
by_cases i' = i,
{ rw [h, update_row_self, if_pos rfl] },
{ rwa [update_row_ne h, if_neg h] }
end
lemma update_column_val [decidable_eq m] {j' : m} : update_column M j c i j' = if j' = j then c i else M i j' :=
begin
by_cases j' = j,
{ rw [h, update_column_self, if_pos rfl] },
{ rwa [update_column_ne h, if_neg h] }
end
lemma update_row_transpose [decidable_eq m] : update_row Mᵀ j c = (update_column M j c)ᵀ :=
begin
ext i' j,
rw [transpose_val, update_row_val, update_column_val],
refl
end
lemma update_column_transpose [decidable_eq n] : update_column Mᵀ i b = (update_row M i b)ᵀ :=
begin
ext i' j,
rw [transpose_val, update_row_val, update_column_val],
refl
end
end update
end matrix
namespace ring_hom
variables {β : Type*} [semiring α] [semiring β]
lemma map_matrix_mul (M : matrix m n α) (N : matrix n o α) (i : m) (j : o) (f : α →+* β) :
f (matrix.mul M N i j) = matrix.mul (λ i j, f (M i j)) (λ i j, f (N i j)) i j :=
by simp [matrix.mul_val, ring_hom.map_sum]
end ring_hom
|
01a09bf5efae67226b80ec14ca9893b2527c756f | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/hott/subst_tac.hlean | 10e04903424cfb8c73e172cb00017582a7cbb30e | [
"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 | 1,067 | hlean | open nat
example (A B : Type) (a : A) (b : B) (h₁ : A = B) (h₂ : eq.rec_on h₁ a = b) : b = eq.rec_on h₁ a :=
begin
subst h₁ h₂
end
example (A B : Type) (a : A) (b : B) (h₁ : A = B) (h₂ : eq.rec_on h₁ a = b) : b = eq.rec_on h₁ a :=
begin
subst B h₂
end
example (a b c : nat) (a0 : a = 0) (b1 : b = 1 + a) (ab : a = b) : empty :=
begin
subst a0,
subst b1,
contradiction
end
example (a : nat) : a = 0 → a = 1 → empty :=
begin
intro a0 a1,
subst a0,
contradiction
end
example (a b c : nat) : a = 0 → b = 1 + a → a = b → empty :=
begin
intro a0 b1 ab,
subst a0,
rewrite b1 at *,
state,
contradiction
end
example (a b c : nat) : a = 0 → b = 1 + a → a = b → empty :=
begin
intro a0 b1 ab,
subst a0, subst b1,
state,
contradiction
end
example (a b c : nat) : a = 0 → 1 + a = b → a = b → empty :=
begin
intro a0 b1 ab,
subst a0 b1,
state,
contradiction
end
example (a b c : nat) : a = 0 → 1 + a = b → a = b → empty :=
begin
intros,
subst a b,
state,
contradiction
end
|
b9e5b9bc625d329c8a1e5763173e7d6296b40cfe | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/num2.lean | 4a2e9a85b046136edd5cec6b0d5817cd1326d4af | [
"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 | 343 | lean | prelude set_option pp.notation false
definition Prop := Type.{0}
constant eq {A : Type} : A → A → Prop
infixl `=`:50 := eq
constant N : Type.{1}
constant z : N
constant o : N
constant b : N
notation 0 := z
notation 1 := o
check 1
check 0
constant G : Type.{1}
constant gz : G
constant a : G
notation 0 := gz
check 0 = a
check b = 0
|
7a19ac0cc988cecbf071db946106e79a83a3ba42 | 0c9c1ff8e5013c525bf1d72338b62db639374733 | /library/init/algebra/classes.lean | c3b73d515ca422bc4c537db5563c816383df420f | [
"Apache-2.0"
] | permissive | semorrison/lean | 1f2bb450c3400098666ff6e43aa29b8e1e3cdc3a | 85dcb385d5219f2fca8c73b2ebca270fe81337e0 | refs/heads/master | 1,638,526,143,586 | 1,634,825,588,000 | 1,634,825,588,000 | 258,650,844 | 0 | 0 | Apache-2.0 | 1,587,772,955,000 | 1,587,772,954,000 | null | UTF-8 | Lean | false | false | 13,793 | 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.logic init.data.ordering.basic
universes u v
/-!
# Unbundled algebra classes
These classes and the `@[algebra]` attribute are part of an incomplete refactor described
[here on the github Wiki](https://github.com/leanprover/lean/wiki/Refactoring-structures#encoding-the-algebraic-hierarchy-1).
By themselves, these classes are not good replacements for the `monoid` / `group` etc structures
provided by mathlib, as they are not discoverable by `simp` unlike the current lemmas due to there
being little to index on. The Wiki page linked above describes an algebraic normalizer, but it is not
implemented.
-/
@[algebra] class is_symm_op (α : Type u) (β : out_param (Type v)) (op : α → α → β) : Prop :=
(symm_op : ∀ a b, op a b = op b a)
@[algebra] class is_commutative (α : Type u) (op : α → α → α) : Prop :=
(comm : ∀ a b, op a b = op b a)
@[priority 100]
instance is_symm_op_of_is_commutative (α : Type u) (op : α → α → α) [is_commutative α op] :
is_symm_op α α op :=
{symm_op := is_commutative.comm}
@[algebra] class is_associative (α : Type u) (op : α → α → α) : Prop :=
(assoc : ∀ a b c, op (op a b) c = op a (op b c))
@[algebra] class is_left_id (α : Type u) (op : α → α → α) (o : out_param α) : Prop :=
(left_id : ∀ a, op o a = a)
@[algebra] class is_right_id (α : Type u) (op : α → α → α) (o : out_param α) : Prop :=
(right_id : ∀ a, op a o = a)
@[algebra] class is_left_null (α : Type u) (op : α → α → α) (o : out_param α) : Prop :=
(left_null : ∀ a, op o a = o)
@[algebra] class is_right_null (α : Type u) (op : α → α → α) (o : out_param α) : Prop :=
(right_null : ∀ a, op a o = o)
@[algebra] class is_left_cancel (α : Type u) (op : α → α → α) : Prop :=
(left_cancel : ∀ a b c, op a b = op a c → b = c)
@[algebra] class is_right_cancel (α : Type u) (op : α → α → α) : Prop :=
(right_cancel : ∀ a b c, op a b = op c b → a = c)
@[algebra] class is_idempotent (α : Type u) (op : α → α → α) : Prop :=
(idempotent : ∀ a, op a a = a)
@[algebra] class is_left_distrib (α : Type u) (op₁ : α → α → α) (op₂ : out_param $ α → α → α) : Prop :=
(left_distrib : ∀ a b c, op₁ a (op₂ b c) = op₂ (op₁ a b) (op₁ a c))
@[algebra] class is_right_distrib (α : Type u) (op₁ : α → α → α) (op₂ : out_param $ α → α → α) : Prop :=
(right_distrib : ∀ a b c, op₁ (op₂ a b) c = op₂ (op₁ a c) (op₁ b c))
@[algebra] class is_left_inv (α : Type u) (op : α → α → α) (inv : out_param $ α → α) (o : out_param α) : Prop :=
(left_inv : ∀ a, op (inv a) a = o)
@[algebra] class is_right_inv (α : Type u) (op : α → α → α) (inv : out_param $ α → α) (o : out_param α) : Prop :=
(right_inv : ∀ a, op a (inv a) = o)
@[algebra] class is_cond_left_inv (α : Type u) (op : α → α → α) (inv : out_param $ α → α) (o : out_param α) (p : out_param $ α → Prop) : Prop :=
(left_inv : ∀ a, p a → op (inv a) a = o)
@[algebra] class is_cond_right_inv (α : Type u) (op : α → α → α) (inv : out_param $ α → α) (o : out_param α) (p : out_param $ α → Prop) : Prop :=
(right_inv : ∀ a, p a → op a (inv a) = o)
@[algebra] class is_distinct (α : Type u) (a : α) (b : α) : Prop :=
(distinct : a ≠ b)
/-
-- The following type class doesn't seem very useful, a regular simp lemma should work for this.
class is_inv (α : Type u) (β : Type v) (f : α → β) (g : out β → α) : Prop :=
(inv : ∀ a, g (f a) = a)
-- The following one can also be handled using a regular simp lemma
class is_idempotent (α : Type u) (f : α → α) : Prop :=
(idempotent : ∀ a, f (f a) = f a)
-/
/-- `is_irrefl X r` means the binary relation `r` on `X` is irreflexive (that is, `r x x` never
holds). -/
@[algebra] class is_irrefl (α : Type u) (r : α → α → Prop) : Prop :=
(irrefl : ∀ a, ¬ r a a)
/-- `is_refl X r` means the binary relation `r` on `X` is reflexive. -/
@[algebra] class is_refl (α : Type u) (r : α → α → Prop) : Prop :=
(refl : ∀ a, r a a)
/-- `is_symm X r` means the binary relation `r` on `X` is symmetric. -/
@[algebra] class is_symm (α : Type u) (r : α → α → Prop) : Prop :=
(symm : ∀ a b, r a b → r b a)
/-- The opposite of a symmetric relation is symmetric. -/
@[priority 100] instance is_symm_op_of_is_symm (α : Type u) (r : α → α → Prop) [is_symm α r] :
is_symm_op α Prop r :=
{symm_op := λ a b, propext $ iff.intro (is_symm.symm a b) (is_symm.symm b a)}
/-- `is_asymm X r` means that the binary relation `r` on `X` is asymmetric, that is,
`r a b → ¬ r b a`. -/
@[algebra] class is_asymm (α : Type u) (r : α → α → Prop) : Prop :=
(asymm : ∀ a b, r a b → ¬ r b a)
/-- `is_antisymm X r` means the binary relation `r` on `X` is antisymmetric. -/
@[algebra] class is_antisymm (α : Type u) (r : α → α → Prop) : Prop :=
(antisymm : ∀ a b, r a b → r b a → a = b)
/-- `is_trans X r` means the binary relation `r` on `X` is transitive. -/
@[algebra] class is_trans (α : Type u) (r : α → α → Prop) : Prop :=
(trans : ∀ a b c, r a b → r b c → r a c)
/-- `is_total X r` means that the binary relation `r` on `X` is total, that is, that for any
`x y : X` we have `r x y` or `r y x`.-/
@[algebra] class is_total (α : Type u) (r : α → α → Prop) : Prop :=
(total : ∀ a b, r a b ∨ r b a)
/-- `is_preorder X r` means that the binary relation `r` on `X` is a pre-order, that is, reflexive
and transitive. -/
@[algebra] class is_preorder (α : Type u) (r : α → α → Prop) extends
is_refl α r, is_trans α r : Prop.
/-- `is_total_preorder X r` means that the binary relation `r` on `X` is total and a preorder. -/
@[algebra] class is_total_preorder (α : Type u) (r : α → α → Prop) extends
is_trans α r, is_total α r : Prop.
/-- Every total pre-order is a pre-order. -/
instance is_total_preorder_is_preorder (α : Type u) (r : α → α → Prop) [s : is_total_preorder α r] :
is_preorder α r :=
{trans := s.trans,
refl := λ a, or.elim (@is_total.total _ r _ a a) id id}
@[algebra] class is_partial_order (α : Type u) (r : α → α → Prop) extends
is_preorder α r, is_antisymm α r : Prop.
@[algebra] class is_linear_order (α : Type u) (r : α → α → Prop) extends
is_partial_order α r, is_total α r : Prop.
@[algebra] class is_equiv (α : Type u) (r : α → α → Prop) extends
is_preorder α r, is_symm α r : Prop.
@[algebra] class is_per (α : Type u) (r : α → α → Prop) extends is_symm α r, is_trans α r : Prop.
@[algebra] class is_strict_order (α : Type u) (r : α → α → Prop) extends
is_irrefl α r, is_trans α r : Prop.
@[algebra] class is_incomp_trans (α : Type u) (lt : α → α → Prop) : Prop :=
(incomp_trans : ∀ a b c, (¬ lt a b ∧ ¬ lt b a) → (¬ lt b c ∧ ¬ lt c b) → (¬ lt a c ∧ ¬ lt c a))
@[algebra] class is_strict_weak_order (α : Type u) (lt : α → α → Prop) extends
is_strict_order α lt, is_incomp_trans α lt : Prop.
@[algebra] class is_trichotomous (α : Type u) (lt : α → α → Prop) : Prop :=
(trichotomous : ∀ a b, lt a b ∨ a = b ∨ lt b a)
@[algebra] class is_strict_total_order (α : Type u) (lt : α → α → Prop)
extends is_trichotomous α lt, is_strict_weak_order α lt : Prop.
instance eq_is_equiv (α : Type u) : is_equiv α (=) :=
{symm := @eq.symm _, trans := @eq.trans _, refl := eq.refl}
section
variables {α : Type u} {r : α → α → Prop}
local infix `≺`:50 := r
lemma irrefl [is_irrefl α r] (a : α) : ¬ a ≺ a :=
is_irrefl.irrefl a
lemma refl [is_refl α r] (a : α) : a ≺ a :=
is_refl.refl a
lemma trans [is_trans α r] {a b c : α} : a ≺ b → b ≺ c → a ≺ c :=
is_trans.trans _ _ _
lemma symm [is_symm α r] {a b : α} : a ≺ b → b ≺ a :=
is_symm.symm _ _
lemma antisymm [is_antisymm α r] {a b : α} : a ≺ b → b ≺ a → a = b :=
is_antisymm.antisymm _ _
lemma asymm [is_asymm α r] {a b : α} : a ≺ b → ¬ b ≺ a :=
is_asymm.asymm _ _
lemma trichotomous [is_trichotomous α r] : ∀ (a b : α), a ≺ b ∨ a = b ∨ b ≺ a :=
is_trichotomous.trichotomous
lemma incomp_trans [is_incomp_trans α r] {a b c : α} : (¬ a ≺ b ∧ ¬ b ≺ a) → (¬ b ≺ c ∧ ¬ c ≺ b) → (¬ a ≺ c ∧ ¬ c ≺ a) :=
is_incomp_trans.incomp_trans _ _ _
@[priority 90]
instance is_asymm_of_is_trans_of_is_irrefl [is_trans α r] [is_irrefl α r] : is_asymm α r :=
⟨λ a b h₁ h₂, absurd (trans h₁ h₂) (irrefl a)⟩
section explicit_relation_variants
variable (r)
@[elab_simple]
lemma irrefl_of [is_irrefl α r] (a : α) : ¬ a ≺ a := irrefl a
@[elab_simple]
lemma refl_of [is_refl α r] (a : α) : a ≺ a := refl a
@[elab_simple]
lemma trans_of [is_trans α r] {a b c : α} : a ≺ b → b ≺ c → a ≺ c := trans
@[elab_simple]
lemma symm_of [is_symm α r] {a b : α} : a ≺ b → b ≺ a := symm
@[elab_simple]
lemma asymm_of [is_asymm α r] {a b : α} : a ≺ b → ¬ b ≺ a := asymm
@[elab_simple]
lemma total_of [is_total α r] (a b : α) : a ≺ b ∨ b ≺ a :=
is_total.total _ _
@[elab_simple]
lemma trichotomous_of [is_trichotomous α r] : ∀ (a b : α), a ≺ b ∨ a = b ∨ b ≺ a := trichotomous
@[elab_simple]
lemma incomp_trans_of [is_incomp_trans α r] {a b c : α} : (¬ a ≺ b ∧ ¬ b ≺ a) → (¬ b ≺ c ∧ ¬ c ≺ b) → (¬ a ≺ c ∧ ¬ c ≺ a) := incomp_trans
end explicit_relation_variants
end
namespace strict_weak_order
section
parameters {α : Type u} {r : α → α → Prop}
local infix `≺`:50 := r
def equiv (a b : α) : Prop :=
¬ a ≺ b ∧ ¬ b ≺ a
parameter [is_strict_weak_order α r]
local infix ` ≈ `:50 := equiv
lemma erefl (a : α) : a ≈ a :=
⟨irrefl a, irrefl a⟩
lemma esymm {a b : α} : a ≈ b → b ≈ a :=
λ ⟨h₁, h₂⟩, ⟨h₂, h₁⟩
lemma etrans {a b c : α} : a ≈ b → b ≈ c → a ≈ c :=
incomp_trans
lemma not_lt_of_equiv {a b : α} : a ≈ b → ¬ a ≺ b :=
λ h, h.1
lemma not_lt_of_equiv' {a b : α} : a ≈ b → ¬ b ≺ a :=
λ h, h.2
instance is_equiv : is_equiv α equiv :=
{refl := erefl, trans := @etrans, symm := @esymm}
end
/- Notation for the equivalence relation induced by lt -/
notation a ` ≈[`:50 lt `]` b:50 := @equiv _ lt a b
end strict_weak_order
lemma is_strict_weak_order_of_is_total_preorder {α : Type u} {le : α → α → Prop} {lt : α → α → Prop} [decidable_rel le] [s : is_total_preorder α le]
(h : ∀ a b, lt a b ↔ ¬ le b a) : is_strict_weak_order α lt :=
{
trans :=
λ a b c hab hbc,
have nba : ¬ le b a, from iff.mp (h _ _) hab,
have ncb : ¬ le c b, from iff.mp (h _ _) hbc,
have hab : le a b, from or.resolve_left (total_of le b a) nba,
have nca : ¬ le c a, from λ hca : le c a,
have hcb : le c b, from trans_of le hca hab,
absurd hcb ncb,
iff.mpr (h _ _) nca,
irrefl := λ a hlt, absurd (refl_of le a) (iff.mp (h _ _) hlt),
incomp_trans := λ a b c ⟨nab, nba⟩ ⟨nbc, ncb⟩,
have hba : le b a, from decidable.of_not_not (iff.mp (not_iff_not_of_iff (h _ _)) nab),
have hab : le a b, from decidable.of_not_not (iff.mp (not_iff_not_of_iff (h _ _)) nba),
have hcb : le c b, from decidable.of_not_not (iff.mp (not_iff_not_of_iff (h _ _)) nbc),
have hbc : le b c, from decidable.of_not_not (iff.mp (not_iff_not_of_iff (h _ _)) ncb),
have hac : le a c, from trans_of le hab hbc,
have hca : le c a, from trans_of le hcb hba,
and.intro
(λ n, absurd hca (iff.mp (h _ _) n))
(λ n, absurd hac (iff.mp (h _ _) n))
}
lemma lt_of_lt_of_incomp {α : Type u} {lt : α → α → Prop} [is_strict_weak_order α lt] [decidable_rel lt]
: ∀ {a b c}, lt a b → (¬ lt b c ∧ ¬ lt c b) → lt a c :=
λ a b c hab ⟨nbc, ncb⟩,
have nca : ¬ lt c a, from λ hca, absurd (trans_of lt hca hab) ncb,
decidable.by_contradiction $
λ nac : ¬ lt a c,
have ¬ lt a b ∧ ¬ lt b a, from incomp_trans_of lt ⟨nac, nca⟩ ⟨ncb, nbc⟩,
absurd hab this.1
lemma lt_of_incomp_of_lt {α : Type u} {lt : α → α → Prop} [is_strict_weak_order α lt] [decidable_rel lt]
: ∀ {a b c}, (¬ lt a b ∧ ¬ lt b a) → lt b c → lt a c :=
λ a b c ⟨nab, nba⟩ hbc,
have nca : ¬ lt c a, from λ hca, absurd (trans_of lt hbc hca) nba,
decidable.by_contradiction $
λ nac : ¬ lt a c,
have ¬ lt b c ∧ ¬ lt c b, from incomp_trans_of lt ⟨nba, nab⟩ ⟨nac, nca⟩,
absurd hbc this.1
lemma eq_of_incomp {α : Type u} {lt : α → α → Prop} [is_trichotomous α lt] {a b} : (¬ lt a b ∧ ¬ lt b a) → a = b :=
λ ⟨nab, nba⟩,
match trichotomous_of lt a b with
| or.inl hab := absurd hab nab
| or.inr (or.inl hab) := hab
| or.inr (or.inr hba) := absurd hba nba
end
lemma eq_of_eqv_lt {α : Type u} {lt : α → α → Prop} [is_trichotomous α lt] {a b} : a ≈[lt] b → a = b :=
eq_of_incomp
lemma incomp_iff_eq {α : Type u} {lt : α → α → Prop} [is_trichotomous α lt] [is_irrefl α lt] (a b) : (¬ lt a b ∧ ¬ lt b a) ↔ a = b :=
iff.intro eq_of_incomp (λ hab, eq.subst hab (and.intro (irrefl_of lt a) (irrefl_of lt a)))
lemma eqv_lt_iff_eq {α : Type u} {lt : α → α → Prop} [is_trichotomous α lt] [is_irrefl α lt] (a b) : a ≈[lt] b ↔ a = b :=
incomp_iff_eq a b
lemma not_lt_of_lt {α : Type u} {lt : α → α → Prop} [is_strict_order α lt] {a b} : lt a b → ¬ lt b a :=
λ h₁ h₂, absurd (trans_of lt h₁ h₂) (irrefl_of lt _)
|
c6d96752e218c806352ca6b55daeb97820217086 | 54d7e71c3616d331b2ec3845d31deb08f3ff1dea | /tests/lean/defeq_simp1.lean | 8542b9ff6349338558944fbabf7f4370642e01fa | [
"Apache-2.0"
] | permissive | pachugupta/lean | 6f3305c4292288311cc4ab4550060b17d49ffb1d | 0d02136a09ac4cf27b5c88361750e38e1f485a1a | refs/heads/master | 1,611,110,653,606 | 1,493,130,117,000 | 1,493,167,649,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 676 | lean | @[reducible]
def nat_has_add2 : has_add nat :=
⟨λ x y : nat, nat.add x y⟩
set_option pp.all true
open tactic
example (a b : nat) (H : @add nat (id (id nat.has_add)) a b = @add nat nat_has_add2 a b) : true :=
by do
s ← simp_lemmas.mk_default,
get_local `H >>= infer_type >>= s^.dsimplify >>= trace,
constructor
example (a b : nat) (H : (λ x : nat, @add nat (id (id nat.has_add)) a b) = (λ x : nat, @add nat nat_has_add2 a x)) : true :=
by do
s ← simp_lemmas.mk_default,
get_local `H >>= infer_type >>= s^.dsimplify >>= trace,
constructor
attribute [reducible]
definition nat_has_add3 : nat → has_add nat :=
λ n, has_add.mk (λ x y : nat, x + y)
|
5b7e666652c90256cf126c61c43d62184742e5ba | 0d9b0a832bc57849732c5bd008a7a142f7e49656 | /src/example_deadlocks.lean | 670698e253b7d6fabdb861c6a84efbe751283442 | [] | no_license | mirefek/sokoban.lean | bb9414af67894e4d8ce75f8c8d7031df02d371d0 | 451c92308afb4d3f8e566594b9751286f93b899b | refs/heads/master | 1,681,025,245,267 | 1,618,997,832,000 | 1,618,997,832,000 | 359,491,681 | 10 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,418 | lean | import .deadlocks
namespace deadlocks_example
open deadlocks
def lev := sokolevel.from_string "
######
# #
# $@ #
# . #
######
"
@[reducible]
def deadlock_local (dl : boxint) : Prop := deadlock lev.avail lev.goal dl
def deadlocks_local (dls : list boxint) : Prop
:= dls.pall (λ dl, deadlock_local dl)
def generate_local : list (ℕ × ℕ) → list (ℕ × ℕ) → ℕ × ℕ → boxint
:= boxint.generate_from_list lev.avail
def dl0 := generate_local [(1,2)] [] (2,2)
theorem dl0_dl : deadlock_local dl0
:=
begin
apply new_deadlock,
analyze_deadlock,
end
#html dl0_dl.to_html
def dl1 := generate_local [(4,2)] [] (1,2)
theorem dl1_dl : deadlock_local dl1
:=
begin
apply new_deadlock,
analyze_deadlock,
end
#html dl1_dl.to_html
def dl2 := generate_local [(2,2)] [] (1,2)
def dl3 := generate_local [(3,2)] [] (1,2)
def dl2_3 := [dl2, dl3]
theorem dl2_3_dl : deadlocks_local dl2_3
:=
begin
refine list.pall_iff.mpr (new_deadlocks _),
rcases list.pall_in dl2_3 with ⟨dl2_in, dl3_in, irrelevant⟩,
refine list.pall_iff.mp ⟨_, _, trivial⟩,
{
analyze_deadlock,
deadlocked_step dl0_dl,
deadlocked_step dl3_in,
}, {
analyze_deadlock,
deadlocked_step dl2_in,
deadlocked_step dl1_dl,
},
end
theorem dl2_dl : deadlock_local dl2
:= dl2_3_dl.1
theorem dl3_dl : deadlock_local dl3
:= dl2_3_dl.2.1
#html dl2_dl.to_html
#html dl3_dl.to_html
end deadlocks_example
|
2f47641287366f0ee9ee4abd561f8c74bd06ea56 | 8b9f17008684d796c8022dab552e42f0cb6fb347 | /tests/lean/run/tactic7.lean | c0a1fd57ce3156038d2f527d4face343a5f1626d | [
"Apache-2.0"
] | permissive | chubbymaggie/lean | 0d06ae25f9dd396306fb02190e89422ea94afd7b | d2c7b5c31928c98f545b16420d37842c43b4ae9a | refs/heads/master | 1,611,313,622,901 | 1,430,266,839,000 | 1,430,267,083,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 327 | lean | import logic
open tactic
theorem tst {A B : Prop} (H1 : A) (H2 : B) : A ∧ B ∧ A
:= by apply and.intro; state; assumption; apply and.intro; assumption
check tst
theorem tst2 {A B : Prop} (H1 : A) (H2 : B) : A ∧ B ∧ A
:= by repeat ((apply @and.intro | assumption) ; trace "STEP"; state; trace "----------")
check tst2
|
012efc9e1ec8eba0bb442395863cc1ee52023fd8 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /03_Propositions_and_Proofs.org.2.lean | 650d0bdf46d026cf278965645760ae594899446b | [] | no_license | cjmazey/lean-tutorial | ba559a49f82aa6c5848b9bf17b7389bf7f4ba645 | 381f61c9fcac56d01d959ae0fa6e376f2c4e3b34 | refs/heads/master | 1,610,286,098,832 | 1,447,124,923,000 | 1,447,124,923,000 | 43,082,433 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 408 | lean | /- page 33 -/
import standard
namespace hide
constant and : Prop → Prop → Prop
constant or : Prop → Prop → Prop
constant not : Prop → Prop
constant implies : Prop → Prop → Prop
-- BEGIN
constant Proof : Prop → Type
constant and_comm : Π p q : Prop, Proof (implies (and p q) (and q p))
variables p q : Prop
check and_comm p q -- Proof (implies (and p q) (and q p))
-- END
end hide
|
c3d274d2f20f8889e0d966feacddb0904bed960a | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/run/consume.lean | 226f736e809296061f67c7e28fbf3097ee90a06c | [
"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 | 116 | lean | definition pr2 {A : Type} (a b : A) := a
check pr2
check pr2
check pr2
check @pr2
check @pr2
check @@pr2
check pr2
|
756651367de5c3cf3d322de30e4dc542bf77119f | cf39355caa609c0f33405126beee2739aa3cb77e | /library/init/control/except.lean | bd3ce437b1ec8a86863c30060537e281e6efbaeb | [
"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 | 5,227 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jared Roesch, Sebastian Ullrich
The except monad transformer.
-/
prelude
import init.control.alternative init.control.lift
universes u v w
inductive except (ε : Type u) (α : Type v)
| error : ε → except
| ok : α → except
namespace except
section
parameter {ε : Type u}
protected def return {α : Type v} (a : α) : except ε α :=
except.ok a
protected def map {α β : Type v} (f : α → β) : except ε α → except ε β
| (except.error err) := except.error err
| (except.ok v) := except.ok $ f v
protected def map_error {ε' : Type u} {α : Type v} (f : ε → ε') : except ε α → except ε' α
| (except.error err) := except.error $ f err
| (except.ok v) := except.ok v
protected def bind {α β : Type v} (ma : except ε α) (f : α → except ε β) : except ε β :=
match ma with
| (except.error err) := except.error err
| (except.ok v) := f v
end
protected def to_bool {α : Type v} : except ε α → bool
| (except.ok _) := tt
| (except.error _) := ff
protected def to_option {α : Type v} : except ε α → option α
| (except.ok a) := some a
| (except.error _) := none
instance : monad (except ε) :=
{ pure := @return, bind := @bind }
end
end except
structure except_t (ε : Type u) (m : Type u → Type v) (α : Type u) : Type v :=
(run : m (except ε α))
attribute [pp_using_anonymous_constructor] except_t
namespace except_t
section
parameters {ε : Type u} {m : Type u → Type v} [monad m]
@[inline] protected def return {α : Type u} (a : α) : except_t ε m α :=
⟨pure $ except.ok a⟩
@[inline] protected def bind_cont {α β : Type u} (f : α → except_t ε m β) : except ε α → m (except ε β)
| (except.ok a) := (f a).run
| (except.error e) := pure (except.error e)
@[inline] protected def bind {α β : Type u} (ma : except_t ε m α) (f : α → except_t ε m β) : except_t ε m β :=
⟨ma.run >>= bind_cont f⟩
@[inline] protected def lift {α : Type u} (t : m α) : except_t ε m α :=
⟨except.ok <$> t⟩
instance : has_monad_lift m (except_t ε m) :=
⟨@except_t.lift⟩
protected def catch {α : Type u} (ma : except_t ε m α) (handle : ε → except_t ε m α) : except_t ε m α :=
⟨ma.run >>= λ res, match res with
| except.ok a := pure (except.ok a)
| except.error e := (handle e).run
end⟩
@[inline] protected def monad_map {m'} [monad m'] {α} (f : ∀ {α}, m α → m' α) : except_t ε m α → except_t ε m' α :=
λ x, ⟨f x.run⟩
instance (m') [monad m'] : monad_functor m m' (except_t ε m) (except_t ε m') :=
⟨@monad_map m' _⟩
instance : monad (except_t ε m) :=
{ pure := @return, bind := @bind }
protected def adapt {ε' α : Type u} (f : ε → ε') : except_t ε m α → except_t ε' m α :=
λ x, ⟨except.map_error f <$> x.run⟩
end
end except_t
/-- An implementation of [MonadError](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Except.html#t:MonadError) -/
class monad_except (ε : out_param (Type u)) (m : Type v → Type w) :=
(throw {α : Type v} : ε → m α)
(catch {α : Type v} : m α → (ε → m α) → m α)
namespace monad_except
variables {ε : Type u} {m : Type v → Type w}
protected def orelse [monad_except ε m] {α : Type v} (t₁ t₂ : m α) : m α :=
catch t₁ $ λ _, t₂
/-- Alternative orelse operator that allows to select which exception should be used.
The default is to use the first exception since the standard `orelse` uses the second. -/
meta def orelse' [monad_except ε m] {α : Type v} (t₁ t₂ : m α) (use_first_ex := tt) : m α :=
catch t₁ $ λ e₁, catch t₂ $ λ e₂, throw (if use_first_ex then e₁ else e₂)
end monad_except
export monad_except (throw catch)
instance (m ε) [monad m] : monad_except ε (except_t ε m) :=
{ throw := λ α, except_t.mk ∘ pure ∘ except.error, catch := @except_t.catch ε _ _ }
/-- Adapt a monad stack, changing its top-most error type.
Note: This class can be seen as a simplification of the more "principled" definition
```
class monad_except_functor (ε ε' : out_param (Type u)) (n n' : Type u → Type u) :=
(map {α : Type u} : (∀ {m : Type u → Type u} [monad m], except_t ε m α → except_t ε' m α) → n α → n' α)
```
-/
class monad_except_adapter (ε ε' : out_param (Type u)) (m m' : Type u → Type v) :=
(adapt_except {α : Type u} : (ε → ε') → m α → m' α)
export monad_except_adapter (adapt_except)
section
variables {ε ε' : Type u} {m m' : Type u → Type v}
@[priority 100]
instance monad_except_adapter_trans {n n' : Type u → Type v} [monad_except_adapter ε ε' m m']
[monad_functor m m' n n'] : monad_except_adapter ε ε' n n' :=
⟨λ α f, monad_map (λ α, (adapt_except f : m α → m' α))⟩
instance [monad m] : monad_except_adapter ε ε' (except_t ε m) (except_t ε' m) :=
⟨λ α, except_t.adapt⟩
end
instance (ε m out) [monad_run out m] : monad_run (λ α, out (except ε α)) (except_t ε m) :=
⟨λ α, run ∘ except_t.run⟩
|
360d76ac4198eeb634bc5e63487ce9ea2dba10e9 | 57fdc8de88f5ea3bfde4325e6ecd13f93a274ab5 | /algebra/big_operators.lean | 2132236c84bd659508f29ac9de12b3d8c326fd67 | [
"Apache-2.0"
] | permissive | louisanu/mathlib | 11f56f2d40dc792bc05ee2f78ea37d73e98ecbfe | 2bd5e2159d20a8f20d04fc4d382e65eea775ed39 | refs/heads/master | 1,617,706,993,439 | 1,523,163,654,000 | 1,523,163,654,000 | 124,519,997 | 0 | 0 | Apache-2.0 | 1,520,588,283,000 | 1,520,588,283,000 | null | UTF-8 | Lean | false | false | 14,412 | 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
Some big operators for lists and finite sets.
-/
import data.list.basic data.list.perm data.finset
algebra.group algebra.ordered_group algebra.group_power
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
namespace finset
variables {s s₁ s₂ : finset α} {a : α} {f g : α → β}
/-- `prod s f` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/
@[to_additive finset.sum]
protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod
attribute [to_additive finset.sum.equations._eqn_1] finset.prod.equations._eqn_1
@[to_additive finset.sum_eq_fold]
theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : s.prod f = s.fold (*) 1 f := rfl
section comm_monoid
variables [comm_monoid β]
@[simp, to_additive finset.sum_empty]
lemma prod_empty {α : Type u} {f : α → β} : (∅:finset α).prod f = 1 := rfl
@[simp, to_additive finset.sum_insert]
lemma prod_insert [decidable_eq α] : a ∉ s → (insert a s).prod f = f a * s.prod f := fold_insert
@[simp, to_additive finset.sum_singleton]
lemma prod_singleton : (singleton a).prod f = f a :=
eq.trans fold_singleton (by simp)
@[simp] lemma prod_const_one : s.prod (λx, (1 : β)) = 1 :=
by simp [finset.prod]
@[simp] lemma sum_const_zero {β} {s : finset α} [add_comm_monoid β] : s.sum (λx, (0 : β)) = 0 :=
@prod_const_one _ (multiplicative β) _ _
attribute [to_additive finset.sum_const_zero] prod_const_one
@[simp, to_additive finset.sum_image]
lemma prod_image [decidable_eq α] [decidable_eq γ] {s : finset γ} {g : γ → α} :
(∀x∈s, ∀y∈s, g x = g y → x = y) → (s.image g).prod f = s.prod (λx, f (g x)) :=
fold_image
@[congr, to_additive finset.sum_congr]
lemma prod_congr (h : s₁ = s₂) : (∀x∈s₂, f x = g x) → s₁.prod f = s₂.prod g :=
by rw [h]; exact fold_congr
attribute [congr] finset.sum_congr
@[to_additive finset.sum_union_inter]
lemma prod_union_inter [decidable_eq α] : (s₁ ∪ s₂).prod f * (s₁ ∩ s₂).prod f = s₁.prod f * s₂.prod f :=
fold_union_inter
@[to_additive finset.sum_union]
lemma prod_union [decidable_eq α] (h : s₁ ∩ s₂ = ∅) : (s₁ ∪ s₂).prod f = s₁.prod f * s₂.prod f :=
by rw [←prod_union_inter, h]; simp
@[to_additive finset.sum_sdiff]
lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) : (s₂ \ s₁).prod f * s₁.prod f = s₂.prod f :=
by rw [←prod_union (sdiff_inter_self _ _), sdiff_union_of_subset h]
@[to_additive finset.sum_bind]
lemma prod_bind [decidable_eq α] {s : finset γ} {t : γ → finset α} :
(∀x∈s, ∀y∈s, x ≠ y → t x ∩ t y = ∅) → (s.bind t).prod f = s.prod (λx, (t x).prod f) :=
by haveI := classical.dec_eq γ; exact
finset.induction_on s (by simp)
(assume x s hxs ih hd,
have hd' : ∀x∈s, ∀y∈s, x ≠ y → t x ∩ t y = ∅,
from assume _ hx _ hy, hd _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy),
have t x ∩ finset.bind s t = ∅,
from ext.2 $ assume a,
by simp [mem_bind];
from assume h₁ y hys hy₂,
have ha : a ∈ t x ∩ t y, by simp [*],
have t x ∩ t y = ∅,
from hd _ (mem_insert_self _ _) _ (mem_insert_of_mem hys) $ assume h, hxs $ h.symm ▸ hys,
by rwa [this] at ha,
by simp [hxs, prod_union this, ih hd'] {contextual := tt})
@[to_additive finset.sum_product]
lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} :
(s.product t).prod f = s.prod (λx, t.prod $ λy, f (x, y)) :=
begin
haveI := classical.dec_eq α, haveI := classical.dec_eq γ,
rw [product_eq_bind, prod_bind (λ x hx y hy h, ext.2 _)], {simp [prod_image]},
simp [mem_image], intros, intro, refine h _, cc
end
@[to_additive finset.sum_sigma]
lemma prod_sigma {σ : α → Type*}
{s : finset α} {t : Πa, finset (σ a)} {f : sigma σ → β} :
(s.sigma t).prod f = s.prod (λa, (t a).prod $ λs, f ⟨a, s⟩) :=
by haveI := classical.dec_eq α; haveI := (λ a, classical.dec_eq (σ a)); exact
have ∀a₁ a₂:α, ∀s₁ : finset (σ a₁), ∀s₂ : finset (σ a₂), a₁ ≠ a₂ →
s₁.image (sigma.mk a₁) ∩ s₂.image (sigma.mk a₂) = ∅,
from assume b₁ b₂ s₁ s₂ h, ext.2 $ assume ⟨b₃, c₃⟩,
by simp [mem_image, sigma.mk.inj_iff, heq_iff_eq] {contextual := tt}; cc,
calc (s.sigma t).prod f =
(s.bind (λa, (t a).image (λs, sigma.mk a s))).prod f : by rw sigma_eq_bind
... = s.prod (λa, ((t a).image (λs, sigma.mk a s)).prod f) :
prod_bind $ assume a₁ ha a₂ ha₂ h, this a₁ a₂ (t a₁) (t a₂) h
... = (s.prod $ λa, (t a).prod $ λs, f ⟨a, s⟩) :
by simp [prod_image, sigma.mk.inj_iff, heq_iff_eq]
@[to_additive finset.sum_add_distrib]
lemma prod_mul_distrib : s.prod (λx, f x * g x) = s.prod f * s.prod g :=
eq.trans (by simp; refl) fold_op_distrib
@[to_additive finset.sum_comm]
lemma prod_comm [decidable_eq γ] {s : finset γ} {t : finset α} {f : γ → α → β} :
s.prod (λx, t.prod $ f x) = t.prod (λy, s.prod $ λx, f x y) :=
finset.induction_on s (by simp) (by simp [prod_mul_distrib] {contextual := tt})
@[to_additive finset.sum_hom]
lemma prod_hom [comm_monoid γ] (g : β → γ)
(h₁ : g 1 = 1) (h₂ : ∀x y, g (x * y) = g x * g y) : s.prod (λx, g (f x)) = g (s.prod f) :=
eq.trans (by rw [h₁]; refl) (fold_hom h₂)
@[to_additive finset.sum_subset]
lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → f x = 1) : s₁.prod f = s₂.prod f :=
by haveI := classical.dec_eq α; exact
have (s₂ \ s₁).prod f = (s₂ \ s₁).prod (λx, 1),
from prod_congr rfl begin simp [hf] {contextual := tt} end,
by rw [←prod_sdiff h]; simp [this]
@[to_additive sum_attach]
lemma prod_attach {f : α → β} : s.attach.prod (λx, f x.val) = s.prod f :=
by haveI := classical.dec_eq α; exact
calc s.attach.prod (λx, f x.val) = ((s.attach).image subtype.val).prod f :
by rw [prod_image]; exact assume x _ y _, subtype.eq
... = _ : by rw [attach_image_val]
@[to_additive finset.sum_bij]
lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β}
(i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha))
(i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) :
s.prod f = t.prod g :=
by haveI := classical.prop_decidable; exact
calc s.prod f = s.attach.prod (λx, f x.val) : prod_attach.symm
... = s.attach.prod (λx, g (i x.1 x.2)) : prod_congr rfl $ assume x hx, h _ _
... = (s.attach.image $ λx:{x // x ∈ s}, i x.1 x.2).prod g :
(prod_image $ assume (a₁:{x // x ∈ s}) _ a₂ _ eq, subtype.eq $ i_inj a₁.1 a₂.1 a₁.2 a₂.2 eq).symm
... = _ :
prod_subset
(by simp [subset_iff]; intros b a h eq; subst eq; exact hi _ _)
(assume b hb, not_imp_comm.mp $ assume hb₂,
let ⟨a, ha, eq⟩ := i_surj b hb in by simp [eq]; exact ⟨_, _, rfl⟩)
@[to_additive finset.sum_bij_ne_zero]
lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β}
(i : Πa∈s, f a ≠ 1 → γ) (hi₁ : ∀a h₁ h₂, i a h₁ h₂ ∈ t) (hi₂ : ∀a h₁ h₂, g (i a h₁ h₂) ≠ 1)
(hi₃ : ∀a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂)
(hi₄ : ∀b∈t, g b ≠ 1 → ∃a h₁ h₂, b = i a h₁ h₂)
(h : ∀a h₁ h₂, f a = g (i a h₁ h₂)) :
s.prod f = t.prod g :=
by haveI := classical.prop_decidable; exact
calc s.prod f = (s.filter $ λx, f x ≠ 1).prod f :
(prod_subset (filter_subset _) $ by simp {contextual:=tt}).symm
... = (t.filter $ λx, g x ≠ 1).prod g :
prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2)
(assume a ha, (mem_filter.mp ha).elim $ λh₁ h₂, mem_filter.mpr ⟨hi₁ a h₁ h₂, hi₂ a h₁ h₂⟩)
(assume a ha, (mem_filter.mp ha).elim $ h a)
(assume a₁ a₂ ha₁ ha₂,
(mem_filter.mp ha₁).elim $ λha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λha₂₁ ha₂₂, hi₃ a₁ a₂ _ _ _ _)
(assume b hb, (mem_filter.mp hb).elim $ λh₁ h₂,
let ⟨a, ha₁, ha₂, eq⟩ := hi₄ b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩)
... = t.prod g :
(prod_subset (filter_subset _) $ by simp {contextual:=tt})
@[to_additive finset.exists_ne_zero_of_sum_ne_zero]
lemma exists_ne_one_of_prod_ne_one : s.prod f ≠ 1 → ∃a∈s, f a ≠ 1 :=
by haveI := classical.dec_eq α; exact
finset.induction_on s (by simp) (assume a s has ih h,
classical.by_cases
(assume ha : f a = 1,
have s.prod f ≠ 1, by simpa [ha, has] using h,
let ⟨a, ha, hfa⟩ := ih this in
⟨a, mem_insert_of_mem ha, hfa⟩)
(assume hna : f a ≠ 1,
⟨a, mem_insert_self _ _, hna⟩))
end comm_monoid
section comm_group
variables [comm_group β]
@[simp, to_additive finset.sum_neg_distrib]
lemma prod_inv_distrib : s.prod (λx, (f x)⁻¹) = (s.prod f)⁻¹ :=
prod_hom has_inv.inv one_inv mul_inv
end comm_group
@[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) :
card (s.sigma t) = s.sum (λ a, card (t a)) :=
multiset.card_sigma _ _
end finset
namespace finset
variables [decidable_eq α] {s s₁ s₂ : finset α} {f g : α → β} {b : β} {a : α}
@[simp] lemma sum_sub_distrib [add_comm_group β] : s.sum (λx, f x - g x) = s.sum f - s.sum g :=
by simp [sum_add_distrib]
section ordered_cancel_comm_monoid
variables [ordered_cancel_comm_monoid β]
lemma sum_le_sum : (∀x∈s, f x ≤ g x) → s.sum f ≤ s.sum g :=
finset.induction_on s (by simp) $ assume a s ha ih h,
have f a + s.sum f ≤ g a + s.sum g,
from add_le_add (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx),
by simp [*]
lemma zero_le_sum (h : ∀x∈s, 0 ≤ f x) : 0 ≤ s.sum f := le_trans (by simp) (sum_le_sum h)
lemma sum_le_zero (h : ∀x∈s, f x ≤ 0) : s.sum f ≤ 0 := le_trans (sum_le_sum h) (by simp)
end ordered_cancel_comm_monoid
section semiring
variables [semiring β]
lemma sum_mul : s.sum f * b = s.sum (λx, f x * b) :=
(sum_hom (λx, x * b) (zero_mul b) (assume a c, add_mul a c b)).symm
lemma mul_sum : b * s.sum f = s.sum (λx, b * f x) :=
(sum_hom (λx, b * x) (mul_zero b) (assume a c, mul_add b a c)).symm
end semiring
section comm_semiring
variables [comm_semiring β]
lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : s.prod f = 0 :=
calc s.prod f = (insert a (erase s a)).prod f : by simp [ha, insert_erase]
... = 0 : by simp [h]
end comm_semiring
section integral_domain /- add integral_semi_domain to support nat and ennreal -/
variables [integral_domain β]
lemma prod_eq_zero_iff : s.prod f = 0 ↔ (∃a∈s, f a = 0) :=
finset.induction_on s (by simp)
begin
intros a s,
rw [bex_def, bex_def, exists_mem_insert],
simp [mul_eq_zero_iff_eq_zero_or_eq_zero] {contextual := tt}
end
end integral_domain
section ordered_comm_monoid
variables [ordered_comm_monoid β]
lemma sum_le_sum' : (∀x∈s, f x ≤ g x) → s.sum f ≤ s.sum g :=
finset.induction_on s (by simp; refl) $ assume a s ha ih h,
have f a + s.sum f ≤ g a + s.sum g,
from add_le_add' (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx),
by simp [*]
lemma zero_le_sum' (h : ∀x∈s, 0 ≤ f x) : 0 ≤ s.sum f := le_trans (by simp) (sum_le_sum' h)
lemma sum_le_zero' (h : ∀x∈s, f x ≤ 0) : s.sum f ≤ 0 := le_trans (sum_le_sum' h) (by simp)
lemma sum_le_sum_of_subset_of_nonneg
(h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → 0 ≤ f x) : s₁.sum f ≤ s₂.sum f :=
calc s₁.sum f ≤ (s₂ \ s₁).sum f + s₁.sum f :
le_add_of_nonneg_left' $ zero_le_sum' $ by simp [hf] {contextual := tt}
... = (s₂ \ s₁ ∪ s₁).sum f : (sum_union (sdiff_inter_self _ _)).symm
... = s₂.sum f : by rw [sdiff_union_of_subset h]
lemma sum_eq_zero_iff_of_nonneg : (∀x∈s, 0 ≤ f x) → (s.sum f = 0 ↔ ∀x∈s, f x = 0) :=
finset.induction_on s (by simp) $
by simp [or_imp_distrib, forall_and_distrib, zero_le_sum' ,
add_eq_zero_iff_eq_zero_and_eq_zero_of_nonneg_of_nonneg'] {contextual := tt}
lemma single_le_sum (hf : ∀x∈s, 0 ≤ f x) {a} (h : a ∈ s) : f a ≤ s.sum f :=
by simpa using show (singleton a).sum f ≤ s.sum f,
from sum_le_sum_of_subset_of_nonneg
(λ x e, (mem_singleton.1 e).symm ▸ h) (λ x h _, hf x h)
end ordered_comm_monoid
section canonically_ordered_monoid
variables [canonically_ordered_monoid β] [@decidable_rel β (≤)]
lemma sum_le_sum_of_subset (h : s₁ ⊆ s₂) : s₁.sum f ≤ s₂.sum f :=
sum_le_sum_of_subset_of_nonneg h $ assume x h₁ h₂, zero_le _
lemma sum_le_sum_of_ne_zero (h : ∀x∈s₁, f x ≠ 0 → x ∈ s₂) : s₁.sum f ≤ s₂.sum f :=
calc s₁.sum f = (s₁.filter (λx, f x = 0)).sum f + (s₁.filter (λx, f x ≠ 0)).sum f :
by rw [←sum_union, filter_union_filter_neg_eq]; apply filter_inter_filter_neg_eq
... ≤ s₂.sum f : add_le_of_nonpos_of_le'
(sum_le_zero' $ by simp {contextual:=tt})
(sum_le_sum_of_subset $ by simp [subset_iff, *] {contextual:=tt})
end canonically_ordered_monoid
section discrete_linear_ordered_field
variables [discrete_linear_ordered_field α] [decidable_eq β]
lemma abs_sum_le_sum_abs {f : β → α} {s : finset β} : abs (s.sum f) ≤ s.sum (λa, abs (f a)) :=
finset.induction_on s (by simp [abs_zero]) $
assume a s has ih,
calc abs (sum (insert a s) f) ≤ abs (f a) + abs (sum s f) :
by simp [has]; exact abs_add_le_abs_add_abs _ _
... ≤ abs (f a) + s.sum (λa, abs (f a)) : add_le_add (le_refl _) ih
... ≤ sum (insert a s) (λ (a : β), abs (f a)) : by simp [has]
end discrete_linear_ordered_field
end finset
section group
open list
variables [group α] [group β]
theorem is_group_hom.prod {f : α → β} (H : is_group_hom f) (l : list α) :
f (prod l) = prod (map f l) :=
by induction l; simp [*, H.mul, H.one]
theorem is_group_anti_hom.prod {f : α → β} (H : is_group_anti_hom f) (l : list α) :
f (prod l) = prod (map f (reverse l)) :=
by induction l; simp [*, H.mul, H.one]
theorem inv_prod : ∀ l : list α, (prod l)⁻¹ = prod (map (λ x, x⁻¹) (reverse l)) :=
inv_is_group_anti_hom.prod
end group
|
c6e6f3267797baaf41d1e0ef3e6812da4e07ff61 | 26ac254ecb57ffcb886ff709cf018390161a9225 | /src/ring_theory/algebraic.lean | 7f826f66fb8a6b3c1e15f80e2715f4e7193d10a1 | [
"Apache-2.0"
] | permissive | eric-wieser/mathlib | 42842584f584359bbe1fc8b88b3ff937c8acd72d | d0df6b81cd0920ad569158c06a3fd5abb9e63301 | refs/heads/master | 1,669,546,404,255 | 1,595,254,668,000 | 1,595,254,668,000 | 281,173,504 | 0 | 0 | Apache-2.0 | 1,595,263,582,000 | 1,595,263,581,000 | null | UTF-8 | Lean | false | false | 4,692 | lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import linear_algebra.finite_dimensional
import ring_theory.integral_closure
import data.polynomial.field_division
/-!
# Algebraic elements and algebraic extensions
An element of an R-algebra is algebraic over R if it is the root of a nonzero polynomial.
An R-algebra is algebraic over R if and only if all its elements are algebraic over R.
The main result in this file proves transitivity of algebraicity:
a tower of algebraic field extensions is algebraic.
-/
universe variables u v
open_locale classical
open polynomial
section
variables (R : Type u) {A : Type v} [comm_ring R] [comm_ring A] [algebra R A]
/-- An element of an R-algebra is algebraic over R if it is the root of a nonzero polynomial. -/
def is_algebraic (x : A) : Prop :=
∃ p : polynomial R, p ≠ 0 ∧ aeval R A x p = 0
variables {R}
/-- A subalgebra is algebraic if all its elements are algebraic. -/
def subalgebra.is_algebraic (S : subalgebra R A) : Prop := ∀ x ∈ S, is_algebraic R x
variables (R A)
/-- An algebra is algebraic if all its elements are algebraic. -/
def algebra.is_algebraic : Prop := ∀ x : A, is_algebraic R x
variables {R A}
/-- A subalgebra is algebraic if and only if it is algebraic an algebra. -/
lemma subalgebra.is_algebraic_iff (S : subalgebra R A) :
S.is_algebraic ↔ @algebra.is_algebraic R S _ _ (S.algebra) :=
begin
delta algebra.is_algebraic subalgebra.is_algebraic,
rw [subtype.forall'],
apply forall_congr, rintro ⟨x, hx⟩,
apply exists_congr, intro p,
apply and_congr iff.rfl,
have h : function.injective (S.val) := subtype.val_injective,
conv_rhs { rw [← h.eq_iff, alg_hom.map_zero], },
rw [← aeval_alg_hom_apply, S.val_apply, subtype.val_eq_coe],
end
/-- An algebra is algebraic if and only if it is algebraic as a subalgebra. -/
lemma algebra.is_algebraic_iff : algebra.is_algebraic R A ↔ (⊤ : subalgebra R A).is_algebraic :=
begin
delta algebra.is_algebraic subalgebra.is_algebraic,
simp only [algebra.mem_top, forall_prop_of_true, iff_self],
end
end
section zero_ne_one
variables (R : Type u) {A : Type v} [comm_ring R] [nontrivial R] [comm_ring A] [algebra R A]
/-- An integral element of an algebra is algebraic.-/
lemma is_integral.is_algebraic {x : A} (h : is_integral R x) : is_algebraic R x :=
by { rcases h with ⟨p, hp, hpx⟩, exact ⟨p, hp.ne_zero, hpx⟩ }
end zero_ne_one
section field
variables (K : Type u) {A : Type v} [field K] [comm_ring A] [algebra K A]
/-- An element of an algebra over a field is algebraic if and only if it is integral.-/
lemma is_algebraic_iff_is_integral {x : A} :
is_algebraic K x ↔ is_integral K x :=
begin
refine ⟨_, is_integral.is_algebraic K⟩,
rintro ⟨p, hp, hpx⟩,
refine ⟨_, monic_mul_leading_coeff_inv hp, _⟩,
rw [alg_hom.map_mul, hpx, zero_mul],
end
end field
namespace algebra
variables {K : Type*} {L : Type*} {A : Type*}
variables [field K] [field L] [comm_ring A]
variables [algebra K L] [algebra L A] [algebra K A] [is_algebra_tower K L A]
/-- If L is an algebraic field extension of K and A is an algebraic algebra over L,
then A is algebraic over K. -/
lemma is_algebraic_trans (L_alg : is_algebraic K L) (A_alg : is_algebraic L A) :
is_algebraic K A :=
begin
simp only [is_algebraic, is_algebraic_iff_is_integral] at L_alg A_alg ⊢,
exact is_integral_trans L_alg A_alg,
end
/-- A field extension is algebraic if it is finite. -/
lemma is_algebraic_of_finite [finite : finite_dimensional K L] : is_algebraic K L :=
λ x, (is_algebraic_iff_is_integral _).mpr (is_integral_of_noetherian ⊤
(is_noetherian_of_submodule_of_noetherian _ _ _ finite) x algebra.mem_top)
end algebra
variables {R S : Type*} [integral_domain R] [comm_ring S]
lemma exists_integral_multiple [algebra R S] {z : S} (hz : is_algebraic R z)
(inj : ∀ x, algebra_map R S x = 0 → x = 0) :
∃ (x : integral_closure R S) (y ≠ (0 : integral_closure R S)),
z * y = x :=
begin
rcases hz with ⟨p, p_ne_zero, px⟩,
set n := p.nat_degree with n_def,
set a := p.leading_coeff with a_def,
have a_ne_zero : a ≠ 0 := mt polynomial.leading_coeff_eq_zero.mp p_ne_zero,
have y_integral : is_integral R (algebra_map R S a) := is_integral_algebra_map,
have x_integral : is_integral R (z * algebra_map R S a) :=
⟨ p.integral_normalization,
monic_integral_normalization p_ne_zero,
integral_normalization_aeval_eq_zero p_ne_zero px inj ⟩,
refine ⟨⟨_, x_integral⟩, ⟨_, y_integral⟩, _, rfl⟩,
exact λ h, a_ne_zero (inj _ (subtype.ext_iff_val.mp h))
end
|
1de15a31042f859af53d6a5fcd68a4f23fffc6ce | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /stage0/src/Lean/PrettyPrinter/Delaborator.lean | 41be185991bdf8ac4e9ee0d6718303ea97d9ae2d | [
"Apache-2.0"
] | permissive | WojciechKarpiel/lean4 | 7f89706b8e3c1f942b83a2c91a3a00b05da0e65b | f6e1314fa08293dea66a329e05b6c196a0189163 | refs/heads/master | 1,686,633,402,214 | 1,625,821,189,000 | 1,625,821,258,000 | 384,640,886 | 0 | 0 | Apache-2.0 | 1,625,903,617,000 | 1,625,903,026,000 | null | UTF-8 | Lean | false | false | 251 | lean | /-
Copyright (c) 2020 Sebastian Ullrich. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
-/
import Lean.PrettyPrinter.Delaborator.Basic
import Lean.PrettyPrinter.Delaborator.Builtins
|
9cd47747d47281a5912a6494753fe67a73d23bc6 | e00ea76a720126cf9f6d732ad6216b5b824d20a7 | /src/category_theory/functor.lean | 46ae92f320764c2fafd3335c624da874b9dfd0ce | [
"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 | 3,478 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Tim Baumann, Stephen Morgan, Scott Morrison
Defines a functor between categories.
(As it is a 'bundled' object rather than the `is_functorial` typeclass parametrised
by the underlying function on objects, the name is capitalised.)
Introduces notations
`C ⥤ D` for the type of all functors from `C` to `D`.
(I would like a better arrow here, unfortunately ⇒ (`\functor`) is taken by core.)
-/
import category_theory.category tactic.reassoc_axiom
namespace category_theory
universes v v₁ v₂ v₃ u u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation
/--
`functor C D` represents a functor between categories `C` and `D`.
To apply a functor `F` to an object use `F.obj X`, and to a morphism use `F.map f`.
The axiom `map_id` expresses preservation of identities, and
`map_comp` expresses functoriality.
-/
structure functor (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] :
Type (max v₁ v₂ u₁ u₂) :=
(obj : C → D)
(map : Π {X Y : C}, (X ⟶ Y) → ((obj X) ⟶ (obj Y)))
(map_id' : ∀ (X : C), map (𝟙 X) = 𝟙 (obj X) . obviously)
(map_comp' : ∀ {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z), map (f ≫ g) = (map f) ≫ (map g) . obviously)
-- A functor is basically a function, so give ⥤ a similar precedence to → (25).
-- For example, `C × D ⥤ E` should parse as `(C × D) ⥤ E` not `C × (D ⥤ E)`.
infixr ` ⥤ `:26 := functor -- type as \func --
restate_axiom functor.map_id'
attribute [simp] functor.map_id
restate_axiom functor.map_comp'
attribute [reassoc, simp] functor.map_comp
namespace functor
section
variables (C : Type u₁) [𝒞 : category.{v₁} C]
include 𝒞
/-- `𝟭 C` is the identity functor on a category `C`. -/
protected def id : C ⥤ C :=
{ obj := λ X, X,
map := λ _ _ f, f }
notation `𝟭` := functor.id
variable {C}
@[simp] lemma id_obj (X : C) : (𝟭 C).obj X = X := rfl
@[simp] lemma id_map {X Y : C} (f : X ⟶ Y) : (𝟭 C).map f = f := rfl
end
section
variables {C : Type u₁} [𝒞 : category.{v₁} C]
{D : Type u₂} [𝒟 : category.{v₂} D]
{E : Type u₃} [ℰ : category.{v₃} E]
include 𝒞 𝒟 ℰ
/--
`F ⋙ G` is the composition of a functor `F` and a functor `G` (`F` first, then `G`).
-/
def comp (F : C ⥤ D) (G : D ⥤ E) : C ⥤ E :=
{ obj := λ X, G.obj (F.obj X),
map := λ _ _ f, G.map (F.map f) }
infixr ` ⋙ `:80 := comp
@[simp] lemma comp_obj (F : C ⥤ D) (G : D ⥤ E) (X : C) : (F ⋙ G).obj X = G.obj (F.obj X) := rfl
@[simp] lemma comp_map (F : C ⥤ D) (G : D ⥤ E) {X Y : C} (f : X ⟶ Y) :
(F ⋙ G).map f = G.map (F.map f) := rfl
omit ℰ
-- These are not simp lemmas because rewriting along equalities between functors
-- is not necessarily a good idea.
-- Natural isomorphisms are also provided in `whiskering.lean`.
protected lemma comp_id (F : C ⥤ D) : F ⋙ (𝟭 D) = F := by cases F; refl
protected lemma id_comp (F : C ⥤ D) : (𝟭 C) ⋙ F = F := by cases F; refl
end
section
variables (C : Type u₁) [𝒞 : category.{v₁} C]
include 𝒞
@[simp] def ulift_down : (ulift.{u₂} C) ⥤ C :=
{ obj := λ X, X.down,
map := λ X Y f, f }
@[simp] def ulift_up : C ⥤ (ulift.{u₂} C) :=
{ obj := λ X, ⟨ X ⟩,
map := λ X Y f, f }
end
end functor
end category_theory
|
9013cc2bfdce6b7bf1325b8f2a71ca700231da3c | 5ec8f5218a7c8e87dd0d70dc6b715b36d61a8d61 | /ast.lean | 0baa7a2d7efb77b6a663438badad9b8721235551 | [] | no_license | mbrodersen/kremlin | f9f2f9dd77b9744fe0ffd5f70d9fa0f1f8bd8cec | d4665929ce9012e93a0b05fc7063b96256bab86f | refs/heads/master | 1,624,057,268,130 | 1,496,957,084,000 | 1,496,957,084,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 22,852 | lean | import .lib .integers .floats .maps .errors
namespace ast
open integers maps errors floats
/- * Syntactic elements -/
/- Identifiers (names of local variables, of global symbols and functions,
etc) are represented by the type [positive] of positive integers. -/
def ident := pos_num
instance pos_num_eq : decidable_eq pos_num := by tactic.mk_dec_eq_instance
instance ident_eq : decidable_eq ident := by tactic.mk_dec_eq_instance
/- The intermediate languages are weakly typed, using the following types: -/
inductive typ : Type
| Tint /- 32-bit integers or pointers -/
| Tfloat /- 64-bit double-precision floats -/
| Tlong /- 64-bit integers -/
| Tsingle /- 32-bit single-precision floats -/
| Tany32 /- any 32-bit value -/
| Tany64 /- any 64-bit value, i.e. any value -/
def typ.Tptr : typ := if archi.ptr64 then typ.Tlong else typ.Tint
open typ
instance typ_eq : decidable_eq typ := by tactic.mk_dec_eq_instance
def typesize : typ → ℤ
| Tint := 4
| Tfloat := 8
| Tlong := 8
| Tsingle := 4
| Tany32 := 4
| Tany64 := 8
lemma typesize_pos (ty) : typesize ty > 0 :=
by cases ty; exact dec_trivial
lemma typesize_Tptr : typesize Tptr = if archi.ptr64 then 8 else 4 :=
by delta Tptr; cases archi.ptr64; refl
/- All values of size 32 bits are also of type [Tany32]. All values
are of type [Tany64]. This corresponds to the following subtyping
relation over types. -/
def subtype : typ → typ → bool
| Tint Tint := tt
| Tlong Tlong := tt
| Tfloat Tfloat := tt
| Tsingle Tsingle := tt
| Tint Tany32 := tt
| Tsingle Tany32 := tt
| Tany32 Tany32 := tt
| _ Tany64 := tt
| _ _ := ff
def subtype_list : list typ → list typ → bool
| [] [] := tt
| (ty1::tys1) (ty2::tys2) := subtype ty1 ty2 && subtype_list tys1 tys2
| _ _ := ff
/- Additionally, function definitions and function calls are annotated
by function signatures indicating:
- the number and types of arguments;
- the type of the returned value, if any;
- additional information on which calling convention to use.
These signatures are used in particular to determine appropriate
calling conventions for the function. -/
structure calling_convention : Type := mkcallconv ::
(cc_vararg : bool) /- variable-arity function -/
(cc_unproto : bool) /- old-style unprototyped function -/
(cc_structret : bool) /- function returning a struct -/
instance calling_convention_eq : decidable_eq calling_convention := by tactic.mk_dec_eq_instance
def cc_default : calling_convention :=
{ cc_vararg := false, cc_unproto := false, cc_structret := false }
structure signature : Type :=
(sig_args : list typ)
(sig_res : option typ)
(sig_cc : calling_convention)
def proj_sig_res (s : signature) : typ :=
s.sig_res.get_or_else Tint
instance signature_eq : decidable_eq signature := by tactic.mk_dec_eq_instance
def signature_main : signature :=
{ sig_args := [], sig_res := some Tint, sig_cc := cc_default }
/- Memory accesses (load and store instructions) are annotated by
a ``memory chunk'' indicating the type, size and signedness of the
chunk of memory being accessed. -/
inductive memory_chunk : Type
| Mint8signed /- 8-bit signed integer -/
| Mint8unsigned /- 8-bit unsigned integer -/
| Mint16signed /- 16-bit signed integer -/
| Mint16unsigned /- 16-bit unsigned integer -/
| Mint32 /- 32-bit integer, or pointer -/
| Mint64 /- 64-bit integer -/
| Mfloat32 /- 32-bit single-precision float -/
| Mfloat64 /- 64-bit double-precision float -/
| Many32 /- any value that fits in 32 bits -/
| Many64 /- any value -/
open memory_chunk
instance chunk_eq : decidable_eq memory_chunk := by tactic.mk_dec_eq_instance
def Mptr : memory_chunk := if archi.ptr64 then Mint64 else Mint32.
/- The type (integer/pointer or float) of a chunk. -/
def memory_chunk.type : memory_chunk → typ
| Mint8signed := Tint
| Mint8unsigned := Tint
| Mint16signed := Tint
| Mint16unsigned := Tint
| Mint32 := Tint
| Mint64 := Tlong
| Mfloat32 := Tsingle
| Mfloat64 := Tfloat
| Many32 := Tany32
| Many64 := Tany64
lemma memory_chunk.Mptr.type : Mptr.type = Tptr :=
by delta Mptr Tptr; cases archi.ptr64; refl
def chunk_of_type : typ → memory_chunk
| Tint := Mint32
| Tfloat := Mfloat64
| Tlong := Mint64
| Tsingle := Mfloat32
| Tany32 := Many32
| Tany64 := Many64
lemma chunk_of_Tptr : chunk_of_type Tptr = Mptr :=
by delta Mptr Tptr; cases archi.ptr64; refl
/- * Properties of memory chunks -/
/- Memory reads and writes are performed by quantities called memory chunks,
encoding the type, size and signedness of the chunk being addressed.
The following functions extract the size information from a chunk. -/
def memory_chunk.size : memory_chunk → ℕ
| Mint8signed := 1
| Mint8unsigned := 1
| Mint16signed := 2
| Mint16unsigned := 2
| Mint32 := 4
| Mint64 := 8
| Mfloat32 := 4
| Mfloat64 := 8
| Many32 := 4
| Many64 := 8
lemma memory_chunk.size_pos (chunk) : memory_chunk.size chunk > 0 :=
by cases chunk; exact dec_trivial
lemma memory_chunk.Mptr.size_eq : Mptr.size = if archi.ptr64 then 8 else 4 :=
by delta Mptr; cases archi.ptr64; refl
/- Memory reads and writes must respect alignment constraints:
the byte offset of the location being addressed should be an exact
multiple of the natural alignment for the chunk being addressed.
This natural alignment is defined by the following
[align_chunk] function. Some target architectures
(e.g. PowerPC and x86) have no alignment constraints, which we could
reflect by taking [align_chunk chunk = 1]. However, other architectures
have stronger alignment requirements. The following definition is
appropriate for PowerPC, ARM and x86. -/
def memory_chunk.align : memory_chunk → ℕ
| Mint8signed := 1
| Mint8unsigned := 1
| Mint16signed := 2
| Mint16unsigned := 2
| Mint32 := 4
| Mint64 := 8
| Mfloat32 := 4
| Mfloat64 := 4
| Many32 := 4
| Many64 := 4
lemma memory_chunk.align_pos (chunk) : memory_chunk.align chunk > 0 :=
by cases chunk; exact dec_trivial
lemma memory_chunk.Mptr.align : Mptr.align = if archi.ptr64 then 8 else 4 :=
by delta Mptr; cases archi.ptr64; refl
lemma align_size_chunk_dvd (chunk : memory_chunk) : chunk.align ∣ chunk.size := sorry'
lemma align_le_dvd (chunk1 chunk2 : memory_chunk) (h : chunk1.align ≤ chunk2.align) :
chunk1.align ∣ chunk2.align := sorry'
/- Initialization data for global variables. -/
inductive init_data : Type
| int8 : int32 → init_data
| int16 : int32 → init_data
| int32 : int32 → init_data
| int64 : int64 → init_data
| float32 : float32 → init_data
| float64 : float → init_data
| space : ℕ → init_data
| addrof : ident → ptrofs → init_data /- address of symbol + offset -/
namespace init_data
def size : init_data → ℕ
| (int8 _) := 1
| (int16 _) := 2
| (int32 _) := 4
| (int64 _) := 8
| (float32 _) := 4
| (float64 _) := 8
| (addrof _ _) := if archi.ptr64 then 8 else 4
| (space n) := n
def align : init_data → ℕ
| (int8 _) := 1
| (int16 _) := 2
| (int32 _) := 4
| (int64 _) := 8
| (float32 _) := 4
| (float64 _) := 4
| (addrof _ _) := if archi.ptr64 then 8 else 4
| (space _) := 1
def list_size : list init_data → ℕ
| [] := 0
| (i :: il') := i.size + list_size il'
lemma size_pos (i : init_data) : i.size ≥ 0 := sorry'
lemma list_size_pos (il) : list_size il ≥ 0 := sorry'
def list_aligned : ℕ → list init_data → Prop
| p [] := true
| p (i1 :: il) := i1.align ∣ p ∧ list_aligned (p + i1.size) il
end init_data
/- Information attached to global variables. -/
structure globvar (V : Type) : Type :=
(info : V) /- language-dependent info, e.g. a type -/
(init : list init_data) /- initialization data -/
(readonly : bool) /- read-only variable? (const) -/
(volatile : bool) /- volatile variable? -/
/- Whole programs consist of:
- a collection of global definitions (name and description);
- a set of public names (the names that are visible outside
this compilation unit);
- the name of the ``main'' function that serves as entry point in the program.
A global definition is either a global function or a global variable.
The type of function descriptions and that of additional information
for variables vary among the various intermediate languages and are
taken as parameters to the [program] type. The other parts of whole
programs are common to all languages. -/
inductive globdef (F V : Type) : Type
| Gfun {} (f : F) : globdef
| Gvar {} (v : globvar V) : globdef
export globdef
structure program (F V : Type) : Type :=
(defs : list (ident × globdef F V))
(public : list ident)
(main : ident)
def program.defs_names {F V : Type} (p : program F V) : list ident :=
p.defs.map prod.fst
/- The "definition map" of a program maps names of globals to their definitions.
If several definitions have the same name, the one appearing last in [p.defs] wins. -/
section defmap
variables {F V : Type}
variable p : program F V
def prog_defmap : PTree (globdef F V) :=
PTree.of_list p.defs
lemma in_prog_defmap {id : ident} {g} : (prog_defmap p ^! id) = some g →
(id, g) ∈ p.defs := sorry'
lemma prog_defmap_dom {id : ident} : id ∈ p.defs_names →
∃ g, (prog_defmap p^!id) = some g := sorry'
lemma prog_defmap_unique (defs1 id g defs2) :
p.defs = defs1 ++ (id, g) :: defs2 →
id ∉ defs2.map prod.fst →
(prog_defmap p^!id) = some g := sorry'
lemma prog_defmap_nodup {id : ident} {g} :
p.defs_names.nodup →
(id, g) ∈ p.defs →
(prog_defmap p ^! id) = some g := sorry'
end defmap
/- * Generic transformations over programs -/
/- We now define a general iterator over programs that applies a given
code transformation function to all function descriptions and leaves
the other parts of the program unchanged. -/
section transf_program
parameters {A B V : Type} (transf : A → B)
def transform_program_globdef : ident × globdef A V → ident × globdef B V
| (id, Gfun f) := (id, Gfun (transf f))
| (id, Gvar v) := (id, Gvar v)
def transform_program : program A V → program B V
| ⟨defs, pub, main⟩ := ⟨defs.map transform_program_globdef, pub, main⟩
end transf_program
/- The following is a more general presentation of [transform_program]:
- Global variable information can be transformed, in addition to function
definitions.
- The transformation functions can fail and return an error message.
- The transformation for function definitions receives a global context
(derived from the compilation unit being transformed) as additiona
argument.
- The transformation functions receive the name of the global as
additional argument. -/
section transf_program_gen
parameters {A B V W : Type}
parameter transf_fun : ident → A → res B.
parameter transf_var : ident → V → res W.
def transf_globvar (i : ident) : globvar V → res (globvar W)
| ⟨info, init, ro, vo⟩ := do info' ← transf_var i info, OK ⟨info', init, ro, vo⟩
def transf_globdefs : list (ident × globdef A V) → res (list (ident × globdef B W))
| [] := OK []
| ((id, Gfun f) :: l') :=
match transf_fun id f with
| error msg := error (MSG "In function " :: CTX id :: MSG ": " :: msg)
| OK tf :=
do tl' ← transf_globdefs l', OK ((id, Gfun tf) :: tl')
end
| ((id, Gvar v) :: l') :=
match transf_globvar id v with
| error msg := error (MSG "In variable " :: CTX id :: MSG ": " :: msg)
| OK tv :=
do tl' ← transf_globdefs l', OK ((id, Gvar tv) :: tl')
end
def transform_partial_program2 : program A V → res (program B W)
| ⟨defs, pub, main⟩ := do gl' ← transf_globdefs defs, OK ⟨gl', pub, main⟩
end transf_program_gen
/- The following is a special case of [transform_partial_program2],
where only function definitions are transformed, but not variable definitions. -/
def transform_partial_program {A B V} (transf_fun : A → res B) : program A V → res (program B V) :=
transform_partial_program2 (λ i, transf_fun) (λ i, OK)
lemma transform_program_partial_program {A B V} (transf_fun : A → B) (p : program A V) :
transform_partial_program (λ f, OK (transf_fun f)) p = OK (transform_program transf_fun p) := sorry'
/- * External functions -/
/- For most languages, the functions composing the program are either
internal functions, defined within the language, or external functions,
defined outside. External functions include system calls but also
compiler built-in functions. We define a type for external functions
and associated operations. -/
inductive external_function : Type
| EF_external (name : string) (sg : signature)
/- A system call or library function. Produces an event
in the trace. -/
| EF_builtin (name : string) (sg : signature)
/- A compiler built-in function. Behaves like an external, but
can be inlined by the compiler. -/
| EF_runtime (name : string) (sg : signature)
/- A function from the run-time library. Behaves like an
external, but must not be redefined. -/
| EF_vload (chunk : memory_chunk)
/- A volatile read operation. If the adress given as first argument
points within a volatile global variable, generate an
event and return the value found in this event. Otherwise,
produce no event and behave like a regular memory load. -/
| EF_vstore (chunk : memory_chunk)
/- A volatile store operation. If the adress given as first argument
points within a volatile global variable, generate an event.
Otherwise, produce no event and behave like a regular memory store. -/
| EF_malloc
/- Dynamic memory allocation. Takes the requested size in bytes
as argument; returns a pointer to a fresh block of the given size.
Produces no observable event. -/
| EF_free
/- Dynamic memory deallocation. Takes a pointer to a block
allocated by an [EF_malloc] external call and frees the
corresponding block.
Produces no observable event. -/
| EF_memcpy (sz al : ℕ)
/- Block copy, of [sz] bytes, between addresses that are [al]-aligned. -/
| EF_annot (text : string) (targs : list typ)
/- A programmer-supplied annotation. Takes zero, one or several arguments,
produces an event carrying the text and the values of these arguments,
and returns no value. -/
| EF_annot_val (text : string) (targ : typ)
/- Another form of annotation that takes one argument, produces
an event carrying the text and the value of this argument,
and returns the value of the argument. -/
| EF_inline_asm (text : string) (sg : signature) (clobbers : list string)
/- Inline [asm] statements. Semantically, treated like an
annotation with no parameters ([EF_annot text nil]). To be
used with caution, as it can invalidate the semantic
preservation theorem. Generated only if [-finline-asm] is
given. -/
| EF_debug (kind : pos_num) (text : ident) (targs : list typ)
/- Transport debugging information from the front-end to the generated
assembly. Takes zero, one or several arguments like [EF_annot].
Unlike [EF_annot], produces no observable event. -/
export external_function
/- The type signature of an external function. -/
def ef_sig : external_function → signature
| (EF_external name sg) := sg
| (EF_builtin name sg) := sg
| (EF_runtime name sg) := sg
| (EF_vload chunk) := ⟨[Tptr], some chunk.type, cc_default⟩
| (EF_vstore chunk) := ⟨[Tptr, chunk.type], none, cc_default⟩
| (EF_malloc) := ⟨[Tptr], some Tptr, cc_default⟩
| (EF_free) := ⟨[Tptr], none, cc_default⟩
| (EF_memcpy sz al) := ⟨[Tptr, Tptr], none, cc_default⟩
| (EF_annot text targs) := ⟨targs, none, cc_default⟩
| (EF_annot_val text targ) := ⟨[Tptr], some targ, cc_default⟩
| (EF_inline_asm text sg clob) := sg
| (EF_debug kind text targs) := ⟨targs, none, cc_default⟩
/- Whether an external function should be inlined by the compiler. -/
def ef_inline : external_function → bool
| (EF_external name sg) := ff
| (EF_builtin name sg) := tt
| (EF_runtime name sg) := ff
| (EF_vload chunk) := tt
| (EF_vstore chunk) := tt
| (EF_malloc) := ff
| (EF_free) := ff
| (EF_memcpy sz al) := tt
| (EF_annot text targs) := tt
| (EF_annot_val text targ) := tt
| (EF_inline_asm text sg clob) := tt
| (EF_debug kind text targs) := tt
/- Whether an external function must reload its arguments. -/
def ef_reloads : external_function → bool
| (EF_annot text targs) := ff
| (EF_debug kind text targs) := ff
| _ := tt
/- Equality between external functions. Used in module [Allocation]. -/
instance external_function_eq : decidable_eq external_function := by tactic.mk_dec_eq_instance
/- Function definitions are the union of internal and external functions. -/
inductive fundef (F : Type) : Type
| Internal {} : F → fundef
| External {} : external_function → fundef
open fundef
section transf_fundef
parameters {A B : Type} (transf : A → B)
def transf_fundef : fundef A → fundef B
| (Internal f) := Internal (transf f)
| (External ef) := External ef
end transf_fundef
section transf_partial_fundef
parameters {A B : Type} (transf_partial : A → res B)
def transf_partial_fundef : fundef A → res (fundef B)
| (Internal f) := do f' ← transf_partial f, OK (Internal f')
| (External ef) := OK (External ef)
end transf_partial_fundef
/- * Register pairs -/
/- In some intermediate languages (LTL, Mach), 64-bit integers can be
split into two 32-bit halves and held in a pair of registers.
Syntactically, this is captured by the type [rpair] below. -/
inductive rpair (A : Type) : Type
| One (r : A) : rpair
| Twolong (rhi rlo : A) : rpair
open rpair
def typ_rpair {A} (typ_of : A → typ) : rpair A → typ
| (One r) := typ_of r
| (Twolong rhi rlo) := Tlong
def map_rpair {A B} (f : A → B) : rpair A → rpair B
| (One r) := One (f r)
| (Twolong rhi rlo) := Twolong (f rhi) (f rlo)
def regs_of_rpair {A} : rpair A → list A
| (One r) := [r]
| (Twolong rhi rlo) := [rhi, rlo]
def regs_of_rpairs {A} : list (rpair A) → list A
| [] := []
| (p :: l) := regs_of_rpair p ++ regs_of_rpairs l
lemma in_regs_of_rpair {A} (x : A) (p) (hm : x ∈ regs_of_rpair p) (l : list (rpair A)) (hp : p ∈ l) :
x ∈ regs_of_rpairs l := sorry'
lemma in_regs_of_rpairs_inv {A} (x : A) (l : list (rpair A)) (hm : x ∈ regs_of_rpairs l) :
∃ p, p ∈ l ∧ x ∈ regs_of_rpair p := sorry'
def forall_rpair {A} (P : A → Prop) : rpair A → Prop
| (One r) := P r
| (Twolong rhi rlo) := P rhi ∧ P rlo
/- * Arguments and results to builtin functions -/
inductive builtin_arg (A : Type) : Type
| BA {} (x : A) : builtin_arg
| BA_int {} (n : int32) : builtin_arg
| BA_long {} (n : int64) : builtin_arg
| BA_float {} (f : float) : builtin_arg
| BA_single {} (f : float32) : builtin_arg
| BA_loadstack {} (chunk : memory_chunk) (ofs : ptrofs) : builtin_arg
| BA_addrstack {} (ofs : ptrofs) : builtin_arg
| BA_loadglobal {} (chunk : memory_chunk) (id : ident) (ofs : ptrofs) : builtin_arg
| BA_addrglobal {} (id : ident) (ofs : ptrofs) : builtin_arg
| BA_splitlong {} (hi lo : builtin_arg) : builtin_arg
export builtin_arg
inductive builtin_res (A : Type) : Type
| BR {} (x : A) : builtin_res
| BR_none {} : builtin_res
| BR_splitlong {} (hi lo : builtin_res) : builtin_res
open builtin_res
def globals_of_builtin_arg {A : Type} : builtin_arg A → list ident
| (BA_loadglobal chunk id ofs) := [id]
| (BA_addrglobal id ofs) := [id]
| (BA_splitlong hi lo) := globals_of_builtin_arg hi ++ globals_of_builtin_arg lo
| _ := []
def globals_of_builtin_args {A} (al : list (builtin_arg A)) : list ident :=
al.foldr (λ a l, globals_of_builtin_arg a ++ l) []
def params_of_builtin_arg {A} : builtin_arg A → list A
| (BA x) := [x]
| (BA_splitlong hi lo) := params_of_builtin_arg hi ++ params_of_builtin_arg lo
| _ := []
def params_of_builtin_args {A} (al : list (builtin_arg A)) : list A :=
al.foldr (λ a l, params_of_builtin_arg a ++ l) []
def params_of_builtin_res {A} : builtin_res A → list A
| (BR x) := [x]
| BR_none := []
| (BR_splitlong hi lo) := params_of_builtin_res hi ++ params_of_builtin_res lo
def map_builtin_arg {A B} (f : A → B) : builtin_arg A → builtin_arg B
| (BA x) := BA (f x)
| (BA_int n) := BA_int n
| (BA_long n) := BA_long n
| (BA_float n) := BA_float n
| (BA_single n) := BA_single n
| (BA_loadstack chunk ofs) := BA_loadstack chunk ofs
| (BA_addrstack ofs) := BA_addrstack ofs
| (BA_loadglobal chunk id ofs) := BA_loadglobal chunk id ofs
| (BA_addrglobal id ofs) := BA_addrglobal id ofs
| (BA_splitlong hi lo) := BA_splitlong (map_builtin_arg hi) (map_builtin_arg lo)
def map_builtin_res {A B} (f : A → B) : builtin_res A → builtin_res B
| (BR x) := BR (f x)
| BR_none := BR_none
| (BR_splitlong hi lo) := BR_splitlong (map_builtin_res hi) (map_builtin_res lo)
/- Which kinds of builtin arguments are supported by which external function. -/
inductive builtin_arg_constraint : Type
| OK_default
| OK_const
| OK_addrstack
| OK_addrglobal
| OK_addrany
| OK_all
open builtin_arg_constraint
def builtin_arg_ok {A} : builtin_arg A → builtin_arg_constraint → bool
| (BA _) _ := tt
| (BA_splitlong (BA _) (BA _)) _ := tt
| (BA_int _) OK_const := tt
| (BA_long _) OK_const := tt
| (BA_float _) OK_const := tt
| (BA_single _) OK_const := tt
| (BA_addrstack _) OK_addrstack := tt
| (BA_addrstack _) OK_addrany := tt
| (BA_addrglobal _ _) OK_addrglobal := tt
| (BA_addrglobal _ _) OK_addrany := tt
| _ OK_all := tt
| _ _ := ff
end ast |
12e47981ae17a37b00a32207d4aa9970e0533a68 | 947b78d97130d56365ae2ec264df196ce769371a | /src/Lean/Elab/Tactic/Match.lean | 6000c9419715827b2cb4fe282fe0405347a96a8a | [
"Apache-2.0"
] | permissive | shyamalschandra/lean4 | 27044812be8698f0c79147615b1d5090b9f4b037 | 6e7a883b21eaf62831e8111b251dc9b18f40e604 | refs/heads/master | 1,671,417,126,371 | 1,601,859,995,000 | 1,601,860,020,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,108 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.Match
import Lean.Elab.Tactic.Basic
import Lean.Elab.Tactic.Induction
namespace Lean
namespace Elab
namespace Tactic
structure AuxMatchTermState :=
(nextIdx : Nat := 1)
(cases : Array Syntax := #[])
private def mkAuxiliaryMatchTermAux (parentTag : Name) (matchTac : Syntax) : StateT AuxMatchTermState MacroM Syntax := do
let matchAlts := matchTac.getArg 4;
let alts := (matchAlts.getArg 1).getArgs;
newAlts ← alts.mapSepElemsM fun alt => do {
let alt := alt.updateKind `Lean.Parser.Term.matchAlt;
let holeOrTacticSeq := alt.getArg 2;
if holeOrTacticSeq.isOfKind `Lean.Parser.Term.syntheticHole then
pure alt
else if holeOrTacticSeq.isOfKind `Lean.Parser.Term.hole then do
s ← get;
let holeName := mkIdentFrom holeOrTacticSeq (parentTag ++ (`match).appendIndexAfter s.nextIdx);
newHole ← `(?$holeName:ident);
modify fun s => { s with nextIdx := s.nextIdx + 1};
pure $ alt.setArg 2 newHole
else withFreshMacroScope do
newHole ← `(?rhs);
let newHoleId := newHole.getArg 1;
newCase ← `(tactic| case $newHoleId => $holeOrTacticSeq:tacticSeq );
modify fun s => { s with cases := s.cases.push newCase };
pure $ alt.setArg 2 newHole
};
let result := matchTac.updateKind `Lean.Parser.Term.match;
let result := result.setArg 4 (matchAlts.setArg 1 (mkNullNode newAlts));
pure result
private def mkAuxiliaryMatchTerm (parentTag : Name) (matchTac : Syntax) : MacroM (Syntax × Array Syntax) := do
(matchTerm, s) ← (mkAuxiliaryMatchTermAux parentTag matchTac).run {};
pure (matchTerm, s.cases)
@[builtinTactic Lean.Parser.Tactic.match] def evalMatch : Tactic :=
fun stx => do
tag ← getMainTag;
(matchTerm, cases) ← liftMacroM $ mkAuxiliaryMatchTerm tag stx;
refineMatchTerm ← `(tactic| refine $matchTerm);
let stxNew := mkNullNode (#[refineMatchTerm] ++ cases);
withMacroExpansion stx stxNew $ evalTactic stxNew
end Tactic
end Elab
end Lean
|
ffdcd79ee0700fdf9ece4f53588ffdcb1da30055 | 5fbbd711f9bfc21ee168f46a4be146603ece8835 | /lean/natural_number_game/power/3.lean | bf34026a944c10cc8af8c4ccf83427cf6b9981bf | [
"LicenseRef-scancode-warranty-disclaimer"
] | 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 | 110 | lean | lemma pow_one (a : mynat) : a ^ (1 : mynat) = a :=
rwa [one_eq_succ_zero, pow_succ, pow_zero, one_mul],
end
|
7efb5ca07dc27e71bf8c7e19be58898b8a8df8fc | 75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2 | /tests/lean/bad_namespace.lean | b5a3ba24beafbf35d60c14dd2950253226dcb9fd | [
"Apache-2.0"
] | permissive | jroesch/lean | 30ef0860fa905d35b9ad6f76de1a4f65c9af6871 | 3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2 | refs/heads/master | 1,586,090,835,348 | 1,455,142,203,000 | 1,455,142,277,000 | 51,536,958 | 1 | 0 | null | 1,455,215,811,000 | 1,455,215,811,000 | null | UTF-8 | Lean | false | false | 17 | lean | namespace _root_
|
fbf739a944edddb50f740fddd8a0cd67fe1bd86f | 1dd482be3f611941db7801003235dc84147ec60a | /src/topology/metric_space/basic.lean | 421f5c989585eca3dbcce27de6db9f3e78bcfe0a | [
"Apache-2.0"
] | permissive | sanderdahmen/mathlib | 479039302bd66434bb5672c2a4cecf8d69981458 | 8f0eae75cd2d8b7a083cf935666fcce4565df076 | refs/heads/master | 1,587,491,322,775 | 1,549,672,060,000 | 1,549,672,060,000 | 169,748,224 | 0 | 0 | Apache-2.0 | 1,549,636,694,000 | 1,549,636,694,000 | null | UTF-8 | Lean | false | false | 61,407 | lean | /-
Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Metric spaces.
Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel
Many definitions and theorems expected on metric spaces are already introduced on uniform spaces and
topological spaces. For example:
open and closed sets, compactness, completeness, continuity and uniform continuity
-/
import data.real.nnreal topology.algebra.topological_structures topology.metric_space.emetric_space
open lattice set filter classical topological_space
noncomputable theory
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
/-- Construct a uniform structure from a distance function and metric space axioms -/
def uniform_space_of_dist
(dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space α :=
uniform_space.of_core {
uniformity := (⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε}),
refl := le_infi $ assume ε, le_infi $
by simp [set.subset_def, id_rel, dist_self, (>)] {contextual := tt},
comp := le_infi $ assume ε, le_infi $ assume h, lift'_le
(mem_infi_sets (ε / 2) $ mem_infi_sets (div_pos_of_pos_of_pos h two_pos) (subset.refl _)) $
have ∀ (a b c : α), dist a c < ε / 2 → dist c b < ε / 2 → dist a b < ε,
from assume a b c hac hcb,
calc dist a b ≤ dist a c + dist c b : dist_triangle _ _ _
... < ε / 2 + ε / 2 : add_lt_add hac hcb
... = ε : by rw [div_add_div_same, add_self_div_two],
by simpa [comp_rel],
symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h,
tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [dist_comm] }
/-- The distance function (given an ambient metric space on `α`), which returns
a nonnegative real number `dist x y` given `x y : α`. -/
class has_dist (α : Type*) := (dist : α → α → ℝ)
export has_dist (dist)
/-- Metric space
Each metric space induces a canonical `uniform_space` and hence a canonical `topological_space`.
This is enforced in the type class definition, by extending the `uniform_space` structure. When
instantiating a `metric_space` structure, the uniformity fields are not necessary, they will be
filled in by default. In the same way, each metric space induces an emetric space structure.
It is included in the structure, but filled in by default.
When one instantiates a metric space structure, for instance a product structure,
this makes it possible to use a uniform structure and an edistance that are exactly
the ones for the uniform spaces product and the emetric spaces products, thereby
ensuring that everything in defeq in diamonds.-/
class metric_space (α : Type u) extends has_dist α : Type u :=
(dist_self : ∀ x : α, dist x x = 0)
(eq_of_dist_eq_zero : ∀ {x y : α}, dist x y = 0 → x = y)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z)
(edist : α → α → ennreal := λx y, ennreal.of_real (dist x y))
(edist_dist : ∀ x y : α, edist x y = ennreal.of_real (dist x y) . control_laws_tac)
(to_uniform_space : uniform_space α := uniform_space_of_dist dist dist_self dist_comm dist_triangle)
(uniformity_dist : uniformity = ⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε} . control_laws_tac)
variables [metric_space α]
instance metric_space.to_uniform_space' : uniform_space α :=
metric_space.to_uniform_space α
instance metric_space.to_has_edist : has_edist α := ⟨metric_space.edist⟩
@[simp] theorem dist_self (x : α) : dist x x = 0 := metric_space.dist_self x
theorem eq_of_dist_eq_zero {x y : α} : dist x y = 0 → x = y :=
metric_space.eq_of_dist_eq_zero
theorem dist_comm (x y : α) : dist x y = dist y x := metric_space.dist_comm x y
theorem edist_dist (x y : α) : edist x y = ennreal.of_real (dist x y) :=
metric_space.edist_dist _ x y
@[simp] theorem dist_eq_zero {x y : α} : dist x y = 0 ↔ x = y :=
iff.intro eq_of_dist_eq_zero (assume : x = y, this ▸ dist_self _)
@[simp] theorem zero_eq_dist {x y : α} : 0 = dist x y ↔ x = y :=
by rw [eq_comm, dist_eq_zero]
theorem dist_triangle (x y z : α) : dist x z ≤ dist x y + dist y z :=
metric_space.dist_triangle x y z
theorem dist_triangle_left (x y z : α) : dist x y ≤ dist z x + dist z y :=
by rw dist_comm z; apply dist_triangle
theorem dist_triangle_right (x y z : α) : dist x y ≤ dist x z + dist y z :=
by rw dist_comm y; apply dist_triangle
lemma dist_triangle4 (x y z w : α) :
dist x w ≤ dist x y + dist y z + dist z w :=
calc
dist x w ≤ dist x z + dist z w : dist_triangle x z w
... ≤ (dist x y + dist y z) + dist z w : add_le_add_right (metric_space.dist_triangle x y z) _
lemma dist_triangle4_left (x₁ y₁ x₂ y₂ : α) :
dist x₂ y₂ ≤ dist x₁ y₁ + (dist x₁ x₂ + dist y₁ y₂) :=
by rw [add_left_comm, dist_comm x₁, ← add_assoc]; apply dist_triangle4
lemma dist_triangle4_right (x₁ y₁ x₂ y₂ : α) :
dist x₁ y₁ ≤ dist x₁ x₂ + dist y₁ y₂ + dist x₂ y₂ :=
by rw [add_right_comm, dist_comm y₁]; apply dist_triangle4
theorem swap_dist : function.swap (@dist α _) = dist :=
by funext x y; exact dist_comm _ _
theorem abs_dist_sub_le (x y z : α) : abs (dist x z - dist y z) ≤ dist x y :=
abs_sub_le_iff.2
⟨sub_le_iff_le_add.2 (dist_triangle _ _ _),
sub_le_iff_le_add.2 (dist_triangle_left _ _ _)⟩
theorem dist_nonneg {x y : α} : 0 ≤ dist x y :=
have 2 * dist x y ≥ 0,
from calc 2 * dist x y = dist x y + dist y x : by rw [dist_comm x y, two_mul]
... ≥ 0 : by rw ← dist_self x; apply dist_triangle,
nonneg_of_mul_nonneg_left this two_pos
@[simp] theorem dist_le_zero {x y : α} : dist x y ≤ 0 ↔ x = y :=
by simpa [le_antisymm_iff, dist_nonneg] using @dist_eq_zero _ _ x y
@[simp] theorem dist_pos {x y : α} : 0 < dist x y ↔ x ≠ y :=
by simpa [-dist_le_zero] using not_congr (@dist_le_zero _ _ x y)
@[simp] theorem abs_dist {a b : α} : abs (dist a b) = dist a b :=
abs_of_nonneg dist_nonneg
theorem eq_of_forall_dist_le {x y : α} (h : ∀ε, ε > 0 → dist x y ≤ ε) : x = y :=
eq_of_dist_eq_zero (eq_of_le_of_forall_le_of_dense dist_nonneg h)
def nndist (a b : α) : nnreal := ⟨dist a b, dist_nonneg⟩
/--Express `nndist` in terms of `edist`-/
lemma nndist_edist (x y : α) : nndist x y = (edist x y).to_nnreal :=
by simp [nndist, edist_dist, nnreal.of_real, max_eq_left dist_nonneg, ennreal.of_real]
/--Express `edist` in terms of `nndist`-/
lemma edist_nndist (x y : α) : edist x y = ↑(nndist x y) :=
by simp [nndist, edist_dist, nnreal.of_real, max_eq_left dist_nonneg, ennreal.of_real]
/--In a metric space, the extended distance is always finite-/
lemma edist_ne_top (x y : α) : edist x y ≠ ⊤ :=
by rw [edist_dist x y]; apply ennreal.coe_ne_top
/--`nndist x x` vanishes-/
@[simp] lemma nndist_self (a : α) : nndist a a = 0 := (nnreal.coe_eq_zero _).1 (dist_self a)
/--Express `dist` in terms of `nndist`-/
lemma dist_nndist (x y : α) : dist x y = ↑(nndist x y) := rfl
/--Express `nndist` in terms of `dist`-/
lemma nndist_dist (x y : α) : nndist x y = nnreal.of_real (dist x y) :=
by rw [dist_nndist, nnreal.of_real_coe]
/--Deduce the equality of points with the vanishing of the nonnegative distance-/
theorem eq_of_nndist_eq_zero {x y : α} : nndist x y = 0 → x = y :=
by simp only [nnreal.eq_iff.symm, (dist_nndist _ _).symm, imp_self, nnreal.coe_zero, dist_eq_zero]
theorem nndist_comm (x y : α) : nndist x y = nndist y x :=
by simpa [nnreal.eq_iff.symm] using dist_comm x y
/--Characterize the equality of points with the vanishing of the nonnegative distance-/
@[simp] theorem nndist_eq_zero {x y : α} : nndist x y = 0 ↔ x = y :=
by simp only [nnreal.eq_iff.symm, (dist_nndist _ _).symm, imp_self, nnreal.coe_zero, dist_eq_zero]
@[simp] theorem zero_eq_nndist {x y : α} : 0 = nndist x y ↔ x = y :=
by simp only [nnreal.eq_iff.symm, (dist_nndist _ _).symm, imp_self, nnreal.coe_zero, zero_eq_dist]
/--Triangle inequality for the nonnegative distance-/
theorem nndist_triangle (x y z : α) : nndist x z ≤ nndist x y + nndist y z :=
by simpa [nnreal.coe_le] using dist_triangle x y z
theorem nndist_triangle_left (x y z : α) : nndist x y ≤ nndist z x + nndist z y :=
by simpa [nnreal.coe_le] using dist_triangle_left x y z
theorem nndist_triangle_right (x y z : α) : nndist x y ≤ nndist x z + nndist y z :=
by simpa [nnreal.coe_le] using dist_triangle_right x y z
/--Express `dist` in terms of `edist`-/
lemma dist_edist (x y : α) : dist x y = (edist x y).to_real :=
by rw [edist_dist, ennreal.to_real_of_real (dist_nonneg)]
namespace metric
/- instantiate metric space as a topology -/
variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α}
/-- `ball x ε` is the set of all points `y` with `dist y x < ε` -/
def ball (x : α) (ε : ℝ) : set α := {y | dist y x < ε}
@[simp] theorem mem_ball : y ∈ ball x ε ↔ dist y x < ε := iff.rfl
theorem mem_ball' : y ∈ ball x ε ↔ dist x y < ε := by rw dist_comm; refl
/-- `closed_ball x ε` is the set of all points `y` with `dist y x ≤ ε` -/
def closed_ball (x : α) (ε : ℝ) := {y | dist y x ≤ ε}
@[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ dist y x ≤ ε := iff.rfl
theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε :=
assume y, by simp; intros h; apply le_of_lt h
theorem pos_of_mem_ball (hy : y ∈ ball x ε) : ε > 0 :=
lt_of_le_of_lt dist_nonneg hy
theorem mem_ball_self (h : ε > 0) : x ∈ ball x ε :=
show dist x x < ε, by rw dist_self; assumption
theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε :=
by simp [dist_comm]
theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ :=
λ y (yx : _ < ε₁), lt_of_lt_of_le yx h
theorem closed_ball_subset_closed_ball {α : Type u} [metric_space α] {ε₁ ε₂ : ℝ} {x : α} (h : ε₁ ≤ ε₂) :
closed_ball x ε₁ ⊆ closed_ball x ε₂ :=
λ y (yx : _ ≤ ε₁), le_trans yx h
theorem ball_disjoint (h : ε₁ + ε₂ ≤ dist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ :=
eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩,
not_lt_of_le (dist_triangle_left x y z)
(lt_of_lt_of_le (add_lt_add h₁ h₂) h)
theorem ball_disjoint_same (h : ε ≤ dist x y / 2) : ball x ε ∩ ball y ε = ∅ :=
ball_disjoint $ by rwa [← two_mul, ← le_div_iff' two_pos]
theorem ball_subset (h : dist x y ≤ ε₂ - ε₁) : ball x ε₁ ⊆ ball y ε₂ :=
λ z zx, by rw ← add_sub_cancel'_right ε₁ ε₂; exact
lt_of_le_of_lt (dist_triangle z x y) (add_lt_add_of_lt_of_le zx h)
theorem ball_half_subset (y) (h : y ∈ ball x (ε / 2)) : ball y (ε / 2) ⊆ ball x ε :=
ball_subset $ by rw sub_self_div_two; exact le_of_lt h
theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε :=
⟨_, sub_pos.2 h, ball_subset $ by rw sub_sub_self⟩
theorem ball_eq_empty_iff_nonpos : ε ≤ 0 ↔ ball x ε = ∅ :=
(eq_empty_iff_forall_not_mem.trans
⟨λ h, le_of_not_gt $ λ ε0, h _ $ mem_ball_self ε0,
λ ε0 y h, not_lt_of_le ε0 $ pos_of_mem_ball h⟩).symm
theorem uniformity_dist : uniformity = (⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε}) :=
metric_space.uniformity_dist _
theorem uniformity_dist' : uniformity = (⨅ε:{ε:ℝ // ε>0}, principal {p:α×α | dist p.1 p.2 < ε.val}) :=
by simp [infi_subtype]; exact uniformity_dist
theorem mem_uniformity_dist {s : set (α×α)} :
s ∈ (@uniformity α _).sets ↔ (∃ε>0, ∀{a b:α}, dist a b < ε → (a, b) ∈ s) :=
begin
rw [uniformity_dist', infi_sets_eq],
simp [subset_def],
exact assume ⟨r, hr⟩ ⟨p, hp⟩, ⟨⟨min r p, lt_min hr hp⟩, by simp [lt_min_iff, (≥)] {contextual := tt}⟩,
exact ⟨⟨1, zero_lt_one⟩⟩
end
theorem dist_mem_uniformity {ε:ℝ} (ε0 : 0 < ε) :
{p:α×α | dist p.1 p.2 < ε} ∈ (@uniformity α _).sets :=
mem_uniformity_dist.2 ⟨ε, ε0, λ a b, id⟩
theorem uniform_continuous_iff [metric_space β] {f : α → β} :
uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0,
∀{a b:α}, dist a b < δ → dist (f a) (f b) < ε :=
uniform_continuous_def.trans
⟨λ H ε ε0, mem_uniformity_dist.1 $ H _ $ dist_mem_uniformity ε0,
λ H r ru,
let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨δ, δ0, hδ⟩ := H _ ε0 in
mem_uniformity_dist.2 ⟨δ, δ0, λ a b h, hε (hδ h)⟩⟩
theorem uniform_embedding_iff [metric_space β] {f : α → β} :
uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧
∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ :=
uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl
⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (dist_mem_uniformity δ0),
⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 tu in
⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩,
λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in
⟨_, dist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩
theorem totally_bounded_iff {s : set α} :
totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε :=
⟨λ H ε ε0, H _ (dist_mem_uniformity ε0),
λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru,
⟨t, ft, h⟩ := H ε ε0 in
⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩
/-- A metric space space is totally bounded if one can reconstruct up to any ε>0 any element of the
space from finitely many data. -/
lemma totally_bounded_of_finite_discretization {α : Type u} [metric_space α] {s : set α}
(H : ∀ε > (0 : ℝ), ∃ (β : Type u) [fintype β] (F : s → β),
∀x y, F x = F y → dist (x:α) y < ε) :
totally_bounded s :=
begin
classical, by_cases hs : s = ∅,
{ rw hs, exact totally_bounded_empty },
rcases exists_mem_of_ne_empty hs with ⟨x0, hx0⟩,
haveI : inhabited s := ⟨⟨x0, hx0⟩⟩,
refine totally_bounded_iff.2 (λ ε ε0, _),
rcases H ε ε0 with ⟨β, fβ, F, hF⟩,
let Finv := function.inv_fun F,
refine ⟨range (subtype.val ∘ Finv), finite_range _, λ x xs, _⟩,
let x' := Finv (F ⟨x, xs⟩),
have : F x' = F ⟨x, xs⟩ := function.inv_fun_eq ⟨⟨x, xs⟩, rfl⟩,
simp only [set.mem_Union, set.mem_range],
exact ⟨_, ⟨F ⟨x, xs⟩, rfl⟩, hF _ _ this.symm⟩
end
protected lemma cauchy_iff {f : filter α} :
cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f.sets, ∀ x y ∈ t, dist x y < ε :=
cauchy_iff.trans $ and_congr iff.rfl
⟨λ H ε ε0, let ⟨t, tf, ts⟩ := H _ (dist_mem_uniformity ε0) in
⟨t, tf, λ x y xt yt, @ts (x, y) ⟨xt, yt⟩⟩,
λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru,
⟨t, tf, h⟩ := H ε ε0 in
⟨t, tf, λ ⟨x, y⟩ ⟨hx, hy⟩, hε (h x y hx hy)⟩⟩
theorem nhds_eq : nhds x = (⨅ε:{ε:ℝ // ε>0}, principal (ball x ε.val)) :=
begin
rw [nhds_eq_uniformity, uniformity_dist', lift'_infi],
{ apply congr_arg, funext ε,
rw [lift'_principal],
{ simp [ball, dist_comm] },
{ exact monotone_preimage } },
{ exact ⟨⟨1, zero_lt_one⟩⟩ },
{ intros, refl }
end
theorem mem_nhds_iff : s ∈ (nhds x).sets ↔ ∃ε>0, ball x ε ⊆ s :=
begin
rw [nhds_eq, infi_sets_eq],
{ simp },
{ intros y z, cases y with y hy, cases z with z hz,
refine ⟨⟨min y z, lt_min hy hz⟩, _⟩,
simp [ball_subset_ball, min_le_left, min_le_right, (≥)] },
{ exact ⟨⟨1, zero_lt_one⟩⟩ }
end
theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s :=
by simp [is_open_iff_nhds, mem_nhds_iff]
theorem is_open_ball : is_open (ball x ε) :=
is_open_iff.2 $ λ y, exists_ball_subset_ball
theorem ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : ball x ε ∈ (nhds x).sets :=
mem_nhds_sets is_open_ball (mem_ball_self ε0)
theorem tendsto_nhds_nhds [metric_space β] {f : α → β} {a b} :
tendsto f (nhds a) (nhds b) ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) b < ε :=
⟨λ H ε ε0, mem_nhds_iff.1 (H (ball_mem_nhds _ ε0)),
λ H s hs,
let ⟨ε, ε0, hε⟩ := mem_nhds_iff.1 hs, ⟨δ, δ0, hδ⟩ := H _ ε0 in
mem_nhds_iff.2 ⟨δ, δ0, λ x h, hε (hδ h)⟩⟩
theorem continuous_iff [metric_space β] {f : α → β} :
continuous f ↔
∀b (ε > 0), ∃ δ > 0, ∀a, dist a b < δ → dist (f a) (f b) < ε :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_nhds
theorem exists_delta_of_continuous [metric_space β] {f : α → β} {ε : ℝ}
(hf : continuous f) (hε : ε > 0) (b : α) :
∃ δ > 0, ∀a, dist a b ≤ δ → dist (f a) (f b) < ε :=
let ⟨δ, δ_pos, hδ⟩ := continuous_iff.1 hf b ε hε in
⟨δ / 2, half_pos δ_pos, assume a ha, hδ a $ lt_of_le_of_lt ha $ div_two_lt_of_pos δ_pos⟩
theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} :
tendsto u f (nhds a) ↔ ∀ ε > 0, ∃ n ∈ f.sets, ∀x ∈ n, dist (u x) a < ε :=
⟨λ H ε ε0, ⟨u⁻¹' (ball a ε), H (ball_mem_nhds _ ε0), by simp⟩,
λ H s hs,
let ⟨ε, ε0, hε⟩ := mem_nhds_iff.1 hs, ⟨δ, δ0, hδ⟩ := H _ ε0 in
f.sets_of_superset δ0 (λx xδ, hε (hδ x xδ))⟩
theorem continuous_iff' [topological_space β] {f : β → α} :
continuous f ↔ ∀a (ε > 0), ∃ n ∈ (nhds a).sets, ∀b ∈ n, dist (f b) (f a) < ε :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds
theorem tendsto_at_top [inhabited β] [semilattice_sup β] {u : β → α} {a : α} :
tendsto u at_top (nhds a) ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) a < ε :=
tendsto_nhds.trans $ ball_congr $ λ ε ε0,
by simp; exact ⟨
λ ⟨s, ⟨N, hN⟩, hs⟩, ⟨N, λn hn, hs _ (hN _ hn)⟩,
λ ⟨N, hN⟩, ⟨{n | n ≥ N}, ⟨⟨N, by simp⟩, hN⟩⟩⟩
end metric
open metric
instance metric_space.to_separated : separated α :=
separated_def.2 $ λ x y h, eq_of_forall_dist_le $
λ ε ε0, le_of_lt (h _ (dist_mem_uniformity ε0))
/-Instantiate a metric space as an emetric space. Before we can state the instance,
we need to show that the uniform structure coming from the edistance and the
distance coincide. -/
/-- Expressing the uniformity in terms of `edist` -/
protected lemma metric.mem_uniformity_edist {s : set (α×α)} :
s ∈ (@uniformity α _).sets ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) :=
begin
refine mem_uniformity_dist.trans ⟨_, _⟩; rintro ⟨ε, ε0, Hε⟩,
{ refine ⟨ennreal.of_real ε, _, λ a b, _⟩,
{ rwa [gt, ennreal.of_real_pos] },
{ rw [edist_dist, ennreal.of_real_lt_of_real_iff ε0],
exact Hε } },
{ rcases ennreal.lt_iff_exists_real_btwn.1 ε0 with ⟨ε', _, ε0', hε⟩,
rw [ennreal.of_real_pos] at ε0',
refine ⟨ε', ε0', λ a b h, Hε (lt_trans _ hε)⟩,
rwa [edist_dist, ennreal.of_real_lt_of_real_iff ε0'] }
end
protected theorem metric.uniformity_edist' : uniformity = (⨅ε:{ε:ennreal // ε>0}, principal {p:α×α | edist p.1 p.2 < ε.val}) :=
begin
ext s, rw infi_sets_eq,
{ simp [metric.mem_uniformity_edist, subset_def] },
{ rintro ⟨r, hr⟩ ⟨p, hp⟩, use ⟨min r p, lt_min hr hp⟩,
simp [lt_min_iff, (≥)] {contextual := tt} },
{ exact ⟨⟨1, ennreal.zero_lt_one⟩⟩ }
end
theorem uniformity_edist : uniformity = (⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε}) :=
by simpa [infi_subtype] using @metric.uniformity_edist' α _
/-- A metric space induces an emetric space -/
instance metric_space.to_emetric_space : emetric_space α :=
{ edist := edist,
edist_self := by simp [edist_dist],
eq_of_edist_eq_zero := assume x y h, by simpa [edist_dist] using h,
edist_comm := by simp only [edist_dist, dist_comm]; simp,
edist_triangle := assume x y z, begin
simp only [edist_dist, (ennreal.of_real_add _ _).symm, dist_nonneg],
rw ennreal.of_real_le_of_real_iff _,
{ exact dist_triangle _ _ _ },
{ simpa using add_le_add (dist_nonneg : 0 ≤ dist x y) dist_nonneg }
end,
uniformity_edist := uniformity_edist,
..‹metric_space α› }
/-- Balls defined using the distance or the edistance coincide -/
lemma metric.emetric_ball {x : α} {ε : ℝ} : emetric.ball x (ennreal.of_real ε) = ball x ε :=
begin
classical, by_cases h : 0 < ε,
{ ext y, by simp [edist_dist, ennreal.of_real_lt_of_real_iff h] },
{ have h' : ε ≤ 0, by simpa using h,
have A : ball x ε = ∅, by simpa [ball_eq_empty_iff_nonpos.symm],
have B : emetric.ball x (ennreal.of_real ε) = ∅,
by simp [ennreal.of_real_eq_zero.2 h', emetric.ball_eq_empty_iff],
rwa [A, B] }
end
/-- Closed balls defined using the distance or the edistance coincide -/
lemma metric.emetric_closed_ball {x : α} {ε : ℝ} (h : 0 ≤ ε) :
emetric.closed_ball x (ennreal.of_real ε) = closed_ball x ε :=
by ext y; simp [edist_dist]; rw ennreal.of_real_le_of_real_iff h
def metric_space.replace_uniformity {α} [U : uniform_space α] (m : metric_space α)
(H : @uniformity _ U = @uniformity _ (metric_space.to_uniform_space α)) :
metric_space α :=
{ dist := @dist _ m.to_has_dist,
dist_self := dist_self,
eq_of_dist_eq_zero := @eq_of_dist_eq_zero _ _,
dist_comm := dist_comm,
dist_triangle := dist_triangle,
edist := edist,
edist_dist := edist_dist,
to_uniform_space := U,
uniformity_dist := H.trans (metric_space.uniformity_dist α) }
/-- One gets a metric space from an emetric space if the edistance
is everywhere finite. We set it up so that the edist and the uniformity are
defeq in the metric space and the emetric space -/
def emetric_space.to_metric_space {α : Type u} [e : emetric_space α] (h : ∀x y: α, edist x y ≠ ⊤) :
metric_space α :=
let m : metric_space α :=
{ dist := λx y, ennreal.to_real (edist x y),
eq_of_dist_eq_zero := λx y hxy, by simpa [dist, ennreal.to_real_eq_zero_iff, h x y] using hxy,
dist_self := λx, by simp,
dist_comm := λx y, by simp [emetric_space.edist_comm],
dist_triangle := λx y z, begin
rw [← ennreal.to_real_add (h _ _) (h _ _), ennreal.to_real_le_to_real (h _ _)],
{ exact edist_triangle _ _ _ },
{ simp [ennreal.add_eq_top, h] }
end,
edist := λx y, edist x y,
edist_dist := λx y, by simp [ennreal.of_real_to_real, h] } in
metric_space.replace_uniformity m (by rw [uniformity_edist, uniformity_edist']; refl)
section real
/-- Instantiate the reals as a metric space. -/
instance real.metric_space : metric_space ℝ :=
{ dist := λx y, abs (x - y),
dist_self := by simp [abs_zero],
eq_of_dist_eq_zero := by simp [add_neg_eq_zero],
dist_comm := assume x y, abs_sub _ _,
dist_triangle := assume x y z, abs_sub_le _ _ _ }
theorem real.dist_eq (x y : ℝ) : dist x y = abs (x - y) := rfl
theorem real.dist_0_eq_abs (x : ℝ) : dist x 0 = abs x :=
by simp [real.dist_eq]
instance : orderable_topology ℝ :=
orderable_topology_of_nhds_abs $ λ x, begin
simp only [show ∀ r, {b : ℝ | abs (x - b) < r} = ball x r,
by simp [-sub_eq_add_neg, abs_sub, ball, real.dist_eq]],
apply le_antisymm,
{ simp [le_infi_iff],
exact λ ε ε0, mem_nhds_sets (is_open_ball) (mem_ball_self ε0) },
{ intros s h,
rcases mem_nhds_iff.1 h with ⟨ε, ε0, ss⟩,
exact mem_infi_sets _ (mem_infi_sets ε0 (mem_principal_sets.2 ss)) },
end
lemma closed_ball_Icc {x r : ℝ} : closed_ball x r = Icc (x-r) (x+r) :=
by ext y; rw [mem_closed_ball, dist_comm, real.dist_eq,
abs_sub_le_iff, mem_Icc, ← sub_le_iff_le_add', sub_le]
lemma squeeze_zero {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀t, 0 ≤ f t) (hft : ∀t, f t ≤ g t)
(g0 : tendsto g t₀ (nhds 0)) : tendsto f t₀ (nhds 0) :=
begin
apply tendsto_of_tendsto_of_tendsto_of_le_of_le (tendsto_const_nhds) g0;
simp [*]; exact filter.univ_mem_sets
end
theorem metric.uniformity_eq_comap_nhds_zero :
uniformity = comap (λp:α×α, dist p.1 p.2) (nhds (0 : ℝ)) :=
begin
simp only [uniformity_dist', nhds_eq, comap_infi, comap_principal],
congr, funext ε,
rw [principal_eq_iff_eq],
ext ⟨a, b⟩,
simp [real.dist_0_eq_abs]
end
lemma cauchy_seq_iff_tendsto_dist_at_top_0 [inhabited β] [semilattice_sup β] {u : β → α} :
cauchy_seq u ↔ tendsto (λ (n : β × β), dist (u n.1) (u n.2)) at_top (nhds 0) :=
by rw [cauchy_seq_iff_prod_map, metric.uniformity_eq_comap_nhds_zero, ← map_le_iff_le_comap,
filter.map_map, tendsto, prod.map_def]
end real
section cauchy_seq
variables [inhabited β] [semilattice_sup β]
/-- In a metric space, Cauchy sequences are characterized by the fact that, eventually,
the distance between its elements is arbitrarily small -/
theorem metric.cauchy_seq_iff {u : β → α} :
cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, dist (u m) (u n) < ε :=
begin
unfold cauchy_seq,
rw metric.cauchy_iff,
simp only [true_and, exists_prop, filter.mem_at_top_sets, filter.at_top_ne_bot,
filter.mem_map, ne.def, filter.map_eq_bot_iff, not_false_iff, set.mem_set_of_eq],
split,
{ intros H ε εpos,
rcases H ε εpos with ⟨t, ⟨N, hN⟩, ht⟩,
exact ⟨N, λm n hm hn, ht _ _ (hN _ hm) (hN _ hn)⟩ },
{ intros H ε εpos,
rcases H (ε/2) (half_pos εpos) with ⟨N, hN⟩,
existsi ball (u N) (ε/2),
split,
{ exact ⟨N, λx hx, hN _ _ hx (le_refl N)⟩ },
{ exact λx y hx hy, calc
dist x y ≤ dist x (u N) + dist y (u N) : dist_triangle_right _ _ _
... < ε/2 + ε/2 : add_lt_add hx hy
... = ε : add_halves _ } }
end
/-- A variation around the metric characterization of Cauchy sequences -/
theorem metric.cauchy_seq_iff' {u : β → α} :
cauchy_seq u ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) (u N) < ε :=
begin
rw metric.cauchy_seq_iff,
split,
{ intros H ε εpos,
rcases H ε εpos with ⟨N, hN⟩,
exact ⟨N, λn hn, hN _ _ hn (le_refl N)⟩ },
{ intros H ε εpos,
rcases H (ε/2) (half_pos εpos) with ⟨N, hN⟩,
exact ⟨N, λ m n hm hn, calc
dist (u m) (u n) ≤ dist (u m) (u N) + dist (u n) (u N) : dist_triangle_right _ _ _
... < ε/2 + ε/2 : add_lt_add (hN _ hm) (hN _ hn)
... = ε : add_halves _⟩ }
end
/-- A Cauchy sequence on the natural numbers is bounded. -/
theorem cauchy_seq_bdd {u : ℕ → α} (hu : cauchy_seq u) :
∃ R > 0, ∀ m n, dist (u m) (u n) < R :=
begin
rcases metric.cauchy_seq_iff'.1 hu 1 zero_lt_one with ⟨N, hN⟩,
suffices : ∃ R > 0, ∀ n, dist (u n) (u N) < R,
{ rcases this with ⟨R, R0, H⟩,
exact ⟨_, add_pos R0 R0, λ m n,
lt_of_le_of_lt (dist_triangle_right _ _ _) (add_lt_add (H m) (H n))⟩ },
let R := finset.sup (finset.range N) (λ n, nndist (u n) (u N)),
refine ⟨↑R + 1, add_pos_of_nonneg_of_pos R.2 zero_lt_one, λ n, _⟩,
cases le_or_lt N n,
{ exact lt_of_lt_of_le (hN _ h) (le_add_of_nonneg_left R.2) },
{ have : _ ≤ R := finset.le_sup (finset.mem_range.2 h),
exact lt_of_le_of_lt this (lt_add_of_pos_right _ zero_lt_one) }
end
/-- Yet another metric characterization of Cauchy sequences on integers. This one is often the
most efficient. -/
lemma cauchy_seq_iff_le_tendsto_0 {s : ℕ → α} : cauchy_seq s ↔ ∃ b : ℕ → ℝ,
(∀ n, 0 ≤ b n) ∧
(∀ n m N : ℕ, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) ∧
tendsto b at_top (nhds 0) :=
⟨λ hs, begin
/- `s` is a Cauchy sequence. The sequence `b` will be constructed by taking
the supremum of the distances between `s n` and `s m` for `n m ≥ N`.
First, we prove that all these distances are bounded, as otherwise the Sup
would not make sense. -/
let S := λ N, (λ(p : ℕ × ℕ), dist (s p.1) (s p.2)) '' {p | p.1 ≥ N ∧ p.2 ≥ N},
have hS : ∀ N, ∃ x, ∀ y ∈ S N, y ≤ x,
{ rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩,
refine λ N, ⟨R, _⟩, rintro _ ⟨⟨m, n⟩, _, rfl⟩,
exact le_of_lt (hR m n) },
have bdd : bdd_above (range (λ(p : ℕ × ℕ), dist (s p.1) (s p.2))),
{ rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩,
use R, rintro _ ⟨⟨m, n⟩, rfl⟩, exact le_of_lt (hR m n) },
-- Prove that it bounds the distances of points in the Cauchy sequence
have ub : ∀ m n N, N ≤ m → N ≤ n → dist (s m) (s n) ≤ real.Sup (S N) :=
λ m n N hm hn, real.le_Sup _ (hS N) ⟨⟨_, _⟩, ⟨hm, hn⟩, rfl⟩,
have S0m : ∀ n, (0:ℝ) ∈ S n := λ n, ⟨⟨n, n⟩, ⟨le_refl _, le_refl _⟩, dist_self _⟩,
have S0 := λ n, real.le_Sup _ (hS n) (S0m n),
-- Prove that it tends to `0`, by using the Cauchy property of `s`
refine ⟨λ N, real.Sup (S N), S0, ub, metric.tendsto_at_top.2 (λ ε ε0, _)⟩,
refine (metric.cauchy_seq_iff.1 hs (ε/2) (half_pos ε0)).imp (λ N hN n hn, _),
rw [real.dist_0_eq_abs, abs_of_nonneg (S0 n)],
refine lt_of_le_of_lt (real.Sup_le_ub _ ⟨_, S0m _⟩ _) (half_lt_self ε0),
rintro _ ⟨⟨m', n'⟩, ⟨hm', hn'⟩, rfl⟩,
exact le_of_lt (hN _ _ (le_trans hn hm') (le_trans hn hn'))
end,
λ ⟨b, _, b_bound, b_lim⟩, metric.cauchy_seq_iff.2 $ λ ε ε0,
(metric.tendsto_at_top.1 b_lim ε ε0).imp $ λ N hN m n hm hn,
calc dist (s m) (s n) ≤ b N : b_bound m n N hm hn
... ≤ abs (b N) : le_abs_self _
... = dist (b N) 0 : by rw real.dist_0_eq_abs; refl
... < ε : (hN _ (le_refl N)) ⟩
end cauchy_seq
def metric_space.induced {α β} (f : α → β) (hf : function.injective f)
(m : metric_space β) : metric_space α :=
{ dist := λ x y, dist (f x) (f y),
dist_self := λ x, dist_self _,
eq_of_dist_eq_zero := λ x y h, hf (dist_eq_zero.1 h),
dist_comm := λ x y, dist_comm _ _,
dist_triangle := λ x y z, dist_triangle _ _ _,
edist := λ x y, edist (f x) (f y),
edist_dist := λ x y, edist_dist _ _,
to_uniform_space := uniform_space.comap f m.to_uniform_space,
uniformity_dist := begin
apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, dist (f x) (f y)),
refine λ s, mem_comap_sets.trans _,
split; intro H,
{ rcases H with ⟨r, ru, rs⟩,
rcases mem_uniformity_dist.1 ru with ⟨ε, ε0, hε⟩,
refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h },
{ rcases H with ⟨ε, ε0, hε⟩,
exact ⟨_, dist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ }
end }
instance metric_space_subtype {p : α → Prop} [t : metric_space α] : metric_space (subtype p) :=
metric_space.induced subtype.val (λ x y, subtype.eq) t
theorem subtype.dist_eq {p : α → Prop} [t : metric_space α] (x y : subtype p) :
dist x y = dist x.1 y.1 := rfl
section nnreal
instance : metric_space nnreal := by unfold nnreal; apply_instance
end nnreal
section prod
instance prod.metric_space_max [metric_space β] : metric_space (α × β) :=
{ dist := λ x y, max (dist x.1 y.1) (dist x.2 y.2),
dist_self := λ x, by simp,
eq_of_dist_eq_zero := λ x y h, begin
cases max_le_iff.1 (le_of_eq h) with h₁ h₂,
exact prod.ext_iff.2 ⟨dist_le_zero.1 h₁, dist_le_zero.1 h₂⟩
end,
dist_comm := λ x y, by simp [dist_comm],
dist_triangle := λ x y z, max_le
(le_trans (dist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _)))
(le_trans (dist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))),
edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2),
edist_dist := assume x y, begin
have : monotone ennreal.of_real := assume x y h, ennreal.of_real_le_of_real h,
rw [edist_dist, edist_dist, (max_distrib_of_monotone this).symm]
end,
uniformity_dist := begin
refine uniformity_prod.trans _,
simp [uniformity_dist, comap_infi],
rw ← infi_inf_eq, congr, funext,
rw ← infi_inf_eq, congr, funext,
simp [inf_principal, ext_iff, max_lt_iff]
end,
to_uniform_space := prod.uniform_space }
lemma prod.dist_eq [metric_space β] {x y : α × β} :
dist x y = max (dist x.1 y.1) (dist x.2 y.2) := rfl
end prod
section sum
variables [metric_space β] [inhabited α] [inhabited β]
open sum (inl inr)
/--Distance on a disjoint union. There are many (noncanonical) ways to put a distance compatible with each factor.
If the two spaces are bounded, one can say for instance that each point in the first is at distance
`diam α + diam β + 1` of each point in the second.
Instead, we choose a construction that works for unbounded spaces, but requires basepoints.
We embed isometrically each factor, set the basepoints at distance 1,
arbitrarily, and say that the distance from `a` to `b` is the sum of the distances of `a` and `b` to
their respective basepoints, plus the distance 1 between the basepoints.
Since there is an arbitrary choice in this construction, it is not an instance by default-/
private def sum.dist : α ⊕ β → α ⊕ β → ℝ
| (inl a) (inl a') := dist a a'
| (inr b) (inr b') := dist b b'
| (inl a) (inr b) := dist a (default α) + 1 + dist (default β) b
| (inr b) (inl a) := dist b (default β) + 1 + dist (default α) a
private lemma sum.dist_comm (x y : α ⊕ β) : sum.dist x y = sum.dist y x :=
by cases x; cases y; simp only [sum.dist, dist_comm, add_comm, add_left_comm]
lemma sum.one_dist_le {x : α} {y : β} : 1 ≤ sum.dist (inl x) (inr y) :=
le_trans (le_add_of_nonneg_right dist_nonneg) $
add_le_add_right (le_add_of_nonneg_left dist_nonneg) _
lemma sum.one_dist_le' {x : α} {y : β} : 1 ≤ sum.dist (inr y) (inl x) :=
by rw sum.dist_comm; exact sum.one_dist_le
private lemma sum.dist_triangle : ∀ x y z : α ⊕ β, sum.dist x z ≤ sum.dist x y + sum.dist y z
| (inl x) (inl y) (inl z) := dist_triangle _ _ _
| (inl x) (inl y) (inr z) := by unfold sum.dist; rw [← add_assoc, ← add_assoc];
exact add_le_add_right (add_le_add_right (dist_triangle _ _ _) _) _
| (inl x) (inr y) (inl z) := by unfold sum.dist; rw [add_assoc _ (1:ℝ), add_assoc];
refine le_trans (dist_triangle _ _ _) (add_le_add_left _ _);
refine le_trans (le_add_of_nonneg_left (add_nonneg zero_le_one dist_nonneg)) (add_le_add_left _ _);
exact le_add_of_nonneg_left (add_nonneg dist_nonneg zero_le_one)
| (inr x) (inl y) (inl z) := by unfold sum.dist; rw [add_assoc _ _ (dist y z)];
exact add_le_add_left (dist_triangle _ _ _) _
| (inr x) (inr y) (inl z) := by unfold sum.dist; rw [← add_assoc, ← add_assoc];
exact add_le_add_right (add_le_add_right (dist_triangle _ _ _) _) _
| (inr x) (inl y) (inr z) := by unfold sum.dist; rw [add_assoc _ (1:ℝ), add_assoc];
refine le_trans (dist_triangle _ _ _) (add_le_add_left _ _);
refine le_trans (le_add_of_nonneg_left (add_nonneg zero_le_one dist_nonneg)) (add_le_add_left _ _);
exact le_add_of_nonneg_left (add_nonneg dist_nonneg zero_le_one)
| (inl x) (inr y) (inr z) := by unfold sum.dist; rw [add_assoc _ _ (dist y z)];
exact add_le_add_left (dist_triangle _ _ _) _
| (inr x) (inr y) (inr z) := dist_triangle _ _ _
private lemma sum.eq_of_dist_eq_zero : ∀ x y : α ⊕ β, sum.dist x y = 0 → x = y
| (inl x) (inl y) h := by simp only [sum.dist] at h ⊢; exact eq_of_dist_eq_zero h
| (inl x) (inr y) h :=
(ne_of_gt (lt_of_lt_of_le zero_lt_one sum.one_dist_le) h).elim
| (inr x) (inl y) h :=
(ne_of_gt (lt_of_lt_of_le zero_lt_one sum.one_dist_le') h).elim
| (inr x) (inr y) h := by simp only [sum.dist] at h ⊢; exact eq_of_dist_eq_zero h
private lemma sum.mem_uniformity (s : set ((α ⊕ β) × (α ⊕ β))) :
s ∈ (@uniformity (α ⊕ β) _).sets ↔ ∃ ε > 0, ∀ a b, sum.dist a b < ε → (a, b) ∈ s :=
begin
split,
{ rintro ⟨hsα, hsβ⟩,
rcases mem_uniformity_dist.1 hsα with ⟨εα, εα0, hα⟩,
rcases mem_uniformity_dist.1 hsβ with ⟨εβ, εβ0, hβ⟩,
refine ⟨min (min εα εβ) 1, lt_min (lt_min εα0 εβ0) zero_lt_one, _⟩,
rintro (a|a) (b|b) h,
{ exact hα (lt_of_lt_of_le h (le_trans (min_le_left _ _) (min_le_left _ _))) },
{ cases not_le_of_lt (lt_of_lt_of_le h (min_le_right _ _)) sum.one_dist_le },
{ cases not_le_of_lt (lt_of_lt_of_le h (min_le_right _ _)) sum.one_dist_le' },
{ exact hβ (lt_of_lt_of_le h (le_trans (min_le_left _ _) (min_le_right _ _))) } },
{ rintro ⟨ε, ε0, H⟩,
split; rw [filter.mem_map, mem_uniformity_dist];
exact ⟨ε, ε0, λ x y h, H _ _ (by exact h)⟩ }
end
/-- The distance on the disjoint union indeed defines a metric space. All the distance properties follow from our
choice of the distance. The harder work is to show that the uniform structure defined by the distance coincides
with the disjoint union uniform structure. -/
def metric_space_sum : metric_space (α ⊕ β) :=
{ dist := sum.dist,
dist_self := λx, by cases x; simp only [sum.dist, dist_self],
dist_comm := sum.dist_comm,
dist_triangle := sum.dist_triangle,
eq_of_dist_eq_zero := sum.eq_of_dist_eq_zero,
to_uniform_space := sum.uniform_space,
uniformity_dist := uniformity_dist_of_mem_uniformity _ _ sum.mem_uniformity }
local attribute [instance] metric_space_sum
lemma sum.dist_eq {x y : α ⊕ β} :
dist x y = sum.dist x y := rfl
end sum
theorem uniform_continuous_dist' : uniform_continuous (λp:α×α, dist p.1 p.2) :=
metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε/2, half_pos ε0,
begin
suffices,
{ intros p q h, cases p with p₁ p₂, cases q with q₁ q₂,
cases max_lt_iff.1 h with h₁ h₂, clear h,
dsimp at h₁ h₂ ⊢,
rw real.dist_eq,
refine abs_sub_lt_iff.2 ⟨_, _⟩,
{ revert p₁ p₂ q₁ q₂ h₁ h₂, exact this },
{ apply this; rwa dist_comm } },
intros p₁ p₂ q₁ q₂ h₁ h₂,
have := add_lt_add
(abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₁ q₁ p₂) h₁)).1
(abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₂ q₂ q₁) h₂)).1,
rwa [add_halves, dist_comm p₂, sub_add_sub_cancel, dist_comm q₂] at this
end⟩)
theorem uniform_continuous_dist [uniform_space β] {f g : β → α}
(hf : uniform_continuous f) (hg : uniform_continuous g) :
uniform_continuous (λb, dist (f b) (g b)) :=
(hf.prod_mk hg).comp uniform_continuous_dist'
theorem continuous_dist' : continuous (λp:α×α, dist p.1 p.2) :=
uniform_continuous_dist'.continuous
theorem continuous_dist [topological_space β] {f g : β → α}
(hf : continuous f) (hg : continuous g) : continuous (λb, dist (f b) (g b)) :=
(hf.prod_mk hg).comp continuous_dist'
theorem tendsto_dist {f g : β → α} {x : filter β} {a b : α}
(hf : tendsto f x (nhds a)) (hg : tendsto g x (nhds b)) :
tendsto (λx, dist (f x) (g x)) x (nhds (dist a b)) :=
have tendsto (λp:α×α, dist p.1 p.2) (nhds (a, b)) (nhds (dist a b)),
from continuous_iff_continuous_at.mp continuous_dist' (a, b),
(hf.prod_mk hg).comp (by rw [nhds_prod_eq] at this; exact this)
lemma nhds_comap_dist (a : α) : (nhds (0 : ℝ)).comap (λa', dist a' a) = nhds a :=
have h₁ : ∀ε, (λa', dist a' a) ⁻¹' ball 0 ε ⊆ ball a ε,
by simp [subset_def, real.dist_0_eq_abs],
have h₂ : tendsto (λa', dist a' a) (nhds a) (nhds (dist a a)),
from tendsto_dist tendsto_id tendsto_const_nhds,
le_antisymm
(by simp [h₁, nhds_eq, infi_le_infi, principal_mono,
-le_principal_iff, -le_infi_iff])
(by simpa [map_le_iff_le_comap.symm, tendsto] using h₂)
lemma tendsto_iff_dist_tendsto_zero {f : β → α} {x : filter β} {a : α} :
(tendsto f x (nhds a)) ↔ (tendsto (λb, dist (f b) a) x (nhds 0)) :=
by rw [← nhds_comap_dist a, tendsto_comap_iff]
lemma uniform_continuous_nndist' : uniform_continuous (λp:α×α, nndist p.1 p.2) :=
uniform_continuous_subtype_mk uniform_continuous_dist' _
lemma continuous_nndist' : continuous (λp:α×α, nndist p.1 p.2) :=
uniform_continuous_nndist'.continuous
lemma tendsto_nndist' (a b :α) :
tendsto (λp:α×α, nndist p.1 p.2) (filter.prod (nhds a) (nhds b)) (nhds (nndist a b)) :=
by rw [← nhds_prod_eq]; exact continuous_iff_continuous_at.1 continuous_nndist' _
namespace metric
variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α}
theorem is_closed_ball : is_closed (closed_ball x ε) :=
is_closed_le (continuous_dist continuous_id continuous_const) continuous_const
/-- ε-characterization of the closure in metric spaces-/
theorem mem_closure_iff' {α : Type u} [metric_space α] {s : set α} {a : α} :
a ∈ closure s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε :=
⟨begin
intros ha ε hε,
have A : ball a ε ∩ s ≠ ∅ := mem_closure_iff.1 ha _ is_open_ball (mem_ball_self hε),
cases ne_empty_iff_exists_mem.1 A with b hb,
simp,
exact ⟨b, ⟨hb.2, by have B := hb.1; simpa [mem_ball'] using B⟩⟩
end,
begin
intros H,
apply mem_closure_iff.2,
intros o ho ao,
rcases is_open_iff.1 ho a ao with ⟨ε, ⟨εpos, hε⟩⟩,
rcases H ε εpos with ⟨b, ⟨bs, bdist⟩⟩,
have B : b ∈ o ∩ s := ⟨hε (by simpa [dist_comm]), bs⟩,
apply ne_empty_of_mem B
end⟩
theorem mem_of_closed' {α : Type u} [metric_space α] {s : set α} (hs : is_closed s)
{a : α} : a ∈ s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε :=
by simpa only [closure_eq_of_is_closed hs] using @mem_closure_iff' _ _ s a
end metric
section pi
open finset lattice
variables {π : β → Type*} [fintype β] [∀b, metric_space (π b)]
instance has_dist_pi : has_dist (Πb, π b) :=
⟨λf g, ((finset.sup univ (λb, nndist (f b) (g b)) : nnreal) : ℝ)⟩
lemma dist_pi_def (f g : Πb, π b) :
dist f g = (finset.sup univ (λb, nndist (f b) (g b)) : nnreal) := rfl
instance metric_space_pi : metric_space (Πb, π b) :=
{ dist := dist,
dist_self := assume f, (nnreal.coe_eq_zero _).2 $ bot_unique $ finset.sup_le $ by simp,
dist_comm := assume f g, nnreal.eq_iff.2 $ by congr; ext a; exact nndist_comm _ _,
dist_triangle := assume f g h, show dist f h ≤ (dist f g) + (dist g h), from
begin
simp only [dist_pi_def, (nnreal.coe_add _ _).symm, nnreal.coe_le.symm,
finset.sup_le_iff],
assume b hb,
exact le_trans (nndist_triangle _ (g b) _) (add_le_add (le_sup hb) (le_sup hb))
end,
eq_of_dist_eq_zero := assume f g eq0,
begin
simp only [dist_pi_def, nnreal.coe_eq_zero, nnreal.bot_eq_zero.symm, eq_bot_iff,
finset.sup_le_iff] at eq0,
exact (funext $ assume b, eq_of_nndist_eq_zero $ bot_unique $ eq0 b $ mem_univ b),
end,
edist := λ f g, finset.sup univ (λb, edist (f b) (g b)),
edist_dist := assume x y, begin
have A : sup univ (λ (b : β), ((nndist (x b) (y b)) : ennreal)) = ↑(sup univ (λ (b : β), nndist (x b) (y b))),
{ refine eq.symm (comp_sup_eq_sup_comp _ _ _),
exact (assume x y h, ennreal.coe_le_coe.2 h), refl },
simp [dist, edist_nndist, ennreal.of_real, A]
end }
end pi
section compact
/-- Any compact set in a metric space can be covered by finitely many balls of a given positive
radius -/
lemma finite_cover_balls_of_compact {α : Type u} [metric_space α] {s : set α}
(hs : compact s) {e : ℝ} (he : e > 0) :
∃t ⊆ s, finite t ∧ s ⊆ ⋃x∈t, ball x e :=
begin
apply compact_elim_finite_subcover_image hs,
{ simp [is_open_ball] },
{ intros x xs,
simp,
exact ⟨x, ⟨xs, by simpa⟩⟩ }
end
end compact
section proper_space
open metric
/-- A metric space is proper if all closed balls are compact. -/
class proper_space (α : Type u) [metric_space α] : Prop :=
(compact_ball : ∀x:α, ∀r, compact (closed_ball x r))
/- A compact metric space is proper -/
instance proper_of_compact [metric_space α] [compact_space α] : proper_space α :=
⟨assume x r, compact_of_is_closed_subset compact_univ is_closed_ball (subset_univ _)⟩
/-- A proper space is locally compact -/
instance locally_compact_of_proper [metric_space α] [proper_space α] :
locally_compact_space α :=
begin
apply locally_compact_of_compact_nhds,
intros x,
existsi closed_ball x 1,
split,
{ apply mem_nhds_iff.2,
existsi (1 : ℝ),
simp,
exact ⟨zero_lt_one, ball_subset_closed_ball⟩ },
{ apply proper_space.compact_ball }
end
/-- A proper space is complete -/
instance complete_of_proper {α : Type u} [metric_space α] [proper_space α] : complete_space α :=
⟨begin
intros f hf,
/- We want to show that the Cauchy filter `f` is converging. It suffices to find a closed
ball (therefore compact by properness) where it is nontrivial. -/
have A : ∃ t ∈ f.sets, ∀ x y ∈ t, dist x y < 1 := (metric.cauchy_iff.1 hf).2 1 zero_lt_one,
rcases A with ⟨t, ⟨t_fset, ht⟩⟩,
rcases inhabited_of_mem_sets hf.1 t_fset with ⟨x, xt⟩,
have : t ⊆ closed_ball x 1 := by intros y yt; simp [dist_comm]; apply le_of_lt (ht x y xt yt),
have : closed_ball x 1 ∈ f.sets := f.sets_of_superset t_fset this,
rcases (compact_iff_totally_bounded_complete.1 (proper_space.compact_ball x 1)).2 f hf (le_principal_iff.2 this)
with ⟨y, _, hy⟩,
exact ⟨y, hy⟩
end⟩
/-- A proper metric space is separable, and therefore second countable. Indeed, any ball is
compact, and therefore admits a countable dense subset. Taking a countable union over the balls
centered at a fixed point and with integer radius, one obtains a countable set which is
dense in the whole space. -/
instance second_countable_of_proper [metric_space α] [proper_space α] :
second_countable_topology α :=
begin
/- We show that the space admits a countable dense subset. The case where the space is empty
is special, and trivial. -/
have A : (univ : set α) = ∅ → ∃(s : set α), countable s ∧ closure s = (univ : set α) :=
assume H, ⟨∅, ⟨by simp, by simp; exact H.symm⟩⟩,
have B : (univ : set α) ≠ ∅ → ∃(s : set α), countable s ∧ closure s = (univ : set α) :=
begin
/- When the space is not empty, we take a point `x` in the space, and then a countable set
`T r` which is dense in the closed ball `closed_ball x r` for each `r`. Then the set
`t = ⋃ T n` (where the union is over all integers `n`) is countable, as a countable union
of countable sets, and dense in the space by construction. -/
assume non_empty,
rcases ne_empty_iff_exists_mem.1 non_empty with ⟨x, x_univ⟩,
choose T a using show ∀ (r:ℝ), ∃ t ⊆ closed_ball x r, (countable (t : set α) ∧ closed_ball x r = closure t),
from assume r, emetric.countable_closure_of_compact (proper_space.compact_ball _ _),
let t := (⋃n:ℕ, T (n : ℝ)),
have T₁ : countable t := by finish [countable_Union],
have T₂ : closure t ⊆ univ := by simp,
have T₃ : univ ⊆ closure t :=
begin
intros y y_univ,
rcases exists_nat_gt (dist y x) with ⟨n, n_large⟩,
have h : y ∈ closed_ball x (n : ℝ) := by simp; apply le_of_lt n_large,
have h' : closed_ball x (n : ℝ) = closure (T (n : ℝ)) := by finish,
have : y ∈ closure (T (n : ℝ)) := by rwa h' at h,
show y ∈ closure t, from mem_of_mem_of_subset this (by apply closure_mono; apply subset_Union (λ(n:ℕ), T (n:ℝ))),
end,
exact ⟨t, ⟨T₁, subset.antisymm T₂ T₃⟩⟩
end,
haveI : separable_space α := ⟨by_cases A B⟩,
apply emetric.second_countable_of_separable,
end
end proper_space
namespace metric
section second_countable
open topological_space
/-- A metric space is second countable if, for every ε > 0, there is a countable set which is ε-dense. -/
lemma second_countable_of_almost_dense_set
(H : ∀ε > (0 : ℝ), ∃ s : set α, countable s ∧ (∀x, ∃y ∈ s, dist x y ≤ ε)) :
second_countable_topology α :=
begin
choose T T_dense using H,
have I1 : ∀n:ℕ, (n:ℝ) + 1 > 0 :=
λn, lt_of_lt_of_le zero_lt_one (le_add_of_nonneg_left (nat.cast_nonneg _)),
have I : ∀n:ℕ, (n+1 : ℝ)⁻¹ > 0 := λn, inv_pos'.2 (I1 n),
let t := ⋃n:ℕ, T (n+1)⁻¹ (I n),
have count_t : countable t := by finish [countable_Union],
have clos_t : closure t = univ,
{ refine subset.antisymm (subset_univ _) (λx xuniv, mem_closure_iff'.2 (λε εpos, _)),
rcases exists_nat_gt ε⁻¹ with ⟨n, hn⟩,
have : ε⁻¹ < n + 1 := lt_of_lt_of_le hn (le_add_of_nonneg_right zero_le_one),
have nε : ((n:ℝ)+1)⁻¹ < ε := (inv_lt (I1 n) εpos).2 this,
rcases (T_dense (n+1)⁻¹ (I n)).2 x with ⟨y, yT, Dxy⟩,
have : y ∈ t := mem_of_mem_of_subset yT (by apply subset_Union (λ (n:ℕ), T (n+1)⁻¹ (I n))),
exact ⟨y, this, lt_of_le_of_lt Dxy nε⟩ },
haveI : separable_space α := ⟨⟨t, ⟨count_t, clos_t⟩⟩⟩,
exact emetric.second_countable_of_separable α
end
/-- A metric space space is second countable if one can reconstruct up to any ε>0 any element of the
space from countably many data. -/
lemma second_countable_of_countable_discretization {α : Type u} [metric_space α]
(H : ∀ε > (0 : ℝ), ∃ (β : Type u) [encodable β] (F : α → β), ∀x y, F x = F y → dist x y ≤ ε) :
second_countable_topology α :=
begin
classical, by_cases hs : (univ : set α) = ∅,
{ haveI : compact_space α := ⟨by rw hs; exact compact_of_finite (set.finite_empty)⟩, by apply_instance },
rcases exists_mem_of_ne_empty hs with ⟨x0, hx0⟩,
letI : inhabited α := ⟨x0⟩,
refine second_countable_of_almost_dense_set (λε ε0, _),
rcases H ε ε0 with ⟨β, fβ, F, hF⟩,
let Finv := function.inv_fun F,
refine ⟨range Finv, ⟨countable_range _, λx, _⟩⟩,
let x' := Finv (F x),
have : F x' = F x := function.inv_fun_eq ⟨x, rfl⟩,
exact ⟨x', mem_range_self _, hF _ _ this.symm⟩
end
end second_countable
end metric
lemma lebesgue_number_lemma_of_metric
{s : set α} {ι} {c : ι → set α} (hs : compact s)
(hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) :
∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i :=
let ⟨n, en, hn⟩ := lebesgue_number_lemma hs hc₁ hc₂,
⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 en in
⟨δ, δ0, assume x hx, let ⟨i, hi⟩ := hn x hx in
⟨i, assume y hy, hi (hδ (mem_ball'.mp hy))⟩⟩
lemma lebesgue_number_lemma_of_metric_sUnion
{s : set α} {c : set (set α)} (hs : compact s)
(hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) :
∃ δ > 0, ∀ x ∈ s, ∃ t ∈ c, ball x δ ⊆ t :=
by rw sUnion_eq_Union at hc₂;
simpa using lebesgue_number_lemma_of_metric hs (by simpa) hc₂
namespace metric
/-- Boundedness of a subset of a metric space. We formulate the definition to work
even in the empty space. -/
def bounded (s : set α) : Prop :=
∃C, ∀x y ∈ s, dist x y ≤ C
section bounded
variables {x : α} {s t : set α} {r : ℝ}
@[simp] lemma bounded_empty : bounded (∅ : set α) :=
⟨0, by simp⟩
lemma bounded_iff_mem_bounded : bounded s ↔ ∀ x ∈ s, bounded s :=
⟨λ h _ _, h, λ H, begin
classical, by_cases s = ∅,
{ subst s, exact ⟨0, by simp⟩ },
{ rcases exists_mem_of_ne_empty h with ⟨x, hx⟩,
exact H x hx }
end⟩
/-- Subsets of a bounded set are also bounded -/
lemma bounded.subset (incl : s ⊆ t) : bounded t → bounded s :=
Exists.imp $ λ C hC x y hx hy, hC x y (incl hx) (incl hy)
/-- Closed balls are bounded -/
lemma bounded_closed_ball : bounded (closed_ball x r) :=
⟨r + r, λ y z hy hz, begin
simp only [mem_closed_ball] at *,
calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _
... ≤ r + r : add_le_add hy hz
end⟩
/-- Open balls are bounded -/
lemma bounded_ball : bounded (ball x r) :=
bounded_closed_ball.subset ball_subset_closed_ball
/-- Given a point, a bounded subset is included in some ball around this point -/
lemma bounded_iff_subset_ball (c : α) : bounded s ↔ ∃r, s ⊆ closed_ball c r :=
begin
split; rintro ⟨C, hC⟩,
{ classical, by_cases s = ∅,
{ subst s, exact ⟨0, by simp⟩ },
{ rcases exists_mem_of_ne_empty h with ⟨x, hx⟩,
exact ⟨C + dist x c, λ y hy, calc
dist y c ≤ dist y x + dist x c : dist_triangle _ _ _
... ≤ C + dist x c : add_le_add_right (hC y x hy hx) _⟩ } },
{ exact bounded_closed_ball.subset hC }
end
/-- The union of two bounded sets is bounded iff each of the sets is bounded -/
@[simp] lemma bounded_union :
bounded (s ∪ t) ↔ bounded s ∧ bounded t :=
⟨λh, ⟨h.subset (by simp), h.subset (by simp)⟩,
begin
rintro ⟨hs, ht⟩,
refine bounded_iff_mem_bounded.2 (λ x _, _),
rw bounded_iff_subset_ball x at hs ht ⊢,
rcases hs with ⟨Cs, hCs⟩, rcases ht with ⟨Ct, hCt⟩,
exact ⟨max Cs Ct, union_subset
(subset.trans hCs $ closed_ball_subset_closed_ball $ le_max_left _ _)
(subset.trans hCt $ closed_ball_subset_closed_ball $ le_max_right _ _)⟩,
end⟩
/-- A finite union of bounded sets is bounded -/
lemma bounded_bUnion {I : set β} {s : β → set α} (H : finite I) :
bounded (⋃i∈I, s i) ↔ ∀i ∈ I, bounded (s i) :=
finite.induction_on H (by simp) $ λ x I _ _ IH,
by simp [or_imp_distrib, forall_and_distrib, IH]
/-- A compact set is bounded -/
lemma bounded_of_compact {s : set α} (h : compact s) : bounded s :=
-- We cover the compact set by finitely many balls of radius 1,
-- and then argue that a finite union of bounded sets is bounded
let ⟨t, ht, fint, subs⟩ := finite_cover_balls_of_compact h zero_lt_one in
bounded.subset subs $ (bounded_bUnion fint).2 $ λ i hi, bounded_ball
/-- A finite set is bounded -/
lemma bounded_of_finite {s : set α} (h : finite s) : bounded s :=
bounded_of_compact $ compact_of_finite h
/-- A singleton is bounded -/
lemma bounded_singleton {x : α} : bounded ({x} : set α) :=
bounded_of_finite $ finite_singleton _
/-- Characterization of the boundedness of the range of a function -/
lemma bounded_range_iff {f : β → α} : bounded (range f) ↔ ∃C, ∀x y, dist (f x) (f y) ≤ C :=
exists_congr $ λ C, ⟨
λ H x y, H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩,
by rintro H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩; exact H x y⟩
/-- In a compact space, all sets are bounded -/
lemma bounded_of_compact_space [compact_space α] : bounded s :=
(bounded_of_compact compact_univ).subset (subset_univ _)
/-- In a proper space, a set is compact if and only if it is closed and bounded -/
lemma compact_iff_closed_bounded [proper_space α] :
compact s ↔ is_closed s ∧ bounded s :=
⟨λ h, ⟨closed_of_compact _ h, bounded_of_compact h⟩, begin
rintro ⟨hc, hb⟩,
classical, by_cases s = ∅, {simp [h, compact_empty]},
rcases exists_mem_of_ne_empty h with ⟨x, hx⟩,
rcases (bounded_iff_subset_ball x).1 hb with ⟨r, hr⟩,
exact compact_of_is_closed_subset (proper_space.compact_ball x r) hc hr
end⟩
end bounded
section diam
variables {s : set α} {x y : α}
/-- The diameter of a set in a metric space. To get controllable behavior even when the diameter
should be infinite, we express it in terms of the emetric.diameter -/
def diam (s : set α) : ℝ := ennreal.to_real (emetric.diam s)
/-- The diameter of a set is always nonnegative -/
lemma diam_nonneg : 0 ≤ diam s :=
by simp [diam]
/-- The empty set has zero diameter -/
@[simp] lemma diam_empty : diam (∅ : set α) = 0 :=
by simp [diam]
/-- A singleton has zero diameter -/
@[simp] lemma diam_singleton : diam ({x} : set α) = 0 :=
by simp [diam]
/-- Characterize the boundedness of a set in terms of the finiteness of its emetric.diameter. -/
lemma bounded_iff_diam_ne_top : bounded s ↔ emetric.diam s ≠ ⊤ :=
begin
classical, by_cases hs : s = ∅,
{ simp [hs] },
{ rcases ne_empty_iff_exists_mem.1 hs with ⟨x, hx⟩,
split,
{ assume bs,
rcases (bounded_iff_subset_ball x).1 bs with ⟨r, hr⟩,
have r0 : 0 ≤ r := by simpa [closed_ball] using hr hx,
have : emetric.diam s < ⊤ := calc
emetric.diam s ≤ emetric.diam (emetric.closed_ball x (ennreal.of_real r)) :
by rw emetric_closed_ball r0; exact emetric.diam_mono hr
... ≤ 2 * (ennreal.of_real r) : emetric.diam_closed_ball
... < ⊤ : begin apply ennreal.lt_top_iff_ne_top.2, simp [ennreal.mul_eq_top], end,
exact ennreal.lt_top_iff_ne_top.1 this },
{ assume ds,
have : s ⊆ closed_ball x (ennreal.to_real (emetric.diam s)),
{ rw [← emetric_closed_ball ennreal.to_real_nonneg, ennreal.of_real_to_real ds],
exact λy hy, emetric.edist_le_diam_of_mem hy hx },
exact bounded.subset this (bounded_closed_ball) }}
end
/-- An unbounded set has zero diameter. If you would prefer to get the value ∞, use `emetric.diam`.
This lemma makes it possible to avoid side conditions in some situations -/
lemma diam_eq_zero_of_unbounded (h : ¬(bounded s)) : diam s = 0 :=
begin
simp only [bounded_iff_diam_ne_top, not_not, ne.def] at h,
simp [diam, h]
end
/-- If `s ⊆ t`, then the diameter of `s` is bounded by that of `t`, provided `t` is bounded. -/
lemma diam_mono {s t : set α} (h : s ⊆ t) (ht : bounded t) : diam s ≤ diam t :=
begin
unfold diam,
rw ennreal.to_real_le_to_real (bounded_iff_diam_ne_top.1 (bounded.subset h ht)) (bounded_iff_diam_ne_top.1 ht),
exact emetric.diam_mono h
end
/-- The distance between two points in a set is controlled by the diameter of the set. -/
lemma dist_le_diam_of_mem (h : bounded s) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s :=
begin
rw [diam, dist_edist],
rw ennreal.to_real_le_to_real (edist_ne_top _ _) (bounded_iff_diam_ne_top.1 h),
exact emetric.edist_le_diam_of_mem hx hy
end
/-- If the distance between any two points in a set is bounded by some constant, this constant
bounds the diameter. -/
lemma diam_le_of_forall_dist_le {d : real} (hd : d ≥ 0) (h : ∀x y ∈ s, dist x y ≤ d) : diam s ≤ d :=
begin
have I : emetric.diam s ≤ ennreal.of_real d,
{ refine emetric.diam_le_of_forall_edist_le (λx y hx hy, _),
rw [edist_dist],
exact ennreal.of_real_le_of_real (h x y hx hy) },
have A : emetric.diam s ≠ ⊤ :=
ennreal.lt_top_iff_ne_top.1 (lt_of_le_of_lt I (ennreal.lt_top_iff_ne_top.2 (by simp))),
rw [← ennreal.to_real_of_real hd, diam, ennreal.to_real_le_to_real A],
{ exact I },
{ simp }
end
/-- The diameter of a union is controlled by the sum of the diameters, and the distance between
any two points in each of the sets. This lemma is true without any side condition, since it is
obviously true if `s ∪ t` is unbounded. -/
lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + dist x y + diam t :=
have I1 : ¬(bounded (s ∪ t)) → diam (s ∪ t) ≤ diam s + dist x y + diam t := λh, calc
diam (s ∪ t) = 0 + 0 + 0 : by simp [diam_eq_zero_of_unbounded h]
... ≤ diam s + dist x y + diam t : add_le_add (add_le_add diam_nonneg dist_nonneg) diam_nonneg,
have I2 : (bounded (s ∪ t)) → diam (s ∪ t) ≤ diam s + dist x y + diam t := λh,
begin
have : bounded s := bounded.subset (subset_union_left _ _) h,
have : bounded t := bounded.subset (subset_union_right _ _) h,
have A : ∀a ∈ s, ∀b ∈ t, dist a b ≤ diam s + dist x y + diam t := λa ha b hb, calc
dist a b ≤ dist a x + dist x y + dist y b : dist_triangle4 _ _ _ _
... ≤ diam s + dist x y + diam t :
add_le_add (add_le_add (dist_le_diam_of_mem ‹bounded s› ha xs) (le_refl _)) (dist_le_diam_of_mem ‹bounded t› yt hb),
have B : ∀a b ∈ s ∪ t, dist a b ≤ diam s + dist x y + diam t := λa b ha hb,
begin
cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b,
{ calc dist a b ≤ diam s : dist_le_diam_of_mem ‹bounded s› h'a h'b
... = diam s + (0 + 0) : by simp
... ≤ diam s + (dist x y + diam t) : add_le_add (le_refl _) (add_le_add dist_nonneg diam_nonneg)
... = diam s + dist x y + diam t : by simp only [add_comm, eq_self_iff_true, add_left_comm] },
{ exact A a h'a b h'b },
{ have Z := A b h'b a h'a, rwa [dist_comm] at Z },
{ calc dist a b ≤ diam t : dist_le_diam_of_mem ‹bounded t› h'a h'b
... = (0 + 0) + diam t : by simp
... ≤ (diam s + dist x y) + diam t : add_le_add (add_le_add diam_nonneg dist_nonneg) (le_refl _) }
end,
have C : 0 ≤ diam s + dist x y + diam t := calc
0 = 0 + 0 + 0 : by simp
... ≤ diam s + dist x y + diam t : add_le_add (add_le_add diam_nonneg dist_nonneg) diam_nonneg,
exact diam_le_of_forall_dist_le C B
end,
classical.by_cases I2 I1
/-- If two sets intersect, the diameter of the union is bounded by the sum of the diameters. -/
lemma diam_union' {t : set α} (h : s ∩ t ≠ ∅) : diam (s ∪ t) ≤ diam s + diam t :=
begin
rcases ne_empty_iff_exists_mem.1 h with ⟨x, ⟨xs, xt⟩⟩,
simpa using diam_union xs xt
end
/-- The diameter of a closed ball of radius `r` is at most `2 r`. -/
lemma diam_closed_ball {r : ℝ} (h : r ≥ 0) : diam (closed_ball x r) ≤ 2 * r :=
diam_le_of_forall_dist_le (mul_nonneg (by norm_num) h) $ λa b ha hb, calc
dist a b ≤ dist a x + dist b x : dist_triangle_right _ _ _
... ≤ r + r : add_le_add ha hb
... = 2 * r : by simp [mul_two, mul_comm]
/-- The diameter of a ball of radius `r` is at most `2 r`. -/
lemma diam_ball {r : ℝ} (h : r ≥ 0) : diam (ball x r) ≤ 2 * r :=
le_trans (diam_mono ball_subset_closed_ball bounded_closed_ball) (diam_closed_ball h)
end diam
end metric
|
38674a84c4917dcc7b856889d11310aba20dbaa6 | 8cb37a089cdb4af3af9d8bf1002b417e407a8e9e | /library/init/meta/constructor_tactic.lean | cca43e168cd8eb9f50f644116601eb7426249061 | [
"Apache-2.0"
] | permissive | kbuzzard/lean | ae3c3db4bb462d750dbf7419b28bafb3ec983ef7 | ed1788fd674bb8991acffc8fca585ec746711928 | refs/heads/master | 1,620,983,366,617 | 1,618,937,600,000 | 1,618,937,600,000 | 359,886,396 | 1 | 0 | Apache-2.0 | 1,618,936,987,000 | 1,618,936,987,000 | null | UTF-8 | Lean | false | false | 3,280 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta.tactic init.function
namespace tactic
/- Return target after instantiating metavars and whnf -/
private meta def target' : tactic expr :=
target >>= instantiate_mvars >>= whnf
meta def get_constructors_for (e : expr) : tactic (list name) :=
do env ← get_env,
I ← return e.extract_opt_auto_param.get_app_fn.const_name,
when (¬env.is_inductive I) (fail "constructor tactic failed, target is not an inductive datatype"),
return $ env.constructors_of I
private meta def try_constructors (cfg : apply_cfg): list name → tactic (list (name × expr))
| [] := fail "constructor tactic failed, none of the constructors is applicable"
| (c::cs) := (mk_const c >>= λ e, apply e cfg) <|> try_constructors cs
meta def constructor (cfg : apply_cfg := {}): tactic (list (name × expr)) :=
target' >>= get_constructors_for >>= try_constructors cfg
meta def econstructor : tactic (list (name × expr)) :=
constructor {new_goals := new_goals.non_dep_only}
meta def fconstructor : tactic (list (name × expr)) :=
constructor {new_goals := new_goals.all}
meta def left : tactic (list (name × expr)) :=
do tgt ← target',
[c₁, c₂] ← get_constructors_for tgt | fail "left tactic failed, target is not an inductive datatype with two constructors",
mk_const c₁ >>= apply
meta def right : tactic (list (name × expr)) :=
do tgt ← target',
[c₁, c₂] ← get_constructors_for tgt | fail "left tactic failed, target is not an inductive datatype with two constructors",
mk_const c₂ >>= apply
meta def constructor_idx (idx : nat) : tactic (list (name × expr)) :=
do cs ← target' >>= get_constructors_for,
some c ← return $ cs.nth (idx - 1) | fail "constructor_idx tactic failed, target is an inductive datatype, but it does not have sufficient constructors",
mk_const c >>= apply
meta def split : tactic (list (name × expr)) :=
do [c] ← target' >>= get_constructors_for | fail "split tactic failed, target is not an inductive datatype with only one constructor",
mk_const c >>= apply
open expr
private meta def apply_num_metavars : expr → expr → nat → tactic expr
| f ftype 0 := return f
| f ftype (n+1) := do
pi m bi d b ← whnf ftype,
a ← mk_meta_var d,
new_f ← return $ f a,
new_ftype ← return $ b.instantiate_var a,
apply_num_metavars new_f new_ftype n
meta def existsi (e : expr) : tactic unit :=
do [c] ← target' >>= get_constructors_for | fail "existsi tactic failed, target is not an inductive datatype with only one constructor",
fn ← mk_const c,
fn_type ← infer_type fn,
n ← get_arity fn,
when (n < 2) (fail "existsi tactic failed, constructor must have at least two arguments"),
t ← apply_num_metavars fn fn_type (n - 2),
eapply (app t e),
t_type ← infer_type t >>= whnf,
e_type ← infer_type e,
(guard t_type.is_pi <|> fail "existsi tactic failed, failed to infer type"),
(unify t_type.binding_domain e_type <|> fail "existsi tactic failed, type mismatch between given term witness and expected type")
end tactic
|
77e90b40664e74c2f067259aafb203451e54e6f4 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/topology/algebra/algebra.lean | 7bff5853a3d23de275052c79c7748b8239e38a72 | [
"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,361 | 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.algebra.subalgebra.basic
import topology.algebra.module.basic
import ring_theory.adjoin.basic
/-!
# Topological (sub)algebras
A topological algebra over a topological semiring `R` is a topological semiring with a compatible
continuous scalar multiplication by elements of `R`. We reuse typeclass `has_continuous_smul` for
topological algebras.
## Results
This is just a minimal stub for now!
The topological closure of a subalgebra is still a subalgebra,
which as an algebra is a topological algebra.
-/
open classical set topological_space algebra
open_locale classical
universes u v w
section topological_algebra
variables (R : Type*) (A : Type u)
variables [comm_semiring R] [semiring A] [algebra R A]
variables [topological_space R] [topological_space A] [topological_semiring A]
lemma continuous_algebra_map_iff_smul :
continuous (algebra_map R A) ↔ continuous (λ p : R × A, p.1 • p.2) :=
begin
refine ⟨λ h, _, λ h, _⟩,
{ simp only [algebra.smul_def], exact (h.comp continuous_fst).mul continuous_snd },
{ rw algebra_map_eq_smul_one', exact h.comp (continuous_id.prod_mk continuous_const) }
end
@[continuity]
lemma continuous_algebra_map [has_continuous_smul R A] :
continuous (algebra_map R A) :=
(continuous_algebra_map_iff_smul R A).2 continuous_smul
lemma has_continuous_smul_of_algebra_map (h : continuous (algebra_map R A)) :
has_continuous_smul R A :=
⟨(continuous_algebra_map_iff_smul R A).1 h⟩
variables [has_continuous_smul R A]
/-- The inclusion of the base ring in a topological algebra as a continuous linear map. -/
@[simps]
def algebra_map_clm : R →L[R] A :=
{ to_fun := algebra_map R A,
cont := continuous_algebra_map R A,
.. algebra.linear_map R A }
lemma algebra_map_clm_coe : ⇑(algebra_map_clm R A) = algebra_map R A := rfl
lemma algebra_map_clm_to_linear_map :
(algebra_map_clm R A).to_linear_map = algebra.linear_map R A := rfl
end topological_algebra
section topological_algebra
variables {R : Type*} [comm_semiring R]
variables {A : Type u} [topological_space A]
variables [semiring A] [algebra R A]
instance subalgebra.has_continuous_smul [topological_space R] [has_continuous_smul R A]
(s : subalgebra R A) :
has_continuous_smul R s :=
s.to_submodule.has_continuous_smul
variables [topological_semiring A]
/-- The closure of a subalgebra in a topological algebra as a subalgebra. -/
def subalgebra.topological_closure (s : subalgebra R A) : subalgebra R A :=
{ carrier := closure (s : set A),
algebra_map_mem' := λ r, s.to_subsemiring.subring_topological_closure (s.algebra_map_mem r),
.. s.to_subsemiring.topological_closure }
@[simp] lemma subalgebra.topological_closure_coe (s : subalgebra R A) :
(s.topological_closure : set A) = closure (s : set A) :=
rfl
instance subalgebra.topological_semiring (s : subalgebra R A) : topological_semiring s :=
s.to_subsemiring.topological_semiring
lemma subalgebra.subalgebra_topological_closure (s : subalgebra R A) :
s ≤ s.topological_closure :=
subset_closure
lemma subalgebra.is_closed_topological_closure (s : subalgebra R A) :
is_closed (s.topological_closure : set A) :=
by convert is_closed_closure
lemma subalgebra.topological_closure_minimal
(s : subalgebra R A) {t : subalgebra R A} (h : s ≤ t) (ht : is_closed (t : set A)) :
s.topological_closure ≤ t :=
closure_minimal h ht
/-- If a subalgebra of a topological algebra is commutative, then so is its topological closure. -/
def subalgebra.comm_semiring_topological_closure [t2_space A] (s : subalgebra R A)
(hs : ∀ (x y : s), x * y = y * x) : comm_semiring s.topological_closure :=
{ ..s.topological_closure.to_semiring,
..s.to_submonoid.comm_monoid_topological_closure hs }
/--
This is really a statement about topological algebra isomorphisms,
but we don't have those, so we use the clunky approach of talking about
an algebra homomorphism, and a separate homeomorphism,
along with a witness that as functions they are the same.
-/
lemma subalgebra.topological_closure_comap_homeomorph
(s : subalgebra R A)
{B : Type*} [topological_space B] [ring B] [topological_ring B] [algebra R B]
(f : B →ₐ[R] A) (f' : B ≃ₜ A) (w : (f : B → A) = f') :
s.topological_closure.comap f = (s.comap f).topological_closure :=
begin
apply set_like.ext',
simp only [subalgebra.topological_closure_coe],
simp only [subalgebra.coe_comap, subsemiring.coe_comap, alg_hom.coe_to_ring_hom],
rw [w],
exact f'.preimage_closure _,
end
end topological_algebra
section ring
variables {R : Type*} [comm_ring R]
variables {A : Type u} [topological_space A]
variables [ring A]
variables [algebra R A] [topological_ring A]
/-- If a subalgebra of a topological algebra is commutative, then so is its topological closure.
See note [reducible non-instances]. -/
@[reducible] def subalgebra.comm_ring_topological_closure [t2_space A] (s : subalgebra R A)
(hs : ∀ (x y : s), x * y = y * x) : comm_ring s.topological_closure :=
{ ..s.topological_closure.to_ring,
..s.to_submonoid.comm_monoid_topological_closure hs }
variables (R)
/-- The topological closure of the subalgebra generated by a single element. -/
def algebra.elemental_algebra (x : A) : subalgebra R A :=
(algebra.adjoin R ({x} : set A)).topological_closure
lemma algebra.self_mem_elemental_algebra (x : A) : x ∈ algebra.elemental_algebra R x :=
set_like.le_def.mp (subalgebra.subalgebra_topological_closure (algebra.adjoin R ({x} : set A))) $
algebra.self_mem_adjoin_singleton R x
variables {R}
instance [t2_space A] {x : A} : comm_ring (algebra.elemental_algebra R x) :=
subalgebra.comm_ring_topological_closure _
begin
letI : comm_ring (algebra.adjoin R ({x} : set A)) := algebra.adjoin_comm_ring_of_comm R
(λ y hy z hz, by {rw [mem_singleton_iff] at hy hz, rw [hy, hz]}),
exact λ _ _, mul_comm _ _,
end
end ring
section division_ring
/-- The action induced by `algebra_rat` is continuous. -/
instance division_ring.has_continuous_const_smul_rat
{A} [division_ring A] [topological_space A] [has_continuous_mul A] [char_zero A] :
has_continuous_const_smul ℚ A :=
⟨λ r, by { simpa only [algebra.smul_def] using continuous_const.mul continuous_id }⟩
end division_ring
|
3444df70f09b6e4a41753c76828c2b8558adfa4b | d1a52c3f208fa42c41df8278c3d280f075eb020c | /tests/lean/run/structuralEqns3.lean | 3e568ac8bc950230213227d29a012600b6ca7654 | [
"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 | 392 | lean | import Lean
open Lean
open Lean.Meta
def tst (declName : Name) : MetaM Unit := do
IO.println (← getEqnsFor? declName)
inductive Wk: Nat -> Nat -> Type 0 where
| id: Wk n n
| step: Wk m n -> Wk (Nat.succ m) n
def wk_comp : Wk n m → Wk m l → Wk n l
| Wk.id, σ => σ
| Wk.step ρ, σ => Wk.step (wk_comp ρ σ)
#eval tst ``wk_comp
#check @wk_comp.eq_1
#check @wk_comp.eq_2
|
b4a308a78f439d8a3649a4ffd4b83fe3259699f5 | 42610cc2e5db9c90269470365e6056df0122eaa0 | /hott/init/equiv.hlean | 2dda02d68a998d5e5bb670c413755818b5975a6e | [
"Apache-2.0"
] | permissive | tomsib2001/lean | 2ab59bfaebd24a62109f800dcf4a7139ebd73858 | eb639a7d53fb40175bea5c8da86b51d14bb91f76 | refs/heads/master | 1,586,128,387,740 | 1,468,968,950,000 | 1,468,968,950,000 | 61,027,234 | 0 | 0 | null | 1,465,813,585,000 | 1,465,813,585,000 | null | UTF-8 | Lean | false | false | 17,634 | hlean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad, Jakob von Raumer, Floris van Doorn
Ported from Coq HoTT
-/
prelude
import .path .function
open eq function lift
/- Equivalences -/
-- This is our definition of equivalence. In the HoTT-book it's called
-- ihae (half-adjoint equivalence).
structure is_equiv [class] {A B : Type} (f : A → B) :=
mk' ::
(inv : B → A)
(right_inv : Πb, f (inv b) = b)
(left_inv : Πa, inv (f a) = a)
(adj : Πx, right_inv (f x) = ap f (left_inv x))
attribute is_equiv.inv [reducible]
-- A more bundled version of equivalence
structure equiv (A B : Type) :=
(to_fun : A → B)
(to_is_equiv : is_equiv to_fun)
namespace is_equiv
/- Some instances and closure properties of equivalences -/
postfix ⁻¹ := inv
/- a second notation for the inverse, which is not overloaded -/
postfix [parsing_only] `⁻¹ᶠ`:std.prec.max_plus := inv
section
variables {A B C : Type} (f : A → B) (g : B → C) {f' : A → B}
-- The variant of mk' where f is explicit.
protected abbreviation mk [constructor] := @is_equiv.mk' A B f
-- The identity function is an equivalence.
definition is_equiv_id [instance] [constructor] (A : Type) : (is_equiv (id : A → A)) :=
is_equiv.mk id id (λa, idp) (λa, idp) (λa, idp)
-- The composition of two equivalences is, again, an equivalence.
definition is_equiv_compose [constructor] [Hf : is_equiv f] [Hg : is_equiv g]
: is_equiv (g ∘ f) :=
is_equiv.mk (g ∘ f) (f⁻¹ ∘ g⁻¹)
abstract (λc, ap g (right_inv f (g⁻¹ c)) ⬝ right_inv g c) end
abstract (λa, ap (inv f) (left_inv g (f a)) ⬝ left_inv f a) end
abstract (λa, (whisker_left _ (adj g (f a))) ⬝
(ap_con g _ _)⁻¹ ⬝
ap02 g ((ap_con_eq_con (right_inv f) (left_inv g (f a)))⁻¹ ⬝
(ap_compose f (inv f) _ ◾ adj f a) ⬝
(ap_con f _ _)⁻¹
) ⬝
(ap_compose g f _)⁻¹) end
-- Any function equal to an equivalence is an equivlance as well.
variable {f}
definition is_equiv_eq_closed [Hf : is_equiv f] (Heq : f = f') : is_equiv f' :=
eq.rec_on Heq Hf
end
section
parameters {A B : Type} (f : A → B) (g : B → A)
(ret : Πb, f (g b) = b) (sec : Πa, g (f a) = a)
definition adjointify_left_inv' (a : A) : g (f a) = a :=
ap g (ap f (inverse (sec a))) ⬝ ap g (ret (f a)) ⬝ sec a
theorem adjointify_adj' (a : A) : ret (f a) = ap f (adjointify_left_inv' a) :=
let fgretrfa := ap f (ap g (ret (f a))) in
let fgfinvsect := ap f (ap g (ap f (sec a)⁻¹)) in
let fgfa := f (g (f a)) in
let retrfa := ret (f a) in
have eq1 : ap f (sec a) = _,
from calc ap f (sec a)
= idp ⬝ ap f (sec a) : by rewrite idp_con
... = (ret (f a) ⬝ (ret (f a))⁻¹) ⬝ ap f (sec a) : by rewrite con.right_inv
... = ((ret fgfa)⁻¹ ⬝ ap (f ∘ g) (ret (f a))) ⬝ ap f (sec a) : by rewrite con_ap_eq_con
... = ((ret fgfa)⁻¹ ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite ap_compose
... = (ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite con.assoc,
have eq2 : ap f (sec a) ⬝ idp = (ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)),
from !con_idp ⬝ eq1,
have eq3 : idp = _,
from calc idp
= (ap f (sec a))⁻¹ ⬝ ((ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a))) : eq_inv_con_of_con_eq eq2
... = ((ap f (sec a))⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite con.assoc'
... = (ap f (sec a)⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite ap_inv
... = ((ap f (sec a)⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite con.assoc'
... = ((retrfa⁻¹ ⬝ ap (f ∘ g) (ap f (sec a)⁻¹)) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite con_ap_eq_con
... = ((retrfa⁻¹ ⬝ fgfinvsect) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite ap_compose
... = (retrfa⁻¹ ⬝ (fgfinvsect ⬝ fgretrfa)) ⬝ ap f (sec a) : by rewrite con.assoc'
... = retrfa⁻¹ ⬝ ap f (ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ ap f (sec a) : by rewrite ap_con
... = retrfa⁻¹ ⬝ (ap f (ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ ap f (sec a)) : by rewrite con.assoc'
... = retrfa⁻¹ ⬝ ap f ((ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ sec a) : by rewrite -ap_con,
show ret (f a) = ap f ((ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ sec a),
from eq_of_idp_eq_inv_con eq3
definition adjointify [constructor] : is_equiv f :=
is_equiv.mk f g ret adjointify_left_inv' adjointify_adj'
end
-- Any function pointwise equal to an equivalence is an equivalence as well.
definition homotopy_closed [constructor] {A B : Type} (f : A → B) {f' : A → B} [Hf : is_equiv f]
(Hty : f ~ f') : is_equiv f' :=
adjointify f'
(inv f)
(λ b, (Hty (inv f b))⁻¹ ⬝ right_inv f b)
(λ a, (ap (inv f) (Hty a))⁻¹ ⬝ left_inv f a)
definition inv_homotopy_closed [constructor] {A B : Type} {f : A → B} {f' : B → A}
[Hf : is_equiv f] (Hty : f⁻¹ ~ f') : is_equiv f :=
adjointify f
f'
(λ b, ap f !Hty⁻¹ ⬝ right_inv f b)
(λ a, !Hty⁻¹ ⬝ left_inv f a)
definition is_equiv_up [instance] [constructor] (A : Type)
: is_equiv (up : A → lift A) :=
adjointify up down (λa, by induction a;reflexivity) (λa, idp)
section
variables {A B C : Type} (f : A → B) {f' : A → B} [Hf : is_equiv f] (g : B → C)
include Hf
--The inverse of an equivalence is, again, an equivalence.
definition is_equiv_inv [instance] [constructor] : is_equiv f⁻¹ :=
adjointify f⁻¹ f (left_inv f) (right_inv f)
-- The 2-out-of-3 properties
definition cancel_right (g : B → C) [Hgf : is_equiv (g ∘ f)] : (is_equiv g) :=
have Hfinv : is_equiv f⁻¹, from is_equiv_inv f,
@homotopy_closed _ _ _ _ (is_equiv_compose f⁻¹ (g ∘ f)) (λb, ap g (@right_inv _ _ f _ b))
definition cancel_left (g : C → A) [Hgf : is_equiv (f ∘ g)] : (is_equiv g) :=
have Hfinv : is_equiv f⁻¹, from is_equiv_inv f,
@homotopy_closed _ _ _ _ (is_equiv_compose (f ∘ g) f⁻¹) (λa, left_inv f (g a))
definition eq_of_fn_eq_fn' {x y : A} (q : f x = f y) : x = y :=
(left_inv f x)⁻¹ ⬝ ap f⁻¹ q ⬝ left_inv f y
definition ap_eq_of_fn_eq_fn' {x y : A} (q : f x = f y) : ap f (eq_of_fn_eq_fn' f q) = q :=
!ap_con ⬝ whisker_right !ap_con _
⬝ ((!ap_inv ⬝ inverse2 (adj f _)⁻¹)
◾ (inverse (ap_compose f f⁻¹ _))
◾ (adj f _)⁻¹)
⬝ con_ap_con_eq_con_con (right_inv f) _ _
⬝ whisker_right !con.left_inv _
⬝ !idp_con
definition eq_of_fn_eq_fn'_ap {x y : A} (q : x = y) : eq_of_fn_eq_fn' f (ap f q) = q :=
by induction q; apply con.left_inv
definition is_equiv_ap [instance] [constructor] (x y : A) : is_equiv (ap f : x = y → f x = f y) :=
adjointify
(ap f)
(eq_of_fn_eq_fn' f)
(ap_eq_of_fn_eq_fn' f)
(eq_of_fn_eq_fn'_ap f)
-- The function equiv_rect says that given an equivalence f : A → B,
-- and a hypothesis from B, one may always assume that the hypothesis
-- is in the image of e.
-- In fibrational terms, if we have a fibration over B which has a section
-- once pulled back along an equivalence f : A → B, then it has a section
-- over all of B.
definition is_equiv_rect (P : B → Type) (g : Πa, P (f a)) (b : B) : P b :=
right_inv f b ▸ g (f⁻¹ b)
definition is_equiv_rect' (P : A → B → Type) (g : Πb, P (f⁻¹ b) b) (a : A) : P a (f a) :=
left_inv f a ▸ g (f a)
definition is_equiv_rect_comp (P : B → Type)
(df : Π (x : A), P (f x)) (x : A) : is_equiv_rect f P df (f x) = df x :=
calc
is_equiv_rect f P df (f x)
= right_inv f (f x) ▸ df (f⁻¹ (f x)) : by esimp
... = ap f (left_inv f x) ▸ df (f⁻¹ (f x)) : by rewrite -adj
... = left_inv f x ▸ df (f⁻¹ (f x)) : by rewrite -tr_compose
... = df x : by rewrite (apdt df (left_inv f x))
theorem adj_inv (b : B) : left_inv f (f⁻¹ b) = ap f⁻¹ (right_inv f b) :=
is_equiv_rect f _
(λa, eq.cancel_right (left_inv f (id a))
(whisker_left _ !ap_id⁻¹ ⬝ (ap_con_eq_con_ap (left_inv f) (left_inv f a))⁻¹) ⬝
!ap_compose ⬝ ap02 f⁻¹ (adj f a)⁻¹)
b
end
section
variables {A B C : Type} {f : A → B} [Hf : is_equiv f]
include Hf
section rewrite_rules
variables {a : A} {b : B}
definition eq_of_eq_inv (p : a = f⁻¹ b) : f a = b :=
ap f p ⬝ right_inv f b
definition eq_of_inv_eq (p : f⁻¹ b = a) : b = f a :=
(eq_of_eq_inv p⁻¹)⁻¹
definition inv_eq_of_eq (p : b = f a) : f⁻¹ b = a :=
ap f⁻¹ p ⬝ left_inv f a
definition eq_inv_of_eq (p : f a = b) : a = f⁻¹ b :=
(inv_eq_of_eq p⁻¹)⁻¹
end rewrite_rules
variable (f)
section pre_compose
variables (α : A → C) (β : B → C)
definition homotopy_of_homotopy_inv_pre (p : β ~ α ∘ f⁻¹) : β ∘ f ~ α :=
λ a, p (f a) ⬝ ap α (left_inv f a)
definition homotopy_of_inv_homotopy_pre (p : α ∘ f⁻¹ ~ β) : α ~ β ∘ f :=
λ a, (ap α (left_inv f a))⁻¹ ⬝ p (f a)
definition inv_homotopy_of_homotopy_pre (p : α ~ β ∘ f) : α ∘ f⁻¹ ~ β :=
λ b, p (f⁻¹ b) ⬝ ap β (right_inv f b)
definition homotopy_inv_of_homotopy_pre (p : β ∘ f ~ α) : β ~ α ∘ f⁻¹ :=
λ b, (ap β (right_inv f b))⁻¹ ⬝ p (f⁻¹ b)
end pre_compose
section post_compose
variables (α : C → A) (β : C → B)
definition homotopy_of_homotopy_inv_post (p : α ~ f⁻¹ ∘ β) : f ∘ α ~ β :=
λ c, ap f (p c) ⬝ (right_inv f (β c))
definition homotopy_of_inv_homotopy_post (p : f⁻¹ ∘ β ~ α) : β ~ f ∘ α :=
λ c, (right_inv f (β c))⁻¹ ⬝ ap f (p c)
definition inv_homotopy_of_homotopy_post (p : β ~ f ∘ α) : f⁻¹ ∘ β ~ α :=
λ c, ap f⁻¹ (p c) ⬝ (left_inv f (α c))
definition homotopy_inv_of_homotopy_post (p : f ∘ α ~ β) : α ~ f⁻¹ ∘ β :=
λ c, (left_inv f (α c))⁻¹ ⬝ ap f⁻¹ (p c)
end post_compose
end
--Transporting is an equivalence
definition is_equiv_tr [constructor] {A : Type} (P : A → Type) {x y : A}
(p : x = y) : (is_equiv (transport P p)) :=
is_equiv.mk _ (transport P p⁻¹) (tr_inv_tr p) (inv_tr_tr p) (tr_inv_tr_lemma p)
section
variables {A : Type} {B C : A → Type} (f : Π{a}, B a → C a) [H : Πa, is_equiv (@f a)]
{g : A → A} {g' : A → A} (h : Π{a}, B (g' a) → B (g a)) (h' : Π{a}, C (g' a) → C (g a))
include H
definition inv_commute' (p : Π⦃a : A⦄ (b : B (g' a)), f (h b) = h' (f b)) {a : A}
(c : C (g' a)) : f⁻¹ (h' c) = h (f⁻¹ c) :=
eq_of_fn_eq_fn' f (right_inv f (h' c) ⬝ ap h' (right_inv f c)⁻¹ ⬝ (p (f⁻¹ c))⁻¹)
definition fun_commute_of_inv_commute' (p : Π⦃a : A⦄ (c : C (g' a)), f⁻¹ (h' c) = h (f⁻¹ c))
{a : A} (b : B (g' a)) : f (h b) = h' (f b) :=
eq_of_fn_eq_fn' f⁻¹ (left_inv f (h b) ⬝ ap h (left_inv f b)⁻¹ ⬝ (p (f b))⁻¹)
definition ap_inv_commute' (p : Π⦃a : A⦄ (b : B (g' a)), f (h b) = h' (f b)) {a : A}
(c : C (g' a)) : ap f (inv_commute' @f @h @h' p c)
= right_inv f (h' c) ⬝ ap h' (right_inv f c)⁻¹ ⬝ (p (f⁻¹ c))⁻¹ :=
!ap_eq_of_fn_eq_fn'
end
-- This is inv_commute' for A ≡ unit
definition inv_commute1' {B C : Type} (f : B → C) [is_equiv f] (h : B → B) (h' : C → C)
(p : Π(b : B), f (h b) = h' (f b)) (c : C) : f⁻¹ (h' c) = h (f⁻¹ c) :=
eq_of_fn_eq_fn' f (right_inv f (h' c) ⬝ ap h' (right_inv f c)⁻¹ ⬝ (p (f⁻¹ c))⁻¹)
end is_equiv
open is_equiv
namespace eq
local attribute is_equiv_tr [instance]
definition tr_inv_fn {A : Type} {B : A → Type} {a a' : A} (p : a = a') :
transport B p⁻¹ = (transport B p)⁻¹ := idp
definition tr_inv {A : Type} {B : A → Type} {a a' : A} (p : a = a') (b : B a') :
p⁻¹ ▸ b = (transport B p)⁻¹ b := idp
definition cast_inv_fn {A B : Type} (p : A = B) : cast p⁻¹ = (cast p)⁻¹ := idp
definition cast_inv {A B : Type} (p : A = B) (b : B) : cast p⁻¹ b = (cast p)⁻¹ b := idp
end eq
infix ` ≃ `:25 := equiv
attribute equiv.to_is_equiv [instance]
namespace equiv
attribute to_fun [coercion]
section
variables {A B C : Type}
protected definition MK [reducible] [constructor] (f : A → B) (g : B → A)
(right_inv : Πb, f (g b) = b) (left_inv : Πa, g (f a) = a) : A ≃ B :=
equiv.mk f (adjointify f g right_inv left_inv)
definition to_inv [reducible] [unfold 3] (f : A ≃ B) : B → A := f⁻¹
definition to_right_inv [reducible] [unfold 3] (f : A ≃ B) (b : B) : f (f⁻¹ b) = b :=
right_inv f b
definition to_left_inv [reducible] [unfold 3] (f : A ≃ B) (a : A) : f⁻¹ (f a) = a :=
left_inv f a
protected definition rfl [refl] [constructor] : A ≃ A :=
equiv.mk id !is_equiv_id
protected definition refl [constructor] [reducible] (A : Type) : A ≃ A :=
@equiv.rfl A
protected definition symm [symm] [constructor] (f : A ≃ B) : B ≃ A :=
equiv.mk f⁻¹ !is_equiv_inv
protected definition trans [trans] [constructor] (f : A ≃ B) (g : B ≃ C) : A ≃ C :=
equiv.mk (g ∘ f) !is_equiv_compose
infixl ` ⬝e `:75 := equiv.trans
postfix `⁻¹ᵉ`:(max + 1) := equiv.symm
-- notation for inverse which is not overloaded
abbreviation erfl [constructor] := @equiv.rfl
definition to_inv_trans [reducible] [unfold_full] (f : A ≃ B) (g : B ≃ C)
: to_inv (f ⬝e g) = to_fun (g⁻¹ᵉ ⬝e f⁻¹ᵉ) :=
idp
definition equiv_change_fun [constructor] (f : A ≃ B) {f' : A → B} (Heq : f ~ f') : A ≃ B :=
equiv.mk f' (is_equiv.homotopy_closed f Heq)
definition equiv_change_inv [constructor] (f : A ≃ B) {f' : B → A} (Heq : f⁻¹ ~ f')
: A ≃ B :=
equiv.mk f (inv_homotopy_closed Heq)
--rename: eq_equiv_fn_eq_of_is_equiv
definition eq_equiv_fn_eq [constructor] (f : A → B) [H : is_equiv f] (a b : A) : (a = b) ≃ (f a = f b) :=
equiv.mk (ap f) !is_equiv_ap
--rename: eq_equiv_fn_eq
definition eq_equiv_fn_eq_of_equiv [constructor] (f : A ≃ B) (a b : A) : (a = b) ≃ (f a = f b) :=
equiv.mk (ap f) !is_equiv_ap
definition equiv_ap [constructor] (P : A → Type) {a b : A} (p : a = b) : P a ≃ P b :=
equiv.mk (transport P p) !is_equiv_tr
definition equiv_of_eq [constructor] {A B : Type} (p : A = B) : A ≃ B :=
equiv.mk (cast p) !is_equiv_tr
definition eq_of_fn_eq_fn (f : A ≃ B) {x y : A} (q : f x = f y) : x = y :=
(left_inv f x)⁻¹ ⬝ ap f⁻¹ q ⬝ left_inv f y
definition eq_of_fn_eq_fn_inv (f : A ≃ B) {x y : B} (q : f⁻¹ x = f⁻¹ y) : x = y :=
(right_inv f x)⁻¹ ⬝ ap f q ⬝ right_inv f y
--we need this theorem for the funext_of_ua proof
theorem inv_eq {A B : Type} (eqf eqg : A ≃ B) (p : eqf = eqg) : (to_fun eqf)⁻¹ = (to_fun eqg)⁻¹ :=
eq.rec_on p idp
definition equiv_of_equiv_of_eq [trans] {A B C : Type} (p : A = B) (q : B ≃ C) : A ≃ C :=
equiv_of_eq p ⬝e q
definition equiv_of_eq_of_equiv [trans] {A B C : Type} (p : A ≃ B) (q : B = C) : A ≃ C :=
p ⬝e equiv_of_eq q
definition equiv_lift [constructor] (A : Type) : A ≃ lift A := equiv.mk up _
definition equiv_rect (f : A ≃ B) (P : B → Type) (g : Πa, P (f a)) (b : B) : P b :=
right_inv f b ▸ g (f⁻¹ b)
definition equiv_rect' (f : A ≃ B) (P : A → B → Type) (g : Πb, P (f⁻¹ b) b) (a : A) : P a (f a) :=
left_inv f a ▸ g (f a)
definition equiv_rect_comp (f : A ≃ B) (P : B → Type)
(df : Π (x : A), P (f x)) (x : A) : equiv_rect f P df (f x) = df x :=
calc
equiv_rect f P df (f x)
= right_inv f (f x) ▸ df (f⁻¹ (f x)) : by esimp
... = ap f (left_inv f x) ▸ df (f⁻¹ (f x)) : by rewrite -adj
... = left_inv f x ▸ df (f⁻¹ (f x)) : by rewrite -tr_compose
... = df x : by rewrite (apdt df (left_inv f x))
end
section
variables {A : Type} {B C : A → Type} (f : Π{a}, B a ≃ C a)
{g : A → A} {g' : A → A} (h : Π{a}, B (g' a) → B (g a)) (h' : Π{a}, C (g' a) → C (g a))
definition inv_commute (p : Π⦃a : A⦄ (b : B (g' a)), f (h b) = h' (f b)) {a : A}
(c : C (g' a)) : f⁻¹ (h' c) = h (f⁻¹ c) :=
inv_commute' @f @h @h' p c
definition fun_commute_of_inv_commute (p : Π⦃a : A⦄ (c : C (g' a)), f⁻¹ (h' c) = h (f⁻¹ c))
{a : A} (b : B (g' a)) : f (h b) = h' (f b) :=
fun_commute_of_inv_commute' @f @h @h' p b
definition inv_commute1 {B C : Type} (f : B ≃ C) (h : B → B) (h' : C → C)
(p : Π(b : B), f (h b) = h' (f b)) (c : C) : f⁻¹ (h' c) = h (f⁻¹ c) :=
inv_commute1' (to_fun f) h h' p c
end
infixl ` ⬝pe `:75 := equiv_of_equiv_of_eq
infixl ` ⬝ep `:75 := equiv_of_eq_of_equiv
end equiv
open equiv
namespace is_equiv
definition is_equiv_of_equiv_of_homotopy [constructor] {A B : Type} (f : A ≃ B)
{f' : A → B} (Hty : f ~ f') : is_equiv f' :=
homotopy_closed f Hty
end is_equiv
export [unfold] equiv
export [unfold] is_equiv
|
50e266f2b1eb6fcba5d3d681372bbe2386619b4f | fcf3ffa92a3847189ca669cb18b34ef6b2ec2859 | /src/world2/level1.lean | 961f295586a3032dc1cff9fdbc03ff71b91a5dee | [
"Apache-2.0"
] | permissive | nomoid/lean-proofs | 4a80a97888699dee42b092b7b959b22d9aa0c066 | b9f03a24623d1a1d111d6c2bbf53c617e2596d6a | refs/heads/master | 1,674,955,317,080 | 1,607,475,706,000 | 1,607,475,706,000 | 314,104,281 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 274 | lean | import mynat.definition
import mynat.add
namespace mynat
lemma zero_add (n : mynat) : 0 + n = n :=
begin [nat_num_game]
induction n with d hd,
{
rw add_zero,
refl,
},
{
rw add_succ,
rw hd,
refl,
},
end
end mynat |
92717021a3d57a653734747493c5544bfe1b7725 | b186c784450e8bcbcf835ab3f10fa7e73f27bc2e | /existential_quantifier.lean | 85651f453f882f49a627f91bd4f9648ad488aaaa | [] | no_license | esclear/Learning-Lean | 9780a0efe769e275992cf3ab4ebf55809ec53b48 | d81d5c4743b94c96d8f1bb135e1f13a1d99b3154 | refs/heads/master | 1,593,312,896,806 | 1,565,904,243,000 | 1,565,904,243,000 | 200,125,941 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,949 | lean | open classical
variables (α : Type) (p q : α → Prop)
variable a : α
variable r : Prop
theorem dne {p : Prop} (hp : ¬¬p) : p :=
by_contradiction (assume hnp : ¬p, absurd hnp hp)
--
example : (∃ x : α, r) → r :=
assume h : (∃ x : α, r),
exists.elim h
(assume w,
assume hr : r,
hr)
example : r → (∃ x : α, r) :=
assume hr : r,
show ∃ x : α, r, from ⟨a, hr⟩
example : (∃ x, p x ∧ r) ↔ (∃ x, p x) ∧ r :=
iff.intro
(assume h : (∃ x, p x ∧ r),
match h with ⟨w, hpw, hr⟩ :=
⟨⟨w, hpw⟩, hr⟩
end)
(assume h : (∃ x, p x) ∧ r,
match h with ⟨⟨w, hpw⟩, hr⟩ :=
⟨w, ⟨hpw, hr⟩⟩
end)
example : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) :=
iff.intro
(assume h : (∃ x, p x ∨ q x),
match h with ⟨w, hpqw⟩ :=
hpqw.elim
(assume hpw : p w,
show (∃ x, p x) ∨ (∃ x, q x), from or.inl ⟨w, hpw⟩)
(assume hqw : q w,
show (∃ x, p x) ∨ (∃ x, q x), from or.inr ⟨w, hqw⟩)
end)
(assume h : (∃ x, p x) ∨ (∃ x, q x),
h.elim
(assume h : (∃ x, p x),
match h with ⟨w, hpw⟩ := ⟨w, or.inl hpw⟩
end)
(assume h : (∃ x, q x),
match h with ⟨w, hqw⟩ := ⟨w, or.inr hqw⟩
end))
--
example : (∀ x, p x) ↔ ¬ (∃ x, ¬ p x) :=
iff.intro
(assume h : ∀ x, p x,
assume hn : ∃ y, ¬ p y,
match hn with ⟨w, hnpw⟩ :=
have hpw : p w, from h w,
absurd hpw hnpw
end)
(assume h : ¬ (∃ x, ¬ p x),
assume x,
have dnp : ¬¬ p x, from (
assume hnpx : ¬ p x,
have hen : ∃ x, ¬ p x, from ⟨x, hnpx⟩,
absurd hen h
),
dne dnp)
example : (∃ x, p x) ↔ ¬ (∀ x, ¬ p x) :=
iff.intro
(assume h : ∃ x, p x,
show ¬(∀ x, ¬ p x), from (
assume hfnp : ∀ x, ¬p x,
match h with ⟨w, hpw⟩ :=
have hnpw : ¬p w, from hfnp w,
absurd hpw hnpw
end
))
(assume h : ¬(∀ x, ¬p x),
by_contradiction
(assume hnex : ¬(∃ x, p x),
have ha : ∀ x, ¬p x, from (
assume x,
assume hp : p x,
have hex: ∃ x, p x, from ⟨x, hp⟩,
absurd hex hnex
),
h ha))
example : (¬ ∃ x, p x) ↔ (∀ x, ¬ p x) :=
iff.intro
(assume h : ¬ ∃ x, p x,
assume x,
show ¬ p x, from (
assume hp : p x,
absurd (exists.intro x hp) h
))
(assume h : ∀ x, ¬ p x,
assume hex : ∃ x, p x,
exists.elim hex (
assume w,
assume hp : p w,
absurd hp (h w)
))
example : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) :=
iff.intro
(assume h : ¬ ∀ x, p x,
by_contradiction
(assume h' : ¬ ∃ x, ¬ p x,
have hfp : ∀ x, p x, from (
assume x,
show p x, from by_contradiction (
assume hnp : ¬ p x,
absurd (exists.intro x hnp) h'
)
),
absurd hfp h))
(assume ⟨w, (hnpw : ¬ p w)⟩,
assume hfp : ∀ x, p x,
absurd (hfp w) hnpw)
--
example : (∀ x, p x → r) ↔ (∃ x, p x) → r :=
iff.intro
(assume h : ∀ x, p x → r,
assume ⟨w, (hpw : p w)⟩,
(h w) hpw)
(assume h : (∃ x, p x) → r,
assume x,
assume hpx : p x,
h ⟨x, hpx⟩)
example : (∃ x, p x → r) ↔ (∀ x, p x) → r :=
iff.intro
(assume ⟨w, (hw : p w → r)⟩,
assume h : ∀ x, p x,
hw (h w))
(assume h : (∀ x, p x) → r,
show ∃ x, p x → r, from
by_cases
(assume hap : ∀ x, p x,
⟨a, (λ h', h hap)⟩)
(assume hnap : ¬(∀ x, p x),
by_contradiction
(assume hnex : ¬ ∃ x, p x → r,
have hap : ∀ x, p x,
from
(assume x,
by_contradiction
(assume hnp : ¬ p x,
have hex : ∃ x, p x → r, from (
have hpair : p x → r, from (assume hpx : p x, absurd hpx hnp),
⟨x, hpair⟩
),
absurd hex hnex)),
absurd hap hnap)
)
)
example : (∃ x, r → p x) ↔ (r → ∃ x, p x) :=
iff.intro
(assume ⟨w, ripw⟩,
assume hr : r,
⟨w, ripw hr⟩)
(assume h : r → ∃ x, p x,
by_cases
(assume hr : r,
match h hr with ⟨w, hpw⟩ :=
have hi : r → p w, from (assume r, hpw),
⟨w, hi⟩
end)
(assume hnr : ¬r,
have hpa : r → p a, from (
assume hr : r,
absurd hr hnr),
⟨a, hpa⟩)) |
ef15f5efe4fa548b93a64b53b01cd3ac2a5233e0 | 367134ba5a65885e863bdc4507601606690974c1 | /src/measure_theory/giry_monad.lean | 30ec040b36595a9c486f4b3f7af4cdec94e3b6ab | [
"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 | 8,045 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import measure_theory.integration
/-!
# The Giry monad
Let X be a measurable space. The collection of all measures on X again
forms a measurable space. This construction forms a monad on
measurable spaces and measurable functions, called the Giry monad.
Note that most sources use the term "Giry monad" for the restriction
to *probability* measures. Here we include all measures on X.
See also `measure_theory/category/Meas.lean`, containing an upgrade of the type-level
monad to an honest monad of the functor `Measure : Meas ⥤ Meas`.
## References
* <https://ncatlab.org/nlab/show/Giry+monad>
## Tags
giry monad
-/
noncomputable theory
open_locale classical big_operators ennreal
open classical set filter
variables {α β γ δ ε : Type*}
namespace measure_theory
namespace measure
variables [measurable_space α] [measurable_space β]
/-- Measurability structure on `measure`: Measures are measurable w.r.t. all projections -/
instance : measurable_space (measure α) :=
⨆ (s : set α) (hs : measurable_set s), (borel ℝ≥0∞).comap (λμ, μ s)
lemma measurable_coe {s : set α} (hs : measurable_set s) : measurable (λμ : measure α, μ s) :=
measurable.of_comap_le $ le_supr_of_le s $ le_supr_of_le hs $ le_refl _
lemma measurable_of_measurable_coe (f : β → measure α)
(h : ∀(s : set α) (hs : measurable_set s), measurable (λb, f b s)) :
measurable f :=
measurable.of_le_map $ bsupr_le $ assume s hs, measurable_space.comap_le_iff_le_map.2 $
by rw [measurable_space.map_comp]; exact h s hs
lemma measurable_measure {μ : α → measure β} :
measurable μ ↔ ∀(s : set β) (hs : measurable_set s), measurable (λb, μ b s) :=
⟨λ hμ s hs, (measurable_coe hs).comp hμ, measurable_of_measurable_coe μ⟩
lemma measurable_map (f : α → β) (hf : measurable f) :
measurable (λμ : measure α, map f μ) :=
measurable_of_measurable_coe _ $ assume s hs,
suffices measurable (λ (μ : measure α), μ (f ⁻¹' s)),
by simpa [map_apply, hs, hf],
measurable_coe (hf hs)
lemma measurable_dirac :
measurable (measure.dirac : α → measure α) :=
measurable_of_measurable_coe _ $ assume s hs,
begin
simp only [dirac_apply', hs],
exact measurable_one.indicator hs
end
lemma measurable_lintegral {f : α → ℝ≥0∞} (hf : measurable f) :
measurable (λμ : measure α, ∫⁻ x, f x ∂μ) :=
begin
simp only [lintegral_eq_supr_eapprox_lintegral, hf, simple_func.lintegral],
refine measurable_supr (λ n, finset.measurable_sum _ (λ i, _)),
refine measurable_const.ennreal_mul _,
exact measurable_coe ((simple_func.eapprox f n).measurable_set_preimage _)
end
/-- Monadic join on `measure` in the category of measurable spaces and measurable
functions. -/
def join (m : measure (measure α)) : measure α :=
measure.of_measurable
(λs hs, ∫⁻ μ, μ s ∂m)
(by simp)
begin
assume f hf h,
simp [measure_Union h hf],
apply lintegral_tsum,
assume i, exact measurable_coe (hf i)
end
@[simp] lemma join_apply {m : measure (measure α)} :
∀{s : set α}, measurable_set s → join m s = ∫⁻ μ, μ s ∂m :=
measure.of_measurable_apply
lemma measurable_join : measurable (join : measure (measure α) → measure α) :=
measurable_of_measurable_coe _ $ assume s hs,
by simp only [join_apply hs]; exact measurable_lintegral (measurable_coe hs)
lemma lintegral_join {m : measure (measure α)} {f : α → ℝ≥0∞} (hf : measurable f) :
∫⁻ x, f x ∂(join m) = ∫⁻ μ, ∫⁻ x, f x ∂μ ∂m :=
begin
rw [lintegral_eq_supr_eapprox_lintegral hf],
have : ∀n x,
join m (⇑(simple_func.eapprox (λ (a : α), f a) n) ⁻¹' {x}) =
∫⁻ μ, μ ((⇑(simple_func.eapprox (λ (a : α), f a) n) ⁻¹' {x})) ∂m :=
assume n x, join_apply (simple_func.measurable_set_preimage _ _),
simp only [simple_func.lintegral, this],
transitivity,
have : ∀(s : ℕ → finset ℝ≥0∞) (f : ℕ → ℝ≥0∞ → measure α → ℝ≥0∞)
(hf : ∀n r, measurable (f n r)) (hm : monotone (λn μ, ∑ r in s n, r * f n r μ)),
(⨆n:ℕ, ∑ r in s n, r * ∫⁻ μ, f n r μ ∂m) =
∫⁻ μ, ⨆n:ℕ, ∑ r in s n, r * f n r μ ∂m,
{ assume s f hf hm,
symmetry,
transitivity,
apply lintegral_supr,
{ assume n,
exact finset.measurable_sum _ (assume r, measurable_const.ennreal_mul (hf _ _)) },
{ exact hm },
congr, funext n,
transitivity,
apply lintegral_finset_sum,
{ assume r, exact measurable_const.ennreal_mul (hf _ _) },
congr, funext r,
apply lintegral_const_mul,
exact hf _ _ },
specialize this (λn, simple_func.range (simple_func.eapprox f n)),
specialize this
(λn r μ, μ (⇑(simple_func.eapprox (λ (a : α), f a) n) ⁻¹' {r})),
refine this _ _; clear this,
{ assume n r,
apply measurable_coe,
exact simple_func.measurable_set_preimage _ _ },
{ change monotone (λn μ, (simple_func.eapprox f n).lintegral μ),
assume n m h μ,
refine simple_func.lintegral_mono _ (le_refl _),
apply simple_func.monotone_eapprox,
assumption },
congr, funext μ,
symmetry,
apply lintegral_eq_supr_eapprox_lintegral,
exact hf
end
/-- Monadic bind on `measure`, only works in the category of measurable spaces and measurable
functions. When the function `f` is not measurable the result is not well defined. -/
def bind (m : measure α) (f : α → measure β) : measure β := join (map f m)
@[simp] lemma bind_apply {m : measure α} {f : α → measure β} {s : set β}
(hs : measurable_set s) (hf : measurable f) :
bind m f s = ∫⁻ a, f a s ∂m :=
by rw [bind, join_apply hs, lintegral_map (measurable_coe hs) hf]
lemma measurable_bind' {g : α → measure β} (hg : measurable g) : measurable (λm, bind m g) :=
measurable_join.comp (measurable_map _ hg)
lemma lintegral_bind {m : measure α} {μ : α → measure β} {f : β → ℝ≥0∞}
(hμ : measurable μ) (hf : measurable f) :
∫⁻ x, f x ∂ (bind m μ) = ∫⁻ a, ∫⁻ x, f x ∂(μ a) ∂m:=
(lintegral_join hf).trans (lintegral_map (measurable_lintegral hf) hμ)
lemma bind_bind {γ} [measurable_space γ] {m : measure α} {f : α → measure β} {g : β → measure γ}
(hf : measurable f) (hg : measurable g) :
bind (bind m f) g = bind m (λa, bind (f a) g) :=
measure.ext $ assume s hs,
begin
rw [bind_apply hs hg, bind_apply hs ((measurable_bind' hg).comp hf), lintegral_bind hf],
{ congr, funext a,
exact (bind_apply hs hg).symm },
exact (measurable_coe hs).comp hg
end
lemma bind_dirac {f : α → measure β} (hf : measurable f) (a : α) : bind (dirac a) f = f a :=
measure.ext $ λ s hs, by rw [bind_apply hs hf, lintegral_dirac' a ((measurable_coe hs).comp hf)]
lemma dirac_bind {m : measure α} : bind m dirac = m :=
measure.ext $ assume s hs,
by simp [bind_apply hs measurable_dirac, dirac_apply' _ hs, lintegral_indicator 1 hs]
lemma join_eq_bind (μ : measure (measure α)) : join μ = bind μ id :=
by rw [bind, map_id]
lemma join_map_map {f : α → β} (hf : measurable f) (μ : measure (measure α)) :
join (map (map f) μ) = map f (join μ) :=
measure.ext $ assume s hs,
begin
rw [join_apply hs, map_apply hf hs, join_apply,
lintegral_map (measurable_coe hs) (measurable_map f hf)],
{ congr, funext ν, exact map_apply hf hs },
exact hf hs
end
lemma join_map_join (μ : measure (measure (measure α))) :
join (map join μ) = join (join μ) :=
begin
show bind μ join = join (join μ),
rw [join_eq_bind, join_eq_bind, bind_bind measurable_id measurable_id],
apply congr_arg (bind μ),
funext ν,
exact join_eq_bind ν
end
lemma join_map_dirac (μ : measure α) : join (map dirac μ) = μ :=
dirac_bind
lemma join_dirac (μ : measure α) : join (dirac μ) = μ :=
eq.trans (join_eq_bind (dirac μ)) (bind_dirac measurable_id _)
end measure
end measure_theory
|
26e95097e567b829b4ab90e1f37b4ae2a4f81e11 | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /src/Lean/Meta/ReduceEval.lean | 6c867be77601a31735fe94587829808984c1d209 | [
"Apache-2.0"
] | permissive | WojciechKarpiel/lean4 | 7f89706b8e3c1f942b83a2c91a3a00b05da0e65b | f6e1314fa08293dea66a329e05b6c196a0189163 | refs/heads/master | 1,686,633,402,214 | 1,625,821,189,000 | 1,625,821,258,000 | 384,640,886 | 0 | 0 | Apache-2.0 | 1,625,903,617,000 | 1,625,903,026,000 | null | UTF-8 | Lean | false | false | 1,872 | lean | /-
Copyright (c) 2020 Sebastian Ullrich. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
-/
/-! Evaluation by reduction -/
import Lean.Meta.Offset
namespace Lean.Meta
class ReduceEval (α : Type) where
reduceEval : Expr → MetaM α
def reduceEval [ReduceEval α] (e : Expr) : MetaM α :=
withAtLeastTransparency TransparencyMode.default $
ReduceEval.reduceEval e
private def throwFailedToEval (e : Expr) : MetaM α :=
throwError "reduceEval: failed to evaluate argument{indentExpr e}"
instance : ReduceEval Nat where
reduceEval e := do
let e ← whnf e
let some n ← evalNat e | throwFailedToEval e
pure n
instance [ReduceEval α] : ReduceEval (Option α) where
reduceEval e := do
let e ← whnf e
let Expr.const c .. ← pure e.getAppFn | throwFailedToEval e
let nargs := e.getAppNumArgs
if c == `Option.none && nargs == 0 then pure none
else if c == `Option.some && nargs == 1 then some <$> reduceEval e.appArg!
else throwFailedToEval e
instance : ReduceEval String where
reduceEval e := do
let Expr.lit (Literal.strVal s) _ ← whnf e | throwFailedToEval e
pure s
private partial def evalName (e : Expr) : MetaM Name := do
let e ← whnf e
let Expr.const c _ _ ← pure e.getAppFn | throwFailedToEval e
let nargs := e.getAppNumArgs
if c == `Lean.Name.anonymous && nargs == 0 then pure Name.anonymous
else if c == `Lean.Name.str && nargs == 3 then do
let n ← evalName $ e.getArg! 0
let s ← reduceEval $ e.getArg! 1
pure $ Name.mkStr n s
else if c == `Lean.Name.num && nargs == 3 then do
let n ← evalName $ e.getArg! 0
let u ← reduceEval $ e.getArg! 1
pure $ Name.mkNum n u
else
throwFailedToEval e
instance : ReduceEval Name where
reduceEval := evalName
end Lean.Meta
|
41ec48179c8a30ef9520e3609d9602bfd56b818d | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/representation_theory/maschke.lean | a1ae33acd1db1ba61af23d3a428cbec0e3d1dbdd | [
"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 | 5,896 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Scott Morrison
-/
import algebra.monoid_algebra
import algebra.invertible
import algebra.char_p
import linear_algebra.basis
/-!
# Maschke's theorem
We prove Maschke's theorem for finite groups,
in the formulation that every submodule of a `k[G]` module has a complement,
when `k` is a field with `¬(ring_char k ∣ fintype.card G)`.
We do the core computation in greater generality.
For any `[comm_ring k]` in which `[invertible (fintype.card G : k)]`,
and a `k[G]`-linear map `i : V → W` which admits a `k`-linear retraction `π`,
we produce a `k[G]`-linear retraction by
taking the average over `G` of the conjugates of `π`.
## Future work
It's not so far to give the usual statement, that every finite dimensional representation
of a finite group is semisimple (i.e. a direct sum of irreducibles).
-/
universes u
noncomputable theory
open semimodule
open monoid_algebra
open_locale big_operators
section
-- At first we work with any `[comm_ring k]`, and add the assumption that
-- `[invertible (fintype.card G : k)]` when it is required.
variables {k : Type u} [comm_ring k] {G : Type u} [group G]
variables {V : Type u} [add_comm_group V] [module (monoid_algebra k G) V]
variables {W : Type u} [add_comm_group W] [module (monoid_algebra k G) W]
/-!
We now do the key calculation in Maschke's theorem.
Given `V → W`, an inclusion of `k[G]` modules,,
assume we have some retraction `π` (i.e. `∀ v, π (i v) = v`),
just as a `k`-linear map.
(When `k` is a field, this will be available cheaply, by choosing a basis.)
We now construct a retraction of the inclusion as a `k[G]`-linear map,
by the formula
$$ \frac{1}{|G|} \sum_{g \in G} g⁻¹ • π(g • -). $$
-/
variables (π : (restrict_scalars k (monoid_algebra k G) W) →ₗ[k]
(restrict_scalars k (monoid_algebra k G) V))
include π
/--
We define the conjugate of `π` by `g`, as a `k`-linear map.
-/
def conjugate (g : G) :
(restrict_scalars k (monoid_algebra k G) W) →ₗ[k] (restrict_scalars k (monoid_algebra k G) V) :=
((group_smul.linear_map k V g⁻¹).comp π).comp (group_smul.linear_map k W g)
variables (i : V →ₗ[monoid_algebra k G] W) (h : ∀ v : V, π (i v) = v)
section
include h
lemma conjugate_i (g : G) (v : V) : (conjugate π g) (i v) = v :=
begin
dsimp [conjugate],
simp only [←i.map_smul, h, ←mul_smul, single_mul_single, mul_one, mul_left_inv],
change (1 : monoid_algebra k G) • v = v,
simp,
end
end
variables [fintype G]
/--
The sum of the conjugates of `π` by each element `g : G`, as a `k`-linear map.
(We postpone dividing by the size of the group as long as possible.)
-/
def sum_of_conjugates :
(restrict_scalars k (monoid_algebra k G) W) →ₗ[k] (restrict_scalars k (monoid_algebra k G) V) :=
∑ g : G, conjugate π g
/--
In fact, the sum over `g : G` of the conjugate of `π` by `g` is a `k[G]`-linear map.
-/
def sum_of_conjugates_equivariant :
W →ₗ[monoid_algebra k G] V :=
monoid_algebra.equivariant_of_linear_of_comm (sum_of_conjugates π) (λ g v,
begin
dsimp [sum_of_conjugates],
simp only [linear_map.sum_apply, finset.smul_sum],
dsimp [conjugate],
conv_lhs {
rw [←finset.univ_map_embedding (mul_right_embedding g⁻¹)],
simp only [mul_right_embedding],
},
simp only [←mul_smul, single_mul_single, mul_inv_rev, mul_one, function.embedding.coe_fn_mk,
finset.sum_map, inv_inv, inv_mul_cancel_right],
end)
section
variables [inv : invertible (fintype.card G : k)]
include inv
section
local attribute [instance] linear_map_algebra_module
/--
We construct our `k[G]`-linear retraction of `i` as
$$ \frac{1}{|G|} \sum_{g \in G} g⁻¹ • π(g • -). $$
-/
def equivariant_projection :
W →ₗ[monoid_algebra k G] V :=
⅟(fintype.card G : k) • (sum_of_conjugates_equivariant π)
end
include h
lemma equivariant_projection_condition (v : V) : (equivariant_projection π) (i v) = v :=
begin
rw [equivariant_projection, linear_map_algebra_module.smul_apply, sum_of_conjugates_equivariant,
equivariant_of_linear_of_comm_apply, sum_of_conjugates],
rw [linear_map.sum_apply],
simp only [conjugate_i π i h],
rw [finset.sum_const, finset.card_univ,
@semimodule.nsmul_eq_smul k _
(restrict_scalars k (monoid_algebra k G) V) _ _ (fintype.card G) v,
←mul_smul, invertible.inv_of_mul_self, one_smul],
end
end
end
-- Now we work over a `[field k]`, and replace the assumption `[invertible (fintype.card G : k)]`
-- with `¬(ring_char k ∣ fintype.card G)`.
variables {k : Type u} [field k] {G : Type u} [fintype G] [group G]
variables {V : Type u} [add_comm_group V] [module (monoid_algebra k G) V]
variables {W : Type u} [add_comm_group W] [module (monoid_algebra k G) W]
lemma monoid_algebra.exists_left_inverse_of_injective
(not_dvd : ¬(ring_char k ∣ fintype.card G))
(f : V →ₗ[monoid_algebra k G] W) (hf_inj : f.ker = ⊥) :
∃ (g : W →ₗ[monoid_algebra k G] V), g.comp f = linear_map.id :=
begin
let E := linear_map.exists_left_inverse_of_injective
(by convert f.restrict_scalars k) (by simp [hf_inj]),
fsplit,
haveI : invertible (fintype.card G : k) :=
invertible_of_ring_char_not_dvd not_dvd,
exact equivariant_projection (classical.some E),
{ ext v,
apply equivariant_projection_condition,
intro v,
have := classical.some_spec E,
have := congr_arg linear_map.to_fun this,
exact congr_fun this v, }
end
lemma monoid_algebra.submodule.exists_is_compl
(not_dvd : ¬(ring_char k ∣ fintype.card G)) (p : submodule (monoid_algebra k G) V) :
∃ q : submodule (monoid_algebra k G) V, is_compl p q :=
let ⟨f, hf⟩ := monoid_algebra.exists_left_inverse_of_injective not_dvd p.subtype p.ker_subtype in
⟨f.ker, linear_map.is_compl_of_proj $ linear_map.ext_iff.1 hf⟩
|
e7c5cb48420ef6bfb269005e4b511158a9efeb0d | 46125763b4dbf50619e8846a1371029346f4c3db | /src/data/semiquot.lean | e589352c7500910b8ff6f12010842309611758d5 | [
"Apache-2.0"
] | permissive | thjread/mathlib | a9d97612cedc2c3101060737233df15abcdb9eb1 | 7cffe2520a5518bba19227a107078d83fa725ddc | refs/heads/master | 1,615,637,696,376 | 1,583,953,063,000 | 1,583,953,063,000 | 246,680,271 | 0 | 0 | Apache-2.0 | 1,583,960,875,000 | 1,583,960,875,000 | null | UTF-8 | Lean | false | false | 7,510 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
A data type for semiquotients, which are classically equivalent to
nonempty sets, but are useful for programming; the idea is that
a semiquotient set `S` represents some (particular but unknown)
element of `S`. This can be used to model nondeterministic functions,
which return something in a range of values (represented by the
predicate `S`) but are not completely determined.
-/
import data.set.lattice data.quot
/-- A member of `semiquot α` is classically a nonempty `set α`,
and in the VM is represented by an element of `α`; the relation
between these is that the VM element is required to be a member
of the set `s`. The specific element of `s` that the VM computes
is hidden by a quotient construction, allowing for the representation
of nondeterministic functions. -/
structure {u} semiquot (α : Type*) := mk' ::
(s : set α)
(val : trunc ↥s)
namespace semiquot
variables {α : Type*} {β : Type*}
instance : has_mem α (semiquot α) := ⟨λ a q, a ∈ q.s⟩
/-- Construct a `semiquot α` from `h : a ∈ s` where `s : set α`. -/
def mk {a : α} {s : set α} (h : a ∈ s) : semiquot α :=
⟨s, trunc.mk ⟨a, h⟩⟩
theorem ext_s {q₁ q₂ : semiquot α} : q₁ = q₂ ↔ q₁.s = q₂.s :=
⟨congr_arg _,
λ h, by cases q₁; cases q₂; congr; exact h⟩
theorem ext {q₁ q₂ : semiquot α} : q₁ = q₂ ↔ ∀ a, a ∈ q₁ ↔ a ∈ q₂ :=
ext_s.trans (set.ext_iff _ _)
theorem exists_mem (q : semiquot α) : ∃ a, a ∈ q :=
let ⟨⟨a, h⟩, h₂⟩ := q.2.exists_rep in ⟨a, h⟩
theorem eq_mk_of_mem {q : semiquot α} {a : α} (h : a ∈ q) :
q = @mk _ a q.1 h := ext_s.2 rfl
theorem nonempty (q : semiquot α) : q.s.nonempty := q.exists_mem
/-- `pure a` is `a` reinterpreted as an unspecified element of `{a}`. -/
protected def pure (a : α) : semiquot α := mk (set.mem_singleton a)
@[simp] theorem mem_pure' {a b : α} : a ∈ semiquot.pure b ↔ a = b :=
set.mem_singleton_iff
/-- Replace `s` in a `semiquot` with a superset. -/
def blur' (q : semiquot α) {s : set α} (h : q.s ⊆ s) : semiquot α :=
⟨s, trunc.lift (λ a : q.s, trunc.mk ⟨a.1, h a.2⟩)
(λ _ _, trunc.eq _ _) q.2⟩
/-- Replace `s` in a `q : semiquot α` with a union `s ∪ q.s` -/
def blur (s : set α) (q : semiquot α) : semiquot α :=
blur' q (set.subset_union_right s q.s)
theorem blur_eq_blur' (q : semiquot α) (s : set α) (h : q.s ⊆ s) :
blur s q = blur' q h :=
by unfold blur; congr; exact set.union_eq_self_of_subset_right h
@[simp] theorem mem_blur' (q : semiquot α) {s : set α} (h : q.s ⊆ s)
{a : α} : a ∈ blur' q h ↔ a ∈ s := iff.rfl
/-- Convert a `trunc α` to a `semiquot α`. -/
def of_trunc (q : trunc α) : semiquot α :=
⟨set.univ, q.map (λ a, ⟨a, trivial⟩)⟩
/-- Convert a `semiquot α` to a `trunc α`. -/
def to_trunc (q : semiquot α) : trunc α :=
q.2.map subtype.val
/-- If `f` is a constant on `q.s`, then `q.lift_on f` is the value of `f`
at any point of `q`. -/
def lift_on (q : semiquot α) (f : α → β) (h : ∀ a b ∈ q, f a = f b) : β :=
trunc.lift_on q.2 (λ x, f x.1) (λ x y, h _ _ x.2 y.2)
theorem lift_on_of_mem (q : semiquot α)
(f : α → β) (h : ∀ a b ∈ q, f a = f b)
(a : α) (aq : a ∈ q) : lift_on q f h = f a :=
by revert h; rw eq_mk_of_mem aq; intro; refl
def map (f : α → β) (q : semiquot α) : semiquot β :=
⟨f '' q.1, q.2.map (λ x, ⟨f x.1, set.mem_image_of_mem _ x.2⟩)⟩
@[simp] theorem mem_map (f : α → β) (q : semiquot α) (b : β) :
b ∈ map f q ↔ ∃ a, a ∈ q ∧ f a = b := set.mem_image _ _ _
def bind (q : semiquot α) (f : α → semiquot β) : semiquot β :=
⟨⋃ a ∈ q.1, (f a).1,
q.2.bind (λ a, (f a.1).2.map (λ b, ⟨b.1, set.mem_bUnion a.2 b.2⟩))⟩
@[simp] theorem mem_bind (q : semiquot α) (f : α → semiquot β) (b : β) :
b ∈ bind q f ↔ ∃ a ∈ q, b ∈ f a := set.mem_bUnion_iff
instance : monad semiquot :=
{ pure := @semiquot.pure,
map := @semiquot.map,
bind := @semiquot.bind }
@[simp] theorem mem_pure {a b : α} : a ∈ (pure b : semiquot α) ↔ a = b :=
set.mem_singleton_iff
theorem mem_pure_self (a : α) : a ∈ (pure a : semiquot α) :=
set.mem_singleton a
@[simp] theorem pure_inj {a b : α} : (pure a : semiquot α) = pure b ↔ a = b :=
ext_s.trans set.singleton_eq_singleton_iff
instance : is_lawful_monad semiquot :=
{ pure_bind := λ α β x f, ext.2 $ by simp,
bind_assoc := λ α β γ s f g, ext.2 $ by simp; exact
λ c, ⟨λ ⟨b, ⟨a, as, bf⟩, cg⟩, ⟨a, as, b, bf, cg⟩,
λ ⟨a, as, b, bf, cg⟩, ⟨b, ⟨a, as, bf⟩, cg⟩⟩,
id_map := λ α q, ext.2 $ by simp,
bind_pure_comp_eq_map := λ α β f s, ext.2 $ by simp [eq_comm] }
instance : has_le (semiquot α) := ⟨λ s t, s.s ⊆ t.s⟩
instance : partial_order (semiquot α) :=
{ le := λ s t, ∀ ⦃x⦄, x ∈ s → x ∈ t,
le_refl := λ s, set.subset.refl _,
le_trans := λ s t u, set.subset.trans,
le_antisymm := λ s t h₁ h₂, ext_s.2 (set.subset.antisymm h₁ h₂) }
instance : lattice.semilattice_sup (semiquot α) :=
{ sup := λ s, blur s.s,
le_sup_left := λ s t, set.subset_union_left _ _,
le_sup_right := λ s t, set.subset_union_right _ _,
sup_le := λ s t u, set.union_subset,
..semiquot.partial_order }
@[simp] theorem pure_le {a : α} {s : semiquot α} : pure a ≤ s ↔ a ∈ s :=
set.singleton_subset_iff
def is_pure (q : semiquot α) := ∀ a b ∈ q, a = b
def get (q : semiquot α) (h : q.is_pure) : α := lift_on q id h
theorem get_mem {q : semiquot α} (p) : get q p ∈ q :=
let ⟨a, h⟩ := exists_mem q in
by unfold get; rw lift_on_of_mem q _ _ a h; exact h
theorem eq_pure {q : semiquot α} (p) : q = pure (get q p) :=
ext.2 $ λ a, by simp; exact
⟨λ h, p _ _ h (get_mem _), λ e, e.symm ▸ get_mem _⟩
@[simp] theorem pure_is_pure (a : α) : is_pure (pure a)
| b c ab ac := by { simp at ab ac, cc }
theorem is_pure_iff {s : semiquot α} : is_pure s ↔ ∃ a, s = pure a :=
⟨λ h, ⟨_, eq_pure h⟩, λ ⟨a, e⟩, e.symm ▸ pure_is_pure _⟩
theorem is_pure.mono {s t : semiquot α}
(st : s ≤ t) (h : is_pure t) : is_pure s
| a b as bs := h _ _ (st as) (st bs)
theorem is_pure.min {s t : semiquot α} (h : is_pure t) : s ≤ t ↔ s = t :=
⟨λ st, le_antisymm st $ by rw [eq_pure h, eq_pure (h.mono st)]; simp;
exact h _ _ (get_mem _) (st $ get_mem _),
le_of_eq⟩
theorem is_pure_of_subsingleton [subsingleton α] (q : semiquot α) : is_pure q
| a b aq bq := subsingleton.elim _ _
/-- `univ : semiquot α` represents an unspecified element of `univ : set α`. -/
def univ [inhabited α] : semiquot α :=
mk $ set.mem_univ (default _)
instance [inhabited α] : inhabited (semiquot α) := ⟨univ⟩
@[simp] theorem mem_univ [inhabited α] : ∀ a, a ∈ @univ α _ :=
@set.mem_univ α
@[congr] theorem univ_unique (I J : inhabited α) : @univ _ I = @univ _ J :=
ext.2 $ by simp
@[simp] theorem is_pure_univ [inhabited α] : @is_pure α univ ↔ subsingleton α :=
⟨λ h, ⟨λ a b, h a b trivial trivial⟩, λ ⟨h⟩ a b _ _, h a b⟩
instance [inhabited α] : lattice.order_top (semiquot α) :=
{ top := univ,
le_top := λ s, set.subset_univ _,
..semiquot.partial_order }
instance [inhabited α] : lattice.semilattice_sup_top (semiquot α) :=
{ ..semiquot.lattice.order_top,
..semiquot.lattice.semilattice_sup }
end semiquot
|
48f25d13a194605219922de07c4c6c64dcc66460 | 0c9c1ff8e5013c525bf1d72338b62db639374733 | /library/init/meta/tactic.lean | 998c30e309b5c978a511a90e7d019c41779c7ce4 | [
"Apache-2.0"
] | permissive | semorrison/lean | 1f2bb450c3400098666ff6e43aa29b8e1e3cdc3a | 85dcb385d5219f2fca8c73b2ebca270fe81337e0 | refs/heads/master | 1,638,526,143,586 | 1,634,825,588,000 | 1,634,825,588,000 | 258,650,844 | 0 | 0 | Apache-2.0 | 1,587,772,955,000 | 1,587,772,954,000 | null | UTF-8 | Lean | false | false | 76,478 | 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.function init.data.option.basic init.util
import init.control.combinators init.control.monad init.control.alternative init.control.monad_fail
import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment
import init.meta.pexpr init.data.repr init.data.string.basic init.meta.interaction_monad
import init.classical
open native
meta constant tactic_state : Type
universes u v
namespace tactic_state
meta constant env : tactic_state → environment
/-- Format the given tactic state. If `target_lhs_only` is true and the target
is of the form `lhs ~ rhs`, where `~` is a simplification relation,
then only the `lhs` is displayed.
Remark: the parameter `target_lhs_only` is a temporary hack used to implement
the `conv` monad. It will be removed in the future. -/
meta constant to_format (s : tactic_state) (target_lhs_only : bool := ff) : format
/-- Format expression with respect to the main goal in the tactic state.
If the tactic state does not contain any goals, then format expression
using an empty local context. -/
meta constant format_expr : tactic_state → expr → format
meta constant get_options : tactic_state → options
meta constant set_options : tactic_state → options → tactic_state
end tactic_state
meta instance : has_to_format tactic_state :=
⟨tactic_state.to_format⟩
meta instance : has_to_string tactic_state :=
⟨λ s, (to_fmt s).to_string s.get_options⟩
/-- `tactic` is the monad for building tactics.
You use this to:
- View and modify the local goals and hypotheses in the prover's state.
- Invoke type checking and elaboration of terms.
- View and modify the environment.
- Build new tactics out of existing ones such as `simp` and `rewrite`.
-/
@[reducible] meta def tactic := interaction_monad tactic_state
@[reducible] meta def tactic_result := interaction_monad.result tactic_state
namespace tactic
export interaction_monad (result result.success result.exception result.cases_on
result_to_string mk_exception silent_fail orelse' bracket)
/-- Cause the tactic to fail with no error message. -/
meta def failed {α : Type} : tactic α := interaction_monad.failed
meta def fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : tactic α :=
interaction_monad.fail msg
end tactic
namespace tactic_result
export interaction_monad.result
end tactic_result
open tactic
open tactic_result
infixl ` >>=[tactic] `:2 := interaction_monad_bind
infixl ` >>[tactic] `:2 := interaction_monad_seq
meta instance : alternative tactic :=
{ failure := @interaction_monad.failed _,
orelse := @interaction_monad_orelse _,
..interaction_monad.monad }
meta def {u₁ u₂} tactic.up {α : Type u₂} (t : tactic α) : tactic (ulift.{u₁} α) :=
λ s, match t s with
| success a s' := success (ulift.up a) s'
| exception t ref s := exception t ref s
end
meta def {u₁ u₂} tactic.down {α : Type u₂} (t : tactic (ulift.{u₁} α)) : tactic α :=
λ s, match t s with
| success (ulift.up a) s' := success a s'
| exception t ref s := exception t ref s
end
namespace interactive
/-- Typeclass for custom interaction monads, which provides
the information required to convert an interactive-mode
construction to a `tactic` which can actually be executed.
Given a `[monad m]`, `execute_with` explains how to turn a `begin ... end`
block, or a `by ...` statement into a `tactic α` which can actually be
executed. The `inhabited` first argument facilitates the passing of an
optional configuration parameter `config`, using the syntax:
```
begin [custom_monad] with config,
...
end
```
-/
meta class executor (m : Type → Type u) [monad m] :=
(config_type : Type)
[inhabited : inhabited config_type]
(execute_with : config_type → m unit → tactic unit)
attribute [inline] executor.execute_with
@[inline]
meta def executor.execute_explicit (m : Type → Type u)
[monad m] [e : executor m] : m unit → tactic unit :=
executor.execute_with e.inhabited.default
@[inline]
meta def executor.execute_with_explicit (m : Type → Type u)
[monad m] [executor m] : executor.config_type m → m unit → tactic unit :=
executor.execute_with
/-- Default `executor` instance for `tactic`s themselves -/
meta instance executor_tactic : executor tactic :=
{ config_type := unit,
inhabited := ⟨()⟩,
execute_with := λ _, id }
end interactive
namespace tactic
open interaction_monad.result
variables {α : Type u}
/-- Does nothing. -/
meta def skip : tactic unit :=
success ()
/--
`try_core t` acts like `t`, but succeeds even if `t` fails. It returns the
result of `t` if `t` succeeded and `none` otherwise.
-/
meta def try_core (t : tactic α) : tactic (option α) := λ s,
match t s with
| (exception _ _ _) := success none s
| (success a s') := success (some a) s'
end
/--
`try t` acts like `t`, but succeeds even if `t` fails.
-/
meta def try (t : tactic α) : tactic unit := λ s,
match t s with
| (exception _ _ _) := success () s
| (success _ s') := success () s'
end
meta def try_lst : list (tactic unit) → tactic unit
| [] := failed
| (tac :: tacs) := λ s,
match tac s with
| success _ s' := try (try_lst tacs) s'
| exception e p s' :=
match try_lst tacs s' with
| exception _ _ _ := exception e p s'
| r := r
end
end
/--
`fail_if_success t` acts like `t`, but succeeds if `t` fails and fails if `t`
succeeds. Changes made by `t` to the `tactic_state` are preserved only if `t`
succeeds.
-/
meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit := λ s,
match (t s) with
| (success a s) := mk_exception "fail_if_success combinator failed, given tactic succeeded" none s
| (exception _ _ _) := success () s
end
/--
`success_if_fail t` acts like `t`, but succeeds if `t` fails and fails if `t`
succeeds. Changes made by `t` to the `tactic_state` are preserved only if `t`
succeeds.
-/
meta def success_if_fail {α : Type u} (t : tactic α) : tactic unit := λ s,
match t s with
| (success a s) :=
mk_exception "success_if_fail combinator failed, given tactic succeeded" none s
| (exception _ _ _) := success () s
end
open nat
/--
`iterate_at_most n t` iterates `t` `n` times or until `t` fails, returning the
result of each successful iteration.
-/
meta def iterate_at_most : nat → tactic α → tactic (list α)
| 0 t := pure []
| (n + 1) t := do
(some a) ← try_core t | pure [],
as ← iterate_at_most n t,
pure $ a :: as
/--
`iterate_at_most' n t` repeats `t` `n` times or until `t` fails.
-/
meta def iterate_at_most' : nat → tactic unit → tactic unit
| 0 t := skip
| (succ n) t := do
(some _) ← try_core t | skip,
iterate_at_most' n t
/--
`iterate_exactly n t` iterates `t` `n` times, returning the result of
each iteration. If any iteration fails, the whole tactic fails.
-/
meta def iterate_exactly : nat → tactic α → tactic (list α)
| 0 t := pure []
| (n + 1) t := do
a ← t,
as ← iterate_exactly n t,
pure $ a ::as
/--
`iterate_exactly' n t` executes `t` `n` times. If any iteration fails, the whole
tactic fails.
-/
meta def iterate_exactly' : nat → tactic unit → tactic unit
| 0 t := skip
| (n + 1) t := t *> iterate_exactly' n t
/--
`iterate t` repeats `t` 100.000 times or until `t` fails, returning the
result of each iteration.
-/
meta def iterate : tactic α → tactic (list α) :=
iterate_at_most 100000
/--
`iterate' t` repeats `t` 100.000 times or until `t` fails.
-/
meta def iterate' : tactic unit → tactic unit :=
iterate_at_most' 100000
meta def returnopt (e : option α) : tactic α :=
λ s, match e with
| (some a) := success a s
| none := mk_exception "failed" none s
end
meta instance opt_to_tac : has_coe (option α) (tactic α) :=
⟨returnopt⟩
/-- Decorate t's exceptions with msg. -/
meta def decorate_ex (msg : format) (t : tactic α) : tactic α :=
λ s, result.cases_on (t s)
success
(λ opt_thunk,
match opt_thunk with
| some e := exception (some (λ u, msg ++ format.nest 2 (format.line ++ e u)))
| none := exception none
end)
/-- Set the tactic_state. -/
@[inline] meta def write (s' : tactic_state) : tactic unit :=
λ s, success () s'
/-- Get the tactic_state. -/
@[inline] meta def read : tactic tactic_state :=
λ s, success s s
/--
`capture t` acts like `t`, but succeeds with a result containing either the returned value
or the exception.
Changes made by `t` to the `tactic_state` are preserved in both cases.
The result can be used to inspect the error message, or passed to `unwrap` to rethrow the
failure later.
-/
meta def capture (t : tactic α) : tactic (tactic_result α) :=
λ s, match t s with
| (success r s') := success (success r s') s'
| (exception f p s') := success (exception f p s') s'
end
/--
`unwrap r` unwraps a result previously obtained using `capture`.
If the previous result was a success, this produces its wrapped value.
If the previous result was an exception, this "rethrows" the exception as if it came
from where it originated.
`do r ← capture t, unwrap r` is identical to `t`, but allows for intermediate tactics to be inserted.
-/
meta def unwrap {α : Type*} (t : tactic_result α) : tactic α :=
match t with
| (success r s') := return r
| e := λ s, e
end
/--
`resume r` continues execution from a result previously obtained using `capture`.
This is like `unwrap`, but the `tactic_state` is rolled back to point of capture even upon success.
-/
meta def resume {α : Type*} (t : tactic_result α) : tactic α :=
λ s, t
meta def get_options : tactic options :=
do s ← read, return s.get_options
meta def set_options (o : options) : tactic unit :=
do s ← read, write (s.set_options o)
meta def save_options {α : Type} (t : tactic α) : tactic α :=
do o ← get_options,
a ← t,
set_options o,
return a
meta def returnex {α : Type} (e : exceptional α) : tactic α :=
λ s, match e with
| exceptional.success a := success a s
| exceptional.exception f :=
match get_options s with
| success opt _ := exception (some (λ u, f opt)) none s
| exception _ _ _ := exception (some (λ u, f options.mk)) none s
end
end
meta instance ex_to_tac {α : Type} : has_coe (exceptional α) (tactic α) :=
⟨returnex⟩
end tactic
meta def tactic_format_expr (e : expr) : tactic format :=
do s ← tactic.read, return (tactic_state.format_expr s e)
meta class has_to_tactic_format (α : Type u) :=
(to_tactic_format : α → tactic format)
meta instance : has_to_tactic_format expr :=
⟨tactic_format_expr⟩
meta def tactic.pp {α : Type u} [has_to_tactic_format α] : α → tactic format :=
has_to_tactic_format.to_tactic_format
open tactic format
meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (list α) :=
⟨λ l, to_fmt <$> l.mmap pp⟩
meta instance (α : Type u) (β : Type v) [has_to_tactic_format α] [has_to_tactic_format β] :
has_to_tactic_format (α × β) :=
⟨λ ⟨a, b⟩, to_fmt <$> (prod.mk <$> pp a <*> pp b)⟩
meta def option_to_tactic_format {α : Type u} [has_to_tactic_format α] : option α → tactic format
| (some a) := do fa ← pp a, return (to_fmt "(some " ++ fa ++ ")")
| none := return "none"
meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (option α) :=
⟨option_to_tactic_format⟩
meta instance {α} (a : α) : has_to_tactic_format (reflected a) :=
⟨λ h, pp h.to_expr⟩
@[priority 10] meta instance has_to_format_to_has_to_tactic_format (α : Type) [has_to_format α] : has_to_tactic_format α :=
⟨(λ x, return x) ∘ to_fmt⟩
namespace tactic
open tactic_state
meta def get_env : tactic environment :=
do s ← read,
return $ env s
meta def get_decl (n : name) : tactic declaration :=
do s ← read,
(env s).get n
meta constant get_trace_msg_pos : tactic pos
meta def trace {α : Type u} [has_to_tactic_format α] (a : α) : tactic unit :=
do fmt ← pp a,
return $ _root_.trace_fmt fmt (λ u, ())
meta def trace_call_stack : tactic unit :=
assume state, _root_.trace_call_stack (success () state)
meta def timetac {α : Type u} (desc : string) (t : thunk (tactic α)) : tactic α :=
λ s, timeit desc (t () s)
meta def trace_state : tactic unit :=
do s ← read,
trace $ to_fmt s
/-- A parameter representing how aggressively definitions should be unfolded when trying to decide if two terms match, unify or are definitionally equal.
By default, theorem declarations are never unfolded.
- `all` will unfold everything, including macros and theorems. Except projection macros.
- `semireducible` will unfold everything except theorems and definitions tagged as irreducible.
- `instances` will unfold all class instance definitions and definitions tagged with reducible.
- `reducible` will only unfold definitions tagged with the `reducible` attribute.
- `none` will never unfold anything.
[NOTE] You are not allowed to tag a definition with more than one of `reducible`, `irreducible`, `semireducible` attributes.
[NOTE] there is a config flag `m_unfold_lemmas`that will make it unfold theorems.
-/
inductive transparency
| all | semireducible | instances | reducible | none
export transparency (reducible semireducible)
/-- (eval_expr α e) evaluates 'e' IF 'e' has type 'α'. -/
meta constant eval_expr (α : Type u) [reflected α] : expr → tactic α
/-- Return the partial term/proof constructed so far. Note that the resultant expression
may contain variables that are not declarate in the current main goal. -/
meta constant result : tactic expr
/-- Display the partial term/proof constructed so far. This tactic is *not* equivalent to
`do { r ← result, s ← read, return (format_expr s r) }` because this one will format the result with respect
to the current goal, and trace_result will do it with respect to the initial goal. -/
meta constant format_result : tactic format
/-- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/
meta constant target : tactic expr
meta constant intro_core : name → tactic expr
meta constant intron : nat → tactic unit
/-- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/
meta constant clear : expr → tactic unit
/-- `revert_lst : list expr → tactic nat` is the reverse of `intron`. It takes a local constant `c` and puts it back as bound by a `pi` or `elet` of the main target.
If there are other local constants that depend on `c`, these are also reverted. Because of this, the `nat` that is returned is the actual number of reverted local constants.
Example: with `x : ℕ, h : P(x) ⊢ T(x)`, `revert_lst [x]` returns `2` and produces the state ` ⊢ Π x, P(x) → T(x)`.
-/
meta constant revert_lst : list expr → tactic nat
/-- Return `e` in weak head normal form with respect to the given transparency setting.
If `unfold_ginductive` is `tt`, then nested and/or mutually recursive inductive datatype constructors
and types are unfolded. Recall that nested and mutually recursive inductive datatype declarations
are compiled into primitive datatypes accepted by the Kernel. -/
meta constant whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic expr
/-- (head) eta expand the given expression. `f : α → β` head-eta-expands to `λ a, f a`. If `f` isn't a function then it just returns `f`. -/
meta constant head_eta_expand : expr → tactic expr
/-- (head) beta reduction. `(λ x, B) c` reduces to `B[x/c]`. -/
meta constant head_beta : expr → tactic expr
/-- (head) zeta reduction. Reduction of let bindings at the head of the expression. `let x : a := b in c` reduces to `c[x/b]`. -/
meta constant head_zeta : expr → tactic expr
/-- Zeta reduction. Reduction of let bindings. `let x : a := b in c` reduces to `c[x/b]`. -/
meta constant zeta : expr → tactic expr
/-- (head) eta reduction. `(λ x, f x)` reduces to `f`. -/
meta constant head_eta : expr → tactic expr
/-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/
meta constant unify (t s : expr) (md := semireducible) (approx := ff) : tactic unit
/-- Similar to `unify`, but it treats metavariables as constants. -/
meta constant is_def_eq (t s : expr) (md := semireducible) (approx := ff) : tactic unit
/-- Infer the type of the given expression.
Remark: transparency does not affect type inference -/
meta constant infer_type : expr → tactic expr
/-- Get the `local_const` expr for the given `name`. -/
meta constant get_local : name → tactic expr
/-- Resolve a name using the current local context, environment, aliases, etc. -/
meta constant resolve_name : name → tactic pexpr
/-- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/
meta constant local_context : tactic (list expr)
/-- Get a fresh name that is guaranteed to not be in use in the local context.
If `n` is provided and `n` is not in use, then `n` is returned.
Otherwise a number `i` is appended to give `"n_i"`.
-/
meta constant get_unused_name (n : name := `_x) (i : option nat := none) : tactic name
/-- Helper tactic for creating simple applications where some arguments are inferred using
type inference.
Example, given
```
rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop
nat : Type
real : Type
vec.{l} : Pi (α : Type l) (n : nat), Type.{l1}
f g : Pi (n : nat), vec real n
```
then
```
mk_app_core semireducible "rel" [f, g]
```
returns the application
```
rel.{1 2} nat (fun n : nat, vec real n) f g
```
The unification constraints due to type inference are solved using the transparency `md`.
-/
meta constant mk_app (fn : name) (args : list expr) (md := semireducible) : tactic expr
/-- Similar to `mk_app`, but allows to specify which arguments are explicit/implicit.
Example, given `(a b : nat)` then
```
mk_mapp "ite" [some (a > b), none, none, some a, some b]
```
returns the application
```
@ite.{1} nat (a > b) (nat.decidable_gt a b) a b
```
-/
meta constant mk_mapp (fn : name) (args : list (option expr)) (md := semireducible) : tactic expr
/-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/
meta constant mk_congr_arg : expr → expr → tactic expr
/-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/
meta constant mk_congr_fun : expr → expr → tactic expr
/-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/
meta constant mk_congr : expr → expr → tactic expr
/-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/
meta constant mk_eq_refl : expr → tactic expr
/-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/
meta constant mk_eq_symm : expr → tactic expr
/-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/
meta constant mk_eq_trans : expr → expr → tactic expr
/-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/
meta constant mk_eq_mp : expr → expr → tactic expr
/-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/
meta constant mk_eq_mpr : expr → expr → tactic expr
/- Given a local constant t, if t has type (lhs = rhs) apply substitution.
Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t).
The tactic fails if the given expression is not a local constant. -/
meta constant subst_core : expr → tactic unit
/-- Close the current goal using `e`. Fail if the type of `e` is not definitionally equal to
the target type. -/
meta constant exact (e : expr) (md := semireducible) : tactic unit
/-- Elaborate the given quoted expression with respect to the current main goal.
Note that this means that any implicit arguments for the given `pexpr` will be applied with fresh metavariables.
If `allow_mvars` is tt, then metavariables are tolerated and become new goals if `subgoals` is tt. -/
meta constant to_expr (q : pexpr) (allow_mvars := tt) (subgoals := tt) : tactic expr
/-- Return true if the given expression is a type class. -/
meta constant is_class : expr → tactic bool
/-- Try to create an instance of the given type class. -/
meta constant mk_instance : expr → tactic expr
/-- Change the target of the main goal.
The input expression must be definitionally equal to the current target.
If `check` is `ff`, then the tactic does not check whether `e`
is definitionally equal to the current target. If it is not,
then the error will only be detected by the kernel type checker. -/
meta constant change (e : expr) (check : bool := tt): tactic unit
/-- `assert_core H T`, adds a new goal for T, and change target to `T -> target`. -/
meta constant assert_core : name → expr → tactic unit
/-- `assertv_core H T P`, change target to (T -> target) if P has type T. -/
meta constant assertv_core : name → expr → expr → tactic unit
/-- `define_core H T`, adds a new goal for T, and change target to `let H : T := ?M in target` in the current goal. -/
meta constant define_core : name → expr → tactic unit
/-- `definev_core H T P`, change target to `let H : T := P in target` if P has type T. -/
meta constant definev_core : name → expr → expr → tactic unit
/-- Rotate goals to the left. That is, `rotate_left 1` takes the main goal and puts it to the back of the subgoal list. -/
meta constant rotate_left : nat → tactic unit
/-- Gets a list of metavariables, one for each goal. -/
meta constant get_goals : tactic (list expr)
/-- Replace the current list of goals with the given one. Each expr in the list should be a metavariable. Any assigned metavariables will be ignored.-/
meta constant set_goals : list expr → tactic unit
/-- How to order the new goals made from an `apply` tactic.
Supposing we were applying `e : ∀ (a:α) (p : P(a)), Q`
- `non_dep_first` would produce goals `⊢ P(?m)`, `⊢ α`. It puts the P goal at the front because none of the arguments after `p` in `e` depend on `p`. It doesn't matter what the result `Q` depends on.
- `non_dep_only` would produce goal `⊢ P(?m)`.
- `all` would produce goals `⊢ α`, `⊢ P(?m)`.
-/
inductive new_goals
| non_dep_first | non_dep_only | all
/-- Configuration options for the `apply` tactic.
- `md` sets how aggressively definitions are unfolded.
- `new_goals` is the strategy for ordering new goals.
- `instances` if `tt`, then `apply` tries to synthesize unresolved `[...]` arguments using type class resolution.
- `auto_param` if `tt`, then `apply` tries to synthesize unresolved `(h : p . tac_id)` arguments using tactic `tac_id`.
- `opt_param` if `tt`, then `apply` tries to synthesize unresolved `(a : t := v)` arguments by setting them to `v`.
- `unify` if `tt`, then `apply` is free to assign existing metavariables in the goal when solving unification constraints.
For example, in the goal `|- ?x < succ 0`, the tactic `apply succ_lt_succ` succeeds with the default configuration,
but `apply_with succ_lt_succ {unify := ff}` doesn't since it would require Lean to assign `?x` to `succ ?y` where
`?y` is a fresh metavariable.
-/
structure apply_cfg :=
(md := semireducible)
(approx := tt)
(new_goals := new_goals.non_dep_first)
(instances := tt)
(auto_param := tt)
(opt_param := tt)
(unify := tt)
/-- Apply the expression `e` to the main goal, the unification is performed using the transparency mode in `cfg`.
Supposing `e : Π (a₁:α₁) ... (aₙ:αₙ), P(a₁,...,aₙ)` and the target is `Q`, `apply` will attempt to unify `Q` with `P(?a₁,...?aₙ)`.
All of the metavariables that are not assigned are added as new metavariables.
If `cfg.approx` is `tt`, then fallback to first-order unification, and approximate context during unification.
`cfg.new_goals` specifies which unassigned metavariables become new goals, and their order.
If `cfg.instances` is `tt`, then use type class resolution to instantiate unassigned meta-variables.
The fields `cfg.auto_param` and `cfg.opt_param` are ignored by this tactic (See `tactic.apply`).
It returns a list of all introduced meta variables and the parameter name associated with them, even the assigned ones. -/
meta constant apply_core (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr))
/- Create a fresh meta universe variable. -/
meta constant mk_meta_univ : tactic level
/- Create a fresh meta-variable with the given type.
The scope of the new meta-variable is the local context of the main goal. -/
meta constant mk_meta_var : expr → tactic expr
/-- Return the value assigned to the given universe meta-variable.
Fail if argument is not an universe meta-variable or if it is not assigned. -/
meta constant get_univ_assignment : level → tactic level
/-- Return the value assigned to the given meta-variable.
Fail if argument is not a meta-variable or if it is not assigned. -/
meta constant get_assignment : expr → tactic expr
/-- Return true if the given meta-variable is assigned.
Fail if argument is not a meta-variable. -/
meta constant is_assigned : expr → tactic bool
/-- Make a name that is guaranteed to be unique. Eg `_fresh.1001.4667`. These will be different for each run of the tactic. -/
meta constant mk_fresh_name : tactic name
/-- Induction on `h` using recursor `rec`, names for the new hypotheses
are retrieved from `ns`. If `ns` does not have sufficient names, then use the internal binder names
in the recursor.
It returns for each new goal the name of the constructor (if `rec_name` is a builtin recursor),
a list of new hypotheses, and a list of substitutions for hypotheses
depending on `h`. The substitutions map internal names to their replacement terms. If the
replacement is again a hypothesis the user name stays the same. The internal names are only valid
in the original goal, not in the type context of the new goal.
Remark: if `rec_name` is not a builtin recursor, we use parameter names of `rec_name` instead of
constructor names.
If `rec` is none, then the type of `h` is inferred, if it is of the form `C ...`, tactic uses `C.rec` -/
meta constant induction (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic (list (name × list expr × list (name × expr)))
/-- Apply `cases_on` recursor, names for the new hypotheses are retrieved from `ns`.
`h` must be a local constant. It returns for each new goal the name of the constructor, a list of new hypotheses, and a list of
substitutions for hypotheses depending on `h`. The number of new goals may be smaller than the
number of constructors. Some goals may be discarded when the indices to not match.
See `induction` for information on the list of substitutions.
The `cases` tactic is implemented using this one, and it relaxes the restriction of `h`.
Note: There is one "new hypothesis" for every constructor argument. These are
usually local constants, but due to dependent pattern matching, they can also
be arbitrary terms. -/
meta constant cases_core (h : expr) (ns : list name := []) (md := semireducible) : tactic (list (name × list expr × list (name × expr)))
/-- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/
meta constant destruct (e : expr) (md := semireducible) : tactic unit
/-- Generalizes the target with respect to `e`. -/
meta constant generalize (e : expr) (n : name := `_x) (md := semireducible) : tactic unit
/-- instantiate assigned metavariables in the given expression -/
meta constant instantiate_mvars : expr → tactic expr
/-- Add the given declaration to the environment -/
meta constant add_decl : declaration → tactic unit
/--
Changes the environment to the `new_env`.
The new environment does not need to be a descendant of the old one.
Use with care.
-/
meta constant set_env_core : environment → tactic unit
/-- Changes the environment to the `new_env`. `new_env` needs to be a descendant from the current environment. -/
meta constant set_env : environment → tactic unit
/-- `doc_string env d k` returns the doc string for `d` (if available) -/
meta constant doc_string : name → tactic string
/-- Set the docstring for the given declaration. -/
meta constant add_doc_string : name → string → tactic unit
/--
Create an auxiliary definition with name `c` where `type` and `value` may contain local constants and
meta-variables. This function collects all dependencies (universe parameters, universe metavariables,
local constants (aka hypotheses) and metavariables).
It updates the environment in the tactic_state, and returns an expression of the form
(c.{l_1 ... l_n} a_1 ... a_m)
where l_i's and a_j's are the collected dependencies.
-/
meta constant add_aux_decl (c : name) (type : expr) (val : expr) (is_lemma : bool) : tactic expr
/-- Returns a list of all top-level (`/-! ... -/`) docstrings in the active module and imported ones.
The returned object is a list of modules, indexed by `(some filename)` for imported modules
and `none` for the active one, where each module in the list is paired with a list
of `(position_in_file, docstring)` pairs. -/
meta constant olean_doc_strings : tactic (list (option string × (list (pos × string))))
/-- Returns a list of docstrings in the active module. An entry in the list can be either:
- a top-level (`/-! ... -/`) docstring, represented as `(none, docstring)`
- a declaration-specific (`/-- ... -/`) docstring, represented as `(some decl_name, docstring)` -/
meta def module_doc_strings : tactic (list (option name × string)) :=
do
/- Obtain a list of top-level docs in current module. -/
mod_docs ← olean_doc_strings,
let mod_docs: list (list (option name × string)) :=
mod_docs.filter_map (λ d,
if d.1.is_none
then some (d.2.map
(λ pos_doc, ⟨none, pos_doc.2⟩))
else none),
let mod_docs := mod_docs.join,
/- Obtain list of declarations in current module. -/
e ← get_env,
let decls := environment.fold e ([]: list name)
(λ d acc, let n := d.to_name in
if (environment.decl_olean e n).is_none
then n::acc else acc),
/- Map declarations to those which have docstrings. -/
decls ← decls.mfoldl (λa n,
(doc_string n >>=
λ doc, pure $ (some n, doc) :: a)
<|> pure a) [],
pure (mod_docs ++ decls)
/-- Set attribute `attr_name` for constant `c_name` with the given priority.
If the priority is none, then use default -/
meta constant set_basic_attribute (attr_name : name) (c_name : name) (persistent := ff) (prio : option nat := none) : tactic unit
/-- `unset_attribute attr_name c_name` -/
meta constant unset_attribute : name → name → tactic unit
/-- `has_attribute attr_name c_name` succeeds if the declaration `decl_name`
has the attribute `attr_name`. The result is the priority and whether or not
the attribute is persistent. -/
meta constant has_attribute : name → name → tactic (bool × nat)
/-- `copy_attribute attr_name c_name p d_name` copy attribute `attr_name` from
`src` to `tgt` if it is defined for `src`; make it persistent if `p` is `tt`;
if `p` is `none`, the copied attribute is made persistent iff it is persistent on `src` -/
meta def copy_attribute (attr_name : name) (src : name) (tgt : name) (p : option bool := none) : tactic unit :=
try $ do
(p', prio) ← has_attribute attr_name src,
let p := p.get_or_else p',
set_basic_attribute attr_name tgt p (some prio)
/-- Name of the declaration currently being elaborated. -/
meta constant decl_name : tactic name
/-- `save_type_info e ref` save (typeof e) at position associated with ref -/
meta constant save_type_info {elab : bool} : expr → expr elab → tactic unit
meta constant save_info_thunk : pos → (unit → format) → tactic unit
/-- Return list of currently open namespaces -/
meta constant open_namespaces : tactic (list name)
/-- Return tt iff `t` "occurs" in `e`. The occurrence checking is performed using
keyed matching with the given transparency setting.
We say `t` occurs in `e` by keyed matching iff there is a subterm `s`
s.t. `t` and `s` have the same head, and `is_def_eq t s md`
The main idea is to minimize the number of `is_def_eq` checks
performed. -/
meta constant kdepends_on (e t : expr) (md := reducible) : tactic bool
/-- Abstracts all occurrences of the term `t` in `e` using keyed matching.
If `unify` is `ff`, then matching is used instead of unification.
That is, metavariables occurring in `e` are not assigned. -/
meta constant kabstract (e t : expr) (md := reducible) (unify := tt) : tactic expr
/-- Blocks the execution of the current thread for at least `msecs` milliseconds.
This tactic is used mainly for debugging purposes. -/
meta constant sleep (msecs : nat) : tactic unit
/-- Type check `e` with respect to the current goal.
Fails if `e` is not type correct. -/
meta constant type_check (e : expr) (md := semireducible) : tactic unit
open list nat
/-- A `tag` is a list of `names`. These are attached to goals to help tactics track them.-/
def tag : Type := list name
/-- Enable/disable goal tagging. -/
meta constant enable_tags (b : bool) : tactic unit
/-- Return tt iff goal tagging is enabled. -/
meta constant tags_enabled : tactic bool
/-- Tag goal `g` with tag `t`. It does nothing if goal tagging is disabled.
Remark: `set_goal g []` removes the tag -/
meta constant set_tag (g : expr) (t : tag) : tactic unit
/-- Return tag associated with `g`. Return `[]` if there is no tag. -/
meta constant get_tag (g : expr) : tactic tag
/-- By default, Lean only considers local instances in the header of declarations.
This has two main benefits.
1- Results produced by the type class resolution procedure can be easily cached.
2- The set of local instances does not have to be recomputed.
This approach has the following disadvantages:
1- Frozen local instances cannot be reverted.
2- Local instances defined inside of a declaration are not considered during type
class resolution.
This tactic resets the set of local instances. After executing this tactic,
the set of local instances will be recomputed and the cache will be frequently
reset. Note that, the cache is still used when executing a single tactic that
may generate many type class resolution problems (e.g., `simp`). -/
meta constant unfreeze_local_instances : tactic unit
/--
Freeze the current set of local instances.
-/
meta constant freeze_local_instances : tactic unit
/- Return the list of frozen local instances. Return `none` if local instances were not frozen. -/
meta constant frozen_local_instances : tactic (option (list expr))
/-- Run the provided tactic, associating it to the given AST node. -/
meta constant with_ast {α : Type u} (ast : ℕ) (t : tactic α) : tactic α
meta def induction' (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic unit :=
induction h ns rec md >> return ()
/-- Remark: set_goals will erase any solved goal -/
meta def cleanup : tactic unit :=
get_goals >>= set_goals
/-- Auxiliary definition used to implement begin ... end blocks -/
meta def step {α : Type u} (t : tactic α) : tactic unit :=
t >>[tactic] cleanup
meta def istep {α : Type u} (line0 col0 line col ast : ℕ) (t : tactic α) : tactic unit :=
λ s, (@scope_trace _ line col (λ _, with_ast ast (step t) s)).clamp_pos line0 line col
meta def is_prop (e : expr) : tactic bool :=
do t ← infer_type e,
return (t = `(Prop))
/-- Return true iff n is the name of declaration that is a proposition. -/
meta def is_prop_decl (n : name) : tactic bool :=
do env ← get_env,
d ← env.get n,
t ← return $ d.type,
is_prop t
meta def is_proof (e : expr) : tactic bool :=
infer_type e >>= is_prop
meta def whnf_no_delta (e : expr) : tactic expr :=
whnf e transparency.none
/-- Return `e` in weak head normal form with respect to the given transparency setting,
or `e` head is a generalized constructor or inductive datatype. -/
meta def whnf_ginductive (e : expr) (md := semireducible) : tactic expr :=
whnf e md ff
meta def whnf_target : tactic unit :=
target >>= whnf >>= change
/-- Change the target of the main goal.
The input expression must be definitionally equal to the current target.
The tactic does not check whether `e`
is definitionally equal to the current target. The error will only be detected by the kernel type checker. -/
meta def unsafe_change (e : expr) : tactic unit :=
change e ff
/-- Pi or elet introduction.
Given the tactic state `⊢ Π x : α, Y`, ``intro `hello`` will produce the state `hello : α ⊢ Y[x/hello]`.
Returns the new local constant. Similarly for `elet` expressions.
If the target is not a Pi or elet it will try to put it in WHNF.
-/
meta def intro (n : name) : tactic expr :=
do t ← target,
if expr.is_pi t ∨ expr.is_let t then intro_core n
else whnf_target >> intro_core n
/--
A variant of `intro` which makes sure that the introduced hypothesis's name is
unique in the context. If there is no hypothesis named `n` in the context yet,
`intro_fresh n` is the same as `intro n`. If there is already a hypothesis named
`n`, the new hypothesis is named `n_1` (or `n_2` if `n_1` already exists, etc.).
If `offset` is given, the new names are `n_offset`, `n_offset+1` etc.
If `n` is `_`, `intro_fresh n` is the same as `intro1`. The `offset` is ignored
in this case.
-/
meta def intro_fresh (n : name) (offset : option nat := none) : tactic expr :=
if n = `_
then intro `_
else do
n ← get_unused_name n offset,
intro n
/-- Like `intro` except the name is derived from the bound name in the Π. -/
meta def intro1 : tactic expr :=
intro `_
/-- Repeatedly apply `intro1` and return the list of new local constants in order of introduction. -/
meta def intros : tactic (list expr) :=
do t ← target,
match t with
| expr.pi _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs)
| expr.elet _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs)
| _ := return []
end
/-- Same as `intros`, except with the given names for the new hypotheses. Use the name ```_``` to instead use the binder's name.-/
meta def intro_lst (ns : list name) : tactic (list expr) :=
ns.mmap intro
/--
A variant of `intro_lst` which makes sure that the introduced hypotheses' names
are unique in the context. See `intro_fresh`.
-/
meta def intro_lst_fresh (ns : list name) : tactic (list expr) :=
ns.mmap intro_fresh
/-- Introduces new hypotheses with forward dependencies. -/
meta def intros_dep : tactic (list expr) :=
do t ← target,
let proc (b : expr) :=
if b.has_var_idx 0 then
do h ← intro1, hs ← intros_dep, return (h::hs)
else
-- body doesn't depend on new hypothesis
return [],
match t with
| expr.pi _ _ _ b := proc b
| expr.elet _ _ _ b := proc b
| _ := return []
end
meta def introv : list name → tactic (list expr)
| [] := intros_dep
| (n::ns) := do hs ← intros_dep, h ← intro n, hs' ← introv ns, return (hs ++ h :: hs')
/--
`intron' n` introduces `n` hypotheses and returns the resulting local
constants. Fails if there are not at least `n` arguments to introduce. If you do
not need the return value, use `intron`.
-/
meta def intron' (n : ℕ) : tactic (list expr)
:= iterate_exactly n intro1
/--
Like `intron'` but the introduced hypotheses' names are derived from `base`,
i.e. `base`, `base_1` etc. The new names are unique in the context. If `offset`
is given, the new names will be `base_offset`, `base_offset+1` etc.
-/
meta def intron_base (n : ℕ) (base : name) (offset : option nat := none)
: tactic (list expr)
:= iterate_exactly n (intro_fresh base offset)
/--
`intron_with i ns base offset` introduces `i` hypotheses using the names from
`ns`. If `ns` contains less than `i` names, the remaining hypotheses' names are
derived from `base` and `offset` (as with `intron_base`). If `base` is `_`, the
names are derived from the Π binder names.
Returns the introduced local constants and the remaining names from `ns` (if
`ns` contains more than `i` names).
-/
meta def intron_with
: ℕ → list name → opt_param name `_ → opt_param (option ℕ) none
→ tactic (list expr × list name)
| 0 ns _ _ := pure ([], ns)
| (i + 1) [] base offset := do
hs ← intron_base (i + 1) base offset,
pure (hs, [])
| (i + 1) (n :: ns) base offset := do
h ← intro n,
⟨hs, rest⟩ ← intron_with i ns base offset,
pure (h :: hs, rest)
/-- Returns n fully qualified if it refers to a constant, or else fails. -/
meta def resolve_constant (n : name) : tactic name :=
do e ← resolve_name n,
match e with
| expr.const n _ := pure n
| _ := do
e ← to_expr e tt ff,
expr.const n _ ← pure $ e.get_app_fn,
pure n
end
meta def to_expr_strict (q : pexpr) : tactic expr :=
to_expr q
/--
Example: with `x : ℕ, h : P(x) ⊢ T(x)`, `revert x` returns `2` and produces the state ` ⊢ Π x, P(x) → T(x)`.
-/
meta def revert (l : expr) : tactic nat :=
revert_lst [l]
/- Revert "all" hypotheses. Actually, the tactic only reverts
hypotheses occurring after the last frozen local instance.
Recall that frozen local instances cannot be reverted.
We can use `unfreeze_local_instances` to workaround this limitation. -/
meta def revert_all : tactic nat :=
do lctx ← local_context,
lis ← frozen_local_instances,
match lis with
| none := revert_lst lctx
| some [] := revert_lst lctx
/- `hi` is the last local instance. We shoul truncate `lctx` at `hi`. -/
| some (hi::his) := revert_lst $ lctx.foldl (λ r h, if h.local_uniq_name = hi.local_uniq_name then [] else h :: r) []
end
meta def clear_lst : list name → tactic unit
| [] := skip
| (n::ns) := do H ← get_local n, clear H, clear_lst ns
meta def match_not (e : expr) : tactic expr :=
match (expr.is_not e) with
| (some a) := return a
| none := fail "expression is not a negation"
end
meta def match_and (e : expr) : tactic (expr × expr) :=
match (expr.is_and e) with
| (some (α, β)) := return (α, β)
| none := fail "expression is not a conjunction"
end
meta def match_or (e : expr) : tactic (expr × expr) :=
match (expr.is_or e) with
| (some (α, β)) := return (α, β)
| none := fail "expression is not a disjunction"
end
meta def match_iff (e : expr) : tactic (expr × expr) :=
match (expr.is_iff e) with
| (some (lhs, rhs)) := return (lhs, rhs)
| none := fail "expression is not an iff"
end
meta def match_eq (e : expr) : tactic (expr × expr) :=
match (expr.is_eq e) with
| (some (lhs, rhs)) := return (lhs, rhs)
| none := fail "expression is not an equality"
end
meta def match_ne (e : expr) : tactic (expr × expr) :=
match (expr.is_ne e) with
| (some (lhs, rhs)) := return (lhs, rhs)
| none := fail "expression is not a disequality"
end
meta def match_heq (e : expr) : tactic (expr × expr × expr × expr) :=
do match (expr.is_heq e) with
| (some (α, lhs, β, rhs)) := return (α, lhs, β, rhs)
| none := fail "expression is not a heterogeneous equality"
end
meta def match_refl_app (e : expr) : tactic (name × expr × expr) :=
do env ← get_env,
match (environment.is_refl_app env e) with
| (some (R, lhs, rhs)) := return (R, lhs, rhs)
| none := fail "expression is not an application of a reflexive relation"
end
meta def match_app_of (e : expr) (n : name) : tactic (list expr) :=
guard (expr.is_app_of e n) >> return e.get_app_args
meta def get_local_type (n : name) : tactic expr :=
get_local n >>= infer_type
meta def trace_result : tactic unit :=
format_result >>= trace
meta def rexact (e : expr) : tactic unit :=
exact e reducible
meta def any_hyp_aux {α : Type} (f : expr → tactic α) : list expr → tactic α
| [] := failed
| (h :: hs) := f h <|> any_hyp_aux hs
meta def any_hyp {α : Type} (f : expr → tactic α) : tactic α :=
local_context >>= any_hyp_aux f
/-- `find_same_type t es` tries to find in es an expression with type definitionally equal to t -/
meta def find_same_type : expr → list expr → tactic expr
| e [] := failed
| e (H :: Hs) :=
do t ← infer_type H,
(unify e t >> return H) <|> find_same_type e Hs
meta def find_assumption (e : expr) : tactic expr :=
do ctx ← local_context, find_same_type e ctx
meta def assumption : tactic unit :=
do { ctx ← local_context,
t ← target,
H ← find_same_type t ctx,
exact H }
<|> fail "assumption tactic failed"
meta def save_info (p : pos) : tactic unit :=
do s ← read,
tactic.save_info_thunk p (λ _, tactic_state.to_format s)
notation `‹` p `›` := (by assumption : p)
/-- Swap first two goals, do nothing if tactic state does not have at least two goals. -/
meta def swap : tactic unit :=
do gs ← get_goals,
match gs with
| (g₁ :: g₂ :: rs) := set_goals (g₂ :: g₁ :: rs)
| e := skip
end
/-- `assert h t`, adds a new goal for t, and the hypothesis `h : t` in the current goal. -/
meta def assert (h : name) (t : expr) : tactic expr :=
do assert_core h t, swap, e ← intro h, swap, return e
/-- `assertv h t v`, adds the hypothesis `h : t` in the current goal if v has type t. -/
meta def assertv (h : name) (t : expr) (v : expr) : tactic expr :=
assertv_core h t v >> intro h
/-- `define h t`, adds a new goal for t, and the hypothesis `h : t := ?M` in the current goal. -/
meta def define (h : name) (t : expr) : tactic expr :=
do define_core h t, swap, e ← intro h, swap, return e
/-- `definev h t v`, adds the hypothesis (h : t := v) in the current goal if v has type t. -/
meta def definev (h : name) (t : expr) (v : expr) : tactic expr :=
definev_core h t v >> intro h
/-- Add `h : t := pr` to the current goal -/
meta def pose (h : name) (t : option expr := none) (pr : expr) : tactic expr :=
let dv := λt, definev h t pr in
option.cases_on t (infer_type pr >>= dv) dv
/-- Add `h : t` to the current goal, given a proof `pr : t` -/
meta def note (h : name) (t : option expr := none) (pr : expr) : tactic expr :=
let dv := λt, assertv h t pr in
option.cases_on t (infer_type pr >>= dv) dv
/-- Return the number of goals that need to be solved -/
meta def num_goals : tactic nat :=
do gs ← get_goals,
return (length gs)
/-- Rotate the goals to the right by `n`. That is, take the goal at the back and push it to the front `n` times.
[NOTE] We have to provide the instance argument `[has_mod nat]` because
mod for nat was not defined yet -/
meta def rotate_right (n : nat) [has_mod nat] : tactic unit :=
do ng ← num_goals,
if ng = 0 then skip
else rotate_left (ng - n % ng)
/-- Rotate the goals to the left by `n`. That is, put the main goal to the back `n` times. -/
meta def rotate : nat → tactic unit :=
rotate_left
private meta def repeat_aux (t : tactic unit) : list expr → list expr → tactic unit
| [] r := set_goals r.reverse
| (g::gs) r := do
ok ← try_core (set_goals [g] >> t),
match ok with
| none := repeat_aux gs (g::r)
| _ := do
gs' ← get_goals,
repeat_aux (gs' ++ gs) r
end
/-- This tactic is applied to each goal. If the application succeeds,
the tactic is applied recursively to all the generated subgoals until it eventually fails.
The recursion stops in a subgoal when the tactic has failed to make progress.
The tactic `repeat` never fails. -/
meta def repeat (t : tactic unit) : tactic unit :=
do gs ← get_goals, repeat_aux t gs []
/-- `first [t_1, ..., t_n]` applies the first tactic that doesn't fail.
The tactic fails if all t_i's fail. -/
meta def first {α : Type u} : list (tactic α) → tactic α
| [] := fail "first tactic failed, no more alternatives"
| (t::ts) := t <|> first ts
/-- Applies the given tactic to the main goal and fails if it is not solved. -/
meta def solve1 {α} (tac : tactic α) : tactic α :=
do gs ← get_goals,
match gs with
| [] := fail "solve1 tactic failed, there isn't any goal left to focus"
| (g::rs) :=
do set_goals [g],
a ← tac,
gs' ← get_goals,
match gs' with
| [] := set_goals rs >> pure a
| gs := fail "solve1 tactic failed, focused goal has not been solved"
end
end
/-- `solve [t_1, ... t_n]` applies the first tactic that solves the main goal. -/
meta def solve {α} (ts : list (tactic α)) : tactic α :=
first $ map solve1 ts
private meta def focus_aux {α} : list (tactic α) → list expr → list expr → tactic (list α)
| [] [] rs := set_goals rs *> pure []
| (t::ts) [] rs := fail "focus tactic failed, insufficient number of goals"
| tts (g::gs) rs :=
mcond (is_assigned g) (focus_aux tts gs rs) $
do set_goals [g],
t::ts ← pure tts | fail "focus tactic failed, insufficient number of tactics",
a ← t,
rs' ← get_goals,
as ← focus_aux ts gs (rs ++ rs'),
pure $ a :: as
/--
`focus [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of
goals is not n. Returns the results of t_i (one per goal).
-/
meta def focus {α} (ts : list (tactic α)) : tactic (list α) :=
do gs ← get_goals, focus_aux ts gs []
private meta def focus'_aux : list (tactic unit) → list expr → list expr → tactic unit
| [] [] rs := set_goals rs
| (t::ts) [] rs := fail "focus' tactic failed, insufficient number of goals"
| tts (g::gs) rs :=
mcond (is_assigned g) (focus'_aux tts gs rs) $
do set_goals [g],
t::ts ← pure tts | fail "focus' tactic failed, insufficient number of tactics",
t,
rs' ← get_goals,
focus'_aux ts gs (rs ++ rs')
/-- `focus' [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of goals is not n. -/
meta def focus' (ts : list (tactic unit)) : tactic unit :=
do gs ← get_goals, focus'_aux ts gs []
meta def focus1 {α} (tac : tactic α) : tactic α :=
do g::gs ← get_goals,
match gs with
| [] := tac
| _ := do
set_goals [g],
a ← tac,
gs' ← get_goals,
set_goals (gs' ++ gs),
return a
end
private meta def all_goals_core {α} (tac : tactic α)
: list expr → list expr → tactic (list α)
| [] ac := set_goals ac *> pure []
| (g :: gs) ac :=
mcond (is_assigned g) (all_goals_core gs ac) $
do set_goals [g],
a ← tac,
new_gs ← get_goals,
as ← all_goals_core gs (ac ++ new_gs),
pure $ a :: as
/--
Apply the given tactic to all goals. Return one result per goal.
-/
meta def all_goals {α} (tac : tactic α) : tactic (list α) :=
do gs ← get_goals,
all_goals_core tac gs []
private meta def all_goals'_core (tac : tactic unit) : list expr → list expr → tactic unit
| [] ac := set_goals ac
| (g :: gs) ac :=
mcond (is_assigned g) (all_goals'_core gs ac) $
do set_goals [g],
tac,
new_gs ← get_goals,
all_goals'_core gs (ac ++ new_gs)
/-- Apply the given tactic to all goals. -/
meta def all_goals' (tac : tactic unit) : tactic unit :=
do gs ← get_goals,
all_goals'_core tac gs []
private meta def any_goals_core {α} (tac : tactic α) : list expr → list expr → bool → tactic (list (option α))
| [] ac progress := guard progress *> set_goals ac *> pure []
| (g :: gs) ac progress :=
mcond (is_assigned g) (any_goals_core gs ac progress) $
do set_goals [g],
res ← try_core tac,
new_gs ← get_goals,
ress ← any_goals_core gs (ac ++ new_gs) (res.is_some || progress),
pure $ res :: ress
/--
Apply `tac` to any goal where it succeeds. The tactic succeeds if `tac`
succeeds for at least one goal. The returned list contains the result of `tac`
for each goal: `some a` if tac succeeded, or `none` if it did not.
-/
meta def any_goals {α} (tac : tactic α) : tactic (list (option α)) :=
do gs ← get_goals,
any_goals_core tac gs [] ff
private meta def any_goals'_core (tac : tactic unit) : list expr → list expr → bool → tactic unit
| [] ac progress := guard progress >> set_goals ac
| (g :: gs) ac progress :=
mcond (is_assigned g) (any_goals'_core gs ac progress) $
do set_goals [g],
succeeded ← try_core tac,
new_gs ← get_goals,
any_goals'_core gs (ac ++ new_gs) (succeeded.is_some || progress)
/-- Apply the given tactic to any goal where it succeeds. The tactic succeeds only if
tac succeeds for at least one goal. -/
meta def any_goals' (tac : tactic unit) : tactic unit :=
do gs ← get_goals,
any_goals'_core tac gs [] ff
/--
LCF-style AND_THEN tactic. It applies `tac1` to the main goal, then applies
`tac2` to each goal produced by `tac1`.
-/
meta def seq {α β} (tac1 : tactic α) (tac2 : α → tactic β) : tactic (list β) :=
do g::gs ← get_goals,
set_goals [g],
a ← tac1,
bs ← all_goals $ tac2 a,
gs' ← get_goals,
set_goals (gs' ++ gs),
pure bs
/-- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/
meta def seq' (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit :=
do g::gs ← get_goals,
set_goals [g],
tac1, all_goals' tac2,
gs' ← get_goals,
set_goals (gs' ++ gs)
/--
Applies `tac1` to the main goal, then applies each of the tactics in `tacs2` to
one of the produced subgoals (like `focus'`).
-/
meta def seq_focus {α β} (tac1 : tactic α) (tacs2 : α → list (tactic β)) : tactic (list β) :=
do g::gs ← get_goals,
set_goals [g],
a ← tac1,
bs ← focus $ tacs2 a,
gs' ← get_goals,
set_goals (gs' ++ gs),
pure bs
/--
Applies `tac1` to the main goal, then applies each of the tactics in `tacs2` to
one of the produced subgoals (like `focus`).
-/
meta def seq_focus' (tac1 : tactic unit) (tacs2 : list (tactic unit)) : tactic unit :=
do g::gs ← get_goals,
set_goals [g],
tac1, focus tacs2,
gs' ← get_goals,
set_goals (gs' ++ gs)
meta instance andthen_seq : has_andthen (tactic unit) (tactic unit) (tactic unit) :=
⟨seq'⟩
meta instance andthen_seq_focus : has_andthen (tactic unit) (list (tactic unit)) (tactic unit) :=
⟨seq_focus'⟩
meta constant is_trace_enabled_for : name → bool
/-- Execute tac only if option trace.n is set to true. -/
meta def when_tracing (n : name) (tac : tactic unit) : tactic unit :=
when (is_trace_enabled_for n = tt) tac
/-- Fail if there are no remaining goals. -/
meta def fail_if_no_goals : tactic unit :=
do n ← num_goals,
when (n = 0) (fail "tactic failed, there are no goals to be solved")
/-- Fail if there are unsolved goals. -/
meta def done : tactic unit :=
do n ← num_goals,
when (n ≠ 0) (fail "done tactic failed, there are unsolved goals")
meta def apply_opt_param : tactic unit :=
do `(opt_param %%t %%v) ← target,
exact v
meta def apply_auto_param : tactic unit :=
do `(auto_param %%type %%tac_name_expr) ← target,
change type,
tac_name ← eval_expr name tac_name_expr,
tac ← eval_expr (tactic unit) (expr.const tac_name []),
tac
meta def has_opt_auto_param (ms : list expr) : tactic bool :=
ms.mfoldl
(λ r m, do type ← infer_type m,
return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2)
ff
meta def try_apply_opt_auto_param (cfg : apply_cfg) (ms : list expr) : tactic unit :=
when (cfg.auto_param || cfg.opt_param) $
mwhen (has_opt_auto_param ms) $ do
gs ← get_goals,
ms.mmap' (λ m, mwhen (bnot <$> is_assigned m) $
set_goals [m] >>
when cfg.opt_param (try apply_opt_param) >>
when cfg.auto_param (try apply_auto_param)),
set_goals gs
meta def has_opt_auto_param_for_apply (ms : list (name × expr)) : tactic bool :=
ms.mfoldl
(λ r m, do type ← infer_type m.2,
return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2)
ff
meta def try_apply_opt_auto_param_for_apply (cfg : apply_cfg) (ms : list (name × expr)) : tactic unit :=
mwhen (has_opt_auto_param_for_apply ms) $ do
gs ← get_goals,
ms.mmap' (λ m, mwhen (bnot <$> (is_assigned m.2)) $
set_goals [m.2] >>
when cfg.opt_param (try apply_opt_param) >>
when cfg.auto_param (try apply_auto_param)),
set_goals gs
meta def apply (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) :=
do r ← apply_core e cfg,
try_apply_opt_auto_param_for_apply cfg r,
return r
/-- Same as `apply` but __all__ arguments that weren't inferred are added to goal list. -/
meta def fapply (e : expr) : tactic (list (name × expr)) :=
apply e {new_goals := new_goals.all}
/-- Same as `apply` but only goals that don't depend on other goals are added to goal list. -/
meta def eapply (e : expr) : tactic (list (name × expr)) :=
apply e {new_goals := new_goals.non_dep_only}
/-- Try to solve the main goal using type class resolution. -/
meta def apply_instance : tactic unit :=
do tgt ← target >>= instantiate_mvars,
b ← is_class tgt,
if b then mk_instance tgt >>= exact
else fail "apply_instance tactic fail, target is not a type class"
/-- Create a list of universe meta-variables of the given size. -/
meta def mk_num_meta_univs : nat → tactic (list level)
| 0 := return []
| (succ n) := do
l ← mk_meta_univ,
ls ← mk_num_meta_univs n,
return (l::ls)
/-- Return `expr.const c [l_1, ..., l_n]` where l_i's are fresh universe meta-variables. -/
meta def mk_const (c : name) : tactic expr :=
do env ← get_env,
decl ← env.get c,
let num := decl.univ_params.length,
ls ← mk_num_meta_univs num,
return (expr.const c ls)
/-- Apply the constant `c` -/
meta def applyc (c : name) (cfg : apply_cfg := {}) : tactic unit :=
do c ← mk_const c, apply c cfg, skip
meta def eapplyc (c : name) : tactic unit :=
do c ← mk_const c, eapply c, skip
meta def save_const_type_info (n : name) {elab : bool} (ref : expr elab) : tactic unit :=
try (do c ← mk_const n, save_type_info c ref)
/-- Create a fresh universe `?u`, a metavariable `?T : Type.{?u}`,
and return metavariable `?M : ?T`.
This action can be used to create a meta-variable when
we don't know its type at creation time -/
meta def mk_mvar : tactic expr :=
do u ← mk_meta_univ,
t ← mk_meta_var (expr.sort u),
mk_meta_var t
/-- Makes a sorry macro with a meta-variable as its type. -/
meta def mk_sorry : tactic expr := do
u ← mk_meta_univ,
t ← mk_meta_var (expr.sort u),
return $ expr.mk_sorry t
/-- Closes the main goal using sorry. -/
meta def admit : tactic unit :=
target >>= exact ∘ expr.mk_sorry
meta def mk_local' (pp_name : name) (bi : binder_info) (type : expr) : tactic expr := do
uniq_name ← mk_fresh_name,
return $ expr.local_const uniq_name pp_name bi type
meta def mk_local_def (pp_name : name) (type : expr) : tactic expr :=
mk_local' pp_name binder_info.default type
meta def mk_local_pis : expr → tactic (list expr × expr)
| (expr.pi n bi d b) := do
p ← mk_local' n bi d,
(ps, r) ← mk_local_pis (expr.instantiate_var b p),
return ((p :: ps), r)
| e := return ([], e)
private meta def get_pi_arity_aux : expr → tactic nat
| (expr.pi n bi d b) :=
do m ← mk_fresh_name,
let l := expr.local_const m n bi d,
new_b ← whnf (expr.instantiate_var b l),
r ← get_pi_arity_aux new_b,
return (r + 1)
| e := return 0
/-- Compute the arity of the given (Pi-)type -/
meta def get_pi_arity (type : expr) : tactic nat :=
whnf type >>= get_pi_arity_aux
/-- Compute the arity of the given function -/
meta def get_arity (fn : expr) : tactic nat :=
infer_type fn >>= get_pi_arity
meta def triv : tactic unit := mk_const `trivial >>= exact
notation `dec_trivial` := of_as_true (by tactic.triv)
meta def by_contradiction (H : name) : tactic expr :=
do tgt ← target,
tgt_wh ← whnf tgt reducible, -- to ensure that `not` in `ne` is found
(match_not tgt_wh $> ()) <|>
(mk_mapp `decidable.by_contradiction [some tgt, none] >>= eapply >> skip) <|>
(mk_mapp `classical.by_contradiction [some tgt] >>= eapply >> skip) <|>
fail "tactic by_contradiction failed, target is not a proposition",
intro H
private meta def generalizes_aux (md : transparency) : list expr → tactic unit
| [] := skip
| (e::es) := generalize e `x md >> generalizes_aux es
meta def generalizes (es : list expr) (md := semireducible) : tactic unit :=
generalizes_aux md es
private meta def kdependencies_core (e : expr) (md : transparency) : list expr → list expr → tactic (list expr)
| [] r := return r
| (h::hs) r :=
do type ← infer_type h,
d ← kdepends_on type e md,
if d then kdependencies_core hs (h::r)
else kdependencies_core hs r
/-- Return all hypotheses that depends on `e`
The dependency test is performed using `kdepends_on` with the given transparency setting. -/
meta def kdependencies (e : expr) (md := reducible) : tactic (list expr) :=
do ctx ← local_context, kdependencies_core e md ctx []
/-- Revert all hypotheses that depend on `e` -/
meta def revert_kdependencies (e : expr) (md := reducible) : tactic nat :=
kdependencies e md >>= revert_lst
meta def revert_kdeps (e : expr) (md := reducible) :=
revert_kdependencies e md
/-- Postprocess the output of `cases_core`:
- The third component of each tuple in the input list (the list of
substitutions) is dropped since we don't use it anywhere.
- The second component (the list of new hypotheses) is filtered: any expression
that is not a local constant is dropped. We only use the new hypotheses for
the renaming functionality of `case`, so we want to keep only those
"new hypotheses" that are, in fact, local constants. -/
private meta def cases_postprocess (hs : list (name × list expr × list (name × expr)))
: list (name × list expr) :=
hs.map $ λ ⟨n, hs, _⟩, (n, hs.filter (λ h, h.is_local_constant))
/-- Similar to `cases_core`, but `e` doesn't need to be a hypothesis.
Remark, it reverts dependencies using `revert_kdeps`.
Two different transparency modes are used `md` and `dmd`.
The mode `md` is used with `cases_core` and `dmd` with `generalize` and `revert_kdeps`.
It returns the constructor names associated with each new goal and the newly
introduced hypotheses. Note that while `cases_core` may return "new
hypotheses" that are not local constants, this tactic only returns local
constants.
-/
meta def cases (e : expr) (ids : list name := []) (md := semireducible) (dmd := semireducible) : tactic (list (name × list expr)) :=
if e.is_local_constant then
do r ← cases_core e ids md, return $ cases_postprocess r
else do
n ← revert_kdependencies e dmd,
x ← get_unused_name,
(tactic.generalize e x dmd)
<|>
(do t ← infer_type e,
tactic.assertv x t e,
get_local x >>= tactic.revert,
return ()),
h ← tactic.intro1,
focus1 $ do
r ← cases_core h ids md,
hs' ← all_goals (intron' n),
return $ cases_postprocess $ r.map₂ (λ ⟨n, hs, x⟩ hs', (n, hs ++ hs', x)) hs'
/-- The same as `exact` except you can add proof holes. -/
meta def refine (e : pexpr) : tactic unit :=
do tgt : expr ← target,
to_expr ``(%%e : %%tgt) tt >>= exact
/--
`by_cases p h` splits the main goal into two cases, assuming `h : p` in the
first branch, and `h : ¬ p` in the second branch. The expression `p` needs to
be a proposition.
The produced proof term is `dite p ?m_1 ?m_2`.
-/
meta def by_cases (e : expr) (h : name) : tactic unit := do
dec_e ← mk_app ``decidable [e] <|> fail "by_cases tactic failed, type is not a proposition",
inst ← mk_instance dec_e <|> pure `(classical.prop_decidable %%e),
tgt ← target,
expr.sort tgt_u ← infer_type tgt >>= whnf,
g1 ← mk_meta_var (e.imp tgt),
g2 ← mk_meta_var (`(¬ %%e).imp tgt),
focus1 $ do
exact $ expr.const ``dite [tgt_u] tgt e inst g1 g2,
set_goals [g1, g2],
all_goals' $ intro h >> skip
meta def funext_core : list name → bool → tactic unit
| [] tt := return ()
| ids only_ids := try $
do some (lhs, rhs) ← expr.is_eq <$> (target >>= whnf),
applyc `funext,
id ← if ids.empty ∨ ids.head = `_ then do
(expr.lam n _ _ _) ← whnf lhs
| pure `_,
return n
else return ids.head,
intro id,
funext_core ids.tail only_ids
meta def funext : tactic unit :=
funext_core [] ff
meta def funext_lst (ids : list name) : tactic unit :=
funext_core ids tt
private meta def get_undeclared_const (env : environment) (base : name) : ℕ → name | i :=
let n := base <.> ("_aux_" ++ repr i) in
if ¬env.contains n then n
else get_undeclared_const (i+1)
meta def new_aux_decl_name : tactic name := do
env ← get_env, n ← decl_name,
return $ get_undeclared_const env n 1
private meta def mk_aux_decl_name : option name → tactic name
| none := new_aux_decl_name
| (some suffix) := do p ← decl_name, return $ p ++ suffix
meta def abstract (tac : tactic unit) (suffix : option name := none) (zeta_reduce := tt) : tactic unit :=
do fail_if_no_goals,
gs ← get_goals,
type ← if zeta_reduce then target >>= zeta else target,
is_lemma ← is_prop type,
m ← mk_meta_var type,
set_goals [m],
tac,
n ← num_goals,
when (n ≠ 0) (fail "abstract tactic failed, there are unsolved goals"),
set_goals gs,
val ← instantiate_mvars m,
val ← if zeta_reduce then zeta val else return val,
c ← mk_aux_decl_name suffix,
e ← add_aux_decl c type val is_lemma,
exact e
/-- `solve_aux type tac` synthesize an element of 'type' using tactic 'tac' -/
meta def solve_aux {α : Type} (type : expr) (tac : tactic α) : tactic (α × expr) :=
do m ← mk_meta_var type,
gs ← get_goals,
set_goals [m],
a ← tac,
set_goals gs,
return (a, m)
/-- Return tt iff 'd' is a declaration in one of the current open namespaces -/
meta def in_open_namespaces (d : name) : tactic bool :=
do ns ← open_namespaces,
env ← get_env,
return $ ns.any (λ n, n.is_prefix_of d) && env.contains d
/-- Execute tac for 'max' "heartbeats". The heartbeat is approx. the maximum number of
memory allocations (in thousands) performed by 'tac'. This is a deterministic way of interrupting
long running tactics. -/
meta def try_for {α} (max : nat) (tac : tactic α) : tactic α :=
λ s,
match _root_.try_for max (tac s) with
| some r := r
| none := mk_exception "try_for tactic failed, timeout" none s
end
/-- Execute `tac` for `max` milliseconds. Useful due to variance
in the number of heartbeats taken by various tactics. -/
meta def try_for_time {α} (max : nat) (tac : tactic α) : tactic α :=
λ s,
match _root_.try_for_time max (tac s) with
| some r := r
| none := mk_exception "try_for_time tactic failed, timeout" none s
end
meta def updateex_env (f : environment → exceptional environment) : tactic unit :=
do env ← get_env,
env ← returnex $ f env,
set_env env
/- Add a new inductive datatype to the environment
name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/
meta def add_inductive (n : name) (ls : list name) (p : nat) (ty : expr) (is : list (name × expr))
(is_meta : bool := ff) : tactic unit :=
updateex_env $ λe, e.add_inductive n ls p ty is is_meta
meta def add_meta_definition (n : name) (lvls : list name) (type value : expr) : tactic unit :=
add_decl (declaration.defn n lvls type value reducibility_hints.abbrev ff)
/-- add declaration `d` as a protected declaration -/
meta def add_protected_decl (d : declaration) : tactic unit :=
updateex_env $ λ e, e.add_protected d
/-- check if `n` is the name of a protected declaration -/
meta def is_protected_decl (n : name) : tactic bool :=
do env ← get_env,
return $ env.is_protected n
/-- `add_defn_equations` adds a definition specified by a list of equations.
The arguments:
* `lp`: list of universe parameters
* `params`: list of parameters (binders before the colon);
* `fn`: a local constant giving the name and type of the declaration
(with `params` in the local context);
* `eqns`: a list of equations, each of which is a list of patterns
(constructors applied to new local constants) and the branch
expression;
* `is_meta`: is the definition meta?
`add_defn_equations` can be used as:
do my_add ← mk_local_def `my_add `(ℕ → ℕ),
a ← mk_local_def `a ℕ,
b ← mk_local_def `b ℕ,
add_defn_equations [a] my_add
[ ([``(nat.zero)], a),
([``(nat.succ %%b)], my_add b) ])
ff -- non-meta
to create the following definition:
def my_add (a : ℕ) : ℕ → ℕ
| nat.zero := a
| (nat.succ b) := my_add b
-/
meta def add_defn_equations (lp : list name) (params : list expr) (fn : expr)
(eqns : list (list pexpr × expr)) (is_meta : bool) : tactic unit :=
do opt ← get_options,
updateex_env $ λ e, e.add_defn_eqns opt lp params fn eqns is_meta
/-- Get the revertible part of the local context. These are the hypotheses that
appear after the last frozen local instance in the local context. We call them
revertible because `revert` can revert them, unlike those hypotheses which occur
before a frozen instance. -/
meta def revertible_local_context : tactic (list expr) :=
do ctx ← local_context,
frozen ← frozen_local_instances,
pure $
match frozen with
| none := ctx
| some [] := ctx
| some (h :: _) := ctx.after (eq h)
end
/--
Rename local hypotheses according to the given `name_map`. The `name_map`
contains as keys those hypotheses that should be renamed; the associated values
are the new names.
This tactic can only rename hypotheses which occur after the last frozen local
instance. If you need to rename earlier hypotheses, try
`unfreeze_local_instances`.
If `strict` is true, we fail if `name_map` refers to hypotheses that do not
appear in the local context or that appear before a frozen local instance.
Conversely, if `strict` is false, some entries of `name_map` may be silently
ignored.
If `use_unique_names` is true, the keys of `name_map` should be the unique names
of hypotheses to be renamed. Otherwise, the keys should be display names.
Note that we allow shadowing, so renamed hypotheses may have the same name
as other hypotheses in the context. If `use_unique_names` is false and there are
multiple hypotheses with the same display name in the context, they are all
renamed.
-/
meta def rename_many (renames : name_map name) (strict := tt) (use_unique_names := ff)
: tactic unit :=
do let hyp_name : expr → name :=
if use_unique_names then expr.local_uniq_name else expr.local_pp_name,
ctx ← revertible_local_context,
-- The part of the context after (but including) the first hypthesis that
-- must be renamed.
let ctx_suffix := ctx.drop_while (λ h, (renames.find $ hyp_name h).is_none),
when strict $ do {
let ctx_names := rb_map.set_of_list (ctx_suffix.map hyp_name),
let invalid_renames :=
(renames.to_list.map prod.fst).filter (λ h, ¬ ctx_names.contains h),
when ¬ invalid_renames.empty $ fail $ format.join
[ "Cannot rename these hypotheses:\n"
, format.join $ (invalid_renames.map to_fmt).intersperse ", "
, format.line
, "This is because these hypotheses either do not occur in the\n"
, "context or they occur before a frozen local instance.\n"
, "In the latter case, try `tactic.unfreeze_local_instances`."
]
},
-- The new names for all hypotheses in ctx_suffix.
let new_names :=
ctx_suffix.map $ λ h,
(renames.find $ hyp_name h).get_or_else h.local_pp_name,
revert_lst ctx_suffix,
intro_lst new_names,
pure ()
/--
Rename a local hypothesis. This is a special case of `rename_many`;
see there for caveats.
-/
meta def rename (curr : name) (new : name) : tactic unit :=
rename_many (rb_map.of_list [⟨curr, new⟩])
/--
Rename a local hypothesis. Unlike `rename` and `rename_many`, this tactic does
not preserve the order of hypotheses. Its implementation is simpler (and
therefore probably faster) than that of `rename`.
-/
meta def rename_unstable (curr : name) (new : name) : tactic unit :=
do h ← get_local curr,
n ← revert h,
intro new,
intron (n - 1)
/--
"Replace" hypothesis `h : type` with `h : new_type` where `eq_pr` is a proof
that (type = new_type). The tactic actually creates a new hypothesis
with the same user facing name, and (tries to) clear `h`.
The `clear` step fails if `h` has forward dependencies. In this case, the old `h`
will remain in the local context. The tactic returns the new hypothesis. -/
meta def replace_hyp (h : expr) (new_type : expr) (eq_pr : expr) : tactic expr :=
do h_type ← infer_type h,
new_h ← assert h.local_pp_name new_type,
mk_eq_mp eq_pr h >>= exact,
try $ clear h,
return new_h
meta def main_goal : tactic expr :=
do g::gs ← get_goals, return g
/- Goal tagging support -/
meta def with_enable_tags {α : Type} (t : tactic α) (b := tt) : tactic α :=
do old ← tags_enabled,
enable_tags b,
r ← t,
enable_tags old,
return r
meta def get_main_tag : tactic tag :=
main_goal >>= get_tag
meta def set_main_tag (t : tag) : tactic unit :=
do g ← main_goal, set_tag g t
meta def subst (h : expr) : tactic unit :=
(do guard h.is_local_constant,
some (α, lhs, β, rhs) ← expr.is_heq <$> infer_type h,
is_def_eq α β,
new_h_type ← mk_app `eq [lhs, rhs],
new_h_pr ← mk_app `eq_of_heq [h],
new_h ← assertv h.local_pp_name new_h_type new_h_pr,
try (clear h),
subst_core new_h)
<|> subst_core h
end tactic
notation [parsing_only] `command`:max := tactic unit
open tactic
namespace list
meta def for_each {α} : list α → (α → tactic unit) → tactic unit
| [] fn := skip
| (e::es) fn := do fn e, for_each es fn
meta def any_of {α β} : list α → (α → tactic β) → tactic β
| [] fn := failed
| (e::es) fn := do opt_b ← try_core (fn e),
match opt_b with
| some b := return b
| none := any_of es fn
end
end list
/- Install monad laws tactic and use it to prove some instances. -/
/-- Try to prove with `iff.refl`.-/
meta def order_laws_tac := whnf_target >> intros >> to_expr ``(iff.refl _) >>= exact
meta def monad_from_pure_bind {m : Type u → Type v}
(pure : Π {α : Type u}, α → m α)
(bind : Π {α β : Type u}, m α → (α → m β) → m β) : monad m :=
{pure := @pure, bind := @bind}
meta instance : monad task :=
{map := @task.map, bind := @task.bind, pure := @task.pure}
namespace tactic
meta def mk_id_proof (prop : expr) (pr : expr) : expr :=
expr.app (expr.app (expr.const ``id [level.zero]) prop) pr
meta def mk_id_eq (lhs : expr) (rhs : expr) (pr : expr) : tactic expr :=
do prop ← mk_app `eq [lhs, rhs],
return $ mk_id_proof prop pr
meta def replace_target (new_target : expr) (pr : expr) : tactic unit :=
do t ← target,
assert `htarget new_target, swap,
ht ← get_local `htarget,
locked_pr ← mk_id_eq t new_target pr,
mk_eq_mpr locked_pr ht >>= exact
meta def eval_pexpr (α) [reflected α] (e : pexpr) : tactic α :=
to_expr ``(%%e : %%(reflect α)) ff ff >>= eval_expr α
meta def run_simple {α} : tactic_state → tactic α → option α
| ts t := match t ts with
| (interaction_monad.result.success a ts') := some a
| (interaction_monad.result.exception _ _ _) := none
end
end tactic
|
318443865f0b1db6946f6417174c53bd6cdcd790 | ed27983dd289b3bcad416f0b1927105d6ef19db8 | /src/inClassNotes/type_library/sum_test.lean | d43e2a50e59399284a14deb0ed59fc2142558858 | [] | no_license | liuxin-James/complogic-s21 | 0d55b76dbe25024473d31d98b5b83655c365f811 | 13e03e0114626643b44015c654151fb651603486 | refs/heads/master | 1,681,109,264,463 | 1,618,848,261,000 | 1,618,848,261,000 | 337,599,491 | 0 | 0 | null | 1,613,141,619,000 | 1,612,925,555,000 | null | UTF-8 | Lean | false | false | 1,676 | lean | /-
The "sum" type is used to hold either
a value of a type, α, or a value of
another type, β.
Here's the definition
universe u
inductive sum (α β : Type u) : Type u
| inl (a : α) : sum
| inr (b : β) : sum
In Haskell this type builder is called Either.
-/
/-
Example #1
A value of a sum type can be used
as a more powerful option type, one
where either a correct value or an
argument-specific error is returned.
-/
-- return either correct answer or error string
def pId (n : ℕ) : sum bool string :=
if (n%2 = 0)
then sum.inl tt
else sum.inr ("pb2n is undefined for n = " ++ repr n)
#eval pId 0
#eval pId 1
#eval pId 2
#eval pId 3
#eval pId 4
#eval pId 5
def pIdIsDef (n : ℕ) : bool :=
let result := (pId n) in
match (result) with
| sum.inl _ := tt
| _ := ff
end
-- predicate, tt if pId defined for n, else ff
#eval pIdIsDef 0
#eval pIdIsDef 1
#eval pIdIsDef 2
#eval pIdIsDef 3
#eval pIdIsDef 4
#eval pIdIsDef 5
/-
Example. Suppose we have a type of healthy food,
fruit, and another type of healthy food, veggy.
-/
inductive fruit
| apple
| orange
| kiwi
inductive veggy
| kale
| brocolli
| turnip
#check fruit
open fruit veggy
/-
How do we combine these types into one
new type? Small portions are especially
healthy, so we don't want a pair of foods.
-/
-- product type
def p1 : prod fruit veggy := prod.mk apple kale
def p2 : fruit × veggy := (apple, kale)
#check p1
#check p2
/-
Rather, we want *either* a fruit or a veggy,
but only one of the two. Voila, the sum type.
-/
-- sum type
def healthy1 : sum fruit veggy := sum.inl apple
def healthy2 : fruit ⊕ veggy := sum.inr kale
#check @sum.inl
#check healthy1
|
76214f39ced57954571f995b5585a97bfe2a5146 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/data/finmap.lean | 32dff22f8305d0f109a5d8138df3dc89f2b5b699 | [
"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 | 19,079 | lean | /-
Copyright (c) 2018 Sean Leather. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sean Leather, Mario Carneiro
-/
import data.list.alist
import data.finset.basic
import data.pfun
/-!
# Finite maps over `multiset`
-/
universes u v w
open list
variables {α : Type u} {β : α → Type v}
/-! ### multisets of sigma types-/
namespace multiset
/-- Multiset of keys of an association multiset. -/
def keys (s : multiset (sigma β)) : multiset α :=
s.map sigma.fst
@[simp] theorem coe_keys {l : list (sigma β)} :
keys (l : multiset (sigma β)) = (l.keys : multiset α) :=
rfl
/-- `nodupkeys s` means that `s` has no duplicate keys. -/
def nodupkeys (s : multiset (sigma β)) : Prop :=
quot.lift_on s list.nodupkeys (λ s t p, propext $ perm_nodupkeys p)
@[simp] theorem coe_nodupkeys {l : list (sigma β)} : @nodupkeys α β l ↔ l.nodupkeys := iff.rfl
end multiset
/-! ### finmap -/
/-- `finmap β` is the type of finite maps over a multiset. It is effectively
a quotient of `alist β` by permutation of the underlying list. -/
structure finmap (β : α → Type v) : Type (max u v) :=
(entries : multiset (sigma β))
(nodupkeys : entries.nodupkeys)
/-- The quotient map from `alist` to `finmap`. -/
def alist.to_finmap (s : alist β) : finmap β := ⟨s.entries, s.nodupkeys⟩
local notation `⟦`:max a `⟧`:0 := alist.to_finmap a
theorem alist.to_finmap_eq {s₁ s₂ : alist β} :
⟦s₁⟧ = ⟦s₂⟧ ↔ s₁.entries ~ s₂.entries :=
by cases s₁; cases s₂; simp [alist.to_finmap]
@[simp] theorem alist.to_finmap_entries (s : alist β) : ⟦s⟧.entries = s.entries := rfl
/-- Given `l : list (sigma β)`, create a term of type `finmap β` by removing
entries with duplicate keys. -/
def list.to_finmap [decidable_eq α] (s : list (sigma β)) : finmap β := s.to_alist.to_finmap
namespace finmap
open alist
/-! ### lifting from alist -/
/-- Lift a permutation-respecting function on `alist` to `finmap`. -/
@[elab_as_eliminator] def lift_on
{γ} (s : finmap β) (f : alist β → γ)
(H : ∀ a b : alist β, a.entries ~ b.entries → f a = f b) : γ :=
begin
refine (quotient.lift_on s.1 (λ l, (⟨_, λ nd, f ⟨l, nd⟩⟩ : roption γ))
(λ l₁ l₂ p, roption.ext' (perm_nodupkeys p) _) : roption γ).get _,
{ exact λ h₁ h₂, H _ _ (by exact p) },
{ have := s.nodupkeys, rcases s.entries with ⟨l⟩, exact id }
end
@[simp] theorem lift_on_to_finmap {γ} (s : alist β) (f : alist β → γ) (H) :
lift_on ⟦s⟧ f H = f s := by cases s; refl
/-- Lift a permutation-respecting function on 2 `alist`s to 2 `finmap`s. -/
@[elab_as_eliminator] def lift_on₂
{γ} (s₁ s₂ : finmap β) (f : alist β → alist β → γ)
(H : ∀ a₁ b₁ a₂ b₂ : alist β, a₁.entries ~ a₂.entries → b₁.entries ~ b₂.entries →
f a₁ b₁ = f a₂ b₂) : γ :=
lift_on s₁
(λ l₁, lift_on s₂ (f l₁) (λ b₁ b₂ p, H _ _ _ _ (perm.refl _) p))
(λ a₁ a₂ p, have H' : f a₁ = f a₂ := funext (λ _, H _ _ _ _ p (perm.refl _)), by simp only [H'])
@[simp] theorem lift_on₂_to_finmap {γ} (s₁ s₂ : alist β) (f : alist β → alist β → γ) (H) :
lift_on₂ ⟦s₁⟧ ⟦s₂⟧ f H = f s₁ s₂ :=
by cases s₁; cases s₂; refl
/-! ### induction -/
@[elab_as_eliminator] theorem induction_on
{C : finmap β → Prop} (s : finmap β) (H : ∀ (a : alist β), C ⟦a⟧) : C s :=
by rcases s with ⟨⟨a⟩, h⟩; exact H ⟨a, h⟩
@[elab_as_eliminator] theorem induction_on₂ {C : finmap β → finmap β → Prop}
(s₁ s₂ : finmap β) (H : ∀ (a₁ a₂ : alist β), C ⟦a₁⟧ ⟦a₂⟧) : C s₁ s₂ :=
induction_on s₁ $ λ l₁, induction_on s₂ $ λ l₂, H l₁ l₂
@[elab_as_eliminator] theorem induction_on₃ {C : finmap β → finmap β → finmap β → Prop}
(s₁ s₂ s₃ : finmap β) (H : ∀ (a₁ a₂ a₃ : alist β), C ⟦a₁⟧ ⟦a₂⟧ ⟦a₃⟧) : C s₁ s₂ s₃ :=
induction_on₂ s₁ s₂ $ λ l₁ l₂, induction_on s₃ $ λ l₃, H l₁ l₂ l₃
/-! ### extensionality -/
@[ext] theorem ext : ∀ {s t : finmap β}, s.entries = t.entries → s = t
| ⟨l₁, h₁⟩ ⟨l₂, h₂⟩ H := by congr'
@[simp] theorem ext_iff {s t : finmap β} : s.entries = t.entries ↔ s = t :=
⟨ext, congr_arg _⟩
/-! ### mem -/
/-- The predicate `a ∈ s` means that `s` has a value associated to the key `a`. -/
instance : has_mem α (finmap β) := ⟨λ a s, a ∈ s.entries.keys⟩
theorem mem_def {a : α} {s : finmap β} :
a ∈ s ↔ a ∈ s.entries.keys := iff.rfl
@[simp] theorem mem_to_finmap {a : α} {s : alist β} :
a ∈ ⟦s⟧ ↔ a ∈ s := iff.rfl
/-! ### keys -/
/-- The set of keys of a finite map. -/
def keys (s : finmap β) : finset α :=
⟨s.entries.keys, induction_on s keys_nodup⟩
@[simp] theorem keys_val (s : alist β) : (keys ⟦s⟧).val = s.keys := rfl
@[simp] theorem keys_ext {s₁ s₂ : alist β} :
keys ⟦s₁⟧ = keys ⟦s₂⟧ ↔ s₁.keys ~ s₂.keys :=
by simp [keys, alist.keys]
theorem mem_keys {a : α} {s : finmap β} : a ∈ s.keys ↔ a ∈ s :=
induction_on s $ λ s, alist.mem_keys
/-! ### empty -/
/-- The empty map. -/
instance : has_emptyc (finmap β) := ⟨⟨0, nodupkeys_nil⟩⟩
instance : inhabited (finmap β) := ⟨∅⟩
@[simp] theorem empty_to_finmap : (⟦∅⟧ : finmap β) = ∅ := rfl
@[simp] theorem to_finmap_nil [decidable_eq α] : ([].to_finmap : finmap β) = ∅ := rfl
theorem not_mem_empty {a : α} : a ∉ (∅ : finmap β) :=
multiset.not_mem_zero a
@[simp] theorem keys_empty : (∅ : finmap β).keys = ∅ := rfl
/-! ### singleton -/
/-- The singleton map. -/
def singleton (a : α) (b : β a) : finmap β := ⟦alist.singleton a b⟧
@[simp] theorem keys_singleton (a : α) (b : β a) :
(singleton a b).keys = {a} := rfl
@[simp] lemma mem_singleton (x y : α) (b : β y) : x ∈ singleton y b ↔ x = y :=
by simp only [singleton]; erw [mem_cons_eq, mem_nil_iff, or_false]
section
variables [decidable_eq α]
instance has_decidable_eq [∀ a, decidable_eq (β a)] : decidable_eq (finmap β)
| s₁ s₂ := decidable_of_iff _ ext_iff
/-! ### lookup -/
/-- Look up the value associated to a key in a map. -/
def lookup (a : α) (s : finmap β) : option (β a) :=
lift_on s (lookup a) (λ s t, perm_lookup)
@[simp] theorem lookup_to_finmap (a : α) (s : alist β) :
lookup a ⟦s⟧ = s.lookup a := rfl
@[simp] theorem lookup_list_to_finmap (a : α) (s : list (sigma β)) :
lookup a s.to_finmap = s.lookup a :=
by rw [list.to_finmap, lookup_to_finmap, lookup_to_alist]
@[simp] theorem lookup_empty (a) : lookup a (∅ : finmap β) = none :=
rfl
theorem lookup_is_some {a : α} {s : finmap β} :
(s.lookup a).is_some ↔ a ∈ s :=
induction_on s $ λ s, alist.lookup_is_some
theorem lookup_eq_none {a} {s : finmap β} : lookup a s = none ↔ a ∉ s :=
induction_on s $ λ s, alist.lookup_eq_none
@[simp] lemma lookup_singleton_eq {a : α} {b : β a} : (singleton a b).lookup a = some b :=
by rw [singleton, lookup_to_finmap, alist.singleton, alist.lookup, lookup_cons_eq]
instance (a : α) (s : finmap β) : decidable (a ∈ s) :=
decidable_of_iff _ lookup_is_some
lemma mem_iff {a : α} {s : finmap β} : a ∈ s ↔ ∃ b, s.lookup a = some b :=
induction_on s $ λ s,
iff.trans list.mem_keys $ exists_congr $ λ b,
(mem_lookup_iff s.nodupkeys).symm
lemma mem_of_lookup_eq_some {a : α} {b : β a} {s : finmap β} (h : s.lookup a = some b) : a ∈ s :=
mem_iff.mpr ⟨_, h⟩
theorem ext_lookup {s₁ s₂ : finmap β} : (∀ x, s₁.lookup x = s₂.lookup x) → s₁ = s₂ :=
induction_on₂ s₁ s₂ $ λ s₁ s₂ h,
begin
simp only [alist.lookup, lookup_to_finmap] at h,
rw [alist.to_finmap_eq],
apply lookup_ext s₁.nodupkeys s₂.nodupkeys,
intros x y,
rw h,
end
/-! ### replace -/
/-- Replace a key with a given value in a finite map.
If the key is not present it does nothing. -/
def replace (a : α) (b : β a) (s : finmap β) : finmap β :=
lift_on s (λ t, ⟦replace a b t⟧) $
λ s₁ s₂ p, to_finmap_eq.2 $ perm_replace p
@[simp] theorem replace_to_finmap (a : α) (b : β a) (s : alist β) :
replace a b ⟦s⟧ = ⟦s.replace a b⟧ := by simp [replace]
@[simp] theorem keys_replace (a : α) (b : β a) (s : finmap β) :
(replace a b s).keys = s.keys :=
induction_on s $ λ s, by simp
@[simp] theorem mem_replace {a a' : α} {b : β a} {s : finmap β} :
a' ∈ replace a b s ↔ a' ∈ s :=
induction_on s $ λ s, by simp
end
/-! ### foldl -/
/-- Fold a commutative function over the key-value pairs in the map -/
def foldl {δ : Type w} (f : δ → Π a, β a → δ)
(H : ∀ d a₁ b₁ a₂ b₂, f (f d a₁ b₁) a₂ b₂ = f (f d a₂ b₂) a₁ b₁)
(d : δ) (m : finmap β) : δ :=
m.entries.foldl (λ d s, f d s.1 s.2) (λ d s t, H _ _ _ _ _) d
/-- `any f s` returns `tt` iff there exists a value `v` in `s` such that `f v = tt`. -/
def any (f : Π x, β x → bool) (s : finmap β) : bool :=
s.foldl (λ x y z, x ∨ f y z) (by simp [or_assoc]; intros; congr' 2; rw or_comm) ff
/-- `all f s` returns `tt` iff `f v = tt` for all values `v` in `s`. -/
def all (f : Π x, β x → bool) (s : finmap β) : bool :=
s.foldl (λ x y z, x ∧ f y z) (by simp [and_assoc]; intros; congr' 2; rw and_comm) ff
/-! ### erase -/
section
variables [decidable_eq α]
/-- Erase a key from the map. If the key is not present it does nothing. -/
def erase (a : α) (s : finmap β) : finmap β :=
lift_on s (λ t, ⟦erase a t⟧) $
λ s₁ s₂ p, to_finmap_eq.2 $ perm_erase p
@[simp] theorem erase_to_finmap (a : α) (s : alist β) :
erase a ⟦s⟧ = ⟦s.erase a⟧ := by simp [erase]
@[simp] theorem keys_erase_to_finset (a : α) (s : alist β) :
keys ⟦s.erase a⟧ = (keys ⟦s⟧).erase a :=
by simp [finset.erase, keys, alist.erase, keys_kerase]
@[simp] theorem keys_erase (a : α) (s : finmap β) :
(erase a s).keys = s.keys.erase a :=
induction_on s $ λ s, by simp
@[simp] theorem mem_erase {a a' : α} {s : finmap β} : a' ∈ erase a s ↔ a' ≠ a ∧ a' ∈ s :=
induction_on s $ λ s, by simp
theorem not_mem_erase_self {a : α} {s : finmap β} : ¬ a ∈ erase a s :=
by rw [mem_erase, not_and_distrib, not_not]; left; refl
@[simp] theorem lookup_erase (a) (s : finmap β) : lookup a (erase a s) = none :=
induction_on s $ lookup_erase a
@[simp] theorem lookup_erase_ne {a a'} {s : finmap β} (h : a ≠ a') :
lookup a (erase a' s) = lookup a s :=
induction_on s $ λ s, lookup_erase_ne h
theorem erase_erase {a a' : α} {s : finmap β} : erase a (erase a' s) = erase a' (erase a s) :=
induction_on s $ λ s, ext (by simp only [erase_erase, erase_to_finmap])
/-! ### sdiff -/
/-- `sdiff s s'` consists of all key-value pairs from `s` and `s'` where the keys are in `s` or
`s'` but not both. -/
def sdiff (s s' : finmap β) : finmap β :=
s'.foldl (λ s x _, s.erase x) (λ a₀ a₁ _ a₂ _, erase_erase) s
instance : has_sdiff (finmap β) := ⟨sdiff⟩
/-! ### insert -/
/-- Insert a key-value pair into a finite map, replacing any existing pair with
the same key. -/
def insert (a : α) (b : β a) (s : finmap β) : finmap β :=
lift_on s (λ t, ⟦insert a b t⟧) $
λ s₁ s₂ p, to_finmap_eq.2 $ perm_insert p
@[simp] theorem insert_to_finmap (a : α) (b : β a) (s : alist β) :
insert a b ⟦s⟧ = ⟦s.insert a b⟧ := by simp [insert]
theorem insert_entries_of_neg {a : α} {b : β a} {s : finmap β} : a ∉ s →
(insert a b s).entries = ⟨a, b⟩ :: s.entries :=
induction_on s $ λ s h,
by simp [insert_entries_of_neg (mt mem_to_finmap.1 h)]
@[simp] theorem mem_insert {a a' : α} {b' : β a'} {s : finmap β} :
a ∈ insert a' b' s ↔ a = a' ∨ a ∈ s :=
induction_on s mem_insert
@[simp] theorem lookup_insert {a} {b : β a} (s : finmap β) :
lookup a (insert a b s) = some b :=
induction_on s $ λ s,
by simp only [insert_to_finmap, lookup_to_finmap, lookup_insert]
@[simp] theorem lookup_insert_of_ne {a a'} {b : β a} (s : finmap β) (h : a' ≠ a) :
lookup a' (insert a b s) = lookup a' s :=
induction_on s $ λ s,
by simp only [insert_to_finmap, lookup_to_finmap, lookup_insert_ne h]
@[simp] theorem insert_insert {a} {b b' : β a} (s : finmap β) :
(s.insert a b).insert a b' = s.insert a b' :=
induction_on s $ λ s,
by simp only [insert_to_finmap, insert_insert]
theorem insert_insert_of_ne {a a'} {b : β a} {b' : β a'} (s : finmap β) (h : a ≠ a') :
(s.insert a b).insert a' b' = (s.insert a' b').insert a b :=
induction_on s $ λ s,
by simp only [insert_to_finmap, alist.to_finmap_eq, insert_insert_of_ne _ h]
theorem to_finmap_cons (a : α) (b : β a) (xs : list (sigma β)) :
list.to_finmap (⟨a,b⟩ :: xs) = insert a b xs.to_finmap := rfl
theorem mem_list_to_finmap (a : α) (xs : list (sigma β)) :
a ∈ xs.to_finmap ↔ (∃ b : β a, sigma.mk a b ∈ xs) :=
by { induction xs with x xs; [skip, cases x];
simp only [to_finmap_cons, *, not_mem_empty, exists_or_distrib, not_mem_nil, to_finmap_nil,
exists_false, mem_cons_iff, mem_insert, exists_and_distrib_left];
apply or_congr _ iff.rfl,
conv { to_lhs, rw ← and_true (a = x_fst) },
apply and_congr_right, rintro ⟨⟩, simp only [exists_eq, iff_self, heq_iff_eq] }
@[simp] theorem insert_singleton_eq {a : α} {b b' : β a} :
insert a b (singleton a b') = singleton a b :=
by simp only [singleton, finmap.insert_to_finmap, alist.insert_singleton_eq]
/-! ### extract -/
/-- Erase a key from the map, and return the corresponding value, if found. -/
def extract (a : α) (s : finmap β) : option (β a) × finmap β :=
lift_on s (λ t, prod.map id to_finmap (extract a t)) $
λ s₁ s₂ p, by simp [perm_lookup p, to_finmap_eq, perm_erase p]
@[simp] theorem extract_eq_lookup_erase (a : α) (s : finmap β) :
extract a s = (lookup a s, erase a s) :=
induction_on s $ λ s, by simp [extract]
/-! ### union -/
/-- `s₁ ∪ s₂` is the key-based union of two finite maps. It is left-biased: if
there exists an `a ∈ s₁`, `lookup a (s₁ ∪ s₂) = lookup a s₁`. -/
def union (s₁ s₂ : finmap β) : finmap β :=
lift_on₂ s₁ s₂ (λ s₁ s₂, ⟦s₁ ∪ s₂⟧) $
λ s₁ s₂ s₃ s₄ p₁₃ p₂₄, to_finmap_eq.mpr $ perm_union p₁₃ p₂₄
instance : has_union (finmap β) := ⟨union⟩
@[simp] theorem mem_union {a} {s₁ s₂ : finmap β} :
a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ :=
induction_on₂ s₁ s₂ $ λ _ _, mem_union
@[simp] theorem union_to_finmap (s₁ s₂ : alist β) : ⟦s₁⟧ ∪ ⟦s₂⟧ = ⟦s₁ ∪ s₂⟧ :=
by simp [(∪), union]
theorem keys_union {s₁ s₂ : finmap β} : (s₁ ∪ s₂).keys = s₁.keys ∪ s₂.keys :=
induction_on₂ s₁ s₂ $ λ s₁ s₂, finset.ext $ by simp [keys]
@[simp] theorem lookup_union_left {a} {s₁ s₂ : finmap β} :
a ∈ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₁ :=
induction_on₂ s₁ s₂ $ λ s₁ s₂, lookup_union_left
@[simp] theorem lookup_union_right {a} {s₁ s₂ : finmap β} :
a ∉ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₂ :=
induction_on₂ s₁ s₂ $ λ s₁ s₂, lookup_union_right
theorem lookup_union_left_of_not_in {a} {s₁ s₂ : finmap β} (h : a ∉ s₂) :
lookup a (s₁ ∪ s₂) = lookup a s₁ :=
begin
by_cases h' : a ∈ s₁,
{ rw lookup_union_left h' },
{ rw [lookup_union_right h', lookup_eq_none.mpr h, lookup_eq_none.mpr h'] }
end
@[simp] theorem mem_lookup_union {a} {b : β a} {s₁ s₂ : finmap β} :
b ∈ lookup a (s₁ ∪ s₂) ↔ b ∈ lookup a s₁ ∨ a ∉ s₁ ∧ b ∈ lookup a s₂ :=
induction_on₂ s₁ s₂ $ λ s₁ s₂, mem_lookup_union
theorem mem_lookup_union_middle {a} {b : β a} {s₁ s₂ s₃ : finmap β} :
b ∈ lookup a (s₁ ∪ s₃) → a ∉ s₂ → b ∈ lookup a (s₁ ∪ s₂ ∪ s₃) :=
induction_on₃ s₁ s₂ s₃ $ λ s₁ s₂ s₃, mem_lookup_union_middle
theorem insert_union {a} {b : β a} {s₁ s₂ : finmap β} :
insert a b (s₁ ∪ s₂) = insert a b s₁ ∪ s₂ :=
induction_on₂ s₁ s₂ $ λ a₁ a₂, by simp [insert_union]
theorem union_assoc {s₁ s₂ s₃ : finmap β} : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) :=
induction_on₃ s₁ s₂ s₃ $ λ s₁ s₂ s₃,
by simp only [alist.to_finmap_eq, union_to_finmap, alist.union_assoc]
@[simp] theorem empty_union {s₁ : finmap β} : ∅ ∪ s₁ = s₁ :=
induction_on s₁ $ λ s₁, by rw ← empty_to_finmap;
simp [- empty_to_finmap, alist.to_finmap_eq, union_to_finmap, alist.union_assoc]
@[simp] theorem union_empty {s₁ : finmap β} : s₁ ∪ ∅ = s₁ :=
induction_on s₁ $ λ s₁, by rw ← empty_to_finmap;
simp [- empty_to_finmap, alist.to_finmap_eq, union_to_finmap, alist.union_assoc]
theorem erase_union_singleton (a : α) (b : β a) (s : finmap β) (h : s.lookup a = some b) :
s.erase a ∪ singleton a b = s :=
ext_lookup
(λ x, by { by_cases h' : x = a,
{ subst a, rw [lookup_union_right not_mem_erase_self, lookup_singleton_eq, h], },
{ have : x ∉ singleton a b, { rwa mem_singleton },
rw [lookup_union_left_of_not_in this, lookup_erase_ne h'] } } )
end
/-! ### disjoint -/
/-- `disjoint s₁ s₂` holds if `s₁` and `s₂` have no keys in common. -/
def disjoint (s₁ s₂ : finmap β) : Prop :=
∀ x ∈ s₁, ¬ x ∈ s₂
lemma disjoint_empty (x : finmap β) : disjoint ∅ x .
@[symm]
lemma disjoint.symm (x y : finmap β) (h : disjoint x y) : disjoint y x :=
λ p hy hx, h p hx hy
lemma disjoint.symm_iff (x y : finmap β) : disjoint x y ↔ disjoint y x :=
⟨disjoint.symm x y, disjoint.symm y x⟩
section
variables [decidable_eq α]
instance : decidable_rel (@disjoint α β) :=
λ x y, by dsimp only [disjoint]; apply_instance
lemma disjoint_union_left (x y z : finmap β) : disjoint (x ∪ y) z ↔ disjoint x z ∧ disjoint y z :=
by simp [disjoint, finmap.mem_union, or_imp_distrib, forall_and_distrib]
lemma disjoint_union_right (x y z : finmap β) : disjoint x (y ∪ z) ↔ disjoint x y ∧ disjoint x z :=
by rw [disjoint.symm_iff, disjoint_union_left, disjoint.symm_iff _ x, disjoint.symm_iff _ x]
theorem union_comm_of_disjoint {s₁ s₂ : finmap β} : disjoint s₁ s₂ → s₁ ∪ s₂ = s₂ ∪ s₁ :=
induction_on₂ s₁ s₂ $ λ s₁ s₂,
by { intros h, simp only [alist.to_finmap_eq, union_to_finmap, alist.union_comm_of_disjoint h] }
theorem union_cancel {s₁ s₂ s₃ : finmap β} (h : disjoint s₁ s₃) (h' : disjoint s₂ s₃) :
s₁ ∪ s₃ = s₂ ∪ s₃ ↔ s₁ = s₂ :=
⟨λ h'', begin
apply ext_lookup, intro x,
have : (s₁ ∪ s₃).lookup x = (s₂ ∪ s₃).lookup x, from h'' ▸ rfl,
by_cases hs₁ : x ∈ s₁,
{ rwa [lookup_union_left hs₁, lookup_union_left_of_not_in (h _ hs₁)] at this, },
{ by_cases hs₂ : x ∈ s₂,
{ rwa [lookup_union_left_of_not_in (h' _ hs₂), lookup_union_left hs₂] at this, },
{ rw [lookup_eq_none.mpr hs₁, lookup_eq_none.mpr hs₂] } }
end,
λ h, h ▸ rfl⟩
end
end finmap
|
2ada8bf5f655e48970262f04eec340c958de6756 | 453dcd7c0d1ef170b0843a81d7d8caedc9741dce | /data/list/perm.lean | 8dc5ffc24e9cf15967c977eab0ed80271ac8c2b3 | [
"Apache-2.0"
] | permissive | amswerdlow/mathlib | 9af77a1f08486d8fa059448ae2d97795bd12ec0c | 27f96e30b9c9bf518341705c99d641c38638dfd0 | refs/heads/master | 1,585,200,953,598 | 1,534,275,532,000 | 1,534,275,532,000 | 144,564,700 | 0 | 0 | null | 1,534,156,197,000 | 1,534,156,197,000 | null | UTF-8 | Lean | false | false | 37,872 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro
List permutations.
-/
import data.list.basic
namespace list
universe variables uu vv
variables {α : Type uu} {β : Type vv}
/-- `perm l₁ l₂` or `l₁ ~ l₂` asserts that `l₁` and `l₂` are permutations
of each other. This is defined by induction using pairwise swaps. -/
inductive perm : list α → list α → Prop
| nil : perm [] []
| skip : Π (x : α) {l₁ l₂ : list α}, perm l₁ l₂ → perm (x::l₁) (x::l₂)
| swap : Π (x y : α) (l : list α), perm (y::x::l) (x::y::l)
| trans : Π {l₁ l₂ l₃ : list α}, perm l₁ l₂ → perm l₂ l₃ → perm l₁ l₃
open perm
infix ~ := perm
@[refl] protected theorem perm.refl : ∀ (l : list α), l ~ l
| [] := perm.nil
| (x::xs) := skip x (perm.refl xs)
@[symm] protected theorem perm.symm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₂ ~ l₁ :=
perm.rec_on p
perm.nil
(λ x l₁ l₂ p₁ r₁, skip x r₁)
(λ x y l, swap y x l)
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₂ r₁)
attribute [trans] perm.trans
theorem perm.eqv (α : Type) : equivalence (@perm α) :=
mk_equivalence (@perm α) (@perm.refl α) (@perm.symm α) (@perm.trans α)
instance is_setoid (α : Type) : setoid (list α) :=
setoid.mk (@perm α) (perm.eqv α)
theorem perm_subset {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁ ⊆ l₂ :=
λ a, perm.rec_on p
(λ h, h)
(λ x l₁ l₂ p₁ r₁ i, or.elim i
(λ ax, by simp [ax])
(λ al₁, or.inr (r₁ al₁)))
(λ x y l ayxl, or.elim ayxl
(λ ay, by simp [ay])
(λ axl, or.elim axl
(λ ax, by simp [ax])
(λ al, or.inr (or.inr al))))
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ ainl₁, r₂ (r₁ ainl₁))
theorem mem_of_perm {a : α} {l₁ l₂ : list α} (h : l₁ ~ l₂) : a ∈ l₁ ↔ a ∈ l₂ :=
iff.intro (λ m, perm_subset h m) (λ m, perm_subset h.symm m)
theorem perm_app_left {l₁ l₂ : list α} (t₁ : list α) (p : l₁ ~ l₂) : l₁++t₁ ~ l₂++t₁ :=
perm.rec_on p
(perm.refl ([] ++ t₁))
(λ x l₁ l₂ p₁ r₁, skip x r₁)
(λ x y l, swap x y _)
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂)
theorem perm_app_right {t₁ t₂ : list α} : ∀ (l : list α), t₁ ~ t₂ → l++t₁ ~ l++t₂
| [] p := p
| (x::xs) p := skip x (perm_app_right xs p)
theorem perm_app {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁++t₁ ~ l₂++t₂ :=
trans (perm_app_left t₁ p₁) (perm_app_right l₂ p₂)
theorem perm_app_cons (a : α) {h₁ h₂ t₁ t₂ : list α}
(p₁ : h₁ ~ h₂) (p₂ : t₁ ~ t₂) : h₁ ++ a::t₁ ~ h₂ ++ a::t₂ :=
perm_app p₁ (skip a p₂)
@[simp] theorem perm_middle {a : α} : ∀ {l₁ l₂ : list α}, l₁++a::l₂ ~ a::(l₁++l₂)
| [] l₂ := perm.refl _
| (b::l₁) l₂ := (skip b (@perm_middle l₁ l₂)).trans (swap a b _)
@[simp] theorem perm_cons_app (a : α) (l : list α) : l ++ [a] ~ a::l :=
by simpa using @perm_middle _ a l []
@[simp] theorem perm_app_comm : ∀ {l₁ l₂ : list α}, (l₁++l₂) ~ (l₂++l₁)
| [] l₂ := by simp
| (a::t) l₂ := (skip a perm_app_comm).trans perm_middle.symm
theorem concat_perm (l : list α) (a : α) : concat l a ~ a :: l :=
by simp
theorem perm_length {l₁ l₂ : list α} (p : l₁ ~ l₂) : length l₁ = length l₂ :=
perm.rec_on p
rfl
(λ x l₁ l₂ p r, by simp[r])
(λ x y l, by simp)
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, eq.trans r₁ r₂)
theorem eq_nil_of_perm_nil {l₁ : list α} (p : [] ~ l₁) : l₁ = [] :=
eq_nil_of_length_eq_zero (perm_length p).symm
theorem perm_nil {l₁ : list α} : l₁ ~ [] ↔ l₁ = [] :=
⟨λ p, eq_nil_of_perm_nil p.symm, λ e, e ▸ perm.refl _⟩
theorem not_perm_nil_cons (x : α) (l : list α) : ¬ [] ~ x::l
| p := by injection eq_nil_of_perm_nil p
theorem eq_singleton_of_perm {a b : α} (p : [a] ~ [b]) : a = b :=
by simpa using perm_subset p (by simp)
theorem eq_singleton_of_perm_inv {a : α} {l : list α} (p : [a] ~ l) : l = [a] :=
match l, show 1 = _, from perm_length p, p with
| [a'], rfl, p := by rw [eq_singleton_of_perm p]
end
@[simp] theorem reverse_perm : ∀ (l : list α), reverse l ~ l
| [] := perm.nil
| (a::l) := by rw reverse_cons; exact
(perm_cons_app _ _).trans (skip a $ reverse_perm l)
theorem perm_cons_app_cons {l l₁ l₂ : list α} (a : α) (p : l ~ l₁++l₂) : a::l ~ l₁++(a::l₂) :=
trans (skip a p) perm_middle.symm
@[simp] theorem perm_repeat {a : α} {n : ℕ} {l : list α} : repeat a n ~ l ↔ repeat a n = l :=
⟨λ p, (eq_repeat.2 $ by exact
⟨by simpa using (perm_length p).symm,
λ b m, eq_of_mem_repeat $ perm_subset p.symm m⟩).symm,
λ h, h ▸ perm.refl _⟩
theorem perm_erase [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : l ~ a :: l.erase a :=
let ⟨l₁, l₂, _, e₁, e₂⟩ := exists_erase_eq h in
e₂.symm ▸ e₁.symm ▸ perm_middle
@[elab_as_eliminator] theorem perm_induction_on
{P : list α → list α → Prop} {l₁ l₂ : list α} (p : l₁ ~ l₂)
(h₁ : P [] [])
(h₂ : ∀ x l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (x::l₁) (x::l₂))
(h₃ : ∀ x y l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (y::x::l₁) (x::y::l₂))
(h₄ : ∀ l₁ l₂ l₃, l₁ ~ l₂ → l₂ ~ l₃ → P l₁ l₂ → P l₂ l₃ → P l₁ l₃) :
P l₁ l₂ :=
have P_refl : ∀ l, P l l, from
assume l,
list.rec_on l h₁ (λ x xs ih, h₂ x xs xs (perm.refl xs) ih),
perm.rec_on p h₁ h₂ (λ x y l, h₃ x y l l (perm.refl l) (P_refl l)) h₄
@[congr] theorem perm_filter_map (f : α → option β) {l₁ l₂ : list α} (p : l₁ ~ l₂) :
filter_map f l₁ ~ filter_map f l₂ :=
begin
induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂,
{ simp },
{ simp [filter_map], cases f x with a; simp [filter_map, IH, skip] },
{ simp [filter_map], cases f x with a; cases f y with b; simp [filter_map, swap] },
{ exact IH₁.trans IH₂ }
end
@[congr] theorem perm_map (f : α → β) {l₁ l₂ : list α} (p : l₁ ~ l₂) :
map f l₁ ~ map f l₂ :=
by rw ← filter_map_eq_map; apply perm_filter_map _ p
theorem perm_pmap {p : α → Prop} (f : Π a, p a → β)
{l₁ l₂ : list α} (p : l₁ ~ l₂) {H₁ H₂} : pmap f l₁ H₁ ~ pmap f l₂ H₂ :=
begin
induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂,
{ simp },
{ simp [IH, skip] },
{ simp [swap] },
{ refine IH₁.trans IH₂,
exact λ a m, H₂ a (perm_subset p₂ m) }
end
theorem perm_filter (p : α → Prop) [decidable_pred p]
{l₁ l₂ : list α} (s : l₁ ~ l₂) : filter p l₁ ~ filter p l₂ :=
by rw ← filter_map_eq_filter; apply perm_filter_map _ s
theorem exists_perm_sublist {l₁ l₂ l₂' : list α}
(s : l₁ <+ l₂) (p : l₂ ~ l₂') : ∃ l₁' ~ l₁, l₁' <+ l₂' :=
begin
induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂ generalizing l₁ s,
{ exact ⟨[], eq_nil_of_sublist_nil s ▸ perm.refl _, nil_sublist _⟩ },
{ cases s with _ _ _ s l₁ _ _ s,
{ exact let ⟨l₁', p', s'⟩ := IH s in ⟨l₁', p', s'.cons _ _ _⟩ },
{ exact let ⟨l₁', p', s'⟩ := IH s in ⟨x::l₁', skip x p', s'.cons2 _ _ _⟩ } },
{ cases s with _ _ _ s l₁ _ _ s; cases s with _ _ _ s l₁ _ _ s,
{ exact ⟨l₁, perm.refl _, (s.cons _ _ _).cons _ _ _⟩ },
{ exact ⟨x::l₁, perm.refl _, (s.cons _ _ _).cons2 _ _ _⟩ },
{ exact ⟨y::l₁, perm.refl _, (s.cons2 _ _ _).cons _ _ _⟩ },
{ exact ⟨x::y::l₁, perm.swap _ _ _, (s.cons2 _ _ _).cons2 _ _ _⟩ } },
{ exact let ⟨m₁, pm, sm⟩ := IH₁ s, ⟨r₁, pr, sr⟩ := IH₂ sm in
⟨r₁, pr.trans pm, sr⟩ }
end
section rel
open relator
variables {γ : Type*} {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop}
local infixr ` ∘r ` : 80 := relation.comp
lemma perm_comp_perm : (perm ∘r perm : list α → list α → Prop) = perm :=
begin
funext a c, apply propext,
split,
{ exact assume ⟨b, hab, hba⟩, perm.trans hab hba },
{ exact assume h, ⟨a, perm.refl a, h⟩ }
end
lemma perm_comp_forall₂ {l u v} (hlu : perm l u) (huv : forall₂ r u v) : (forall₂ r ∘r perm) l v :=
begin
induction hlu generalizing v,
case perm.nil { cases huv, exact ⟨[], forall₂.nil, perm.nil⟩ },
case perm.skip : a l u hlu ih {
cases huv with _ b _ v hab huv',
rcases ih huv' with ⟨l₂, h₁₂, h₂₃⟩,
exact ⟨b::l₂, forall₂.cons hab h₁₂, perm.skip _ h₂₃⟩
},
case perm.swap : a₁ a₂ l₁ l₂ h₂₃ {
cases h₂₃ with _ b₁ _ l₂ h₁ hr_₂₃,
cases hr_₂₃ with _ b₂ _ l₂ h₂ h₁₂,
exact ⟨b₂::b₁::l₂, forall₂.cons h₂ (forall₂.cons h₁ h₁₂), perm.swap _ _ _⟩
},
case perm.trans : la₁ la₂ la₃ _ _ ih₁ ih₂ {
rcases ih₂ huv with ⟨lb₂, hab₂, h₂₃⟩,
rcases ih₁ hab₂ with ⟨lb₁, hab₁, h₁₂⟩,
exact ⟨lb₁, hab₁, perm.trans h₁₂ h₂₃⟩
}
end
lemma forall₂_comp_perm_eq_perm_comp_forall₂ : forall₂ r ∘r perm = perm ∘r forall₂ r :=
begin
funext l₁ l₃, apply propext,
split,
{ assume h, rcases h with ⟨l₂, h₁₂, h₂₃⟩,
have : forall₂ (flip r) l₂ l₁, from forall₂_flip h₁₂,
rcases perm_comp_forall₂ h₂₃.symm this with ⟨l', h₁, h₂⟩,
exact ⟨l', h₂.symm, forall₂_flip h₁⟩ },
{ exact assume ⟨l₂, h₁₂, h₂₃⟩, perm_comp_forall₂ h₁₂ h₂₃ }
end
lemma rel_perm_imp (hr : right_unique r) : (forall₂ r ⇒ forall₂ r ⇒ implies) perm perm :=
assume a b h₁ c d h₂ h,
have (flip (forall₂ r) ∘r (perm ∘r forall₂ r)) b d, from ⟨a, h₁, c, h, h₂⟩,
have ((flip (forall₂ r) ∘r forall₂ r) ∘r perm) b d,
by rwa [← forall₂_comp_perm_eq_perm_comp_forall₂, ← relation.comp_assoc] at this,
let ⟨b', ⟨c', hbc, hcb⟩, hbd⟩ := this in
have b' = b, from right_unique_forall₂ @hr hcb hbc,
this ▸ hbd
lemma rel_perm (hr : bi_unique r) : (forall₂ r ⇒ forall₂ r ⇒ (↔)) perm perm :=
assume a b hab c d hcd, iff.intro
(rel_perm_imp hr.2 hab hcd)
(rel_perm_imp (assume a b c, left_unique_flip hr.1) (forall₂_flip hab) (forall₂_flip hcd))
end rel
section subperm
/-- `subperm l₁ l₂`, denoted `l₁ <+~ l₂`, means that `l₁` is a sublist of
a permutation of `l₂`. This is an analogue of `l₁ ⊆ l₂` which respects
multiplicities of elements, and is used for the `≤` relation on multisets. -/
def subperm (l₁ l₂ : list α) : Prop := ∃ l ~ l₁, l <+ l₂
infix ` <+~ `:50 := subperm
theorem perm.subperm_left {l l₁ l₂ : list α} (p : l₁ ~ l₂) : l <+~ l₁ ↔ l <+~ l₂ :=
suffices ∀ {l₁ l₂ : list α}, l₁ ~ l₂ → l <+~ l₁ → l <+~ l₂,
from ⟨this p, this p.symm⟩,
λ l₁ l₂ p ⟨u, pu, su⟩,
let ⟨v, pv, sv⟩ := exists_perm_sublist su p in
⟨v, pv.trans pu, sv⟩
theorem perm.subperm_right {l₁ l₂ l : list α} (p : l₁ ~ l₂) : l₁ <+~ l ↔ l₂ <+~ l :=
⟨λ ⟨u, pu, su⟩, ⟨u, pu.trans p, su⟩,
λ ⟨u, pu, su⟩, ⟨u, pu.trans p.symm, su⟩⟩
theorem subperm_of_sublist {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁ <+~ l₂ :=
⟨l₁, perm.refl _, s⟩
theorem subperm_of_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁ <+~ l₂ :=
⟨l₂, p.symm, sublist.refl _⟩
theorem subperm.refl (l : list α) : l <+~ l := subperm_of_perm (perm.refl _)
theorem subperm.trans {l₁ l₂ l₃ : list α} : l₁ <+~ l₂ → l₂ <+~ l₃ → l₁ <+~ l₃
| s ⟨l₂', p₂, s₂⟩ :=
let ⟨l₁', p₁, s₁⟩ := p₂.subperm_left.2 s in ⟨l₁', p₁, s₁.trans s₂⟩
theorem length_le_of_subperm {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₁ ≤ length l₂
| ⟨l, p, s⟩ := perm_length p ▸ length_le_of_sublist s
theorem subperm.perm_of_length_le {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₂ ≤ length l₁ → l₁ ~ l₂
| ⟨l, p, s⟩ h :=
suffices l = l₂, from this ▸ p.symm,
eq_of_sublist_of_length_le s $ perm_length p.symm ▸ h
theorem subperm.antisymm {l₁ l₂ : list α} (h₁ : l₁ <+~ l₂) (h₂ : l₂ <+~ l₁) : l₁ ~ l₂ :=
h₁.perm_of_length_le (length_le_of_subperm h₂)
theorem subset_of_subperm {l₁ l₂ : list α} : l₁ <+~ l₂ → l₁ ⊆ l₂
| ⟨l, p, s⟩ := subset.trans (perm_subset p.symm) (subset_of_sublist s)
end subperm
theorem exists_perm_append_of_sublist : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → ∃ l, l₂ ~ l₁ ++ l
| ._ ._ sublist.slnil := ⟨nil, perm.refl _⟩
| ._ ._ (sublist.cons l₁ l₂ a s) :=
let ⟨l, p⟩ := exists_perm_append_of_sublist s in
⟨a::l, (skip a p).trans perm_middle.symm⟩
| ._ ._ (sublist.cons2 l₁ l₂ a s) :=
let ⟨l, p⟩ := exists_perm_append_of_sublist s in
⟨l, skip a p⟩
theorem perm_countp (p : α → Prop) [decidable_pred p]
{l₁ l₂ : list α} (s : l₁ ~ l₂) : countp p l₁ = countp p l₂ :=
by rw [countp_eq_length_filter, countp_eq_length_filter];
exact perm_length (perm_filter _ s)
theorem countp_le_of_subperm (p : α → Prop) [decidable_pred p]
{l₁ l₂ : list α} : l₁ <+~ l₂ → countp p l₁ ≤ countp p l₂
| ⟨l, p', s⟩ := perm_countp p p' ▸ countp_le_of_sublist s
theorem perm_count [decidable_eq α] {l₁ l₂ : list α}
(p : l₁ ~ l₂) (a) : count a l₁ = count a l₂ :=
perm_countp _ p
theorem count_le_of_subperm [decidable_eq α] {l₁ l₂ : list α}
(s : l₁ <+~ l₂) (a) : count a l₁ ≤ count a l₂ :=
countp_le_of_subperm _ s
theorem foldl_eq_of_perm {f : β → α → β} {l₁ l₂ : list α} (rcomm : right_commutative f) (p : l₁ ~ l₂) :
∀ b, foldl f b l₁ = foldl f b l₂ :=
perm_induction_on p
(λ b, rfl)
(λ x t₁ t₂ p r b, r (f b x))
(λ x y t₁ t₂ p r b, by simp; rw rcomm; exact r (f (f b x) y))
(λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ b, eq.trans (r₁ b) (r₂ b))
theorem foldr_eq_of_perm {f : α → β → β} {l₁ l₂ : list α} (lcomm : left_commutative f) (p : l₁ ~ l₂) :
∀ b, foldr f b l₁ = foldr f b l₂ :=
perm_induction_on p
(λ b, rfl)
(λ x t₁ t₂ p r b, by simp; rw [r b])
(λ x y t₁ t₂ p r b, by simp; rw [lcomm, r b])
(λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ a, eq.trans (r₁ a) (r₂ a))
lemma rec_heq_of_perm {β : list α → Sort*} {f : Πa l, β l → β (a::l)} {b : β []} {l l' : list α}
(hl : perm l l')
(f_congr : ∀{a l l' b b'}, perm l l' → b == b' → f a l b == f a l' b')
(f_swap : ∀{a a' l b}, f a (a'::l) (f a' l b) == f a' (a::l) (f a l b)) :
@list.rec α β b f l == @list.rec α β b f l' :=
begin
induction hl,
case list.perm.nil { refl },
case list.perm.skip : a l l' h ih { exact f_congr h ih },
case list.perm.swap : a a' l { exact f_swap },
case list.perm.trans : l₁ l₂ l₃ h₁ h₂ ih₁ ih₂ { exact heq.trans ih₁ ih₂ }
end
section
variables {op : α → α → α} [is_associative α op] [is_commutative α op]
local notation a * b := op a b
local notation l <*> a := foldl op a l
lemma fold_op_eq_of_perm {l₁ l₂ : list α} {a : α} (h : l₁ ~ l₂) : l₁ <*> a = l₂ <*> a :=
foldl_eq_of_perm (right_comm _ (is_commutative.comm _) (is_associative.assoc _)) h _
end
section comm_monoid
open list
variable [comm_monoid α]
@[to_additive list.sum_eq_of_perm]
lemma prod_eq_of_perm {l₁ l₂ : list α} (h : perm l₁ l₂) : prod l₁ = prod l₂ :=
by induction h; simp [*, mul_left_comm]
@[to_additive list.sum_reverse]
lemma prod_reverse (l : list α) : prod l.reverse = prod l :=
prod_eq_of_perm $ reverse_perm l
end comm_monoid
theorem perm_inv_core {a : α} {l₁ l₂ r₁ r₂ : list α} : l₁++a::r₁ ~ l₂++a::r₂ → l₁++r₁ ~ l₂++r₂ :=
begin
generalize e₁ : l₁++a::r₁ = s₁, generalize e₂ : l₂++a::r₂ = s₂,
intro p, revert l₁ l₂ r₁ r₂ e₁ e₂,
refine perm_induction_on p _ (λ x t₁ t₂ p IH, _) (λ x y t₁ t₂ p IH, _) (λ t₁ t₂ t₃ p₁ p₂ IH₁ IH₂, _);
intros l₁ l₂ r₁ r₂ e₁ e₂,
{ apply (not_mem_nil a).elim, rw ← e₁, simp },
{ cases l₁ with y l₁; cases l₂ with z l₂;
dsimp at e₁ e₂; injections; subst x,
{ substs t₁ t₂, exact p },
{ substs z t₁ t₂, exact p.trans perm_middle },
{ substs y t₁ t₂, exact perm_middle.symm.trans p },
{ substs z t₁ t₂, exact skip y (IH rfl rfl) } },
{ rcases l₁ with _|⟨y, _|⟨z, l₁⟩⟩; rcases l₂ with _|⟨u, _|⟨v, l₂⟩⟩;
dsimp at e₁ e₂; injections; substs x y,
{ substs r₁ r₂, exact skip a p },
{ substs r₁ r₂, exact skip u p },
{ substs r₁ v t₂, exact skip u (p.trans perm_middle) },
{ substs r₁ r₂, exact skip y p },
{ substs r₁ r₂ y u, exact skip a p },
{ substs r₁ u v t₂, exact (skip y $ p.trans perm_middle).trans (swap _ _ _) },
{ substs r₂ z t₁, exact skip y (perm_middle.symm.trans p) },
{ substs r₂ y z t₁, exact (swap _ _ _).trans (skip u $ perm_middle.symm.trans p) },
{ substs u v t₁ t₂, exact (swap _ _ _).trans (skip z $ skip y $ IH rfl rfl) } },
{ substs t₁ t₃,
have : a ∈ t₂ := perm_subset p₁ (by simp),
rcases mem_split this with ⟨l₂, r₂, e₂⟩,
subst t₂, exact (IH₁ rfl rfl).trans (IH₂ rfl rfl) }
end
theorem perm_cons_inv {a : α} {l₁ l₂ : list α} : a::l₁ ~ a::l₂ → l₁ ~ l₂ :=
@perm_inv_core _ _ [] [] _ _
theorem perm_cons (a : α) {l₁ l₂ : list α} : a::l₁ ~ a::l₂ ↔ l₁ ~ l₂ :=
⟨perm_cons_inv, skip a⟩
theorem perm_app_left_iff {l₁ l₂ : list α} : ∀ l, l++l₁ ~ l++l₂ ↔ l₁ ~ l₂
| [] := iff.rfl
| (a::l) := (perm_cons a).trans (perm_app_left_iff l)
theorem perm_app_right_iff {l₁ l₂ : list α} (l) : l₁++l ~ l₂++l ↔ l₁ ~ l₂ :=
⟨λ p, (perm_app_left_iff _).1 $ trans perm_app_comm $ trans p perm_app_comm,
perm_app_left _⟩
theorem subperm_cons (a : α) {l₁ l₂ : list α} : a::l₁ <+~ a::l₂ ↔ l₁ <+~ l₂ :=
⟨λ ⟨l, p, s⟩, begin
cases s with _ _ _ s' u _ _ s',
{ exact (p.subperm_left.2 $ subperm_of_sublist $ sublist_cons _ _).trans
(subperm_of_sublist s') },
{ exact ⟨u, perm_cons_inv p, s'⟩ }
end, λ ⟨l, p, s⟩, ⟨a::l, skip a p, s.cons2 _ _ _⟩⟩
theorem cons_subperm_of_mem {a : α} {l₁ l₂ : list α} (d₁ : nodup l₁) (h₁ : a ∉ l₁) (h₂ : a ∈ l₂)
(s : l₁ <+~ l₂) : a :: l₁ <+~ l₂ :=
begin
rcases s with ⟨l, p, s⟩,
induction s generalizing l₁,
case list.sublist.slnil { cases h₂ },
case list.sublist.cons : r₁ r₂ b s' ih {
simp at h₂,
cases h₂ with e m,
{ subst b, exact ⟨a::r₁, skip a p, s'.cons2 _ _ _⟩ },
{ rcases ih m d₁ h₁ p with ⟨t, p', s'⟩, exact ⟨t, p', s'.cons _ _ _⟩ } },
case list.sublist.cons2 : r₁ r₂ b s' ih {
have bm : b ∈ l₁ := (perm_subset p $ mem_cons_self _ _),
have am : a ∈ r₂ := h₂.resolve_left (λ e, h₁ $ e.symm ▸ bm),
rcases mem_split bm with ⟨t₁, t₂, rfl⟩,
have st : t₁ ++ t₂ <+ t₁ ++ b :: t₂ := by simp,
rcases ih am (nodup_of_sublist st d₁)
(mt (λ x, subset_of_sublist st x) h₁)
(perm_cons_inv $ p.trans perm_middle) with ⟨t, p', s'⟩,
exact ⟨b::t, (skip b p').trans $ (swap _ _ _).trans (skip a perm_middle.symm), s'.cons2 _ _ _⟩ }
end
theorem subperm_app_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+~ l++l₂ ↔ l₁ <+~ l₂
| [] := iff.rfl
| (a::l) := (subperm_cons a).trans (subperm_app_left l)
theorem subperm_app_right {l₁ l₂ : list α} (l) : l₁++l <+~ l₂++l ↔ l₁ <+~ l₂ :=
(perm_app_comm.subperm_left.trans perm_app_comm.subperm_right).trans (subperm_app_left l)
theorem subperm.exists_of_length_lt {l₁ l₂ : list α} :
l₁ <+~ l₂ → length l₁ < length l₂ → ∃ a, a :: l₁ <+~ l₂
| ⟨l, p, s⟩ h :=
suffices length l < length l₂ → ∃ (a : α), a :: l <+~ l₂, from
(this $ perm_length p.symm ▸ h).imp (λ a, (skip a p).subperm_right.1),
begin
clear subperm.exists_of_length_lt p h l₁, rename l₂ u,
induction s with l₁ l₂ a s IH _ _ b s IH; intro h,
{ cases h },
{ cases lt_or_eq_of_le (nat.le_of_lt_succ h : length l₁ ≤ length l₂) with h h,
{ exact (IH h).imp (λ a s, s.trans (subperm_of_sublist $ sublist_cons _ _)) },
{ exact ⟨a, eq_of_sublist_of_length_eq s h ▸ subperm.refl _⟩ } },
{ exact (IH $ nat.lt_of_succ_lt_succ h).imp
(λ a s, (swap _ _ _).subperm_right.1 $ (subperm_cons _).2 s) }
end
theorem subperm_of_subset_nodup
{l₁ l₂ : list α} (d : nodup l₁) (H : l₁ ⊆ l₂) : l₁ <+~ l₂ :=
begin
induction d with a l₁' h d IH,
{ exact ⟨nil, perm.nil, nil_sublist _⟩ },
{ cases forall_mem_cons.1 H with H₁ H₂,
simp at h,
exact cons_subperm_of_mem d h H₁ (IH H₂) }
end
theorem perm_ext {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) : l₁ ~ l₂ ↔ ∀a, a ∈ l₁ ↔ a ∈ l₂ :=
⟨λ p a, mem_of_perm p, λ H, subperm.antisymm
(subperm_of_subset_nodup d₁ (λ a, (H a).1))
(subperm_of_subset_nodup d₂ (λ a, (H a).2))⟩
theorem perm_ext_sublist_nodup {l₁ l₂ l : list α} (d : nodup l)
(s₁ : l₁ <+ l) (s₂ : l₂ <+ l) : l₁ ~ l₂ ↔ l₁ = l₂ :=
⟨λ h, begin
induction s₂ with l₂ l a s₂ IH l₂ l a s₂ IH generalizing l₁,
{ exact eq_nil_of_perm_nil h.symm },
{ simp at d,
cases s₁ with _ _ _ s₁ l₁ _ _ s₁,
{ exact IH d.2 s₁ h },
{ apply d.1.elim,
exact subset_of_subperm ⟨_, h.symm, s₂⟩ (mem_cons_self _ _) } },
{ simp at d,
cases s₁ with _ _ _ s₁ l₁ _ _ s₁,
{ apply d.1.elim,
exact subset_of_subperm ⟨_, h, s₁⟩ (mem_cons_self _ _) },
{ rw IH d.2 s₁ (perm_cons_inv h) } }
end, λ h, by rw h⟩
section
variable [decidable_eq α]
-- attribute [congr]
theorem erase_perm_erase (a : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) :
l₁.erase a ~ l₂.erase a :=
if h₁ : a ∈ l₁ then
have h₂ : a ∈ l₂, from perm_subset p h₁,
perm_cons_inv $ trans (perm_erase h₁).symm $ trans p (perm_erase h₂)
else
have h₂ : a ∉ l₂, from mt (mem_of_perm p).2 h₁,
by rw [erase_of_not_mem h₁, erase_of_not_mem h₂]; exact p
theorem perm_diff_left {l₁ l₂ : list α} (t : list α) (h : l₁ ~ l₂) : l₁.diff t ~ l₂.diff t :=
by induction t generalizing l₁ l₂ h; simp [*, erase_perm_erase]
theorem perm_diff_right (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : l.diff t₁ = l.diff t₂ :=
by induction h generalizing l; simp [*, erase_perm_erase, erase_comm]
<|> exact (ih_1 _).trans (ih_2 _)
theorem perm_bag_inter_left {l₁ l₂ : list α} (t : list α) (h : l₁ ~ l₂) : l₁.bag_inter t ~ l₂.bag_inter t :=
begin
induction h with x _ _ _ _ x y _ _ _ _ _ _ ih_1 ih_2 generalizing t, {simp},
{ by_cases x ∈ t; simp [*, skip] },
{ by_cases x = y, {simp [h]},
by_cases xt : x ∈ t; by_cases yt : y ∈ t,
{ simp [xt, yt, mem_erase_of_ne h, mem_erase_of_ne (ne.symm h), erase_comm, swap] },
{ simp [xt, yt, mt mem_of_mem_erase, skip] },
{ simp [xt, yt, mt mem_of_mem_erase, skip] },
{ simp [xt, yt] } },
{ exact (ih_1 _).trans (ih_2 _) }
end
theorem perm_bag_inter_right (l : list α) {t₁ t₂ : list α} (p : t₁ ~ t₂) : l.bag_inter t₁ = l.bag_inter t₂ :=
begin
induction l with a l IH generalizing t₁ t₂ p, {simp},
by_cases a ∈ t₁,
{ simp [h, (mem_of_perm p).1 h, IH (erase_perm_erase _ p)] },
{ simp [h, mt (mem_of_perm p).2 h, IH p] }
end
theorem cons_perm_iff_perm_erase {a : α} {l₁ l₂ : list α} : a::l₁ ~ l₂ ↔ a ∈ l₂ ∧ l₁ ~ l₂.erase a :=
⟨λ h, have a ∈ l₂, from perm_subset h (mem_cons_self a l₁),
⟨this, perm_cons_inv $ h.trans $ perm_erase this⟩,
λ ⟨m, h⟩, trans (skip a h) (perm_erase m).symm⟩
theorem perm_iff_count {l₁ l₂ : list α} : l₁ ~ l₂ ↔ ∀ a, count a l₁ = count a l₂ :=
⟨perm_count, λ H, begin
induction l₁ with a l₁ IH generalizing l₂,
{ cases l₂ with b l₂, {refl},
specialize H b, simp at H, contradiction },
{ have : a ∈ l₂ := count_pos.1 (by rw ← H; simp; apply nat.succ_pos),
refine trans (skip a $ IH $ λ b, _) (perm_erase this).symm,
specialize H b,
rw perm_count (perm_erase this) at H,
by_cases b = a; simp [h] at H ⊢; assumption }
end⟩
instance decidable_perm : ∀ (l₁ l₂ : list α), decidable (l₁ ~ l₂)
| [] [] := is_true $ perm.refl _
| [] (b::l₂) := is_false $ λ h, by have := eq_nil_of_perm_nil h; contradiction
| (a::l₁) l₂ := by haveI := decidable_perm l₁ (l₂.erase a);
exact decidable_of_iff' _ cons_perm_iff_perm_erase
-- @[congr]
theorem perm_erase_dup_of_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) :
erase_dup l₁ ~ erase_dup l₂ :=
perm_iff_count.2 $ λ a,
if h : a ∈ l₁
then by simp [nodup_erase_dup, h, perm_subset p h]
else by simp [h, mt (mem_of_perm p).2 h]
-- attribute [congr]
theorem perm_insert (a : α)
{l₁ l₂ : list α} (p : l₁ ~ l₂) : insert a l₁ ~ insert a l₂ :=
if h : a ∈ l₁
then by simpa [h, perm_subset p h] using p
else by simpa [h, mt (mem_of_perm p).2 h] using skip a p
theorem perm_insert_swap (x y : α) (l : list α) :
insert x (insert y l) ~ insert y (insert x l) :=
begin
by_cases xl : x ∈ l; by_cases yl : y ∈ l; simp [xl, yl],
by_cases xy : x = y, { simp [xy] },
simp [not_mem_cons_of_ne_of_not_mem xy xl,
not_mem_cons_of_ne_of_not_mem (ne.symm xy) yl],
constructor
end
theorem perm_union_left {l₁ l₂ : list α} (t₁ : list α) (h : l₁ ~ l₂) : l₁ ∪ t₁ ~ l₂ ∪ t₁ :=
begin
induction h with a _ _ _ ih _ _ _ _ _ _ _ _ ih_1 ih_2; try {simp},
{ exact perm_insert a ih },
{ apply perm_insert_swap },
{ exact ih_1.trans ih_2 }
end
theorem perm_union_right (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : l ∪ t₁ ~ l ∪ t₂ :=
by induction l; simp [*, perm_insert]
-- @[congr]
theorem perm_union {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∪ t₁ ~ l₂ ∪ t₂ :=
trans (perm_union_left t₁ p₁) (perm_union_right l₂ p₂)
theorem perm_inter_left {l₁ l₂ : list α} (t₁ : list α) : l₁ ~ l₂ → l₁ ∩ t₁ ~ l₂ ∩ t₁ :=
perm_filter _
theorem perm_inter_right (l : list α) {t₁ t₂ : list α} (p : t₁ ~ t₂) : l ∩ t₁ = l ∩ t₂ :=
by dsimp [(∩), list.inter]; congr; funext a; rw [mem_of_perm p]
-- @[congr]
theorem perm_inter {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∩ t₁ ~ l₂ ∩ t₂ :=
perm_inter_right l₂ p₂ ▸ perm_inter_left t₁ p₁
end
theorem perm_pairwise {R : α → α → Prop} (S : symmetric R) :
∀ {l₁ l₂ : list α} (p : l₁ ~ l₂), pairwise R l₁ ↔ pairwise R l₂ :=
suffices ∀ {l₁ l₂}, l₁ ~ l₂ → pairwise R l₁ → pairwise R l₂, from λ l₁ l₂ p, ⟨this p, this p.symm⟩,
λ l₁ l₂ p d, begin
induction d with a l₁ h d IH generalizing l₂,
{ rw eq_nil_of_perm_nil p, constructor },
{ have : a ∈ l₂ := perm_subset p (mem_cons_self _ _),
rcases mem_split this with ⟨s₂, t₂, rfl⟩,
have p' := perm_cons_inv (p.trans perm_middle),
refine (pairwise_middle S).2 (pairwise_cons.2 ⟨λ b m, _, IH _ p'⟩),
exact h _ (perm_subset p'.symm m) }
end
theorem perm_nodup {l₁ l₂ : list α} : l₁ ~ l₂ → (nodup l₁ ↔ nodup l₂) :=
perm_pairwise $ @ne.symm α
theorem perm_bind_left {l₁ l₂ : list α} (f : α → list β) (p : l₁ ~ l₂) :
l₁.bind f ~ l₂.bind f :=
begin
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp},
{ simp, exact perm_app_right _ IH },
{ simp, rw [← append_assoc, ← append_assoc], exact perm_app_left _ perm_app_comm },
{ exact trans IH₁ IH₂ }
end
theorem perm_bind_right (l : list α) {f g : α → list β} (h : ∀ a, f a ~ g a) :
l.bind f ~ l.bind g :=
by induction l with a l IH; simp; exact perm_app (h a) IH
theorem perm_product_left {l₁ l₂ : list α} (t₁ : list β) (p : l₁ ~ l₂) : product l₁ t₁ ~ product l₂ t₁ :=
perm_bind_left _ p
theorem perm_product_right (l : list α) {t₁ t₂ : list β} (p : t₁ ~ t₂) : product l t₁ ~ product l t₂ :=
perm_bind_right _ $ λ a, perm_map _ p
@[congr] theorem perm_product {l₁ l₂ : list α} {t₁ t₂ : list β}
(p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : product l₁ t₁ ~ product l₂ t₂ :=
trans (perm_product_left t₁ p₁) (perm_product_right l₂ p₂)
theorem sublists_cons_perm_append (a : α) (l : list α) :
sublists (a :: l) ~ sublists l ++ map (cons a) (sublists l) :=
begin
simp [sublists, sublists_aux_cons_cons],
refine skip _ ((skip _ _).trans perm_middle.symm),
induction sublists_aux l cons with b l IH; simp,
exact skip b ((skip _ IH).trans perm_middle.symm)
end
theorem sublists_perm_sublists' : ∀ l : list α, sublists l ~ sublists' l
| [] := perm.refl _
| (a::l) := let IH := sublists_perm_sublists' l in
by rw sublists'_cons; exact
(sublists_cons_perm_append _ _).trans (perm_app IH (perm_map _ IH))
theorem revzip_sublists (l : list α) :
∀ l₁ l₂, (l₁, l₂) ∈ revzip l.sublists → l₁ ++ l₂ ~ l :=
begin
rw revzip,
apply list.reverse_rec_on l,
{ intros l₁ l₂ h, simp at h, simp [h] },
{ intros l a IH l₁ l₂ h,
rw [sublists_concat, reverse_append, zip_append, ← map_reverse,
zip_map_right, zip_map_left] at h; [simp at h, simp],
rcases h with ⟨l₁, l₂', h, rfl, rfl⟩ | ⟨l₁', l₂, h, rfl, rfl⟩,
{ rw ← append_assoc,
exact perm_app_left _ (IH _ _ h) },
{ rw append_assoc,
apply (perm_app_right _ perm_app_comm).trans,
rw ← append_assoc,
exact perm_app_left _ (IH _ _ h) } }
end
theorem revzip_sublists' (l : list α) :
∀ l₁ l₂, (l₁, l₂) ∈ revzip l.sublists' → l₁ ++ l₂ ~ l :=
begin
rw revzip,
induction l with a l IH; intros l₁ l₂ h,
{ simp at h, simp [h] },
{ rw [sublists'_cons, reverse_append, zip_append, ← map_reverse,
zip_map_right, zip_map_left] at h; [simp at h, simp],
rcases h with ⟨l₁, l₂', h, rfl, rfl⟩ | ⟨l₁', l₂, h, rfl, rfl⟩,
{ exact perm_middle.trans (skip _ (IH _ _ h)) },
{ exact skip _ (IH _ _ h) } }
end
/- enumerating permutations -/
section permutations
theorem permutations_aux2_fst (t : α) (ts : list α) (r : list β) : ∀ (ys : list α) (f : list α → β),
(permutations_aux2 t ts r ys f).1 = ys ++ ts
| [] f := rfl
| (y::ys) f := match _, permutations_aux2_fst ys _ : ∀ o : list α × list β, o.1 = ys ++ ts →
(permutations_aux2._match_1 t y f o).1 = y :: ys ++ ts with
| ⟨_, zs⟩, rfl := rfl
end
@[simp] theorem permutations_aux2_snd_nil (t : α) (ts : list α) (r : list β) (f : list α → β) :
(permutations_aux2 t ts r [] f).2 = r := rfl
@[simp] theorem permutations_aux2_snd_cons (t : α) (ts : list α) (r : list β) (y : α) (ys : list α) (f : list α → β) :
(permutations_aux2 t ts r (y::ys) f).2 = f (t :: y :: ys ++ ts) ::
(permutations_aux2 t ts r ys (λx : list α, f (y::x))).2 :=
match _, permutations_aux2_fst t ts r _ _ : ∀ o : list α × list β, o.1 = ys ++ ts →
(permutations_aux2._match_1 t y f o).2 = f (t :: y :: ys ++ ts) :: o.2 with
| ⟨_, zs⟩, rfl := rfl
end
theorem permutations_aux2_append (t : α) (ts : list α) (r : list β) (ys : list α) (f : list α → β) :
(permutations_aux2 t ts nil ys f).2 ++ r = (permutations_aux2 t ts r ys f).2 :=
by induction ys generalizing f; simp *
theorem mem_permutations_aux2 {t : α} {ts : list α} {ys : list α} {l l' : list α} :
l' ∈ (permutations_aux2 t ts [] ys (append l)).2 ↔
∃ l₁ l₂, l₂ ≠ [] ∧ ys = l₁ ++ l₂ ∧ l' = l ++ l₁ ++ t :: l₂ ++ ts :=
begin
induction ys with y ys ih generalizing l,
{ simp {contextual := tt} },
{ rw [permutations_aux2_snd_cons, show (λ (x : list α), l ++ y :: x) = append (l ++ [y]),
by funext; simp, mem_cons_iff, ih], split; intro h,
{ rcases h with e | ⟨l₁, l₂, l0, ye, _⟩,
{ subst l', exact ⟨[], y::ys, by simp⟩ },
{ substs l' ys, exact ⟨y::l₁, l₂, l0, by simp⟩ } },
{ rcases h with ⟨_ | ⟨y', l₁⟩, l₂, l0, ye, rfl⟩,
{ simp [ye] },
{ simp at ye, rcases ye with ⟨rfl, rfl⟩,
exact or.inr ⟨l₁, l₂, l0, by simp⟩ } } }
end
theorem mem_permutations_aux2' {t : α} {ts : list α} {ys : list α} {l : list α} :
l ∈ (permutations_aux2 t ts [] ys id).2 ↔
∃ l₁ l₂, l₂ ≠ [] ∧ ys = l₁ ++ l₂ ∧ l = l₁ ++ t :: l₂ ++ ts :=
by rw [show @id (list α) = append nil, by funext; refl]; apply mem_permutations_aux2
theorem length_permutations_aux2 (t : α) (ts : list α) (ys : list α) (f : list α → β) :
length (permutations_aux2 t ts [] ys f).2 = length ys :=
by induction ys generalizing f; simp *
theorem foldr_permutations_aux2 (t : α) (ts : list α) (r L : list (list α)) :
foldr (λy r, (permutations_aux2 t ts r y id).2) r L = L.bind (λ y, (permutations_aux2 t ts [] y id).2) ++ r :=
by induction L with l L ih; [refl, {simp [ih], rw ← permutations_aux2_append}]
theorem mem_foldr_permutations_aux2 {t : α} {ts : list α} {r L : list (list α)} {l' : list α} :
l' ∈ foldr (λy r, (permutations_aux2 t ts r y id).2) r L ↔ l' ∈ r ∨
∃ l₁ l₂, l₁ ++ l₂ ∈ L ∧ l₂ ≠ [] ∧ l' = l₁ ++ t :: l₂ ++ ts :=
have (∃ (a : list α), a ∈ L ∧
∃ (l₁ l₂ : list α), ¬l₂ = nil ∧ a = l₁ ++ l₂ ∧ l' = l₁ ++ t :: (l₂ ++ ts)) ↔
∃ (l₁ l₂ : list α), ¬l₂ = nil ∧ l₁ ++ l₂ ∈ L ∧ l' = l₁ ++ t :: (l₂ ++ ts),
from ⟨λ ⟨a, aL, l₁, l₂, l0, e, h⟩, ⟨l₁, l₂, l0, e ▸ aL, h⟩,
λ ⟨l₁, l₂, l0, aL, h⟩, ⟨_, aL, l₁, l₂, l0, rfl, h⟩⟩,
by rw foldr_permutations_aux2; simp [mem_permutations_aux2', this,
or.comm, or.left_comm, or.assoc, and.comm, and.left_comm, and.assoc]
theorem length_foldr_permutations_aux2 (t : α) (ts : list α) (r L : list (list α)) :
length (foldr (λy r, (permutations_aux2 t ts r y id).2) r L) = sum (map length L) + length r :=
by simp [foldr_permutations_aux2, (∘), length_permutations_aux2]
theorem length_foldr_permutations_aux2' (t : α) (ts : list α) (r L : list (list α))
(n) (H : ∀ l ∈ L, length l = n) :
length (foldr (λy r, (permutations_aux2 t ts r y id).2) r L) = n * length L + length r :=
begin
rw [length_foldr_permutations_aux2, (_ : sum (map length L) = n * length L)],
induction L with l L ih, {simp},
simp [ih (λ l m, H l (mem_cons_of_mem _ m)), H l (mem_cons_self _ _), mul_add]
end
theorem perm_of_mem_permutations_aux :
∀ {ts is l : list α}, l ∈ permutations_aux ts is → l ~ ts ++ is :=
begin
refine permutations_aux.rec (by simp) _,
introv IH1 IH2 m,
rw [permutations_aux_cons, permutations, mem_foldr_permutations_aux2] at m,
rcases m with m | ⟨l₁, l₂, m, _, e⟩,
{ exact (IH1 m).trans perm_middle },
{ subst e,
have p : l₁ ++ l₂ ~ is,
{ simp [permutations] at m,
cases m with e m, {simp [e]},
exact is.append_nil ▸ IH2 m },
exact (perm_app_left _ (perm_middle.trans (skip _ p))).trans (skip _ perm_app_comm) }
end
theorem perm_of_mem_permutations {l₁ l₂ : list α}
(h : l₁ ∈ permutations l₂) : l₁ ~ l₂ :=
(eq_or_mem_of_mem_cons h).elim (λ e, e ▸ perm.refl _)
(λ m, append_nil l₂ ▸ perm_of_mem_permutations_aux m)
theorem length_permutations_aux :
∀ ts is : list α, length (permutations_aux ts is) + is.length.fact = (length ts + length is).fact :=
begin
refine permutations_aux.rec (by simp) _,
intros t ts is IH1 IH2,
have IH2 : length (permutations_aux is nil) + 1 = is.length.fact,
{ simpa using IH2 },
simp [-add_comm, nat.fact, nat.add_succ, mul_comm] at IH1,
rw [permutations_aux_cons,
length_foldr_permutations_aux2' _ _ _ _ _
(λ l m, perm_length (perm_of_mem_permutations m)),
permutations, length, length, IH2,
nat.succ_add, nat.fact_succ, mul_comm (nat.succ _), ← IH1,
add_comm (_*_), add_assoc, nat.mul_succ, mul_comm]
end
theorem length_permutations (l : list α) : length (permutations l) = (length l).fact :=
length_permutations_aux l []
theorem mem_permutations_of_perm_lemma {is l : list α}
(H : l ~ [] ++ is → (∃ ts' ~ [], l = ts' ++ is) ∨ l ∈ permutations_aux is [])
: l ~ is → l ∈ permutations is :=
by simpa [permutations, perm_nil] using H
theorem mem_permutations_aux_of_perm :
∀ {ts is l : list α}, l ~ is ++ ts → (∃ is' ~ is, l = is' ++ ts) ∨ l ∈ permutations_aux ts is :=
begin
refine permutations_aux.rec (by simp) _,
intros t ts is IH1 IH2 l p,
rw [permutations_aux_cons, mem_foldr_permutations_aux2],
rcases IH1 (p.trans perm_middle) with ⟨is', p', e⟩ | m,
{ clear p, subst e,
rcases mem_split (perm_subset p'.symm (mem_cons_self _ _)) with ⟨l₁, l₂, e⟩,
subst is',
have p := perm_cons_inv (perm_middle.symm.trans p'),
cases l₂ with a l₂',
{ exact or.inl ⟨l₁, by simpa using p⟩ },
{ exact or.inr (or.inr ⟨l₁, a::l₂',
mem_permutations_of_perm_lemma IH2 p, by simp⟩) } },
{ exact or.inr (or.inl m) }
end
@[simp] theorem mem_permutations (s t : list α) : s ∈ permutations t ↔ s ~ t :=
⟨perm_of_mem_permutations, mem_permutations_of_perm_lemma mem_permutations_aux_of_perm⟩
end permutations
end list
|
d592782696f8cf4cc49afb69354f4e383b117c0a | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/category_theory/functor/left_derived.lean | 8f8f9baf18c768c2633b8b1e361e132923d40cd0 | [
"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 | 7,816 | lean | /-
Copyright (c) 2021 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.preadditive.projective_resolution
/-!
# Left-derived functors
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We define the left-derived functors `F.left_derived n : C ⥤ D` for any additive functor `F`
out of a category with projective resolutions.
The definition is
```
projective_resolutions C ⋙ F.map_homotopy_category _ ⋙ homotopy_category.homology_functor D _ n
```
that is, we pick a projective resolution (thought of as an object of the homotopy category),
we apply `F` objectwise, and compute `n`-th homology.
We show that these left-derived functors can be calculated
on objects using any choice of projective resolution,
and on morphisms by any choice of lift to a chain map between chosen projective resolutions.
Similarly we define natural transformations between left-derived functors coming from
natural transformations between the original additive functors,
and show how to compute the components.
## Implementation
We don't assume the categories involved are abelian
(just preadditive, and have equalizers, cokernels, and image maps),
or that the functors are right exact.
None of these assumptions are needed yet.
It is often convenient, of course, to work with `[abelian C] [enough_projectives C] [abelian D]`
which (assuming the results from `category_theory.abelian.projective`) are enough to
provide all the typeclass hypotheses assumed here.
-/
noncomputable theory
open category_theory
open category_theory.limits
universes v u
namespace category_theory
variables {C : Type u} [category.{v} C] {D : Type*} [category D]
-- Importing `category_theory.abelian.projective` and assuming
-- `[abelian C] [enough_projectives C] [abelian D]` suffices to acquire all the following:
variables [preadditive C] [has_zero_object C] [has_equalizers C]
[has_images C] [has_projective_resolutions C]
variables [preadditive D] [has_equalizers D] [has_cokernels D]
[has_images D] [has_image_maps D]
/-- The left derived functors of an additive functor. -/
def functor.left_derived (F : C ⥤ D) [F.additive] (n : ℕ) : C ⥤ D :=
projective_resolutions C ⋙ F.map_homotopy_category _ ⋙ homotopy_category.homology_functor D _ n
-- TODO the left derived functors are additive (and linear when `F` is linear)
/-- We can compute a left derived functor using a chosen projective resolution. -/
@[simps]
def functor.left_derived_obj_iso (F : C ⥤ D) [F.additive] (n : ℕ)
{X : C} (P : ProjectiveResolution X) :
(F.left_derived n).obj X ≅
(homology_functor D _ n).obj ((F.map_homological_complex _).obj P.complex) :=
(homotopy_category.homology_functor D _ n).map_iso
(homotopy_category.iso_of_homotopy_equiv
(F.map_homotopy_equiv (ProjectiveResolution.homotopy_equiv _ P)))
≪≫ (homotopy_category.homology_factors D _ n).app _
section
variables [has_zero_object D]
/-- The 0-th derived functor of `F` on a projective object `X` is just `F.obj X`. -/
@[simps]
def functor.left_derived_obj_projective_zero (F : C ⥤ D) [F.additive]
(X : C) [projective X] :
(F.left_derived 0).obj X ≅ F.obj X :=
F.left_derived_obj_iso 0 (ProjectiveResolution.self X) ≪≫
(homology_functor _ _ _).map_iso ((chain_complex.single₀_map_homological_complex F).app X) ≪≫
(chain_complex.homology_functor_0_single₀ D).app (F.obj X)
open_locale zero_object
/-- The higher derived functors vanish on projective objects. -/
@[simps inv]
def functor.left_derived_obj_projective_succ (F : C ⥤ D) [F.additive] (n : ℕ)
(X : C) [projective X] :
(F.left_derived (n+1)).obj X ≅ 0 :=
F.left_derived_obj_iso (n+1) (ProjectiveResolution.self X) ≪≫
(homology_functor _ _ _).map_iso ((chain_complex.single₀_map_homological_complex F).app X) ≪≫
(chain_complex.homology_functor_succ_single₀ D n).app (F.obj X) ≪≫
(functor.zero_obj _).iso_zero
end
/--
We can compute a left derived functor on a morphism using a lift of that morphism
to a chain map between chosen projective resolutions.
-/
lemma functor.left_derived_map_eq (F : C ⥤ D) [F.additive] (n : ℕ) {X Y : C} (f : X ⟶ Y)
{P : ProjectiveResolution X} {Q : ProjectiveResolution Y} (g : P.complex ⟶ Q.complex)
(w : g ≫ Q.π = P.π ≫ (chain_complex.single₀ C).map f) :
(F.left_derived n).map f =
(F.left_derived_obj_iso n P).hom ≫
(homology_functor D _ n).map ((F.map_homological_complex _).map g) ≫
(F.left_derived_obj_iso n Q).inv :=
begin
dsimp only [functor.left_derived, functor.left_derived_obj_iso],
dsimp, simp only [category.comp_id, category.id_comp],
rw [←homology_functor_map, homotopy_category.homology_functor_map_factors],
simp only [←functor.map_comp],
congr' 1,
apply homotopy_category.eq_of_homotopy,
apply functor.map_homotopy,
apply homotopy.trans,
exact homotopy_category.homotopy_out_map _,
apply ProjectiveResolution.lift_homotopy f,
{ simp, },
{ simp [w], },
end
/-- The natural transformation between left-derived functors induced by a natural transformation. -/
@[simps]
def nat_trans.left_derived {F G : C ⥤ D} [F.additive] [G.additive] (α : F ⟶ G) (n : ℕ) :
F.left_derived n ⟶ G.left_derived n :=
whisker_left (projective_resolutions C)
(whisker_right (nat_trans.map_homotopy_category α _)
(homotopy_category.homology_functor D _ n))
@[simp] lemma nat_trans.left_derived_id (F : C ⥤ D) [F.additive] (n : ℕ) :
nat_trans.left_derived (𝟙 F) n = 𝟙 (F.left_derived n) :=
by { simp [nat_trans.left_derived], refl, }
-- The `simp_nf` linter times out here, so we disable it.
@[simp, nolint simp_nf] lemma nat_trans.left_derived_comp
{F G H : C ⥤ D} [F.additive] [G.additive] [H.additive]
(α : F ⟶ G) (β : G ⟶ H) (n : ℕ) :
nat_trans.left_derived (α ≫ β) n = nat_trans.left_derived α n ≫ nat_trans.left_derived β n :=
by simp [nat_trans.left_derived]
/--
A component of the natural transformation between left-derived functors can be computed
using a chosen projective resolution.
-/
lemma nat_trans.left_derived_eq {F G : C ⥤ D} [F.additive] [G.additive] (α : F ⟶ G) (n : ℕ)
{X : C} (P : ProjectiveResolution X) :
(nat_trans.left_derived α n).app X =
(F.left_derived_obj_iso n P).hom ≫
(homology_functor D _ n).map ((nat_trans.map_homological_complex α _).app P.complex) ≫
(G.left_derived_obj_iso n P).inv :=
begin
symmetry,
dsimp [nat_trans.left_derived, functor.left_derived_obj_iso],
simp only [category.comp_id, category.id_comp],
rw [←homology_functor_map, homotopy_category.homology_functor_map_factors],
simp only [←functor.map_comp],
congr' 1,
apply homotopy_category.eq_of_homotopy,
simp only [nat_trans.map_homological_complex_naturality_assoc,
←functor.map_comp],
apply homotopy.comp_left_id,
rw [←functor.map_id],
apply functor.map_homotopy,
apply homotopy_equiv.homotopy_hom_inv_id,
end
-- TODO:
-- lemma nat_trans.left_derived_projective_zero {F G : C ⥤ D} [F.additive] [G.additive] (α : F ⟶ G)
-- (X : C) [projective X] :
-- (nat_trans.left_derived α 0).app X =
-- (F.left_derived_obj_projective_zero X).hom ≫
-- α.app X ≫
-- (G.left_derived_obj_projective_zero X).inv := sorry
-- TODO:
-- lemma nat_trans.left_derived_projective_succ {F G : C ⥤ D} [F.additive] [G.additive] (α : F ⟶ G)
-- (n : ℕ) (X : C) [projective X] :
-- (nat_trans.left_derived α (n+1)).app X = 0 := sorry
-- TODO left-derived functors of the identity functor are the identity
-- (requires we assume `abelian`?)
-- PROJECT left-derived functors of a composition (Grothendieck sequence)
end category_theory
|
2ef5ccb6d942c4159919d94d95de4fecfe75a97a | 359199d7253811b032ab92108191da7336eba86e | /src/mywork/blah.lean | 8a80bd4e198d0659aef584bf3811977ed2f457bd | [] | no_license | arte-et-marte/my_cs2120f21 | 0bc6215cb5018a3b7c90d9d399a173233f587064 | 91609c3609ad81fda895bee8b97cc76813241e17 | refs/heads/main | 1,693,298,928,348 | 1,634,931,202,000 | 1,634,931,202,000 | 399,946,705 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 465 | lean | /-
Social Networks
-/
axioms
(Person : Type)
(Nice : Person → Prop)
(Likes : Person → Person → Prop)
/-
What does this say, in English? It is true?
-/
example :
-- If there's a person, p1, who everyone likes,
(∃ (p1 : Person), ∀ (p2 : Person), Likes p2 p1) →
-- then everyone likes someone
(∀ (e : Person), ∃ (s : Person), Likes e s) :=
begin
assume h,
cases h with p pf,
assume e,
apply exists.intro p,
exact (pf e),
end |
0974b69edb2d3428587083d123e3dfccbda9b7a9 | c76cc4eaee3c806716844e49b5175747d1aa170a | /src/solutions_sheet_five.lean | 1c8df166b78006a58ba2e8a5e88e15f97b63da58 | [] | no_license | ImperialCollegeLondon/M40002 | 0fb55848adbb0d8bc4a65ca5d7ed6edd18764c28 | a499db70323bd5ccae954c680ec9afbf15ffacca | refs/heads/master | 1,674,878,059,748 | 1,607,624,828,000 | 1,607,624,828,000 | 309,696,750 | 3 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,214 | lean | import tactic
import data.real.basic
import data.pnat.basic
local notation `|` x `|` := abs x
def is_limit (a : ℕ → ℝ) (l : ℝ) : Prop :=
∀ ε > 0, ∃ N, ∀ n ≥ N, | a n - l | < ε
def tends_to_plus_infinity (a : ℕ → ℝ) : Prop :=
∀ B, ∃ N, ∀ n ≥ N, B < a n
def is_convergent (a : ℕ → ℝ) : Prop :=
∃ l : ℝ, is_limit a l
namespace sheet_five
theorem Q1a (x : ℝ) (hx : 0 < x) (n : ℕ) : (1 : ℝ) + n * x ≤ (1 + x)^n :=
begin
sorry
end
theorem Q1b (x : ℝ) (hx : 0 < x) : is_limit (λ n, (1 + x) ^ (-(n : ℤ))) 0 :=
begin
intros ε hε,
obtain ⟨N, hN⟩ := add_one_pow_unbounded_of_pos (1/ε) hx,
existsi N,
intros n hn,
dsimp only,
rw sub_zero,
have hx2 : 0 < 1 + x,
linarith,
have hx3 : ∀ m, (1+x) ^ m > 0,
intro m,
exact fpow_pos_of_pos hx2 m,
rw abs_of_pos (hx3 _),
simp,
rw ← one_div,
rw one_div_lt (pow_pos hx2 n) hε,
refine lt_of_lt_of_le hN _,
rw add_comm,
apply pow_le_pow,
linarith,
assumption,
end
theorem Q1c (r : ℝ) (hr : r ∈ set.Ioo (0 : ℝ) 1) : is_limit (λ n, r ^ n) 0 :=
begin
sorry
end
theorem Q1d (r : ℝ) (hr : 1 < r) : tends_to_plus_infinity (λ n, r ^ n) :=
begin
sorry
end |
b0990daf73b6e580d916dc4953c6cc4c27c9006a | 367134ba5a65885e863bdc4507601606690974c1 | /src/order/compactly_generated.lean | 8e3965f7c8277fe2319e254cbc7652434413a8d7 | [
"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 | 20,341 | lean | /-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import data.set.finite
import data.finset.order
import order.well_founded
import order.order_iso_nat
import order.atoms
import order.zorn
import tactic.tfae
/-!
# Compactness properties for complete lattices
For complete lattices, there are numerous equivalent ways to express the fact that the relation `>`
is well-founded. In this file we define three especially-useful characterisations and provide
proofs that they are indeed equivalent to well-foundedness.
## Main definitions
* `complete_lattice.is_sup_closed_compact`
* `complete_lattice.is_Sup_finite_compact`
* `complete_lattice.is_compact_element`
* `complete_lattice.is_compactly_generated`
## Main results
The main result is that the following four conditions are equivalent for a complete lattice:
* `well_founded (>)`
* `complete_lattice.is_sup_closed_compact`
* `complete_lattice.is_Sup_finite_compact`
* `∀ k, complete_lattice.is_compact_element k`
This is demonstrated by means of the following four lemmas:
* `complete_lattice.well_founded.is_Sup_finite_compact`
* `complete_lattice.is_Sup_finite_compact.is_sup_closed_compact`
* `complete_lattice.is_sup_closed_compact.well_founded`
* `complete_lattice.is_Sup_finite_compact_iff_all_elements_compact`
We also show well-founded lattices are compactly generated
(`complete_lattice.compactly_generated_of_well_founded`).
## References
- [G. Călugăreanu, *Lattice Concepts of Module Theory*][calugareanu]
## Tags
complete lattice, well-founded, compact
-/
variables {α : Type*} [complete_lattice α]
namespace complete_lattice
variables (α)
/-- A compactness property for a complete lattice is that any `sup`-closed non-empty subset
contains its `Sup`. -/
def is_sup_closed_compact : Prop :=
∀ (s : set α) (h : s.nonempty), (∀ a b, a ∈ s → b ∈ s → a ⊔ b ∈ s) → (Sup s) ∈ s
/-- A compactness property for a complete lattice is that any subset has a finite subset with the
same `Sup`. -/
def is_Sup_finite_compact : Prop :=
∀ (s : set α), ∃ (t : finset α), ↑t ⊆ s ∧ Sup s = t.sup id
/-- An element `k` of a complete lattice is said to be compact if any set with `Sup`
above `k` has a finite subset with `Sup` above `k`. Such an element is also called
"finite" or "S-compact". -/
def is_compact_element {α : Type*} [complete_lattice α] (k : α) :=
∀ s : set α, k ≤ Sup s → ∃ t : finset α, ↑t ⊆ s ∧ k ≤ t.sup id
/-- An element `k` is compact if and only if any directed set with `Sup` above
`k` already got above `k` at some point in the set. -/
theorem is_compact_element_iff_le_of_directed_Sup_le (k : α) :
is_compact_element k ↔
∀ s : set α, s.nonempty → directed_on (≤) s → k ≤ Sup s → ∃ x : α, x ∈ s ∧ k ≤ x :=
begin
classical,
split,
{ by_cases hbot : k = ⊥,
-- Any nonempty directed set certainly has sup above ⊥
{ rintros _ _ ⟨x, hx⟩ _ _, use x, by simp only [hx, hbot, bot_le, and_self], },
{ intros hk s hne hdir hsup,
obtain ⟨t, ht⟩ := hk s hsup,
-- If t were empty, its sup would be ⊥, which is not above k ≠ ⊥.
have tne : t.nonempty,
{ by_contradiction n,
rw [finset.nonempty_iff_ne_empty, not_not] at n,
simp only [n, true_and, set.empty_subset, finset.coe_empty,
finset.sup_empty, le_bot_iff] at ht,
exact absurd ht hbot, },
-- certainly every element of t is below something in s, since ↑t ⊆ s.
have t_below_s : ∀ x ∈ t, ∃ y ∈ s, x ≤ y, from λ x hxt, ⟨x, ht.left hxt, by refl⟩,
obtain ⟨x, ⟨hxs, hsupx⟩⟩ := finset.sup_le_of_le_directed s hne hdir t t_below_s,
exact ⟨x, ⟨hxs, le_trans ht.right hsupx⟩⟩, }, },
{ intros hk s hsup,
-- Consider the set of finite joins of elements of the (plain) set s.
let S : set α := { x | ∃ t : finset α, ↑t ⊆ s ∧ x = t.sup id },
-- S is directed, nonempty, and still has sup above k.
have dir_US : directed_on (≤) S,
{ rintros x ⟨c, hc⟩ y ⟨d, hd⟩,
use x ⊔ y,
split,
{ use c ∪ d,
split,
{ simp only [hc.left, hd.left, set.union_subset_iff, finset.coe_union, and_self], },
{ simp only [hc.right, hd.right, finset.sup_union], }, },
simp only [and_self, le_sup_left, le_sup_right], },
have sup_S : Sup s ≤ Sup S,
{ apply Sup_le_Sup,
intros x hx, use {x},
simpa only [and_true, id.def, finset.coe_singleton, eq_self_iff_true, finset.sup_singleton,
set.singleton_subset_iff], },
have Sne : S.nonempty,
{ suffices : ⊥ ∈ S, from set.nonempty_of_mem this,
use ∅,
simp only [set.empty_subset, finset.coe_empty, finset.sup_empty,
eq_self_iff_true, and_self], },
-- Now apply the defn of compact and finish.
obtain ⟨j, ⟨hjS, hjk⟩⟩ := hk S Sne dir_US (le_trans hsup sup_S),
obtain ⟨t, ⟨htS, htsup⟩⟩ := hjS,
use t, exact ⟨htS, by rwa ←htsup⟩, },
end
/-- A compact element `k` has the property that any directed set lying strictly below `k` has
its Sup strictly below `k`. -/
lemma is_compact_element.directed_Sup_lt_of_lt {α : Type*} [complete_lattice α] {k : α}
(hk : is_compact_element k) {s : set α} (hemp : s.nonempty) (hdir : directed_on (≤) s)
(hbelow : ∀ x ∈ s, x < k) : Sup s < k :=
begin
rw is_compact_element_iff_le_of_directed_Sup_le at hk,
by_contradiction,
have sSup : Sup s ≤ k, from Sup_le (λ s hs, (hbelow s hs).le),
replace sSup : Sup s = k := eq_iff_le_not_lt.mpr ⟨sSup, h⟩,
obtain ⟨x, hxs, hkx⟩ := hk s hemp hdir sSup.symm.le,
obtain hxk := hbelow x hxs,
exact hxk.ne (hxk.le.antisymm hkx),
end
lemma finset_sup_compact_of_compact {α β : Type*} [complete_lattice α] {f : β → α}
(s : finset β) (h : ∀ x ∈ s, is_compact_element (f x)) : is_compact_element (s.sup f) :=
begin
classical,
rw is_compact_element_iff_le_of_directed_Sup_le,
intros d hemp hdir hsup,
change f with id ∘ f, rw finset.sup_finset_image,
apply finset.sup_le_of_le_directed d hemp hdir,
rintros x hx,
obtain ⟨p, ⟨hps, rfl⟩⟩ := finset.mem_image.mp hx,
specialize h p hps,
rw is_compact_element_iff_le_of_directed_Sup_le at h,
specialize h d hemp hdir (le_trans (finset.le_sup hps) hsup),
simpa only [exists_prop],
end
lemma well_founded.is_Sup_finite_compact (h : well_founded ((>) : α → α → Prop)) :
is_Sup_finite_compact α :=
begin
intros s,
let p : set α := { x | ∃ (t : finset α), ↑t ⊆ s ∧ t.sup id = x },
have hp : p.nonempty, { use [⊥, ∅], simp, },
obtain ⟨m, ⟨t, ⟨ht₁, ht₂⟩⟩, hm⟩ := well_founded.well_founded_iff_has_max'.mp h p hp,
use t, simp only [ht₁, ht₂, true_and], apply le_antisymm,
{ apply Sup_le, intros y hy, classical,
have hy' : (insert y t).sup id ∈ p,
{ use insert y t, simp, rw set.insert_subset, exact ⟨hy, ht₁⟩, },
have hm' : m ≤ (insert y t).sup id, { rw ← ht₂, exact finset.sup_mono (t.subset_insert y), },
rw ← hm _ hy' hm', simp, },
{ rw [← ht₂, finset.sup_eq_Sup], exact Sup_le_Sup ht₁, },
end
lemma is_Sup_finite_compact.is_sup_closed_compact (h : is_Sup_finite_compact α) :
is_sup_closed_compact α :=
begin
intros s hne hsc, obtain ⟨t, ht₁, ht₂⟩ := h s, clear h,
cases t.eq_empty_or_nonempty with h h,
{ subst h, rw finset.sup_empty at ht₂, rw ht₂,
simp [eq_singleton_bot_of_Sup_eq_bot_of_nonempty ht₂ hne], },
{ rw ht₂, exact t.sup_closed_of_sup_closed h ht₁ hsc, },
end
lemma is_sup_closed_compact.well_founded (h : is_sup_closed_compact α) :
well_founded ((>) : α → α → Prop) :=
begin
rw rel_embedding.well_founded_iff_no_descending_seq, rintros ⟨a⟩,
suffices : Sup (set.range a) ∈ set.range a,
{ obtain ⟨n, hn⟩ := set.mem_range.mp this,
have h' : Sup (set.range a) < a (n+1), { change _ > _, simp [← hn, a.map_rel_iff], },
apply lt_irrefl (a (n+1)), apply lt_of_le_of_lt _ h', apply le_Sup, apply set.mem_range_self, },
apply h (set.range a),
{ use a 37, apply set.mem_range_self, },
{ rintros x y ⟨m, hm⟩ ⟨n, hn⟩, use m ⊔ n, rw [← hm, ← hn], apply a.to_rel_hom.map_sup, },
end
lemma is_Sup_finite_compact_iff_all_elements_compact :
is_Sup_finite_compact α ↔ (∀ k : α, is_compact_element k) :=
begin
split,
{ intros h k s hs,
obtain ⟨t, ⟨hts, htsup⟩⟩ := h s,
use [t, hts],
rwa ←htsup, },
{ intros h s,
obtain ⟨t, ⟨hts, htsup⟩⟩ := h (Sup s) s (by refl),
have : Sup s = t.sup id,
{ suffices : t.sup id ≤ Sup s, by { apply le_antisymm; assumption },
simp only [id.def, finset.sup_le_iff],
intros x hx,
apply le_Sup, exact hts hx, },
use [t, hts], assumption, },
end
lemma well_founded_characterisations :
tfae [well_founded ((>) : α → α → Prop),
is_Sup_finite_compact α,
is_sup_closed_compact α,
∀ k : α, is_compact_element k] :=
begin
tfae_have : 1 → 2, by { exact well_founded.is_Sup_finite_compact α, },
tfae_have : 2 → 3, by { exact is_Sup_finite_compact.is_sup_closed_compact α, },
tfae_have : 3 → 1, by { exact is_sup_closed_compact.well_founded α, },
tfae_have : 2 ↔ 4, by { exact is_Sup_finite_compact_iff_all_elements_compact α },
tfae_finish,
end
lemma well_founded_iff_is_Sup_finite_compact :
well_founded ((>) : α → α → Prop) ↔ is_Sup_finite_compact α :=
(well_founded_characterisations α).out 0 1
lemma is_Sup_finite_compact_iff_is_sup_closed_compact :
is_Sup_finite_compact α ↔ is_sup_closed_compact α :=
(well_founded_characterisations α).out 1 2
lemma is_sup_closed_compact_iff_well_founded :
is_sup_closed_compact α ↔ well_founded ((>) : α → α → Prop) :=
(well_founded_characterisations α).out 2 0
alias well_founded_iff_is_Sup_finite_compact ↔ _ is_Sup_finite_compact.well_founded
alias is_Sup_finite_compact_iff_is_sup_closed_compact ↔
_ is_sup_closed_compact.is_Sup_finite_compact
alias is_sup_closed_compact_iff_well_founded ↔ _ well_founded.is_sup_closed_compact
end complete_lattice
/-- A complete lattice is said to be compactly generated if any
element is the `Sup` of compact elements. -/
class is_compactly_generated (α : Type*) [complete_lattice α] : Prop :=
(exists_Sup_eq :
∀ (x : α), ∃ (s : set α), (∀ x ∈ s, complete_lattice.is_compact_element x) ∧ Sup s = x)
section
variables {α} [is_compactly_generated α] {a b : α} {s : set α}
@[simp]
lemma Sup_compact_le_eq (b) : Sup {c : α | complete_lattice.is_compact_element c ∧ c ≤ b} = b :=
begin
rcases is_compactly_generated.exists_Sup_eq b with ⟨s, hs, rfl⟩,
exact le_antisymm (Sup_le (λ c hc, hc.2)) (Sup_le_Sup (λ c cs, ⟨hs c cs, le_Sup cs⟩)),
end
@[simp]
theorem Sup_compact_eq_top :
Sup {a : α | complete_lattice.is_compact_element a} = ⊤ :=
begin
refine eq.trans (congr rfl (set.ext (λ x, _))) (Sup_compact_le_eq ⊤),
exact (and_iff_left le_top).symm,
end
theorem le_iff_compact_le_imp {a b : α} :
a ≤ b ↔ ∀ c : α, complete_lattice.is_compact_element c → c ≤ a → c ≤ b :=
⟨λ ab c hc ca, le_trans ca ab, λ h, begin
rw [← Sup_compact_le_eq a, ← Sup_compact_le_eq b],
exact Sup_le_Sup (λ c hc, ⟨hc.1, h c hc.1 hc.2⟩),
end⟩
/-- This property is sometimes referred to as `α` being upper continuous. -/
theorem inf_Sup_eq_of_directed_on (h : directed_on (≤) s):
a ⊓ Sup s = ⨆ b ∈ s, a ⊓ b :=
le_antisymm (begin
rw le_iff_compact_le_imp,
by_cases hs : s.nonempty,
{ intros c hc hcinf,
rw le_inf_iff at hcinf,
rw complete_lattice.is_compact_element_iff_le_of_directed_Sup_le at hc,
rcases hc s hs h hcinf.2 with ⟨d, ds, cd⟩,
exact (le_inf hcinf.1 cd).trans (le_bsupr d ds) },
{ rw set.not_nonempty_iff_eq_empty at hs,
simp [hs] }
end) supr_inf_le_inf_Sup
/-- This property is equivalent to `α` being upper continuous. -/
theorem inf_Sup_eq_supr_inf_sup_finset :
a ⊓ Sup s = ⨆ (t : finset α) (H : ↑t ⊆ s), a ⊓ (t.sup id) :=
le_antisymm (begin
rw le_iff_compact_le_imp,
intros c hc hcinf,
rw le_inf_iff at hcinf,
rcases hc s hcinf.2 with ⟨t, ht1, ht2⟩,
exact (le_inf hcinf.1 ht2).trans (le_bsupr t ht1),
end) (supr_le $ λ t, supr_le $ λ h, inf_le_inf_left _ ((finset.sup_eq_Sup t).symm ▸ (Sup_le_Sup h)))
theorem complete_lattice.independent_iff_finite {s : set α} :
complete_lattice.independent s ↔
∀ t : finset α, ↑t ⊆ s → complete_lattice.independent (↑t : set α) :=
⟨λ hs t ht, hs.mono ht, λ h a ha, begin
rw [disjoint_iff, inf_Sup_eq_supr_inf_sup_finset, supr_eq_bot],
intro t,
rw [supr_eq_bot, finset.sup_eq_Sup],
intro ht,
classical,
have h' := (h (insert a t) _ (t.mem_insert_self a)).eq_bot,
{ rwa [finset.coe_insert, set.insert_diff_self_of_not_mem] at h',
exact λ con, ((set.mem_diff a).1 (ht con)).2 (set.mem_singleton a) },
{ rw [finset.coe_insert, set.insert_subset],
exact ⟨ha, set.subset.trans ht (set.diff_subset _ _)⟩ }
end⟩
lemma complete_lattice.independent_Union_of_directed {η : Type*}
{s : η → set α} (hs : directed (⊆) s)
(h : ∀ i, complete_lattice.independent (s i)) :
complete_lattice.independent (⋃ i, s i) :=
begin
by_cases hη : nonempty η,
{ resetI,
rw complete_lattice.independent_iff_finite,
intros t ht,
obtain ⟨I, fi, hI⟩ := set.finite_subset_Union t.finite_to_set ht,
obtain ⟨i, hi⟩ := hs.finset_le fi.to_finset,
exact (h i).mono (set.subset.trans hI $ set.bUnion_subset $
λ j hj, hi j (fi.mem_to_finset.2 hj)) },
{ rintros a ⟨_, ⟨i, _⟩, _⟩,
exfalso, exact hη ⟨i⟩, },
end
lemma complete_lattice.independent_sUnion_of_directed {s : set (set α)}
(hs : directed_on (⊆) s)
(h : ∀ a ∈ s, complete_lattice.independent a) :
complete_lattice.independent (⋃₀ s) :=
by rw set.sUnion_eq_Union; exact
complete_lattice.independent_Union_of_directed hs.directed_coe (by simpa using h)
end
namespace complete_lattice
lemma compactly_generated_of_well_founded (h : well_founded ((>) : α → α → Prop)) :
is_compactly_generated α :=
begin
rw [well_founded_iff_is_Sup_finite_compact, is_Sup_finite_compact_iff_all_elements_compact] at h,
-- x is the join of the set of compact elements {x}
exact ⟨λ x, ⟨{x}, ⟨λ x _, h x, Sup_singleton⟩⟩⟩,
end
/-- A compact element `k` has the property that any `b < `k lies below a "maximal element below
`k`", which is to say `[⊥, k]` is coatomic. -/
theorem Iic_coatomic_of_compact_element {k : α} (h : is_compact_element k) :
is_coatomic (set.Iic k) :=
⟨λ ⟨b, hbk⟩, begin
by_cases htriv : b = k,
{ left, ext, simp only [htriv, set.Iic.coe_top, subtype.coe_mk], },
right,
rcases zorn.zorn_partial_order₀ (set.Iio k) _ b (lt_of_le_of_ne hbk htriv) with ⟨a, a₀, ba, h⟩,
{ refine ⟨⟨a, le_of_lt a₀⟩, ⟨ne_of_lt a₀, λ c hck, by_contradiction $ λ c₀, _⟩, ba⟩,
cases h c.1 (lt_of_le_of_ne c.2 (λ con, c₀ (subtype.ext con))) hck.le,
exact lt_irrefl _ hck, },
{ intros S SC cC I IS,
by_cases hS : S.nonempty,
{ exact ⟨Sup S, h.directed_Sup_lt_of_lt hS cC.directed_on SC, λ _, le_Sup⟩, },
exact ⟨b, lt_of_le_of_ne hbk htriv, by simp only [set.not_nonempty_iff_eq_empty.mp hS,
set.mem_empty_eq, forall_const, forall_prop_of_false, not_false_iff]⟩, },
end⟩
lemma coatomic_of_top_compact (h : is_compact_element (⊤ : α)) : is_coatomic α :=
(@order_iso.Iic_top α _).is_coatomic_iff.mp (Iic_coatomic_of_compact_element h)
end complete_lattice
section
variables [is_modular_lattice α] [is_compactly_generated α]
@[priority 100]
instance is_atomic_of_is_complemented [is_complemented α] : is_atomic α :=
⟨λ b, begin
by_cases h : {c : α | complete_lattice.is_compact_element c ∧ c ≤ b} ⊆ {⊥},
{ left,
rw [← Sup_compact_le_eq b, Sup_eq_bot],
exact h },
{ rcases set.not_subset.1 h with ⟨c, ⟨hc, hcb⟩, hcbot⟩,
right,
have hc' := complete_lattice.Iic_coatomic_of_compact_element hc,
rw ← is_atomic_iff_is_coatomic at hc',
haveI := hc',
obtain con | ⟨a, ha, hac⟩ := eq_bot_or_exists_atom_le (⟨c, le_refl c⟩ : set.Iic c),
{ exfalso,
apply hcbot,
simp only [subtype.ext_iff, set.Iic.coe_bot, subtype.coe_mk] at con,
exact con },
rw [← subtype.coe_le_coe, subtype.coe_mk] at hac,
exact ⟨a, ha.of_is_atom_coe_Iic, hac.trans hcb⟩ },
end⟩
/-- See Lemma 5.1, Călugăreanu -/
@[priority 100]
instance is_atomistic_of_is_complemented [is_complemented α] : is_atomistic α :=
⟨λ b, ⟨{a | is_atom a ∧ a ≤ b}, begin
symmetry,
have hle : Sup {a : α | is_atom a ∧ a ≤ b} ≤ b := (Sup_le $ λ _, and.right),
apply (lt_or_eq_of_le hle).resolve_left (λ con, _),
obtain ⟨c, hc⟩ := exists_is_compl (⟨Sup {a : α | is_atom a ∧ a ≤ b}, hle⟩ : set.Iic b),
obtain rfl | ⟨a, ha, hac⟩ := eq_bot_or_exists_atom_le c,
{ exact ne_of_lt con (subtype.ext_iff.1 (eq_top_of_is_compl_bot hc)) },
{ apply ha.1,
rw eq_bot_iff,
apply le_trans (le_inf _ hac) hc.1,
rw [← subtype.coe_le_coe, subtype.coe_mk],
exact le_Sup ⟨ha.of_is_atom_coe_Iic, a.2⟩ }
end, λ _, and.left⟩⟩
/-- See Theorem 6.6, Călugăreanu -/
theorem is_complemented_of_Sup_atoms_eq_top (h : Sup {a : α | is_atom a} = ⊤) : is_complemented α :=
⟨λ b, begin
obtain ⟨s, ⟨s_ind, b_inf_Sup_s, s_atoms⟩, s_max⟩ := zorn.zorn_subset
{s : set α | complete_lattice.independent s ∧ b ⊓ Sup s = ⊥ ∧ ∀ a ∈ s, is_atom a} _,
{ refine ⟨Sup s, le_of_eq b_inf_Sup_s, _⟩,
rw [← h, Sup_le_iff],
intros a ha,
rw ← inf_eq_left,
refine (eq_bot_or_eq_of_le_atom ha inf_le_left).resolve_left (λ con, ha.1 _),
rw [eq_bot_iff, ← con],
refine le_inf (le_refl a) ((le_Sup _).trans le_sup_right),
rw ← disjoint_iff at *,
have a_dis_Sup_s : disjoint a (Sup s) := con.mono_right le_sup_right,
rw ← s_max (s ∪ {a}) ⟨λ x hx, _, ⟨_, λ x hx, _⟩⟩ (set.subset_union_left _ _),
{ exact set.mem_union_right _ (set.mem_singleton _) },
{ rw [set.mem_union, set.mem_singleton_iff] at hx,
by_cases xa : x = a,
{ simp only [xa, set.mem_singleton, set.insert_diff_of_mem, set.union_singleton],
exact con.mono_right (le_trans (Sup_le_Sup (set.diff_subset s {a})) le_sup_right) },
{ have h : (s ∪ {a}) \ {x} = (s \ {x}) ∪ {a},
{ simp only [set.union_singleton],
rw set.insert_diff_of_not_mem,
rw set.mem_singleton_iff,
exact ne.symm xa },
rw [h, Sup_union, Sup_singleton],
apply (s_ind (hx.resolve_right xa)).disjoint_sup_right_of_disjoint_sup_left
(a_dis_Sup_s.mono_right _).symm,
rw [← Sup_insert, set.insert_diff_singleton,
set.insert_eq_of_mem (hx.resolve_right xa)] } },
{ rw [Sup_union, Sup_singleton, ← disjoint_iff],
exact b_inf_Sup_s.disjoint_sup_right_of_disjoint_sup_left con.symm },
{ rw [set.mem_union, set.mem_singleton_iff] at hx,
cases hx,
{ exact s_atoms x hx },
{ rw hx,
exact ha } } },
{ intros c hc1 hc2,
refine ⟨⋃₀ c, ⟨complete_lattice.independent_sUnion_of_directed hc2.directed_on
(λ s hs, (hc1 hs).1), _, λ a ha, _⟩, λ _, set.subset_sUnion_of_mem⟩,
{ rw [Sup_sUnion, ← Sup_image, inf_Sup_eq_of_directed_on, supr_eq_bot],
{ intro i,
rw supr_eq_bot,
intro hi,
obtain ⟨x, xc, rfl⟩ := (set.mem_image _ _ _).1 hi,
exact (hc1 xc).2.1 },
{ rw directed_on_image,
refine hc2.directed_on.mono (λ s t, Sup_le_Sup) } },
{ rcases set.mem_sUnion.1 ha with ⟨s, sc, as⟩,
exact (hc1 sc).2.2 a as } }
end⟩
/-- See Theorem 6.6, Călugăreanu -/
theorem is_complemented_of_is_atomistic [is_atomistic α] : is_complemented α :=
is_complemented_of_Sup_atoms_eq_top Sup_atoms_eq_top
theorem is_complemented_iff_is_atomistic : is_complemented α ↔ is_atomistic α :=
begin
split; introsI,
{ exact is_atomistic_of_is_complemented },
{ exact is_complemented_of_is_atomistic }
end
end
|
1268f4a27e2c0e318fc6369bde7c389bdc7102ed | 7007bb645068e0b6b859aab9da7cf5c1c79e98be | /library/init/meta/tactic.lean | 211c2ff85b06300652357454f9d9cfcd44e2c687 | [
"Apache-2.0"
] | permissive | EdAyers/lean | 7d3fb852380bc386545ebc119b7d03c128c3ce1c | be72c8dc527a062e243a408480f487a55b06cb0a | refs/heads/master | 1,624,443,179,694 | 1,592,837,958,000 | 1,592,837,958,000 | 154,972,348 | 0 | 0 | Apache-2.0 | 1,557,768,267,000 | 1,540,649,772,000 | C++ | UTF-8 | Lean | false | false | 71,301 | 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.function init.data.option.basic init.util
import init.control.combinators init.control.monad init.control.alternative init.control.monad_fail
import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment
import init.meta.pexpr init.data.repr init.data.string.basic init.meta.interaction_monad
open native
meta constant tactic_state : Type
universes u v
namespace tactic_state
meta constant env : tactic_state → environment
/-- Format the given tactic state. If `target_lhs_only` is true and the target
is of the form `lhs ~ rhs`, where `~` is a simplification relation,
then only the `lhs` is displayed.
Remark: the parameter `target_lhs_only` is a temporary hack used to implement
the `conv` monad. It will be removed in the future. -/
meta constant to_format (s : tactic_state) (target_lhs_only : bool := ff) : format
/-- Format expression with respect to the main goal in the tactic state.
If the tactic state does not contain any goals, then format expression
using an empty local context. -/
meta constant format_expr : tactic_state → expr → format
meta constant get_options : tactic_state → options
meta constant set_options : tactic_state → options → tactic_state
end tactic_state
meta instance : has_to_format tactic_state :=
⟨tactic_state.to_format⟩
meta instance : has_to_string tactic_state :=
⟨λ s, (to_fmt s).to_string s.get_options⟩
/-- `tactic` is the monad for building tactics.
You use this to:
- View and modify the local goals and hypotheses in the prover's state.
- Invoke type checking and elaboration of terms.
- View and modify the environment.
- Build new tactics out of existing ones such as `simp` and `rewrite`.
-/
@[reducible] meta def tactic := interaction_monad tactic_state
@[reducible] meta def tactic_result := interaction_monad.result tactic_state
namespace tactic
export interaction_monad (hiding failed fail)
/-- Cause the tactic to fail with no error message. -/
meta def failed {α : Type} : tactic α := interaction_monad.failed
meta def fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : tactic α :=
interaction_monad.fail msg
end tactic
namespace tactic_result
export interaction_monad.result
end tactic_result
open tactic
open tactic_result
infixl ` >>=[tactic] `:2 := interaction_monad_bind
infixl ` >>[tactic] `:2 := interaction_monad_seq
meta instance : alternative tactic :=
{ failure := @interaction_monad.failed _,
orelse := @interaction_monad_orelse _,
..interaction_monad.monad }
meta def {u₁ u₂} tactic.up {α : Type u₂} (t : tactic α) : tactic (ulift.{u₁} α) :=
λ s, match t s with
| success a s' := success (ulift.up a) s'
| exception t ref s := exception t ref s
end
meta def {u₁ u₂} tactic.down {α : Type u₂} (t : tactic (ulift.{u₁} α)) : tactic α :=
λ s, match t s with
| success (ulift.up a) s' := success a s'
| exception t ref s := exception t ref s
end
namespace interactive
/-- Typeclass for custom interaction monads, which provides
the information required to convert an interactive-mode
construction to a `tactic` which can actually be executed.
Given a `[monad m]`, `execute_with` explains how to turn a `begin ... end`
block, or a `by ...` statement into a `tactic α` which can actually be
executed. The `inhabited` first argument facilitates the passing of an
optional configuration parameter `config`, using the syntax:
```
begin [custom_monad] with config,
...
end
```
-/
meta class executor (m : Type → Type u) [monad m] :=
(config_type : Type)
[inhabited : inhabited config_type]
(execute_with : config_type → m unit → tactic unit)
attribute [inline] executor.execute_with
@[inline]
meta def executor.execute_explicit (m : Type → Type u)
[monad m] [e : executor m] : m unit → tactic unit :=
executor.execute_with e.inhabited.default
@[inline]
meta def executor.execute_with_explicit (m : Type → Type u)
[monad m] [executor m] : executor.config_type m → m unit → tactic unit :=
executor.execute_with
/-- Default `executor` instance for `tactic`s themselves -/
meta instance : executor tactic :=
{ config_type := unit,
inhabited := ⟨()⟩,
execute_with := λ _, id }
end interactive
namespace tactic
open interaction_monad.result
variables {α : Type u}
/-- Does nothing. -/
meta def skip : tactic unit :=
success ()
/--
`try_core t` acts like `t`, but succeeds even if `t` fails. It returns the
result of `t` if `t` succeeded and `none` otherwise.
-/
meta def try_core (t : tactic α) : tactic (option α) := λ s,
match t s with
| (exception _ _ _) := success none s
| (success a s') := success (some a) s'
end
/--
`try t` acts like `t`, but succeeds even if `t` fails.
-/
meta def try (t : tactic α) : tactic unit := λ s,
match t s with
| (exception _ _ _) := success () s
| (success _ s') := success () s'
end
meta def try_lst : list (tactic unit) → tactic unit
| [] := failed
| (tac :: tacs) := λ s,
match tac s with
| success _ s' := try (try_lst tacs) s'
| exception e p s' :=
match try_lst tacs s' with
| exception _ _ _ := exception e p s'
| r := r
end
end
/--
`fail_if_success t` acts like `t`, but succeeds if `t` fails and fails if `t`
succeeds. Changes made by `t` to the `tactic_state` are preserved only if `t`
succeeds.
-/
meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit := λ s,
match (t s) with
| (success a s) := mk_exception "fail_if_success combinator failed, given tactic succeeded" none s
| (exception _ _ _) := success () s
end
/--
`success_if_fail t` acts like `t`, but succeeds if `t` fails and fails if `t`
succeeds. Changes made by `t` to the `tactic_state` are preserved only if `t`
succeeds.
-/
meta def success_if_fail {α : Type u} (t : tactic α) : tactic unit := λ s,
match t s with
| (success a s) :=
mk_exception "success_if_fail combinator failed, given tactic succeeded" none s
| (exception _ _ _) := success () s
end
open nat
/--
`iterate_at_most n t` iterates `t` `n` times or until `t` fails, returning the
result of each successful iteration.
-/
meta def iterate_at_most : nat → tactic α → tactic (list α)
| 0 t := pure []
| (n + 1) t := do
(some a) ← try_core t | pure [],
as ← iterate_at_most n t,
pure $ a :: as
/--
`iterate_at_most' n t` repeats `t` `n` times or until `t` fails.
-/
meta def iterate_at_most' : nat → tactic unit → tactic unit
| 0 t := skip
| (succ n) t := do
(some _) ← try_core t | skip,
iterate_at_most' n t
/--
`iterate_exactly n t` iterates `t` `n` times, returning the result of
each iteration. If any iteration fails, the whole tactic fails.
-/
meta def iterate_exactly : nat → tactic α → tactic (list α)
| 0 t := pure []
| (n + 1) t := do
a ← t,
as ← iterate_exactly n t,
pure $ a ::as
/--
`iterate_exactly' n t` executes `t` `n` times. If any iteration fails, the whole
tactic fails.
-/
meta def iterate_exactly' : nat → tactic unit → tactic unit
| 0 t := skip
| (n + 1) t := t *> iterate_exactly' n t
/--
`iterate t` repeats `t` 100.000 times or until `t` fails, returning the
result of each iteration.
-/
meta def iterate : tactic α → tactic (list α) :=
iterate_at_most 100000
/--
`iterate' t` repeats `t` 100.000 times or until `t` fails.
-/
meta def iterate' : tactic unit → tactic unit :=
iterate_at_most' 100000
meta def returnopt (e : option α) : tactic α :=
λ s, match e with
| (some a) := success a s
| none := mk_exception "failed" none s
end
meta instance opt_to_tac : has_coe (option α) (tactic α) :=
⟨returnopt⟩
/-- Decorate t's exceptions with msg. -/
meta def decorate_ex (msg : format) (t : tactic α) : tactic α :=
λ s, result.cases_on (t s)
success
(λ opt_thunk,
match opt_thunk with
| some e := exception (some (λ u, msg ++ format.nest 2 (format.line ++ e u)))
| none := exception none
end)
/-- Set the tactic_state. -/
@[inline] meta def write (s' : tactic_state) : tactic unit :=
λ s, success () s'
/-- Get the tactic_state. -/
@[inline] meta def read : tactic tactic_state :=
λ s, success s s
meta def get_options : tactic options :=
do s ← read, return s.get_options
meta def set_options (o : options) : tactic unit :=
do s ← read, write (s.set_options o)
meta def save_options {α : Type} (t : tactic α) : tactic α :=
do o ← get_options,
a ← t,
set_options o,
return a
meta def returnex {α : Type} (e : exceptional α) : tactic α :=
λ s, match e with
| exceptional.success a := success a s
| exceptional.exception f :=
match get_options s with
| success opt _ := exception (some (λ u, f opt)) none s
| exception _ _ _ := exception (some (λ u, f options.mk)) none s
end
end
meta instance ex_to_tac {α : Type} : has_coe (exceptional α) (tactic α) :=
⟨returnex⟩
end tactic
meta def tactic_format_expr (e : expr) : tactic format :=
do s ← tactic.read, return (tactic_state.format_expr s e)
meta class has_to_tactic_format (α : Type u) :=
(to_tactic_format : α → tactic format)
meta instance : has_to_tactic_format expr :=
⟨tactic_format_expr⟩
meta def tactic.pp {α : Type u} [has_to_tactic_format α] : α → tactic format :=
has_to_tactic_format.to_tactic_format
open tactic format
meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (list α) :=
⟨λ l, to_fmt <$> l.mmap pp⟩
meta instance (α : Type u) (β : Type v) [has_to_tactic_format α] [has_to_tactic_format β] :
has_to_tactic_format (α × β) :=
⟨λ ⟨a, b⟩, to_fmt <$> (prod.mk <$> pp a <*> pp b)⟩
meta def option_to_tactic_format {α : Type u} [has_to_tactic_format α] : option α → tactic format
| (some a) := do fa ← pp a, return (to_fmt "(some " ++ fa ++ ")")
| none := return "none"
meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (option α) :=
⟨option_to_tactic_format⟩
meta instance {α} (a : α) : has_to_tactic_format (reflected a) :=
⟨λ h, pp h.to_expr⟩
@[priority 10] meta instance has_to_format_to_has_to_tactic_format (α : Type) [has_to_format α] : has_to_tactic_format α :=
⟨(λ x, return x) ∘ to_fmt⟩
namespace tactic
open tactic_state
meta def get_env : tactic environment :=
do s ← read,
return $ env s
meta def get_decl (n : name) : tactic declaration :=
do s ← read,
(env s).get n
meta def trace {α : Type u} [has_to_tactic_format α] (a : α) : tactic unit :=
do fmt ← pp a,
return $ _root_.trace_fmt fmt (λ u, ())
meta def trace_call_stack : tactic unit :=
assume state, _root_.trace_call_stack (success () state)
meta def timetac {α : Type u} (desc : string) (t : thunk (tactic α)) : tactic α :=
λ s, timeit desc (t () s)
meta def trace_state : tactic unit :=
do s ← read,
trace $ to_fmt s
/-- A parameter representing how aggressively definitions should be unfolded when trying to decide if two terms match, unify or are definitionally equal.
By default, theorem declarations are never unfolded.
- `all` will unfold everything, including macros and theorems. Except projection macros.
- `semireducible` will unfold everything except theorems and definitions tagged as irreducible.
- `instances` will unfold all class instance definitions and definitions tagged with reducible.
- `reducible` will only unfold definitions tagged with the `reducible` attribute.
- `none` will never unfold anything.
[NOTE] You are not allowed to tag a definition with more than one of `reducible`, `irreducible`, `semireducible` attributes.
[NOTE] there is a config flag `m_unfold_lemmas`that will make it unfold theorems.
-/
inductive transparency
| all | semireducible | instances | reducible | none
export transparency (reducible semireducible)
/-- (eval_expr α e) evaluates 'e' IF 'e' has type 'α'. -/
meta constant eval_expr (α : Type u) [reflected α] : expr → tactic α
/-- Return the partial term/proof constructed so far. Note that the resultant expression
may contain variables that are not declarate in the current main goal. -/
meta constant result : tactic expr
/-- Display the partial term/proof constructed so far. This tactic is *not* equivalent to
`do { r ← result, s ← read, return (format_expr s r) }` because this one will format the result with respect
to the current goal, and trace_result will do it with respect to the initial goal. -/
meta constant format_result : tactic format
/-- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/
meta constant target : tactic expr
meta constant intro_core : name → tactic expr
meta constant intron : nat → tactic unit
/-- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/
meta constant clear : expr → tactic unit
/-- `revert_lst : list expr → tactic nat` is the reverse of `intron`. It takes a local constant `c` and puts it back as bound by a `pi` or `elet` of the main target.
If there are other local constants that depend on `c`, these are also reverted. Because of this, the `nat` that is returned is the actual number of reverted local constants.
Example: with `x : ℕ, h : P(x) ⊢ T(x)`, `revert_lst [x]` returns `2` and produces the state ` ⊢ Π x, P(x) → T(x)`.
-/
meta constant revert_lst : list expr → tactic nat
/-- Return `e` in weak head normal form with respect to the given transparency setting.
If `unfold_ginductive` is `tt`, then nested and/or mutually recursive inductive datatype constructors
and types are unfolded. Recall that nested and mutually recursive inductive datatype declarations
are compiled into primitive datatypes accepted by the Kernel. -/
meta constant whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic expr
/-- (head) eta expand the given expression. `f : α → β` head-eta-expands to `λ a, f a`. If `f` isn't a function then it just returns `f`. -/
meta constant head_eta_expand : expr → tactic expr
/-- (head) beta reduction. `(λ x, B) c` reduces to `B[x/c]`. -/
meta constant head_beta : expr → tactic expr
/-- (head) zeta reduction. Reduction of let bindings at the head of the expression. `let x : a := b in c` reduces to `c[x/b]`. -/
meta constant head_zeta : expr → tactic expr
/-- Zeta reduction. Reduction of let bindings. `let x : a := b in c` reduces to `c[x/b]`. -/
meta constant zeta : expr → tactic expr
/-- (head) eta reduction. `(λ x, f x)` reduces to `f`. -/
meta constant head_eta : expr → tactic expr
/-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/
meta constant unify (t s : expr) (md := semireducible) (approx := ff) : tactic unit
/-- Similar to `unify`, but it treats metavariables as constants. -/
meta constant is_def_eq (t s : expr) (md := semireducible) (approx := ff) : tactic unit
/-- Infer the type of the given expression.
Remark: transparency does not affect type inference -/
meta constant infer_type : expr → tactic expr
/-- Get the `local_const` expr for the given `name`. -/
meta constant get_local : name → tactic expr
/-- Resolve a name using the current local context, environment, aliases, etc. -/
meta constant resolve_name : name → tactic pexpr
/-- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/
meta constant local_context : tactic (list expr)
/-- Get a fresh name that is guaranteed to not be in use in the local context.
If `n` is provided and `n` is not in use, then `n` is returned.
Otherwise a number `i` is appended to give `"n_i"`.
-/
meta constant get_unused_name (n : name := `_x) (i : option nat := none) : tactic name
/-- Helper tactic for creating simple applications where some arguments are inferred using
type inference.
Example, given
```
rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop
nat : Type
real : Type
vec.{l} : Pi (α : Type l) (n : nat), Type.{l1}
f g : Pi (n : nat), vec real n
```
then
```
mk_app_core semireducible "rel" [f, g]
```
returns the application
```
rel.{1 2} nat (fun n : nat, vec real n) f g
```
The unification constraints due to type inference are solved using the transparency `md`.
-/
meta constant mk_app (fn : name) (args : list expr) (md := semireducible) : tactic expr
/-- Similar to `mk_app`, but allows to specify which arguments are explicit/implicit.
Example, given `(a b : nat)` then
```
mk_mapp "ite" [some (a > b), none, none, some a, some b]
```
returns the application
```
@ite.{1} (a > b) (nat.decidable_gt a b) nat a b
```
-/
meta constant mk_mapp (fn : name) (args : list (option expr)) (md := semireducible) : tactic expr
/-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/
meta constant mk_congr_arg : expr → expr → tactic expr
/-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/
meta constant mk_congr_fun : expr → expr → tactic expr
/-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/
meta constant mk_congr : expr → expr → tactic expr
/-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/
meta constant mk_eq_refl : expr → tactic expr
/-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/
meta constant mk_eq_symm : expr → tactic expr
/-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/
meta constant mk_eq_trans : expr → expr → tactic expr
/-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/
meta constant mk_eq_mp : expr → expr → tactic expr
/-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/
meta constant mk_eq_mpr : expr → expr → tactic expr
/- Given a local constant t, if t has type (lhs = rhs) apply substitution.
Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t).
The tactic fails if the given expression is not a local constant. -/
meta constant subst_core : expr → tactic unit
/-- Close the current goal using `e`. Fail is the type of `e` is not definitionally equal to
the target type. -/
meta constant exact (e : expr) (md := semireducible) : tactic unit
/-- Elaborate the given quoted expression with respect to the current main goal.
Note that this means that any implicit arguments for the given `pexpr` will be applied with fresh metavariables.
If `allow_mvars` is tt, then metavariables are tolerated and become new goals if `subgoals` is tt. -/
meta constant to_expr (q : pexpr) (allow_mvars := tt) (subgoals := tt) : tactic expr
/-- Return true if the given expression is a type class. -/
meta constant is_class : expr → tactic bool
/-- Try to create an instance of the given type class. -/
meta constant mk_instance : expr → tactic expr
/-- Change the target of the main goal.
The input expression must be definitionally equal to the current target.
If `check` is `ff`, then the tactic does not check whether `e`
is definitionally equal to the current target. If it is not,
then the error will only be detected by the kernel type checker. -/
meta constant change (e : expr) (check : bool := tt): tactic unit
/-- `assert_core H T`, adds a new goal for T, and change target to `T -> target`. -/
meta constant assert_core : name → expr → tactic unit
/-- `assertv_core H T P`, change target to (T -> target) if P has type T. -/
meta constant assertv_core : name → expr → expr → tactic unit
/-- `define_core H T`, adds a new goal for T, and change target to `let H : T := ?M in target` in the current goal. -/
meta constant define_core : name → expr → tactic unit
/-- `definev_core H T P`, change target to `let H : T := P in target` if P has type T. -/
meta constant definev_core : name → expr → expr → tactic unit
/-- Rotate goals to the left. That is, `rotate_left 1` takes the main goal and puts it to the back of the subgoal list. -/
meta constant rotate_left : nat → tactic unit
/-- Gets a list of metavariables, one for each goal. -/
meta constant get_goals : tactic (list expr)
/-- Replace the current list of goals with the given one. Each expr in the list should be a metavariable. Any assigned metavariables will be ignored.-/
meta constant set_goals : list expr → tactic unit
/-- How to order the new goals made from an `apply` tactic.
Supposing we were applying `e : ∀ (a:α) (p : P(a)), Q`
- `non_dep_first` would produce goals `⊢ P(?m)`, `⊢ α`. It puts the P goal at the front because none of the arguments after `p` in `e` depend on `p`. It doesn't matter what the result `Q` depends on.
- `non_dep_only` would produce goal `⊢ P(?m)`.
- `all` would produce goals `⊢ α`, `⊢ P(?m)`.
-/
inductive new_goals
| non_dep_first | non_dep_only | all
/-- Configuration options for the `apply` tactic.
- `md` sets how aggressively definitions are unfolded.
- `new_goals` is the strategy for ordering new goals.
- `instances` if `tt`, then `apply` tries to synthesize unresolved `[...]` arguments using type class resolution.
- `auto_param` if `tt`, then `apply` tries to synthesize unresolved `(h : p . tac_id)` arguments using tactic `tac_id`.
- `opt_param` if `tt`, then `apply` tries to synthesize unresolved `(a : t := v)` arguments by setting them to `v`.
- `unify` if `tt`, then `apply` is free to assign existing metavariables in the goal when solving unification constraints.
For example, in the goal `|- ?x < succ 0`, the tactic `apply succ_lt_succ` succeeds with the default configuration,
but `apply_with succ_lt_succ {unify := ff}` doesn't since it would require Lean to assign `?x` to `succ ?y` where
`?y` is a fresh metavariable.
-/
structure apply_cfg :=
(md := semireducible)
(approx := tt)
(new_goals := new_goals.non_dep_first)
(instances := tt)
(auto_param := tt)
(opt_param := tt)
(unify := tt)
/-- Apply the expression `e` to the main goal, the unification is performed using the transparency mode in `cfg`.
Supposing `e : Π (a₁:α₁) ... (aₙ:αₙ), P(a₁,...,aₙ)` and the target is `Q`, `apply` will attempt to unify `Q` with `P(?a₁,...?aₙ)`.
All of the metavariables that are not assigned are added as new metavariables.
If `cfg.approx` is `tt`, then fallback to first-order unification, and approximate context during unification.
`cfg.new_goals` specifies which unassigned metavariables become new goals, and their order.
If `cfg.instances` is `tt`, then use type class resolution to instantiate unassigned meta-variables.
The fields `cfg.auto_param` and `cfg.opt_param` are ignored by this tactic (See `tactic.apply`).
It returns a list of all introduced meta variables and the parameter name associated with them, even the assigned ones. -/
meta constant apply_core (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr))
/- Create a fresh meta universe variable. -/
meta constant mk_meta_univ : tactic level
/- Create a fresh meta-variable with the given type.
The scope of the new meta-variable is the local context of the main goal. -/
meta constant mk_meta_var : expr → tactic expr
/-- Return the value assigned to the given universe meta-variable.
Fail if argument is not an universe meta-variable or if it is not assigned. -/
meta constant get_univ_assignment : level → tactic level
/-- Return the value assigned to the given meta-variable.
Fail if argument is not a meta-variable or if it is not assigned. -/
meta constant get_assignment : expr → tactic expr
/-- Return true if the given meta-variable is assigned.
Fail if argument is not a meta-variable. -/
meta constant is_assigned : expr → tactic bool
/-- Make a name that is guaranteed to be unique. Eg `_fresh.1001.4667`. These will be different for each run of the tactic. -/
meta constant mk_fresh_name : tactic name
/-- Induction on `h` using recursor `rec`, names for the new hypotheses
are retrieved from `ns`. If `ns` does not have sufficient names, then use the internal binder names
in the recursor.
It returns for each new goal the name of the constructor (if `rec_name` is a builtin recursor),
a list of new hypotheses, and a list of substitutions for hypotheses
depending on `h`. The substitutions map internal names to their replacement terms. If the
replacement is again a hypothesis the user name stays the same. The internal names are only valid
in the original goal, not in the type context of the new goal.
Remark: if `rec_name` is not a builtin recursor, we use parameter names of `rec_name` instead of
constructor names.
If `rec` is none, then the type of `h` is inferred, if it is of the form `C ...`, tactic uses `C.rec` -/
meta constant induction (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic (list (name × list expr × list (name × expr)))
/-- Apply `cases_on` recursor, names for the new hypotheses are retrieved from `ns`.
`h` must be a local constant. It returns for each new goal the name of the constructor, a list of new hypotheses, and a list of
substitutions for hypotheses depending on `h`. The number of new goals may be smaller than the
number of constructors. Some goals may be discarded when the indices to not match.
See `induction` for information on the list of substitutions.
The `cases` tactic is implemented using this one, and it relaxes the restriction of `h`. -/
meta constant cases_core (h : expr) (ns : list name := []) (md := semireducible) : tactic (list (name × list expr × list (name × expr)))
/-- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/
meta constant destruct (e : expr) (md := semireducible) : tactic unit
/-- Generalizes the target with respect to `e`. -/
meta constant generalize (e : expr) (n : name := `_x) (md := semireducible) : tactic unit
/-- instantiate assigned metavariables in the given expression -/
meta constant instantiate_mvars : expr → tactic expr
/-- Add the given declaration to the environment -/
meta constant add_decl : declaration → tactic unit
/--
Changes the environment to the `new_env`.
The new environment does not need to be a descendant of the old one.
Use with care.
-/
meta constant set_env_core : environment → tactic unit
/-- Changes the environment to the `new_env`. `new_env` needs to be a descendant from the current environment. -/
meta constant set_env : environment → tactic unit
/-- `doc_string env d k` returns the doc string for `d` (if available) -/
meta constant doc_string : name → tactic string
/-- Set the docstring for the given declaration. -/
meta constant add_doc_string : name → string → tactic unit
/--
Create an auxiliary definition with name `c` where `type` and `value` may contain local constants and
meta-variables. This function collects all dependencies (universe parameters, universe metavariables,
local constants (aka hypotheses) and metavariables).
It updates the environment in the tactic_state, and returns an expression of the form
(c.{l_1 ... l_n} a_1 ... a_m)
where l_i's and a_j's are the collected dependencies.
-/
meta constant add_aux_decl (c : name) (type : expr) (val : expr) (is_lemma : bool) : tactic expr
/-- Returns a list of all top-level (`/-! ... -/`) docstrings in the active module and imported ones.
The returned object is a list of modules, indexed by `(some filename)` for imported modules
and `none` for the active one, where each module in the list is paired with a list
of `(position_in_file, docstring)` pairs. -/
meta constant olean_doc_strings : tactic (list (option string × (list (pos × string))))
/-- Returns a list of docstrings in the active module. An entry in the list can be either:
- a top-level (`/-! ... -/`) docstring, represented as `(none, docstring)`
- a declaration-specific (`/-- ... -/`) docstring, represented as `(some decl_name, docstring)` -/
meta def module_doc_strings : tactic (list (option name × string)) :=
do
/- Obtain a list of top-level docs in current module. -/
mod_docs ← olean_doc_strings,
let mod_docs: list (list (option name × string)) :=
mod_docs.filter_map (λ d,
if d.1.is_none
then some (d.2.map
(λ pos_doc, ⟨none, pos_doc.2⟩))
else none),
let mod_docs := mod_docs.join,
/- Obtain list of declarations in current module. -/
e ← get_env,
let decls := environment.fold e ([]: list name)
(λ d acc, let n := d.to_name in
if (environment.decl_olean e n).is_none
then n::acc else acc),
/- Map declarations to those which have docstrings. -/
decls ← decls.mfoldl (λa n,
(doc_string n >>=
λ doc, pure $ (some n, doc) :: a)
<|> pure a) [],
pure (mod_docs ++ decls)
/-- Set attribute `attr_name` for constant `c_name` with the given priority.
If the priority is none, then use default -/
meta constant set_basic_attribute (attr_name : name) (c_name : name) (persistent := ff) (prio : option nat := none) : tactic unit
/-- `unset_attribute attr_name c_name` -/
meta constant unset_attribute : name → name → tactic unit
/-- `has_attribute attr_name c_name` succeeds if the declaration `decl_name`
has the attribute `attr_name`. The result is the priority and whether or not
the attribute is persistent. -/
meta constant has_attribute : name → name → tactic (bool × nat)
/-- `copy_attribute attr_name c_name p d_name` copy attribute `attr_name` from
`src` to `tgt` if it is defined for `src`; make it persistent if `p` is `tt`;
if `p` is `none`, the copied attribute is made persistent iff it is persistent on `src` -/
meta def copy_attribute (attr_name : name) (src : name) (tgt : name) (p : option bool := none) : tactic unit :=
try $ do
(p', prio) ← has_attribute attr_name src,
let p := p.get_or_else p',
set_basic_attribute attr_name tgt p (some prio)
/-- Name of the declaration currently being elaborated. -/
meta constant decl_name : tactic name
/-- `save_type_info e ref` save (typeof e) at position associated with ref -/
meta constant save_type_info {elab : bool} : expr → expr elab → tactic unit
meta constant save_info_thunk : pos → (unit → format) → tactic unit
/-- Return list of currently open namespaces -/
meta constant open_namespaces : tactic (list name)
/-- Return tt iff `t` "occurs" in `e`. The occurrence checking is performed using
keyed matching with the given transparency setting.
We say `t` occurs in `e` by keyed matching iff there is a subterm `s`
s.t. `t` and `s` have the same head, and `is_def_eq t s md`
The main idea is to minimize the number of `is_def_eq` checks
performed. -/
meta constant kdepends_on (e t : expr) (md := reducible) : tactic bool
/-- Abstracts all occurrences of the term `t` in `e` using keyed matching.
If `unify` is `ff`, then matching is used instead of unification.
That is, metavariables occurring in `e` are not assigned. -/
meta constant kabstract (e t : expr) (md := reducible) (unify := tt) : tactic expr
/-- Blocks the execution of the current thread for at least `msecs` milliseconds.
This tactic is used mainly for debugging purposes. -/
meta constant sleep (msecs : nat) : tactic unit
/-- Type check `e` with respect to the current goal.
Fails if `e` is not type correct. -/
meta constant type_check (e : expr) (md := semireducible) : tactic unit
open list nat
/-- A `tag` is a list of `names`. These are attached to goals to help tactics track them.-/
def tag : Type := list name
/-- Enable/disable goal tagging. -/
meta constant enable_tags (b : bool) : tactic unit
/-- Return tt iff goal tagging is enabled. -/
meta constant tags_enabled : tactic bool
/-- Tag goal `g` with tag `t`. It does nothing if goal tagging is disabled.
Remark: `set_goal g []` removes the tag -/
meta constant set_tag (g : expr) (t : tag) : tactic unit
/-- Return tag associated with `g`. Return `[]` if there is no tag. -/
meta constant get_tag (g : expr) : tactic tag
/-- By default, Lean only considers local instances in the header of declarations.
This has two main benefits.
1- Results produced by the type class resolution procedure can be easily cached.
2- The set of local instances does not have to be recomputed.
This approach has the following disadvantages:
1- Frozen local instances cannot be reverted.
2- Local instances defined inside of a declaration are not considered during type
class resolution.
This tactic resets the set of local instances. After executing this tactic,
the set of local instances will be recomputed and the cache will be frequently
reset. Note that, the cache is still used when executing a single tactic that
may generate many type class resolution problems (e.g., `simp`). -/
meta constant unfreeze_local_instances : tactic unit
/--
Freeze the current set of local instances.
-/
meta constant freeze_local_instances : tactic unit
/- Return the list of frozen local instances. Return `none` if local instances were not frozen. -/
meta constant frozen_local_instances : tactic (option (list expr))
meta def induction' (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic unit :=
induction h ns rec md >> return ()
/-- Remark: set_goals will erase any solved goal -/
meta def cleanup : tactic unit :=
get_goals >>= set_goals
/-- Auxiliary definition used to implement begin ... end blocks -/
meta def step {α : Type u} (t : tactic α) : tactic unit :=
t >>[tactic] cleanup
meta def istep {α : Type u} (line0 col0 : ℕ) (line col : ℕ) (t : tactic α) : tactic unit :=
λ s, (@scope_trace _ line col (λ _, step t s)).clamp_pos line0 line col
meta def is_prop (e : expr) : tactic bool :=
do t ← infer_type e,
return (t = `(Prop))
/-- Return true iff n is the name of declaration that is a proposition. -/
meta def is_prop_decl (n : name) : tactic bool :=
do env ← get_env,
d ← env.get n,
t ← return $ d.type,
is_prop t
meta def is_proof (e : expr) : tactic bool :=
infer_type e >>= is_prop
meta def whnf_no_delta (e : expr) : tactic expr :=
whnf e transparency.none
/-- Return `e` in weak head normal form with respect to the given transparency setting,
or `e` head is a generalized constructor or inductive datatype. -/
meta def whnf_ginductive (e : expr) (md := semireducible) : tactic expr :=
whnf e md ff
meta def whnf_target : tactic unit :=
target >>= whnf >>= change
/-- Change the target of the main goal.
The input expression must be definitionally equal to the current target.
The tactic does not check whether `e`
is definitionally equal to the current target. The error will only be detected by the kernel type checker. -/
meta def unsafe_change (e : expr) : tactic unit :=
change e ff
/-- Pi or elet introduction.
Given the tactic state `⊢ Π x : α, Y`, ``intro `hello`` will produce the state `hello : α ⊢ Y[x/hello]`.
Returns the new local constant. Similarly for `elet` expressions.
If the target is not a Pi or elet it will try to put it in WHNF.
-/
meta def intro (n : name) : tactic expr :=
do t ← target,
if expr.is_pi t ∨ expr.is_let t then intro_core n
else whnf_target >> intro_core n
/-- Like `intro` except the name is derived from the bound name in the Π. -/
meta def intro1 : tactic expr :=
intro `_
/-- Repeatedly apply `intro1` and return the list of new local constants in order of introduction.-/
meta def intros : tactic (list expr) :=
do t ← target,
match t with
| expr.pi _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs)
| expr.elet _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs)
| _ := return []
end
/-- Same as `intros`, except with the given names for the new hypotheses. Use the name ```_``` to instead use the binder's name.-/
meta def intro_lst : list name → tactic (list expr)
| [] := return []
| (n::ns) := do H ← intro n, Hs ← intro_lst ns, return (H :: Hs)
/-- Introduces new hypotheses with forward dependencies. -/
meta def intros_dep : tactic (list expr) :=
do t ← target,
let proc (b : expr) :=
if b.has_var_idx 0 then
do h ← intro1, hs ← intros_dep, return (h::hs)
else
-- body doesn't depend on new hypothesis
return [],
match t with
| expr.pi _ _ _ b := proc b
| expr.elet _ _ _ b := proc b
| _ := return []
end
meta def introv : list name → tactic (list expr)
| [] := intros_dep
| (n::ns) := do hs ← intros_dep, h ← intro n, hs' ← introv ns, return (hs ++ h :: hs')
/--
`intron' n` introduces `n` hypotheses and returns the resulting local
constants. Fails if there are not at least `n` arguments to introduce. If you do
not need the return value, use `intron`.
-/
meta def intron' : ℕ → tactic (list expr)
| 0 := pure []
| (n + 1) := do
h ← intro1,
hs ← intron' n,
pure $ h :: hs
/-- Returns n fully qualified if it refers to a constant, or else fails. -/
meta def resolve_constant (n : name) : tactic name :=
do (expr.const n _) ← resolve_name n,
pure n
meta def to_expr_strict (q : pexpr) : tactic expr :=
to_expr q
/--
Example: with `x : ℕ, h : P(x) ⊢ T(x)`, `revert x` returns `2` and produces the state ` ⊢ Π x, P(x) → T(x)`.
-/
meta def revert (l : expr) : tactic nat :=
revert_lst [l]
/- Revert "all" hypotheses. Actually, the tactic only reverts
hypotheses occurring after the last frozen local instance.
Recall that frozen local instances cannot be reverted.
We can use `unfreeze_local_instances` to workaround this limitation. -/
meta def revert_all : tactic nat :=
do lctx ← local_context,
lis ← frozen_local_instances,
match lis with
| none := revert_lst lctx
| some [] := revert_lst lctx
/- `hi` is the last local instance. We shoul truncate `lctx` at `hi`. -/
| some (hi::his) := revert_lst $ lctx.foldl (λ r h, if h.local_uniq_name = hi.local_uniq_name then [] else h :: r) []
end
meta def clear_lst : list name → tactic unit
| [] := skip
| (n::ns) := do H ← get_local n, clear H, clear_lst ns
meta def match_not (e : expr) : tactic expr :=
match (expr.is_not e) with
| (some a) := return a
| none := fail "expression is not a negation"
end
meta def match_and (e : expr) : tactic (expr × expr) :=
match (expr.is_and e) with
| (some (α, β)) := return (α, β)
| none := fail "expression is not a conjunction"
end
meta def match_or (e : expr) : tactic (expr × expr) :=
match (expr.is_or e) with
| (some (α, β)) := return (α, β)
| none := fail "expression is not a disjunction"
end
meta def match_iff (e : expr) : tactic (expr × expr) :=
match (expr.is_iff e) with
| (some (lhs, rhs)) := return (lhs, rhs)
| none := fail "expression is not an iff"
end
meta def match_eq (e : expr) : tactic (expr × expr) :=
match (expr.is_eq e) with
| (some (lhs, rhs)) := return (lhs, rhs)
| none := fail "expression is not an equality"
end
meta def match_ne (e : expr) : tactic (expr × expr) :=
match (expr.is_ne e) with
| (some (lhs, rhs)) := return (lhs, rhs)
| none := fail "expression is not a disequality"
end
meta def match_heq (e : expr) : tactic (expr × expr × expr × expr) :=
do match (expr.is_heq e) with
| (some (α, lhs, β, rhs)) := return (α, lhs, β, rhs)
| none := fail "expression is not a heterogeneous equality"
end
meta def match_refl_app (e : expr) : tactic (name × expr × expr) :=
do env ← get_env,
match (environment.is_refl_app env e) with
| (some (R, lhs, rhs)) := return (R, lhs, rhs)
| none := fail "expression is not an application of a reflexive relation"
end
meta def match_app_of (e : expr) (n : name) : tactic (list expr) :=
guard (expr.is_app_of e n) >> return e.get_app_args
meta def get_local_type (n : name) : tactic expr :=
get_local n >>= infer_type
meta def trace_result : tactic unit :=
format_result >>= trace
meta def rexact (e : expr) : tactic unit :=
exact e reducible
meta def any_hyp_aux {α : Type} (f : expr → tactic α) : list expr → tactic α
| [] := failed
| (h :: hs) := f h <|> any_hyp_aux hs
meta def any_hyp {α : Type} (f : expr → tactic α) : tactic α :=
local_context >>= any_hyp_aux f
/-- `find_same_type t es` tries to find in es an expression with type definitionally equal to t -/
meta def find_same_type : expr → list expr → tactic expr
| e [] := failed
| e (H :: Hs) :=
do t ← infer_type H,
(unify e t >> return H) <|> find_same_type e Hs
meta def find_assumption (e : expr) : tactic expr :=
do ctx ← local_context, find_same_type e ctx
meta def assumption : tactic unit :=
do { ctx ← local_context,
t ← target,
H ← find_same_type t ctx,
exact H }
<|> fail "assumption tactic failed"
meta def save_info (p : pos) : tactic unit :=
do s ← read,
tactic.save_info_thunk p (λ _, tactic_state.to_format s)
notation `‹` p `›` := (by assumption : p)
/-- Swap first two goals, do nothing if tactic state does not have at least two goals. -/
meta def swap : tactic unit :=
do gs ← get_goals,
match gs with
| (g₁ :: g₂ :: rs) := set_goals (g₂ :: g₁ :: rs)
| e := skip
end
/-- `assert h t`, adds a new goal for t, and the hypothesis `h : t` in the current goal. -/
meta def assert (h : name) (t : expr) : tactic expr :=
do assert_core h t, swap, e ← intro h, swap, return e
/-- `assertv h t v`, adds the hypothesis `h : t` in the current goal if v has type t. -/
meta def assertv (h : name) (t : expr) (v : expr) : tactic expr :=
assertv_core h t v >> intro h
/-- `define h t`, adds a new goal for t, and the hypothesis `h : t := ?M` in the current goal. -/
meta def define (h : name) (t : expr) : tactic expr :=
do define_core h t, swap, e ← intro h, swap, return e
/-- `definev h t v`, adds the hypothesis (h : t := v) in the current goal if v has type t. -/
meta def definev (h : name) (t : expr) (v : expr) : tactic expr :=
definev_core h t v >> intro h
/-- Add `h : t := pr` to the current goal -/
meta def pose (h : name) (t : option expr := none) (pr : expr) : tactic expr :=
let dv := λt, definev h t pr in
option.cases_on t (infer_type pr >>= dv) dv
/-- Add `h : t` to the current goal, given a proof `pr : t` -/
meta def note (h : name) (t : option expr := none) (pr : expr) : tactic expr :=
let dv := λt, assertv h t pr in
option.cases_on t (infer_type pr >>= dv) dv
/-- Return the number of goals that need to be solved -/
meta def num_goals : tactic nat :=
do gs ← get_goals,
return (length gs)
/-- Rotate the goals to the right by `n`. That is, take the goal at the back and push it to the front `n` times.
[NOTE] We have to provide the instance argument `[has_mod nat]` because
mod for nat was not defined yet -/
meta def rotate_right (n : nat) [has_mod nat] : tactic unit :=
do ng ← num_goals,
if ng = 0 then skip
else rotate_left (ng - n % ng)
/-- Rotate the goals to the left by `n`. That is, put the main goal to the back `n` times. -/
meta def rotate : nat → tactic unit :=
rotate_left
private meta def repeat_aux (t : tactic unit) : list expr → list expr → tactic unit
| [] r := set_goals r.reverse
| (g::gs) r := do
ok ← try_core (set_goals [g] >> t),
match ok with
| none := repeat_aux gs (g::r)
| _ := do
gs' ← get_goals,
repeat_aux (gs' ++ gs) r
end
/-- This tactic is applied to each goal. If the application succeeds,
the tactic is applied recursively to all the generated subgoals until it eventually fails.
The recursion stops in a subgoal when the tactic has failed to make progress.
The tactic `repeat` never fails. -/
meta def repeat (t : tactic unit) : tactic unit :=
do gs ← get_goals, repeat_aux t gs []
/-- `first [t_1, ..., t_n]` applies the first tactic that doesn't fail.
The tactic fails if all t_i's fail. -/
meta def first {α : Type u} : list (tactic α) → tactic α
| [] := fail "first tactic failed, no more alternatives"
| (t::ts) := t <|> first ts
/-- Applies the given tactic to the main goal and fails if it is not solved. -/
meta def solve1 {α} (tac : tactic α) : tactic α :=
do gs ← get_goals,
match gs with
| [] := fail "solve1 tactic failed, there isn't any goal left to focus"
| (g::rs) :=
do set_goals [g],
a ← tac,
gs' ← get_goals,
match gs' with
| [] := set_goals rs >> pure a
| gs := fail "solve1 tactic failed, focused goal has not been solved"
end
end
/-- `solve [t_1, ... t_n]` applies the first tactic that solves the main goal. -/
meta def solve {α} (ts : list (tactic α)) : tactic α :=
first $ map solve1 ts
private meta def focus_aux {α} : list (tactic α) → list expr → list expr → tactic (list α)
| [] [] rs := set_goals rs *> pure []
| (t::ts) [] rs := fail "focus' tactic failed, insufficient number of goals"
| tts (g::gs) rs :=
mcond (is_assigned g) (focus_aux tts gs rs) $
do set_goals [g],
t::ts ← pure tts | fail "focus' tactic failed, insufficient number of tactics",
a ← t,
rs' ← get_goals,
as ← focus_aux ts gs (rs ++ rs'),
pure $ a :: as
/--
`focus [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of
goals is not n. Returns the results of t_i (one per goal).
-/
meta def focus {α} (ts : list (tactic α)) : tactic (list α) :=
do gs ← get_goals, focus_aux ts gs []
private meta def focus'_aux : list (tactic unit) → list expr → list expr → tactic unit
| [] [] rs := set_goals rs
| (t::ts) [] rs := fail "focus tactic failed, insufficient number of goals"
| tts (g::gs) rs :=
mcond (is_assigned g) (focus'_aux tts gs rs) $
do set_goals [g],
t::ts ← pure tts | fail "focus tactic failed, insufficient number of tactics",
t,
rs' ← get_goals,
focus'_aux ts gs (rs ++ rs')
/-- `focus' [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of goals is not n. -/
meta def focus' (ts : list (tactic unit)) : tactic unit :=
do gs ← get_goals, focus'_aux ts gs []
meta def focus1 {α} (tac : tactic α) : tactic α :=
do g::gs ← get_goals,
match gs with
| [] := tac
| _ := do
set_goals [g],
a ← tac,
gs' ← get_goals,
set_goals (gs' ++ gs),
return a
end
private meta def all_goals_core {α} (tac : tactic α)
: list expr → list expr → tactic (list α)
| [] ac := set_goals ac *> pure []
| (g :: gs) ac :=
mcond (is_assigned g) (all_goals_core gs ac) $
do set_goals [g],
a ← tac,
new_gs ← get_goals,
as ← all_goals_core gs (ac ++ new_gs),
pure $ a :: as
/--
Apply the given tactic to all goals. Return one result per goal.
-/
meta def all_goals {α} (tac : tactic α) : tactic (list α) :=
do gs ← get_goals,
all_goals_core tac gs []
private meta def all_goals'_core (tac : tactic unit) : list expr → list expr → tactic unit
| [] ac := set_goals ac
| (g :: gs) ac :=
mcond (is_assigned g) (all_goals'_core gs ac) $
do set_goals [g],
tac,
new_gs ← get_goals,
all_goals'_core gs (ac ++ new_gs)
/-- Apply the given tactic to all goals. -/
meta def all_goals' (tac : tactic unit) : tactic unit :=
do gs ← get_goals,
all_goals'_core tac gs []
private meta def any_goals_core {α} (tac : tactic α) : list expr → list expr → bool → tactic (list (option α))
| [] ac progress := guard progress *> set_goals ac *> pure []
| (g :: gs) ac progress :=
mcond (is_assigned g) (any_goals_core gs ac progress) $
do set_goals [g],
res ← try_core tac,
new_gs ← get_goals,
ress ← any_goals_core gs (ac ++ new_gs) (res.is_some || progress),
pure $ res :: ress
/--
Apply `tac` to any goal where it succeeds. The tactic succeeds if `tac`
succeeds for at least one goal. The returned list contains the result of `tac`
for each goal: `some a` if tac succeeded, or `none` if it did not.
-/
meta def any_goals {α} (tac : tactic α) : tactic (list (option α)) :=
do gs ← get_goals,
any_goals_core tac gs [] ff
private meta def any_goals'_core (tac : tactic unit) : list expr → list expr → bool → tactic unit
| [] ac progress := guard progress >> set_goals ac
| (g :: gs) ac progress :=
mcond (is_assigned g) (any_goals'_core gs ac progress) $
do set_goals [g],
succeeded ← try_core tac,
new_gs ← get_goals,
any_goals'_core gs (ac ++ new_gs) (succeeded.is_some || progress)
/-- Apply the given tactic to any goal where it succeeds. The tactic succeeds only if
tac succeeds for at least one goal. -/
meta def any_goals' (tac : tactic unit) : tactic unit :=
do gs ← get_goals,
any_goals'_core tac gs [] ff
/--
LCF-style AND_THEN tactic. It applies `tac1` to the main goal, then applies
`tac2` to each goal produced by `tac1`.
-/
meta def seq {α β} (tac1 : tactic α) (tac2 : α → tactic β) : tactic (list β) :=
do g::gs ← get_goals,
set_goals [g],
a ← tac1,
bs ← all_goals $ tac2 a,
gs' ← get_goals,
set_goals (gs' ++ gs),
pure bs
/-- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/
meta def seq' (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit :=
do g::gs ← get_goals,
set_goals [g],
tac1, all_goals' tac2,
gs' ← get_goals,
set_goals (gs' ++ gs)
/--
Applies `tac1` to the main goal, then applies each of the tactics in `tacs2` to
one of the produced subgoals (like `focus'`).
-/
meta def seq_focus {α β} (tac1 : tactic α) (tacs2 : α → list (tactic β)) : tactic (list β) :=
do g::gs ← get_goals,
set_goals [g],
a ← tac1,
bs ← focus $ tacs2 a,
gs' ← get_goals,
set_goals (gs' ++ gs),
pure bs
/--
Applies `tac1` to the main goal, then applies each of the tactics in `tacs2` to
one of the produced subgoals (like `focus`).
-/
meta def seq_focus' (tac1 : tactic unit) (tacs2 : list (tactic unit)) : tactic unit :=
do g::gs ← get_goals,
set_goals [g],
tac1, focus tacs2,
gs' ← get_goals,
set_goals (gs' ++ gs)
meta instance andthen_seq : has_andthen (tactic unit) (tactic unit) (tactic unit) :=
⟨seq'⟩
meta instance andthen_seq_focus : has_andthen (tactic unit) (list (tactic unit)) (tactic unit) :=
⟨seq_focus'⟩
meta constant is_trace_enabled_for : name → bool
/-- Execute tac only if option trace.n is set to true. -/
meta def when_tracing (n : name) (tac : tactic unit) : tactic unit :=
when (is_trace_enabled_for n = tt) tac
/-- Fail if there are no remaining goals. -/
meta def fail_if_no_goals : tactic unit :=
do n ← num_goals,
when (n = 0) (fail "tactic failed, there are no goals to be solved")
/-- Fail if there are unsolved goals. -/
meta def done : tactic unit :=
do n ← num_goals,
when (n ≠ 0) (fail "done tactic failed, there are unsolved goals")
meta def apply_opt_param : tactic unit :=
do `(opt_param %%t %%v) ← target,
exact v
meta def apply_auto_param : tactic unit :=
do `(auto_param %%type %%tac_name_expr) ← target,
change type,
tac_name ← eval_expr name tac_name_expr,
tac ← eval_expr (tactic unit) (expr.const tac_name []),
tac
meta def has_opt_auto_param (ms : list expr) : tactic bool :=
ms.mfoldl
(λ r m, do type ← infer_type m,
return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2)
ff
meta def try_apply_opt_auto_param (cfg : apply_cfg) (ms : list expr) : tactic unit :=
when (cfg.auto_param || cfg.opt_param) $
mwhen (has_opt_auto_param ms) $ do
gs ← get_goals,
ms.mmap' (λ m, mwhen (bnot <$> is_assigned m) $
set_goals [m] >>
when cfg.opt_param (try apply_opt_param) >>
when cfg.auto_param (try apply_auto_param)),
set_goals gs
meta def has_opt_auto_param_for_apply (ms : list (name × expr)) : tactic bool :=
ms.mfoldl
(λ r m, do type ← infer_type m.2,
return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2)
ff
meta def try_apply_opt_auto_param_for_apply (cfg : apply_cfg) (ms : list (name × expr)) : tactic unit :=
mwhen (has_opt_auto_param_for_apply ms) $ do
gs ← get_goals,
ms.mmap' (λ m, mwhen (bnot <$> (is_assigned m.2)) $
set_goals [m.2] >>
when cfg.opt_param (try apply_opt_param) >>
when cfg.auto_param (try apply_auto_param)),
set_goals gs
meta def apply (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) :=
do r ← apply_core e cfg,
try_apply_opt_auto_param_for_apply cfg r,
return r
/-- Same as `apply` but __all__ arguments that weren't inferred are added to goal list. -/
meta def fapply (e : expr) : tactic (list (name × expr)) :=
apply e {new_goals := new_goals.all}
/-- Same as `apply` but only goals that don't depend on other goals are added to goal list. -/
meta def eapply (e : expr) : tactic (list (name × expr)) :=
apply e {new_goals := new_goals.non_dep_only}
/-- Try to solve the main goal using type class resolution. -/
meta def apply_instance : tactic unit :=
do tgt ← target >>= instantiate_mvars,
b ← is_class tgt,
if b then mk_instance tgt >>= exact
else fail "apply_instance tactic fail, target is not a type class"
/-- Create a list of universe meta-variables of the given size. -/
meta def mk_num_meta_univs : nat → tactic (list level)
| 0 := return []
| (succ n) := do
l ← mk_meta_univ,
ls ← mk_num_meta_univs n,
return (l::ls)
/-- Return `expr.const c [l_1, ..., l_n]` where l_i's are fresh universe meta-variables. -/
meta def mk_const (c : name) : tactic expr :=
do env ← get_env,
decl ← env.get c,
let num := decl.univ_params.length,
ls ← mk_num_meta_univs num,
return (expr.const c ls)
/-- Apply the constant `c` -/
meta def applyc (c : name) (cfg : apply_cfg := {}) : tactic unit :=
do c ← mk_const c, apply c cfg, skip
meta def eapplyc (c : name) : tactic unit :=
do c ← mk_const c, eapply c, skip
meta def save_const_type_info (n : name) {elab : bool} (ref : expr elab) : tactic unit :=
try (do c ← mk_const n, save_type_info c ref)
/-- Create a fresh universe `?u`, a metavariable `?T : Type.{?u}`,
and return metavariable `?M : ?T`.
This action can be used to create a meta-variable when
we don't know its type at creation time -/
meta def mk_mvar : tactic expr :=
do u ← mk_meta_univ,
t ← mk_meta_var (expr.sort u),
mk_meta_var t
/-- Makes a sorry macro with a meta-variable as its type. -/
meta def mk_sorry : tactic expr := do
u ← mk_meta_univ,
t ← mk_meta_var (expr.sort u),
return $ expr.mk_sorry t
/-- Closes the main goal using sorry. -/
meta def admit : tactic unit :=
target >>= exact ∘ expr.mk_sorry
meta def mk_local' (pp_name : name) (bi : binder_info) (type : expr) : tactic expr := do
uniq_name ← mk_fresh_name,
return $ expr.local_const uniq_name pp_name bi type
meta def mk_local_def (pp_name : name) (type : expr) : tactic expr :=
mk_local' pp_name binder_info.default type
meta def mk_local_pis : expr → tactic (list expr × expr)
| (expr.pi n bi d b) := do
p ← mk_local' n bi d,
(ps, r) ← mk_local_pis (expr.instantiate_var b p),
return ((p :: ps), r)
| e := return ([], e)
private meta def get_pi_arity_aux : expr → tactic nat
| (expr.pi n bi d b) :=
do m ← mk_fresh_name,
let l := expr.local_const m n bi d,
new_b ← whnf (expr.instantiate_var b l),
r ← get_pi_arity_aux new_b,
return (r + 1)
| e := return 0
/-- Compute the arity of the given (Pi-)type -/
meta def get_pi_arity (type : expr) : tactic nat :=
whnf type >>= get_pi_arity_aux
/-- Compute the arity of the given function -/
meta def get_arity (fn : expr) : tactic nat :=
infer_type fn >>= get_pi_arity
meta def triv : tactic unit := mk_const `trivial >>= exact
notation `dec_trivial` := of_as_true (by tactic.triv)
meta def by_contradiction (H : option name := none) : tactic expr :=
do tgt : expr ← target,
(match_not tgt >> return ())
<|>
(mk_mapp `decidable.by_contradiction [some tgt, none] >>= eapply >> skip)
<|>
fail "tactic by_contradiction failed, target is not a negation nor a decidable proposition (remark: when 'local attribute [instance] classical.prop_decidable' is used, all propositions are decidable)",
match H with
| some n := intro n
| none := intro1
end
private meta def generalizes_aux (md : transparency) : list expr → tactic unit
| [] := skip
| (e::es) := generalize e `x md >> generalizes_aux es
meta def generalizes (es : list expr) (md := semireducible) : tactic unit :=
generalizes_aux md es
private meta def kdependencies_core (e : expr) (md : transparency) : list expr → list expr → tactic (list expr)
| [] r := return r
| (h::hs) r :=
do type ← infer_type h,
d ← kdepends_on type e md,
if d then kdependencies_core hs (h::r)
else kdependencies_core hs r
/-- Return all hypotheses that depends on `e`
The dependency test is performed using `kdepends_on` with the given transparency setting. -/
meta def kdependencies (e : expr) (md := reducible) : tactic (list expr) :=
do ctx ← local_context, kdependencies_core e md ctx []
/-- Revert all hypotheses that depend on `e` -/
meta def revert_kdependencies (e : expr) (md := reducible) : tactic nat :=
kdependencies e md >>= revert_lst
meta def revert_kdeps (e : expr) (md := reducible) :=
revert_kdependencies e md
/-- Similar to `cases_core`, but `e` doesn't need to be a hypothesis.
Remark, it reverts dependencies using `revert_kdeps`.
Two different transparency modes are used `md` and `dmd`.
The mode `md` is used with `cases_core` and `dmd` with `generalize` and `revert_kdeps`.
It returns the constructor names associated with each new goal and the newly
introduced hypotheses.
-/
meta def cases (e : expr) (ids : list name := []) (md := semireducible) (dmd := semireducible) : tactic (list (name × list expr)) :=
if e.is_local_constant then
do r ← cases_core e ids md, return $ r.map (λ ⟨n, hs, _⟩, ⟨n, hs⟩)
else do
n ← revert_kdependencies e dmd,
x ← get_unused_name,
(tactic.generalize e x dmd)
<|>
(do t ← infer_type e,
tactic.assertv x t e,
get_local x >>= tactic.revert,
return ()),
h ← tactic.intro1,
focus1 $ do
r ← cases_core h ids md,
hs' ← all_goals (intron' n),
return $ r.map₂ (λ ⟨n, hs, _⟩ hs', ⟨n, hs ++ hs'⟩) hs'
/-- The same as `exact` except you can add proof holes. -/
meta def refine (e : pexpr) : tactic unit :=
do tgt : expr ← target,
to_expr ``(%%e : %%tgt) tt >>= exact
meta def by_cases (e : expr) (h : name) : tactic unit :=
do dec_e ← (mk_app `decidable [e] <|> fail "by_cases tactic failed, type is not a proposition"),
inst ← (mk_instance dec_e <|> fail "by_cases tactic failed, type of given expression is not decidable"),
t ← target,
tm ← mk_mapp `dite [some e, some inst, some t],
seq' (apply tm >> skip) (intro h >> skip)
meta def funext_core : list name → bool → tactic unit
| [] tt := return ()
| ids only_ids := try $
do some (lhs, rhs) ← expr.is_eq <$> (target >>= whnf),
applyc `funext,
id ← if ids.empty ∨ ids.head = `_ then do
(expr.lam n _ _ _) ← whnf lhs
| pure `_,
return n
else return ids.head,
intro id,
funext_core ids.tail only_ids
meta def funext : tactic unit :=
funext_core [] ff
meta def funext_lst (ids : list name) : tactic unit :=
funext_core ids tt
private meta def get_undeclared_const (env : environment) (base : name) : ℕ → name | i :=
let n := base <.> ("_aux_" ++ repr i) in
if ¬env.contains n then n
else get_undeclared_const (i+1)
meta def new_aux_decl_name : tactic name := do
env ← get_env, n ← decl_name,
return $ get_undeclared_const env n 1
private meta def mk_aux_decl_name : option name → tactic name
| none := new_aux_decl_name
| (some suffix) := do p ← decl_name, return $ p ++ suffix
meta def abstract (tac : tactic unit) (suffix : option name := none) (zeta_reduce := tt) : tactic unit :=
do fail_if_no_goals,
gs ← get_goals,
type ← if zeta_reduce then target >>= zeta else target,
is_lemma ← is_prop type,
m ← mk_meta_var type,
set_goals [m],
tac,
n ← num_goals,
when (n ≠ 0) (fail "abstract tactic failed, there are unsolved goals"),
set_goals gs,
val ← instantiate_mvars m,
val ← if zeta_reduce then zeta val else return val,
c ← mk_aux_decl_name suffix,
e ← add_aux_decl c type val is_lemma,
exact e
/-- `solve_aux type tac` synthesize an element of 'type' using tactic 'tac' -/
meta def solve_aux {α : Type} (type : expr) (tac : tactic α) : tactic (α × expr) :=
do m ← mk_meta_var type,
gs ← get_goals,
set_goals [m],
a ← tac,
set_goals gs,
return (a, m)
/-- Return tt iff 'd' is a declaration in one of the current open namespaces -/
meta def in_open_namespaces (d : name) : tactic bool :=
do ns ← open_namespaces,
env ← get_env,
return $ ns.any (λ n, n.is_prefix_of d) && env.contains d
/-- Execute tac for 'max' "heartbeats". The heartbeat is approx. the maximum number of
memory allocations (in thousands) performed by 'tac'. This is a deterministic way of interrupting
long running tactics. -/
meta def try_for {α} (max : nat) (tac : tactic α) : tactic α :=
λ s,
match _root_.try_for max (tac s) with
| some r := r
| none := mk_exception "try_for tactic failed, timeout" none s
end
meta def updateex_env (f : environment → exceptional environment) : tactic unit :=
do env ← get_env,
env ← returnex $ f env,
set_env env
/- Add a new inductive datatype to the environment
name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/
meta def add_inductive (n : name) (ls : list name) (p : nat) (ty : expr) (is : list (name × expr))
(is_meta : bool := ff) : tactic unit :=
updateex_env $ λe, e.add_inductive n ls p ty is is_meta
meta def add_meta_definition (n : name) (lvls : list name) (type value : expr) : tactic unit :=
add_decl (declaration.defn n lvls type value reducibility_hints.abbrev ff)
/-- add declaration `d` as a protected declaration -/
meta def add_protected_decl (d : declaration) : tactic unit :=
updateex_env $ λ e, e.add_protected d
/-- check if `n` is the name of a protected declaration -/
meta def is_protected_decl (n : name) : tactic bool :=
do env ← get_env,
return $ env.is_protected n
/-- `add_defn_equations` adds a definition specified by a list of equations.
The arguments:
* `lp`: list of universe parameters
* `params`: list of parameters (binders before the colon);
* `fn`: a local constant giving the name and type of the declaration
(with `params` in the local context);
* `eqns`: a list of equations, each of which is a list of patterns
(constructors applied to new local constants) and the branch
expression;
* `is_meta`: is the definition meta?
`add_defn_equations` can be used as:
do my_add ← mk_local_def `my_add `(ℕ → ℕ),
a ← mk_local_def `a ℕ,
b ← mk_local_def `b ℕ,
add_defn_equations [a] my_add
[ ([``(nat.zero)], a),
([``(nat.succ %%b)], my_add b) ])
ff -- non-meta
to create the following definition:
def my_add (a : ℕ) : ℕ → ℕ
| nat.zero := a
| (nat.succ b) := my_add b
-/
meta def add_defn_equations (lp : list name) (params : list expr) (fn : expr)
(eqns : list (list pexpr × expr)) (is_meta : bool) : tactic unit :=
do opt ← get_options,
updateex_env $ λ e, e.add_defn_eqns opt lp params fn eqns is_meta
/-- Get the revertible part of the local context. These are the hypotheses that
appear after the last frozen local instance in the local context. We call them
revertible because `revert` can revert them, unlike those hypotheses which occur
before a frozen instance. -/
meta def revertible_local_context : tactic (list expr) :=
do ctx ← local_context,
frozen ← frozen_local_instances,
pure $
match frozen with
| none := ctx
| some [] := ctx
| some (h :: _) := ctx.after (eq h)
end
/--
Rename local hypotheses according to the given `name_map`. The `name_map`
contains as keys those hypotheses that should be renamed; the associated values
are the new names.
This tactic can only rename hypotheses which occur after the last frozen local
instance. If you need to rename earlier hypotheses, try
`unfreeze_local_instances`.
If `strict` is true, we fail if `name_map` refers to hypotheses that do not
appear in the local context or that appear before a frozen local instance.
Conversely, if `strict` is false, some entries of `name_map` may be silently
ignored.
If `use_unique_names` is true, the keys of `name_map` should be the unique names
of hypotheses to be renamed. Otherwise, the keys should be display names.
Note that we allow shadowing, so renamed hypotheses may have the same name
as other hypotheses in the context. If `use_unique_names` is false and there are
multiple hypotheses with the same display name in the context, they are all
renamed.
-/
meta def rename_many (renames : name_map name) (strict := tt) (use_unique_names := ff)
: tactic unit :=
do let hyp_name : expr → name :=
if use_unique_names then expr.local_uniq_name else expr.local_pp_name,
ctx ← revertible_local_context,
-- The part of the context after (but including) the first hypthesis that
-- must be renamed.
let ctx_suffix := ctx.drop_while (λ h, (renames.find $ hyp_name h).is_none),
when strict $ do {
let ctx_names := rb_map.set_of_list (ctx_suffix.map hyp_name),
let invalid_renames :=
(renames.to_list.map prod.fst).filter (λ h, ¬ ctx_names.contains h),
when ¬ invalid_renames.empty $ fail $ format.join
[ "Cannot rename these hypotheses:\n"
, format.join $ (invalid_renames.map to_fmt).intersperse ", "
, format.line
, "This is because these hypotheses either do not occur in the\n"
, "context or they occur before a frozen local instance.\n"
, "In the latter case, try `tactic.unfreeze_local_instances`."
]
},
-- The new names for all hypotheses in ctx_suffix.
let new_names :=
ctx_suffix.map $ λ h,
(renames.find $ hyp_name h).get_or_else h.local_pp_name,
revert_lst ctx_suffix,
intro_lst new_names,
pure ()
/--
Rename a local hypothesis. This is a special case of `rename_many`;
see there for caveats.
-/
meta def rename (curr : name) (new : name) : tactic unit :=
rename_many (rb_map.of_list [⟨curr, new⟩])
/--
Rename a local hypothesis. Unlike `rename` and `rename_many`, this tactic does
not preserve the order of hypotheses. Its implementation is simpler (and
therefore probably faster) than that of `rename`.
-/
meta def rename_unstable (curr : name) (new : name) : tactic unit :=
do h ← get_local curr,
n ← revert h,
intro new,
intron (n - 1)
/--
"Replace" hypothesis `h : type` with `h : new_type` where `eq_pr` is a proof
that (type = new_type). The tactic actually creates a new hypothesis
with the same user facing name, and (tries to) clear `h`.
The `clear` step fails if `h` has forward dependencies. In this case, the old `h`
will remain in the local context. The tactic returns the new hypothesis. -/
meta def replace_hyp (h : expr) (new_type : expr) (eq_pr : expr) : tactic expr :=
do h_type ← infer_type h,
new_h ← assert h.local_pp_name new_type,
mk_eq_mp eq_pr h >>= exact,
try $ clear h,
return new_h
meta def main_goal : tactic expr :=
do g::gs ← get_goals, return g
/- Goal tagging support -/
meta def with_enable_tags {α : Type} (t : tactic α) (b := tt) : tactic α :=
do old ← tags_enabled,
enable_tags b,
r ← t,
enable_tags old,
return r
meta def get_main_tag : tactic tag :=
main_goal >>= get_tag
meta def set_main_tag (t : tag) : tactic unit :=
do g ← main_goal, set_tag g t
meta def subst (h : expr) : tactic unit :=
(do guard h.is_local_constant,
some (α, lhs, β, rhs) ← expr.is_heq <$> infer_type h,
is_def_eq α β,
new_h_type ← mk_app `eq [lhs, rhs],
new_h_pr ← mk_app `eq_of_heq [h],
new_h ← assertv h.local_pp_name new_h_type new_h_pr,
try (clear h),
subst_core new_h)
<|> subst_core h
end tactic
notation [parsing_only] `command`:max := tactic unit
open tactic
namespace list
meta def for_each {α} : list α → (α → tactic unit) → tactic unit
| [] fn := skip
| (e::es) fn := do fn e, for_each es fn
meta def any_of {α β} : list α → (α → tactic β) → tactic β
| [] fn := failed
| (e::es) fn := do opt_b ← try_core (fn e),
match opt_b with
| some b := return b
| none := any_of es fn
end
end list
/- Install monad laws tactic and use it to prove some instances. -/
/-- Try to prove with `iff.refl`.-/
meta def order_laws_tac := whnf_target >> intros >> to_expr ``(iff.refl _) >>= exact
meta def monad_from_pure_bind {m : Type u → Type v}
(pure : Π {α : Type u}, α → m α)
(bind : Π {α β : Type u}, m α → (α → m β) → m β) : monad m :=
{pure := @pure, bind := @bind}
meta instance : monad task :=
{map := @task.map, bind := @task.bind, pure := @task.pure}
namespace tactic
meta def mk_id_proof (prop : expr) (pr : expr) : expr :=
expr.app (expr.app (expr.const ``id [level.zero]) prop) pr
meta def mk_id_eq (lhs : expr) (rhs : expr) (pr : expr) : tactic expr :=
do prop ← mk_app `eq [lhs, rhs],
return $ mk_id_proof prop pr
meta def replace_target (new_target : expr) (pr : expr) : tactic unit :=
do t ← target,
assert `htarget new_target, swap,
ht ← get_local `htarget,
locked_pr ← mk_id_eq t new_target pr,
mk_eq_mpr locked_pr ht >>= exact
meta def eval_pexpr (α) [reflected α] (e : pexpr) : tactic α :=
to_expr ``(%%e : %%(reflect α)) ff ff >>= eval_expr α
meta def run_simple {α} : tactic_state → tactic α → option α
| ts t := match t ts with
| (interaction_monad.result.success a ts') := some a
| (interaction_monad.result.exception _ _ _) := none
end
end tactic
|
af2f92f9a7d3cbfe8487ead9f7c5b70f54df0a8d | d436468d80b739ba7e06843c4d0d2070e43448e5 | /src/logic/relator.lean | d596d474e261d1a2477140777a39352675b0528a | [
"Apache-2.0"
] | permissive | roro47/mathlib | 761fdc002aef92f77818f3fef06bf6ec6fc1a28e | 80aa7d52537571a2ca62a3fdf71c9533a09422cf | refs/heads/master | 1,599,656,410,625 | 1,573,649,488,000 | 1,573,649,488,000 | 221,452,951 | 0 | 0 | Apache-2.0 | 1,573,647,693,000 | 1,573,647,692,000 | null | UTF-8 | Lean | false | false | 3,698 | 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
Relator for functions, pairs, sums, and lists.
-/
namespace relator
universe variables u₁ u₂ v₁ v₂
reserve infixr ` ⇒ `:40
/- TODO(johoelzl):
* should we introduce relators of datatypes as recursive function or as inductive
predicate? For now we stick to the recursor approach.
* relation lift for datatypes, Π, Σ, set, and subtype types
* proof composition and identity laws
* implement method to derive relators from datatype
-/
section
variables {α : Sort u₁} {β : Sort u₂} {γ : Sort v₁} {δ : Sort v₂}
variables (R : α → β → Prop) (S : γ → δ → Prop)
def lift_fun (f : α → γ) (g : β → δ) : Prop :=
∀⦃a b⦄, R a b → S (f a) (g b)
infixr ⇒ := lift_fun
end
section
variables {α : Type u₁} {β : out_param $ Type u₂} (R : out_param $ α → β → Prop)
@[class] def right_total := ∀b, ∃a, R a b
@[class] def left_total := ∀a, ∃b, R a b
@[class] def bi_total := left_total R ∧ right_total R
end
section
variables {α : Type u₁} {β : Type u₂} (R : α → β → Prop)
@[class] def left_unique := ∀{a b c}, R a b → R c b → a = c
@[class] def right_unique := ∀{a b c}, R a b → R a c → b = c
lemma rel_forall_of_right_total [t : right_total R] : ((R ⇒ implies) ⇒ implies) (λp, ∀i, p i) (λq, ∀i, q i) :=
assume p q Hrel H b, exists.elim (t b) (assume a Rab, Hrel Rab (H _))
lemma rel_exists_of_left_total [t : left_total R] : ((R ⇒ implies) ⇒ implies) (λp, ∃i, p i) (λq, ∃i, q i) :=
assume p q Hrel ⟨a, pa⟩, let ⟨b, Rab⟩ := t a in ⟨b, Hrel Rab pa⟩
lemma rel_forall_of_total [t : bi_total R] : ((R ⇒ iff) ⇒ iff) (λp, ∀i, p i) (λq, ∀i, q i) :=
assume p q Hrel,
⟨assume H b, exists.elim (t.right b) (assume a Rab, (Hrel Rab).mp (H _)),
assume H a, exists.elim (t.left a) (assume b Rab, (Hrel Rab).mpr (H _))⟩
lemma rel_exists_of_total [t : bi_total R] : ((R ⇒ iff) ⇒ iff) (λp, ∃i, p i) (λq, ∃i, q i) :=
assume p q Hrel,
⟨assume ⟨a, pa⟩, let ⟨b, Rab⟩ := t.left a in ⟨b, (Hrel Rab).1 pa⟩,
assume ⟨b, qb⟩, let ⟨a, Rab⟩ := t.right b in ⟨a, (Hrel Rab).2 qb⟩⟩
lemma left_unique_of_rel_eq {eq' : β → β → Prop} (he : (R ⇒ (R ⇒ iff)) eq eq') : left_unique R
| a b c (ab : R a b) (cb : R c b) :=
have eq' b b,
from iff.mp (he ab ab) rfl,
iff.mpr (he ab cb) this
end
lemma rel_imp : (iff ⇒ (iff ⇒ iff)) implies implies :=
assume p q h r s l, imp_congr h l
lemma rel_not : (iff ⇒ iff) not not :=
assume p q h, not_congr h
instance bi_total_eq {α : Type u₁} : relator.bi_total (@eq α) :=
⟨assume a, ⟨a, rfl⟩, assume a, ⟨a, rfl⟩⟩
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
variables {r : α → β → Prop} {p : β → γ → Prop} {q : γ → δ → Prop}
def bi_unique (r : α → β → Prop) : Prop := left_unique r ∧ right_unique r
lemma left_unique_flip (h : left_unique r) : right_unique (flip r)
| a b c h₁ h₂ := h h₁ h₂
lemma rel_and : ((↔) ⇒ (↔) ⇒ (↔)) (∧) (∧) :=
assume a b h₁ c d h₂, and_congr h₁ h₂
lemma rel_or : ((↔) ⇒ (↔) ⇒ (↔)) (∨) (∨) :=
assume a b h₁ c d h₂, or_congr h₁ h₂
lemma rel_iff : ((↔) ⇒ (↔) ⇒ (↔)) (↔) (↔) :=
assume a b h₁ c d h₂, iff_congr h₁ h₂
lemma rel_eq {r : α → β → Prop} (hr : bi_unique r) : (r ⇒ r ⇒ (↔)) (=) (=) :=
assume a b h₁ c d h₂,
iff.intro
begin intro h, subst h, exact hr.right h₁ h₂ end
begin intro h, subst h, exact hr.left h₁ h₂ end
end relator
|
d719eb764520ff192367bc61f9f1f55f53f07187 | 75c54c8946bb4203e0aaf196f918424a17b0de99 | /src/regular_open_algebra.lean | ca173a96784dc655b12b5d01d2909e9c00dc4e8e | [
"Apache-2.0"
] | permissive | urkud/flypitch | 261e2a45f1038130178575406df8aea78255ba77 | 2250f5eda14b6ef9fc3e4e1f4a9ac4005634de5c | refs/heads/master | 1,653,266,469,246 | 1,577,819,679,000 | 1,577,819,679,000 | 259,862,235 | 1 | 0 | Apache-2.0 | 1,588,147,244,000 | 1,588,147,244,000 | null | UTF-8 | Lean | false | false | 29,647 | lean | /-
Copyright (c) 2019 The Flypitch Project. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jesse Han, Floris van Doorn
-/
import .set_theory order.complete_boolean_algebra
local attribute [instance] classical.prop_decidable
open set
meta def not_as_big_bertha : tactic string := `[cc] >> pure "cc"
meta def not_as_big_bertha' : tactic string := `[{[smt] close}] >> pure "{[smt] close}"
meta def with_cc : list (tactic string) := tactic.tidy.default_tactics ++ [not_as_big_bertha]
meta def with_cc' : list (tactic string) := tactic.tidy.default_tactics ++ [not_as_big_bertha']
namespace topological_space
section topology_lemmas
variables {α : Type*} [τ : topological_space α]
local notation `cl`:65 := closure
local notation `int`:65 := interior
attribute [simp] interior_eq_of_open
include τ
def dense (S : set α) : Prop := ∀ U : set α, @is_open α τ U → U ≠ ∅ → U ∩ S ≠ ∅
-- S is dense in S₀ if S ∩ S₀ is dense in the subspace S₀
def rel_dense (S₀ S : set α) : Prop := ∀ U : set α, @is_open α τ U → U ∩ S₀ ≠ ∅ → U ∩ S₀ ∩ S ≠ ∅
lemma closure_univ_of_dense {S : set α} (H_dense : dense S) : closure S = univ :=
dense_iff_inter_open.mpr H_dense
lemma closure_rel_dense_of_open {S₀ S : set α} (H_open : is_open τ S₀) (H_rel_dense : rel_dense S₀ S) : cl S ∩ S₀ = S₀ :=
begin
ext, split; intro H_mem,
{ cases H_mem with H₁ H₂, from ‹_› },
{ refine ⟨_,‹_›⟩, rw mem_closure_iff,
intros o Ho H_mem_o, specialize H_rel_dense (o ∩ S₀) (by {apply is_open_inter, from ‹_›, from ‹_›}) _,
rw set.ne_empty_iff_exists_mem at H_rel_dense ⊢, cases H_rel_dense with x Hx, repeat {auto_cases},
use x, finish, rw set.ne_empty_iff_exists_mem, use x, finish}
end
/--
S is dense in the basis 𝓑 if S meets every B ∈ 𝓑.
-/
def dense_in_basis (S : set α) {𝓑 : set $ set α} (H_basis : is_topological_basis 𝓑) : Prop :=
∀ B ∈ 𝓑, B ≠ ∅ → B ∩ S ≠ ∅
lemma dense_of_dense_in_basis (S : set α) {𝓑} (H_basis : is_topological_basis 𝓑) (H : dense_in_basis S H_basis) : dense S :=
begin
intros U HU HU_ne,
cases (exists_mem_of_ne_empty ‹_›) with a Ha,
rcases mem_basis_subset_of_mem_open ‹_› Ha ‹_› with ⟨B, ⟨HB₁, ⟨HB₂, HB₃⟩⟩⟩,
suffices this : ∃ a', a' ∈ U ∧ a' ∈ S,
from ne_empty_of_exists_mem this,
have := exists_mem_of_ne_empty (H _ HB₁ (ne_empty_of_exists_mem (by finish))),
rcases this with ⟨x,⟨Hx₁,Hx₂⟩⟩, use x, tidy
end
def rel_dense_in_basis (S₀ : set α) (S : set α) {𝓑 : set $ set α} (H_basis : is_topological_basis 𝓑) : Prop :=
∀ B ∈ 𝓑, B ∩ S₀ ≠ ∅ → B ∩ S₀ ∩ S ≠ ∅
lemma rel_dense_of_dense_in_basis (S₀ : set α) (S : set α) {𝓑} (H_basis : is_topological_basis 𝓑) (H : rel_dense_in_basis S₀ S H_basis) : rel_dense S₀ S :=
begin
intros U HU HU_ne,
rcases (exists_mem_of_ne_empty ‹_›) with ⟨a,Ha,Ha₀⟩,
rcases mem_basis_subset_of_mem_open ‹_› Ha ‹_› with ⟨B, ⟨HB₁, ⟨HB₂, HB₃⟩⟩⟩,
suffices this : ∃ a', a' ∈ U ∧ a' ∈ S₀ ∧ a' ∈ S,
from ne_empty_of_exists_mem (by finish),
have := exists_mem_of_ne_empty (H _ HB₁ (ne_empty_of_exists_mem (by finish))),
rcases this with ⟨x,⟨Hx₁,Hx₂⟩⟩, use x, tidy
end
def nowhere_dense (S : set α) : Prop := int (cl S) = ∅
lemma frontier_closed_of_open {S : set α} (H : @is_open _ τ S) : is_closed (frontier S) :=
begin
unfold frontier, rw[diff_eq], apply is_closed_inter, tidy
end
lemma frontier_nowhere_dense_of_open {S : set α} (H : @is_open _ τ S) : nowhere_dense (frontier S) :=
begin
unfold nowhere_dense frontier,
ext, split; intros, swap, cases a,
rw[diff_eq] at a,
rw[show cl(cl S ∩ -int S) = cl(S) ∩ -int S,
by {apply closure_eq_of_is_closed, from frontier_closed_of_open H}] at a,
rw[show int S = S, by {apply interior_eq_of_open, from ‹_›}] at a,
rw[interior_inter] at a, simp at a, tidy
end
lemma is_clopen_interior {S : set α} (H : (: is_clopen S :)) : interior S = S :=
interior_eq_of_open H.left
local attribute [ematch] is_clopen_interior
lemma is_clopen_closure {S : set α} (H : (: is_clopen S :)) : closure S = S :=
closure_eq_of_is_closed H.right
local attribute [ematch] is_clopen_closure
@[simp]lemma closure_mono' {s t : set α} (H : (: s ⊆ t :)) : closure s ⊆ closure t ↔ true := by finish[closure_mono]
local attribute [ematch] closure_mono'
lemma closure_eq_compl_interior_compl' {s : set α} :
closure s = - interior (- s) := closure_eq_compl_interior_compl
local attribute [ematch] closure_eq_compl_interior_compl'
lemma interior_compl' {s : set α} : interior (- s) = - closure s :=
by apply interior_compl
@[ematch]lemma interior_eq_compl_closure_compl {s : set α} :
interior s = - closure (- s) :=
by ext; simp
lemma subset_anti {s t : set α} : -s ⊆ -t ↔ t ⊆ s :=
compl_subset_compl
lemma subset_anti' {s t : set α} (H : t ⊆ s) : - (closure s) ⊆ - (closure t) :=
by finish[subset_anti]
local attribute [ematch] subset_anti'
lemma subset_anti_right {s t : set α} (H : s ⊆ -t) : s ⊆ -t ↔ t ⊆ -s :=
by {split, clear H, intro, rw[<-subset_anti], convert a, simp, finish}
local attribute [ematch] subset_anti_right
lemma compl_mono {s t : set α} (H : s ⊆ t) : - t ⊆ - s := by simp[*,subset_anti]
end topology_lemmas
end topological_space
open lattice
section regular
variables {α : Type*} [τ : topological_space α]
include τ
@[reducible]def topological_space.is_regular (S : set α) : Prop :=
S = interior (closure S)
open topological_space
local attribute [ematch] is_clopen_interior is_clopen_closure closure_mono'
is_regular subset_anti_right subset_anti' closure_eq_compl_interior_compl'
-- @[reducible,simp,ematch]def int_of_cl (S : set α) := interior (closure S)
def perp (S : set α) : set α := - (closure S)
local attribute [reducible] perp
local postfix `ᵖ`:80 := perp
local notation `cl`:65 := closure
local notation `int`:65 := interior
@[ematch]lemma perp_unfold (S : set α) : Sᵖ = - (cl S) := rfl
lemma perp_eq_int_neg {S : set α} : Sᵖ = int (- S) :=
by simp [perp]
lemma mem_perp_iff {S : set α} {x : α} :
x ∈ Sᵖ ↔ ∃T, T ∩ S = ∅ ∧ _root_.is_open T ∧ x ∈ T :=
by simp [perp_eq_int_neg, subset_compl_iff_disjoint, mem_interior, -interior_compl]
@[simp]lemma is_open_perp {S : set α} : is_open (Sᵖ) :=
by {unfold perp, apply is_open_compl_iff.mpr, simp}
@[simp]lemma perp_univ : univᵖ = (∅ : set α) :=
by simp[perp_unfold]
@[simp]lemma perp_empty : (∅ : set α)ᵖ = univ :=
by simp[perp_unfold]
@[simp]lemma is_open_of_is_regular {S : set α} (H : (: is_regular S :)) : is_open S :=
by {unfold is_regular at H, rw[H], simp}
local attribute [ematch] is_open_of_is_regular
@[simp]lemma is_regular_of_clopen {S : set α} (H : is_clopen S) : is_regular S :=
by {[smt] eblast}
lemma regular_iff_p_p {S : set α} : is_regular S ↔ (Sᵖᵖ) = S :=
begin
split; intro H, unfold is_regular at H,
{[smt] eblast},
{[smt] eblast}
end
lemma p_p_eq_int_cl {S : set α} : Sᵖᵖ = interior (closure S) :=
by {have := @regular_iff_p_p α _ S; {[smt] eblast}}
lemma int_cl_eq_p_p {S : set α} : int (cl S) = Sᵖᵖ := p_p_eq_int_cl.symm
@[ematch]lemma mem_int_cl_iff_mem_eq_p_p {S : set α} {a : α} : a ∈ int (cl S) ↔ a ∈ (Sᵖᵖ) := by rw[int_cl_eq_p_p]
lemma is_open_of_p_p {S : set α} (H : Sᵖᵖ = S) : is_open S :=
by {rw[p_p_eq_int_cl] at H, from is_open_of_is_regular (by {unfold is_regular, from H.symm})}
@[simp]lemma is_regular_empty : is_regular (∅ : set α) :=
by simp
@[simp]lemma is_regular_univ : is_regular (univ : set α) :=
by simp
lemma p_anti {P Q : set α} (H : P ⊆ Q) : Qᵖ ⊆ Pᵖ :=
by {have := subset_anti' H, from this}
lemma p_p_mono {P Q : set α} (H : P ⊆ Q) : Pᵖᵖ ⊆ Qᵖᵖ :=
p_anti $ p_anti H
lemma in_p_p_of_open {S : set α} (H : is_open S) : S ⊆ Sᵖᵖ :=
begin
have : S ⊆ cl S := subset_closure,
rw[<-subset_anti] at this,
replace this := closure_mono this,
rw[<-subset_anti] at this,
convert this, simp*
end
lemma p_eq_p_p_p {S : set α} (H : is_open S) : Sᵖ = Sᵖᵖᵖ :=
begin
have := p_anti (in_p_p_of_open ‹_›),
have := in_p_p_of_open (show is_open (Sᵖ), by simp),
ext; split; intros; solve_by_elim
end
@[simp]lemma p_p_p_p_eq_p_p {S : set α} : Sᵖᵖᵖᵖ = Sᵖᵖ :=
by {rw[<-p_eq_p_p_p], simp}
lemma is_regular_stable_subset {S₁ S₂ : set α} (H : is_regular S₂) (H₂ : S₁ ⊆ S₂) : S₁ᵖᵖ ⊆ S₂ :=
by {rw[regular_iff_p_p] at H,
replace H₂ := p_anti (p_anti H₂), convert H₂, cc}
@[simp]lemma is_regular_eq_p_p {S : set α} (H : is_regular S) : Sᵖᵖ = S :=
begin
refine le_antisymm _ _,
apply is_regular_stable_subset ‹_›, intros _ _, from ‹_›,
from in_p_p_of_open (is_open_of_is_regular ‹_›)
end
lemma subset_p_p_of_open {S : set α} (H : (: is_open S :)) : S ⊆ Sᵖᵖ :=
in_p_p_of_open ‹_›
lemma subset_int_cl_of_open {S : set α} (H : is_open S) : S ⊆ int (cl S) :=
by {rw[<-p_p_eq_int_cl], from subset_p_p_of_open ‹_›}
lemma is_regular_sup {S₁ S₂ : set α} : is_regular ((S₁ ∪ S₂)ᵖᵖ) :=
by rw[regular_iff_p_p]; simp
@[simp]lemma is_open_of_p_p' {S : set α} : is_open (Sᵖᵖ) :=
by {simp}
@[simp]lemma is_regular_p_p {S : set α} : is_regular (Sᵖᵖ) :=
begin
refine le_antisymm _ _,
rw[<-p_p_eq_int_cl], apply subset_p_p_of_open,
apply is_open_of_p_p',
rw[<-p_p_eq_int_cl], simp, intros _ _, from ‹_›
end
lemma inter_eq_inter_aux (S₁ S₂ : set α) (H : is_open S₁) : S₁ ∩ (cl S₂) ⊆ cl (S₁ ∩ S₂) :=
closure_inter_open ‹_›
@[simp]lemma cl_compl_of_is_open (S : set α) (H : is_open S) : cl(-S) = -S :=
by have : is_closed (-S); by simp*; simp[this]
lemma inter_eq_inter_aux₂ (S₁ S₂ : set α) {H₁ : is_open S₁} {H₂ : is_open S₂} : S₁ ∩ (S₂ᵖᵖ) ⊆ (S₁ ∩ S₂)ᵖᵖ :=
begin
have this₃ := inter_eq_inter_aux S₁ S₂ H₁,
have this₄ := compl_mono (this₃),
rw[compl_inter] at this₄,
have this₅ := p_anti this₄,
unfold perp at this₅, rw[closure_union] at this₅,
rw[cl_compl_of_is_open] at this₅, rw[compl_union] at this₅,
convert this₅, simp, from ‹_›
end
lemma p_p_inter_eq_inter_p_p {S₁ S₂ : set α} (H₁ : is_open S₁) (H₂ : is_open S₂): (S₁ ∩ S₂)ᵖᵖ = S₁ᵖᵖ ∩ S₂ᵖᵖ :=
begin
have this₀_left : S₁ ∩ S₂ ⊆ S₁, by simp,
have this₀_right : S₁ ∩ S₂ ⊆ S₂, by simp,
have this₁_left : (S₁ ∩ S₂)ᵖᵖ ⊆ S₁ᵖᵖ, from p_anti (p_anti this₀_left),
have this₁_right : (S₁ ∩ S₂)ᵖᵖ ⊆ S₂ᵖᵖ, from p_anti (p_anti this₀_right),
have this₂ : (S₁ ∩ S₂)ᵖᵖ ⊆ S₁ᵖᵖ ∩ S₂ᵖᵖ,
by {intros x Hx, split, from this₁_left ‹_›, from this₁_right ‹_›},
apply subset.antisymm, exact λ _ _, this₂ ‹_›,
show S₁ᵖᵖ ∩ S₂ᵖᵖ ⊆ (S₁ ∩ S₂)ᵖᵖ,
have this₃ := inter_eq_inter_aux S₁ S₂ H₁,
have this₄ := compl_mono (this₃),
have this₅ := p_anti this₄,
change _ ᵖ ⊆ _ ᵖᵖ at this₅,
have this₆ : S₁ ∩ (S₂ᵖᵖ) ⊆ (S₁ ∩ S₂)ᵖᵖ,
by {apply inter_eq_inter_aux₂; from ‹_›},
have this₇ : (S₁ᵖᵖ) ∩ (S₂ᵖᵖ) ⊆ ((S₁ᵖᵖ) ∩ S₂)ᵖᵖ,
by {apply inter_eq_inter_aux₂ (S₁ᵖᵖ), simpa},
have this₈ : (S₂ ∩ S₁ᵖᵖ) ⊆ (S₂ ∩ S₁)ᵖᵖ,
by {apply inter_eq_inter_aux₂ S₂ S₁; from ‹_›},
have this₉ : (S₁ᵖᵖ ∩ S₂)ᵖᵖ ⊆ (S₁ ∩ S₂)ᵖᵖᵖᵖ,
by {replace this₈ := p_anti this₈, replace this₈ := p_anti this₈,
conv {congr, rw[inter_comm], skip, rw[inter_comm]}, from this₈},
rw[<-p_eq_p_p_p] at this₉,
from subset.trans this₇ this₉, from is_open_perp
end
@[simp]lemma is_regular_inter {S₁ S₂ : set α} (H₁ : is_regular S₁) (H₂ : is_regular S₂) : is_regular (S₁ ∩ S₂) :=
by {rw[regular_iff_p_p] at *, rw[p_p_inter_eq_inter_p_p (is_open_of_p_p H₁) (is_open_of_p_p H₂)], cc}
lemma Union_perp_subset (C : set (set α)) : ⋃₀ (perp '' C) ⊆ (⋂₀ C)ᵖ :=
begin
intros x hx, simp [-mem_compl_eq, mem_perp_iff] at hx ⊢, rcases hx with ⟨s, hs, t, hts, ht⟩,
refine ⟨t, _, ht⟩, rw [← subset_empty_iff, ← hts], apply inter_subset_inter_right,
apply sInter_subset_of_mem hs
end
lemma perp_sUnion_perp {C : set (set α)} (h : ∀(s ∈ C), is_regular s) :
(⋃₀ (perp '' C))ᵖ = (⋂₀ C)ᵖᵖ :=
begin
refine subset.antisymm _ (p_anti $ Union_perp_subset C),
intros x hx, simp [-mem_compl_eq, mem_perp_iff] at hx ⊢,
rcases hx with ⟨t, h1t, h2t, h3t⟩,
rw [← subset_compl_iff_disjoint, compl_bUnion, ← subset_interior_iff_subset_of_open h2t] at h1t,
simp only [compl_compl] at h1t,
simp only [subset_compl_iff_disjoint.symm, compl_compl],
refine ⟨t, _, h2t, h3t⟩,
have := subset.trans h1t (interior_bInter_subset _),
rw [subset_bInter_iff] at this,
refine subset.trans _ subset_closure,
rw [subset_sInter_iff], intros s hs,
convert this s hs, exact h s hs
end
end regular
open topological_space
section regular_algebra
local postfix `ᵖ`:80 := perp
local notation `cl`:65 := closure
local notation `int`:65 := interior
variables {α : Type*} [τ : topological_space α]
include τ
variable (α)
def regular_opens := {S : set α // is_regular S}
local attribute [reducible] regular_opens
local attribute [reducible] perp
variable{α}
def regular_open_poset : partial_order (regular_opens α) :=
{le := λ S₁ S₂, S₁.val ⊆ S₂.val,
lt := λ S₁ S₂, S₁.val ⊆ S₂.val ∧ S₁.val ≠ S₂.val,
le_refl := by {intro a, simp only},
le_trans := by {intros a b c H₁ H₂, apply subset.trans H₁ H₂},
lt_iff_le_not_le := by {intros a b, split; intro H, tidy,
suffices : a_val = b_val,
by contradiction, ext; intros; split; intros,
from H_left ‹_›, from a ‹_›},
le_antisymm :=
begin
intros a b H₁ H₂, apply subtype.eq,
ext; intros; split; intros, from H₁ ‹_›, from H₂ ‹_›
end}
local attribute [instance] regular_open_poset
lemma le_iff_subset {S₁ S₂ : regular_opens α} : S₁ ≤ S₂ ↔ S₁.val ⊆ S₂ := by refl
def regular_open_lattice : lattice (regular_opens α) :=
{ sup := λ S₁ S₂, ⟨(S₁.val ∪ S₂.val)ᵖᵖ, by {apply is_regular_sup}⟩,
le_sup_left :=
begin
intros a b, refine subset.trans (show a.val ⊆ a.val ∪ b.val, by simp) (show a.val ∪ b.val ⊆ (a.val ∪ b.val)ᵖᵖ, from _),
apply subset_p_p_of_open (is_open_union (is_open_of_is_regular a.property) (is_open_of_is_regular b.property)),
end,
le_sup_right :=
begin
intros a b, refine subset.trans (show b.val ⊆ a.val ∪ b.val, by simp) (show a.val ∪ b.val ⊆ (a.val ∪ b.val)ᵖᵖ, from _),
apply subset_p_p_of_open (is_open_union (is_open_of_is_regular a.property) (is_open_of_is_regular b.property)),
end,
sup_le := by {intros a b c H₁ H₂, apply is_regular_stable_subset, from c.property, intros x Hx, cases Hx; solve_by_elim},
inf := λ S₁ S₂, ⟨S₁.val ∩ S₂.val, by {apply is_regular_inter, from S₁.property, from S₂.property}⟩,
inf_le_left :=
begin
intros a b, intros x Hx, from Hx.left
end,
inf_le_right :=
begin
intros a b, intros x Hx, from Hx.right
end,
le_inf :=
begin
intros a b c H₁ H₂, intros x Hx, split; solve_by_elim
end,
..regular_open_poset}
local attribute [instance] regular_open_lattice
def regular_open_bounded_lattice : bounded_lattice (regular_opens α) :=
{ top := ⟨set.univ, is_regular_univ⟩,
le_top := by tidy,
bot := ⟨∅, is_regular_empty⟩,
bot_le := by tidy,
.. regular_open_lattice}
local attribute [instance] regular_open_bounded_lattice
lemma coe_bot : ((⊥ : regular_opens α) : set α) = ∅ := by refl
def regular_open.neg : (regular_opens α) → (regular_opens α) := λ x, ⟨xᵖ, by {rw[regular_iff_p_p], symmetry, apply p_eq_p_p_p,
from is_open_of_is_regular x.property}⟩
def regular_open_has_neg : has_neg (regular_opens α) :=
⟨regular_open.neg⟩
local attribute [instance] regular_open_has_neg
def regular_open.Sup : set (regular_opens α) → (regular_opens α) :=
λ 𝒮, ⟨⋃₀(subtype.val '' 𝒮)ᵖᵖ, is_regular_p_p⟩
def regular_open_has_Sup : has_Sup (regular_opens α) :=
⟨regular_open.Sup⟩
local attribute [instance] regular_open_has_Sup
lemma Sup_unfold {𝒜 : set (regular_opens α)} : Sup 𝒜 = regular_open.Sup 𝒜 := rfl
lemma regular_open_le_Sup :
∀ (s : set (regular_opens α)) (a : {S // is_regular S}), a ∈ s → a ≤ has_Sup.Sup s :=
begin
intros s a Ha, intros x Hx, unfold has_Sup.Sup regular_open.Sup,
simp, suffices : x ∈ (⋃ (x : {S // is_regular S}) (H : x ∈ s), x.val),
apply subset_int_cl_of_open, {apply is_open_Union, intros, apply is_open_Union,
intros, from is_open_of_is_regular i.property},
simp, use a, tidy, recover
end
lemma regular_open_Sup_le :
∀ (s : set (regular_opens α)) (a : {S // is_regular S}),
(∀ (b : {S // is_regular S}), b ∈ s → b ≤ a) → has_Sup.Sup s ≤ a :=
begin
intros 𝒜 A H,
unfold has_Sup.Sup regular_open_has_Sup regular_open.Sup, simp,
suffices : (⋃ (x : {S // is_regular S}) (H : x ∈ 𝒜), x.val)ᵖᵖ ⊆ A.val,
by tidy,
apply is_regular_stable_subset, from A.property, tidy
end
lemma perp_self_empty {S : set α} : S ∩ (Sᵖ) = ∅ :=
by tidy
lemma inf_unfold {x₁ x₂ : (regular_opens α)} : (x₁ ⊓ x₂) = ⟨x₁.val ∩ x₂.val, is_regular_inter x₁.property x₂.property⟩ :=
by refl
local attribute [simp, priority 0] inf_unfold
lemma neg_unfold {x : (regular_opens α)} : (- x) = ⟨xᵖ, by {rw[regular_iff_p_p], symmetry, apply p_eq_p_p_p,
from is_open_of_is_regular x.property}⟩ := by refl
local attribute [simp, priority 0] neg_unfold
@[simp]lemma neg_neg_eq_self {x : (regular_opens α)} : - - x = x :=
begin
simp, apply subtype.eq, simp, apply is_regular_eq_p_p, from x.property
end
local attribute [simp] neg_neg_eq_self
lemma sup_unfold {x₁ x₂ : (regular_opens α)} :
(x₁ ⊔ x₂) = ⟨(x₁.val ∪ x₂.val)ᵖᵖ, by {apply is_regular_sup}⟩ := by refl
local attribute [simp, priority 0] sup_unfold
lemma top_unfold : (⊤ : (regular_opens α)).val = set.univ := rfl
local attribute [simp, priority 0] top_unfold
lemma regular_open_inf_neg_eq_bot : ∀ (x : (regular_opens α)), x ⊓ -x = ⊥ :=
by {tidy, suffices : x_val ∩ (x_valᵖ) = (⊥ : (regular_opens α)).val, apply subtype.eq,
from this, from perp_self_empty}
lemma regular_open_sup_neg_eq_top : ∀ (x : (regular_opens α)), x ⊔ -x = ⊤ :=
begin
intro x, apply subtype.eq, simp, ext, split; intros, trivial,
tidy, unfold is_regular at x_property, rw[<-x_property] at a_1,
suffices : cl x_val ∪ - x_val = univ,
{rw[this] at a_1, apply a_1, simp},
tidy, by_cases x ∈ x_val,
left, from subset_closure h,
right, from ‹_›
end
def regular_open_boolean_algebra : boolean_algebra (regular_opens α) :=
{le_sup_inf :=
begin
intros x y z,
intros a Ha, simp only [inf_unfold, sup_unfold] at Ha ⊢,
rw[<-p_p_inter_eq_inter_p_p] at Ha,
suffices : (x.val ∪ y.val) ∩ (x.val ∪ z.val) ⊆ x.val ∪ y.val ∩ z.val,
by {apply p_p_mono; from ‹_›},
simp only [inter_distrib_left, inter_distrib_right],
tactic.rotate 1,
from is_open_union (is_open_of_is_regular x.property) (is_open_of_is_regular y.property),
from is_open_union (is_open_of_is_regular x.property) (is_open_of_is_regular z.property),
/- `tidy` says -/ intros a_1 a_2, cases a_2, cases z, cases y, cases x,
work_on_goal 0 { cases a_2, work_on_goal 0 { cases a_2, dsimp at *, simp at *,
cases Ha, cases Ha_h, cases Ha_h_w, cc },
cases a_2, dsimp at *, simp at *, cases Ha, cases Ha_h, cases Ha_h_w, cc },
cases a_2, cases z, cases y, cases x,
work_on_goal 0 { cases a_2, dsimp at *, simp at *, cases Ha, cases Ha_h, cases Ha_h_w, cc },
cases a_2, cases z, cases y, cases x, dsimp at *, simp at *,
cases Ha, cases Ha_h, cases Ha_h_w, cc
end,
sub := λ A B, A ⊓ (-B),
inf_neg_eq_bot := regular_open_inf_neg_eq_bot,
sup_neg_eq_top := regular_open_sup_neg_eq_top,
sub_eq := by {intros x y, refl},
.. regular_open_has_neg,
.. regular_open_bounded_lattice
}
local attribute [instance] regular_open_boolean_algebra
def regular_open_has_Inf : has_Inf (regular_opens α) :=
{ Inf := λ 𝒮, ⟨regular_open.neg ((Sup) ((λ x : (regular_opens α), -x) '' 𝒮)),
begin
rw[regular_iff_p_p], change (_)ᵖᵖᵖ = (_)ᵖ, symmetry,
apply p_eq_p_p_p, rw[Sup_unfold], simp[regular_open.Sup]
end⟩ }
local attribute [instance] regular_open_has_Inf
include α
@[simp]lemma Inf_unfold : ∀ s : set (regular_opens α), Inf s = - Sup ((λ x, - x) '' s) :=
by tidy
lemma regular_open_Inf_le : ∀s : set (regular_opens α), ∀a ∈ s, Inf s ≤ a :=
begin
intros 𝒜 A H_mem,
rw[show A = - - A, from (lattice.neg_neg).symm],
have := lattice.neg_le_neg _,
convert this, apply regular_open_le_Sup, use A, tidy
end
lemma regular_open_le_Inf : ∀(s : set (regular_opens α)) a, (∀b∈s, a ≤ b) → a ≤ Inf s :=
begin
intros 𝒜 A H_mme, rw[show A = - - A, from (lattice.neg_neg).symm],
rw[Inf_unfold], apply lattice.neg_le_neg _,
have := regular_open_Sup_le _ _ _,
convert this, intros, specialize H_mme (-b),
simp[-neg_unfold] at a,
rcases a with ⟨w,⟨h₁,⟨h₂,h₃⟩⟩⟩,
suffices : A ≤ -b,
replace this := lattice.neg_le_neg this,
convert this, symmetry, apply neg_neg_eq_self,
replace h₃ := (congr_arg (λ x, - x) h₃).symm,
dsimp at h₃, simp only [h₃] at *,
apply H_mme, simp*
end
def regular_open_complete_lattice : complete_lattice (regular_opens α) :=
{le_Sup := regular_open_le_Sup,
Sup_le := regular_open_Sup_le,
Inf_le := regular_open_Inf_le,
le_Inf := regular_open_le_Inf,
.. regular_open_boolean_algebra,
.. regular_open_has_Inf,
.. regular_open_has_Sup,
.. regular_open_has_neg,
.. regular_open_bounded_lattice}
local attribute [instance] regular_open_complete_lattice
lemma regular_open_inf_Sup_le_supr_inf : ∀(a : (regular_opens α)) s, a ⊓ Sup s ≤ (⨆ b ∈ s, a ⊓ b) :=
begin
letI : complete_lattice (regular_opens α) := by apply_instance,
intros A 𝒜, rw[inf_comm], rw[deduction], let X := _, change _ ≤ X, have := Sup_le, show Type u_1, from (regular_opens α),
show complete_lattice _, dsimp, apply_instance, dsimp at this,
tactic.rotate 2, from X, apply this, dsimp[X], intros B H_B, rw[<-deduction],
rw[inf_comm], have := le_supr_of_le, tactic.rotate 1, from (regular_opens α), tactic.rotate 1,
apply_instance, from λ (b : subtype is_regular), ⨆(H : b ∈ 𝒜), A ⊓ b, from A ⊓ B,
specialize this B, apply this, have := @le_supr_of_le (regular_opens α) (B ∈ 𝒜) _,
apply this, from ‹_›, apply regular_open_poset.le_refl
end
lemma shift_neg_right {a b : (regular_opens α)} (h : a = -b) : -a = b :=
by {rw[h], from lattice.neg_neg}
lemma regular_open_infi_sup_le_sup_Inf : ∀(a : (regular_opens α)) s, (⨅ b ∈ s, a ⊔ b) ≤ a ⊔ Inf s :=
begin
intros A 𝒜,
have : A ⊔ Inf 𝒜 = -(-A ⊓ -(Inf 𝒜)),
by {symmetry, apply shift_neg_right, rw[neg_sup]},
rw[this], apply' neg_le_neg',
unfold infi,
simp only[Inf_unfold], have this₁ := @lattice.neg_neg (regular_opens α) _ _,
rw[this₁], have this₂ := @lattice.neg_neg (regular_opens α) _ _, rw[this₂],
have this' := @le_trans (regular_opens α) _,
have := @regular_open_inf_Sup_le_supr_inf α _ (-A) (has_neg.neg '' 𝒜),
have this_le := @le_trans (regular_opens α) _, specialize this_le this,
swap, from Sup
(has_neg.neg '' range (λ (b : {S // is_regular S}), -Sup (has_neg.neg '' range (λ (H : b ∈ 𝒜), A ⊔ b)))),
rw[inf_comm], rw[deduction], have := @Sup_le (regular_opens α) _ (has_neg.neg '' 𝒜),
let X := _, change _ ≤ X, specialize @this X, apply this, intros b Hb, dsimp[X], rw[<-deduction, inf_comm],
clear this_le, simp only [mem_image] at Hb, cases Hb with b' Hb', rcases Hb' with ⟨H'', ⟨Hb''₁, Hb''₂⟩⟩,
change -A ⊓ -(b') ≤ _,
have : -A ⊓ (-b') = -(A ⊔ b'), by {rw[<-neg_sup]}, rw[this],
have := @le_Sup (regular_opens α) _ (has_neg.neg '' range (λ (b : subtype is_regular), -Sup (has_neg.neg '' range (λ (H : b ∈ 𝒜), A ⊔ b)))),
apply this, simp only [mem_image],
use (A ⊔ b'), split, apply mem_range.mpr,
use b', apply shift_neg_right, clear this,
refine le_antisymm _ _, apply' Sup_le,
intros b'' Hb'',
simp at Hb'', rcases Hb'' with ⟨w, ⟨⟨Hw₁, Hw₂⟩, ⟨Hw₃, Hw₄⟩⟩⟩,
rw[<-Hw₄], replace Hw₂ := (congr_arg perp Hw₂).symm,
simp only [Hw₂], apply le_of_eq _, refl,
apply' le_Sup, simp only [mem_range, mem_image], use (A ⊔ b'), use H'',
refl, refl
end
def regular_open_algebra [H_nonempty : nonempty α] :
nontrivial_complete_boolean_algebra (regular_opens α) :=
{infi_sup_le_sup_Inf := regular_open_infi_sup_le_sup_Inf,
inf_Sup_le_supr_inf := regular_open_inf_Sup_le_supr_inf,
bot_lt_top :=
by {apply lt_iff_le_and_ne.mpr, split,
have := regular_open_bounded_lattice.bot_le, specialize this ⊤,
from this, intro H, simp[subtype.ext] at H,
change (∅ : set α) = univ at H, tactic.unfreeze_local_instances,
cases H_nonempty, suffices : H_nonempty ∈ (∅ : set α), by {cases this}, simp[H]},
.. regular_open_boolean_algebra,
..regular_open_complete_lattice
}
lemma p_p_eq_univ_of_dense {S : set α} (H_dense : dense S) : Sᵖᵖ = univ :=
by simp only [perp_unfold, closure_univ_of_dense H_dense,
set.compl_univ, closure_empty, set.compl_empty]
lemma p_p_eq_univ_of_rel_dense_of_open {S₀ : set α} {S : set α} (H_open : is_open S₀) (H_rel_dense : rel_dense S₀ S) : S₀ ∩ Sᵖᵖ = S₀ :=
begin
simp [perp_unfold], have := closure_rel_dense_of_open H_open H_rel_dense,
have : S₀ = int S₀, by simp*, {[smt] eblast_using [interior_inter]}
end
lemma Sup_eq_top_of_dense_Union {ι} {rO : ι → regular_opens α}
(H_dense : dense $ ⋃₀(subtype.val '' range (λ (i : ι), rO i)))
: (⨆i, rO i : regular_opens α) = ⊤ :=
by {change Sup _ = _, rw[Sup_unfold], exact subtype.ext.mpr (p_p_eq_univ_of_dense ‹_›)}
lemma Sup_eq_top_of_dense_Union_rel {ι} {rO : ι → regular_opens α} (S : regular_opens α)
(H_dense : rel_dense S.1 $ ⋃₀(subtype.val '' range (λ (i : ι), rO i)))
: ((⨆i, rO i : regular_opens α) ⊓ S = S) :=
begin
{change (Sup _) ⊓ _ = _, rw Sup_unfold, have := (p_p_eq_univ_of_rel_dense_of_open (is_open_of_is_regular S.property) ‹_›), rw inter_comm at this, exact subtype.ext.mpr this}
end
open cardinal function
local attribute [instance, priority 0] subtype.preorder
lemma CCC_regular_opens (h : countable_chain_condition α) : CCC (regular_opens α) :=
begin
intros β O hO h2O,
have O_inj : injective (subtype.val ∘ O),
{ apply injective_comp subtype.val_injective, intros x y hxy,
by_contra, apply not_le_of_gt (hO y),
have := h2O _ _ a, rwa [hxy, inf_self] at this },
have := h (range (subtype.val ∘ O)) _ _,
rw [countable_iff] at this, convert this using 1,
{ rw [mk_range_eq], exact O_inj },
{ rintro _ ⟨x, rfl⟩, exact is_open_of_is_regular (O x).2 },
{ rintro _ ⟨x, rfl⟩ _ ⟨y, rfl⟩ hxy,
have : x ≠ y, { intro h, apply hxy, exact congr_arg (subtype.val ∘ O) h },
rw [disjoint_iff_eq_empty], refine subset.antisymm _ (empty_subset _), exact h2O _ _ this }
end
local attribute [instance, priority 10] regular_open_algebra
lemma regular_open.bot_lt [nonempty α] {o : regular_opens α} : ⊥ < o ↔ ∃x, x ∈ (o : set α) :=
by { refine bot_lt_iff_ne_bot.trans _,
rw [← set.ne_empty_iff_exists_mem], rw [← subtype.val_injective.ne_iff], refl }
lemma fst_Sup [nonempty α] {f : set (regular_opens α)} : ↑(Sup f) = (Sup (subtype.val '' f))ᵖᵖ :=
by refl
lemma fst_supr [nonempty α] {ι} {f : ι → regular_opens α} : ↑(⨆ i, f i) = (⨆ i, (f i).1)ᵖᵖ :=
by { rw [supr, fst_Sup], congr' 3, rw [range_comp] }
lemma fst_Inf [nonempty α] {f : set (regular_opens α)} : ↑(Inf f) = (Inf (subtype.val '' f))ᵖᵖ :=
begin
rw [Inf_unfold, neg_unfold], dsimp,
rw [fst_Sup, ← p_eq_p_p_p, image_image],
{ refine eq.trans _ (perp_sUnion_perp _),
{ rw [image_image], refl },
intros s hs, rw [mem_image] at hs, rcases hs with ⟨t, ht, rfl⟩, exact t.2 },
apply _root_.is_open_sUnion,
intros t ht, rw [mem_image] at ht, rcases ht with ⟨t, ht, rfl⟩, exact is_open_of_is_regular t.2
end
lemma fst_infi [nonempty α] {ι} {f : ι → regular_opens α} : ↑(⨅ i, f i) = (⨅ i, (f i).1)ᵖᵖ :=
by { rw [infi, fst_Inf], congr' 3, rw [range_comp] }
lemma fst_infi' [nonempty α] {ι} {f : ι → regular_opens α} : (⨅ i, f i).1 = (⨅ i, (f i).1)ᵖᵖ :=
by { convert fst_infi, from ‹_› }
-- lemma fst_infi' [nonempty α] {ι} {f : ι → regular_opens α} : ↑(⨅ i, f i) = int (⨅ i, (f i).1) :=
-- sorry
end regular_algebra
|
103df93ddeff198542ccddba4f5b132173051895 | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /src/Lean/Server/Watchdog.lean | e10edeabfbb95363adac1fe8e6b64935dc3b0020 | [
"Apache-2.0"
] | permissive | collares/lean4 | 861a9269c4592bce49b71059e232ff0bfe4594cc | 52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee | refs/heads/master | 1,691,419,031,324 | 1,618,678,138,000 | 1,618,678,138,000 | 358,989,750 | 0 | 0 | Apache-2.0 | 1,618,696,333,000 | 1,618,696,333,000 | null | UTF-8 | Lean | false | false | 25,292 | lean | /-
Copyright (c) 2020 Marc Huisinga. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Marc Huisinga, Wojciech Nawrocki
-/
import Init.System.IO
import Init.Data.ByteArray
import Std.Data.RBMap
import Lean.Elab.Import
import Lean.Data.Lsp
import Lean.Server.FileSource
import Lean.Server.Utils
/-!
For general server architecture, see `README.md`. This module implements the watchdog process.
## Watchdog state
Most LSP clients only send us file diffs, so to facilitate sending entire file contents to freshly restarted
workers, the watchdog needs to maintain the current state of each file. It can also use this state to detect changes
to the header and thus restart the corresponding worker, freeing its imports.
TODO(WN):
We may eventually want to keep track of approximately (since this isn't knowable exactly) where in the file a worker
crashed. Then on restart, we tell said worker to only parse up to that point and query the user about how to proceed
(continue OR allow the user to fix the bug and then continue OR ..). Without this, if the crash is deterministic,
users may be confused about why the server seemingly stopped working for a single file.
## Watchdog <-> worker communication
The watchdog process and its file worker processes communicate via LSP. If the necessity arises,
we might add non-standard commands similarly based on JSON-RPC. Most requests and notifications
are forwarded to the corresponding file worker process, with the exception of these notifications:
- textDocument/didOpen: Launch the file worker, create the associated watchdog state and launch a task to
asynchronously receive LSP packets from the worker (e.g. request responses).
- textDocument/didChange: Update the local file state. If the header was mutated,
signal a shutdown to the file worker by closing the I/O channels.
Then restart the file worker. Otherwise, forward the `didChange` notification.
- textDocument/didClose: Signal a shutdown to the file worker and remove the associated watchdog state.
Moreover, we don't implement the full protocol at this level:
- Upon starting, the `initialize` request is forwarded to the worker, but it must not respond with its server
capabilities. Consequently, the watchdog will not send an `initialized` notification to the worker.
- After `initialize`, the watchdog sends the corresponding `didOpen` notification with the full current state of
the file. No additional `didOpen` notifications will be forwarded to the worker process.
- `$/cancelRequest` notifications are forwarded to all file workers.
- File workers are always terminated with an `exit` notification, without previously receiving a `shutdown` request.
Similarly, they never receive a `didClose` notification.
## Watchdog <-> client communication
The watchdog itself should implement the LSP standard as closely as possible. However we reserve the right to add
non-standard extensions in case they're needed, for example to communicate tactic state.
-/
namespace Lean.Server.Watchdog
open IO
open Std (RBMap RBMap.empty)
open Lsp
open JsonRpc
section Utils
structure OpenDocument where
meta : DocumentMeta
headerAst : Syntax
def workerCfg : Process.StdioConfig := {
stdin := Process.Stdio.piped
stdout := Process.Stdio.piped
-- We pass workers' stderr through to the editor.
stderr := Process.Stdio.inherit
}
/-- Events that worker-specific tasks signal to the main thread. -/
inductive WorkerEvent where
/- A synthetic event signalling that the grouped edits should be processed. -/
| processGroupedEdits
| terminated
| crashed (e : IO.Error)
| ioError (e : IO.Error)
inductive WorkerState where
/- The watchdog can detect a crashed file worker in two places: When trying to send a message to the file worker
and when reading a request reply.
In the latter case, the forwarding task terminates and delegates a `crashed` event to the main task.
Then, in both cases, the file worker has its state set to `crashed` and requests that are in-flight are errored.
Upon receiving the next packet for that file worker, the file worker is restarted and the packet is forwarded
to it. If the crash was detected while writing a packet, we queue that packet until the next packet for the file
worker arrives. -/
| crashed (queuedMsgs : Array JsonRpc.Message)
| running
abbrev PendingRequestMap := RBMap RequestID JsonRpc.Message (fun a b => Decidable.decide (a < b))
private def parseHeaderAst (input : String) : IO Syntax := do
let inputCtx := Parser.mkInputContext input "<input>"
let (stx, _, _) ← Parser.parseHeader inputCtx
return stx
end Utils
section FileWorker
/-- A group of edits which will be processed at a future instant. -/
structure GroupedEdits where
/-- When to process the edits. -/
applyTime : Nat
params : DidChangeTextDocumentParams
/-- Signals when `applyTime` has been reached. -/
signalTask : Task WorkerEvent
/-- We should not reorder messages when delaying edits, so we queue other messages since the last request here. -/
queuedMsgs : Array JsonRpc.Message
structure FileWorker where
doc : OpenDocument
proc : Process.Child workerCfg
commTask : Task WorkerEvent
state : WorkerState
-- This should not be mutated outside of namespace FileWorker, as it is used as shared mutable state
pendingRequestsRef : IO.Ref PendingRequestMap
groupedEditsRef : IO.Ref (Option GroupedEdits)
namespace FileWorker
def stdin (fw : FileWorker) : FS.Stream :=
FS.Stream.ofHandle fw.proc.stdin
def stdout (fw : FileWorker) : FS.Stream :=
FS.Stream.ofHandle fw.proc.stdout
def readMessage (fw : FileWorker) : IO JsonRpc.Message := do
let msg ← fw.stdout.readLspMessage
if let Message.response id _ := msg then
fw.pendingRequestsRef.modify (fun pendingRequests => pendingRequests.erase id)
if let Message.responseError id _ _ _ := msg then
fw.pendingRequestsRef.modify (fun pendingRequests => pendingRequests.erase id)
return msg
def errorPendingRequests (fw : FileWorker) (hError : FS.Stream) (code : ErrorCode) (msg : String) : IO Unit := do
let pendingRequests ← fw.pendingRequestsRef.modifyGet (fun pendingRequests => (pendingRequests, RBMap.empty))
for ⟨id, _⟩ in pendingRequests do
hError.writeLspResponseError { id := id, code := code, message := msg }
partial def runEditsSignalTask (fw : FileWorker) : IO (Task WorkerEvent) := do
-- check `applyTime` in a loop since it might have been postponed by a subsequent edit notification
let rec loopAction : IO WorkerEvent := do
let now ← monoMsNow
let some ge ← fw.groupedEditsRef.get
| throwServerError "Internal error: empty grouped edits reference in signal task"
if ge.applyTime ≤ now then
return WorkerEvent.processGroupedEdits
else
IO.sleep <| UInt32.ofNat <| ge.applyTime - now
loopAction
let t ← IO.asTask loopAction
return t.map fun
| Except.ok ev => ev
| Except.error e => WorkerEvent.ioError e
end FileWorker
end FileWorker
section ServerM
abbrev FileWorkerMap := RBMap DocumentUri FileWorker (fun a b => Decidable.decide (a < b))
structure ServerContext where
hIn : FS.Stream
hOut : FS.Stream
hLog : FS.Stream
/-- Command line arguments. -/
args : List String
fileWorkersRef : IO.Ref FileWorkerMap
/-- We store these to pass them to workers. -/
initParams : InitializeParams
editDelay : Nat
workerPath : String
abbrev ServerM := ReaderT ServerContext IO
def updateFileWorkers (val : FileWorker) : ServerM Unit := do
(←read).fileWorkersRef.modify (fun fileWorkers => fileWorkers.insert val.doc.meta.uri val)
def findFileWorker (uri : DocumentUri) : ServerM FileWorker := do
match (←(←read).fileWorkersRef.get).find? uri with
| some fw => fw
| none => throwServerError s!"Got unknown document URI ({uri})"
def eraseFileWorker (uri : DocumentUri) : ServerM Unit := do
(←read).fileWorkersRef.modify (fun fileWorkers => fileWorkers.erase uri)
def log (msg : String) : ServerM Unit := do
let st ← read
st.hLog.putStrLn msg
st.hLog.flush
/-- Creates a Task which forwards a worker's messages into the output stream until an event
which must be handled in the main watchdog thread (e.g. an I/O error) happens. -/
private partial def forwardMessages (fw : FileWorker) : ServerM (Task WorkerEvent) := do
let o := (←read).hOut
let rec loop : ServerM WorkerEvent := do
try
let msg ← fw.readMessage
-- Writes to Lean I/O channels are atomic, so these won't trample on each other.
o.writeLspMessage msg
catch err =>
-- If writeLspMessage from above errors we will block here, but the main task will
-- quit eventually anyways if that happens
let exitCode ← fw.proc.wait
if exitCode = 0 then
-- Worker was terminated
fw.errorPendingRequests o ErrorCode.contentModified
("The file worker has been terminated. Either the header has changed,"
++ " or the file was closed, or the server is shutting down.")
return WorkerEvent.terminated
else
-- Worker crashed
fw.errorPendingRequests o ErrorCode.internalError
s!"Server process for {fw.doc.meta.uri} crashed, {if exitCode = 1 then "see stderr for exception" else "likely due to a stack overflow in user code"}."
return WorkerEvent.crashed err
loop
let task ← IO.asTask (loop $ ←read) Task.Priority.dedicated
task.map $ fun
| Except.ok ev => ev
| Except.error e => WorkerEvent.ioError e
def startFileWorker (m : DocumentMeta) : ServerM Unit := do
let st ← read
let headerAst ← parseHeaderAst m.text.source
let workerProc ← Process.spawn {
toStdioConfig := workerCfg
cmd := st.workerPath
args := #["--worker"] ++ st.args.toArray
}
let pendingRequestsRef ← IO.mkRef (RBMap.empty : PendingRequestMap)
-- The task will never access itself, so this is fine
let fw : FileWorker := {
doc := ⟨m, headerAst⟩
proc := workerProc
commTask := Task.pure WorkerEvent.terminated
state := WorkerState.running
pendingRequestsRef := pendingRequestsRef
groupedEditsRef := ← IO.mkRef none
}
let commTask ← forwardMessages fw
let fw : FileWorker := { fw with commTask := commTask }
fw.stdin.writeLspRequest ⟨0, "initialize", st.initParams⟩
fw.stdin.writeLspNotification {
method := "textDocument/didOpen"
param := {
textDocument := {
uri := m.uri
languageId := "lean"
version := m.version
text := m.text.source
} : DidOpenTextDocumentParams
}
}
updateFileWorkers fw
def terminateFileWorker (uri : DocumentUri) : ServerM Unit := do
/- The file worker must have crashed just when we were about to terminate it!
That's fine - just forget about it then.
(on didClose we won't need the crashed file worker anymore,
when the header changed we'll start a new one right after
anyways and when we're shutting down the server
it's over either way.) -/
try (←findFileWorker uri).stdin.writeLspMessage (Message.notification "exit" none)
catch err => ()
eraseFileWorker uri
def handleCrash (uri : DocumentUri) (queuedMsgs : Array JsonRpc.Message) : ServerM Unit := do
updateFileWorkers { ←findFileWorker uri with state := WorkerState.crashed queuedMsgs }
/-- Tries to write a message, sets the state of the FileWorker to `crashed` if it does not succeed
and restarts the file worker if the `crashed` flag was already set.
Messages that couldn't be sent can be queued up via the queueFailedMessage flag and
will be discharged after the FileWorker is restarted. -/
def tryWriteMessage (uri : DocumentUri) (msg : JsonRpc.Message) (queueFailedMessage := true) (restartCrashedWorker := false) :
ServerM Unit := do
let fw ← findFileWorker uri
let pendingEdit ← fw.groupedEditsRef.modifyGet fun
| some ge => (true, some { ge with queuedMsgs := ge.queuedMsgs.push msg })
| none => (false, none)
if pendingEdit then
return
match fw.state with
| WorkerState.crashed queuedMsgs =>
let mut queuedMsgs := queuedMsgs
if queueFailedMessage then
queuedMsgs := queuedMsgs.push msg
if !restartCrashedWorker then
return
-- restart the crashed FileWorker
eraseFileWorker uri
startFileWorker fw.doc.meta
let newFw ← findFileWorker uri
let mut crashedMsgs := #[]
-- try to discharge all queued msgs, tracking the ones that we can't discharge
for msg in queuedMsgs do
try
newFw.stdin.writeLspMessage msg
catch _ =>
crashedMsgs := crashedMsgs.push msg
if ¬ crashedMsgs.isEmpty then
handleCrash uri crashedMsgs
| WorkerState.running =>
let initialQueuedMsgs :=
if queueFailedMessage then
#[msg]
else
#[]
try
fw.stdin.writeLspMessage msg
catch _ =>
handleCrash uri initialQueuedMsgs
end ServerM
section NotificationHandling
def handleDidOpen (p : DidOpenTextDocumentParams) : ServerM Unit :=
let doc := p.textDocument
/- NOTE(WN): `toFileMap` marks line beginnings as immediately following
"\n", which should be enough to handle both LF and CRLF correctly.
This is because LSP always refers to characters by (line, column),
so if we get the line number correct it shouldn't matter that there
is a CR there. -/
startFileWorker ⟨doc.uri, doc.version, doc.text.toFileMap⟩
def handleEdits (fw : FileWorker) : ServerM Unit := do
let some ge ← fw.groupedEditsRef.modifyGet (·, none)
| throwServerError "Internal error: empty grouped edits reference"
let doc := ge.params.textDocument
let changes := ge.params.contentChanges
let oldDoc := fw.doc
let some newVersion ← pure doc.version?
| throwServerError "Expected version number"
if newVersion <= oldDoc.meta.version then
throwServerError "Got outdated version number"
if changes.isEmpty then
return
let (newDocText, _) := foldDocumentChanges changes oldDoc.meta.text
let newMeta : DocumentMeta := ⟨doc.uri, newVersion, newDocText⟩
let newHeaderAst ← parseHeaderAst newDocText.source
if newHeaderAst != oldDoc.headerAst then
terminateFileWorker doc.uri
startFileWorker newMeta
else
let newDoc : OpenDocument := ⟨newMeta, oldDoc.headerAst⟩
updateFileWorkers { fw with doc := newDoc }
tryWriteMessage doc.uri (Notification.mk "textDocument/didChange" ge.params) (restartCrashedWorker := true)
for msg in ge.queuedMsgs do
tryWriteMessage doc.uri msg
def handleDidClose (p : DidCloseTextDocumentParams) : ServerM Unit :=
terminateFileWorker p.textDocument.uri
def handleCancelRequest (p : CancelParams) : ServerM Unit := do
let fileWorkers ← (←read).fileWorkersRef.get
for ⟨uri, fw⟩ in fileWorkers do
let req? ← fw.pendingRequestsRef.modifyGet (fun pendingRequests =>
(pendingRequests.find? p.id, pendingRequests.erase p.id))
if let some req := req? then
tryWriteMessage uri (Notification.mk "$/cancelRequest" p) (queueFailedMessage := false)
end NotificationHandling
section MessageHandling
def parseParams (paramType : Type) [FromJson paramType] (params : Json) : ServerM paramType :=
match fromJson? params with
| some parsed => pure parsed
| none => throwServerError s!"Got param with wrong structure: {params.compress}"
def handleRequest (id : RequestID) (method : String) (params : Json) : ServerM Unit := do
let handle := fun α [FromJson α] [ToJson α] [FileSource α] => do
let parsedParams ← parseParams α params
let uri := fileSource parsedParams
let fw ← try
findFileWorker uri
catch _ =>
-- VS Code sometimes sends us requests just after closing a file?
-- This is permitted by the spec, but seems pointless, and there's not much we can do,
-- so we return an error instead.
(←read).hOut.writeLspResponseError
{ id := id
code := ErrorCode.contentModified
message := s!"Cannot process request to closed file '{uri}'" }
return
let r := Request.mk id method params
fw.pendingRequestsRef.modify (·.insert id r)
tryWriteMessage uri r
match method with
| "textDocument/waitForDiagnostics" => handle WaitForDiagnosticsParams
| "textDocument/completion" => handle CompletionParams
| "textDocument/hover" => handle HoverParams
| "textDocument/declaration" => handle DeclarationParams
| "textDocument/definition" => handle DefinitionParams
| "textDocument/typeDefinition" => handle TypeDefinitionParams
| "textDocument/documentHighlight" => handle DocumentHighlightParams
| "textDocument/documentSymbol" => handle DocumentSymbolParams
| "textDocument/semanticTokens/range" => handle SemanticTokensRangeParams
| "textDocument/semanticTokens/full" => handle SemanticTokensParams
| "$/lean/plainGoal" => handle PlainGoalParams
| _ =>
(←read).hOut.writeLspResponseError
{ id := id
code := ErrorCode.methodNotFound
message := s!"Unsupported request method: {method}" }
def handleNotification (method : String) (params : Json) : ServerM Unit := do
let handle := (fun α [FromJson α] (handler : α → ServerM Unit) => parseParams α params >>= handler)
match method with
| "textDocument/didOpen" => handle DidOpenTextDocumentParams handleDidOpen
/- NOTE: textDocument/didChange is handled in the main loop. -/
| "textDocument/didClose" => handle DidCloseTextDocumentParams handleDidClose
| "$/cancelRequest" => handle CancelParams handleCancelRequest
| _ =>
if !"$/".isPrefixOf method then -- implementation-dependent notifications can be safely ignored
(←read).hLog.putStrLn s!"Got unsupported notification: {method}"
end MessageHandling
section MainLoop
def shutdown : ServerM Unit := do
let fileWorkers ← (←read).fileWorkersRef.get
for ⟨uri, _⟩ in fileWorkers do
terminateFileWorker uri
for ⟨_, fw⟩ in fileWorkers do
discard <| IO.wait fw.commTask
inductive ServerEvent where
| workerEvent (fw : FileWorker) (ev : WorkerEvent)
| clientMsg (msg : JsonRpc.Message)
| clientError (e : IO.Error)
def runClientTask : ServerM (Task ServerEvent) := do
let st ← read
let readMsgAction : IO ServerEvent := do
/- Runs asynchronously. -/
let msg ← st.hIn.readLspMessage
ServerEvent.clientMsg msg
let clientTask := (←IO.asTask readMsgAction).map $ fun
| Except.ok ev => ev
| Except.error e => ServerEvent.clientError e
return clientTask
partial def mainLoop (clientTask : Task ServerEvent) : ServerM Unit := do
let st ← read
let workers ← st.fileWorkersRef.get
let mut workerTasks := #[]
for (_, fw) in workers do
if let WorkerState.running := fw.state then
workerTasks := workerTasks.push <| fw.commTask.map (ServerEvent.workerEvent fw)
if let some ge ← fw.groupedEditsRef.get then
workerTasks := workerTasks.push <| ge.signalTask.map (ServerEvent.workerEvent fw)
let ev ← IO.waitAny (workerTasks.push clientTask |>.toList)
match ev with
| ServerEvent.clientMsg msg =>
match msg with
| Message.request id "shutdown" _ =>
shutdown
st.hOut.writeLspResponse ⟨id, Json.null⟩
| Message.request id method (some params) =>
handleRequest id method (toJson params)
mainLoop (←runClientTask)
| Message.notification "textDocument/didChange" (some params) =>
let p ← parseParams DidChangeTextDocumentParams (toJson params)
let fw ← findFileWorker p.textDocument.uri
let now ← monoMsNow
/- We wait `editDelay`ms since last edit before applying the changes. -/
let applyTime := now + st.editDelay
let pendingEdit ← fw.groupedEditsRef.modifyGet fun
| some ge => (true, some { ge with
applyTime := applyTime
params.textDocument := p.textDocument
params.contentChanges := ge.params.contentChanges ++ p.contentChanges
-- drain now-outdated messages and respond with `contentModified` below
queuedMsgs := #[] })
| none => (false, some {
applyTime := applyTime
params := p
/- This is overwritten just below. -/
signalTask := Task.pure WorkerEvent.processGroupedEdits
queuedMsgs := #[] })
if pendingEdit then
fw.errorPendingRequests (←read).hOut ErrorCode.contentModified "File changed."
else
let t ← fw.runEditsSignalTask
fw.groupedEditsRef.modify (Option.map fun ge => { ge with signalTask := t } )
mainLoop (←runClientTask)
| Message.notification method (some params) =>
handleNotification method (toJson params)
mainLoop (←runClientTask)
| _ => throwServerError "Got invalid JSON-RPC message"
| ServerEvent.clientError e => throw e
| ServerEvent.workerEvent fw ev =>
match ev with
| WorkerEvent.processGroupedEdits =>
handleEdits fw
mainLoop clientTask
| WorkerEvent.ioError e =>
throwServerError s!"IO error while processing events for {fw.doc.meta.uri}: {e}"
| WorkerEvent.crashed e =>
handleCrash fw.doc.meta.uri #[]
mainLoop clientTask
| WorkerEvent.terminated =>
throwServerError "Internal server error: got termination event for worker that should have been removed"
end MainLoop
def mkLeanServerCapabilities : ServerCapabilities := {
textDocumentSync? := some {
openClose := true
change := TextDocumentSyncKind.incremental
willSave := false
willSaveWaitUntil := false
save? := none
}
-- refine
completionProvider? := some {
triggerCharacters? := some #["."]
}
hoverProvider := true
declarationProvider := true
definitionProvider := true
typeDefinitionProvider := true
documentHighlightProvider := true
documentSymbolProvider := true
semanticTokensProvider? := some {
legend := {
tokenTypes := SemanticTokenType.names
tokenModifiers := #[]
}
full := true
range := true
}
}
def initAndRunWatchdogAux : ServerM Unit := do
let st ← read
try
discard $ st.hIn.readLspNotificationAs "initialized" InitializedParams
let clientTask ← runClientTask
mainLoop clientTask
let Message.notification "exit" none ← st.hIn.readLspMessage
| throwServerError "Expected an exit notification"
catch err =>
shutdown
throw err
def initAndRunWatchdog (args : List String) (i o e : FS.Stream) : IO Unit := do
let mut workerPath ← IO.appPath
if let some path := (←IO.getEnv "LEAN_SYSROOT") then
workerPath := s!"{path}/bin/lean{System.FilePath.exeSuffix}"
if let some path := (←IO.getEnv "LEAN_WORKER_PATH") then
workerPath := path
let fileWorkersRef ← IO.mkRef (RBMap.empty : FileWorkerMap)
let i ← maybeTee "wdIn.txt" false i
let o ← maybeTee "wdOut.txt" true o
let e ← maybeTee "wdErr.txt" true e
let initRequest ← i.readLspRequestAs "initialize" InitializeParams
o.writeLspResponse {
id := initRequest.id
result := {
capabilities := mkLeanServerCapabilities
serverInfo? := some {
name := "Lean 4 server"
version? := "0.0.1"
}
: InitializeResult
}
}
ReaderT.run initAndRunWatchdogAux {
hIn := i
hOut := o
hLog := e
args := args
fileWorkersRef := fileWorkersRef
initParams := initRequest.param
editDelay := initRequest.param.initializationOptions? |>.bind InitializationOptions.editDelay? |>.getD 200
workerPath := workerPath
: ServerContext
}
@[export lean_server_watchdog_main]
def watchdogMain (args : List String) : IO UInt32 := do
let i ← IO.getStdin
let o ← IO.getStdout
let e ← IO.getStderr
try
initAndRunWatchdog args i o e
return 0
catch err =>
e.putStrLn s!"Watchdog error: {err}"
return 1
end Lean.Server.Watchdog
|
4c7e73da162fd8e25bc6061e9951ebb988148a58 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/data/multiset/sections.lean | 34ca9ce9caa608c2ead17951ec7200e6a97f7fc2 | [
"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 | 2,230 | lean | /-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import data.multiset.basic
/-!
# Sections of a multiset
-/
namespace multiset
variables {α : Type*}
section sections
/--
The sections of a multiset of multisets `s` consists of all those multisets
which can be put in bijection with `s`, so each element is an member of the corresponding multiset.
-/
def sections (s : multiset (multiset α)) : multiset (multiset α) :=
multiset.rec_on s {0} (λs _ c, s.bind $ λa, c.map (multiset.cons 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} :=
rfl
@[simp] lemma sections_cons (s : multiset (multiset α)) (m : multiset α) :
sections (m ::ₘ s) = m.bind (λa, (sections s).map (multiset.cons 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
end multiset
|
9c31e52afb8dd05dbd1c4a6b710ffd8e2bf13b20 | 5b273b8c05e2f73fb74340ce100ce261900a98cd | /sum_between_nats.lean | 950ce389c271a1555c9f995331cc3214f243b03b | [] | no_license | ChrisHughes24/leanstuff1 | 2eba44bc48da6e544e07495b41e1703f81dc1c24 | cbcd788b8b1d07b20b2fff4482c870077a13d1c0 | refs/heads/master | 1,631,670,333,297 | 1,527,093,981,000 | 1,527,093,981,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 19,820 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import data.nat.basic algebra.group data.real.cau_seq tactic.ring data.nat.choose algebra.archimedean
open nat is_absolute_value
variables {α : Type*} {β : Type*}
def series [has_add α] (f : ℕ → α) : ℕ → α
| 0 := f 0
| (n + 1) := series n + f (n + 1)
def sum_between [has_add α] (f : ℕ → α) (n m : ℕ) := series (λ k, f (k + n)) (m - n)
@[simp] lemma series_zero [has_add α] (f : ℕ → α) : series f 0 = f 0 := by unfold series
lemma series_succ [has_add α] (f : ℕ → α) (n : ℕ) : series f (succ n) = series f n + f (succ n):= by unfold series
lemma series_eq_finset_sum [add_comm_monoid α] (f : ℕ → α) (n : ℕ) : series f n = finset.sum (finset.range (succ n)) f := begin
induction n with n' hi,
simp!,rw [finset.range_succ,series_succ],
have : succ n' ∉ (finset.range (succ n')) := by {rw finset.mem_range,
exact lt_irrefl _},
rw [finset.sum_insert this,hi,add_comm],
end
lemma series_succ₁ [add_comm_monoid α] (f : ℕ → α) (i : ℕ) : series f (succ i) = f 0 + series (λ i, f (succ i)) i := begin
induction i with i' hi,
refl,
rw [series_succ, hi, series_succ, add_assoc],
end
lemma series_comm [add_comm_monoid α] (f : ℕ → α) (n : ℕ) : series f n = series (λ i, f (n - i)) n := begin
induction n with n' hi,
simp!,simp!,rw hi,
have : (λ (i : ℕ), f (succ n' - i)) (succ n') = f (n' - n'),simp,
rw ←this,have : (λ (i : ℕ), f (succ n' - i)) (succ n') + series (λ (i : ℕ), f (succ n' - i)) n' = series (λ (i : ℕ), f (succ n' - i)) (succ n'),simp!,
rw this,
have : (λ i, f (n' - i)) = (λ i, f (succ n' - succ i)) := by
{apply funext,assume i,rw succ_sub_succ},
rw this,clear this,
have : f (succ n') = (λ (i : ℕ), f (succ n' - i)) 0,simp,rw this,rw ←series_succ₁,
end
lemma series_neg [ring α] (f : ℕ → α) (n : ℕ) : -series f n = series (λ m, -f m) n := begin
induction n with n' hi, simp!,simp![hi],
end
lemma series_sub_series [ring α] (f : ℕ → α) {i j : ℕ} : i < j → series f j - series f i
= series (λ (k : ℕ), f (k + (i + 1))) (j - (i + 1)) := begin
assume ij,
induction i with i' hi,
cases j with j',exact absurd ij dec_trivial,
rw sub_eq_iff_eq_add',
exact series_succ₁ _ _,
rw [series_succ,sub_add_eq_sub_sub,hi (lt_of_succ_lt ij),sub_eq_iff_eq_add'],
have : (j - (i' + 1)) = succ (j - (succ i' + 1)) := by
{rw [←nat.succ_sub ij,succ_sub_succ]},
rw this,
have : f (succ i') = (λ (k : ℕ), f (k + (i' + 1))) 0 := by simp,
rw this,simp[succ_add,add_succ],
rw series_succ₁,simp,
end
lemma series_const_zero [has_zero α] (i : ℕ): series (λ j, 0) i = 0 := begin
induction i with i' hi,simp,simpa [series_succ],
end
lemma series_add [add_comm_monoid α] (f g : ℕ → α) (n : ℕ) : series (λ i, f i + g i) n = series f n + series g n := begin
induction n with n' hi,simp[series_zero],simp[series_succ,hi],
end
lemma series_mul_left [semiring α] (f : ℕ → α) (a : α) (n : ℕ) : series (λ i, a * f i) n = a * series f n := begin
induction n with n' hi,simp[series_zero],simp[series_succ,hi,mul_add],
end
lemma series_mul_right [semiring α] (f : ℕ → α) (a : α) (n : ℕ) : series (λ i, f i * a) n = series f n * a:= begin
induction n with n' hi,simp[series_zero],simp[series_succ,hi,add_mul],
end
lemma abv_series_le_series_abv [discrete_linear_ordered_field α] [ring β] {f : ℕ → β}
{abv : β → α} [is_absolute_value abv] (n : ℕ) : abv (series f n) ≤ series (λ i, abv (f i)) n := begin
induction n with n' hi,
simp,simp[series_succ],
exact le_trans (abv_add _ _ _) (add_le_add_left hi _),
end
lemma series_mul_series [semiring α] (f g : ℕ → α) (n m : ℕ) : series f n * series g m
= series (λ i, f i * series g m) n := begin
induction n with n' hi,
simp,simp[series_succ,mul_add,add_mul,hi],
end
lemma series_le_series [ordered_cancel_comm_monoid α] {f g : ℕ → α} {n : ℕ} : (∀ m ≤ n, f m ≤ g m) →
series f n ≤ series g n := begin
assume h,induction n with n' hi,exact h 0 (le_refl _),
unfold series,exact add_le_add (hi (λ m hm, h m (le_succ_of_le hm))) (h _ (le_refl _)),
end
lemma series_lt_series [ordered_cancel_comm_monoid α] {f g : ℕ → α} {n : ℕ} : (∀ m ≤ n, f m < g m) →
series f n < series g n := begin
assume h,induction n with n' hi,exact h 0 (le_refl _),
unfold series,exact add_lt_add (hi (λ m hm, h m (le_succ_of_le hm))) (h _ (le_refl _)),
end
lemma series_congr [has_add α] {f g : ℕ → α} {i : ℕ} : (∀ j ≤ i, f j = g j) → series f i = series g i := begin
assume h,induction i with i' hi,exact h 0 (zero_le _),
unfold series,rw h _ (le_refl (succ i')),
rw hi (λ j ji, h j (le_succ_of_le ji)),
end
lemma series_nonneg [ordered_cancel_comm_monoid α] {f : ℕ → α} {n : ℕ} : (∀ m ≤ n, 0 ≤ f m) → 0 ≤ series f n := begin
induction n with n' hi,simp,assume h,exact h 0 (le_refl _),
assume h,unfold series,refine add_nonneg (hi (λ m hm, h m (le_succ_of_le hm))) (h _ (le_refl _)),
end
lemma series_pos [ordered_cancel_comm_monoid α] {f : ℕ → α} {n : ℕ} : (∀ m ≤ n, 0 < f m) → 0 < series f n := begin
induction n with n' hi,simp,assume h,exact h 0 (le_refl _),
assume h,unfold series,refine add_pos (hi (λ m hm, h m (le_succ_of_le hm))) (h _ (le_refl _)),
end
-- proof that two different ways of representing a sum across a 2D plane are equal, used
-- in proof of exp (x + y) = exp x * exp y
lemma series_series_diag_flip [add_comm_monoid α] (f : ℕ → ℕ → α) (n : ℕ) : series (λ i,
series (λ k, f k (i - k)) i) n = series (λ i, series (λ k, f i k) (n - i)) n := begin
have : ∀ m : ℕ, m ≤ n → series (λ (i : ℕ), series (λ k, f k (i - k)) (min m i)) n =
series (λ i, series (λ k, f i k) (n - i)) m := by
{ assume m mn, induction m with m' hi,
simp[series_succ,series_zero,mul_add,max_eq_left (zero_le n)],
simp only [series_succ _ m'],rw ←hi (le_of_succ_le mn),clear hi,
induction n with n' hi,
simp[series_succ],exact absurd mn dec_trivial,cases n' with n₂,
simp [series_succ],rw [min_eq_left mn,series_succ,min_eq_left (le_of_succ_le mn)],
rw eq_zero_of_le_zero (le_of_succ_le_succ mn),simp,
cases lt_or_eq_of_le mn,
simp [series_succ _ (succ n₂),min_eq_left mn,hi (le_of_lt_succ h)],rw [←add_assoc,←add_assoc],
suffices : series (f (succ m')) (n₂ - m') + series (λ (k : ℕ), f k (succ (succ n₂) - k)) (succ m')
= series (f (succ m')) (succ n₂ - m') +
series (λ (k : ℕ), f k (succ (succ n₂) - k)) (min m' (succ (succ n₂))),
rw this,rw[min_eq_left (le_of_succ_le mn),series_succ,succ_sub_succ,succ_sub (le_of_succ_le_succ (le_of_lt_succ h)),series_succ],
rw [add_comm (series (λ (k : ℕ), f k (succ (succ n₂) - k)) m'),add_assoc],
rw ←h,simp[nat.sub_self],clear hi mn h,simp[series_succ,nat.sub_self],
suffices : series (λ (i : ℕ), series (λ (k : ℕ), f k (i - k)) (min (succ m') i)) m' = series (λ (i : ℕ), series (λ (k : ℕ), f k (i - k)) (min m' i)) m',
rw [this,min_eq_left (le_succ _)],clear n₂,
have h₁ : ∀ i ≤ m', (λ (i : ℕ), series (λ (k : ℕ), f k (i - k)) (min (succ m') i)) i = (λ (i : ℕ), series (λ (k : ℕ), f k (i - k)) (min m' i)) i,
assume i im,simp, rw [min_eq_right im,min_eq_right (le_succ_of_le im)],
rw series_congr h₁},
specialize this n (le_refl _),
rw ←this,refine series_congr _,assume i ni,rw min_eq_right ni,
end
open monoid
theorem series_binomial {α : Type*} [comm_semiring α] (x y : α) (i : ℕ) : pow (x + y) i =
series (λ j, choose i j * pow x j * pow y (i - j)) i := begin
induction i with i' hi,
simp!,unfold monoid.pow,rw hi,
rw [←series_mul_left],
have : ∀ j : ℕ, j ≤ i' → (λ (i : ℕ), (x + y) * (↑(choose i' i) * pow x i * pow y (i' - i))) j
= choose i' j * pow x (succ j) * pow y (i' - j) + choose i' j * pow x j * pow y (succ i' - j) := by
{ assume j ji,dsimp only,rw add_mul,
have : x * (↑(choose i' j) * pow x j * pow y (i' - j)) + y * (↑(choose i' j) * pow x j * pow y (i' - j))
= ↑(choose i' j) * (x * pow x j) * pow y (i' - j) + ↑(choose i' j) * pow x j * (y * pow y (i' - j)),
simp[mul_comm,_root_.mul_assoc,mul_left_comm],
rw [this,←_root_.pow_succ,←_root_.pow_succ,succ_sub ji]},
rw [series_congr this],clear this,
clear hi,rw series_add,
have : series (λ (i : ℕ), ↑(choose i' i) * pow x i * pow y (succ i' - i)) i' =
series (λ (i : ℕ), ↑(choose i' i) * pow x i * pow y (succ i' - i)) (succ i') := by
{ simp[series_succ],},
rw [this,series_succ₁,series_succ₁],
simp[nat.sub_self],rw ←series_add,
refine congr_arg _ (series_congr _),
assume j ji,unfold choose,rw [nat.cast_add,add_mul,add_mul],
end
lemma geo_series_eq {α : Type*} [field α] (x : α) (n : ℕ) : x ≠ 1 → series (pow x) n = (1 - pow x (succ n)) / (1 - x) := begin
assume x1,have x1' : 1 + -x ≠ 0,assume h,rw [eq_comm, ←sub_eq_iff_eq_add] at h,simp at h,trivial,
induction n with n' hi,
{simp![div_self x1']},
{rw eq_div_iff_mul_eq,simpa,
rw [_root_.series_succ,_root_.pow_succ _ (succ n')],
rw hi,simp,rw [add_mul,div_mul_cancel _ x1',mul_add],ring,exact x1'},
end
lemma is_cau_geo_series {α : Type*} [discrete_linear_ordered_field α] [archimedean α] (x : α) :
abs x < 1 → is_cau_seq abs (series (pow x)) := begin
assume x1, have : series (pow x) = λ n,(1 - pow x (succ n)) / (1 - x),
apply funext,assume n,refine geo_series_eq x n _ ,assume h, rw h at x1,exact absurd x1 (by norm_num),rw this,
have absx : 0 < abs (1 - x),refine abs_pos_of_ne_zero _,assume h,rw sub_eq_zero_iff_eq at h,rw ←h at x1,
have : ¬abs (1 : α) < 1,norm_num,trivial,simp at absx,
cases classical.em (x = 0),rw h,simp[monoid.pow],assume ε ε0,existsi 1,assume j j1,simpa!,
have x2: 1 < (abs x)⁻¹,rw lt_inv,simpa,{norm_num},exact abs_pos_of_ne_zero h,
have pos_x : 0 < abs x := abs_pos_of_ne_zero h,
assume ε ε0,
cases pow_unbounded_of_gt_one (2 / (ε * abs (1 - x))) x2 with i hi,
have ε2 : 0 < 2 / (ε * abs (1 - x)) := div_pos (by norm_num) (mul_pos ε0 absx),
rw [pow_inv,lt_inv ε2 (pow_pos pos_x _)] at hi,
existsi i,assume j ji,rw [inv_eq_one_div,div_div_eq_mul_div,_root_.one_mul,lt_div_iff (by norm_num : (0 : α) < 2)] at hi,
rw [div_sub_div_same,abs_div,div_lt_iff absx],
refine lt_of_le_of_lt _ hi,
simp,
refine le_trans (abs_add _ _) _,
have : pow (abs x) i * 2 = pow (abs x) i + pow (abs x) i,ring,
rw this,
refine add_le_add _ _,
{rw [←_root_.one_mul (pow (abs x) i),pow_abs,_root_.pow_succ,abs_mul],
exact mul_le_mul_of_nonneg_right (le_of_lt x1) (abs_nonneg _)},
{rw [abs_neg,←pow_abs],
rw [←inv_le_inv (pow_pos pos_x _) (pow_pos pos_x _),←pow_inv,←pow_inv],
refine pow_le_pow (le_of_lt x2) (le_succ_of_le ji),}
end
lemma is_cau_geo_series_const {α : Type*} [discrete_linear_ordered_field α] [archimedean α] (a x : α) :
abs x < 1 → is_cau_seq abs (series (λ n, a * pow x n)) := begin
assume x1 ε ε0,
cases classical.em (a = 0),
existsi 0,intros,rw [series_mul_left],induction j,simp!,assumption,rw h,simpa!,
cases is_cau_geo_series x x1 (ε / abs a) (div_pos ε0 (abs_pos_of_ne_zero h)) with i hi,
existsi i,assume j ji,rw [series_mul_left,series_mul_left,←mul_sub,abs_mul,mul_comm,←lt_div_iff],
exact hi j ji,exact abs_pos_of_ne_zero h,
end
lemma is_cau_series_of_abv_le_cau {α : Type*} {β : Type*} [discrete_linear_ordered_field α] [ring β] {f : ℕ → β}
{g : ℕ → α} {abv : β → α} [is_absolute_value abv] (n : ℕ) : (∀ m, n ≤ m → abv (f m) ≤ g m) →
is_cau_seq abs (series g) → is_cau_seq abv (series f) := begin
assume hm hg ε ε0,cases hg (ε / 2) (div_pos ε0 (by norm_num)) with i hi,
existsi max n i,
assume j ji,
have hi₁ := hi j (le_trans (le_max_right n i) ji),
have hi₂ := hi (max n i) (le_max_right n i),
have sub_le := abs_sub_le (series g j) (series g i) (series g (max n i)),
have := add_lt_add hi₁ hi₂,rw abs_sub (series g (max n i)) at this,
have ε2 : ε / 2 + ε / 2 = ε,ring,
rw ε2 at this,
refine lt_of_le_of_lt _ this,
refine le_trans _ sub_le,
refine le_trans _ (le_abs_self _),
generalize hk : j - max n i = k,clear this ε2 hi₂ hi₁ hi ε0 ε hg sub_le,
rw nat.sub_eq_iff_eq_add ji at hk,rw hk, clear hk ji j,
induction k with k' hi,simp,rw abv_zero abv,
rw succ_add,unfold series,
rw [add_comm,add_sub_assoc],
refine le_trans (abv_add _ _ _) _,
rw [add_comm (series g (k' + max n i)),add_sub_assoc],
refine add_le_add _ _,
refine hm _ _,rw [←zero_add n,←succ_add],refine add_le_add _ _,exact zero_le _,
simp, exact le_max_left _ _,assumption,
end
-- The form of ratio test with 0 ≤ r < 1, and abv (f (succ m)) ≤ r * abv (f m) handled zero terms of series the best
lemma series_ratio_test {α : Type*} {β : Type*} [discrete_linear_ordered_field α] [ring β]
[archimedean α] {abv : β → α} [is_absolute_value abv] {f : ℕ → β} (n : ℕ) (r : α) :
0 ≤ r → r < 1 → (∀ m, n ≤ m → abv (f (succ m)) ≤ r * abv (f m)) → is_cau_seq abv (series f)
:= begin
assume r0 r1 h,
refine is_cau_series_of_abv_le_cau (succ n) _ (is_cau_geo_series_const (abv (f (succ n)) * pow r⁻¹ (succ n)) r _),
assume m mn,
generalize hk : m - (succ n) = k,rw nat.sub_eq_iff_eq_add mn at hk,
cases classical.em (r = 0) with r_zero r_pos,have m_pos := lt_of_lt_of_le (succ_pos n) mn,
have := pred_le_pred mn,simp at this,
have := h (pred m) this,simp[r_zero,succ_pred_eq_of_pos m_pos] at this,
refine le_trans this _,refine mul_nonneg _ _,refine mul_nonneg (abv_nonneg _ _) (pow_nonneg (inv_nonneg.mpr r0) _),exact pow_nonneg r0 _,
replace r_pos : 0 < r,cases lt_or_eq_of_le r0 with h h,exact h,exact absurd h.symm r_pos,
revert m n,
induction k with k' hi,assume m n h mn hk,
rw [hk,zero_add,mul_right_comm,←pow_inv _ _ (ne_of_lt r_pos).symm,←div_eq_mul_inv,mul_div_cancel],
exact (ne_of_lt (pow_pos r_pos _)).symm,
assume m n h mn hk,rw [hk,succ_add],
have kn : k' + (succ n) ≥ (succ n), rw ←zero_add (succ n),refine add_le_add _ _,exact zero_le _,simp,
replace hi := hi (k' + (succ n)) n h kn rfl,
rw [(by simp!;ring : pow r (succ (k' + succ n)) = pow r (k' + succ n) * r),←_root_.mul_assoc],
replace h := h (k' + succ n) (le_of_succ_le kn),rw mul_comm at h,
exact le_trans h (mul_le_mul_of_nonneg_right hi r0),
rwa abs_of_nonneg r0,
end
lemma series_cau_of_abv_cau {α : Type*} {β : Type*} [discrete_linear_ordered_field α] [ring β] {abv : β → α} {f : ℕ → β}
[is_absolute_value abv] : is_cau_seq abs (series (λ n, abv (f n))) → is_cau_seq abv (series f) :=
λ h, is_cau_series_of_abv_le_cau 0 (λ n h, le_refl _) h
-- I did not use the equivalent function on cauchy sequences as I do not have a proof
-- series (λ n, series (λ m, a m * b (n - m)) n) j) is a cauchy sequence. Using this lemma
-- and of_near, this can be proven to be a cauchy sequence
lemma series_cauchy_prod {α β : Type*} [discrete_linear_ordered_field α] [ring β] {a b : ℕ → β}
{abv : β → α} [is_absolute_value abv] : is_cau_seq abs (series (λ n, abv (a n))) → is_cau_seq abv (series b) →
∀ ε : α, 0 < ε → ∃ i : ℕ, ∀ j ≥ i, abv (series a j * series b j - series (λ n,
series (λ m, a m * b (n - m)) n) j) < ε := begin
-- slightly adapted version of theorem 9.4.7 from "The Real Numbers and Real Analysis", Ethan D. Bloch
assume ha hb ε ε0,
cases cau_seq.bounded ⟨_, hb⟩ with Q hQ,simp at hQ,
cases cau_seq.bounded ⟨_, ha⟩ with P hP,simp at hP,
have P0 : 0 < P,exact lt_of_le_of_lt (abs_nonneg _) (hP 0),
have Pε0 := div_pos ε0 (mul_pos (show (2 : α) > 0, from by norm_num) P0),
cases cau_seq.cauchy₂ ⟨_, hb⟩ Pε0 with N hN,simp at hN,
have Qε0 := div_pos ε0 (mul_pos (show (4 : α) > 0, from by norm_num) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))),
cases cau_seq.cauchy₂ ⟨_, ha⟩ Qε0 with M hM,simp at hM,
existsi 2 * (max N M + 1),
assume K hK,have := series_series_diag_flip (λ m n, a m * b n) K,simp at this,rw this,clear this,
have : (λ (i : ℕ), series (λ (k : ℕ), a i * b k) (K - i)) = (λ (i : ℕ), a i * series (λ (k : ℕ), b k) (K - i)) := by
{apply funext,assume i,rw series_mul_left},
rw this,clear this,simp,
have : series (λ (i : ℕ), a i * series b (K - i)) K = series (λ (i : ℕ), a i * (series b (K - i) - series b K))
K + series (λ i, a i * series b K) K,
{rw ←series_add,simp[(mul_add _ _ _).symm]},
rw this, clear this,
rw series_mul_series,simp,
rw abv_neg abv,
refine lt_of_le_of_lt (abv_series_le_series_abv _) _,
simp [abv_mul abv],
suffices : series (λ (i : ℕ), abv (a i) * abv (series b (K - i) + -series b K)) (max N M + 1) +
(series (λ (i : ℕ), abv (a i) * abv (series b (K - i) + -series b K)) K -series (λ (i : ℕ),
abv (a i) * abv (series b (K - i) + -series b K)) (max N M + 1)) < ε / (2 * P) * P + ε / (4 * Q) * (2 * Q),
{ simp [(div_div_eq_div_mul _ _ _).symm] at this,
rwa[div_mul_cancel _ (ne_of_lt P0).symm,(by norm_num : (4 : α) = 2 * 2),←div_div_eq_div_mul,mul_comm (2 : α),←_root_.mul_assoc,
div_mul_cancel _ (ne_of_lt (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))).symm,div_mul_cancel,add_halves] at this,
norm_num},
refine add_lt_add _ _,
{have : series (λ (i : ℕ), abv (a i) * abv (series b (K - i) + -series b K)) (max N M + 1) ≤ series
(λ (i : ℕ), abv (a i) * (ε / (2 * P))) (max N M + 1) := by
{refine series_le_series _,assume m mJ,refine mul_le_mul_of_nonneg_left _ _,
{refine le_of_lt (hN (K - m) K _ _),{
refine nat.le_sub_left_of_add_le (le_trans _ hK),
rw[succ_mul,_root_.one_mul],
exact add_le_add mJ (le_trans (le_max_left _ _) (le_of_lt (lt_add_one _)))},
{refine le_trans _ hK,rw ←_root_.one_mul N,
refine mul_le_mul (by norm_num) (by rw _root_.one_mul;exact le_trans (le_max_left _ _)
(le_of_lt (lt_add_one _))) (zero_le _) (zero_le _)}},
exact abv_nonneg abv _},
refine lt_of_le_of_lt this _,
rw [series_mul_right,mul_comm],
specialize hP (max N M + 1),rwa abs_of_nonneg at hP,
exact (mul_lt_mul_left Pε0).mpr hP,
exact series_nonneg (λ x h, abv_nonneg abv _)},
{have hNMK : max N M + 1 < K := by
{refine lt_of_lt_of_le _ hK,
rw [succ_mul,_root_.one_mul,←add_zero (max N M + 1)],
refine add_lt_add_of_le_of_lt (le_refl _) _,rw add_zero,
refine add_pos_of_nonneg_of_pos (zero_le _) (by norm_num)},
rw series_sub_series _ hNMK,
have : series (λ (k : ℕ), abv (a (k + (max N M + 1 + 1))) * abv
(series b (K - (k + (max N M + 1 + 1))) + -series b K)) (K - (max N M + 1 + 1)) ≤
series (λ (k : ℕ), abv (a (k + (max N M + 1 + 1))) * (2 * Q)) (K - (max N M + 1 + 1)) := by
{refine series_le_series _,
assume m hm,
refine mul_le_mul_of_nonneg_left _ _,
{refine le_trans (abv_add abv _ _) _,
rw (by ring : 2 * Q = Q + Q),
refine add_le_add (le_of_lt (hQ _)) _,
rw abv_neg abv, exact le_of_lt (hQ _)},
exact abv_nonneg abv _},
refine lt_of_le_of_lt this _,
rw [series_mul_right],
refine (mul_lt_mul_right (mul_pos (by norm_num) (lt_of_le_of_lt (abv_nonneg abv _) (hQ 0)))).mpr _,
refine lt_of_le_of_lt (le_abs_self _) _,
rw[←@series_sub_series _ _ (λ k, abv (a k)) (max N M + 1) K hNMK],
refine hM _ _ _ (le_trans (le_max_right _ _) (le_of_lt (lt_add_one _))),
refine le_trans _ hK,
rw [succ_mul,_root_.one_mul,←add_zero M],
exact add_le_add (le_trans (le_max_right _ _) (le_of_lt (lt_add_one _))) (zero_le _)},
end
|
bdcd3b43acd672bbe04d8f09bd732d738b827af0 | 6b609a616109fa46986f865a054cd5a3a29d42b2 | /Congruence_Manipulation.lean | b0ac977d5d600c00ecda1b0b7f68e626d85707ef | [] | no_license | kckennylau/Lean_ElementaryNT | ae013bb3df1d2c0869098aca751b55236c88f742 | c93c5754b99a906a62e67a754bd4bac8c0c4c525 | refs/heads/master | 1,621,064,756,453 | 1,509,670,063,000 | 1,509,670,063,000 | 109,455,937 | 0 | 0 | null | 1,509,756,894,000 | 1,509,756,894,000 | null | UTF-8 | Lean | false | false | 13,569 | lean |
-- a congruent to b modulo m
def cong (a:int) (b: int) (m: int): Prop := ∃ x: int, a-b = m*x
-- p is prime
def is_prime (p:nat): Prop := ∀ x y: int, cong (x*y) 0 p → cong x 0 p ∨ cong y 0 p
-- f is the floor of a/b
def floor (a:int) (b:int) (f:int): Prop := (f*b ≤ a ∧ ∀ y: int, y*b ≤ a → y≤f)
-- g is the gcd of a and b
def gcd (a:int) (b:int) (g:int): Prop := g > 0 ∧ cong a 0 g ∧ cong b 0 g ∧
(∀ y:nat, cong a 0 y ∧ cong b 0 y → g ≥ y)
-- Solution to linear diophantine equation with constants a b k
def LDE (a:int) (b:int) (k:int): Prop := ∃ x y: int, a*x + b*y = k
-- existence of floor, gcd, and a solution to LDEs.
axiom Efloor (a: int) (b:int): ∃ x:int, floor a b x
axiom Egcd (a:int) (b: int): ∃ x: nat, gcd a b x
axiom ELDE (a:int) (b: int): ∃ k: int, LDE a b k ∧ k > 0 ∧ (∀ y: int, LDE a b y → y ≥ k)
-- All of the above can be proven from Wop, but are temporarily axiomatised
axiom WOP {k: nat} (p:nat → Prop) (H: p k): ∃ n: nat, p n ∧ (∀ y:nat, p y → y ≥ n)
--
lemma SwapSums (a b x : int) : (a-b) + (-x + x) = (a-x) - (b-x) :=
begin
have goal: (a-b) + (-x + x) = (a-x) - (b-x), from calc
(a-b) + (-x + x) = (a-b) + (-x + x) : eq.refl ((a-b) + (-x + x))
... = (a-b) + (x-x) : by rw [neg_add_eq_sub]
... = (a-b) + x - x : by rw [add_sub_assoc]
... = (a-b) - x + x : by rw [sub_add_eq_add_sub (a-b) x x]
... = a-(x+b) + x: by rw [sub_add_eq_sub_sub_swap]
... = a- x -b + x: by rw [sub_add_eq_sub_sub]
... = a- x + -b + x: by rw [sub_eq_add_neg]
... = a- x + (-b + x): by rw [add_assoc]
... = (a-x) + (x - b): by rw [neg_add_eq_sub]
... = (a-x) + -(b - x) : by rw [eq.symm (neg_sub b x)]
... = (a-x) -(b - x) : by rw [eq.symm (sub_eq_add_neg (a-x) (b-x))],
exact goal
end
lemma NegCommViaMul (a:int) (b:int) : (-1)*(a - b) = b - a :=
begin
calc
(-1)*(a - b) = (-1)*(a - b) : eq.refl (-1*(a - b))
... = -(a - b) : eq.symm (neg_eq_neg_one_mul ((a - b)))
... = -(-b + a): by rw [eq.symm (neg_add_eq_sub b a)]
... = -(-b) + -a : neg_add (-b) a
... = b + -a : by rw [neg_neg b]
... = b - a : eq.symm (sub_eq_add_neg b a)
end
lemma simplifyTransum (a: int) (b: int) (c: int) : (a-b) + (b-c) = a - c :=
begin
have H: a - c = (a-b) + (b-c), from calc
a-c = b-c + (a-b) : sub_eq_sub_add_sub a c b
... = (a-b) + (b-c) : add_comm (b-c) (a-b),
have H2: (a-b) + (b-c) = a - c, from eq.symm H,
exact H2
end
theorem Mreflex (a:int) (m: nat): cong a a m :=
begin
have H1: a-a = 0, from trans_rel_left eq (sub_eq_add_neg a a) (add_right_neg a),
have H2: a-a = m*0, from trans_rel_left eq (H1) (eq.symm (mul_zero m)),
exact exists.intro 0 H2
end
theorem Msymmetric {a b : int} {m: int} (H1: cong a b m): cong b a m :=
begin
have H: (cong b a m), from exists.elim H1 (fun (k:int) (Hw1 : a-b = m*k),
have introMinusOne: -1*(a - b) = -1*(m*k), from by rw [Hw1],
have simplifiedLeft: b - a = -1*(m*k), from trans_rel_left eq (eq.symm (NegCommViaMul a b)) introMinusOne,
have rearrange : b - a = m*((-1)*k), from calc
b - a = -1*(m*k) : simplifiedLeft
... = m*((-1)*k): mul_left_comm (-1) m k,
have goal: cong b a m, from exists.intro ((-1)*k) rearrange,
goal),
exact H
end
theorem Mtrans {a b c: int} (m: nat) (H1: cong a b m) (H2: cong b c m): cong a c m :=
begin
have p: cong a c m, from exists.elim H1 (fun (k:int) (Hw1 : a-b = m*k),
exists.elim H2 (fun (j:int) (Hw2 : b-c = m*j),
have Ha: (a-b) + (b-c) = m*k + m*j, from by rw [Hw1,Hw2],
have Hb: a-c = m*k + m*j, from trans_rel_left eq (eq.symm (simplifyTransum a b c)) Ha,
have goal: cong a c m, from exists.intro (k+j) (calc
a-c = m*k + m*j : Hb
... = m*(k+j) : eq.symm (mul_add m k j)),
goal )),
exact p
end
theorem Mmul {x a b: int} (n:int) (H1: cong a b n) : cong (a*x) (b*x) n:=
begin
have p: cong (a*x) (b*x) n, from exists.elim H1 (fun (k:int) (Hw1: a-b = n*k) ,
have H2: (a-b)*x = n*k*x, from by rw [Hw1],
have H3: a*x-b*x = n*k*x, from trans_rel_left eq (eq.symm (sub_mul a b x)) H2,
have H4:a*x-b*x = n*(k*x), from calc
a*x-b*x = n*k*x : H3
... = n*(k*x) : mul_assoc n k x,
have goal: cong (a*x) (b*x) n, from exists.intro (k*x) H4,
goal),
exact p
end
theorem Msub {a b: int} {n:nat} (x:int) (H1: cong a b n) : cong (a-x) (b-x) n:=
begin
have p: cong (a-x) (b-x) n, from exists.elim H1 (fun (k:int) (Hw1: a-b = n*k) ,
have H2: (a-b) + (-x + x) = n*k + 0, from by rw [Hw1, add_left_neg x],
have H3:(a-b) + (-x + x)= n*k, from calc
(a-b) + (-x + x) = n*k + 0: H2
... = n*k : (add_zero (n*k)),
have goal: (a-x) - (b-x) = n*k, from trans_rel_left eq (eq.symm (SwapSums a b x)) H3,
have q: cong (a-x) (b-x) n, from exists.intro k goal,
q),
exact p
end
theorem MinsertLeft {a b c: int} {n:int} (H1: cong a b n) (H2: a = c): cong c b n:=
begin
have goal: cong c b n, from exists.elim H1 (fun (k:int) (Hw1: a-b = n*k) ,
have Z1: c-a = 0, from sub_eq_zero_of_eq (eq.symm H2),
have L1: (a-b) + (c-a) = n*k + 0, from by rw [Hw1,Z1],
have L2: (a-b) + (c-a) = n*k, from by rw [L1,add_zero],
have L3: c - b = n*k, from trans_rel_left eq (sub_eq_sub_add_sub c b a) L2,
have p: cong c b n, from exists.intro k L3,
p),
exact goal
end
theorem MinsertRight {a b c: int} {n:int} (H1: cong a b n) (H2: b = c): cong a c n:=
begin
have goal: cong b a n, from Msymmetric H1,
have p: cong c a n, from MinsertLeft goal H2,
have q: cong a c n, from Msymmetric p,
exact q
end
theorem Madd {a b: int} {n:nat} (x: int) (H1: cong a b n) : cong (a+x) (b+x) n:=
begin
have start: cong (a - (-x)) (b - (-x)) n, from Msub (-x) (H1),
have L: cong (a+x) (b - (-x)) n, from MinsertLeft start (sub_neg_eq_add a x),
have R: cong (a + x) (b + x) n, from MinsertRight L (sub_neg_eq_add b x),
exact R
end
theorem Mcancel {p:nat} {a b x} (H1: is_prime p) (H2: cong (x*a) (x*b) p): (cong a b p) ∨ (cong x 0 p) :=
begin
have L1: cong (x*a - x*b) (x*b - x*b) p, from Msub (x*b) H2,
have L2: cong (x*a - x*b) 0 p, from MinsertRight L1 (add_neg_self (x*b)),
have L3: cong (x*(a-b)) 0 p, from MinsertLeft L2 (eq.symm(mul_sub x a b)),
have goal: cong x 0 p ∨ cong (a-b) 0 p, from (H1 x (a-b)) L3,
have goal2: (cong a b p) ∨ (cong x 0 p), from or.cases_on goal
(assume ass: cong x 0 p,
have g2: (cong a b p) ∨ (cong x 0 p), from or.intro_right (cong a b p) ass,
g2)
(assume ass: cong (a-b) 0 p,
have J1: cong (a-b + b) (0+b) p, from Madd b ass,
have J2: cong (a-b +b) b p, from MinsertRight J1 (zero_add b),
have J3: cong a b p, from MinsertLeft J2 (sub_add_cancel a b),
have J4: (cong a b p) ∨ (cong x 0 p), from or.intro_left (cong x 0 p) J3,
J4),
exact goal2
end
theorem MDsum {a b c d n: int} (H1: cong a b n) (H2: cong c d n): cong (a+c) (b+d) n :=
begin
have H: cong (a+c) (b+d) n, from sorry,
exact H
end
theorem basicInequality {a b : int} (H1: cong a 0 b) (h2: a > 0): a ≥ b :=
begin
have H: a ≥ b , from sorry,
exact H
end
-- Division algorithm
theorem DivAlgo (a : int) (b : int): ∃ q r : int, a = b*q + r ∧ 0 ≤ r ∧ b > r :=
begin
have Q: ∃ q r: int, a = b*q + r ∧ 0 ≤ r ∧ b > r,
from exists.elim (Efloor a b) (fun (x:int) (H: x*b ≤ a ∧ ∀ y: int, y*b ≤ a → y≤x),
have Hl: x*b ≤ a, from and.elim_left H,
have Hr: ∀ y: int, y*b ≤ a → y≤x, from and.elim_right H,
have L1: 0 = b*x - b*x, from eq.symm (sub_eq_zero_of_eq (eq.refl (b*x))),
have G1: a = b*x + (a-x*b), from calc
a = 0 + a: eq.symm (zero_add a)
... = b*x - b*x + a: by rw [L1]
... = b*x - x*b + a: by rw [mul_comm]
... = b*x + a - x*b: sub_add_eq_add_sub (b*x) (x*b) a
... = b*x + (a - x*b): add_sub_assoc (b*x) a (x*b),
have G2: 0 ≤ (a - x*b), from sub_nonneg_of_le Hl,
have Trich: b ≤ (a - x*b) ∨ b > (a - x*b), from le_or_gt b (a - x*b),
have G3: b > (a - x*b), from or.cases_on Trich
(assume ass: b ≤ (a - x*b),
have L2: a ≥ b + x*b, from add_le_of_le_sub_right ass,
have L3: b + (x*b) = 1*b + (x*b), from by rw [one_mul],
have L4: (x+1)*b = (1+x)*b, from by rw [add_comm],
have C: (x+1)*b ≤ a, from calc
a ≥ b + (x*b) : L2
... ≥ 1*b + (x*b): le_of_eq (eq.symm L3)
... ≥ (1+x)*b : le_of_eq (add_mul 1 x b)
... ≥ (x+1)*b : le_of_eq L4,
have F: x+1 ≤ x, from Hr (x+1) C,
have T: x+1 > x, from int.lt_add_one_of_le (le_of_eq (eq.refl x)),
have will: b > (a - x*b), from absurd F (not_le_of_gt T),
will)
(assume ass: b > (a - x*b),
ass),
have final: ∃ q r: int, a = b*q + r ∧ 0 ≤ r ∧ b > r,
from exists.intro x (exists.intro (a - x*b) (and.intro G1 (and.intro G2 G3))),
final),
exact Q
end
--Lemma for proving that Z is a principal ideal domain later on
lemma LDEsimp {a b p :int} (W1: LDE a b p ∧ p > 0 ∧ (∀ (q: int), LDE a b q → q ≥ p)) : cong a 0 p:=
begin
exact exists.elim W1.1
(fun (x : int) (W2: ∃ y:int, a*x + b*y = p),
exists.elim W2
(fun (y : int) (W3: a*x + b*y = p),
have App: ∃ m n: int, a = p*m + n ∧ 0 ≤ n ∧ p > n, from DivAlgo a p,
exists.elim (App)
(fun (m : int) (D1: ∃ n: int, a = p*m + n ∧ 0 ≤ n ∧ p > n),
exists.elim D1
(fun (n : int) (D: a = p*m + n ∧ (0 ≤ n ∧ p > n)),
have Ntest: 0 ≤ n, from and.elim_left (and.elim_right D),
have UB: p > n, from and.elim_right (and.elim_right D),
have A1: a = p*m + n, from and.elim_left D,
have A2: a = (a*x + b*y)*m + n, from eq.subst (eq.symm W3) A1,
have A3: n = a - (a*x + b*y)*m, from eq_sub_of_add_eq' (eq.symm A2),
have A: a*(1-x*m) + b*(-(y*m)) = n, from eq.symm (calc
n = a - (a*x + b*y)*m : A3
... = a - (a*x*m + b*y*m) : by rw [add_mul (a*x) (b*y) m]
... = a - a*x*m - b*y*m : sub_add_eq_sub_sub a (a*x*m) (b*y*m)
... = a*1 - a*x*m - b*y*m : by rw [mul_one]
... = a*1 - a*(x*m) - b*y*m : by rw [mul_assoc]
... = a*(1 - x*m) - (b*y*m) : by rw [eq.symm (mul_sub a 1 (x*m))]
... = a*(1-x*m) + -(b*y*m) : by rw [sub_eq_add_neg]
... = a*(1-x*m) + -(b*(y*m)) : by rw [mul_assoc]
... = a*(1-x*m) + b*(-(y*m)) : by rw [neg_mul_eq_mul_neg]
),
have Z1: n = 0, from or.by_cases (lt_or_eq_of_le Ntest)
(assume H1: n > 0,
have C0: LDE a b n, from exists.intro (1-x*m) (exists.intro (-(y*m)) A),
have C1: ∀ q: int, LDE a b q → q ≥ p, from W1.2.2,
have C2: n ≥ p, from C1 n C0,
have C4: ¬ n < p, from not_lt_of_ge C2,
have E: n = 0, from absurd UB C4,
E)
(assume H: 0 = n,
eq.symm H),
have P1: a = (p*m) + 0, from eq.subst Z1 A1,
have P2: a = (p*m), from calc a = (p*m) + 0 : P1 ... = (p*m) : by rw [add_zero],
have P3: a - 0 = p*m, from eq.trans (sub_zero a) P2,
have P4: cong a 0 p, from exists.intro m P3,
P4
)
)
)
)
end
lemma LDEcomm {a b p: int} (H: LDE a b p) : LDE b a p :=
begin
have H1: ∃ x y: int, a*x + b*y = p, from H,
have H2: LDE b a p, from exists.elim (H1) (
(fun (x : int) (W1: ∃ y: int, a*x + b*y = p),
exists.elim (W1) (
(fun (y : int) (W1: a*x + b*y = p),
have W3: b*y + a*x = p, from eq.symm (calc
p = a*x + b*y : eq.symm W1
... = b*y + a*x : add_comm (a*x) (b*y)
),
exists.intro y (exists.intro x W3)
)
))),
exact H2
end
lemma PisGCD {j b p: int} (W2: p > 0) (W11: LDE j b p) (y: int): cong j 0 y ∧ cong b 0 y → p ≥ y :=
begin
have goal: cong j 0 y ∧ cong b 0 y → p ≥ y, from
(assume P: cong j 0 y ∧ cong b 0 y,
have r: cong b 0 y, from P.2,
have l: cong j 0 y, from P.1,
have F: cong p 0 y, from exists.elim (W11) (fun (x : int) (F1: ∃ w:int, j*x + b*w = p),
exists.elim F1 (fun (w : int) (F2: j*x + b*w = p),
have r2: cong (b*w) (0*w) y, from Mmul y r,
have r3: cong (b*w) 0 y, from MinsertRight r2 (zero_mul w),
have l2: cong (j*x) (0*x) y, from Mmul y l,
have l3: cong (j*x) 0 y, from MinsertRight l2 (zero_mul x),
have c: cong (j*x + b*w) 0 y, from MDsum l3 r3,
have c2 : cong p 0 y, from MinsertLeft c F2,
c2
)),
have en: p ≥ y, from basicInequality F W2,
en),
exact goal
end
theorem IntegersFormPID (j : int) (b : int): ∃ g:int, LDE j b g ∧ gcd j b g :=
begin
have H1: ∃ g:int, LDE j b g ∧ gcd j b g, from exists.elim (ELDE j b)
(fun (p:int) (W1: LDE j b p ∧ p > 0 ∧ (∀ q: int, LDE j b q → q ≥ p)),
have Ha: cong j 0 p, from LDEsimp W1,
have W11: LDE j b p, from W1.1,
have W12: LDE b j p, from LDEcomm W11,
have W2: p > 0, from W1.2.1,
have W6: (∀ q: int, LDE b j q → q ≥ p), from (λ q H, (W1.2.2 q) (LDEcomm H)),
have W7: LDE b j p ∧ p > 0 ∧ (∀ q: int, LDE b j q → q ≥ p), from ⟨W12,W2,W6⟩,
have Hb: cong b 0 p, from LDEsimp W7,
have pre: (∀ y:int, cong j 0 y ∧ cong b 0 y → p ≥ y), from PisGCD W2 W11,
have goal: gcd j b p, from ⟨ W2, Ha, Hb, pre⟩,
exists.intro p (and.intro W11 goal)
),
exact H1
end
|
7b1d4445b9ead673b52f6e17e0394ce7f2e5f4e2 | efa51dd2edbbbbd6c34bd0ce436415eb405832e7 | /20161026_ICTAC_Tutorial/ex24.lean | b49d9ebdc158169516c6618553605cb29b471182 | [
"Apache-2.0"
] | permissive | leanprover/presentations | dd031a05bcb12c8855676c77e52ed84246bd889a | 3ce2d132d299409f1de269fa8e95afa1333d644e | refs/heads/master | 1,688,703,388,796 | 1,686,838,383,000 | 1,687,465,742,000 | 29,750,158 | 12 | 9 | Apache-2.0 | 1,540,211,670,000 | 1,422,042,683,000 | Lean | UTF-8 | Lean | false | false | 341 | lean | /- Σ x : A, B x -/
variable A : Type
variable B : A → Type
variable a : A
variable b : B a
check sigma.mk a b -- Σ (a : A), B a
check (sigma.mk a b).1 -- A
check (sigma.mk a b).2 -- B (sigma.fst (sigma.mk a b))
eval (sigma.mk a b).1 -- a
eval (sigma.mk a b).2 -- b
eval sigma.fst (sigma.mk a b)
eval sigma.snd (sigma.mk a b)
|
0c6ac669c316f2f5210e0072ad5ab76e58b52896 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /tests/lean/smartUnfolding.lean | 243a863d2ddce770456f6ca1f7cb923226348975 | [
"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 | 247 | lean | theorem ex1 (x y : Nat) (h : x + 2 = y + 2) : x = y := by
injection h with h
trace_state -- without smart unfolding the state would be a mess
injection h with h
trace_state -- without smart unfolding the state would be a mess
assumption
|
fb6499fde2d0e56043cb5aefc095d046ee852e9d | 2a70b774d16dbdf5a533432ee0ebab6838df0948 | /_target/deps/mathlib/src/data/equiv/mul_add.lean | 83f6b2e48905a2a723ca59ba04ff90740b4d4998 | [
"Apache-2.0"
] | permissive | hjvromen/lewis | 40b035973df7c77ebf927afab7878c76d05ff758 | 105b675f73630f028ad5d890897a51b3c1146fb0 | refs/heads/master | 1,677,944,636,343 | 1,676,555,301,000 | 1,676,555,301,000 | 327,553,599 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,368 | lean | /-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Callum Sutton, Yury Kudryashov
-/
import algebra.group.hom
import algebra.group.type_tags
import algebra.group.units_hom
/-!
# Multiplicative and additive equivs
In this file we define two extensions of `equiv` called `add_equiv` and `mul_equiv`, which are
datatypes representing isomorphisms of `add_monoid`s/`add_group`s and `monoid`s/`group`s.
## Notations
The extended equivs all have coercions to functions, and the coercions are the canonical
notation when treating the isomorphisms as maps.
## Implementation notes
The fields for `mul_equiv`, `add_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as
these are deprecated.
## Tags
equiv, mul_equiv, add_equiv
-/
variables {A : Type*} {B : Type*} {M : Type*} {N : Type*} {P : Type*} {G : Type*} {H : Type*}
set_option old_structure_cmd true
/-- add_equiv α β is the type of an equiv α ≃ β which preserves addition. -/
structure add_equiv (A B : Type*) [has_add A] [has_add B] extends A ≃ B, add_hom A B
/-- The `equiv` underlying an `add_equiv`. -/
add_decl_doc add_equiv.to_equiv
/-- The `add_hom` underlying a `add_equiv`. -/
add_decl_doc add_equiv.to_add_hom
/-- `mul_equiv α β` is the type of an equiv `α ≃ β` which preserves multiplication. -/
@[to_additive]
structure mul_equiv (M N : Type*) [has_mul M] [has_mul N] extends M ≃ N, mul_hom M N
/-- The `equiv` underlying a `mul_equiv`. -/
add_decl_doc mul_equiv.to_equiv
/-- The `mul_hom` underlying a `mul_equiv`. -/
add_decl_doc mul_equiv.to_mul_hom
infix ` ≃* `:25 := mul_equiv
infix ` ≃+ `:25 := add_equiv
namespace mul_equiv
@[to_additive]
instance [has_mul M] [has_mul N] : has_coe_to_fun (M ≃* N) := ⟨_, mul_equiv.to_fun⟩
variables [has_mul M] [has_mul N] [has_mul P]
@[simp, to_additive]
lemma to_fun_apply {f : M ≃* N} {m : M} : f.to_fun m = f m := rfl
@[simp, to_additive]
lemma to_equiv_apply {f : M ≃* N} {m : M} : f.to_equiv m = f m := rfl
/-- A multiplicative isomorphism preserves multiplication (canonical form). -/
@[simp, to_additive]
lemma map_mul (f : M ≃* N) : ∀ x y, f (x * y) = f x * f y := f.map_mul'
/-- Makes a multiplicative isomorphism from a bijection which preserves multiplication. -/
@[to_additive "Makes an additive isomorphism from a bijection which preserves addition."]
def mk' (f : M ≃ N) (h : ∀ x y, f (x * y) = f x * f y) : M ≃* N :=
⟨f.1, f.2, f.3, f.4, h⟩
@[to_additive]
protected lemma bijective (e : M ≃* N) : function.bijective e := e.to_equiv.bijective
@[to_additive]
protected lemma injective (e : M ≃* N) : function.injective e := e.to_equiv.injective
@[to_additive]
protected lemma surjective (e : M ≃* N) : function.surjective e := e.to_equiv.surjective
/-- The identity map is a multiplicative isomorphism. -/
@[refl, to_additive "The identity map is an additive isomorphism."]
def refl (M : Type*) [has_mul M] : M ≃* M :=
{ map_mul' := λ _ _, rfl,
..equiv.refl _}
instance : inhabited (M ≃* M) := ⟨refl M⟩
/-- The inverse of an isomorphism is an isomorphism. -/
@[symm, to_additive "The inverse of an isomorphism is an isomorphism."]
def symm (h : M ≃* N) : N ≃* M :=
{ map_mul' := λ n₁ n₂, h.injective $
begin
have : ∀ x, h (h.to_equiv.symm.to_fun x) = x := h.to_equiv.apply_symm_apply,
simp only [this, h.map_mul]
end,
.. h.to_equiv.symm}
/-- See Note [custom simps projection] -/
-- we don't hyperlink the note in the additive version, since that breaks syntax highlighting
-- in the whole file.
@[to_additive add_equiv.simps.inv_fun "See Note custom simps projection"]
def simps.inv_fun (e : M ≃* N) : N → M := e.symm
initialize_simps_projections add_equiv (to_fun → apply, inv_fun → symm_apply)
initialize_simps_projections mul_equiv (to_fun → apply, inv_fun → symm_apply)
@[simp, to_additive]
theorem to_equiv_symm (f : M ≃* N) : f.symm.to_equiv = f.to_equiv.symm := rfl
@[simp, to_additive]
theorem coe_mk (f : M → N) (g h₁ h₂ h₃) : ⇑(mul_equiv.mk f g h₁ h₂ h₃) = f := rfl
@[simp, to_additive]
theorem coe_symm_mk (f : M → N) (g h₁ h₂ h₃) : ⇑(mul_equiv.mk f g h₁ h₂ h₃).symm = g := rfl
/-- Transitivity of multiplication-preserving isomorphisms -/
@[trans, to_additive "Transitivity of addition-preserving isomorphisms"]
def trans (h1 : M ≃* N) (h2 : N ≃* P) : (M ≃* P) :=
{ map_mul' := λ x y, show h2 (h1 (x * y)) = h2 (h1 x) * h2 (h1 y),
by rw [h1.map_mul, h2.map_mul],
..h1.to_equiv.trans h2.to_equiv }
/-- e.right_inv in canonical form -/
@[simp, to_additive]
lemma apply_symm_apply (e : M ≃* N) : ∀ y, e (e.symm y) = y :=
e.to_equiv.apply_symm_apply
/-- e.left_inv in canonical form -/
@[simp, to_additive]
lemma symm_apply_apply (e : M ≃* N) : ∀ x, e.symm (e x) = x :=
e.to_equiv.symm_apply_apply
@[simp, to_additive]
theorem refl_apply (m : M) : refl M m = m := rfl
@[simp, to_additive]
theorem trans_apply (e₁ : M ≃* N) (e₂ : N ≃* P) (m : M) : e₁.trans e₂ m = e₂ (e₁ m) := rfl
@[simp, to_additive] theorem apply_eq_iff_eq (e : M ≃* N) {x y : M} : e x = e y ↔ x = y :=
e.injective.eq_iff
@[to_additive]
lemma apply_eq_iff_symm_apply (e : M ≃* N) {x : M} {y : N} : e x = y ↔ x = e.symm y :=
e.to_equiv.apply_eq_iff_eq_symm_apply
@[to_additive]
lemma symm_apply_eq (e : M ≃* N) {x y} : e.symm x = y ↔ x = e y :=
e.to_equiv.symm_apply_eq
@[to_additive]
lemma eq_symm_apply (e : M ≃* N) {x y} : y = e.symm x ↔ e y = x :=
e.to_equiv.eq_symm_apply
/-- a multiplicative equiv of monoids sends 1 to 1 (and is hence a monoid isomorphism) -/
@[simp, to_additive]
lemma map_one {M N} [monoid M] [monoid N] (h : M ≃* N) : h 1 = 1 :=
by rw [←mul_one (h 1), ←h.apply_symm_apply 1, ←h.map_mul, one_mul]
@[simp, to_additive]
lemma map_eq_one_iff {M N} [monoid M] [monoid N] (h : M ≃* N) {x : M} :
h x = 1 ↔ x = 1 :=
h.map_one ▸ h.to_equiv.apply_eq_iff_eq
@[to_additive]
lemma map_ne_one_iff {M N} [monoid M] [monoid N] (h : M ≃* N) {x : M} :
h x ≠ 1 ↔ x ≠ 1 :=
⟨mt h.map_eq_one_iff.2, mt h.map_eq_one_iff.1⟩
/-- A bijective `monoid` homomorphism is an isomorphism -/
@[to_additive "A bijective `add_monoid` homomorphism is an isomorphism"]
noncomputable def of_bijective {M N} [monoid M] [monoid N] (f : M →* N)
(hf : function.bijective f) : M ≃* N :=
{ map_mul' := f.map_mul',
..equiv.of_bijective f hf }
/--
Extract the forward direction of a multiplicative equivalence
as a multiplication-preserving function.
-/
@[to_additive "Extract the forward direction of an additive equivalence
as an addition-preserving function."]
def to_monoid_hom {M N} [monoid M] [monoid N] (h : M ≃* N) : (M →* N) :=
{ map_one' := h.map_one, .. h }
@[simp, to_additive]
lemma coe_to_monoid_hom {M N} [monoid M] [monoid N] (e : M ≃* N) :
⇑e.to_monoid_hom = e :=
rfl
@[to_additive]
lemma to_monoid_hom_apply {M N} [monoid M] [monoid N] (e : M ≃* N) (x : M) :
e.to_monoid_hom x = e x :=
rfl
/-- A multiplicative equivalence of groups preserves inversion. -/
@[simp, to_additive]
lemma map_inv [group G] [group H] (h : G ≃* H) (x : G) : h x⁻¹ = (h x)⁻¹ :=
h.to_monoid_hom.map_inv x
/-- Two multiplicative isomorphisms agree if they are defined by the
same underlying function. -/
@[ext, to_additive
"Two additive isomorphisms agree if they are defined by the same underlying function."]
lemma ext {f g : mul_equiv M N} (h : ∀ x, f x = g x) : 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
@[to_additive]
protected lemma congr_arg {f : mul_equiv M N} : Π {x x' : M}, x = x' → f x = f x'
| _ _ rfl := rfl
@[to_additive]
protected lemma congr_fun {f g : mul_equiv M N} (h : f = g) (x : M) : f x = g x := h ▸ rfl
@[to_additive]
lemma ext_iff {f g : mul_equiv M N} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, ext⟩
@[to_additive] lemma to_monoid_hom_injective
{M N} [monoid M] [monoid N] : function.injective (to_monoid_hom : (M ≃* N) → M →* N) :=
λ f g h, mul_equiv.ext (monoid_hom.ext_iff.1 h)
attribute [ext] add_equiv.ext
end mul_equiv
-- We don't use `to_additive` to generate definition because it fails to tell Lean about
-- equational lemmas
/-- Given a pair of additive monoid homomorphisms `f`, `g` such that `g.comp f = id` and
`f.comp g = id`, returns an additive equivalence with `to_fun = f` and `inv_fun = g`. This
constructor is useful if the underlying type(s) have specialized `ext` lemmas for additive
monoid homomorphisms. -/
def add_monoid_hom.to_add_equiv [add_monoid M] [add_monoid N] (f : M →+ N) (g : N →+ M)
(h₁ : g.comp f = add_monoid_hom.id _) (h₂ : f.comp g = add_monoid_hom.id _) :
M ≃+ N :=
{ to_fun := f,
inv_fun := g,
left_inv := add_monoid_hom.congr_fun h₁,
right_inv := add_monoid_hom.congr_fun h₂,
map_add' := f.map_add }
/-- Given a pair of monoid homomorphisms `f`, `g` such that `g.comp f = id` and `f.comp g = id`,
returns an multiplicative equivalence with `to_fun = f` and `inv_fun = g`. This constructor is
useful if the underlying type(s) have specialized `ext` lemmas for monoid homomorphisms. -/
@[to_additive]
def monoid_hom.to_mul_equiv [monoid M] [monoid N] (f : M →* N) (g : N →* M)
(h₁ : g.comp f = monoid_hom.id _) (h₂ : f.comp g = monoid_hom.id _) :
M ≃* N :=
{ to_fun := f,
inv_fun := g,
left_inv := monoid_hom.congr_fun h₁,
right_inv := monoid_hom.congr_fun h₂,
map_mul' := f.map_mul }
@[simp, to_additive]
lemma monoid_hom.coe_to_mul_equiv [monoid M] [monoid N] (f : M →* N) (g : N →* M) (h₁ h₂) :
⇑(f.to_mul_equiv g h₁ h₂) = f := rfl
/-- An additive equivalence of additive groups preserves subtraction. -/
lemma add_equiv.map_sub [add_group A] [add_group B] (h : A ≃+ B) (x y : A) :
h (x - y) = h x - h y :=
h.to_add_monoid_hom.map_sub x y
instance add_equiv.inhabited {M : Type*} [has_add M] : inhabited (M ≃+ M) := ⟨add_equiv.refl M⟩
/-- A group is isomorphic to its group of units. -/
@[to_additive to_add_units "An additive group is isomorphic to its group of additive units"]
def to_units {G} [group G] : G ≃* units G :=
{ to_fun := λ x, ⟨x, x⁻¹, mul_inv_self _, inv_mul_self _⟩,
inv_fun := coe,
left_inv := λ x, rfl,
right_inv := λ u, units.ext rfl,
map_mul' := λ x y, units.ext rfl }
namespace units
variables [monoid M] [monoid N] [monoid P]
/-- A multiplicative equivalence of monoids defines a multiplicative equivalence
of their groups of units. -/
def map_equiv (h : M ≃* N) : units M ≃* units N :=
{ inv_fun := map h.symm.to_monoid_hom,
left_inv := λ u, ext $ h.left_inv u,
right_inv := λ u, ext $ h.right_inv u,
.. map h.to_monoid_hom }
/-- Left multiplication by a unit of a monoid is a permutation of the underlying type. -/
@[to_additive "Left addition of an additive unit is a permutation of the underlying type."]
def mul_left (u : units M) : equiv.perm M :=
{ to_fun := λx, u * x,
inv_fun := λx, ↑u⁻¹ * x,
left_inv := u.inv_mul_cancel_left,
right_inv := u.mul_inv_cancel_left }
@[simp, to_additive]
lemma coe_mul_left (u : units M) : ⇑u.mul_left = (*) u := rfl
@[simp, to_additive]
lemma mul_left_symm (u : units M) : u.mul_left.symm = u⁻¹.mul_left :=
equiv.ext $ λ x, rfl
/-- Right multiplication by a unit of a monoid is a permutation of the underlying type. -/
@[to_additive "Right addition of an additive unit is a permutation of the underlying type."]
def mul_right (u : units M) : equiv.perm M :=
{ to_fun := λx, x * u,
inv_fun := λx, x * ↑u⁻¹,
left_inv := λ x, mul_inv_cancel_right x u,
right_inv := λ x, inv_mul_cancel_right x u }
@[simp, to_additive]
lemma coe_mul_right (u : units M) : ⇑u.mul_right = λ x : M, x * u := rfl
@[simp, to_additive]
lemma mul_right_symm (u : units M) : u.mul_right.symm = u⁻¹.mul_right :=
equiv.ext $ λ x, rfl
end units
namespace equiv
section group
variables [group G]
/-- Left multiplication in a `group` is a permutation of the underlying type. -/
@[to_additive "Left addition in an `add_group` is a permutation of the underlying type."]
protected def mul_left (a : G) : perm G := (to_units a).mul_left
@[simp, to_additive]
lemma coe_mul_left (a : G) : ⇑(equiv.mul_left a) = (*) a := rfl
/-- extra simp lemma that `dsimp` can use. `simp` will never use this. -/
@[simp, nolint simp_nf, to_additive]
lemma mul_left_symm_apply (a : G) : ((equiv.mul_left a).symm : G → G) = (*) a⁻¹ := rfl
@[simp, to_additive]
lemma mul_left_symm (a : G) : (equiv.mul_left a).symm = equiv.mul_left a⁻¹ :=
ext $ λ x, rfl
/-- Right multiplication in a `group` is a permutation of the underlying type. -/
@[to_additive "Right addition in an `add_group` is a permutation of the underlying type."]
protected def mul_right (a : G) : perm G := (to_units a).mul_right
@[simp, to_additive]
lemma coe_mul_right (a : G) : ⇑(equiv.mul_right a) = λ x, x * a := rfl
@[simp, to_additive]
lemma mul_right_symm (a : G) : (equiv.mul_right a).symm = equiv.mul_right a⁻¹ :=
ext $ λ x, rfl
/-- extra simp lemma that `dsimp` can use. `simp` will never use this. -/
@[simp, nolint simp_nf, to_additive]
lemma mul_right_symm_apply (a : G) : ((equiv.mul_right a).symm : G → G) = λ x, x * a⁻¹ := rfl
attribute [nolint simp_nf] add_left_symm_apply add_right_symm_apply
variable (G)
/-- Inversion on a `group` is a permutation of the underlying type. -/
@[to_additive "Negation on an `add_group` is a permutation of the underlying type."]
protected def inv : perm G :=
{ to_fun := λa, a⁻¹,
inv_fun := λa, a⁻¹,
left_inv := assume a, inv_inv a,
right_inv := assume a, inv_inv a }
variable {G}
@[simp, to_additive]
lemma coe_inv : ⇑(equiv.inv G) = has_inv.inv := rfl
@[simp, to_additive]
lemma inv_symm : (equiv.inv G).symm = equiv.inv G := rfl
end group
end equiv
section type_tags
/-- Reinterpret `G ≃+ H` as `multiplicative G ≃* multiplicative H`. -/
def add_equiv.to_multiplicative [add_monoid G] [add_monoid H] :
(G ≃+ H) ≃ (multiplicative G ≃* multiplicative H) :=
{ to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative, f.symm.to_add_monoid_hom.to_multiplicative, f.3, f.4, f.5⟩,
inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩,
left_inv := λ x, by { ext, refl, },
right_inv := λ x, by { ext, refl, }, }
/-- Reinterpret `G ≃* H` as `additive G ≃+ additive H`. -/
def mul_equiv.to_additive [monoid G] [monoid H] :
(G ≃* H) ≃ (additive G ≃+ additive H) :=
{ to_fun := λ f, ⟨f.to_monoid_hom.to_additive, f.symm.to_monoid_hom.to_additive, f.3, f.4, f.5⟩,
inv_fun := λ f, ⟨f.to_add_monoid_hom, f.symm.to_add_monoid_hom, f.3, f.4, f.5⟩,
left_inv := λ x, by { ext, refl, },
right_inv := λ x, by { ext, refl, }, }
/-- Reinterpret `additive G ≃+ H` as `G ≃* multiplicative H`. -/
def add_equiv.to_multiplicative' [monoid G] [add_monoid H] :
(additive G ≃+ H) ≃ (G ≃* multiplicative H) :=
{ to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative', f.symm.to_add_monoid_hom.to_multiplicative'', f.3, f.4, f.5⟩,
inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩,
left_inv := λ x, by { ext, refl, },
right_inv := λ x, by { ext, refl, }, }
/-- Reinterpret `G ≃* multiplicative H` as `additive G ≃+ H` as. -/
def mul_equiv.to_additive' [monoid G] [add_monoid H] :
(G ≃* multiplicative H) ≃ (additive G ≃+ H) :=
add_equiv.to_multiplicative'.symm
/-- Reinterpret `G ≃+ additive H` as `multiplicative G ≃* H`. -/
def add_equiv.to_multiplicative'' [add_monoid G] [monoid H] :
(G ≃+ additive H) ≃ (multiplicative G ≃* H) :=
{ to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative'', f.symm.to_add_monoid_hom.to_multiplicative', f.3, f.4, f.5⟩,
inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩,
left_inv := λ x, by { ext, refl, },
right_inv := λ x, by { ext, refl, }, }
/-- Reinterpret `multiplicative G ≃* H` as `G ≃+ additive H` as. -/
def mul_equiv.to_additive'' [add_monoid G] [monoid H] :
(multiplicative G ≃* H) ≃ (G ≃+ additive H) :=
add_equiv.to_multiplicative''.symm
end type_tags
|
33dcdd7aa43c881e33e801741cd7d9e54152594a | b561a44b48979a98df50ade0789a21c79ee31288 | /src/Lean/Elab.lean | b56422ff40a6db7ae4292eec7ac322a1a5230134 | [
"Apache-2.0"
] | permissive | 3401ijk/lean4 | 97659c475ebd33a034fed515cb83a85f75ccfb06 | a5b1b8de4f4b038ff752b9e607b721f15a9a4351 | refs/heads/master | 1,693,933,007,651 | 1,636,424,845,000 | 1,636,424,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,187 | 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.Elab.Import
import Lean.Elab.Exception
import Lean.Elab.Command
import Lean.Elab.Term
import Lean.Elab.App
import Lean.Elab.Binders
import Lean.Elab.LetRec
import Lean.Elab.Frontend
import Lean.Elab.BuiltinNotation
import Lean.Elab.Declaration
import Lean.Elab.Tactic
import Lean.Elab.Match
-- HACK: must come after `Match` because builtin elaborators (for `match` in this case) do not take priorities
import Lean.Elab.Quotation
import Lean.Elab.Syntax
import Lean.Elab.Do
import Lean.Elab.StructInst
import Lean.Elab.Inductive
import Lean.Elab.Structure
import Lean.Elab.Print
import Lean.Elab.MutualDef
import Lean.Elab.AuxDef
import Lean.Elab.PreDefinition
import Lean.Elab.Deriving
import Lean.Elab.DeclarationRange
import Lean.Elab.Extra
import Lean.Elab.GenInjective
import Lean.Elab.BuiltinTerm
import Lean.Elab.Arg
import Lean.Elab.PatternVar
import Lean.Elab.ElabRules
import Lean.Elab.Macro
import Lean.Elab.Notation
import Lean.Elab.Mixfix
import Lean.Elab.MacroRules
import Lean.Elab.BuiltinCommand
|
e457e7fe20139642f2dedf9d4490a13803e5a4b2 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/eqThm.lean | 4cbcb76345b6ae9db692b7b5472184c5fff0df48 | [
"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,436 | lean | def f : Nat → Bool → Nat
| 0, true => 1
| 0, false => 2
| 1, true => 3
| 1, _ => 4
| x+2, true => f x true
| x+2, b => f x (not b)
macro "urfl" : tactic => `(tactic| set_option smartUnfolding false in rfl)
theorem f_main_eq : f x b = f.match_1 (fun _ _ => Nat) x b (fun _ => 1) (fun _ => 2) (fun _ => 3) (fun _ => 4) (fun x => f x true) (fun x b => f x (not b)) := by
split <;> (first | rfl | (conv => lhs; delta f; whnf; simp_match); try urfl)
#check @f_main_eq
def g : List Nat → List Nat → Nat
| [], y::ys => y
| [], ys => 0
| x1::x2::xs, ys => g xs ys
| x::xs, y::ys => g xs ys + y
| x::xs, [] => g xs []
theorem g_main_eq (xs ys : List Nat) : g xs ys = g.match_1 (fun _ _ => Nat) xs ys (fun y ys => y) (fun _ => 0) (fun _ _ xs ys => g xs ys) (fun _ xs y ys => g xs ys + y) (fun _ xs => g xs []) := by
split <;> (first | rfl | (conv => lhs; delta g; whnf; simp_match); try urfl)
#check @g_main_eq
def foo (xs : List Nat) : List Nat :=
match xs with
| [] => []
| x::xs =>
let y := 2 * x;
match xs with
| [] => []
| x::xs => (y + x) :: foo xs
theorem foo_main_eq (xs : List Nat) : foo xs = foo.match_1 (fun _ => List Nat) xs (fun _ => []) (fun x xs => let y := 2*x; foo.match_1 (fun _ => List Nat) xs (fun _ => []) (fun x xs => (y + x)::foo xs)) := by
split
· rfl
· split
· rfl
· rfl
#check @foo_main_eq
|
f98464d3e9f551332ba61c8f072e80abc9168f4d | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/openTermTactic.lean | 101dde0ce0c24c1b8715ca6047985321cd0ea42d | [
"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 | 897 | lean | def f (x : Nat) :=
open Nat in
succ (succ x)
theorem f_eq : f x = Nat.succ (Nat.succ x) :=
rfl
def g (x : Nat) := open Nat in succ (succ x)
theorem f_eq_g : f x = g x := rfl
def h (x : Nat) := Nat.succ (open Nat in succ x)
theorem f_eq_h : f x = h x := rfl
open Nat in
def h' (x : Nat) := succ x
theorem ex (x y : Nat) (h : x = y) : x + 1 = y + 1 := by
open Nat in show succ x = succ y
apply congrArg
assumption
inductive InductiveWithAVeryLongName where
| c1 | c2 | c3 | c4 | c5 | c6 | c7
def foo (e : InductiveWithAVeryLongName) : Type :=
open InductiveWithAVeryLongName in
match e with
| c1 => Nat
| c2 => Nat → Nat
| c3 => Nat → Nat → Nat
| c4 => Nat → Nat → Nat → Nat
| c5 => Nat → Nat → Nat → Nat → Nat
| c6 => Nat → Nat → Nat → Nat → Nat → Nat
| c7 => Nat → Nat → Nat → Nat → Nat → Nat → Nat
|
5d3ec53de33dd22baa18460682b19c3081d7fd9f | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/field_theory/abel_ruffini.lean | 54929a6b44529906e35d69568cfe6d5f467690ee | [
"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 | 17,428 | lean | /-
Copyright (c) 2020 Thomas Browning and Patrick Lutz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Thomas Browning, Patrick Lutz
-/
import group_theory.solvable
import field_theory.polynomial_galois_group
import ring_theory.roots_of_unity
/-!
# The Abel-Ruffini Theorem
This file proves one direction of the Abel-Ruffini theorem, namely that if an element is solvable
by radicals, then its minimal polynomial has solvable Galois group.
## Main definitions
* `solvable_by_rad F E` : the intermediate field of solvable-by-radicals elements
## Main results
* the Abel-Ruffini Theorem `solvable_by_rad.is_solvable'` : An irreducible polynomial with a root
that is solvable by radicals has a solvable Galois group.
-/
noncomputable theory
open_locale classical
open polynomial intermediate_field
section abel_ruffini
variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E]
lemma gal_zero_is_solvable : is_solvable (0 : polynomial F).gal :=
by apply_instance
lemma gal_one_is_solvable : is_solvable (1 : polynomial F).gal :=
by apply_instance
lemma gal_C_is_solvable (x : F) : is_solvable (C x).gal :=
by apply_instance
lemma gal_X_is_solvable : is_solvable (X : polynomial F).gal :=
by apply_instance
lemma gal_X_sub_C_is_solvable (x : F) : is_solvable (X - C x).gal :=
by apply_instance
lemma gal_X_pow_is_solvable (n : ℕ) : is_solvable (X ^ n : polynomial F).gal :=
by apply_instance
lemma gal_mul_is_solvable {p q : polynomial F}
(hp : is_solvable p.gal) (hq : is_solvable q.gal) : is_solvable (p * q).gal :=
solvable_of_solvable_injective (gal.restrict_prod_injective p q)
lemma gal_prod_is_solvable {s : multiset (polynomial F)}
(hs : ∀ p ∈ s, is_solvable (gal p)) : is_solvable s.prod.gal :=
begin
apply multiset.induction_on' s,
{ exact gal_one_is_solvable },
{ intros p t hps hts ht,
rw [multiset.insert_eq_cons, multiset.prod_cons],
exact gal_mul_is_solvable (hs p hps) ht },
end
lemma gal_is_solvable_of_splits {p q : polynomial F}
(hpq : fact (p.splits (algebra_map F q.splitting_field))) (hq : is_solvable q.gal) :
is_solvable p.gal :=
begin
haveI : is_solvable (q.splitting_field ≃ₐ[F] q.splitting_field) := hq,
exact solvable_of_surjective (alg_equiv.restrict_normal_hom_surjective q.splitting_field),
end
lemma gal_is_solvable_tower (p q : polynomial F)
(hpq : p.splits (algebra_map F q.splitting_field))
(hp : is_solvable p.gal)
(hq : is_solvable (q.map (algebra_map F p.splitting_field)).gal) :
is_solvable q.gal :=
begin
let K := p.splitting_field,
let L := q.splitting_field,
haveI : fact (p.splits (algebra_map F L)) := ⟨hpq⟩,
let ϕ : (L ≃ₐ[K] L) ≃* (q.map (algebra_map F K)).gal :=
(is_splitting_field.alg_equiv L (q.map (algebra_map F K))).aut_congr,
have ϕ_inj : function.injective ϕ.to_monoid_hom := ϕ.injective,
haveI : is_solvable (K ≃ₐ[F] K) := hp,
haveI : is_solvable (L ≃ₐ[K] L) := solvable_of_solvable_injective ϕ_inj,
exact is_solvable_of_is_scalar_tower F p.splitting_field q.splitting_field,
end
section gal_X_pow_sub_C
lemma gal_X_pow_sub_one_is_solvable (n : ℕ) : is_solvable (X ^ n - 1 : polynomial F).gal :=
begin
by_cases hn : n = 0,
{ rw [hn, pow_zero, sub_self],
exact gal_zero_is_solvable },
have hn' : 0 < n := pos_iff_ne_zero.mpr hn,
have hn'' : (X ^ n - 1 : polynomial F) ≠ 0 :=
λ h, one_ne_zero ((leading_coeff_X_pow_sub_one hn').symm.trans (congr_arg leading_coeff h)),
apply is_solvable_of_comm,
intros σ τ,
ext a ha,
rw [mem_root_set hn'', alg_hom.map_sub, aeval_X_pow, aeval_one, sub_eq_zero] at ha,
have key : ∀ σ : (X ^ n - 1 : polynomial F).gal, ∃ m : ℕ, σ a = a ^ m,
{ intro σ,
obtain ⟨m, hm⟩ := map_root_of_unity_eq_pow_self σ.to_alg_hom
⟨is_unit.unit (is_unit_of_pow_eq_one a n ha hn'),
by { ext, rwa [units.coe_pow, is_unit.unit_spec, subtype.coe_mk n hn'] }⟩,
use m,
convert hm },
obtain ⟨c, hc⟩ := key σ,
obtain ⟨d, hd⟩ := key τ,
rw [σ.mul_apply, τ.mul_apply, hc, τ.map_pow, hd, σ.map_pow, hc, ←pow_mul, pow_mul'],
end
lemma gal_X_pow_sub_C_is_solvable_aux (n : ℕ) (a : F)
(h : (X ^ n - 1 : polynomial F).splits (ring_hom.id F)) : is_solvable (X ^ n - C a).gal :=
begin
by_cases ha : a = 0,
{ rw [ha, C_0, sub_zero],
exact gal_X_pow_is_solvable n },
have ha' : algebra_map F (X ^ n - C a).splitting_field a ≠ 0 :=
mt ((ring_hom.injective_iff _).mp (ring_hom.injective _) a) ha,
by_cases hn : n = 0,
{ rw [hn, pow_zero, ←C_1, ←C_sub],
exact gal_C_is_solvable (1 - a) },
have hn' : 0 < n := pos_iff_ne_zero.mpr hn,
have hn'' : X ^ n - C a ≠ 0 :=
λ h, one_ne_zero ((leading_coeff_X_pow_sub_C hn').symm.trans (congr_arg leading_coeff h)),
have hn''' : (X ^ n - 1 : polynomial F) ≠ 0 :=
λ h, one_ne_zero ((leading_coeff_X_pow_sub_one hn').symm.trans (congr_arg leading_coeff h)),
have mem_range : ∀ {c}, c ^ n = 1 → ∃ d, algebra_map F (X ^ n - C a).splitting_field d = c :=
λ c hc, ring_hom.mem_range.mp (minpoly.mem_range_of_degree_eq_one F c (or.resolve_left h hn'''
(minpoly.irreducible ((splitting_field.normal (X ^ n - C a)).is_integral c)) (minpoly.dvd F c
(by rwa [map_id, alg_hom.map_sub, sub_eq_zero, aeval_X_pow, aeval_one])))),
apply is_solvable_of_comm,
intros σ τ,
ext b hb,
rw [mem_root_set hn'', alg_hom.map_sub, aeval_X_pow, aeval_C, sub_eq_zero] at hb,
have hb' : b ≠ 0,
{ intro hb',
rw [hb', zero_pow hn'] at hb,
exact ha' hb.symm },
have key : ∀ σ : (X ^ n - C a).gal, ∃ c, σ b = b * algebra_map F _ c,
{ intro σ,
have key : (σ b / b) ^ n = 1 := by rw [div_pow, ←σ.map_pow, hb, σ.commutes, div_self ha'],
obtain ⟨c, hc⟩ := mem_range key,
use c,
rw [hc, mul_div_cancel' (σ b) hb'] },
obtain ⟨c, hc⟩ := key σ,
obtain ⟨d, hd⟩ := key τ,
rw [σ.mul_apply, τ.mul_apply, hc, τ.map_mul, τ.commutes, hd, σ.map_mul, σ.commutes, hc],
rw [mul_assoc, mul_assoc, mul_right_inj' hb', mul_comm],
end
lemma splits_X_pow_sub_one_of_X_pow_sub_C {F : Type*} [field F] {E : Type*} [field E]
(i : F →+* E) (n : ℕ) {a : F} (ha : a ≠ 0) (h : (X ^ n - C a).splits i) : (X ^ n - 1).splits i :=
begin
have ha' : i a ≠ 0 := mt (i.injective_iff.mp (i.injective) a) ha,
by_cases hn : n = 0,
{ rw [hn, pow_zero, sub_self],
exact splits_zero i },
have hn' : 0 < n := pos_iff_ne_zero.mpr hn,
have hn'' : (X ^ n - C a).degree ≠ 0 :=
ne_of_eq_of_ne (degree_X_pow_sub_C hn' a) (mt with_bot.coe_eq_coe.mp hn),
obtain ⟨b, hb⟩ := exists_root_of_splits i h hn'',
rw [eval₂_sub, eval₂_X_pow, eval₂_C, sub_eq_zero] at hb,
have hb' : b ≠ 0,
{ intro hb',
rw [hb', zero_pow hn'] at hb,
exact ha' hb.symm },
let s := ((X ^ n - C a).map i).roots,
have hs : _ = _ * (s.map _).prod := eq_prod_roots_of_splits h,
rw [leading_coeff_X_pow_sub_C hn', ring_hom.map_one, C_1, one_mul] at hs,
have hs' : s.card = n := (nat_degree_eq_card_roots h).symm.trans nat_degree_X_pow_sub_C,
apply @splits_of_exists_multiset F E _ _ i (X ^ n - 1) (s.map (λ c : E, c / b)),
rw [leading_coeff_X_pow_sub_one hn', ring_hom.map_one, C_1, one_mul, multiset.map_map],
have C_mul_C : (C (i a⁻¹)) * (C (i a)) = 1,
{ rw [←C_mul, ←i.map_mul, inv_mul_cancel ha, i.map_one, C_1] },
have key1 : (X ^ n - 1).map i = C (i a⁻¹) * ((X ^ n - C a).map i).comp (C b * X),
{ rw [polynomial.map_sub, polynomial.map_sub, polynomial.map_pow, map_X, map_C,
polynomial.map_one, sub_comp, pow_comp, X_comp, C_comp, mul_pow, ←C_pow, hb, mul_sub,
←mul_assoc, C_mul_C, one_mul] },
have key2 : (λ q : polynomial E, q.comp (C b * X)) ∘ (λ c : E, X - C c) =
(λ c : E, C b * (X - C (c / b))),
{ ext1 c,
change (X - C c).comp (C b * X) = C b * (X - C (c / b)),
rw [sub_comp, X_comp, C_comp, mul_sub, ←C_mul, mul_div_cancel' c hb'] },
rw [key1, hs, prod_comp, multiset.map_map, key2, multiset.prod_map_mul, multiset.map_const,
multiset.prod_repeat, hs', ←C_pow, hb, ←mul_assoc, C_mul_C, one_mul],
all_goals { exact field.to_nontrivial F },
end
lemma gal_X_pow_sub_C_is_solvable (n : ℕ) (x : F) : is_solvable (X ^ n - C x).gal :=
begin
by_cases hx : x = 0,
{ rw [hx, C_0, sub_zero],
exact gal_X_pow_is_solvable n },
apply gal_is_solvable_tower (X ^ n - 1) (X ^ n - C x),
{ exact splits_X_pow_sub_one_of_X_pow_sub_C _ n hx (splitting_field.splits _) },
{ exact gal_X_pow_sub_one_is_solvable n },
{ rw [polynomial.map_sub, polynomial.map_pow, map_X, map_C],
apply gal_X_pow_sub_C_is_solvable_aux,
have key := splitting_field.splits (X ^ n - 1 : polynomial F),
rwa [←splits_id_iff_splits, polynomial.map_sub, polynomial.map_pow, map_X, polynomial.map_one]
at key }
end
end gal_X_pow_sub_C
variables (F)
/-- Inductive definition of solvable by radicals -/
inductive is_solvable_by_rad : E → Prop
| base (a : F) : is_solvable_by_rad (algebra_map F E a)
| add (a b : E) : is_solvable_by_rad a → is_solvable_by_rad b → is_solvable_by_rad (a + b)
| neg (α : E) : is_solvable_by_rad α → is_solvable_by_rad (-α)
| mul (α β : E) : is_solvable_by_rad α → is_solvable_by_rad β → is_solvable_by_rad (α * β)
| inv (α : E) : is_solvable_by_rad α → is_solvable_by_rad α⁻¹
| rad (α : E) (n : ℕ) (hn : n ≠ 0) : is_solvable_by_rad (α^n) → is_solvable_by_rad α
variables (E)
/-- The intermediate field of solvable-by-radicals elements -/
def solvable_by_rad : intermediate_field F E :=
{ carrier := is_solvable_by_rad F,
zero_mem' := by { convert is_solvable_by_rad.base (0 : F), rw ring_hom.map_zero },
add_mem' := is_solvable_by_rad.add,
neg_mem' := is_solvable_by_rad.neg,
one_mem' := by { convert is_solvable_by_rad.base (1 : F), rw ring_hom.map_one },
mul_mem' := is_solvable_by_rad.mul,
inv_mem' := is_solvable_by_rad.inv,
algebra_map_mem' := is_solvable_by_rad.base }
namespace solvable_by_rad
variables {F} {E} {α : E}
lemma induction (P : solvable_by_rad F E → Prop)
(base : ∀ α : F, P (algebra_map F (solvable_by_rad F E) α))
(add : ∀ α β : solvable_by_rad F E, P α → P β → P (α + β))
(neg : ∀ α : solvable_by_rad F E, P α → P (-α))
(mul : ∀ α β : solvable_by_rad F E, P α → P β → P (α * β))
(inv : ∀ α : solvable_by_rad F E, P α → P α⁻¹)
(rad : ∀ α : solvable_by_rad F E, ∀ n : ℕ, n ≠ 0 → P (α^n) → P α)
(α : solvable_by_rad F E) : P α :=
begin
revert α,
suffices : ∀ (α : E), is_solvable_by_rad F α → (∃ β : solvable_by_rad F E, ↑β = α ∧ P β),
{ intro α,
obtain ⟨α₀, hα₀, Pα⟩ := this α (subtype.mem α),
convert Pα,
exact subtype.ext hα₀.symm },
apply is_solvable_by_rad.rec,
{ exact λ α, ⟨algebra_map F (solvable_by_rad F E) α, rfl, base α⟩ },
{ intros α β hα hβ Pα Pβ,
obtain ⟨⟨α₀, hα₀, Pα⟩, β₀, hβ₀, Pβ⟩ := ⟨Pα, Pβ⟩,
exact ⟨α₀ + β₀, by {rw [←hα₀, ←hβ₀], refl }, add α₀ β₀ Pα Pβ⟩ },
{ intros α hα Pα,
obtain ⟨α₀, hα₀, Pα⟩ := Pα,
exact ⟨-α₀, by {rw ←hα₀, refl }, neg α₀ Pα⟩ },
{ intros α β hα hβ Pα Pβ,
obtain ⟨⟨α₀, hα₀, Pα⟩, β₀, hβ₀, Pβ⟩ := ⟨Pα, Pβ⟩,
exact ⟨α₀ * β₀, by {rw [←hα₀, ←hβ₀], refl }, mul α₀ β₀ Pα Pβ⟩ },
{ intros α hα Pα,
obtain ⟨α₀, hα₀, Pα⟩ := Pα,
exact ⟨α₀⁻¹, by {rw ←hα₀, refl }, inv α₀ Pα⟩ },
{ intros α n hn hα Pα,
obtain ⟨α₀, hα₀, Pα⟩ := Pα,
refine ⟨⟨α, is_solvable_by_rad.rad α n hn hα⟩, rfl, rad _ n hn _⟩,
convert Pα,
exact subtype.ext (eq.trans ((solvable_by_rad F E).coe_pow _ n) hα₀.symm) }
end
theorem is_integral (α : solvable_by_rad F E) : is_integral F α :=
begin
revert α,
apply solvable_by_rad.induction,
{ exact λ _, is_integral_algebra_map },
{ exact λ _ _, is_integral_add },
{ exact λ _, is_integral_neg },
{ exact λ _ _, is_integral_mul },
{ exact λ α hα, subalgebra.inv_mem_of_algebraic (integral_closure F (solvable_by_rad F E))
(show is_algebraic F ↑(⟨α, hα⟩ : integral_closure F (solvable_by_rad F E)),
by exact is_algebraic_iff_is_integral.mpr hα) },
{ intros α n hn hα,
obtain ⟨p, h1, h2⟩ := is_algebraic_iff_is_integral.mpr hα,
refine is_algebraic_iff_is_integral.mp ⟨p.comp (X ^ n),
⟨λ h, h1 (leading_coeff_eq_zero.mp _), by rw [aeval_comp, aeval_X_pow, h2]⟩⟩,
rwa [←leading_coeff_eq_zero, leading_coeff_comp, leading_coeff_X_pow, one_pow, mul_one] at h,
rwa nat_degree_X_pow }
end
/-- The statement to be proved inductively -/
def P (α : solvable_by_rad F E) : Prop := is_solvable (minpoly F α).gal
/-- An auxiliary induction lemma, which is generalized by `solvable_by_rad.is_solvable`. -/
lemma induction3 {α : solvable_by_rad F E} {n : ℕ} (hn : n ≠ 0) (hα : P (α ^ n)) : P α :=
begin
let p := minpoly F (α ^ n),
have hp : p.comp (X ^ n) ≠ 0,
{ intro h,
cases (comp_eq_zero_iff.mp h) with h' h',
{ exact minpoly.ne_zero (is_integral (α ^ n)) h' },
{ exact hn (by rw [←nat_degree_C _, ←h'.2, nat_degree_X_pow]) } },
apply gal_is_solvable_of_splits,
{ exact ⟨splits_of_splits_of_dvd _ hp (splitting_field.splits (p.comp (X ^ n)))
(minpoly.dvd F α (by rw [aeval_comp, aeval_X_pow, minpoly.aeval]))⟩ },
{ refine gal_is_solvable_tower p (p.comp (X ^ n)) _ hα _,
{ exact gal.splits_in_splitting_field_of_comp _ _ (by rwa [nat_degree_X_pow]) },
{ obtain ⟨s, hs⟩ := exists_multiset_of_splits _ (splitting_field.splits p),
rw [map_comp, polynomial.map_pow, map_X, hs, mul_comp, C_comp],
apply gal_mul_is_solvable (gal_C_is_solvable _),
rw prod_comp,
apply gal_prod_is_solvable,
intros q hq,
rw multiset.mem_map at hq,
obtain ⟨q, hq, rfl⟩ := hq,
rw multiset.mem_map at hq,
obtain ⟨q, hq, rfl⟩ := hq,
rw [sub_comp, X_comp, C_comp],
exact gal_X_pow_sub_C_is_solvable n q } },
end
/-- An auxiliary induction lemma, which is generalized by `solvable_by_rad.is_solvable`. -/
lemma induction2 {α β γ : solvable_by_rad F E} (hγ : γ ∈ F⟮α, β⟯) (hα : P α) (hβ : P β) : P γ :=
begin
let p := (minpoly F α),
let q := (minpoly F β),
have hpq := polynomial.splits_of_splits_mul _ (mul_ne_zero (minpoly.ne_zero (is_integral α))
(minpoly.ne_zero (is_integral β))) (splitting_field.splits (p * q)),
let f : F⟮α, β⟯ →ₐ[F] (p * q).splitting_field := classical.choice (alg_hom_mk_adjoin_splits
begin
intros x hx,
cases hx,
rw hx,
exact ⟨is_integral α, hpq.1⟩,
cases hx,
exact ⟨is_integral β, hpq.2⟩,
end),
have key : minpoly F γ = minpoly F (f ⟨γ, hγ⟩) := minpoly.eq_of_irreducible_of_monic
(minpoly.irreducible (is_integral γ)) begin
suffices : aeval (⟨γ, hγ⟩ : F ⟮α, β⟯) (minpoly F γ) = 0,
{ rw [aeval_alg_hom_apply, this, alg_hom.map_zero] },
apply (algebra_map F⟮α, β⟯ (solvable_by_rad F E)).injective,
rw [ring_hom.map_zero, is_scalar_tower.algebra_map_aeval],
exact minpoly.aeval F γ,
end (minpoly.monic (is_integral γ)),
rw [P, key],
exact gal_is_solvable_of_splits ⟨normal.splits (splitting_field.normal _) _⟩
(gal_mul_is_solvable hα hβ),
end
/-- An auxiliary induction lemma, which is generalized by `solvable_by_rad.is_solvable`. -/
lemma induction1 {α β : solvable_by_rad F E} (hβ : β ∈ F⟮α⟯) (hα : P α) : P β :=
induction2 (adjoin.mono F _ _ (ge_of_eq (set.pair_eq_singleton α)) hβ) hα hα
theorem is_solvable (α : solvable_by_rad F E) :
is_solvable (minpoly F α).gal :=
begin
revert α,
apply solvable_by_rad.induction,
{ exact λ α, by { rw minpoly.eq_X_sub_C, exact gal_X_sub_C_is_solvable α } },
{ exact λ α β, induction2 (add_mem _ (subset_adjoin F _ (set.mem_insert α _))
(subset_adjoin F _ (set.mem_insert_of_mem α (set.mem_singleton β)))) },
{ exact λ α, induction1 (neg_mem _ (mem_adjoin_simple_self F α)) },
{ exact λ α β, induction2 (mul_mem _ (subset_adjoin F _ (set.mem_insert α _))
(subset_adjoin F _ (set.mem_insert_of_mem α (set.mem_singleton β)))) },
{ exact λ α, induction1 (inv_mem _ (mem_adjoin_simple_self F α)) },
{ exact λ α n, induction3 },
end
/-- **Abel-Ruffini Theorem** (one direction): An irreducible polynomial with an
`is_solvable_by_rad` root has solvable Galois group -/
lemma is_solvable' {α : E} {q : polynomial F} (q_irred : irreducible q)
(q_aeval : aeval α q = 0) (hα : is_solvable_by_rad F α) :
_root_.is_solvable q.gal :=
begin
haveI : _root_.is_solvable (q * C q.leading_coeff⁻¹).gal,
{ rw [minpoly.eq_of_irreducible q_irred q_aeval,
←show minpoly F (⟨α, hα⟩ : solvable_by_rad F E) = minpoly F α,
from minpoly.eq_of_algebra_map_eq (ring_hom.injective _) (is_integral ⟨α, hα⟩) rfl],
exact is_solvable ⟨α, hα⟩ },
refine solvable_of_surjective (gal.restrict_dvd_surjective ⟨C q.leading_coeff⁻¹, rfl⟩ _),
rw [mul_ne_zero_iff, ne, ne, C_eq_zero, inv_eq_zero],
exact ⟨q_irred.ne_zero, leading_coeff_ne_zero.mpr q_irred.ne_zero⟩,
end
end solvable_by_rad
end abel_ruffini
|
8fa2a4637ee82be8887259b2c7f2853e9bb0d3ed | 471bedbd023d35c9d078c2f936dd577ace7f5813 | /library/init/meta/declaration.lean | 6e179294ab47514b4e939affeee5816e6135254f | [
"Apache-2.0"
] | permissive | lambdaxymox/lean | e06f0fa503666df827edd9867d7f49ca017aae64 | fc13c8c72a15dab71a2c2b31410c2cadc3526bd7 | refs/heads/master | 1,666,785,407,985 | 1,666,153,673,000 | 1,666,153,673,000 | 310,165,986 | 0 | 0 | Apache-2.0 | 1,604,542,096,000 | 1,604,542,095,000 | null | UTF-8 | Lean | false | false | 5,469 | 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.expr init.meta.name init.meta.task
/--
Reducibility hints are used in the convertibility checker.
When trying to solve a constraint such a
(f ...) =?= (g ...)
where f and g are definitions, the checker has to decide which one will be unfolded.
If f (g) is opaque, then g (f) is unfolded if it is also not marked as opaque,
Else if f (g) is abbrev, then f (g) is unfolded if g (f) is also not marked as abbrev,
Else if f and g are regular, then we unfold the one with the biggest definitional height.
Otherwise both are unfolded.
The arguments of the `regular` constructor are: the definitional height and the flag `self_opt`.
The definitional height is by default computed by the kernel. It only takes into account
other regular definitions used in a definition. When creating declarations using meta-programming,
we can specify the definitional depth manually.
For definitions marked as regular, we also have a hint for constraints such as
(f a) =?= (f b)
if self_opt == true, then checker will first try to solve (a =?= b), only if it fails,
it unfolds f.
Remark: the hint only affects performance. None of the hints prevent the kernel from unfolding a
declaration during type checking.
Remark: the reducibility_hints are not related to the attributes: reducible/irrelevance/semireducible.
These attributes are used by the elaborator. The reducibility_hints are used by the kernel (and elaborator).
Moreover, the reducibility_hints cannot be changed after a declaration is added to the kernel.
-/
inductive reducibility_hints
| opaque : reducibility_hints
| abbrev : reducibility_hints
| regular : nat → bool → reducibility_hints
/-- Reflect a C++ declaration object. The VM replaces it with the C++ implementation. -/
meta inductive declaration
/- definition: name, list universe parameters, type, value, is_trusted -/
| defn : name → list name → expr → expr → reducibility_hints → bool → declaration
/- theorem: name, list universe parameters, type, value (remark: theorems are always trusted) -/
| thm : name → list name → expr → task expr → declaration
/- constant assumption: name, list universe parameters, type, is_trusted -/
| cnst : name → list name → expr → bool → declaration
/- axiom : name → list universe parameters, type (remark: axioms are always trusted) -/
| ax : name → list name → expr → declaration
open declaration
meta def mk_definition (n : name) (ls : list name) (v : expr) (e : expr) : declaration :=
defn n ls v e (reducibility_hints.regular 1 tt) tt
namespace declaration
meta def to_name : declaration → name
| (defn n _ _ _ _ _) := n
| (thm n _ _ _) := n
| (cnst n _ _ _) := n
| (ax n _ _) := n
meta def univ_params : declaration → list name
| (defn _ ls _ _ _ _) := ls
| (thm _ ls _ _) := ls
| (cnst _ ls _ _) := ls
| (ax _ ls _) := ls
meta def type : declaration → expr
| (defn _ _ t _ _ _) := t
| (thm _ _ t _) := t
| (cnst _ _ t _) := t
| (ax _ _ t) := t
meta def value : declaration → expr
| (defn _ _ _ v _ _) := v
| (thm _ _ _ v) := v.get
| _ := default
meta def value_task : declaration → task expr
| (defn _ _ _ v _ _) := task.pure v
| (thm _ _ _ v) := v
| _ := task.pure default
meta def is_trusted : declaration → bool
| (defn _ _ _ _ _ t) := t
| (cnst _ _ _ t) := t
| _ := tt
meta def update_type : declaration → expr → declaration
| (defn n ls t v h tr) new_t := defn n ls new_t v h tr
| (thm n ls t v) new_t := thm n ls new_t v
| (cnst n ls t tr) new_t := cnst n ls new_t tr
| (ax n ls t) new_t := ax n ls new_t
meta def update_name : declaration → name → declaration
| (defn n ls t v h tr) new_n := defn new_n ls t v h tr
| (thm n ls t v) new_n := thm new_n ls t v
| (cnst n ls t tr) new_n := cnst new_n ls t tr
| (ax n ls t) new_n := ax new_n ls t
meta def update_value : declaration → expr → declaration
| (defn n ls t v h tr) new_v := defn n ls t new_v h tr
| (thm n ls t v) new_v := thm n ls t (task.pure new_v)
| d new_v := d
meta def update_value_task : declaration → task expr → declaration
| (defn n ls t v h tr) new_v := defn n ls t new_v.get h tr
| (thm n ls t v) new_v := thm n ls t new_v
| d new_v := d
meta def map_value : declaration → (expr → expr) → declaration
| (defn n ls t v h tr) f := defn n ls t (f v) h tr
| (thm n ls t v) f := thm n ls t (task.map f v)
| d f := d
meta def to_definition : declaration → declaration
| (cnst n ls t tr) := defn n ls t default reducibility_hints.abbrev tr
| (ax n ls t) := thm n ls t (task.pure default)
| d := d
meta def is_definition : declaration → bool
| (defn _ _ _ _ _ _) := tt
| _ := ff
/-- Instantiate a universe polymorphic declaration type with the given universes. -/
meta constant instantiate_type_univ_params : declaration → list level → option expr
/-- Instantiate a universe polymorphic declaration value with the given universes. -/
meta constant instantiate_value_univ_params : declaration → list level → option expr
end declaration
|
b63c9fe9ef61996e36e0b96077865e9d56e580d5 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/lie/of_associative.lean | e63c1a71f10e12cb57d8e45e6fcd603648b033d3 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 10,761 | lean | /-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import algebra.lie.basic
import algebra.lie.subalgebra
import algebra.lie.submodule
import algebra.algebra.subalgebra.basic
/-!
# Lie algebras of associative algebras
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines the Lie algebra structure that arises on an associative algebra via the ring
commutator.
Since the linear endomorphisms of a Lie algebra form an associative algebra, one can define the
adjoint action as a morphism of Lie algebras from a Lie algebra to its linear endomorphisms. We
make such a definition in this file.
## Main definitions
* `lie_algebra.of_associative_algebra`
* `lie_algebra.of_associative_algebra_hom`
* `lie_module.to_endomorphism`
* `lie_algebra.ad`
* `linear_equiv.lie_conj`
* `alg_equiv.to_lie_equiv`
## Tags
lie algebra, ring commutator, adjoint action
-/
universes u v w w₁ w₂
section of_associative
variables {A : Type v} [ring A]
namespace ring
/-- The bracket operation for rings is the ring commutator, which captures the extent to which a
ring is commutative. It is identically zero exactly when the ring is commutative. -/
@[priority 100]
instance : has_bracket A A := ⟨λ x y, x*y - y*x⟩
lemma lie_def (x y : A) : ⁅x, y⁆ = x*y - y*x := rfl
end ring
lemma commute_iff_lie_eq {x y : A} : commute x y ↔ ⁅x, y⁆ = 0 := sub_eq_zero.symm
lemma commute.lie_eq {x y : A} (h : commute x y) : ⁅x, y⁆ = 0 := sub_eq_zero_of_eq h
namespace lie_ring
/-- An associative ring gives rise to a Lie ring by taking the bracket to be the ring commutator. -/
@[priority 100]
instance of_associative_ring : lie_ring A :=
{ add_lie := by simp only [ring.lie_def, right_distrib, left_distrib,
sub_eq_add_neg, add_comm, add_left_comm, forall_const, eq_self_iff_true, neg_add_rev],
lie_add := by simp only [ring.lie_def, right_distrib, left_distrib,
sub_eq_add_neg, add_comm, add_left_comm, forall_const, eq_self_iff_true, neg_add_rev],
lie_self := by simp only [ring.lie_def, forall_const, sub_self],
leibniz_lie := λ x y z, by { repeat { rw ring.lie_def, }, noncomm_ring, } }
lemma of_associative_ring_bracket (x y : A) : ⁅x, y⁆ = x*y - y*x := rfl
@[simp] lemma lie_apply {α : Type*} (f g : α → A) (a : α) : ⁅f, g⁆ a = ⁅f a, g a⁆ := rfl
end lie_ring
section associative_module
variables {M : Type w} [add_comm_group M] [module A M]
/-- We can regard a module over an associative ring `A` as a Lie ring module over `A` with Lie
bracket equal to its ring commutator.
Note that this cannot be a global instance because it would create a diamond when `M = A`,
specifically we can build two mathematically-different `has_bracket A A`s:
1. `@ring.has_bracket A _` which says `⁅a, b⁆ = a * b - b * a`
2. `(@lie_ring_module.of_associative_module A _ A _ _).to_has_bracket` which says `⁅a, b⁆ = a • b`
(and thus `⁅a, b⁆ = a * b`)
See note [reducible non-instances] -/
@[reducible]
def lie_ring_module.of_associative_module : lie_ring_module A M :=
{ bracket := (•),
add_lie := add_smul,
lie_add := smul_add,
leibniz_lie :=
by simp [lie_ring.of_associative_ring_bracket, sub_smul, mul_smul, sub_add_cancel], }
local attribute [instance] lie_ring_module.of_associative_module
lemma lie_eq_smul (a : A) (m : M) : ⁅a, m⁆ = a • m := rfl
end associative_module
section lie_algebra
variables {R : Type u} [comm_ring R] [algebra R A]
/-- An associative algebra gives rise to a Lie algebra by taking the bracket to be the ring
commutator. -/
@[priority 100]
instance lie_algebra.of_associative_algebra : lie_algebra R A :=
{ lie_smul := λ t x y,
by rw [lie_ring.of_associative_ring_bracket, lie_ring.of_associative_ring_bracket,
algebra.mul_smul_comm, algebra.smul_mul_assoc, smul_sub], }
local attribute [instance] lie_ring_module.of_associative_module
section associative_representation
variables {M : Type w} [add_comm_group M] [module R M] [module A M] [is_scalar_tower R A M]
/-- A representation of an associative algebra `A` is also a representation of `A`, regarded as a
Lie algebra via the ring commutator.
See the comment at `lie_ring_module.of_associative_module` for why the possibility `M = A` means
this cannot be a global instance. -/
def lie_module.of_associative_module : lie_module R A M :=
{ smul_lie := smul_assoc,
lie_smul := smul_algebra_smul_comm }
instance module.End.lie_ring_module : lie_ring_module (module.End R M) M :=
lie_ring_module.of_associative_module
instance module.End.lie_module : lie_module R (module.End R M) M :=
lie_module.of_associative_module
end associative_representation
namespace alg_hom
variables {B : Type w} {C : Type w₁} [ring B] [ring C] [algebra R B] [algebra R C]
variables (f : A →ₐ[R] B) (g : B →ₐ[R] C)
/-- The map `of_associative_algebra` associating a Lie algebra to an associative algebra is
functorial. -/
def to_lie_hom : A →ₗ⁅R⁆ B :=
{ map_lie' := λ x y, show f ⁅x,y⁆ = ⁅f x,f y⁆,
by simp only [lie_ring.of_associative_ring_bracket, alg_hom.map_sub, alg_hom.map_mul],
..f.to_linear_map, }
instance : has_coe (A →ₐ[R] B) (A →ₗ⁅R⁆ B) := ⟨to_lie_hom⟩
@[simp] lemma to_lie_hom_coe : f.to_lie_hom = ↑f := rfl
@[simp] lemma coe_to_lie_hom : ((f : A →ₗ⁅R⁆ B) : A → B) = f := rfl
lemma to_lie_hom_apply (x : A) : f.to_lie_hom x = f x := rfl
@[simp] lemma to_lie_hom_id : (alg_hom.id R A : A →ₗ⁅R⁆ A) = lie_hom.id := rfl
@[simp] lemma to_lie_hom_comp : (g.comp f : A →ₗ⁅R⁆ C) = (g : B →ₗ⁅R⁆ C).comp (f : A →ₗ⁅R⁆ B) := rfl
lemma to_lie_hom_injective {f g : A →ₐ[R] B}
(h : (f : A →ₗ⁅R⁆ B) = (g : A →ₗ⁅R⁆ B)) : f = g :=
by { ext a, exact lie_hom.congr_fun h a, }
end alg_hom
end lie_algebra
end of_associative
section adjoint_action
variables (R : Type u) (L : Type v) (M : Type w)
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M]
variables [lie_ring_module L M] [lie_module R L M]
/-- A Lie module yields a Lie algebra morphism into the linear endomorphisms of the module.
See also `lie_module.to_module_hom`. -/
@[simps] def lie_module.to_endomorphism : L →ₗ⁅R⁆ module.End R M :=
{ to_fun := λ x,
{ to_fun := λ m, ⁅x, m⁆,
map_add' := lie_add x,
map_smul' := λ t, lie_smul t x, },
map_add' := λ x y, by { ext m, apply add_lie, },
map_smul' := λ t x, by { ext m, apply smul_lie, },
map_lie' := λ x y, by { ext m, apply lie_lie, }, }
/-- The adjoint action of a Lie algebra on itself. -/
def lie_algebra.ad : L →ₗ⁅R⁆ module.End R L := lie_module.to_endomorphism R L L
@[simp] lemma lie_algebra.ad_apply (x y : L) : lie_algebra.ad R L x y = ⁅x, y⁆ := rfl
@[simp] lemma lie_module.to_endomorphism_module_End :
lie_module.to_endomorphism R (module.End R M) M = lie_hom.id :=
by { ext g m, simp [lie_eq_smul], }
lemma lie_subalgebra.to_endomorphism_eq (K : lie_subalgebra R L) {x : K} :
lie_module.to_endomorphism R K M x = lie_module.to_endomorphism R L M x :=
rfl
@[simp] lemma lie_subalgebra.to_endomorphism_mk (K : lie_subalgebra R L) {x : L} (hx : x ∈ K) :
lie_module.to_endomorphism R K M ⟨x, hx⟩ = lie_module.to_endomorphism R L M x :=
rfl
variables {R L M}
namespace lie_submodule
open lie_module
variables {N : lie_submodule R L M} {x : L}
lemma coe_map_to_endomorphism_le :
(N : submodule R M).map (lie_module.to_endomorphism R L M x) ≤ N :=
begin
rintros n ⟨m, hm, rfl⟩,
exact N.lie_mem hm,
end
variables (N x)
lemma to_endomorphism_comp_subtype_mem (m : M) (hm : m ∈ (N : submodule R M)) :
(to_endomorphism R L M x).comp (N : submodule R M).subtype ⟨m, hm⟩ ∈ (N : submodule R M) :=
by simpa using N.lie_mem hm
@[simp] lemma to_endomorphism_restrict_eq_to_endomorphism
(h := N.to_endomorphism_comp_subtype_mem x) :
(to_endomorphism R L M x).restrict h = to_endomorphism R L N x :=
by { ext, simp [linear_map.restrict_apply], }
end lie_submodule
open lie_algebra
lemma lie_algebra.ad_eq_lmul_left_sub_lmul_right (A : Type v) [ring A] [algebra R A] :
(ad R A : A → module.End R A) = linear_map.mul_left R - linear_map.mul_right R :=
by { ext a b, simp [lie_ring.of_associative_ring_bracket], }
lemma lie_subalgebra.ad_comp_incl_eq (K : lie_subalgebra R L) (x : K) :
(ad R L ↑x).comp (K.incl : K →ₗ[R] L) = (K.incl : K →ₗ[R] L).comp (ad R K x) :=
begin
ext y,
simp only [ad_apply, lie_hom.coe_to_linear_map, lie_subalgebra.coe_incl, linear_map.coe_comp,
lie_subalgebra.coe_bracket, function.comp_app],
end
end adjoint_action
/-- A subalgebra of an associative algebra is a Lie subalgebra of the associated Lie algebra. -/
def lie_subalgebra_of_subalgebra (R : Type u) [comm_ring R] (A : Type v) [ring A] [algebra R A]
(A' : subalgebra R A) : lie_subalgebra R A :=
{ lie_mem' := λ x y hx hy, by
{ change ⁅x, y⁆ ∈ A', change x ∈ A' at hx, change y ∈ A' at hy,
rw lie_ring.of_associative_ring_bracket,
have hxy := A'.mul_mem hx hy,
have hyx := A'.mul_mem hy hx,
exact submodule.sub_mem A'.to_submodule hxy hyx, },
..A'.to_submodule }
namespace linear_equiv
variables {R : Type u} {M₁ : Type v} {M₂ : Type w}
variables [comm_ring R] [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂]
variables (e : M₁ ≃ₗ[R] M₂)
/-- A linear equivalence of two modules induces a Lie algebra equivalence of their endomorphisms. -/
def lie_conj : module.End R M₁ ≃ₗ⁅R⁆ module.End R M₂ :=
{ map_lie' := λ f g, show e.conj ⁅f, g⁆ = ⁅e.conj f, e.conj g⁆,
by simp only [lie_ring.of_associative_ring_bracket, linear_map.mul_eq_comp, e.conj_comp,
linear_equiv.map_sub],
..e.conj }
@[simp] lemma lie_conj_apply (f : module.End R M₁) : e.lie_conj f = e.conj f := rfl
@[simp] lemma lie_conj_symm : e.lie_conj.symm = e.symm.lie_conj := rfl
end linear_equiv
namespace alg_equiv
variables {R : Type u} {A₁ : Type v} {A₂ : Type w}
variables [comm_ring R] [ring A₁] [ring A₂] [algebra R A₁] [algebra R A₂]
variables (e : A₁ ≃ₐ[R] A₂)
/-- An equivalence of associative algebras is an equivalence of associated Lie algebras. -/
def to_lie_equiv : A₁ ≃ₗ⁅R⁆ A₂ :=
{ to_fun := e.to_fun,
map_lie' := λ x y, by simp [lie_ring.of_associative_ring_bracket],
..e.to_linear_equiv }
@[simp] lemma to_lie_equiv_apply (x : A₁) : e.to_lie_equiv x = e x := rfl
@[simp] lemma to_lie_equiv_symm_apply (x : A₂) : e.to_lie_equiv.symm x = e.symm x := rfl
end alg_equiv
|
d425a6d739ab91f2bd3b4462ae923560f75e2d16 | 9d2e3d5a2e2342a283affd97eead310c3b528a24 | /src/exercises_sources/thursday/afternoon/category_theory/exercise8.lean | 7a307acad0a36cf48af6c6349ca17487392c8448 | [] | permissive | Vtec234/lftcm2020 | ad2610ab614beefe44acc5622bb4a7fff9a5ea46 | bbbd4c8162f8c2ef602300ab8fdeca231886375d | refs/heads/master | 1,668,808,098,623 | 1,594,989,081,000 | 1,594,990,079,000 | 280,423,039 | 0 | 0 | MIT | 1,594,990,209,000 | 1,594,990,209,000 | null | UTF-8 | Lean | false | false | 1,557 | lean | import algebra.category.Module.basic
import linear_algebra.finite_dimensional
/-!
Every monomorphism in fdVec splits.
This is not-so-secretly an exercise in using the linear algebra library
-/
variables (𝕜 : Type) [field 𝕜]
open category_theory
abbreviation Vec := Module 𝕜
@[derive category]
def fdVec := { V : Vec 𝕜 // finite_dimensional 𝕜 V }
/--
We set up a `has_coe_to_sort` for `fdVec 𝕜`, sending an object directly to the underlying type.
-/
instance : has_coe_to_sort (fdVec 𝕜) :=
{ S := Type*,
coe := λ V, V.val, }
/--
Lean can already work out that this underlying type has the `module 𝕜` typeclass.
-/
example (V : fdVec 𝕜) : module 𝕜 V := by apply_instance
/--
But we need to tell it about the availability of the `finite_dimensional 𝕜` typeclass.
-/
instance fdVec_finite_dimensional (V : fdVec 𝕜) : finite_dimensional 𝕜 V := V.property
def exercise {X Y : fdVec 𝕜} (f : X ⟶ Y) [mono f] : split_mono f :=
-- We want to
-- * pick a basis of `X`, using `exists_is_basis`
-- * see that its image under `f` is linearly independent in `Y`, using `linear_independent.image_subtype`
-- * extend that set to a basis of `Y` using `exists_subset_is_basis`
-- * define a map back using `is_basis.constr`
-- * check it has the right property, using `is_basis.ext`
sorry
/-!
In practice, one should just prove this theorem directly in the linear algebra library,
without reference to `fdVec`. The statement will be more verbose!
The proof of the "categorical" statement should just be one line.
-/
|
1eea8587428d593322fb9d7cee3e8186ead29ea0 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/algebra/group_with_zero/basic.lean | 49998d2c7aceb20a4cd157799b6324939d9eba27 | [
"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 | 45,938 | 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 logic.nontrivial
import algebra.group.units_hom
import algebra.group.inj_surj
import algebra.group_with_zero.defs
/-!
# Groups with an adjoined zero element
This file describes structures that are not usually studied on their own right in mathematics,
namely a special sort of monoid: apart from a distinguished “zero element” they form a group,
or in other words, they are groups with an adjoined zero element.
Examples are:
* division rings;
* the value monoid of a multiplicative valuation;
* in particular, the non-negative real numbers.
## Main definitions
Various lemmas about `group_with_zero` and `comm_group_with_zero`.
To reduce import dependencies, the type-classes themselves are in
`algebra.group_with_zero.defs`.
## Implementation details
As is usual in mathlib, we extend the inverse function to the zero element,
and require `0⁻¹ = 0`.
-/
set_option old_structure_cmd true
open_locale classical
open function
variables {M₀ G₀ M₀' G₀' : Type*}
mk_simp_attribute field_simps "The simpset `field_simps` is used by the tactic `field_simp` to
reduce an expression in a field to an expression of the form `n / d` where `n` and `d` are
division-free."
attribute [field_simps] mul_div_assoc'
section
section mul_zero_class
variables [mul_zero_class M₀] {a b : M₀}
/-- Pullback a `mul_zero_class` instance along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.mul_zero_class [has_mul M₀'] [has_zero M₀'] (f : M₀' → M₀)
(hf : injective f) (zero : f 0 = 0) (mul : ∀ a b, f (a * b) = f a * f b) :
mul_zero_class M₀' :=
{ mul := (*),
zero := 0,
zero_mul := λ a, hf $ by simp only [mul, zero, zero_mul],
mul_zero := λ a, hf $ by simp only [mul, zero, mul_zero] }
/-- Pushforward a `mul_zero_class` instance along an surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.mul_zero_class [has_mul M₀'] [has_zero M₀'] (f : M₀ → M₀')
(hf : surjective f) (zero : f 0 = 0) (mul : ∀ a b, f (a * b) = f a * f b) :
mul_zero_class M₀' :=
{ mul := (*),
zero := 0,
mul_zero := hf.forall.2 $ λ x, by simp only [← zero, ← mul, mul_zero],
zero_mul := hf.forall.2 $ λ x, by simp only [← zero, ← mul, zero_mul] }
lemma mul_eq_zero_of_left (h : a = 0) (b : M₀) : a * b = 0 := h.symm ▸ zero_mul b
lemma mul_eq_zero_of_right (a : M₀) (h : b = 0) : a * b = 0 := h.symm ▸ mul_zero a
lemma left_ne_zero_of_mul : a * b ≠ 0 → a ≠ 0 := mt (λ h, mul_eq_zero_of_left h b)
lemma right_ne_zero_of_mul : a * b ≠ 0 → b ≠ 0 := mt (mul_eq_zero_of_right a)
lemma ne_zero_and_ne_zero_of_mul (h : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 :=
⟨left_ne_zero_of_mul h, right_ne_zero_of_mul h⟩
lemma mul_eq_zero_of_ne_zero_imp_eq_zero {a b : M₀} (h : a ≠ 0 → b = 0) :
a * b = 0 :=
if ha : a = 0 then by rw [ha, zero_mul] else by rw [h ha, mul_zero]
end mul_zero_class
/-- Pushforward a `no_zero_divisors` instance along an injective function. -/
protected lemma function.injective.no_zero_divisors [has_mul M₀] [has_zero M₀]
[has_mul M₀'] [has_zero M₀'] [no_zero_divisors M₀']
(f : M₀ → M₀') (hf : injective f) (zero : f 0 = 0) (mul : ∀ x y, f (x * y) = f x * f y) :
no_zero_divisors M₀ :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ x y H,
have f x * f y = 0, by rw [← mul, H, zero],
(eq_zero_or_eq_zero_of_mul_eq_zero this).imp (λ H, hf $ by rwa zero) (λ H, hf $ by rwa zero) }
lemma eq_zero_of_mul_self_eq_zero [has_mul M₀] [has_zero M₀] [no_zero_divisors M₀]
{a : M₀} (h : a * a = 0) :
a = 0 :=
(eq_zero_or_eq_zero_of_mul_eq_zero h).elim id id
section
variables [mul_zero_class M₀] [no_zero_divisors M₀] {a b : M₀}
/-- If `α` has no zero divisors, then the product of two elements equals zero iff one of them
equals zero. -/
@[simp] theorem mul_eq_zero : a * b = 0 ↔ a = 0 ∨ b = 0 :=
⟨eq_zero_or_eq_zero_of_mul_eq_zero,
λo, o.elim (λ h, mul_eq_zero_of_left h b) (mul_eq_zero_of_right a)⟩
/-- If `α` has no zero divisors, then the product of two elements equals zero iff one of them
equals zero. -/
@[simp] theorem zero_eq_mul : 0 = a * b ↔ a = 0 ∨ b = 0 :=
by rw [eq_comm, mul_eq_zero]
/-- If `α` has no zero divisors, then the product of two elements is nonzero iff both of them
are nonzero. -/
theorem mul_ne_zero_iff : a * b ≠ 0 ↔ a ≠ 0 ∧ b ≠ 0 :=
(not_congr mul_eq_zero).trans not_or_distrib
@[field_simps] theorem mul_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : a * b ≠ 0 :=
mul_ne_zero_iff.2 ⟨ha, hb⟩
/-- If `α` has no zero divisors, then for elements `a, b : α`, `a * b` equals zero iff so is
`b * a`. -/
theorem mul_eq_zero_comm : a * b = 0 ↔ b * a = 0 :=
mul_eq_zero.trans $ (or_comm _ _).trans mul_eq_zero.symm
/-- If `α` has no zero divisors, then for elements `a, b : α`, `a * b` is nonzero iff so is
`b * a`. -/
theorem mul_ne_zero_comm : a * b ≠ 0 ↔ b * a ≠ 0 :=
not_congr mul_eq_zero_comm
lemma mul_self_eq_zero : a * a = 0 ↔ a = 0 := by simp
lemma zero_eq_mul_self : 0 = a * a ↔ a = 0 := by simp
end
end
section
variables [mul_zero_one_class M₀]
/-- Pullback a `mul_zero_one_class` instance along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.mul_zero_one_class [has_mul M₀'] [has_zero M₀'] [has_one M₀']
(f : M₀' → M₀)
(hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ a b, f (a * b) = f a * f b) :
mul_zero_one_class M₀' :=
{ ..hf.mul_zero_class f zero mul, ..hf.mul_one_class f one mul }
/-- Pushforward a `mul_zero_one_class` instance along an surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.mul_zero_one_class [has_mul M₀'] [has_zero M₀'] [has_one M₀']
(f : M₀ → M₀')
(hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ a b, f (a * b) = f a * f b) :
mul_zero_one_class M₀' :=
{ ..hf.mul_zero_class f zero mul, ..hf.mul_one_class f one mul }
/-- In a monoid with zero, if zero equals one, then zero is the only element. -/
lemma eq_zero_of_zero_eq_one (h : (0 : M₀) = 1) (a : M₀) : a = 0 :=
by rw [← mul_one a, ← h, mul_zero]
/-- In a monoid with zero, if zero equals one, then zero is the unique element.
Somewhat arbitrarily, we define the default element to be `0`.
All other elements will be provably equal to it, but not necessarily definitionally equal. -/
def unique_of_zero_eq_one (h : (0 : M₀) = 1) : unique M₀ :=
{ default := 0, uniq := eq_zero_of_zero_eq_one h }
/-- In a monoid with zero, zero equals one if and only if all elements of that semiring
are equal. -/
theorem subsingleton_iff_zero_eq_one : (0 : M₀) = 1 ↔ subsingleton M₀ :=
⟨λ h, @unique.subsingleton _ (unique_of_zero_eq_one h), λ h, @subsingleton.elim _ h _ _⟩
alias subsingleton_iff_zero_eq_one ↔ subsingleton_of_zero_eq_one _
lemma eq_of_zero_eq_one (h : (0 : M₀) = 1) (a b : M₀) : a = b :=
@subsingleton.elim _ (subsingleton_of_zero_eq_one h) a b
/-- In a monoid with zero, either zero and one are nonequal, or zero is the only element. -/
lemma zero_ne_one_or_forall_eq_0 : (0 : M₀) ≠ 1 ∨ (∀a:M₀, a = 0) :=
not_or_of_imp eq_zero_of_zero_eq_one
end
section
variables [mul_zero_one_class M₀] [nontrivial M₀] {a b : M₀}
/-- In a nontrivial monoid with zero, zero and one are different. -/
@[simp] lemma zero_ne_one : 0 ≠ (1:M₀) :=
begin
assume h,
rcases exists_pair_ne M₀ with ⟨x, y, hx⟩,
apply hx,
calc x = 1 * x : by rw [one_mul]
... = 0 : by rw [← h, zero_mul]
... = 1 * y : by rw [← h, zero_mul]
... = y : by rw [one_mul]
end
@[simp] lemma one_ne_zero : (1:M₀) ≠ 0 :=
zero_ne_one.symm
lemma ne_zero_of_eq_one {a : M₀} (h : a = 1) : a ≠ 0 :=
calc a = 1 : h
... ≠ 0 : one_ne_zero
lemma left_ne_zero_of_mul_eq_one (h : a * b = 1) : a ≠ 0 :=
left_ne_zero_of_mul $ ne_zero_of_eq_one h
lemma right_ne_zero_of_mul_eq_one (h : a * b = 1) : b ≠ 0 :=
right_ne_zero_of_mul $ ne_zero_of_eq_one h
/-- Pullback a `nontrivial` instance along a function sending `0` to `0` and `1` to `1`. -/
protected lemma pullback_nonzero [has_zero M₀'] [has_one M₀']
(f : M₀' → M₀) (zero : f 0 = 0) (one : f 1 = 1) : nontrivial M₀' :=
⟨⟨0, 1, mt (congr_arg f) $ by { rw [zero, one], exact zero_ne_one }⟩⟩
end
section semigroup_with_zero
/-- Pullback a `semigroup_with_zero` class along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.semigroup_with_zero
[has_zero M₀'] [has_mul M₀'] [semigroup_with_zero M₀] (f : M₀' → M₀) (hf : injective f)
(zero : f 0 = 0) (mul : ∀ x y, f (x * y) = f x * f y) :
semigroup_with_zero M₀' :=
{ .. hf.mul_zero_class f zero mul,
.. ‹has_zero M₀'›,
.. hf.semigroup f mul }
/-- Pushforward a `semigroup_with_zero` class along an surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.semigroup_with_zero
[semigroup_with_zero M₀] [has_zero M₀'] [has_mul M₀'] (f : M₀ → M₀') (hf : surjective f)
(zero : f 0 = 0) (mul : ∀ x y, f (x * y) = f x * f y) :
semigroup_with_zero M₀' :=
{ .. hf.mul_zero_class f zero mul,
.. ‹has_zero M₀'›,
.. hf.semigroup f mul }
end semigroup_with_zero
section monoid_with_zero
/-- Pullback a `monoid_with_zero` class along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀']
[monoid_with_zero M₀]
(f : M₀' → M₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
monoid_with_zero M₀' :=
{ .. hf.monoid f one mul, .. hf.mul_zero_class f zero mul }
/-- Pushforward a `monoid_with_zero` class along a surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀']
[monoid_with_zero M₀]
(f : M₀ → M₀') (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
monoid_with_zero M₀' :=
{ .. hf.monoid f one mul, .. hf.mul_zero_class f zero mul }
/-- Pullback a `monoid_with_zero` class along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.comm_monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀']
[comm_monoid_with_zero M₀]
(f : M₀' → M₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
comm_monoid_with_zero M₀' :=
{ .. hf.comm_monoid f one mul, .. hf.mul_zero_class f zero mul }
/-- Pushforward a `monoid_with_zero` class along a surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.comm_monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀']
[comm_monoid_with_zero M₀]
(f : M₀ → M₀') (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
comm_monoid_with_zero M₀' :=
{ .. hf.comm_monoid f one mul, .. hf.mul_zero_class f zero mul }
variables [monoid_with_zero M₀]
namespace units
/-- An element of the unit group of a nonzero monoid with zero represented as an element
of the monoid is nonzero. -/
@[simp] lemma ne_zero [nontrivial M₀] (u : units M₀) :
(u : M₀) ≠ 0 :=
left_ne_zero_of_mul_eq_one u.mul_inv
-- We can't use `mul_eq_zero` + `units.ne_zero` in the next two lemmas because we don't assume
-- `nonzero M₀`.
@[simp] lemma mul_left_eq_zero (u : units M₀) {a : M₀} : a * u = 0 ↔ a = 0 :=
⟨λ h, by simpa using mul_eq_zero_of_left h ↑u⁻¹, λ h, mul_eq_zero_of_left h u⟩
@[simp] lemma mul_right_eq_zero (u : units M₀) {a : M₀} : ↑u * a = 0 ↔ a = 0 :=
⟨λ h, by simpa using mul_eq_zero_of_right ↑u⁻¹ h, mul_eq_zero_of_right u⟩
end units
namespace is_unit
lemma ne_zero [nontrivial M₀] {a : M₀} (ha : is_unit a) : a ≠ 0 := let ⟨u, hu⟩ :=
ha in hu ▸ u.ne_zero
lemma mul_right_eq_zero {a b : M₀} (ha : is_unit a) : a * b = 0 ↔ b = 0 :=
let ⟨u, hu⟩ := ha in hu ▸ u.mul_right_eq_zero
lemma mul_left_eq_zero {a b : M₀} (hb : is_unit b) : a * b = 0 ↔ a = 0 :=
let ⟨u, hu⟩ := hb in hu ▸ u.mul_left_eq_zero
end is_unit
@[simp] theorem is_unit_zero_iff : is_unit (0 : M₀) ↔ (0:M₀) = 1 :=
⟨λ ⟨⟨_, a, (a0 : 0 * a = 1), _⟩, rfl⟩, by rwa zero_mul at a0,
λ h, @is_unit_of_subsingleton _ _ (subsingleton_of_zero_eq_one h) 0⟩
@[simp] theorem not_is_unit_zero [nontrivial M₀] : ¬ is_unit (0 : M₀) :=
mt is_unit_zero_iff.1 zero_ne_one
namespace ring
open_locale classical
/-- Introduce a function `inverse` on a monoid with zero `M₀`, which sends `x` to `x⁻¹` if `x` is
invertible and to `0` otherwise. This definition is somewhat ad hoc, but one needs a fully (rather
than partially) defined inverse function for some purposes, including for calculus.
Note that while this is in the `ring` namespace for brevity, it requires the weaker assumption
`monoid_with_zero M₀` instead of `ring M₀`. -/
noncomputable def inverse : M₀ → M₀ :=
λ x, if h : is_unit x then ((h.unit⁻¹ : units M₀) : M₀) else 0
/-- By definition, if `x` is invertible then `inverse x = x⁻¹`. -/
@[simp] lemma inverse_unit (u : units M₀) : inverse (u : M₀) = (u⁻¹ : units M₀) :=
begin
simp only [units.is_unit, inverse, dif_pos],
exact units.inv_unique rfl
end
/-- By definition, if `x` is not invertible then `inverse x = 0`. -/
@[simp] lemma inverse_non_unit (x : M₀) (h : ¬(is_unit x)) : inverse x = 0 := dif_neg h
lemma mul_inverse_cancel (x : M₀) (h : is_unit x) : x * inverse x = 1 :=
by { rcases h with ⟨u, rfl⟩, rw [inverse_unit, units.mul_inv], }
lemma inverse_mul_cancel (x : M₀) (h : is_unit x) : inverse x * x = 1 :=
by { rcases h with ⟨u, rfl⟩, rw [inverse_unit, units.inv_mul], }
lemma mul_inverse_cancel_right (x y : M₀) (h : is_unit x) : y * x * inverse x = y :=
by rw [mul_assoc, mul_inverse_cancel x h, mul_one]
lemma inverse_mul_cancel_right (x y : M₀) (h : is_unit x) : y * inverse x * x = y :=
by rw [mul_assoc, inverse_mul_cancel x h, mul_one]
lemma mul_inverse_cancel_left (x y : M₀) (h : is_unit x) : x * (inverse x * y) = y :=
by rw [← mul_assoc, mul_inverse_cancel x h, one_mul]
lemma inverse_mul_cancel_left (x y : M₀) (h : is_unit x) : inverse x * (x * y) = y :=
by rw [← mul_assoc, inverse_mul_cancel x h, one_mul]
variables (M₀)
@[simp] lemma inverse_one : inverse (1 : M₀) = 1 :=
inverse_unit 1
@[simp] lemma inverse_zero : inverse (0 : M₀) = 0 :=
by { nontriviality, exact inverse_non_unit _ not_is_unit_zero }
variables {M₀}
lemma mul_inverse_rev' {a b : M₀} (h : commute a b) : inverse (a * b) = inverse b * inverse a :=
begin
by_cases hab : is_unit (a * b),
{ obtain ⟨⟨a, rfl⟩, b, rfl⟩ := h.is_unit_mul_iff.mp hab,
rw [←units.coe_mul, inverse_unit, inverse_unit, inverse_unit, ←units.coe_mul,
mul_inv_rev], },
obtain ha | hb := not_and_distrib.mp (mt h.is_unit_mul_iff.mpr hab),
{ rw [inverse_non_unit _ hab, inverse_non_unit _ ha, mul_zero]},
{ rw [inverse_non_unit _ hab, inverse_non_unit _ hb, zero_mul]},
end
lemma mul_inverse_rev {M₀} [comm_monoid_with_zero M₀] (a b : M₀) :
ring.inverse (a * b) = inverse b * inverse a :=
mul_inverse_rev' (commute.all _ _)
end ring
lemma is_unit.ring_inverse {a : M₀} : is_unit a → is_unit (ring.inverse a)
| ⟨u, hu⟩ := hu ▸ ⟨u⁻¹, (ring.inverse_unit u).symm⟩
@[simp] lemma is_unit_ring_inverse {a : M₀} : is_unit (ring.inverse a) ↔ is_unit a :=
⟨λ h, begin
casesI subsingleton_or_nontrivial M₀,
{ convert h },
{ contrapose h,
rw ring.inverse_non_unit _ h,
exact not_is_unit_zero, },
end, is_unit.ring_inverse⟩
lemma commute.ring_inverse_ring_inverse {a b : M₀} (h : commute a b) :
commute (ring.inverse a) (ring.inverse b) :=
(ring.mul_inverse_rev' h.symm).symm.trans $ (congr_arg _ h.symm.eq).trans $ ring.mul_inverse_rev' h
variable (M₀)
end monoid_with_zero
section cancel_monoid_with_zero
variables [cancel_monoid_with_zero M₀] {a b c : M₀}
@[priority 10] -- see Note [lower instance priority]
instance cancel_monoid_with_zero.to_no_zero_divisors : no_zero_divisors M₀ :=
⟨λ a b ab0, by { by_cases a = 0, { left, exact h }, right,
apply cancel_monoid_with_zero.mul_left_cancel_of_ne_zero h, rw [ab0, mul_zero], }⟩
lemma mul_left_inj' (hc : c ≠ 0) : a * c = b * c ↔ a = b := ⟨mul_right_cancel₀ hc, λ h, h ▸ rfl⟩
lemma mul_right_inj' (ha : a ≠ 0) : a * b = a * c ↔ b = c := ⟨mul_left_cancel₀ ha, λ h, h ▸ rfl⟩
@[simp] lemma mul_eq_mul_right_iff : a * c = b * c ↔ a = b ∨ c = 0 :=
by by_cases hc : c = 0; [simp [hc], simp [mul_left_inj', hc]]
@[simp] lemma mul_eq_mul_left_iff : a * b = a * c ↔ b = c ∨ a = 0 :=
by by_cases ha : a = 0; [simp [ha], simp [mul_right_inj', ha]]
/-- Pullback a `monoid_with_zero` class along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.cancel_monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀']
(f : M₀' → M₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
cancel_monoid_with_zero M₀' :=
{ mul_left_cancel_of_ne_zero := λ x y z hx H, hf $ mul_left_cancel₀ ((hf.ne_iff' zero).2 hx) $
by erw [← mul, ← mul, H]; refl,
mul_right_cancel_of_ne_zero := λ x y z hx H, hf $ mul_right_cancel₀ ((hf.ne_iff' zero).2 hx) $
by erw [← mul, ← mul, H]; refl,
.. hf.monoid f one mul, .. hf.mul_zero_class f zero mul }
/-- An element of a `cancel_monoid_with_zero` fixed by right multiplication by an element other
than one must be zero. -/
theorem eq_zero_of_mul_eq_self_right (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 :=
classical.by_contradiction $ λ ha, h₁ $ mul_left_cancel₀ ha $ h₂.symm ▸ (mul_one a).symm
/-- An element of a `cancel_monoid_with_zero` fixed by left multiplication by an element other
than one must be zero. -/
theorem eq_zero_of_mul_eq_self_left (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 :=
classical.by_contradiction $ λ ha, h₁ $ mul_right_cancel₀ ha $ h₂.symm ▸ (one_mul a).symm
end cancel_monoid_with_zero
section comm_cancel_monoid_with_zero
variables [comm_cancel_monoid_with_zero M₀] {a b c : M₀}
/-- Pullback a `comm_cancel_monoid_with_zero` class along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.comm_cancel_monoid_with_zero
[has_zero M₀'] [has_mul M₀'] [has_one M₀']
(f : M₀' → M₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
comm_cancel_monoid_with_zero M₀' :=
{ .. hf.comm_monoid_with_zero f zero one mul,
.. hf.cancel_monoid_with_zero f zero one mul }
end comm_cancel_monoid_with_zero
section group_with_zero
variables [group_with_zero G₀] {a b c g h x : G₀}
alias div_eq_mul_inv ← division_def
/-- Pullback a `group_with_zero` class along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.group_with_zero [has_zero G₀'] [has_mul G₀'] [has_one G₀']
[has_inv G₀'] [has_div G₀'] (f : G₀' → G₀) (hf : injective f) (zero : f 0 = 0) (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_with_zero G₀' :=
{ inv_zero := hf $ by erw [inv, zero, inv_zero],
mul_inv_cancel := λ x hx, hf $ by erw [one, mul, inv, mul_inv_cancel ((hf.ne_iff' zero).2 hx)],
.. hf.monoid_with_zero f zero one mul,
.. hf.div_inv_monoid f one mul inv div,
.. pullback_nonzero f zero one, }
/-- Pushforward a `group_with_zero` class along an surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.group_with_zero [has_zero G₀'] [has_mul G₀'] [has_one G₀']
[has_inv G₀'] [has_div G₀'] (h01 : (0:G₀') ≠ 1) (f : G₀ → G₀') (hf : surjective f)
(zero : f 0 = 0) (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_with_zero G₀' :=
{ inv_zero := by erw [← zero, ← inv, inv_zero],
mul_inv_cancel := hf.forall.2 $ λ x hx,
by erw [← inv, ← mul, mul_inv_cancel (mt (congr_arg f) $ trans_rel_left ne hx zero.symm)];
exact one,
exists_pair_ne := ⟨0, 1, h01⟩,
.. hf.monoid_with_zero f zero one mul,
.. hf.div_inv_monoid f one mul inv div }
@[simp] lemma mul_inv_cancel_right₀ (h : b ≠ 0) (a : G₀) :
(a * b) * b⁻¹ = a :=
calc (a * b) * b⁻¹ = a * (b * b⁻¹) : mul_assoc _ _ _
... = a : by simp [h]
@[simp] lemma mul_inv_cancel_left₀ (h : a ≠ 0) (b : G₀) :
a * (a⁻¹ * b) = b :=
calc a * (a⁻¹ * b) = (a * a⁻¹) * b : (mul_assoc _ _ _).symm
... = b : by simp [h]
lemma inv_ne_zero (h : a ≠ 0) : a⁻¹ ≠ 0 :=
assume a_eq_0, by simpa [a_eq_0] using mul_inv_cancel h
@[simp] lemma inv_mul_cancel (h : a ≠ 0) : a⁻¹ * a = 1 :=
calc a⁻¹ * a = (a⁻¹ * a) * a⁻¹ * a⁻¹⁻¹ : by simp [inv_ne_zero h]
... = a⁻¹ * a⁻¹⁻¹ : by simp [h]
... = 1 : by simp [inv_ne_zero h]
lemma group_with_zero.mul_left_injective (h : x ≠ 0) :
function.injective (λ y, x * y) :=
λ y y' w, by simpa only [←mul_assoc, inv_mul_cancel h, one_mul] using congr_arg (λ y, x⁻¹ * y) w
lemma group_with_zero.mul_right_injective (h : x ≠ 0) :
function.injective (λ y, y * x) :=
λ y y' w, by simpa only [mul_assoc, mul_inv_cancel h, mul_one] using congr_arg (λ y, y * x⁻¹) w
@[simp] lemma inv_mul_cancel_right₀ (h : b ≠ 0) (a : G₀) :
(a * b⁻¹) * b = a :=
calc (a * b⁻¹) * b = a * (b⁻¹ * b) : mul_assoc _ _ _
... = a : by simp [h]
@[simp] lemma inv_mul_cancel_left₀ (h : a ≠ 0) (b : G₀) :
a⁻¹ * (a * b) = b :=
calc a⁻¹ * (a * b) = (a⁻¹ * a) * b : (mul_assoc _ _ _).symm
... = b : by simp [h]
@[simp] lemma inv_one : 1⁻¹ = (1:G₀) :=
calc 1⁻¹ = 1 * 1⁻¹ : by rw [one_mul]
... = (1:G₀) : by simp
@[simp] lemma inv_inv₀ (a : G₀) : a⁻¹⁻¹ = a :=
begin
by_cases h : a = 0, { simp [h] },
calc a⁻¹⁻¹ = a * (a⁻¹ * a⁻¹⁻¹) : by simp [h]
... = a : by simp [inv_ne_zero h]
end
/-- Multiplying `a` by itself and then by its inverse results in `a`
(whether or not `a` is zero). -/
@[simp] lemma mul_self_mul_inv (a : G₀) : a * a * a⁻¹ = a :=
begin
by_cases h : a = 0,
{ rw [h, inv_zero, mul_zero] },
{ rw [mul_assoc, mul_inv_cancel h, mul_one] }
end
/-- Multiplying `a` by its inverse and then by itself results in `a`
(whether or not `a` is zero). -/
@[simp] lemma mul_inv_mul_self (a : G₀) : a * a⁻¹ * a = a :=
begin
by_cases h : a = 0,
{ rw [h, inv_zero, mul_zero] },
{ rw [mul_inv_cancel h, one_mul] }
end
/-- Multiplying `a⁻¹` by `a` twice results in `a` (whether or not `a`
is zero). -/
@[simp] lemma inv_mul_mul_self (a : G₀) : a⁻¹ * a * a = a :=
begin
by_cases h : a = 0,
{ rw [h, inv_zero, mul_zero] },
{ rw [inv_mul_cancel h, one_mul] }
end
/-- Multiplying `a` by itself and then dividing by itself results in
`a` (whether or not `a` is zero). -/
@[simp] lemma mul_self_div_self (a : G₀) : a * a / a = a :=
by rw [div_eq_mul_inv, mul_self_mul_inv a]
/-- Dividing `a` by itself and then multiplying by itself results in
`a` (whether or not `a` is zero). -/
@[simp] lemma div_self_mul_self (a : G₀) : a / a * a = a :=
by rw [div_eq_mul_inv, mul_inv_mul_self a]
lemma inv_involutive₀ : function.involutive (has_inv.inv : G₀ → G₀) :=
inv_inv₀
lemma eq_inv_of_mul_right_eq_one (h : a * b = 1) :
b = a⁻¹ :=
by rw [← inv_mul_cancel_left₀ (left_ne_zero_of_mul_eq_one h) b, h, mul_one]
lemma eq_inv_of_mul_left_eq_one (h : a * b = 1) :
a = b⁻¹ :=
by rw [← mul_inv_cancel_right₀ (right_ne_zero_of_mul_eq_one h) a, h, one_mul]
lemma inv_injective₀ : function.injective (@has_inv.inv G₀ _) :=
inv_involutive₀.injective
@[simp] lemma inv_inj₀ : g⁻¹ = h⁻¹ ↔ g = h := inv_injective₀.eq_iff
/-- This is the analogue of `inv_eq_iff_inv_eq` for `group_with_zero`.
It could also be named `inv_eq_iff_inv_eq'`. -/
lemma inv_eq_iff : g⁻¹ = h ↔ h⁻¹ = g :=
by rw [← inv_inj₀, eq_comm, inv_inv₀]
/-- This is the analogue of `eq_inv_iff_eq_inv` for `group_with_zero`.
It could also be named `eq_inv_iff_eq_inv'`. -/
lemma eq_inv_iff : a = b⁻¹ ↔ b = a⁻¹ :=
by rw [eq_comm, inv_eq_iff, eq_comm]
@[simp] lemma inv_eq_one₀ : g⁻¹ = 1 ↔ g = 1 :=
by rw [inv_eq_iff, inv_one, eq_comm]
lemma eq_mul_inv_iff_mul_eq₀ (hc : c ≠ 0) : a = b * c⁻¹ ↔ a * c = b :=
by split; rintro rfl; [rw inv_mul_cancel_right₀ hc, rw mul_inv_cancel_right₀ hc]
lemma eq_inv_mul_iff_mul_eq₀ (hb : b ≠ 0) : a = b⁻¹ * c ↔ b * a = c :=
by split; rintro rfl; [rw mul_inv_cancel_left₀ hb, rw inv_mul_cancel_left₀ hb]
lemma inv_mul_eq_iff_eq_mul₀ (ha : a ≠ 0) : a⁻¹ * b = c ↔ b = a * c :=
by rw [eq_comm, eq_inv_mul_iff_mul_eq₀ ha, eq_comm]
lemma mul_inv_eq_iff_eq_mul₀ (hb : b ≠ 0) : a * b⁻¹ = c ↔ a = c * b :=
by rw [eq_comm, eq_mul_inv_iff_mul_eq₀ hb, eq_comm]
lemma mul_inv_eq_one₀ (hb : b ≠ 0) : a * b⁻¹ = 1 ↔ a = b :=
by rw [mul_inv_eq_iff_eq_mul₀ hb, one_mul]
lemma inv_mul_eq_one₀ (ha : a ≠ 0) : a⁻¹ * b = 1 ↔ a = b :=
by rw [inv_mul_eq_iff_eq_mul₀ ha, mul_one, eq_comm]
lemma mul_eq_one_iff_eq_inv₀ (hb : b ≠ 0) : a * b = 1 ↔ a = b⁻¹ :=
by { convert mul_inv_eq_one₀ (inv_ne_zero hb), rw [inv_inv₀] }
lemma mul_eq_one_iff_inv_eq₀ (ha : a ≠ 0) : a * b = 1 ↔ a⁻¹ = b :=
by { convert inv_mul_eq_one₀ (inv_ne_zero ha), rw [inv_inv₀] }
end group_with_zero
namespace units
variables [group_with_zero G₀]
variables {a b : G₀}
/-- Embed a non-zero element of a `group_with_zero` into the unit group.
By combining this function with the operations on units,
or the `/ₚ` operation, it is possible to write a division
as a partial function with three arguments. -/
def mk0 (a : G₀) (ha : a ≠ 0) : units G₀ :=
⟨a, a⁻¹, mul_inv_cancel ha, inv_mul_cancel ha⟩
@[simp] lemma mk0_one (h := one_ne_zero) :
mk0 (1 : G₀) h = 1 :=
by { ext, refl }
@[simp] lemma coe_mk0 {a : G₀} (h : a ≠ 0) : (mk0 a h : G₀) = a := rfl
@[simp] lemma mk0_coe (u : units G₀) (h : (u : G₀) ≠ 0) : mk0 (u : G₀) h = u :=
units.ext rfl
@[simp, norm_cast] lemma coe_inv' (u : units G₀) : ((u⁻¹ : units G₀) : G₀) = u⁻¹ :=
eq_inv_of_mul_left_eq_one u.inv_mul
@[simp] lemma mul_inv' (u : units G₀) : (u : G₀) * u⁻¹ = 1 := mul_inv_cancel u.ne_zero
@[simp] lemma inv_mul' (u : units G₀) : (u⁻¹ : G₀) * u = 1 := inv_mul_cancel u.ne_zero
@[simp] lemma mk0_inj {a b : G₀} (ha : a ≠ 0) (hb : b ≠ 0) :
units.mk0 a ha = units.mk0 b hb ↔ a = b :=
⟨λ h, by injection h, λ h, units.ext h⟩
@[simp] lemma exists_iff_ne_zero {x : G₀} : (∃ u : units G₀, ↑u = x) ↔ x ≠ 0 :=
⟨λ ⟨u, hu⟩, hu ▸ u.ne_zero, assume hx, ⟨mk0 x hx, rfl⟩⟩
lemma _root_.group_with_zero.eq_zero_or_unit (a : G₀) :
a = 0 ∨ ∃ u : units G₀, a = u :=
begin
by_cases h : a = 0,
{ left,
exact h },
{ right,
simpa only [eq_comm] using units.exists_iff_ne_zero.mpr h }
end
instance : can_lift G₀ (units G₀) :=
{ coe := coe,
cond := (≠ 0),
prf := λ x, exists_iff_ne_zero.mpr }
end units
section group_with_zero
variables [group_with_zero G₀]
lemma is_unit.mk0 (x : G₀) (hx : x ≠ 0) : is_unit x := (units.mk0 x hx).is_unit
lemma is_unit_iff_ne_zero {x : G₀} : is_unit x ↔ x ≠ 0 :=
units.exists_iff_ne_zero
@[priority 10] -- see Note [lower instance priority]
instance group_with_zero.no_zero_divisors : no_zero_divisors G₀ :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h,
begin
contrapose! h,
exact ((units.mk0 a h.1) * (units.mk0 b h.2)).ne_zero
end,
.. (‹_› : group_with_zero G₀) }
@[priority 10] -- see Note [lower instance priority]
instance group_with_zero.cancel_monoid_with_zero : cancel_monoid_with_zero G₀ :=
{ mul_left_cancel_of_ne_zero := λ x y z hx h,
by rw [← inv_mul_cancel_left₀ hx y, h, inv_mul_cancel_left₀ hx z],
mul_right_cancel_of_ne_zero := λ x y z hy h,
by rw [← mul_inv_cancel_right₀ hy x, h, mul_inv_cancel_right₀ hy z],
.. (‹_› : group_with_zero G₀) }
-- Can't be put next to the other `mk0` lemmas becuase it depends on the
-- `no_zero_divisors` instance, which depends on `mk0`.
@[simp] lemma units.mk0_mul (x y : G₀) (hxy) :
units.mk0 (x * y) hxy =
units.mk0 x (mul_ne_zero_iff.mp hxy).1 * units.mk0 y (mul_ne_zero_iff.mp hxy).2 :=
by { ext, refl }
lemma mul_inv_rev₀ (x y : G₀) : (x * y)⁻¹ = y⁻¹ * x⁻¹ :=
begin
by_cases hx : x = 0, { simp [hx] },
by_cases hy : y = 0, { simp [hy] },
symmetry,
apply eq_inv_of_mul_left_eq_one,
simp [mul_assoc, hx, hy]
end
@[simp] lemma div_self {a : G₀} (h : a ≠ 0) : a / a = 1 :=
by rw [div_eq_mul_inv, mul_inv_cancel h]
@[simp] lemma div_one (a : G₀) : a / 1 = a :=
by simp [div_eq_mul_inv a 1]
@[simp] lemma zero_div (a : G₀) : 0 / a = 0 :=
by rw [div_eq_mul_inv, zero_mul]
@[simp] lemma div_zero (a : G₀) : a / 0 = 0 :=
by rw [div_eq_mul_inv, inv_zero, mul_zero]
@[simp] lemma div_mul_cancel (a : G₀) {b : G₀} (h : b ≠ 0) : a / b * b = a :=
by rw [div_eq_mul_inv, inv_mul_cancel_right₀ h a]
lemma div_mul_cancel_of_imp {a b : G₀} (h : b = 0 → a = 0) : a / b * b = a :=
classical.by_cases (λ hb : b = 0, by simp [*]) (div_mul_cancel a)
@[simp] lemma mul_div_cancel (a : G₀) {b : G₀} (h : b ≠ 0) : a * b / b = a :=
by rw [div_eq_mul_inv, mul_inv_cancel_right₀ h a]
lemma mul_div_cancel_of_imp {a b : G₀} (h : b = 0 → a = 0) : a * b / b = a :=
classical.by_cases (λ hb : b = 0, by simp [*]) (mul_div_cancel a)
local attribute [simp] div_eq_mul_inv mul_comm mul_assoc mul_left_comm
@[simp] lemma div_self_mul_self' (a : G₀) : a / (a * a) = a⁻¹ :=
calc a / (a * a) = a⁻¹⁻¹ * a⁻¹ * a⁻¹ : by simp [mul_inv_rev₀]
... = a⁻¹ : inv_mul_mul_self _
lemma div_eq_mul_one_div (a b : G₀) : a / b = a * (1 / b) :=
by simp
lemma mul_one_div_cancel {a : G₀} (h : a ≠ 0) : a * (1 / a) = 1 :=
by simp [h]
lemma one_div_mul_cancel {a : G₀} (h : a ≠ 0) : (1 / a) * a = 1 :=
by simp [h]
lemma one_div_one : 1 / 1 = (1:G₀) :=
div_self (ne.symm zero_ne_one)
lemma one_div_ne_zero {a : G₀} (h : a ≠ 0) : 1 / a ≠ 0 :=
by simpa only [one_div] using inv_ne_zero h
lemma eq_one_div_of_mul_eq_one {a b : G₀} (h : a * b = 1) : b = 1 / a :=
by simpa only [one_div] using eq_inv_of_mul_right_eq_one h
lemma eq_one_div_of_mul_eq_one_left {a b : G₀} (h : b * a = 1) : b = 1 / a :=
by simpa only [one_div] using eq_inv_of_mul_left_eq_one h
@[simp] lemma one_div_div (a b : G₀) : 1 / (a / b) = b / a :=
by rw [one_div, div_eq_mul_inv, mul_inv_rev₀, inv_inv₀, div_eq_mul_inv]
lemma one_div_one_div (a : G₀) : 1 / (1 / a) = a :=
by simp
lemma eq_of_one_div_eq_one_div {a b : G₀} (h : 1 / a = 1 / b) : a = b :=
by rw [← one_div_one_div a, h, one_div_one_div]
variables {a b c : G₀}
@[simp] lemma inv_eq_zero {a : G₀} : a⁻¹ = 0 ↔ a = 0 :=
by rw [inv_eq_iff, inv_zero, eq_comm]
@[simp] lemma zero_eq_inv {a : G₀} : 0 = a⁻¹ ↔ 0 = a :=
eq_comm.trans $ inv_eq_zero.trans eq_comm
lemma one_div_mul_one_div_rev (a b : G₀) : (1 / a) * (1 / b) = 1 / (b * a) :=
by simp only [div_eq_mul_inv, one_mul, mul_inv_rev₀]
theorem divp_eq_div (a : G₀) (u : units G₀) : a /ₚ u = a / u :=
by simpa only [div_eq_mul_inv] using congr_arg ((*) a) u.coe_inv'
@[simp] theorem divp_mk0 (a : G₀) {b : G₀} (hb : b ≠ 0) :
a /ₚ units.mk0 b hb = a / b :=
divp_eq_div _ _
lemma inv_div : (a / b)⁻¹ = b / a :=
by rw [div_eq_mul_inv, mul_inv_rev₀, div_eq_mul_inv, inv_inv₀]
lemma inv_div_left : a⁻¹ / b = (b * a)⁻¹ :=
by rw [mul_inv_rev₀, div_eq_mul_inv]
lemma div_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : a / b ≠ 0 :=
by { rw div_eq_mul_inv, exact mul_ne_zero ha (inv_ne_zero hb) }
@[simp] lemma div_eq_zero_iff : a / b = 0 ↔ a = 0 ∨ b = 0:=
by simp [div_eq_mul_inv]
lemma div_ne_zero_iff : a / b ≠ 0 ↔ a ≠ 0 ∧ b ≠ 0 :=
(not_congr div_eq_zero_iff).trans not_or_distrib
lemma div_left_inj' (hc : c ≠ 0) : a / c = b / c ↔ a = b :=
by rw [← divp_mk0 _ hc, ← divp_mk0 _ hc, divp_left_inj]
lemma div_eq_iff_mul_eq (hb : b ≠ 0) : a / b = c ↔ c * b = a :=
⟨λ h, by rw [← h, div_mul_cancel _ hb],
λ h, by rw [← h, mul_div_cancel _ hb]⟩
lemma eq_div_iff_mul_eq (hc : c ≠ 0) : a = b / c ↔ a * c = b :=
by rw [eq_comm, div_eq_iff_mul_eq hc]
lemma div_eq_of_eq_mul {x : G₀} (hx : x ≠ 0) {y z : G₀} (h : y = z * x) : y / x = z :=
(div_eq_iff_mul_eq hx).2 h.symm
lemma eq_div_of_mul_eq {x : G₀} (hx : x ≠ 0) {y z : G₀} (h : z * x = y) : z = y / x :=
eq.symm $ div_eq_of_eq_mul hx h.symm
lemma eq_of_div_eq_one (h : a / b = 1) : a = b :=
begin
by_cases hb : b = 0,
{ rw [hb, div_zero] at h,
exact eq_of_zero_eq_one h a b },
{ rwa [div_eq_iff_mul_eq hb, one_mul, eq_comm] at h }
end
lemma div_eq_one_iff_eq (hb : b ≠ 0) : a / b = 1 ↔ a = b :=
⟨eq_of_div_eq_one, λ h, h.symm ▸ div_self hb⟩
lemma div_mul_left {a b : G₀} (hb : b ≠ 0) : b / (a * b) = 1 / a :=
by simp only [div_eq_mul_inv, mul_inv_rev₀, mul_inv_cancel_left₀ hb, one_mul]
lemma mul_div_mul_right (a b : G₀) {c : G₀} (hc : c ≠ 0) :
(a * c) / (b * c) = a / b :=
by simp only [div_eq_mul_inv, mul_inv_rev₀, mul_assoc, mul_inv_cancel_left₀ hc]
lemma mul_mul_div (a : G₀) {b : G₀} (hb : b ≠ 0) : a = a * b * (1 / b) :=
by simp [hb]
lemma ring.inverse_eq_inv (a : G₀) : ring.inverse a = a⁻¹ :=
begin
obtain rfl | ha := eq_or_ne a 0,
{ simp },
{ exact ring.inverse_unit (units.mk0 a ha) }
end
@[simp] lemma ring.inverse_eq_inv' : (ring.inverse : G₀ → G₀) = has_inv.inv :=
funext ring.inverse_eq_inv
@[field_simps] lemma div_div_eq_mul_div (a b c : G₀) :
a / (b / c) = (a * c) / b :=
by rw [div_eq_mul_one_div, one_div_div, ← mul_div_assoc]
/-- Dividing `a` by the result of dividing `a` by itself results in
`a` (whether or not `a` is zero). -/
@[simp] lemma div_div_self (a : G₀) : a / (a / a) = a :=
begin
rw div_div_eq_mul_div,
exact mul_self_div_self a
end
lemma ne_zero_of_one_div_ne_zero {a : G₀} (h : 1 / a ≠ 0) : a ≠ 0 :=
assume ha : a = 0, begin rw [ha, div_zero] at h, contradiction end
lemma eq_zero_of_one_div_eq_zero {a : G₀} (h : 1 / a = 0) : a = 0 :=
classical.by_cases
(assume ha, ha)
(assume ha, ((one_div_ne_zero ha) h).elim)
lemma div_div_div_cancel_right (a : G₀) (hc : c ≠ 0) : (a / c) / (b / c) = a / b :=
by rw [div_div_eq_mul_div, div_mul_cancel _ hc]
lemma div_mul_div_cancel (a : G₀) (hc : c ≠ 0) : (a / c) * (c / b) = a / b :=
by rw [← mul_div_assoc, div_mul_cancel _ hc]
@[field_simps] lemma eq_div_iff (hb : b ≠ 0) : c = a / b ↔ c * b = a :=
eq_div_iff_mul_eq hb
@[field_simps] lemma div_eq_iff (hb : b ≠ 0) : a / b = c ↔ a = c * b :=
(div_eq_iff_mul_eq hb).trans eq_comm
end group_with_zero
section comm_group_with_zero -- comm
variables [comm_group_with_zero G₀] {a b c : G₀}
@[priority 10] -- see Note [lower instance priority]
instance comm_group_with_zero.comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero G₀ :=
{ ..group_with_zero.cancel_monoid_with_zero, ..comm_group_with_zero.to_comm_monoid_with_zero G₀ }
/-- Pullback a `comm_group_with_zero` class along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.comm_group_with_zero [has_zero G₀'] [has_mul G₀'] [has_one G₀']
[has_inv G₀'] [has_div G₀'] (f : G₀' → G₀) (hf : injective f) (zero : f 0 = 0) (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_with_zero G₀' :=
{ .. hf.group_with_zero f zero one mul inv div, .. hf.comm_semigroup f mul }
/-- Pushforward a `comm_group_with_zero` class along a surjective function. -/
protected def function.surjective.comm_group_with_zero [has_zero G₀'] [has_mul G₀']
[has_one G₀'] [has_inv G₀'] [has_div G₀'] (h01 : (0:G₀') ≠ 1) (f : G₀ → G₀') (hf : surjective f)
(zero : f 0 = 0) (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_with_zero G₀' :=
{ .. hf.group_with_zero h01 f zero one mul inv div, .. hf.comm_semigroup f mul }
lemma mul_inv₀ : (a * b)⁻¹ = a⁻¹ * b⁻¹ :=
by rw [mul_inv_rev₀, mul_comm]
lemma one_div_mul_one_div (a b : G₀) : (1 / a) * (1 / b) = 1 / (a * b) :=
by rw [one_div_mul_one_div_rev, mul_comm b]
lemma div_mul_right {a : G₀} (b : G₀) (ha : a ≠ 0) : a / (a * b) = 1 / b :=
by rw [mul_comm, div_mul_left ha]
lemma mul_div_cancel_left_of_imp {a b : G₀} (h : a = 0 → b = 0) : a * b / a = b :=
by rw [mul_comm, mul_div_cancel_of_imp h]
lemma mul_div_cancel_left {a : G₀} (b : G₀) (ha : a ≠ 0) : a * b / a = b :=
mul_div_cancel_left_of_imp $ λ h, (ha h).elim
lemma mul_div_cancel_of_imp' {a b : G₀} (h : b = 0 → a = 0) : b * (a / b) = a :=
by rw [mul_comm, div_mul_cancel_of_imp h]
lemma mul_div_cancel' (a : G₀) {b : G₀} (hb : b ≠ 0) : b * (a / b) = a :=
by rw [mul_comm, (div_mul_cancel _ hb)]
local attribute [simp] mul_assoc mul_comm mul_left_comm
lemma div_mul_div (a b c d : G₀) :
(a / b) * (c / d) = (a * c) / (b * d) :=
by simp [div_eq_mul_inv, mul_inv₀]
lemma mul_div_mul_left (a b : G₀) {c : G₀} (hc : c ≠ 0) :
(c * a) / (c * b) = a / b :=
by rw [mul_comm c, mul_comm c, mul_div_mul_right _ _ hc]
@[field_simps] lemma div_mul_eq_mul_div (a b c : G₀) : (b / c) * a = (b * a) / c :=
by simp [div_eq_mul_inv]
lemma div_mul_eq_mul_div_comm (a b c : G₀) :
(b / c) * a = b * (a / c) :=
by rw [div_mul_eq_mul_div, ← one_mul c, ← div_mul_div, div_one, one_mul]
lemma mul_eq_mul_of_div_eq_div (a : G₀) {b : G₀} (c : G₀) {d : G₀} (hb : b ≠ 0)
(hd : d ≠ 0) (h : a / b = c / d) : a * d = c * b :=
by rw [← mul_one (a*d), mul_assoc, mul_comm d, ← mul_assoc, ← div_self hb,
← div_mul_eq_mul_div_comm, h, div_mul_eq_mul_div, div_mul_cancel _ hd]
@[field_simps] lemma div_div_eq_div_mul (a b c : G₀) :
(a / b) / c = a / (b * c) :=
by rw [div_eq_mul_one_div, div_mul_div, mul_one]
lemma div_div_div_div_eq (a : G₀) {b c d : G₀} :
(a / b) / (c / d) = (a * d) / (b * c) :=
by rw [div_div_eq_mul_div, div_mul_eq_mul_div, div_div_eq_div_mul]
lemma div_mul_eq_div_mul_one_div (a b c : G₀) :
a / (b * c) = (a / b) * (1 / c) :=
by rw [← div_div_eq_div_mul, ← div_eq_mul_one_div]
lemma div_helper {a : G₀} (b : G₀) (h : a ≠ 0) : (1 / (a * b)) * a = 1 / b :=
by rw [div_mul_eq_mul_div, one_mul, div_mul_right _ h]
end comm_group_with_zero
section comm_group_with_zero
variables [comm_group_with_zero G₀] {a b c d : G₀}
lemma div_eq_inv_mul : a / b = b⁻¹ * a :=
by rw [div_eq_mul_inv, mul_comm]
lemma mul_div_right_comm (a b c : G₀) : (a * b) / c = (a / c) * b :=
by rw [div_eq_mul_inv, mul_assoc, mul_comm b, ← mul_assoc, div_eq_mul_inv]
lemma mul_comm_div' (a b c : G₀) : (a / b) * c = a * (c / b) :=
by rw [← mul_div_assoc, mul_div_right_comm]
lemma div_mul_comm' (a b c : G₀) : (a / b) * c = (c / b) * a :=
by rw [div_mul_eq_mul_div, mul_comm, mul_div_right_comm]
lemma mul_div_comm (a b c : G₀) : a * (b / c) = b * (a / c) :=
by rw [← mul_div_assoc, mul_comm, mul_div_assoc]
lemma div_right_comm (a : G₀) : (a / b) / c = (a / c) / b :=
by rw [div_div_eq_div_mul, div_div_eq_div_mul, mul_comm]
@[field_simps] lemma div_eq_div_iff (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = c * b :=
calc a / b = c / d ↔ a / b * (b * d) = c / d * (b * d) :
by rw [mul_left_inj' (mul_ne_zero hb hd)]
... ↔ a * d = c * b :
by rw [← mul_assoc, div_mul_cancel _ hb,
← mul_assoc, mul_right_comm, div_mul_cancel _ hd]
lemma div_div_cancel' (ha : a ≠ 0) : a / (a / b) = b :=
by rw [div_eq_mul_inv, inv_div, mul_div_cancel' _ ha]
end comm_group_with_zero
namespace semiconj_by
@[simp] lemma zero_right [mul_zero_class G₀] (a : G₀) : semiconj_by a 0 0 :=
by simp only [semiconj_by, mul_zero, zero_mul]
@[simp] lemma zero_left [mul_zero_class G₀] (x y : G₀) : semiconj_by 0 x y :=
by simp only [semiconj_by, mul_zero, zero_mul]
variables [group_with_zero G₀] {a x y x' y' : G₀}
@[simp] lemma inv_symm_left_iff₀ : semiconj_by a⁻¹ x y ↔ semiconj_by a y x :=
classical.by_cases
(λ ha : a = 0, by simp only [ha, inv_zero, semiconj_by.zero_left])
(λ ha, @units_inv_symm_left_iff _ _ (units.mk0 a ha) _ _)
lemma inv_symm_left₀ (h : semiconj_by a x y) : semiconj_by a⁻¹ y x :=
semiconj_by.inv_symm_left_iff₀.2 h
lemma inv_right₀ (h : semiconj_by a x y) : semiconj_by a x⁻¹ y⁻¹ :=
begin
by_cases ha : a = 0,
{ simp only [ha, zero_left] },
by_cases hx : x = 0,
{ subst x,
simp only [semiconj_by, mul_zero, @eq_comm _ _ (y * a), mul_eq_zero] at h,
simp [h.resolve_right ha] },
{ have := mul_ne_zero ha hx,
rw [h.eq, mul_ne_zero_iff] at this,
exact @units_inv_right _ _ _ (units.mk0 x hx) (units.mk0 y this.1) h },
end
@[simp] lemma inv_right_iff₀ : semiconj_by a x⁻¹ y⁻¹ ↔ semiconj_by a x y :=
⟨λ h, inv_inv₀ x ▸ inv_inv₀ y ▸ h.inv_right₀, inv_right₀⟩
lemma div_right (h : semiconj_by a x y) (h' : semiconj_by a x' y') :
semiconj_by a (x / x') (y / y') :=
by { rw [div_eq_mul_inv, div_eq_mul_inv], exact h.mul_right h'.inv_right₀ }
end semiconj_by
namespace commute
@[simp] theorem zero_right [mul_zero_class G₀] (a : G₀) :commute a 0 := semiconj_by.zero_right a
@[simp] theorem zero_left [mul_zero_class G₀] (a : G₀) : commute 0 a := semiconj_by.zero_left a a
variables [group_with_zero G₀] {a b c : G₀}
@[simp] theorem inv_left_iff₀ : commute a⁻¹ b ↔ commute a b :=
semiconj_by.inv_symm_left_iff₀
theorem inv_left₀ (h : commute a b) : commute a⁻¹ b := inv_left_iff₀.2 h
@[simp] theorem inv_right_iff₀ : commute a b⁻¹ ↔ commute a b :=
semiconj_by.inv_right_iff₀
theorem inv_right₀ (h : commute a b) : commute a b⁻¹ := inv_right_iff₀.2 h
theorem inv_inv₀ (h : commute a b) : commute a⁻¹ b⁻¹ := h.inv_left₀.inv_right₀
@[simp] theorem div_right (hab : commute a b) (hac : commute a c) :
commute a (b / c) :=
hab.div_right hac
@[simp] theorem div_left (hac : commute a c) (hbc : commute b c) :
commute (a / b) c :=
by { rw div_eq_mul_inv, exact hac.mul_left hbc.inv_left₀ }
end commute
namespace monoid_with_zero_hom
variables [group_with_zero G₀] [group_with_zero G₀'] [monoid_with_zero M₀] [nontrivial M₀]
section monoid_with_zero
variables (f : monoid_with_zero_hom G₀ M₀) {a : G₀}
lemma map_ne_zero : f a ≠ 0 ↔ a ≠ 0 :=
⟨λ hfa ha, hfa $ ha.symm ▸ f.map_zero, λ ha, ((is_unit.mk0 a ha).map f.to_monoid_hom).ne_zero⟩
@[simp] lemma map_eq_zero : f a = 0 ↔ a = 0 :=
not_iff_not.1 f.map_ne_zero
end monoid_with_zero
section group_with_zero
variables (f : monoid_with_zero_hom G₀ G₀') (a b : G₀)
/-- A monoid homomorphism between groups with zeros sending `0` to `0` sends `a⁻¹` to `(f a)⁻¹`. -/
@[simp] lemma map_inv : f a⁻¹ = (f a)⁻¹ :=
begin
by_cases h : a = 0, by simp [h],
apply eq_inv_of_mul_left_eq_one,
rw [← f.map_mul, inv_mul_cancel h, f.map_one]
end
@[simp] lemma map_div : f (a / b) = f a / f b :=
by simpa only [div_eq_mul_inv] using ((f.map_mul _ _).trans $ _root_.congr_arg _ $ f.map_inv b)
end group_with_zero
end monoid_with_zero_hom
@[simp] lemma monoid_hom.map_units_inv {M G₀ : Type*} [monoid M] [group_with_zero G₀]
(f : M →* G₀) (u : units M) : f ↑u⁻¹ = (f u)⁻¹ :=
by rw [← units.coe_map, ← units.coe_map, ← units.coe_inv', monoid_hom.map_inv]
@[simp] lemma monoid_with_zero_hom.map_units_inv {M G₀ : Type*} [monoid_with_zero M]
[group_with_zero G₀] (f : monoid_with_zero_hom M G₀) (u : units M) : f ↑u⁻¹ = (f u)⁻¹ :=
f.to_monoid_hom.map_units_inv u
section noncomputable_defs
variables {M : Type*} [nontrivial M]
/-- Constructs a `group_with_zero` structure on a `monoid_with_zero`
consisting only of units and 0. -/
noncomputable def group_with_zero_of_is_unit_or_eq_zero [hM : monoid_with_zero M]
(h : ∀ (a : M), is_unit a ∨ a = 0) : group_with_zero M :=
{ inv := λ a, if h0 : a = 0 then 0 else ↑((h a).resolve_right h0).unit⁻¹,
inv_zero := dif_pos rfl,
mul_inv_cancel := λ a h0, by {
change a * (if h0 : a = 0 then 0 else ↑((h a).resolve_right h0).unit⁻¹) = 1,
rw [dif_neg h0, units.mul_inv_eq_iff_eq_mul, one_mul, is_unit.unit_spec] },
exists_pair_ne := nontrivial.exists_pair_ne,
.. hM }
/-- Constructs a `comm_group_with_zero` structure on a `comm_monoid_with_zero`
consisting only of units and 0. -/
noncomputable def comm_group_with_zero_of_is_unit_or_eq_zero [hM : comm_monoid_with_zero M]
(h : ∀ (a : M), is_unit a ∨ a = 0) : comm_group_with_zero M :=
{ .. (group_with_zero_of_is_unit_or_eq_zero h), .. hM }
end noncomputable_defs
|
4038c3ca963665c23273b577b6fcc254b1307c41 | 556aeb81a103e9e0ac4e1fe0ce1bc6e6161c3c5e | /src/starkware/cairo/common/cairo_secp/verification/verification/signature_recover_public_key_nondet_bigint3_soundness.lean | 5bcaefe0717d40b0b545f26b28c4e8e490d51ef3 | [] | permissive | starkware-libs/formal-proofs | d6b731604461bf99e6ba820e68acca62a21709e8 | f5fa4ba6a471357fd171175183203d0b437f6527 | refs/heads/master | 1,691,085,444,753 | 1,690,507,386,000 | 1,690,507,386,000 | 410,476,629 | 32 | 9 | Apache-2.0 | 1,690,506,773,000 | 1,632,639,790,000 | Lean | UTF-8 | Lean | false | false | 6,644 | lean | /-
File: signature_recover_public_key_nondet_bigint3_soundness.lean
Autogenerated file.
-/
import starkware.cairo.lean.semantics.soundness.hoare
import .signature_recover_public_key_code
import ..signature_recover_public_key_spec
open tactic
open starkware.cairo.common.cairo_secp.bigint
open starkware.cairo.common.cairo_secp.constants
variables {F : Type} [field F] [decidable_eq F] [prelude_hyps F]
variable mem : F → F
variable σ : register_state F
/- starkware.cairo.common.cairo_secp.bigint.nondet_bigint3 autogenerated soundness theorem -/
theorem auto_sound_nondet_bigint3
-- arguments
(range_check_ptr : F)
-- code is in memory at σ.pc
(h_mem : mem_at mem code_nondet_bigint3 σ.pc)
-- input arguments on the stack
(hin_range_check_ptr : range_check_ptr = mem (σ.fp - 3))
-- conclusion
: ensures_ret mem σ (λ κ τ,
τ.ap = σ.ap + 8 ∧
∃ μ ≤ κ, rc_ensures mem (rc_bound F) μ (mem (σ.fp - 3)) (mem $ τ.ap - 4)
(spec_nondet_bigint3 mem κ range_check_ptr (mem (τ.ap - 4)) (cast_BigInt3 mem (τ.ap - 3)))) :=
begin
apply ensures_of_ensuresb, intro νbound,
have h_mem_rec := h_mem,
unpack_memory code_nondet_bigint3 at h_mem with ⟨hpc0, hpc1, hpc2, hpc3, hpc4, hpc5, hpc6, hpc7, hpc8, hpc9, hpc10, hpc11⟩,
-- let (ap reference)
apply of_register_state,
intros regstate_res regstateeq_res,
generalize' hl_rev_res: cast_BigInt3 mem (regstate_res.ap + 5) = res,
have hl_res := hl_rev_res.symm,
rw [regstateeq_res] at hl_res, try { dsimp at hl_res },
-- const
set! MAX_SUM := (232113757366008801543585789 : F) with hc_MAX_SUM,
-- compound assert eq
step_assert_eq hpc0 hpc1 with temp0,
step_assert_eq hpc2 with temp1,
step_assert_eq hpc3 with temp2,
step_assert_eq hpc4 with temp3,
step_assert_eq hpc5 with temp4,
have a0: mem (range_check_ptr) = MAX_SUM - (res.d0 + res.d1 + res.d2), {
apply assert_eq_reduction temp4.symm,
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hl_res, hc_MAX_SUM] },
try { dsimp [cast_BigInt3] },
try { arith_simps }, try { simp only [temp0, temp1, temp2, (eq_sub_of_eq_add temp3)] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },
},
try { dsimp at a0 }, try { arith_simps at a0 },
clear temp0 temp1 temp2 temp3 temp4,
-- tempvar
step_assert_eq hpc6 hpc7 with tv_range_check_ptr0,
generalize' hl_rev_range_check_ptr₁: (range_check_ptr + 4 : F) = range_check_ptr₁,
have hl_range_check_ptr₁ := hl_rev_range_check_ptr₁.symm, clear hl_rev_range_check_ptr₁,
have htv_range_check_ptr₁: range_check_ptr₁ = _, {
apply eq.symm, apply eq.trans tv_range_check_ptr0,
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hl_res, hc_MAX_SUM, hl_range_check_ptr₁] },
try { dsimp [cast_BigInt3] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },
clear tv_range_check_ptr0,
try { dsimp at hl_range_check_ptr₁ }, try { arith_simps at hl_range_check_ptr₁ },
-- assert eq
step_assert_eq hpc8 with temp0,
have a8: mem (range_check_ptr₁ - 3) = res.d0, {
apply assert_eq_reduction temp0.symm,
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hl_res, hc_MAX_SUM, hl_range_check_ptr₁, htv_range_check_ptr₁] },
try { dsimp [cast_BigInt3] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },
},
try { dsimp at a8 }, try { arith_simps at a8 },
clear temp0,
-- assert eq
step_assert_eq hpc9 with temp0,
have a9: mem (range_check_ptr₁ - 2) = res.d1, {
apply assert_eq_reduction temp0.symm,
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hl_res, hc_MAX_SUM, hl_range_check_ptr₁, htv_range_check_ptr₁] },
try { dsimp [cast_BigInt3] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },
},
try { dsimp at a9 }, try { arith_simps at a9 },
clear temp0,
-- assert eq
step_assert_eq hpc10 with temp0,
have a10: mem (range_check_ptr₁ - 1) = res.d2, {
apply assert_eq_reduction temp0.symm,
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hl_res, hc_MAX_SUM, hl_range_check_ptr₁, htv_range_check_ptr₁] },
try { dsimp [cast_BigInt3] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },
},
try { dsimp at a10 }, try { arith_simps at a10 },
clear temp0,
-- return
step_ret hpc11,
-- finish
step_done, use_only [rfl, rfl],
split, refl,
-- range check condition
use_only (4+0+0), split,
linarith [],
split,
{ arith_simps,
rw [←htv_range_check_ptr₁, hl_range_check_ptr₁, hin_range_check_ptr],
try { arith_simps, refl <|> norm_cast }, try { refl } },
intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },
have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,
-- Final Proof
-- user-provided reduction
suffices auto_spec: auto_spec_nondet_bigint3 mem _ range_check_ptr _ _,
{ apply sound_nondet_bigint3, apply auto_spec },
-- prove the auto generated assertion
dsimp [auto_spec_nondet_bigint3],
try { norm_num1 }, try { arith_simps },
use_only [res],
use [MAX_SUM, hc_MAX_SUM],
use_only [a0],
cases rc_h_range_check_ptr' (0) (by norm_num1) with n hn, arith_simps at hn,
use_only [n], { simp only [a0.symm, hin_range_check_ptr], arith_simps, exact hn },
have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr,
have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁,try { norm_cast at rc_h_range_check_ptr₁' },
use_only [range_check_ptr₁, hl_range_check_ptr₁],
use_only [a8],
cases rc_h_range_check_ptr' (1) (by norm_num1) with n hn, arith_simps at hn,
use_only [n], { simp only [a8.symm, hl_range_check_ptr₁, hin_range_check_ptr], arith_simps, exact hn },
use_only [a9],
cases rc_h_range_check_ptr' (2) (by norm_num1) with n hn, arith_simps at hn,
use_only [n], { simp only [a9.symm, hl_range_check_ptr₁, hin_range_check_ptr], arith_simps, exact hn },
use_only [a10],
cases rc_h_range_check_ptr' (3) (by norm_num1) with n hn, arith_simps at hn,
use_only [n], { simp only [a10.symm, hl_range_check_ptr₁, hin_range_check_ptr], arith_simps, exact hn },
try { split, linarith },
try { ensures_simps; try { simp only [add_neg_eq_sub, hin_range_check_ptr, hl_res, hc_MAX_SUM, hl_range_check_ptr₁, htv_range_check_ptr₁] }, },
try { dsimp [cast_BigInt3] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },
end
|
566cb1dea6027aa54a696d602cd163cea92b07a0 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/fin/fin2.lean | d005f33e90a0d39dba6d72aadd1fc1fd00df94c2 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 4,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
-/
/-!
# Inductive type variant of `fin`
`fin` is defined as a subtype of `ℕ`. This file defines an equivalent type, `fin2`, which is
defined inductively. This is useful for its induction principle and different definitional
equalities.
## Main declarations
* `fin2 n`: Inductive type variant of `fin n`. `fz` corresponds to `0` and `fs n` corresponds to
`n`.
* `to_nat`, `opt_of_nat`, `of_nat'`: Conversions to and from `ℕ`. `of_nat' m` takes a proof that
`m < n` through the class `is_lt`.
* `add k`: Takes `i : fin2 n` to `i + k : fin2 (n + k)`.
* `left`: Embeds `fin2 n` into `fin2 (n + k)`.
* `insert_perm a`: Permutation of `fin2 n` which cycles `0, ..., a - 1` and leaves `a, ..., n - 1`
unchanged.
* `remap_left f`: Function `fin2 (m + k) → fin2 (n + k)` by applying `f : fin m → fin n` to
`0, ..., m - 1` and sending `m + i` to `n + i`.
-/
open nat
universes u
/-- An alternate definition of `fin n` defined as an inductive type instead of a subtype of `ℕ`. -/
inductive fin2 : ℕ → Type
/-- `0` as a member of `fin (succ n)` (`fin 0` is empty) -/
| fz {n} : fin2 (succ n)
/-- `n` as a member of `fin (succ n)` -/
| fs {n} : fin2 n → fin2 (succ n)
namespace fin2
/-- Define a dependent function on `fin2 (succ n)` by giving its value at
zero (`H1`) and by giving a dependent function on the rest (`H2`). -/
@[elab_as_eliminator]
protected def cases' {n} {C : fin2 (succ n) → Sort u} (H1 : C fz) (H2 : Π n, C (fs n)) :
Π (i : fin2 (succ n)), C i
| fz := H1
| (fs n) := H2 n
/-- Ex falso. The dependent eliminator for the empty `fin2 0` type. -/
def elim0 {C : fin2 0 → Sort u} : Π (i : fin2 0), C i.
/-- Converts a `fin2` into a natural. -/
def to_nat : Π {n}, fin2 n → ℕ
| ._ (@fz n) := 0
| ._ (@fs n i) := succ (to_nat i)
/-- Converts a natural into a `fin2` if it is in range -/
def opt_of_nat : Π {n} (k : ℕ), option (fin2 n)
| 0 _ := none
| (succ n) 0 := some fz
| (succ n) (succ k) := fs <$> @opt_of_nat n k
/-- `i + k : fin2 (n + k)` when `i : fin2 n` and `k : ℕ` -/
def add {n} (i : fin2 n) : Π k, fin2 (n + k)
| 0 := i
| (succ k) := fs (add k)
/-- `left k` is the embedding `fin2 n → fin2 (k + n)` -/
def left (k) : Π {n}, fin2 n → fin2 (k + n)
| ._ (@fz n) := fz
| ._ (@fs n i) := fs (left i)
/-- `insert_perm a` is a permutation of `fin2 n` with the following properties:
* `insert_perm a i = i+1` if `i < a`
* `insert_perm a a = 0`
* `insert_perm a i = i` if `i > a` -/
def insert_perm : Π {n}, fin2 n → fin2 n → fin2 n
| ._ (@fz n) (@fz ._) := fz
| ._ (@fz n) (@fs ._ j) := fs j
| ._ (@fs (succ n) i) (@fz ._) := fs fz
| ._ (@fs (succ n) i) (@fs ._ j) := match insert_perm i j with fz := fz | fs k := fs (fs k) end
/-- `remap_left f k : fin2 (m + k) → fin2 (n + k)` applies the function
`f : fin2 m → fin2 n` to inputs less than `m`, and leaves the right part
on the right (that is, `remap_left f k (m + i) = n + i`). -/
def remap_left {m n} (f : fin2 m → fin2 n) : Π k, fin2 (m + k) → fin2 (n + k)
| 0 i := f i
| (succ k) (@fz ._) := fz
| (succ k) (@fs ._ i) := fs (remap_left _ i)
/-- This is a simple type class inference prover for proof obligations
of the form `m < n` where `m n : ℕ`. -/
class is_lt (m n : ℕ) := (h : m < n)
instance is_lt.zero (n) : is_lt 0 (succ n) := ⟨succ_pos _⟩
instance is_lt.succ (m n) [l : is_lt m n] : is_lt (succ m) (succ n) := ⟨succ_lt_succ l.h⟩
/-- Use type class inference to infer the boundedness proof, so that we can directly convert a
`nat` into a `fin2 n`. This supports notation like `&1 : fin 3`. -/
def of_nat' : Π {n} m [is_lt m n], fin2 n
| 0 m ⟨h⟩ := absurd h (nat.not_lt_zero _)
| (succ n) 0 ⟨h⟩ := fz
| (succ n) (succ m) ⟨h⟩ := fs (@of_nat' n m ⟨lt_of_succ_lt_succ h⟩)
local prefix `&`:max := of_nat'
instance : inhabited (fin2 1) := ⟨fz⟩
end fin2
|
119540f82af51eeab1eebb739a79f33cb690d4af | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/tactic24.lean | 65049d7b39222643c63a40d780c4c20afeeff76b | [
"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 | 653 | lean | import logic
open tactic
notation `(` h `|` r:(foldl `|` (e r, tactic.or_else r e) h) `)` := r
infixl `;`:15 := tactic.and_then
definition my_tac1 := apply @eq.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 my_tac3
theorem T3 {a b c : Prop} (Hb : b) : a ∨ b ∨ c
:= _
|
f8f73bfd394fbbf383526a26442c3ec2c814383b | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/linear_algebra/matrix/to_linear_equiv.lean | d11f840052bdb835a03aa1f8329778bf45486ef1 | [
"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 | 7,274 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Patrick Massot, Casper Putz, Anne Baanen
-/
import linear_algebra.finite_dimensional
import linear_algebra.matrix.general_linear_group
import linear_algebra.matrix.nondegenerate
import linear_algebra.matrix.nonsingular_inverse
import linear_algebra.matrix.to_lin
import ring_theory.localization.fraction_ring
import ring_theory.localization.integer
/-!
# Matrices and linear equivalences
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file gives the map `matrix.to_linear_equiv` from matrices with invertible determinant,
to linear equivs.
## Main definitions
* `matrix.to_linear_equiv`: a matrix with an invertible determinant forms a linear equiv
## Main results
* `matrix.exists_mul_vec_eq_zero_iff`: `M` maps some `v ≠ 0` to zero iff `det M = 0`
## Tags
matrix, linear_equiv, determinant, inverse
-/
namespace matrix
open linear_map
variables {R M : Type*} [comm_ring R] [add_comm_group M] [module R M]
variables {n : Type*} [fintype n]
section to_linear_equiv'
variables [decidable_eq n]
/-- An invertible matrix yields a linear equivalence from the free module to itself.
See `matrix.to_linear_equiv` for the same map on arbitrary modules.
-/
def to_linear_equiv' (P : matrix n n R) (h : invertible P) : (n → R) ≃ₗ[R] (n → R) :=
general_linear_group.general_linear_equiv _ _ $
matrix.general_linear_group.to_linear $ unit_of_invertible P
@[simp] lemma to_linear_equiv'_apply (P : matrix n n R) (h : invertible P) :
(↑(P.to_linear_equiv' h) : module.End R (n → R)) = P.to_lin' := rfl
@[simp] lemma to_linear_equiv'_symm_apply (P : matrix n n R) (h : invertible P) :
(↑(P.to_linear_equiv' h).symm : module.End R (n → R)) = (⅟P).to_lin' :=
rfl
end to_linear_equiv'
section to_linear_equiv
variables (b : basis n R M)
include b
/-- Given `hA : is_unit A.det` and `b : basis R b`, `A.to_linear_equiv b hA` is
the `linear_equiv` arising from `to_lin b b A`.
See `matrix.to_linear_equiv'` for this result on `n → R`.
-/
@[simps apply]
noncomputable def to_linear_equiv [decidable_eq n] (A : matrix n n R) (hA : is_unit A.det) :
M ≃ₗ[R] M :=
begin
refine
{ to_fun := to_lin b b A,
inv_fun := to_lin b b A⁻¹,
left_inv := λ x, _,
right_inv := λ x, _,
.. to_lin b b A };
rw ← linear_map.comp_apply;
simp only [← matrix.to_lin_mul b b b,
matrix.nonsing_inv_mul _ hA, matrix.mul_nonsing_inv _ hA,
to_lin_one, linear_map.id_apply]
end
lemma ker_to_lin_eq_bot [decidable_eq n] (A : matrix n n R) (hA : is_unit A.det) :
(to_lin b b A).ker = ⊥ :=
ker_eq_bot.mpr (to_linear_equiv b A hA).injective
lemma range_to_lin_eq_top [decidable_eq n] (A : matrix n n R) (hA : is_unit A.det) :
(to_lin b b A).range = ⊤ :=
range_eq_top.mpr (to_linear_equiv b A hA).surjective
end to_linear_equiv
section nondegenerate
open_locale matrix
/-- This holds for all integral domains (see `matrix.exists_mul_vec_eq_zero_iff`),
not just fields, but it's easier to prove it for the field of fractions first. -/
lemma exists_mul_vec_eq_zero_iff_aux {K : Type*} [decidable_eq n] [field K] {M : matrix n n K} :
(∃ (v ≠ 0), M.mul_vec v = 0) ↔ M.det = 0 :=
begin
split,
{ rintros ⟨v, hv, mul_eq⟩,
contrapose! hv,
exact eq_zero_of_mul_vec_eq_zero hv mul_eq },
{ contrapose!,
intros h,
have : function.injective M.to_lin',
{ simpa only [← linear_map.ker_eq_bot, ker_to_lin'_eq_bot_iff, not_imp_not] using h },
have : M ⬝ linear_map.to_matrix'
((linear_equiv.of_injective_endo M.to_lin' this).symm : (n → K) →ₗ[K] (n → K)) = 1,
{ refine matrix.to_lin'.injective (linear_map.ext $ λ v, _),
rw [matrix.to_lin'_mul, matrix.to_lin'_one, matrix.to_lin'_to_matrix', linear_map.comp_apply],
exact (linear_equiv.of_injective_endo M.to_lin' this).apply_symm_apply v },
exact matrix.det_ne_zero_of_right_inverse this }
end
lemma exists_mul_vec_eq_zero_iff' {A : Type*} (K : Type*) [decidable_eq n]
[comm_ring A] [nontrivial A]
[field K] [algebra A K] [is_fraction_ring A K]
{M : matrix n n A} :
(∃ (v ≠ 0), M.mul_vec v = 0) ↔ M.det = 0 :=
begin
have : (∃ (v ≠ 0), mul_vec ((algebra_map A K).map_matrix M) v = 0) ↔ _ :=
exists_mul_vec_eq_zero_iff_aux,
rw [← ring_hom.map_det, is_fraction_ring.to_map_eq_zero_iff] at this,
refine iff.trans _ this, split; rintro ⟨v, hv, mul_eq⟩,
{ refine ⟨λ i, algebra_map _ _ (v i), mt (λ h, funext $ λ i, _) hv, _⟩,
{ exact is_fraction_ring.to_map_eq_zero_iff.mp (congr_fun h i) },
{ ext i,
refine (ring_hom.map_mul_vec _ _ _ i).symm.trans _,
rw [mul_eq, pi.zero_apply, ring_hom.map_zero, pi.zero_apply] } },
{ letI := classical.dec_eq K,
obtain ⟨⟨b, hb⟩, ba_eq⟩ := is_localization.exist_integer_multiples_of_finset
(non_zero_divisors A) (finset.univ.image v),
choose f hf using ba_eq,
refine ⟨λ i, f _ (finset.mem_image.mpr ⟨i, finset.mem_univ i, rfl⟩),
mt (λ h, funext $ λ i, _) hv, _⟩,
{ have := congr_arg (algebra_map A K) (congr_fun h i),
rw [hf, subtype.coe_mk, pi.zero_apply, ring_hom.map_zero, algebra.smul_def,
mul_eq_zero, is_fraction_ring.to_map_eq_zero_iff] at this,
exact this.resolve_left (non_zero_divisors.ne_zero hb), },
{ ext i,
refine is_fraction_ring.injective A K _,
calc algebra_map A K (M.mul_vec (λ (i : n), f (v i) _) i)
= ((algebra_map A K).map_matrix M).mul_vec
(algebra_map _ K b • v) i : _
... = 0 : _
... = algebra_map A K 0 : (ring_hom.map_zero _).symm,
{ simp_rw [ring_hom.map_mul_vec, mul_vec, dot_product, function.comp_app, hf,
subtype.coe_mk, ring_hom.map_matrix_apply, pi.smul_apply, smul_eq_mul,
algebra.smul_def] },
{ rw [mul_vec_smul, mul_eq, pi.smul_apply, pi.zero_apply, smul_zero] } } },
end
lemma exists_mul_vec_eq_zero_iff {A : Type*} [decidable_eq n] [comm_ring A] [is_domain A]
{M : matrix n n A} :
(∃ (v ≠ 0), M.mul_vec v = 0) ↔ M.det = 0 :=
exists_mul_vec_eq_zero_iff' (fraction_ring A)
lemma exists_vec_mul_eq_zero_iff {A : Type*} [decidable_eq n] [comm_ring A] [is_domain A]
{M : matrix n n A} :
(∃ (v ≠ 0), M.vec_mul v = 0) ↔ M.det = 0 :=
by simpa only [← M.det_transpose, ← mul_vec_transpose] using exists_mul_vec_eq_zero_iff
theorem nondegenerate_iff_det_ne_zero {A : Type*} [decidable_eq n] [comm_ring A] [is_domain A]
{M : matrix n n A} :
nondegenerate M ↔ M.det ≠ 0 :=
begin
refine iff.trans _ (not_iff_not.mpr exists_vec_mul_eq_zero_iff),
simp only [not_exists],
split,
{ intros hM v hv hMv,
obtain ⟨w, hwMv⟩ := hM.exists_not_ortho_of_ne_zero hv,
simpa only [dot_product_mul_vec, hMv, zero_dot_product] using hwMv },
{ intros h v hv,
refine not_imp_not.mp (h v) (funext $ λ i, _),
simpa only [dot_product_mul_vec, dot_product_single, mul_one] using hv (pi.single i 1) }
end
alias nondegenerate_iff_det_ne_zero ↔ nondegenerate.det_ne_zero nondegenerate.of_det_ne_zero
end nondegenerate
end matrix
|
3a3f1f330eade6ef3e30b5aacba910db0f13a9b3 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebra/module/prod.lean | 9620c9d1cfe25bfa486597837fe7df22a9d99a8a | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,456 | 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 Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.module.basic
import Mathlib.PostPort
universes u_1 u_2 u_3
namespace Mathlib
/-!
# Prod instances for module and multiplicative actions
This file defines instances for binary product of modules
-/
namespace prod
protected instance has_scalar {α : Type u_1} {β : Type u_2} {γ : Type u_3} [has_scalar α β] [has_scalar α γ] : has_scalar α (β × γ) :=
has_scalar.mk fun (a : α) (p : β × γ) => (a • fst p, a • snd p)
@[simp] theorem smul_fst {α : Type u_1} {β : Type u_2} {γ : Type u_3} [has_scalar α β] [has_scalar α γ] (a : α) (x : β × γ) : fst (a • x) = a • fst x :=
rfl
@[simp] theorem smul_snd {α : Type u_1} {β : Type u_2} {γ : Type u_3} [has_scalar α β] [has_scalar α γ] (a : α) (x : β × γ) : snd (a • x) = a • snd x :=
rfl
@[simp] theorem smul_mk {α : Type u_1} {β : Type u_2} {γ : Type u_3} [has_scalar α β] [has_scalar α γ] (a : α) (b : β) (c : γ) : a • (b, c) = (a • b, a • c) :=
rfl
protected instance semimodule {α : Type u_1} {β : Type u_2} {γ : Type u_3} {r : semiring α} [add_comm_monoid β] [add_comm_monoid γ] [semimodule α β] [semimodule α γ] : semimodule α (β × γ) :=
semimodule.mk sorry sorry
|
2a8cc72459fed75473d0ad859cf2455c3a1fedbd | 680b0d1592ce164979dab866b232f6fa743f2cc8 | /library/theories/analysis/metric_space.lean | c5e89957b88b63d6f5c464a41c85e9c4028c83aa | [
"Apache-2.0"
] | permissive | syohex/lean | 657428ab520f8277fc18cf04bea2ad200dbae782 | 081ad1212b686780f3ff8a6d0e5f8a1d29a7d8bc | refs/heads/master | 1,611,274,838,635 | 1,452,668,188,000 | 1,452,668,188,000 | 49,562,028 | 0 | 0 | null | 1,452,675,604,000 | 1,452,675,602,000 | null | UTF-8 | Lean | false | false | 10,012 | lean | /-
Copyright (c) 2015 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad
Metric spaces.
-/
import data.real.division
open real eq.ops classical
structure metric_space [class] (M : Type) : Type :=
(dist : M → M → ℝ)
(dist_self : ∀ x : M, dist x x = 0)
(eq_of_dist_eq_zero : ∀ {x y : M}, dist x y = 0 → x = y)
(dist_comm : ∀ x y : M, dist x y = dist y x)
(dist_triangle : ∀ x y z : M, dist x y + dist y z ≥ dist x z)
namespace metric_space
section metric_space_M
variables {M : Type} [strucM : metric_space M]
include strucM
proposition dist_eq_zero_iff (x y : M) : dist x y = 0 ↔ x = y :=
iff.intro eq_of_dist_eq_zero (suppose x = y, this ▸ !dist_self)
proposition dist_nonneg (x y : M) : 0 ≤ dist x y :=
have dist x y + dist y x ≥ 0, by rewrite -(dist_self x); apply dist_triangle,
have 2 * dist x y ≥ 0, using this,
by krewrite [-real.one_add_one, right_distrib, +one_mul, dist_comm at {2}]; apply this,
nonneg_of_mul_nonneg_left this two_pos
proposition dist_pos_of_ne {x y : M} (H : x ≠ y) : dist x y > 0 :=
lt_of_le_of_ne !dist_nonneg (suppose 0 = dist x y, H (iff.mp !dist_eq_zero_iff this⁻¹))
proposition eq_of_forall_dist_le {x y : M} (H : ∀ ε, ε > 0 → dist x y ≤ ε) : x = y :=
eq_of_dist_eq_zero (eq_zero_of_nonneg_of_forall_le !dist_nonneg H)
open nat
/- convergence of a sequence -/
definition converges_to_seq (X : ℕ → M) (y : M) : Prop :=
∀ ⦃ε : ℝ⦄, ε > 0 → ∃ N : ℕ, ∀ ⦃n⦄, n ≥ N → dist (X n) y < ε
-- the same, with ≤ in place of <; easier to prove, harder to use
definition converges_to_seq.intro {X : ℕ → M} {y : M}
(H : ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → dist (X n) y ≤ ε) :
converges_to_seq X y :=
take ε, assume epos : ε > 0,
have e2pos : ε / 2 > 0, from div_pos_of_pos_of_pos `ε > 0` two_pos,
obtain N HN, from H e2pos,
exists.intro N
(take n, suppose n ≥ N,
calc
dist (X n) y ≤ ε / 2 : HN _ `n ≥ N`
... < ε : div_two_lt_of_pos epos)
notation X `⟶` y `in` `ℕ` := converges_to_seq X y
definition converges_seq [class] (X : ℕ → M) : Prop := ∃ y, X ⟶ y in ℕ
noncomputable definition limit_seq (X : ℕ → M) [H : converges_seq X] : M := some H
proposition converges_to_limit_seq (X : ℕ → M) [H : converges_seq X] :
(X ⟶ limit_seq X in ℕ) :=
some_spec H
proposition converges_to_seq_unique {X : ℕ → M} {y₁ y₂ : M}
(H₁ : X ⟶ y₁ in ℕ) (H₂ : X ⟶ y₂ in ℕ) : y₁ = y₂ :=
eq_of_forall_dist_le
(take ε, suppose ε > 0,
have e2pos : ε / 2 > 0, from div_pos_of_pos_of_pos `ε > 0` two_pos,
obtain N₁ (HN₁ : ∀ {n}, n ≥ N₁ → dist (X n) y₁ < ε / 2), from H₁ e2pos,
obtain N₂ (HN₂ : ∀ {n}, n ≥ N₂ → dist (X n) y₂ < ε / 2), from H₂ e2pos,
let N := max N₁ N₂ in
have dN₁ : dist (X N) y₁ < ε / 2, from HN₁ !le_max_left,
have dN₂ : dist (X N) y₂ < ε / 2, from HN₂ !le_max_right,
have dist y₁ y₂ < ε, from calc
dist y₁ y₂ ≤ dist y₁ (X N) + dist (X N) y₂ : dist_triangle
... = dist (X N) y₁ + dist (X N) y₂ : dist_comm
... < ε / 2 + ε / 2 : add_lt_add dN₁ dN₂
... = ε : add_halves,
show dist y₁ y₂ ≤ ε, from le_of_lt this)
proposition eq_limit_of_converges_to_seq {X : ℕ → M} {y : M} (H : X ⟶ y in ℕ) :
y = @limit_seq M _ X (exists.intro y H) :=
converges_to_seq_unique H (@converges_to_limit_seq M _ X (exists.intro y H))
proposition converges_to_seq_constant (y : M) : (λn, y) ⟶ y in ℕ :=
take ε, assume egt0 : ε > 0,
exists.intro 0
(take n, suppose n ≥ 0,
calc
dist y y = 0 : !dist_self
... < ε : egt0)
proposition converges_to_seq_offset {X : ℕ → M} {y : M} (k : ℕ) (H : X ⟶ y in ℕ) :
(λ n, X (n + k)) ⟶ y in ℕ :=
take ε, suppose ε > 0,
obtain N HN, from H `ε > 0`,
exists.intro N
(take n : ℕ, assume ngtN : n ≥ N,
show dist (X (n + k)) y < ε, from HN (n + k) (le.trans ngtN !le_add_right))
proposition converges_to_seq_offset_left {X : ℕ → M} {y : M} (k : ℕ) (H : X ⟶ y in ℕ) :
(λ n, X (k + n)) ⟶ y in ℕ :=
have aux : (λ n, X (k + n)) = (λ n, X (n + k)), from funext (take n, by rewrite add.comm),
by+ rewrite aux; exact converges_to_seq_offset k H
proposition converges_to_seq_offset_succ {X : ℕ → M} {y : M} (H : X ⟶ y in ℕ) :
(λ n, X (succ n)) ⟶ y in ℕ :=
converges_to_seq_offset 1 H
proposition converges_to_seq_of_converges_to_seq_offset
{X : ℕ → M} {y : M} {k : ℕ} (H : (λ n, X (n + k)) ⟶ y in ℕ) :
X ⟶ y in ℕ :=
take ε, suppose ε > 0,
obtain N HN, from H `ε > 0`,
exists.intro (N + k)
(take n : ℕ, assume nge : n ≥ N + k,
have n - k ≥ N, from nat.le_sub_of_add_le nge,
have dist (X (n - k + k)) y < ε, from HN (n - k) this,
show dist (X n) y < ε, using this,
by rewrite [(nat.sub_add_cancel (le.trans !le_add_left nge)) at this]; exact this)
proposition converges_to_seq_of_converges_to_seq_offset_left
{X : ℕ → M} {y : M} {k : ℕ} (H : (λ n, X (k + n)) ⟶ y in ℕ) :
X ⟶ y in ℕ :=
have aux : (λ n, X (k + n)) = (λ n, X (n + k)), from funext (take n, by rewrite add.comm),
by+ rewrite aux at H; exact converges_to_seq_of_converges_to_seq_offset H
proposition converges_to_seq_of_converges_to_seq_offset_succ
{X : ℕ → M} {y : M} (H : (λ n, X (succ n)) ⟶ y in ℕ) :
X ⟶ y in ℕ :=
@converges_to_seq_of_converges_to_seq_offset M strucM X y 1 H
proposition converges_to_seq_offset_iff (X : ℕ → M) (y : M) (k : ℕ) :
((λ n, X (n + k)) ⟶ y in ℕ) ↔ (X ⟶ y in ℕ) :=
iff.intro converges_to_seq_of_converges_to_seq_offset !converges_to_seq_offset
proposition converges_to_seq_offset_left_iff (X : ℕ → M) (y : M) (k : ℕ) :
((λ n, X (k + n)) ⟶ y in ℕ) ↔ (X ⟶ y in ℕ) :=
iff.intro converges_to_seq_of_converges_to_seq_offset_left !converges_to_seq_offset_left
proposition converges_to_seq_offset_succ_iff (X : ℕ → M) (y : M) :
((λ n, X (succ n)) ⟶ y in ℕ) ↔ (X ⟶ y in ℕ) :=
iff.intro converges_to_seq_of_converges_to_seq_offset_succ !converges_to_seq_offset_succ
/- cauchy sequences -/
definition cauchy (X : ℕ → M) : Prop :=
∀ ε : ℝ, ε > 0 → ∃ N, ∀ m n, m ≥ N → n ≥ N → dist (X m) (X n) < ε
proposition cauchy_of_converges_seq (X : ℕ → M) [H : converges_seq X] : cauchy X :=
take ε, suppose ε > 0,
obtain y (Hy : converges_to_seq X y), from H,
have e2pos : ε / 2 > 0, from div_pos_of_pos_of_pos `ε > 0` two_pos,
obtain N₁ (HN₁ : ∀ {n}, n ≥ N₁ → dist (X n) y < ε / 2), from Hy e2pos,
obtain N₂ (HN₂ : ∀ {n}, n ≥ N₂ → dist (X n) y < ε / 2), from Hy e2pos,
let N := max N₁ N₂ in
exists.intro N
(take m n, suppose m ≥ N, suppose n ≥ N,
have m ≥ N₁, from le.trans !le_max_left `m ≥ N`,
have n ≥ N₂, from le.trans !le_max_right `n ≥ N`,
have dN₁ : dist (X m) y < ε / 2, from HN₁ `m ≥ N₁`,
have dN₂ : dist (X n) y < ε / 2, from HN₂ `n ≥ N₂`,
show dist (X m) (X n) < ε, from calc
dist (X m) (X n) ≤ dist (X m) y + dist y (X n) : dist_triangle
... = dist (X m) y + dist (X n) y : dist_comm
... < ε / 2 + ε / 2 : add_lt_add dN₁ dN₂
... = ε : add_halves)
end metric_space_M
/- convergence of a function at a point -/
section metric_space_M_N
variables {M N : Type} [strucM : metric_space M] [strucN : metric_space N]
include strucM strucN
definition converges_to_at (f : M → N) (y : N) (x : M) :=
∀ ⦃ε⦄, ε > 0 → ∃ δ, δ > 0 ∧ ∀ x', x ≠ x' ∧ dist x x' < δ → dist (f x') y < ε
notation f `⟶` y `at` x := converges_to_at f y x
definition converges_at [class] (f : M → N) (x : M) :=
∃ y, converges_to_at f y x
noncomputable definition limit_at (f : M → N) (x : M) [H : converges_at f x] : N :=
some H
proposition converges_to_limit_at (f : M → N) (x : M) [H : converges_at f x] :
(f ⟶ limit_at f x at x) :=
some_spec H
definition continuous_at (f : M → N) (x : M) := converges_to_at f (f x) x
definition continuous (f : M → N) := ∀ x, continuous_at f x
theorem continuous_at_spec {f : M → N} {x : M} (Hf : continuous_at f x) :
∀ ⦃ε⦄, ε > 0 → ∃ δ, δ > 0 ∧ ∀ x', dist x x' < δ → dist (f x') (f x) < ε :=
take ε, suppose ε > 0,
obtain δ Hδ, from Hf this,
exists.intro δ (and.intro
(and.left Hδ)
(take x', suppose dist x x' < δ,
if Heq : x = x' then
by rewrite [Heq, dist_self]; assumption
else
(suffices dist x x' < δ, from and.right Hδ x' (and.intro Heq this),
this)))
theorem image_seq_converges_of_converges [instance] (X : ℕ → M) [HX : converges_seq X] {f : M → N}
(Hf : continuous f) :
converges_seq (λ n, f (X n)) :=
begin
cases HX with xlim Hxlim,
existsi f xlim,
rewrite ↑converges_to_seq at *,
intros ε Hε,
let Hcont := Hf xlim Hε,
cases Hcont with δ Hδ,
cases Hxlim (and.left Hδ) with B HB,
existsi B,
intro n Hn,
cases em (xlim = X n),
rewrite [a, dist_self],
assumption,
apply and.right Hδ,
split,
exact a,
rewrite dist_comm,
apply HB Hn
end
end metric_space_M_N
end metric_space
/- complete metric spaces -/
open metric_space
structure complete_metric_space [class] (M : Type) extends metricM : metric_space M : Type :=
(complete : ∀ X, @cauchy M metricM X → @converges_seq M metricM X)
proposition complete (M : Type) [cmM : complete_metric_space M] {X : ℕ → M} (H : cauchy X) :
converges_seq X :=
complete_metric_space.complete X H
|
3a6db06a639f78e62a520206e1b0cb8af7dc346b | ba4794a0deca1d2aaa68914cd285d77880907b5c | /src/game/world2/level4.lean | dd926d299c083f832962ba876fa142b507479bd2 | [
"Apache-2.0"
] | permissive | ChrisHughes24/natural_number_game | c7c00aa1f6a95004286fd456ed13cf6e113159ce | 9d09925424da9f6275e6cfe427c8bcf12bb0944f | refs/heads/master | 1,600,715,773,528 | 1,573,910,462,000 | 1,573,910,462,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 900 | lean | import mynat.definition -- hide
import mynat.add -- hide
import game.world2.level3 -- hide
namespace mynat -- hide
/-
# Addition World
## Level 4: `add_comm` (boss level)
[boss battle music]
Look in Theorem statements -> Addition world to see the proofs you have.
These should be enough.
-/
/- Lemma
On the set of natural numbers, addition is commutative.
In other words, for all natural numbers $a$ and $b$, we have
$$ a + b = b + a. $$
-/
lemma add_comm (a b : mynat) : a + b = b + a :=
begin [less_leaky]
induction b with d hd,
{ rw zero_add,
rw add_zero,
refl
},
{ rw add_succ,
rw hd,
rw succ_add,
refl
}
end
/-
If you got this far -- nice! You're nearly ready to make a choice:
Multiplication World or Function World. But there are just a couple
more useful lemmas in Addition World which you should prove first.
Press on to level 5.
-/
end mynat -- hide
|
d31d670393f775716b59fc3462a5cd8be9011a23 | b9a81ebb9de684db509231c4469a7d2c88915808 | /src/super/resolution.lean | 35df2e3d04117b43fdba2264798898fa558d5ab1 | [] | no_license | leanprover/super | 3dd81ce8d9ac3cba20bce55e84833fadb2f5716e | 47b107b4cec8f3b41d72daba9cbda2f9d54025de | refs/heads/master | 1,678,482,996,979 | 1,676,526,367,000 | 1,676,526,367,000 | 92,215,900 | 12 | 6 | null | 1,513,327,539,000 | 1,495,570,640,000 | Lean | UTF-8 | Lean | false | false | 2,262 | lean | /-
Copyright (c) 2017 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import .clause .prover_state .utils
open tactic monad native
namespace super
variable gt : expr → expr → bool
variables (ac1 ac2 : derived_clause)
variables (c1 c2 : clause)
variables (i1 i2 : nat)
-- c1 : ... → ¬a → ...
-- c2 : ... → a → ...
meta def try_resolve : tactic clause := do
qf1 ← c1.open_metan c1.num_quants,
qf2 ← c2.open_metan c2.num_quants,
-- FIXME: using default transparency unifies m*n with (x*y*z)*w here ???
unify (qf1.1.get_lit i1).formula (qf2.1.get_lit i2).formula transparency.reducible,
qf1i ← qf1.1.inst_mvars,
guard $ clause.is_maximal gt qf1i i1,
op1 ← qf1.1.open_constn i1,
op2 ← qf2.1.open_constn c2.num_lits,
a_in_op2 ← (op2.2.nth i2).to_monad,
clause.meta_closure (qf1.2 ++ qf2.2) $
(op1.1.inst (op2.1.close_const a_in_op2).proof).close_constn (op1.2 ++ op2.2.remove_nth i2)
meta def try_add_resolvent : prover unit := do
c' ← try_resolve gt ac1.c ac2.c i1 i2,
inf_score 1 [ac1.sc, ac2.sc] >>= mk_derived c' >>= add_inferred
meta def maybe_add_resolvent : prover unit :=
try_add_resolvent gt ac1 ac2 i1 i2 <|> return ()
meta def resolution_left_inf : inference :=
assume given, do active ← get_active, sequence' $ do
given_i ← given.selected,
guard $ clause.literal.is_neg (given.c.get_lit given_i),
other ← rb_map.values active,
guard $ ¬given.sc.in_sos ∨ ¬other.sc.in_sos,
other_i ← other.selected,
guard $ clause.literal.is_pos (other.c.get_lit other_i),
[maybe_add_resolvent gt other given other_i given_i]
meta def resolution_right_inf : inference :=
assume given, do active ← get_active, sequence' $ do
given_i ← given.selected,
guard $ clause.literal.is_pos (given.c.get_lit given_i),
other ← rb_map.values active,
guard $ ¬given.sc.in_sos ∨ ¬other.sc.in_sos,
other_i ← other.selected,
guard $ clause.literal.is_neg (other.c.get_lit other_i),
[maybe_add_resolvent gt given other given_i other_i]
@[super.inf]
meta def resolution_inf : inf_decl := inf_decl.mk 40 $
assume given, do gt ← get_term_order, resolution_left_inf gt given >> resolution_right_inf gt given
end super
|
dc3b8302a2a47bcae61e477009e13448a14d0802 | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/group_theory/subgroup.lean | a22f526b9f9bfd6d78daae0b97f869baf43ddd5c | [
"Apache-2.0"
] | permissive | abentkamp/mathlib | d9a75d291ec09f4637b0f30cc3880ffb07549ee5 | 5360e476391508e092b5a1e5210bd0ed22dc0755 | refs/heads/master | 1,682,382,954,948 | 1,622,106,077,000 | 1,622,106,077,000 | 149,285,665 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 71,636 | lean | /-
Copyright (c) 2020 Kexing Ying. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kexing Ying
-/
import group_theory.submonoid
import algebra.group.conj
import algebra.pointwise
import order.atoms
/-!
# Subgroups
This file defines multiplicative and additive subgroups as an extension of submonoids, in a bundled
form (unbundled subgroups are in `deprecated/subgroups.lean`).
We prove subgroups of a group form a complete lattice, and results about images and preimages of
subgroups under group homomorphisms. The bundled subgroups use bundled monoid homomorphisms.
There are also theorems about the subgroups generated by an element or a subset of a group,
defined both inductively and as the infimum of the set of subgroups containing a given
element/subset.
Special thanks goes to Amelia Livingston and Yury Kudryashov for their help and inspiration.
## Main definitions
Notation used here:
- `G N` are `group`s
- `A` is an `add_group`
- `H K` are `subgroup`s of `G` or `add_subgroup`s of `A`
- `x` is an element of type `G` or type `A`
- `f g : N →* G` are group homomorphisms
- `s k` are sets of elements of type `G`
Definitions in the file:
* `subgroup G` : the type of subgroups of a group `G`
* `add_subgroup A` : the type of subgroups of an additive group `A`
* `complete_lattice (subgroup G)` : the subgroups of `G` form a complete lattice
* `subgroup.closure k` : the minimal subgroup that includes the set `k`
* `subgroup.subtype` : the natural group homomorphism from a subgroup of group `G` to `G`
* `subgroup.gi` : `closure` forms a Galois insertion with the coercion to set
* `subgroup.comap H f` : the preimage of a subgroup `H` along the group homomorphism `f` is also a
subgroup
* `subgroup.map f H` : the image of a subgroup `H` along the group homomorphism `f` is also a
subgroup
* `subgroup.prod H K` : the product of subgroups `H`, `K` of groups `G`, `N` respectively, `H × K`
is a subgroup of `G × N`
* `monoid_hom.range f` : the range of the group homomorphism `f` is a subgroup
* `monoid_hom.ker f` : the kernel of a group homomorphism `f` is the subgroup of elements `x : G`
such that `f x = 1`
* `monoid_hom.eq_locus f g` : given group homomorphisms `f`, `g`, the elements of `G` such that
`f x = g x` form a subgroup of `G`
* `is_simple_group G` : a class indicating that a group has exactly two normal subgroups
## Implementation notes
Subgroup inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as
membership of a subgroup's underlying set.
## Tags
subgroup, subgroups
-/
open_locale big_operators
variables {G : Type*} [group G]
variables {A : Type*} [add_group A]
set_option old_structure_cmd true
/-- A subgroup of a group `G` is a subset containing 1, closed under multiplication
and closed under multiplicative inverse. -/
structure subgroup (G : Type*) [group G] extends submonoid G :=
(inv_mem' {x} : x ∈ carrier → x⁻¹ ∈ carrier)
/-- An additive subgroup of an additive group `G` is a subset containing 0, closed
under addition and additive inverse. -/
structure add_subgroup (G : Type*) [add_group G] extends add_submonoid G:=
(neg_mem' {x} : x ∈ carrier → -x ∈ carrier)
attribute [to_additive] subgroup
attribute [to_additive add_subgroup.to_add_submonoid] subgroup.to_submonoid
/-- Reinterpret a `subgroup` as a `submonoid`. -/
add_decl_doc subgroup.to_submonoid
/-- Reinterpret an `add_subgroup` as an `add_submonoid`. -/
add_decl_doc add_subgroup.to_add_submonoid
namespace subgroup
@[to_additive]
instance : set_like (subgroup G) G :=
⟨subgroup.carrier, λ p q h, by cases p; cases q; congr'⟩
@[simp, to_additive]
lemma mem_carrier {s : subgroup G} {x : G} : x ∈ s.carrier ↔ x ∈ s := iff.rfl
/-- See Note [custom simps projection] -/
@[to_additive "See Note [custom simps projection]"]
def simps.coe (S : subgroup G) : set G := S
initialize_simps_projections subgroup (carrier → coe)
initialize_simps_projections add_subgroup (carrier → coe)
@[simp, to_additive]
lemma coe_to_submonoid (K : subgroup G) : (K.to_submonoid : set G) = K := rfl
@[simp, to_additive]
lemma mem_to_submonoid (K : subgroup G) (x : G) : x ∈ K.to_submonoid ↔ x ∈ K := iff.rfl
@[to_additive]
instance (K : subgroup G) [d : decidable_pred (∈ K)] [fintype G] : fintype K :=
show fintype {g : G // g ∈ K}, from infer_instance
@[to_additive]
theorem to_submonoid_injective :
function.injective (to_submonoid : subgroup G → submonoid G) :=
λ p q h, set_like.ext'_iff.2 (show _, from set_like.ext'_iff.1 h)
@[simp, to_additive]
theorem to_submonoid_eq {p q : subgroup G} : p.to_submonoid = q.to_submonoid ↔ p = q :=
to_submonoid_injective.eq_iff
@[mono, to_additive] lemma to_submonoid_strict_mono :
strict_mono (to_submonoid : subgroup G → submonoid G) := λ _ _, id
@[mono, to_additive]
lemma to_submonoid_mono : monotone (to_submonoid : subgroup G → submonoid G) :=
to_submonoid_strict_mono.monotone
@[simp, to_additive]
lemma to_submonoid_le {p q : subgroup G} : p.to_submonoid ≤ q.to_submonoid ↔ p ≤ q :=
iff.rfl
end subgroup
/-!
### Conversion to/from `additive`/`multiplicative`
-/
section mul_add
/-- Supgroups of a group `G` are isomorphic to additive subgroups of `additive G`. -/
@[simps]
def subgroup.to_add_subgroup : subgroup G ≃o add_subgroup (additive G) :=
{ to_fun := λ S,
{ neg_mem' := S.inv_mem',
..S.to_submonoid.to_add_submonoid },
inv_fun := λ S,
{ inv_mem' := S.neg_mem',
..S.to_add_submonoid.to_submonoid' },
left_inv := λ x, by cases x; refl,
right_inv := λ x, by cases x; refl,
map_rel_iff' := λ a b, iff.rfl, }
/-- Additive subgroup of an additive group `additive G` are isomorphic to subgroup of `G`. -/
abbreviation add_subgroup.to_subgroup' : add_subgroup (additive G) ≃o subgroup G :=
subgroup.to_add_subgroup.symm
/-- Additive supgroups of an additive group `A` are isomorphic to subgroups of `multiplicative A`.
-/
@[simps]
def add_subgroup.to_subgroup : add_subgroup A ≃o subgroup (multiplicative A) :=
{ to_fun := λ S,
{ inv_mem' := S.neg_mem',
..S.to_add_submonoid.to_submonoid },
inv_fun := λ S,
{ neg_mem' := S.inv_mem',
..S.to_submonoid.to_add_submonoid' },
left_inv := λ x, by cases x; refl,
right_inv := λ x, by cases x; refl,
map_rel_iff' := λ a b, iff.rfl, }
/-- Subgroups of an additive group `multiplicative A` are isomorphic to additive subgroups of `A`.
-/
abbreviation subgroup.to_add_subgroup' : subgroup (multiplicative A) ≃o add_subgroup A :=
add_subgroup.to_subgroup.symm
end mul_add
namespace subgroup
variables (H K : subgroup G)
/-- Copy of a subgroup with a new `carrier` equal to the old one. Useful to fix definitional
equalities.-/
@[to_additive "Copy of an additive subgroup with a new `carrier` equal to the old one.
Useful to fix definitional equalities"]
protected def copy (K : subgroup G) (s : set G) (hs : s = K) : subgroup G :=
{ carrier := s,
one_mem' := hs.symm ▸ K.one_mem',
mul_mem' := hs.symm ▸ K.mul_mem',
inv_mem' := hs.symm ▸ K.inv_mem' }
/-- Two subgroups are equal if they have the same elements. -/
@[ext, to_additive "Two `add_subgroup`s are equal if they have the same elements."]
theorem ext {H K : subgroup G} (h : ∀ x, x ∈ H ↔ x ∈ K) : H = K := set_like.ext h
attribute [ext] add_subgroup.ext
/-- A subgroup contains the group's 1. -/
@[to_additive "An `add_subgroup` contains the group's 0."]
theorem one_mem : (1 : G) ∈ H := H.one_mem'
/-- A subgroup is closed under multiplication. -/
@[to_additive "An `add_subgroup` is closed under addition."]
theorem mul_mem {x y : G} : x ∈ H → y ∈ H → x * y ∈ H := λ hx hy, H.mul_mem' hx hy
/-- A subgroup is closed under inverse. -/
@[to_additive "An `add_subgroup` is closed under inverse."]
theorem inv_mem {x : G} : x ∈ H → x⁻¹ ∈ H := λ hx, H.inv_mem' hx
/-- A subgroup is closed under division. -/
@[to_additive "An `add_subgroup` is closed under subtraction."]
theorem div_mem {x y : G} (hx : x ∈ H) (hy : y ∈ H) : x / y ∈ H :=
by simpa only [div_eq_mul_inv] using H.mul_mem' hx (H.inv_mem' hy)
@[simp, to_additive] theorem inv_mem_iff {x : G} : x⁻¹ ∈ H ↔ x ∈ H :=
⟨λ h, inv_inv x ▸ H.inv_mem h, H.inv_mem⟩
@[to_additive] lemma div_mem_comm_iff {a b : G} : a / b ∈ H ↔ b / a ∈ H :=
by rw [← H.inv_mem_iff, div_eq_mul_inv, div_eq_mul_inv, mul_inv_rev, inv_inv]
@[simp, to_additive]
theorem inv_coe_set : (H : set G)⁻¹ = H :=
by { ext, simp, }
@[simp, to_additive]
lemma exists_inv_mem_iff_exists_mem (K : subgroup G) {P : G → Prop} :
(∃ (x : G), x ∈ K ∧ P x⁻¹) ↔ ∃ x ∈ K, P x :=
by split; { rintros ⟨x, x_in, hx⟩, exact ⟨x⁻¹, inv_mem K x_in, by simp [hx]⟩ }
@[to_additive]
lemma mul_mem_cancel_right {x y : G} (h : x ∈ H) : y * x ∈ H ↔ y ∈ H :=
⟨λ hba, by simpa using H.mul_mem hba (H.inv_mem h), λ hb, H.mul_mem hb h⟩
@[to_additive]
lemma mul_mem_cancel_left {x y : G} (h : x ∈ H) : x * y ∈ H ↔ y ∈ H :=
⟨λ hab, by simpa using H.mul_mem (H.inv_mem h) hab, H.mul_mem h⟩
/-- Product of a list of elements in a subgroup is in the subgroup. -/
@[to_additive "Sum of a list of elements in an `add_subgroup` is in the `add_subgroup`."]
lemma list_prod_mem {l : list G} : (∀ x ∈ l, x ∈ K) → l.prod ∈ K :=
K.to_submonoid.list_prod_mem
/-- Product of a multiset of elements in a subgroup of a `comm_group` is in the subgroup. -/
@[to_additive "Sum of a multiset of elements in an `add_subgroup` of an `add_comm_group`
is in the `add_subgroup`."]
lemma multiset_prod_mem {G} [comm_group G] (K : subgroup G) (g : multiset G) :
(∀ a ∈ g, a ∈ K) → g.prod ∈ K := K.to_submonoid.multiset_prod_mem g
/-- Product of elements of a subgroup of a `comm_group` indexed by a `finset` is in the
subgroup. -/
@[to_additive "Sum of elements in an `add_subgroup` of an `add_comm_group` indexed by a `finset`
is in the `add_subgroup`."]
lemma prod_mem {G : Type*} [comm_group G] (K : subgroup G)
{ι : Type*} {t : finset ι} {f : ι → G} (h : ∀ c ∈ t, f c ∈ K) :
∏ c in t, f c ∈ K :=
K.to_submonoid.prod_mem h
lemma pow_mem {x : G} (hx : x ∈ K) : ∀ n : ℕ, x ^ n ∈ K := K.to_submonoid.pow_mem hx
lemma gpow_mem {x : G} (hx : x ∈ K) : ∀ n : ℤ, x ^ n ∈ K
| (n : ℕ) := by { rw [gpow_coe_nat], exact pow_mem _ hx n }
| -[1+ n] := by { rw [gpow_neg_succ_of_nat], exact K.inv_mem (K.pow_mem hx n.succ) }
/-- Construct a subgroup from a nonempty set that is closed under division. -/
@[to_additive "Construct a subgroup from a nonempty set that is closed under subtraction"]
def of_div (s : set G) (hsn : s.nonempty) (hs : ∀ x y ∈ s, x * y⁻¹ ∈ s) : subgroup G :=
have one_mem : (1 : G) ∈ s, from let ⟨x, hx⟩ := hsn in by simpa using hs x x hx hx,
have inv_mem : ∀ x, x ∈ s → x⁻¹ ∈ s, from λ x hx, by simpa using hs 1 x one_mem hx,
{ carrier := s,
one_mem' := one_mem,
inv_mem' := inv_mem,
mul_mem' := λ x y hx hy, by simpa using hs x y⁻¹ hx (inv_mem y hy) }
/-- A subgroup of a group inherits a multiplication. -/
@[to_additive "An `add_subgroup` of an `add_group` inherits an addition."]
instance has_mul : has_mul H := H.to_submonoid.has_mul
/-- A subgroup of a group inherits a 1. -/
@[to_additive "An `add_subgroup` of an `add_group` inherits a zero."]
instance has_one : has_one H := H.to_submonoid.has_one
/-- A subgroup of a group inherits an inverse. -/
@[to_additive "A `add_subgroup` of a `add_group` inherits an inverse."]
instance has_inv : has_inv H := ⟨λ a, ⟨a⁻¹, H.inv_mem a.2⟩⟩
/-- A subgroup of a group inherits a division -/
@[to_additive "An `add_subgroup` of an `add_group` inherits a subtraction."]
instance has_div : has_div H := ⟨λ a b, ⟨a / b, H.div_mem a.2 b.2⟩⟩
@[simp, norm_cast, to_additive] lemma coe_mul (x y : H) : (↑(x * y) : G) = ↑x * ↑y := rfl
@[simp, norm_cast, to_additive] lemma coe_one : ((1 : H) : G) = 1 := rfl
@[simp, norm_cast, to_additive] lemma coe_inv (x : H) : ↑(x⁻¹ : H) = (x⁻¹ : G) := rfl
@[simp, norm_cast, to_additive] lemma coe_mk (x : G) (hx : x ∈ H) : ((⟨x, hx⟩ : H) : G) = x := rfl
attribute [norm_cast] add_subgroup.coe_add add_subgroup.coe_zero
add_subgroup.coe_neg add_subgroup.coe_mk
/-- A subgroup of a group inherits a group structure. -/
@[to_additive "An `add_subgroup` of an `add_group` inherits an `add_group` structure."]
instance to_group {G : Type*} [group G] (H : subgroup G) : group H :=
subtype.coe_injective.group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl)
/-- A subgroup of a `comm_group` is a `comm_group`. -/
@[to_additive "An `add_subgroup` of an `add_comm_group` is an `add_comm_group`."]
instance to_comm_group {G : Type*} [comm_group G] (H : subgroup G) : comm_group H :=
subtype.coe_injective.comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl)
/-- A subgroup of an `ordered_comm_group` is an `ordered_comm_group`. -/
@[to_additive "An `add_subgroup` of an `add_ordered_comm_group` is an `add_ordered_comm_group`."]
instance to_ordered_comm_group {G : Type*} [ordered_comm_group G] (H : subgroup G) :
ordered_comm_group H :=
subtype.coe_injective.ordered_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl)
/-- A subgroup of a `linear_ordered_comm_group` is a `linear_ordered_comm_group`. -/
@[to_additive "An `add_subgroup` of a `linear_ordered_add_comm_group` is a
`linear_ordered_add_comm_group`."]
instance to_linear_ordered_comm_group {G : Type*} [linear_ordered_comm_group G]
(H : subgroup G) : linear_ordered_comm_group H :=
subtype.coe_injective.linear_ordered_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl)
/-- The natural group hom from a subgroup of group `G` to `G`. -/
@[to_additive "The natural group hom from an `add_subgroup` of `add_group` `G` to `G`."]
def subtype : H →* G := ⟨coe, rfl, λ _ _, rfl⟩
@[simp, to_additive] theorem coe_subtype : ⇑H.subtype = coe := rfl
@[simp, norm_cast] lemma coe_pow (x : H) (n : ℕ) : ((x ^ n : H) : G) = x ^ n :=
coe_subtype H ▸ monoid_hom.map_pow _ _ _
@[simp, norm_cast] lemma coe_gpow (x : H) (n : ℤ) : ((x ^ n : H) : G) = x ^ n :=
coe_subtype H ▸ monoid_hom.map_gpow _ _ _
/-- The inclusion homomorphism from a subgroup `H` contained in `K` to `K`. -/
@[to_additive "The inclusion homomorphism from a additive subgroup `H` contained in `K` to `K`."]
def inclusion {H K : subgroup G} (h : H ≤ K) : H →* K :=
monoid_hom.mk' (λ x, ⟨x, h x.prop⟩) (λ ⟨a, ha⟩ ⟨b, hb⟩, rfl)
@[simp, to_additive]
lemma coe_inclusion {H K : subgroup G} {h : H ≤ K} (a : H) : (inclusion h a : G) = a :=
by { cases a, simp only [inclusion, coe_mk, monoid_hom.mk'_apply] }
@[simp, to_additive]
lemma subtype_comp_inclusion {H K : subgroup G} (hH : H ≤ K) :
K.subtype.comp (inclusion hH) = H.subtype :=
by { ext, simp }
/-- The subgroup `G` of the group `G`. -/
@[to_additive "The `add_subgroup G` of the `add_group G`."]
instance : has_top (subgroup G) :=
⟨{ inv_mem' := λ _ _, set.mem_univ _ , .. (⊤ : submonoid G) }⟩
/-- The trivial subgroup `{1}` of an group `G`. -/
@[to_additive "The trivial `add_subgroup` `{0}` of an `add_group` `G`."]
instance : has_bot (subgroup G) :=
⟨{ inv_mem' := λ _, by simp *, .. (⊥ : submonoid G) }⟩
@[to_additive]
instance : inhabited (subgroup G) := ⟨⊥⟩
@[simp, to_additive] lemma mem_bot {x : G} : x ∈ (⊥ : subgroup G) ↔ x = 1 := iff.rfl
@[simp, to_additive] lemma mem_top (x : G) : x ∈ (⊤ : subgroup G) := set.mem_univ x
@[simp, to_additive] lemma coe_top : ((⊤ : subgroup G) : set G) = set.univ := rfl
@[simp, to_additive] lemma coe_bot : ((⊥ : subgroup G) : set G) = {1} := rfl
@[to_additive] lemma eq_bot_iff_forall : H = ⊥ ↔ ∀ x ∈ H, x = (1 : G) :=
begin
rw set_like.ext'_iff,
simp only [coe_bot, set.eq_singleton_iff_unique_mem, set_like.mem_coe, H.one_mem, true_and],
end
@[to_additive] lemma eq_bot_of_subsingleton [subsingleton H] : H = ⊥ :=
begin
rw subgroup.eq_bot_iff_forall,
intros y hy,
rw [← subgroup.coe_mk H y hy, subsingleton.elim (⟨y, hy⟩ : H) 1, subgroup.coe_one],
end
@[to_additive] instance fintype_bot : fintype (⊥ : subgroup G) := ⟨{1},
by {rintro ⟨x, ⟨hx⟩⟩, exact finset.mem_singleton_self _}⟩
@[simp] lemma _root_.add_subgroup.card_bot : fintype.card (⊥ : add_subgroup A) = 1 :=
fintype.card_eq_one_iff.2
⟨⟨(0 : A), set.mem_singleton 0⟩, λ ⟨y, hy⟩, subtype.eq $ add_subgroup.mem_bot.1 hy⟩
-- `@[to_additive]` doesn't work, because it converts the `1 : ℕ` to `0`.
@[simp] lemma card_bot : fintype.card (⊥ : subgroup G) = 1 :=
fintype.card_eq_one_iff.2
⟨⟨(1 : G), set.mem_singleton 1⟩, λ ⟨y, hy⟩, subtype.eq $ subgroup.mem_bot.1 hy⟩
@[to_additive] lemma eq_top_of_card_eq [fintype H] [fintype G]
(h : fintype.card H = fintype.card G) : H = ⊤ :=
begin
haveI : fintype (H : set G) := ‹fintype H›,
rw [set_like.ext'_iff, coe_top, ← finset.coe_univ, ← (H : set G).coe_to_finset, finset.coe_inj,
← finset.card_eq_iff_eq_univ, ← h, set.to_finset_card],
congr
end
@[to_additive] lemma nontrivial_iff_exists_ne_one (H : subgroup G) :
nontrivial H ↔ ∃ x ∈ H, x ≠ (1:G) :=
subtype.nontrivial_iff_exists_ne (λ x, x ∈ H) (1 : H)
/-- A subgroup is either the trivial subgroup or nontrivial. -/
@[to_additive] lemma bot_or_nontrivial (H : subgroup G) : H = ⊥ ∨ nontrivial H :=
begin
classical,
by_cases h : ∀ x ∈ H, x = (1 : G),
{ left,
exact H.eq_bot_iff_forall.mpr h },
{ right,
push_neg at h,
simpa [nontrivial_iff_exists_ne_one] using h },
end
/-- A subgroup is either the trivial subgroup or contains a nonzero element. -/
@[to_additive] lemma bot_or_exists_ne_one (H : subgroup G) : H = ⊥ ∨ ∃ x ∈ H, x ≠ (1:G) :=
begin
convert H.bot_or_nontrivial,
rw nontrivial_iff_exists_ne_one
end
/-- The inf of two subgroups is their intersection. -/
@[to_additive "The inf of two `add_subgroups`s is their intersection."]
instance : has_inf (subgroup G) :=
⟨λ H₁ H₂,
{ inv_mem' := λ _ ⟨hx, hx'⟩, ⟨H₁.inv_mem hx, H₂.inv_mem hx'⟩,
.. H₁.to_submonoid ⊓ H₂.to_submonoid }⟩
@[simp, to_additive]
lemma coe_inf (p p' : subgroup G) : ((p ⊓ p' : subgroup G) : set G) = p ∩ p' := rfl
@[simp, to_additive]
lemma mem_inf {p p' : subgroup G} {x : G} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl
@[to_additive]
instance : has_Inf (subgroup G) :=
⟨λ s,
{ inv_mem' := λ x hx, set.mem_bInter $ λ i h, i.inv_mem (by apply set.mem_bInter_iff.1 hx i h),
.. (⨅ S ∈ s, subgroup.to_submonoid S).copy (⋂ S ∈ s, ↑S) (by simp) }⟩
@[simp, to_additive]
lemma coe_Inf (H : set (subgroup G)) : ((Inf H : subgroup G) : set G) = ⋂ s ∈ H, ↑s := rfl
attribute [norm_cast] coe_Inf add_subgroup.coe_Inf
@[simp, to_additive]
lemma mem_Inf {S : set (subgroup G)} {x : G} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff
@[to_additive]
lemma mem_infi {ι : Sort*} {S : ι → subgroup G} {x : G} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i :=
by simp only [infi, mem_Inf, set.forall_range_iff]
@[simp, to_additive]
lemma coe_infi {ι : Sort*} {S : ι → subgroup G} : (↑(⨅ i, S i) : set G) = ⋂ i, S i :=
by simp only [infi, coe_Inf, set.bInter_range]
attribute [norm_cast] coe_infi add_subgroup.coe_infi
/-- Subgroups of a group form a complete lattice. -/
@[to_additive "The `add_subgroup`s of an `add_group` form a complete lattice."]
instance : complete_lattice (subgroup G) :=
{ bot := (⊥),
bot_le := λ S x hx, (mem_bot.1 hx).symm ▸ S.one_mem,
top := (⊤),
le_top := λ S x hx, mem_top x,
inf := (⊓),
le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩,
inf_le_left := λ a b x, and.left,
inf_le_right := λ a b x, and.right,
.. complete_lattice_of_Inf (subgroup G) $ λ s, is_glb.of_image
(λ H K, show (H : set G) ≤ K ↔ H ≤ K, from set_like.coe_subset_coe) is_glb_binfi }
@[to_additive]
lemma mem_sup_left {S T : subgroup G} : ∀ {x : G}, x ∈ S → x ∈ S ⊔ T :=
show S ≤ S ⊔ T, from le_sup_left
@[to_additive]
lemma mem_sup_right {S T : subgroup G} : ∀ {x : G}, x ∈ T → x ∈ S ⊔ T :=
show T ≤ S ⊔ T, from le_sup_right
@[to_additive]
lemma mem_supr_of_mem {ι : Type*} {S : ι → subgroup G} (i : ι) :
∀ {x : G}, x ∈ S i → x ∈ supr S :=
show S i ≤ supr S, from le_supr _ _
@[to_additive]
lemma mem_Sup_of_mem {S : set (subgroup G)} {s : subgroup G}
(hs : s ∈ S) : ∀ {x : G}, x ∈ s → x ∈ Sup S :=
show s ≤ Sup S, from le_Sup hs
@[to_additive]
lemma subsingleton_iff : subsingleton G ↔ subsingleton (subgroup G) :=
⟨ λ h, by exactI ⟨λ x y, subgroup.ext $ λ i, subsingleton.elim 1 i ▸ by simp [subgroup.one_mem]⟩,
λ h, by exactI ⟨λ x y,
have ∀ i : G, i = 1 := λ i, mem_bot.mp $ subsingleton.elim (⊤ : subgroup G) ⊥ ▸ mem_top i,
(this x).trans (this y).symm⟩⟩
@[to_additive]
lemma nontrivial_iff : nontrivial G ↔ nontrivial (subgroup G) :=
not_iff_not.mp (
(not_nontrivial_iff_subsingleton.trans subsingleton_iff).trans
not_nontrivial_iff_subsingleton.symm)
@[to_additive]
instance [subsingleton G] : unique (subgroup G) :=
⟨⟨⊥⟩, λ a, @subsingleton.elim _ (subsingleton_iff.mp ‹_›) a _⟩
@[to_additive]
instance [nontrivial G] : nontrivial (subgroup G) := nontrivial_iff.mp ‹_›
@[to_additive] lemma eq_top_iff' : H = ⊤ ↔ ∀ x : G, x ∈ H :=
eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩
/-- The `subgroup` generated by a set. -/
@[to_additive "The `add_subgroup` generated by a set"]
def closure (k : set G) : subgroup G := Inf {K | k ⊆ K}
variable {k : set G}
@[to_additive]
lemma mem_closure {x : G} : x ∈ closure k ↔ ∀ K : subgroup G, k ⊆ K → x ∈ K :=
mem_Inf
/-- The subgroup generated by a set includes the set. -/
@[simp, to_additive "The `add_subgroup` generated by a set includes the set."]
lemma subset_closure : k ⊆ closure k := λ x hx, mem_closure.2 $ λ K hK, hK hx
open set
/-- A subgroup `K` includes `closure k` if and only if it includes `k`. -/
@[simp, to_additive "An additive subgroup `K` includes `closure k` if and only if it includes `k`"]
lemma closure_le : closure k ≤ K ↔ k ⊆ K :=
⟨subset.trans subset_closure, λ h, Inf_le h⟩
@[to_additive]
lemma closure_eq_of_le (h₁ : k ⊆ K) (h₂ : K ≤ closure k) : closure k = K :=
le_antisymm ((closure_le $ K).2 h₁) h₂
/-- An induction principle for closure membership. If `p` holds for `1` and all elements of `k`, and
is preserved under multiplication and inverse, then `p` holds for all elements of the closure
of `k`. -/
@[to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all
elements of `k`, and is preserved under addition and inverses, then `p` holds for all elements
of the additive closure of `k`."]
lemma closure_induction {p : G → Prop} {x} (h : x ∈ closure k)
(Hk : ∀ x ∈ k, p x) (H1 : p 1)
(Hmul : ∀ x y, p x → p y → p (x * y))
(Hinv : ∀ x, p x → p x⁻¹) : p x :=
(@closure_le _ _ ⟨p, H1, Hmul, Hinv⟩ _).2 Hk h
attribute [elab_as_eliminator] subgroup.closure_induction add_subgroup.closure_induction
/-- An induction principle on elements of the subtype `subgroup.closure`.
If `p` holds for `1` and all elements of `k`, and is preserved under multiplication and inverse,
then `p` holds for all elements `x : closure k`.
The difference with `subgroup.closure_induction` is that this acts on the subtype.
-/
@[to_additive "An induction principle on elements of the subtype `add_subgroup.closure`.
If `p` holds for `0` and all elements of `k`, and is preserved under addition and negation,
then `p` holds for all elements `x : closure k`.
The difference with `add_subgroup.closure_induction` is that this acts on the subtype."]
lemma closure_induction' (k : set G) {p : closure k → Prop}
(Hk : ∀ x (h : x ∈ k), p ⟨x, subset_closure h⟩)
(H1 : p 1)
(Hmul : ∀ x y, p x → p y → p (x * y))
(Hinv : ∀ x, p x → p x⁻¹)
(x : closure k) :
p x :=
subtype.rec_on x $ λ x hx, begin
refine exists.elim _ (λ (hx : x ∈ closure k) (hc : p ⟨x, hx⟩), hc),
exact closure_induction hx
(λ x hx, ⟨subset_closure hx, Hk x hx⟩)
⟨one_mem _, H1⟩
(λ x y hx hy, exists.elim hx $ λ hx' hx, exists.elim hy $ λ hy' hy,
⟨mul_mem _ hx' hy', Hmul _ _ hx hy⟩)
(λ x hx, exists.elim hx $ λ hx' hx, ⟨inv_mem _ hx', Hinv _ hx⟩),
end
attribute [elab_as_eliminator] subgroup.closure_induction' add_subgroup.closure_induction'
variable (G)
/-- `closure` forms a Galois insertion with the coercion to set. -/
@[to_additive "`closure` forms a Galois insertion with the coercion to set."]
protected def gi : galois_insertion (@closure G _) coe :=
{ choice := λ s _, closure s,
gc := λ s t, @closure_le _ _ t s,
le_l_u := λ s, subset_closure,
choice_eq := λ s h, rfl }
variable {G}
/-- Subgroup closure of a set is monotone in its argument: if `h ⊆ k`,
then `closure h ≤ closure k`. -/
@[to_additive "Additive subgroup closure of a set is monotone in its argument: if `h ⊆ k`,
then `closure h ≤ closure k`"]
lemma closure_mono ⦃h k : set G⦄ (h' : h ⊆ k) : closure h ≤ closure k :=
(subgroup.gi G).gc.monotone_l h'
/-- Closure of a subgroup `K` equals `K`. -/
@[simp, to_additive "Additive closure of an additive subgroup `K` equals `K`"]
lemma closure_eq : closure (K : set G) = K := (subgroup.gi G).l_u_eq K
@[simp, to_additive] lemma closure_empty : closure (∅ : set G) = ⊥ :=
(subgroup.gi G).gc.l_bot
@[simp, to_additive] lemma closure_univ : closure (univ : set G) = ⊤ :=
@coe_top G _ ▸ closure_eq ⊤
@[to_additive]
lemma closure_union (s t : set G) : closure (s ∪ t) = closure s ⊔ closure t :=
(subgroup.gi G).gc.l_sup
@[to_additive]
lemma closure_Union {ι} (s : ι → set G) : closure (⋃ i, s i) = ⨆ i, closure (s i) :=
(subgroup.gi G).gc.l_supr
@[to_additive]
lemma closure_eq_bot_iff (G : Type*) [group G] (S : set G) :
closure S = ⊥ ↔ S ⊆ {1} :=
by { rw [← le_bot_iff], exact closure_le _}
/-- The subgroup generated by an element of a group equals the set of integer number powers of
the element. -/
lemma mem_closure_singleton {x y : G} : y ∈ closure ({x} : set G) ↔ ∃ n : ℤ, x ^ n = y :=
begin
refine ⟨λ hy, closure_induction hy _ _ _ _,
λ ⟨n, hn⟩, hn ▸ gpow_mem _ (subset_closure $ mem_singleton x) n⟩,
{ intros y hy,
rw [eq_of_mem_singleton hy],
exact ⟨1, gpow_one x⟩ },
{ exact ⟨0, gpow_zero x⟩ },
{ rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩,
exact ⟨n + m, gpow_add x n m⟩ },
rintros _ ⟨n, rfl⟩,
exact ⟨-n, gpow_neg x n⟩
end
lemma closure_singleton_one : closure ({1} : set G) = ⊥ :=
by simp [eq_bot_iff_forall, mem_closure_singleton]
@[simp, to_additive] lemma inv_subset_closure (S : set G) : S⁻¹ ⊆ closure S :=
begin
intros s hs,
rw [set_like.mem_coe, ←subgroup.inv_mem_iff],
exact subset_closure (mem_inv.mp hs),
end
@[simp, to_additive] lemma closure_inv (S : set G) : closure S⁻¹ = closure S :=
begin
refine le_antisymm ((subgroup.closure_le _).2 _) ((subgroup.closure_le _).2 _),
{ exact inv_subset_closure S },
{ simpa only [set.inv_inv] using inv_subset_closure S⁻¹ },
end
@[to_additive]
lemma closure_to_submonoid (S : set G) :
(closure S).to_submonoid = submonoid.closure (S ∪ S⁻¹) :=
begin
refine le_antisymm _ (submonoid.closure_le.2 _),
{ intros x hx,
refine closure_induction hx (λ x hx, submonoid.closure_mono (subset_union_left S S⁻¹)
(submonoid.subset_closure hx)) (submonoid.one_mem _) (λ x y hx hy, submonoid.mul_mem _ hx hy)
(λ x hx, _),
rwa [←submonoid.mem_closure_inv, set.union_inv, set.inv_inv, set.union_comm] },
{ simp only [true_and, coe_to_submonoid, union_subset_iff, subset_closure, inv_subset_closure] }
end
/-- An induction principle for closure membership. If `p` holds for `1` and all elements of
`k` and their inverse, and is preserved under multiplication, then `p` holds for all elements of
the closure of `k`. -/
@[to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all
elements of `k` and their negation, and is preserved under addition, then `p` holds for all
elements of the additive closure of `k`."]
lemma closure_induction'' {p : G → Prop} {x} (h : x ∈ closure k)
(Hk : ∀ x ∈ k, p x) (Hk_inv : ∀ x ∈ k, p x⁻¹) (H1 : p 1)
(Hmul : ∀ x y, p x → p y → p (x * y)) : p x :=
begin
rw [← mem_to_submonoid, closure_to_submonoid k] at h,
refine submonoid.closure_induction h (λ x hx, _) H1 (λ x y hx hy, Hmul x y hx hy),
{ rw [mem_union, mem_inv] at hx,
cases hx with mem invmem,
{ exact Hk x mem },
{ rw [← inv_inv x],
exact Hk_inv _ invmem } },
end
@[to_additive]
lemma mem_supr_of_directed {ι} [hι : nonempty ι] {K : ι → subgroup G} (hK : directed (≤) K)
{x : G} :
x ∈ (supr K : subgroup G) ↔ ∃ i, x ∈ K i :=
begin
refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr K i) hi⟩,
suffices : x ∈ closure (⋃ i, (K i : set G)) → ∃ i, x ∈ K i,
by simpa only [closure_Union, closure_eq (K _)] using this,
refine (λ hx, closure_induction hx (λ _, mem_Union.1) _ _ _),
{ exact hι.elim (λ i, ⟨i, (K i).one_mem⟩) },
{ rintros x y ⟨i, hi⟩ ⟨j, hj⟩,
rcases hK i j with ⟨k, hki, hkj⟩,
exact ⟨k, (K k).mul_mem (hki hi) (hkj hj)⟩ },
rintros _ ⟨i, hi⟩, exact ⟨i, inv_mem (K i) hi⟩
end
@[to_additive]
lemma coe_supr_of_directed {ι} [nonempty ι] {S : ι → subgroup G} (hS : directed (≤) S) :
((⨆ i, S i : subgroup G) : set G) = ⋃ i, ↑(S i) :=
set.ext $ λ x, by simp [mem_supr_of_directed hS]
@[to_additive]
lemma mem_Sup_of_directed_on {K : set (subgroup G)} (Kne : K.nonempty)
(hK : directed_on (≤) K) {x : G} :
x ∈ Sup K ↔ ∃ s ∈ K, x ∈ s :=
begin
haveI : nonempty K := Kne.to_subtype,
simp only [Sup_eq_supr', mem_supr_of_directed hK.directed_coe, set_coe.exists, subtype.coe_mk]
end
variables {N : Type*} [group N] {P : Type*} [group P]
/-- The preimage of a subgroup along a monoid homomorphism is a subgroup. -/
@[to_additive "The preimage of an `add_subgroup` along an `add_monoid` homomorphism
is an `add_subgroup`."]
def comap {N : Type*} [group N] (f : G →* N)
(H : subgroup N) : subgroup G :=
{ carrier := (f ⁻¹' H),
inv_mem' := λ a ha,
show f a⁻¹ ∈ H, by rw f.map_inv; exact H.inv_mem ha,
.. H.to_submonoid.comap f }
@[simp, to_additive]
lemma coe_comap (K : subgroup N) (f : G →* N) : (K.comap f : set G) = f ⁻¹' K := rfl
@[simp, to_additive]
lemma mem_comap {K : subgroup N} {f : G →* N} {x : G} : x ∈ K.comap f ↔ f x ∈ K := iff.rfl
@[to_additive]
lemma comap_mono {f : G →* N} {K K' : subgroup N} : K ≤ K' → comap f K ≤ comap f K' :=
preimage_mono
@[to_additive]
lemma comap_comap (K : subgroup P) (g : N →* P) (f : G →* N) :
(K.comap g).comap f = K.comap (g.comp f) :=
rfl
/-- The image of a subgroup along a monoid homomorphism is a subgroup. -/
@[to_additive "The image of an `add_subgroup` along an `add_monoid` homomorphism
is an `add_subgroup`."]
def map (f : G →* N) (H : subgroup G) : subgroup N :=
{ carrier := (f '' H),
inv_mem' := by { rintros _ ⟨x, hx, rfl⟩, exact ⟨x⁻¹, H.inv_mem hx, f.map_inv x⟩ },
.. H.to_submonoid.map f }
@[simp, to_additive]
lemma coe_map (f : G →* N) (K : subgroup G) :
(K.map f : set N) = f '' K := rfl
@[simp, to_additive]
lemma mem_map {f : G →* N} {K : subgroup G} {y : N} :
y ∈ K.map f ↔ ∃ x ∈ K, f x = y :=
mem_image_iff_bex
@[to_additive]
lemma mem_map_of_mem (f : G →* N) {K : subgroup G} {x : G} (hx : x ∈ K) : f x ∈ K.map f :=
mem_image_of_mem f hx
@[to_additive]
lemma apply_coe_mem_map (f : G →* N) (K : subgroup G) (x : K) : f x ∈ K.map f :=
mem_map_of_mem f x.prop
@[to_additive]
lemma map_mono {f : G →* N} {K K' : subgroup G} : K ≤ K' → map f K ≤ map f K' :=
image_subset _
@[to_additive]
lemma map_map (g : N →* P) (f : G →* N) : (K.map f).map g = K.map (g.comp f) :=
set_like.coe_injective $ image_image _ _ _
@[to_additive]
lemma map_le_iff_le_comap {f : G →* N} {K : subgroup G} {H : subgroup N} :
K.map f ≤ H ↔ K ≤ H.comap f :=
image_subset_iff
@[to_additive]
lemma gc_map_comap (f : G →* N) : galois_connection (map f) (comap f) :=
λ _ _, map_le_iff_le_comap
@[to_additive]
lemma map_sup (H K : subgroup G) (f : G →* N) : (H ⊔ K).map f = H.map f ⊔ K.map f :=
(gc_map_comap f).l_sup
@[to_additive]
lemma map_supr {ι : Sort*} (f : G →* N) (s : ι → subgroup G) :
(supr s).map f = ⨆ i, (s i).map f :=
(gc_map_comap f).l_supr
@[to_additive]
lemma comap_inf (H K : subgroup N) (f : G →* N) : (H ⊓ K).comap f = H.comap f ⊓ K.comap f :=
(gc_map_comap f).u_inf
@[to_additive]
lemma comap_infi {ι : Sort*} (f : G →* N) (s : ι → subgroup N) :
(infi s).comap f = ⨅ i, (s i).comap f :=
(gc_map_comap f).u_infi
@[simp, to_additive] lemma map_bot (f : G →* N) : (⊥ : subgroup G).map f = ⊥ :=
(gc_map_comap f).l_bot
@[simp, to_additive] lemma comap_top (f : G →* N) : (⊤ : subgroup N).comap f = ⊤ :=
(gc_map_comap f).u_top
@[simp, to_additive]
lemma comap_subtype_inf_left {H K : subgroup G} : comap H.subtype (H ⊓ K) = comap H.subtype K :=
ext $ λ x, and_iff_right_of_imp (λ _, x.prop)
@[simp, to_additive]
lemma comap_subtype_inf_right {H K : subgroup G} : comap K.subtype (H ⊓ K) = comap K.subtype H :=
ext $ λ x, and_iff_left_of_imp (λ _, x.prop)
/-- Given `subgroup`s `H`, `K` of groups `G`, `N` respectively, `H × K` as a subgroup of `G × N`. -/
@[to_additive prod "Given `add_subgroup`s `H`, `K` of `add_group`s `A`, `B` respectively, `H × K`
as an `add_subgroup` of `A × B`."]
def prod (H : subgroup G) (K : subgroup N) : subgroup (G × N) :=
{ inv_mem' := λ _ hx, ⟨H.inv_mem' hx.1, K.inv_mem' hx.2⟩,
.. submonoid.prod H.to_submonoid K.to_submonoid}
@[to_additive coe_prod]
lemma coe_prod (H : subgroup G) (K : subgroup N) :
(H.prod K : set (G × N)) = (H : set G).prod (K : set N) := rfl
@[to_additive mem_prod]
lemma mem_prod {H : subgroup G} {K : subgroup N} {p : G × N} :
p ∈ H.prod K ↔ p.1 ∈ H ∧ p.2 ∈ K := iff.rfl
@[to_additive prod_mono]
lemma prod_mono : ((≤) ⇒ (≤) ⇒ (≤)) (@prod G _ N _) (@prod G _ N _) :=
λ s s' hs t t' ht, set.prod_mono hs ht
@[to_additive prod_mono_right]
lemma prod_mono_right (K : subgroup G) : monotone (λ t : subgroup N, K.prod t) :=
prod_mono (le_refl K)
@[to_additive prod_mono_left]
lemma prod_mono_left (H : subgroup N) : monotone (λ K : subgroup G, K.prod H) :=
λ s₁ s₂ hs, prod_mono hs (le_refl H)
@[to_additive prod_top]
lemma prod_top (K : subgroup G) :
K.prod (⊤ : subgroup N) = K.comap (monoid_hom.fst G N) :=
ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst]
@[to_additive top_prod]
lemma top_prod (H : subgroup N) :
(⊤ : subgroup G).prod H = H.comap (monoid_hom.snd G N) :=
ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd]
@[simp, to_additive top_prod_top]
lemma top_prod_top : (⊤ : subgroup G).prod (⊤ : subgroup N) = ⊤ :=
(top_prod _).trans $ comap_top _
@[to_additive] lemma bot_prod_bot : (⊥ : subgroup G).prod (⊥ : subgroup N) = ⊥ :=
set_like.coe_injective $ by simp [coe_prod, prod.one_eq_mk]
/-- Product of subgroups is isomorphic to their product as groups. -/
@[to_additive prod_equiv "Product of additive subgroups is isomorphic to their product
as additive groups"]
def prod_equiv (H : subgroup G) (K : subgroup N) : H.prod K ≃* H × K :=
{ map_mul' := λ x y, rfl, .. equiv.set.prod ↑H ↑K }
/-- A subgroup is normal if whenever `n ∈ H`, then `g * n * g⁻¹ ∈ H` for every `g : G` -/
structure normal : Prop :=
(conj_mem : ∀ n, n ∈ H → ∀ g : G, g * n * g⁻¹ ∈ H)
attribute [class] normal
end subgroup
namespace add_subgroup
/-- An add_subgroup is normal if whenever `n ∈ H`, then `g + n - g ∈ H` for every `g : G` -/
structure normal (H : add_subgroup A) : Prop :=
(conj_mem [] : ∀ n, n ∈ H → ∀ g : A, g + n + -g ∈ H)
attribute [to_additive add_subgroup.normal] subgroup.normal
attribute [class] normal
end add_subgroup
namespace subgroup
variables {H K : subgroup G}
@[priority 100, to_additive]
instance normal_of_comm {G : Type*} [comm_group G] (H : subgroup G) : H.normal :=
⟨by simp [mul_comm, mul_left_comm]⟩
namespace normal
variable (nH : H.normal)
@[to_additive] lemma mem_comm {a b : G} (h : a * b ∈ H) : b * a ∈ H :=
have a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ H, from nH.conj_mem (a * b) h a⁻¹, by simpa
@[to_additive] lemma mem_comm_iff {a b : G} : a * b ∈ H ↔ b * a ∈ H :=
⟨nH.mem_comm, nH.mem_comm⟩
end normal
@[priority 100, to_additive]
instance bot_normal : normal (⊥ : subgroup G) := ⟨by simp⟩
@[priority 100, to_additive]
instance top_normal : normal (⊤ : subgroup G) := ⟨λ _ _, mem_top⟩
variable (G)
/-- The center of a group `G` is the set of elements that commute with everything in `G` -/
@[to_additive "The center of a group `G` is the set of elements that commute with everything in
`G`"]
def center : subgroup G :=
{ carrier := {z | ∀ g, g * z = z * g},
one_mem' := by simp,
mul_mem' := λ a b (ha : ∀ g, g * a = a * g) (hb : ∀ g, g * b = b * g) g,
by assoc_rw [ha, hb g],
inv_mem' := λ a (ha : ∀ g, g * a = a * g) g,
by rw [← inv_inj, mul_inv_rev, inv_inv, ← ha, mul_inv_rev, inv_inv] }
variable {G}
@[to_additive] lemma mem_center_iff {z : G} : z ∈ center G ↔ ∀ g, g * z = z * g := iff.rfl
@[priority 100, to_additive]
instance center_normal : (center G).normal :=
⟨begin
assume n hn g h,
assoc_rw [hn (h * g), hn g],
simp
end⟩
variables {G} (H)
/-- The `normalizer` of `H` is the largest subgroup of `G` inside which `H` is normal. -/
@[to_additive "The `normalizer` of `H` is the largest subgroup of `G` inside which `H` is normal."]
def normalizer : subgroup G :=
{ carrier := {g : G | ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H},
one_mem' := by simp,
mul_mem' := λ a b (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) (hb : ∀ n, n ∈ H ↔ b * n * b⁻¹ ∈ H) n,
by { rw [hb, ha], simp [mul_assoc] },
inv_mem' := λ a (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) n,
by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } }
-- variant for sets.
-- TODO should this replace `normalizer`?
/-- The `set_normalizer` of `S` is the subgroup of `G` whose elements satisfy `g*S*g⁻¹=S` -/
@[to_additive "The `set_normalizer` of `S` is the subgroup of `G` whose elements satisfy
`g+S-g=S`."]
def set_normalizer (S : set G) : subgroup G :=
{ carrier := {g : G | ∀ n, n ∈ S ↔ g * n * g⁻¹ ∈ S},
one_mem' := by simp,
mul_mem' := λ a b (ha : ∀ n, n ∈ S ↔ a * n * a⁻¹ ∈ S) (hb : ∀ n, n ∈ S ↔ b * n * b⁻¹ ∈ S) n,
by { rw [hb, ha], simp [mul_assoc] },
inv_mem' := λ a (ha : ∀ n, n ∈ S ↔ a * n * a⁻¹ ∈ S) n,
by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } }
lemma mem_normalizer_fintype {S : set G} [fintype S] {x : G}
(h : ∀ n, n ∈ S → x * n * x⁻¹ ∈ S) : x ∈ subgroup.set_normalizer S :=
by haveI := classical.prop_decidable;
haveI := set.fintype_image S (λ n, x * n * x⁻¹); exact
λ n, ⟨h n, λ h₁,
have heq : (λ n, x * n * x⁻¹) '' S = S := set.eq_of_subset_of_card_le
(λ n ⟨y, hy⟩, hy.2 ▸ h y hy.1) (by rw set.card_image_of_injective S conj_injective),
have x * n * x⁻¹ ∈ (λ n, x * n * x⁻¹) '' S := heq.symm ▸ h₁,
let ⟨y, hy⟩ := this in conj_injective hy.2 ▸ hy.1⟩
variable {H}
@[to_additive] lemma mem_normalizer_iff {g : G} :
g ∈ normalizer H ↔ ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H := iff.rfl
@[to_additive] lemma le_normalizer : H ≤ normalizer H :=
λ x xH n, by rw [H.mul_mem_cancel_right (H.inv_mem xH), H.mul_mem_cancel_left xH]
@[priority 100, to_additive]
instance normal_in_normalizer : (H.comap H.normalizer.subtype).normal :=
⟨λ x xH g, by simpa using (g.2 x).1 xH⟩
open_locale classical
@[to_additive]
lemma le_normalizer_of_normal [hK : (H.comap K.subtype).normal] (HK : H ≤ K) : K ≤ H.normalizer :=
λ x hx y, ⟨λ yH, hK.conj_mem ⟨y, HK yH⟩ yH ⟨x, hx⟩,
λ yH, by simpa [mem_comap, mul_assoc] using
hK.conj_mem ⟨x * y * x⁻¹, HK yH⟩ yH ⟨x⁻¹, K.inv_mem hx⟩⟩
end subgroup
namespace group
variables {s : set G}
/-- Given a set `s`, `conjugates_of_set s` is the set of all conjugates of
the elements of `s`. -/
def conjugates_of_set (s : set G) : set G := ⋃ a ∈ s, conjugates_of a
lemma mem_conjugates_of_set_iff {x : G} : x ∈ conjugates_of_set s ↔ ∃ a ∈ s, is_conj a x :=
set.mem_bUnion_iff
theorem subset_conjugates_of_set : s ⊆ conjugates_of_set s :=
λ (x : G) (h : x ∈ s), mem_conjugates_of_set_iff.2 ⟨x, h, is_conj_refl _⟩
theorem conjugates_of_set_mono {s t : set G} (h : s ⊆ t) :
conjugates_of_set s ⊆ conjugates_of_set t :=
set.bUnion_subset_bUnion_left h
lemma conjugates_subset_normal {N : subgroup G} [tn : N.normal] {a : G} (h : a ∈ N) :
conjugates_of a ⊆ N :=
by { rintros a hc, obtain ⟨c, rfl⟩ := is_conj_iff.1 hc, exact tn.conj_mem a h c }
theorem conjugates_of_set_subset {s : set G} {N : subgroup G} [N.normal] (h : s ⊆ N) :
conjugates_of_set s ⊆ N :=
set.bUnion_subset (λ x H, conjugates_subset_normal (h H))
/-- The set of conjugates of `s` is closed under conjugation. -/
lemma conj_mem_conjugates_of_set {x c : G} :
x ∈ conjugates_of_set s → (c * x * c⁻¹ ∈ conjugates_of_set s) :=
λ H,
begin
rcases (mem_conjugates_of_set_iff.1 H) with ⟨a,h₁,h₂⟩,
exact mem_conjugates_of_set_iff.2 ⟨a, h₁, is_conj_trans h₂ (is_conj_iff.2 ⟨c,rfl⟩)⟩,
end
end group
namespace subgroup
open group
variable {s : set G}
/-- The normal closure of a set `s` is the subgroup closure of all the conjugates of
elements of `s`. It is the smallest normal subgroup containing `s`. -/
def normal_closure (s : set G) : subgroup G := closure (conjugates_of_set s)
theorem conjugates_of_set_subset_normal_closure : conjugates_of_set s ⊆ normal_closure s :=
subset_closure
theorem subset_normal_closure : s ⊆ normal_closure s :=
set.subset.trans subset_conjugates_of_set conjugates_of_set_subset_normal_closure
theorem le_normal_closure {H : subgroup G} : H ≤ normal_closure ↑H :=
λ _ h, subset_normal_closure h
/-- The normal closure of `s` is a normal subgroup. -/
instance normal_closure_normal : (normal_closure s).normal :=
⟨λ n h g,
begin
refine subgroup.closure_induction h (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _),
{ exact (conjugates_of_set_subset_normal_closure (conj_mem_conjugates_of_set hx)) },
{ simpa using (normal_closure s).one_mem },
{ rw ← conj_mul,
exact mul_mem _ ihx ihy },
{ rw ← conj_inv,
exact inv_mem _ ihx }
end⟩
/-- The normal closure of `s` is the smallest normal subgroup containing `s`. -/
theorem normal_closure_le_normal {N : subgroup G} [N.normal]
(h : s ⊆ N) : normal_closure s ≤ N :=
begin
assume a w,
refine closure_induction w (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _),
{ exact (conjugates_of_set_subset h hx) },
{ exact subgroup.one_mem _ },
{ exact subgroup.mul_mem _ ihx ihy },
{ exact subgroup.inv_mem _ ihx }
end
lemma normal_closure_subset_iff {N : subgroup G} [N.normal] : s ⊆ N ↔ normal_closure s ≤ N :=
⟨normal_closure_le_normal, set.subset.trans (subset_normal_closure)⟩
theorem normal_closure_mono {s t : set G} (h : s ⊆ t) : normal_closure s ≤ normal_closure t :=
normal_closure_le_normal (set.subset.trans h subset_normal_closure)
theorem normal_closure_eq_infi : normal_closure s =
⨅ (N : subgroup G) [normal N] (hs : s ⊆ N), N :=
le_antisymm
(le_infi (λ N, le_infi (λ hN, by exactI le_infi (normal_closure_le_normal))))
(infi_le_of_le (normal_closure s) (infi_le_of_le (by apply_instance)
(infi_le_of_le subset_normal_closure (le_refl _))))
@[simp] theorem normal_closure_eq_self (H : subgroup G) [H.normal] : normal_closure ↑H = H :=
le_antisymm (normal_closure_le_normal rfl.subset) (le_normal_closure)
@[simp] theorem normal_closure_idempotent : normal_closure ↑(normal_closure s) = normal_closure s :=
normal_closure_eq_self _
theorem closure_le_normal_closure {s : set G} : closure s ≤ normal_closure s :=
by simp only [subset_normal_closure, closure_le]
@[simp] theorem normal_closure_closure_eq_normal_closure {s : set G} :
normal_closure ↑(closure s) = normal_closure s :=
le_antisymm (normal_closure_le_normal closure_le_normal_closure)
(normal_closure_mono subset_closure)
end subgroup
namespace add_subgroup
open set
lemma gsmul_mem (H : add_subgroup A) {x : A} (hx : x ∈ H) :
∀ n : ℤ, n • x ∈ H
| (n : ℕ) := by { rw [gsmul_coe_nat], exact add_submonoid.nsmul_mem H.to_add_submonoid hx n }
| -[1+ n] := begin
rw gsmul_neg_succ_of_nat,
apply H.neg_mem',
exact add_submonoid.nsmul_mem H.to_add_submonoid hx n.succ
end
/-- The `add_subgroup` generated by an element of an `add_group` equals the set of
natural number multiples of the element. -/
lemma mem_closure_singleton {x y : A} :
y ∈ closure ({x} : set A) ↔ ∃ n : ℤ, n • x = y :=
begin
refine ⟨λ hy, closure_induction hy _ _ _ _,
λ ⟨n, hn⟩, hn ▸ gsmul_mem _ (subset_closure $ mem_singleton x) n⟩,
{ intros y hy,
rw [eq_of_mem_singleton hy],
exact ⟨1, one_gsmul x⟩ },
{ exact ⟨0, zero_gsmul x⟩ },
{ rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩,
exact ⟨n + m, add_gsmul x n m⟩ },
{ rintros _ ⟨n, rfl⟩,
refine ⟨-n, neg_gsmul x n⟩ }
end
lemma closure_singleton_zero : closure ({0} : set A) = ⊥ :=
by simp [eq_bot_iff_forall, mem_closure_singleton]
variable (H : add_subgroup A)
@[simp] lemma coe_smul (x : H) (n : ℕ) : ((n • x : H) : A) = n • x :=
coe_subtype H ▸ add_monoid_hom.map_nsmul _ _ _
@[simp] lemma coe_gsmul (x : H) (n : ℤ) : ((n • x : H) : A) = n • x :=
coe_subtype H ▸ add_monoid_hom.map_gsmul _ _ _
attribute [to_additive add_subgroup.coe_smul] subgroup.coe_pow
attribute [to_additive add_subgroup.coe_gsmul] subgroup.coe_gpow
end add_subgroup
namespace monoid_hom
variables {N : Type*} {P : Type*} [group N] [group P] (K : subgroup G)
open subgroup
/-- The range of a monoid homomorphism from a group is a subgroup. -/
@[to_additive "The range of an `add_monoid_hom` from an `add_group` is an `add_subgroup`."]
def range (f : G →* N) : subgroup N :=
subgroup.copy ((⊤ : subgroup G).map f) (set.range f) (by simp [set.ext_iff])
@[to_additive]
instance decidable_mem_range (f : G →* N) [fintype G] [decidable_eq N] :
decidable_pred (λ x, x ∈ f.range) :=
λ x, fintype.decidable_exists_fintype
@[simp, to_additive] lemma coe_range (f : G →* N) :
(f.range : set N) = set.range f := rfl
@[simp, to_additive] lemma mem_range {f : G →* N} {y : N} :
y ∈ f.range ↔ ∃ x, f x = y :=
iff.rfl
@[to_additive] lemma range_eq_map (f : G →* N) : f.range = (⊤ : subgroup G).map f :=
by ext; simp
/-- The canonical surjective group homomorphism `G →* f(G)` induced by a group
homomorphism `G →* N`. -/
@[to_additive "The canonical surjective `add_group` homomorphism `G →+ f(G)` induced by a group
homomorphism `G →+ N`."]
def range_restrict (f : G →* N) : G →* f.range :=
monoid_hom.mk' (λ g, ⟨f g, ⟨g, rfl⟩⟩) $ λ a b, by {ext, exact f.map_mul' _ _}
@[simp, to_additive]
lemma coe_range_restrict (f : G →* N) (g : G) : (f.range_restrict g : N) = f g := rfl
@[to_additive]
lemma map_range (g : N →* P) (f : G →* N) : f.range.map g = (g.comp f).range :=
by rw [range_eq_map, range_eq_map]; exact (⊤ : subgroup G).map_map g f
@[to_additive]
lemma range_top_iff_surjective {N} [group N] {f : G →* N} :
f.range = (⊤ : subgroup N) ↔ function.surjective f :=
set_like.ext'_iff.trans $ iff.trans (by rw [coe_range, coe_top]) set.range_iff_surjective
/-- The range of a surjective monoid homomorphism is the whole of the codomain. -/
@[to_additive "The range of a surjective `add_monoid` homomorphism is the whole of the codomain."]
lemma range_top_of_surjective {N} [group N] (f : G →* N) (hf : function.surjective f) :
f.range = (⊤ : subgroup N) :=
range_top_iff_surjective.2 hf
@[simp, to_additive] lemma _root_.subgroup.subtype_range (H : subgroup G) : H.subtype.range = H :=
by { rw [range_eq_map, ← set_like.coe_set_eq, coe_map, subgroup.coe_subtype], ext, simp }
/-- Restriction of a group hom to a subgroup of the domain. -/
@[to_additive "Restriction of an `add_group` hom to an `add_subgroup` of the domain."]
def restrict (f : G →* N) (H : subgroup G) : H →* N :=
f.comp H.subtype
@[simp, to_additive]
lemma restrict_apply {H : subgroup G} (f : G →* N) (x : H) :
f.restrict H x = f (x : G) := rfl
/-- Restriction of a group hom to a subgroup of the codomain. -/
@[to_additive "Restriction of an `add_group` hom to an `add_subgroup` of the codomain."]
def cod_restrict (f : G →* N) (S : subgroup N) (h : ∀ x, f x ∈ S) : G →* S :=
{ to_fun := λ n, ⟨f n, h n⟩,
map_one' := subtype.eq f.map_one,
map_mul' := λ x y, subtype.eq (f.map_mul x y) }
/-- Computable alternative to `monoid_hom.of_injective`. -/
def of_left_inverse {f : G →* N} {g : N →* G} (h : function.left_inverse g f) : G ≃* f.range :=
{ to_fun := f.range_restrict,
inv_fun := g ∘ f.range.subtype,
left_inv := h,
right_inv := by
{ rintros ⟨x, y, rfl⟩,
apply subtype.ext,
rw [coe_range_restrict, function.comp_apply, subgroup.coe_subtype, subtype.coe_mk, h] },
.. f.range_restrict }
@[simp] lemma of_left_inverse_apply {f : G →* N} {g : N →* G}
(h : function.left_inverse g f) (x : G) :
↑(of_left_inverse h x) = f x := rfl
@[simp] lemma of_left_inverse_symm_apply {f : G →* N} {g : N →* G}
(h : function.left_inverse g f) (x : f.range) :
(of_left_inverse h).symm x = g x := rfl
/-- The range of an injective group homomorphism is isomorphic to its domain. -/
noncomputable def of_injective {f : G →* N} (hf : function.injective f) : G ≃* f.range :=
(mul_equiv.of_bijective (f.cod_restrict f.range (λ x, ⟨x, rfl⟩))
⟨λ x y h, hf (subtype.ext_iff.mp h), by { rintros ⟨x, y, rfl⟩, exact ⟨y, rfl⟩ }⟩)
lemma of_injective_apply {f : G →* N} (hf : function.injective f) {x : G} :
↑(of_injective hf x) = f x := rfl
/-- The multiplicative kernel of a monoid homomorphism is the subgroup of elements `x : G` such that
`f x = 1` -/
@[to_additive "The additive kernel of an `add_monoid` homomorphism is the `add_subgroup` of elements
such that `f x = 0`"]
def ker (f : G →* N) := (⊥ : subgroup N).comap f
@[to_additive]
lemma mem_ker (f : G →* N) {x : G} : x ∈ f.ker ↔ f x = 1 := iff.rfl
@[to_additive]
lemma coe_ker (f : G →* N) : (f.ker : set G) = (f : G → N) ⁻¹' {1} := rfl
@[to_additive]
lemma eq_iff (f : G →* N) {x y : G} : f x = f y ↔ y⁻¹ * x ∈ f.ker :=
by rw [f.mem_ker, f.map_mul, f.map_inv, inv_mul_eq_one, eq_comm]
@[to_additive]
instance decidable_mem_ker [decidable_eq N] (f : G →* N) :
decidable_pred (∈ f.ker) :=
λ x, decidable_of_iff (f x = 1) f.mem_ker
@[to_additive]
lemma comap_ker (g : N →* P) (f : G →* N) : g.ker.comap f = (g.comp f).ker := rfl
@[to_additive] lemma range_restrict_ker (f : G →* N) : ker (range_restrict f) = ker f :=
begin
ext,
change (⟨f x, _⟩ : range f) = ⟨1, _⟩ ↔ f x = 1,
simp only [],
end
@[simp, to_additive]
lemma ker_one : (1 : G →* N).ker = ⊤ :=
by { ext, simp [mem_ker] }
@[to_additive] lemma ker_eq_bot_iff (f : G →* N) : f.ker = ⊥ ↔ function.injective f :=
begin
split,
{ intros h x y hxy,
rwa [←mul_inv_eq_one, ←map_inv, ←map_mul, ←mem_ker, h, mem_bot, mul_inv_eq_one] at hxy },
{ exact λ h, le_bot_iff.mp (λ x hx, h (hx.trans f.map_one.symm)) },
end
/-- The subgroup of elements `x : G` such that `f x = g x` -/
@[to_additive "The additive subgroup of elements `x : G` such that `f x = g x`"]
def eq_locus (f g : G →* N) : subgroup G :=
{ inv_mem' := λ x (hx : f x = g x), show f x⁻¹ = g x⁻¹, by rw [f.map_inv, g.map_inv, hx],
.. eq_mlocus f g}
/-- If two monoid homomorphisms are equal on a set, then they are equal on its subgroup closure. -/
@[to_additive]
lemma eq_on_closure {f g : G →* N} {s : set G} (h : set.eq_on f g s) :
set.eq_on f g (closure s) :=
show closure s ≤ f.eq_locus g, from (closure_le _).2 h
@[to_additive]
lemma eq_of_eq_on_top {f g : G →* N} (h : set.eq_on f g (⊤ : subgroup G)) :
f = g :=
ext $ λ x, h trivial
@[to_additive]
lemma eq_of_eq_on_dense {s : set G} (hs : closure s = ⊤) {f g : G →* N} (h : s.eq_on f g) :
f = g :=
eq_of_eq_on_top $ hs ▸ eq_on_closure h
@[to_additive]
lemma gclosure_preimage_le (f : G →* N) (s : set N) :
closure (f ⁻¹' s) ≤ (closure s).comap f :=
(closure_le _).2 $ λ x hx, by rw [set_like.mem_coe, mem_comap]; exact subset_closure hx
/-- The image under a monoid homomorphism of the subgroup generated by a set equals the subgroup
generated by the image of the set. -/
@[to_additive "The image under an `add_monoid` hom of the `add_subgroup` generated by a set equals
the `add_subgroup` generated by the image of the set."]
lemma map_closure (f : G →* N) (s : set G) :
(closure s).map f = closure (f '' s) :=
le_antisymm
(map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image f s)
(gclosure_preimage_le _ _))
((closure_le _).2 $ set.image_subset _ subset_closure)
end monoid_hom
namespace subgroup
variables {N : Type*} [group N] (H : subgroup G)
@[to_additive] lemma map_eq_bot_iff {f : G →* N} : H.map f = ⊥ ↔ H ≤ f.ker :=
begin
rw eq_bot_iff,
split,
{ exact λ h x hx, h ⟨x, hx, rfl⟩ },
{ intros h x hx,
obtain ⟨y, hy, rfl⟩ := hx,
exact h hy },
end
@[to_additive]
lemma map_eq_bot_iff_of_injective {f : G →* N} (hf : function.injective f) : H.map f = ⊥ ↔ H = ⊥ :=
by rw [map_eq_bot_iff, f.ker_eq_bot_iff.mpr hf, le_bot_iff]
end subgroup
namespace subgroup
open monoid_hom
variables {H : Type*} [group H]
@[to_additive]
lemma map_le_range (f : G →* H) (K : subgroup G) : map f K ≤ f.range :=
(range_eq_map f).symm ▸ map_mono le_top
@[to_additive]
lemma ker_le_comap (f : G →* H) (K : subgroup H) : f.ker ≤ comap f K :=
comap_mono bot_le
@[to_additive]
lemma map_comap_le (f : G →* H) (K : subgroup H) : map f (comap f K) ≤ K :=
(gc_map_comap f).l_u_le _
@[to_additive]
lemma le_comap_map (f : G →* H) (K : subgroup G) : K ≤ comap f (map f K) :=
(gc_map_comap f).le_u_l _
@[to_additive]
lemma map_comap_eq (f : G →* H) (K : subgroup H) :
map f (comap f K) = f.range ⊓ K :=
set_like.ext' begin
convert set.image_preimage_eq_inter_range,
simp [set.inter_comm],
end
@[to_additive]
lemma comap_map_eq (f : G →* H) (K : subgroup G) :
comap f (map f K) = K ⊔ f.ker :=
begin
refine le_antisymm _ (sup_le (le_comap_map _ _) (ker_le_comap _ _)),
intros x hx, simp only [exists_prop, mem_map, mem_comap] at hx,
rcases hx with ⟨y, hy, hy'⟩,
have : y⁻¹ * x ∈ f.ker, { rw mem_ker, simp [hy'] },
convert mul_mem _ (mem_sup_left hy) (mem_sup_right this),
simp,
end
@[to_additive]
lemma map_comap_eq_self {f : G →* H} {K : subgroup H} (h : K ≤ f.range) :
map f (comap f K) = K :=
by rwa [map_comap_eq, inf_eq_right]
@[to_additive]
lemma map_comap_eq_self_of_surjective {f : G →* H} (h : function.surjective f) (K : subgroup H) :
map f (comap f K) = K :=
map_comap_eq_self ((range_top_of_surjective _ h).symm ▸ le_top)
@[to_additive]
lemma comap_injective {f : G →* H} (h : function.surjective f) : function.injective (comap f) :=
λ K L hKL, by { apply_fun map f at hKL, simpa [map_comap_eq_self_of_surjective h] using hKL }
@[to_additive]
lemma comap_map_eq_self {f : G →* H} {K : subgroup G} (h : f.ker ≤ K) :
comap f (map f K) = K :=
by rwa [comap_map_eq, sup_eq_left]
@[to_additive]
lemma comap_map_eq_self_of_injective {f : G →* H} (h : function.injective f) (K : subgroup G) :
comap f (map f K) = K :=
comap_map_eq_self (((ker_eq_bot_iff _).mpr h).symm ▸ bot_le)
@[to_additive]
lemma map_injective {f : G →* H} (h : function.injective f) : function.injective (map f) :=
λ K L hKL, by { apply_fun comap f at hKL, simpa [comap_map_eq_self_of_injective h] using hKL }
@[to_additive]
lemma map_eq_comap_of_inverse {f : G →* H} {g : H →* G} (hl : function.left_inverse g f)
(hr : function.right_inverse g f) (K : subgroup G) : map f K = comap g K :=
set_like.ext' $ by rw [coe_map, coe_comap, set.image_eq_preimage_of_inverse hl hr]
end subgroup
namespace monoid_hom
variables {G₁ G₂ G₃ : Type*} [group G₁] [group G₂] [group G₃]
variables (f : G₁ →* G₂) (f_inv : G₂ → G₁)
/-- Auxiliary definition used to define `lift_of_right_inverse` -/
@[to_additive "Auxiliary definition used to define `lift_of_right_inverse`"]
def lift_of_right_inverse_aux
(hf : function.right_inverse f_inv f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) :
G₂ →* G₃ :=
{ to_fun := λ b, g (f_inv b),
map_one' := hg (hf 1),
map_mul' :=
begin
intros x y,
rw [← g.map_mul, ← mul_inv_eq_one, ← g.map_inv, ← g.map_mul, ← g.mem_ker],
apply hg,
rw [f.mem_ker, f.map_mul, f.map_inv, mul_inv_eq_one, f.map_mul],
simp only [hf _],
end }
@[simp, to_additive]
lemma lift_of_right_inverse_aux_comp_apply
(hf : function.right_inverse f_inv f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) (x : G₁) :
(f.lift_of_right_inverse_aux f_inv hf g hg) (f x) = g x :=
begin
dsimp [lift_of_right_inverse_aux],
rw [← mul_inv_eq_one, ← g.map_inv, ← g.map_mul, ← g.mem_ker],
apply hg,
rw [f.mem_ker, f.map_mul, f.map_inv, mul_inv_eq_one],
simp only [hf _],
end
/-- `lift_of_right_inverse f hf g hg` is the unique group homomorphism `φ`
* such that `φ.comp f = g` (`monoid_hom.lift_of_right_inverse_comp`),
* where `f : G₁ →+* G₂` has a right_inverse `f_inv` (`hf`),
* and `g : G₂ →+* G₃` satisfies `hg : f.ker ≤ g.ker`.
See `monoid_hom.eq_lift_of_right_inverse` for the uniqueness lemma.
```
G₁.
| \
f | \ g
| \
v \⌟
G₂----> G₃
∃!φ
```
-/
@[to_additive "`lift_of_right_inverse f f_inv hf g hg` is the unique additive group homomorphism `φ`
* such that `φ.comp f = g` (`add_monoid_hom.lift_of_right_inverse_comp`),
* where `f : G₁ →+ G₂` has a right_inverse `f_inv` (`hf`),
* and `g : G₂ →+ G₃` satisfies `hg : f.ker ≤ g.ker`.
See `add_monoid_hom.eq_lift_of_right_inverse` for the uniqueness lemma.
```
G₁.
| \\
f | \\ g
| \\
v \\⌟
G₂----> G₃
∃!φ
```"]
def lift_of_right_inverse
(hf : function.right_inverse f_inv f) : {g : G₁ →* G₃ // f.ker ≤ g.ker} ≃ (G₂ →* G₃) :=
{ to_fun := λ g, f.lift_of_right_inverse_aux f_inv hf g.1 g.2,
inv_fun := λ φ, ⟨φ.comp f, λ x hx, (mem_ker _).mpr $ by simp [(mem_ker _).mp hx]⟩,
left_inv := λ g, by {
ext,
simp only [comp_apply, lift_of_right_inverse_aux_comp_apply, subtype.coe_mk,
subtype.val_eq_coe], },
right_inv := λ φ, by {
ext b,
simp [lift_of_right_inverse_aux, hf b], } }
/-- A non-computable version of `monoid_hom.lift_of_right_inverse` for when no computable right
inverse is available, that uses `function.surj_inv`. -/
@[simp, to_additive "A non-computable version of `add_monoid_hom.lift_of_right_inverse` for when no
computable right inverse is available."]
noncomputable abbreviation lift_of_surjective
(hf : function.surjective f) : {g : G₁ →* G₃ // f.ker ≤ g.ker} ≃ (G₂ →* G₃) :=
f.lift_of_right_inverse (function.surj_inv hf) (function.right_inverse_surj_inv hf)
@[simp, to_additive]
lemma lift_of_right_inverse_comp_apply
(hf : function.right_inverse f_inv f) (g : {g : G₁ →* G₃ // f.ker ≤ g.ker}) (x : G₁) :
(f.lift_of_right_inverse f_inv hf g) (f x) = g x :=
f.lift_of_right_inverse_aux_comp_apply f_inv hf g.1 g.2 x
@[simp, to_additive]
lemma lift_of_right_inverse_comp (hf : function.right_inverse f_inv f)
(g : {g : G₁ →* G₃ // f.ker ≤ g.ker}) :
(f.lift_of_right_inverse f_inv hf g).comp f = g :=
monoid_hom.ext $ f.lift_of_right_inverse_comp_apply f_inv hf g
@[to_additive]
lemma eq_lift_of_right_inverse (hf : function.right_inverse f_inv f) (g : G₁ →* G₃)
(hg : f.ker ≤ g.ker) (h : G₂ →* G₃) (hh : h.comp f = g) :
h = (f.lift_of_right_inverse f_inv hf ⟨g, hg⟩) :=
begin
simp_rw ←hh,
exact ((f.lift_of_right_inverse f_inv hf).apply_symm_apply _).symm,
end
end monoid_hom
variables {N : Type*} [group N]
-- Here `H.normal` is an explicit argument so we can use dot notation with `comap`.
@[to_additive]
lemma subgroup.normal.comap {H : subgroup N} (hH : H.normal) (f : G →* N) :
(H.comap f).normal :=
⟨λ _, by simp [subgroup.mem_comap, hH.conj_mem] {contextual := tt}⟩
@[priority 100, to_additive]
instance subgroup.normal_comap {H : subgroup N}
[nH : H.normal] (f : G →* N) : (H.comap f).normal := nH.comap _
@[priority 100, to_additive]
instance monoid_hom.normal_ker (f : G →* N) : f.ker.normal :=
by rw [monoid_hom.ker]; apply_instance
@[priority 100, to_additive]
instance subgroup.normal_inf (H N : subgroup G) [hN : N.normal] :
((H ⊓ N).comap H.subtype).normal :=
⟨λ x hx g, begin
simp only [subgroup.mem_inf, coe_subtype, subgroup.mem_comap] at hx,
simp only [subgroup.coe_mul, subgroup.mem_inf, coe_subtype, subgroup.coe_inv, subgroup.mem_comap],
exact ⟨H.mul_mem (H.mul_mem g.2 hx.1) (H.inv_mem g.2), hN.1 x hx.2 g⟩,
end⟩
namespace subgroup
/-- The subgroup generated by an element. -/
def gpowers (g : G) : subgroup G :=
subgroup.copy (gpowers_hom G g).range (set.range ((^) g : ℤ → G)) rfl
@[simp] lemma mem_gpowers (g : G) : g ∈ gpowers g := ⟨1, gpow_one _⟩
lemma gpowers_eq_closure (g : G) : gpowers g = closure {g} :=
by { ext, exact mem_closure_singleton.symm }
@[simp] lemma range_gpowers_hom (g : G) : (gpowers_hom G g).range = gpowers g := rfl
lemma gpowers_subset {a : G} {K : subgroup G} (h : a ∈ K) : gpowers a ≤ K :=
λ x hx, match x, hx with _, ⟨i, rfl⟩ := K.gpow_mem h i end
end subgroup
namespace add_subgroup
/-- The subgroup generated by an element. -/
def gmultiples (a : A) : add_subgroup A :=
add_subgroup.copy (gmultiples_hom A a).range (set.range ((• a) : ℤ → A)) rfl
@[simp] lemma mem_gmultiples (a : A) : a ∈ gmultiples a := ⟨1, one_gsmul _⟩
lemma gmultiples_eq_closure (a : A) : gmultiples a = closure {a} :=
by { ext, exact mem_closure_singleton.symm }
@[simp] lemma range_gmultiples_hom (a : A) : (gmultiples_hom A a).range = gmultiples a := rfl
lemma gmultiples_subset {a : A} {B : add_subgroup A} (h : a ∈ B) : gmultiples a ≤ B :=
@subgroup.gpowers_subset (multiplicative A) _ _ (B.to_subgroup) h
attribute [to_additive add_subgroup.gmultiples] subgroup.gpowers
attribute [to_additive add_subgroup.mem_gmultiples] subgroup.mem_gpowers
attribute [to_additive add_subgroup.gmultiples_eq_closure] subgroup.gpowers_eq_closure
attribute [to_additive add_subgroup.range_gmultiples_hom] subgroup.range_gpowers_hom
attribute [to_additive add_subgroup.gmultiples_subset] subgroup.gpowers_subset
end add_subgroup
lemma of_mul_image_gpowers_eq_gmultiples_of_mul { x : G } :
additive.of_mul '' ((subgroup.gpowers x) : set G) = add_subgroup.gmultiples (additive.of_mul x) :=
begin
ext y,
split,
{ rintro ⟨z, ⟨m, hm⟩, hz2⟩,
use m,
simp only,
rwa [← of_mul_gpow, hm] },
{ rintros ⟨n, hn⟩,
refine ⟨x ^ n, ⟨n, rfl⟩, _⟩,
rwa of_mul_gpow }
end
lemma of_add_image_gmultiples_eq_gpowers_of_add {x : A} :
multiplicative.of_add '' ((add_subgroup.gmultiples x) : set A) =
subgroup.gpowers (multiplicative.of_add x) :=
begin
symmetry,
rw equiv.eq_image_iff_symm_image_eq,
exact of_mul_image_gpowers_eq_gmultiples_of_mul,
end
namespace mul_equiv
variables {H K : subgroup G}
/-- Makes the identity isomorphism from a proof two subgroups of a multiplicative
group are equal. -/
@[to_additive "Makes the identity additive isomorphism from a proof
two subgroups of an additive group are equal."]
def subgroup_congr (h : H = K) : H ≃* K :=
{ map_mul' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h }
end mul_equiv
-- TODO : ↥(⊤ : subgroup H) ≃* H ?
namespace subgroup
variables {C : Type*} [comm_group C] {s t : subgroup C} {x : C}
@[to_additive]
lemma mem_sup : x ∈ s ⊔ t ↔ ∃ (y ∈ s) (z ∈ t), y * z = x :=
⟨λ h, begin
rw [← closure_eq s, ← closure_eq t, ← closure_union] at h,
apply closure_induction h,
{ rintro y (h | h),
{ exact ⟨y, h, 1, t.one_mem, by simp⟩ },
{ exact ⟨1, s.one_mem, y, h, by simp⟩ } },
{ exact ⟨1, s.one_mem, 1, ⟨t.one_mem, mul_one 1⟩⟩ },
{ rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩,
exact ⟨_, mul_mem _ hy₁ hy₂, _, mul_mem _ hz₁ hz₂, by simp [mul_assoc]; cc⟩ },
{ rintro _ ⟨y, hy, z, hz, rfl⟩,
exact ⟨_, inv_mem _ hy, _, inv_mem _ hz, mul_comm z y ▸ (mul_inv_rev z y).symm⟩ }
end,
by rintro ⟨y, hy, z, hz, rfl⟩; exact mul_mem _
((le_sup_left : s ≤ s ⊔ t) hy)
((le_sup_right : t ≤ s ⊔ t) hz)⟩
@[to_additive]
lemma mem_sup' : x ∈ s ⊔ t ↔ ∃ (y : s) (z : t), (y:C) * z = x :=
mem_sup.trans $ by simp only [set_like.exists, coe_mk]
@[to_additive]
instance : is_modular_lattice (subgroup C) :=
⟨λ x y z xz a ha, begin
rw [mem_inf, mem_sup] at ha,
rcases ha with ⟨⟨b, hb, c, hc, rfl⟩, haz⟩,
rw mem_sup,
refine ⟨b, hb, c, mem_inf.2 ⟨hc, _⟩, rfl⟩,
rw ← inv_mul_cancel_left b c,
apply z.mul_mem (z.inv_mem (xz hb)) haz,
end⟩
end subgroup
section
variables (G) (A)
/-- A `group` is simple when it has exactly two normal `subgroup`s. -/
class is_simple_group extends nontrivial G : Prop :=
(eq_bot_or_eq_top_of_normal : ∀ H : subgroup G, H.normal → H = ⊥ ∨ H = ⊤)
/-- An `add_group` is simple when it has exactly two normal `add_subgroup`s. -/
class is_simple_add_group extends nontrivial A : Prop :=
(eq_bot_or_eq_top_of_normal : ∀ H : add_subgroup A, H.normal → H = ⊥ ∨ H = ⊤)
attribute [to_additive] is_simple_group
variables {G} {A}
@[to_additive]
lemma subgroup.normal.eq_bot_or_eq_top [is_simple_group G] {H : subgroup G} (Hn : H.normal) :
H = ⊥ ∨ H = ⊤ :=
is_simple_group.eq_bot_or_eq_top_of_normal H Hn
namespace is_simple_group
@[to_additive]
instance {C : Type*} [comm_group C] [is_simple_group C] :
is_simple_lattice (subgroup C) :=
⟨λ H, H.normal_of_comm.eq_bot_or_eq_top⟩
open subgroup
@[to_additive]
lemma is_simple_group_of_surjective {H : Type*} [group H] [is_simple_group G]
[nontrivial H] (f : G →* H) (hf : function.surjective f) :
is_simple_group H :=
⟨nontrivial.exists_pair_ne, λ H iH, begin
refine ((iH.comap f).eq_bot_or_eq_top).imp (λ h, _) (λ h, _),
{ rw [←map_bot f, ←h, map_comap_eq_self_of_surjective hf] },
{ rw [←comap_top f] at h, exact comap_injective hf h }
end⟩
end is_simple_group
end
section pointwise
namespace subgroup
@[to_additive]
lemma closure_mul_le (S T : set G) : closure (S * T) ≤ closure S ⊔ closure T :=
Inf_le $ λ x ⟨s, t, hs, ht, hx⟩, hx ▸ (closure S ⊔ closure T).mul_mem
(set_like.le_def.mp le_sup_left $ subset_closure hs)
(set_like.le_def.mp le_sup_right $ subset_closure ht)
@[to_additive]
lemma sup_eq_closure (H K : subgroup G) : H ⊔ K = closure (H * K) :=
le_antisymm
(sup_le
(λ h hh, subset_closure ⟨h, 1, hh, K.one_mem, mul_one h⟩)
(λ k hk, subset_closure ⟨1, k, H.one_mem, hk, one_mul k⟩))
(by conv_rhs { rw [← closure_eq H, ← closure_eq K] }; apply closure_mul_le)
@[to_additive]
private def mul_normal_aux (H N : subgroup G) [hN : N.normal] : subgroup G :=
{ carrier := (H : set G) * N,
one_mem' := ⟨1, 1, H.one_mem, N.one_mem, by rw mul_one⟩,
mul_mem' := λ a b ⟨h, n, hh, hn, ha⟩ ⟨h', n', hh', hn', hb⟩,
⟨h * h', h'⁻¹ * n * h' * n',
H.mul_mem hh hh', N.mul_mem (by simpa using hN.conj_mem _ hn h'⁻¹) hn',
by simp [← ha, ← hb, mul_assoc]⟩,
inv_mem' := λ x ⟨h, n, hh, hn, hx⟩,
⟨h⁻¹, h * n⁻¹ * h⁻¹, H.inv_mem hh, hN.conj_mem _ (N.inv_mem hn) h,
by rw [mul_assoc h, inv_mul_cancel_left, ← hx, mul_inv_rev]⟩ }
/-- The carrier of `H ⊔ N` is just `↑H * ↑N` (pointwise set product) when `N` is normal. -/
@[to_additive "The carrier of `H ⊔ N` is just `↑H + ↑N` (pointwise set addition)
when `N` is normal."]
lemma mul_normal (H N : subgroup G) [N.normal] : (↑(H ⊔ N) : set G) = H * N :=
set.subset.antisymm
(show H ⊔ N ≤ mul_normal_aux H N,
by { rw sup_eq_closure, apply Inf_le _, dsimp, refl })
((sup_eq_closure H N).symm ▸ subset_closure)
@[to_additive]
private def normal_mul_aux (N H : subgroup G) [hN : N.normal] : subgroup G :=
{ carrier := (N : set G) * H,
one_mem' := ⟨1, 1, N.one_mem, H.one_mem, by rw mul_one⟩,
mul_mem' := λ a b ⟨n, h, hn, hh, ha⟩ ⟨n', h', hn', hh', hb⟩,
⟨n * (h * n' * h⁻¹), h * h',
N.mul_mem hn (hN.conj_mem _ hn' _), H.mul_mem hh hh',
by simp [← ha, ← hb, mul_assoc]⟩,
inv_mem' := λ x ⟨n, h, hn, hh, hx⟩,
⟨h⁻¹ * n⁻¹ * h, h⁻¹,
by simpa using hN.conj_mem _ (N.inv_mem hn) h⁻¹, H.inv_mem hh,
by rw [mul_inv_cancel_right, ← mul_inv_rev, hx]⟩ }
/-- The carrier of `N ⊔ H` is just `↑N * ↑H` (pointwise set product) when `N` is normal. -/
@[to_additive "The carrier of `N ⊔ H` is just `↑N + ↑H` (pointwise set addition)
when `N` is normal."]
lemma normal_mul (N H : subgroup G) [N.normal] : (↑(N ⊔ H) : set G) = N * H :=
set.subset.antisymm
(show N ⊔ H ≤ normal_mul_aux N H,
by { rw sup_eq_closure, apply Inf_le _, dsimp, refl })
((sup_eq_closure N H).symm ▸ subset_closure)
end subgroup
end pointwise
/-! ### Actions by `subgroup`s
These are just copies of the definitions about `submonoid` starting from `submonoid.mul_action`.
-/
section actions
namespace subgroup
variables {α β : Type*}
/-- The action by a subgroup is the action by the underlying group. -/
@[to_additive /-"The additive action by an add_subgroup is the action by the underlying
add_group. "-/]
instance [mul_action G α] (S : subgroup G) : mul_action S α :=
S.to_submonoid.mul_action
@[to_additive]
lemma smul_def [mul_action G α] {S : subgroup G} (g : S) (m : α) : g • m = (g : G) • m := rfl
@[to_additive]
instance smul_comm_class_left
[mul_action G β] [has_scalar α β] [smul_comm_class G α β] (S : subgroup G) :
smul_comm_class S α β :=
S.to_submonoid.smul_comm_class_left
@[to_additive]
instance smul_comm_class_right
[has_scalar α β] [mul_action G β] [smul_comm_class α G β] (S : subgroup G) :
smul_comm_class α S β :=
S.to_submonoid.smul_comm_class_right
/-- Note that this provides `is_scalar_tower S G G` which is needed by `smul_mul_assoc`. -/
instance
[has_scalar α β] [mul_action G α] [mul_action G β] [is_scalar_tower G α β] (S : subgroup G) :
is_scalar_tower S α β :=
S.to_submonoid.is_scalar_tower
/-- The action by a subgroup is the action by the underlying group. -/
instance [add_monoid α] [distrib_mul_action G α] (S : subgroup G) : distrib_mul_action S α :=
S.to_submonoid.distrib_mul_action
end subgroup
end actions
|
25ec5d7e2877fbc1799ba8108199fbb423ef49f8 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/data/complex/module.lean | b9246960022e51936c04f7f7a2f6289b251297ee | [
"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 | 15,811 | lean | /-
Copyright (c) 2020 Alexander Bentkamp, Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alexander Bentkamp, Sébastien Gouëzel, Eric Wieser
-/
import algebra.order.smul
import data.complex.basic
import data.fin.vec_notation
import field_theory.tower
import algebra.char_p.invertible
/-!
# Complex number as a vector space over `ℝ`
This file contains the following instances:
* Any `•`-structure (`has_smul`, `mul_action`, `distrib_mul_action`, `module`, `algebra`) on
`ℝ` imbues a corresponding structure on `ℂ`. This includes the statement that `ℂ` is an `ℝ`
algebra.
* any complex vector space is a real vector space;
* any finite dimensional complex vector space is a finite dimensional real vector space;
* the space of `ℝ`-linear maps from a real vector space to a complex vector space is a complex
vector space.
It also defines bundled versions of four standard maps (respectively, the real part, the imaginary
part, the embedding of `ℝ` in `ℂ`, and the complex conjugate):
* `complex.re_lm` (`ℝ`-linear map);
* `complex.im_lm` (`ℝ`-linear map);
* `complex.of_real_am` (`ℝ`-algebra (homo)morphism);
* `complex.conj_ae` (`ℝ`-algebra equivalence).
It also provides a universal property of the complex numbers `complex.lift`, which constructs a
`ℂ →ₐ[ℝ] A` into any `ℝ`-algebra `A` given a square root of `-1`.
In addition, this file provides a decomposition into `real_part` and `imaginary_part` for any
element of a `star_module` over `ℂ`.
## Notation
* `ℜ` and `ℑ` for the `real_part` and `imaginary_part`, respectively, in the locale
`complex_star_module`.
-/
namespace complex
open_locale complex_conjugate
variables {R : Type*} {S : Type*}
section
variables [has_smul R ℝ]
/- The useless `0` multiplication in `smul` is to make sure that
`restrict_scalars.module ℝ ℂ ℂ = complex.module` definitionally. -/
instance : has_smul R ℂ :=
{ smul := λ r x, ⟨r • x.re - 0 * x.im, r • x.im + 0 * x.re⟩ }
lemma smul_re (r : R) (z : ℂ) : (r • z).re = r • z.re := by simp [(•)]
lemma smul_im (r : R) (z : ℂ) : (r • z).im = r • z.im := by simp [(•)]
@[simp] lemma real_smul {x : ℝ} {z : ℂ} : x • z = x * z := rfl
end
instance [has_smul R ℝ] [has_smul S ℝ] [smul_comm_class R S ℝ] : smul_comm_class R S ℂ :=
{ smul_comm := λ r s x, by ext; simp [smul_re, smul_im, smul_comm] }
instance [has_smul R S] [has_smul R ℝ] [has_smul S ℝ] [is_scalar_tower R S ℝ] :
is_scalar_tower R S ℂ :=
{ smul_assoc := λ r s x, by ext; simp [smul_re, smul_im, smul_assoc] }
instance [has_smul R ℝ] [has_smul Rᵐᵒᵖ ℝ] [is_central_scalar R ℝ] :
is_central_scalar R ℂ :=
{ op_smul_eq_smul := λ r x, by ext; simp [smul_re, smul_im, op_smul_eq_smul] }
instance [monoid R] [mul_action R ℝ] : mul_action R ℂ :=
{ one_smul := λ x, by ext; simp [smul_re, smul_im, one_smul],
mul_smul := λ r s x, by ext; simp [smul_re, smul_im, mul_smul] }
instance [semiring R] [distrib_mul_action R ℝ] : distrib_mul_action R ℂ :=
{ smul_add := λ r x y, by ext; simp [smul_re, smul_im, smul_add],
smul_zero := λ r, by ext; simp [smul_re, smul_im, smul_zero] }
instance [semiring R] [module R ℝ] : module R ℂ :=
{ add_smul := λ r s x, by ext; simp [smul_re, smul_im, add_smul],
zero_smul := λ r, by ext; simp [smul_re, smul_im, zero_smul] }
instance [comm_semiring R] [algebra R ℝ] : algebra R ℂ :=
{ smul := (•),
smul_def' := λ r x, by ext; simp [smul_re, smul_im, algebra.smul_def],
commutes' := λ r ⟨xr, xi⟩, by ext; simp [smul_re, smul_im, algebra.commutes],
..complex.of_real.comp (algebra_map R ℝ) }
instance : star_module ℝ ℂ :=
⟨λ r x, by simp only [star_def, star_trivial, real_smul, map_mul, conj_of_real]⟩
@[simp] lemma coe_algebra_map : (algebra_map ℝ ℂ : ℝ → ℂ) = coe := rfl
section
variables {A : Type*} [semiring A] [algebra ℝ A]
/-- We need this lemma since `complex.coe_algebra_map` diverts the simp-normal form away from
`alg_hom.commutes`. -/
@[simp] lemma _root_.alg_hom.map_coe_real_complex (f : ℂ →ₐ[ℝ] A) (x : ℝ) :
f x = algebra_map ℝ A x :=
f.commutes x
/-- Two `ℝ`-algebra homomorphisms from ℂ are equal if they agree on `complex.I`. -/
@[ext]
lemma alg_hom_ext ⦃f g : ℂ →ₐ[ℝ] A⦄ (h : f I = g I) : f = g :=
begin
ext ⟨x, y⟩,
simp only [mk_eq_add_mul_I, alg_hom.map_add, alg_hom.map_coe_real_complex, alg_hom.map_mul, h]
end
end
section
open_locale complex_order
protected lemma ordered_smul : ordered_smul ℝ ℂ :=
ordered_smul.mk' $ λ a b r hab hr, ⟨by simp [hr, hab.1.le], by simp [hab.2]⟩
localized "attribute [instance] complex.ordered_smul" in complex_order
end
open submodule finite_dimensional
/-- `ℂ` has a basis over `ℝ` given by `1` and `I`. -/
noncomputable def basis_one_I : basis (fin 2) ℝ ℂ :=
basis.of_equiv_fun
{ to_fun := λ z, ![z.re, z.im],
inv_fun := λ c, c 0 + c 1 • I,
left_inv := λ z, by simp,
right_inv := λ c, by { ext i, fin_cases i; simp },
map_add' := λ z z', by simp,
-- why does `simp` not know how to apply `smul_cons`, which is a `@[simp]` lemma, here?
map_smul' := λ c z, by simp [matrix.smul_cons c z.re, matrix.smul_cons c z.im] }
@[simp] lemma coe_basis_one_I_repr (z : ℂ) : ⇑(basis_one_I.repr z) = ![z.re, z.im] := rfl
@[simp] lemma coe_basis_one_I : ⇑basis_one_I = ![1, I] :=
funext $ λ i, basis.apply_eq_iff.mpr $ finsupp.ext $ λ j,
by fin_cases i; fin_cases j;
simp only [coe_basis_one_I_repr, finsupp.single_eq_same, finsupp.single_eq_of_ne,
matrix.cons_val_zero, matrix.cons_val_one, matrix.head_cons,
nat.one_ne_zero, fin.one_eq_zero_iff, fin.zero_eq_one_iff, ne.def, not_false_iff,
one_re, one_im, I_re, I_im]
instance : finite_dimensional ℝ ℂ := of_fintype_basis basis_one_I
@[simp] lemma finrank_real_complex : finite_dimensional.finrank ℝ ℂ = 2 :=
by rw [finrank_eq_card_basis basis_one_I, fintype.card_fin]
@[simp] lemma dim_real_complex : module.rank ℝ ℂ = 2 :=
by simp [← finrank_eq_dim, finrank_real_complex]
lemma {u} dim_real_complex' : cardinal.lift.{u} (module.rank ℝ ℂ) = 2 :=
by simp [← finrank_eq_dim, finrank_real_complex, bit0]
/-- `fact` version of the dimension of `ℂ` over `ℝ`, locally useful in the definition of the
circle. -/
lemma finrank_real_complex_fact : fact (finrank ℝ ℂ = 2) := ⟨finrank_real_complex⟩
end complex
/- Register as an instance (with low priority) the fact that a complex vector space is also a real
vector space. -/
@[priority 900]
instance module.complex_to_real (E : Type*) [add_comm_group E] [module ℂ E] : module ℝ E :=
restrict_scalars.module ℝ ℂ E
instance module.real_complex_tower (E : Type*) [add_comm_group E] [module ℂ E] :
is_scalar_tower ℝ ℂ E :=
restrict_scalars.is_scalar_tower ℝ ℂ E
@[simp, norm_cast] lemma complex.coe_smul {E : Type*} [add_comm_group E] [module ℂ E]
(x : ℝ) (y : E) :
(x : ℂ) • y = x • y :=
rfl
@[priority 100]
instance finite_dimensional.complex_to_real (E : Type*) [add_comm_group E] [module ℂ E]
[finite_dimensional ℂ E] : finite_dimensional ℝ E :=
finite_dimensional.trans ℝ ℂ E
lemma dim_real_of_complex (E : Type*) [add_comm_group E] [module ℂ E] :
module.rank ℝ E = 2 * module.rank ℂ E :=
cardinal.lift_inj.1 $
by { rw [← dim_mul_dim' ℝ ℂ E, complex.dim_real_complex], simp [bit0] }
lemma finrank_real_of_complex (E : Type*) [add_comm_group E] [module ℂ E] :
finite_dimensional.finrank ℝ E = 2 * finite_dimensional.finrank ℂ E :=
by rw [← finite_dimensional.finrank_mul_finrank ℝ ℂ E, complex.finrank_real_complex]
@[priority 900]
instance star_module.complex_to_real {E : Type*} [add_comm_group E] [has_star E] [module ℂ E]
[star_module ℂ E] : star_module ℝ E :=
⟨λ r a, by rw [star_trivial r, restrict_scalars_smul_def, restrict_scalars_smul_def, star_smul,
complex.coe_algebra_map, complex.star_def, complex.conj_of_real]⟩
namespace complex
open_locale complex_conjugate
/-- Linear map version of the real part function, from `ℂ` to `ℝ`. -/
def re_lm : ℂ →ₗ[ℝ] ℝ :=
{ to_fun := λx, x.re,
map_add' := add_re,
map_smul' := by simp, }
@[simp] lemma re_lm_coe : ⇑re_lm = re := rfl
/-- Linear map version of the imaginary part function, from `ℂ` to `ℝ`. -/
def im_lm : ℂ →ₗ[ℝ] ℝ :=
{ to_fun := λx, x.im,
map_add' := add_im,
map_smul' := by simp, }
@[simp] lemma im_lm_coe : ⇑im_lm = im := rfl
/-- `ℝ`-algebra morphism version of the canonical embedding of `ℝ` in `ℂ`. -/
def of_real_am : ℝ →ₐ[ℝ] ℂ := algebra.of_id ℝ ℂ
@[simp] lemma of_real_am_coe : ⇑of_real_am = coe := rfl
/-- `ℝ`-algebra isomorphism version of the complex conjugation function from `ℂ` to `ℂ` -/
def conj_ae : ℂ ≃ₐ[ℝ] ℂ :=
{ inv_fun := conj,
left_inv := star_star,
right_inv := star_star,
commutes' := conj_of_real,
.. conj }
@[simp] lemma conj_ae_coe : ⇑conj_ae = conj := rfl
/-- The matrix representation of `conj_ae`. -/
@[simp] lemma to_matrix_conj_ae :
linear_map.to_matrix basis_one_I basis_one_I conj_ae.to_linear_map = !![1, 0; 0, -1] :=
begin
ext i j,
simp [linear_map.to_matrix_apply],
fin_cases i; fin_cases j; simp
end
/-- The identity and the complex conjugation are the only two `ℝ`-algebra homomorphisms of `ℂ`. -/
lemma real_alg_hom_eq_id_or_conj (f : ℂ →ₐ[ℝ] ℂ) : f = alg_hom.id ℝ ℂ ∨ f = conj_ae :=
begin
refine (eq_or_eq_neg_of_sq_eq_sq (f I) I $ by rw [← map_pow, I_sq, map_neg, map_one]).imp _ _;
refine λ h, alg_hom_ext _,
exacts [h, conj_I.symm ▸ h],
end
section lift
variables {A : Type*} [ring A] [algebra ℝ A]
/-- There is an alg_hom from `ℂ` to any `ℝ`-algebra with an element that squares to `-1`.
See `complex.lift` for this as an equiv. -/
def lift_aux (I' : A) (hf : I' * I' = -1) : ℂ →ₐ[ℝ] A :=
alg_hom.of_linear_map
((algebra.of_id ℝ A).to_linear_map.comp re_lm + (linear_map.to_span_singleton _ _ I').comp im_lm)
(show algebra_map ℝ A 1 + (0 : ℝ) • I' = 1,
by rw [ring_hom.map_one, zero_smul, add_zero])
(λ ⟨x₁, y₁⟩ ⟨x₂, y₂⟩, show algebra_map ℝ A (x₁ * x₂ - y₁ * y₂) + (x₁ * y₂ + y₁ * x₂) • I'
= (algebra_map ℝ A x₁ + y₁ • I') * (algebra_map ℝ A x₂ + y₂ • I'),
begin
rw [add_mul, mul_add, mul_add, add_comm _ (y₁ • I' * y₂ • I'), add_add_add_comm],
congr' 1, -- equate "real" and "imaginary" parts
{ rw [smul_mul_smul, hf, smul_neg, ←algebra.algebra_map_eq_smul_one, ←sub_eq_add_neg,
←ring_hom.map_mul, ←ring_hom.map_sub], },
{ rw [algebra.smul_def, algebra.smul_def, algebra.smul_def, ←algebra.right_comm _ x₂,
←mul_assoc, ←add_mul, ←ring_hom.map_mul, ←ring_hom.map_mul, ←ring_hom.map_add] }
end)
@[simp]
lemma lift_aux_apply (I' : A) (hI') (z : ℂ) :
lift_aux I' hI' z = algebra_map ℝ A z.re + z.im • I' := rfl
lemma lift_aux_apply_I (I' : A) (hI') : lift_aux I' hI' I = I' := by simp
/-- A universal property of the complex numbers, providing a unique `ℂ →ₐ[ℝ] A` for every element
of `A` which squares to `-1`.
This can be used to embed the complex numbers in the `quaternion`s.
This isomorphism is named to match the very similar `zsqrtd.lift`. -/
@[simps {simp_rhs := tt}]
def lift : {I' : A // I' * I' = -1} ≃ (ℂ →ₐ[ℝ] A) :=
{ to_fun := λ I', lift_aux I' I'.prop,
inv_fun := λ F, ⟨F I, by rw [←F.map_mul, I_mul_I, alg_hom.map_neg, alg_hom.map_one]⟩,
left_inv := λ I', subtype.ext $ lift_aux_apply_I I' I'.prop,
right_inv := λ F, alg_hom_ext $ lift_aux_apply_I _ _, }
/- When applied to `complex.I` itself, `lift` is the identity. -/
@[simp]
lemma lift_aux_I : lift_aux I I_mul_I = alg_hom.id ℝ ℂ :=
alg_hom_ext $ lift_aux_apply_I _ _
/- When applied to `-complex.I`, `lift` is conjugation, `conj`. -/
@[simp]
lemma lift_aux_neg_I : lift_aux (-I) ((neg_mul_neg _ _).trans I_mul_I) = conj_ae :=
alg_hom_ext $ (lift_aux_apply_I _ _).trans conj_I.symm
end lift
end complex
section real_imaginary_part
open complex
variables {A : Type*} [add_comm_group A] [module ℂ A] [star_add_monoid A] [star_module ℂ A]
/-- Create a `self_adjoint` element from a `skew_adjoint` element by multiplying by the scalar
`-complex.I`. -/
@[simps] def skew_adjoint.neg_I_smul : skew_adjoint A →ₗ[ℝ] self_adjoint A :=
{ to_fun := λ a, ⟨-I • a, by simp only [self_adjoint.mem_iff, neg_smul, star_neg, star_smul,
star_def, conj_I, skew_adjoint.star_coe_eq, neg_smul_neg]⟩,
map_add' := λ a b, by { ext, simp only [add_subgroup.coe_add, smul_add, add_mem_class.mk_add_mk]},
map_smul' := λ a b, by { ext, simp only [neg_smul, skew_adjoint.coe_smul, add_subgroup.coe_mk,
ring_hom.id_apply, self_adjoint.coe_smul, smul_neg, neg_inj], rw smul_comm, } }
lemma skew_adjoint.I_smul_neg_I (a : skew_adjoint A) :
I • (skew_adjoint.neg_I_smul a : A) = a :=
by simp only [smul_smul, skew_adjoint.neg_I_smul_apply_coe, neg_smul, smul_neg, I_mul_I, one_smul,
neg_neg]
/-- The real part `ℜ a` of an element `a` of a star module over `ℂ`, as a linear map. This is just
`self_adjoint_part ℝ`, but we provide it as a separate definition in order to link it with lemmas
concerning the `imaginary_part`, which doesn't exist in star modules over other rings. -/
noncomputable def real_part : A →ₗ[ℝ] self_adjoint A := self_adjoint_part ℝ
/-- The imaginary part `ℑ a` of an element `a` of a star module over `ℂ`, as a linear map into the
self adjoint elements. In a general star module, we have a decomposition into the `self_adjoint`
and `skew_adjoint` parts, but in a star module over `ℂ` we have
`real_part_add_I_smul_imaginary_part`, which allows us to decompose into a linear combination of
`self_adjoint`s. -/
noncomputable
def imaginary_part : A →ₗ[ℝ] self_adjoint A := skew_adjoint.neg_I_smul.comp (skew_adjoint_part ℝ)
localized "notation `ℜ` := real_part" in complex_star_module
localized "notation `ℑ` := imaginary_part" in complex_star_module
@[simp] lemma real_part_apply_coe (a : A) :
(ℜ a : A) = (2 : ℝ)⁻¹ • (a + star a) :=
by { unfold real_part, simp only [self_adjoint_part_apply_coe, inv_of_eq_inv]}
@[simp] lemma imaginary_part_apply_coe (a : A) :
(ℑ a : A) = -I • (2 : ℝ)⁻¹ • (a - star a) :=
begin
unfold imaginary_part,
simp only [linear_map.coe_comp, skew_adjoint.neg_I_smul_apply_coe, skew_adjoint_part_apply_coe,
inv_of_eq_inv],
end
/-- The standard decomposition of `ℜ a + complex.I • ℑ a = a` of an element of a star module over
`ℂ` into a linear combination of self adjoint elements. -/
lemma real_part_add_I_smul_imaginary_part (a : A) : (ℜ a + I • ℑ a : A) = a :=
by simpa only [smul_smul, real_part_apply_coe, imaginary_part_apply_coe, neg_smul, I_mul_I,
one_smul, neg_sub, add_add_sub_cancel, smul_sub, smul_add, neg_sub_neg, inv_of_eq_inv]
using inv_of_two_smul_add_inv_of_two_smul ℝ a
@[simp] lemma real_part_I_smul (a : A) : ℜ (I • a) = - ℑ a :=
by { ext, simp [smul_comm I, smul_sub, sub_eq_add_neg, add_comm] }
@[simp] lemma imaginary_part_I_smul (a : A) : ℑ (I • a) = ℜ a :=
by { ext, simp [smul_comm I, smul_smul I] }
lemma real_part_smul (z : ℂ) (a : A) : ℜ (z • a) = z.re • ℜ a - z.im • ℑ a :=
by { nth_rewrite 0 ←re_add_im z, simp [-re_add_im, add_smul, ←smul_smul, sub_eq_add_neg] }
lemma imaginary_part_smul (z : ℂ) (a : A) : ℑ (z • a) = z.re • ℑ a + z.im • ℜ a :=
by { nth_rewrite 0 ←re_add_im z, simp [-re_add_im, add_smul, ←smul_smul] }
end real_imaginary_part
|
665f5be9298790b02925439c8b835122e3b0bd83 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/topology/algebra/algebra.lean | b484baf2e78cfd89a8dcdc21922c275f1fc0a91c | [
"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 | 6,061 | 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.algebra.subalgebra.basic
import topology.algebra.module.basic
import topology.algebra.field
/-!
# Topological (sub)algebras
A topological algebra over a topological semiring `R` is a topological semiring with a compatible
continuous scalar multiplication by elements of `R`. We reuse typeclass `has_continuous_smul` for
topological algebras.
## Results
This is just a minimal stub for now!
The topological closure of a subalgebra is still a subalgebra,
which as an algebra is a topological algebra.
-/
open classical set topological_space algebra
open_locale classical
universes u v w
section topological_algebra
variables (R : Type*) [topological_space R] [comm_semiring R]
variables (A : Type u) [topological_space A]
variables [semiring A]
lemma continuous_algebra_map_iff_smul [algebra R A] [topological_semiring A] :
continuous (algebra_map R A) ↔ continuous (λ p : R × A, p.1 • p.2) :=
begin
refine ⟨λ h, _, λ h, _⟩,
{ simp only [algebra.smul_def], exact (h.comp continuous_fst).mul continuous_snd },
{ rw algebra_map_eq_smul_one', exact h.comp (continuous_id.prod_mk continuous_const) }
end
@[continuity]
lemma continuous_algebra_map [algebra R A] [topological_semiring A] [has_continuous_smul R A] :
continuous (algebra_map R A) :=
(continuous_algebra_map_iff_smul R A).2 continuous_smul
lemma has_continuous_smul_of_algebra_map [algebra R A] [topological_semiring A]
(h : continuous (algebra_map R A)) :
has_continuous_smul R A :=
⟨(continuous_algebra_map_iff_smul R A).1 h⟩
end topological_algebra
section topological_algebra
variables {R : Type*} [comm_semiring R]
variables {A : Type u} [topological_space A]
variables [semiring A]
variables [algebra R A] [topological_semiring A]
/-- The closure of a subalgebra in a topological algebra as a subalgebra. -/
def subalgebra.topological_closure (s : subalgebra R A) : subalgebra R A :=
{ carrier := closure (s : set A),
algebra_map_mem' := λ r, s.to_subsemiring.subring_topological_closure (s.algebra_map_mem r),
.. s.to_subsemiring.topological_closure }
@[simp] lemma subalgebra.topological_closure_coe (s : subalgebra R A) :
(s.topological_closure : set A) = closure (s : set A) :=
rfl
instance subalgebra.topological_closure_topological_semiring (s : subalgebra R A) :
topological_semiring (s.topological_closure) :=
s.to_subsemiring.topological_closure_topological_semiring
instance subalgebra.topological_closure_topological_algebra
[topological_space R] [has_continuous_smul R A] (s : subalgebra R A) :
has_continuous_smul R (s.topological_closure) :=
s.to_submodule.topological_closure_has_continuous_smul
lemma subalgebra.subalgebra_topological_closure (s : subalgebra R A) :
s ≤ s.topological_closure :=
subset_closure
lemma subalgebra.is_closed_topological_closure (s : subalgebra R A) :
is_closed (s.topological_closure : set A) :=
by convert is_closed_closure
lemma subalgebra.topological_closure_minimal
(s : subalgebra R A) {t : subalgebra R A} (h : s ≤ t) (ht : is_closed (t : set A)) :
s.topological_closure ≤ t :=
closure_minimal h ht
/-- If a subalgebra of a topological algebra is commutative, then so is its topological closure. -/
def subalgebra.comm_semiring_topological_closure [t2_space A] (s : subalgebra R A)
(hs : ∀ (x y : s), x * y = y * x) : comm_semiring s.topological_closure :=
{ ..s.topological_closure.to_semiring,
..s.to_submonoid.comm_monoid_topological_closure hs }
/--
This is really a statement about topological algebra isomorphisms,
but we don't have those, so we use the clunky approach of talking about
an algebra homomorphism, and a separate homeomorphism,
along with a witness that as functions they are the same.
-/
lemma subalgebra.topological_closure_comap_homeomorph
(s : subalgebra R A)
{B : Type*} [topological_space B] [ring B] [topological_ring B] [algebra R B]
(f : B →ₐ[R] A) (f' : B ≃ₜ A) (w : (f : B → A) = f') :
s.topological_closure.comap f = (s.comap f).topological_closure :=
begin
apply set_like.ext',
simp only [subalgebra.topological_closure_coe],
simp only [subalgebra.coe_comap, subsemiring.coe_comap, alg_hom.coe_to_ring_hom],
rw [w],
exact f'.preimage_closure _,
end
end topological_algebra
section ring
variables {R : Type*} [comm_ring R]
variables {A : Type u} [topological_space A]
variables [ring A]
variables [algebra R A] [topological_ring A]
/-- If a subalgebra of a topological algebra is commutative, then so is its topological closure.
See note [reducible non-instances]. -/
@[reducible] def subalgebra.comm_ring_topological_closure [t2_space A] (s : subalgebra R A)
(hs : ∀ (x y : s), x * y = y * x) : comm_ring s.topological_closure :=
{ ..s.topological_closure.to_ring,
..s.to_submonoid.comm_monoid_topological_closure hs }
variables (R)
/-- The topological closure of the subalgebra generated by a single element. -/
def algebra.elemental_algebra (x : A) : subalgebra R A :=
(algebra.adjoin R ({x} : set A)).topological_closure
lemma algebra.self_mem_elemental_algebra (x : A) : x ∈ algebra.elemental_algebra R x :=
set_like.le_def.mp (subalgebra.subalgebra_topological_closure (algebra.adjoin R ({x} : set A))) $
algebra.self_mem_adjoin_singleton R x
variables {R}
instance [t2_space A] {x : A} : comm_ring (algebra.elemental_algebra R x) :=
subalgebra.comm_ring_topological_closure _
begin
letI : comm_ring (algebra.adjoin R ({x} : set A)) := algebra.adjoin_comm_ring_of_comm R
(λ y hy z hz, by {rw [mem_singleton_iff] at hy hz, rw [hy, hz]}),
exact λ _ _, mul_comm _ _,
end
end ring
section division_ring
/-- The action induced by `algebra_rat` is continuous. -/
instance division_ring.has_continuous_const_smul_rat
{A} [division_ring A] [topological_space A] [has_continuous_mul A] [char_zero A] :
has_continuous_const_smul ℚ A :=
⟨λ r, continuous_const.mul continuous_id⟩
end division_ring
|
b3c52d0df51ee307243cafa514e3d022bc89e4bc | 54deab7025df5d2df4573383df7e1e5497b7a2c2 | /data/set/prod.lean | 93906ece7575bf76b883ecf3244628a49ee3f2c4 | [
"Apache-2.0"
] | permissive | HGldJ1966/mathlib | f8daac93a5b4ae805cfb0ecebac21a9ce9469009 | c5c5b504b918a6c5e91e372ee29ed754b0513e85 | refs/heads/master | 1,611,340,395,683 | 1,503,040,489,000 | 1,503,040,489,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,205 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl
-/
import data.set.lattice data.prod
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
variables {s s₁ s₂ : set α} {t t₁ t₂ : set β}
namespace set
protected def prod (s : set α) (t : set β) : set (α × β) :=
{p | p.1 ∈ s ∧ p.2 ∈ t}
lemma mem_prod_eq {p : α × β} : p ∈ set.prod s t = (p.1 ∈ s ∧ p.2 ∈ t) :=
rfl
theorem prod_preimage_eq {f : γ → α} {g : δ → β} :
set.prod (preimage f s) (preimage g t) = preimage (λp, (f p.1, g p.2)) (set.prod s t) := rfl
lemma prod_mono {s₁ s₂ : set α} {t₁ t₂ : set β} (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) :
set.prod s₁ t₁ ⊆ set.prod s₂ t₂ :=
assume x ⟨h₁, h₂⟩, ⟨hs h₁, ht h₂⟩
lemma prod_inter_prod : set.prod s₁ t₁ ∩ set.prod s₂ t₂ = set.prod (s₁ ∩ s₂) (t₁ ∩ t₂) :=
subset.antisymm
(assume ⟨a, b⟩ ⟨⟨ha₁, hb₁⟩, ⟨ha₂, hb₂⟩⟩, ⟨⟨ha₁, ha₂⟩, ⟨hb₁, hb₂⟩⟩)
(subset_inter
(prod_mono (inter_subset_left _ _) (inter_subset_left _ _))
(prod_mono (inter_subset_right _ _) (inter_subset_right _ _)))
theorem monotone_prod [preorder α] {f : α → set β} {g : α → set γ}
(hf : monotone f) (hg : monotone g) : monotone (λx, set.prod (f x) (g x)) :=
assume a b h, prod_mono (hf h) (hg h)
lemma image_swap_prod : (λp:β×α, (p.2, p.1)) '' set.prod t s = set.prod s t :=
set.ext $ assume ⟨a, b⟩, by simp [mem_image_eq, set.prod]; exact
⟨ assume ⟨b', a', h_a, h_b, h⟩, by rw [h_a, h_b] at h; assumption,
assume ⟨ha, hb⟩, ⟨b, a, rfl, rfl, ⟨ha, hb⟩⟩⟩
theorem image_swap_eq_preimage_swap : image (@prod.swap α β) = preimage prod.swap :=
image_eq_preimage_of_inverse (@prod.swap α β) (@prod.swap β α)
begin simp; intros; trivial end
begin simp; intros; trivial end
lemma prod_image_image_eq {m₁ : α → γ} {m₂ : β → δ} :
set.prod (image m₁ s) (image m₂ t) = image (λp:α×β, (m₁ p.1, m₂ p.2)) (set.prod s t) :=
set.ext $ assume ⟨b₁, b₂⟩,
⟨assume ⟨⟨a₁, ha₁, (eq₁ : m₁ a₁ = b₁)⟩, ⟨a₂, ha₂, (eq₂ : m₂ a₂ = b₂)⟩⟩,
mem_image
(show (a₁, a₂) ∈ set.prod s t, from ⟨ha₁, ha₂⟩)
(by simp [eq₁, eq₂]),
assume ⟨⟨a₁, a₂⟩, ⟨ha₁, ha₂⟩, eq⟩, eq ▸ ⟨mem_image_of_mem m₁ ha₁, mem_image_of_mem m₂ ha₂⟩⟩
@[simp] lemma prod_singleton_singleton {a : α} {b : β} :
set.prod {a} {b} = ({(a, b)} : set (α×β)) :=
set.ext $ assume ⟨a', b'⟩, by simp [set.prod]
lemma prod_neq_empty_iff {s : set α} {t : set β} :
set.prod s t ≠ ∅ ↔ (s ≠ ∅ ∧ t ≠ ∅) :=
begin
rw [ne_empty_iff_exists_mem, ne_empty_iff_exists_mem, ne_empty_iff_exists_mem,
prod.exists],
exact ⟨assume ⟨a, b, ha, hb⟩, ⟨⟨a, ha⟩, ⟨b, hb⟩⟩,
assume ⟨⟨a, ha⟩, ⟨b, hb⟩⟩, ⟨a, b, ha, hb⟩⟩
end
@[simp] lemma prod_mk_mem_set_prod_eq {a : α} {b : β} {s : set α} {t : set β} :
(a, b) ∈ set.prod s t = (a ∈ s ∧ b ∈ t) := rfl
end set |
6d52b80ec7a3820f4e278a1e1bd05b612c23ad05 | 218e2afdf9209a5f82db7ac0089f79064e52bd80 | /lean/src/test.lean | 55bc3913fc79010e56e40c4a478c7a3937985388 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | mk12/analysis-i | 1f022e81cdc5cae5b25360f93000186874e1d02b | e85deae5441f705d9284eeb204c9c3ecb450c93a | refs/heads/main | 1,637,808,582,073 | 1,636,857,479,000 | 1,636,857,479,000 | 67,387,570 | 8 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 497 | lean | import standard
open eq.ops
open nat classical set
check sigma.
-- Axiom of specification for Mem
-- section specification
-- parameters {X : Set} (P : Mem X → Prop)
-- definition specify_mem : Set :=
-- λ x, x ∈ X ∧ ∀ Hx : x ∈ X, P (Mem.mk Hx)
-- definition specify_mem_subset : specify_mem ⊆ X :=
-- take x,
-- suppose x ∈ specify_mem,
-- show x ∈ X, from and.left this
-- end specification
check trivial
find_decl (_ → (_ → _))
|
b68bc4782154e4120a94f803be77da6ab99b5480 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/rewrite9.lean | 25403496520c02fc2f4a5ed0111abda8fd09e05f | [
"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 | 200 | lean | import data.nat
open nat
constant f : nat → nat
theorem tst1 (x y : nat) (H1 : (λ z, z + 0) x = y) (H2 : x = y + 0) (H3 : x = y * 0) : f x = f y :=
begin
rewrite [▸ x = y at (H1, H2), H2]
end
|
149903ed0d856591df0e478a4f0db593bc0c1e29 | 491068d2ad28831e7dade8d6dff871c3e49d9431 | /tests/lean/coe.lean | 758f8b098c8e2195dd1e6bd60de9be722a0bfd5f | [
"Apache-2.0"
] | permissive | davidmueller13/lean | 65a3ed141b4088cd0a268e4de80eb6778b21a0e9 | c626e2e3c6f3771e07c32e82ee5b9e030de5b050 | refs/heads/master | 1,611,278,313,401 | 1,444,021,177,000 | 1,444,021,177,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 251 | lean | import logic
set_option pp.notation false
inductive Functor :=
mk : (Π (A B : Type), A → B) → Functor
definition Functor.to_fun [coercion] (f : Functor) {A B : Type} : A → B :=
Functor.rec (λ f, f) f A B
constant f : Functor
check f 0 = 0
|
8061b697d548e0619a5ab5097594ac6733d0c948 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /src/Init/WFTactics.lean | e019a077e3cdd725f2609b87d6291fa18b8adac5 | [
"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 | 2,578 | lean | /-
Copyright (c) 2022 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import Init.SizeOf
import Init.WF
/-- Unfold definitions commonly used in well founded relation definitions.
This is primarily intended for internal use in `decreasing_tactic`. -/
macro "simp_wf" : tactic =>
`(simp [invImage, InvImage, Prod.lex, sizeOfWFRel,
measure, Nat.lt_wfRel, WellFoundedRelation.rel])
/-- Extensible helper tactic for `decreasing_tactic`. This handles the "base case"
reasoning after applying lexicographic order lemmas.
It can be extended by adding more macro definitions, e.g.
```
macro_rules | `(tactic| decreasing_trivial) => `(tactic| linarith)
```
-/
syntax "decreasing_trivial" : tactic
macro_rules | `(tactic| decreasing_trivial) => `(tactic| simp (config := { arith := true }); done)
macro_rules | `(tactic| decreasing_trivial) => `(tactic| assumption)
macro_rules | `(tactic| decreasing_trivial) => `(tactic| apply Nat.sub_succ_lt_self; assumption) -- a - (i+1) < a - i if i < a
macro_rules | `(tactic| decreasing_trivial) => `(tactic| apply Nat.pred_lt'; assumption) -- i-1 < i if j < i
macro_rules | `(tactic| decreasing_trivial) => `(tactic| apply Nat.pred_lt; assumption) -- i-1 < i if i ≠ 0
/-- Constructs a proof of decreasing along a well founded relation, by applying
lexicographic order lemmas and using `ts` to solve the base case. If it fails,
it prints a message to help the user diagnose an ill-founded recursive definition. -/
macro "decreasing_with " ts:tacticSeq : tactic =>
`((simp_wf
repeat (first | apply Prod.Lex.right | apply Prod.Lex.left)
repeat (first | apply PSigma.Lex.right | apply PSigma.Lex.left)
first
| $ts
| fail "failed to prove termination, possible solutions:
- Use `have`-expressions to prove the remaining goals
- Use `termination_by` to specify a different well-founded relation
- Use `decreasing_by` to specify your own tactic for discharging this kind of goal"))
/-- `decreasing_tactic` is called by default on well-founded recursions in order
to synthesize a proof that recursive calls decrease along the selected
well founded relation. It can be locally overridden by using `decreasing_by tac`
on the recursive definition, and it can also be globally extended by adding
more definitions for `decreasing_tactic` (or `decreasing_trivial`,
which this tactic calls). -/
macro "decreasing_tactic" : tactic =>
`(decreasing_with first | decreasing_trivial | subst_vars; decreasing_trivial)
|
6d43c3606c1f6090ae97d55f10394d37847a8a4c | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/topology/category/TopCommRing.lean | c5b2e678d71c2ac1e66ab01df505044a7d60a265 | [
"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 | 3,531 | 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 algebra.category.CommRing.basic
import topology.category.Top.basic
import topology.algebra.ring
/-!
# Category of topological commutative rings
We introduce the category `TopCommRing` of topological commutative rings together with the relevant
forgetful functors to topological spaces and commutative rings.
-/
universes u
open category_theory
/-- A bundled topological commutative ring. -/
structure TopCommRing :=
(α : Type u)
[is_comm_ring : comm_ring α]
[is_topological_space : topological_space α]
[is_topological_ring : topological_ring α]
namespace TopCommRing
instance : has_coe_to_sort TopCommRing :=
{ S := Type u, coe := TopCommRing.α }
attribute [instance] is_comm_ring is_topological_space is_topological_ring
instance : category TopCommRing.{u} :=
{ hom := λ R S, {f : R →+* S // continuous f },
id := λ R, ⟨ring_hom.id R, by obviously⟩, -- TODO remove obviously?
comp := λ R S T f g, ⟨g.val.comp f.val,
begin -- TODO automate
cases f, cases g,
dsimp, apply continuous.comp ; assumption
end⟩ }
instance : concrete_category TopCommRing.{u} :=
{ forget := { obj := λ R, R, map := λ R S f, f.val },
forget_faithful := { } }
/-- Construct a bundled `TopCommRing` from the underlying type and the appropriate typeclasses. -/
def of (X : Type u) [comm_ring X] [topological_space X] [topological_ring X] : TopCommRing := ⟨X⟩
@[simp] lemma coe_of (X : Type u) [comm_ring X] [topological_space X] [topological_ring X] :
(of X : Type u) = X := rfl
instance forget_topological_space (R : TopCommRing) :
topological_space ((forget TopCommRing).obj R) :=
R.is_topological_space
instance forget_comm_ring (R : TopCommRing) :
comm_ring ((forget TopCommRing).obj R) :=
R.is_comm_ring
instance forget_topological_ring (R : TopCommRing) :
topological_ring ((forget TopCommRing).obj R) :=
R.is_topological_ring
instance has_forget_to_CommRing : has_forget₂ TopCommRing CommRing :=
has_forget₂.mk'
(λ R, CommRing.of R)
(λ x, rfl)
(λ R S f, f.val)
(λ R S f, heq.rfl)
instance forget_to_CommRing_topological_space (R : TopCommRing) :
topological_space ((forget₂ TopCommRing CommRing).obj R) :=
R.is_topological_space
/-- The forgetful functor to Top. -/
instance has_forget_to_Top : has_forget₂ TopCommRing Top :=
has_forget₂.mk'
(λ R, Top.of R)
(λ x, rfl)
(λ R S f, ⟨⇑f.1, f.2⟩)
(λ R S f, heq.rfl)
instance forget_to_Top_comm_ring (R : TopCommRing) :
comm_ring ((forget₂ TopCommRing Top).obj R) :=
R.is_comm_ring
instance forget_to_Top_topological_ring (R : TopCommRing) :
topological_ring ((forget₂ TopCommRing Top).obj R) :=
R.is_topological_ring
/--
The forgetful functors to `Type` do not reflect isomorphisms,
but the forgetful functor from `TopCommRing` to `Top` does.
-/
instance : reflects_isomorphisms (forget₂ TopCommRing Top) :=
{ reflects := λ X Y f _,
begin
resetI,
-- We have an isomorphism in `Top`,
let i_Top := as_iso ((forget₂ TopCommRing Top).map f),
-- and a `ring_equiv`.
let e_Ring : X ≃+* Y := { ..f.1, ..((forget Top).map_iso i_Top).to_equiv },
-- Putting these together we obtain the isomorphism we're after:
exact
⟨⟨⟨e_Ring.symm, i_Top.inv.2⟩,
⟨by { ext x, exact e_Ring.left_inv x, }, by { ext x, exact e_Ring.right_inv x, }⟩⟩⟩
end }
end TopCommRing
|
9c2dbb30e34872e7a55c7a4a90c232330bd7239f | 07c6143268cfb72beccd1cc35735d424ebcb187b | /src/data/real/basic.lean | 090cdc60e421003d65d9219aee89753f96ad1b7a | [
"Apache-2.0"
] | permissive | khoek/mathlib | bc49a842910af13a3c372748310e86467d1dc766 | aa55f8b50354b3e11ba64792dcb06cccb2d8ee28 | refs/heads/master | 1,588,232,063,837 | 1,587,304,803,000 | 1,587,304,803,000 | 176,688,517 | 0 | 0 | Apache-2.0 | 1,553,070,585,000 | 1,553,070,585,000 | null | UTF-8 | Lean | false | false | 26,276 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Floris van Doorn
The (classical) real numbers ℝ. This is a direct construction
from Cauchy sequences.
-/
import order.conditionally_complete_lattice data.real.cau_seq_completion
algebra.archimedean order.bounds
def real := @cau_seq.completion.Cauchy ℚ _ _ _ abs _
notation `ℝ` := real
namespace real
open cau_seq cau_seq.completion
variables {x y : ℝ}
def comm_ring_aux : comm_ring ℝ := cau_seq.completion.comm_ring
instance : comm_ring ℝ := { ..comm_ring_aux }
/- Extra instances to short-circuit type class resolution -/
instance : ring ℝ := by apply_instance
instance : comm_semiring ℝ := by apply_instance
instance : semiring ℝ := by apply_instance
instance : add_comm_group ℝ := by apply_instance
instance : add_group ℝ := by apply_instance
instance : add_comm_monoid ℝ := by apply_instance
instance : add_monoid ℝ := by apply_instance
instance : add_left_cancel_semigroup ℝ := by apply_instance
instance : add_right_cancel_semigroup ℝ := by apply_instance
instance : add_comm_semigroup ℝ := by apply_instance
instance : add_semigroup ℝ := by apply_instance
instance : comm_monoid ℝ := by apply_instance
instance : monoid ℝ := by apply_instance
instance : comm_semigroup ℝ := by apply_instance
instance : semigroup ℝ := by apply_instance
instance : inhabited ℝ := ⟨0⟩
/-- Coercion `ℚ` → `ℝ` as a `ring_hom`. Note that this
is `cau_seq.completion.of_rat`, not `rat.cast`. -/
def of_rat : ℚ →+* ℝ := ⟨of_rat, rfl, of_rat_mul, rfl, of_rat_add⟩
/-- Make a real number from a Cauchy sequence of rationals (by taking the equivalence class). -/
def mk (x : cau_seq ℚ abs) : ℝ := cau_seq.completion.mk x
theorem of_rat_sub (x y : ℚ) : of_rat (x - y) = of_rat x - of_rat y :=
congr_arg mk (const_sub _ _)
instance : has_lt ℝ :=
⟨λ x y, quotient.lift_on₂ x y (<) $
λ f₁ g₁ f₂ g₂ hf hg, propext $
⟨λ h, lt_of_eq_of_lt (setoid.symm hf) (lt_of_lt_of_eq h hg),
λ h, lt_of_eq_of_lt hf (lt_of_lt_of_eq h (setoid.symm hg))⟩⟩
@[simp] theorem mk_lt {f g : cau_seq ℚ abs} : mk f < mk g ↔ f < g := iff.rfl
theorem mk_eq {f g : cau_seq ℚ abs} : mk f = mk g ↔ f ≈ g := mk_eq
theorem quotient_mk_eq_mk (f : cau_seq ℚ abs) : ⟦f⟧ = mk f := rfl
theorem mk_eq_mk {f : cau_seq ℚ abs} : cau_seq.completion.mk f = mk f := rfl
@[simp] theorem mk_pos {f : cau_seq ℚ abs} : 0 < mk f ↔ pos f :=
iff_of_eq (congr_arg pos (sub_zero f))
protected def le (x y : ℝ) : Prop := x < y ∨ x = y
instance : has_le ℝ := ⟨real.le⟩
@[simp] theorem mk_le {f g : cau_seq ℚ abs} : mk f ≤ mk g ↔ f ≤ g :=
or_congr iff.rfl quotient.eq
theorem add_lt_add_iff_left {a b : ℝ} (c : ℝ) : c + a < c + b ↔ a < b :=
quotient.induction_on₃ a b c (λ f g h,
iff_of_eq (congr_arg pos $ by rw add_sub_add_left_eq_sub))
instance : linear_order ℝ :=
{ le := (≤), lt := (<),
le_refl := λ a, or.inr rfl,
le_trans := λ a b c, quotient.induction_on₃ a b c $
λ f g h, by simpa [quotient_mk_eq_mk] using le_trans,
lt_iff_le_not_le := λ a b, quotient.induction_on₂ a b $
λ f g, by simpa [quotient_mk_eq_mk] using lt_iff_le_not_le,
le_antisymm := λ a b, quotient.induction_on₂ a b $
λ f g, by simpa [mk_eq, quotient_mk_eq_mk] using @cau_seq.le_antisymm _ _ f g,
le_total := λ a b, quotient.induction_on₂ a b $
λ f g, by simpa [quotient_mk_eq_mk] using le_total f g }
instance : partial_order ℝ := by apply_instance
instance : preorder ℝ := by apply_instance
theorem of_rat_lt {x y : ℚ} : of_rat x < of_rat y ↔ x < y := const_lt
protected theorem zero_lt_one : (0 : ℝ) < 1 := of_rat_lt.2 zero_lt_one
protected theorem mul_pos {a b : ℝ} : 0 < a → 0 < b → 0 < a * b :=
quotient.induction_on₂ a b $ λ f g,
show pos (f - 0) → pos (g - 0) → pos (f * g - 0),
by simpa using cau_seq.mul_pos
instance : linear_ordered_comm_ring ℝ :=
{ add_le_add_left := λ a b h c,
(le_iff_le_iff_lt_iff_lt.2 $ real.add_lt_add_iff_left c).2 h,
zero_ne_one := ne_of_lt real.zero_lt_one,
mul_pos := @real.mul_pos,
zero_lt_one := real.zero_lt_one,
..real.comm_ring, ..real.linear_order, ..real.semiring }
/- Extra instances to short-circuit type class resolution -/
instance : linear_ordered_ring ℝ := by apply_instance
instance : ordered_ring ℝ := by apply_instance
instance : linear_ordered_semiring ℝ := by apply_instance
instance : ordered_semiring ℝ := by apply_instance
instance : ordered_add_comm_group ℝ := by apply_instance
instance : ordered_cancel_add_comm_monoid ℝ := by apply_instance
instance : ordered_add_comm_monoid ℝ := by apply_instance
instance : domain ℝ := by apply_instance
instance : has_one ℝ := by apply_instance
instance : has_zero ℝ := by apply_instance
instance : has_mul ℝ := by apply_instance
instance : has_add ℝ := by apply_instance
instance : has_sub ℝ := by apply_instance
open_locale classical
noncomputable instance : discrete_linear_ordered_field ℝ :=
{ decidable_le := by apply_instance,
..real.linear_ordered_comm_ring,
..real.domain,
..cau_seq.completion.field }
/- Extra instances to short-circuit type class resolution -/
noncomputable instance : linear_ordered_field ℝ := by apply_instance
noncomputable instance : decidable_linear_ordered_comm_ring ℝ := by apply_instance
noncomputable instance : decidable_linear_ordered_semiring ℝ := by apply_instance
noncomputable instance : decidable_linear_ordered_add_comm_group ℝ := by apply_instance
noncomputable instance field : field ℝ := by apply_instance
noncomputable instance : division_ring ℝ := by apply_instance
noncomputable instance : integral_domain ℝ := by apply_instance
noncomputable instance : nonzero_comm_ring ℝ := by apply_instance
noncomputable instance : decidable_linear_order ℝ := by apply_instance
noncomputable instance : distrib_lattice ℝ := by apply_instance
noncomputable instance : lattice ℝ := by apply_instance
noncomputable instance : semilattice_inf ℝ := by apply_instance
noncomputable instance : semilattice_sup ℝ := by apply_instance
noncomputable instance : has_inf ℝ := by apply_instance
noncomputable instance : has_sup ℝ := by apply_instance
lemma le_of_forall_epsilon_le {a b : real} (h : ∀ε, ε > 0 → a ≤ b + ε) : a ≤ b :=
le_of_forall_le_of_dense $ assume x hxb,
calc a ≤ b + (x - b) : h (x-b) $ sub_pos.2 hxb
... = x : by rw [add_comm]; simp
open rat
@[simp] theorem of_rat_eq_cast : ∀ x : ℚ, of_rat x = x :=
of_rat.eq_rat_cast
theorem le_mk_of_forall_le {f : cau_seq ℚ abs} :
(∃ i, ∀ j ≥ i, x ≤ f j) → x ≤ mk f :=
quotient.induction_on x $ λ g h, le_of_not_lt $
λ ⟨K, K0, hK⟩,
let ⟨i, H⟩ := exists_forall_ge_and h $
exists_forall_ge_and hK (f.cauchy₃ $ half_pos K0) in
begin
apply not_lt_of_le (H _ (le_refl _)).1,
rw ← of_rat_eq_cast,
refine ⟨_, half_pos K0, i, λ j ij, _⟩,
have := add_le_add (H _ ij).2.1
(le_of_lt (abs_lt.1 $ (H _ (le_refl _)).2.2 _ ij).1),
rwa [← sub_eq_add_neg, sub_self_div_two, sub_apply, sub_add_sub_cancel] at this
end
theorem mk_le_of_forall_le {f : cau_seq ℚ abs} {x : ℝ} :
(∃ i, ∀ j ≥ i, (f j : ℝ) ≤ x) → mk f ≤ x
| ⟨i, H⟩ := by rw [← neg_le_neg_iff, ← mk_eq_mk, mk_neg]; exact
le_mk_of_forall_le ⟨i, λ j ij, by simp [H _ ij]⟩
theorem mk_near_of_forall_near {f : cau_seq ℚ abs} {x : ℝ} {ε : ℝ}
(H : ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) ≤ ε) : abs (mk f - x) ≤ ε :=
abs_sub_le_iff.2
⟨sub_le_iff_le_add'.2 $ mk_le_of_forall_le $
H.imp $ λ i h j ij, sub_le_iff_le_add'.1 (abs_sub_le_iff.1 $ h j ij).1,
sub_le.1 $ le_mk_of_forall_le $
H.imp $ λ i h j ij, sub_le.1 (abs_sub_le_iff.1 $ h j ij).2⟩
instance : archimedean ℝ :=
archimedean_iff_rat_le.2 $ λ x, quotient.induction_on x $ λ f,
let ⟨M, M0, H⟩ := f.bounded' 0 in
⟨M, mk_le_of_forall_le ⟨0, λ i _,
rat.cast_le.2 $ le_of_lt (abs_lt.1 (H i)).2⟩⟩
/- mark `real` irreducible in order to prevent `auto_cases` unfolding reals,
since users rarely want to consider real numbers as Cauchy sequences.
Marking `comm_ring_aux` `irreducible` is done to ensure that there are no problems
with non definitionally equal instances, caused by making `real` irreducible-/
attribute [irreducible] real comm_ring_aux
noncomputable instance : floor_ring ℝ := archimedean.floor_ring _
theorem is_cau_seq_iff_lift {f : ℕ → ℚ} : is_cau_seq abs f ↔ is_cau_seq abs (λ i, (f i : ℝ)) :=
⟨λ H ε ε0,
let ⟨δ, δ0, δε⟩ := exists_pos_rat_lt ε0 in
(H _ δ0).imp $ λ i hi j ij, lt_trans
(by simpa using (@rat.cast_lt ℝ _ _ _).2 (hi _ ij)) δε,
λ H ε ε0, (H _ (rat.cast_pos.2 ε0)).imp $
λ i hi j ij, (@rat.cast_lt ℝ _ _ _).1 $ by simpa using hi _ ij⟩
theorem of_near (f : ℕ → ℚ) (x : ℝ)
(h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) < ε) :
∃ h', real.mk ⟨f, h'⟩ = x :=
⟨is_cau_seq_iff_lift.2 (of_near _ (const abs x) h),
sub_eq_zero.1 $ abs_eq_zero.1 $
eq_of_le_of_forall_le_of_dense (abs_nonneg _) $ λ ε ε0,
mk_near_of_forall_near $
(h _ ε0).imp (λ i h j ij, le_of_lt (h j ij))⟩
theorem exists_floor (x : ℝ) : ∃ (ub : ℤ), (ub:ℝ) ≤ x ∧
∀ (z : ℤ), (z:ℝ) ≤ x → z ≤ ub :=
int.exists_greatest_of_bdd
(let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h',
int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩)
(let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩)
theorem exists_sup (S : set ℝ) : (∃ x, x ∈ S) → (∃ x, ∀ y ∈ S, y ≤ x) →
∃ x, ∀ y, x ≤ y ↔ ∀ z ∈ S, z ≤ y
| ⟨L, hL⟩ ⟨U, hU⟩ := begin
choose f hf using begin
refine λ d : ℕ, @int.exists_greatest_of_bdd
(λ n, ∃ y ∈ S, (n:ℝ) ≤ y * d) _ _,
{ cases exists_int_gt U with k hk,
refine ⟨k * d, λ z h, _⟩,
rcases h with ⟨y, yS, hy⟩,
refine int.cast_le.1 (le_trans hy _),
simp,
exact mul_le_mul_of_nonneg_right
(le_trans (hU _ yS) (le_of_lt hk)) (nat.cast_nonneg _) },
{ exact ⟨⌊L * d⌋, L, hL, floor_le _⟩ }
end,
have hf₁ : ∀ n > 0, ∃ y ∈ S, ((f n / n:ℚ):ℝ) ≤ y := λ n n0,
let ⟨y, yS, hy⟩ := (hf n).1 in
⟨y, yS, by simpa using (div_le_iff ((nat.cast_pos.2 n0):((_:ℝ) < _))).2 hy⟩,
have hf₂ : ∀ (n > 0) (y ∈ S), (y - (n:ℕ)⁻¹ : ℝ) < (f n / n:ℚ),
{ intros n n0 y yS,
have := lt_of_lt_of_le (sub_one_lt_floor _)
(int.cast_le.2 $ (hf n).2 _ ⟨y, yS, floor_le _⟩),
simp [-sub_eq_add_neg],
rwa [lt_div_iff ((nat.cast_pos.2 n0):((_:ℝ) < _)), sub_mul, _root_.inv_mul_cancel],
exact ne_of_gt (nat.cast_pos.2 n0) },
suffices hg, let g : cau_seq ℚ abs := ⟨λ n, f n / n, hg⟩,
refine ⟨mk g, λ y, ⟨λ h x xS, le_trans _ h, λ h, _⟩⟩,
{ refine le_of_forall_ge_of_dense (λ z xz, _),
cases exists_nat_gt (x - z)⁻¹ with K hK,
refine le_mk_of_forall_le ⟨K, λ n nK, _⟩,
replace xz := sub_pos.2 xz,
replace hK := le_trans (le_of_lt hK) (nat.cast_le.2 nK),
have n0 : 0 < n := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 xz) hK),
refine le_trans _ (le_of_lt $ hf₂ _ n0 _ xS),
rwa [le_sub, inv_le ((nat.cast_pos.2 n0):((_:ℝ) < _)) xz] },
{ exact mk_le_of_forall_le ⟨1, λ n n1,
let ⟨x, xS, hx⟩ := hf₁ _ n1 in le_trans hx (h _ xS)⟩ },
intros ε ε0,
suffices : ∀ j k ≥ nat_ceil ε⁻¹, (f j / j - f k / k : ℚ) < ε,
{ refine ⟨_, λ j ij, abs_lt.2 ⟨_, this _ _ ij (le_refl _)⟩⟩,
rw [neg_lt, neg_sub], exact this _ _ (le_refl _) ij },
intros j k ij ik,
replace ij := le_trans (le_nat_ceil _) (nat.cast_le.2 ij),
replace ik := le_trans (le_nat_ceil _) (nat.cast_le.2 ik),
have j0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 ε0) ij),
have k0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 ε0) ik),
rcases hf₁ _ j0 with ⟨y, yS, hy⟩,
refine lt_of_lt_of_le ((@rat.cast_lt ℝ _ _ _).1 _)
((inv_le ε0 (nat.cast_pos.2 k0)).1 ik),
simpa using sub_lt_iff_lt_add'.2
(lt_of_le_of_lt hy $ sub_lt_iff_lt_add.1 $ hf₂ _ k0 _ yS)
end
noncomputable instance : has_Sup ℝ :=
⟨λ S, if h : (∃ x, x ∈ S) ∧ (∃ x, ∀ y ∈ S, y ≤ x)
then classical.some (exists_sup S h.1 h.2) else 0⟩
lemma Sup_def (S : set ℝ) :
Sup S = if h : (∃ x, x ∈ S) ∧ (∃ x, ∀ y ∈ S, y ≤ x)
then classical.some (exists_sup S h.1 h.2) else 0 := rfl
theorem Sup_le (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x)
{y} : Sup S ≤ y ↔ ∀ z ∈ S, z ≤ y :=
by simp [Sup_def, h₁, h₂]; exact
classical.some_spec (exists_sup S h₁ h₂) y
section
-- this proof times out without this
local attribute [instance, priority 1000] classical.prop_decidable
theorem lt_Sup (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x)
{y} : y < Sup S ↔ ∃ z ∈ S, y < z :=
by simpa [not_forall] using not_congr (@Sup_le S h₁ h₂ y)
end
theorem le_Sup (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {x} (xS : x ∈ S) : x ≤ Sup S :=
(Sup_le S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS
theorem Sup_le_ub (S : set ℝ) (h₁ : ∃ x, x ∈ S) {ub} (h₂ : ∀ y ∈ S, y ≤ ub) : Sup S ≤ ub :=
(Sup_le S h₁ ⟨_, h₂⟩).2 h₂
protected lemma is_lub_Sup {s : set ℝ} {a b : ℝ} (ha : a ∈ s) (hb : b ∈ upper_bounds s) :
is_lub s (Sup s) :=
⟨λ x xs, real.le_Sup s ⟨_, hb⟩ xs,
λ u h, real.Sup_le_ub _ ⟨_, ha⟩ h⟩
noncomputable instance : has_Inf ℝ := ⟨λ S, -Sup {x | -x ∈ S}⟩
lemma Inf_def (S : set ℝ) : Inf S = -Sup {x | -x ∈ S} := rfl
theorem le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y)
{y} : y ≤ Inf S ↔ ∀ z ∈ S, y ≤ z :=
begin
refine le_neg.trans ((Sup_le _ _ _).trans _),
{ cases h₁ with x xS, exact ⟨-x, by simp [xS]⟩ },
{ cases h₂ with ub h, exact ⟨-ub, λ y hy, le_neg.1 $ h _ hy⟩ },
split; intros H z hz,
{ exact neg_le_neg_iff.1 (H _ $ by simp [hz]) },
{ exact le_neg.2 (H _ hz) }
end
section
-- this proof times out without this
local attribute [instance, priority 1000] classical.prop_decidable
theorem Inf_lt (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y)
{y} : Inf S < y ↔ ∃ z ∈ S, z < y :=
by simpa [not_forall] using not_congr (@le_Inf S h₁ h₂ y)
end
theorem Inf_le (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {x} (xS : x ∈ S) : Inf S ≤ x :=
(le_Inf S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS
theorem lb_le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) {lb} (h₂ : ∀ y ∈ S, lb ≤ y) : lb ≤ Inf S :=
(le_Inf S h₁ ⟨_, h₂⟩).2 h₂
noncomputable instance : conditionally_complete_linear_order ℝ :=
{ Sup := has_Sup.Sup,
Inf := has_Inf.Inf,
le_cSup :=
assume (s : set ℝ) (a : ℝ) (_ : bdd_above s) (_ : a ∈ s),
show a ≤ Sup s,
from le_Sup s ‹bdd_above s› ‹a ∈ s›,
cSup_le :=
assume (s : set ℝ) (a : ℝ) (_ : s.nonempty) (H : ∀b∈s, b ≤ a),
show Sup s ≤ a,
from Sup_le_ub s ‹s.nonempty› H,
cInf_le :=
assume (s : set ℝ) (a : ℝ) (_ : bdd_below s) (_ : a ∈ s),
show Inf s ≤ a,
from Inf_le s ‹bdd_below s› ‹a ∈ s›,
le_cInf :=
assume (s : set ℝ) (a : ℝ) (_ : s.nonempty) (H : ∀b∈s, a ≤ b),
show a ≤ Inf s,
from lb_le_Inf s ‹s.nonempty› H,
decidable_le := classical.dec_rel _,
..real.linear_order, ..real.lattice}
theorem Sup_empty : Sup (∅ : set ℝ) = 0 := dif_neg $ by simp
theorem Sup_of_not_bdd_above {s : set ℝ} (hs : ¬ bdd_above s) : Sup s = 0 :=
dif_neg $ assume h, hs h.2
theorem Sup_univ : Sup (@set.univ ℝ) = 0 :=
real.Sup_of_not_bdd_above $ λ ⟨x, h⟩, not_le_of_lt (lt_add_one _) $ h (set.mem_univ _)
theorem Inf_empty : Inf (∅ : set ℝ) = 0 :=
by simp [Inf_def, Sup_empty]
theorem Inf_of_not_bdd_below {s : set ℝ} (hs : ¬ bdd_below s) : Inf s = 0 :=
have bdd_above {x | -x ∈ s} → bdd_below s, from
assume ⟨b, hb⟩, ⟨-b, assume x hxs, neg_le.2 $ hb $ by simp [hxs]⟩,
have ¬ bdd_above {x | -x ∈ s}, from mt this hs,
neg_eq_zero.2 $ Sup_of_not_bdd_above $ this
theorem cau_seq_converges (f : cau_seq ℝ abs) : ∃ x, f ≈ const abs x :=
begin
let S := {x : ℝ | const abs x < f},
have lb : ∃ x, x ∈ S := exists_lt f,
have ub' : ∀ x, f < const abs x → ∀ y ∈ S, y ≤ x :=
λ x h y yS, le_of_lt $ const_lt.1 $ cau_seq.lt_trans yS h,
have ub : ∃ x, ∀ y ∈ S, y ≤ x := (exists_gt f).imp ub',
refine ⟨Sup S,
((lt_total _ _).resolve_left (λ h, _)).resolve_right (λ h, _)⟩,
{ rcases h with ⟨ε, ε0, i, ih⟩,
refine not_lt_of_le (Sup_le_ub S lb (ub' _ _))
((sub_lt_self_iff _).2 (half_pos ε0)),
refine ⟨_, half_pos ε0, i, λ j ij, _⟩,
rw [sub_apply, const_apply, sub_right_comm,
le_sub_iff_add_le, add_halves],
exact ih _ ij },
{ rcases h with ⟨ε, ε0, i, ih⟩,
refine not_lt_of_le (le_Sup S ub _)
((lt_add_iff_pos_left _).2 (half_pos ε0)),
refine ⟨_, half_pos ε0, i, λ j ij, _⟩,
rw [sub_apply, const_apply, add_comm, ← sub_sub,
le_sub_iff_add_le, add_halves],
exact ih _ ij }
end
noncomputable instance : cau_seq.is_complete ℝ abs := ⟨cau_seq_converges⟩
theorem sqrt_exists : ∀ {x : ℝ}, 0 ≤ x → ∃ y, 0 ≤ y ∧ y * y = x :=
suffices H : ∀ {x : ℝ}, 0 < x → x ≤ 1 → ∃ y, 0 < y ∧ y * y = x, begin
intros x x0, cases x0,
cases le_total x 1 with x1 x1,
{ rcases H x0 x1 with ⟨y, y0, hy⟩,
exact ⟨y, le_of_lt y0, hy⟩ },
{ have := (inv_le_inv x0 zero_lt_one).2 x1,
rw inv_one at this,
rcases H (inv_pos.2 x0) this with ⟨y, y0, hy⟩,
refine ⟨y⁻¹, le_of_lt (inv_pos.2 y0), _⟩, rw [← mul_inv', hy, inv_inv'] },
{ exact ⟨0, by simp [x0.symm]⟩ }
end,
λ x x0 x1, begin
let S := {y | 0 < y ∧ y * y ≤ x},
have lb : x ∈ S := ⟨x0, by simpa using (mul_le_mul_right x0).2 x1⟩,
have ub : ∀ y ∈ S, (y:ℝ) ≤ 1,
{ intros y yS, cases yS with y0 yx,
refine (mul_self_le_mul_self_iff (le_of_lt y0) zero_le_one).2 _,
simpa using le_trans yx x1 },
have S0 : 0 < Sup S := lt_of_lt_of_le x0 (le_Sup _ ⟨_, ub⟩ lb),
refine ⟨Sup S, S0, le_antisymm (not_lt.1 $ λ h, _) (not_lt.1 $ λ h, _)⟩,
{ rw [← div_lt_iff S0, lt_Sup S ⟨_, lb⟩ ⟨_, ub⟩] at h,
rcases h with ⟨y, ⟨y0, yx⟩, hy⟩,
rw [div_lt_iff S0, ← div_lt_iff' y0, lt_Sup S ⟨_, lb⟩ ⟨_, ub⟩] at hy,
rcases hy with ⟨z, ⟨z0, zx⟩, hz⟩,
rw [div_lt_iff y0] at hz,
exact not_lt_of_lt
((mul_lt_mul_right y0).1 (lt_of_le_of_lt yx hz))
((mul_lt_mul_left z0).1 (lt_of_le_of_lt zx hz)) },
{ let s := Sup S, let y := s + (x - s * s) / 3,
replace h : 0 < x - s * s := sub_pos.2 h,
have _30 := bit1_pos zero_le_one,
have : s < y := (lt_add_iff_pos_right _).2 (div_pos h _30),
refine not_le_of_lt this (le_Sup S ⟨_, ub⟩ ⟨lt_trans S0 this, _⟩),
rw [add_mul_self_eq, add_assoc, ← le_sub_iff_add_le', ← add_mul,
← le_div_iff (div_pos h _30), div_div_cancel' (ne_of_gt h)],
apply add_le_add,
{ simpa using (mul_le_mul_left (@two_pos ℝ _)).2 (Sup_le_ub _ ⟨_, lb⟩ ub) },
{ rw [div_le_one_iff_le _30],
refine le_trans (sub_le_self _ (mul_self_nonneg _)) (le_trans x1 _),
exact (le_add_iff_nonneg_left _).2 (le_of_lt two_pos) } }
end
def sqrt_aux (f : cau_seq ℚ abs) : ℕ → ℚ
| 0 := rat.mk_nat (f 0).num.to_nat.sqrt (f 0).denom.sqrt
| (n + 1) := let s := sqrt_aux n in max 0 $ (s + f (n+1) / s) / 2
theorem sqrt_aux_nonneg (f : cau_seq ℚ abs) : ∀ i : ℕ, 0 ≤ sqrt_aux f i
| 0 := by rw [sqrt_aux, mk_nat_eq, mk_eq_div];
apply div_nonneg'; exact int.cast_nonneg.2 (int.of_nat_nonneg _)
| (n + 1) := le_max_left _ _
/- TODO(Mario): finish the proof
theorem sqrt_aux_converges (f : cau_seq ℚ abs) : ∃ h x, 0 ≤ x ∧ x * x = max 0 (mk f) ∧
mk ⟨sqrt_aux f, h⟩ = x :=
begin
rcases sqrt_exists (le_max_left 0 (mk f)) with ⟨x, x0, hx⟩,
suffices : ∃ h, mk ⟨sqrt_aux f, h⟩ = x,
{ exact this.imp (λ h e, ⟨x, x0, hx, e⟩) },
apply of_near,
suffices : ∃ δ > 0, ∀ i, abs (↑(sqrt_aux f i) - x) < δ / 2 ^ i,
{ rcases this with ⟨δ, δ0, hδ⟩,
intros,
}
end -/
noncomputable def sqrt (x : ℝ) : ℝ :=
classical.some (sqrt_exists (le_max_left 0 x))
/-quotient.lift_on x
(λ f, mk ⟨sqrt_aux f, (sqrt_aux_converges f).fst⟩)
(λ f g e, begin
rcases sqrt_aux_converges f with ⟨hf, x, x0, xf, xs⟩,
rcases sqrt_aux_converges g with ⟨hg, y, y0, yg, ys⟩,
refine xs.trans (eq.trans _ ys.symm),
rw [← @mul_self_inj_of_nonneg ℝ _ x y x0 y0, xf, yg],
congr' 1, exact quotient.sound e
end)-/
theorem sqrt_prop (x : ℝ) : 0 ≤ sqrt x ∧ sqrt x * sqrt x = max 0 x :=
classical.some_spec (sqrt_exists (le_max_left 0 x))
/-quotient.induction_on x $ λ f,
by rcases sqrt_aux_converges f with ⟨hf, _, x0, xf, rfl⟩; exact ⟨x0, xf⟩-/
theorem sqrt_eq_zero_of_nonpos (h : x ≤ 0) : sqrt x = 0 :=
eq_zero_of_mul_self_eq_zero $ (sqrt_prop x).2.trans $ max_eq_left h
theorem sqrt_nonneg (x : ℝ) : 0 ≤ sqrt x := (sqrt_prop x).1
@[simp] theorem mul_self_sqrt (h : 0 ≤ x) : sqrt x * sqrt x = x :=
(sqrt_prop x).2.trans (max_eq_right h)
@[simp] theorem sqrt_mul_self (h : 0 ≤ x) : sqrt (x * x) = x :=
(mul_self_inj_of_nonneg (sqrt_nonneg _) h).1 (mul_self_sqrt (mul_self_nonneg _))
theorem sqrt_eq_iff_mul_self_eq (hx : 0 ≤ x) (hy : 0 ≤ y) :
sqrt x = y ↔ y * y = x :=
⟨λ h, by rw [← h, mul_self_sqrt hx],
λ h, by rw [← h, sqrt_mul_self hy]⟩
@[simp] theorem sqr_sqrt (h : 0 ≤ x) : sqrt x ^ 2 = x :=
by rw [pow_two, mul_self_sqrt h]
@[simp] theorem sqrt_sqr (h : 0 ≤ x) : sqrt (x ^ 2) = x :=
by rw [pow_two, sqrt_mul_self h]
theorem sqrt_eq_iff_sqr_eq (hx : 0 ≤ x) (hy : 0 ≤ y) :
sqrt x = y ↔ y ^ 2 = x :=
by rw [pow_two, sqrt_eq_iff_mul_self_eq hx hy]
theorem sqrt_mul_self_eq_abs (x : ℝ) : sqrt (x * x) = abs x :=
(le_total 0 x).elim
(λ h, (sqrt_mul_self h).trans (abs_of_nonneg h).symm)
(λ h, by rw [← neg_mul_neg,
sqrt_mul_self (neg_nonneg.2 h), abs_of_nonpos h])
theorem sqrt_sqr_eq_abs (x : ℝ) : sqrt (x ^ 2) = abs x :=
by rw [pow_two, sqrt_mul_self_eq_abs]
@[simp] theorem sqrt_zero : sqrt 0 = 0 :=
by simpa using sqrt_mul_self (le_refl _)
@[simp] theorem sqrt_one : sqrt 1 = 1 :=
by simpa using sqrt_mul_self zero_le_one
@[simp] theorem sqrt_le (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x ≤ sqrt y ↔ x ≤ y :=
by rw [mul_self_le_mul_self_iff (sqrt_nonneg _) (sqrt_nonneg _),
mul_self_sqrt hx, mul_self_sqrt hy]
@[simp] theorem sqrt_lt (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x < sqrt y ↔ x < y :=
lt_iff_lt_of_le_iff_le (sqrt_le hy hx)
lemma sqrt_le_sqrt (h : x ≤ y) : sqrt x ≤ sqrt y :=
begin
rw [mul_self_le_mul_self_iff (sqrt_nonneg _) (sqrt_nonneg _), (sqrt_prop _).2, (sqrt_prop _).2],
exact max_le_max (le_refl _) h
end
lemma sqrt_le_left (hy : 0 ≤ y) : sqrt x ≤ y ↔ x ≤ y ^ 2 :=
begin
rw [mul_self_le_mul_self_iff (sqrt_nonneg _) hy, pow_two],
cases le_total 0 x with hx hx,
{ rw [mul_self_sqrt hx] },
{ have h1 : 0 ≤ y * y := mul_nonneg hy hy,
have h2 : x ≤ y * y := le_trans hx h1,
simp [sqrt_eq_zero_of_nonpos, hx, h1, h2] }
end
/- note: if you want to conclude `x ≤ sqrt y`, then use `le_sqrt_of_sqr_le`.
if you have `x > 0`, consider using `le_sqrt'` -/
lemma le_sqrt (hx : 0 ≤ x) (hy : 0 ≤ y) : x ≤ sqrt y ↔ x ^ 2 ≤ y :=
by rw [mul_self_le_mul_self_iff hx (sqrt_nonneg _), pow_two, mul_self_sqrt hy]
lemma le_sqrt' (hx : 0 < x) : x ≤ sqrt y ↔ x ^ 2 ≤ y :=
begin
rw [mul_self_le_mul_self_iff (le_of_lt hx) (sqrt_nonneg _), pow_two],
cases le_total 0 y with hy hy,
{ rw [mul_self_sqrt hy] },
{ have h1 : 0 < x * x := mul_pos hx hx,
have h2 : ¬x * x ≤ y := not_le_of_lt (lt_of_le_of_lt hy h1),
simp [sqrt_eq_zero_of_nonpos, hy, h1, h2] }
end
lemma le_sqrt_of_sqr_le (h : x ^ 2 ≤ y) : x ≤ sqrt y :=
begin
cases lt_or_ge 0 x with hx hx,
{ rwa [le_sqrt' hx] },
{ exact le_trans hx (sqrt_nonneg y) }
end
@[simp] theorem sqrt_inj (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x = sqrt y ↔ x = y :=
by simp [le_antisymm_iff, hx, hy]
@[simp] theorem sqrt_eq_zero (h : 0 ≤ x) : sqrt x = 0 ↔ x = 0 :=
by simpa using sqrt_inj h (le_refl _)
theorem sqrt_eq_zero' : sqrt x = 0 ↔ x ≤ 0 :=
(le_total x 0).elim
(λ h, by simp [h, sqrt_eq_zero_of_nonpos])
(λ h, by simp [h]; simp [le_antisymm_iff, h])
@[simp] theorem sqrt_pos : 0 < sqrt x ↔ 0 < x :=
lt_iff_lt_of_le_iff_le (iff.trans
(by simp [le_antisymm_iff, sqrt_nonneg]) sqrt_eq_zero')
@[simp] theorem sqrt_mul' (x) {y : ℝ} (hy : 0 ≤ y) : sqrt (x * y) = sqrt x * sqrt y :=
begin
cases le_total 0 x with hx hx,
{ refine (mul_self_inj_of_nonneg _ (mul_nonneg _ _)).1 _; try {apply sqrt_nonneg},
rw [mul_self_sqrt (mul_nonneg hx hy), mul_assoc,
mul_left_comm (sqrt y), mul_self_sqrt hy, ← mul_assoc, mul_self_sqrt hx] },
{ rw [sqrt_eq_zero'.2 (mul_nonpos_of_nonpos_of_nonneg hx hy),
sqrt_eq_zero'.2 hx, zero_mul] }
end
@[simp] theorem sqrt_mul (hx : 0 ≤ x) (y : ℝ) : sqrt (x * y) = sqrt x * sqrt y :=
by rw [mul_comm, sqrt_mul' _ hx, mul_comm]
@[simp] theorem sqrt_inv (x : ℝ) : sqrt x⁻¹ = (sqrt x)⁻¹ :=
(le_or_lt x 0).elim
(λ h, by simp [sqrt_eq_zero'.2, inv_nonpos, h])
(λ h, by rw [
← mul_self_inj_of_nonneg (sqrt_nonneg _) (le_of_lt $ inv_pos.2 $ sqrt_pos.2 h),
mul_self_sqrt (le_of_lt $ inv_pos.2 h), ← mul_inv', mul_self_sqrt (le_of_lt h)])
@[simp] theorem sqrt_div (hx : 0 ≤ x) (y : ℝ) : sqrt (x / y) = sqrt x / sqrt y :=
by rw [division_def, sqrt_mul hx, sqrt_inv]; refl
attribute [irreducible] real.le
end real
|
76d5bc4509684c13942b656b1182e15258178ef5 | f618aea02cb4104ad34ecf3b9713065cc0d06103 | /src/logic/embedding.lean | 351497664c081253a67b832d042b66f7dbf5c50f | [
"Apache-2.0"
] | permissive | joehendrix/mathlib | 84b6603f6be88a7e4d62f5b1b0cbb523bb82b9a5 | c15eab34ad754f9ecd738525cb8b5a870e834ddc | refs/heads/master | 1,589,606,591,630 | 1,555,946,393,000 | 1,555,946,393,000 | 182,813,854 | 0 | 0 | null | 1,555,946,309,000 | 1,555,946,308,000 | null | UTF-8 | Lean | false | false | 6,204 | 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
Injective functions.
-/
import data.equiv.basic data.option.basic data.subtype
universes u v w x
namespace function
structure embedding (α : Sort*) (β : Sort*) :=
(to_fun : α → β)
(inj : injective to_fun)
infixr ` ↪ `:25 := embedding
instance {α : Sort u} {β : Sort v} : has_coe_to_fun (α ↪ β) := ⟨_, embedding.to_fun⟩
end function
protected def equiv.to_embedding {α : Sort u} {β : Sort v} (f : α ≃ β) : α ↪ β :=
⟨f, f.injective⟩
@[simp] theorem equiv.to_embedding_coe_fn {α : Sort u} {β : Sort v} (f : α ≃ β) :
(f.to_embedding : α → β) = f := rfl
namespace function
namespace embedding
@[simp] theorem to_fun_eq_coe {α β} (f : α ↪ β) : to_fun f = f := rfl
@[simp] theorem coe_fn_mk {α β} (f : α → β) (i) :
(@mk _ _ f i : α → β) = f := rfl
theorem inj' {α β} : ∀ (f : α ↪ β), injective f
| ⟨f, hf⟩ := hf
@[refl] protected def refl (α : Sort*) : α ↪ α :=
⟨id, injective_id⟩
@[trans] protected def trans {α β γ} (f : α ↪ β) (g : β ↪ γ) : α ↪ γ :=
⟨_, injective_comp g.inj' f.inj'⟩
@[simp] theorem refl_apply {α} (x : α) : embedding.refl α x = x := rfl
@[simp] theorem trans_apply {α β γ} (f : α ↪ β) (g : β ↪ γ) (a : α) :
(f.trans g) a = g (f a) := rfl
protected def congr {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort x}
(e₁ : α ≃ β) (e₂ : γ ≃ δ) (f : α ↪ γ) : (β ↪ δ) :=
(equiv.to_embedding e₁.symm).trans (f.trans e₂.to_embedding)
protected noncomputable def of_surjective {α β} {f : β → α} (hf : surjective f) :
α ↪ β :=
⟨surj_inv hf, injective_surj_inv _⟩
protected noncomputable def equiv_of_surjective {α β} (f : α ↪ β) (hf : surjective f) :
α ≃ β :=
equiv.of_bijective ⟨f.inj, hf⟩
protected def of_not_nonempty {α β} (hα : ¬ nonempty α) : α ↪ β :=
⟨λa, (hα ⟨a⟩).elim, assume a, (hα ⟨a⟩).elim⟩
noncomputable def set_value {α β} (f : α ↪ β) (a : α) (b : β) : α ↪ β :=
by haveI := classical.dec; exact
if h : ∃ a', f a' = b then
(equiv.swap a (classical.some h)).to_embedding.trans f
else
⟨λ a', if a' = a then b else f a',
λ a₁ a₂ e, begin
simp at e, split_ifs at e with h₁ h₂,
{ cc },
{ cases h ⟨_, e.symm⟩ },
{ cases h ⟨_, e⟩ },
{ exact f.2 e }
end⟩
theorem set_value_eq {α β} (f : α ↪ β) (a : α) (b : β) : set_value f a b a = b :=
begin
rw [set_value],
cases classical.dec (∃ a', f a' = b);
dsimp [dite], {simp},
simp [equiv.swap_apply_left],
apply classical.some_spec h
end
/-- Embedding into `option` -/
protected def some {α} : α ↪ option α :=
⟨some, option.injective_some α⟩
def subtype {α} (p : α → Prop) : subtype p ↪ α :=
⟨subtype.val, λ _ _, subtype.eq'⟩
/-- Restrict the codomain of an embedding. -/
def cod_restrict {α β} (p : set β) (f : α ↪ β) (H : ∀ a, f a ∈ p) : α ↪ p :=
⟨λ a, ⟨f a, H a⟩, λ a b h, f.inj (@congr_arg _ _ _ _ subtype.val h)⟩
@[simp] theorem cod_restrict_apply {α β} (p) (f : α ↪ β) (H a) :
cod_restrict p f H a = ⟨f a, H a⟩ := rfl
def prod_congr {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α × γ ↪ β × δ :=
⟨assume ⟨a, b⟩, (e₁ a, e₂ b),
assume ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ h,
have a₁ = a₂ ∧ b₁ = b₂, from (prod.mk.inj h).imp (assume h, e₁.inj h) (assume h, e₂.inj h),
this.left ▸ this.right ▸ rfl⟩
section sum
open sum
def sum_congr {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α ⊕ γ ↪ β ⊕ δ :=
⟨assume s, match s with inl a := inl (e₁ a) | inr b := inr (e₂ b) end,
assume s₁ s₂ h, match s₁, s₂, h with
| inl a₁, inl a₂, h := congr_arg inl $ e₁.inj $ inl.inj h
| inr b₁, inr b₂, h := congr_arg inr $ e₂.inj $ inr.inj h
end⟩
@[simp] theorem sum_congr_apply_inl {α β γ δ}
(e₁ : α ↪ β) (e₂ : γ ↪ δ) (a) : sum_congr e₁ e₂ (inl a) = inl (e₁ a) := rfl
@[simp] theorem sum_congr_apply_inr {α β γ δ}
(e₁ : α ↪ β) (e₂ : γ ↪ δ) (b) : sum_congr e₁ e₂ (inr b) = inr (e₂ b) := rfl
end sum
section sigma
open sigma
def sigma_congr_right {α : Type*} {β γ : α → Type*} (e : ∀ a, β a ↪ γ a) : sigma β ↪ sigma γ :=
⟨λ ⟨a, b⟩, ⟨a, e a b⟩, λ ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ h, begin
injection h with h₁ h₂, subst a₂,
congr,
exact (e a₁).2 (eq_of_heq h₂)
end⟩
end sigma
def Pi_congr_right {α : Sort*} {β γ : α → Sort*} (e : ∀ a, β a ↪ γ a) : (Π a, β a) ↪ (Π a, γ a) :=
⟨λf a, e a (f a), λ f₁ f₂ h, funext $ λ a, (e a).inj (congr_fun h a)⟩
def arrow_congr_left {α : Sort u} {β : Sort v} {γ : Sort w}
(e : α ↪ β) : (γ → α) ↪ (γ → β) :=
Pi_congr_right (λ _, e)
noncomputable def arrow_congr_right {α : Sort u} {β : Sort v} {γ : Sort w} [inhabited γ]
(e : α ↪ β) : (α → γ) ↪ (β → γ) :=
by haveI := classical.prop_decidable; exact
let f' : (α → γ) → (β → γ) := λf b, if h : ∃c, e c = b then f (classical.some h) else default γ in
⟨f', assume f₁ f₂ h, funext $ assume c,
have ∃c', e c' = e c, from ⟨c, rfl⟩,
have eq' : f' f₁ (e c) = f' f₂ (e c), from congr_fun h _,
have eq_b : classical.some this = c, from e.inj $ classical.some_spec this,
by simp [f', this, if_pos, eq_b] at eq'; assumption⟩
protected def subtype_map {α β} {p : α → Prop} {q : β → Prop} (f : α ↪ β)
(h : ∀{{x}}, p x → q (f x)) : {x : α // p x} ↪ {y : β // q y} :=
⟨subtype.map f h, subtype.map_injective h f.2⟩
open set
protected def image {α β} (f : α ↪ β) : set α ↪ set β :=
⟨image f, injective_image f.2⟩
end embedding
end function
namespace set
/-- The injection map is an embedding between subsets. -/
def embedding_of_subset {α} {s t : set α} (h : s ⊆ t) : s ↪ t :=
⟨λ x, ⟨x.1, h x.2⟩, λ ⟨x, hx⟩ ⟨y, hy⟩ h, by congr; injection h⟩
end set
|
08bfb905884f3a54759d3c1eaf91e76aa09d8082 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/276.lean | 36905318c8aecd11cab651849c5bccf2cf4684ba | [
"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 | 289 | lean | universe u v
-- `#check` works
set_option pp.all true in
#check fun {α : Sort v} => PEmpty.rec (fun _ => α)
-- but `def` doesn't work
-- error: (kernel) compiler failed to infer low level type, unknown declaration 'PEmpty.rec'
def PEmpty.elim {α : Sort v} := PEmpty.rec (fun _ => α)
|
7ba1f30afd52e4d0f703cde8cd378e0409d46bb0 | 597e185014db6ce8a949dac0322798f11218338b | /src/kruskal_katona_abstract.lean | d6a1af3342f11da72611dd6bd4d070ef9926c704 | [] | no_license | b-mehta/lean-experiments | 58ce21c7106dfde163c236175fee30b341ba69ee | 5f0aed189f724ae6f739ec75dcdddcd2687614e1 | refs/heads/master | 1,598,987,002,293 | 1,576,649,380,000 | 1,576,649,380,000 | 219,032,370 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,501 | lean | import data.finset
import data.fintype
open fintype
open finset
variable {n : ℕ}
local notation `X` := fin n
def compress_family (U V : finset X) (𝒜 : finset (finset X)) : finset (finset X) := sorry
def shadow (𝒜 : finset (finset X)) : finset (finset X) := sorry
reserve prefix `∂`:90
notation ∂𝒜 := shadow 𝒜
def is_compressed (U V : finset X) (𝒜 : finset (finset X)) : Prop := compress_family U V 𝒜 = 𝒜
lemma is_compressed_empty (𝒜 : finset (finset X)) : is_compressed ∅ ∅ 𝒜 := sorry
def c_measure (𝒜 : finset (finset X)) : ℕ := sorry
lemma compress_family_idempotent (U V : finset X) (𝒜 : finset (finset X)) : is_compressed U V (compress_family U V 𝒜) := sorry
def gamma : rel (finset X) (finset X) := (λ U V, ∃ (HU : U ≠ ∅), ∃ (HV : V ≠ ∅), disjoint U V ∧ finset.card U = finset.card V ∧ max' U HU < max' V HV)
lemma compression_improved (U V : finset X) (𝒜 : finset (finset X)) (h₁ : gamma U V)
(h₂ : ∀ U₁ V₁, gamma U₁ V₁ ∧ U₁.card < U.card → is_compressed U₁ V₁ 𝒜) (h₃ : ¬ is_compressed U V 𝒜):
c_measure (compress_family U V 𝒜) < c_measure 𝒜 ∧ (compress_family U V 𝒜).card = 𝒜.card ∧ (∂ compress_family U V 𝒜).card ≤ (∂𝒜).card := sorry
theorem kruskal_katona_helper (𝒜 : finset (finset X)) :
∃ (ℬ : finset (finset X)), 𝒜.card = ℬ.card ∧ (∂ℬ).card ≤ (∂𝒜).card ∧ (∀ U V, gamma U V → is_compressed U V ℬ) :=
sorry |
2d2340e164b1b371f461dd41b36dcebdd1f8e8e7 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/data/bitvec/core.lean | d256483d96bf7c6f809cac6253b48488b495ccd8 | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 8,736 | lean | /-
Copyright (c) 2015 Joe Hendrix. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joe Hendrix, Sebastian Ullrich
-/
import data.vector
import data.nat.basic
/-!
# Basic operations on bitvectors
This is a work-in-progress, and contains additions to other theories.
This file was moved to mathlib from core Lean in the switch to Lean 3.20.0c. It is not fully in compliance with mathlib style standards.
-/
/-- `bitvec n` is a `vector` of `bool` with length `n`. -/
@[reducible] def bitvec (n : ℕ) := vector bool n
namespace bitvec
open nat
open vector
local infix `++ₜ`:65 := vector.append
/-- Create a zero bitvector -/
@[reducible] protected def zero (n : ℕ) : bitvec n := repeat ff n
/-- Create a bitvector of length `n` whose `n-1`st entry is 1 and other entries are 0. -/
@[reducible] protected def one : Π (n : ℕ), bitvec n
| 0 := nil
| (succ n) := repeat ff n ++ₜ tt::nil
/-- Create a bitvector from another with a provably equal length. -/
protected def cong {a b : ℕ} (h : a = b) : bitvec a → bitvec b
| ⟨x, p⟩ := ⟨x, h ▸ p⟩
/-- `bitvec` specific version of `vector.append` -/
def append {m n} : bitvec m → bitvec n → bitvec (m + n) := vector.append
/-! ### Shift operations -/
section shift
variable {n : ℕ}
/-- `shl x i` is the bitvector obtained by left-shifting `x` `i` times and padding with `ff`.
If `x.length < i` then this will return the all-`ff`s bitvector. -/
def shl (x : bitvec n) (i : ℕ) : bitvec n :=
bitvec.cong (by simp) $
drop i x ++ₜ repeat ff (min n i)
/-- `fill_shr x i fill` is the bitvector obtained by right-shifting `x` `i` times and then
padding with `fill : bool`. If `x.length < i` then this will return the constant `fill`
bitvector. -/
def fill_shr (x : bitvec n) (i : ℕ) (fill : bool) : bitvec n :=
bitvec.cong
begin
by_cases (i ≤ n),
{ have h₁ := sub_le n i,
rw [min_eq_right h], rw [min_eq_left h₁, ← nat.add_sub_assoc h, nat.add_comm, nat.add_sub_cancel] },
{ have h₁ := le_of_not_ge h,
rw [min_eq_left h₁, sub_eq_zero_of_le h₁, zero_min, nat.add_zero] }
end $
repeat fill (min n i) ++ₜ take (n-i) x
/-- unsigned shift right -/
def ushr (x : bitvec n) (i : ℕ) : bitvec n :=
fill_shr x i ff
/-- signed shift right -/
def sshr : Π {m : ℕ}, bitvec m → ℕ → bitvec m
| 0 _ _ := nil
| (succ m) x i := head x :: fill_shr (tail x) i (head x)
end shift
/-! ### Bitwise operations -/
section bitwise
variable {n : ℕ}
/-- bitwise not -/
def not : bitvec n → bitvec n := map bnot
/-- bitwise and -/
def and : bitvec n → bitvec n → bitvec n := map₂ band
/-- bitwise or -/
def or : bitvec n → bitvec n → bitvec n := map₂ bor
/-- bitwise xor -/
def xor : bitvec n → bitvec n → bitvec n := map₂ bxor
end bitwise
/-! ### Arithmetic operators -/
section arith
variable {n : ℕ}
/-- `xor3 x y c` is `((x XOR y) XOR c)`. -/
protected def xor3 (x y c : bool) := bxor (bxor x y) c
/-- `carry x y c` is `x && y || x && c || y && c`. -/
protected def carry (x y c : bool) :=
x && y || x && c || y && c
/-- `neg x` is the two's complement of `x`. -/
protected def neg (x : bitvec n) : bitvec n :=
let f := λ y c, (y || c, bxor y c) in
prod.snd (map_accumr f x ff)
/-- Add with carry (no overflow) -/
def adc (x y : bitvec n) (c : bool) : bitvec (n+1) :=
let f := λ x y c, (bitvec.carry x y c, bitvec.xor3 x y c) in
let ⟨c, z⟩ := vector.map_accumr₂ f x y c in
c :: z
/-- The sum of two bitvectors -/
protected def add (x y : bitvec n) : bitvec n := tail (adc x y ff)
/-- Subtract with borrow -/
def sbb (x y : bitvec n) (b : bool) : bool × bitvec n :=
let f := λ x y c, (bitvec.carry (bnot x) y c, bitvec.xor3 x y c) in
vector.map_accumr₂ f x y b
/-- The difference of two bitvectors -/
protected def sub (x y : bitvec n) : bitvec n := prod.snd (sbb x y ff)
instance : has_zero (bitvec n) := ⟨bitvec.zero n⟩
instance : has_one (bitvec n) := ⟨bitvec.one n⟩
instance : has_add (bitvec n) := ⟨bitvec.add⟩
instance : has_sub (bitvec n) := ⟨bitvec.sub⟩
instance : has_neg (bitvec n) := ⟨bitvec.neg⟩
/-- The product of two bitvectors -/
protected def mul (x y : bitvec n) : bitvec n :=
let f := λ r b, cond b (r + r + y) (r + r) in
(to_list x).foldl f 0
instance : has_mul (bitvec n) := ⟨bitvec.mul⟩
end arith
/-! ### Comparison operators -/
section comparison
variable {n : ℕ}
/-- `uborrow x y` returns `tt` iff the "subtract with borrow" operation on `x`, `y` and `ff`
required a borrow. -/
def uborrow (x y : bitvec n) : bool := prod.fst (sbb x y ff)
/-- unsigned less-than proposition -/
def ult (x y : bitvec n) : Prop := uborrow x y
/-- unsigned greater-than proposition -/
def ugt (x y : bitvec n) : Prop := ult y x
/-- unsigned less-than-or-equal-to proposition -/
def ule (x y : bitvec n) : Prop := ¬ (ult y x)
/-- unsigned greater-than-or-equal-to proposition -/
def uge (x y : bitvec n) : Prop := ule y x
/-- `sborrow x y` returns `tt` iff `x < y` as two's complement integers -/
def sborrow : Π {n : ℕ}, bitvec n → bitvec n → bool
| 0 _ _ := ff
| (succ n) x y :=
match (head x, head y) with
| (tt, ff) := tt
| (ff, tt) := ff
| _ := uborrow (tail x) (tail y)
end
/-- signed less-than proposition -/
def slt (x y : bitvec n) : Prop := sborrow x y
/-- signed greater-than proposition -/
def sgt (x y : bitvec n) : Prop := slt y x
/-- signed less-than-or-equal-to proposition -/
def sle (x y : bitvec n) : Prop := ¬ (slt y x)
/-- signed greater-than-or-equal-to proposition -/
def sge (x y : bitvec n) : Prop := sle y x
end comparison
/-! ### Conversion to `nat` and `int` -/
section conversion
variable {α : Type}
/-- Create a bitvector from a `nat` -/
protected def of_nat : Π (n : ℕ), nat → bitvec n
| 0 x := nil
| (succ n) x := of_nat n (x / 2) ++ₜ to_bool (x % 2 = 1) :: nil
/-- Create a bitvector in the two's complement representation from an `int` -/
protected def of_int : Π (n : ℕ), int → bitvec (succ n)
| n (int.of_nat m) := ff :: bitvec.of_nat n m
| n (int.neg_succ_of_nat m) := tt :: not (bitvec.of_nat n m)
/-- `add_lsb r b` is `r + r + 1` if `b` is `tt` and `r + r` otherwise. -/
def add_lsb (r : ℕ) (b : bool) := r + r + cond b 1 0
/-- Given a `list` of `bool`s, return the `nat` they represent as a list of binary digits. -/
def bits_to_nat (v : list bool) : nat :=
v.foldl add_lsb 0
/-- Return the natural number encoded by the input bitvector -/
protected def to_nat {n : nat} (v : bitvec n) : nat :=
bits_to_nat (to_list v)
theorem bits_to_nat_to_list {n : ℕ} (x : bitvec n) :
bitvec.to_nat x = bits_to_nat (vector.to_list x) := rfl
local attribute [simp] nat.add_comm nat.add_assoc nat.add_left_comm nat.mul_comm nat.mul_assoc
local attribute [simp] nat.zero_add nat.add_zero nat.one_mul nat.mul_one nat.zero_mul nat.mul_zero
-- mul_left_comm
theorem to_nat_append {m : ℕ} (xs : bitvec m) (b : bool) :
bitvec.to_nat (xs ++ₜ b::nil) = bitvec.to_nat xs * 2 + bitvec.to_nat (b::nil) :=
begin
cases xs with xs P,
simp [bits_to_nat_to_list], clear P,
unfold bits_to_nat list.foldl,
-- generalize the accumulator of foldl
generalize h : 0 = x, conv in (add_lsb x b) { rw ←h }, clear h,
simp,
induction xs with x xs generalizing x,
{ simp, unfold list.foldl add_lsb, simp [nat.mul_succ] },
{ simp, apply xs_ih }
end
theorem bits_to_nat_to_bool (n : ℕ)
: bitvec.to_nat (to_bool (n % 2 = 1) :: nil) = n % 2 :=
begin
simp [bits_to_nat_to_list],
unfold bits_to_nat add_lsb list.foldl cond,
simp [cond_to_bool_mod_two],
end
theorem of_nat_succ {k n : ℕ}
: bitvec.of_nat (succ k) n = bitvec.of_nat k (n / 2) ++ₜ to_bool (n % 2 = 1) :: nil :=
rfl
theorem to_nat_of_nat {k n : ℕ}
: bitvec.to_nat (bitvec.of_nat k n) = n % 2 ^ k :=
begin
induction k with k ih generalizing n,
{ simp [nat.mod_one], refl },
{ have h : 0 < 2, { apply le_succ },
rw [of_nat_succ, to_nat_append, ih, bits_to_nat_to_bool, mod_pow_succ h, nat.mul_comm] }
end
/-- Return the integer encoded by the input bitvector -/
protected def to_int : Π {n : nat}, bitvec n → int
| 0 _ := 0
| (succ n) v :=
cond (head v)
(int.neg_succ_of_nat $ bitvec.to_nat $ not $ tail v)
(int.of_nat $ bitvec.to_nat $ tail v)
end conversion
/-! ### Miscellaneous instances -/
private def repr {n : nat} : bitvec n → string
| ⟨bs, p⟩ :=
"0b" ++ (bs.map (λ b : bool, if b then '1' else '0')).as_string
instance (n : nat) : has_repr (bitvec n) :=
⟨repr⟩
end bitvec
instance {n} {x y : bitvec n} : decidable (bitvec.ult x y) := bool.decidable_eq _ _
instance {n} {x y : bitvec n} : decidable (bitvec.ugt x y) := bool.decidable_eq _ _
|
210e90e3033558c727d87e593abc6d5fd7887cc5 | 6ae186a0c6ab366b39397ec9250541c9d5aeb023 | /src/category_theory/products/associator.lean | 2c44ac326f1cc511ee6f077b613c8400b2315911 | [] | no_license | ThanhPhamPhuong/lean-category-theory | 0d5c4fe1137866b4fe29ec2753d99aa0d0667881 | 968a29fe7c0b20e10d8a27e120aca8ddc184e1ea | refs/heads/master | 1,587,206,682,489 | 1,544,045,056,000 | 1,544,045,056,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,583 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Stephen Morgan, Scott Morrison
import category_theory.products
import category_theory.equivalence
open category_theory
namespace category_theory.prod
universes u₁ v₁ u₂ v₂ u₃ v₃
variables (C : Type u₁) [𝒞 : category.{u₁ v₁} C] (D : Type u₂) [𝒟 : category.{u₂ v₂} D] (E : Type u₃) [ℰ : category.{u₃ v₃} E]
include 𝒞 𝒟 ℰ
local attribute [tidy] tactic.assumption
def associator : ((C × D) × E) ⥤ (C × (D × E)) := by tidy
-- { obj := λ X, (X.1.1, (X.1.2, X.2)),
-- map := λ _ _ f, (f.1.1, (f.1.2, f.2)) }
-- @[simp] lemma associator_obj (X) : (associator C D E) X = (X.1.1, (X.1.2, X.2)) := rfl
-- @[simp] lemma associator_map {X Y} (f : X ⟶ Y) : (associator C D E).map f = (f.1.1, (f.1.2, f.2)) := rfl
def inverse_associator : (C × (D × E)) ⥤ ((C × D) × E) := by tidy
-- { obj := λ X, ((X.1, X.2.1), X.2.2),
-- map := λ _ _ f, ((f.1, f.2.1), f.2.2) }
-- @[simp] lemma inverse_associator_obj (X) : (inverse_associator C D E) X = ((X.1, X.2.1), X.2.2) := rfl
-- @[simp] lemma inverse_associator_map {X Y} (f : X ⟶ Y) : (inverse_associator C D E).map f = ((f.1, f.2.1), f.2.2) := rfl
local attribute [back] category.id
def associativity : equivalence ((C × D) × E) (C × (D × E)) := --by obviously -- times out
{ functor := associator C D E,
inverse := inverse_associator C D E, }
-- TODO pentagon natural transformation? satisfying?
end category_theory.prod
|
49781d99eff0b34e911b4e16ddb96bb5ffe3d324 | 4b846d8dabdc64e7ea03552bad8f7fa74763fc67 | /library/init/meta/task.lean | 43c9331dd9a24f72c273a9ad427b812198f92e21 | [
"Apache-2.0"
] | permissive | pacchiano/lean | 9324b33f3ac3b5c5647285160f9f6ea8d0d767dc | fdadada3a970377a6df8afcd629a6f2eab6e84e8 | refs/heads/master | 1,611,357,380,399 | 1,489,870,101,000 | 1,489,870,101,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 727 | lean | prelude
import init.category
meta constant {u} task : Type u → Type u
namespace task
meta constant {u} get {α : Type u} (t : task α) : α
protected meta constant {u} pure {α : Type u} (t : α) : task α
protected meta constant {u v} map {α : Type u} {β : Type v} (f : α → β) (t : task α) : task β
protected meta constant {u} flatten {α : Type u} : task (task α) → task α
protected meta def {u v} bind {α : Type u} {β : Type v} (t : task α) (f : α → task β) : task β :=
task.flatten (task.map f t)
meta instance : monad task :=
{ map := @task.map, bind := @task.bind, pure := @task.pure }
@[inline]
meta def {u} delay {α : Type u} (f : unit → α) : task α :=
task.map f (return ())
end task
|
ca7c46bf31bcf09077517ce225213dc74bbad2d9 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/typeclass_loop.lean | d872a7e269a5e7ef8a6690affadcd0626936bc32 | [
"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 | 123 | lean |
example (M : Type → Type) [Monad M] : ExceptT Unit (ReaderT Unit (StateT Unit M)) Unit := do
let ctx ← read;
pure ()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.