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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6608dda2783bbf13acff7e041ef5c0682ccffe1a | aa2345b30d710f7e75f13157a35845ee6d48c017 | /analysis/topology/topological_space.lean | 06eab0e6dc7e49706b8a9130de23b989f2a99d32 | [
"Apache-2.0"
] | permissive | CohenCyril/mathlib | 5241b20a3fd0ac0133e48e618a5fb7761ca7dcbe | a12d5a192f5923016752f638d19fc1a51610f163 | refs/heads/master | 1,586,031,957,957 | 1,541,432,824,000 | 1,541,432,824,000 | 156,246,337 | 0 | 0 | Apache-2.0 | 1,541,434,514,000 | 1,541,434,513,000 | null | UTF-8 | Lean | false | false | 86,976 | 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
Theory of topological spaces.
Parts of the formalization is based on the books:
N. Bourbaki: General Topology
I. M. James: Topologies and Uniformities
A major difference is that this formalization is heavily based on the filter library.
-/
import order.filter data.set.countable tactic
open set filter lattice classical
local attribute [instance] prop_decidable
universes u v w
structure topological_space (α : Type u) :=
(is_open : set α → Prop)
(is_open_univ : is_open univ)
(is_open_inter : ∀s t, is_open s → is_open t → is_open (s ∩ t))
(is_open_sUnion : ∀s, (∀t∈s, is_open t) → is_open (⋃₀ s))
attribute [class] topological_space
section topological_space
variables {α : Type u} {β : Type v} {ι : Sort w} {a a₁ a₂ : α} {s s₁ s₂ : set α} {p p₁ p₂ : α → Prop}
@[extensionality]
lemma topological_space_eq : ∀ {f g : topological_space α}, f.is_open = g.is_open → f = g
| ⟨a, _, _, _⟩ ⟨b, _, _, _⟩ rfl := rfl
section
variables [t : topological_space α]
include t
/-- `is_open s` means that `s` is open in the ambient topological space on `α` -/
def is_open (s : set α) : Prop := topological_space.is_open t s
@[simp]
lemma is_open_univ : is_open (univ : set α) := topological_space.is_open_univ t
lemma is_open_inter (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∩ s₂) :=
topological_space.is_open_inter t s₁ s₂ h₁ h₂
lemma is_open_sUnion {s : set (set α)} (h : ∀t ∈ s, is_open t) : is_open (⋃₀ s) :=
topological_space.is_open_sUnion t s h
end
lemma is_open_fold {s : set α} {t : topological_space α} : t.is_open s = @is_open α t s :=
rfl
variables [topological_space α]
lemma is_open_Union {f : ι → set α} (h : ∀i, is_open (f i)) : is_open (⋃i, f i) :=
is_open_sUnion $ by rintro _ ⟨i, rfl⟩; exact h i
lemma is_open_bUnion {s : set β} {f : β → set α} (h : ∀i∈s, is_open (f i)) :
is_open (⋃i∈s, f i) :=
is_open_Union $ assume i, is_open_Union $ assume hi, h i hi
lemma is_open_union (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∪ s₂) :=
by rw union_eq_Union; exact is_open_Union (bool.forall_bool.2 ⟨h₂, h₁⟩)
@[simp] lemma is_open_empty : is_open (∅ : set α) :=
by rw ← sUnion_empty; exact is_open_sUnion (assume a, false.elim)
lemma is_open_sInter {s : set (set α)} (hs : finite s) : (∀t ∈ s, is_open t) → is_open (⋂₀ s) :=
finite.induction_on hs (λ _, by rw sInter_empty; exact is_open_univ) $
λ a s has hs ih h, by rw sInter_insert; exact
is_open_inter (h _ $ mem_insert _ _) (ih $ λ t, h t ∘ mem_insert_of_mem _)
lemma is_open_bInter {s : set β} {f : β → set α} (hs : finite s) :
(∀i∈s, is_open (f i)) → is_open (⋂i∈s, f i) :=
finite.induction_on hs
(λ _, by rw bInter_empty; exact is_open_univ)
(λ a s has hs ih h, by rw bInter_insert; exact
is_open_inter (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi))))
lemma is_open_const {p : Prop} : is_open {a : α | p} :=
by_cases
(assume : p, begin simp only [this]; exact is_open_univ end)
(assume : ¬ p, begin simp only [this]; exact is_open_empty end)
lemma is_open_and : is_open {a | p₁ a} → is_open {a | p₂ a} → is_open {a | p₁ a ∧ p₂ a} :=
is_open_inter
/-- A set is closed if its complement is open -/
def is_closed (s : set α) : Prop := is_open (-s)
@[simp] lemma is_closed_empty : is_closed (∅ : set α) :=
by unfold is_closed; rw compl_empty; exact is_open_univ
@[simp] lemma is_closed_univ : is_closed (univ : set α) :=
by unfold is_closed; rw compl_univ; exact is_open_empty
lemma is_closed_union : is_closed s₁ → is_closed s₂ → is_closed (s₁ ∪ s₂) :=
λ h₁ h₂, by unfold is_closed; rw compl_union; exact is_open_inter h₁ h₂
lemma is_closed_sInter {s : set (set α)} : (∀t ∈ s, is_closed t) → is_closed (⋂₀ s) :=
by simp only [is_closed, compl_sInter, sUnion_image]; exact assume h, is_open_Union $ assume t, is_open_Union $ assume ht, h t ht
lemma is_closed_Inter {f : ι → set α} (h : ∀i, is_closed (f i)) : is_closed (⋂i, f i ) :=
is_closed_sInter $ assume t ⟨i, (heq : t = f i)⟩, heq.symm ▸ h i
@[simp] lemma is_open_compl_iff {s : set α} : is_open (-s) ↔ is_closed s := iff.rfl
@[simp] lemma is_closed_compl_iff {s : set α} : is_closed (-s) ↔ is_open s :=
by rw [←is_open_compl_iff, compl_compl]
lemma is_open_diff {s t : set α} (h₁ : is_open s) (h₂ : is_closed t) : is_open (s \ t) :=
is_open_inter h₁ $ is_open_compl_iff.mpr h₂
lemma is_closed_inter (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (s₁ ∩ s₂) :=
by rw [is_closed, compl_inter]; exact is_open_union h₁ h₂
lemma is_closed_Union {s : set β} {f : β → set α} (hs : finite s) :
(∀i∈s, is_closed (f i)) → is_closed (⋃i∈s, f i) :=
finite.induction_on hs
(λ _, by rw bUnion_empty; exact is_closed_empty)
(λ a s has hs ih h, by rw bUnion_insert; exact
is_closed_union (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi))))
lemma is_closed_imp {p q : α → Prop} (hp : is_open {x | p x})
(hq : is_closed {x | q x}) : is_closed {x | p x → q x} :=
have {x | p x → q x} = (- {x | p x}) ∪ {x | q x}, from set.ext $ λ x, imp_iff_not_or,
by rw [this]; exact is_closed_union (is_closed_compl_iff.mpr hp) hq
lemma is_open_neg : is_closed {a | p a} → is_open {a | ¬ p a} :=
is_open_compl_iff.mpr
/-- The interior of a set `s` is the largest open subset of `s`. -/
def interior (s : set α) : set α := ⋃₀ {t | is_open t ∧ t ⊆ s}
lemma mem_interior {s : set α} {x : α} :
x ∈ interior s ↔ ∃ t ⊆ s, is_open t ∧ x ∈ t :=
by simp only [interior, mem_set_of_eq, exists_prop, and_assoc, and.left_comm]
@[simp] lemma is_open_interior {s : set α} : is_open (interior s) :=
is_open_sUnion $ assume t ⟨h₁, h₂⟩, h₁
lemma interior_subset {s : set α} : interior s ⊆ s :=
sUnion_subset $ assume t ⟨h₁, h₂⟩, h₂
lemma interior_maximal {s t : set α} (h₁ : t ⊆ s) (h₂ : is_open t) : t ⊆ interior s :=
subset_sUnion_of_mem ⟨h₂, h₁⟩
lemma interior_eq_of_open {s : set α} (h : is_open s) : interior s = s :=
subset.antisymm interior_subset (interior_maximal (subset.refl s) h)
lemma interior_eq_iff_open {s : set α} : interior s = s ↔ is_open s :=
⟨assume h, h ▸ is_open_interior, interior_eq_of_open⟩
lemma subset_interior_iff_open {s : set α} : s ⊆ interior s ↔ is_open s :=
by simp only [interior_eq_iff_open.symm, subset.antisymm_iff, interior_subset, true_and]
lemma subset_interior_iff_subset_of_open {s t : set α} (h₁ : is_open s) :
s ⊆ interior t ↔ s ⊆ t :=
⟨assume h, subset.trans h interior_subset, assume h₂, interior_maximal h₂ h₁⟩
lemma interior_mono {s t : set α} (h : s ⊆ t) : interior s ⊆ interior t :=
interior_maximal (subset.trans interior_subset h) is_open_interior
@[simp] lemma interior_empty : interior (∅ : set α) = ∅ :=
interior_eq_of_open is_open_empty
@[simp] lemma interior_univ : interior (univ : set α) = univ :=
interior_eq_of_open is_open_univ
@[simp] lemma interior_interior {s : set α} : interior (interior s) = interior s :=
interior_eq_of_open is_open_interior
@[simp] lemma interior_inter {s t : set α} : interior (s ∩ t) = interior s ∩ interior t :=
subset.antisymm
(subset_inter (interior_mono $ inter_subset_left s t) (interior_mono $ inter_subset_right s t))
(interior_maximal (inter_subset_inter interior_subset interior_subset) $ is_open_inter is_open_interior is_open_interior)
lemma interior_union_is_closed_of_interior_empty {s t : set α} (h₁ : is_closed s) (h₂ : interior t = ∅) :
interior (s ∪ t) = interior s :=
have interior (s ∪ t) ⊆ s, from
assume x ⟨u, ⟨(hu₁ : is_open u), (hu₂ : u ⊆ s ∪ t)⟩, (hx₁ : x ∈ u)⟩,
classical.by_contradiction $ assume hx₂ : x ∉ s,
have u \ s ⊆ t,
from assume x ⟨h₁, h₂⟩, or.resolve_left (hu₂ h₁) h₂,
have u \ s ⊆ interior t,
by rwa subset_interior_iff_subset_of_open (is_open_diff hu₁ h₁),
have u \ s ⊆ ∅,
by rwa h₂ at this,
this ⟨hx₁, hx₂⟩,
subset.antisymm
(interior_maximal this is_open_interior)
(interior_mono $ subset_union_left _ _)
lemma is_open_iff_forall_mem_open : is_open s ↔ ∀ x ∈ s, ∃ t ⊆ s, is_open t ∧ x ∈ t :=
by rw ← subset_interior_iff_open; simp only [subset_def, mem_interior]
/-- The closure of `s` is the smallest closed set containing `s`. -/
def closure (s : set α) : set α := ⋂₀ {t | is_closed t ∧ s ⊆ t}
@[simp] lemma is_closed_closure {s : set α} : is_closed (closure s) :=
is_closed_sInter $ assume t ⟨h₁, h₂⟩, h₁
lemma subset_closure {s : set α} : s ⊆ closure s :=
subset_sInter $ assume t ⟨h₁, h₂⟩, h₂
lemma closure_minimal {s t : set α} (h₁ : s ⊆ t) (h₂ : is_closed t) : closure s ⊆ t :=
sInter_subset_of_mem ⟨h₂, h₁⟩
lemma closure_eq_of_is_closed {s : set α} (h : is_closed s) : closure s = s :=
subset.antisymm (closure_minimal (subset.refl s) h) subset_closure
lemma closure_eq_iff_is_closed {s : set α} : closure s = s ↔ is_closed s :=
⟨assume h, h ▸ is_closed_closure, closure_eq_of_is_closed⟩
lemma closure_subset_iff_subset_of_is_closed {s t : set α} (h₁ : is_closed t) :
closure s ⊆ t ↔ s ⊆ t :=
⟨subset.trans subset_closure, assume h, closure_minimal h h₁⟩
lemma closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t :=
closure_minimal (subset.trans h subset_closure) is_closed_closure
@[simp] lemma closure_empty : closure (∅ : set α) = ∅ :=
closure_eq_of_is_closed is_closed_empty
lemma closure_empty_iff (s : set α) : closure s = ∅ ↔ s = ∅ :=
begin
split; intro h,
{ rw set.eq_empty_iff_forall_not_mem,
intros x H,
simpa only [h] using subset_closure H },
{ exact (eq.symm h) ▸ closure_empty },
end
@[simp] lemma closure_univ : closure (univ : set α) = univ :=
closure_eq_of_is_closed is_closed_univ
@[simp] lemma closure_closure {s : set α} : closure (closure s) = closure s :=
closure_eq_of_is_closed is_closed_closure
@[simp] lemma closure_union {s t : set α} : closure (s ∪ t) = closure s ∪ closure t :=
subset.antisymm
(closure_minimal (union_subset_union subset_closure subset_closure) $ is_closed_union is_closed_closure is_closed_closure)
(union_subset (closure_mono $ subset_union_left _ _) (closure_mono $ subset_union_right _ _))
lemma interior_subset_closure {s : set α} : interior s ⊆ closure s :=
subset.trans interior_subset subset_closure
lemma closure_eq_compl_interior_compl {s : set α} : closure s = - interior (- s) :=
begin
unfold interior closure is_closed,
rw [compl_sUnion, compl_image_set_of],
simp only [compl_subset_compl]
end
@[simp] lemma interior_compl {s : set α} : interior (- s) = - closure s :=
by simp [closure_eq_compl_interior_compl]
@[simp] lemma closure_compl {s : set α} : closure (- s) = - interior s :=
by simp [closure_eq_compl_interior_compl]
theorem mem_closure_iff {s : set α} {a : α} : a ∈ closure s ↔ ∀ o, is_open o → a ∈ o → o ∩ s ≠ ∅ :=
⟨λ h o oo ao os,
have s ⊆ -o, from λ x xs xo, @ne_empty_of_mem α (o∩s) x ⟨xo, xs⟩ os,
closure_minimal this (is_closed_compl_iff.2 oo) h ao,
λ H c ⟨h₁, h₂⟩, classical.by_contradiction $ λ nc,
let ⟨x, hc, hs⟩ := exists_mem_of_ne_empty (H _ h₁ nc) in hc (h₂ hs)⟩
lemma dense_iff_inter_open {s : set α} : closure s = univ ↔ ∀ U, is_open U → U ≠ ∅ → U ∩ s ≠ ∅ :=
begin
split ; intro h,
{ intros U U_op U_ne,
cases exists_mem_of_ne_empty U_ne with x x_in,
exact mem_closure_iff.1 (by simp only [h]) U U_op x_in },
{ apply eq_univ_of_forall, intro x,
rw mem_closure_iff,
intros U U_op x_in,
exact h U U_op (ne_empty_of_mem x_in) },
end
/-- The frontier of a set is the set of points between the closure and interior. -/
def frontier (s : set α) : set α := closure s \ interior s
lemma frontier_eq_closure_inter_closure {s : set α} :
frontier s = closure s ∩ closure (- s) :=
by rw [closure_compl, frontier, diff_eq]
@[simp] lemma frontier_compl (s : set α) : frontier (-s) = frontier s :=
by simp only [frontier_eq_closure_inter_closure, lattice.neg_neg, inter_comm]
/-- neighbourhood filter -/
def nhds (a : α) : filter α := (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, principal s)
lemma tendsto_nhds {m : β → α} {f : filter β} (h : ∀s, a ∈ s → is_open s → m ⁻¹' s ∈ f.sets) :
tendsto m f (nhds a) :=
show map m f ≤ (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, principal s),
from le_infi $ assume s, le_infi $ assume ⟨ha, hs⟩, le_principal_iff.mpr $ h s ha hs
lemma tendsto_const_nhds {a : α} {f : filter β} : tendsto (λb:β, a) f (nhds a) :=
tendsto_nhds $ assume s ha hs, univ_mem_sets' $ assume _, ha
lemma nhds_sets {a : α} : (nhds a).sets = {s | ∃t⊆s, is_open t ∧ a ∈ t} :=
calc (nhds a).sets = (⋃s∈{s : set α| a ∈ s ∧ is_open s}, (principal s).sets) : infi_sets_eq'
(assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩,
⟨x ∩ y, ⟨⟨hx₁, hy₁⟩, is_open_inter hx₂ hy₂⟩,
le_principal_iff.2 (inter_subset_left _ _),
le_principal_iff.2 (inter_subset_right _ _)⟩)
⟨univ, mem_univ _, is_open_univ⟩
... = {s | ∃t⊆s, is_open t ∧ a ∈ t} :
le_antisymm
(supr_le $ assume i, supr_le $ assume ⟨hi₁, hi₂⟩ t ht, ⟨i, ht, hi₂, hi₁⟩)
(assume t ⟨i, hi₁, hi₂, hi₃⟩, mem_Union.2 ⟨i, mem_Union.2 ⟨⟨hi₃, hi₂⟩, hi₁⟩⟩)
lemma map_nhds {a : α} {f : α → β} :
map f (nhds a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, principal (image f s)) :=
calc map f (nhds a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, map f (principal s)) :
map_binfi_eq
(assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩,
⟨x ∩ y, ⟨⟨hx₁, hy₁⟩, is_open_inter hx₂ hy₂⟩,
le_principal_iff.2 (inter_subset_left _ _),
le_principal_iff.2 (inter_subset_right _ _)⟩)
⟨univ, mem_univ _, is_open_univ⟩
... = _ : by simp only [map_principal]
lemma mem_nhds_sets_iff {a : α} {s : set α} :
s ∈ (nhds a).sets ↔ ∃t⊆s, is_open t ∧ a ∈ t :=
by simp only [nhds_sets, mem_set_of_eq, exists_prop]
lemma mem_of_nhds {a : α} {s : set α} : s ∈ (nhds a).sets → a ∈ s :=
λ H, let ⟨t, ht, _, hs⟩ := mem_nhds_sets_iff.1 H in ht hs
lemma mem_nhds_sets {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) :
s ∈ (nhds a).sets :=
mem_nhds_sets_iff.2 ⟨s, subset.refl _, hs, ha⟩
lemma pure_le_nhds : pure ≤ (nhds : α → filter α) :=
assume a, le_infi $ assume s, le_infi $ assume ⟨h₁, _⟩, principal_mono.mpr $
singleton_subset_iff.2 h₁
lemma tendsto_pure_nhds [topological_space β] (f : α → β) (a : α) :
tendsto f (pure a) (nhds (f a)) :=
begin
rw [tendsto, filter.map_pure],
exact pure_le_nhds (f a)
end
@[simp] lemma nhds_neq_bot {a : α} : nhds a ≠ ⊥ :=
assume : nhds a = ⊥,
have pure a = (⊥ : filter α),
from lattice.bot_unique $ this ▸ pure_le_nhds a,
pure_neq_bot this
lemma interior_eq_nhds {s : set α} : interior s = {a | nhds a ≤ principal s} :=
set.ext $ λ x, by simp only [mem_interior, le_principal_iff, mem_nhds_sets_iff]; refl
lemma mem_interior_iff_mem_nhds {s : set α} {a : α} :
a ∈ interior s ↔ s ∈ (nhds a).sets :=
by simp only [interior_eq_nhds, le_principal_iff]; refl
lemma is_open_iff_nhds {s : set α} : is_open s ↔ ∀a∈s, nhds a ≤ principal s :=
calc is_open s ↔ s ⊆ interior s : subset_interior_iff_open.symm
... ↔ (∀a∈s, nhds a ≤ principal s) : by rw [interior_eq_nhds]; refl
lemma is_open_iff_mem_nhds {s : set α} : is_open s ↔ ∀a∈s, s ∈ (nhds a).sets :=
is_open_iff_nhds.trans $ forall_congr $ λ _, imp_congr_right $ λ _, le_principal_iff
lemma closure_eq_nhds {s : set α} : closure s = {a | nhds a ⊓ principal s ≠ ⊥} :=
calc closure s = - interior (- s) : closure_eq_compl_interior_compl
... = {a | ¬ nhds a ≤ principal (-s)} : by rw [interior_eq_nhds]; refl
... = {a | nhds a ⊓ principal s ≠ ⊥} : set.ext $ assume a, not_congr
(inf_eq_bot_iff_le_compl
(show principal s ⊔ principal (-s) = ⊤, by simp only [sup_principal, union_compl_self, principal_univ])
(by simp only [inf_principal, inter_compl_self, principal_empty])).symm
theorem mem_closure_iff_nhds {s : set α} {a : α} : a ∈ closure s ↔ ∀ t ∈ (nhds a).sets, t ∩ s ≠ ∅ :=
mem_closure_iff.trans
⟨λ H t ht, subset_ne_empty
(inter_subset_inter_left _ interior_subset)
(H _ is_open_interior (mem_interior_iff_mem_nhds.2 ht)),
λ H o oo ao, H _ (mem_nhds_sets oo ao)⟩
/-- `x` belongs to the closure of `s` if and only if some ultrafilter
supported on `s` converges to `x`. -/
lemma mem_closure_iff_ultrafilter {s : set α} {x : α} :
x ∈ closure s ↔ ∃ (u : ultrafilter α), s ∈ u.val.sets ∧ u.val ≤ nhds x :=
begin
rw closure_eq_nhds, change nhds x ⊓ principal s ≠ ⊥ ↔ _, symmetry,
convert exists_ultrafilter_iff _, ext u,
rw [←le_principal_iff, inf_comm, le_inf_iff]
end
lemma is_closed_iff_nhds {s : set α} : is_closed s ↔ ∀a, nhds a ⊓ principal s ≠ ⊥ → a ∈ s :=
calc is_closed s ↔ closure s = s : by rw [closure_eq_iff_is_closed]
... ↔ closure s ⊆ s : ⟨assume h, by rw h, assume h, subset.antisymm h subset_closure⟩
... ↔ (∀a, nhds a ⊓ principal s ≠ ⊥ → a ∈ s) : by rw [closure_eq_nhds]; refl
lemma closure_inter_open {s t : set α} (h : is_open s) : s ∩ closure t ⊆ closure (s ∩ t) :=
assume a ⟨hs, ht⟩,
have s ∈ (nhds a).sets, from mem_nhds_sets h hs,
have nhds a ⊓ principal s = nhds a, from inf_of_le_left $ by rwa le_principal_iff,
have nhds a ⊓ principal (s ∩ t) ≠ ⊥,
from calc nhds a ⊓ principal (s ∩ t) = nhds a ⊓ (principal s ⊓ principal t) : by rw inf_principal
... = nhds a ⊓ principal t : by rw [←inf_assoc, this]
... ≠ ⊥ : by rw [closure_eq_nhds] at ht; assumption,
by rw [closure_eq_nhds]; assumption
lemma closure_diff {s t : set α} : closure s - closure t ⊆ closure (s - t) :=
calc closure s \ closure t = (- closure t) ∩ closure s : by simp only [diff_eq, inter_comm]
... ⊆ closure (- closure t ∩ s) : closure_inter_open $ is_open_compl_iff.mpr $ is_closed_closure
... = closure (s \ closure t) : by simp only [diff_eq, inter_comm]
... ⊆ closure (s \ t) : closure_mono $ diff_subset_diff (subset.refl s) subset_closure
lemma mem_of_closed_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α}
(hb : b ≠ ⊥) (hf : tendsto f b (nhds a)) (hs : is_closed s) (h : f ⁻¹' s ∈ b.sets) : a ∈ s :=
have b.map f ≤ nhds a ⊓ principal s,
from le_trans (le_inf (le_refl _) (le_principal_iff.mpr h)) (inf_le_inf hf (le_refl _)),
is_closed_iff_nhds.mp hs a $ neq_bot_of_le_neq_bot (map_ne_bot hb) this
lemma mem_closure_of_tendsto {f : β → α} {x : filter β} {a : α} {s : set α}
(hf : tendsto f x (nhds a)) (hs : is_closed s) (h : x ⊓ principal (f ⁻¹' s) ≠ ⊥) : a ∈ s :=
is_closed_iff_nhds.mp hs _ $ neq_bot_of_le_neq_bot (@map_ne_bot _ _ _ f h) $
le_inf (le_trans (map_mono $ inf_le_left) hf) $
le_trans (map_mono $ inf_le_right_of_le $ by simp only [comap_principal, le_principal_iff]; exact subset.refl _) (@map_comap_le _ _ _ f)
/- locally finite family [General Topology (Bourbaki, 1995)] -/
section locally_finite
/-- A family of sets in `set α` is locally finite if at every point `x:α`,
there is a neighborhood of `x` which meets only finitely many sets in the family -/
def locally_finite (f : β → set α) :=
∀x:α, ∃t∈(nhds x).sets, finite {i | f i ∩ t ≠ ∅ }
lemma locally_finite_of_finite {f : β → set α} (h : finite (univ : set β)) : locally_finite f :=
assume x, ⟨univ, univ_mem_sets, finite_subset h $ subset_univ _⟩
lemma locally_finite_subset
{f₁ f₂ : β → set α} (hf₂ : locally_finite f₂) (hf : ∀b, f₁ b ⊆ f₂ b) : locally_finite f₁ :=
assume a,
let ⟨t, ht₁, ht₂⟩ := hf₂ a in
⟨t, ht₁, finite_subset ht₂ $ assume i hi,
neq_bot_of_le_neq_bot hi $ inter_subset_inter (hf i) $ subset.refl _⟩
lemma is_closed_Union_of_locally_finite {f : β → set α}
(h₁ : locally_finite f) (h₂ : ∀i, is_closed (f i)) : is_closed (⋃i, f i) :=
is_open_iff_nhds.mpr $ assume a, assume h : a ∉ (⋃i, f i),
have ∀i, a ∈ -f i,
from assume i hi, h $ mem_Union.2 ⟨i, hi⟩,
have ∀i, - f i ∈ (nhds a).sets,
by rw [nhds_sets]; exact assume i, ⟨- f i, subset.refl _, h₂ i, this i⟩,
let ⟨t, h_sets, (h_fin : finite {i | f i ∩ t ≠ ∅ })⟩ := h₁ a in
calc nhds a ≤ principal (t ∩ (⋂ i∈{i | f i ∩ t ≠ ∅ }, - f i)) :
begin
rw [le_principal_iff],
apply @filter.inter_mem_sets _ (nhds a) _ _ h_sets,
apply @filter.Inter_mem_sets _ (nhds a) _ _ _ h_fin,
exact assume i h, this i
end
... ≤ principal (- ⋃i, f i) :
begin
simp only [principal_mono, subset_def, mem_compl_eq, mem_inter_eq,
mem_Inter, mem_set_of_eq, mem_Union, and_imp, not_exists,
not_eq_empty_iff_exists, exists_imp_distrib, (≠)],
exact assume x xt ht i xfi, ht i x xfi xt xfi
end
end locally_finite
/- compact sets -/
section compact
/-- A set `s` is compact if for every filter `f` that contains `s`,
every set of `f` also meets every neighborhood of some `a ∈ s`. -/
def compact (s : set α) := ∀f, f ≠ ⊥ → f ≤ principal s → ∃a∈s, f ⊓ nhds a ≠ ⊥
lemma compact_inter {s t : set α} (hs : compact s) (ht : is_closed t) : compact (s ∩ t) :=
assume f hnf hstf,
let ⟨a, hsa, (ha : f ⊓ nhds a ≠ ⊥)⟩ := hs f hnf (le_trans hstf (le_principal_iff.2 (inter_subset_left _ _))) in
have ∀a, principal t ⊓ nhds a ≠ ⊥ → a ∈ t,
by intro a; rw [inf_comm]; rw [is_closed_iff_nhds] at ht; exact ht a,
have a ∈ t,
from this a $ neq_bot_of_le_neq_bot ha $ inf_le_inf (le_trans hstf (le_principal_iff.2 (inter_subset_right _ _))) (le_refl _),
⟨a, ⟨hsa, this⟩, ha⟩
lemma compact_diff {s t : set α} (hs : compact s) (ht : is_open t) : compact (s \ t) :=
compact_inter hs (is_closed_compl_iff.mpr ht)
lemma compact_of_is_closed_subset {s t : set α}
(hs : compact s) (ht : is_closed t) (h : t ⊆ s) : compact t :=
by convert ← compact_inter hs ht; exact inter_eq_self_of_subset_right h
lemma compact_adherence_nhdset {s t : set α} {f : filter α}
(hs : compact s) (hf₂ : f ≤ principal s) (ht₁ : is_open t) (ht₂ : ∀a∈s, nhds a ⊓ f ≠ ⊥ → a ∈ t) :
t ∈ f.sets :=
classical.by_cases mem_sets_of_neq_bot $
assume : f ⊓ principal (- t) ≠ ⊥,
let ⟨a, ha, (hfa : f ⊓ principal (-t) ⊓ nhds a ≠ ⊥)⟩ := hs _ this $ inf_le_left_of_le hf₂ in
have a ∈ t,
from ht₂ a ha $ neq_bot_of_le_neq_bot hfa $ le_inf inf_le_right $ inf_le_left_of_le inf_le_left,
have nhds a ⊓ principal (-t) ≠ ⊥,
from neq_bot_of_le_neq_bot hfa $ le_inf inf_le_right $ inf_le_left_of_le inf_le_right,
have ∀s∈(nhds a ⊓ principal (-t)).sets, s ≠ ∅,
from forall_sets_neq_empty_iff_neq_bot.mpr this,
have false,
from this _ ⟨t, mem_nhds_sets ht₁ ‹a ∈ t›, -t, subset.refl _, subset.refl _⟩ (inter_compl_self _),
by contradiction
lemma compact_iff_ultrafilter_le_nhds {s : set α} :
compact s ↔ (∀f, is_ultrafilter f → f ≤ principal s → ∃a∈s, f ≤ nhds a) :=
⟨assume hs : compact s, assume f hf hfs,
let ⟨a, ha, h⟩ := hs _ hf.left hfs in
⟨a, ha, le_of_ultrafilter hf h⟩,
assume hs : (∀f, is_ultrafilter f → f ≤ principal s → ∃a∈s, f ≤ nhds a),
assume f hf hfs,
let ⟨a, ha, (h : ultrafilter_of f ≤ nhds a)⟩ :=
hs (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs) in
have ultrafilter_of f ⊓ nhds a ≠ ⊥,
by simp only [inf_of_le_left, h]; exact (ultrafilter_ultrafilter_of hf).left,
⟨a, ha, neq_bot_of_le_neq_bot this (inf_le_inf ultrafilter_of_le (le_refl _))⟩⟩
lemma compact_elim_finite_subcover {s : set α} {c : set (set α)}
(hs : compact s) (hc₁ : ∀t∈c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c' :=
classical.by_contradiction $ assume h,
have h : ∀{c'}, c' ⊆ c → finite c' → ¬ s ⊆ ⋃₀ c',
from assume c' h₁ h₂ h₃, h ⟨c', h₁, h₂, h₃⟩,
let
f : filter α := (⨅c':{c' : set (set α) // c' ⊆ c ∧ finite c'}, principal (s - ⋃₀ c')),
⟨a, ha⟩ := @exists_mem_of_ne_empty α s
(assume h', h (empty_subset _) finite_empty $ h'.symm ▸ empty_subset _)
in
have f ≠ ⊥, from infi_neq_bot_of_directed ⟨a⟩
(assume ⟨c₁, hc₁, hc'₁⟩ ⟨c₂, hc₂, hc'₂⟩, ⟨⟨c₁ ∪ c₂, union_subset hc₁ hc₂, finite_union hc'₁ hc'₂⟩,
principal_mono.mpr $ diff_subset_diff_right $ sUnion_mono $ subset_union_left _ _,
principal_mono.mpr $ diff_subset_diff_right $ sUnion_mono $ subset_union_right _ _⟩)
(assume ⟨c', hc'₁, hc'₂⟩, show principal (s \ _) ≠ ⊥, by simp only [ne.def, principal_eq_bot_iff, diff_eq_empty]; exact h hc'₁ hc'₂),
have f ≤ principal s, from infi_le_of_le ⟨∅, empty_subset _, finite_empty⟩ $
show principal (s \ ⋃₀∅) ≤ principal s, from le_principal_iff.2 (diff_subset _ _),
let
⟨a, ha, (h : f ⊓ nhds a ≠ ⊥)⟩ := hs f ‹f ≠ ⊥› this,
⟨t, ht₁, (ht₂ : a ∈ t)⟩ := hc₂ ha
in
have f ≤ principal (-t),
from infi_le_of_le ⟨{t}, by rwa singleton_subset_iff, finite_insert _ finite_empty⟩ $
principal_mono.mpr $
show s - ⋃₀{t} ⊆ - t, begin rw sUnion_singleton; exact assume x ⟨_, hnt⟩, hnt end,
have is_closed (- t), from is_open_compl_iff.mp $ by rw lattice.neg_neg; exact hc₁ t ht₁,
have a ∈ - t, from is_closed_iff_nhds.mp this _ $ neq_bot_of_le_neq_bot h $
le_inf inf_le_right (inf_le_left_of_le ‹f ≤ principal (- t)›),
this ‹a ∈ t›
lemma compact_elim_finite_subcover_image {s : set α} {b : set β} {c : β → set α}
(hs : compact s) (hc₁ : ∀i∈b, is_open (c i)) (hc₂ : s ⊆ ⋃i∈b, c i) :
∃b'⊆b, finite b' ∧ s ⊆ ⋃i∈b', c i :=
if h : b = ∅ then ⟨∅, empty_subset _, finite_empty, h ▸ hc₂⟩ else
let ⟨i, hi⟩ := exists_mem_of_ne_empty h in
have hc'₁ : ∀i∈c '' b, is_open i, from assume i ⟨j, hj, h⟩, h ▸ hc₁ _ hj,
have hc'₂ : s ⊆ ⋃₀ (c '' b), by rwa set.sUnion_image,
let ⟨d, hd₁, hd₂, hd₃⟩ := compact_elim_finite_subcover hs hc'₁ hc'₂ in
have ∀x : d, ∃i, i ∈ b ∧ c i = x, from assume ⟨x, hx⟩, hd₁ hx,
let ⟨f', hf⟩ := axiom_of_choice this,
f := λx:set α, (if h : x ∈ d then f' ⟨x, h⟩ else i : β) in
have ∀(x : α) (i : set α), i ∈ d → x ∈ i → (∃ (i : β), i ∈ f '' d ∧ x ∈ c i),
from assume x i hid hxi, ⟨f i, mem_image_of_mem f hid,
by simpa only [f, dif_pos hid, (hf ⟨_, hid⟩).2] using hxi⟩,
⟨f '' d,
assume i ⟨j, hj, h⟩,
h ▸ by simpa only [f, dif_pos hj] using (hf ⟨_, hj⟩).1,
finite_image f hd₂,
subset.trans hd₃ $ by simpa only [subset_def, mem_sUnion, exists_imp_distrib, mem_Union, exists_prop, and_imp]⟩
lemma compact_of_finite_subcover {s : set α}
(h : ∀c, (∀t∈c, is_open t) → s ⊆ ⋃₀ c → ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c') : compact s :=
assume f hfn hfs, classical.by_contradiction $ assume : ¬ (∃x∈s, f ⊓ nhds x ≠ ⊥),
have hf : ∀x∈s, nhds x ⊓ f = ⊥,
by simpa only [not_exists, not_not, inf_comm],
have ¬ ∃x∈s, ∀t∈f.sets, x ∈ closure t,
from assume ⟨x, hxs, hx⟩,
have ∅ ∈ (nhds x ⊓ f).sets, by rw [empty_in_sets_eq_bot, hf x hxs],
let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := by rw [mem_inf_sets] at this; exact this in
have ∅ ∈ (nhds x ⊓ principal t₂).sets,
from (nhds x ⊓ principal t₂).sets_of_superset (inter_mem_inf_sets ht₁ (subset.refl t₂)) ht,
have nhds x ⊓ principal t₂ = ⊥,
by rwa [empty_in_sets_eq_bot] at this,
by simp only [closure_eq_nhds] at hx; exact hx t₂ ht₂ this,
have ∀x∈s, ∃t∈f.sets, x ∉ closure t, by simpa only [not_exists, not_forall],
let c := (λt, - closure t) '' f.sets, ⟨c', hcc', hcf, hsc'⟩ := h c
(assume t ⟨s, hs, h⟩, h ▸ is_closed_closure) (by simpa only [subset_def, sUnion_image, mem_Union]) in
let ⟨b, hb⟩ := axiom_of_choice $
show ∀s:c', ∃t, t ∈ f.sets ∧ - closure t = s,
from assume ⟨x, hx⟩, hcc' hx in
have (⋂s∈c', if h : s ∈ c' then b ⟨s, h⟩ else univ) ∈ f.sets,
from Inter_mem_sets hcf $ assume t ht, by rw [dif_pos ht]; exact (hb ⟨t, ht⟩).left,
have s ∩ (⋂s∈c', if h : s ∈ c' then b ⟨s, h⟩ else univ) ∈ f.sets,
from inter_mem_sets (le_principal_iff.1 hfs) this,
have ∅ ∈ f.sets,
from mem_sets_of_superset this $ assume x ⟨hxs, hxi⟩,
let ⟨t, htc', hxt⟩ := (show ∃t ∈ c', x ∈ t, from hsc' hxs) in
have -closure (b ⟨t, htc'⟩) = t, from (hb _).right,
have x ∈ - t,
from this ▸ (calc x ∈ b ⟨t, htc'⟩ : by rw mem_bInter_iff at hxi; have h := hxi t htc'; rwa [dif_pos htc'] at h
... ⊆ closure (b ⟨t, htc'⟩) : subset_closure
... ⊆ - - closure (b ⟨t, htc'⟩) : by rw lattice.neg_neg; exact subset.refl _),
show false, from this hxt,
hfn $ by rwa [empty_in_sets_eq_bot] at this
lemma compact_iff_finite_subcover {s : set α} :
compact s ↔ (∀c, (∀t∈c, is_open t) → s ⊆ ⋃₀ c → ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c') :=
⟨assume hc c, compact_elim_finite_subcover hc, compact_of_finite_subcover⟩
lemma compact_empty : compact (∅ : set α) :=
assume f hnf hsf, not.elim hnf $
empty_in_sets_eq_bot.1 $ le_principal_iff.1 hsf
lemma compact_singleton {a : α} : compact ({a} : set α) :=
compact_of_finite_subcover $ assume c hc₁ hc₂,
let ⟨i, hic, hai⟩ := (show ∃i ∈ c, a ∈ i, from mem_sUnion.1 $ singleton_subset_iff.1 hc₂) in
⟨{i}, singleton_subset_iff.2 hic, finite_singleton _, by rwa [sUnion_singleton, singleton_subset_iff]⟩
lemma compact_bUnion_of_compact {s : set β} {f : β → set α} (hs : finite s) :
(∀i ∈ s, compact (f i)) → compact (⋃i ∈ s, f i) :=
assume hf, compact_of_finite_subcover $ assume c c_open c_cover,
have ∀i : subtype s, ∃c' ⊆ c, finite c' ∧ f i ⊆ ⋃₀ c', from
assume ⟨i, hi⟩, compact_elim_finite_subcover (hf i hi) c_open
(calc f i ⊆ ⋃i ∈ s, f i : subset_bUnion_of_mem hi
... ⊆ ⋃₀ c : c_cover),
let ⟨finite_subcovers, h⟩ := axiom_of_choice this in
let c' := ⋃i, finite_subcovers i in
have c' ⊆ c, from Union_subset (λi, (h i).fst),
have finite c', from @finite_Union _ _ hs.fintype _ (λi, (h i).snd.1),
have (⋃i ∈ s, f i) ⊆ ⋃₀ c', from bUnion_subset $ λi hi, calc
f i ⊆ ⋃₀ finite_subcovers ⟨i,hi⟩ : (h ⟨i,hi⟩).snd.2
... ⊆ ⋃₀ c' : sUnion_mono (subset_Union _ _),
⟨c', ‹c' ⊆ c›, ‹finite c'›, this⟩
lemma compact_of_finite {s : set α} (hs : finite s) : compact s :=
let s' : set α := ⋃i ∈ s, {i} in
have e : s' = s, from ext $ λi, by simp only [mem_bUnion_iff, mem_singleton_iff, exists_eq_right'],
have compact s', from compact_bUnion_of_compact hs (λ_ _, compact_singleton),
e ▸ this
end compact
section clopen
def is_clopen (s : set α) : Prop :=
is_open s ∧ is_closed s
theorem is_clopen_union {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∪ t) :=
⟨is_open_union hs.1 ht.1, is_closed_union hs.2 ht.2⟩
theorem is_clopen_inter {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∩ t) :=
⟨is_open_inter hs.1 ht.1, is_closed_inter hs.2 ht.2⟩
@[simp] theorem is_clopen_empty : is_clopen (∅ : set α) :=
⟨is_open_empty, is_closed_empty⟩
@[simp] theorem is_clopen_univ : is_clopen (univ : set α) :=
⟨is_open_univ, is_closed_univ⟩
theorem is_clopen_compl {s : set α} (hs : is_clopen s) : is_clopen (-s) :=
⟨hs.2, is_closed_compl_iff.2 hs.1⟩
@[simp] theorem is_clopen_compl_iff {s : set α} : is_clopen (-s) ↔ is_clopen s :=
⟨λ h, compl_compl s ▸ is_clopen_compl h, is_clopen_compl⟩
theorem is_clopen_diff {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s-t) :=
is_clopen_inter hs (is_clopen_compl ht)
end clopen
section irreducible
/-- A irreducible set is one where there is no non-trivial pair of disjoint opens. -/
def is_irreducible (s : set α) : Prop :=
∀ (u v : set α), is_open u → is_open v →
(∃ x, x ∈ s ∩ u) → (∃ x, x ∈ s ∩ v) → ∃ x, x ∈ s ∩ (u ∩ v)
theorem is_irreducible_empty : is_irreducible (∅ : set α) :=
λ _ _ _ _ _ ⟨x, h1, h2⟩, h1.elim
theorem is_irreducible_singleton {x} : is_irreducible ({x} : set α) :=
λ u v _ _ ⟨y, h1, h2⟩ ⟨z, h3, h4⟩, by rw mem_singleton_iff at h1 h3;
substs y z; exact ⟨x, or.inl rfl, h2, h4⟩
theorem is_irreducible_closure {s : set α} (H : is_irreducible s) :
is_irreducible (closure s) :=
λ u v hu hv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩,
let ⟨p, hpu, hps⟩ := exists_mem_of_ne_empty (mem_closure_iff.1 hycs u hu hyu) in
let ⟨q, hqv, hqs⟩ := exists_mem_of_ne_empty (mem_closure_iff.1 hzcs v hv hzv) in
let ⟨r, hrs, hruv⟩ := H u v hu hv ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in
⟨r, subset_closure hrs, hruv⟩
theorem exists_irreducible (s : set α) (H : is_irreducible s) :
∃ t : set α, is_irreducible t ∧ s ⊆ t ∧ ∀ u, is_irreducible u → t ⊆ u → u = t :=
let ⟨⟨m, hsm, hm⟩, hm_max⟩ := @zorn.zorn { t | s ⊆ t ∧ is_irreducible t } (subrel (⊆) _)
(λ c hchain, classical.by_cases
(assume hc : c = ∅, ⟨⟨s, set.subset.refl s, H⟩, λ ⟨t, hsx, hx⟩,
hc.symm ▸ false.elim⟩)
(assume hc : c ≠ ∅, let ⟨⟨x, hsx, hx⟩, hxc⟩ := exists_mem_of_ne_empty hc in
⟨⟨⋃ t ∈ c, subtype.val t, λ z hz, mem_bUnion hxc (hsx hz), λ u v hu hv ⟨y, hy, hyu⟩ ⟨z, hz, hzv⟩,
let ⟨p, hpc, hyp⟩ := mem_bUnion_iff.1 hy,
⟨q, hqc, hzq⟩ := mem_bUnion_iff.1 hz in
or.cases_on (zorn.chain.total hchain hpc hqc)
(assume hpq : p.1 ⊆ q.1, let ⟨x, hxp, hxuv⟩ := q.2.2 u v hu hv
⟨y, hpq hyp, hyu⟩ ⟨z, hzq, hzv⟩ in
⟨x, mem_bUnion hqc hxp, hxuv⟩)
(assume hqp : q.1 ⊆ p, let ⟨x, hxp, hxuv⟩ := p.2.2 u v hu hv
⟨y, hyp, hyu⟩ ⟨z, hqp hzq, hzv⟩ in
⟨x, mem_bUnion hpc hxp, hxuv⟩)⟩,
λ ⟨p, hsp, hp⟩ hpc z hzp, mem_bUnion hpc hzp⟩))
(λ _ _ _, set.subset.trans) in
⟨m, hm, hsm, λ u hu hmu, subset.antisymm (hm_max ⟨_, set.subset.trans hsm hmu, hu⟩ hmu) hmu⟩
def irreducible_component (x : α) : set α :=
classical.some (exists_irreducible {x} is_irreducible_singleton)
theorem is_irreducible_irreducible_component {x : α} : is_irreducible (irreducible_component x) :=
(classical.some_spec (exists_irreducible {x} is_irreducible_singleton)).1
theorem mem_irreducible_component {x : α} : x ∈ irreducible_component x :=
singleton_subset_iff.1
(classical.some_spec (exists_irreducible {x} is_irreducible_singleton)).2.1
theorem eq_irreducible_component {x : α} :
∀ {s : set α}, is_irreducible s → irreducible_component x ⊆ s → s = irreducible_component x :=
(classical.some_spec (exists_irreducible {x} is_irreducible_singleton)).2.2
theorem is_closed_irreducible_component {x : α} :
is_closed (irreducible_component x) :=
closure_eq_iff_is_closed.1 $ eq_irreducible_component
(is_irreducible_closure is_irreducible_irreducible_component)
subset_closure
/-- A irreducible space is one where there is no non-trivial pair of disjoint opens. -/
class irreducible_space (α : Type u) [topological_space α] : Prop :=
(is_irreducible_univ : is_irreducible (univ : set α))
theorem irreducible_exists_mem_inter [irreducible_space α] {s t : set α} :
is_open s → is_open t → (∃ x, x ∈ s) → (∃ x, x ∈ t) → ∃ x, x ∈ s ∩ t :=
by simpa only [univ_inter, univ_subset_iff] using
@irreducible_space.is_irreducible_univ α _ _ s t
end irreducible
section connected
/-- A connected set is one where there is no non-trivial open partition. -/
def is_connected (s : set α) : Prop :=
∀ (u v : set α), is_open u → is_open v → s ⊆ u ∪ v →
(∃ x, x ∈ s ∩ u) → (∃ x, x ∈ s ∩ v) → ∃ x, x ∈ s ∩ (u ∩ v)
theorem is_connected_of_is_irreducible {s : set α} (H : is_irreducible s) : is_connected s :=
λ _ _ hu hv _, H _ _ hu hv
theorem is_connected_empty : is_connected (∅ : set α) :=
is_connected_of_is_irreducible is_irreducible_empty
theorem is_connected_singleton {x} : is_connected ({x} : set α) :=
is_connected_of_is_irreducible is_irreducible_singleton
theorem is_connected_sUnion (x : α) (c : set (set α)) (H1 : ∀ s ∈ c, x ∈ s)
(H2 : ∀ s ∈ c, is_connected s) : is_connected (⋃₀ c) :=
begin
rintro u v hu hv hUcuv ⟨y, hyUc, hyu⟩ ⟨z, hzUc, hzv⟩,
cases classical.em (c = ∅) with hc hc,
{ rw [hc, sUnion_empty] at hyUc, exact hyUc.elim },
cases ne_empty_iff_exists_mem.1 hc with s hs,
cases hUcuv (mem_sUnion_of_mem (H1 s hs) hs) with hxu hxv,
{ rcases hzUc with ⟨t, htc, hzt⟩,
specialize H2 t htc u v hu hv (subset.trans (subset_sUnion_of_mem htc) hUcuv),
cases H2 ⟨x, H1 t htc, hxu⟩ ⟨z, hzt, hzv⟩ with r hr,
exact ⟨r, mem_sUnion_of_mem hr.1 htc, hr.2⟩ },
{ rcases hyUc with ⟨t, htc, hyt⟩,
specialize H2 t htc u v hu hv (subset.trans (subset_sUnion_of_mem htc) hUcuv),
cases H2 ⟨y, hyt, hyu⟩ ⟨x, H1 t htc, hxv⟩ with r hr,
exact ⟨r, mem_sUnion_of_mem hr.1 htc, hr.2⟩ }
end
theorem is_connected_union (x : α) {s t : set α} (H1 : x ∈ s) (H2 : x ∈ t)
(H3 : is_connected s) (H4 : is_connected t) : is_connected (s ∪ t) :=
have _ := is_connected_sUnion x {t,s}
(by rintro r (rfl | rfl | h); [exact H1, exact H2, exact h.elim])
(by rintro r (rfl | rfl | h); [exact H3, exact H4, exact h.elim]),
have h2 : ⋃₀ {t, s} = s ∪ t, from (sUnion_insert _ _).trans (by rw sUnion_singleton),
by rwa h2 at this
theorem is_connected_closure {s : set α} (H : is_connected s) :
is_connected (closure s) :=
λ u v hu hv hcsuv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩,
let ⟨p, hpu, hps⟩ := exists_mem_of_ne_empty (mem_closure_iff.1 hycs u hu hyu) in
let ⟨q, hqv, hqs⟩ := exists_mem_of_ne_empty (mem_closure_iff.1 hzcs v hv hzv) in
let ⟨r, hrs, hruv⟩ := H u v hu hv (subset.trans subset_closure hcsuv) ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in
⟨r, subset_closure hrs, hruv⟩
def connected_component (x : α) : set α :=
⋃₀ { s : set α | is_connected s ∧ x ∈ s }
theorem is_connected_connected_component {x : α} : is_connected (connected_component x) :=
is_connected_sUnion x _ (λ _, and.right) (λ _, and.left)
theorem mem_connected_component {x : α} : x ∈ connected_component x :=
mem_sUnion_of_mem (mem_singleton x) ⟨is_connected_singleton, mem_singleton x⟩
theorem subset_connected_component {x : α} {s : set α} (H1 : is_connected s) (H2 : x ∈ s) :
s ⊆ connected_component x :=
λ z hz, mem_sUnion_of_mem hz ⟨H1, H2⟩
theorem is_closed_connected_component {x : α} :
is_closed (connected_component x) :=
closure_eq_iff_is_closed.1 $ subset.antisymm
(subset_connected_component
(is_connected_closure is_connected_connected_component)
(subset_closure mem_connected_component))
subset_closure
theorem irreducible_component_subset_connected_component {x : α} :
irreducible_component x ⊆ connected_component x :=
subset_connected_component
(is_connected_of_is_irreducible is_irreducible_irreducible_component)
mem_irreducible_component
/-- A connected space is one where there is no non-trivial open partition. -/
class connected_space (α : Type u) [topological_space α] : Prop :=
(is_connected_univ : is_connected (univ : set α))
instance irreducible_space.connected_space (α : Type u) [topological_space α]
[irreducible_space α] : connected_space α :=
⟨is_connected_of_is_irreducible $ irreducible_space.is_irreducible_univ α⟩
theorem exists_mem_inter [connected_space α] {s t : set α} :
is_open s → is_open t → s ∪ t = univ →
(∃ x, x ∈ s) → (∃ x, x ∈ t) → ∃ x, x ∈ s ∩ t :=
by simpa only [univ_inter, univ_subset_iff] using
@connected_space.is_connected_univ α _ _ s t
theorem is_clopen_iff [connected_space α] {s : set α} : is_clopen s ↔ s = ∅ ∨ s = univ :=
⟨λ hs, classical.by_contradiction $ λ h,
have h1 : s ≠ ∅ ∧ -s ≠ ∅, from ⟨mt or.inl h,
mt (λ h2, or.inr $ (by rw [← compl_compl s, h2, compl_empty] : s = univ)) h⟩,
let ⟨_, h2, h3⟩ := exists_mem_inter hs.1 hs.2 (union_compl_self s)
(ne_empty_iff_exists_mem.1 h1.1) (ne_empty_iff_exists_mem.1 h1.2) in
h3 h2,
by rintro (rfl | rfl); [exact is_clopen_empty, exact is_clopen_univ]⟩
end connected
section totally_disconnected
def is_totally_disconnected (s : set α) : Prop :=
∀ t, t ⊆ s → is_connected t → subsingleton t
theorem is_totally_disconnected_empty : is_totally_disconnected (∅ : set α) :=
λ t ht _, ⟨λ ⟨_, h⟩, (ht h).elim⟩
theorem is_totally_disconnected_singleton {x} : is_totally_disconnected ({x} : set α) :=
λ t ht _, ⟨λ ⟨p, hp⟩ ⟨q, hq⟩, subtype.eq $ show p = q,
from (eq_of_mem_singleton (ht hp)).symm ▸ (eq_of_mem_singleton (ht hq)).symm⟩
class totally_disconnected_space (α : Type u) [topological_space α] : Prop :=
(is_totally_disconnected_univ : is_totally_disconnected (univ : set α))
end totally_disconnected
section totally_separated
def is_totally_separated (s : set α) : Prop :=
∀ x ∈ s, ∀ y ∈ s, x ≠ y → ∃ u v : set α, is_open u ∧ is_open v ∧
x ∈ u ∧ y ∈ v ∧ s ⊆ u ∪ v ∧ u ∩ v = ∅
theorem is_totally_separated_empty : is_totally_separated (∅ : set α) :=
λ x, false.elim
theorem is_totally_separated_singleton {x} : is_totally_separated ({x} : set α) :=
λ p hp q hq hpq, (hpq $ (eq_of_mem_singleton hp).symm ▸ (eq_of_mem_singleton hq).symm).elim
theorem is_totally_disconnected_of_is_totally_separated {s : set α}
(H : is_totally_separated s) : is_totally_disconnected s :=
λ t hts ht, ⟨λ ⟨x, hxt⟩ ⟨y, hyt⟩, subtype.eq $ classical.by_contradiction $
assume hxy : x ≠ y, let ⟨u, v, hu, hv, hxu, hyv, hsuv, huv⟩ := H x (hts hxt) y (hts hyt) hxy in
let ⟨r, hrt, hruv⟩ := ht u v hu hv (subset.trans hts hsuv) ⟨x, hxt, hxu⟩ ⟨y, hyt, hyv⟩ in
((ext_iff _ _).1 huv r).1 hruv⟩
class totally_separated_space (α : Type u) [topological_space α] : Prop :=
(is_totally_separated_univ : is_totally_separated (univ : set α))
instance totally_separated_space.totally_disconnected_space (α : Type u) [topological_space α]
[totally_separated_space α] : totally_disconnected_space α :=
⟨is_totally_disconnected_of_is_totally_separated $ totally_separated_space.is_totally_separated_univ α⟩
end totally_separated
/- separation axioms -/
section separation
/-- A T₀ space, also known as a Kolmogorov space, is a topological space
where for every pair `x ≠ y`, there is an open set containing one but not the other. -/
class t0_space (α : Type u) [topological_space α] : Prop :=
(t0 : ∀ x y, x ≠ y → ∃ U:set α, is_open U ∧ (xor (x ∈ U) (y ∈ U)))
theorem exists_open_singleton_of_fintype [t0_space α]
[f : fintype α] [decidable_eq α] [ha : nonempty α] :
∃ x:α, is_open ({x}:set α) :=
have H : ∀ (T : finset α), T ≠ ∅ → ∃ x ∈ T, ∃ u, is_open u ∧ {x} = {y | y ∈ T} ∩ u :=
begin
intro T,
apply finset.case_strong_induction_on T,
{ intro h, exact (h rfl).elim },
{ intros x S hxS ih h,
by_cases hs : S = ∅,
{ existsi [x, finset.mem_insert_self x S, univ, is_open_univ],
rw [hs, inter_univ], refl },
{ rcases ih S (finset.subset.refl S) hs with ⟨y, hy, V, hv1, hv2⟩,
by_cases hxV : x ∈ V,
{ cases t0_space.t0 x y (λ hxy, hxS $ by rwa hxy) with U hu,
rcases hu with ⟨hu1, ⟨hu2, hu3⟩ | ⟨hu2, hu3⟩⟩,
{ existsi [x, finset.mem_insert_self x S, U ∩ V, is_open_inter hu1 hv1],
apply set.ext,
intro z,
split,
{ intro hzx,
rw set.mem_singleton_iff at hzx,
rw hzx,
exact ⟨finset.mem_insert_self x S, ⟨hu2, hxV⟩⟩ },
{ intro hz,
rw set.mem_singleton_iff,
rcases hz with ⟨hz1, hz2, hz3⟩,
cases finset.mem_insert.1 hz1 with hz4 hz4,
{ exact hz4 },
{ have h1 : z ∈ {y : α | y ∈ S} ∩ V,
{ exact ⟨hz4, hz3⟩ },
rw ← hv2 at h1,
rw set.mem_singleton_iff at h1,
rw h1 at hz2,
exact (hu3 hz2).elim } } },
{ existsi [y, finset.mem_insert_of_mem hy, U ∩ V, is_open_inter hu1 hv1],
apply set.ext,
intro z,
split,
{ intro hz,
rw set.mem_singleton_iff at hz,
rw hz,
refine ⟨finset.mem_insert_of_mem hy, hu2, _⟩,
have h1 : y ∈ {y} := set.mem_singleton y,
rw hv2 at h1,
exact h1.2 },
{ intro hz,
rw set.mem_singleton_iff,
cases hz with hz1 hz2,
cases finset.mem_insert.1 hz1 with hz3 hz3,
{ rw hz3 at hz2,
exact (hu3 hz2.1).elim },
{ have h1 : z ∈ {y : α | y ∈ S} ∩ V := ⟨hz3, hz2.2⟩,
rw ← hv2 at h1,
rw set.mem_singleton_iff at h1,
exact h1 } } } },
{ existsi [y, finset.mem_insert_of_mem hy, V, hv1],
apply set.ext,
intro z,
split,
{ intro hz,
rw set.mem_singleton_iff at hz,
rw hz,
split,
{ exact finset.mem_insert_of_mem hy },
{ have h1 : y ∈ {y} := set.mem_singleton y,
rw hv2 at h1,
exact h1.2 } },
{ intro hz,
rw hv2,
cases hz with hz1 hz2,
cases finset.mem_insert.1 hz1 with hz3 hz3,
{ rw hz3 at hz2,
exact (hxV hz2).elim },
{ exact ⟨hz3, hz2⟩ } } } } }
end,
begin
apply nonempty.elim ha, intro x,
specialize H finset.univ (finset.ne_empty_of_mem $ finset.mem_univ x),
rcases H with ⟨y, hyf, U, hu1, hu2⟩,
existsi y,
have h1 : {y : α | y ∈ finset.univ} = (univ : set α),
{ exact set.eq_univ_of_forall (λ x : α,
by rw mem_set_of_eq; exact finset.mem_univ x) },
rw h1 at hu2,
rw set.univ_inter at hu2,
rw hu2,
exact hu1
end
/-- A T₁ space, also known as a Fréchet space, is a topological space
where every singleton set is closed. Equivalently, for every pair
`x ≠ y`, there is an open set containing `x` and not `y`. -/
class t1_space (α : Type u) [topological_space α] : Prop :=
(t1 : ∀x, is_closed ({x} : set α))
lemma is_closed_singleton [t1_space α] {x : α} : is_closed ({x} : set α) :=
t1_space.t1 x
instance t1_space.t0_space [t1_space α] : t0_space α :=
⟨λ x y h, ⟨-{x}, is_open_compl_iff.2 is_closed_singleton,
or.inr ⟨λ hyx, or.cases_on hyx h.symm id, λ hx, hx $ or.inl rfl⟩⟩⟩
lemma compl_singleton_mem_nhds [t1_space α] {x y : α} (h : y ≠ x) : - {x} ∈ (nhds y).sets :=
mem_nhds_sets is_closed_singleton $ by rwa [mem_compl_eq, mem_singleton_iff]
@[simp] lemma closure_singleton [t1_space α] {a : α} :
closure ({a} : set α) = {a} :=
closure_eq_of_is_closed is_closed_singleton
/-- A T₂ space, also known as a Hausdorff space, is one in which for every
`x ≠ y` there exists disjoint open sets around `x` and `y`. This is
the most widely used of the separation axioms. -/
class t2_space (α : Type u) [topological_space α] : Prop :=
(t2 : ∀x y, x ≠ y → ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅)
lemma t2_separation [t2_space α] {x y : α} (h : x ≠ y) :
∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ :=
t2_space.t2 x y h
instance t2_space.t1_space [t2_space α] : t1_space α :=
⟨λ x, is_open_iff_forall_mem_open.2 $ λ y hxy,
let ⟨u, v, hu, hv, hyu, hxv, huv⟩ := t2_separation (mt mem_singleton_of_eq hxy) in
⟨u, λ z hz1 hz2, ((ext_iff _ _).1 huv x).1 ⟨mem_singleton_iff.1 hz2 ▸ hz1, hxv⟩, hu, hyu⟩⟩
lemma eq_of_nhds_neq_bot [ht : t2_space α] {x y : α} (h : nhds x ⊓ nhds y ≠ ⊥) : x = y :=
classical.by_contradiction $ assume : x ≠ y,
let ⟨u, v, hu, hv, hx, hy, huv⟩ := t2_space.t2 x y this in
have u ∩ v ∈ (nhds x ⊓ nhds y).sets,
from inter_mem_inf_sets (mem_nhds_sets hu hx) (mem_nhds_sets hv hy),
h $ empty_in_sets_eq_bot.mp $ huv ▸ this
lemma t2_iff_nhds : t2_space α ↔ ∀ {x y : α}, nhds x ⊓ nhds y ≠ ⊥ → x = y :=
⟨assume h, by exactI λ x y, eq_of_nhds_neq_bot,
assume h, ⟨assume x y xy,
have nhds x ⊓ nhds y = ⊥ := classical.by_contradiction (mt h xy),
let ⟨u', hu', v', hv', u'v'⟩ := empty_in_sets_eq_bot.mpr this,
⟨u, uu', uo, hu⟩ := mem_nhds_sets_iff.mp hu',
⟨v, vv', vo, hv⟩ := mem_nhds_sets_iff.mp hv' in
⟨u, v, uo, vo, hu, hv, disjoint.eq_bot $ disjoint_mono uu' vv' u'v'⟩⟩⟩
lemma t2_iff_ultrafilter :
t2_space α ↔ ∀ f {x y : α}, is_ultrafilter f → f ≤ nhds x → f ≤ nhds y → x = y :=
t2_iff_nhds.trans
⟨assume h f x y u fx fy, h $ neq_bot_of_le_neq_bot u.1 (le_inf fx fy),
assume h x y xy,
let ⟨f, hf, uf⟩ := exists_ultrafilter xy in
h f uf (le_trans hf lattice.inf_le_left) (le_trans hf lattice.inf_le_right)⟩
@[simp] lemma nhds_eq_nhds_iff {a b : α} [t2_space α] : nhds a = nhds b ↔ a = b :=
⟨assume h, eq_of_nhds_neq_bot $ by rw [h, inf_idem]; exact nhds_neq_bot, assume h, h ▸ rfl⟩
@[simp] lemma nhds_le_nhds_iff {a b : α} [t2_space α] : nhds a ≤ nhds b ↔ a = b :=
⟨assume h, eq_of_nhds_neq_bot $ by rw [inf_of_le_left h]; exact nhds_neq_bot, assume h, h ▸ le_refl _⟩
lemma tendsto_nhds_unique [t2_space α] {f : β → α} {l : filter β} {a b : α}
(hl : l ≠ ⊥) (ha : tendsto f l (nhds a)) (hb : tendsto f l (nhds b)) : a = b :=
eq_of_nhds_neq_bot $ neq_bot_of_le_neq_bot (map_ne_bot hl) $ le_inf ha hb
end separation
section regularity
/-- A T₃ space, also known as a regular space (although this condition sometimes
omits T₂), is one in which for every closed `C` and `x ∉ C`, there exist
disjoint open sets containing `x` and `C` respectively. -/
class regular_space (α : Type u) [topological_space α] extends t1_space α : Prop :=
(regular : ∀{s:set α} {a}, is_closed s → a ∉ s → ∃t, is_open t ∧ s ⊆ t ∧ nhds a ⊓ principal t = ⊥)
lemma nhds_is_closed [regular_space α] {a : α} {s : set α} (h : s ∈ (nhds a).sets) :
∃t∈(nhds a).sets, t ⊆ s ∧ is_closed t :=
let ⟨s', h₁, h₂, h₃⟩ := mem_nhds_sets_iff.mp h in
have ∃t, is_open t ∧ -s' ⊆ t ∧ nhds a ⊓ principal t = ⊥,
from regular_space.regular (is_closed_compl_iff.mpr h₂) (not_not_intro h₃),
let ⟨t, ht₁, ht₂, ht₃⟩ := this in
⟨-t,
mem_sets_of_neq_bot $ by rwa [lattice.neg_neg],
subset.trans (compl_subset_comm.1 ht₂) h₁,
is_closed_compl_iff.mpr ht₁⟩
variable (α)
instance regular_space.t2_space [regular_space α] : t2_space α :=
⟨λ x y hxy,
let ⟨s, hs, hys, hxs⟩ := regular_space.regular is_closed_singleton
(mt mem_singleton_iff.1 hxy),
⟨t, hxt, u, hsu, htu⟩ := empty_in_sets_eq_bot.2 hxs,
⟨v, hvt, hv, hxv⟩ := mem_nhds_sets_iff.1 hxt in
⟨v, s, hv, hs, hxv, singleton_subset_iff.1 hys,
eq_empty_of_subset_empty $ λ z ⟨hzv, hzs⟩, htu ⟨hvt hzv, hsu hzs⟩⟩⟩
end regularity
section normality
/-- A T₄ space, also known as a normal space (although this condition sometimes
omits T₂), is one in which for every pair of disjoint closed sets `C` and `D`,
there exist disjoint open sets containing `C` and `D` respectively. -/
class normal_space (α : Type u) [topological_space α] extends t1_space α : Prop :=
(normal : ∀ s t : set α, is_closed s → is_closed t → disjoint s t →
∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v)
theorem normal_separation [normal_space α] (s t : set α)
(H1 : is_closed s) (H2 : is_closed t) (H3 : disjoint s t) :
∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v :=
normal_space.normal s t H1 H2 H3
variable (α)
instance normal_space.regular_space [normal_space α] : regular_space α :=
{ regular := λ s x hs hxs, let ⟨u, v, hu, hv, hsu, hxv, huv⟩ := normal_separation s {x} hs is_closed_singleton
(λ _ ⟨hx, hy⟩, hxs $ set.mem_of_eq_of_mem (set.eq_of_mem_singleton hy).symm hx) in
⟨u, hu, hsu, filter.empty_in_sets_eq_bot.1 $ filter.mem_inf_sets.2
⟨v, mem_nhds_sets hv (set.singleton_subset_iff.1 hxv), u, filter.mem_principal_self u, set.inter_comm u v ▸ huv⟩⟩ }
end normality
/- generating sets -/
end topological_space
namespace topological_space
variables {α : Type u}
/-- The least topology containing a collection of basic sets. -/
inductive generate_open (g : set (set α)) : set α → Prop
| basic : ∀s∈g, generate_open s
| univ : generate_open univ
| inter : ∀s t, generate_open s → generate_open t → generate_open (s ∩ t)
| sUnion : ∀k, (∀s∈k, generate_open s) → generate_open (⋃₀ k)
/-- The smallest topological space containing the collection `g` of basic sets -/
def generate_from (g : set (set α)) : topological_space α :=
{ is_open := generate_open g,
is_open_univ := generate_open.univ g,
is_open_inter := generate_open.inter,
is_open_sUnion := generate_open.sUnion }
lemma nhds_generate_from {g : set (set α)} {a : α} :
@nhds α (generate_from g) a = (⨅s∈{s | a ∈ s ∧ s ∈ g}, principal s) :=
le_antisymm
(infi_le_infi $ assume s, infi_le_infi_const $ assume ⟨as, sg⟩, ⟨as, generate_open.basic _ sg⟩)
(le_infi $ assume s, le_infi $ assume ⟨as, hs⟩,
have ∀s, generate_open g s → a ∈ s → (⨅s∈{s | a ∈ s ∧ s ∈ g}, principal s) ≤ principal s,
begin
intros s hs,
induction hs,
case generate_open.basic : s hs
{ exact assume as, infi_le_of_le s $ infi_le _ ⟨as, hs⟩ },
case generate_open.univ
{ rw [principal_univ],
exact assume _, le_top },
case generate_open.inter : s t hs' ht' hs ht
{ exact assume ⟨has, hat⟩, calc _ ≤ principal s ⊓ principal t : le_inf (hs has) (ht hat)
... = _ : inf_principal },
case generate_open.sUnion : k hk' hk
{ exact λ ⟨t, htk, hat⟩, calc _ ≤ principal t : hk t htk hat
... ≤ _ : le_principal_iff.2 $ subset_sUnion_of_mem htk }
end,
this s hs as)
lemma tendsto_nhds_generate_from {β : Type*} {m : α → β} {f : filter α} {g : set (set β)} {b : β}
(h : ∀s∈g, b ∈ s → m ⁻¹' s ∈ f.sets) : tendsto m f (@nhds β (generate_from g) b) :=
by rw [nhds_generate_from]; exact
(tendsto_infi.2 $ assume s, tendsto_infi.2 $ assume ⟨hbs, hsg⟩, tendsto_principal.2 $ h s hsg hbs)
protected def mk_of_nhds (n : α → filter α) : topological_space α :=
{ is_open := λs, ∀a∈s, s ∈ (n a).sets,
is_open_univ := assume x h, univ_mem_sets,
is_open_inter := assume s t hs ht x ⟨hxs, hxt⟩, inter_mem_sets (hs x hxs) (ht x hxt),
is_open_sUnion := assume s hs a ⟨x, hx, hxa⟩, mem_sets_of_superset (hs x hx _ hxa) (set.subset_sUnion_of_mem hx) }
lemma nhds_mk_of_nhds (n : α → filter α) (a : α)
(h₀ : pure ≤ n) (h₁ : ∀{a s}, s ∈ (n a).sets → ∃t∈(n a).sets, t ⊆ s ∧ ∀a'∈t, s ∈ (n a').sets) :
@nhds α (topological_space.mk_of_nhds n) a = n a :=
begin
letI := topological_space.mk_of_nhds n,
refine le_antisymm (assume s hs, _) (assume s hs, _),
{ have h₀ : {b | s ∈ (n b).sets} ⊆ s := assume b hb, mem_pure_sets.1 $ h₀ b hb,
have h₁ : {b | s ∈ (n b).sets} ∈ (nhds a).sets,
{ refine mem_nhds_sets (assume b (hb : s ∈ (n b).sets), _) hs,
rcases h₁ hb with ⟨t, ht, hts, h⟩,
exact mem_sets_of_superset ht h },
exact mem_sets_of_superset h₁ h₀ },
{ rcases (@mem_nhds_sets_iff α (topological_space.mk_of_nhds n) _ _).1 hs with ⟨t, hts, ht, hat⟩,
exact (n a).sets_of_superset (ht _ hat) hts },
end
end topological_space
section lattice
variables {α : Type u} {β : Type v}
instance : partial_order (topological_space α) :=
{ le := λt s, t.is_open ≤ s.is_open,
le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₁ h₂,
le_refl := assume t, le_refl t.is_open,
le_trans := assume a b c h₁ h₂, @le_trans _ _ a.is_open b.is_open c.is_open h₁ h₂ }
lemma generate_from_le_iff_subset_is_open {g : set (set α)} {t : topological_space α} :
topological_space.generate_from g ≤ t ↔ g ⊆ {s | t.is_open s} :=
iff.intro
(assume ht s hs, ht _ $ topological_space.generate_open.basic s hs)
(assume hg s hs, hs.rec_on (assume v hv, hg hv)
t.is_open_univ (assume u v _ _, t.is_open_inter u v) (assume k _, t.is_open_sUnion k))
protected def mk_of_closure (s : set (set α))
(hs : {u | (topological_space.generate_from s).is_open u} = s) : topological_space α :=
{ is_open := λu, u ∈ s,
is_open_univ := hs ▸ topological_space.generate_open.univ _,
is_open_inter := hs ▸ topological_space.generate_open.inter,
is_open_sUnion := hs ▸ topological_space.generate_open.sUnion }
lemma mk_of_closure_sets {s : set (set α)}
{hs : {u | (topological_space.generate_from s).is_open u} = s} :
mk_of_closure s hs = topological_space.generate_from s :=
topological_space_eq hs.symm
def gi_generate_from (α : Type*) :
galois_insertion topological_space.generate_from (λt:topological_space α, {s | t.is_open s}) :=
{ gc := assume g t, generate_from_le_iff_subset_is_open,
le_l_u := assume ts s hs, topological_space.generate_open.basic s hs,
choice := λg hg, mk_of_closure g
(subset.antisymm hg $ generate_from_le_iff_subset_is_open.1 $ le_refl _),
choice_eq := assume s hs, mk_of_closure_sets }
lemma generate_from_mono {α} {g₁ g₂ : set (set α)} (h : g₁ ⊆ g₂) :
topological_space.generate_from g₁ ≤ topological_space.generate_from g₂ :=
(gi_generate_from _).gc.monotone_l h
instance {α : Type u} : complete_lattice (topological_space α) :=
(gi_generate_from α).lift_complete_lattice
class discrete_topology (α : Type*) [t : topological_space α] :=
(eq_top : t = ⊤)
@[simp] lemma is_open_discrete [topological_space α] [discrete_topology α] (s : set α) :
is_open s :=
(discrete_topology.eq_top α).symm ▸ trivial
lemma nhds_top (α : Type*) : (@nhds α ⊤) = pure :=
begin
ext a s,
rw [mem_nhds_sets_iff, mem_pure_iff],
split,
{ exact assume ⟨t, ht, _, hta⟩, ht hta },
{ exact assume h, ⟨{a}, set.singleton_subset_iff.2 h, trivial, set.mem_singleton a⟩ }
end
lemma nhds_discrete (α : Type*) [topological_space α] [discrete_topology α] : (@nhds α _) = pure :=
(discrete_topology.eq_top α).symm ▸ nhds_top α
instance t2_space_discrete [topological_space α] [discrete_topology α] : t2_space α :=
{ t2 := assume x y hxy, ⟨{x}, {y}, is_open_discrete _, is_open_discrete _, mem_insert _ _, mem_insert _ _,
eq_empty_iff_forall_not_mem.2 $ by intros z hz;
cases eq_of_mem_singleton hz.1; cases eq_of_mem_singleton hz.2; cc⟩ }
lemma le_of_nhds_le_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₂ x ≤ @nhds α t₁ x) :
t₁ ≤ t₂ :=
assume s, show @is_open α t₁ s → @is_open α t₂ s,
begin simp only [is_open_iff_nhds, le_principal_iff];
exact assume hs a ha, h _ $ hs _ ha end
lemma eq_of_nhds_eq_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₂ x = @nhds α t₁ x) :
t₁ = t₂ :=
le_antisymm
(le_of_nhds_le_nhds $ assume x, le_of_eq $ h x)
(le_of_nhds_le_nhds $ assume x, le_of_eq $ (h x).symm)
end lattice
section galois_connection
variables {α : Type*} {β : Type*} {γ : Type*}
/-- Given `f : α → β` and a topology on `β`, the induced topology on `α` is the collection of
sets that are preimages of some open set in `β`. This is the coarsest topology that
makes `f` continuous. -/
def topological_space.induced {α : Type u} {β : Type v} (f : α → β) (t : topological_space β) :
topological_space α :=
{ is_open := λs, ∃s', t.is_open s' ∧ s = f ⁻¹' s',
is_open_univ := ⟨univ, t.is_open_univ, preimage_univ.symm⟩,
is_open_inter := by rintro s₁ s₂ ⟨s'₁, hs₁, rfl⟩ ⟨s'₂, hs₂, rfl⟩;
exact ⟨s'₁ ∩ s'₂, t.is_open_inter _ _ hs₁ hs₂, preimage_inter⟩,
is_open_sUnion := assume s h,
begin
simp only [classical.skolem] at h,
cases h with f hf,
apply exists.intro (⋃(x : set α) (h : x ∈ s), f x h),
simp only [sUnion_eq_bUnion, preimage_Union, (λx h, (hf x h).right.symm)], refine ⟨_, rfl⟩,
exact (@is_open_Union β _ t _ $ assume i,
show is_open (⋃h, f i h), from @is_open_Union β _ t _ $ assume h, (hf i h).left)
end }
lemma is_open_induced_iff [t : topological_space β] {s : set α} {f : α → β} :
@is_open α (t.induced f) s ↔ (∃t, is_open t ∧ s = f ⁻¹' t) :=
iff.refl _
lemma is_closed_induced_iff [t : topological_space β] {s : set α} {f : α → β} :
@is_closed α (t.induced f) s ↔ (∃t, is_closed t ∧ s = f ⁻¹' t) :=
⟨assume ⟨t, ht, heq⟩, ⟨-t, is_closed_compl_iff.2 ht, by simp only [preimage_compl, heq.symm, lattice.neg_neg]⟩,
assume ⟨t, ht, heq⟩, ⟨-t, ht, by simp only [preimage_compl, heq.symm]⟩⟩
/-- Given `f : α → β` and a topology on `α`, the coinduced topology on `β` is defined
such that `s:set β` is open if the preimage of `s` is open. This is the finest topology that
makes `f` continuous. -/
def topological_space.coinduced {α : Type u} {β : Type v} (f : α → β) (t : topological_space α) :
topological_space β :=
{ is_open := λs, t.is_open (f ⁻¹' s),
is_open_univ := by rw preimage_univ; exact t.is_open_univ,
is_open_inter := assume s₁ s₂ h₁ h₂, by rw preimage_inter; exact t.is_open_inter _ _ h₁ h₂,
is_open_sUnion := assume s h, by rw [preimage_sUnion]; exact (@is_open_Union _ _ t _ $ assume i,
show is_open (⋃ (H : i ∈ s), f ⁻¹' i), from
@is_open_Union _ _ t _ $ assume hi, h i hi) }
lemma is_open_coinduced {t : topological_space α} {s : set β} {f : α → β} :
@is_open β (topological_space.coinduced f t) s ↔ is_open (f ⁻¹' s) :=
iff.refl _
variables {t t₁ t₂ : topological_space α} {t' : topological_space β} {f : α → β} {g : β → α}
lemma induced_le_iff_le_coinduced {f : α → β } {tα : topological_space α} {tβ : topological_space β} :
tβ.induced f ≤ tα ↔ tβ ≤ tα.coinduced f :=
iff.intro
(assume h s hs, show tα.is_open (f ⁻¹' s), from h _ ⟨s, hs, rfl⟩)
(assume h s ⟨t, ht, hst⟩, hst.symm ▸ h _ ht)
lemma gc_induced_coinduced (f : α → β) :
galois_connection (topological_space.induced f) (topological_space.coinduced f) :=
assume f g, induced_le_iff_le_coinduced
lemma induced_mono (h : t₁ ≤ t₂) : t₁.induced g ≤ t₂.induced g :=
(gc_induced_coinduced g).monotone_l h
lemma coinduced_mono (h : t₁ ≤ t₂) : t₁.coinduced f ≤ t₂.coinduced f :=
(gc_induced_coinduced f).monotone_u h
@[simp] lemma induced_bot : (⊥ : topological_space α).induced g = ⊥ :=
(gc_induced_coinduced g).l_bot
@[simp] lemma induced_sup : (t₁ ⊔ t₂).induced g = t₁.induced g ⊔ t₂.induced g :=
(gc_induced_coinduced g).l_sup
@[simp] lemma induced_supr {ι : Sort w} {t : ι → topological_space α} :
(⨆i, t i).induced g = (⨆i, (t i).induced g) :=
(gc_induced_coinduced g).l_supr
@[simp] lemma coinduced_top : (⊤ : topological_space α).coinduced f = ⊤ :=
(gc_induced_coinduced f).u_top
@[simp] lemma coinduced_inf : (t₁ ⊓ t₂).coinduced f = t₁.coinduced f ⊓ t₂.coinduced f :=
(gc_induced_coinduced f).u_inf
@[simp] lemma coinduced_infi {ι : Sort w} {t : ι → topological_space α} :
(⨅i, t i).coinduced f = (⨅i, (t i).coinduced f) :=
(gc_induced_coinduced f).u_infi
lemma induced_id [t : topological_space α] : t.induced id = t :=
topological_space_eq $ funext $ assume s, propext $
⟨assume ⟨s', hs, h⟩, h.symm ▸ hs, assume hs, ⟨s, hs, rfl⟩⟩
lemma induced_compose [tβ : topological_space β] [tγ : topological_space γ]
{f : α → β} {g : β → γ} : (tγ.induced g).induced f = tγ.induced (g ∘ f) :=
topological_space_eq $ funext $ assume s, propext $
⟨assume ⟨s', ⟨s, hs, h₂⟩, h₁⟩, h₁.symm ▸ h₂.symm ▸ ⟨s, hs, rfl⟩,
assume ⟨s, hs, h⟩, ⟨preimage g s, ⟨s, hs, rfl⟩, h ▸ rfl⟩⟩
lemma coinduced_id [t : topological_space α] : t.coinduced id = t :=
topological_space_eq rfl
lemma coinduced_compose [tα : topological_space α]
{f : α → β} {g : β → γ} : (tα.coinduced f).coinduced g = tα.coinduced (g ∘ f) :=
topological_space_eq rfl
end galois_connection
/- constructions using the complete lattice structure -/
section constructions
open topological_space
variables {α : Type u} {β : Type v}
instance inhabited_topological_space {α : Type u} : inhabited (topological_space α) :=
⟨⊤⟩
instance : topological_space empty := ⊤
instance : discrete_topology empty := ⟨rfl⟩
instance : topological_space unit := ⊤
instance : discrete_topology unit := ⟨rfl⟩
instance : topological_space bool := ⊤
instance : discrete_topology bool := ⟨rfl⟩
instance : topological_space ℕ := ⊤
instance : discrete_topology ℕ := ⟨rfl⟩
instance : topological_space ℤ := ⊤
instance : discrete_topology ℤ := ⟨rfl⟩
instance sierpinski_space : topological_space Prop :=
generate_from {{true}}
instance {p : α → Prop} [t : topological_space α] : topological_space (subtype p) :=
induced subtype.val 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 [topological_space α] : topological_space (list α) :=
topological_space.mk_of_nhds (traverse nhds)
lemma nhds_list [topological_space α] (as : list α) : nhds as = traverse nhds as :=
begin
refine nhds_mk_of_nhds _ _ _ _,
{ assume l, induction l,
case list.nil { exact le_refl _ },
case list.cons : a l ih {
suffices : list.cons <$> pure a <*> pure l ≤ list.cons <$> nhds a <*> traverse nhds l,
{ simpa only [-filter.pure_def] with functor_norm using this },
exact filter.seq_mono (filter.map_mono $ pure_le_nhds a) ih } },
{ assume l s hs,
rcases (mem_traverse_sets_iff _ _).1 hs with ⟨u, hu, hus⟩, clear as hs,
have : ∃v:list (set α), l.forall₂ (λa s, is_open s ∧ a ∈ s) v ∧ sequence v ⊆ s,
{ induction hu generalizing s,
case list.forall₂.nil : hs this { existsi [], simpa only [list.forall₂_nil_left_iff, exists_eq_left] },
case list.forall₂.cons : a s as ss ht h ih t hts {
rcases mem_nhds_sets_iff.1 ht with ⟨u, hut, hu⟩,
rcases ih (subset.refl _) with ⟨v, hv, hvss⟩,
exact ⟨u::v, list.forall₂.cons hu hv,
subset.trans (set.seq_mono (set.image_subset _ hut) hvss) hts⟩ } },
rcases this with ⟨v, hv, hvs⟩,
refine ⟨sequence v, mem_traverse_sets _ _ _, hvs, _⟩,
{ exact hv.imp (assume a s ⟨hs, ha⟩, mem_nhds_sets hs ha) },
{ assume u hu,
have hu := (list.mem_traverse _ _).1 hu,
have : list.forall₂ (λa s, is_open s ∧ a ∈ s) u v,
{ refine list.forall₂.flip _,
replace hv := hv.flip,
simp only [list.forall₂_and_left, flip] at ⊢ hv,
exact ⟨hv.1, hu.flip⟩ },
refine mem_sets_of_superset _ hvs,
exact mem_traverse_sets _ _ (this.imp $ assume a s ⟨hs, ha⟩, mem_nhds_sets hs ha) } }
end
lemma nhds_nil [topological_space α] : nhds ([] : list α) = pure [] :=
by rw [nhds_list, list.traverse_nil _]; apply_instance
lemma nhds_cons [topological_space α] (a : α) (l : list α) :
nhds (a :: l) = list.cons <$> nhds a <*> nhds l :=
by rw [nhds_list, list.traverse_cons _, ← nhds_list]; apply_instance
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_eq, y_x, x_in_U],
have V_op : is_open V := U_op,
have : V ∩ s ≠ ∅ := mem_closure_iff.1 (H y) V V_op y_in_V,
rcases exists_mem_of_ne_empty this with ⟨w, w_in_V, w_in_range⟩,
exact ne_empty_of_mem ⟨w_in_V, mem_image_of_mem quotient.mk w_in_range⟩
end
lemma generate_from_le {t : topological_space α} { g : set (set α) } (h : ∀s∈g, is_open s) :
generate_from g ≤ t :=
generate_from_le_iff_subset_is_open.2 h
protected def topological_space.nhds_adjoint (a : α) (f : filter α) : topological_space α :=
{ is_open := λs, a ∈ s → s ∈ f.sets,
is_open_univ := assume s, univ_mem_sets,
is_open_inter := assume s t hs ht ⟨has, hat⟩, inter_mem_sets (hs has) (ht hat),
is_open_sUnion := assume k hk ⟨u, hu, hau⟩, mem_sets_of_superset (hk u hu hau) (subset_sUnion_of_mem hu) }
lemma gc_nhds (a : α) :
@galois_connection _ (order_dual (filter α)) _ _ (λt, @nhds α t a) (topological_space.nhds_adjoint a) :=
assume t (f : filter α), show f ≤ @nhds α t a ↔ _, from iff.intro
(assume h s hs has, h $ @mem_nhds_sets α t a s hs has)
(assume h, le_infi $ assume u, le_infi $ assume ⟨hau, hu⟩, le_principal_iff.2 $ h _ hu hau)
lemma nhds_mono {t₁ t₂ : topological_space α} {a : α} (h : t₁ ≤ t₂) :
@nhds α t₂ a ≤ @nhds α t₁ a := (gc_nhds a).monotone_l h
lemma nhds_supr {ι : Sort*} {t : ι → topological_space α} {a : α} :
@nhds α (supr t) a = (⨅i, @nhds α (t i) a) := (gc_nhds a).l_supr
lemma nhds_Sup {s : set (topological_space α)} {a : α} :
@nhds α (Sup s) a = (⨅t∈s, @nhds α t a) := (gc_nhds a).l_Sup
lemma nhds_sup {t₁ t₂ : topological_space α} {a : α} :
@nhds α (t₁ ⊔ t₂) a = @nhds α t₁ a ⊓ @nhds α t₂ a := (gc_nhds a).l_sup
lemma nhds_bot {a : α} : @nhds α ⊥ a = ⊤ := (gc_nhds a).l_bot
private lemma separated_by_f
[tα : topological_space α] [tβ : topological_space β] [t2_space β]
(f : α → β) (hf : induced f tβ ≤ tα) {x y : α} (h : f x ≠ f y) :
∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ :=
let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h in
⟨f ⁻¹' u, f ⁻¹' v, hf _ ⟨u, uo, rfl⟩, hf _ ⟨v, vo, rfl⟩, xu, yv,
by rw [←preimage_inter, uv, preimage_empty]⟩
instance {p : α → Prop} [t : topological_space α] [t2_space α] : t2_space (subtype p) :=
⟨assume x y h,
separated_by_f subtype.val (le_refl _) (mt subtype.eq h)⟩
instance [t₁ : topological_space α] [t2_space α] [t₂ : topological_space β] [t2_space β] :
t2_space (α × β) :=
⟨assume ⟨x₁,x₂⟩ ⟨y₁,y₂⟩ h,
or.elim (not_and_distrib.mp (mt prod.ext_iff.mpr h))
(λ h₁, separated_by_f prod.fst le_sup_left h₁)
(λ h₂, separated_by_f prod.snd le_sup_right h₂)⟩
instance Pi.t2_space {β : α → Type v} [t₂ : Πa, topological_space (β a)] [Πa, t2_space (β a)] :
t2_space (Πa, β a) :=
⟨assume x y h,
let ⟨i, hi⟩ := not_forall.mp (mt funext h) in
separated_by_f (λz, z i) (le_supr _ i) hi⟩
instance {p : α → Prop} [topological_space α] [discrete_topology α] :
discrete_topology (subtype p) :=
⟨top_unique $ assume s hs,
⟨subtype.val '' s, is_open_discrete _, (set.preimage_image_eq _ subtype.val_injective).symm⟩⟩
end constructions
namespace topological_space
/- countability axioms
For our applications we are interested that there exists a countable basis, but we do not need the
concrete basis itself. This allows us to declare these type classes as `Prop` to use them as mixins.
-/
variables {α : Type u} [t : topological_space α]
include t
/-- A topological basis is one that satisfies the necessary conditions so that
it suffices to take unions of the basis sets to get a topology (without taking
finite intersections as well). -/
def is_topological_basis (s : set (set α)) : Prop :=
(∀t₁∈s, ∀t₂∈s, ∀ x ∈ t₁ ∩ t₂, ∃ t₃∈s, x ∈ t₃ ∧ t₃ ⊆ t₁ ∩ t₂) ∧
(⋃₀ s) = univ ∧
t = generate_from s
lemma is_topological_basis_of_subbasis {s : set (set α)} (hs : t = generate_from s) :
is_topological_basis ((λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ ⋂₀ f ≠ ∅}) :=
let b' := (λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ ⋂₀ f ≠ ∅} in
⟨assume s₁ ⟨t₁, ⟨hft₁, ht₁b, ht₁⟩, eq₁⟩ s₂ ⟨t₂, ⟨hft₂, ht₂b, ht₂⟩, eq₂⟩,
have ie : ⋂₀(t₁ ∪ t₂) = ⋂₀ t₁ ∩ ⋂₀ t₂, from Inf_union,
eq₁ ▸ eq₂ ▸ assume x h,
⟨_, ⟨t₁ ∪ t₂, ⟨finite_union hft₁ hft₂, union_subset ht₁b ht₂b,
by simpa only [ie] using ne_empty_of_mem h⟩, ie⟩, h, subset.refl _⟩,
eq_univ_iff_forall.2 $ assume a, ⟨univ, ⟨∅, ⟨finite_empty, empty_subset _,
by rw sInter_empty; exact nonempty_iff_univ_ne_empty.1 ⟨a⟩⟩, sInter_empty⟩, mem_univ _⟩,
have generate_from s = generate_from b',
from le_antisymm
(generate_from_le $ assume s hs,
by_cases
(assume : s = ∅, by rw [this]; apply @is_open_empty _ _)
(assume : s ≠ ∅, generate_open.basic _ ⟨{s}, ⟨finite_singleton s, singleton_subset_iff.2 hs,
by rwa [sInter_singleton]⟩, sInter_singleton s⟩))
(generate_from_le $ assume u ⟨t, ⟨hft, htb, ne⟩, eq⟩,
eq ▸ @is_open_sInter _ (generate_from s) _ hft (assume s hs, generate_open.basic _ $ htb hs)),
this ▸ hs⟩
lemma is_topological_basis_of_open_of_nhds {s : set (set α)}
(h_open : ∀ u ∈ s, _root_.is_open u)
(h_nhds : ∀(a:α) (u : set α), a ∈ u → _root_.is_open u → ∃v ∈ s, a ∈ v ∧ v ⊆ u) :
is_topological_basis s :=
⟨assume t₁ ht₁ t₂ ht₂ x ⟨xt₁, xt₂⟩,
h_nhds x (t₁ ∩ t₂) ⟨xt₁, xt₂⟩
(is_open_inter _ _ _ (h_open _ ht₁) (h_open _ ht₂)),
eq_univ_iff_forall.2 $ assume a,
let ⟨u, h₁, h₂, _⟩ := h_nhds a univ trivial (is_open_univ _) in
⟨u, h₁, h₂⟩,
le_antisymm
(assume u hu,
(@is_open_iff_nhds α (generate_from _) _).mpr $ assume a hau,
let ⟨v, hvs, hav, hvu⟩ := h_nhds a u hau hu in
by rw nhds_generate_from; exact infi_le_of_le v (infi_le_of_le ⟨hav, hvs⟩ $ le_principal_iff.2 hvu))
(generate_from_le h_open)⟩
lemma mem_nhds_of_is_topological_basis {a : α} {s : set α} {b : set (set α)}
(hb : is_topological_basis b) : s ∈ (nhds a).sets ↔ ∃t∈b, a ∈ t ∧ t ⊆ s :=
begin
rw [hb.2.2, nhds_generate_from, infi_sets_eq'],
{ simp only [mem_bUnion_iff, exists_prop, mem_set_of_eq, and_assoc, and.left_comm]; refl },
{ exact assume s ⟨hs₁, hs₂⟩ t ⟨ht₁, ht₂⟩,
have a ∈ s ∩ t, from ⟨hs₁, ht₁⟩,
let ⟨u, hu₁, hu₂, hu₃⟩ := hb.1 _ hs₂ _ ht₂ _ this in
⟨u, ⟨hu₂, hu₁⟩, le_principal_iff.2 (subset.trans hu₃ (inter_subset_left _ _)),
le_principal_iff.2 (subset.trans hu₃ (inter_subset_right _ _))⟩ },
{ rcases eq_univ_iff_forall.1 hb.2.1 a with ⟨i, h1, h2⟩,
exact ⟨i, h2, h1⟩ }
end
lemma is_open_of_is_topological_basis {s : set α} {b : set (set α)}
(hb : is_topological_basis b) (hs : s ∈ b) : _root_.is_open s :=
is_open_iff_mem_nhds.2 $ λ a as,
(mem_nhds_of_is_topological_basis hb).2 ⟨s, hs, as, subset.refl _⟩
lemma mem_basis_subset_of_mem_open {b : set (set α)}
(hb : is_topological_basis b) {a:α} {u : set α} (au : a ∈ u)
(ou : _root_.is_open u) : ∃v ∈ b, a ∈ v ∧ v ⊆ u :=
(mem_nhds_of_is_topological_basis hb).1 $ mem_nhds_sets ou au
lemma sUnion_basis_of_is_open {B : set (set α)}
(hB : is_topological_basis B) {u : set α} (ou : _root_.is_open u) :
∃ S ⊆ B, u = ⋃₀ S :=
⟨{s ∈ B | s ⊆ u}, λ s h, h.1, set.ext $ λ a,
⟨λ ha, let ⟨b, hb, ab, bu⟩ := mem_basis_subset_of_mem_open hB ha ou in
⟨b, ⟨hb, bu⟩, ab⟩,
λ ⟨b, ⟨hb, bu⟩, ab⟩, bu ab⟩⟩
lemma Union_basis_of_is_open {B : set (set α)}
(hB : is_topological_basis B) {u : set α} (ou : _root_.is_open u) :
∃ (β : Type u) (f : β → set α), u = (⋃ i, f i) ∧ ∀ i, f i ∈ B :=
let ⟨S, sb, su⟩ := sUnion_basis_of_is_open hB ou in
⟨S, subtype.val, su.trans set.sUnion_eq_Union, λ ⟨b, h⟩, sb h⟩
variables (α)
/-- A separable space is one with a countable dense subset. -/
class separable_space : Prop :=
(exists_countable_closure_eq_univ : ∃s:set α, countable s ∧ closure s = univ)
/-- A first-countable space is one in which every point has a
countable neighborhood basis. -/
class first_countable_topology : Prop :=
(nhds_generated_countable : ∀a:α, ∃s:set (set α), countable s ∧ nhds a = (⨅t∈s, principal t))
/-- A second-countable space is one with a countable basis. -/
class second_countable_topology : Prop :=
(is_open_generated_countable : ∃b:set (set α), countable b ∧ t = topological_space.generate_from b)
instance second_countable_topology.to_first_countable_topology
[second_countable_topology α] : first_countable_topology α :=
let ⟨b, hb, eq⟩ := second_countable_topology.is_open_generated_countable α in
⟨assume a, ⟨{s | a ∈ s ∧ s ∈ b},
countable_subset (assume x ⟨_, hx⟩, hx) hb, by rw [eq, nhds_generate_from]⟩⟩
lemma is_open_generated_countable_inter [second_countable_topology α] :
∃b:set (set α), countable b ∧ ∅ ∉ b ∧ is_topological_basis b :=
let ⟨b, hb₁, hb₂⟩ := second_countable_topology.is_open_generated_countable α in
let b' := (λs, ⋂₀ s) '' {s:set (set α) | finite s ∧ s ⊆ b ∧ ⋂₀ s ≠ ∅} in
⟨b',
countable_image _ $ countable_subset
(by simp only [(and_assoc _ _).symm]; exact inter_subset_left _ _)
(countable_set_of_finite_subset hb₁),
assume ⟨s, ⟨_, _, hn⟩, hp⟩, hn hp,
is_topological_basis_of_subbasis hb₂⟩
instance second_countable_topology.to_separable_space
[second_countable_topology α] : separable_space α :=
let ⟨b, hb₁, hb₂, hb₃, hb₄, eq⟩ := is_open_generated_countable_inter α in
have nhds_eq : ∀a, nhds a = (⨅ s : {s : set α // a ∈ s ∧ s ∈ b}, principal s.val),
by intro a; rw [eq, nhds_generate_from, infi_subtype]; refl,
have ∀s∈b, ∃a, a ∈ s, from assume s hs, exists_mem_of_ne_empty $ assume eq, hb₂ $ eq ▸ hs,
have ∃f:∀s∈b, α, ∀s h, f s h ∈ s, by simp only [skolem] at this; exact this,
let ⟨f, hf⟩ := this in
⟨⟨(⋃s∈b, ⋃h:s∈b, {f s h}),
countable_bUnion hb₁ (λ _ _, countable_Union_Prop $ λ _, countable_singleton _),
set.ext $ assume a,
have a ∈ (⋃₀ b), by rw [hb₄]; exact trivial,
let ⟨t, ht₁, ht₂⟩ := this in
have w : {s : set α // a ∈ s ∧ s ∈ b}, from ⟨t, ht₂, ht₁⟩,
suffices (⨅ (x : {s // a ∈ s ∧ s ∈ b}), principal (x.val ∩ ⋃s (h₁ h₂ : s ∈ b), {f s h₂})) ≠ ⊥,
by simpa only [closure_eq_nhds, nhds_eq, infi_inf w, inf_principal, mem_set_of_eq, mem_univ, iff_true],
infi_neq_bot_of_directed ⟨a⟩
(assume ⟨s₁, has₁, hs₁⟩ ⟨s₂, has₂, hs₂⟩,
have a ∈ s₁ ∩ s₂, from ⟨has₁, has₂⟩,
let ⟨s₃, hs₃, has₃, hs⟩ := hb₃ _ hs₁ _ hs₂ _ this in
⟨⟨s₃, has₃, hs₃⟩, begin
simp only [le_principal_iff, mem_principal_sets, (≥)],
simp only [subset_inter_iff] at hs, split;
apply inter_subset_inter_left; simp only [hs]
end⟩)
(assume ⟨s, has, hs⟩,
have s ∩ (⋃ (s : set α) (H h : s ∈ b), {f s h}) ≠ ∅,
from ne_empty_of_mem ⟨hf _ hs, mem_bUnion hs $ mem_Union.mpr ⟨hs, mem_singleton _⟩⟩,
mt principal_eq_bot_iff.1 this) ⟩⟩
variables {α}
lemma is_open_Union_countable [second_countable_topology α]
{ι} (s : ι → set α) (H : ∀ i, _root_.is_open (s i)) :
∃ T : set ι, countable T ∧ (⋃ i ∈ T, s i) = ⋃ i, s i :=
let ⟨B, cB, _, bB⟩ := is_open_generated_countable_inter α in
begin
let B' := {b ∈ B | ∃ i, b ⊆ s i},
choose f hf using λ b:B', b.2.2,
haveI : encodable B' := (countable_subset (sep_subset _ _) cB).to_encodable,
refine ⟨_, countable_range f,
subset.antisymm (bUnion_subset_Union _ _) (sUnion_subset _)⟩,
rintro _ ⟨i, rfl⟩ x xs,
rcases mem_basis_subset_of_mem_open bB xs (H _) with ⟨b, hb, xb, bs⟩,
exact ⟨_, ⟨_, rfl⟩, _, ⟨⟨⟨_, hb, _, bs⟩, rfl⟩, rfl⟩, hf _ (by exact xb)⟩
end
lemma is_open_sUnion_countable [second_countable_topology α]
(S : set (set α)) (H : ∀ s ∈ S, _root_.is_open s) :
∃ T : set (set α), countable T ∧ T ⊆ S ∧ ⋃₀ T = ⋃₀ S :=
let ⟨T, cT, hT⟩ := is_open_Union_countable (λ s:S, s.1) (λ s, H s.1 s.2) in
⟨subtype.val '' T, countable_image _ cT,
image_subset_iff.2 $ λ ⟨x, xs⟩ xt, xs,
by rwa [sUnion_image, sUnion_eq_Union]⟩
variable (α)
def opens := {s : set α // _root_.is_open s}
variable {α}
instance : has_coe (opens α) (set α) := { coe := subtype.val }
instance : has_subset (opens α) :=
{ subset := λ U V, U.val ⊆ V.val }
instance : has_mem α (opens α) :=
{ mem := λ a U, a ∈ U.val }
namespace opens
@[extensionality] lemma ext {U V : opens α} (h : U.val = V.val) : U = V := subtype.ext.mpr h
instance : partial_order (opens α) := subtype.partial_order _
def interior (s : set α) : opens α := ⟨interior s, is_open_interior⟩
def gc : galois_connection (subtype.val : opens α → set α) interior :=
λ U s, ⟨λ h, interior_maximal h U.property, λ h, le_trans h interior_subset⟩
def gi : @galois_insertion (order_dual (set α)) (order_dual (opens α)) _ _ interior (subtype.val) :=
{ choice := λ s hs, ⟨s, interior_eq_iff_open.mp $ le_antisymm interior_subset hs⟩,
gc := gc.dual,
le_l_u := λ _, interior_subset,
choice_eq := λ s hs, le_antisymm interior_subset hs }
instance : complete_lattice (opens α) :=
@order_dual.lattice.complete_lattice _
(@galois_insertion.lift_complete_lattice
(order_dual (set α)) (order_dual (opens α)) _ interior (subtype.val : opens α → set α) _ gi)
@[simp] lemma Sup_s {Us : set (opens α)} : (Sup Us).val = ⋃₀ (subtype.val '' Us) :=
begin
rw [@galois_connection.l_Sup (opens α) (set α) _ _ (subtype.val : opens α → set α) interior gc Us, set.sUnion_image],
congr
end
def is_basis (B : set (opens α)) : Prop := is_topological_basis (subtype.val '' B)
lemma is_basis_iff_nbhd {B : set (opens α)} :
is_basis B ↔ ∀ {U : opens α} {x}, x ∈ U → ∃ U' ∈ B, x ∈ U' ∧ U' ⊆ U :=
begin
split; intro h,
{ rintros ⟨sU, hU⟩ x hx,
rcases (mem_nhds_of_is_topological_basis h).mp (mem_nhds_sets hU hx) with ⟨sV, ⟨⟨V, H₁, H₂⟩, hsV⟩⟩,
refine ⟨V, H₁, _⟩,
cases V, dsimp at H₂, subst H₂, exact hsV },
{ refine is_topological_basis_of_open_of_nhds _ _,
{ rintros sU ⟨U, ⟨H₁, H₂⟩⟩, subst H₂, exact U.property },
{ intros x sU hx hsU,
rcases @h (⟨sU, hsU⟩ : opens α) x hx with ⟨V, hV, H⟩,
exact ⟨V, ⟨V, hV, rfl⟩, H⟩ } }
end
lemma is_basis_iff_cover {B : set (opens α)} :
is_basis B ↔ ∀ U : opens α, ∃ Us ⊆ B, U = Sup Us :=
begin
split,
{ intros hB U,
rcases sUnion_basis_of_is_open hB U.property with ⟨sUs, H, hU⟩,
existsi {U : opens α | U ∈ B ∧ U.val ∈ sUs},
split,
{ intros U hU, exact hU.left },
{ apply ext,
rw [Sup_s, hU],
congr,
ext s; split; intro hs,
{ rcases H hs with ⟨V, hV⟩,
rw ← hV.right at hs,
refine ⟨V, ⟨⟨hV.left, hs⟩, hV.right⟩⟩ },
{ rcases hs with ⟨V, ⟨⟨H₁, H₂⟩, H₃⟩⟩,
subst H₃, exact H₂ } } },
{ intro h,
rw is_basis_iff_nbhd,
intros U x hx,
rcases h U with ⟨Us, hUs, H⟩,
replace H := congr_arg subtype.val H,
rw Sup_s at H,
change x ∈ U.val at hx,
rw H at hx,
rcases set.mem_sUnion.mp hx with ⟨sV, ⟨⟨V, H₁, H₂⟩, hsV⟩⟩,
refine ⟨V,hUs H₁,_⟩,
cases V with V hV,
dsimp at H₂, subst H₂,
refine ⟨hsV,_⟩,
change V ⊆ U.val, rw H,
exact set.subset_sUnion_of_mem ⟨⟨V, _⟩, ⟨H₁, rfl⟩⟩ }
end
end opens
end topological_space
section limit
variables {α : Type u} [inhabited α] [topological_space α]
open classical
/-- If `f` is a filter, then `lim f` is a limit of the filter, if it exists. -/
noncomputable def lim (f : filter α) : α := epsilon $ λa, f ≤ nhds a
lemma lim_spec {f : filter α} (h : ∃a, f ≤ nhds a) : f ≤ nhds (lim f) := epsilon_spec h
variables [t2_space α] {f : filter α}
lemma lim_eq {a : α} (hf : f ≠ ⊥) (h : f ≤ nhds a) : lim f = a :=
eq_of_nhds_neq_bot $ neq_bot_of_le_neq_bot hf $ le_inf (lim_spec ⟨_, h⟩) h
@[simp] lemma lim_nhds_eq {a : α} : lim (nhds a) = a :=
lim_eq nhds_neq_bot (le_refl _)
@[simp] lemma lim_nhds_eq_of_closure {a : α} {s : set α} (h : a ∈ closure s) :
lim (nhds a ⊓ principal s) = a :=
lim_eq begin rw [closure_eq_nhds] at h, exact h end inf_le_left
end limit
|
a42b48725d67a843a6b057e17ebc8c41b11f29de | 0179bcdbf094a112437450a02dc2bdc8b2f921d4 | /fabstract/Hales_T_et_al_Kepler_conj/fabstract.lean | d757ef120f1f593b5eda89a56066dcbbf2dfb88a | [
"CC-BY-4.0"
] | permissive | haselwarter/formalabstracts | cf0c129fc086526cef1bd65d95c6f95a9a7ec5c8 | eab6d94850308df9f09d23f3a9a2f7b5ac5c6c7a | refs/heads/master | 1,609,515,992,248 | 1,500,418,815,000 | 1,500,418,815,000 | 97,696,544 | 0 | 0 | null | 1,500,455,350,000 | 1,500,455,350,000 | null | UTF-8 | Lean | false | false | 2,890 | lean | import ...meta_data ...folklore.real_axiom
import data.list data.vector
namespace Hales_T_et_al_Kepler_conj
noncomputable theory
open classical nat set list vector real_axiom
-- cardinality of finite sets.
-- Surely this must exist somewhere. But where?
universe u
def set_of_list {α : Type u} : (list α) → set α
| [] y := false
| (x :: rest) y := (x = y) ∨ set_of_list rest y
def finite {α : Type u} (P : set α) :=
(∃ l, P = set_of_list l)
unfinished least : set ℕ → ℕ :=
{ description := "every subset of natural numbers has a least element" }
unfinished least_empty : least ∅ = 0 :=
{ description := "the least element of the empty set is 0 by convention" }
unfinished least_nonempty :
∀ (P : set ℕ),
P ≠ ∅ → (least P ∈ P ∧ ∀ m, m ∈ P → least P ≤ m) :=
{ description := "the defining property of the least element of a subset" }
-- defaults to zero if the set is not finite:
def card {α : Type u} (P : set α) : ℕ :=
least (λ n, ∃ xs, set_of_list xs = P ∧ list.length xs = n)
/-
Here are some Euclidean vector space definitions that
should eventually be part of a general library
-/
local infix `^` := real_pow
def euclid_metric {n : ℕ} (u : vector ℝ n) (v : vector ℝ n) : ℝ :=
let subsquare (x : ℝ) (y : ℝ) : ℝ := (x-y)^2,
d := to_list (map₂ subsquare u v) in real_sqrt (list.sum d)
def packing {n : ℕ} (V : set (vector ℝ n)) :=
(∀ u v, V u ∧ v ∈ V ∧ euclid_metric u v < 2 → (u = v))
-- Todo: check that open balls are used (not that it matters)
def open_ball {n : ℕ} (x0 : vector ℝ n) (r : ℝ) : (set (vector ℝ n)) :=
{ u | euclid_metric x0 u < r}
def origin₃ : vector ℝ 3 := [0,0,0]
-- TODO: provide the theorem number from the paper
unfinished Kepler_conjecture :
(∀ (V : set (vector ℝ 3)), packing V →
(∃ (c : ℝ), ∀ (r : ℝ), (r ≥ 1) ->
(↑(card(V ∩ open_ball origin₃ r)) ≤ pi* r^3/real_sqrt(18) + c*r^2))) :=
{ description := "Proof of Kepler conjecture",
references := [cite.Item cite.Ibidem "Theorem X.Y"] }
open result
def fabstract : meta_data := {
description := "This article announces the formal proof of the Kepler conjecture on dense sphere packings in a combination of the HOL Light and Isabelle/HOL proof assistants. It represents the primary result of the now completed Flyspeck project.",
authors := ["Thomas Hales", "Mark Adams", "Gertrud Bauer", "Tat Dat Dang", "John Harrison", "Le Truong Hoang", "Cezary Kaliszyk", "Victor Magron", "Sean McLaughlin", "Tat Thang Nguyen", "Quang Truong Nguyen", "Tobias Nipkow", "Steven Obua", "Joseph Pleso", "Jason Rute", "Alexey Solovyev", "Thi Hoai An Ta", "Nam Trung Tran", "Thi Diep Trieu", "Josef Urban", "Ky Vu", "Roland Zumkeller"],
primary := cite.DOI "/10.1017/fmp.2017.1",
secondary := [],
results := [Proof Kepler_conjecture]
}
end Hales_T_et_al_Kepler_conj
|
50d87cef1aec569e353b40badeac48e1b65e83c4 | fc086f79b20cf002d6f34b023749998408e94fbf | /src/tidy/tidy.lean | c07be6437a81c94db723cf77ae812bb75fbb7b14 | [] | no_license | semorrison/lean-tidy | f039460136b898fb282f75efedd92f2d5c5d90f8 | 6c1d46de6cff05e1c2c4c9692af812bca3e13b6c | refs/heads/master | 1,624,461,332,392 | 1,559,655,744,000 | 1,559,655,744,000 | 96,569,994 | 9 | 4 | null | 1,538,287,895,000 | 1,499,455,306,000 | Lean | UTF-8 | Lean | false | false | 1,524 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
import tactic.basic
import tactic.tidy
import tactic.rewrite_search
import .backwards_reasoning
import .forwards_reasoning
import .luxembourg_chain
import category_theory.category
open tactic
meta def extended_tidy_tactics : list (tactic string) :=
[ reflexivity >> pure "refl",
`[exact dec_trivial] >> pure "exact dec_trivial",
propositional_goal >> assumption >> pure "assumption",
backwards_reasoning,
`[ext1] >> pure "ext1",
intros1 >>= λ ns, pure ("intros " ++ (" ".intercalate (ns.map (λ e, e.to_string)))),
auto_cases,
`[apply_auto_param] >> pure "apply_auto_param",
`[dsimp at *] >> pure "dsimp at *",
`[simp at *] >> pure "simp at *",
fsplit >> pure "fsplit",
injections_and_clear >> pure "injections_and_clear",
terminal_goal >> (`[solve_by_elim]) >> pure "solve_by_elim",
forwards_reasoning,
propositional_goal >> forwards_library_reasoning,
`[unfold_aux] >> pure "unfold_aux",
rewrite_search {},
tidy.run_tactics ]
@[obviously] meta def obviously_1 := tidy { tactics := extended_tidy_tactics }
|
6e1e49ace585cf4bc7ec4e107f99a286b525fa43 | 76df16d6c3760cb415f1294caee997cc4736e09b | /lean/src/tactic/cases_all.lean | 1d450184cc7340703e63cb01221792c95c2f67f7 | [
"MIT"
] | permissive | uw-unsat/leanette-popl22-artifact | 70409d9cbd8921d794d27b7992bf1d9a4087e9fe | 80fea2519e61b45a283fbf7903acdf6d5528dbe7 | refs/heads/master | 1,681,592,449,670 | 1,637,037,431,000 | 1,637,037,431,000 | 414,331,908 | 6 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 734 | lean | import tactic.basic
import tactic.induction
import .base
open tactic.interactive
setup_tactic_parser
/--
`cases_all h : e` is equivalent to `cases h : e; rewrite h at *`.
That is, it performs a case analysis on an expression and use the result
uniformly throughout the context and goal.
-/
@[interactive] meta def cases_all
(h : parse ident)
(_x : parse (parser.tk ":"))
(e : parse types.texpr)
(with_ids : parse with_ident_list) :=
tactic.seq'
(cases (h, e) with_ids)
(do
e_h ← tactic.get_local h,
tactic.interactive.rewrite
(tactic.interactive.rw_rules_t.mk
[(tactic.interactive.rw_rule.mk
dummy_loc ff (pexpr.of_expr e_h))]
none)
interactive.loc.wildcard)
|
4978cfae364c8131790f3f3f5eba0d03e8bd684c | d1a52c3f208fa42c41df8278c3d280f075eb020c | /src/Leanpkg/Git.lean | 55ce109228d27eb3b2b91e9115dbf0829c4d9200 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | cipher1024/lean4 | 6e1f98bb58e7a92b28f5364eb38a14c8d0aae393 | 69114d3b50806264ef35b57394391c3e738a9822 | refs/heads/master | 1,642,227,983,603 | 1,642,011,696,000 | 1,642,011,696,000 | 228,607,691 | 0 | 0 | Apache-2.0 | 1,576,584,269,000 | 1,576,584,268,000 | null | UTF-8 | Lean | false | false | 1,352 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner, Sebastian Ullrich
-/
import Leanpkg.LeanVersion
open System
namespace Leanpkg
def upstreamGitBranch :=
"master"
def gitdefaultRevision : Option String → String
| none => upstreamGitBranch
| some branch => branch
def gitParseRevision (gitRepo : FilePath) (rev : String) : IO String := do
let rev ← IO.Process.run {cmd := "git", args := #["rev-parse", "-q", "--verify", rev], cwd := gitRepo}
rev.trim -- remove newline at end
def gitHeadRevision (gitRepo : FilePath) : IO String :=
gitParseRevision gitRepo "HEAD"
def gitParseOriginRevision (gitRepo : FilePath) (rev : String) : IO String :=
(gitParseRevision gitRepo $ "origin/" ++ rev) <|> gitParseRevision gitRepo rev
<|> throw (IO.userError s!"cannot find revision {rev} in repository {gitRepo}")
def gitLatestOriginRevision (gitRepo : FilePath) (branch : Option String) : IO String := do
discard <| IO.Process.run {cmd := "git", args := #["fetch"], cwd := gitRepo}
gitParseOriginRevision gitRepo (gitdefaultRevision branch)
def gitRevisionExists (gitRepo : FilePath) (rev : String) : IO Bool := do
try
discard <| gitParseRevision gitRepo (rev ++ "^{commit}")
true
catch _ => false
end Leanpkg
|
7413848f56aec45cb9b6ff765ba33d4dd634b915 | 7b9ff28673cd3dd7dd3dcfe2ab8449f9244fe05a | /src/jesse/finish_demo.lean | f63f02ecb271f55199d17ff843a3890689ca83ea | [] | no_license | jesse-michael-han/hanoi-lean-2019 | ea2f0e04f81093373c48447065765a964ee82262 | a5a9f368e394d563bfcc13e3773863924505b1ce | refs/heads/master | 1,591,320,223,247 | 1,561,022,886,000 | 1,561,022,886,000 | 192,264,820 | 1 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 3,940 | lean | import order.lattice data.nat.gcd tactic tactic.explode
class lattice' (α : Type*) extends lattice.has_inf α, lattice.has_sup α :=
(inf_comm : ∀ x y : α, x ⊓ y = y ⊓ x)
(inf_assoc : ∀ x y z : α, x ⊓ y ⊓ z = x ⊓ (y ⊓ z))
(sup_comm : ∀ x y : α, x ⊔ y = y ⊔ x)
(sup_assoc : ∀ x y z : α, x ⊔ y ⊔ z = x ⊔ (y ⊔ z))
(inf_absorb : ∀ x y : α, x ⊓ (x ⊔ y) = x)
(sup_absorb : ∀ x y : α, x ⊔ (x ⊓ y) = x)
namespace lattice'
attribute [ematch] inf_comm inf_assoc sup_comm sup_assoc inf_absorb sup_absorb
-- inside the namespace, you can refer to the axioms without a prefix
variables {α : Type*} [lattice' α]
lemma try_me (x : α) : x ⊔ x = x :=
begin
conv {to_lhs, congr, skip, rw[<-inf_absorb x x]},
rw[sup_absorb x _]
end
@[ematch]theorem sup_idem (x : α) : x ⊔ x = x := by finish
@[ematch]theorem inf_idem (x : α) : x ⊓ x = x := by finish
protected def le (x y : α) := x = x ⊓ y
instance : has_le α := ⟨lattice'.le⟩
@[ematch]lemma le_unfold {x y : α} : x ≤ y ↔ x = x ⊓ y := by refl
@[ematch]theorem le_def (x y : α) : (x ≤ y) = (x = x ⊓ y) := rfl
@[ematch]theorem le_refl (x : α) : x ≤ x := by rw [le_def, inf_idem]
-- you can use `rw le_def at *` to unfold the definition everywhere
-- Wikipedia also tells you how to prove this one:
@[ematch]theorem le_def' (x y : α) : (x ≤ y) ↔ (y = x ⊔ y) :=
by split; intros; finish
@[ematch]theorem le_trans {x y z : α} (h : x ≤ y) (h' : y ≤ z) : x ≤ z := by finish
@[ematch]theorem le_antisymm {x y : α} (h : x ≤ y) (h' : y ≤ x) : x = y := by finish
@[ematch]theorem le_sup_left (x y : α) : x ≤ x ⊔ y := by finish
@[ematch]theorem le_sup_right (x y : α) : y ≤ x ⊔ y := by finish
@[ematch]theorem sup_le {x y z : α} (h₁ : x ≤ z) (h₂ : y ≤ z) : x ⊔ y ≤ z := by finish
@[ematch]theorem inf_le_left (x y : α) : x ⊓ y ≤ x := by finish
@[ematch]theorem inf_le_right (x y : α) : x ⊓ y ≤ y := by finish
@[ematch]theorem le_inf {x y z : α} (h₁ : x ≤ y) (h₂ : x ≤ z) : x ≤ y ⊓ z := by finish
end lattice'
-- instance to_lattice : lattice.lattice α :=
-- { sup := λ x y, x ⊔ y,
-- inf := λ x y, x ⊓ y,
-- le := lattice'.le,
-- le_refl := le_refl,
-- le_trans := @le_trans _ _,
-- le_antisymm := @le_antisymm _ _,
-- le_sup_left := le_sup_left,
-- le_sup_right := le_sup_right,
-- sup_le := @sup_le _ _,
-- inf_le_left := inf_le_left,
-- inf_le_right := inf_le_right,
-- le_inf := @le_inf _ _ }
-- end lattice'
/- This part is required of graduate students only. It shows that, conversely,
a lattice is a lattice'.
To do this, you will want to take a look at the theorems in order.lattice.
-/
namespace lattice
variables {α : Type*} [lattice α]
theorem inf_absorb (x y : α) : x ⊓ (x ⊔ y) = x :=
by {apply le_antisymm; finish}
theorem sup_absorb (x y : α) : x ⊔ (x ⊓ y) = x :=
by {apply le_antisymm; finish}
-- For this, you will want to you use the badly named theorem, `inf_of_le_left`.
-- (It should be named `inf_eq_of_le_left`.)
theorem le_iff (x y : α) : x ≤ y ↔ x = x ⊓ y :=
by {split; intros, {apply le_antisymm; finish}, finish}
end lattice
/-
Optional: show that the natural numbers form a lattice where the ordering
is the divsibility relation, sup is the least common multiple, and inf is
the greatest common divisor.
To do this, look at the theorems in data.nat.gcd.
Remember, to type `x ∣ y`, use `\|`.
-/
section
open lattice nat
instance nat_div_lattice : lattice nat :=
{ le := λ x y, x ∣ y,
sup := lcm,
inf := gcd,
le_refl := sorry,
le_trans := sorry,
le_antisymm := sorry,
le_sup_left := sorry,
le_sup_right := sorry,
sup_le := sorry,
inf_le_left := sorry,
inf_le_right := sorry,
le_inf := sorry }
end
|
c17c6af5538047d0ab7cafd35697a4cdd57cfd94 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/category_theory/category/Bipointed.lean | 8b71cc51310e69e6ac2ac399013af73eeefcf41a | [
"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 | 6,891 | lean | /-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import category_theory.category.Pointed
/-!
# The category of bipointed types
This defines `Bipointed`, the category of bipointed types.
## TODO
Monoidal structure
-/
open category_theory
universes u
variables {α β : Type*}
/-- The category of bipointed types. -/
structure Bipointed : Type.{u + 1} :=
(X : Type.{u})
(to_prod : X × X)
namespace Bipointed
instance : has_coe_to_sort Bipointed Type* := ⟨X⟩
attribute [protected] Bipointed.X
/-- Turns a bipointing into a bipointed type. -/
def of {X : Type*} (to_prod : X × X) : Bipointed := ⟨X, to_prod⟩
@[simp] lemma coe_of {X : Type*} (to_prod : X × X) : ↥(of to_prod) = X := rfl
alias of ← prod.Bipointed
instance : inhabited Bipointed := ⟨of ((), ())⟩
/-- Morphisms in `Bipointed`. -/
@[ext] protected structure hom (X Y : Bipointed.{u}) : Type u :=
(to_fun : X → Y)
(map_fst : to_fun X.to_prod.1 = Y.to_prod.1)
(map_snd : to_fun X.to_prod.2 = Y.to_prod.2)
namespace hom
/-- The identity morphism of `X : Bipointed`. -/
@[simps] def id (X : Bipointed) : hom X X := ⟨id, rfl, rfl⟩
instance (X : Bipointed) : inhabited (hom X X) := ⟨id X⟩
/-- Composition of morphisms of `Bipointed`. -/
@[simps] def comp {X Y Z : Bipointed.{u}} (f : hom X Y) (g : hom Y Z) : hom X Z :=
⟨g.to_fun ∘ f.to_fun, by rw [function.comp_apply, f.map_fst, g.map_fst],
by rw [function.comp_apply, f.map_snd, g.map_snd]⟩
end hom
instance large_category : large_category Bipointed :=
{ hom := hom,
id := hom.id,
comp := @hom.comp,
id_comp' := λ _ _ _, hom.ext _ _ rfl,
comp_id' := λ _ _ _, hom.ext _ _ rfl,
assoc' := λ _ _ _ _ _ _ _, hom.ext _ _ rfl }
instance concrete_category : concrete_category Bipointed :=
{ forget := { obj := Bipointed.X, map := @hom.to_fun },
forget_faithful := ⟨@hom.ext⟩ }
/-- Swaps the pointed elements of a bipointed type. `prod.swap` as a functor. -/
@[simps] def swap : Bipointed ⥤ Bipointed :=
{ obj := λ X, ⟨X, X.to_prod.swap⟩, map := λ X Y f, ⟨f.to_fun, f.map_snd, f.map_fst⟩ }
/-- The equivalence between `Bipointed` and itself induced by `prod.swap` both ways. -/
@[simps] def swap_equiv : Bipointed ≌ Bipointed :=
equivalence.mk swap swap
(nat_iso.of_components (λ X, { hom := ⟨id, rfl, rfl⟩, inv := ⟨id, rfl, rfl⟩ }) $ λ X Y f, rfl)
(nat_iso.of_components (λ X, { hom := ⟨id, rfl, rfl⟩, inv := ⟨id, rfl, rfl⟩ }) $ λ X Y f, rfl)
@[simp] lemma swap_equiv_symm : swap_equiv.symm = swap_equiv := rfl
end Bipointed
/-- The forgetful functor from `Bipointed` to `Pointed` which forgets about the second point. -/
def Bipointed_to_Pointed_fst : Bipointed ⥤ Pointed :=
{ obj := λ X, ⟨X, X.to_prod.1⟩, map := λ X Y f, ⟨f.to_fun, f.map_fst⟩ }
/-- The forgetful functor from `Bipointed` to `Pointed` which forgets about the first point. -/
def Bipointed_to_Pointed_snd : Bipointed ⥤ Pointed :=
{ obj := λ X, ⟨X, X.to_prod.2⟩, map := λ X Y f, ⟨f.to_fun, f.map_snd⟩ }
@[simp] lemma Bipointed_to_Pointed_fst_comp_forget :
Bipointed_to_Pointed_fst ⋙ forget Pointed = forget Bipointed := rfl
@[simp] lemma Bipointed_to_Pointed_snd_comp_forget :
Bipointed_to_Pointed_snd ⋙ forget Pointed = forget Bipointed := rfl
@[simp] lemma swap_comp_Bipointed_to_Pointed_fst :
Bipointed.swap ⋙ Bipointed_to_Pointed_fst = Bipointed_to_Pointed_snd := rfl
@[simp] lemma swap_comp_Bipointed_to_Pointed_snd :
Bipointed.swap ⋙ Bipointed_to_Pointed_snd = Bipointed_to_Pointed_fst := rfl
/-- The functor from `Pointed` to `Bipointed` which bipoints the point. -/
def Pointed_to_Bipointed : Pointed.{u} ⥤ Bipointed :=
{ obj := λ X, ⟨X, X.point, X.point⟩, map := λ X Y f, ⟨f.to_fun, f.map_point, f.map_point⟩ }
/-- The functor from `Pointed` to `Bipointed` which adds a second point. -/
def Pointed_to_Bipointed_fst : Pointed.{u} ⥤ Bipointed :=
{ obj := λ X, ⟨option X, X.point, none⟩,
map := λ X Y f, ⟨option.map f.to_fun, congr_arg _ f.map_point, rfl⟩,
map_id' := λ X, Bipointed.hom.ext _ _ option.map_id,
map_comp' := λ X Y Z f g, Bipointed.hom.ext _ _ (option.map_comp_map _ _).symm }
/-- The functor from `Pointed` to `Bipointed` which adds a first point. -/
def Pointed_to_Bipointed_snd : Pointed.{u} ⥤ Bipointed :=
{ obj := λ X, ⟨option X, none, X.point⟩,
map := λ X Y f, ⟨option.map f.to_fun, rfl, congr_arg _ f.map_point⟩,
map_id' := λ X, Bipointed.hom.ext _ _ option.map_id,
map_comp' := λ X Y Z f g, Bipointed.hom.ext _ _ (option.map_comp_map _ _).symm }
@[simp] lemma Pointed_to_Bipointed_fst_comp_swap :
Pointed_to_Bipointed_fst ⋙ Bipointed.swap = Pointed_to_Bipointed_snd := rfl
@[simp] lemma Pointed_to_Bipointed_snd_comp_swap :
Pointed_to_Bipointed_snd ⋙ Bipointed.swap = Pointed_to_Bipointed_fst := rfl
/-- `Bipointed_to_Pointed_fst` is inverse to `Pointed_to_Bipointed`. -/
@[simps] def Pointed_to_Bipointed_comp_Bipointed_to_Pointed_fst :
Pointed_to_Bipointed ⋙ Bipointed_to_Pointed_fst ≅ 𝟭 _ :=
nat_iso.of_components (λ X, { hom := ⟨id, rfl⟩, inv := ⟨id, rfl⟩ }) $ λ X Y f, rfl
/-- `Bipointed_to_Pointed_snd` is inverse to `Pointed_to_Bipointed`. -/
@[simps] def Pointed_to_Bipointed_comp_Bipointed_to_Pointed_snd :
Pointed_to_Bipointed ⋙ Bipointed_to_Pointed_snd ≅ 𝟭 _ :=
nat_iso.of_components (λ X, { hom := ⟨id, rfl⟩, inv := ⟨id, rfl⟩ }) $ λ X Y f, rfl
/-- The free/forgetful adjunction between `Pointed_to_Bipointed_fst` and `Bipointed_to_Pointed_fst`.
-/
def Pointed_to_Bipointed_fst_Bipointed_to_Pointed_fst_adjunction :
Pointed_to_Bipointed_fst ⊣ Bipointed_to_Pointed_fst :=
adjunction.mk_of_hom_equiv
{ hom_equiv := λ X Y, { to_fun := λ f, ⟨f.to_fun ∘ option.some, f.map_fst⟩,
inv_fun := λ f, ⟨λ o, o.elim Y.to_prod.2 f.to_fun, f.map_point, rfl⟩,
left_inv := λ f, by { ext, cases x, exact f.map_snd.symm, refl },
right_inv := λ f, Pointed.hom.ext _ _ rfl },
hom_equiv_naturality_left_symm' := λ X' X Y f g, by { ext, cases x; refl } }
/-- The free/forgetful adjunction between `Pointed_to_Bipointed_snd` and `Bipointed_to_Pointed_snd`.
-/
def Pointed_to_Bipointed_snd_Bipointed_to_Pointed_snd_adjunction :
Pointed_to_Bipointed_snd ⊣ Bipointed_to_Pointed_snd :=
adjunction.mk_of_hom_equiv
{ hom_equiv := λ X Y, { to_fun := λ f, ⟨f.to_fun ∘ option.some, f.map_snd⟩,
inv_fun := λ f, ⟨λ o, o.elim Y.to_prod.1 f.to_fun, rfl, f.map_point⟩,
left_inv := λ f, by { ext, cases x, exact f.map_fst.symm, refl },
right_inv := λ f, Pointed.hom.ext _ _ rfl },
hom_equiv_naturality_left_symm' := λ X' X Y f g, by { ext, cases x; refl } }
|
68107d3e8d5f653efbea85139dfefe5f7d46986b | ba306bac106b8f27befb2a800f4357237f86c760 | /lean/love05_inductive_predicates_demo.lean | a9f566dc1ab7309ea2dc7782d961651348b892c8 | [] | no_license | qyqnl/logical_verification_2020 | 406aa4cc47797501275ea07de5d6f59f01e977d0 | 17dff35b56336acb671ddfb36871f98475bc0b96 | refs/heads/master | 1,672,501,336,112 | 1,603,724,260,000 | 1,603,724,260,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,868 | lean | import .love03_forward_proofs_demo
import .love04_functional_programming_demo
/- # LoVe Demo 5: Inductive Predicates
__Inductive predicates__, or inductively defined propositions, are a convenient
way to specify functions of type `⋯ → Prop`. They are reminiscent of formal
systems and of the Horn clauses of Prolog, the logic programming language par
excellence.
A possible view of Lean:
Lean = functional programming + logic programming + more logic -/
set_option pp.beta true
set_option pp.generalized_field_notation false
namespace LoVe
/- ## Introductory Examples
### Even Numbers
Mathematicians often define sets as the smallest that meets some criteria. For
example:
The set `E` of even natural numbers is defined as the smallest set closed
under the following rules: (1) `0 ∈ E` and (2) for every `k ∈ ℕ`, if
`k ∈ E`, then `k + 2 ∈ E`.
In Lean, we can define the corresponding "is even" predicate as follows: -/
inductive even : ℕ → Prop
| zero : even 0
| add_two : ∀k : ℕ, even k → even (k + 2)
/- This should look familiar. We have used the same syntax, except with `Type`
instead of `Prop`, for inductive types.
The above command introduces a new unary predicate `even` as well as two
constructors, `even.zero` and `even.add_two`, which can be used to build proof
terms. Thanks to the "no junk" guarantee of inductive definitions, `even.zero`
and `even.add_two` are the only two ways to construct proofs of `even`.
By the Curry–Howard correspondence, `even` can be seen as a data type, the
values being the proof terms. -/
lemma even_4 :
even 4 :=
have even_0 : even 0 :=
even.zero,
have even_2 : even 2 :=
even.add_two _ even_0,
show even 4, from
even.add_two _ even_2
/- Why cannot we simply define `even` recursively? Indeed, why not? -/
def even₂ : ℕ → bool
| 0 := tt
| 1 := ff
| (k + 2) := even₂ k
/- There are advantages and disadvantages to both styles.
The recursive version requires us to specify a false case (1), and it requires
us to worry about termination. On the other hand, because it is computational,
it works well with `refl`, `simp`, `#reduce`, and `#eval`.
The inductive version is often considered more abstract and elegant. Each rule
is stated independently of the others.
Yet another way to define `even` is as a nonrecursive definition: -/
def even₃ (k : ℕ) : bool :=
k % 2 = 0
/- Mathematicians would probably find this the most satisfactory definition.
But the inductive version is a convenient, intuitive example that is typical of
many realistic inductive definitions.
### Tennis Games
Transition systems consists of transition rules, which together specify a
binary predicate connecting a "before" and an "after" state. As a simple
specimen of a transition system, we consider the possible transitions, in a game
of tennis, starting from 0–0. -/
inductive score : Type
| vs : ℕ → ℕ → score
| adv_srv : score
| adv_rcv : score
| game_srv : score
| game_rcv : score
infixr ` – ` : 10 := score.vs
inductive step : score → score → Prop
| srv_0_15 : ∀n, step (0–n) (15–n)
| srv_15_30 : ∀n, step (15–n) (30–n)
| srv_30_40 : ∀n, step (30–n) (40–n)
| srv_40_game : ∀n, n < 40 → step (40–n) score.game_srv
| srv_40_adv : step (40–40) score.adv_srv
| srv_adv_40 : step score.adv_srv (40–40)
| rcv_0_15 : ∀n, step (n–0) (n–15)
| rcv_15_30 : ∀n, step (n–15) (n–30)
| rcv_30_40 : ∀n, step (n–30) (n–40)
| rcv_40_game : ∀n, n < 40 → step (n–40) score.game_rcv
| rcv_40_adv : step (40–40) score.adv_rcv
| rcv_adv_40 : step score.adv_rcv (40–40)
infixr ` ⇒ ` := step
/- We can ask, and formally answer, questions such as: Is this transition
system confluent? Does it always terminate? Can the score 65–15 be reached from
0–0?
### Reflexive Transitive Closure
Our last introductory example is the reflexive transitive closure of a
relation `r`, modeled as a binary predicate `star r`. -/
inductive star {α : Type} (r : α → α → Prop) : α → α → Prop
| base (a b : α) : r a b → star a b
| refl (a : α) : star a a
| trans (a b c : α) : star a b → star b c → star a c
/- The first rule embeds `r` into `star r`. The second rule achieves the
reflexive closure. The third rule achieves the transitive closure.
The definition is truly elegant. If you doubt this, try implementing `star` as a
recursive function: -/
def star₂ {α : Type} (r : α → α → Prop) : α → α → Prop :=
sorry
/- ### A Nonexample
Not all inductive definitions admit a least solution. -/
-- fails
inductive illegal₂ : Prop
| intro : ¬ illegal₂ → illegal₂
/- ## Logical Symbols
The truth values `false` and `true`, the connectives `∧` and `∨`, the
`∃`-quantifier, and the equality predicate `=` are all defined as inductive
propositions or predicates. In contrast, `∀` (= `Π`) and `→` are built into
the logic.
Syntactic sugar:
`∃x : α, p` := `Exists (λx : α, p)`
`x = y` := `eq x y` -/
namespace logical_symbols
inductive and (a b : Prop) : Prop
| intro : a → b → and
inductive or (a b : Prop) : Prop
| intro_left : a → or
| intro_right : b → or
inductive iff (a b : Prop) : Prop
| intro : (a → b) → (b → a) → iff
inductive Exists {α : Type} (p : α → Prop) : Prop
| intro : ∀a : α, p a → Exists
inductive true : Prop
| intro : true
inductive false : Prop
inductive eq {α : Type} : α → α → Prop
| refl : ∀a : α, eq a a
end logical_symbols
#print and
#print or
#print iff
#print Exists
#print true
#print false
#print eq
/- ## Rule Induction
Just as we can perform induction on a term, we can perform induction on a proof
term.
This is called __rule induction__, because the induction is on the introduction
rules (i.e., the constructors of the proof term). Thanks to the Curry–Howard
correspondence, this works as expected. -/
lemma mod_two_eq_zero_of_even (n : ℕ) (h : even n) :
n % 2 = 0 :=
begin
induction' h,
case even.zero {
refl },
case even.add_two : k hk ih {
simp [ih] }
end
lemma not_even_two_mul_add_one (n : ℕ) :
¬ even (2 * n + 1) :=
begin
intro h,
induction' h,
apply ih (n - 1),
cases' n,
case zero {
linarith },
case succ {
simp [nat.succ_eq_add_one] at *,
linarith }
end
/- `linarith` proves goals involving linear arithmetic equalities or
inequalities. "Linear" means it works only with `+` and `-`, not `*` and `/`
(but multiplication by a constant is supported). -/
lemma linarith_example (i : ℤ) (hi : i > 5) :
2 * i + 3 > 11 :=
by linarith
lemma star_star_iff_star {α : Type} (r : α → α → Prop)
(a b : α) :
star (star r) a b ↔ star r a b :=
begin
apply iff.intro,
{ intro h,
induction' h,
case star.base : a b hab {
exact hab },
case star.refl : a {
apply star.refl },
case star.trans : a b c hab hbc ihab ihbc {
apply star.trans a b,
{ exact ihab },
{ exact ihbc } } },
{ intro h,
apply star.base,
exact h }
end
@[simp] lemma star_star_eq_star {α : Type}
(r : α → α → Prop) :
star (star r) = star r :=
begin
apply funext,
intro a,
apply funext,
intro b,
apply propext,
apply star_star_iff_star
end
#check funext
#check propext
/- ## Elimination
Given an inductive predicate `p`, its introduction rules typically have the form
`∀…, ⋯ → p …` and can be used to prove goals of the form `⊢ p …`.
Elimination works the other way around: It extracts information from a lemma or
hypothesis of the form `p …`. Elimination takes various forms: pattern matching,
the `cases'` and `induction'` tactics, and custom elimination rules (e.g.,
`and.elim_left`).
* `cases'` works like `induction'` but without induction hypothesis.
* `match` is available as well, but it corresponds to dependently typed pattern
matching (cf. `vector` in lecture 4).
Now we can finally analyze how `cases' h`, where `h : l = r`, and how
`cases' classical.em h` work. -/
#print eq
lemma cases_eq_example {α : Type} (l r : α) (h : l = r)
(p : α → α → Prop) :
p l r :=
begin
cases' h,
sorry
end
#check classical.em
#print or
lemma cases_classical_em_example {α : Type} (a : α)
(p q : α → Prop) :
q a :=
begin
have h : p a ∨ ¬ p a :=
classical.em (p a),
cases' h,
case or.inl {
sorry },
case or.inr {
sorry }
end
/- Often it is convenient to rewrite concrete terms of the form `p (c …)`,
where `c` is typically a constructor. We can state and prove an
__inversion rule__ to support such eliminative reasoning.
Typical inversion rule:
`∀x y, p (c x y) → (∃…, ⋯ ∧ ⋯) ∨ ⋯ ∨ (∃…, ⋯ ∧ ⋯)`
It can be useful to combine introduction and elimination into a single lemma,
which can be used for rewriting both the hypotheses and conclusions of goals:
`∀x y, p (c x y) ↔ (∃…, ⋯ ∧ ⋯) ∨ ⋯ ∨ (∃…, ⋯ ∧ ⋯)` -/
lemma even_iff (n : ℕ) :
even n ↔ n = 0 ∨ (∃m : ℕ, n = m + 2 ∧ even m) :=
begin
apply iff.intro,
{ intro hn,
cases' hn,
case even.zero {
simp },
case even.add_two : k hk {
apply or.intro_right,
apply exists.intro k,
simp [hk] } },
{ intro hor,
cases' hor,
case or.inl : heq {
simp [heq, even.zero] },
case or.inr : hex {
cases' hex with k hand,
cases' hand with heq hk,
simp [heq, even.add_two _ hk] } }
end
lemma even_iff₂ (n : ℕ) :
even n ↔ n = 0 ∨ (∃m : ℕ, n = m + 2 ∧ even m) :=
iff.intro
(assume hn : even n,
match n, hn with
| _, even.zero :=
show 0 = 0 ∨ _, from
by simp
| _, even.add_two k hk :=
show _ ∨ (∃m, k + 2 = m + 2 ∧ even m), from
or.intro_right _ (exists.intro k (by simp [*]))
end)
(assume hor : n = 0 ∨ (∃m, n = m + 2 ∧ even m),
match hor with
| or.intro_left _ heq :=
show even n, from
by simp [heq, even.zero]
| or.intro_right _ hex :=
match hex with
| Exists.intro m hand :=
match hand with
| and.intro heq hm :=
show even n, from
by simp [heq, even.add_two _ hm]
end
end
end)
/- ## Further Examples
### Sorted Lists -/
inductive sorted : list ℕ → Prop
| nil : sorted []
| single {x : ℕ} : sorted [x]
| two_or_more {x y : ℕ} {zs : list ℕ} (hle : x ≤ y)
(hsorted : sorted (y :: zs)) :
sorted (x :: y :: zs)
lemma sorted_nil :
sorted [] :=
sorted.nil
lemma sorted_2 :
sorted [2] :=
sorted.single
lemma sorted_3_5 :
sorted [3, 5] :=
begin
apply sorted.two_or_more,
{ linarith },
{ exact sorted.single }
end
lemma sorted_3_5₂ :
sorted [3, 5] :=
sorted.two_or_more (by linarith) sorted.single
lemma sorted_7_9_9_11 :
sorted [7, 9, 9, 11] :=
sorted.two_or_more (by linarith)
(sorted.two_or_more (by linarith)
(sorted.two_or_more (by linarith)
sorted.single))
lemma not_sorted_17_13 :
¬ sorted [17, 13] :=
begin
intro h,
cases' h,
linarith
end
/- ### Palindromes -/
inductive palindrome {α : Type} : list α → Prop
| nil : palindrome []
| single (x : α) : palindrome [x]
| sandwich (x : α) (xs : list α) (hxs : palindrome xs) :
palindrome ([x] ++ xs ++ [x])
-- fails
def palindrome₂ {α : Type} : list α → Prop
| [] := true
| [_] := true
| ([x] ++ xs ++ [x]) := palindrome₂ xs
| _ := false
lemma palindrome_aa {α : Type} (a : α) :
palindrome [a, a] :=
palindrome.sandwich a _ palindrome.nil
lemma palindrome_aba {α : Type} (a b : α) :
palindrome [a, b, a] :=
palindrome.sandwich a _ (palindrome.single b)
lemma reverse_palindrome {α : Type} (xs : list α)
(hxs : palindrome xs) :
palindrome (reverse xs) :=
begin
induction' hxs,
case nil {
exact palindrome.nil },
case single {
exact palindrome.single x },
case sandwich {
simp [reverse, reverse_append],
exact palindrome.sandwich _ _ ih }
end
/- ### Full Binary Trees -/
#check btree
inductive is_full {α : Type} : btree α → Prop
| empty : is_full btree.empty
| node (a : α) (l r : btree α)
(hl : is_full l) (hr : is_full r)
(hiff : l = btree.empty ↔ r = btree.empty) :
is_full (btree.node a l r)
lemma is_full_singleton {α : Type} (a : α) :
is_full (btree.node a btree.empty btree.empty) :=
begin
apply is_full.node,
{ exact is_full.empty },
{ exact is_full.empty },
{ refl }
end
lemma is_full_mirror {α : Type} (t : btree α)
(ht : is_full t) :
is_full (mirror t) :=
begin
induction' ht,
case empty {
exact is_full.empty },
case node : a l r hl hr hiff ih_l ih_r {
rw mirror,
apply is_full.node,
{ exact ih_r },
{ exact ih_l },
{ simp [mirror_eq_empty_iff, *] } }
end
lemma is_full_mirror₂ {α : Type} :
∀t : btree α, is_full t → is_full (mirror t)
| btree.empty :=
begin
intro ht,
exact ht
end
| (btree.node a l r) :=
begin
intro ht,
cases ht with _ _ _ hl hr hiff,
rw mirror,
apply is_full.node,
{ exact is_full_mirror₂ _ hr },
{ apply is_full_mirror₂ _ hl },
{ simp [mirror_eq_empty_iff, *] }
end
/- ### First-Order Terms -/
inductive term (α β : Type) : Type
| var {} : β → term
| fn : α → list term → term
inductive well_formed {α β : Type} (arity : α → ℕ) :
term α β → Prop
| var (x : β) : well_formed (term.var x)
| fn (f : α) (ts : list (term α β))
(hargs : ∀t ∈ ts, well_formed t)
(hlen : list.length ts = arity f) :
well_formed (term.fn f ts)
inductive variable_free {α β : Type} : term α β → Prop
| fn (f : α) (ts : list (term α β))
(hargs : ∀t ∈ ts, variable_free t) :
variable_free (term.fn f ts)
end LoVe
|
8fc7aa614244eb216a04d4cc4c97da56d2b70e0f | 9b9a16fa2cb737daee6b2785474678b6fa91d6d4 | /src/category_theory/isomorphism.lean | 1d1001b91ff0995e30ed2697a9596246172c90a3 | [
"Apache-2.0"
] | permissive | johoelzl/mathlib | 253f46daa30b644d011e8e119025b01ad69735c4 | 592e3c7a2dfbd5826919b4605559d35d4d75938f | refs/heads/master | 1,625,657,216,488 | 1,551,374,946,000 | 1,551,374,946,000 | 98,915,829 | 0 | 0 | Apache-2.0 | 1,522,917,267,000 | 1,501,524,499,000 | Lean | UTF-8 | Lean | false | false | 6,533 | 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
import category_theory.functor
universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation
namespace category_theory
structure iso {C : Type u} [category.{v} C] (X Y : C) :=
(hom : X ⟶ Y)
(inv : Y ⟶ X)
(hom_inv_id' : hom ≫ inv = 𝟙 X . obviously)
(inv_hom_id' : inv ≫ hom = 𝟙 Y . obviously)
restate_axiom iso.hom_inv_id'
restate_axiom iso.inv_hom_id'
attribute [simp] iso.hom_inv_id iso.inv_hom_id
infixr ` ≅ `:10 := iso -- type as \cong or \iso
variables {C : Type u} [𝒞 : category.{v} C]
include 𝒞
variables {X Y Z : C}
namespace iso
@[simp] lemma hom_inv_id_assoc (α : X ≅ Y) (f : X ⟶ Z) : α.hom ≫ α.inv ≫ f = f :=
by rw [←category.assoc, α.hom_inv_id, category.id_comp]
@[simp] lemma inv_hom_id_assoc (α : X ≅ Y) (f : Y ⟶ Z) : α.inv ≫ α.hom ≫ f = f :=
by rw [←category.assoc, α.inv_hom_id, category.id_comp]
@[extensionality] lemma ext (α β : X ≅ Y) (w : α.hom = β.hom) : α = β :=
suffices α.inv = β.inv, by cases α; cases β; cc,
calc α.inv
= α.inv ≫ (β.hom ≫ β.inv) : by rw [iso.hom_inv_id, category.comp_id]
... = (α.inv ≫ α.hom) ≫ β.inv : by rw [category.assoc, ←w]
... = β.inv : by rw [iso.inv_hom_id, category.id_comp]
@[symm] def symm (I : X ≅ Y) : Y ≅ X :=
{ hom := I.inv,
inv := I.hom,
hom_inv_id' := I.inv_hom_id',
inv_hom_id' := I.hom_inv_id' }
@[simp] lemma symm_hom (α : X ≅ Y) : α.symm.hom = α.inv := rfl
@[simp] lemma symm_inv (α : X ≅ Y) : α.symm.inv = α.hom := rfl
@[refl] def refl (X : C) : X ≅ X :=
{ hom := 𝟙 X,
inv := 𝟙 X }
@[simp] lemma refl_hom (X : C) : (iso.refl X).hom = 𝟙 X := rfl
@[simp] lemma refl_inv (X : C) : (iso.refl X).inv = 𝟙 X := rfl
@[trans] def trans (α : X ≅ Y) (β : Y ≅ Z) : X ≅ Z :=
{ hom := α.hom ≫ β.hom,
inv := β.inv ≫ α.inv }
infixr ` ≪≫ `:80 := iso.trans -- type as `\ll \gg`.
@[simp] lemma trans_hom (α : X ≅ Y) (β : Y ≅ Z) : (α ≪≫ β).hom = α.hom ≫ β.hom := rfl
@[simp] lemma trans_inv (α : X ≅ Y) (β : Y ≅ Z) : (α ≪≫ β).inv = β.inv ≫ α.inv := rfl
@[simp] lemma refl_symm (X : C) : (iso.refl X).hom = 𝟙 X := rfl
@[simp] lemma trans_symm (α : X ≅ Y) (β : Y ≅ Z) : (α ≪≫ β).inv = β.inv ≫ α.inv := rfl
lemma inv_comp_eq (α : X ≅ Y) {f : X ⟶ Z} {g : Y ⟶ Z} : α.inv ≫ f = g ↔ f = α.hom ≫ g :=
⟨λ H, by simp [H.symm], λ H, by simp [H]⟩
lemma eq_inv_comp (α : X ≅ Y) {f : X ⟶ Z} {g : Y ⟶ Z} : g = α.inv ≫ f ↔ α.hom ≫ g = f :=
(inv_comp_eq α.symm).symm
lemma comp_inv_eq (α : X ≅ Y) {f : Z ⟶ Y} {g : Z ⟶ X} : f ≫ α.inv = g ↔ f = g ≫ α.hom :=
⟨λ H, by simp [H.symm], λ H, by simp [H]⟩
lemma eq_comp_inv (α : X ≅ Y) {f : Z ⟶ Y} {g : Z ⟶ X} : g = f ≫ α.inv ↔ g ≫ α.hom = f :=
(comp_inv_eq α.symm).symm
end iso
/-- `is_iso` typeclass expressing that a morphism is invertible.
This contains the data of the inverse, but is a subsingleton type. -/
class is_iso (f : X ⟶ Y) :=
(inv : Y ⟶ X)
(hom_inv_id' : f ≫ inv = 𝟙 X . obviously)
(inv_hom_id' : inv ≫ f = 𝟙 Y . obviously)
def inv (f : X ⟶ Y) [is_iso f] := is_iso.inv f
namespace is_iso
@[simp] lemma hom_inv_id (f : X ⟶ Y) [is_iso f] : f ≫ category_theory.inv f = 𝟙 X :=
is_iso.hom_inv_id' f
@[simp] lemma inv_hom_id (f : X ⟶ Y) [is_iso f] : category_theory.inv f ≫ f = 𝟙 Y :=
is_iso.inv_hom_id' f
@[simp] lemma hom_inv_id_assoc {Z} (f : X ⟶ Y) [is_iso f] (g : X ⟶ Z) : f ≫ category_theory.inv f ≫ g = g :=
by rw [←category.assoc, hom_inv_id, category.id_comp]
@[simp] lemma inv_hom_id_assoc {Z} (f : X ⟶ Y) [is_iso f] (g : Y ⟶ Z) : category_theory.inv f ≫ f ≫ g = g :=
by rw [←category.assoc, inv_hom_id, category.id_comp]
instance (X : C) : is_iso (𝟙 X) :=
{ inv := 𝟙 X }
instance of_iso (f : X ≅ Y) : is_iso f.hom :=
{ inv := f.inv }
instance of_iso_inverse (f : X ≅ Y) : is_iso f.inv :=
{ inv := f.hom }
end is_iso
def as_iso (f : X ⟶ Y) [is_iso f] : X ≅ Y :=
{ hom := f, inv := inv f }
@[simp] lemma as_iso_hom (f : X ⟶ Y) [is_iso f] : (as_iso f).hom = f := rfl
@[simp] lemma as_iso_inv (f : X ⟶ Y) [is_iso f] : (as_iso f).inv = inv f := rfl
instance (f : X ⟶ Y) : subsingleton (is_iso f) :=
⟨λ a b,
suffices a.inv = b.inv, by cases a; cases b; congr; exact this,
show (@as_iso C _ _ _ f a).inv = (@as_iso C _ _ _ f b).inv,
by congr' 1; ext; refl⟩
namespace functor
universes u₁ v₁ u₂ v₂
variables {D : Type u₂}
variables [𝒟 : category.{v₂} D]
include 𝒟
def on_iso (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : F.obj X ≅ F.obj Y :=
{ hom := F.map i.hom,
inv := F.map i.inv,
hom_inv_id' := by rw [←map_comp, iso.hom_inv_id, ←map_id],
inv_hom_id' := by rw [←map_comp, iso.inv_hom_id, ←map_id] }
@[simp] lemma on_iso_hom (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : (F.on_iso i).hom = F.map i.hom := rfl
@[simp] lemma on_iso_inv (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : (F.on_iso i).inv = F.map i.inv := rfl
instance (F : C ⥤ D) (f : X ⟶ Y) [is_iso f] : is_iso (F.map f) :=
{ inv := F.map (inv f),
hom_inv_id' := by rw [← F.map_comp, is_iso.hom_inv_id, map_id],
inv_hom_id' := by rw [← F.map_comp, is_iso.inv_hom_id, map_id] }
end functor
instance epi_of_iso (f : X ⟶ Y) [is_iso f] : epi f :=
{ left_cancellation := begin
-- This is an interesting test case for better rewrite automation.
intros,
rw [←category.id_comp C g, ←category.id_comp C h],
rw [← is_iso.inv_hom_id f],
rw [category.assoc, w, category.assoc],
end }
instance mono_of_iso (f : X ⟶ Y) [is_iso f] : mono f :=
{ right_cancellation := begin
intros,
rw [←category.comp_id C g, ←category.comp_id C h],
rw [← is_iso.hom_inv_id f],
rw [←category.assoc, w, ←category.assoc]
end }
def Aut (X : C) := X ≅ X
attribute [extensionality Aut] iso.ext
instance {X : C} : group (Aut X) :=
by refine { one := iso.refl X,
inv := iso.symm,
mul := iso.trans, .. } ; obviously
end category_theory
|
e61de8839068adaf08d020118406422800eb977f | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/category_theory/limits/preserves/shapes/equalizers.lean | a02122d528bfb56e3cf8d168add7864f0a44e07d | [
"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 | 7,363 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import category_theory.limits.shapes.split_coequalizer
import category_theory.limits.preserves.basic
/-!
# Preserving (co)equalizers
Constructions to relate the notions of preserving (co)equalizers and reflecting (co)equalizers
to concrete (co)forks.
In particular, we show that `equalizer_comparison f g G` is an isomorphism iff `G` preserves
the limit of the parallel pair `f,g`, as well as the dual result.
-/
noncomputable theory
universes w v₁ v₂ u₁ u₂
open category_theory category_theory.category category_theory.limits
variables {C : Type u₁} [category.{v₁} C]
variables {D : Type u₂} [category.{v₂} D]
variables (G : C ⥤ D)
namespace category_theory.limits
section equalizers
variables {X Y Z : C} {f g : X ⟶ Y} {h : Z ⟶ X} (w : h ≫ f = h ≫ g)
/--
The map of a fork is a limit iff the fork consisting of the mapped morphisms is a limit. This
essentially lets us commute `fork.of_ι` with `functor.map_cone`.
-/
def is_limit_map_cone_fork_equiv :
is_limit (G.map_cone (fork.of_ι h w)) ≃
is_limit (fork.of_ι (G.map h) (by simp only [←G.map_comp, w]) : fork (G.map f) (G.map g)) :=
(is_limit.postcompose_hom_equiv (diagram_iso_parallel_pair _) _).symm.trans
(is_limit.equiv_iso_limit (fork.ext (iso.refl _) (by { simp [fork.ι] })))
/-- The property of preserving equalizers expressed in terms of forks. -/
def is_limit_fork_map_of_is_limit [preserves_limit (parallel_pair f g) G]
(l : is_limit (fork.of_ι h w)) :
is_limit (fork.of_ι (G.map h) (by simp only [←G.map_comp, w]) : fork (G.map f) (G.map g)) :=
is_limit_map_cone_fork_equiv G w (preserves_limit.preserves l)
/-- The property of reflecting equalizers expressed in terms of forks. -/
def is_limit_of_is_limit_fork_map [reflects_limit (parallel_pair f g) G]
(l : is_limit (fork.of_ι (G.map h) (by simp only [←G.map_comp, w]) : fork (G.map f) (G.map g))) :
is_limit (fork.of_ι h w) :=
reflects_limit.reflects ((is_limit_map_cone_fork_equiv G w).symm l)
variables (f g) [has_equalizer f g]
/--
If `G` preserves equalizers and `C` has them, then the fork constructed of the mapped morphisms of
a fork is a limit.
-/
def is_limit_of_has_equalizer_of_preserves_limit
[preserves_limit (parallel_pair f g) G] :
is_limit (fork.of_ι (G.map (equalizer.ι f g))
(by simp only [←G.map_comp, equalizer.condition])) :=
is_limit_fork_map_of_is_limit G _ (equalizer_is_equalizer f g)
variables [has_equalizer (G.map f) (G.map g)]
/--
If the equalizer comparison map for `G` at `(f,g)` is an isomorphism, then `G` preserves the
equalizer of `(f,g)`.
-/
def preserves_equalizer.of_iso_comparison [i : is_iso (equalizer_comparison f g G)] :
preserves_limit (parallel_pair f g) G :=
begin
apply preserves_limit_of_preserves_limit_cone (equalizer_is_equalizer f g),
apply (is_limit_map_cone_fork_equiv _ _).symm _,
apply is_limit.of_point_iso (limit.is_limit (parallel_pair (G.map f) (G.map g))),
apply i,
end
variables [preserves_limit (parallel_pair f g) G]
/--
If `G` preserves the equalizer of `(f,g)`, then the equalizer comparison map for `G` at `(f,g)` is
an isomorphism.
-/
def preserves_equalizer.iso :
G.obj (equalizer f g) ≅ equalizer (G.map f) (G.map g) :=
is_limit.cone_point_unique_up_to_iso
(is_limit_of_has_equalizer_of_preserves_limit G f g)
(limit.is_limit _)
@[simp]
lemma preserves_equalizer.iso_hom :
(preserves_equalizer.iso G f g).hom = equalizer_comparison f g G :=
rfl
instance : is_iso (equalizer_comparison f g G) :=
begin
rw ← preserves_equalizer.iso_hom,
apply_instance
end
end equalizers
section coequalizers
variables {X Y Z : C} {f g : X ⟶ Y} {h : Y ⟶ Z} (w : f ≫ h = g ≫ h)
/--
The map of a cofork is a colimit iff the cofork consisting of the mapped morphisms is a colimit.
This essentially lets us commute `cofork.of_π` with `functor.map_cocone`.
-/
def is_colimit_map_cocone_cofork_equiv :
is_colimit (G.map_cocone (cofork.of_π h w)) ≃
is_colimit (cofork.of_π (G.map h) (by simp only [←G.map_comp, w]) : cofork (G.map f) (G.map g)) :=
(is_colimit.precompose_inv_equiv (diagram_iso_parallel_pair _) _).symm.trans $
is_colimit.equiv_iso_colimit $ cofork.ext (iso.refl _) $
begin
dsimp only [cofork.π, cofork.of_π_ι_app],
dsimp, rw [category.comp_id, category.id_comp]
end
/-- The property of preserving coequalizers expressed in terms of coforks. -/
def is_colimit_cofork_map_of_is_colimit [preserves_colimit (parallel_pair f g) G]
(l : is_colimit (cofork.of_π h w)) :
is_colimit (cofork.of_π (G.map h) (by simp only [←G.map_comp, w]) : cofork (G.map f) (G.map g)) :=
is_colimit_map_cocone_cofork_equiv G w (preserves_colimit.preserves l)
/-- The property of reflecting coequalizers expressed in terms of coforks. -/
def is_colimit_of_is_colimit_cofork_map [reflects_colimit (parallel_pair f g) G]
(l : is_colimit (cofork.of_π (G.map h) (by simp only [←G.map_comp, w])
: cofork (G.map f) (G.map g))) :
is_colimit (cofork.of_π h w) :=
reflects_colimit.reflects ((is_colimit_map_cocone_cofork_equiv G w).symm l)
variables (f g) [has_coequalizer f g]
/--
If `G` preserves coequalizers and `C` has them, then the cofork constructed of the mapped morphisms
of a cofork is a colimit.
-/
def is_colimit_of_has_coequalizer_of_preserves_colimit
[preserves_colimit (parallel_pair f g) G] :
is_colimit (cofork.of_π (G.map (coequalizer.π f g)) _) :=
is_colimit_cofork_map_of_is_colimit G _ (coequalizer_is_coequalizer f g)
variables [has_coequalizer (G.map f) (G.map g)]
/--
If the coequalizer comparison map for `G` at `(f,g)` is an isomorphism, then `G` preserves the
coequalizer of `(f,g)`.
-/
def of_iso_comparison [i : is_iso (coequalizer_comparison f g G)] :
preserves_colimit (parallel_pair f g) G :=
begin
apply preserves_colimit_of_preserves_colimit_cocone (coequalizer_is_coequalizer f g),
apply (is_colimit_map_cocone_cofork_equiv _ _).symm _,
apply is_colimit.of_point_iso (colimit.is_colimit (parallel_pair (G.map f) (G.map g))),
apply i,
end
variables [preserves_colimit (parallel_pair f g) G]
/--
If `G` preserves the coequalizer of `(f,g)`, then the coequalizer comparison map for `G` at `(f,g)`
is an isomorphism.
-/
def preserves_coequalizer.iso :
coequalizer (G.map f) (G.map g) ≅ G.obj (coequalizer f g) :=
is_colimit.cocone_point_unique_up_to_iso
(colimit.is_colimit _)
(is_colimit_of_has_coequalizer_of_preserves_colimit G f g)
@[simp]
lemma preserves_coequalizer.iso_hom :
(preserves_coequalizer.iso G f g).hom = coequalizer_comparison f g G :=
rfl
instance : is_iso (coequalizer_comparison f g G) :=
begin
rw ← preserves_coequalizer.iso_hom,
apply_instance
end
/-- Any functor preserves coequalizers of split pairs. -/
@[priority 1]
instance preserves_split_coequalizers (f g : X ⟶ Y) [has_split_coequalizer f g] :
preserves_colimit (parallel_pair f g) G :=
begin
apply preserves_colimit_of_preserves_colimit_cocone
((has_split_coequalizer.is_split_coequalizer f g).is_coequalizer),
apply (is_colimit_map_cocone_cofork_equiv G _).symm
((has_split_coequalizer.is_split_coequalizer f g).map G).is_coequalizer,
end
end coequalizers
end category_theory.limits
|
34858d4b009981cdbca8100298d3f9a17c150c6b | 22e97a5d648fc451e25a06c668dc03ac7ed7bc25 | /src/analysis/specific_limits.lean | 21949bf1be4156c02d61987a48e5e5b874e80e8b | [
"Apache-2.0"
] | permissive | keeferrowan/mathlib | f2818da875dbc7780830d09bd4c526b0764a4e50 | aad2dfc40e8e6a7e258287a7c1580318e865817e | refs/heads/master | 1,661,736,426,952 | 1,590,438,032,000 | 1,590,438,032,000 | 266,892,663 | 0 | 0 | Apache-2.0 | 1,590,445,835,000 | 1,590,445,835,000 | null | UTF-8 | Lean | false | false | 23,680 | 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
A collection of specific limit computations.
-/
import analysis.normed_space.basic
import algebra.geom_sum
import topology.instances.ennreal
noncomputable theory
open_locale classical topological_space
open classical function filter finset metric
open_locale big_operators
variables {α : Type*} {β : Type*} {ι : Type*}
lemma tendsto_norm_at_top_at_top : tendsto (norm : ℝ → ℝ) at_top at_top :=
tendsto_abs_at_top_at_top
/-- If a function tends to infinity along a filter, then this function multiplied by a positive
constant (on the left) also tends to infinity. The archimedean assumption is convenient to get a
statement that works on `ℕ`, `ℤ` and `ℝ`, although not necessary (a version in ordered fields is
given in `tendsto_at_top_mul_left'`). -/
lemma tendsto_at_top_mul_left [decidable_linear_ordered_semiring α] [archimedean α]
{l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) :
tendsto (λx, r * f x) l at_top :=
begin
apply (tendsto_at_top _ _).2 (λb, _),
obtain ⟨n, hn⟩ : ∃ (n : ℕ), (1 : α) ≤ n • r := archimedean.arch 1 hr,
have hn' : 1 ≤ r * n, by rwa add_monoid.smul_eq_mul' at hn,
filter_upwards [(tendsto_at_top _ _).1 hf (n * max b 0)],
assume x hx,
calc b ≤ 1 * max b 0 : by { rw [one_mul], exact le_max_left _ _ }
... ≤ (r * n) * max b 0 : mul_le_mul_of_nonneg_right hn' (le_max_right _ _)
... = r * (n * max b 0) : by rw [mul_assoc]
... ≤ r * f x : mul_le_mul_of_nonneg_left hx (le_of_lt hr)
end
/-- If a function tends to infinity along a filter, then this function multiplied by a positive
constant (on the right) also tends to infinity. The archimedean assumption is convenient to get a
statement that works on `ℕ`, `ℤ` and `ℝ`, although not necessary (a version in ordered fields is
given in `tendsto_at_top_mul_right'`). -/
lemma tendsto_at_top_mul_right [decidable_linear_ordered_semiring α] [archimedean α]
{l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) :
tendsto (λx, f x * r) l at_top :=
begin
apply (tendsto_at_top _ _).2 (λb, _),
obtain ⟨n, hn⟩ : ∃ (n : ℕ), (1 : α) ≤ n • r := archimedean.arch 1 hr,
have hn' : 1 ≤ (n : α) * r, by rwa add_monoid.smul_eq_mul at hn,
filter_upwards [(tendsto_at_top _ _).1 hf (max b 0 * n)],
assume x hx,
calc b ≤ max b 0 * 1 : by { rw [mul_one], exact le_max_left _ _ }
... ≤ max b 0 * (n * r) : mul_le_mul_of_nonneg_left hn' (le_max_right _ _)
... = (max b 0 * n) * r : by rw [mul_assoc]
... ≤ f x * r : mul_le_mul_of_nonneg_right hx (le_of_lt hr)
end
/-- If a function tends to infinity along a filter, then this function multiplied by a positive
constant (on the left) also tends to infinity. For a version working in `ℕ` or `ℤ`, use
`tendsto_at_top_mul_left` instead. -/
lemma tendsto_at_top_mul_left' [linear_ordered_field α]
{l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) :
tendsto (λx, r * f x) l at_top :=
begin
apply (tendsto_at_top _ _).2 (λb, _),
filter_upwards [(tendsto_at_top _ _).1 hf (b/r)],
assume x hx,
simpa [div_le_iff' hr] using hx
end
/-- If a function tends to infinity along a filter, then this function multiplied by a positive
constant (on the right) also tends to infinity. For a version working in `ℕ` or `ℤ`, use
`tendsto_at_top_mul_right` instead. -/
lemma tendsto_at_top_mul_right' [linear_ordered_field α]
{l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) :
tendsto (λx, f x * r) l at_top :=
by simpa [mul_comm] using tendsto_at_top_mul_left' hr hf
/-- If a function tends to infinity along a filter, then this function divided by a positive
constant also tends to infinity. -/
lemma tendsto_at_top_div [linear_ordered_field α]
{l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) :
tendsto (λx, f x / r) l at_top :=
tendsto_at_top_mul_right' (inv_pos.2 hr) hf
/-- The function `x ↦ x⁻¹` tends to `+∞` on the right of `0`. -/
lemma tendsto_inv_zero_at_top [discrete_linear_ordered_field α] [topological_space α]
[order_topology α] : tendsto (λx:α, x⁻¹) (nhds_within (0 : α) (set.Ioi 0)) at_top :=
begin
apply (tendsto_at_top _ _).2 (λb, _),
refine mem_nhds_within_Ioi_iff_exists_Ioo_subset.2 ⟨(max b 1)⁻¹, by simp [zero_lt_one], λx hx, _⟩,
calc b ≤ max b 1 : le_max_left _ _
... ≤ x⁻¹ : begin
apply (le_inv _ hx.1).2 (le_of_lt hx.2),
exact lt_of_lt_of_le zero_lt_one (le_max_right _ _)
end
end
/-- The function `r ↦ r⁻¹` tends to `0` on the right as `r → +∞`. -/
lemma tendsto_inv_at_top_zero' [discrete_linear_ordered_field α] [topological_space α]
[order_topology α] : tendsto (λr:α, r⁻¹) at_top (nhds_within (0 : α) (set.Ioi 0)) :=
begin
assume s hs,
rw mem_nhds_within_Ioi_iff_exists_Ioc_subset at hs,
rcases hs with ⟨C, C0, hC⟩,
change 0 < C at C0,
refine filter.mem_map.2 (mem_sets_of_superset (mem_at_top C⁻¹) (λ x hx, hC _)),
have : 0 < x, from lt_of_lt_of_le (inv_pos.2 C0) hx,
exact ⟨inv_pos.2 this, (inv_le C0 this).1 hx⟩
end
lemma tendsto_inv_at_top_zero [discrete_linear_ordered_field α] [topological_space α]
[order_topology α] : tendsto (λr:α, r⁻¹) at_top (𝓝 0) :=
tendsto_le_right inf_le_left tendsto_inv_at_top_zero'
lemma summable_of_absolute_convergence_real {f : ℕ → ℝ} :
(∃r, tendsto (λn, (∑ i in range n, abs (f i))) at_top (𝓝 r)) → summable f
| ⟨r, hr⟩ :=
begin
refine summable_of_summable_norm ⟨r, (has_sum_iff_tendsto_nat_of_nonneg _ _).2 _⟩,
exact assume i, norm_nonneg _,
simpa only using hr
end
lemma tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ)⁻¹) at_top (𝓝 0) :=
tendsto_inv_at_top_zero.comp (tendsto_coe_nat_real_at_top_iff.2 tendsto_id)
lemma tendsto_const_div_at_top_nhds_0_nat (C : ℝ) : tendsto (λ n : ℕ, C / n) at_top (𝓝 0) :=
by simpa only [mul_zero] using tendsto_const_nhds.mul tendsto_inverse_at_top_nhds_0_nat
lemma nnreal.tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : nnreal)⁻¹) at_top (𝓝 0) :=
by { rw ← nnreal.tendsto_coe, convert tendsto_inverse_at_top_nhds_0_nat, simp }
lemma nnreal.tendsto_const_div_at_top_nhds_0_nat (C : nnreal) :
tendsto (λ n : ℕ, C / n) at_top (𝓝 0) :=
by simpa using tendsto_const_nhds.mul nnreal.tendsto_inverse_at_top_nhds_0_nat
lemma tendsto_one_div_add_at_top_nhds_0_nat :
tendsto (λ n : ℕ, 1 / ((n : ℝ) + 1)) at_top (𝓝 0) :=
suffices tendsto (λ n : ℕ, 1 / (↑(n + 1) : ℝ)) at_top (𝓝 0), by simpa,
(tendsto_add_at_top_iff_nat 1).2 (tendsto_const_div_at_top_nhds_0_nat 1)
/-! ### Powers -/
lemma tendsto_pow_at_top_at_top_of_gt_1 {r : ℝ} (h : 1 < r) :
tendsto (λn:ℕ, r ^ n) at_top at_top :=
(tendsto_at_top_at_top _).2 $ assume p,
let ⟨n, hn⟩ := pow_unbounded_of_one_lt p h in
⟨n, λ m hnm, le_of_lt $
lt_of_lt_of_le hn (pow_le_pow (le_of_lt h) hnm)⟩
lemma lim_norm_zero' {𝕜 : Type*} [normed_group 𝕜] :
tendsto (norm : 𝕜 → ℝ) (nhds_within 0 {x | x ≠ 0}) (nhds_within 0 (set.Ioi 0)) :=
lim_norm_zero.inf $ tendsto_principal_principal.2 $ λ x hx, norm_pos_iff.2 hx
lemma normed_field.tendsto_norm_inverse_nhds_within_0_at_top {𝕜 : Type*} [normed_field 𝕜] :
tendsto (λ x:𝕜, ∥x⁻¹∥) (nhds_within 0 {x | x ≠ 0}) at_top :=
(tendsto_inv_zero_at_top.comp lim_norm_zero').congr $ λ x, (normed_field.norm_inv x).symm
lemma tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) :
tendsto (λn:ℕ, r^n) at_top (𝓝 0) :=
by_cases
(assume : r = 0, (tendsto_add_at_top_iff_nat 1).mp $ by simp [pow_succ, this, tendsto_const_nhds])
(assume : r ≠ 0,
have tendsto (λn, (r⁻¹ ^ n)⁻¹) at_top (𝓝 0),
from tendsto_inv_at_top_zero.comp
(tendsto_pow_at_top_at_top_of_gt_1 $ one_lt_inv (lt_of_le_of_ne h₁ this.symm) h₂),
tendsto.congr' (univ_mem_sets' $ by simp *) this)
lemma nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : nnreal} (hr : r < 1) :
tendsto (λ n:ℕ, r^n) at_top (𝓝 0) :=
nnreal.tendsto_coe.1 $ by simp only [nnreal.coe_pow, nnreal.coe_zero,
tendsto_pow_at_top_nhds_0_of_lt_1 r.coe_nonneg hr]
lemma ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : ennreal} (hr : r < 1) :
tendsto (λ n:ℕ, r^n) at_top (𝓝 0) :=
begin
rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩,
rw [← ennreal.coe_zero],
norm_cast at *,
apply nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 hr
end
lemma tendsto_pow_at_top_nhds_0_of_norm_lt_1 {K : Type*} [normed_field K] {ξ : K}
(_ : ∥ξ∥ < 1) : tendsto (λ n : ℕ, ξ^n) at_top (𝓝 0) :=
begin
rw [tendsto_iff_norm_tendsto_zero],
convert tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg ξ) ‹∥ξ∥ < 1›,
ext n,
simp
end
lemma tendsto_pow_at_top_nhds_0_of_abs_lt_1 {r : ℝ} (h : abs r < 1) :
tendsto (λn:ℕ, r^n) at_top (𝓝 0) :=
tendsto_pow_at_top_nhds_0_of_norm_lt_1 h
lemma tendsto_pow_at_top_at_top_of_gt_1_nat {k : ℕ} (h : 1 < k) :
tendsto (λn:ℕ, k ^ n) at_top at_top :=
tendsto_coe_nat_real_at_top_iff.1 $
have hr : 1 < (k : ℝ), by rw [← nat.cast_one, nat.cast_lt]; exact h,
by simpa using tendsto_pow_at_top_at_top_of_gt_1 hr
/-! ### Geometric series-/
section geometric
lemma has_sum_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) :
has_sum (λn:ℕ, r ^ n) (1 - r)⁻¹ :=
have r ≠ 1, from ne_of_lt h₂,
have r + -1 ≠ 0,
by rw [←sub_eq_add_neg, ne, sub_eq_iff_eq_add]; simp; assumption,
have tendsto (λn, (r ^ n - 1) * (r - 1)⁻¹) at_top (𝓝 ((0 - 1) * (r - 1)⁻¹)),
from ((tendsto_pow_at_top_nhds_0_of_lt_1 h₁ h₂).sub tendsto_const_nhds).mul tendsto_const_nhds,
have (λ n, (∑ i in range n, r ^ i)) = (λ n, geom_series r n) := rfl,
(has_sum_iff_tendsto_nat_of_nonneg (pow_nonneg h₁) _).mpr $
by simp [neg_inv, geom_sum, div_eq_mul_inv, *] at *
lemma summable_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : summable (λn:ℕ, r ^ n) :=
⟨_, has_sum_geometric_of_lt_1 h₁ h₂⟩
lemma tsum_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : (∑'n:ℕ, r ^ n) = (1 - r)⁻¹ :=
tsum_eq_has_sum (has_sum_geometric_of_lt_1 h₁ h₂)
lemma has_sum_geometric_two : has_sum (λn:ℕ, ((1:ℝ)/2) ^ n) 2 :=
by convert has_sum_geometric_of_lt_1 _ _; norm_num
lemma summable_geometric_two : summable (λn:ℕ, ((1:ℝ)/2) ^ n) :=
⟨_, has_sum_geometric_two⟩
lemma tsum_geometric_two : (∑'n:ℕ, ((1:ℝ)/2) ^ n) = 2 :=
tsum_eq_has_sum has_sum_geometric_two
lemma has_sum_geometric_two' (a : ℝ) : has_sum (λn:ℕ, (a / 2) / 2 ^ n) a :=
begin
convert has_sum.mul_left (a / 2) (has_sum_geometric_of_lt_1
(le_of_lt one_half_pos) one_half_lt_one),
{ funext n, simp, refl, },
{ norm_num }
end
lemma summable_geometric_two' (a : ℝ) : summable (λ n:ℕ, (a / 2) / 2 ^ n) :=
⟨a, has_sum_geometric_two' a⟩
lemma tsum_geometric_two' (a : ℝ) : (∑' n:ℕ, (a / 2) / 2^n) = a :=
tsum_eq_has_sum $ has_sum_geometric_two' a
lemma nnreal.has_sum_geometric {r : nnreal} (hr : r < 1) :
has_sum (λ n : ℕ, r ^ n) (1 - r)⁻¹ :=
begin
apply nnreal.has_sum_coe.1,
push_cast,
rw [nnreal.coe_sub (le_of_lt hr)],
exact has_sum_geometric_of_lt_1 r.coe_nonneg hr
end
lemma nnreal.summable_geometric {r : nnreal} (hr : r < 1) : summable (λn:ℕ, r ^ n) :=
⟨_, nnreal.has_sum_geometric hr⟩
lemma tsum_geometric_nnreal {r : nnreal} (hr : r < 1) : (∑'n:ℕ, r ^ n) = (1 - r)⁻¹ :=
tsum_eq_has_sum (nnreal.has_sum_geometric hr)
/-- The series `pow r` converges to `(1-r)⁻¹`. For `r < 1` the RHS is a finite number,
and for `1 ≤ r` the RHS equals `∞`. -/
lemma ennreal.tsum_geometric (r : ennreal) : (∑'n:ℕ, r ^ n) = (1 - r)⁻¹ :=
begin
cases lt_or_le r 1 with hr hr,
{ rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩,
norm_cast at *,
convert ennreal.tsum_coe_eq (nnreal.has_sum_geometric hr),
rw [ennreal.coe_inv $ ne_of_gt $ nnreal.sub_pos.2 hr] },
{ rw [ennreal.sub_eq_zero_of_le hr, ennreal.inv_zero, ennreal.tsum_eq_supr_nat, supr_eq_top],
refine λ a ha, (ennreal.exists_nat_gt (lt_top_iff_ne_top.1 ha)).imp
(λ n hn, lt_of_lt_of_le hn _),
have : ∀ k:ℕ, 1 ≤ r^k, by simpa using canonically_ordered_semiring.pow_le_pow_of_le_left hr,
calc (n:ennreal) = (∑ i in range n, 1) : by rw [sum_const, add_monoid.smul_one, card_range]
... ≤ ∑ i in range n, r ^ i : sum_le_sum (λ k _, this k) }
end
variables {K : Type*} [normed_field K] {ξ : K}
lemma has_sum_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : has_sum (λn:ℕ, ξ ^ n) (1 - ξ)⁻¹ :=
begin
have xi_ne_one : ξ ≠ 1, by { contrapose! h, simp [h] },
have A : tendsto (λn, (ξ ^ n - 1) * (ξ - 1)⁻¹) at_top (𝓝 ((0 - 1) * (ξ - 1)⁻¹)),
from ((tendsto_pow_at_top_nhds_0_of_norm_lt_1 h).sub tendsto_const_nhds).mul tendsto_const_nhds,
have B : (λ n, (∑ i in range n, ξ ^ i)) = (λ n, geom_series ξ n) := rfl,
rw [has_sum_iff_tendsto_nat_of_summable_norm, B],
{ simpa [geom_sum, xi_ne_one, neg_inv] using A },
{ simp [normed_field.norm_pow, summable_geometric_of_lt_1 (norm_nonneg _) h] }
end
lemma summable_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : summable (λn:ℕ, ξ ^ n) :=
⟨_, has_sum_geometric_of_norm_lt_1 h⟩
lemma tsum_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : (∑'n:ℕ, ξ ^ n) = (1 - ξ)⁻¹ :=
tsum_eq_has_sum (has_sum_geometric_of_norm_lt_1 h)
lemma has_sum_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : has_sum (λn:ℕ, r ^ n) (1 - r)⁻¹ :=
has_sum_geometric_of_norm_lt_1 h
lemma summable_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : summable (λn:ℕ, r ^ n) :=
summable_geometric_of_norm_lt_1 h
lemma tsum_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : (∑'n:ℕ, r ^ n) = (1 - r)⁻¹ :=
tsum_geometric_of_norm_lt_1 h
end geometric
/-!
### Sequences with geometrically decaying distance in metric spaces
In this paragraph, we discuss sequences in metric spaces or emetric spaces for which the distance
between two consecutive terms decays geometrically. We show that such sequences are Cauchy
sequences, and bound their distances to the limit. We also discuss series with geometrically
decaying terms.
-/
section edist_le_geometric
variables [emetric_space α] (r C : ennreal) (hr : r < 1) (hC : C ≠ ⊤) {f : ℕ → α}
(hu : ∀n, edist (f n) (f (n+1)) ≤ C * r^n)
include hr hC hu
/-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, `C ≠ ∞`, `r < 1`,
then `f` is a Cauchy sequence.-/
lemma cauchy_seq_of_edist_le_geometric : cauchy_seq f :=
begin
refine cauchy_seq_of_edist_le_of_tsum_ne_top _ hu _,
rw [ennreal.tsum_mul_left, ennreal.tsum_geometric],
refine ennreal.mul_ne_top hC (ennreal.inv_ne_top.2 _),
exact ne_of_gt (ennreal.zero_lt_sub_iff_lt.2 hr)
end
omit hr hC
/-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from
`f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/
lemma edist_le_of_edist_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) :
edist (f n) a ≤ (C * r^n) / (1 - r) :=
begin
convert edist_le_tsum_of_edist_le_of_tendsto _ hu ha _,
simp only [pow_add, ennreal.tsum_mul_left, ennreal.tsum_geometric, ennreal.div_def, mul_assoc]
end
/-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from
`f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/
lemma edist_le_of_edist_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) :
edist (f 0) a ≤ C / (1 - r) :=
by simpa only [pow_zero, mul_one] using edist_le_of_edist_le_geometric_of_tendsto r C hu ha 0
end edist_le_geometric
section edist_le_geometric_two
variables [emetric_space α] (C : ennreal) (hC : C ≠ ⊤) {f : ℕ → α}
(hu : ∀n, edist (f n) (f (n+1)) ≤ C / 2^n) {a : α} (ha : tendsto f at_top (𝓝 a))
include hC hu
/-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then `f` is a Cauchy sequence.-/
lemma cauchy_seq_of_edist_le_geometric_two : cauchy_seq f :=
begin
simp only [ennreal.div_def, ennreal.inv_pow] at hu,
refine cauchy_seq_of_edist_le_geometric 2⁻¹ C _ hC hu,
simp [ennreal.one_lt_two]
end
omit hC
include ha
/-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from
`f n` to the limit of `f` is bounded above by `2 * C * 2^-n`. -/
lemma edist_le_of_edist_le_geometric_two_of_tendsto (n : ℕ) :
edist (f n) a ≤ 2 * C / 2^n :=
begin
simp only [ennreal.div_def, ennreal.inv_pow] at hu,
rw [ennreal.div_def, mul_assoc, mul_comm, ennreal.inv_pow],
convert edist_le_of_edist_le_geometric_of_tendsto 2⁻¹ C hu ha n,
rw [ennreal.one_sub_inv_two, ennreal.inv_inv]
end
/-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from
`f 0` to the limit of `f` is bounded above by `2 * C`. -/
lemma edist_le_of_edist_le_geometric_two_of_tendsto₀: edist (f 0) a ≤ 2 * C :=
by simpa only [pow_zero, ennreal.div_def, ennreal.inv_one, mul_one]
using edist_le_of_edist_le_geometric_two_of_tendsto C hu ha 0
end edist_le_geometric_two
section le_geometric
variables [metric_space α] {r C : ℝ} (hr : r < 1) {f : ℕ → α}
(hu : ∀n, dist (f n) (f (n+1)) ≤ C * r^n)
include hr hu
lemma aux_has_sum_of_le_geometric : has_sum (λ n : ℕ, C * r^n) (C / (1 - r)) :=
begin
have h0 : 0 ≤ C,
by simpa using le_trans dist_nonneg (hu 0),
rcases eq_or_lt_of_le h0 with rfl | Cpos,
{ simp [has_sum_zero] },
{ have rnonneg: r ≥ 0, from nonneg_of_mul_nonneg_left
(by simpa only [pow_one] using le_trans dist_nonneg (hu 1)) Cpos,
refine has_sum.mul_left C _,
by simpa using has_sum_geometric_of_lt_1 rnonneg hr }
end
variables (r C)
/-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then `f` is a Cauchy sequence.
Note that this lemma does not assume `0 ≤ C` or `0 ≤ r`. -/
lemma cauchy_seq_of_le_geometric : cauchy_seq f :=
cauchy_seq_of_dist_le_of_summable _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩
/-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from
`f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/
lemma dist_le_of_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) :
dist (f 0) a ≤ C / (1 - r) :=
(tsum_eq_has_sum $ aux_has_sum_of_le_geometric hr hu) ▸
dist_le_tsum_of_dist_le_of_tendsto₀ _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩ ha
/-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from
`f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/
lemma dist_le_of_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) :
dist (f n) a ≤ (C * r^n) / (1 - r) :=
begin
have := aux_has_sum_of_le_geometric hr hu,
convert dist_le_tsum_of_dist_le_of_tendsto _ hu ⟨_, this⟩ ha n,
simp only [pow_add, mul_left_comm C, mul_div_right_comm],
rw [mul_comm],
exact (eq.symm $ tsum_eq_has_sum $ this.mul_left _)
end
omit hr hu
variable (hu₂ : ∀ n, dist (f n) (f (n+1)) ≤ (C / 2) / 2^n)
/-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then `f` is a Cauchy sequence. -/
lemma cauchy_seq_of_le_geometric_two : cauchy_seq f :=
cauchy_seq_of_dist_le_of_summable _ hu₂ $ ⟨_, has_sum_geometric_two' C⟩
/-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from
`f 0` to the limit of `f` is bounded above by `C`. -/
lemma dist_le_of_le_geometric_two_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) :
dist (f 0) a ≤ C :=
(tsum_geometric_two' C) ▸ dist_le_tsum_of_dist_le_of_tendsto₀ _ hu₂ (summable_geometric_two' C) ha
include hu₂
/-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from
`f n` to the limit of `f` is bounded above by `C / 2^n`. -/
lemma dist_le_of_le_geometric_two_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) :
dist (f n) a ≤ C / 2^n :=
begin
convert dist_le_tsum_of_dist_le_of_tendsto _ hu₂ (summable_geometric_two' C) ha n,
simp only [add_comm n, pow_add, (div_div_eq_div_mul _ _ _).symm],
symmetry,
exact tsum_eq_has_sum (has_sum.mul_right _ $ has_sum_geometric_two' C)
end
end le_geometric
section summable_le_geometric
variables [normed_group α] {r C : ℝ} {f : ℕ → α}
lemma dist_partial_sum_le_of_le_geometric (hf : ∀n, ∥f n∥ ≤ C * r^n) (n : ℕ) :
dist (∑ i in range n, f i) (∑ i in range (n+1), f i) ≤ C * r ^ n :=
begin
rw [sum_range_succ, dist_eq_norm, ← norm_neg],
convert hf n,
rw [neg_sub, add_sub_cancel]
end
/-- If `∥f n∥ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` form a
Cauchy sequence. This lemma does not assume `0 ≤ r` or `0 ≤ C`. -/
lemma cauchy_seq_finset_of_geometric_bound (hr : r < 1) (hf : ∀n, ∥f n∥ ≤ C * r^n) :
cauchy_seq (λ s : finset (ℕ), s.sum f) :=
cauchy_seq_finset_of_norm_bounded _
(aux_has_sum_of_le_geometric hr (dist_partial_sum_le_of_le_geometric hf)).summable hf
/-- If `∥f n∥ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` are within
distance `C * r ^ n / (1 - r)` of the sum of the series. This lemma does not assume `0 ≤ r` or
`0 ≤ C`. -/
lemma norm_sub_le_of_geometric_bound_of_has_sum (hr : r < 1) (hf : ∀n, ∥f n∥ ≤ C * r^n)
{a : α} (ha : has_sum f a) (n : ℕ) :
∥(finset.range n).sum f - a∥ ≤ (C * r ^ n) / (1 - r) :=
begin
rw ← dist_eq_norm,
apply dist_le_of_le_geometric_of_tendsto r C hr (dist_partial_sum_le_of_le_geometric hf),
exact ha.tendsto_sum_nat
end
end summable_le_geometric
/-! ### Positive sequences with small sums on encodable types -/
/-- For any positive `ε`, define on an encodable type a positive sequence with sum less than `ε` -/
def pos_sum_of_encodable {ε : ℝ} (hε : 0 < ε)
(ι) [encodable ι] : {ε' : ι → ℝ // (∀ i, 0 < ε' i) ∧ ∃ c, has_sum ε' c ∧ c ≤ ε} :=
begin
let f := λ n, (ε / 2) / 2 ^ n,
have hf : has_sum f ε := has_sum_geometric_two' _,
have f0 : ∀ n, 0 < f n := λ n, div_pos (half_pos hε) (pow_pos two_pos _),
refine ⟨f ∘ encodable.encode, λ i, f0 _, _⟩,
rcases hf.summable.summable_comp_of_injective (@encodable.encode_injective ι _)
with ⟨c, hg⟩,
refine ⟨c, hg, has_sum_le_inj _ (@encodable.encode_injective ι _) _ _ hg hf⟩,
{ assume i _, exact le_of_lt (f0 _) },
{ assume n, exact le_refl _ }
end
namespace nnreal
theorem exists_pos_sum_of_encodable {ε : nnreal} (hε : 0 < ε) (ι) [encodable ι] :
∃ ε' : ι → nnreal, (∀ i, 0 < ε' i) ∧ ∃c, has_sum ε' c ∧ c < ε :=
let ⟨a, a0, aε⟩ := dense hε in
let ⟨ε', hε', c, hc, hcε⟩ := pos_sum_of_encodable a0 ι in
⟨ λi, ⟨ε' i, le_of_lt $ hε' i⟩, assume i, nnreal.coe_lt_coe.2 $ hε' i,
⟨c, has_sum_le (assume i, le_of_lt $ hε' i) has_sum_zero hc ⟩, nnreal.has_sum_coe.1 hc,
lt_of_le_of_lt (nnreal.coe_le_coe.1 hcε) aε ⟩
end nnreal
namespace ennreal
theorem exists_pos_sum_of_encodable {ε : ennreal} (hε : 0 < ε) (ι) [encodable ι] :
∃ ε' : ι → nnreal, (∀ i, 0 < ε' i) ∧ (∑' i, (ε' i : ennreal)) < ε :=
begin
rcases dense hε with ⟨r, h0r, hrε⟩,
rcases lt_iff_exists_coe.1 hrε with ⟨x, rfl, hx⟩,
rcases nnreal.exists_pos_sum_of_encodable (coe_lt_coe.1 h0r) ι with ⟨ε', hp, c, hc, hcr⟩,
exact ⟨ε', hp, (ennreal.tsum_coe_eq hc).symm ▸ lt_trans (coe_lt_coe.2 hcr) hrε⟩
end
end ennreal
|
630e0855fb435eb82dcfadce4631d4e8d41dc9ef | 4fa161becb8ce7378a709f5992a594764699e268 | /src/data/seq/wseq.lean | 37a19a3673528a8772af9a7df2eb5d65b4af763c | [
"Apache-2.0"
] | permissive | laughinggas/mathlib | e4aa4565ae34e46e834434284cb26bd9d67bc373 | 86dcd5cda7a5017c8b3c8876c89a510a19d49aad | refs/heads/master | 1,669,496,232,688 | 1,592,831,995,000 | 1,592,831,995,000 | 274,155,979 | 0 | 0 | Apache-2.0 | 1,592,835,190,000 | 1,592,835,189,000 | null | UTF-8 | Lean | false | false | 54,997 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import data.seq.seq
import data.dlist
universes u v w
/-
coinductive wseq (α : Type u) : Type u
| nil : wseq α
| cons : α → wseq α → wseq α
| think : wseq α → wseq α
-/
/-- Weak sequences.
While the `seq` structure allows for lists which may not be finite,
a weak sequence also allows the computation of each element to
involve an indeterminate amount of computation, including possibly
an infinite loop. This is represented as a regular `seq` interspersed
with `none` elements to indicate that computation is ongoing.
This model is appropriate for Haskell style lazy lists, and is closed
under most interesting computation patterns on infinite lists,
but conversely it is difficult to extract elements from it. -/
def wseq (α) := seq (option α)
namespace wseq
variables {α : Type u} {β : Type v} {γ : Type w}
/-- Turn a sequence into a weak sequence -/
def of_seq : seq α → wseq α := (<$>) some
/-- Turn a list into a weak sequence -/
def of_list (l : list α) : wseq α := of_seq l
/-- Turn a stream into a weak sequence -/
def of_stream (l : stream α) : wseq α := of_seq l
instance coe_seq : has_coe (seq α) (wseq α) := ⟨of_seq⟩
instance coe_list : has_coe (list α) (wseq α) := ⟨of_list⟩
instance coe_stream : has_coe (stream α) (wseq α) := ⟨of_stream⟩
/-- The empty weak sequence -/
def nil : wseq α := seq.nil
instance : inhabited (wseq α) := ⟨nil⟩
/-- Prepend an element to a weak sequence -/
def cons (a : α) : wseq α → wseq α := seq.cons (some a)
/-- Compute for one tick, without producing any elements -/
def think : wseq α → wseq α := seq.cons none
/-- Destruct a weak sequence, to (eventually possibly) produce either
`none` for `nil` or `some (a, s)` if an element is produced. -/
def destruct : wseq α → computation (option (α × wseq α)) :=
computation.corec (λs, match seq.destruct s with
| none := sum.inl none
| some (none, s') := sum.inr s'
| some (some a, s') := sum.inl (some (a, s'))
end)
def cases_on {C : wseq α → Sort v} (s : wseq α) (h1 : C nil)
(h2 : ∀ x s, C (cons x s)) (h3 : ∀ s, C (think s)) : C s :=
seq.cases_on s h1 (λ o, option.cases_on o h3 h2)
protected def mem (a : α) (s : wseq α) := seq.mem (some a) s
instance : has_mem α (wseq α) :=
⟨wseq.mem⟩
theorem not_mem_nil (a : α) : a ∉ @nil α := seq.not_mem_nil a
/-- Get the head of a weak sequence. This involves a possibly
infinite computation. -/
def head (s : wseq α) : computation (option α) :=
computation.map ((<$>) prod.fst) (destruct s)
/-- Encode a computation yielding a weak sequence into additional
`think` constructors in a weak sequence -/
def flatten : computation (wseq α) → wseq α :=
seq.corec (λc, match computation.destruct c with
| sum.inl s := seq.omap return (seq.destruct s)
| sum.inr c' := some (none, c')
end)
/-- Get the tail of a weak sequence. This doesn't need a `computation`
wrapper, unlike `head`, because `flatten` allows us to hide this
in the construction of the weak sequence itself. -/
def tail (s : wseq α) : wseq α :=
flatten $ (λo, option.rec_on o nil prod.snd) <$> destruct s
/-- drop the first `n` elements from `s`. -/
def drop (s : wseq α) : ℕ → wseq α
| 0 := s
| (n+1) := tail (drop n)
attribute [simp] drop
/-- Get the nth element of `s`. -/
def nth (s : wseq α) (n : ℕ) : computation (option α) := head (drop s n)
/-- Convert `s` to a list (if it is finite and completes in finite time). -/
def to_list (s : wseq α) : computation (list α) :=
@computation.corec (list α) (list α × wseq α) (λ⟨l, s⟩,
match seq.destruct s with
| none := sum.inl l.reverse
| some (none, s') := sum.inr (l, s')
| some (some a, s') := sum.inr (a::l, s')
end) ([], s)
/-- Get the length of `s` (if it is finite and completes in finite time). -/
def length (s : wseq α) : computation ℕ :=
@computation.corec ℕ (ℕ × wseq α) (λ⟨n, s⟩,
match seq.destruct s with
| none := sum.inl n
| some (none, s') := sum.inr (n, s')
| some (some a, s') := sum.inr (n+1, s')
end) (0, s)
/-- A weak sequence is finite if `to_list s` terminates. Equivalently,
it is a finite number of `think` and `cons` applied to `nil`. -/
@[class] def is_finite (s : wseq α) : Prop := (to_list s).terminates
instance to_list_terminates (s : wseq α) [h : is_finite s] : (to_list s).terminates := h
/-- Get the list corresponding to a finite weak sequence. -/
def get (s : wseq α) [is_finite s] : list α := (to_list s).get
/-- A weak sequence is *productive* if it never stalls forever - there are
always a finite number of `think`s between `cons` constructors.
The sequence itself is allowed to be infinite though. -/
@[class] def productive (s : wseq α) : Prop := ∀ n, (nth s n).terminates
instance nth_terminates (s : wseq α) [h : productive s] : ∀ n, (nth s n).terminates := h
instance head_terminates (s : wseq α) [h : productive s] : (head s).terminates := h 0
/-- Replace the `n`th element of `s` with `a`. -/
def update_nth (s : wseq α) (n : ℕ) (a : α) : wseq α :=
@seq.corec (option α) (ℕ × wseq α) (λ⟨n, s⟩,
match seq.destruct s, n with
| none, n := none
| some (none, s'), n := some (none, n, s')
| some (some a', s'), 0 := some (some a', 0, s')
| some (some a', s'), 1 := some (some a, 0, s')
| some (some a', s'), (n+2) := some (some a', n+1, s')
end) (n+1, s)
/-- Remove the `n`th element of `s`. -/
def remove_nth (s : wseq α) (n : ℕ) : wseq α :=
@seq.corec (option α) (ℕ × wseq α) (λ⟨n, s⟩,
match seq.destruct s, n with
| none, n := none
| some (none, s'), n := some (none, n, s')
| some (some a', s'), 0 := some (some a', 0, s')
| some (some a', s'), 1 := some (none, 0, s')
| some (some a', s'), (n+2) := some (some a', n+1, s')
end) (n+1, s)
/-- Map the elements of `s` over `f`, removing any values that yield `none`. -/
def filter_map (f : α → option β) : wseq α → wseq β :=
seq.corec (λs, match seq.destruct s with
| none := none
| some (none, s') := some (none, s')
| some (some a, s') := some (f a, s')
end)
/-- Select the elements of `s` that satisfy `p`. -/
def filter (p : α → Prop) [decidable_pred p] : wseq α → wseq α :=
filter_map (λa, if p a then some a else none)
-- example of infinite list manipulations
/-- Get the first element of `s` satisfying `p`. -/
def find (p : α → Prop) [decidable_pred p] (s : wseq α) : computation (option α) :=
head $ filter p s
/-- Zip a function over two weak sequences -/
def zip_with (f : α → β → γ) (s1 : wseq α) (s2 : wseq β) : wseq γ :=
@seq.corec (option γ) (wseq α × wseq β) (λ⟨s1, s2⟩,
match seq.destruct s1, seq.destruct s2 with
| some (none, s1'), some (none, s2') := some (none, s1', s2')
| some (some a1, s1'), some (none, s2') := some (none, s1, s2')
| some (none, s1'), some (some a2, s2') := some (none, s1', s2)
| some (some a1, s1'), some (some a2, s2') := some (some (f a1 a2), s1', s2')
| _, _ := none
end) (s1, s2)
/-- Zip two weak sequences into a single sequence of pairs -/
def zip : wseq α → wseq β → wseq (α × β) := zip_with prod.mk
/-- Get the list of indexes of elements of `s` satisfying `p` -/
def find_indexes (p : α → Prop) [decidable_pred p] (s : wseq α) : wseq ℕ :=
(zip s (stream.nats : wseq ℕ)).filter_map
(λ ⟨a, n⟩, if p a then some n else none)
/-- Get the index of the first element of `s` satisfying `p` -/
def find_index (p : α → Prop) [decidable_pred p] (s : wseq α) : computation ℕ :=
(λ o, option.get_or_else o 0) <$> head (find_indexes p s)
/-- Get the index of the first occurrence of `a` in `s` -/
def index_of [decidable_eq α] (a : α) : wseq α → computation ℕ := find_index (eq a)
/-- Get the indexes of occurrences of `a` in `s` -/
def indexes_of [decidable_eq α] (a : α) : wseq α → wseq ℕ := find_indexes (eq a)
/-- `union s1 s2` is a weak sequence which interleaves `s1` and `s2` in
some order (nondeterministically). -/
def union (s1 s2 : wseq α) : wseq α :=
@seq.corec (option α) (wseq α × wseq α) (λ⟨s1, s2⟩,
match seq.destruct s1, seq.destruct s2 with
| none, none := none
| some (a1, s1'), none := some (a1, s1', nil)
| none, some (a2, s2') := some (a2, nil, s2')
| some (none, s1'), some (none, s2') := some (none, s1', s2')
| some (some a1, s1'), some (none, s2') := some (some a1, s1', s2')
| some (none, s1'), some (some a2, s2') := some (some a2, s1', s2')
| some (some a1, s1'), some (some a2, s2') := some (some a1, cons a2 s1', s2')
end) (s1, s2)
/-- Returns `tt` if `s` is `nil` and `ff` if `s` has an element -/
def is_empty (s : wseq α) : computation bool :=
computation.map option.is_none $ head s
/-- Calculate one step of computation -/
def compute (s : wseq α) : wseq α :=
match seq.destruct s with
| some (none, s') := s'
| _ := s
end
/-- Get the first `n` elements of a weak sequence -/
def take (s : wseq α) (n : ℕ) : wseq α :=
@seq.corec (option α) (ℕ × wseq α) (λ⟨n, s⟩,
match n, seq.destruct s with
| 0, _ := none
| m+1, none := none
| m+1, some (none, s') := some (none, m+1, s')
| m+1, some (some a, s') := some (some a, m, s')
end) (n, s)
/-- Split the sequence at position `n` into a finite initial segment
and the weak sequence tail -/
def split_at (s : wseq α) (n : ℕ) : computation (list α × wseq α) :=
@computation.corec (list α × wseq α) (ℕ × list α × wseq α) (λ⟨n, l, s⟩,
match n, seq.destruct s with
| 0, _ := sum.inl (l.reverse, s)
| m+1, none := sum.inl (l.reverse, s)
| m+1, some (none, s') := sum.inr (n, l, s')
| m+1, some (some a, s') := sum.inr (m, a::l, s')
end) (n, [], s)
/-- Returns `tt` if any element of `s` satisfies `p` -/
def any (s : wseq α) (p : α → bool) : computation bool :=
computation.corec (λs : wseq α,
match seq.destruct s with
| none := sum.inl ff
| some (none, s') := sum.inr s'
| some (some a, s') := if p a then sum.inl tt else sum.inr s'
end) s
/-- Returns `tt` if every element of `s` satisfies `p` -/
def all (s : wseq α) (p : α → bool) : computation bool :=
computation.corec (λs : wseq α,
match seq.destruct s with
| none := sum.inl tt
| some (none, s') := sum.inr s'
| some (some a, s') := if p a then sum.inr s' else sum.inl ff
end) s
/-- Apply a function to the elements of the sequence to produce a sequence
of partial results. (There is no `scanr` because this would require
working from the end of the sequence, which may not exist.) -/
def scanl (f : α → β → α) (a : α) (s : wseq β) : wseq α :=
cons a $ @seq.corec (option α) (α × wseq β) (λ⟨a, s⟩,
match seq.destruct s with
| none := none
| some (none, s') := some (none, a, s')
| some (some b, s') := let a' := f a b in some (some a', a', s')
end) (a, s)
/-- Get the weak sequence of initial segments of the input sequence -/
def inits (s : wseq α) : wseq (list α) :=
cons [] $ @seq.corec (option (list α)) (dlist α × wseq α) (λ ⟨l, s⟩,
match seq.destruct s with
| none := none
| some (none, s') := some (none, l, s')
| some (some a, s') := let l' := l.concat a in
some (some l'.to_list, l', s')
end) (dlist.empty, s)
/-- Like take, but does not wait for a result. Calculates `n` steps of
computation and returns the sequence computed so far -/
def collect (s : wseq α) (n : ℕ) : list α :=
(seq.take n s).filter_map id
/-- Append two weak sequences. As with `seq.append`, this may not use
the second sequence if the first one takes forever to compute -/
def append : wseq α → wseq α → wseq α := seq.append
/-- Map a function over a weak sequence -/
def map (f : α → β) : wseq α → wseq β := seq.map (option.map f)
/-- Flatten a sequence of weak sequences. (Note that this allows
empty sequences, unlike `seq.join`.) -/
def join (S : wseq (wseq α)) : wseq α :=
seq.join ((λo : option (wseq α), match o with
| none := seq1.ret none
| some s := (none, s)
end) <$> S)
/-- Monadic bind operator for weak sequences -/
def bind (s : wseq α) (f : α → wseq β) : wseq β :=
join (map f s)
@[simp] def lift_rel_o (R : α → β → Prop) (C : wseq α → wseq β → Prop) :
option (α × wseq α) → option (β × wseq β) → Prop
| none none := true
| (some (a, s)) (some (b, t)) := R a b ∧ C s t
| _ _ := false
theorem lift_rel_o.imp {R S : α → β → Prop} {C D : wseq α → wseq β → Prop}
(H1 : ∀ a b, R a b → S a b) (H2 : ∀ s t, C s t → D s t) :
∀ {o p}, lift_rel_o R C o p → lift_rel_o S D o p
| none none h := trivial
| (some (a, s)) (some (b, t)) h := and.imp (H1 _ _) (H2 _ _) h
| none (some _) h := false.elim h
| (some (_, _)) none h := false.elim h
theorem lift_rel_o.imp_right (R : α → β → Prop) {C D : wseq α → wseq β → Prop}
(H : ∀ s t, C s t → D s t) {o p} : lift_rel_o R C o p → lift_rel_o R D o p :=
lift_rel_o.imp (λ _ _, id) H
@[simp] def bisim_o (R : wseq α → wseq α → Prop) :
option (α × wseq α) → option (α × wseq α) → Prop := lift_rel_o (=) R
theorem bisim_o.imp {R S : wseq α → wseq α → Prop} (H : ∀ s t, R s t → S s t) {o p} :
bisim_o R o p → bisim_o S o p :=
lift_rel_o.imp_right _ H
/-- Two weak sequences are `lift_rel R` related if they are either both empty,
or they are both nonempty and the heads are `R` related and the tails are
`lift_rel R` related. (This is a coinductive definition.) -/
def lift_rel (R : α → β → Prop) (s : wseq α) (t : wseq β) : Prop :=
∃ C : wseq α → wseq β → Prop, C s t ∧
∀ {s t}, C s t → computation.lift_rel (lift_rel_o R C) (destruct s) (destruct t)
/-- If two sequences are equivalent, then they have the same values and
the same computational behavior (i.e. if one loops forever then so does
the other), although they may differ in the number of `think`s needed to
arrive at the answer. -/
def equiv : wseq α → wseq α → Prop := lift_rel (=)
theorem lift_rel_destruct {R : α → β → Prop} {s : wseq α} {t : wseq β} :
lift_rel R s t →
computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t)
| ⟨R, h1, h2⟩ :=
by refine computation.lift_rel.imp _ _ _ (h2 h1);
apply lift_rel_o.imp_right; exact λ s' t' h', ⟨R, h', @h2⟩
theorem lift_rel_destruct_iff {R : α → β → Prop} {s : wseq α} {t : wseq β} :
lift_rel R s t ↔
computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t) :=
⟨lift_rel_destruct, λ h, ⟨λ s t, lift_rel R s t ∨
computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t),
or.inr h, λ s t h, begin
have h : computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t),
{ cases h with h h, exact lift_rel_destruct h, assumption },
apply computation.lift_rel.imp _ _ _ h,
intros a b, apply lift_rel_o.imp_right,
intros s t, apply or.inl
end⟩⟩
infix ~ := equiv
theorem destruct_congr {s t : wseq α} :
s ~ t → computation.lift_rel (bisim_o (~)) (destruct s) (destruct t) :=
lift_rel_destruct
theorem destruct_congr_iff {s t : wseq α} :
s ~ t ↔ computation.lift_rel (bisim_o (~)) (destruct s) (destruct t) :=
lift_rel_destruct_iff
theorem lift_rel.refl (R : α → α → Prop) (H : reflexive R) : reflexive (lift_rel R) :=
λ s, begin
refine ⟨(=), rfl, λ s t (h : s = t), _⟩,
rw ←h, apply computation.lift_rel.refl,
intro a, cases a with a, simp, cases a; simp, apply H
end
theorem lift_rel_o.swap (R : α → β → Prop) (C) :
function.swap (lift_rel_o R C) = lift_rel_o (function.swap R) (function.swap C) :=
by funext x y; cases x with x; [skip, cases x]; { cases y with y; [skip, cases y]; refl }
theorem lift_rel.swap_lem {R : α → β → Prop} {s1 s2} (h : lift_rel R s1 s2) :
lift_rel (function.swap R) s2 s1 :=
begin
refine ⟨function.swap (lift_rel R), h, λ s t (h : lift_rel R t s), _⟩,
rw [←lift_rel_o.swap, computation.lift_rel.swap],
apply lift_rel_destruct h
end
theorem lift_rel.swap (R : α → β → Prop) :
function.swap (lift_rel R) = lift_rel (function.swap R) :=
funext $ λ x, funext $ λ y, propext ⟨lift_rel.swap_lem, lift_rel.swap_lem⟩
theorem lift_rel.symm (R : α → α → Prop) (H : symmetric R) : symmetric (lift_rel R) :=
λ s1 s2 (h : function.swap (lift_rel R) s2 s1),
by rwa [lift_rel.swap, show function.swap R = R, from
funext $ λ a, funext $ λ b, propext $ by constructor; apply H] at h
theorem lift_rel.trans (R : α → α → Prop) (H : transitive R) : transitive (lift_rel R) :=
λ s t u h1 h2, begin
refine ⟨λ s u, ∃ t, lift_rel R s t ∧ lift_rel R t u, ⟨t, h1, h2⟩, λ s u h, _⟩,
rcases h with ⟨t, h1, h2⟩,
have h1 := lift_rel_destruct h1,
have h2 := lift_rel_destruct h2,
refine computation.lift_rel_def.2
⟨(computation.terminates_of_lift_rel h1).trans
(computation.terminates_of_lift_rel h2), λ a c ha hc, _⟩,
rcases h1.left ha with ⟨b, hb, t1⟩,
have t2 := computation.rel_of_lift_rel h2 hb hc,
cases a with a; cases c with c,
{ trivial },
{ cases b, {cases t2}, {cases t1} },
{ cases a, cases b with b, {cases t1}, {cases b, cases t2} },
{ cases a with a s, cases b with b, {cases t1},
cases b with b t, cases c with c u,
cases t1 with ab st, cases t2 with bc tu,
exact ⟨H ab bc, t, st, tu⟩ }
end
theorem lift_rel.equiv (R : α → α → Prop) : equivalence R → equivalence (lift_rel R)
| ⟨refl, symm, trans⟩ :=
⟨lift_rel.refl R refl, lift_rel.symm R symm, lift_rel.trans R trans⟩
@[refl] theorem equiv.refl : ∀ (s : wseq α), s ~ s :=
lift_rel.refl (=) eq.refl
@[symm] theorem equiv.symm : ∀ {s t : wseq α}, s ~ t → t ~ s :=
lift_rel.symm (=) (@eq.symm _)
@[trans] theorem equiv.trans : ∀ {s t u : wseq α}, s ~ t → t ~ u → s ~ u :=
lift_rel.trans (=) (@eq.trans _)
theorem equiv.equivalence : equivalence (@equiv α) :=
⟨@equiv.refl _, @equiv.symm _, @equiv.trans _⟩
open computation
local notation `return` := computation.return
@[simp] theorem destruct_nil : destruct (nil : wseq α) = return none :=
computation.destruct_eq_ret rfl
@[simp] theorem destruct_cons (a : α) (s) : destruct (cons a s) = return (some (a, s)) :=
computation.destruct_eq_ret $ by simp [destruct, cons, computation.rmap]
@[simp] theorem destruct_think (s : wseq α) : destruct (think s) = (destruct s).think :=
computation.destruct_eq_think $ by simp [destruct, think, computation.rmap]
@[simp] theorem seq_destruct_nil : seq.destruct (nil : wseq α) = none :=
seq.destruct_nil
@[simp] theorem seq_destruct_cons (a : α) (s) : seq.destruct (cons a s) = some (some a, s) :=
seq.destruct_cons _ _
@[simp] theorem seq_destruct_think (s : wseq α) : seq.destruct (think s) = some (none, s) :=
seq.destruct_cons _ _
@[simp] theorem head_nil : head (nil : wseq α) = return none := by simp [head]; refl
@[simp] theorem head_cons (a : α) (s) : head (cons a s) = return (some a) := by simp [head]; refl
@[simp] theorem head_think (s : wseq α) : head (think s) = (head s).think := by simp [head]; refl
@[simp] theorem flatten_ret (s : wseq α) : flatten (return s) = s :=
begin
refine seq.eq_of_bisim (λs1 s2, flatten (return s2) = s1) _ rfl,
intros s' s h, rw ←h, simp [flatten],
cases seq.destruct s, { simp },
{ cases val with o s', simp }
end
@[simp] theorem flatten_think (c : computation (wseq α)) : flatten c.think = think (flatten c) :=
seq.destruct_eq_cons $ by simp [flatten, think]
@[simp]
theorem destruct_flatten (c : computation (wseq α)) : destruct (flatten c) = c >>= destruct :=
begin
refine computation.eq_of_bisim (λc1 c2, c1 = c2 ∨
∃ c, c1 = destruct (flatten c) ∧ c2 = computation.bind c destruct) _ (or.inr ⟨c, rfl, rfl⟩),
intros c1 c2 h, exact match c1, c2, h with
| _, _, (or.inl $ eq.refl c) := by cases c.destruct; simp
| _, _, (or.inr ⟨c, rfl, rfl⟩) := begin
apply c.cases_on (λa, _) (λc', _); repeat {simp},
{ cases (destruct a).destruct; simp },
{ exact or.inr ⟨c', rfl, rfl⟩ }
end end
end
theorem head_terminates_iff (s : wseq α) : terminates (head s) ↔ terminates (destruct s) :=
terminates_map_iff _ (destruct s)
@[simp] theorem tail_nil : tail (nil : wseq α) = nil := by simp [tail]
@[simp] theorem tail_cons (a : α) (s) : tail (cons a s) = s := by simp [tail]
@[simp] theorem tail_think (s : wseq α) : tail (think s) = (tail s).think := by simp [tail]
@[simp] theorem dropn_nil (n) :
drop (nil : wseq α) n = nil := by induction n; simp [*, drop]
@[simp] theorem dropn_cons (a : α) (s) (n) :
drop (cons a s) (n+1) = drop s n := by induction n; simp [*, drop]
@[simp] theorem dropn_think (s : wseq α) (n) :
drop (think s) n = (drop s n).think := by induction n; simp [*, drop]
theorem dropn_add (s : wseq α) (m) : ∀ n, drop s (m + n) = drop (drop s m) n
| 0 := rfl
| (n+1) := congr_arg tail (dropn_add n)
theorem dropn_tail (s : wseq α) (n) : drop (tail s) n = drop s (n + 1) :=
by rw add_comm; symmetry; apply dropn_add
theorem nth_add (s : wseq α) (m n) : nth s (m + n) = nth (drop s m) n :=
congr_arg head (dropn_add _ _ _)
theorem nth_tail (s : wseq α) (n) : nth (tail s) n = nth s (n + 1) :=
congr_arg head (dropn_tail _ _)
@[simp] theorem join_nil : join nil = (nil : wseq α) := seq.join_nil
@[simp] theorem join_think (S : wseq (wseq α)) :
join (think S) = think (join S) :=
by { simp [think, join], unfold functor.map, simp [join, seq1.ret] }
@[simp] theorem join_cons (s : wseq α) (S) :
join (cons s S) = think (append s (join S)) :=
by { simp [think, join], unfold functor.map, simp [join, cons, append] }
@[simp] theorem nil_append (s : wseq α) : append nil s = s := seq.nil_append _
@[simp] theorem cons_append (a : α) (s t) :
append (cons a s) t = cons a (append s t) := seq.cons_append _ _ _
@[simp] theorem think_append (s t : wseq α) :
append (think s) t = think (append s t) := seq.cons_append _ _ _
@[simp] theorem append_nil (s : wseq α) : append s nil = s := seq.append_nil _
@[simp] theorem append_assoc (s t u : wseq α) :
append (append s t) u = append s (append t u) := seq.append_assoc _ _ _
@[simp] def tail.aux : option (α × wseq α) → computation (option (α × wseq α))
| none := return none
| (some (a, s)) := destruct s
theorem destruct_tail (s : wseq α) :
destruct (tail s) = destruct s >>= tail.aux :=
begin
dsimp [tail], simp, rw [← bind_pure_comp_eq_map, is_lawful_monad.bind_assoc],
apply congr_arg, ext (_|⟨a, s⟩);
apply (@pure_bind computation _ _ _ _ _ _).trans _; simp
end
@[simp] def drop.aux : ℕ → option (α × wseq α) → computation (option (α × wseq α))
| 0 := return
| (n+1) := λ a, tail.aux a >>= drop.aux n
theorem drop.aux_none : ∀ n, @drop.aux α n none = return none
| 0 := rfl
| (n+1) := show computation.bind (return none) (drop.aux n) = return none,
by rw [ret_bind, drop.aux_none]
theorem destruct_dropn :
∀ (s : wseq α) n, destruct (drop s n) = destruct s >>= drop.aux n
| s 0 := (bind_ret' _).symm
| s (n+1) := by rw [← dropn_tail, destruct_dropn _ n,
destruct_tail, is_lawful_monad.bind_assoc]; refl
theorem head_terminates_of_head_tail_terminates (s : wseq α) [T : terminates (head (tail s))] :
terminates (head s) :=
(head_terminates_iff _).2 $ begin
cases (head_terminates_iff _).1 T with a h,
simp [tail] at h,
rcases exists_of_mem_bind h with ⟨s', h1, h2⟩,
unfold functor.map at h1,
exact let ⟨t, h3, h4⟩ := exists_of_mem_map h1 in terminates_of_mem h3
end
theorem destruct_some_of_destruct_tail_some {s : wseq α} {a}
(h : some a ∈ destruct (tail s)) : ∃ a', some a' ∈ destruct s :=
begin
unfold tail functor.map at h, simp at h,
rcases exists_of_mem_bind h with ⟨t, tm, td⟩, clear h,
rcases exists_of_mem_map tm with ⟨t', ht', ht2⟩, clear tm,
cases t' with t'; rw ←ht2 at td; simp at td,
{ have := mem_unique td (ret_mem _), contradiction },
{ exact ⟨_, ht'⟩ }
end
theorem head_some_of_head_tail_some {s : wseq α} {a}
(h : some a ∈ head (tail s)) : ∃ a', some a' ∈ head s :=
begin
unfold head at h,
rcases exists_of_mem_map h with ⟨o, md, e⟩, clear h,
cases o with o; injection e with h', clear e h',
cases destruct_some_of_destruct_tail_some md with a am,
exact ⟨_, mem_map ((<$>) (@prod.fst α (wseq α))) am⟩
end
theorem head_some_of_nth_some {s : wseq α} {a n}
(h : some a ∈ nth s n) : ∃ a', some a' ∈ head s :=
begin
revert a, induction n with n IH; intros,
exacts [⟨_, h⟩, let ⟨a', h'⟩ := head_some_of_head_tail_some h in IH h']
end
instance productive_tail (s : wseq α) [productive s] : productive (tail s) :=
λ n, by rw [nth_tail]; apply_instance
instance productive_dropn (s : wseq α) [productive s] (n) : productive (drop s n) :=
λ m, by rw [←nth_add]; apply_instance
/-- Given a productive weak sequence, we can collapse all the `think`s to
produce a sequence. -/
def to_seq (s : wseq α) [productive s] : seq α :=
⟨λ n, (nth s n).get, λn h,
begin
cases e : computation.get (nth s (n + 1)), {assumption},
have := mem_of_get_eq _ e,
simp [nth] at this h, cases head_some_of_head_tail_some this with a' h',
have := mem_unique h' (@mem_of_get_eq _ _ _ _ h),
contradiction
end⟩
theorem nth_terminates_le {s : wseq α} {m n} (h : m ≤ n) :
terminates (nth s n) → terminates (nth s m) :=
by induction h with m' h IH; [exact id,
exact λ T, IH (@head_terminates_of_head_tail_terminates _ _ T)]
theorem head_terminates_of_nth_terminates {s : wseq α} {n} :
terminates (nth s n) → terminates (head s) :=
nth_terminates_le (nat.zero_le n)
theorem destruct_terminates_of_nth_terminates {s : wseq α} {n} (T : terminates (nth s n)) :
terminates (destruct s) :=
(head_terminates_iff _).1 $ head_terminates_of_nth_terminates T
theorem mem_rec_on {C : wseq α → Prop} {a s} (M : a ∈ s)
(h1 : ∀ b s', (a = b ∨ C s') → C (cons b s'))
(h2 : ∀ s, C s → C (think s)) : C s :=
begin
apply seq.mem_rec_on M,
intros o s' h, cases o with b,
{ apply h2, cases h, {contradiction}, {assumption} },
{ apply h1, apply or.imp_left _ h, intro h, injection h }
end
@[simp] theorem mem_think (s : wseq α) (a) : a ∈ think s ↔ a ∈ s :=
begin
cases s with f al,
change some (some a) ∈ some none :: f ↔ some (some a) ∈ f,
constructor; intro h,
{ apply (stream.eq_or_mem_of_mem_cons h).resolve_left,
intro, injections },
{ apply stream.mem_cons_of_mem _ h }
end
theorem eq_or_mem_iff_mem {s : wseq α} {a a' s'} :
some (a', s') ∈ destruct s → (a ∈ s ↔ a = a' ∨ a ∈ s') :=
begin
generalize e : destruct s = c, intro h,
revert s, apply computation.mem_rec_on h _ (λ c IH, _); intro s;
apply s.cases_on _ (λ x s, _) (λ s, _); intros m;
have := congr_arg computation.destruct m; simp at this;
cases this with i1 i2,
{ rw [i1, i2],
cases s' with f al,
unfold cons has_mem.mem wseq.mem seq.mem seq.cons, simp,
have h_a_eq_a' : a = a' ↔ some (some a) = some (some a'), {simp},
rw [h_a_eq_a'],
refine ⟨stream.eq_or_mem_of_mem_cons, λo, _⟩,
{ cases o with e m,
{ rw e, apply stream.mem_cons },
{ exact stream.mem_cons_of_mem _ m } } },
{ simp, exact IH this }
end
@[simp] theorem mem_cons_iff (s : wseq α) (b) {a} : a ∈ cons b s ↔ a = b ∨ a ∈ s :=
eq_or_mem_iff_mem $ by simp [ret_mem]
theorem mem_cons_of_mem {s : wseq α} (b) {a} (h : a ∈ s) : a ∈ cons b s :=
(mem_cons_iff _ _).2 (or.inr h)
theorem mem_cons (s : wseq α) (a) : a ∈ cons a s :=
(mem_cons_iff _ _).2 (or.inl rfl)
theorem mem_of_mem_tail {s : wseq α} {a} : a ∈ tail s → a ∈ s :=
begin
intro h, have := h, cases h with n e, revert s, simp [stream.nth],
induction n with n IH; intro s; apply s.cases_on _ (λx s, _) (λ s, _);
repeat{simp}; intros m e; injections,
{ exact or.inr m },
{ exact or.inr m },
{ apply IH m, rw e, cases tail s, refl }
end
theorem mem_of_mem_dropn {s : wseq α} {a} : ∀ {n}, a ∈ drop s n → a ∈ s
| 0 h := h
| (n+1) h := @mem_of_mem_dropn n (mem_of_mem_tail h)
theorem nth_mem {s : wseq α} {a n} : some a ∈ nth s n → a ∈ s :=
begin
revert s, induction n with n IH; intros s h,
{ rcases exists_of_mem_map h with ⟨o, h1, h2⟩,
cases o with o; injection h2 with h',
cases o with a' s',
exact (eq_or_mem_iff_mem h1).2 (or.inl h'.symm) },
{ have := @IH (tail s), rw nth_tail at this,
exact mem_of_mem_tail (this h) }
end
theorem exists_nth_of_mem {s : wseq α} {a} (h : a ∈ s) : ∃ n, some a ∈ nth s n :=
begin
apply mem_rec_on h,
{ intros a' s' h, cases h with h h,
{ existsi 0, simp [nth], rw h, apply ret_mem },
{ cases h with n h, existsi n+1,
simp [nth], exact h } },
{ intros s' h, cases h with n h,
existsi n, simp [nth], apply think_mem h }
end
theorem exists_dropn_of_mem {s : wseq α} {a} (h : a ∈ s) :
∃ n s', some (a, s') ∈ destruct (drop s n) :=
let ⟨n, h⟩ := exists_nth_of_mem h in ⟨n, begin
cases (head_terminates_iff _).1 ⟨_, h⟩ with o om,
have := mem_unique (mem_map _ om) h,
cases o with o; injection this with i,
cases o with a' s', dsimp at i,
rw i at om, exact ⟨_, om⟩
end⟩
theorem lift_rel_dropn_destruct {R : α → β → Prop} {s t} (H : lift_rel R s t) :
∀ n, computation.lift_rel (lift_rel_o R (lift_rel R))
(destruct (drop s n)) (destruct (drop t n))
| 0 := lift_rel_destruct H
| (n+1) := begin
simp [destruct_tail],
apply lift_rel_bind,
apply lift_rel_dropn_destruct n,
exact λ a b o, match a, b, o with
| none, none, _ := by simp
| some (a, s), some (b, t), ⟨h1, h2⟩ := by simp [tail.aux]; apply lift_rel_destruct h2
end
end
theorem exists_of_lift_rel_left {R : α → β → Prop} {s t}
(H : lift_rel R s t) {a} (h : a ∈ s) : ∃ {b}, b ∈ t ∧ R a b :=
let ⟨n, h⟩ := exists_nth_of_mem h,
⟨some (._, s'), sd, rfl⟩ := exists_of_mem_map h,
⟨some (b, t'), td, ⟨ab, _⟩⟩ := (lift_rel_dropn_destruct H n).left sd in
⟨b, nth_mem (mem_map ((<$>) prod.fst.{v v}) td), ab⟩
theorem exists_of_lift_rel_right {R : α → β → Prop} {s t}
(H : lift_rel R s t) {b} (h : b ∈ t) : ∃ {a}, a ∈ s ∧ R a b :=
by rw ←lift_rel.swap at H; exact exists_of_lift_rel_left H h
theorem head_terminates_of_mem {s : wseq α} {a} (h : a ∈ s) : terminates (head s) :=
let ⟨n, h⟩ := exists_nth_of_mem h in head_terminates_of_nth_terminates ⟨_, h⟩
theorem of_mem_append {s₁ s₂ : wseq α} {a : α} : a ∈ append s₁ s₂ → a ∈ s₁ ∨ a ∈ s₂ :=
seq.of_mem_append
theorem mem_append_left {s₁ s₂ : wseq α} {a : α} : a ∈ s₁ → a ∈ append s₁ s₂ :=
seq.mem_append_left
theorem exists_of_mem_map {f} {b : β} : ∀ {s : wseq α}, b ∈ map f s → ∃ a, a ∈ s ∧ f a = b
| ⟨g, al⟩ h := let ⟨o, om, oe⟩ := seq.exists_of_mem_map h in
by cases o with a; injection oe with h'; exact ⟨a, om, h'⟩
@[simp] theorem lift_rel_nil (R : α → β → Prop) : lift_rel R nil nil :=
by rw [lift_rel_destruct_iff]; simp
@[simp] theorem lift_rel_cons (R : α → β → Prop) (a b s t) :
lift_rel R (cons a s) (cons b t) ↔ R a b ∧ lift_rel R s t :=
by rw [lift_rel_destruct_iff]; simp
@[simp] theorem lift_rel_think_left (R : α → β → Prop) (s t) :
lift_rel R (think s) t ↔ lift_rel R s t :=
by rw [lift_rel_destruct_iff, lift_rel_destruct_iff]; simp
@[simp] theorem lift_rel_think_right (R : α → β → Prop) (s t) :
lift_rel R s (think t) ↔ lift_rel R s t :=
by rw [lift_rel_destruct_iff, lift_rel_destruct_iff]; simp
theorem cons_congr {s t : wseq α} (a : α) (h : s ~ t) : cons a s ~ cons a t :=
by unfold equiv; simp; exact h
theorem think_equiv (s : wseq α) : think s ~ s :=
by unfold equiv; simp; apply equiv.refl
theorem think_congr {s t : wseq α} (a : α) (h : s ~ t) : think s ~ think t :=
by unfold equiv; simp; exact h
theorem head_congr : ∀ {s t : wseq α}, s ~ t → head s ~ head t :=
suffices ∀ {s t : wseq α}, s ~ t → ∀ {o}, o ∈ head s → o ∈ head t, from
λ s t h o, ⟨this h, this h.symm⟩,
begin
intros s t h o ho,
rcases @computation.exists_of_mem_map _ _ _ _ (destruct s) ho with ⟨ds, dsm, dse⟩,
rw ←dse,
cases destruct_congr h with l r,
rcases l dsm with ⟨dt, dtm, dst⟩,
cases ds with a; cases dt with b,
{ apply mem_map _ dtm },
{ cases b, cases dst },
{ cases a, cases dst },
{ cases a with a s', cases b with b t', rw dst.left,
exact @mem_map _ _ (@functor.map _ _ (α × wseq α) _ prod.fst)
_ (destruct t) dtm }
end
theorem flatten_equiv {c : computation (wseq α)} {s} (h : s ∈ c) : flatten c ~ s :=
begin
apply computation.mem_rec_on h, { simp },
{ intro s', apply equiv.trans, simp [think_equiv] }
end
theorem lift_rel_flatten {R : α → β → Prop} {c1 : computation (wseq α)} {c2 : computation (wseq β)}
(h : c1.lift_rel (lift_rel R) c2) : lift_rel R (flatten c1) (flatten c2) :=
let S := λ s t,
∃ c1 c2, s = flatten c1 ∧ t = flatten c2 ∧ computation.lift_rel (lift_rel R) c1 c2 in
⟨S, ⟨c1, c2, rfl, rfl, h⟩, λ s t h,
match s, t, h with ._, ._, ⟨c1, c2, rfl, rfl, h⟩ := begin
simp, apply lift_rel_bind _ _ h,
intros a b ab, apply computation.lift_rel.imp _ _ _ (lift_rel_destruct ab),
intros a b, apply lift_rel_o.imp_right,
intros s t h, refine ⟨return s, return t, _, _, _⟩; simp [h]
end end⟩
theorem flatten_congr {c1 c2 : computation (wseq α)} :
computation.lift_rel equiv c1 c2 → flatten c1 ~ flatten c2 := lift_rel_flatten
theorem tail_congr {s t : wseq α} (h : s ~ t) : tail s ~ tail t :=
begin
apply flatten_congr,
unfold functor.map, rw [←bind_ret, ←bind_ret],
apply lift_rel_bind _ _ (destruct_congr h),
intros a b h, simp,
cases a with a; cases b with b,
{ trivial },
{ cases h },
{ cases a, cases h },
{ cases a with a s', cases b with b t', exact h.right }
end
theorem dropn_congr {s t : wseq α} (h : s ~ t) (n) : drop s n ~ drop t n :=
by induction n; simp [*, tail_congr]
theorem nth_congr {s t : wseq α} (h : s ~ t) (n) : nth s n ~ nth t n :=
head_congr (dropn_congr h _)
theorem mem_congr {s t : wseq α} (h : s ~ t) (a) : a ∈ s ↔ a ∈ t :=
suffices ∀ {s t : wseq α}, s ~ t → a ∈ s → a ∈ t, from ⟨this h, this h.symm⟩,
λ s t h as, let ⟨n, hn⟩ := exists_nth_of_mem as in
nth_mem ((nth_congr h _ _).1 hn)
theorem productive_congr {s t : wseq α} (h : s ~ t) : productive s ↔ productive t :=
forall_congr $ λn, terminates_congr $ nth_congr h _
theorem equiv.ext {s t : wseq α} (h : ∀ n, nth s n ~ nth t n) : s ~ t :=
⟨λ s t, ∀ n, nth s n ~ nth t n, h, λs t h, begin
refine lift_rel_def.2 ⟨_, _⟩,
{ rw [←head_terminates_iff, ←head_terminates_iff],
exact terminates_congr (h 0) },
{ intros a b ma mb,
cases a with a; cases b with b,
{ trivial },
{ injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) },
{ injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) },
{ cases a with a s', cases b with b t',
injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) with ab,
refine ⟨ab, λ n, _⟩,
refine (nth_congr (flatten_equiv (mem_map _ ma)) n).symm.trans
((_ : nth (tail s) n ~ nth (tail t) n).trans
(nth_congr (flatten_equiv (mem_map _ mb)) n)),
rw [nth_tail, nth_tail], apply h } }
end⟩
theorem length_eq_map (s : wseq α) : length s = computation.map list.length (to_list s) :=
begin
refine eq_of_bisim
(λ c1 c2, ∃ (l : list α) (s : wseq α),
c1 = corec length._match_2 (l.length, s) ∧
c2 = computation.map list.length (corec to_list._match_2 (l, s)))
_ ⟨[], s, rfl, rfl⟩,
intros s1 s2 h, rcases h with ⟨l, s, h⟩, rw [h.left, h.right],
apply s.cases_on _ (λ a s, _) (λ s, _);
repeat {simp [to_list, nil, cons, think, length]},
{ refine ⟨a::l, s, _, _⟩; simp },
{ refine ⟨l, s, _, _⟩; simp }
end
@[simp] theorem of_list_nil : of_list [] = (nil : wseq α) := rfl
@[simp] theorem of_list_cons (a : α) (l) :
of_list (a :: l) = cons a (of_list l) :=
show seq.map some (seq.of_list (a :: l)) =
seq.cons (some a) (seq.map some (seq.of_list l)), by simp
@[simp] theorem to_list'_nil (l : list α) :
corec to_list._match_2 (l, nil) = return l.reverse :=
destruct_eq_ret rfl
@[simp] theorem to_list'_cons (l : list α) (s : wseq α) (a : α) :
corec to_list._match_2 (l, cons a s) =
(corec to_list._match_2 (a::l, s)).think :=
destruct_eq_think $ by simp [to_list, cons]
@[simp] theorem to_list'_think (l : list α) (s : wseq α) :
corec to_list._match_2 (l, think s) =
(corec to_list._match_2 (l, s)).think :=
destruct_eq_think $ by simp [to_list, think]
theorem to_list'_map (l : list α) (s : wseq α) :
corec to_list._match_2 (l, s) =
((++) l.reverse) <$> to_list s :=
begin
refine eq_of_bisim
(λ c1 c2, ∃ (l' : list α) (s : wseq α),
c1 = corec to_list._match_2 (l' ++ l, s) ∧
c2 = computation.map ((++) l.reverse) (corec to_list._match_2 (l', s)))
_ ⟨[], s, rfl, rfl⟩,
intros s1 s2 h, rcases h with ⟨l', s, h⟩, rw [h.left, h.right],
apply s.cases_on _ (λ a s, _) (λ s, _);
repeat {simp [to_list, nil, cons, think, length]},
{ refine ⟨a::l', s, _, _⟩; simp },
{ refine ⟨l', s, _, _⟩; simp }
end
@[simp] theorem to_list_cons (a : α) (s) :
to_list (cons a s) = (list.cons a <$> to_list s).think :=
destruct_eq_think $ by unfold to_list; simp; rw to_list'_map; simp; refl
@[simp] theorem to_list_nil : to_list (nil : wseq α) = return [] :=
destruct_eq_ret rfl
theorem to_list_of_list (l : list α) : l ∈ to_list (of_list l) :=
by induction l with a l IH; simp [ret_mem]; exact think_mem (mem_map _ IH)
@[simp] theorem destruct_of_seq (s : seq α) :
destruct (of_seq s) = return (s.head.map $ λ a, (a, of_seq s.tail)) :=
destruct_eq_ret $ begin
simp [of_seq, head, destruct, seq.destruct, seq.head],
rw [show seq.nth (some <$> s) 0 = some <$> seq.nth s 0, by apply seq.map_nth],
cases seq.nth s 0 with a, { refl },
unfold functor.map,
simp [destruct]
end
@[simp] theorem head_of_seq (s : seq α) : head (of_seq s) = return s.head :=
by simp [head]; cases seq.head s; refl
@[simp] theorem tail_of_seq (s : seq α) : tail (of_seq s) = of_seq s.tail :=
begin
simp [tail], apply s.cases_on _ (λ x s, _); simp [of_seq], {refl},
rw [seq.head_cons, seq.tail_cons], refl
end
@[simp] theorem dropn_of_seq (s : seq α) : ∀ n, drop (of_seq s) n = of_seq (s.drop n)
| 0 := rfl
| (n+1) := by dsimp [drop]; rw [dropn_of_seq, tail_of_seq]
theorem nth_of_seq (s : seq α) (n) : nth (of_seq s) n = return (seq.nth s n) :=
by dsimp [nth]; rw [dropn_of_seq, head_of_seq, seq.head_dropn]
instance productive_of_seq (s : seq α) : productive (of_seq s) :=
λ n, by rw nth_of_seq; apply_instance
theorem to_seq_of_seq (s : seq α) : to_seq (of_seq s) = s :=
begin
apply subtype.eq, funext n,
dsimp [to_seq], apply get_eq_of_mem,
rw nth_of_seq, apply ret_mem
end
/-- The monadic `return a` is a singleton list containing `a`. -/
def ret (a : α) : wseq α := of_list [a]
@[simp] theorem map_nil (f : α → β) : map f nil = nil := rfl
@[simp] theorem map_cons (f : α → β) (a s) :
map f (cons a s) = cons (f a) (map f s) := seq.map_cons _ _ _
@[simp] theorem map_think (f : α → β) (s) :
map f (think s) = think (map f s) := seq.map_cons _ _ _
@[simp] theorem map_id (s : wseq α) : map id s = s := by simp [map]
@[simp] theorem map_ret (f : α → β) (a) : map f (ret a) = ret (f a) := by simp [ret]
@[simp] theorem map_append (f : α → β) (s t) : map f (append s t) = append (map f s) (map f t) :=
seq.map_append _ _ _
theorem map_comp (f : α → β) (g : β → γ) (s : wseq α) :
map (g ∘ f) s = map g (map f s) :=
begin
dsimp [map], rw ←seq.map_comp,
apply congr_fun, apply congr_arg,
ext ⟨⟩; refl
end
theorem mem_map (f : α → β) {a : α} {s : wseq α} : a ∈ s → f a ∈ map f s :=
seq.mem_map (option.map f)
-- The converse is not true without additional assumptions
theorem exists_of_mem_join {a : α} : ∀ {S : wseq (wseq α)}, a ∈ join S → ∃ s, s ∈ S ∧ a ∈ s :=
suffices ∀ ss : wseq α, a ∈ ss → ∀ s S, append s (join S) = ss →
a ∈ append s (join S) → a ∈ s ∨ ∃ s, s ∈ S ∧ a ∈ s, from λ S h,
(this _ h nil S (by simp) (by simp [h])).resolve_left (not_mem_nil _),
begin
intros ss h, apply mem_rec_on h (λ b ss o, _) (λ ss IH, _); intros s S,
{ refine s.cases_on (S.cases_on _ (λ s S, _) (λ S, _)) (λ b' s, _) (λ s, _);
intros ej m; simp at ej;
have := congr_arg seq.destruct ej; simp at this;
try {cases this}; try {contradiction},
substs b' ss,
simp at m ⊢,
cases o with e IH, { simp [e] },
cases m with e m, { simp [e] },
exact or.imp_left or.inr (IH _ _ rfl m) },
{ refine s.cases_on (S.cases_on _ (λ s S, _) (λ S, _)) (λ b' s, _) (λ s, _);
intros ej m; simp at ej;
have := congr_arg seq.destruct ej; simp at this;
try { try {have := this.1}, contradiction }; subst ss,
{ apply or.inr, simp at m ⊢,
cases IH s S rfl m with as ex,
{ exact ⟨s, or.inl rfl, as⟩ },
{ rcases ex with ⟨s', sS, as⟩,
exact ⟨s', or.inr sS, as⟩ } },
{ apply or.inr, simp at m,
rcases (IH nil S (by simp) (by simp [m])).resolve_left (not_mem_nil _) with ⟨s, sS, as⟩,
exact ⟨s, by simp [sS], as⟩ },
{ simp at m IH ⊢, apply IH _ _ rfl m } }
end
theorem exists_of_mem_bind {s : wseq α} {f : α → wseq β} {b}
(h : b ∈ bind s f) : ∃ a ∈ s, b ∈ f a :=
let ⟨t, tm, bt⟩ := exists_of_mem_join h,
⟨a, as, e⟩ := exists_of_mem_map tm in ⟨a, as, by rwa e⟩
theorem destruct_map (f : α → β) (s : wseq α) :
destruct (map f s) = computation.map (option.map (prod.map f (map f))) (destruct s) :=
begin
apply eq_of_bisim (λ c1 c2, ∃ s, c1 = destruct (map f s) ∧
c2 = computation.map (option.map (prod.map f (map f))) (destruct s)),
{ intros c1 c2 h, cases h with s h, rw [h.left, h.right],
apply s.cases_on _ (λ a s, _) (λ s, _); simp,
exact ⟨s, rfl, rfl⟩ },
{ exact ⟨s, rfl, rfl⟩ }
end
theorem lift_rel_map {δ} (R : α → β → Prop) (S : γ → δ → Prop)
{s1 : wseq α} {s2 : wseq β}
{f1 : α → γ} {f2 : β → δ}
(h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → S (f1 a) (f2 b))
: lift_rel S (map f1 s1) (map f2 s2) :=
⟨λ s1 s2, ∃ s t, s1 = map f1 s ∧ s2 = map f2 t ∧ lift_rel R s t,
⟨s1, s2, rfl, rfl, h1⟩,
λ s1 s2 h, match s1, s2, h with ._, ._, ⟨s, t, rfl, rfl, h⟩ := begin
simp [destruct_map], apply computation.lift_rel_map _ _ (lift_rel_destruct h),
intros o p h,
cases o with a; cases p with b; simp,
{ cases b; cases h },
{ cases a; cases h },
{ cases a with a s; cases b with b t, cases h with r h,
exact ⟨h2 r, s, rfl, t, rfl, h⟩ }
end end⟩
theorem map_congr (f : α → β) {s t : wseq α} (h : s ~ t) : map f s ~ map f t :=
lift_rel_map _ _ h (λ _ _, congr_arg _)
@[simp] def destruct_append.aux (t : wseq α) :
option (α × wseq α) → computation (option (α × wseq α))
| none := destruct t
| (some (a, s)) := return (some (a, append s t))
theorem destruct_append (s t : wseq α) :
destruct (append s t) = (destruct s).bind (destruct_append.aux t) :=
begin
apply eq_of_bisim (λ c1 c2, ∃ s t, c1 = destruct (append s t) ∧
c2 = (destruct s).bind (destruct_append.aux t)) _ ⟨s, t, rfl, rfl⟩,
intros c1 c2 h, rcases h with ⟨s, t, h⟩, rw [h.left, h.right],
apply s.cases_on _ (λ a s, _) (λ s, _); simp,
{ apply t.cases_on _ (λ b t, _) (λ t, _); simp,
{ refine ⟨nil, t, _, _⟩; simp } },
{ exact ⟨s, t, rfl, rfl⟩ }
end
@[simp] def destruct_join.aux : option (wseq α × wseq (wseq α)) → computation (option (α × wseq α))
| none := return none
| (some (s, S)) := (destruct (append s (join S))).think
theorem destruct_join (S : wseq (wseq α)) :
destruct (join S) = (destruct S).bind destruct_join.aux :=
begin
apply eq_of_bisim (λ c1 c2, c1 = c2 ∨ ∃ S, c1 = destruct (join S) ∧
c2 = (destruct S).bind destruct_join.aux) _ (or.inr ⟨S, rfl, rfl⟩),
intros c1 c2 h, exact match c1, c2, h with
| _, _, (or.inl $ eq.refl c) := by cases c.destruct; simp
| _, _, or.inr ⟨S, rfl, rfl⟩ := begin
apply S.cases_on _ (λ s S, _) (λ S, _); simp,
{ refine or.inr ⟨S, rfl, rfl⟩ }
end end
end
theorem lift_rel_append (R : α → β → Prop) {s1 s2 : wseq α} {t1 t2 : wseq β}
(h1 : lift_rel R s1 t1) (h2 : lift_rel R s2 t2) :
lift_rel R (append s1 s2) (append t1 t2) :=
⟨λ s t, lift_rel R s t ∨ ∃ s1 t1, s = append s1 s2 ∧ t = append t1 t2 ∧ lift_rel R s1 t1,
or.inr ⟨s1, t1, rfl, rfl, h1⟩,
λ s t h, match s, t, h with
| s, t, or.inl h := begin
apply computation.lift_rel.imp _ _ _ (lift_rel_destruct h),
intros a b, apply lift_rel_o.imp_right,
intros s t, apply or.inl
end
| ._, ._, or.inr ⟨s1, t1, rfl, rfl, h⟩ := begin
simp [destruct_append],
apply computation.lift_rel_bind _ _ (lift_rel_destruct h),
intros o p h,
cases o with a; cases p with b,
{ simp, apply computation.lift_rel.imp _ _ _ (lift_rel_destruct h2),
intros a b, apply lift_rel_o.imp_right,
intros s t, apply or.inl },
{ cases b; cases h },
{ cases a; cases h },
{ cases a with a s; cases b with b t, cases h with r h,
simp, exact ⟨r, or.inr ⟨s, rfl, t, rfl, h⟩⟩ }
end
end⟩
theorem lift_rel_join.lem (R : α → β → Prop) {S T} {U : wseq α → wseq β → Prop}
(ST : lift_rel (lift_rel R) S T) (HU : ∀ s1 s2, (∃ s t S T,
s1 = append s (join S) ∧ s2 = append t (join T) ∧
lift_rel R s t ∧ lift_rel (lift_rel R) S T) → U s1 s2) {a} (ma : a ∈ destruct (join S)) :
∃ {b}, b ∈ destruct (join T) ∧ lift_rel_o R U a b :=
begin
cases exists_results_of_mem ma with n h, clear ma, revert a S T,
apply nat.strong_induction_on n _,
intros n IH a S T ST ra, simp [destruct_join] at ra, exact
let ⟨o, m, k, rs1, rs2, en⟩ := of_results_bind ra,
⟨p, mT, rop⟩ := computation.exists_of_lift_rel_left (lift_rel_destruct ST) rs1.mem in
by exact match o, p, rop, rs1, rs2, mT with
| none, none, _, rs1, rs2, mT := by simp [destruct_join]; exact
⟨none, mem_bind mT (ret_mem _), by rw eq_of_ret_mem rs2.mem; trivial⟩
| some (s, S'), some (t, T'), ⟨st, ST'⟩, rs1, rs2, mT :=
by simp [destruct_append] at rs2; exact
let ⟨k1, rs3, ek⟩ := of_results_think rs2,
⟨o', m1, n1, rs4, rs5, ek1⟩ := of_results_bind rs3,
⟨p', mt, rop'⟩ := computation.exists_of_lift_rel_left (lift_rel_destruct st) rs4.mem in
by exact match o', p', rop', rs4, rs5, mt with
| none, none, _, rs4, rs5', mt :=
have n1 < n, begin
rw [en, ek, ek1],
apply lt_of_lt_of_le _ (nat.le_add_right _ _),
apply nat.lt_succ_of_le (nat.le_add_right _ _)
end,
let ⟨ob, mb, rob⟩ := IH _ this ST' rs5' in by refine ⟨ob, _, rob⟩;
{ simp [destruct_join], apply mem_bind mT, simp [destruct_append],
apply think_mem, apply mem_bind mt, exact mb }
| some (a, s'), some (b, t'), ⟨ab, st'⟩, rs4, rs5, mt := begin
simp at rs5,
refine ⟨some (b, append t' (join T')), _, _⟩,
{ simp [destruct_join], apply mem_bind mT, simp [destruct_append],
apply think_mem, apply mem_bind mt, apply ret_mem },
rw eq_of_ret_mem rs5.mem,
exact ⟨ab, HU _ _ ⟨s', t', S', T', rfl, rfl, st', ST'⟩⟩
end end
end
end
theorem lift_rel_join (R : α → β → Prop) {S : wseq (wseq α)} {T : wseq (wseq β)}
(h : lift_rel (lift_rel R) S T) : lift_rel R (join S) (join T) :=
⟨λ s1 s2, ∃ s t S T,
s1 = append s (join S) ∧ s2 = append t (join T) ∧
lift_rel R s t ∧ lift_rel (lift_rel R) S T,
⟨nil, nil, S, T, by simp, by simp, by simp, h⟩,
λs1 s2 ⟨s, t, S, T, h1, h2, st, ST⟩, begin
clear _fun_match _x,
rw [h1, h2], rw [destruct_append, destruct_append],
apply computation.lift_rel_bind _ _ (lift_rel_destruct st),
exact λ o p h, match o, p, h with
| some (a, s), some (b, t), ⟨h1, h2⟩ :=
by simp; exact ⟨h1, s, t, S, rfl, T, rfl, h2, ST⟩
| none, none, _ := begin
dsimp [destruct_append.aux, computation.lift_rel], constructor,
{ intro, apply lift_rel_join.lem _ ST (λ _ _, id) },
{ intros b mb,
rw [←lift_rel_o.swap], apply lift_rel_join.lem (function.swap R),
{ rw [←lift_rel.swap R, ←lift_rel.swap], apply ST },
{ rw [←lift_rel.swap R, ←lift_rel.swap (lift_rel R)],
exact λ s1 s2 ⟨s, t, S, T, h1, h2, st, ST⟩,
⟨t, s, T, S, h2, h1, st, ST⟩ },
{ exact mb } }
end end
end⟩
theorem join_congr {S T : wseq (wseq α)} (h : lift_rel equiv S T) : join S ~ join T :=
lift_rel_join _ h
theorem lift_rel_bind {δ} (R : α → β → Prop) (S : γ → δ → Prop)
{s1 : wseq α} {s2 : wseq β}
{f1 : α → wseq γ} {f2 : β → wseq δ}
(h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → lift_rel S (f1 a) (f2 b))
: lift_rel S (bind s1 f1) (bind s2 f2) :=
lift_rel_join _ (lift_rel_map _ _ h1 @h2)
theorem bind_congr {s1 s2 : wseq α} {f1 f2 : α → wseq β}
(h1 : s1 ~ s2) (h2 : ∀ a, f1 a ~ f2 a) : bind s1 f1 ~ bind s2 f2 :=
lift_rel_bind _ _ h1 (λ a b h, by rw h; apply h2)
@[simp] theorem join_ret (s : wseq α) : join (ret s) ~ s :=
by simp [ret]; apply think_equiv
@[simp] theorem join_map_ret (s : wseq α) : join (map ret s) ~ s :=
begin
refine ⟨λ s1 s2, join (map ret s2) = s1, rfl, _⟩,
intros s' s h, rw ←h,
apply lift_rel_rec
(λ c1 c2, ∃ s,
c1 = destruct (join (map ret s)) ∧ c2 = destruct s),
{ exact λ c1 c2 h, match c1, c2, h with
| ._, ._, ⟨s, rfl, rfl⟩ := begin
clear h _match,
apply s.cases_on _ (λ a s, _) (λ s, _); simp [ret],
{ refine ⟨_, ret_mem _, _⟩, simp },
{ exact ⟨s, rfl, rfl⟩ }
end end },
{ exact ⟨s, rfl, rfl⟩ }
end
@[simp] theorem join_append (S T : wseq (wseq α)) :
join (append S T) ~ append (join S) (join T) :=
begin
refine ⟨λ s1 s2, ∃ s S T,
s1 = append s (join (append S T)) ∧
s2 = append s (append (join S) (join T)), ⟨nil, S, T, by simp, by simp⟩, _⟩,
intros s1 s2 h,
apply lift_rel_rec (λ c1 c2, ∃ (s : wseq α) S T,
c1 = destruct (append s (join (append S T))) ∧
c2 = destruct (append s (append (join S) (join T)))) _ _ _
(let ⟨s, S, T, h1, h2⟩ := h in
⟨s, S, T, congr_arg destruct h1, congr_arg destruct h2⟩),
intros c1 c2 h,
exact match c1, c2, h with ._, ._, ⟨s, S, T, rfl, rfl⟩ := begin
clear _match h h,
apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp,
{ apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp,
{ apply wseq.cases_on T _ (λ s T, _) (λ T, _); simp,
{ refine ⟨s, nil, T, _, _⟩; simp },
{ refine ⟨nil, nil, T, _, _⟩; simp } },
{ exact ⟨s, S, T, rfl, rfl⟩ },
{ refine ⟨nil, S, T, _, _⟩; simp } },
{ exact ⟨s, S, T, rfl, rfl⟩ },
{ exact ⟨s, S, T, rfl, rfl⟩ }
end end
end
@[simp] theorem bind_ret (f : α → β) (s) : bind s (ret ∘ f) ~ map f s :=
begin
dsimp [bind], change (λx, ret (f x)) with (ret ∘ f),
rw [map_comp], apply join_map_ret
end
@[simp] theorem ret_bind (a : α) (f : α → wseq β) :
bind (ret a) f ~ f a := by simp [bind]
@[simp] theorem map_join (f : α → β) (S) :
map f (join S) = join (map (map f) S) :=
begin
apply seq.eq_of_bisim (λs1 s2,
∃ s S, s1 = append s (map f (join S)) ∧
s2 = append s (join (map (map f) S))),
{ intros s1 s2 h,
exact match s1, s2, h with ._, ._, ⟨s, S, rfl, rfl⟩ := begin
apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp,
{ apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp,
{ exact ⟨map f s, S, rfl, rfl⟩ },
{ refine ⟨nil, S, _, _⟩; simp } },
{ exact ⟨_, _, rfl, rfl⟩ },
{ exact ⟨_, _, rfl, rfl⟩ }
end end },
{ refine ⟨nil, S, _, _⟩; simp }
end
@[simp] theorem join_join (SS : wseq (wseq (wseq α))) :
join (join SS) ~ join (map join SS) :=
begin
refine ⟨λ s1 s2, ∃ s S SS,
s1 = append s (join (append S (join SS))) ∧
s2 = append s (append (join S) (join (map join SS))),
⟨nil, nil, SS, by simp, by simp⟩, _⟩,
intros s1 s2 h,
apply lift_rel_rec (λ c1 c2, ∃ s S SS,
c1 = destruct (append s (join (append S (join SS)))) ∧
c2 = destruct (append s (append (join S) (join (map join SS)))))
_ (destruct s1) (destruct s2)
(let ⟨s, S, SS, h1, h2⟩ := h in ⟨s, S, SS, by simp [h1], by simp [h2]⟩),
intros c1 c2 h,
exact match c1, c2, h with ._, ._, ⟨s, S, SS, rfl, rfl⟩ := begin
clear _match h h,
apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp,
{ apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp,
{ apply wseq.cases_on SS _ (λ S SS, _) (λ SS, _); simp,
{ refine ⟨nil, S, SS, _, _⟩; simp },
{ refine ⟨nil, nil, SS, _, _⟩; simp } },
{ exact ⟨s, S, SS, rfl, rfl⟩ },
{ refine ⟨nil, S, SS, _, _⟩; simp } },
{ exact ⟨s, S, SS, rfl, rfl⟩ },
{ exact ⟨s, S, SS, rfl, rfl⟩ }
end end
end
@[simp] theorem bind_assoc (s : wseq α) (f : α → wseq β) (g : β → wseq γ) :
bind (bind s f) g ~ bind s (λ (x : α), bind (f x) g) :=
begin
simp [bind], rw [← map_comp f (map g), map_comp (map g ∘ f) join],
apply join_join
end
instance : monad wseq :=
{ map := @map,
pure := @ret,
bind := @bind }
/-
Unfortunately, wseq is not a lawful monad, because it does not satisfy
the monad laws exactly, only up to sequence equivalence.
Furthermore, even quotienting by the equivalence is not sufficient,
because the join operation involves lists of quotient elements,
with a lifted equivalence relation, and pure quotients cannot handle
this type of construction.
instance : is_lawful_monad wseq :=
{ id_map := @map_id,
bind_pure_comp_eq_map := @bind_ret,
pure_bind := @ret_bind,
bind_assoc := @bind_assoc }
-/
end wseq
|
10ac114d515036db199f377dabc47c576a4e6efc | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /08_Building_Theories_and_Proofs.org.34.lean | b0fc81842a5f0dba9475451d8b4fd83d7ec559d0 | [] | 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 | 81 | lean | import standard
import data.nat
open [declarations] nat (add add.assoc add.comm)
|
cf98150bc4cd2cf9acc891620e50c61d4acc616a | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/list/of_fn.lean | d5164175aef1f3ae99c3f56d19520566041ec5a3 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 9,861 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.fin.tuple.basic
import data.list.join
import data.list.pairwise
/-!
# Lists from functions
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Theorems and lemmas for dealing with `list.of_fn`, which converts a function on `fin n` to a list
of length `n`.
## Main Statements
The main statements pertain to lists generated using `of_fn`
- `list.length_of_fn`, which tells us the length of such a list
- `list.nth_of_fn`, which tells us the nth element of such a list
- `list.array_eq_of_fn`, which interprets the list form of an array as such a list.
- `list.equiv_sigma_tuple`, which is an `equiv` between lists and the functions that generate them
via `list.of_fn`.
-/
universes u
variables {α : Type u}
open nat
namespace list
lemma length_of_fn_aux {n} (f : fin n → α) :
∀ m h l, length (of_fn_aux f m h l) = length l + m
| 0 h l := rfl
| (succ m) h l := (length_of_fn_aux m _ _).trans (succ_add _ _)
/-- The length of a list converted from a function is the size of the domain. -/
@[simp] theorem length_of_fn {n} (f : fin n → α) : length (of_fn f) = n :=
(length_of_fn_aux f _ _ _).trans (zero_add _)
lemma nth_of_fn_aux {n} (f : fin n → α) (i) :
∀ m h l,
(∀ i, nth l i = of_fn_nth_val f (i + m)) →
nth (of_fn_aux f m h l) i = of_fn_nth_val f i
| 0 h l H := H i
| (succ m) h l H := nth_of_fn_aux m _ _ begin
intro j, cases j with j,
{ simp only [nth, of_fn_nth_val, zero_add, dif_pos (show m < n, from h)] },
{ simp only [nth, H, add_succ, succ_add] }
end
/-- The `n`th element of a list -/
@[simp] theorem nth_of_fn {n} (f : fin n → α) (i) :
nth (of_fn f) i = of_fn_nth_val f i :=
nth_of_fn_aux f _ _ _ _ $ λ i,
by simp only [of_fn_nth_val, dif_neg (not_lt.2 (nat.le_add_left n i))]; refl
theorem nth_le_of_fn {n} (f : fin n → α) (i : fin n) :
nth_le (of_fn f) i ((length_of_fn f).symm ▸ i.2) = f i :=
option.some.inj $ by rw [← nth_le_nth];
simp only [list.nth_of_fn, of_fn_nth_val, fin.eta, dif_pos i.is_lt]
@[simp] theorem nth_le_of_fn' {n} (f : fin n → α) {i : ℕ} (h : i < (of_fn f).length) :
nth_le (of_fn f) i h = f ⟨i, ((length_of_fn f) ▸ h)⟩ :=
nth_le_of_fn f ⟨i, ((length_of_fn f) ▸ h)⟩
@[simp] lemma map_of_fn {β : Type*} {n : ℕ} (f : fin n → α) (g : α → β) :
map g (of_fn f) = of_fn (g ∘ f) :=
ext_le (by simp) (λ i h h', by simp)
/-- Arrays converted to lists are the same as `of_fn` on the indexing function of the array. -/
theorem array_eq_of_fn {n} (a : array n α) : a.to_list = of_fn a.read :=
suffices ∀ {m h l}, d_array.rev_iterate_aux a
(λ i, cons) m h l = of_fn_aux (d_array.read a) m h l, from this,
begin
intros, induction m with m IH generalizing l, {refl},
simp only [d_array.rev_iterate_aux, of_fn_aux, IH]
end
@[congr]
theorem of_fn_congr {m n : ℕ} (h : m = n) (f : fin m → α) :
of_fn f = of_fn (λ i : fin n, f (fin.cast h.symm i)) :=
begin
subst h,
simp_rw [fin.cast_refl, order_iso.refl_apply],
end
/-- `of_fn` on an empty domain is the empty list. -/
@[simp] theorem of_fn_zero (f : fin 0 → α) : of_fn f = [] := rfl
@[simp] theorem of_fn_succ {n} (f : fin (succ n) → α) :
of_fn f = f 0 :: of_fn (λ i, f i.succ) :=
suffices ∀ {m h l}, of_fn_aux f (succ m) (succ_le_succ h) l =
f 0 :: of_fn_aux (λ i, f i.succ) m h l, from this,
begin
intros, induction m with m IH generalizing l, {refl},
rw [of_fn_aux, IH], refl
end
theorem of_fn_succ' {n} (f : fin (succ n) → α) :
of_fn f = (of_fn (λ i, f i.cast_succ)).concat (f (fin.last _)) :=
begin
induction n with n IH,
{ rw [of_fn_zero, concat_nil, of_fn_succ, of_fn_zero], refl },
{ rw [of_fn_succ, IH, of_fn_succ, concat_cons, fin.cast_succ_zero],
congr' 3,
simp_rw [fin.cast_succ_fin_succ], }
end
@[simp] lemma of_fn_eq_nil_iff {n : ℕ} {f : fin n → α} :
of_fn f = [] ↔ n = 0 :=
by cases n; simp only [of_fn_zero, of_fn_succ, eq_self_iff_true, nat.succ_ne_zero]
lemma last_of_fn {n : ℕ} (f : fin n → α) (h : of_fn f ≠ [])
(hn : n - 1 < n := nat.pred_lt $ of_fn_eq_nil_iff.not.mp h) :
last (of_fn f) h = f ⟨n - 1, hn⟩ :=
by simp [last_eq_nth_le]
lemma last_of_fn_succ {n : ℕ} (f : fin n.succ → α)
(h : of_fn f ≠ [] := mt of_fn_eq_nil_iff.mp (nat.succ_ne_zero _)) :
last (of_fn f) h = f (fin.last _) :=
last_of_fn f h
/-- Note this matches the convention of `list.of_fn_succ'`, putting the `fin m` elements first. -/
theorem of_fn_add {m n} (f : fin (m + n) → α) :
list.of_fn f = list.of_fn (λ i, f (fin.cast_add n i)) ++ list.of_fn (λ j, f (fin.nat_add m j)) :=
begin
induction n with n IH,
{ rw [of_fn_zero, append_nil, fin.cast_add_zero, fin.cast_refl], refl },
{ rw [of_fn_succ', of_fn_succ', IH, append_concat], refl, },
end
@[simp] theorem of_fn_fin_append {m n} (a : fin m → α) (b : fin n → α) :
list.of_fn (fin.append a b) = list.of_fn a ++ list.of_fn b :=
by simp_rw [of_fn_add, fin.append_left, fin.append_right]
/-- This breaks a list of `m*n` items into `m` groups each containing `n` elements. -/
theorem of_fn_mul {m n} (f : fin (m * n) → α) :
list.of_fn f = list.join (list.of_fn $ λ i : fin m, list.of_fn $ λ j : fin n,
f ⟨i * n + j,
calc ↑i * n + j < (i + 1) *n : (add_lt_add_left j.prop _).trans_eq (add_one_mul _ _).symm
... ≤ _ : nat.mul_le_mul_right _ i.prop⟩) :=
begin
induction m with m IH,
{ simp_rw [of_fn_zero, zero_mul, of_fn_zero, join], },
{ simp_rw [of_fn_succ', succ_mul, join_concat, of_fn_add, IH], refl, },
end
/-- This breaks a list of `m*n` items into `n` groups each containing `m` elements. -/
theorem of_fn_mul' {m n} (f : fin (m * n) → α) :
list.of_fn f = list.join (list.of_fn $ λ i : fin n, list.of_fn $ λ j : fin m,
f ⟨m * i + j,
calc m * i + j < m * (i + 1) : (add_lt_add_left j.prop _).trans_eq (mul_add_one _ _).symm
... ≤ _ : nat.mul_le_mul_left _ i.prop⟩) :=
by simp_rw [mul_comm m n, mul_comm m, of_fn_mul, fin.cast_mk]
theorem of_fn_nth_le : ∀ l : list α, of_fn (λ i, nth_le l i i.2) = l
| [] := rfl
| (a::l) := by { rw of_fn_succ, congr, simp only [fin.coe_succ], exact of_fn_nth_le l }
-- not registered as a simp lemma, as otherwise it fires before `forall_mem_of_fn_iff` which
-- is much more useful
lemma mem_of_fn {n} (f : fin n → α) (a : α) :
a ∈ of_fn f ↔ a ∈ set.range f :=
begin
simp only [mem_iff_nth_le, set.mem_range, nth_le_of_fn'],
exact ⟨λ ⟨i, hi, h⟩, ⟨_, h⟩, λ ⟨i, hi⟩, ⟨i.1, (length_of_fn f).symm ▸ i.2, by simpa using hi⟩⟩
end
@[simp] lemma forall_mem_of_fn_iff {n : ℕ} {f : fin n → α} {P : α → Prop} :
(∀ i ∈ of_fn f, P i) ↔ ∀ j : fin n, P (f j) :=
by simp only [mem_of_fn, set.forall_range_iff]
@[simp] lemma of_fn_const (n : ℕ) (c : α) :
of_fn (λ i : fin n, c) = replicate n c :=
nat.rec_on n (by simp) $ λ n ihn, by simp [ihn]
@[simp] theorem of_fn_fin_repeat {m} (a : fin m → α) (n : ℕ) :
list.of_fn (fin.repeat n a) = (list.replicate n (list.of_fn a)).join :=
by simp_rw [of_fn_mul, ←of_fn_const, fin.repeat, fin.mod_nat, fin.coe_mk,
add_comm, nat.add_mul_mod_self_right, nat.mod_eq_of_lt (fin.is_lt _), fin.eta]
@[simp] lemma pairwise_of_fn {R : α → α → Prop} {n} {f : fin n → α} :
(of_fn f).pairwise R ↔ ∀ ⦃i j⦄, i < j → R (f i) (f j) :=
by { simp only [pairwise_iff_nth_le, fin.forall_iff, length_of_fn, nth_le_of_fn', fin.mk_lt_mk],
exact ⟨λ h i hi j hj hij, h _ _ hj hij, λ h i j hj hij, h _ (hij.trans hj) _ hj hij⟩ }
/-- Lists are equivalent to the sigma type of tuples of a given length. -/
@[simps]
def equiv_sigma_tuple : list α ≃ Σ n, fin n → α :=
{ to_fun := λ l, ⟨l.length, λ i, l.nth_le ↑i i.2⟩,
inv_fun := λ f, list.of_fn f.2,
left_inv := list.of_fn_nth_le,
right_inv := λ ⟨n, f⟩, fin.sigma_eq_of_eq_comp_cast (length_of_fn _) $ funext $ λ i,
nth_le_of_fn' f i.prop }
/-- A recursor for lists that expands a list into a function mapping to its elements.
This can be used with `induction l using list.of_fn_rec`. -/
@[elab_as_eliminator]
def of_fn_rec {C : list α → Sort*} (h : Π n (f : fin n → α), C (list.of_fn f)) (l : list α) : C l :=
cast (congr_arg _ l.of_fn_nth_le) $ h l.length (λ i, l.nth_le ↑i i.2)
@[simp]
lemma of_fn_rec_of_fn {C : list α → Sort*} (h : Π n (f : fin n → α), C (list.of_fn f))
{n : ℕ} (f : fin n → α) : @of_fn_rec _ C h (list.of_fn f) = h _ f :=
equiv_sigma_tuple.right_inverse_symm.cast_eq (λ s, h s.1 s.2) ⟨n, f⟩
lemma exists_iff_exists_tuple {P : list α → Prop} :
(∃ l : list α, P l) ↔ ∃ n (f : fin n → α), P (list.of_fn f) :=
equiv_sigma_tuple.symm.surjective.exists.trans sigma.exists
lemma forall_iff_forall_tuple {P : list α → Prop} :
(∀ l : list α, P l) ↔ ∀ n (f : fin n → α), P (list.of_fn f) :=
equiv_sigma_tuple.symm.surjective.forall.trans sigma.forall
/-- `fin.sigma_eq_iff_eq_comp_cast` may be useful to work with the RHS of this expression. -/
lemma of_fn_inj' {m n : ℕ} {f : fin m → α} {g : fin n → α} :
of_fn f = of_fn g ↔ (⟨m, f⟩ : Σ n, fin n → α) = ⟨n, g⟩ :=
iff.symm $ equiv_sigma_tuple.symm.injective.eq_iff.symm
/-- Note we can only state this when the two functions are indexed by defeq `n`. -/
lemma of_fn_injective {n : ℕ} : function.injective (of_fn : (fin n → α) → list α) :=
λ f g h, eq_of_heq $ by injection of_fn_inj'.mp h
/-- A special case of `list.of_fn_inj'` for when the two functions are indexed by defeq `n`. -/
@[simp] lemma of_fn_inj {n : ℕ} {f g : fin n → α} : of_fn f = of_fn g ↔ f = g :=
of_fn_injective.eq_iff
end list
|
781ea295667c146e3f6cc41b06a8e3001ae721a7 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/data/mv_polynomial/funext.lean | b25387b185d159a303c47c3d9bef730cf0114325 | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 3,161 | 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 data.polynomial.ring_division
import data.mv_polynomial.rename
import ring_theory.polynomial.basic
/-!
## Function extensionality for multivariate polynomials
In this file we show that two multivariate polynomials over an infinite integral domain are equal
if they are equal upon evaluating them on an arbitrary assignment of the variables.
# Main declaration
* `mv_polynomial.funext`: two polynomials `φ ψ : mv_polynomial σ R`
over an infinite integral domain `R` are equal if `eval x φ = eval x ψ` for all `x : σ → R`.
-/
namespace mv_polynomial
variables {R : Type*} [integral_domain R] [infinite R]
private lemma funext_fin {n : ℕ} {p : mv_polynomial (fin n) R}
(h : ∀ x : fin n → R, eval x p = 0) : p = 0 :=
begin
unfreezingI { revert R },
induction n with n ih,
{ introsI R _ _ p h,
let e := (ring_equiv_of_equiv R fin_zero_equiv').trans (mv_polynomial.pempty_ring_equiv R),
apply e.injective,
rw ring_equiv.map_zero,
convert h fin_zero_elim,
show (eval₂_hom (ring_hom.id _) pempty.elim) (rename fin_zero_equiv' p) = _,
rw [eval₂_hom_rename],
exact eval₂_hom_congr rfl (subsingleton.elim _ _) rfl },
{ introsI R _ _ p h,
let e := fin_succ_equiv R n,
apply e.injective,
simp only [ring_equiv.map_zero],
apply polynomial.funext,
intro q,
rw [polynomial.eval_zero],
apply ih, swap, { apply_instance },
intro x,
dsimp [e],
rw [fin_succ_equiv_apply],
calc _ = eval _ p : _
... = 0 : h _,
{ intro i, exact fin.cases (eval x q) x i },
apply induction_on p,
{ intro r,
simp only [eval_C, polynomial.eval_C, ring_hom.coe_comp, eval₂_hom_C], },
{ intros, simp only [*, ring_hom.map_add, polynomial.eval_add] },
{ intros φ i hφ, simp only [*, eval_X, polynomial.eval_mul, ring_hom.map_mul, eval₂_hom_X'],
congr' 1,
by_cases hi : i = 0,
{ subst hi, simp only [polynomial.eval_X, fin.cases_zero] },
{ rw [← fin.succ_pred i hi], simp only [eval_X, polynomial.eval_C, fin.cases_succ] } } }
end
/-- Two multivariate polynomials over an infinite integral domain are equal
if they are equal upon evaluating them on an arbitrary assignment of the variables. -/
lemma funext {σ : Type*} {p q : mv_polynomial σ R}
(h : ∀ x : σ → R, eval x p = eval x q) : p = q :=
begin
suffices : ∀ p, (∀ (x : σ → R), eval x p = 0) → p = 0,
{ rw [← sub_eq_zero, this (p - q)], simp only [h, ring_hom.map_sub, forall_const, sub_self] },
clear h p q,
intros p h,
obtain ⟨n, f, hf, p, rfl⟩ := exists_fin_rename p,
suffices : p = 0, { rw [this, alg_hom.map_zero] },
apply funext_fin,
intro x,
classical,
convert h (function.extend f x 0),
simp only [eval, eval₂_hom_rename, function.extend_comp hf]
end
lemma funext_iff {σ : Type*} {p q : mv_polynomial σ R} :
p = q ↔ (∀ x : σ → R, eval x p = eval x q) :=
⟨by rintro rfl; simp only [forall_const, eq_self_iff_true], funext⟩
end mv_polynomial
|
375e6c16a9414ea9b940e0733e56ef1c479b3543 | fe84e287c662151bb313504482b218a503b972f3 | /src/combinatorics/enumeration.lean | 95cc39e0e54ae1c4b0b20cf970b8eb736c0013b0 | [] | no_license | NeilStrickland/lean_lib | 91e163f514b829c42fe75636407138b5c75cba83 | 6a9563de93748ace509d9db4302db6cd77d8f92c | refs/heads/master | 1,653,408,198,261 | 1,652,996,419,000 | 1,652,996,419,000 | 181,006,067 | 4 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 5,467 | lean | /-
Copyright (c) 2019 Neil Strickland. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Neil Strickland
This file defines a typeclass for types α with an ordered
enumeration of the elements (as opposed to a `fintype`
instance, which is an unordered enumeration). This is
intended to allow for explicit calculation in a wider range
of cases.
-/
-- TODO:
-- instances for (co) products etc
import data.finset data.fintype.basic data.list.basic logic.encodable.basic
namespace combinatorics
universes u v
variables {α : Type*} {β : Type*} {γ : Type*}
class enumeration (α : Type*) :=
(elems : list α)
(nodup : list.nodup elems)
(complete : ∀ x : α, x ∈ elems)
instance enumeration_fintype [e : enumeration α] : fintype α :=
⟨⟨e.elems,e.nodup⟩,e.complete⟩
namespace enumeration
variable (α)
variable [enumeration α]
def univ_list : list α := (@enumeration.elems α _)
def univ_nodup : list.nodup (univ_list α) := (@enumeration.nodup α _)
def univ_complete := (@enumeration.complete α _)
lemma enum_card : fintype.card α = (@enumeration.elems α _).length :=
begin
dsimp[fintype.card,finset.univ,fintype.elems,finset.card],refl,
end
#check function.left_inverse.injective
def of_equiv (f : α ≃ β) : enumeration β :=
{ elems := (univ_list α).map f.to_fun,
nodup := list.nodup.map f.left_inv.injective (univ_nodup α),
complete :=
begin
intro b,
rw[← f.right_inv b],
exact list.mem_map_of_mem f.to_fun (univ_complete α (f.inv_fun b)),
end }
variable [decidable_eq α]
def fin_equiv {n : ℕ} (h : (univ_list α).length = n) : α ≃ (fin n) :=
begin
let els := univ_list α,
let inv_fun : (fin n) → α :=
λ i, els.nth_le i.val (@eq.subst ℕ (nat.lt i.val) _ _ h.symm i.is_lt),
let to_fun_aux : ∀ (a : α), {i : fin n // inv_fun i = a} :=
begin
intro a,
let i_val := els.index_of a,
let i_lt_l := list.index_of_lt_length.mpr (enumeration.complete a),
let i_lt_n : i_val < n := @eq.subst ℕ (nat.lt i_val) _ _ h i_lt_l,
let i : fin n := ⟨i_val,i_lt_n⟩,
have : inv_fun i = a :=
by { cases h,exact list.index_of_nth_le i_lt_l },
exact ⟨i,this⟩
end,
let to_fun : α → (fin n) := λ a, (to_fun_aux a).val,
let left_inv : ∀ a : α, inv_fun (to_fun a) = a :=
λ a, (to_fun_aux a).property,
let right_inv : ∀ i : (fin n), to_fun (inv_fun i) = i :=
begin
intro i,cases i with i_val i_is_lt,
apply fin.eq_of_veq,
let i_lt_l : i_val < els.length :=
@eq.subst ℕ (nat.lt i_val) _ _ h.symm i_is_lt,
exact list.nth_le_index_of (univ_nodup α) i_val i_lt_l,
end,
exact ⟨to_fun,inv_fun,left_inv,right_inv⟩
end
instance : encodable α :=
begin
let els := univ_list α,
let f := fin_equiv α rfl,
let encode : α → ℕ := λ a,(f.to_fun a).val,
let decode : ℕ → option α :=
begin
intro i,
by_cases h : i < els.length,
{exact some (f.inv_fun ⟨i,h⟩),},
{exact none,}
end,
let encodek : ∀ a, decode (encode a) = some a :=
begin
intro a,
dsimp[decode,encode],
rw[dif_pos (f a).is_lt],simp[f.left_inv a],
end,
exact ⟨encode,decode,encodek⟩
end
def subtype_enumeration {p : α → Prop} (l : list α)
(l_nodup : list.nodup l)
(l_mem : ∀ x : α, x ∈ l ↔ p x) : enumeration {x // p x} :=
begin
let α1 := {x // p x},
let elems1 : list α1 := @list.pmap α α1 p subtype.mk l (λ x, (l_mem x).mp),
let nodup : elems1.nodup :=
@list.nodup.pmap α α1 p subtype.mk l (λ x, (l_mem x).mp)
(λ a _ b _,congr_arg subtype.val) l_nodup,
let complete : ∀ a1 : α1, a1 ∈ elems1 :=
begin
intro a1, cases a1,
let h0 := ((@list.mem_pmap α α1 p subtype.mk l
(λ x, (l_mem x).mp)) ⟨a1_val,a1_property⟩).mpr,
have h1 : a1_val ∈ l := (l_mem a1_val).mpr a1_property,
exact h0 ⟨a1_val,h1,rfl⟩,
end,
exact ⟨elems1,nodup,complete⟩
end
instance (p : α → Prop) [decidable_pred p] : enumeration {a // p a} :=
begin
let l := (univ_list α).filter p,
let l_nodup : l.nodup := list.nodup.filter p (univ_nodup α),
let l_mem : ∀ x : α, x ∈ l ↔ p x :=
begin
intro x,
let h0 : x ∈ univ_list α := (univ_complete α) x,
simp[list.mem_filter,h0],
end,
exact subtype_enumeration α l l_nodup l_mem,
end
end enumeration
end combinatorics
namespace fin
instance enum : ∀ (n : ℕ), combinatorics.enumeration (fin n)
| 0 := { elems := [], nodup := list.nodup_nil, complete := λ x, fin.elim0 x }
| (n + 1) := {
elems := (0 : fin n.succ) :: ((enum n).elems.map fin.succ),
nodup :=
begin
rw [list.nodup_cons], split,
{ intro h, rcases list.mem_map.mp h with ⟨i,⟨hm,he⟩⟩,
exact fin.succ_ne_zero i he },
{ exact list.nodup.map (λ i j e, fin.succ_inj.mp e) (enum n).nodup }
end,
complete :=
λ i, begin
by_cases h : i = 0,
{ rw [h], exact list.mem_cons_self _ _ },
{ let j := fin.pred i h,
have : i = j.succ := (fin.succ_pred i h).symm,
rw [this],
let hc := (enum n).complete,
exact list.mem_cons_of_mem _
(list.mem_map_of_mem fin.succ (hc j)),
}
end
}
lemma enum_length : ∀ (n : ℕ), (fin.enum n).elems.length = n
| 0 := rfl
| (n + 1) :=
begin
change (list.cons (0 : fin (n + 1)) ((fin.enum n).elems.map fin.succ)).length = n + 1,
rw [list.length, list.length_map, enum_length n]
end
end fin
|
e80c3a4462af9c27d36da81c29a4201c0050a749 | 3f7026ea8bef0825ca0339a275c03b911baef64d | /src/data/rat/floor.lean | 347b70985871f85688bddc3b9585c0c43f9368b7 | [
"Apache-2.0"
] | permissive | rspencer01/mathlib | b1e3afa5c121362ef0881012cc116513ab09f18c | c7d36292c6b9234dc40143c16288932ae38fdc12 | refs/heads/master | 1,595,010,346,708 | 1,567,511,503,000 | 1,567,511,503,000 | 206,071,681 | 0 | 0 | Apache-2.0 | 1,567,513,643,000 | 1,567,513,643,000 | null | UTF-8 | Lean | false | false | 4,171 | 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, Mario Carneiro
-/
import data.rat.order
import data.rat.cast
/-!
# Floor and Ceil Functions for Rational Numbers
## Summary
We define the `floor`, `ceil`, and `nat_ceil` functions on `ℚ`.
## Main Definitions
- `floor q` is the largest integer `z` such that `z ≤ q`.
- `ceil q` is the smallest integer `z` such that `q ≤ z` .
- `nat_ceil q` is the smallest nonnegative integer `n` with `q ≤ n`.
## Tags
rat, rationals, field, ℚ, numerator, denominator, num, denom, ceil, floor
-/
namespace rat
section floor
/-- `floor q` is the largest integer `z` such that `z ≤ q` -/
def floor : ℚ → ℤ
| ⟨n, d, h, c⟩ := n / d
lemma floor_def {q : ℚ} : floor q = q.num / q.denom := by { cases q, refl }
theorem le_floor {z : ℤ} : ∀ {r : ℚ}, z ≤ floor r ↔ (z : ℚ) ≤ r
| ⟨n, d, h, c⟩ := begin
simp [floor],
rw [num_denom'],
have h' := int.coe_nat_lt.2 h,
conv { to_rhs,
rw [coe_int_eq_mk, rat.le_def zero_lt_one h', mul_one] },
exact int.le_div_iff_mul_le h'
end
theorem floor_lt {r : ℚ} {z : ℤ} : floor r < z ↔ r < z :=
lt_iff_lt_of_le_iff_le le_floor
theorem floor_le (r : ℚ) : (floor r : ℚ) ≤ r :=
le_floor.1 (le_refl _)
theorem lt_succ_floor (r : ℚ) : r < (floor r).succ :=
floor_lt.1 $ int.lt_succ_self _
@[simp] theorem floor_coe (z : ℤ) : floor z = z :=
eq_of_forall_le_iff $ λ a, by rw [le_floor, int.cast_le]
theorem floor_mono {a b : ℚ} (h : a ≤ b) : floor a ≤ floor b :=
le_floor.2 (le_trans (floor_le _) h)
@[simp] theorem floor_add_int (r : ℚ) (z : ℤ) : floor (r + z) = floor r + z :=
eq_of_forall_le_iff $ λ a, by rw [le_floor,
← sub_le_iff_le_add, ← sub_le_iff_le_add, le_floor, int.cast_sub]
theorem floor_sub_int (r : ℚ) (z : ℤ) : floor (r - z) = floor r - z :=
eq.trans (by rw [int.cast_neg]; refl) (floor_add_int _ _)
end floor
section ceil
/-- `ceil q` is the smallest integer `z` such that `q ≤ z` -/
def ceil (r : ℚ) : ℤ :=
-(floor (-r))
theorem ceil_le {z : ℤ} {r : ℚ} : ceil r ≤ z ↔ r ≤ z :=
by rw [ceil, neg_le, le_floor, int.cast_neg, neg_le_neg_iff]
theorem le_ceil (r : ℚ) : r ≤ ceil r :=
ceil_le.1 (le_refl _)
@[simp] theorem ceil_coe (z : ℤ) : ceil z = z :=
by rw [ceil, ← int.cast_neg, floor_coe, neg_neg]
theorem ceil_mono {a b : ℚ} (h : a ≤ b) : ceil a ≤ ceil b :=
ceil_le.2 (le_trans h (le_ceil _))
@[simp] theorem ceil_add_int (r : ℚ) (z : ℤ) : ceil (r + z) = ceil r + z :=
by rw [ceil, neg_add', floor_sub_int, neg_sub, sub_eq_neg_add]; refl
theorem ceil_sub_int (r : ℚ) (z : ℤ) : ceil (r - z) = ceil r - z :=
eq.trans (by rw [int.cast_neg]; refl) (ceil_add_int _ _)
end ceil
section nat_ceil
/-- `nat_ceil q` is the smallest nonnegative integer `n` with `q ≤ n`.
It is the same as `ceil q` when `q ≥ 0`, otherwise it is `0`. -/
def nat_ceil (q : ℚ) : ℕ := int.to_nat (ceil q)
theorem nat_ceil_le {q : ℚ} {n : ℕ} : nat_ceil q ≤ n ↔ q ≤ n :=
by rw [nat_ceil, int.to_nat_le, ceil_le]; refl
theorem lt_nat_ceil {q : ℚ} {n : ℕ} : n < nat_ceil q ↔ (n : ℚ) < q :=
not_iff_not.1 $ by rw [not_lt, not_lt, nat_ceil_le]
theorem le_nat_ceil (q : ℚ) : q ≤ nat_ceil q :=
nat_ceil_le.1 (le_refl _)
theorem nat_ceil_mono {q₁ q₂ : ℚ} (h : q₁ ≤ q₂) : nat_ceil q₁ ≤ nat_ceil q₂ :=
nat_ceil_le.2 (le_trans h (le_nat_ceil _))
@[simp] theorem nat_ceil_coe (n : ℕ) : nat_ceil n = n :=
show (ceil (n:ℤ)).to_nat = n, by rw [ceil_coe]; refl
@[simp] theorem nat_ceil_zero : nat_ceil 0 = 0 := nat_ceil_coe 0
theorem nat_ceil_add_nat {q : ℚ} (hq : 0 ≤ q) (n : ℕ) : nat_ceil (q + n) = nat_ceil q + n :=
show int.to_nat (ceil (q + (n:ℤ))) = int.to_nat (ceil q) + n,
by rw [ceil_add_int]; exact
match ceil q, int.eq_coe_of_zero_le (ceil_mono hq) with
| _, ⟨m, rfl⟩ := rfl
end
theorem nat_ceil_lt_add_one {q : ℚ} (hq : q ≥ 0) : ↑(nat_ceil q) < q + 1 :=
lt_nat_ceil.1 $ by rw [
show nat_ceil (q+1) = nat_ceil q+1, from nat_ceil_add_nat hq 1]; apply nat.lt_succ_self
end nat_ceil
end rat
|
14e4d798f47dd88be7ea067c89ff7dc5de81cf23 | 57fdc8de88f5ea3bfde4325e6ecd13f93a274ab5 | /data/int/modeq.lean | 951b1af52a1199a00d77ba0f25e87dc6506816a9 | [
"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 | 3,311 | 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.int.basic data.nat.modeq
namespace int
def modeq (n a b : ℤ) := a % n = b % n
notation a ` ≡ `:50 b ` [ZMOD `:50 n `]`:0 := modeq n a b
namespace modeq
variables {n m a b c d : ℤ}
@[refl] protected theorem refl (a : ℤ) : a ≡ a [ZMOD n] := @rfl _ _
@[symm] protected theorem symm : a ≡ b [ZMOD n] → b ≡ a [ZMOD n] := eq.symm
@[trans] protected theorem trans : a ≡ b [ZMOD n] → b ≡ c [ZMOD n] → a ≡ c [ZMOD n] := eq.trans
lemma coe_nat_modeq_iff (a b n : ℕ) : a ≡ b [ZMOD n] ↔ a ≡ b [MOD n] :=
by unfold modeq nat.modeq; rw ← int.coe_nat_eq_coe_nat_iff; simp [int.coe_nat_mod]
instance : decidable (a ≡ b [ZMOD n]) := by unfold modeq; apply_instance
theorem modeq_zero_iff : a ≡ 0 [ZMOD n] ↔ n ∣ a :=
by rw [modeq, zero_mod, dvd_iff_mod_eq_zero]
theorem modeq_iff_dvd : a ≡ b [ZMOD n] ↔ (n:ℤ) ∣ b - a :=
by rw [modeq, eq_comm];
simp [int.mod_eq_mod_iff_mod_sub_eq_zero, int.dvd_iff_mod_eq_zero]
theorem modeq_of_dvd_of_modeq (d : m ∣ n) (h : a ≡ b [ZMOD n]) : a ≡ b [ZMOD m] :=
modeq_iff_dvd.2 $ dvd_trans d (modeq_iff_dvd.1 h)
theorem modeq_mul_left' (hc : 0 ≤ c) (h : a ≡ b [ZMOD n]) : c * a ≡ c * b [ZMOD (c * n)] :=
or.cases_on (lt_or_eq_of_le hc) (λ hc,
by unfold modeq;
simp [mul_mod_mul_of_pos _ _ hc, (show _ = _, from h)] )
(λ hc, by simp [hc.symm])
theorem modeq_mul_right' (hc : 0 ≤ c) (h : a ≡ b [ZMOD n]) : a * c ≡ b * c [ZMOD (n * c)] :=
by rw [mul_comm a, mul_comm b, mul_comm n]; exact modeq_mul_left' hc h
theorem modeq_add (h₁ : a ≡ b [ZMOD n]) (h₂ : c ≡ d [ZMOD n]) : a + c ≡ b + d [ZMOD n] :=
modeq_iff_dvd.2 $ by simpa using dvd_add (modeq_iff_dvd.1 h₁) (modeq_iff_dvd.1 h₂)
theorem modeq_add_cancel_left (h₁ : a ≡ b [ZMOD n]) (h₂ : a + c ≡ b + d [ZMOD n]) : c ≡ d [ZMOD n] :=
have (n:ℤ) ∣ a + (-a + (d + -c)),
by simpa using dvd_sub (modeq_iff_dvd.1 h₂) (modeq_iff_dvd.1 h₁),
modeq_iff_dvd.2 $ by rwa add_neg_cancel_left at this
theorem modeq_add_cancel_right (h₁ : c ≡ d [ZMOD n]) (h₂ : a + c ≡ b + d [ZMOD n]) : a ≡ b [ZMOD n] :=
by rw [add_comm a, add_comm b] at h₂; exact modeq_add_cancel_left h₁ h₂
theorem modeq_neg (h : a ≡ b [ZMOD n]) : -a ≡ -b [ZMOD n] :=
modeq_add_cancel_left h (by simp)
theorem modeq_sub (h₁ : a ≡ b [ZMOD n]) (h₂ : c ≡ d [ZMOD n]) : a - c ≡ b - d [ZMOD n] :=
by rw [sub_eq_add_neg, sub_eq_add_neg]; exact modeq_add h₁ (modeq_neg h₂)
theorem modeq_mul_left (c : ℤ) (h : a ≡ b [ZMOD n]) : c * a ≡ c * b [ZMOD n] :=
or.cases_on (le_total 0 c)
(λ hc, modeq_of_dvd_of_modeq (dvd_mul_left _ _) (modeq_mul_left' hc h))
(λ hc, by rw [← neg_neg c, ← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul _ b];
exact modeq_neg (modeq_of_dvd_of_modeq (dvd_mul_left _ _)
(modeq_mul_left' (neg_nonneg.2 hc) h)))
theorem modeq_mul_right (c : ℤ) (h : a ≡ b [ZMOD n]) : a * c ≡ b * c [ZMOD n] :=
by rw [mul_comm a, mul_comm b]; exact modeq_mul_left c h
theorem modeq_mul (h₁ : a ≡ b [ZMOD n]) (h₂ : c ≡ d [ZMOD n]) : a * c ≡ b * d [ZMOD n] :=
(modeq_mul_left _ h₂).trans (modeq_mul_right _ h₁)
end modeq
end int
|
251ec74bf1f88c722390b5c1c70edf6f3a89f08f | c777c32c8e484e195053731103c5e52af26a25d1 | /src/logic/nontrivial.lean | 99388b9a6b5a1f2a4c195882561600027b89c70e | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 7,212 | lean | /-
Copyright (c) 2020 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import data.prod.basic
import data.subtype
import logic.function.basic
import logic.unique
/-!
# Nontrivial types
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
A type is *nontrivial* if it contains at least two elements. This is useful in particular for rings
(where it is equivalent to the fact that zero is different from one) and for vector spaces
(where it is equivalent to the fact that the dimension is positive).
We introduce a typeclass `nontrivial` formalizing this property.
-/
variables {α : Type*} {β : Type*}
open_locale classical
/-- Predicate typeclass for expressing that a type is not reduced to a single element. In rings,
this is equivalent to `0 ≠ 1`. In vector spaces, this is equivalent to positive dimension. -/
class nontrivial (α : Type*) : Prop :=
(exists_pair_ne : ∃ (x y : α), x ≠ y)
lemma nontrivial_iff : nontrivial α ↔ ∃ (x y : α), x ≠ y :=
⟨λ h, h.exists_pair_ne, λ h, ⟨h⟩⟩
lemma exists_pair_ne (α : Type*) [nontrivial α] : ∃ (x y : α), x ≠ y :=
nontrivial.exists_pair_ne
-- See Note [decidable namespace]
protected lemma decidable.exists_ne [nontrivial α] [decidable_eq α] (x : α) : ∃ y, y ≠ x :=
begin
rcases exists_pair_ne α with ⟨y, y', h⟩,
by_cases hx : x = y,
{ rw ← hx at h,
exact ⟨y', h.symm⟩ },
{ exact ⟨y, ne.symm hx⟩ }
end
lemma exists_ne [nontrivial α] (x : α) : ∃ y, y ≠ x :=
by classical; exact decidable.exists_ne x
-- `x` and `y` are explicit here, as they are often needed to guide typechecking of `h`.
lemma nontrivial_of_ne (x y : α) (h : x ≠ y) : nontrivial α :=
⟨⟨x, y, h⟩⟩
-- `x` and `y` are explicit here, as they are often needed to guide typechecking of `h`.
lemma nontrivial_of_lt [preorder α] (x y : α) (h : x < y) : nontrivial α :=
⟨⟨x, y, ne_of_lt h⟩⟩
lemma exists_pair_lt (α : Type*) [nontrivial α] [linear_order α] : ∃ (x y : α), x < y :=
begin
rcases exists_pair_ne α with ⟨x, y, hxy⟩,
cases lt_or_gt_of_ne hxy;
exact ⟨_, _, h⟩
end
lemma nontrivial_iff_lt [linear_order α] : nontrivial α ↔ ∃ (x y : α), x < y :=
⟨λ h, @exists_pair_lt α h _, λ ⟨x, y, h⟩, nontrivial_of_lt x y h⟩
lemma nontrivial_iff_exists_ne (x : α) : nontrivial α ↔ ∃ y, y ≠ x :=
⟨λ h, @exists_ne α h x, λ ⟨y, hy⟩, nontrivial_of_ne _ _ hy⟩
lemma subtype.nontrivial_iff_exists_ne (p : α → Prop) (x : subtype p) :
nontrivial (subtype p) ↔ ∃ (y : α) (hy : p y), y ≠ x :=
by simp only [nontrivial_iff_exists_ne x, subtype.exists, ne.def, subtype.ext_iff, subtype.coe_mk]
instance : nontrivial Prop := ⟨⟨true, false, true_ne_false⟩⟩
/--
See Note [lower instance priority]
Note that since this and `nonempty_of_inhabited` are the most "obvious" way to find a nonempty
instance if no direct instance can be found, we give this a higher priority than the usual `100`.
-/
@[priority 500]
instance nontrivial.to_nonempty [nontrivial α] : nonempty α :=
let ⟨x, _⟩ := exists_pair_ne α in ⟨x⟩
attribute [instance, priority 500] nonempty_of_inhabited
/-- An inhabited type is either nontrivial, or has a unique element. -/
noncomputable def nontrivial_psum_unique (α : Type*) [inhabited α] :
psum (nontrivial α) (unique α) :=
if h : nontrivial α then psum.inl h else psum.inr
{ default := default,
uniq := λ (x : α),
begin
change x = default,
contrapose! h,
use [x, default]
end }
lemma subsingleton_iff : subsingleton α ↔ ∀ (x y : α), x = y :=
⟨by { introsI h, exact subsingleton.elim }, λ h, ⟨h⟩⟩
lemma not_nontrivial_iff_subsingleton : ¬(nontrivial α) ↔ subsingleton α :=
by { rw [nontrivial_iff, subsingleton_iff], push_neg, refl }
lemma not_nontrivial (α) [subsingleton α] : ¬nontrivial α :=
λ ⟨⟨x, y, h⟩⟩, h $ subsingleton.elim x y
lemma not_subsingleton (α) [h : nontrivial α] : ¬subsingleton α :=
let ⟨⟨x, y, hxy⟩⟩ := h in λ ⟨h'⟩, hxy $ h' x y
/-- A type is either a subsingleton or nontrivial. -/
lemma subsingleton_or_nontrivial (α : Type*) : subsingleton α ∨ nontrivial α :=
by { rw [← not_nontrivial_iff_subsingleton, or_comm], exact classical.em _ }
lemma false_of_nontrivial_of_subsingleton (α : Type*) [nontrivial α] [subsingleton α] : false :=
let ⟨x, y, h⟩ := exists_pair_ne α in h $ subsingleton.elim x y
instance option.nontrivial [nonempty α] : nontrivial (option α) :=
by { inhabit α, use [none, some default] }
/-- Pushforward a `nontrivial` instance along an injective function. -/
protected lemma function.injective.nontrivial [nontrivial α]
{f : α → β} (hf : function.injective f) : nontrivial β :=
let ⟨x, y, h⟩ := exists_pair_ne α in ⟨⟨f x, f y, hf.ne h⟩⟩
/-- Pullback a `nontrivial` instance along a surjective function. -/
protected lemma function.surjective.nontrivial [nontrivial β]
{f : α → β} (hf : function.surjective f) : nontrivial α :=
begin
rcases exists_pair_ne β with ⟨x, y, h⟩,
rcases hf x with ⟨x', hx'⟩,
rcases hf y with ⟨y', hy'⟩,
have : x' ≠ y', by { contrapose! h, rw [← hx', ← hy', h] },
exact ⟨⟨x', y', this⟩⟩
end
/-- An injective function from a nontrivial type has an argument at
which it does not take a given value. -/
protected lemma function.injective.exists_ne [nontrivial α] {f : α → β}
(hf : function.injective f) (y : β) : ∃ x, f x ≠ y :=
begin
rcases exists_pair_ne α with ⟨x₁, x₂, hx⟩,
by_cases h : f x₂ = y,
{ exact ⟨x₁, (hf.ne_iff' h).2 hx⟩ },
{ exact ⟨x₂, h⟩ }
end
instance nontrivial_prod_right [nonempty α] [nontrivial β] : nontrivial (α × β) :=
prod.snd_surjective.nontrivial
instance nontrivial_prod_left [nontrivial α] [nonempty β] : nontrivial (α × β) :=
prod.fst_surjective.nontrivial
namespace pi
variables {I : Type*} {f : I → Type*}
/-- A pi type is nontrivial if it's nonempty everywhere and nontrivial somewhere. -/
lemma nontrivial_at (i' : I) [inst : Π i, nonempty (f i)] [nontrivial (f i')] :
nontrivial (Π i : I, f i) :=
by classical; exact
(function.update_injective (λ i, classical.choice (inst i)) i').nontrivial
/--
As a convenience, provide an instance automatically if `(f default)` is nontrivial.
If a different index has the non-trivial type, then use `haveI := nontrivial_at that_index`.
-/
instance nontrivial [inhabited I] [inst : Π i, nonempty (f i)] [nontrivial (f default)] :
nontrivial (Π i : I, f i) := nontrivial_at default
end pi
instance function.nontrivial [h : nonempty α] [nontrivial β] : nontrivial (α → β) :=
h.elim $ λ a, pi.nontrivial_at a
mk_simp_attribute nontriviality "Simp lemmas for `nontriviality` tactic"
protected lemma subsingleton.le [preorder α] [subsingleton α] (x y : α) : x ≤ y :=
le_of_eq (subsingleton.elim x y)
attribute [nontriviality] eq_iff_true_of_subsingleton subsingleton.le
namespace bool
instance : nontrivial bool := ⟨⟨tt,ff, tt_eq_ff_eq_false⟩⟩
end bool
|
c1b1d56d7b6f6115baae6caed4fd0de8773e5684 | a7dd8b83f933e72c40845fd168dde330f050b1c9 | /src/tactic/rcases.lean | be1ec91bf6bd0fff514eec7cca585c1a0e516439 | [
"Apache-2.0"
] | permissive | NeilStrickland/mathlib | 10420e92ee5cb7aba1163c9a01dea2f04652ed67 | 3efbd6f6dff0fb9b0946849b43b39948560a1ffe | refs/heads/master | 1,589,043,046,346 | 1,558,938,706,000 | 1,558,938,706,000 | 181,285,984 | 0 | 0 | Apache-2.0 | 1,568,941,848,000 | 1,555,233,833,000 | Lean | UTF-8 | Lean | false | false | 17,139 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.dlist tactic.core
open lean lean.parser
namespace tactic
/-
These synonyms for `list` are used to clarify the meanings of the many
usages of lists in this module.
- `listΣ` is used where a list represents a disjunction, such as the
list of possible constructors of an inductive type.
- `listΠ` is used where a list represents a conjunction, such as the
list of arguments of an individual constructor.
These are merely type synonyms, and so are not checked for consistency
by the compiler.
The `def`/`local notation` combination makes Lean retain these
annotations in reported types.
-/
@[reducible] def list_Sigma := list
@[reducible] def list_Pi := list
local notation `listΣ` := list_Sigma
local notation `listΠ` := list_Pi
@[reducible] meta def goals := list expr
meta inductive rcases_patt : Type
| one : name → rcases_patt
| many : listΣ (listΠ rcases_patt) → rcases_patt
meta instance rcases_patt.inhabited : inhabited rcases_patt :=
⟨rcases_patt.one `_⟩
meta def rcases_patt.name : rcases_patt → name
| (rcases_patt.one n) := n
| _ := `_
meta instance rcases_patt.has_reflect : has_reflect rcases_patt
| (rcases_patt.one n) := `(_)
| (rcases_patt.many l) := `(λ l, rcases_patt.many l).subst $
by haveI := rcases_patt.has_reflect; exact list.reflect l
/--
The parser/printer uses an "inverted" meaning for the `many` constructor:
rather than representing a sum of products, here it represents a
product of sums. We fix this by applying `invert`, defined below, to
the result.
-/
meta inductive rcases_patt_inverted : Type
| one : name → rcases_patt_inverted
| many : listΠ (listΣ rcases_patt_inverted) → rcases_patt_inverted
meta instance rcases_patt_inverted.inhabited : inhabited rcases_patt_inverted :=
⟨rcases_patt_inverted.one `_⟩
meta instance rcases_patt_inverted.has_reflect : has_reflect rcases_patt_inverted
| (rcases_patt_inverted.one n) := `(_)
| (rcases_patt_inverted.many l) := `(λ l, rcases_patt_inverted.many l).subst $
by haveI := rcases_patt_inverted.has_reflect; exact list.reflect l
meta mutual def rcases_patt_inverted.invert, rcases_patt_inverted.invert_list
with rcases_patt_inverted.invert : listΣ rcases_patt_inverted → rcases_patt
| [rcases_patt_inverted.one n] := rcases_patt.one n
| l := rcases_patt.many (rcases_patt_inverted.invert_list l)
with rcases_patt_inverted.invert_list : listΣ rcases_patt_inverted → listΣ (listΠ rcases_patt)
| l := l.map $ λ p,
match p with
| rcases_patt_inverted.one n := [rcases_patt.one n]
| rcases_patt_inverted.many l := rcases_patt_inverted.invert <$> l
end
meta mutual def rcases_patt.invert, rcases_patt.invert_many, rcases_patt.invert_list, rcases_patt.invert'
with rcases_patt.invert : rcases_patt → listΣ rcases_patt_inverted
| (rcases_patt.one n) := [rcases_patt_inverted.one n]
| (rcases_patt.many ls) := rcases_patt.invert_many ls
with rcases_patt.invert_many : listΣ (listΠ rcases_patt) → listΣ rcases_patt_inverted
| [] := []
| [[rcases_patt.many ls@(_::_::_)]] := rcases_patt.invert_many ls
| (l::ls) := rcases_patt.invert' l :: rcases_patt.invert_many ls
with rcases_patt.invert_list : listΠ rcases_patt → listΠ (listΣ rcases_patt_inverted)
| [] := []
| [rcases_patt.many [l@(_::_::_)]] := rcases_patt.invert_list l
| (p::l) := rcases_patt.invert p :: rcases_patt.invert_list l
with rcases_patt.invert' : listΠ rcases_patt → rcases_patt_inverted
| [rcases_patt.one n] := rcases_patt_inverted.one n
| [] := rcases_patt_inverted.one `_
| ls := rcases_patt_inverted.many (rcases_patt.invert_list ls)
meta mutual def rcases_patt_inverted.format, rcases_patt_inverted.format_list
with rcases_patt_inverted.format : rcases_patt_inverted → format
| (rcases_patt_inverted.one n) := to_fmt n
| (rcases_patt_inverted.many []) := "⟨⟩"
| (rcases_patt_inverted.many ls) := "⟨" ++ format.group (format.nest 1 $
format.join $ list.intersperse ("," ++ format.line) $
ls.map (format.group ∘ rcases_patt_inverted.format_list)) ++ "⟩"
with rcases_patt_inverted.format_list : listΣ rcases_patt_inverted → opt_param bool ff → format
| [] br := "⟨⟩"
| [p] br := rcases_patt_inverted.format p
| (p::l) br :=
let fmt := rcases_patt_inverted.format p ++ " |" ++ format.space ++
rcases_patt_inverted.format_list l in
if br then format.bracket "(" ")" fmt else fmt
meta instance rcases_patt_inverted.has_to_format :
has_to_format rcases_patt_inverted := ⟨rcases_patt_inverted.format⟩
meta def rcases_patt.format (p : rcases_patt) (br := ff) : format :=
rcases_patt_inverted.format_list p.invert br
meta instance rcases_patt.has_to_format : has_to_format rcases_patt := ⟨rcases_patt.format⟩
/--
Takes the number of fields of a single constructor and patterns to
match its fields against (not necessarily the same number). The
returned lists each contain one element per field of the
constructor. The `name` is the name which will be used in the
top-level `cases` tactic, and the `rcases_patt` is the pattern which
the field will be matched against by subsequent `cases` tactics.
-/
meta def rcases.process_constructor :
nat → listΠ rcases_patt → listΠ name × listΠ rcases_patt
| 0 ids := ([], [])
| 1 [] := ([`_], [default _])
| 1 [id] := ([id.name], [id])
-- The interesting case: we matched the last field against multiple
-- patterns, so split off the remaining patterns into a subsequent
-- match. This handles matching `α × β × γ` against `⟨a, b, c⟩`.
| 1 ids := ([`_], [rcases_patt.many [ids]])
| (n+1) ids :=
let (ns, ps) := rcases.process_constructor n ids.tail,
p := ids.head in
(p.name :: ns, p :: ps)
meta def rcases.process_constructors (params : nat) :
listΣ name → listΣ (listΠ rcases_patt) →
tactic (dlist name × listΣ (name × listΠ rcases_patt))
| [] ids := pure (dlist.empty, [])
| (c::cs) ids := do
n ← mk_const c >>= get_arity,
let (h, t) := (match cs, ids.tail with
-- We matched the last constructor against multiple patterns,
-- so split off the remaining constructors. This handles matching
-- `α ⊕ β ⊕ γ` against `a|b|c`.
| [], _::_ := ([rcases_patt.many ids], [])
| _, _ := (ids.head, ids.tail)
end : _),
let (ns, ps) := rcases.process_constructor (n - params) h,
(l, r) ← rcases.process_constructors cs t,
pure (dlist.of_list ns ++ l, (c, ps) :: r)
private def align {α β} (p : α → β → Prop) [∀ a b, decidable (p a b)] :
list α → list β → list (α × β)
| (a::as) (b::bs) :=
if p a b then (a, b) :: align as bs else align as (b::bs)
| _ _ := []
private meta def get_local_and_type (e : expr) : tactic (expr × expr) :=
(do t ← infer_type e, pure (t, e)) <|> (do
e ← get_local e.local_pp_name,
t ← infer_type e, pure (t, e))
meta mutual def rcases_core, rcases.continue
with rcases_core : listΣ (listΠ rcases_patt) → expr → tactic goals
| ids e := do
(t, e) ← get_local_and_type e,
t ← whnf t,
env ← get_env,
let I := t.get_app_fn.const_name,
(ids, r, l) ← (if I ≠ `quot
then do
when (¬env.is_inductive I) $
fail format!"rcases tactic failed: {e} : {I} is not an inductive datatype",
let params := env.inductive_num_params I,
let c := env.constructors_of I,
(ids, r) ← rcases.process_constructors params c ids,
l ← cases_core e ids.to_list,
return (ids, r, l)
else do
(ids, r) ← rcases.process_constructors 2 [`quot.mk] ids,
[(_, d)] ← induction e ids.to_list `quot.induction_on |
fail format!"quotient induction on {e} failed. Maybe goal is not in Prop?",
-- the result from `induction` is missing the information that the original constructor was
-- `quot.mk` so we fix this up:
return (ids, r, [(`quot.mk, d)])),
gs ← get_goals,
-- `cases_core` may not generate a new goal for every constructor,
-- as some constructors may be impossible for type reasons. (See its
-- documentation.) Match up the new goals with our remaining work
-- by constructor name.
list.join <$> (align (λ (a : name × _) (b : _ × name × _), a.1 = b.2.1) r (gs.zip l)).mmap
(λ⟨⟨_, ps⟩, g, _, hs, _⟩,
set_goals [g] >> rcases.continue (ps.zip hs))
with rcases.continue : listΠ (rcases_patt × expr) → tactic goals
| [] := get_goals
| ((rcases_patt.many ids, e) :: l) := do
gs ← rcases_core ids e,
list.join <$> gs.mmap (λ g, set_goals [g] >> rcases.continue l)
| ((rcases_patt.one `rfl, e) :: l) := do
(t, e) ← get_local_and_type e,
subst e,
rcases.continue l
-- If the pattern is any other name, we already bound the name in the
-- top-level `cases` tactic, so there is no more work to do for it.
| (_ :: l) := rcases.continue l
meta def rcases (p : pexpr) (ids : listΣ (listΠ rcases_patt)) : tactic unit :=
do e ← i_to_expr p,
if e.is_local_constant then
focus1 (rcases_core ids e >>= set_goals)
else do
x ← mk_fresh_name,
n ← revert_kdependencies e semireducible,
(tactic.generalize e x)
<|>
(do t ← infer_type e,
tactic.assertv x t e,
get_local x >>= tactic.revert,
return ()),
h ← tactic.intro1,
focus1 (rcases_core ids h >>= set_goals)
meta def rintro (ids : listΠ rcases_patt) : tactic unit :=
do l ← ids.mmap (λ id, do
e ← intro id.name,
return (id, e)),
focus1 (rcases.continue l >>= set_goals)
def merge_list {α} (m : α → α → α) : list α → list α → list α
| [] l₂ := l₂
| l₁ [] := l₁
| (a :: l₁) (b :: l₂) := m a b :: merge_list l₁ l₂
meta def rcases_patt.merge : rcases_patt → rcases_patt → rcases_patt
| (rcases_patt.many ids₁) (rcases_patt.many ids₂) :=
rcases_patt.many (merge_list (merge_list rcases_patt.merge) ids₁ ids₂)
| (rcases_patt.one `rfl) (rcases_patt.many ids₂) :=
rcases_patt.many (merge_list (merge_list rcases_patt.merge) [[]] ids₂)
| (rcases_patt.many ids₁) (rcases_patt.one `rfl) :=
rcases_patt.many (merge_list (merge_list rcases_patt.merge) ids₁ [[]])
| (rcases_patt.one `rfl) (rcases_patt.one `rfl) := rcases_patt.one `rfl
| (rcases_patt.one `_) p := p
| p (rcases_patt.one `_) := p
| (rcases_patt.one n) _ := rcases_patt.one n
| _ (rcases_patt.one n) := rcases_patt.one n
meta mutual def rcases_hint_core, rcases_hint.process_constructors, rcases_hint.continue
with rcases_hint_core : ℕ → expr → tactic (rcases_patt × goals)
| depth e := do
(t, e) ← get_local_and_type e,
t ← whnf t,
env ← get_env,
some l ← try_core (guard (depth ≠ 0) >> cases_core e) |
prod.mk (rcases_patt.one e.local_pp_name) <$> get_goals,
let I := t.get_app_fn.const_name,
if I = ``eq then
prod.mk (rcases_patt.one `rfl) <$> get_goals
else do
let c := env.constructors_of I,
gs ← get_goals,
(ps, gs') ← rcases_hint.process_constructors (depth - 1) c (gs.zip l),
pure (rcases_patt.many ps, gs')
with rcases_hint.process_constructors : ℕ → listΣ name →
list (expr × name × listΠ expr × list (name × expr)) →
tactic (listΣ (listΠ rcases_patt) × goals)
| depth [] _ := pure ([], [])
| depth cs [] := pure (cs.map (λ _, []), [])
| depth (c::cs) ((g, c', hs, _) :: l) :=
if c ≠ c' then do
(ps, gs) ← rcases_hint.process_constructors depth cs l,
pure ([] :: ps, gs)
else do
(p, gs) ← set_goals [g] >> rcases_hint.continue depth hs,
(ps, gs') ← rcases_hint.process_constructors depth cs l,
pure (p :: ps, gs ++ gs')
with rcases_hint.continue : ℕ → listΠ expr → tactic (listΠ rcases_patt × goals)
| depth [] := prod.mk [] <$> get_goals
| depth (e :: l) := do
(p, gs) ← rcases_hint_core depth e,
(ps, gs') ← gs.mfoldl (λ (r : listΠ rcases_patt × goals) g,
do (ps, gs') ← set_goals [g] >> rcases_hint.continue depth l,
pure (merge_list rcases_patt.merge r.1 ps, r.2 ++ gs')) ([], []),
pure (p :: ps, gs')
meta def rcases_hint (p : pexpr) (depth : nat) : tactic rcases_patt :=
do e ← i_to_expr p,
if e.is_local_constant then
focus1 $ do (p, gs) ← rcases_hint_core depth e, set_goals gs, pure p
else do
x ← mk_fresh_name,
n ← revert_kdependencies e semireducible,
(tactic.generalize e x)
<|>
(do t ← infer_type e,
tactic.assertv x t e,
get_local x >>= tactic.revert,
pure ()),
h ← tactic.intro1,
focus1 $ do (p, gs) ← rcases_hint_core depth h, set_goals gs, pure p
meta def rintro_hint (depth : nat) : tactic (listΠ rcases_patt) :=
do l ← intros,
focus1 $ do
(p, gs) ← rcases_hint.continue depth l,
set_goals gs,
pure p
setup_tactic_parser
local notation `listΣ` := list_Sigma
local notation `listΠ` := list_Pi
meta def rcases_patt_parse_core
(rcases_patt_parse_list : parser (listΣ rcases_patt_inverted)) :
parser rcases_patt_inverted | x :=
((rcases_patt_inverted.one <$> ident_) <|>
(rcases_patt_inverted.many <$> brackets "⟨" "⟩"
(sep_by (tk ",") rcases_patt_parse_list))) x
meta def rcases_patt_parse_list : parser (listΣ rcases_patt_inverted) :=
with_desc "patt" $
list.cons <$> rcases_patt_parse_core rcases_patt_parse_list <*>
(tk "|" *> rcases_patt_parse_core rcases_patt_parse_list)*
meta def rcases_patt_parse : parser rcases_patt_inverted :=
with_desc "patt_list" $ rcases_patt_parse_core rcases_patt_parse_list
meta def rcases_parse_depth : parser nat :=
do o ← (tk ":" *> small_nat)?, pure $ o.get_or_else 5
precedence `?`:max
meta def rcases_parse : parser (pexpr × (listΣ (listΠ rcases_patt) ⊕ nat)) :=
do hint ← (tk "?")?,
p ← texpr,
match hint with
| none := do
ids ← (tk "with" *> rcases_patt_parse_list)?,
pure (p, sum.inl $ rcases_patt_inverted.invert_list (ids.get_or_else [default _]))
| some _ := do depth ← rcases_parse_depth, pure (p, sum.inr depth)
end
meta def rintro_parse : parser (listΠ rcases_patt ⊕ nat) :=
(tk "?" >> sum.inr <$> rcases_parse_depth) <|>
sum.inl <$> (rcases_patt_inverted.invert <$>
(brackets "(" ")" rcases_patt_parse_list <|>
(λ x, [x]) <$> rcases_patt_parse))*
meta def ext_patt := listΠ rcases_patt
meta def ext_parse : parser ext_patt :=
(rcases_patt_inverted.invert <$>
(brackets "(" ")" rcases_patt_parse_list <|>
(λ x, [x]) <$> rcases_patt_parse))*
namespace interactive
open interactive interactive.types expr
/--
The `rcases` tactic is the same as `cases`, but with more flexibility in the
`with` pattern syntax to allow for recursive case splitting. The pattern syntax
uses the following recursive grammar:
```
patt ::= (patt_list "|")* patt_list
patt_list ::= id | "_" | "⟨" (patt ",")* patt "⟩"
```
A pattern like `⟨a, b, c⟩ | ⟨d, e⟩` will do a split over the inductive datatype,
naming the first three parameters of the first constructor as `a,b,c` and the
first two of the second constructor `d,e`. If the list is not as long as the
number of arguments to the constructor or the number of constructors, the
remaining variables will be automatically named. If there are nested brackets
such as `⟨⟨a⟩, b | c⟩ | d` then these will cause more case splits as necessary.
If there are too many arguments, such as `⟨a, b, c⟩` for splitting on
`∃ x, ∃ y, p x`, then it will be treated as `⟨a, ⟨b, c⟩⟩`, splitting the last
parameter as necessary.
`rcases` also has special support for quotient types: quotient induction into Prop works like
matching on the constructor `quot.mk`.
`rcases? e` will perform case splits on `e` in the same way as `rcases e`,
but rather than accepting a pattern, it does a maximal cases and prints the
pattern that would produce this case splitting. The default maximum depth is 5,
but this can be modified with `rcases? e : n`.
-/
meta def rcases : parse rcases_parse → tactic unit
| (p, sum.inl ids) := tactic.rcases p ids
| (p, sum.inr depth) := do
patt ← tactic.rcases_hint p depth,
pe ← pp p,
trace $ ↑"snippet: rcases " ++ pe ++ " with " ++ to_fmt patt
/--
The `rintro` tactic is a combination of the `intros` tactic with `rcases` to
allow for destructuring patterns while introducing variables. See `rcases` for
a description of supported patterns. For example, `rintros (a | ⟨b, c⟩) ⟨d, e⟩`
will introduce two variables, and then do case splits on both of them producing
two subgoals, one with variables `a d e` and the other with `b c d e`.
`rintro?` will introduce and case split on variables in the same way as
`rintro`, but will also print the `rintro` invocation that would have the same
result. Like `rcases?`, `rintro? : n` allows for modifying the
depth of splitting; the default is 5.
-/
meta def rintro : parse rintro_parse → tactic unit
| (sum.inl []) := intros []
| (sum.inl l) := tactic.rintro l
| (sum.inr depth) := do
ps ← tactic.rintro_hint depth,
trace $ ↑"snippet: rintro" ++ format.join (ps.map $ λ p,
format.space ++ format.group (p.format tt))
/-- Alias for `rintro`. -/
meta def rintros := rintro
end interactive
end tactic
|
b7af278cdd5424917443ab1fc15805f756693185 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/algebra/field/opposite.lean | 2a6f100dcd73b93d611fcf9f52708d9283bdce88 | [
"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 | 558 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import algebra.field.basic
import algebra.ring.opposite
/-!
# Field structure on the multiplicative opposite
-/
variables (α : Type*)
namespace mul_opposite
instance [division_ring α] : division_ring αᵐᵒᵖ :=
{ .. mul_opposite.group_with_zero α, .. mul_opposite.ring α }
instance [field α] : field αᵐᵒᵖ :=
{ .. mul_opposite.division_ring α, .. mul_opposite.comm_ring α }
end mul_opposite
|
27ea74ab73ae2e9eed0a30f2bbe7674f75026066 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/unify_tac1.lean | ab348a9841664ec016f2272bc2fd3f00771a1547 | [
"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 | 577 | lean | open tactic
example (A : Type) (a : A) (p : A → Prop) (H : p a) : ∃ x, p x :=
by do
constructor,
tgt ← target,
t ← get_local `H >>= infer_type,
unify tgt t, -- Succeeds unifying p a =?= p ?m_1
assumption
example (A : Type) (a : A) (p : A → Prop) (H : p a) : ∃ x, p x :=
by do
econstructor,
tgt ← target,
t ← get_local `H >>= infer_type,
is_def_eq tgt t, -- Fails at p a =?= p ?m_1
assumption
example (a : nat) : true :=
by do
t1 ← to_expr ```(nat.succ a),
t2 ← to_expr ```(a + 1),
is_def_eq t1 t2, -- Succeeds
constructor
|
5fb33ccf9b606d8982147a4dd9a8dedf9d3c9588 | ee8cdbabf07f77e7be63a449b8483ce308d37218 | /lean/src/test/imo-2019-q1.lean | 9fffcef4b7586c487475aab617e398a967fec1b5 | [
"MIT",
"Apache-2.0"
] | permissive | zeta1999/miniF2F | 6d66c75d1c18152e224d07d5eed57624f731d4b7 | c1ba9629559c5273c92ec226894baa0c1ce27861 | refs/heads/main | 1,681,897,460,642 | 1,620,646,361,000 | 1,620,646,361,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 331 | lean | /-
Copyright (c) 2021 OpenAI. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kunhao Zheng
-/
import data.int.basic
example (f : ℤ → ℤ) : ( ∀ a b, f ( 2 * a ) + ( 2 * f b ) = f ( f ( a + b ) ) ↔ ( ∀ z, f z = 0 \/ ∃ c, ∀ z, f z = 2 * z + c ) ) :=
begin
sorry
end
|
f7437ad44cffc10c30e95316938747182b65e3ca | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/quandle.lean | 6e98bb487b0e94f943ca1ebc3c8554fb514cbb5b | [
"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 | 26,284 | lean | /-
Copyright (c) 2020 Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kyle Miller
-/
import algebra.hom.equiv.basic
import algebra.hom.aut
import data.zmod.defs
import tactic.group
/-!
# Racks and Quandles
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines racks and quandles, algebraic structures for sets
that bijectively act on themselves with a self-distributivity
property. If `R` is a rack and `act : R → (R ≃ R)` is the self-action,
then the self-distributivity is, equivalently, that
```
act (act x y) = act x * act y * (act x)⁻¹
```
where multiplication is composition in `R ≃ R` as a group.
Quandles are racks such that `act x x = x` for all `x`.
One example of a quandle (not yet in mathlib) is the action of a Lie
algebra on itself, defined by `act x y = Ad (exp x) y`.
Quandles and racks were independently developed by multiple
mathematicians. David Joyce introduced quandles in his thesis
[Joyce1982] to define an algebraic invariant of knot and link
complements that is analogous to the fundamental group of the
exterior, and he showed that the quandle associated to an oriented
knot is invariant up to orientation-reversed mirror image. Racks were
used by Fenn and Rourke for framed codimension-2 knots and
links in [FennRourke1992]. Unital shelves are discussed in [crans2017].
The name "rack" came from wordplay by Conway and Wraith for the "wrack
and ruin" of forgetting everything but the conjugation operation for a
group.
## Main definitions
* `shelf` is a type with a self-distributive action
* `unital_shelf` is a shelf with a left and right unit
* `rack` is a shelf whose action for each element is invertible
* `quandle` is a rack whose action for an element fixes that element
* `quandle.conj` defines a quandle of a group acting on itself by conjugation.
* `shelf_hom` is homomorphisms of shelves, racks, and quandles.
* `rack.envel_group` gives the universal group the rack maps to as a conjugation quandle.
* `rack.opp` gives the rack with the action replaced by its inverse.
## Main statements
* `rack.envel_group` is left adjoint to `quandle.conj` (`to_envel_group.map`).
The universality statements are `to_envel_group.univ` and `to_envel_group.univ_uniq`.
## Implementation notes
"Unital racks" are uninteresting (see `rack.assoc_iff_id`, `unital_shelf.assoc`), so we do not
define them.
## Notation
The following notation is localized in `quandles`:
* `x ◃ y` is `shelf.act x y`
* `x ◃⁻¹ y` is `rack.inv_act x y`
* `S →◃ S'` is `shelf_hom S S'`
Use `open_locale quandles` to use these.
## Todo
* If `g` is the Lie algebra of a Lie group `G`, then `(x ◃ y) = Ad (exp x) x` forms a quandle.
* If `X` is a symmetric space, then each point has a corresponding involution that acts on `X`,
forming a quandle.
* Alexander quandle with `a ◃ b = t * b + (1 - t) * b`, with `a` and `b` elements
of a module over `Z[t,t⁻¹]`.
* If `G` is a group, `H` a subgroup, and `z` in `H`, then there is a quandle `(G/H;z)` defined by
`yH ◃ xH = yzy⁻¹xH`. Every homogeneous quandle (i.e., a quandle `Q` whose automorphism group acts
transitively on `Q` as a set) is isomorphic to such a quandle.
There is a generalization to this arbitrary quandles in [Joyce's paper (Theorem 7.2)][Joyce1982].
## Tags
rack, quandle
-/
open mul_opposite
universes u v
/--
A *shelf* is a structure with a self-distributive binary operation.
The binary operation is regarded as a left action of the type on itself.
-/
class shelf (α : Type u) :=
(act : α → α → α)
(self_distrib : ∀ {x y z : α}, act x (act y z) = act (act x y) (act x z))
/--
A *unital shelf* is a shelf equipped with an element `1` such that, for all elements `x`,
we have both `x ◃ 1` and `1 ◃ x` equal `x`.
-/
class unital_shelf (α : Type u) extends shelf α, has_one α :=
(one_act : ∀ a : α, act 1 a = a)
(act_one : ∀ a : α, act a 1 = a)
/--
The type of homomorphisms between shelves.
This is also the notion of rack and quandle homomorphisms.
-/
@[ext]
structure shelf_hom (S₁ : Type*) (S₂ : Type*) [shelf S₁] [shelf S₂] :=
(to_fun : S₁ → S₂)
(map_act' : ∀ {x y : S₁}, to_fun (shelf.act x y) = shelf.act (to_fun x) (to_fun y))
/--
A *rack* is an automorphic set (a set with an action on itself by
bijections) that is self-distributive. It is a shelf such that each
element's action is invertible.
The notations `x ◃ y` and `x ◃⁻¹ y` denote the action and the
inverse action, respectively, and they are right associative.
-/
class rack (α : Type u) extends shelf α :=
(inv_act : α → α → α)
(left_inv : ∀ x, function.left_inverse (inv_act x) (act x))
(right_inv : ∀ x, function.right_inverse (inv_act x) (act x))
localized "infixr (name := shelf.act) ` ◃ `:65 := shelf.act" in quandles
localized "infixr (name := rack.inv_act) ` ◃⁻¹ `:65 := rack.inv_act" in quandles
localized "infixr (name := shelf_hom) ` →◃ `:25 := shelf_hom" in quandles
open_locale quandles
namespace unital_shelf
open shelf
variables {S : Type*} [unital_shelf S]
/--
A monoid is *graphic* if, for all `x` and `y`, the *graphic identity*
`(x * y) * x = x * y` holds. For a unital shelf, this graphic
identity holds.
-/
lemma act_act_self_eq (x y : S) : (x ◃ y) ◃ x = x ◃ y :=
begin
have h : (x ◃ y) ◃ x = (x ◃ y) ◃ (x ◃ 1) := by rw act_one,
rw [h, ←shelf.self_distrib, act_one],
end
lemma act_idem (x : S) : (x ◃ x) = x := by rw [←act_one x, ←shelf.self_distrib, act_one, act_one]
lemma act_self_act_eq (x y : S) : x ◃ (x ◃ y) = x ◃ y :=
begin
have h : x ◃ (x ◃ y) = (x ◃ 1) ◃ (x ◃ y) := by rw act_one,
rw [h, ←shelf.self_distrib, one_act],
end
/--
The associativity of a unital shelf comes for free.
-/
lemma assoc (x y z : S) : (x ◃ y) ◃ z = x ◃ y ◃ z :=
by rw [self_distrib, self_distrib, act_act_self_eq, act_self_act_eq]
end unital_shelf
namespace rack
variables {R : Type*} [rack R]
lemma self_distrib {x y z : R} : x ◃ (y ◃ z) = (x ◃ y) ◃ (x ◃ z) :=
shelf.self_distrib
/--
A rack acts on itself by equivalences.
-/
def act (x : R) : R ≃ R :=
{ to_fun := shelf.act x,
inv_fun := inv_act x,
left_inv := left_inv x,
right_inv := right_inv x }
@[simp] lemma act_apply (x y : R) : act x y = x ◃ y := rfl
@[simp] lemma act_symm_apply (x y : R) : (act x).symm y = x ◃⁻¹ y := rfl
@[simp] lemma inv_act_apply (x y : R) : (act x)⁻¹ y = x ◃⁻¹ y := rfl
@[simp] lemma inv_act_act_eq (x y : R) : x ◃⁻¹ x ◃ y = y := left_inv x y
@[simp] lemma act_inv_act_eq (x y : R) : x ◃ x ◃⁻¹ y = y := right_inv x y
lemma left_cancel (x : R) {y y' : R} : x ◃ y = x ◃ y' ↔ y = y' :=
by { split, apply (act x).injective, rintro rfl, refl }
lemma left_cancel_inv (x : R) {y y' : R} : x ◃⁻¹ y = x ◃⁻¹ y' ↔ y = y' :=
by { split, apply (act x).symm.injective, rintro rfl, refl }
lemma self_distrib_inv {x y z : R} : x ◃⁻¹ y ◃⁻¹ z = (x ◃⁻¹ y) ◃⁻¹ (x ◃⁻¹ z) :=
begin
rw [←left_cancel (x ◃⁻¹ y), right_inv, ←left_cancel x, right_inv, self_distrib],
repeat {rw right_inv },
end
/--
The *adjoint action* of a rack on itself is `op'`, and the adjoint
action of `x ◃ y` is the conjugate of the action of `y` by the action
of `x`. It is another way to understand the self-distributivity axiom.
This is used in the natural rack homomorphism `to_conj` from `R` to
`conj (R ≃ R)` defined by `op'`.
-/
lemma ad_conj {R : Type*} [rack R] (x y : R) :
act (x ◃ y) = act x * act y * (act x)⁻¹ :=
begin
rw [eq_mul_inv_iff_mul_eq], ext z,
apply self_distrib.symm,
end
/--
The opposite rack, swapping the roles of `◃` and `◃⁻¹`.
-/
instance opposite_rack : rack Rᵐᵒᵖ :=
{ act := λ x y, op (inv_act (unop x) (unop y)),
self_distrib := mul_opposite.rec $ λ x, mul_opposite.rec $ λ y, mul_opposite.rec $ λ z, begin
simp only [unop_op, op_inj],
exact self_distrib_inv,
end,
inv_act := λ x y, op (shelf.act (unop x) (unop y)),
left_inv := mul_opposite.rec $ λ x, mul_opposite.rec $ λ y, by simp,
right_inv := mul_opposite.rec $ λ x, mul_opposite.rec $ λ y, by simp }
@[simp] lemma op_act_op_eq {x y : R} : (op x) ◃ (op y) = op (x ◃⁻¹ y) := rfl
@[simp] lemma op_inv_act_op_eq {x y : R} : (op x) ◃⁻¹ (op y) = op (x ◃ y) := rfl
@[simp]
lemma self_act_act_eq {x y : R} : (x ◃ x) ◃ y = x ◃ y :=
by { rw [←right_inv x y, ←self_distrib] }
@[simp]
lemma self_inv_act_inv_act_eq {x y : R} : (x ◃⁻¹ x) ◃⁻¹ y = x ◃⁻¹ y :=
by { have h := @self_act_act_eq _ _ (op x) (op y), simpa using h }
@[simp]
lemma self_act_inv_act_eq {x y : R} : (x ◃ x) ◃⁻¹ y = x ◃⁻¹ y :=
by { rw ←left_cancel (x ◃ x), rw right_inv, rw self_act_act_eq, rw right_inv }
@[simp]
lemma self_inv_act_act_eq {x y : R} : (x ◃⁻¹ x) ◃ y = x ◃ y :=
by { have h := @self_act_inv_act_eq _ _ (op x) (op y), simpa using h }
lemma self_act_eq_iff_eq {x y : R} : x ◃ x = y ◃ y ↔ x = y :=
begin
split, swap, rintro rfl, refl,
intro h,
transitivity (x ◃ x) ◃⁻¹ (x ◃ x),
rw [←left_cancel (x ◃ x), right_inv, self_act_act_eq],
rw [h, ←left_cancel (y ◃ y), right_inv, self_act_act_eq],
end
lemma self_inv_act_eq_iff_eq {x y : R} : x ◃⁻¹ x = y ◃⁻¹ y ↔ x = y :=
by { have h := @self_act_eq_iff_eq _ _ (op x) (op y), simpa using h }
/--
The map `x ↦ x ◃ x` is a bijection. (This has applications for the
regular isotopy version of the Reidemeister I move for knot diagrams.)
-/
def self_apply_equiv (R : Type*) [rack R] : R ≃ R :=
{ to_fun := λ x, x ◃ x,
inv_fun := λ x, x ◃⁻¹ x,
left_inv := λ x, by simp,
right_inv := λ x, by simp }
/--
An involutory rack is one for which `rack.op R x` is an involution for every x.
-/
def is_involutory (R : Type*) [rack R] : Prop := ∀ x : R, function.involutive (shelf.act x)
lemma involutory_inv_act_eq_act {R : Type*} [rack R] (h : is_involutory R) (x y : R) :
x ◃⁻¹ y = x ◃ y :=
begin
rw [←left_cancel x, right_inv],
exact ((h x).left_inverse y).symm,
end
/--
An abelian rack is one for which the mediality axiom holds.
-/
def is_abelian (R : Type*) [rack R] : Prop :=
∀ (x y z w : R), (x ◃ y) ◃ (z ◃ w) = (x ◃ z) ◃ (y ◃ w)
/--
Associative racks are uninteresting.
-/
lemma assoc_iff_id {R : Type*} [rack R] {x y z : R} :
x ◃ y ◃ z = (x ◃ y) ◃ z ↔ x ◃ z = z :=
by { rw self_distrib, rw left_cancel }
end rack
namespace shelf_hom
variables {S₁ : Type*} {S₂ : Type*} {S₃ : Type*} [shelf S₁] [shelf S₂] [shelf S₃]
instance : has_coe_to_fun (S₁ →◃ S₂) (λ _, S₁ → S₂) := ⟨shelf_hom.to_fun⟩
@[simp] lemma to_fun_eq_coe (f : S₁ →◃ S₂) : f.to_fun = f := rfl
@[simp] lemma map_act (f : S₁ →◃ S₂) {x y : S₁} : f (x ◃ y) = f x ◃ f y := map_act' f
/-- The identity homomorphism -/
def id (S : Type*) [shelf S] : S →◃ S :=
{ to_fun := id,
map_act' := by simp }
instance inhabited (S : Type*) [shelf S] : inhabited (S →◃ S) :=
⟨id S⟩
/-- The composition of shelf homomorphisms -/
def comp (g : S₂ →◃ S₃) (f : S₁ →◃ S₂) : S₁ →◃ S₃ :=
{ to_fun := g.to_fun ∘ f.to_fun,
map_act' := by simp }
@[simp]
lemma comp_apply (g : S₂ →◃ S₃) (f : S₁ →◃ S₂) (x : S₁) :
(g.comp f) x = g (f x) := rfl
end shelf_hom
/--
A quandle is a rack such that each automorphism fixes its corresponding element.
-/
class quandle (α : Type*) extends rack α :=
(fix : ∀ {x : α}, act x x = x)
namespace quandle
open rack
variables {Q : Type*} [quandle Q]
attribute [simp] fix
@[simp]
lemma fix_inv {x : Q} : x ◃⁻¹ x = x :=
by { rw ←left_cancel x, simp }
instance opposite_quandle : quandle Qᵐᵒᵖ :=
{ fix := λ x, by { induction x using mul_opposite.rec, simp } }
/--
The conjugation quandle of a group. Each element of the group acts by
the corresponding inner automorphism.
-/
@[nolint has_nonempty_instance]
def conj (G : Type*) := G
instance conj.quandle (G : Type*) [group G] : quandle (conj G) :=
{ act := (λ x, @mul_aut.conj G _ x),
self_distrib := λ x y z, begin
dsimp only [mul_equiv.coe_to_equiv, mul_aut.conj_apply, conj],
group,
end,
inv_act := (λ x, (@mul_aut.conj G _ x).symm),
left_inv := λ x y, by { dsimp [act, conj], group },
right_inv := λ x y, by { dsimp [act, conj], group },
fix := λ x, by simp }
@[simp]
lemma conj_act_eq_conj {G : Type*} [group G] (x y : conj G) :
x ◃ y = ((x : G) * (y : G) * (x : G)⁻¹ : G) := rfl
lemma conj_swap {G : Type*} [group G] (x y : conj G) :
x ◃ y = y ↔ y ◃ x = x :=
begin
dsimp [conj] at *, split,
repeat { intro h, conv_rhs { rw eq_mul_inv_of_mul_eq (eq_mul_inv_of_mul_eq h) }, simp, },
end
/--
`conj` is functorial
-/
def conj.map {G : Type*} {H : Type*} [group G] [group H] (f : G →* H) : conj G →◃ conj H :=
{ to_fun := f,
map_act' := by simp }
instance {G : Type*} {H : Type*} [group G] [group H] : has_lift (G →* H) (conj G →◃ conj H) :=
{ lift := conj.map }
/--
The dihedral quandle. This is the conjugation quandle of the dihedral group restrict to flips.
Used for Fox n-colorings of knots.
-/
@[nolint has_nonempty_instance]
def dihedral (n : ℕ) := zmod n
/--
The operation for the dihedral quandle. It does not need to be an equivalence
because it is an involution (see `dihedral_act.inv`).
-/
def dihedral_act (n : ℕ) (a : zmod n) : zmod n → zmod n :=
λ b, 2 * a - b
lemma dihedral_act.inv (n : ℕ) (a : zmod n) : function.involutive (dihedral_act n a) :=
by { intro b, dsimp [dihedral_act], ring }
instance (n : ℕ) : quandle (dihedral n) :=
{ act := dihedral_act n,
self_distrib := λ x y z, begin
dsimp [dihedral_act], ring,
end,
inv_act := dihedral_act n,
left_inv := λ x, (dihedral_act.inv n x).left_inverse,
right_inv := λ x, (dihedral_act.inv n x).right_inverse,
fix := λ x, begin
dsimp [dihedral_act], ring,
end }
end quandle
namespace rack
/--
This is the natural rack homomorphism to the conjugation quandle of the group `R ≃ R`
that acts on the rack.
-/
def to_conj (R : Type*) [rack R] : R →◃ quandle.conj (R ≃ R) :=
{ to_fun := act,
map_act' := ad_conj }
section envel_group
/-!
### Universal enveloping group of a rack
The universal enveloping group `envel_group R` of a rack `R` is the
universal group such that every rack homomorphism `R →◃ conj G` is
induced by a unique group homomorphism `envel_group R →* G`.
For quandles, Joyce called this group `AdConj R`.
The `envel_group` functor is left adjoint to the `conj` forgetful
functor, and the way we construct the enveloping group is via a
technique that should work for left adjoints of forgetful functors in
general. It involves thinking a little about 2-categories, but the
payoff is that the map `envel_group R →* G` has a nice description.
Let's think of a group as being a one-object category. The first step
is to define `pre_envel_group`, which gives formal expressions for all
the 1-morphisms and includes the unit element, elements of `R`,
multiplication, and inverses. To introduce relations, the second step
is to define `pre_envel_group_rel'`, which gives formal expressions
for all 2-morphisms between the 1-morphisms. The 2-morphisms include
associativity, multiplication by the unit, multiplication by inverses,
compatibility with multiplication and inverses (`congr_mul` and
`congr_inv`), the axioms for an equivalence relation, and,
importantly, the relationship between conjugation and the rack action
(see `rack.ad_conj`).
None of this forms a 2-category yet, for example due to lack of
associativity of `trans`. The `pre_envel_group_rel` relation is a
`Prop`-valued version of `pre_envel_group_rel'`, and making it
`Prop`-valued essentially introduces enough 3-isomorphisms so that
every pair of compatible 2-morphisms is isomorphic. Now, while
composition in `pre_envel_group` does not strictly satisfy the category
axioms, `pre_envel_group` and `pre_envel_group_rel'` do form a weak
2-category.
Since we just want a 1-category, the last step is to quotient
`pre_envel_group` by `pre_envel_group_rel'`, and the result is the
group `envel_group`.
For a homomorphism `f : R →◃ conj G`, how does
`envel_group.map f : envel_group R →* G` work? Let's think of `G` as
being a 2-category with one object, a 1-morphism per element of `G`,
and a single 2-morphism called `eq.refl` for each 1-morphism. We
define the map using a "higher `quotient.lift`" -- not only do we
evaluate elements of `pre_envel_group` as expressions in `G` (this is
`to_envel_group.map_aux`), but we evaluate elements of
`pre_envel_group'` as expressions of 2-morphisms of `G` (this is
`to_envel_group.map_aux.well_def`). That is to say,
`to_envel_group.map_aux.well_def` recursively evaluates formal
expressions of 2-morphisms as equality proofs in `G`. Now that all
morphisms are accounted for, the map descends to a homomorphism
`envel_group R →* G`.
Note: `Type`-valued relations are not common. The fact it is
`Type`-valued is what makes `to_envel_group.map_aux.well_def` have
well-founded recursion.
-/
/--
Free generators of the enveloping group.
-/
inductive pre_envel_group (R : Type u) : Type u
| unit : pre_envel_group
| incl (x : R) : pre_envel_group
| mul (a b : pre_envel_group) : pre_envel_group
| inv (a : pre_envel_group) : pre_envel_group
instance pre_envel_group.inhabited (R : Type u) : inhabited (pre_envel_group R) :=
⟨pre_envel_group.unit⟩
open pre_envel_group
/--
Relations for the enveloping group. This is a type-valued relation because
`to_envel_group.map_aux.well_def` inducts on it to show `to_envel_group.map`
is well-defined. The relation `pre_envel_group_rel` is the `Prop`-valued version,
which is used to define `envel_group` itself.
-/
inductive pre_envel_group_rel' (R : Type u) [rack R] :
pre_envel_group R → pre_envel_group R → Type u
| refl {a : pre_envel_group R} : pre_envel_group_rel' a a
| symm {a b : pre_envel_group R} (hab : pre_envel_group_rel' a b) : pre_envel_group_rel' b a
| trans {a b c : pre_envel_group R}
(hab : pre_envel_group_rel' a b) (hbc : pre_envel_group_rel' b c) : pre_envel_group_rel' a c
| congr_mul {a b a' b' : pre_envel_group R}
(ha : pre_envel_group_rel' a a') (hb : pre_envel_group_rel' b b') :
pre_envel_group_rel' (mul a b) (mul a' b')
| congr_inv {a a' : pre_envel_group R} (ha : pre_envel_group_rel' a a') :
pre_envel_group_rel' (inv a) (inv a')
| assoc (a b c : pre_envel_group R) : pre_envel_group_rel' (mul (mul a b) c) (mul a (mul b c))
| one_mul (a : pre_envel_group R) : pre_envel_group_rel' (mul unit a) a
| mul_one (a : pre_envel_group R) : pre_envel_group_rel' (mul a unit) a
| mul_left_inv (a : pre_envel_group R) : pre_envel_group_rel' (mul (inv a) a) unit
| act_incl (x y : R) :
pre_envel_group_rel' (mul (mul (incl x) (incl y)) (inv (incl x))) (incl (x ◃ y))
instance pre_envel_group_rel'.inhabited (R : Type u) [rack R] :
inhabited (pre_envel_group_rel' R unit unit) :=
⟨pre_envel_group_rel'.refl⟩
/--
The `pre_envel_group_rel` relation as a `Prop`. Used as the relation for `pre_envel_group.setoid`.
-/
inductive pre_envel_group_rel (R : Type u) [rack R] : pre_envel_group R → pre_envel_group R → Prop
| rel {a b : pre_envel_group R} (r : pre_envel_group_rel' R a b) : pre_envel_group_rel a b
/--
A quick way to convert a `pre_envel_group_rel'` to a `pre_envel_group_rel`.
-/
lemma pre_envel_group_rel'.rel {R : Type u} [rack R] {a b : pre_envel_group R} :
pre_envel_group_rel' R a b → pre_envel_group_rel R a b :=
pre_envel_group_rel.rel
@[refl]
lemma pre_envel_group_rel.refl {R : Type u} [rack R] {a : pre_envel_group R} :
pre_envel_group_rel R a a :=
pre_envel_group_rel.rel pre_envel_group_rel'.refl
@[symm]
lemma pre_envel_group_rel.symm {R : Type u} [rack R] {a b : pre_envel_group R} :
pre_envel_group_rel R a b → pre_envel_group_rel R b a
| ⟨r⟩ := r.symm.rel
@[trans]
lemma pre_envel_group_rel.trans {R : Type u} [rack R] {a b c : pre_envel_group R} :
pre_envel_group_rel R a b → pre_envel_group_rel R b c → pre_envel_group_rel R a c
| ⟨rab⟩ ⟨rbc⟩ := (rab.trans rbc).rel
instance pre_envel_group.setoid (R : Type*) [rack R] : setoid (pre_envel_group R) :=
{ r := pre_envel_group_rel R,
iseqv := begin
split, apply pre_envel_group_rel.refl,
split, apply pre_envel_group_rel.symm,
apply pre_envel_group_rel.trans
end }
/--
The universal enveloping group for the rack R.
-/
def envel_group (R : Type*) [rack R] := quotient (pre_envel_group.setoid R)
-- Define the `group` instances in two steps so `inv` can be inferred correctly.
-- TODO: is there a non-invasive way of defining the instance directly?
instance (R : Type*) [rack R] : div_inv_monoid (envel_group R) :=
{ mul := λ a b, quotient.lift_on₂ a b
(λ a b, ⟦pre_envel_group.mul a b⟧)
(λ a b a' b' ⟨ha⟩ ⟨hb⟩,
quotient.sound (pre_envel_group_rel'.congr_mul ha hb).rel),
one := ⟦unit⟧,
inv := λ a, quotient.lift_on a
(λ a, ⟦pre_envel_group.inv a⟧)
(λ a a' ⟨ha⟩,
quotient.sound (pre_envel_group_rel'.congr_inv ha).rel),
mul_assoc := λ a b c,
quotient.induction_on₃ a b c (λ a b c, quotient.sound (pre_envel_group_rel'.assoc a b c).rel),
one_mul := λ a,
quotient.induction_on a (λ a, quotient.sound (pre_envel_group_rel'.one_mul a).rel),
mul_one := λ a,
quotient.induction_on a (λ a, quotient.sound (pre_envel_group_rel'.mul_one a).rel),}
instance (R : Type*) [rack R] : group (envel_group R) :=
{ mul_left_inv := λ a,
quotient.induction_on a (λ a, quotient.sound (pre_envel_group_rel'.mul_left_inv a).rel),
.. envel_group.div_inv_monoid _ }
instance envel_group.inhabited (R : Type*) [rack R] : inhabited (envel_group R) := ⟨1⟩
/--
The canonical homomorphism from a rack to its enveloping group.
Satisfies universal properties given by `to_envel_group.map` and `to_envel_group.univ`.
-/
def to_envel_group (R : Type*) [rack R] : R →◃ quandle.conj (envel_group R) :=
{ to_fun := λ x, ⟦incl x⟧,
map_act' := λ x y, quotient.sound (pre_envel_group_rel'.act_incl x y).symm.rel }
/--
The preliminary definition of the induced map from the enveloping group.
See `to_envel_group.map`.
-/
def to_envel_group.map_aux {R : Type*} [rack R] {G : Type*} [group G]
(f : R →◃ quandle.conj G) : pre_envel_group R → G
| unit := 1
| (incl x) := f x
| (mul a b) := to_envel_group.map_aux a * to_envel_group.map_aux b
| (inv a) := (to_envel_group.map_aux a)⁻¹
namespace to_envel_group.map_aux
open pre_envel_group_rel'
/--
Show that `to_envel_group.map_aux` sends equivalent expressions to equal terms.
-/
lemma well_def {R : Type*} [rack R] {G : Type*} [group G] (f : R →◃ quandle.conj G) :
Π {a b : pre_envel_group R}, pre_envel_group_rel' R a b →
to_envel_group.map_aux f a = to_envel_group.map_aux f b
| a b refl := rfl
| a b (symm h) := (well_def h).symm
| a b (trans hac hcb) := eq.trans (well_def hac) (well_def hcb)
| _ _ (congr_mul ha hb) := by { simp [to_envel_group.map_aux, well_def ha, well_def hb] }
| _ _ (congr_inv ha) := by { simp [to_envel_group.map_aux, well_def ha] }
| _ _ (assoc a b c) := by { apply mul_assoc }
| _ _ (one_mul a) := by { simp [to_envel_group.map_aux] }
| _ _ (mul_one a) := by { simp [to_envel_group.map_aux] }
| _ _ (mul_left_inv a) := by { simp [to_envel_group.map_aux] }
| _ _ (act_incl x y) := by { simp [to_envel_group.map_aux] }
end to_envel_group.map_aux
/--
Given a map from a rack to a group, lift it to being a map from the enveloping group.
More precisely, the `envel_group` functor is left adjoint to `quandle.conj`.
-/
def to_envel_group.map {R : Type*} [rack R] {G : Type*} [group G] :
(R →◃ quandle.conj G) ≃ (envel_group R →* G) :=
{ to_fun := λ f,
{ to_fun := λ x, quotient.lift_on x (to_envel_group.map_aux f)
(λ a b ⟨hab⟩, to_envel_group.map_aux.well_def f hab),
map_one' := begin
change quotient.lift_on ⟦rack.pre_envel_group.unit⟧ (to_envel_group.map_aux f) _ = 1,
simp [to_envel_group.map_aux],
end,
map_mul' := λ x y, quotient.induction_on₂ x y (λ x y, begin
change quotient.lift_on ⟦mul x y⟧ (to_envel_group.map_aux f) _ = _,
simp [to_envel_group.map_aux],
end) },
inv_fun := λ F, (quandle.conj.map F).comp (to_envel_group R),
left_inv := λ f, by { ext, refl },
right_inv := λ F, monoid_hom.ext $ λ x, quotient.induction_on x $ λ x, begin
induction x,
{ exact F.map_one.symm, },
{ refl, },
{ have hm : ⟦x_a.mul x_b⟧ = @has_mul.mul (envel_group R) _ ⟦x_a⟧ ⟦x_b⟧ := rfl,
rw [hm, F.map_mul, monoid_hom.map_mul, ←x_ih_a, ←x_ih_b] },
{ have hm : ⟦x_a.inv⟧ = @has_inv.inv (envel_group R) _ ⟦x_a⟧ := rfl,
rw [hm, F.map_inv, monoid_hom.map_inv, x_ih], }
end, }
/--
Given a homomorphism from a rack to a group, it factors through the enveloping group.
-/
lemma to_envel_group.univ (R : Type*) [rack R] (G : Type*) [group G]
(f : R →◃ quandle.conj G) :
(quandle.conj.map (to_envel_group.map f)).comp (to_envel_group R) = f :=
to_envel_group.map.symm_apply_apply f
/--
The homomorphism `to_envel_group.map f` is the unique map that fits into the commutative
triangle in `to_envel_group.univ`.
-/
lemma to_envel_group.univ_uniq (R : Type*) [rack R] (G : Type*) [group G]
(f : R →◃ quandle.conj G)
(g : envel_group R →* G) (h : f = (quandle.conj.map g).comp (to_envel_group R)) :
g = to_envel_group.map f :=
h.symm ▸ (to_envel_group.map.apply_symm_apply g).symm
/--
The induced group homomorphism from the enveloping group into bijections of the rack,
using `rack.to_conj`. Satisfies the property `envel_action_prop`.
This gives the rack `R` the structure of an augmented rack over `envel_group R`.
-/
def envel_action {R : Type*} [rack R] : envel_group R →* (R ≃ R) :=
to_envel_group.map (to_conj R)
@[simp]
lemma envel_action_prop {R : Type*} [rack R] (x y : R) :
envel_action (to_envel_group R x) y = x ◃ y := rfl
end envel_group
end rack
|
e6ba3f9e4f79172fd019cddb2b2cbb6ee520df5b | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/omega/int/main.lean | cc7e4d77ce504b9931b3949f8182aebf06da8ea4 | [] | 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 | 727 | lean | /-
Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Seul Baek
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.omega.prove_unsats
import Mathlib.tactic.omega.int.dnf
import Mathlib.PostPort
namespace Mathlib
/-
Main procedure for linear integer arithmetic.
-/
namespace omega
namespace int
theorem univ_close_of_unsat_clausify (m : ℕ) (p : preform) : clauses.unsat (dnf (preform.not p)) → univ_close p (fun (x : ℕ) => 0) m :=
fun (ᾰ : clauses.unsat (dnf (preform.not p))) =>
idRhs (univ_close p (fun (x : ℕ) => 0) m) (univ_close_of_valid (valid_of_unsat_not (unsat_of_clauses_unsat ᾰ)))
|
f51a8073b670c35a8a21af377d1e73b0157f8f23 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/hash_map_auto.lean | 7cdd34121264f74a3a21be9174e8f7865a9de2b4 | [] | 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 | 19,942 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Mario Carneiro
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.pnat.basic
import Mathlib.data.list.range
import Mathlib.data.array.lemmas
import Mathlib.algebra.group.default
import Mathlib.data.sigma.basic
import Mathlib.PostPort
universes u v w l u_1
namespace Mathlib
/-!
# Hash maps
Defines a hash map data structure, representing a finite key-value map
with a value type that may depend on the key type. The structure
requires a `nat`-valued hash function to associate keys to buckets.
## Main definitions
* `hash_map`: constructed with `mk_hash_map`.
## Implementation details
A hash map with key type `α` and (dependent) value type `β : α → Type*`
consists of an array of *buckets*, which are lists containing
key/value pairs for that bucket. The hash function is taken modulo `n`
to assign keys to their respective bucket. Because of this, some care
should be put into the hash function to ensure it evenly distributes
keys.
The bucket array is an `array`. These have special VM support for
in-place modification if there is only ever one reference to them. If
one takes special care to never keep references to old versions of a
hash map alive after updating it, then the hash map will be modified
in-place. In this documentation, when we say a hash map is modified
in-place, we are assuming the API is being used in this manner.
When inserting (`hash_map.insert`), if the number of stored pairs (the
*size*) is going to exceed the number of buckets, then a new hash map
is first created with double the number of buckets and everything in
the old hash map is reinserted along with the new key/value pair.
Otherwise, the bucket array is modified in-place. The amortized
running time of inserting $$n$$ elements into a hash map is $$O(n)$$.
When removing (`hash_map.erase`), the hash map is modified in-place.
The implementation does not reduce the number of buckets in the hash
map if the size gets too low.
## Tags
hash map
-/
/-- `bucket_array α β` is the underlying data type for `hash_map α β`,
an array of linked lists of key-value pairs. -/
def bucket_array (α : Type u) (β : α → Type v) (n : ℕ+) :=
array (↑n) (List (sigma fun (a : α) => β a))
/-- Make a hash_map index from a `nat` hash value and a (positive) buffer size -/
def hash_map.mk_idx (n : ℕ+) (i : ℕ) : fin ↑n := { val := i % ↑n, property := sorry }
namespace bucket_array
protected instance inhabited {α : Type u} {β : α → Type v} {n : ℕ+} :
Inhabited (bucket_array α β n) :=
{ default := mk_array ↑n [] }
/-- Read the bucket corresponding to an element -/
def read {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) {n : ℕ+} (data : bucket_array α β n)
(a : α) : List (sigma fun (a : α) => β a) :=
let bidx : fin ↑n := hash_map.mk_idx n (hash_fn a);
array.read data bidx
/-- Write the bucket corresponding to an element -/
def write {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) {n : ℕ+} (data : bucket_array α β n)
(a : α) (l : List (sigma fun (a : α) => β a)) : bucket_array α β n :=
let bidx : fin ↑n := hash_map.mk_idx n (hash_fn a);
array.write data bidx l
/-- Modify (read, apply `f`, and write) the bucket corresponding to an element -/
def modify {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) {n : ℕ+} (data : bucket_array α β n)
(a : α) (f : List (sigma fun (a : α) => β a) → List (sigma fun (a : α) => β a)) :
bucket_array α β n :=
let bidx : fin ↑n := hash_map.mk_idx n (hash_fn a);
array.write data bidx (f (array.read data bidx))
/-- The list of all key-value pairs in the bucket list -/
def as_list {α : Type u} {β : α → Type v} {n : ℕ+} (data : bucket_array α β n) :
List (sigma fun (a : α) => β a) :=
list.join (array.to_list data)
theorem mem_as_list {α : Type u} {β : α → Type v} {n : ℕ+} (data : bucket_array α β n)
{a : sigma fun (a : α) => β a} : a ∈ as_list data ↔ ∃ (i : fin ↑n), a ∈ array.read data i :=
sorry
/-- Fold a function `f` over the key-value pairs in the bucket list -/
def foldl {α : Type u} {β : α → Type v} {n : ℕ+} (data : bucket_array α β n) {δ : Type w} (d : δ)
(f : δ → (a : α) → β a → δ) : δ :=
array.foldl data d
fun (b : List (sigma fun (a : α) => β a)) (d : δ) =>
list.foldl (fun (r : δ) (a : sigma fun (a : α) => β a) => f r (sigma.fst a) (sigma.snd a)) d b
theorem foldl_eq {α : Type u} {β : α → Type v} {n : ℕ+} (data : bucket_array α β n) {δ : Type w}
(d : δ) (f : δ → (a : α) → β a → δ) :
foldl data d f =
list.foldl (fun (r : δ) (a : sigma fun (a : α) => β a) => f r (sigma.fst a) (sigma.snd a)) d
(as_list data) :=
sorry
end bucket_array
namespace hash_map
/-- Insert the pair `⟨a, b⟩` into the correct location in the bucket array
(without checking for duplication) -/
def reinsert_aux {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) {n : ℕ+}
(data : bucket_array α β n) (a : α) (b : β a) : bucket_array α β n :=
bucket_array.modify hash_fn data a fun (l : List (sigma fun (a : α) => β a)) => sigma.mk a b :: l
theorem mk_as_list {α : Type u} {β : α → Type v} (n : ℕ+) :
bucket_array.as_list (mk_array ↑n []) = [] :=
sorry
/-- Search a bucket for a key `a` and return the value -/
def find_aux {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) :
List (sigma fun (a : α) => β a) → Option (β a) :=
sorry
theorem find_aux_iff {α : Type u} {β : α → Type v} [DecidableEq α] {a : α} {b : β a}
{l : List (sigma fun (a : α) => β a)} :
list.nodup (list.map sigma.fst l) → (find_aux a l = some b ↔ sigma.mk a b ∈ l) :=
sorry
/-- Returns `tt` if the bucket `l` contains the key `a` -/
def contains_aux {α : Type u} {β : α → Type v} [DecidableEq α] (a : α)
(l : List (sigma fun (a : α) => β a)) : Bool :=
option.is_some (find_aux a l)
theorem contains_aux_iff {α : Type u} {β : α → Type v} [DecidableEq α] {a : α}
{l : List (sigma fun (a : α) => β a)} (nd : list.nodup (list.map sigma.fst l)) :
↥(contains_aux a l) ↔ a ∈ list.map sigma.fst l :=
sorry
/-- Modify a bucket to replace a value in the list. Leaves the list
unchanged if the key is not found. -/
def replace_aux {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (b : β a) :
List (sigma fun (a : α) => β a) → List (sigma fun (a : α) => β a) :=
sorry
/-- Modify a bucket to remove a key, if it exists. -/
def erase_aux {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) :
List (sigma fun (a : α) => β a) → List (sigma fun (a : α) => β a) :=
sorry
/-- The predicate `valid bkts sz` means that `bkts` satisfies the `hash_map`
invariants: There are exactly `sz` elements in it, every pair is in the
bucket determined by its key and the hash function, and no key appears
multiple times in the list. -/
structure valid {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) [DecidableEq α] {n : ℕ+}
(bkts : bucket_array α β n) (sz : ℕ)
where
len : list.length (bucket_array.as_list bkts) = sz
idx :
∀ {i : fin ↑n} {a : sigma fun (a : α) => β a},
a ∈ array.read bkts i → mk_idx n (hash_fn (sigma.fst a)) = i
nodup : ∀ (i : fin ↑n), list.nodup (list.map sigma.fst (array.read bkts i))
theorem valid.idx_enum {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) [DecidableEq α] {n : ℕ+}
{bkts : bucket_array α β n} {sz : ℕ} (v : valid hash_fn bkts sz) {i : ℕ}
{l : List (sigma fun (a : α) => β a)} (he : (i, l) ∈ list.enum (array.to_list bkts)) {a : α}
{b : β a} (hl : sigma.mk a b ∈ l) :
∃ (h : i < ↑n), mk_idx n (hash_fn a) = { val := i, property := h } :=
sorry
theorem valid.idx_enum_1 {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) [DecidableEq α] {n : ℕ+}
{bkts : bucket_array α β n} {sz : ℕ} (v : valid hash_fn bkts sz) {i : ℕ}
{l : List (sigma fun (a : α) => β a)} (he : (i, l) ∈ list.enum (array.to_list bkts)) {a : α}
{b : β a} (hl : sigma.mk a b ∈ l) : subtype.val (mk_idx n (hash_fn a)) = i :=
sorry
theorem valid.as_list_nodup {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) [DecidableEq α] {n : ℕ+}
{bkts : bucket_array α β n} {sz : ℕ} (v : valid hash_fn bkts sz) :
list.nodup (list.map sigma.fst (bucket_array.as_list bkts)) :=
sorry
theorem mk_valid {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) [DecidableEq α] (n : ℕ+) :
valid hash_fn (mk_array ↑n []) 0 :=
sorry
theorem valid.find_aux_iff {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) [DecidableEq α] {n : ℕ+}
{bkts : bucket_array α β n} {sz : ℕ} (v : valid hash_fn bkts sz) {a : α} {b : β a} :
find_aux a (bucket_array.read hash_fn bkts a) = some b ↔
sigma.mk a b ∈ bucket_array.as_list bkts :=
sorry
theorem valid.contains_aux_iff {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) [DecidableEq α]
{n : ℕ+} {bkts : bucket_array α β n} {sz : ℕ} (v : valid hash_fn bkts sz) (a : α) :
↥(contains_aux a (bucket_array.read hash_fn bkts a)) ↔
a ∈ list.map sigma.fst (bucket_array.as_list bkts) :=
sorry
theorem append_of_modify {α : Type u} {β : α → Type v} [DecidableEq α] {n : ℕ+}
{bkts : bucket_array α β n} {bidx : fin ↑n}
{f : List (sigma fun (a : α) => β a) → List (sigma fun (a : α) => β a)}
(u : List (sigma fun (a : α) => β a)) (v1 : List (sigma fun (a : α) => β a))
(v2 : List (sigma fun (a : α) => β a)) (w : List (sigma fun (a : α) => β a))
(hl : array.read bkts bidx = u ++ v1 ++ w) (hfl : f (array.read bkts bidx) = u ++ v2 ++ w) :
∃ (u' : List (sigma fun (a : α) => β a)),
∃ (w' : List (sigma fun (a : α) => β a)),
bucket_array.as_list bkts = u' ++ v1 ++ w' ∧
bucket_array.as_list bkts' = u' ++ v2 ++ w' :=
sorry
theorem valid.modify {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) [DecidableEq α] {n : ℕ+}
{bkts : bucket_array α β n} {bidx : fin ↑n}
{f : List (sigma fun (a : α) => β a) → List (sigma fun (a : α) => β a)}
(u : List (sigma fun (a : α) => β a)) (v1 : List (sigma fun (a : α) => β a))
(v2 : List (sigma fun (a : α) => β a)) (w : List (sigma fun (a : α) => β a))
(hl : array.read bkts bidx = u ++ v1 ++ w) (hfl : f (array.read bkts bidx) = u ++ v2 ++ w)
(hvnd : list.nodup (list.map sigma.fst v2))
(hal : ∀ (a : sigma fun (a : α) => β a), a ∈ v2 → mk_idx n (hash_fn (sigma.fst a)) = bidx)
(djuv : list.disjoint (list.map sigma.fst u) (list.map sigma.fst v2))
(djwv : list.disjoint (list.map sigma.fst w) (list.map sigma.fst v2)) {sz : ℕ}
(v : valid hash_fn bkts sz) :
list.length v1 ≤ sz + list.length v2 ∧
valid hash_fn bkts' (sz + list.length v2 - list.length v1) :=
sorry
theorem valid.replace_aux {α : Type u} {β : α → Type v} [DecidableEq α] (a : α) (b : β a)
(l : List (sigma fun (a : α) => β a)) :
a ∈ list.map sigma.fst l →
∃ (u : List (sigma fun (a : α) => β a)),
∃ (w : List (sigma fun (a : α) => β a)),
∃ (b' : β a),
l = u ++ [sigma.mk a b'] ++ w ∧ replace_aux a b l = u ++ [sigma.mk a b] ++ w :=
sorry
theorem valid.replace {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) [DecidableEq α] {n : ℕ+}
{bkts : bucket_array α β n} {sz : ℕ} (a : α) (b : β a)
(Hc : ↥(contains_aux a (bucket_array.read hash_fn bkts a))) (v : valid hash_fn bkts sz) :
valid hash_fn (bucket_array.modify hash_fn bkts a (replace_aux a b)) sz :=
sorry
theorem valid.insert {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) [DecidableEq α] {n : ℕ+}
{bkts : bucket_array α β n} {sz : ℕ} (a : α) (b : β a)
(Hnc : ¬↥(contains_aux a (bucket_array.read hash_fn bkts a))) (v : valid hash_fn bkts sz) :
valid hash_fn (reinsert_aux hash_fn bkts a b) (sz + 1) :=
sorry
theorem valid.erase_aux {α : Type u} {β : α → Type v} [DecidableEq α] (a : α)
(l : List (sigma fun (a : α) => β a)) :
a ∈ list.map sigma.fst l →
∃ (u : List (sigma fun (a : α) => β a)),
∃ (w : List (sigma fun (a : α) => β a)),
∃ (b : β a), l = u ++ [sigma.mk a b] ++ w ∧ erase_aux a l = u ++ [] ++ w :=
sorry
theorem valid.erase {α : Type u} {β : α → Type v} (hash_fn : α → ℕ) [DecidableEq α] {n : ℕ+}
{bkts : bucket_array α β n} {sz : ℕ} (a : α)
(Hc : ↥(contains_aux a (bucket_array.read hash_fn bkts a))) (v : valid hash_fn bkts sz) :
valid hash_fn (bucket_array.modify hash_fn bkts a (erase_aux a)) (sz - 1) :=
sorry
end hash_map
/-- A hash map data structure, representing a finite key-value map
with key type `α` and value type `β` (which may depend on `α`). -/
structure hash_map (α : Type u) [DecidableEq α] (β : α → Type v) where
hash_fn : α → ℕ
size : ℕ
nbuckets : ℕ+
buckets : bucket_array α β nbuckets
is_valid : hash_map.valid hash_fn buckets size
/-- Construct an empty hash map with buffer size `nbuckets` (default 8). -/
def mk_hash_map {α : Type u} [DecidableEq α] {β : α → Type v} (hash_fn : α → ℕ)
(nbuckets : optParam ℕ (bit0 (bit0 (bit0 1)))) : hash_map α β :=
let n : optParam ℕ (bit0 (bit0 (bit0 1))) := ite (nbuckets = 0) (bit0 (bit0 (bit0 1))) nbuckets;
let nz : n > 0 := sorry;
hash_map.mk hash_fn 0 { val := n, property := nz } (mk_array n []) sorry
namespace hash_map
/-- Return the value corresponding to a key, or `none` if not found -/
def find {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a : α) : Option (β a) :=
find_aux a (bucket_array.read (hash_fn m) (buckets m) a)
/-- Return `tt` if the key exists in the map -/
def contains {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a : α) : Bool :=
option.is_some (find m a)
protected instance has_mem {α : Type u} {β : α → Type v} [DecidableEq α] :
has_mem α (hash_map α β) :=
has_mem.mk fun (a : α) (m : hash_map α β) => ↥(contains m a)
/-- Fold a function over the key-value pairs in the map -/
def fold {α : Type u} {β : α → Type v} [DecidableEq α] {δ : Type w} (m : hash_map α β) (d : δ)
(f : δ → (a : α) → β a → δ) : δ :=
bucket_array.foldl (buckets m) d f
/-- The list of key-value pairs in the map -/
def entries {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) :
List (sigma fun (a : α) => β a) :=
bucket_array.as_list (buckets m)
/-- The list of keys in the map -/
def keys {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) : List α :=
list.map sigma.fst (entries m)
theorem find_iff {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a : α)
(b : β a) : find m a = some b ↔ sigma.mk a b ∈ entries m :=
valid.find_aux_iff (hash_fn m) (is_valid m)
theorem contains_iff {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a : α) :
↥(contains m a) ↔ a ∈ keys m :=
valid.contains_aux_iff (hash_fn m) (is_valid m) a
theorem entries_empty {α : Type u} {β : α → Type v} [DecidableEq α] (hash_fn : α → ℕ)
(n : optParam ℕ (bit0 (bit0 (bit0 1)))) : entries (mk_hash_map hash_fn n) = [] :=
mk_as_list (nbuckets (mk_hash_map hash_fn n))
theorem keys_empty {α : Type u} {β : α → Type v} [DecidableEq α] (hash_fn : α → ℕ)
(n : optParam ℕ (bit0 (bit0 (bit0 1)))) : keys (mk_hash_map hash_fn n) = [] :=
sorry
theorem find_empty {α : Type u} {β : α → Type v} [DecidableEq α] (hash_fn : α → ℕ)
(n : optParam ℕ (bit0 (bit0 (bit0 1)))) (a : α) : find (mk_hash_map hash_fn n) a = none :=
sorry
theorem not_contains_empty {α : Type u} {β : α → Type v} [DecidableEq α] (hash_fn : α → ℕ)
(n : optParam ℕ (bit0 (bit0 (bit0 1)))) (a : α) : ¬↥(contains (mk_hash_map hash_fn n) a) :=
sorry
theorem insert_lemma {α : Type u} {β : α → Type v} [DecidableEq α] (hash_fn : α → ℕ) {n : ℕ+}
{n' : ℕ+} {bkts : bucket_array α β n} {sz : ℕ} (v : valid hash_fn bkts sz) :
valid hash_fn (bucket_array.foldl bkts (mk_array ↑n' []) (reinsert_aux hash_fn)) sz :=
sorry
/-- Insert a key-value pair into the map. (Modifies `m` in-place when applicable) -/
def insert {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a : α) (b : β a) :
hash_map α β :=
sorry
theorem mem_insert {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a : α)
(b : β a) (a' : α) (b' : β a') :
sigma.mk a' b' ∈ entries (insert m a b) ↔ ite (a = a') (b == b') (sigma.mk a' b' ∈ entries m) :=
sorry
theorem find_insert_eq {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a : α)
(b : β a) : find (insert m a b) a = some b :=
iff.mpr (find_iff (insert m a b) a b)
(iff.mpr (mem_insert m a b a b)
(eq.mpr
(id (Eq._oldrec (Eq.refl (ite (a = a) (b == b) (sigma.mk a b ∈ entries m))) (if_pos rfl)))
(HEq.refl b)))
theorem find_insert_ne {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a : α)
(a' : α) (b : β a) (h : a ≠ a') : find (insert m a b) a' = find m a' :=
sorry
theorem find_insert {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a' : α)
(a : α) (b : β a) :
find (insert m a b) a' =
dite (a = a') (fun (h : a = a') => some (eq.rec_on h b)) fun (h : ¬a = a') => find m a' :=
sorry
/-- Insert a list of key-value pairs into the map. (Modifies `m` in-place when applicable) -/
def insert_all {α : Type u} {β : α → Type v} [DecidableEq α] (l : List (sigma fun (a : α) => β a))
(m : hash_map α β) : hash_map α β :=
list.foldl (fun (m : hash_map α β) (_x : sigma fun (a : α) => β a) => sorry) m l
/-- Construct a hash map from a list of key-value pairs. -/
def of_list {α : Type u} {β : α → Type v} [DecidableEq α] (l : List (sigma fun (a : α) => β a))
(hash_fn : α → ℕ) : hash_map α β :=
insert_all l (mk_hash_map hash_fn (bit0 1 * list.length l))
/-- Remove a key from the map. (Modifies `m` in-place when applicable) -/
def erase {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a : α) : hash_map α β :=
sorry
theorem mem_erase {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a : α) (a' : α)
(b' : β a') : sigma.mk a' b' ∈ entries (erase m a) ↔ a ≠ a' ∧ sigma.mk a' b' ∈ entries m :=
sorry
theorem find_erase_eq {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a : α) :
find (erase m a) a = none :=
sorry
theorem find_erase_ne {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a : α)
(a' : α) (h : a ≠ a') : find (erase m a) a' = find m a' :=
sorry
theorem find_erase {α : Type u} {β : α → Type v} [DecidableEq α] (m : hash_map α β) (a' : α)
(a : α) : find (erase m a) a' = ite (a = a') none (find m a') :=
sorry
protected instance has_to_string {α : Type u} {β : α → Type v} [DecidableEq α] [has_to_string α]
[(a : α) → has_to_string (β a)] : has_to_string (hash_map α β) :=
has_to_string.mk to_string
/-- `hash_map` with key type `nat` and value type that may vary. -/
protected instance inhabited {β : ℕ → Type u_1} : Inhabited (hash_map ℕ β) :=
{ default := mk_hash_map id }
end Mathlib |
7dc5fdb8a9707d2aad5d22d8c730fc7b405b0058 | 37da0369b6c03e380e057bf680d81e6c9fdf9219 | /hott/init/funext.hlean | 4b5671d30a14fcd2bf3537d3f3f6ccc9d710144e | [
"Apache-2.0"
] | permissive | kodyvajjha/lean2 | 72b120d95c3a1d77f54433fa90c9810e14a931a4 | 227fcad22ab2bc27bb7471be7911075d101ba3f9 | refs/heads/master | 1,627,157,512,295 | 1,501,855,676,000 | 1,504,809,427,000 | 109,317,326 | 0 | 0 | null | 1,509,839,253,000 | 1,509,655,713,000 | C++ | UTF-8 | Lean | false | false | 12,783 | hlean | /-
Copyright (c) 2014 Jakob von Raumer. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jakob von Raumer, Floris van Doorn
Ported from Coq HoTT
-/
prelude
import .trunc .equiv .ua
open eq is_trunc sigma function is_equiv equiv prod unit prod.ops lift
/-
We now prove that funext follows from a couple of weaker-looking forms
of function extensionality.
This proof is originally due to Voevodsky; it has since been simplified
by Peter Lumsdaine and Michael Shulman.
-/
definition funext.{l k} :=
Π ⦃A : Type.{l}⦄ {P : A → Type.{k}} (f g : Π x, P x), is_equiv (@apd10 A P f g)
-- Naive funext is the simple assertion that pointwise equal functions are equal.
definition naive_funext :=
Π ⦃A : Type⦄ {P : A → Type} (f g : Πx, P x), (f ~ g) → f = g
-- Weak funext says that a product of contractible types is contractible.
definition weak_funext :=
Π ⦃A : Type⦄ (P : A → Type) [H: Πx, is_contr (P x)], is_contr (Πx, P x)
definition weak_funext_of_naive_funext : naive_funext → weak_funext :=
(λ nf A P (Pc : Πx, is_contr (P x)),
let c := λx, center (P x) in
is_contr.mk c (λ f,
have eq' : (λx, center (P x)) ~ f,
from (λx, center_eq (f x)),
have eq : (λx, center (P x)) = f,
from nf A P (λx, center (P x)) f eq',
eq
)
)
/-
The less obvious direction is that weak_funext implies funext
(and hence all three are logically equivalent). The point is that under weak
funext, the space of "pointwise homotopies" has the same universal property as
the space of paths.
-/
section
universe variables l k
parameters [wf : weak_funext.{l k}] {A : Type.{l}} {B : A → Type.{k}} (f : Π x, B x)
definition is_contr_sigma_homotopy : is_contr (Σ (g : Π x, B x), f ~ g) :=
is_contr.mk (sigma.mk f (homotopy.refl f))
(λ dp, sigma.rec_on dp
(λ (g : Π x, B x) (h : f ~ g),
let r := λ (k : Π x, Σ y, f x = y),
@sigma.mk _ (λg, f ~ g)
(λx, pr1 (k x)) (λx, pr2 (k x)) in
let s := λ g h x, @sigma.mk _ (λy, f x = y) (g x) (h x) in
have t1 : Πx, is_contr (Σ y, f x = y),
from (λx, !is_contr_sigma_eq),
have t2 : is_contr (Πx, Σ y, f x = y),
from !wf,
have t3 : (λ x, @sigma.mk _ (λ y, f x = y) (f x) idp) = s g h,
from @eq_of_is_contr (Π x, Σ y, f x = y) t2 _ _,
have t4 : r (λ x, sigma.mk (f x) idp) = r (s g h),
from ap r t3,
have endt : sigma.mk f (homotopy.refl f) = sigma.mk g h,
from t4,
endt
)
)
local attribute is_contr_sigma_homotopy [instance]
parameters (Q : Π g (h : f ~ g), Type) (d : Q f (homotopy.refl f))
definition homotopy_ind (g : Πx, B x) (h : f ~ g) : Q g h :=
@transport _ (λ gh, Q (pr1 gh) (pr2 gh)) (sigma.mk f (homotopy.refl f)) (sigma.mk g h)
(@eq_of_is_contr _ is_contr_sigma_homotopy _ _) d
local attribute weak_funext [reducible]
local attribute homotopy_ind [reducible]
definition homotopy_ind_comp : homotopy_ind f (homotopy.refl f) = d :=
(@prop_eq_of_is_contr _ _ _ _ !eq_of_is_contr idp)⁻¹ ▸ idp
end
/- Now the proof is fairly easy; we can just use the same induction principle on both sides. -/
section
universe variables l k
local attribute weak_funext [reducible]
theorem funext_of_weak_funext (wf : weak_funext.{l k}) : funext.{l k} :=
λ A B f g,
let eq_to_f := (λ g' x, f = g') in
let sim2path := homotopy_ind f eq_to_f idp in
have t1 : sim2path f (homotopy.refl f) = idp,
proof homotopy_ind_comp f eq_to_f idp qed,
have t2 : apd10 (sim2path f (homotopy.refl f)) = (homotopy.refl f),
proof ap apd10 t1 qed,
have left_inv : apd10 ∘ (sim2path g) ~ id,
proof (homotopy_ind f (λ g' x, apd10 (sim2path g' x) = x) t2) g qed,
have right_inv : (sim2path g) ∘ apd10 ~ id,
from (λ h, eq.rec_on h (homotopy_ind_comp f _ idp)),
is_equiv.adjointify apd10 (sim2path g) left_inv right_inv
definition funext_from_naive_funext : naive_funext → funext :=
compose funext_of_weak_funext weak_funext_of_naive_funext
end
section
universe variables l
private theorem ua_isequiv_postcompose {A B : Type.{l}} {C : Type}
{w : A → B} [H0 : is_equiv w] : is_equiv (@compose C A B w) :=
let w' := equiv.mk w H0 in
let eqinv : A = B := ((@is_equiv.inv _ _ _ (univalence A B)) w') in
let eq' := equiv_of_eq eqinv in
is_equiv.adjointify (@compose C A B w)
(@compose C B A (is_equiv.inv w))
(λ (x : C → B),
have eqretr : eq' = w',
from (@right_inv _ _ (@equiv_of_eq A B) (univalence A B) w'),
have invs_eq : (to_fun eq')⁻¹ = (to_fun w')⁻¹,
from inv_eq eq' w' eqretr,
have eqfin1 : Π(p : A = B), (to_fun (equiv_of_eq p)) ∘ ((to_fun (equiv_of_eq p))⁻¹ ∘ x) = x,
by intro p; induction p; reflexivity,
have eqfin : (to_fun eq') ∘ ((to_fun eq')⁻¹ ∘ x) = x,
from eqfin1 eqinv,
have eqfin' : (to_fun w') ∘ ((to_fun eq')⁻¹ ∘ x) = x,
from ap (λu, u ∘ _) eqretr⁻¹ ⬝ eqfin,
show (to_fun w') ∘ ((to_fun w')⁻¹ ∘ x) = x,
from ap (λu, _ ∘ (u ∘ _)) invs_eq⁻¹ ⬝ eqfin'
)
(λ (x : C → A),
have eqretr : eq' = w',
from (@right_inv _ _ (@equiv_of_eq A B) (univalence A B) w'),
have invs_eq : (to_fun eq')⁻¹ = (to_fun w')⁻¹,
from inv_eq eq' w' eqretr,
have eqfin1 : Π(p : A = B), (to_fun (equiv_of_eq p))⁻¹ ∘ ((to_fun (equiv_of_eq p)) ∘ x) = x,
by intro p; induction p; reflexivity,
have eqfin : (to_fun eq')⁻¹ ∘ ((to_fun eq') ∘ x) = x,
from eqfin1 eqinv,
have eqfin' : (to_fun eq')⁻¹ ∘ ((to_fun w') ∘ x) = x,
from ap (λu, _ ∘ (u ∘ _)) eqretr⁻¹ ⬝ eqfin,
show (to_fun w')⁻¹ ∘ ((to_fun w') ∘ x) = x,
from ap (λu, u ∘ _) invs_eq⁻¹ ⬝ eqfin'
)
-- We are ready to prove functional extensionality,
-- starting with the naive non-dependent version.
private definition diagonal [reducible] (B : Type) : Type
:= Σ xy : B × B, pr₁ xy = pr₂ xy
private definition isequiv_src_compose {A B : Type}
: @is_equiv (A → diagonal B)
(A → B)
(compose (pr₁ ∘ pr1)) :=
@ua_isequiv_postcompose _ _ _ (pr₁ ∘ pr1)
(is_equiv.adjointify (pr₁ ∘ pr1)
(λ x, sigma.mk (x , x) idp) (λx, idp)
(λ x, sigma.rec_on x
(λ xy, prod.rec_on xy
(λ b c p, eq.rec_on p idp))))
private definition isequiv_tgt_compose {A B : Type}
: is_equiv (compose (pr₂ ∘ pr1) : (A → diagonal B) → (A → B)) :=
begin
refine @ua_isequiv_postcompose _ _ _ (pr2 ∘ pr1) _,
fapply adjointify,
{ intro b, exact ⟨(b, b), idp⟩},
{ intro b, reflexivity},
{ intro a, induction a with q p, induction q, esimp at *, induction p, reflexivity}
end
theorem nondep_funext_from_ua {A : Type} {B : Type}
: Π {f g : A → B}, f ~ g → f = g :=
(λ (f g : A → B) (p : f ~ g),
let d := λ (x : A), @sigma.mk (B × B) (λ (xy : B × B), xy.1 = xy.2) (f x , f x) (eq.refl (f x, f x).1) in
let e := λ (x : A), @sigma.mk (B × B) (λ (xy : B × B), xy.1 = xy.2) (f x , g x) (p x) in
let precomp1 := compose (pr₁ ∘ sigma.pr1) in
have equiv1 : is_equiv precomp1,
from @isequiv_src_compose A B,
have equiv2 : Π (x y : A → diagonal B), is_equiv (ap precomp1),
from is_equiv.is_equiv_ap precomp1,
have H' : Π (x y : A → diagonal B), pr₁ ∘ pr1 ∘ x = pr₁ ∘ pr1 ∘ y → x = y,
from (λ x y, is_equiv.inv (ap precomp1)),
have eq2 : pr₁ ∘ pr1 ∘ d = pr₁ ∘ pr1 ∘ e,
from idp,
have eq0 : d = e,
from H' d e eq2,
have eq1 : (pr₂ ∘ pr1) ∘ d = (pr₂ ∘ pr1) ∘ e,
from ap _ eq0,
eq1
)
end
-- Now we use this to prove weak funext, which as we know
-- implies (with dependent eta) also the strong dependent funext.
theorem weak_funext_of_ua : weak_funext :=
(λ (A : Type) (P : A → Type) allcontr,
let U := (λ (x : A), lift unit) in
have pequiv : Π (x : A), P x ≃ unit,
from (λ x, @equiv_unit_of_is_contr (P x) (allcontr x)),
have psim : Π (x : A), P x = U x,
from (λ x, eq_of_equiv_lift (pequiv x)),
have p : P = U,
from @nondep_funext_from_ua A Type P U psim,
have tU' : is_contr (A → lift unit),
from is_contr.mk (λ x, up ⋆)
(λ f, nondep_funext_from_ua (λa, by induction (f a) with u;induction u;reflexivity)),
have tU : is_contr (Π x, U x),
from tU',
have tlast : is_contr (Πx, P x),
from p⁻¹ ▸ tU,
tlast)
-- we have proven function extensionality from the univalence axiom
definition funext_of_ua : funext :=
funext_of_weak_funext (@weak_funext_of_ua)
/-
We still take funext as an axiom, so that when you write "print axioms foo", you can see whether
it uses only function extensionality, and not also univalence.
-/
axiom function_extensionality : funext
variables {A : Type} {P : A → Type} {f g : Π x, P x}
namespace funext
theorem is_equiv_apdt [instance] (f g : Π x, P x) : is_equiv (@apd10 A P f g) :=
function_extensionality f g
end funext
open funext
namespace eq
definition eq_equiv_homotopy : (f = g) ≃ (f ~ g) :=
equiv.mk apd10 _
definition eq_of_homotopy [reducible] : f ~ g → f = g :=
(@apd10 A P f g)⁻¹
definition apd10_eq_of_homotopy (p : f ~ g) : apd10 (eq_of_homotopy p) = p :=
right_inv apd10 p
definition eq_of_homotopy_apd10 (p : f = g) : eq_of_homotopy (apd10 p) = p :=
left_inv apd10 p
definition eq_of_homotopy_idp (f : Π x, P x) : eq_of_homotopy (λx : A, idpath (f x)) = idpath f :=
is_equiv.left_inv apd10 idp
definition naive_funext_of_ua : naive_funext :=
λ A P f g h, eq_of_homotopy h
protected definition homotopy.rec_on [recursor] {Q : (f ~ g) → Type} (p : f ~ g)
(H : Π(q : f = g), Q (apd10 q)) : Q p :=
right_inv apd10 p ▸ H (eq_of_homotopy p)
protected definition homotopy.rec_on_idp [recursor] {Q : Π{g}, (f ~ g) → Type} {g : Π x, P x}
(p : f ~ g) (H : Q (homotopy.refl f)) : Q p :=
homotopy.rec_on p (λq, eq.rec_on q H)
protected definition homotopy.rec_on' {f f' : Πa, P a} {Q : (f ~ f') → (f = f') → Type}
(p : f ~ f') (H : Π(q : f = f'), Q (apd10 q) q) : Q p (eq_of_homotopy p) :=
begin
refine homotopy.rec_on p _,
intro q, exact (left_inv (apd10) q)⁻¹ ▸ H q
end
protected definition homotopy.rec_on_idp' {f : Πa, P a} {Q : Π{g}, (f ~ g) → (f = g) → Type}
{g : Πa, P a} (p : f ~ g) (H : Q (homotopy.refl f) idp) : Q p (eq_of_homotopy p) :=
begin
refine homotopy.rec_on' p _, intro q, induction q, exact H
end
protected definition homotopy.rec_on_idp_left {A : Type} {P : A → Type} {g : Πa, P a}
{Q : Πf, (f ~ g) → Type} {f : Π x, P x}
(p : f ~ g) (H : Q g (homotopy.refl g)) : Q f p :=
begin
induction p using homotopy.rec_on, induction q, exact H
end
definition homotopy.rec_idp [recursor] {A : Type} {P : A → Type} {f : Πa, P a}
(Q : Π{g}, (f ~ g) → Type) (H : Q (homotopy.refl f)) {g : Π x, P x} (p : f ~ g) : Q p :=
homotopy.rec_on_idp p H
definition homotopy_rec_on_apd10 {A : Type} {P : A → Type} {f g : Πa, P a}
(Q : f ~ g → Type) (H : Π(q : f = g), Q (apd10 q)) (p : f = g) :
homotopy.rec_on (apd10 p) H = H p :=
begin
unfold [homotopy.rec_on],
refine ap (λp, p ▸ _) !adj ⬝ _,
refine !tr_compose⁻¹ ⬝ _,
apply apdt
end
definition homotopy_rec_idp_refl {A : Type} {P : A → Type} {f : Πa, P a}
(Q : Π{g}, f ~ g → Type) (H : Q homotopy.rfl) :
homotopy.rec_idp @Q H homotopy.rfl = H :=
!homotopy_rec_on_apd10
definition eq_of_homotopy_inv {f g : Π x, P x} (H : f ~ g)
: eq_of_homotopy (λx, (H x)⁻¹) = (eq_of_homotopy H)⁻¹ :=
begin
apply homotopy.rec_on_idp H,
rewrite [+eq_of_homotopy_idp]
end
definition eq_of_homotopy_con {f g h : Π x, P x} (H1 : f ~ g) (H2 : g ~ h)
: eq_of_homotopy (λx, H1 x ⬝ H2 x) = eq_of_homotopy H1 ⬝ eq_of_homotopy H2 :=
begin
apply homotopy.rec_on_idp H1,
apply homotopy.rec_on_idp H2,
rewrite [+eq_of_homotopy_idp]
end
definition compose_eq_of_homotopy {A B C : Type} (g : B → C) {f f' : A → B} (H : f ~ f') :
ap (λf, g ∘ f) (eq_of_homotopy H) = eq_of_homotopy (hwhisker_left g H) :=
begin
refine homotopy.rec_on_idp' H _, exact !eq_of_homotopy_idp⁻¹
end
end eq
|
344cce0c70aa18d951dbb5d4e3fbf513d379f1c6 | 4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d | /stage0/src/Lean/Widget/InteractiveDiagnostic.lean | 6bd29b89037927bb213cca0a7c20704ac7c61a3b | [
"Apache-2.0"
] | permissive | subfish-zhou/leanprover-zh_CN.github.io | 30b9fba9bd790720bd95764e61ae796697d2f603 | 8b2985d4a3d458ceda9361ac454c28168d920d3f | refs/heads/master | 1,689,709,967,820 | 1,632,503,056,000 | 1,632,503,056,000 | 409,962,097 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,038 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Wojciech Nawrocki
-/
import Lean.Data.Lsp
import Lean.Message
import Lean.Elab.InfoTree
import Lean.PrettyPrinter
import Lean.Server.Utils
import Lean.Server.Rpc.Basic
import Lean.Widget.TaggedText
import Lean.Widget.InteractiveCode
import Lean.Widget.InteractiveGoal
namespace Lean.Widget
open Lsp Server
deriving instance RpcEncoding with { withRef := true } for MessageData
inductive MsgEmbed where
| expr : CodeWithInfos → MsgEmbed
| goal : InteractiveGoal → MsgEmbed
| lazyTrace : Nat → Name → WithRpcRef MessageData → MsgEmbed
deriving Inhabited
namespace MsgEmbed
-- TODO(WN): `deriving RpcEncoding` for `inductive` to replace the following hack
@[reducible]
def rpcPacketFor {β : outParam Type} (α : Type) [RpcEncoding α β] := β
private inductive RpcEncodingPacket where
| expr : TaggedText (rpcPacketFor CodeToken) → RpcEncodingPacket
| goal : rpcPacketFor InteractiveGoal → RpcEncodingPacket
| lazyTrace : Nat → Name → Lsp.RpcRef → RpcEncodingPacket
deriving Inhabited, FromJson, ToJson
instance : RpcEncoding MsgEmbed RpcEncodingPacket where
rpcEncode a := match a with
| expr t => return RpcEncodingPacket.expr (← rpcEncode t)
| goal g => return RpcEncodingPacket.goal (← rpcEncode g)
| lazyTrace col n t => return RpcEncodingPacket.lazyTrace col n (← rpcEncode t)
rpcDecode a := match a with
| RpcEncodingPacket.expr t => return expr (← rpcDecode t)
| RpcEncodingPacket.goal g => return goal (← rpcDecode g)
| RpcEncodingPacket.lazyTrace col n t => return lazyTrace col n (← rpcDecode t)
end MsgEmbed
/-- We embed objects in LSP diagnostics by storing them in the tag of an empty subtree (`text ""`).
In other words, we terminate the `MsgEmbed`-tagged tree at embedded objects and instead store
the pretty-printed embed (which can itself be a `TaggedText`) in the tag. -/
abbrev InteractiveDiagnostic := Lsp.DiagnosticWith (TaggedText MsgEmbed)
namespace InteractiveDiagnostic
open Lsp
private abbrev RpcEncodingPacket := Lsp.DiagnosticWith (TaggedText MsgEmbed.RpcEncodingPacket)
instance : RpcEncoding InteractiveDiagnostic RpcEncodingPacket where
rpcEncode a := return { a with message := ← rpcEncode a.message }
rpcDecode a := return { a with message := ← rpcDecode a.message }
end InteractiveDiagnostic
namespace InteractiveDiagnostic
open MsgEmbed
def toDiagnostic (diag : InteractiveDiagnostic) : Lsp.Diagnostic :=
{ diag with message := prettyTt diag.message }
where
prettyTt (tt : TaggedText MsgEmbed) : String :=
let tt : TaggedText MsgEmbed := tt.rewrite fun
| expr tt, _ => TaggedText.text tt.stripTags
| goal g, _ => TaggedText.text (toString g.pretty)
| lazyTrace _ _ _, subTt => subTt
tt.stripTags
end InteractiveDiagnostic
private def mkPPContext (nCtx : NamingContext) (ctx : MessageDataContext) : PPContext := {
env := ctx.env, mctx := ctx.mctx, lctx := ctx.lctx, opts := ctx.opts,
currNamespace := nCtx.currNamespace, openDecls := nCtx.openDecls
}
private inductive EmbedFmt
/- Tags denote `Info` objects. -/
| expr (ctx : Elab.ContextInfo) (lctx : LocalContext) (infos : Std.RBMap Nat Elab.Info compare)
| goal (ctx : Elab.ContextInfo) (lctx : LocalContext) (g : MVarId)
/- Some messages (in particular, traces) are too costly to print eagerly. Instead, we allow
the user to expand sub-traces interactively. -/
| lazyTrace (nCtx : NamingContext) (ctx? : Option MessageDataContext) (cls : Name) (m : MessageData)
/- Ignore any tags in this subtree. -/
| ignoreTags
deriving Inhabited
private abbrev MsgFmtM := StateT (Array EmbedFmt) IO
open MessageData in
/-- We first build a `Nat`-tagged `Format` with the most shallow tag, if any,
in every branch indexing into the array of embedded objects. -/
private partial def msgToInteractiveAux (msgData : MessageData) : IO (Format × Array EmbedFmt) :=
go { currNamespace := Name.anonymous, openDecls := [] } none msgData #[]
where
pushEmbed (e : EmbedFmt) : MsgFmtM Nat :=
modifyGet fun es => (es.size, es.push e)
withIgnoreTags (x : MsgFmtM Format) : MsgFmtM Format := do
let fmt ← x
let t ← pushEmbed EmbedFmt.ignoreTags
return Format.tag t fmt
go : NamingContext → Option MessageDataContext → MessageData → MsgFmtM Format
| _, _, ofFormat fmt => withIgnoreTags fmt
| _, _, ofLevel u => format u
| _, _, ofName n => format n
| nCtx, some ctx, ofSyntax s => withIgnoreTags (ppTerm (mkPPContext nCtx ctx) s) -- HACK: might not be a term
| _, none, ofSyntax s => withIgnoreTags s.formatStx
| _, none, ofExpr e => format (toString e)
| nCtx, some ctx, ofExpr e => do
let ci : Elab.ContextInfo := {
env := ctx.env
mctx := ctx.mctx
fileMap := arbitrary
options := ctx.opts
currNamespace := nCtx.currNamespace
openDecls := nCtx.openDecls
}
let (fmt, infos) ← ci.runMetaM ctx.lctx (formatInfos e)
let t ← pushEmbed <| EmbedFmt.expr ci ctx.lctx infos
return Format.tag t fmt
| _, none, ofGoal mvarId => pure $ "goal " ++ format (mkMVar mvarId)
| nCtx, some ctx, ofGoal mvarId => withIgnoreTags <| ppGoal (mkPPContext nCtx ctx) mvarId
| nCtx, _, withContext ctx d => go nCtx ctx d
| _, ctx, withNamingContext nCtx d => go nCtx ctx d
| nCtx, ctx, tagged t d => do
-- We postfix trace contexts with `_traceCtx` in order to detect them in messages.
if let Name.str cls "_traceCtx" _ := t then
let f ← pushEmbed <| EmbedFmt.lazyTrace nCtx ctx cls d
Format.tag f s!"[{cls}] (trace hidden)"
else
go nCtx ctx d
| nCtx, ctx, nest n d => Format.nest n <$> go nCtx ctx d
| nCtx, ctx, compose d₁ d₂ => do let d₁ ← go nCtx ctx d₁; let d₂ ← go nCtx ctx d₂; pure $ d₁ ++ d₂
| nCtx, ctx, group d => Format.group <$> go nCtx ctx d
| nCtx, ctx, node ds => Format.nest 2 <$> ds.foldlM (fun r d => do let d ← go nCtx ctx d; pure $ r ++ Format.line ++ d) Format.nil
partial def msgToInteractive (msgData : MessageData) (indent : Nat := 0) : IO (TaggedText MsgEmbed) := do
let (fmt, embeds) ← msgToInteractiveAux msgData
let tt := TaggedText.prettyTagged fmt indent
/- Here we rewrite a `TaggedText Nat` corresponding to a whole `MessageData` into one where
the tags are `TaggedText MsgEmbed`s corresponding to embedded objects with their subtree
empty (`text ""`). In other words, we terminate the `MsgEmbed`-tagged -tree at embedded objects
and store the pretty-printed embed (which can itself be a `TaggedText`) in the tag. -/
tt.rewriteM fun (n, col) subTt =>
match embeds.get! n with
| EmbedFmt.expr ctx lctx infos =>
let subTt' := tagExprInfos ctx lctx infos subTt
TaggedText.tag (MsgEmbed.expr subTt') (TaggedText.text subTt.stripTags)
| EmbedFmt.goal ctx lctx g =>
-- TODO(WN): use InteractiveGoal types here
unreachable!
| EmbedFmt.lazyTrace nCtx ctx? cls m =>
let msg :=
match ctx? with
| some ctx => MessageData.withNamingContext nCtx <| MessageData.withContext ctx m
| none => MessageData.withNamingContext nCtx m
TaggedText.tag (MsgEmbed.lazyTrace col cls ⟨msg⟩) (TaggedText.text subTt.stripTags)
| EmbedFmt.ignoreTags => TaggedText.text subTt.stripTags
/-- Transform a Lean Message concerning the given text into an LSP Diagnostic. -/
def msgToInteractiveDiagnostic (text : FileMap) (m : Message) : IO InteractiveDiagnostic := do
let low : Lsp.Position := text.leanPosToLspPos m.pos
let fullHigh := text.leanPosToLspPos <| m.endPos.getD m.pos
let high : Lsp.Position := match m.endPos with
| some endPos =>
/-
Truncate messages that are more than one line long.
This is a workaround to avoid big blocks of "red squiggly lines" on VS Code.
TODO: should it be a parameter?
-/
let endPos := if endPos.line > m.pos.line then { line := m.pos.line + 1, column := 0 } else endPos
text.leanPosToLspPos endPos
| none => low
let range : Range := ⟨low, high⟩
let fullRange : Range := ⟨low, fullHigh⟩
let severity := match m.severity with
| MessageSeverity.information => DiagnosticSeverity.information
| MessageSeverity.warning => DiagnosticSeverity.warning
| MessageSeverity.error => DiagnosticSeverity.error
let source := "Lean 4"
pure {
range := range
fullRange := fullRange
severity? := severity
source? := source
message := ← msgToInteractive m.data
}
end Lean.Widget
|
8e26b5056f6eca6a78f54090663dfe4a772bf814 | f57749ca63d6416f807b770f67559503fdb21001 | /hott/init/pathover.hlean | 8c3be3fb52e7c5f70a36c9294f4b56acbeae46e3 | [
"Apache-2.0"
] | permissive | aliassaf/lean | bd54e85bed07b1ff6f01396551867b2677cbc6ac | f9b069b6a50756588b309b3d716c447004203152 | refs/heads/master | 1,610,982,152,948 | 1,438,916,029,000 | 1,438,916,029,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,452 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Basic theorems about pathovers
-/
prelude
import .path .equiv
open equiv is_equiv equiv.ops
variables {A A' : Type} {B B' : A → Type} {C : Πa, B a → Type}
{a a₂ a₃ a₄ : A} {p p' : a = a₂} {p₂ : a₂ = a₃} {p₃ : a₃ = a₄}
{b b' : B a} {b₂ b₂' : B a₂} {b₃ : B a₃} {b₄ : B a₄}
{c : C a b} {c₂ : C a₂ b₂}
namespace eq
inductive pathover.{l} (B : A → Type.{l}) (b : B a) : Π{a₂ : A}, a = a₂ → B a₂ → Type.{l} :=
idpatho : pathover B b (refl a) b
notation b `=[`:50 p:0 `]`:0 b₂:50 := pathover _ b p b₂
definition idpo [reducible] [constructor] : b =[refl a] b :=
pathover.idpatho b
/- equivalences with equality using transport -/
definition pathover_of_tr_eq (r : p ▸ b = b₂) : b =[p] b₂ :=
by cases p; cases r; exact idpo
definition pathover_of_eq_tr (r : b = p⁻¹ ▸ b₂) : b =[p] b₂ :=
by cases p; cases r; exact idpo
definition tr_eq_of_pathover [unfold 8] (r : b =[p] b₂) : p ▸ b = b₂ :=
by cases r; exact idp
definition eq_tr_of_pathover [unfold 8] (r : b =[p] b₂) : b = p⁻¹ ▸ b₂ :=
by cases r; exact idp
definition pathover_equiv_tr_eq [constructor] (p : a = a₂) (b : B a) (b₂ : B a₂)
: (b =[p] b₂) ≃ (p ▸ b = b₂) :=
begin
fapply equiv.MK,
{ exact tr_eq_of_pathover},
{ exact pathover_of_tr_eq},
{ intro r, cases p, cases r, apply idp},
{ intro r, cases r, apply idp},
end
definition pathover_equiv_eq_tr [constructor] (p : a = a₂) (b : B a) (b₂ : B a₂)
: (b =[p] b₂) ≃ (b = p⁻¹ ▸ b₂) :=
begin
fapply equiv.MK,
{ exact eq_tr_of_pathover},
{ exact pathover_of_eq_tr},
{ intro r, cases p, cases r, apply idp},
{ intro r, cases r, apply idp},
end
definition pathover_tr [unfold 5] (p : a = a₂) (b : B a) : b =[p] p ▸ b :=
by cases p;exact idpo
definition tr_pathover [unfold 5] (p : a = a₂) (b : B a₂) : p⁻¹ ▸ b =[p] b :=
pathover_of_eq_tr idp
definition concato [unfold 12] (r : b =[p] b₂) (r₂ : b₂ =[p₂] b₃) : b =[p ⬝ p₂] b₃ :=
pathover.rec_on r₂ r
definition inverseo [unfold 8] (r : b =[p] b₂) : b₂ =[p⁻¹] b :=
pathover.rec_on r idpo
definition apdo [unfold 6] (f : Πa, B a) (p : a = a₂) : f a =[p] f a₂ :=
eq.rec_on p idpo
definition oap [unfold 6] {C : A → Type} (f : Πa, B a → C a) (p : a = a₂) : f a =[p] f a₂ :=
eq.rec_on p idpo
definition concato_eq [unfold 10] (r : b =[p] b₂) (q : b₂ = b₂') : b =[p] b₂' :=
eq.rec_on q r
definition eq_concato [unfold 9] (q : b = b') (r : b' =[p] b₂) : b =[p] b₂ :=
by induction q;exact r
-- infix `⬝` := concato
infix `⬝o`:75 := concato
infix `⬝op`:75 := concato_eq
infix `⬝po`:75 := eq_concato
-- postfix `⁻¹` := inverseo
postfix `⁻¹ᵒ`:(max+10) := inverseo
/- Some of the theorems analogous to theorems for = in init.path -/
definition cono_idpo (r : b =[p] b₂) : r ⬝o idpo =[con_idp p] r :=
pathover.rec_on r idpo
definition idpo_cono (r : b =[p] b₂) : idpo ⬝o r =[idp_con p] r :=
pathover.rec_on r idpo
definition cono.assoc' (r : b =[p] b₂) (r₂ : b₂ =[p₂] b₃) (r₃ : b₃ =[p₃] b₄) :
r ⬝o (r₂ ⬝o r₃) =[!con.assoc'] (r ⬝o r₂) ⬝o r₃ :=
pathover.rec_on r₃ (pathover.rec_on r₂ (pathover.rec_on r idpo))
definition cono.assoc (r : b =[p] b₂) (r₂ : b₂ =[p₂] b₃) (r₃ : b₃ =[p₃] b₄) :
(r ⬝o r₂) ⬝o r₃ =[!con.assoc] r ⬝o (r₂ ⬝o r₃) :=
pathover.rec_on r₃ (pathover.rec_on r₂ (pathover.rec_on r idpo))
definition cono.right_inv (r : b =[p] b₂) : r ⬝o r⁻¹ᵒ =[!con.right_inv] idpo :=
pathover.rec_on r idpo
definition cono.left_inv (r : b =[p] b₂) : r⁻¹ᵒ ⬝o r =[!con.left_inv] idpo :=
pathover.rec_on r idpo
definition eq_of_pathover {a' a₂' : A'} (q : a' =[p] a₂') : a' = a₂' :=
by cases q;reflexivity
definition pathover_of_eq {a' a₂' : A'} (q : a' = a₂') : a' =[p] a₂' :=
by cases p;cases q;exact idpo
definition pathover_constant [constructor] (p : a = a₂) (a' a₂' : A') : a' =[p] a₂' ≃ a' = a₂' :=
begin
fapply equiv.MK,
{ exact eq_of_pathover},
{ exact pathover_of_eq},
{ intro r, cases p, cases r, exact idp},
{ intro r, cases r, exact idp},
end
definition eq_of_pathover_idp [unfold 6] {b' : B a} (q : b =[idpath a] b') : b = b' :=
tr_eq_of_pathover q
--should B be explicit in the next two definitions?
definition pathover_idp_of_eq [unfold 6] {b' : B a} (q : b = b') : b =[idpath a] b' :=
pathover_of_tr_eq q
definition pathover_idp [constructor] (b : B a) (b' : B a) : b =[idpath a] b' ≃ b = b' :=
equiv.MK eq_of_pathover_idp
(pathover_idp_of_eq)
(to_right_inv !pathover_equiv_tr_eq)
(to_left_inv !pathover_equiv_tr_eq)
-- definition pathover_idp (b : B a) (b' : B a) : b =[idpath a] b' ≃ b = b' :=
-- pathover_equiv_tr_eq idp b b'
-- definition eq_of_pathover_idp [reducible] {b' : B a} (q : b =[idpath a] b') : b = b' :=
-- to_fun !pathover_idp q
-- definition pathover_idp_of_eq [reducible] {b' : B a} (q : b = b') : b =[idpath a] b' :=
-- to_inv !pathover_idp q
definition idp_rec_on [recursor] {P : Π⦃b₂ : B a⦄, b =[idpath a] b₂ → Type}
{b₂ : B a} (r : b =[idpath a] b₂) (H : P idpo) : P r :=
have H2 : P (pathover_idp_of_eq (eq_of_pathover_idp r)), from
eq.rec_on (eq_of_pathover_idp r) H,
proof left_inv !pathover_idp r ▸ H2 qed
definition rec_on_right [recursor] {P : Π⦃b₂ : B a₂⦄, b =[p] b₂ → Type}
{b₂ : B a₂} (r : b =[p] b₂) (H : P !pathover_tr) : P r :=
by cases r; exact H
definition rec_on_left [recursor] {P : Π⦃b : B a⦄, b =[p] b₂ → Type}
{b : B a} (r : b =[p] b₂) (H : P !tr_pathover) : P r :=
by cases r; exact H
--pathover with fibration B' ∘ f
definition pathover_ap [unfold 10] (B' : A' → Type) (f : A → A') {p : a = a₂}
{b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[p] b₂) : b =[ap f p] b₂ :=
by cases q; exact idpo
definition pathover_of_pathover_ap (B' : A' → Type) (f : A → A') {p : a = a₂}
{b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[ap f p] b₂) : b =[p] b₂ :=
by cases p; apply (idp_rec_on q); apply idpo
definition pathover_compose (B' : A' → Type) (f : A → A') (p : a = a₂)
(b : B' (f a)) (b₂ : B' (f a₂)) : b =[p] b₂ ≃ b =[ap f p] b₂ :=
begin
fapply equiv.MK,
{ apply pathover_ap},
{ apply pathover_of_pathover_ap},
{ intro q, cases p, esimp, apply (idp_rec_on q), apply idp},
{ intro q, cases q, exact idp},
end
definition apdo_con (f : Πa, B a) (p : a = a₂) (q : a₂ = a₃)
: apdo f (p ⬝ q) = apdo f p ⬝o apdo f q :=
by cases p; cases q; exact idp
definition apdo_inv (f : Πa, B a) (p : a = a₂) : apdo f p⁻¹ = (apdo f p)⁻¹ᵒ :=
by cases p; exact idp
definition apdo_eq_pathover_of_eq_ap (f : A → A') (p : a = a₂) :
apdo f p = pathover_of_eq (ap f p) :=
eq.rec_on p idp
definition pathover_of_pathover_tr (q : b =[p ⬝ p₂] p₂ ▸ b₂) : b =[p] b₂ :=
by cases p₂;exact q
definition pathover_tr_of_pathover {p : a = a₃} (q : b =[p ⬝ p₂⁻¹] b₂) : b =[p] p₂ ▸ b₂ :=
by cases p₂;exact q
definition pathover_tr_of_eq (q : b = b') : b =[p] p ▸ b' :=
by cases q;apply pathover_tr
definition tr_pathover_of_eq (q : b₂ = b₂') : p⁻¹ ▸ b₂ =[p] b₂' :=
by cases q;apply tr_pathover
definition apo011 (f : Πa, B a → A') (Ha : a = a₂) (Hb : b =[Ha] b₂)
: f a b = f a₂ b₂ :=
by cases Hb; exact idp
definition apo0111 (f : Πa b, C a b → A') (Ha : a = a₂) (Hb : b =[Ha] b₂)
(Hc : c =[apo011 C Ha Hb] c₂) : f a b c = f a₂ b₂ c₂ :=
by cases Hb; apply (idp_rec_on Hc); apply idp
definition apo11 {f : Πb, C a b} {g : Πb₂, C a₂ b₂} (r : f =[p] g)
{b : B a} {b₂ : B a₂} (q : b =[p] b₂) : f b =[apo011 C p q] g b₂ :=
by cases r; apply (idp_rec_on q); exact idpo
definition apo10 {f : Πb, C a b} {g : Πb₂, C a₂ b₂} (r : f =[p] g)
{b : B a} : f b =[apo011 C p !pathover_tr] g (p ▸ b) :=
by cases r; exact idpo
definition cono.right_inv_eq (q : b = b')
: concato_eq (pathover_idp_of_eq q) q⁻¹ = (idpo : b =[refl a] b) :=
by induction q;constructor
definition cono.right_inv_eq' (q : b = b')
: eq_concato q (pathover_idp_of_eq q⁻¹) = (idpo : b =[refl a] b) :=
by induction q;constructor
definition cono.left_inv_eq (q : b = b')
: concato_eq (pathover_idp_of_eq q⁻¹) q = (idpo : b' =[refl a] b') :=
by induction q;constructor
definition cono.left_inv_eq' (q : b = b')
: eq_concato q⁻¹ (pathover_idp_of_eq q) = (idpo : b' =[refl a] b') :=
by induction q;constructor
definition change_path (q : p = p') (r : b =[p] b₂) : b =[p'] b₂ :=
by induction q;exact r
definition change_path_equiv (f : Π{a}, B a ≃ B' a) (r : b =[p] b₂) : f b =[p] f b₂ :=
by induction r;constructor
definition change_path_equiv' (f : Π{a}, B a ≃ B' a) (r : f b =[p] f b₂) : b =[p] b₂ :=
(left_inv f b)⁻¹ ⬝po change_path_equiv (λa, f⁻¹ᵉ) r ⬝op left_inv f b₂
end eq
|
35859025dbdc0fce72db8b0f681f3f9cbd45800a | 6214e13b31733dc9aeb4833db6a6466005763162 | /src/qi.lean | cc23d318e92631b013c0583bc46e9eb7c33a1be0 | [] | no_license | joshua0pang/esverify-theory | 272a250445f3aeea49a7e72d1ab58c2da6618bbe | 8565b123c87b0113f83553d7732cd6696c9b5807 | refs/heads/master | 1,585,873,849,081 | 1,527,304,393,000 | 1,527,304,393,000 | 154,901,199 | 1 | 0 | null | 1,540,593,067,000 | 1,540,593,067,000 | null | UTF-8 | Lean | false | false | 95,400 | lean | -- quantifier instantiation
import .definitions3 .freevars .substitution .logic
lemma prop.has_call_p.term.inv {c: calltrigger} {t: term}: c ∉ calls_p t :=
assume t_has_call: prop.has_call_p c t,
show «false», by cases t_has_call
lemma prop.has_call_p.not.inv {c: calltrigger} {P: prop}: c ∈ calls_p P.not → c ∈ calls_n P :=
assume not_has_call: c ∈ calls_p P.not,
begin
cases not_has_call,
from a
end
lemma prop.has_call_p.and.inv {c: calltrigger} {P₁ P₂: prop}: c ∈ calls_p (P₁ ⋀ P₂) → c ∈ calls_p P₁ ∨ c ∈ calls_p P₂ :=
assume and_has_call: c ∈ calls_p (P₁ ⋀ P₂),
begin
cases and_has_call,
show c ∈ calls_p P₁ ∨ c ∈ calls_p P₂, from or.inl a,
show c ∈ calls_p P₁ ∨ c ∈ calls_p P₂, from or.inr a
end
lemma prop.has_call_p.or.inv {c: calltrigger} {P₁ P₂: prop}: c ∈ calls_p (P₁ ⋁ P₂) → c ∈ calls_p P₁ ∨ c ∈ calls_p P₂ :=
assume or_has_call: c ∈ calls_p (P₁ ⋁ P₂),
begin
cases or_has_call,
show c ∈ calls_p P₁ ∨ c ∈ calls_p P₂, from or.inl a,
show c ∈ calls_p P₁ ∨ c ∈ calls_p P₂, from or.inr a
end
lemma prop.has_call_p.pre₁.inv {c: calltrigger} {op: unop} {t: term}: c ∉ calls_p (prop.pre₁ op t) :=
assume pre_has_call: c ∈ calls_p (prop.pre₁ op t),
show «false», by cases pre_has_call
lemma prop.has_call_p.pre₂.inv {c: calltrigger} {op: binop} {t₁ t₂: term}: c ∉ calls_p (prop.pre₂ op t₁ t₂) :=
assume pre_has_call: c ∈ calls_p (prop.pre₂ op t₁ t₂),
show «false», by cases pre_has_call
lemma prop.has_call_p.pre.inv {c: calltrigger} {t₁ t₂: term}: c ∉ calls_p (prop.pre t₁ t₂) :=
assume pre_has_call: c ∈ calls_p (prop.pre t₁ t₂),
show «false», by cases pre_has_call
lemma prop.has_call_p.post.inv {c: calltrigger} {t₁ t₂: term}: c ∉ calls_p (prop.post t₁ t₂) :=
assume post_has_call: c ∈ calls_p (prop.post t₁ t₂),
show «false», by cases post_has_call
lemma prop.has_call_p.call.inv {c: calltrigger} {t: term}:
c ∈ calls_p (prop.call t) → (c = calltrigger.mk t) :=
assume call_has_call: c ∈ calls_p (prop.call t),
show c = calltrigger.mk t, by { cases call_has_call, refl }
lemma prop.has_call_p.forallc.inv {c: calltrigger} {x: var} {t: term} {P: prop}:
c ∉ calls_p (prop.forallc x P) :=
assume forall_has_call: c ∈ calls_p (prop.forallc x P),
begin
cases forall_has_call
end
lemma prop.has_call_p.exis.inv {c: calltrigger} {x: var} {P: prop}: c ∉ calls_p (prop.exis x P) :=
assume exis_has_call: c ∈ calls_p (prop.exis x P),
begin
cases exis_has_call
end
lemma prop.has_call_n.term.inv {c: calltrigger} {t: term}: c ∉ calls_n t :=
assume t_has_call_n: prop.has_call_n c t,
show «false», by cases t_has_call_n
lemma prop.has_call_n.not.inv {c: calltrigger} {P: prop}: c ∈ calls_n P.not → c ∈ calls_p P :=
assume not_has_call_n: c ∈ calls_n P.not,
begin
cases not_has_call_n,
from a
end
lemma prop.has_call_n.and.inv {c: calltrigger} {P₁ P₂: prop}: c ∈ calls_n (P₁ ⋀ P₂) → c ∈ calls_n P₁ ∨ c ∈ calls_n P₂ :=
assume and_has_call_n: c ∈ calls_n (P₁ ⋀ P₂),
begin
cases and_has_call_n,
show c ∈ calls_n P₁ ∨ c ∈ calls_n P₂, from or.inl a,
show c ∈ calls_n P₁ ∨ c ∈ calls_n P₂, from or.inr a
end
lemma prop.has_call_n.or.inv {c: calltrigger} {P₁ P₂: prop}: c ∈ calls_n (P₁ ⋁ P₂) → c ∈ calls_n P₁ ∨ c ∈ calls_n P₂ :=
assume or_has_call_n: c ∈ calls_n (P₁ ⋁ P₂),
begin
cases or_has_call_n,
show c ∈ calls_n P₁ ∨ c ∈ calls_n P₂, from or.inl a,
show c ∈ calls_n P₁ ∨ c ∈ calls_n P₂, from or.inr a
end
lemma prop.has_call_n.pre₁.inv {c: calltrigger} {op: unop} {t: term}: c ∉ calls_n (prop.pre₁ op t) :=
assume pre_has_call_n: c ∈ calls_n (prop.pre₁ op t),
show «false», by cases pre_has_call_n
lemma prop.has_call_n.pre₂.inv {c: calltrigger} {op: binop} {t₁ t₂: term}: c ∉ calls_n (prop.pre₂ op t₁ t₂) :=
assume pre_has_call_n: c ∈ calls_n (prop.pre₂ op t₁ t₂),
show «false», by cases pre_has_call_n
lemma prop.has_call_n.pre.inv {c: calltrigger} {t₁ t₂: term}: c ∉ calls_n (prop.pre t₁ t₂) :=
assume pre_has_call_n: c ∈ calls_n (prop.pre t₁ t₂),
show «false», by cases pre_has_call_n
lemma prop.has_call_n.post.inv {c: calltrigger} {t₁ t₂: term}: c ∉ calls_n (prop.post t₁ t₂) :=
assume post_has_call_n: c ∈ calls_n (prop.post t₁ t₂),
show «false», by cases post_has_call_n
lemma prop.has_call_n.call.inv {c: calltrigger} {t₁ t₂: term}: c ∉ calls_n (prop.call t₁ t₂) :=
assume call_has_call_n: c ∈ calls_n (prop.call t₁ t₂),
show «false», by cases call_has_call_n
lemma prop.has_call_n.forallc.inv {c: calltrigger} {x: var} {t: term} {P: prop}:
c ∉ calls_n (prop.forallc x P) :=
assume forall_has_call_n: c ∈ calls_n (prop.forallc x P),
begin
cases forall_has_call_n
end
lemma prop.has_call_n.exis.inv {c: calltrigger} {x: var} {P: prop}: c ∉ calls_n (prop.exis x P) :=
assume exis_has_call_n: c ∈ calls_n (prop.exis x P),
begin
cases exis_has_call_n
end
lemma prop.has_quantifier_p.term.inv {q: callquantifier} {t: term}: q ∉ quantifiers_p t :=
assume t_has_quantifier_p: prop.has_quantifier_p q t,
show «false», by cases t_has_quantifier_p
lemma prop.has_quantifier_p.not.inv {q: callquantifier} {P: prop}: q ∈ quantifiers_p P.not → q ∈ quantifiers_n P :=
assume not_has_quantifier_p: q ∈ quantifiers_p P.not,
begin
cases not_has_quantifier_p with a,
from a
end
lemma prop.has_quantifier_p.and.inv {q: callquantifier} {P₁ P₂: prop}:
q ∈ quantifiers_p (P₁ ⋀ P₂) → q ∈ quantifiers_p P₁ ∨ q ∈ quantifiers_p P₂ :=
assume and_has_quantifier_p: q ∈ quantifiers_p (P₁ ⋀ P₂),
begin
cases and_has_quantifier_p,
show q ∈ quantifiers_p P₁ ∨ q ∈ quantifiers_p P₂, from or.inl a,
show q ∈ quantifiers_p P₁ ∨ q ∈ quantifiers_p P₂, from or.inr a
end
lemma prop.has_quantifier_p.or.inv {q: callquantifier} {P₁ P₂: prop}:
q ∈ quantifiers_p (P₁ ⋁ P₂) → q ∈ quantifiers_p P₁ ∨ q ∈ quantifiers_p P₂ :=
assume or_has_quantifier_p: q ∈ quantifiers_p (P₁ ⋁ P₂),
begin
cases or_has_quantifier_p,
show q ∈ quantifiers_p P₁ ∨ q ∈ quantifiers_p P₂, from or.inl a,
show q ∈ quantifiers_p P₁ ∨ q ∈ quantifiers_p P₂, from or.inr a
end
lemma prop.has_quantifier_p.pre₁.inv {q: callquantifier} {op: unop} {t: term}: q ∉ quantifiers_p (prop.pre₁ op t) :=
assume pre_has_quantifier_p: q ∈ quantifiers_p (prop.pre₁ op t),
show «false», by cases pre_has_quantifier_p
lemma prop.has_quantifier_p.pre₂.inv {q: callquantifier} {op: binop} {t₁ t₂: term}: q ∉ quantifiers_p (prop.pre₂ op t₁ t₂) :=
assume pre_has_quantifier_p: q ∈ quantifiers_p (prop.pre₂ op t₁ t₂),
show «false», by cases pre_has_quantifier_p
lemma prop.has_quantifier_p.pre.inv {q: callquantifier} {t₁ t₂: term}: q ∉ quantifiers_p (prop.pre t₁ t₂) :=
assume pre_has_quantifier_p: q ∈ quantifiers_p (prop.pre t₁ t₂),
show «false», by cases pre_has_quantifier_p
lemma prop.has_quantifier_p.post.inv {q: callquantifier} {t₁ t₂: term}: q ∉ quantifiers_p (prop.post t₁ t₂) :=
assume post_has_quantifier_p: q ∈ quantifiers_p (prop.post t₁ t₂),
show «false», by cases post_has_quantifier_p
lemma prop.has_quantifier_p.call.inv {q: callquantifier} {t₁ t₂: term}: q ∉ quantifiers_p (prop.call t₁ t₂) :=
assume call_has_quantifier_p: q ∈ quantifiers_p (prop.call t₁ t₂),
show «false», by cases call_has_quantifier_p
lemma prop.has_quantifier_p.forallc.inv {q: callquantifier} {x: var} {P: prop}:
q ∈ quantifiers_p (prop.forallc x P) → (q = ⟨x, P⟩) :=
assume forall_has_quantifier_p: q ∈ quantifiers_p (prop.forallc x P),
begin
cases forall_has_quantifier_p,
from rfl
end
lemma prop.has_quantifier_n.term.inv {q: callquantifier} {t: term}: q ∉ quantifiers_n t :=
assume t_has_quantifier_n: prop.has_quantifier_n q t,
show «false», by cases t_has_quantifier_n
lemma prop.has_quantifier_n.not.inv {q: callquantifier} {P: prop}: q ∈ quantifiers_n P.not → q ∈ quantifiers_p P :=
assume not_has_quantifier_n: q ∈ quantifiers_n P.not,
begin
cases not_has_quantifier_n,
from a
end
lemma prop.has_quantifier_n.and.inv {q: callquantifier} {P₁ P₂: prop}:
q ∈ quantifiers_n (P₁ ⋀ P₂) → q ∈ quantifiers_n P₁ ∨ q ∈ quantifiers_n P₂ :=
assume and_has_quantifier_n: q ∈ quantifiers_n (P₁ ⋀ P₂),
begin
cases and_has_quantifier_n,
show q ∈ quantifiers_n P₁ ∨ q ∈ quantifiers_n P₂, from or.inl a,
show q ∈ quantifiers_n P₁ ∨ q ∈ quantifiers_n P₂, from or.inr a
end
lemma prop.has_quantifier_n.or.inv {q: callquantifier} {P₁ P₂: prop}:
q ∈ quantifiers_n (P₁ ⋁ P₂) → q ∈ quantifiers_n P₁ ∨ q ∈ quantifiers_n P₂ :=
assume or_has_quantifier_n: q ∈ quantifiers_n (P₁ ⋁ P₂),
begin
cases or_has_quantifier_n,
show q ∈ quantifiers_n P₁ ∨ q ∈ quantifiers_n P₂, from or.inl a,
show q ∈ quantifiers_n P₁ ∨ q ∈ quantifiers_n P₂, from or.inr a
end
lemma prop.has_quantifier_n.pre₁.inv {q: callquantifier} {op: unop} {t: term}: q ∉ quantifiers_n (prop.pre₁ op t) :=
assume pre_has_quantifier_n: q ∈ quantifiers_n (prop.pre₁ op t),
show «false», by cases pre_has_quantifier_n
lemma prop.has_quantifier_n.pre₂.inv {q: callquantifier} {op: binop} {t₁ t₂: term}: q ∉ quantifiers_n (prop.pre₂ op t₁ t₂) :=
assume pre_has_quantifier_n: q ∈ quantifiers_n (prop.pre₂ op t₁ t₂),
show «false», by cases pre_has_quantifier_n
lemma prop.has_quantifier_n.pre.inv {q: callquantifier} {t₁ t₂: term}: q ∉ quantifiers_n (prop.pre t₁ t₂) :=
assume pre_has_quantifier_n: q ∈ quantifiers_n (prop.pre t₁ t₂),
show «false», by cases pre_has_quantifier_n
lemma prop.has_quantifier_n.post.inv {q: callquantifier} {t₁ t₂: term}: q ∉ quantifiers_n (prop.post t₁ t₂) :=
assume post_has_quantifier_n: q ∈ quantifiers_n (prop.post t₁ t₂),
show «false», by cases post_has_quantifier_n
lemma prop.has_quantifier_n.call.inv {q: callquantifier} {t₁ t₂: term}: q ∉ quantifiers_n (prop.call t₁ t₂) :=
assume call_has_quantifier_n: q ∈ quantifiers_n (prop.call t₁ t₂),
show «false», by cases call_has_quantifier_n
lemma prop.has_quantifier_n.forallc.inv {q: callquantifier} {x: var} {P: prop}:
q ∉ quantifiers_n (prop.forallc x P) :=
assume forall_has_quantifier_n: q ∈ quantifiers_n (prop.forallc x P),
begin
cases forall_has_quantifier_n
end
lemma prop.has_call_p_subst.term.inv {c: calltrigger} {t: term} {σ: env}:
c ∉ calls_p_subst σ t :=
assume : c ∈ calls_p_subst σ t,
have c ∈ (calltrigger.subst σ) '' calls_p t, from this,
@set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst σ) (calls_p t)
(λa, «false») c this (
assume c': calltrigger,
assume : c' ∈ calls_p t,
show «false», from prop.has_call_p.term.inv this
)
lemma prop.has_call_p_subst.and₁ {c: calltrigger} {P₁ P₂: prop} {σ: env}:
c ∈ calls_p_subst σ P₁ → c ∈ calls_p_subst σ (P₁ ⋀ P₂) :=
assume : c ∈ calls_p_subst σ P₁,
have c ∈ (calltrigger.subst σ) '' calls_p P₁, from this,
@set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst σ) (calls_p P₁)
(λa, a ∈ calls_p_subst σ (P₁ ⋀ P₂)) c this (
assume c': calltrigger,
assume : c' ∈ calls_p P₁,
have c' ∈ calls_p (P₁ ⋀ P₂), from prop.has_call_p.and₁ this,
show calltrigger.subst σ c' ∈ calls_p_subst σ (P₁ ⋀ P₂), from set.mem_image this rfl
)
lemma prop.has_call_p_subst.and₂ {c: calltrigger} {P₁ P₂: prop} {σ: env}:
c ∈ calls_p_subst σ P₂ → c ∈ calls_p_subst σ (P₁ ⋀ P₂) :=
assume : c ∈ calls_p_subst σ P₂,
have c ∈ (calltrigger.subst σ) '' calls_p P₂, from this,
@set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst σ) (calls_p P₂)
(λa, a ∈ calls_p_subst σ (P₁ ⋀ P₂)) c this (
assume c': calltrigger,
assume : c' ∈ calls_p P₂,
have c' ∈ calls_p (P₁ ⋀ P₂), from prop.has_call_p.and₂ this,
show calltrigger.subst σ c' ∈ calls_p_subst σ (P₁ ⋀ P₂), from set.mem_image this rfl
)
lemma prop.has_call_p_subst.not {c: calltrigger} {P: prop} {σ: env}:
c ∈ calls_p_subst σ P → c ∈ calls_n_subst σ P.not :=
assume : c ∈ calls_p_subst σ P,
have c ∈ (calltrigger.subst σ) '' calls_p P, from this,
@set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst σ) (calls_p P)
(λa, a ∈ calls_n_subst σ P.not) c this (
assume c': calltrigger,
assume : c' ∈ calls_p P,
have c' ∈ calls_n P.not, from prop.has_call_n.not this,
show calltrigger.subst σ c' ∈ calls_n_subst σ P.not, from set.mem_image this rfl
)
lemma prop.has_call_n_subst.term.inv {c: calltrigger} {t: term} {σ: env}:
c ∉ calls_n_subst σ t :=
assume : c ∈ calls_n_subst σ t,
have c ∈ (calltrigger.subst σ) '' calls_n t, from this,
@set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst σ) (calls_n t)
(λa, «false») c this (
assume c': calltrigger,
assume : c' ∈ calls_n t,
show «false», from prop.has_call_n.term.inv this
)
lemma prop.has_call_n_subst.not {c: calltrigger} {P: prop} {σ: env}:
c ∈ calls_n_subst σ P → c ∈ calls_p_subst σ P.not :=
assume : c ∈ calls_n_subst σ P,
have c ∈ (calltrigger.subst σ) '' calls_n P, from this,
@set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst σ) (calls_n P)
(λa, a ∈ calls_p_subst σ P.not) c this (
assume c': calltrigger,
assume : c' ∈ calls_n P,
have c' ∈ calls_p P.not, from prop.has_call_p.not this,
show calltrigger.subst σ c' ∈ calls_p_subst σ P.not, from set.mem_image this rfl
)
lemma prop.has_call_p_subst.not.inv {c: calltrigger} {P: prop} {σ: env}:
c ∈ calls_p_subst σ P.not → c ∈ calls_n_subst σ P :=
assume : c ∈ calls_p_subst σ P.not,
have c ∈ (calltrigger.subst σ) '' calls_p P.not, from this,
@set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst σ) (calls_p P.not)
(λa, a ∈ calls_n_subst σ P) c this (
assume c': calltrigger,
assume : c' ∈ calls_p P.not,
have c' ∈ calls_n P, from prop.has_call_p.not.inv this,
show calltrigger.subst σ c' ∈ calls_n_subst σ P, from set.mem_image this rfl
)
lemma prop.has_call_n_subst.not.inv {c: calltrigger} {P: prop} {σ: env}:
c ∈ calls_n_subst σ P.not → c ∈ calls_p_subst σ P :=
assume : c ∈ calls_n_subst σ P.not,
have c ∈ (calltrigger.subst σ) '' calls_n P.not, from this,
@set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst σ) (calls_n P.not)
(λa, a ∈ calls_p_subst σ P) c this (
assume c': calltrigger,
assume : c' ∈ calls_n P.not,
have c' ∈ calls_p P, from prop.has_call_n.not.inv this,
show calltrigger.subst σ c' ∈ calls_p_subst σ P, from set.mem_image this rfl
)
lemma prop.has_call_p_subst.and.inv {c: calltrigger} {P₁ P₂: prop} {σ: env}:
c ∈ calls_p_subst σ (P₁ ⋀ P₂) → c ∈ calls_p_subst σ P₁ ∨ c ∈ calls_p_subst σ P₂ :=
assume : c ∈ calls_p_subst σ (P₁ ⋀ P₂),
have c ∈ (calltrigger.subst σ) '' calls_p (P₁ ⋀ P₂), from this,
@set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst σ) (calls_p (P₁ ⋀ P₂))
(λa, a ∈ calls_p_subst σ P₁ ∨ a ∈ calls_p_subst σ P₂) c this (
assume c': calltrigger,
assume : c' ∈ calls_p (P₁ ⋀ P₂),
or.elim (prop.has_call_p.and.inv this) (
assume : c' ∈ calls_p P₁,
have calltrigger.subst σ c' ∈ calls_p_subst σ P₁, from set.mem_image this rfl,
show calltrigger.subst σ c' ∈ calls_p_subst σ P₁
∨ calltrigger.subst σ c' ∈ calls_p_subst σ P₂, from or.inl this
) (
assume : c' ∈ calls_p P₂,
have calltrigger.subst σ c' ∈ calls_p_subst σ P₂, from set.mem_image this rfl,
show calltrigger.subst σ c' ∈ calls_p_subst σ P₁
∨ calltrigger.subst σ c' ∈ calls_p_subst σ P₂, from or.inr this
)
)
lemma prop.has_call_p_subst.or.inv {c: calltrigger} {P₁ P₂: prop} {σ: env}:
c ∈ calls_p_subst σ (P₁ ⋁ P₂) → c ∈ calls_p_subst σ P₁ ∨ c ∈ calls_p_subst σ P₂ :=
assume : c ∈ calls_p_subst σ (P₁ ⋁ P₂),
have c ∈ (calltrigger.subst σ) '' calls_p (P₁ ⋁ P₂), from this,
@set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst σ) (calls_p (P₁ ⋁ P₂))
(λa, a ∈ calls_p_subst σ P₁ ∨ a ∈ calls_p_subst σ P₂) c this (
assume c': calltrigger,
assume : c' ∈ calls_p (P₁ ⋁ P₂),
or.elim (prop.has_call_p.or.inv this) (
assume : c' ∈ calls_p P₁,
have calltrigger.subst σ c' ∈ calls_p_subst σ P₁, from set.mem_image this rfl,
show calltrigger.subst σ c' ∈ calls_p_subst σ P₁
∨ calltrigger.subst σ c' ∈ calls_p_subst σ P₂, from or.inl this
) (
assume : c' ∈ calls_p P₂,
have calltrigger.subst σ c' ∈ calls_p_subst σ P₂, from set.mem_image this rfl,
show calltrigger.subst σ c' ∈ calls_p_subst σ P₁
∨ calltrigger.subst σ c' ∈ calls_p_subst σ P₂, from or.inr this
)
)
lemma prop.has_call_n_subst.and.inv {c: calltrigger} {P₁ P₂: prop} {σ: env}:
c ∈ calls_n_subst σ (P₁ ⋀ P₂) → c ∈ calls_n_subst σ P₁ ∨ c ∈ calls_n_subst σ P₂ :=
assume : c ∈ calls_n_subst σ (P₁ ⋀ P₂),
have c ∈ (calltrigger.subst σ) '' calls_n (P₁ ⋀ P₂), from this,
@set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst σ) (calls_n (P₁ ⋀ P₂))
(λa, a ∈ calls_n_subst σ P₁ ∨ a ∈ calls_n_subst σ P₂) c this (
assume c': calltrigger,
assume : c' ∈ calls_n (P₁ ⋀ P₂),
or.elim (prop.has_call_n.and.inv this) (
assume : c' ∈ calls_n P₁,
have calltrigger.subst σ c' ∈ calls_n_subst σ P₁, from set.mem_image this rfl,
show calltrigger.subst σ c' ∈ calls_n_subst σ P₁
∨ calltrigger.subst σ c' ∈ calls_n_subst σ P₂, from or.inl this
) (
assume : c' ∈ calls_n P₂,
have calltrigger.subst σ c' ∈ calls_n_subst σ P₂, from set.mem_image this rfl,
show calltrigger.subst σ c' ∈ calls_n_subst σ P₁
∨ calltrigger.subst σ c' ∈ calls_n_subst σ P₂, from or.inr this
)
)
lemma prop.has_call_n_subst.or.inv {c: calltrigger} {P₁ P₂: prop} {σ: env}:
c ∈ calls_n_subst σ (P₁ ⋁ P₂) → c ∈ calls_n_subst σ P₁ ∨ c ∈ calls_n_subst σ P₂ :=
assume : c ∈ calls_n_subst σ (P₁ ⋁ P₂),
have c ∈ (calltrigger.subst σ) '' calls_n (P₁ ⋁ P₂), from this,
@set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst σ) (calls_n (P₁ ⋁ P₂))
(λa, a ∈ calls_n_subst σ P₁ ∨ a ∈ calls_n_subst σ P₂) c this (
assume c': calltrigger,
assume : c' ∈ calls_n (P₁ ⋁ P₂),
or.elim (prop.has_call_n.or.inv this) (
assume : c' ∈ calls_n P₁,
have calltrigger.subst σ c' ∈ calls_n_subst σ P₁, from set.mem_image this rfl,
show calltrigger.subst σ c' ∈ calls_n_subst σ P₁
∨ calltrigger.subst σ c' ∈ calls_n_subst σ P₂, from or.inl this
) (
assume : c' ∈ calls_n P₂,
have calltrigger.subst σ c' ∈ calls_n_subst σ P₂, from set.mem_image this rfl,
show calltrigger.subst σ c' ∈ calls_n_subst σ P₁
∨ calltrigger.subst σ c' ∈ calls_n_subst σ P₂, from or.inr this
)
)
lemma no_instantiations.term {t: term}: no_instantiations t :=
have h1: calls_p t = ∅, from set.eq_empty_of_forall_not_mem (
assume c: calltrigger,
assume : c ∈ calls_p t,
show «false», from prop.has_call_p.term.inv this
),
have h2: calls_n t = ∅, from set.eq_empty_of_forall_not_mem (
assume c: calltrigger,
assume : c ∈ calls_n t,
show «false», from prop.has_call_n.term.inv this
),
have h3: quantifiers_p t = ∅, from set.eq_empty_of_forall_not_mem (
assume q: callquantifier,
assume : q ∈ quantifiers_p t,
show «false», from prop.has_quantifier_p.term.inv this
),
have h4: quantifiers_n t = ∅, from set.eq_empty_of_forall_not_mem (
assume q: callquantifier,
assume : q ∈ quantifiers_n t,
show «false», from prop.has_quantifier_n.term.inv this
),
⟨h1, ⟨h2, ⟨h3, h4⟩⟩⟩
lemma no_instantiations.not {P: prop}: no_instantiations P → no_instantiations P.not :=
assume ⟨no_calls_p_in_P, ⟨no_calls_n_in_P, ⟨no_quantifiers_p_in_P, no_quantifiers_n_in_P⟩⟩⟩,
have h1: calls_p P.not = ∅, from set.eq_empty_of_forall_not_mem (
assume c: calltrigger,
assume : c ∈ calls_p P.not,
have c_in_calls_p_P: c ∈ calls_n P, from prop.has_call_p.not.inv this,
have c_not_in_calls_p_P: c ∉ calls_n P, from set.forall_not_mem_of_eq_empty no_calls_n_in_P c,
show «false», from c_not_in_calls_p_P c_in_calls_p_P
),
have h2: calls_n P.not = ∅, from set.eq_empty_of_forall_not_mem (
assume c: calltrigger,
assume : c ∈ calls_n P.not,
have c_in_calls_p_P: c ∈ calls_p P, from prop.has_call_n.not.inv this,
have c_not_in_calls_p_P: c ∉ calls_p P, from set.forall_not_mem_of_eq_empty no_calls_p_in_P c,
show «false», from c_not_in_calls_p_P c_in_calls_p_P
),
have h3: quantifiers_p P.not = ∅, from set.eq_empty_of_forall_not_mem (
assume q: callquantifier,
assume : q ∈ quantifiers_p P.not,
have c_in_quantifiers_p_P: q ∈ quantifiers_n P, from prop.has_quantifier_p.not.inv this,
have c_not_in_quantifiers_p_P: q ∉ quantifiers_n P, from set.forall_not_mem_of_eq_empty no_quantifiers_n_in_P q,
show «false», from c_not_in_quantifiers_p_P c_in_quantifiers_p_P
),
have h4: quantifiers_n P.not = ∅, from set.eq_empty_of_forall_not_mem (
assume q: callquantifier,
assume : q ∈ quantifiers_n P.not,
have c_in_quantifiers_p_P: q ∈ quantifiers_p P, from prop.has_quantifier_n.not.inv this,
have c_not_in_quantifiers_p_P: q ∉ quantifiers_p P, from set.forall_not_mem_of_eq_empty no_quantifiers_p_in_P q,
show «false», from c_not_in_quantifiers_p_P c_in_quantifiers_p_P
),
⟨h1, ⟨h2, ⟨h3, h4⟩⟩⟩
lemma no_instantiations.and {P₁ P₂: prop}:
no_instantiations P₁ → no_instantiations P₂ → no_instantiations (prop.and P₁ P₂) :=
assume ⟨no_calls_p_in_P₁, ⟨no_calls_n_in_P₁, ⟨no_quantifiers_p_in_P₁, no_quantifiers_n_in_P₁⟩⟩⟩,
assume ⟨no_calls_p_in_P₂, ⟨no_calls_n_in_P₂, ⟨no_quantifiers_p_in_P₂, no_quantifiers_n_in_P₂⟩⟩⟩,
have h1: calls_p (P₁ ⋀ P₂) = ∅, from set.eq_empty_of_forall_not_mem (
assume c: calltrigger,
assume : c ∈ calls_p (P₁ ⋀ P₂),
have c ∈ calls_p P₁ ∨ c ∈ calls_p P₂, from prop.has_call_p.and.inv this,
or.elim this (
assume c_in_calls_p_P₁: c ∈ calls_p P₁,
have c_not_in_calls_p_P₁: c ∉ calls_p P₁, from set.forall_not_mem_of_eq_empty no_calls_p_in_P₁ c,
show «false», from c_not_in_calls_p_P₁ c_in_calls_p_P₁
) (
assume c_in_calls_p_P₂: c ∈ calls_p P₂,
have c_not_in_calls_p_P₂: c ∉ calls_p P₂, from set.forall_not_mem_of_eq_empty no_calls_p_in_P₂ c,
show «false», from c_not_in_calls_p_P₂ c_in_calls_p_P₂
)
),
have h2: calls_n (P₁ ⋀ P₂) = ∅, from set.eq_empty_of_forall_not_mem (
assume c: calltrigger,
assume : c ∈ calls_n (P₁ ⋀ P₂),
have c ∈ calls_n P₁ ∨ c ∈ calls_n P₂, from prop.has_call_n.and.inv this,
or.elim this (
assume c_in_calls_p_P₁: c ∈ calls_n P₁,
have c_not_in_calls_p_P₁: c ∉ calls_n P₁, from set.forall_not_mem_of_eq_empty no_calls_n_in_P₁ c,
show «false», from c_not_in_calls_p_P₁ c_in_calls_p_P₁
) (
assume c_in_calls_p_P₂: c ∈ calls_n P₂,
have c_not_in_calls_p_P₂: c ∉ calls_n P₂, from set.forall_not_mem_of_eq_empty no_calls_n_in_P₂ c,
show «false», from c_not_in_calls_p_P₂ c_in_calls_p_P₂
)
),
have h3: quantifiers_p (P₁ ⋀ P₂) = ∅, from set.eq_empty_of_forall_not_mem (
assume q: callquantifier,
assume : q ∈ quantifiers_p (P₁ ⋀ P₂),
have q ∈ quantifiers_p P₁ ∨ q ∈ quantifiers_p P₂, from prop.has_quantifier_p.and.inv this,
or.elim this (
assume q_in_quantifiers_p_P₁: q ∈ quantifiers_p P₁,
have q_not_in_quantifiers_p_P₁: q ∉ quantifiers_p P₁, from set.forall_not_mem_of_eq_empty no_quantifiers_p_in_P₁ q,
show «false», from q_not_in_quantifiers_p_P₁ q_in_quantifiers_p_P₁
) (
assume q_in_quantifiers_p_P₂: q ∈ quantifiers_p P₂,
have q_not_in_quantifiers_p_P₂: q ∉ quantifiers_p P₂, from set.forall_not_mem_of_eq_empty no_quantifiers_p_in_P₂ q,
show «false», from q_not_in_quantifiers_p_P₂ q_in_quantifiers_p_P₂
)
),
have h4: quantifiers_n (P₁ ⋀ P₂) = ∅, from set.eq_empty_of_forall_not_mem (
assume q: callquantifier,
assume : q ∈ quantifiers_n (P₁ ⋀ P₂),
have q ∈ quantifiers_n P₁ ∨ q ∈ quantifiers_n P₂, from prop.has_quantifier_n.and.inv this,
or.elim this (
assume q_in_quantifiers_p_P₁: q ∈ quantifiers_n P₁,
have q_not_in_quantifiers_p_P₁: q ∉ quantifiers_n P₁, from set.forall_not_mem_of_eq_empty no_quantifiers_n_in_P₁ q,
show «false», from q_not_in_quantifiers_p_P₁ q_in_quantifiers_p_P₁
) (
assume q_in_quantifiers_p_P₂: q ∈ quantifiers_n P₂,
have q_not_in_quantifiers_p_P₂: q ∉ quantifiers_n P₂, from set.forall_not_mem_of_eq_empty no_quantifiers_n_in_P₂ q,
show «false», from q_not_in_quantifiers_p_P₂ q_in_quantifiers_p_P₂
)
),
⟨h1, ⟨h2, ⟨h3, h4⟩⟩⟩
lemma no_instantiations.or {P₁ P₂: prop}:
no_instantiations P₁ → no_instantiations P₂ → no_instantiations (prop.or P₁ P₂) :=
assume ⟨no_calls_p_in_P₁, ⟨no_calls_n_in_P₁, ⟨no_quantifiers_p_in_P₁, no_quantifiers_n_in_P₁⟩⟩⟩,
assume ⟨no_calls_p_in_P₂, ⟨no_calls_n_in_P₂, ⟨no_quantifiers_p_in_P₂, no_quantifiers_n_in_P₂⟩⟩⟩,
have h1: calls_p (P₁ ⋁ P₂) = ∅, from set.eq_empty_of_forall_not_mem (
assume c: calltrigger,
assume : c ∈ calls_p (P₁ ⋁ P₂),
have c ∈ calls_p P₁ ∨ c ∈ calls_p P₂, from prop.has_call_p.or.inv this,
or.elim this (
assume c_in_calls_p_P₁: c ∈ calls_p P₁,
have c_not_in_calls_p_P₁: c ∉ calls_p P₁, from set.forall_not_mem_of_eq_empty no_calls_p_in_P₁ c,
show «false», from c_not_in_calls_p_P₁ c_in_calls_p_P₁
) (
assume c_in_calls_p_P₂: c ∈ calls_p P₂,
have c_not_in_calls_p_P₂: c ∉ calls_p P₂, from set.forall_not_mem_of_eq_empty no_calls_p_in_P₂ c,
show «false», from c_not_in_calls_p_P₂ c_in_calls_p_P₂
)
),
have h2: calls_n (P₁ ⋁ P₂) = ∅, from set.eq_empty_of_forall_not_mem (
assume c: calltrigger,
assume : c ∈ calls_n (P₁ ⋁ P₂),
have c ∈ calls_n P₁ ∨ c ∈ calls_n P₂, from prop.has_call_n.or.inv this,
or.elim this (
assume c_in_calls_p_P₁: c ∈ calls_n P₁,
have c_not_in_calls_p_P₁: c ∉ calls_n P₁, from set.forall_not_mem_of_eq_empty no_calls_n_in_P₁ c,
show «false», from c_not_in_calls_p_P₁ c_in_calls_p_P₁
) (
assume c_in_calls_p_P₂: c ∈ calls_n P₂,
have c_not_in_calls_p_P₂: c ∉ calls_n P₂, from set.forall_not_mem_of_eq_empty no_calls_n_in_P₂ c,
show «false», from c_not_in_calls_p_P₂ c_in_calls_p_P₂
)
),
have h3: quantifiers_p (P₁ ⋁ P₂) = ∅, from set.eq_empty_of_forall_not_mem (
assume q: callquantifier,
assume : q ∈ quantifiers_p (P₁ ⋁ P₂),
have q ∈ quantifiers_p P₁ ∨ q ∈ quantifiers_p P₂, from prop.has_quantifier_p.or.inv this,
or.elim this (
assume q_in_quantifiers_p_P₁: q ∈ quantifiers_p P₁,
have q_not_in_quantifiers_p_P₁: q ∉ quantifiers_p P₁, from set.forall_not_mem_of_eq_empty no_quantifiers_p_in_P₁ q,
show «false», from q_not_in_quantifiers_p_P₁ q_in_quantifiers_p_P₁
) (
assume q_in_quantifiers_p_P₂: q ∈ quantifiers_p P₂,
have q_not_in_quantifiers_p_P₂: q ∉ quantifiers_p P₂, from set.forall_not_mem_of_eq_empty no_quantifiers_p_in_P₂ q,
show «false», from q_not_in_quantifiers_p_P₂ q_in_quantifiers_p_P₂
)
),
have h4: quantifiers_n (P₁ ⋁ P₂) = ∅, from set.eq_empty_of_forall_not_mem (
assume q: callquantifier,
assume : q ∈ quantifiers_n (P₁ ⋁ P₂),
have q ∈ quantifiers_n P₁ ∨ q ∈ quantifiers_n P₂, from prop.has_quantifier_n.or.inv this,
or.elim this (
assume q_in_quantifiers_p_P₁: q ∈ quantifiers_n P₁,
have q_not_in_quantifiers_p_P₁: q ∉ quantifiers_n P₁, from set.forall_not_mem_of_eq_empty no_quantifiers_n_in_P₁ q,
show «false», from q_not_in_quantifiers_p_P₁ q_in_quantifiers_p_P₁
) (
assume q_in_quantifiers_p_P₂: q ∈ quantifiers_n P₂,
have q_not_in_quantifiers_p_P₂: q ∉ quantifiers_n P₂, from set.forall_not_mem_of_eq_empty no_quantifiers_n_in_P₂ q,
show «false», from q_not_in_quantifiers_p_P₂ q_in_quantifiers_p_P₂
)
),
⟨h1, ⟨h2, ⟨h3, h4⟩⟩⟩
lemma no_instantiations.pre {t₁ t₂: term}: no_instantiations (prop.pre t₁ t₂) :=
have h1: calls_p (prop.pre t₁ t₂) = ∅, from set.eq_empty_of_forall_not_mem (
assume c: calltrigger,
assume : c ∈ calls_p (prop.pre t₁ t₂),
show «false», from prop.has_call_p.pre.inv this
),
have h2: calls_n (prop.pre t₁ t₂) = ∅, from set.eq_empty_of_forall_not_mem (
assume c: calltrigger,
assume : c ∈ calls_n (prop.pre t₁ t₂),
show «false», from prop.has_call_n.pre.inv this
),
have h3: quantifiers_p (prop.pre t₁ t₂) = ∅, from set.eq_empty_of_forall_not_mem (
assume q: callquantifier,
assume : q ∈ quantifiers_p (prop.pre t₁ t₂),
show «false», from prop.has_quantifier_p.pre.inv this
),
have h4: quantifiers_n (prop.pre t₁ t₂) = ∅, from set.eq_empty_of_forall_not_mem (
assume q: callquantifier,
assume : q ∈ quantifiers_n (prop.pre t₁ t₂),
show «false», from prop.has_quantifier_n.pre.inv this
),
⟨h1, ⟨h2, ⟨h3, h4⟩⟩⟩
lemma no_instantiations.pre₁ {t: term} {op: unop}: no_instantiations (prop.pre₁ op t) :=
have h1: calls_p (prop.pre₁ op t) = ∅, from set.eq_empty_of_forall_not_mem (
assume c: calltrigger,
assume : c ∈ calls_p (prop.pre₁ op t),
show «false», from prop.has_call_p.pre₁.inv this
),
have h2: calls_n (prop.pre₁ op t) = ∅, from set.eq_empty_of_forall_not_mem (
assume c: calltrigger,
assume : c ∈ calls_n (prop.pre₁ op t),
show «false», from prop.has_call_n.pre₁.inv this
),
have h3: quantifiers_p (prop.pre₁ op t) = ∅, from set.eq_empty_of_forall_not_mem (
assume q: callquantifier,
assume : q ∈ quantifiers_p (prop.pre₁ op t),
show «false», from prop.has_quantifier_p.pre₁.inv this
),
have h4: quantifiers_n (prop.pre₁ op t) = ∅, from set.eq_empty_of_forall_not_mem (
assume q: callquantifier,
assume : q ∈ quantifiers_n (prop.pre₁ op t),
show «false», from prop.has_quantifier_n.pre₁.inv this
),
⟨h1, ⟨h2, ⟨h3, h4⟩⟩⟩
lemma no_instantiations.pre₂ {t₁ t₂: term} {op: binop}: no_instantiations (prop.pre₂ op t₁ t₂) :=
have h1: calls_p (prop.pre₂ op t₁ t₂) = ∅, from set.eq_empty_of_forall_not_mem (
assume c: calltrigger,
assume : c ∈ calls_p (prop.pre₂ op t₁ t₂),
show «false», from prop.has_call_p.pre₂.inv this
),
have h2: calls_n (prop.pre₂ op t₁ t₂) = ∅, from set.eq_empty_of_forall_not_mem (
assume c: calltrigger,
assume : c ∈ calls_n (prop.pre₂ op t₁ t₂),
show «false», from prop.has_call_n.pre₂.inv this
),
have h3: quantifiers_p (prop.pre₂ op t₁ t₂) = ∅, from set.eq_empty_of_forall_not_mem (
assume q: callquantifier,
assume : q ∈ quantifiers_p (prop.pre₂ op t₁ t₂),
show «false», from prop.has_quantifier_p.pre₂.inv this
),
have h4: quantifiers_n (prop.pre₂ op t₁ t₂) = ∅, from set.eq_empty_of_forall_not_mem (
assume q: callquantifier,
assume : q ∈ quantifiers_n (prop.pre₂ op t₁ t₂),
show «false», from prop.has_quantifier_n.pre₂.inv this
),
⟨h1, ⟨h2, ⟨h3, h4⟩⟩⟩
lemma no_instantiations.post {t₁ t₂: term}: no_instantiations (prop.post t₁ t₂) :=
have h1: calls_p (prop.post t₁ t₂) = ∅, from set.eq_empty_of_forall_not_mem (
assume c: calltrigger,
assume : c ∈ calls_p (prop.post t₁ t₂),
show «false», from prop.has_call_p.post.inv this
),
have h2: calls_n (prop.post t₁ t₂) = ∅, from set.eq_empty_of_forall_not_mem (
assume c: calltrigger,
assume : c ∈ calls_n (prop.post t₁ t₂),
show «false», from prop.has_call_n.post.inv this
),
have h3: quantifiers_p (prop.post t₁ t₂) = ∅, from set.eq_empty_of_forall_not_mem (
assume q: callquantifier,
assume : q ∈ quantifiers_p (prop.post t₁ t₂),
show «false», from prop.has_quantifier_p.post.inv this
),
have h4: quantifiers_n (prop.post t₁ t₂) = ∅, from set.eq_empty_of_forall_not_mem (
assume q: callquantifier,
assume : q ∈ quantifiers_n (prop.post t₁ t₂),
show «false», from prop.has_quantifier_n.post.inv this
),
⟨h1, ⟨h2, ⟨h3, h4⟩⟩⟩
lemma prop.erased_n.implies {P Q: prop}:
(prop.implies P Q).erased_n = vc.implies P.erased_p Q.erased_n :=
by calc
(prop.implies P Q).erased_n = (prop.or (prop.not P) Q).erased_n : rfl
... = ((prop.not P).erased_n ⋁ Q.erased_n) : by unfold prop.erased_n
... = ((vc.not P.erased_p) ⋁ Q.erased_n) : by unfold prop.erased_n
lemma prop.erased_p.implies {P Q: prop}:
(prop.implies P Q).erased_p = vc.implies P.erased_n Q.erased_p :=
by calc
(prop.implies P Q).erased_p = (prop.or (prop.not P) Q).erased_p : rfl
... = ((prop.not P).erased_p ⋁ Q.erased_p) : by unfold prop.erased_p
... = (vc.not P.erased_n ⋁ Q.erased_p) : by unfold prop.erased_p
lemma free_of_erased_n_free {x: var} {P: prop}: (x ∈ FV P.erased_n ∨ x ∈ FV P.erased_p) → x ∈ FV P :=
assume x_free_in_erased_n_or_erased_p,
begin
induction P,
case prop.term t { from (
or.elim x_free_in_erased_n_or_erased_p
(
assume x_free_in_t: free_in_vc x (prop.term t).erased_n,
have (prop.term t).erased_n = vc.term t, by unfold prop.erased_n,
have free_in_vc x (vc.term t), from this ▸ x_free_in_t,
have free_in_term x t, from free_in_vc.term.inv this,
show free_in_prop x (prop.term t), from free_in_prop.term this
) (
assume x_free_in_t: free_in_vc x (prop.term t).erased_p,
have (prop.term t).erased_p = vc.term t, by unfold prop.erased_p,
have free_in_vc x (vc.term t), from this ▸ x_free_in_t,
have free_in_term x t, from free_in_vc.term.inv this,
show free_in_prop x (prop.term t), from free_in_prop.term this
)
)},
case prop.not P₁ ih { from (
or.elim x_free_in_erased_n_or_erased_p
(
assume x_free: x ∈ FV (prop.not P₁).erased_n,
have (prop.not P₁).erased_n = vc.not P₁.erased_p, by unfold prop.erased_n,
have x ∈ FV (vc.not P₁.erased_p), from this ▸ x_free,
have x ∈ FV P₁.erased_p, from free_in_vc.not.inv this,
have x ∈ FV P₁, from ih (or.inr this),
show x ∈ FV P₁.not, from free_in_prop.not this
) (
assume x_free: x ∈ FV (prop.not P₁).erased_p,
have (prop.not P₁).erased_p = vc.not P₁.erased_n, by unfold prop.erased_p,
have x ∈ FV (vc.not P₁.erased_n), from this ▸ x_free,
have x ∈ FV P₁.erased_n, from free_in_vc.not.inv this,
have x ∈ FV P₁, from ih (or.inl this),
show x ∈ FV P₁.not, from free_in_prop.not this
)
)},
case prop.and P₁ P₂ P₁_ih P₂_ih { from (
or.elim x_free_in_erased_n_or_erased_p (
assume x_free: x ∈ FV (P₁ ⋀ P₂).erased_n,
have (prop.and P₁ P₂).erased_n = (P₁.erased_n ⋀ P₂.erased_n), by unfold prop.erased_n,
have x ∈ FV (P₁.erased_n ⋀ P₂.erased_n), from this ▸ x_free,
have x ∈ FV P₁.erased_n ∨ x ∈ FV P₂.erased_n, from free_in_vc.and.inv this,
or.elim this (
assume : x ∈ FV P₁.erased_n,
have x ∈ FV P₁, from P₁_ih (or.inl this),
show x ∈ FV (P₁ ⋀ P₂), from free_in_prop.and₁ this
) (
assume : x ∈ FV P₂.erased_n,
have x ∈ FV P₂, from P₂_ih (or.inl this),
show x ∈ FV (P₁ ⋀ P₂), from free_in_prop.and₂ this
)
) (
assume x_free: x ∈ FV (P₁ ⋀ P₂).erased_p,
have (prop.and P₁ P₂).erased_p = (P₁.erased_p ⋀ P₂.erased_p), by unfold prop.erased_p,
have x ∈ FV (P₁.erased_p ⋀ P₂.erased_p), from this ▸ x_free,
have x ∈ FV P₁.erased_p ∨ x ∈ FV P₂.erased_p, from free_in_vc.and.inv this,
or.elim this (
assume : x ∈ FV P₁.erased_p,
have x ∈ FV P₁, from P₁_ih (or.inr this),
show x ∈ FV (P₁ ⋀ P₂), from free_in_prop.and₁ this
) (
assume : x ∈ FV P₂.erased_p,
have x ∈ FV P₂, from P₂_ih (or.inr this),
show x ∈ FV (P₁ ⋀ P₂), from free_in_prop.and₂ this
)
)
)},
case prop.or P₁ P₂ P₁_ih P₂_ih { from (
or.elim x_free_in_erased_n_or_erased_p (
assume x_free: x ∈ FV (P₁ ⋁ P₂).erased_n,
have (prop.or P₁ P₂).erased_n = (P₁.erased_n ⋁ P₂.erased_n), by unfold prop.erased_n,
have x ∈ FV (P₁.erased_n ⋁ P₂.erased_n), from this ▸ x_free,
have x ∈ FV P₁.erased_n ∨ x ∈ FV P₂.erased_n, from free_in_vc.or.inv this,
or.elim this (
assume : x ∈ FV P₁.erased_n,
have x ∈ FV P₁, from P₁_ih (or.inl this),
show x ∈ FV (P₁ ⋁ P₂), from free_in_prop.or₁ this
) (
assume : x ∈ FV P₂.erased_n,
have x ∈ FV P₂, from P₂_ih (or.inl this),
show x ∈ FV (P₁ ⋁ P₂), from free_in_prop.or₂ this
)
) (
assume x_free: x ∈ FV (P₁ ⋁ P₂).erased_p,
have (prop.or P₁ P₂).erased_p = (P₁.erased_p ⋁ P₂.erased_p), by unfold prop.erased_p,
have x ∈ FV (P₁.erased_p ⋁ P₂.erased_p), from this ▸ x_free,
have x ∈ FV P₁.erased_p ∨ x ∈ FV P₂.erased_p, from free_in_vc.or.inv this,
or.elim this (
assume : x ∈ FV P₁.erased_p,
have x ∈ FV P₁, from P₁_ih (or.inr this),
show x ∈ FV (P₁ ⋁ P₂), from free_in_prop.or₁ this
) (
assume : x ∈ FV P₂.erased_p,
have x ∈ FV P₂, from P₂_ih (or.inr this),
show x ∈ FV (P₁ ⋁ P₂), from free_in_prop.or₂ this
)
)
)},
case prop.pre t₁ t₂ { from (
or.elim x_free_in_erased_n_or_erased_p (
assume x_free: x ∈ FV (prop.pre t₁ t₂).erased_n,
have (prop.pre t₁ t₂).erased_n = vc.pre t₁ t₂, by unfold prop.erased_n,
have x ∈ FV (vc.pre t₁ t₂), from this ▸ x_free,
have x ∈ FV t₁ ∨ x ∈ FV t₂, from free_in_vc.pre.inv this,
or.elim this (
assume : x ∈ FV t₁,
show free_in_prop x (prop.pre t₁ t₂), from free_in_prop.pre₁ this
) (
assume : x ∈ FV t₂,
show free_in_prop x (prop.pre t₁ t₂), from free_in_prop.pre₂ this
)
) (
assume x_free: x ∈ FV (prop.pre t₁ t₂).erased_p,
have (prop.pre t₁ t₂).erased_p = vc.pre t₁ t₂, by unfold prop.erased_p,
have x ∈ FV (vc.pre t₁ t₂), from this ▸ x_free,
have x ∈ FV t₁ ∨ x ∈ FV t₂, from free_in_vc.pre.inv this,
or.elim this (
assume : x ∈ FV t₁,
show free_in_prop x (prop.pre t₁ t₂), from free_in_prop.pre₁ this
) (
assume : x ∈ FV t₂,
show free_in_prop x (prop.pre t₁ t₂), from free_in_prop.pre₂ this
)
)
)},
case prop.pre₁ op t { from (
or.elim x_free_in_erased_n_or_erased_p (
assume x_free_in_t: free_in_vc x (prop.pre₁ op t).erased_n,
have (prop.pre₁ op t).erased_n = vc.pre₁ op t, by unfold prop.erased_n,
have free_in_vc x (vc.pre₁ op t), from this ▸ x_free_in_t,
have free_in_term x t, from free_in_vc.pre₁.inv this,
show free_in_prop x (prop.pre₁ op t), from free_in_prop.preop this
) (
assume x_free_in_t: free_in_vc x (prop.pre₁ op t).erased_p,
have (prop.pre₁ op t).erased_p = vc.pre₁ op t, by unfold prop.erased_p,
have free_in_vc x (vc.pre₁ op t), from this ▸ x_free_in_t,
have free_in_term x t, from free_in_vc.pre₁.inv this,
show free_in_prop x (prop.pre₁ op t), from free_in_prop.preop this
)
)},
case prop.pre₂ op t₁ t₂ { from (
or.elim x_free_in_erased_n_or_erased_p (
assume x_free: x ∈ FV (prop.pre₂ op t₁ t₂).erased_n,
have (prop.pre₂ op t₁ t₂).erased_n = vc.pre₂ op t₁ t₂, by unfold prop.erased_n,
have x ∈ FV (vc.pre₂ op t₁ t₂), from this ▸ x_free,
have x ∈ FV t₁ ∨ x ∈ FV t₂, from free_in_vc.pre₂.inv this,
or.elim this (
assume : x ∈ FV t₁,
show free_in_prop x (prop.pre₂ op t₁ t₂), from free_in_prop.preop₁ this
) (
assume : x ∈ FV t₂,
show free_in_prop x (prop.pre₂ op t₁ t₂), from free_in_prop.preop₂ this
)
) (
assume x_free: x ∈ FV (prop.pre₂ op t₁ t₂).erased_p,
have (prop.pre₂ op t₁ t₂).erased_p = vc.pre₂ op t₁ t₂, by unfold prop.erased_p,
have x ∈ FV (vc.pre₂ op t₁ t₂), from this ▸ x_free,
have x ∈ FV t₁ ∨ x ∈ FV t₂, from free_in_vc.pre₂.inv this,
or.elim this (
assume : x ∈ FV t₁,
show free_in_prop x (prop.pre₂ op t₁ t₂), from free_in_prop.preop₁ this
) (
assume : x ∈ FV t₂,
show free_in_prop x (prop.pre₂ op t₁ t₂), from free_in_prop.preop₂ this
)
)
)},
case prop.post t₁ t₂ { from (
or.elim x_free_in_erased_n_or_erased_p (
assume x_free: x ∈ FV (prop.post t₁ t₂).erased_n,
have (prop.post t₁ t₂).erased_n = vc.post t₁ t₂, by unfold prop.erased_n,
have x ∈ FV (vc.post t₁ t₂), from this ▸ x_free,
have x ∈ FV t₁ ∨ x ∈ FV t₂, from free_in_vc.post.inv this,
or.elim this (
assume : x ∈ FV t₁,
show free_in_prop x (prop.post t₁ t₂), from free_in_prop.post₁ this
) (
assume : x ∈ FV t₂,
show free_in_prop x (prop.post t₁ t₂), from free_in_prop.post₂ this
)
) (
assume x_free: x ∈ FV (prop.post t₁ t₂).erased_p,
have (prop.post t₁ t₂).erased_p = vc.post t₁ t₂, by unfold prop.erased_p,
have x ∈ FV (vc.post t₁ t₂), from this ▸ x_free,
have x ∈ FV t₁ ∨ x ∈ FV t₂, from free_in_vc.post.inv this,
or.elim this (
assume : x ∈ FV t₁,
show free_in_prop x (prop.post t₁ t₂), from free_in_prop.post₁ this
) (
assume : x ∈ FV t₂,
show free_in_prop x (prop.post t₁ t₂), from free_in_prop.post₂ this
)
)
)},
case prop.call t { from (
or.elim x_free_in_erased_n_or_erased_p (
assume x_free: x ∈ FV (prop.call t).erased_n,
have (prop.call t).erased_n = vc.term value.true, by unfold prop.erased_n,
have x ∈ FV (vc.term value.true), from this ▸ x_free,
have x ∈ FV (term.value value.true), from free_in_vc.term.inv this,
absurd this (free_in_term.value.inv)
) (
assume x_free: x ∈ FV (prop.call t).erased_p,
have (prop.call t).erased_p = vc.term value.true, by unfold prop.erased_p,
have x ∈ FV (vc.term value.true), from this ▸ x_free,
have x ∈ FV (term.value value.true), from free_in_vc.term.inv this,
absurd this (free_in_term.value.inv)
)
)},
case prop.forallc y P₁ ih { from (
or.elim x_free_in_erased_n_or_erased_p (
assume x_free: x ∈ FV (prop.forallc y P₁).erased_n,
have (prop.forallc y P₁).erased_n = vc.univ y P₁.erased_n, by unfold prop.erased_n,
have x ∈ FV (vc.univ y P₁.erased_n), from this ▸ x_free,
have h2: (x ≠ y) ∧ free_in_vc x P₁.erased_n, from free_in_vc.univ.inv this,
have x ∈ FV P₁, from ih (or.inl h2.right),
show x ∈ FV (prop.forallc y P₁), from free_in_prop.forallc h2.left this
) (
assume x_free: x ∈ FV (prop.forallc y P₁).erased_p,
have (prop.forallc y P₁).erased_p = vc.term value.true, by unfold prop.erased_p,
have x ∈ FV (vc.term value.true), from this ▸ x_free,
have x ∈ FV (term.value value.true), from free_in_vc.term.inv this,
absurd this (free_in_term.value.inv)
)
)},
case prop.exis y P₁ ih { from (
or.elim x_free_in_erased_n_or_erased_p (
assume x_free: x ∈ FV (prop.exis y P₁).erased_n,
have (prop.exis y P₁).erased_n = vc.not (vc.univ y (vc.not P₁.erased_n)), by unfold prop.erased_n,
have x ∈ FV (vc.not (vc.univ y (vc.not P₁.erased_n))), from this ▸ x_free,
have x ∈ FV (vc.univ y (vc.not P₁.erased_n)), from free_in_vc.not.inv this,
have h2: (x ≠ y) ∧ free_in_vc x (vc.not P₁.erased_n), from free_in_vc.univ.inv this,
have h3: x ∈ FV P₁.erased_n, from free_in_vc.not.inv h2.right,
have x ∈ FV P₁, from ih (or.inl h3),
show x ∈ FV (prop.exis y P₁), from free_in_prop.exis h2.left this
)
(
assume x_free: x ∈ FV (prop.exis y P₁).erased_p,
have (prop.exis y P₁).erased_p = vc.not (vc.univ y (vc.not P₁.erased_p)), by unfold prop.erased_p,
have x ∈ FV (vc.not (vc.univ y (vc.not P₁.erased_p))), from this ▸ x_free,
have x ∈ FV (vc.univ y (vc.not P₁.erased_p)), from free_in_vc.not.inv this,
have h2: (x ≠ y) ∧ free_in_vc x (vc.not P₁.erased_p), from free_in_vc.univ.inv this,
have h3: x ∈ FV P₁.erased_p, from free_in_vc.not.inv h2.right,
have x ∈ FV P₁, from ih (or.inr h3),
show x ∈ FV (prop.exis y P₁), from free_in_prop.exis h2.left this
)
)}
end
lemma free_of_erased_free {x: var} {P: prop}: (x ∈ FV P.erased_p ∨ x ∈ FV P.erased_n) → x ∈ FV P :=
assume : x ∈ FV P.erased_p ∨ x ∈ FV P.erased_n,
have x ∈ FV P.erased_n ∨ x ∈ FV P.erased_p, from this.symm,
show x ∈ FV P, from free_of_erased_n_free this
lemma prop.has_call_p.and_union {P₁ P₂: prop}:
calls_p (P₁ ⋀ P₂) = calls_p P₁ ∪ calls_p P₂ :=
set.eq_of_subset_of_subset (
assume c: calltrigger,
assume : c ∈ calls_p (P₁ ⋀ P₂),
or.elim (prop.has_call_p.and.inv this) (
assume : c ∈ calls_p P₁,
show c ∈ calls_p P₁ ∪ calls_p P₂, from set.mem_union_left (calls_p P₂) this
) (
assume : c ∈ calls_p P₂,
show c ∈ calls_p P₁ ∪ calls_p P₂, from set.mem_union_right (calls_p P₁) this
)
) (
assume c: calltrigger,
assume : c ∈ calls_p P₁ ∪ calls_p P₂,
or.elim (set.mem_or_mem_of_mem_union this) (
assume : c ∈ calls_p P₁,
show c ∈ calls_p (P₁ ⋀ P₂), from prop.has_call_p.and₁ this
) (
assume : c ∈ calls_p P₂,
show c ∈ calls_p (P₁ ⋀ P₂), from prop.has_call_p.and₂ this
)
)
lemma prop.has_call_p.and.symm {P₁ P₂: prop}:
calls_p (P₁ ⋀ P₂) = calls_p (P₂ ⋀ P₁) :=
set.eq_of_subset_of_subset (
assume c: calltrigger,
assume : c ∈ calls_p (P₁ ⋀ P₂),
or.elim (prop.has_call_p.and.inv this) (
assume : c ∈ calls_p P₁,
show c ∈ calls_p (P₂ ⋀ P₁), from prop.has_call_p.and₂ this
) (
assume : c ∈ calls_p P₂,
show c ∈ calls_p (P₂ ⋀ P₁), from prop.has_call_p.and₁ this
)
) (
assume c: calltrigger,
assume : c ∈ calls_p (P₂ ⋀ P₁),
or.elim (prop.has_call_p.and.inv this) (
assume : c ∈ calls_p P₂,
show c ∈ calls_p (P₁ ⋀ P₂), from prop.has_call_p.and₂ this
) (
assume : c ∈ calls_p P₁,
show c ∈ calls_p (P₁ ⋀ P₂), from prop.has_call_p.and₁ this
)
)
lemma prop.has_quantifier_p.and.symm {P₁ P₂: prop}:
quantifiers_p (P₁ ⋀ P₂) = quantifiers_p (P₂ ⋀ P₁) :=
set.eq_of_subset_of_subset (
assume q: callquantifier,
assume : q ∈ quantifiers_p (P₁ ⋀ P₂),
or.elim (prop.has_quantifier_p.and.inv this) (
assume : q ∈ quantifiers_p P₁,
show q ∈ quantifiers_p (P₂ ⋀ P₁), from prop.has_quantifier_p.and₂ this
) (
assume : q ∈ quantifiers_p P₂,
show q ∈ quantifiers_p (P₂ ⋀ P₁), from prop.has_quantifier_p.and₁ this
)
) (
assume q: callquantifier,
assume : q ∈ quantifiers_p (P₂ ⋀ P₁),
or.elim (prop.has_quantifier_p.and.inv this) (
assume : q ∈ quantifiers_p P₂,
show q ∈ quantifiers_p (P₁ ⋀ P₂), from prop.has_quantifier_p.and₂ this
) (
assume : q ∈ quantifiers_p P₁,
show q ∈ quantifiers_p (P₁ ⋀ P₂), from prop.has_quantifier_p.and₁ this
)
)
lemma prop.has_call_p.and.comm {P₁ P₂ P₃: prop}:
calls_p (P₁ ⋀ P₂ ⋀ P₃) = calls_p ((P₁ ⋀ P₂) ⋀ P₃) :=
set.eq_of_subset_of_subset (
assume c: calltrigger,
assume : c ∈ calls_p (P₁ ⋀ P₂ ⋀ P₃),
or.elim (prop.has_call_p.and.inv this) (
assume : c ∈ calls_p P₁,
have c ∈ calls_p (P₁ ⋀ P₂), from prop.has_call_p.and₁ this,
show c ∈ calls_p ((P₁ ⋀ P₂) ⋀ P₃), from prop.has_call_p.and₁ this
) (
assume : c ∈ calls_p (P₂ ⋀ P₃),
or.elim (prop.has_call_p.and.inv this) (
assume : c ∈ calls_p P₂,
have c ∈ calls_p (P₁ ⋀ P₂), from prop.has_call_p.and₂ this,
show c ∈ calls_p ((P₁ ⋀ P₂) ⋀ P₃), from prop.has_call_p.and₁ this
) (
assume : c ∈ calls_p P₃,
show c ∈ calls_p ((P₁ ⋀ P₂) ⋀ P₃), from prop.has_call_p.and₂ this
)
)
) (
assume c: calltrigger,
assume : c ∈ calls_p ((P₁ ⋀ P₂) ⋀ P₃),
or.elim (prop.has_call_p.and.inv this) (
assume : c ∈ calls_p (P₁ ⋀ P₂),
or.elim (prop.has_call_p.and.inv this) (
assume : c ∈ calls_p P₁,
show c ∈ calls_p (P₁ ⋀ P₂ ⋀ P₃), from prop.has_call_p.and₁ this
) (
assume : c ∈ calls_p P₂,
have c ∈ calls_p (P₂ ⋀ P₃), from prop.has_call_p.and₁ this,
show c ∈ calls_p (P₁ ⋀ P₂ ⋀ P₃), from prop.has_call_p.and₂ this
)
) (
assume : c ∈ calls_p P₃,
have c ∈ calls_p (P₂ ⋀ P₃), from prop.has_call_p.and₂ this,
show c ∈ calls_p (P₁ ⋀ P₂ ⋀ P₃), from prop.has_call_p.and₂ this
)
)
lemma prop.has_quantifier_p.and.comm {P₁ P₂ P₃: prop}:
quantifiers_p (P₁ ⋀ P₂ ⋀ P₃) = quantifiers_p ((P₁ ⋀ P₂) ⋀ P₃) :=
set.eq_of_subset_of_subset (
assume q: callquantifier,
assume : q ∈ quantifiers_p (P₁ ⋀ P₂ ⋀ P₃),
or.elim (prop.has_quantifier_p.and.inv this) (
assume : q ∈ quantifiers_p P₁,
have q ∈ quantifiers_p (P₁ ⋀ P₂), from prop.has_quantifier_p.and₁ this,
show q ∈ quantifiers_p ((P₁ ⋀ P₂) ⋀ P₃), from prop.has_quantifier_p.and₁ this
) (
assume : q ∈ quantifiers_p (P₂ ⋀ P₃),
or.elim (prop.has_quantifier_p.and.inv this) (
assume : q ∈ quantifiers_p P₂,
have q ∈ quantifiers_p (P₁ ⋀ P₂), from prop.has_quantifier_p.and₂ this,
show q ∈ quantifiers_p ((P₁ ⋀ P₂) ⋀ P₃), from prop.has_quantifier_p.and₁ this
) (
assume : q ∈ quantifiers_p P₃,
show q ∈ quantifiers_p ((P₁ ⋀ P₂) ⋀ P₃), from prop.has_quantifier_p.and₂ this
)
)
) (
assume q: callquantifier,
assume : q ∈ quantifiers_p ((P₁ ⋀ P₂) ⋀ P₃),
or.elim (prop.has_quantifier_p.and.inv this) (
assume : q ∈ quantifiers_p (P₁ ⋀ P₂),
or.elim (prop.has_quantifier_p.and.inv this) (
assume : q ∈ quantifiers_p P₁,
show q ∈ quantifiers_p (P₁ ⋀ P₂ ⋀ P₃), from prop.has_quantifier_p.and₁ this
) (
assume : q ∈ quantifiers_p P₂,
have q ∈ quantifiers_p (P₂ ⋀ P₃), from prop.has_quantifier_p.and₁ this,
show q ∈ quantifiers_p (P₁ ⋀ P₂ ⋀ P₃), from prop.has_quantifier_p.and₂ this
)
) (
assume : q ∈ quantifiers_p P₃,
have q ∈ quantifiers_p (P₂ ⋀ P₃), from prop.has_quantifier_p.and₂ this,
show q ∈ quantifiers_p (P₁ ⋀ P₂ ⋀ P₃), from prop.has_quantifier_p.and₂ this
)
)
lemma same_calls_p_and_left {P P' Q: prop} {σ: env}:
calls_p_subst σ P' ⊆ calls_p_subst σ P → (calls_p_subst σ (P' ⋀ Q) ⊆ calls_p_subst σ (P ⋀ Q)) :=
assume calls_P'_P: calls_p_subst σ P' ⊆ calls_p_subst σ P,
assume c: calltrigger,
assume : c ∈ calls_p_subst σ (P' ⋀ Q),
or.elim (prop.has_call_p_subst.and.inv this) (
assume : c ∈ calls_p_subst σ P',
have c ∈ calls_p_subst σ P, from set.mem_of_mem_of_subset this calls_P'_P,
show c ∈ calls_p_subst σ (P ⋀ Q), from prop.has_call_p_subst.and₁ this
)
(
assume : c ∈ calls_p_subst σ Q,
show c ∈ calls_p_subst σ (P ⋀ Q), from prop.has_call_p_subst.and₂ this
)
lemma prop.has_call_of_subst_has_call {P: prop} {c: calltrigger} {y: var} {v: value}:
(c ∈ calls_p (prop.subst y v P) → ∃c', c' ∈ calls_p P) ∧
(c ∈ calls_n (prop.subst y v P) → ∃c', c' ∈ calls_n P) :=
begin
induction P,
case prop.term t {
split,
intro h,
unfold prop.subst at h,
cases h,
intro h,
unfold prop.subst at h,
cases h
},
case prop.not P₁ P₁_ih {
split,
intro h,
unfold prop.subst at h,
have h2, from prop.has_call_p.not.inv h,
have h3, from P₁_ih.right h2,
cases h3 with c' a,
from ⟨c', prop.has_call_p.not a⟩,
intro h,
unfold prop.subst at h,
have h2, from prop.has_call_n.not.inv h,
have h3, from P₁_ih.left h2,
cases h3 with c' h3,
from ⟨c', prop.has_call_n.not h3⟩,
},
case prop.and P₂ P₃ P₂_ih P₃_ih {
split,
intro h,
unfold prop.subst at h,
have h2, from prop.has_call_p.and.inv h,
cases h2,
have h3, from P₂_ih.left a,
cases h3 with c' h3,
from ⟨c', prop.has_call_p.and₁ h3⟩,
have h3, from P₃_ih.left a,
cases h3 with c' h3,
from ⟨c', prop.has_call_p.and₂ h3⟩,
intro h,
unfold prop.subst at h,
have h2, from prop.has_call_n.and.inv h,
cases h2,
have h3, from P₂_ih.right a,
cases h3 with c' h3,
from ⟨c', prop.has_call_n.and₁ h3⟩,
have h3, from P₃_ih.right a,
cases h3 with c' h3,
from ⟨c', prop.has_call_n.and₂ h3⟩,
},
case prop.or P₄ P₅ P₄_ih P₅_ih {
split,
intro h,
unfold prop.subst at h,
have h2, from prop.has_call_p.or.inv h,
cases h2,
have h3, from P₄_ih.left a,
cases h3 with c' h3,
from ⟨c', prop.has_call_p.or₁ h3⟩,
have h3, from P₅_ih.left a,
cases h3 with c' h3,
from ⟨c', prop.has_call_p.or₂ h3⟩,
intro h,
unfold prop.subst at h,
have h2, from prop.has_call_n.or.inv h,
cases h2,
have h3, from P₄_ih.right a,
cases h3 with c' h3,
from ⟨c', prop.has_call_n.or₁ h3⟩,
have h3, from P₅_ih.right a,
cases h3 with c' h3,
from ⟨c', prop.has_call_n.or₂ h3⟩,
},
case prop.pre t₁ t₂ {
split,
intro h,
unfold prop.subst at h,
cases h,
intro h,
unfold prop.subst at h,
cases h
},
case prop.pre₁ op t {
split,
intro h,
unfold prop.subst at h,
cases h,
intro h,
unfold prop.subst at h,
cases h
},
case prop.pre₂ op t₁ t₂ {
split,
intro h,
unfold prop.subst at h,
cases h,
intro h,
unfold prop.subst at h,
cases h
},
case prop.post t₁ t₂ {
split,
intro h,
unfold prop.subst at h,
cases h,
intro h,
unfold prop.subst at h,
cases h
},
case prop.call t {
split,
intro h,
existsi (calltrigger.mk t),
apply prop.has_call_p.calltrigger,
intro h,
unfold prop.subst at h,
cases h
},
case prop.forallc z t P ih {
split,
intro h,
unfold prop.subst at h,
cases h,
intro h,
unfold prop.subst at h,
cases h
},
case prop.exis z P ih {
split,
intro h,
unfold prop.subst at h,
cases h,
intro h,
unfold prop.subst at h,
cases h
}
end
lemma prop.has_call_of_subst_env_has_call {P: prop} {σ: env}:
(∀c, c ∈ calls_p (prop.subst_env σ P) → ∃c', c' ∈ calls_p P) ∧
(∀c, c ∈ calls_n (prop.subst_env σ P) → ∃c', c' ∈ calls_n P) :=
begin
induction σ with σ' y v ih,
split,
intro c,
intro h,
unfold prop.subst_env at h,
existsi c,
from h,
intro c,
intro h,
unfold prop.subst_env at h,
existsi c,
from h,
split,
intro c,
intro h,
unfold prop.subst_env at h,
have h2, from prop.has_call_of_subst_has_call.left h,
cases h2 with c' h3,
from ih.left c' h3,
intro c,
intro h,
unfold prop.subst_env at h,
have h2, from prop.has_call_of_subst_has_call.right h,
cases h2 with c' h3,
from ih.right c' h3,
end
lemma find_calls_equiv_has_call {P: prop} {c: calltrigger}:
(c ∈ calls_p P ↔ c ∈ P.find_calls_p) ∧ (c ∈ calls_n P ↔ c ∈ P.find_calls_n) :=
begin
induction P,
case prop.term t {
split,
split,
assume h1,
cases h1,
assume h1,
unfold prop.find_calls_p at h1,
cases h1,
split,
assume h1,
cases h1,
assume h1,
unfold prop.find_calls_n at h1,
cases h1
},
case prop.not P₁ ih {
split,
split,
assume h1,
cases h1,
have h2: c ∈ calls_n P₁, from a,
unfold prop.find_calls_p,
from ih.right.mp h2,
assume h1,
unfold prop.find_calls_p at h1,
have h2, from ih.right.mpr h1,
unfold has_mem.mem at h2,
unfold set.mem at h2,
unfold calls_n at h2,
unfold has_mem.mem,
unfold set.mem,
unfold calls_p,
from prop.has_call_p.not h2,
split,
assume h1,
cases h1,
have h2: c ∈ calls_p P₁, from a,
unfold prop.find_calls_n,
from ih.left.mp h2,
assume h1,
unfold prop.find_calls_n at h1,
have h2, from ih.left.mpr h1,
unfold has_mem.mem at h2,
unfold set.mem at h2,
unfold calls_p at h2,
unfold has_mem.mem,
unfold set.mem,
unfold calls_n,
from prop.has_call_n.not h2
},
case prop.and P₁ P₂ P₁_ih P₂_ih {
split,
split,
assume h1,
cases h1,
have h2: c ∈ calls_p P₁, from a,
unfold prop.find_calls_p,
apply list.mem_append.mpr,
left,
from P₁_ih.left.mp h2,
have h2: c ∈ calls_p P₂, from a,
unfold prop.find_calls_p,
apply list.mem_append.mpr,
right,
from P₂_ih.left.mp h2,
assume h1,
change prop.has_call_p c (prop.and P₁ P₂),
unfold prop.find_calls_p at h1,
have h2, from list.mem_append.mp h1,
cases h2,
have h3, from P₁_ih.left.mpr a,
have h4: prop.has_call_p c P₁, from h3,
from prop.has_call_p.and₁ h4,
have h3, from P₂_ih.left.mpr a,
have h4: prop.has_call_p c P₂, from h3,
from prop.has_call_p.and₂ h4,
split,
assume h1,
cases h1,
have h2: c ∈ calls_n P₁, from a,
unfold prop.find_calls_n,
apply list.mem_append.mpr,
left,
from P₁_ih.right.mp h2,
have h2: c ∈ calls_n P₂, from a,
unfold prop.find_calls_n,
apply list.mem_append.mpr,
right,
from P₂_ih.right.mp h2,
assume h1,
change prop.has_call_n c (prop.and P₁ P₂),
unfold prop.find_calls_n at h1,
have h2, from list.mem_append.mp h1,
cases h2,
have h3, from P₁_ih.right.mpr a,
have h4: prop.has_call_n c P₁, from h3,
from prop.has_call_n.and₁ h4,
have h3, from P₂_ih.right.mpr a,
have h4: prop.has_call_n c P₂, from h3,
from prop.has_call_n.and₂ h4
},
case prop.or P₁ P₂ P₁_ih P₂_ih {
split,
split,
assume h1,
cases h1,
have h2: c ∈ calls_p P₁, from a,
unfold prop.find_calls_p,
apply list.mem_append.mpr,
left,
from P₁_ih.left.mp h2,
have h2: c ∈ calls_p P₂, from a,
unfold prop.find_calls_p,
apply list.mem_append.mpr,
right,
from P₂_ih.left.mp h2,
assume h1,
change prop.has_call_p c (prop.or P₁ P₂),
unfold prop.find_calls_p at h1,
have h2, from list.mem_append.mp h1,
cases h2,
have h3, from P₁_ih.left.mpr a,
have h4: prop.has_call_p c P₁, from h3,
from prop.has_call_p.or₁ h4,
have h3, from P₂_ih.left.mpr a,
have h4: prop.has_call_p c P₂, from h3,
from prop.has_call_p.or₂ h4,
split,
assume h1,
cases h1,
have h2: c ∈ calls_n P₁, from a,
unfold prop.find_calls_n,
apply list.mem_append.mpr,
left,
from P₁_ih.right.mp h2,
have h2: c ∈ calls_n P₂, from a,
unfold prop.find_calls_n,
apply list.mem_append.mpr,
right,
from P₂_ih.right.mp h2,
assume h1,
change prop.has_call_n c (prop.or P₁ P₂),
unfold prop.find_calls_n at h1,
have h2, from list.mem_append.mp h1,
cases h2,
have h3, from P₁_ih.right.mpr a,
have h4: prop.has_call_n c P₁, from h3,
from prop.has_call_n.or₁ h4,
have h3, from P₂_ih.right.mpr a,
have h4: prop.has_call_n c P₂, from h3,
from prop.has_call_n.or₂ h4
},
case prop.pre t₁ t₂ {
split,
split,
assume h1,
cases h1,
assume h1,
unfold prop.find_calls_p at h1,
cases h1,
split,
assume h1,
cases h1,
assume h1,
unfold prop.find_calls_n at h1,
cases h1
},
case prop.pre₁ op t {
split,
split,
assume h1,
cases h1,
assume h1,
unfold prop.find_calls_p at h1,
cases h1,
split,
assume h1,
cases h1,
assume h1,
unfold prop.find_calls_n at h1,
cases h1
},
case prop.pre₂ op t₁ t₂ {
split,
split,
assume h1,
cases h1,
assume h1,
unfold prop.find_calls_p at h1,
cases h1,
split,
assume h1,
cases h1,
assume h1,
unfold prop.find_calls_n at h1,
cases h1
},
case prop.call t {
split,
split,
assume h1,
cases h1,
unfold prop.find_calls_p,
simp,
assume h1,
unfold prop.find_calls_p at h1,
simp at h1,
change prop.has_call_p c (prop.call t),
rw[h1],
from prop.has_call_p.calltrigger,
split,
assume h1,
cases h1,
assume h1,
unfold prop.find_calls_n at h1,
cases h1
},
case prop.post t₁ t₂ {
split,
split,
assume h1,
cases h1,
assume h1,
unfold prop.find_calls_p at h1,
cases h1,
split,
assume h1,
cases h1,
assume h1,
unfold prop.find_calls_n at h1,
cases h1
},
case prop.forallc y P₁ P₁_ih {
split,
split,
assume h1,
cases h1,
assume h1,
unfold prop.find_calls_p at h1,
cases h1,
split,
assume h1,
cases h1,
assume h1,
unfold prop.find_calls_n at h1,
cases h1
},
case prop.exis y P₁ P₁_ih {
split,
split,
assume h1,
cases h1,
assume h1,
unfold prop.find_calls_p at h1,
cases h1,
split,
assume h1,
cases h1,
assume h1,
unfold prop.find_calls_n at h1,
cases h1
}
end
lemma to_vc_valid_of_erased_n_valid:
∀P: prop, ((⊨ P.erased_n) → ⊨ P.to_vc) ∧ ((⊨ P.to_vc) → ⊨ P.erased_p)
| (prop.term t) := begin
split,
unfold prop.erased_n,
unfold prop.to_vc,
from id,
unfold prop.erased_p,
unfold prop.to_vc,
from id
end
| (prop.not P₁) :=
have rec_wf: P₁.simplesize < (prop.not P₁).simplesize, from simplesize_prop_not,
begin
split,
unfold prop.erased_n,
unfold prop.to_vc,
assume h1,
have h2, from mt (to_vc_valid_of_erased_n_valid P₁).right,
have h3, from valid.not.mpr h1,
have h4, from h2 h3,
from valid.not.mp h4,
unfold prop.erased_p,
unfold prop.to_vc,
assume h1,
have h2, from mt (to_vc_valid_of_erased_n_valid P₁).left,
have h3, from valid.not.mpr h1,
have h4, from h2 h3,
from valid.not.mp h4
end
| (prop.and P₁ P₂) :=
have rec_1: P₁.simplesize < (prop.and P₁ P₂).simplesize, from simplesize_prop_and₁,
have rec_2: P₂.simplesize < (prop.and P₁ P₂).simplesize, from simplesize_prop_and₂,
begin
split,
unfold prop.erased_n,
unfold prop.to_vc,
assume h1,
apply valid.and.mp,
split,
show ⊨ prop.to_vc P₁, by begin
have h2, from (valid.and.mpr h1).left,
from (to_vc_valid_of_erased_n_valid P₁).left h2
end,
show ⊨ prop.to_vc P₂, by begin
have h2, from (valid.and.mpr h1).right,
from (to_vc_valid_of_erased_n_valid P₂).left h2
end,
unfold prop.erased_p,
unfold prop.to_vc,
assume h1,
apply valid.and.mp,
split,
show ⊨prop.erased_p P₁, by begin
have h2, from (valid.and.mpr h1).left,
from (to_vc_valid_of_erased_n_valid P₁).right h2
end,
show ⊨prop.erased_p P₂, by begin
have h2, from (valid.and.mpr h1).right,
from (to_vc_valid_of_erased_n_valid P₂).right h2
end
end
| (prop.or P₁ P₂) :=
have rec_1: P₁.simplesize < (prop.or P₁ P₂).simplesize, from simplesize_prop_or₁,
have rec_2: P₂.simplesize < (prop.or P₁ P₂).simplesize, from simplesize_prop_or₂,
begin
split,
unfold prop.erased_n,
unfold prop.to_vc,
assume h2,
cases (valid.or.elim h2),
apply valid.or.left,
from (to_vc_valid_of_erased_n_valid P₁).left a,
apply valid.or.right,
from (to_vc_valid_of_erased_n_valid P₂).left a,
unfold prop.erased_p,
unfold prop.to_vc,
assume h2,
cases (valid.or.elim h2),
apply valid.or.left,
from (to_vc_valid_of_erased_n_valid P₁).right a,
apply valid.or.right,
from (to_vc_valid_of_erased_n_valid P₂).right a
end
| (prop.pre t₁ t₂) := begin
split,
unfold prop.erased_n,
unfold prop.to_vc,
from id,
unfold prop.erased_p,
unfold prop.to_vc,
from id
end
| (prop.pre₁ op t) := begin
split,
unfold prop.erased_n,
unfold prop.to_vc,
from id,
unfold prop.erased_p,
unfold prop.to_vc,
from id
end
| (prop.pre₂ op t₁ t₂) := begin
split,
unfold prop.erased_n,
unfold prop.to_vc,
from id,
unfold prop.erased_p,
unfold prop.to_vc,
from id
end
| (prop.call t) := begin
split,
unfold prop.erased_n,
unfold prop.to_vc,
from id,
unfold prop.erased_p,
unfold prop.to_vc,
from id
end
| (prop.post t₁ t₂) := begin
split,
unfold prop.erased_n,
unfold prop.to_vc,
from id,
unfold prop.erased_p,
unfold prop.to_vc,
from id
end
| (prop.forallc y P₁) :=
begin
split,
unfold prop.erased_n,
unfold prop.to_vc,
assume h1,
have h2, from valid.univ.mpr h1,
apply valid.univ.mp,
assume v,
have h3, from h2 v,
have h3b: (vc.substt y v (prop.erased_n P₁) = vc.subst y v (prop.erased_n P₁)),
from vc.substt_value_eq_subst,
have h3c: ⊨vc.subst y v (prop.erased_n P₁), from h3b ▸ h3,
have h4: (vc.subst y v (prop.erased_n P₁) = prop.erased_n (prop.subst y v P₁)),
from subst_distrib_erased.right,
have h5: ⊨ prop.erased_n (prop.subst y v P₁), from h4 ▸ h3c,
have h6: (vc.subst y v (prop.to_vc P₁) = prop.to_vc (prop.subst y v P₁)),
from subst_distrib_to_vc,
rw[h6],
show ⊨prop.to_vc (prop.subst y v P₁), from (
have ht1: P₁.simplesize = (prop.subst y v P₁).simplesize, from same_simplesize_after_subst,
have ht2: P₁.simplesize < (prop.forallc y P₁).simplesize, from simplesize_prop_forall,
have rec_wf: (prop.subst y v P₁).simplesize < (prop.forallc y P₁).simplesize, from ht1 ▸ ht2,
(to_vc_valid_of_erased_n_valid (prop.subst y v P₁)).left h5
),
assume h1,
unfold prop.erased_p,
from valid.tru
end
| (prop.exis y P₁) := begin
split,
unfold prop.erased_n,
unfold prop.to_vc,
assume h1,
have h2, from valid.not.mpr h1,
apply valid.not.mp,
by_contradiction h3,
have h4: ⊨vc.univ y (vc.not (prop.erased_n P₁)), by begin
have h5, from valid.univ.mpr h3,
apply valid.univ.mp,
assume v: value,
have h6, from h5 v,
have h6b: (vc.substt y v (vc.not (prop.to_vc P₁)) = vc.subst y v (vc.not (prop.to_vc P₁))),
from vc.substt_value_eq_subst,
have h6c: ⊨vc.subst y v (vc.not (prop.to_vc P₁)), from h6b ▸ h6,
have h7: (vc.subst y v (vc.not (prop.to_vc P₁)) = vc.not (vc.subst y v (prop.to_vc P₁))),
by unfold vc.subst,
rw[h7] at h6c,
have h8: (vc.subst y v (vc.not (prop.erased_n P₁)) = vc.not (vc.subst y v (prop.erased_n P₁))),
by unfold vc.subst,
rw[h8],
have h9, from valid.not.mpr h6,
apply valid.not.mp,
by_contradiction h10,
have h11: ⊨vc.subst y v (prop.to_vc P₁), by begin
have h12: (vc.subst y v (prop.erased_n P₁) = prop.erased_n (prop.subst y v P₁)),
from subst_distrib_erased.right,
have h13: ⊨ prop.erased_n (prop.subst y v P₁), from h12 ▸ h10,
have h14: (vc.subst y v (prop.to_vc P₁) = prop.to_vc (prop.subst y v P₁)),
from subst_distrib_to_vc,
rw[h14],
show ⊨prop.to_vc (prop.subst y v P₁), from (
have ht1: P₁.simplesize = (prop.subst y v P₁).simplesize, from same_simplesize_after_subst,
have ht2: P₁.simplesize < (prop.forallc y P₁).simplesize, from simplesize_prop_forall,
have rec_wf: (prop.subst y v P₁).simplesize < (prop.forallc y P₁).simplesize, from ht1 ▸ ht2,
(to_vc_valid_of_erased_n_valid (prop.subst y v P₁)).left h13
)
end,
from h9 h11
end,
from h2 h4,
unfold prop.erased_p,
unfold prop.to_vc,
assume h1,
have h2, from valid.not.mpr h1,
apply valid.not.mp,
by_contradiction h3,
have h4: ⊨vc.univ y (vc.not (prop.to_vc P₁)), by begin
have h5, from valid.univ.mpr h3,
apply valid.univ.mp,
assume v: value,
have h6, from h5 v,
have h7: (vc.subst y v (vc.not (prop.erased_p P₁)) = vc.not (vc.subst y v (prop.erased_p P₁))),
by unfold vc.subst,
have h8: (vc.subst y v (vc.not (prop.to_vc P₁)) = vc.not (vc.subst y v (prop.to_vc P₁))),
by unfold vc.subst,
rw[h8],
have h9, from valid.not.mpr h6,
apply valid.not.mp,
by_contradiction h10,
have h11: ⊨vc.subst y v (prop.erased_p P₁), by begin
have h12: (vc.subst y v (prop.to_vc P₁) = prop.to_vc (prop.subst y v P₁)),
from subst_distrib_to_vc,
have h13: ⊨ prop.to_vc (prop.subst y v P₁), from h12 ▸ h10,
have h14: (vc.subst y v (prop.erased_p P₁) = prop.erased_p (prop.subst y v P₁)),
from subst_distrib_erased.left,
rw[h14],
show ⊨prop.erased_p (prop.subst y v P₁), from (
have ht1: P₁.simplesize = (prop.subst y v P₁).simplesize, from same_simplesize_after_subst,
have ht2: P₁.simplesize < (prop.forallc y P₁).simplesize, from simplesize_prop_forall,
have rec_wf: (prop.subst y v P₁).simplesize < (prop.forallc y P₁).simplesize, from ht1 ▸ ht2,
(to_vc_valid_of_erased_n_valid (prop.subst y v P₁)).right h13
)
end,
from h9 h11
end,
from h2 h4
end
using_well_founded {
rel_tac := λ _ _, `[exact ⟨_, measure_wf $ λ s, s.simplesize⟩],
dec_tac := tactic.assumption
}
lemma and_lifted_p_is_some {P₁ P₂ Q: prop} {x: var}:
prop.lift_p (prop.and P₁ P₂) x = some Q →
(∃Q₁: prop, P₁.lift_p x = some Q₁ ∧ (Q = (Q₁ ⋀ P₂))) ∨ (∃Q₂: prop, P₂.lift_p x = some Q₂ ∧ (Q = (P₁ ⋀ Q₂))) :=
begin
assume h1,
unfold prop.lift_p at h1,
cases (prop.lift_p P₁ x) with Q₁ h2,
unfold prop.lift_p._match_1 at h1,
have h3, from eq_from_map_result_some h1,
cases h3 with Q₂ h4,
right,
existsi Q₂,
from h4,
unfold prop.lift_p._match_1 at h1,
have h2, from option.some.inj h1,
left,
existsi Q₁,
split,
from rfl,
from h2.symm
end
lemma and_lifted_n_is_some {P₁ P₂ Q: prop} {x: var}:
prop.lift_n (prop.and P₁ P₂) x = some Q →
(∃Q₁: prop, P₁.lift_n x = some Q₁ ∧ (Q = (Q₁ ⋀ P₂))) ∨ (∃Q₂: prop, P₂.lift_n x = some Q₂ ∧ (Q = (P₁ ⋀ Q₂))) :=
begin
assume h1,
unfold prop.lift_n at h1,
cases (prop.lift_n P₁ x) with Q₁ h2,
unfold prop.lift_n._match_1 at h1,
have h3, from eq_from_map_result_some h1,
cases h3 with Q₂ h4,
right,
existsi Q₂,
from h4,
unfold prop.lift_n._match_1 at h1,
have h2, from option.some.inj h1,
left,
existsi Q₁,
split,
from rfl,
from h2.symm
end
lemma or_lifted_p_is_some {P₁ P₂ Q: prop} {x: var}:
prop.lift_p (prop.or P₁ P₂) x = some Q →
(∃Q₁: prop, P₁.lift_p x = some Q₁ ∧ (Q = (Q₁ ⋁ P₂))) ∨ (∃Q₂: prop, P₂.lift_p x = some Q₂ ∧ (Q = (P₁ ⋁ Q₂))) :=
begin
assume h1,
unfold prop.lift_p at h1,
cases (prop.lift_p P₁ x) with Q₁ h2,
unfold prop.lift_p._match_2 at h1,
have h3, from eq_from_map_result_some h1,
cases h3 with Q₂ h4,
right,
existsi Q₂,
from h4,
unfold prop.lift_p._match_2 at h1,
have h2, from option.some.inj h1,
left,
existsi Q₁,
split,
from rfl,
from h2.symm
end
lemma or_lifted_n_is_some {P₁ P₂ Q: prop} {x: var}:
prop.lift_n (prop.or P₁ P₂) x = some Q →
(∃Q₁: prop, P₁.lift_n x = some Q₁ ∧ (Q = (Q₁ ⋁ P₂))) ∨ (∃Q₂: prop, P₂.lift_n x = some Q₂ ∧ (Q = (P₁ ⋁ Q₂))) :=
begin
assume h1,
unfold prop.lift_n at h1,
cases (prop.lift_n P₁ x) with Q₁ h2,
unfold prop.lift_n._match_2 at h1,
have h3, from eq_from_map_result_some h1,
cases h3 with Q₂ h4,
right,
existsi Q₂,
from h4,
unfold prop.lift_n._match_2 at h1,
have h2, from option.some.inj h1,
left,
existsi Q₁,
split,
from rfl,
from h2.symm
end
lemma to_vc_valid_of_lifted_to_vc_valid {x: var}:
∀P: prop, ∀Q: prop, ¬ prop.uses_var x P →
(P.lift_p x = some Q → (⊨ Q.to_vc) → ⊨ P.to_vc) ∧
(P.lift_n x = some Q → (⊨ P.to_vc) → ⊨ Q.to_vc)
| (prop.term t) := begin
assume Q,
assume x_unused,
split,
assume h1,
unfold prop.lift_p at h1,
contradiction,
assume h1,
unfold prop.lift_n at h1,
contradiction
end
| (prop.not P₁) :=
have rec_wf: P₁.simplesize < (prop.not P₁).simplesize, from simplesize_prop_not,
begin
assume Q,
assume x_unused,
split,
assume h1,
unfold prop.lift_p at h1,
have h2, from eq_from_map_result_some h1,
cases h2 with Q₂ h3,
assume h4,
rw[h3.right] at h4,
unfold prop.to_vc at h4,
unfold prop.to_vc,
apply valid.not.mp,
have h5, from valid.not.mpr h4,
by_contradiction h6,
have h7: ⊨prop.to_vc Q₂, by begin
have h8: ¬ prop.uses_var x P₁, by begin
assume h9,
have h10, from prop.uses_var.not h9,
from x_unused h10
end,
from (to_vc_valid_of_lifted_to_vc_valid P₁ Q₂ h8).right h3.left h6
end,
from h5 h7,
assume h1,
unfold prop.lift_n at h1,
have h2, from eq_from_map_result_some h1,
cases h2 with Q₂ h3,
assume h4,
rw[h3.right],
unfold prop.to_vc at h4,
unfold prop.to_vc,
apply valid.not.mp,
have h5, from valid.not.mpr h4,
by_contradiction h6,
have h7: ⊨prop.to_vc P₁, by begin
have h8: ¬ prop.uses_var x P₁, by begin
assume h9,
have h10, from prop.uses_var.not h9,
from x_unused h10
end,
from (to_vc_valid_of_lifted_to_vc_valid P₁ Q₂ h8).left h3.left h6
end,
from h5 h7
end
| (prop.and P₁ P₂) :=
have rec_1: P₁.simplesize < (prop.and P₁ P₂).simplesize, from simplesize_prop_and₁,
have rec_2: P₂.simplesize < (prop.and P₁ P₂).simplesize, from simplesize_prop_and₂,
begin
assume Q,
assume x_unused,
split,
assume h1,
have h2, from and_lifted_p_is_some h1,
cases h2 with h3 h4,
cases h3 with Q₁ h4,
assume h5,
rw[h4.right] at h5,
have h6: ⊨prop.to_vc (prop.and Q₁ P₂), from h5,
unfold prop.to_vc at h6,
unfold prop.to_vc,
apply valid.and.mp,
split,
have h7, from (valid.and.mpr h6).left,
have h8: ¬ prop.uses_var x P₁, by begin
assume h9,
have h10: prop.uses_var x (prop.and P₁ P₂), from prop.uses_var.and₁ h9,
from x_unused h10
end,
from (to_vc_valid_of_lifted_to_vc_valid P₁ Q₁ h8).left h4.left h7,
from (valid.and.mpr h6).right,
cases h4 with Q₂ h5,
assume h6,
rw[h5.right] at h6,
have h7: ⊨prop.to_vc (prop.and P₁ Q₂), from h6,
unfold prop.to_vc at h7,
have h8, from valid.and.mpr h7,
unfold prop.to_vc,
apply valid.and.mp,
split,
from h8.left,
have h9: ¬ prop.uses_var x P₂, by begin
assume h9,
have h10: prop.uses_var x (prop.and P₁ P₂), from prop.uses_var.and₂ h9,
from x_unused h10
end,
from (to_vc_valid_of_lifted_to_vc_valid P₂ Q₂ h9).left h5.left h8.right,
assume h1,
have h2, from and_lifted_n_is_some h1,
cases h2 with h3 h4,
cases h3 with Q₁ h4,
assume h5,
rw[h4.right],
unfold prop.to_vc at h5,
change ⊨prop.to_vc (prop.and Q₁ P₂),
unfold prop.to_vc,
apply valid.and.mp,
split,
have h7, from (valid.and.mpr h5).left,
have h8: ¬ prop.uses_var x P₁, by begin
assume h9,
have h10: prop.uses_var x (prop.and P₁ P₂), from prop.uses_var.and₁ h9,
from x_unused h10
end,
from (to_vc_valid_of_lifted_to_vc_valid P₁ Q₁ h8).right h4.left h7,
from (valid.and.mpr h5).right,
cases h4 with Q₂ h5,
assume h6,
rw[h5.right],
change ⊨prop.to_vc (prop.and P₁ Q₂),
unfold prop.to_vc,
unfold prop.to_vc at h6,
have h7, from valid.and.mpr h6,
apply valid.and.mp,
split,
from h7.left,
have h8: ¬ prop.uses_var x P₂, by begin
assume h9,
have h10: prop.uses_var x (prop.and P₁ P₂), from prop.uses_var.and₂ h9,
from x_unused h10
end,
from (to_vc_valid_of_lifted_to_vc_valid P₂ Q₂ h8).right h5.left h7.right
end
| (prop.or P₁ P₂) :=
have rec_1: P₁.simplesize < (prop.or P₁ P₂).simplesize, from simplesize_prop_or₁,
have rec_2: P₂.simplesize < (prop.or P₁ P₂).simplesize, from simplesize_prop_or₂,
begin
assume Q,
assume x_unused,
split,
assume h1,
have h2, from or_lifted_p_is_some h1,
cases h2 with h3 h4,
cases h3 with Q₁ h4,
assume h5,
rw[h4.right] at h5,
have h6: ⊨prop.to_vc (prop.or Q₁ P₂), from h5,
unfold prop.to_vc at h6,
unfold prop.to_vc,
cases (valid.or.elim h6) with h7 h8,
apply valid.or.left,
have h8: ¬ prop.uses_var x P₁, by begin
assume h9,
have h10: prop.uses_var x (prop.or P₁ P₂), from prop.uses_var.or₁ h9,
from x_unused h10
end,
from (to_vc_valid_of_lifted_to_vc_valid P₁ Q₁ h8).left h4.left h7,
apply valid.or.right,
from h8,
assume h5,
unfold prop.to_vc,
cases h4 with Q₂ h6,
rw[h6.right] at h5,
have h7: ⊨prop.to_vc (prop.or P₁ Q₂), from h5,
unfold prop.to_vc at h7,
cases (valid.or.elim h7) with h8 h9,
apply valid.or.left,
from h8,
apply valid.or.right,
have h10: ¬ prop.uses_var x P₂, by begin
assume h9,
have h10: prop.uses_var x (prop.or P₁ P₂), from prop.uses_var.or₂ h9,
from x_unused h10
end,
from (to_vc_valid_of_lifted_to_vc_valid P₂ Q₂ h10).left h6.left h9,
assume h1,
have h2, from or_lifted_n_is_some h1,
cases h2 with h3 h4,
cases h3 with Q₁ h4,
assume h5,
rw[h4.right],
change ⊨prop.to_vc (prop.or Q₁ P₂),
unfold prop.to_vc at h5,
unfold prop.to_vc,
cases (valid.or.elim h5) with h7 h8,
apply valid.or.left,
have h8: ¬ prop.uses_var x P₁, by begin
assume h9,
have h10: prop.uses_var x (prop.or P₁ P₂), from prop.uses_var.or₁ h9,
from x_unused h10
end,
from (to_vc_valid_of_lifted_to_vc_valid P₁ Q₁ h8).right h4.left h7,
apply valid.or.right,
from h8,
assume h5,
unfold prop.to_vc at h5,
cases h4 with Q₂ h6,
rw[h6.right],
change ⊨prop.to_vc (prop.or P₁ Q₂),
unfold prop.to_vc,
cases (valid.or.elim h5) with h8 h9,
apply valid.or.left,
from h8,
apply valid.or.right,
have h10: ¬ prop.uses_var x P₂, by begin
assume h9,
have h10: prop.uses_var x (prop.or P₁ P₂), from prop.uses_var.or₂ h9,
from x_unused h10
end,
from (to_vc_valid_of_lifted_to_vc_valid P₂ Q₂ h10).right h6.left h9
end
| (prop.pre t₁ t₂) := begin
assume Q,
assume x_unused,
split,
assume h1,
unfold prop.lift_p at h1,
contradiction,
assume h1,
unfold prop.lift_n at h1,
contradiction
end
| (prop.pre₁ op t) := begin
assume Q,
assume x_unused,
split,
assume h1,
unfold prop.lift_p at h1,
contradiction,
assume h1,
unfold prop.lift_n at h1,
contradiction
end
| (prop.pre₂ op t₁ t₂) := begin
assume Q,
assume x_unused,
split,
assume h1,
unfold prop.lift_p at h1,
contradiction,
assume h1,
unfold prop.lift_n at h1,
contradiction
end
| (prop.call t) := begin
assume Q,
assume x_unused,
split,
assume h1,
unfold prop.lift_p at h1,
contradiction,
assume h1,
unfold prop.lift_n at h1,
contradiction
end
| (prop.post t₁ t₂) := begin
assume Q,
assume x_unused,
split,
assume h1,
unfold prop.lift_p at h1,
contradiction,
assume h1,
unfold prop.lift_n at h1,
contradiction
end
| (prop.forallc y P₁) := begin
assume Q,
assume x_unused,
split,
assume h1,
unfold prop.lift_p at h1,
have h2, from option.some.inj h1,
assume h3,
rw[h2.symm] at h3,
unfold prop.to_vc at h3,
cases (valid.or.elim h3) with h4 h5,
have h5, from valid.not.mpr h4,
have h6: ⊨vc.term ↑value.true, from valid.tru,
contradiction,
unfold prop.to_vc,
apply valid.univ.mp,
assume v,
have h6: (vc.substt y x (prop.to_vc P₁) = prop.to_vc (prop.substt y x P₁)),
from substt_distrib_to_vc,
rw[←h6] at h5,
by_cases (free_in_vc y P₁.to_vc) with h7,
have h8: ⊨ vc.substt x y (vc.substt y ↑x (prop.to_vc P₁)), from valid.alpha_equiv h5,
have h9: ¬ vc.uses_var x (prop.to_vc P₁), by begin
assume h10,
have h11, from prop_uses_var_of_to_vc_uses_var h10,
have h12: prop.uses_var x (prop.forallc y P₁), from prop.uses_var.forallc h11,
contradiction
end,
have h10: (vc.substt x y (vc.substt y x (prop.to_vc P₁)) = (prop.to_vc P₁)),
from vc.substt_var_cancel h9,
rw[h10] at h8,
have h11: ⊨ vc.univ y P₁.to_vc, from valid.univ.free ⟨h7, h8⟩,
have h12: ⊨ vc.substt y v (prop.to_vc P₁),
from valid.univ.mpr h11 v,
have h13: (vc.substt y v (prop.to_vc P₁) = vc.subst y v (prop.to_vc P₁)),
from vc.substt_value_eq_subst,
rw[h13] at h12,
from h12,
have h8: (vc.subst y v (prop.to_vc P₁) = (prop.to_vc P₁)),
from unchanged_of_subst_nonfree_vc h7,
rw[h8],
have h9: (vc.substt y x (prop.to_vc P₁) = (prop.to_vc P₁)),
from unchanged_of_substt_nonfree_vc h7,
rw[h9] at h5,
from h5,
assume h1,
unfold prop.lift_n at h1,
exfalso,
from option.no_confusion h1
end
| (prop.exis y P₁) := begin
assume Q,
assume x_unused,
split,
assume h1,
unfold prop.lift_p at h1,
exfalso,
from option.no_confusion h1,
assume h1,
unfold prop.lift_n at h1,
exfalso,
from option.no_confusion h1,
end
using_well_founded {
rel_tac := λ _ _, `[exact ⟨_, measure_wf $ λ s, s.simplesize⟩],
dec_tac := tactic.assumption
}
lemma to_vc_valid_of_lift_all_to_vc_valid: ∀P:prop, (⊨ P.lift_all.to_vc) → ⊨ P.to_vc
| P :=
begin
assume h1,
unfold prop.lift_all at h1,
by_cases (option.is_none_prop (prop.lift_p P (prop.fresh_var P))) with h2,
have h3: (prop.lift_p P (prop.fresh_var P) = none), from option.is_none.inv.mpr h2,
simp[h3] at h1,
from h1,
have h3, from option.some_iff_not_none.mpr h2,
have h4: ∃Q, (prop.lift_p P (prop.fresh_var P) = some Q), from option.is_some_iff_exists.mp h3,
cases h4 with Q h5,
simp[h5] at h1,
show ⊨ prop.to_vc P, from (
have Q.num_quantifiers < P.num_quantifiers, from (lifted_prop_smaller Q).left h5,
have h6: ⊨ Q.to_vc, from to_vc_valid_of_lift_all_to_vc_valid Q h1,
have P.fresh_var ≤ P.fresh_var, from le_refl P.fresh_var,
have ¬ prop.uses_var (prop.fresh_var P) P, from prop.fresh_var_is_unused P.fresh_var this,
(to_vc_valid_of_lifted_to_vc_valid P Q this).left h5 h6
)
end
using_well_founded {
rel_tac := λ _ _, `[exact ⟨_, measure_wf $ λ s, s.num_quantifiers ⟩],
dec_tac := tactic.assumption
}
lemma erased_valid_of_instantiated_with_erased_valid {P: prop} {t: calltrigger}:
((⊨ (P.instantiate_with_n t).to_vc) → ⊨ P.to_vc) ∧
((⊨ P.to_vc) → ⊨ (P.instantiate_with_p t).to_vc) :=
begin
induction P,
case prop.term t {
split,
unfold prop.instantiate_with_n,
from id,
unfold prop.instantiate_with_p,
from id
},
case prop.not P₁ ih {
split,
unfold prop.instantiate_with_n,
unfold prop.to_vc,
assume h1,
apply valid.not.mp,
by_contradiction,
have h4: ⊨ prop.to_vc (prop.instantiate_with_p P₁ t),
from ih.right a,
have h5, from valid.not.mpr h1,
from h5 h4,
unfold prop.instantiate_with_p,
unfold prop.to_vc,
assume h1,
apply valid.not.mp,
by_contradiction,
have h2: ⊨ prop.to_vc P₁,
from ih.left a,
have h3, from valid.not.mpr h1,
from h3 h2
},
case prop.and P₁ P₂ P₁_ih P₂_ih {
split,
unfold prop.instantiate_with_n,
unfold prop.to_vc,
assume h1,
have h2: ⊨ prop.to_vc (prop.and (prop.instantiate_with_n P₁ t) (prop.instantiate_with_n P₂ t)), from h1,
unfold prop.to_vc at h2,
have h3, from valid.and.mpr h2,
apply valid.and.mp,
split,
show ⊨ prop.to_vc P₁, from P₁_ih.left h3.left,
show ⊨ prop.to_vc P₂, from P₂_ih.left h3.right,
unfold prop.instantiate_with_p,
unfold prop.to_vc,
assume h1,
have h2, from valid.and.mpr h1,
change ⊨ prop.to_vc (prop.and (prop.instantiate_with_p P₁ t) (prop.instantiate_with_p P₂ t)),
unfold prop.to_vc,
apply valid.and.mp,
split,
show ⊨ prop.to_vc (prop.instantiate_with_p P₁ t), from P₁_ih.right h2.left,
show ⊨ prop.to_vc (prop.instantiate_with_p P₂ t), from P₂_ih.right h2.right
},
case prop.or P₁ P₂ P₁_ih P₂_ih {
split,
unfold prop.instantiate_with_n,
unfold prop.to_vc,
assume h1,
have h2: ⊨ prop.to_vc (prop.or (prop.instantiate_with_n P₁ t) (prop.instantiate_with_n P₂ t)), from h1,
unfold prop.to_vc at h2,
cases valid.or.elim h2 with h3 h4,
apply valid.or.left,
from P₁_ih.left h3,
apply valid.or.right,
from P₂_ih.left h4,
unfold prop.instantiate_with_p,
unfold prop.to_vc,
assume h1,
change ⊨ prop.to_vc (prop.or (prop.instantiate_with_p P₁ t) (prop.instantiate_with_p P₂ t)),
unfold prop.to_vc,
cases valid.or.elim h1 with h3 h4,
apply valid.or.left,
from P₁_ih.right h3,
apply valid.or.right,
from P₂_ih.right h4
},
case prop.pre t₁ t₂ {
split,
unfold prop.instantiate_with_n,
from id,
unfold prop.instantiate_with_p,
from id
},
case prop.pre₁ op t {
split,
unfold prop.instantiate_with_n,
from id,
unfold prop.instantiate_with_p,
from id
},
case prop.pre₂ op t₁ t₂ {
split,
unfold prop.instantiate_with_n,
from id,
unfold prop.instantiate_with_p,
from id
},
case prop.call t {
split,
unfold prop.instantiate_with_n,
from id,
unfold prop.instantiate_with_p,
from id
},
case prop.post t₁ t₂ {
split,
unfold prop.instantiate_with_n,
from id,
unfold prop.instantiate_with_p,
from id
},
case prop.forallc y P₁ P₁_ih {
split,
unfold prop.instantiate_with_n,
from id,
unfold prop.instantiate_with_p,
unfold prop.to_vc,
assume h1,
change ⊨ prop.to_vc (prop.and (prop.forallc y P₁) (prop.substt y (t.x) P₁)),
unfold prop.to_vc,
apply valid.and.mp,
split,
from h1,
have h2: (vc.substt y (t.x) (prop.to_vc P₁) = prop.to_vc (prop.substt y (t.x) P₁)),
from substt_distrib_to_vc,
rw[←h2],
from valid.univ.mpr h1 t.x
},
case prop.exis y P₁ P₁_ih {
split,
unfold prop.instantiate_with_n,
from id,
unfold prop.instantiate_with_p,
from id
}
end
lemma to_vc_valid_of_instantiate_with_all_lifted_to_vc_valid {T: list calltrigger}:
∀P: prop, (⊨ (P.instantiate_with_all T).lift_all.to_vc) → ⊨ P.to_vc :=
begin
induction T,
case list.nil {
assume P,
assume h1,
unfold prop.instantiate_with_all at h1,
from to_vc_valid_of_lift_all_to_vc_valid P h1
},
case list.cons t T ih {
assume P,
assume h1,
unfold prop.instantiate_with_all at h1,
have h3, from ih (prop.instantiate_with_n P t),
have h4, from h3 h1,
from erased_valid_of_instantiated_with_erased_valid.left h4
}
end
lemma lifted_all_to_vc_valid_of_instantiate_rep_valid {n: ℕ}:
∀P: prop, (⊨ P.instantiate_rep n) → ⊨ P.lift_all.to_vc :=
begin
induction n,
case nat.zero {
assume P,
assume h1,
unfold prop.instantiate_rep at h1,
from (to_vc_valid_of_erased_n_valid (prop.lift_all P)).left h1
},
case nat.succ n ih {
assume P,
unfold prop.instantiate_rep,
assume h1,
have h2, from ih (prop.instantiate_with_all (prop.lift_all P) (prop.find_calls_n (prop.lift_all P))) h1,
from to_vc_valid_of_instantiate_with_all_lifted_to_vc_valid P.lift_all h2
}
end
-- inst_n(P) ⇒ inst_p(P)
-- ⇘ ⇗
-- ⇑ P ⇓
-- ⇗ ⇘
-- erased_n(P) ⇒ erased_p(P)
lemma to_vc_valid_of_instantiated_n_valid {P: prop}:
(⊨ P.instantiated_n) → ⊨ P.to_vc :=
assume : ⊨ P.instantiated_n,
have ⊨ P.instantiate_rep P.max_nesting_level, by { unfold prop.instantiated_n at this, from this },
have ⊨ P.lift_all.to_vc, from lifted_all_to_vc_valid_of_instantiate_rep_valid P this,
show ⊨ P.to_vc, from to_vc_valid_of_lift_all_to_vc_valid P this
lemma vc_valid_from_inst_valid {P: prop}:
⟪ P ⟫ → ⦃ P ⦄ :=
assume h1: ⟪ P ⟫,
assume σ: env,
assume h2: closed_subst σ P,
have h3: ⊨ (prop.subst_env σ P).instantiated_n, from h1 σ h2,
have h4: ⊨ (prop.subst_env σ P).to_vc, from to_vc_valid_of_instantiated_n_valid h3,
have h5: (vc.subst_env σ (prop.to_vc P) = prop.to_vc (prop.subst_env σ P)),
from subst_env_distrib_to_vc,
show ⊨ vc.subst_env σ (prop.to_vc P), from h5.symm ▸ h4
|
38133a3e4bee05c50c949fedefa13e6950ba0c07 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/logic/basic.lean | 02a810e41786baeb3601302fe93ecbe765a21845 | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 49,098 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura
-/
import tactic.doc_commands
/-!
# Basic logic properties
This file is one of the earliest imports in mathlib.
## Implementation notes
Theorems that require decidability hypotheses are in the namespace "decidable".
Classical versions are in the namespace "classical".
In the presence of automation, this whole file may be unnecessary. On the other hand,
maybe it is useful for writing automation.
-/
local attribute [instance, priority 10] classical.prop_decidable
section miscellany
/- We add the `inline` attribute to optimize VM computation using these declarations. For example,
`if p ∧ q then ... else ...` will not evaluate the decidability of `q` if `p` is false. -/
attribute [inline] and.decidable or.decidable decidable.false xor.decidable iff.decidable
decidable.true implies.decidable not.decidable ne.decidable
bool.decidable_eq decidable.to_bool
attribute [simp] cast_eq
variables {α : Type*} {β : Type*}
/-- An identity function with its main argument implicit. This will be printed as `hidden` even
if it is applied to a large term, so it can be used for elision,
as done in the `elide` and `unelide` tactics. -/
@[reducible] def hidden {α : Sort*} {a : α} := a
/-- Ex falso, the nondependent eliminator for the `empty` type. -/
def empty.elim {C : Sort*} : empty → C.
instance : subsingleton empty := ⟨λa, a.elim⟩
instance subsingleton.prod {α β : Type*} [subsingleton α] [subsingleton β] : subsingleton (α × β) :=
⟨by { intros a b, cases a, cases b, congr, }⟩
instance : decidable_eq empty := λa, a.elim
instance sort.inhabited : inhabited (Sort*) := ⟨punit⟩
instance sort.inhabited' : inhabited (default (Sort*)) := ⟨punit.star⟩
instance psum.inhabited_left {α β} [inhabited α] : inhabited (psum α β) := ⟨psum.inl (default _)⟩
instance psum.inhabited_right {α β} [inhabited β] : inhabited (psum α β) := ⟨psum.inr (default _)⟩
@[priority 10] instance decidable_eq_of_subsingleton
{α} [subsingleton α] : decidable_eq α
| a b := is_true (subsingleton.elim a b)
@[simp] lemma eq_iff_true_of_subsingleton [subsingleton α] (x y : α) :
x = y ↔ true :=
by cc
/-- Add an instance to "undo" coercion transitivity into a chain of coercions, because
most simp lemmas are stated with respect to simple coercions and will not match when
part of a chain. -/
@[simp] theorem coe_coe {α β γ} [has_coe α β] [has_coe_t β γ]
(a : α) : (a : γ) = (a : β) := rfl
theorem coe_fn_coe_trans
{α β γ} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_fun γ]
(x : α) : @coe_fn α _ x = @coe_fn β _ x := rfl
@[simp] theorem coe_fn_coe_base
{α β} [has_coe α β] [has_coe_to_fun β]
(x : α) : @coe_fn α _ x = @coe_fn β _ x := rfl
theorem coe_sort_coe_trans
{α β γ} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_sort γ]
(x : α) : @coe_sort α _ x = @coe_sort β _ x := rfl
/--
Many structures such as bundled morphisms coerce to functions so that you can
transparently apply them to arguments. For example, if `e : α ≃ β` and `a : α`
then you can write `e a` and this is elaborated as `⇑e a`. This type of
coercion is implemented using the `has_coe_to_fun`type class. There is one
important consideration:
If a type coerces to another type which in turn coerces to a function,
then it **must** implement `has_coe_to_fun` directly:
```lean
structure sparkling_equiv (α β) extends α ≃ β
-- if we add a `has_coe` instance,
instance {α β} : has_coe (sparkling_equiv α β) (α ≃ β) :=
⟨sparkling_equiv.to_equiv⟩
-- then a `has_coe_to_fun` instance **must** be added as well:
instance {α β} : has_coe_to_fun (sparkling_equiv α β) :=
⟨λ _, α → β, λ f, f.to_equiv.to_fun⟩
```
(Rationale: if we do not declare the direct coercion, then `⇑e a` is not in
simp-normal form. The lemma `coe_fn_coe_base` will unfold it to `⇑↑e a`. This
often causes loops in the simplifier.)
-/
library_note "function coercion"
@[simp] theorem coe_sort_coe_base
{α β} [has_coe α β] [has_coe_to_sort β]
(x : α) : @coe_sort α _ x = @coe_sort β _ x := rfl
/-- `pempty` is the universe-polymorphic analogue of `empty`. -/
@[derive decidable_eq]
inductive {u} pempty : Sort u
/-- Ex falso, the nondependent eliminator for the `pempty` type. -/
def pempty.elim {C : Sort*} : pempty → C.
instance subsingleton_pempty : subsingleton pempty := ⟨λa, a.elim⟩
@[simp] lemma not_nonempty_pempty : ¬ nonempty pempty :=
assume ⟨h⟩, h.elim
@[simp] theorem forall_pempty {P : pempty → Prop} : (∀ x : pempty, P x) ↔ true :=
⟨λ h, trivial, λ h x, by cases x⟩
@[simp] theorem exists_pempty {P : pempty → Prop} : (∃ x : pempty, P x) ↔ false :=
⟨λ h, by { cases h with w, cases w }, false.elim⟩
lemma congr_arg_heq {α} {β : α → Sort*} (f : ∀ a, β a) : ∀ {a₁ a₂ : α}, a₁ = a₂ → f a₁ == f a₂
| a _ rfl := heq.rfl
lemma plift.down_inj {α : Sort*} : ∀ (a b : plift α), a.down = b.down → a = b
| ⟨a⟩ ⟨b⟩ rfl := rfl
-- missing [symm] attribute for ne in core.
attribute [symm] ne.symm
lemma ne_comm {α} {a b : α} : a ≠ b ↔ b ≠ a := ⟨ne.symm, ne.symm⟩
@[simp] lemma eq_iff_eq_cancel_left {b c : α} :
(∀ {a}, a = b ↔ a = c) ↔ (b = c) :=
⟨λ h, by rw [← h], λ h a, by rw h⟩
@[simp] lemma eq_iff_eq_cancel_right {a b : α} :
(∀ {c}, a = c ↔ b = c) ↔ (a = b) :=
⟨λ h, by rw h, λ h a, by rw h⟩
/-- Wrapper for adding elementary propositions to the type class systems.
Warning: this can easily be abused. See the rest of this docstring for details.
Certain propositions should not be treated as a class globally,
but sometimes it is very convenient to be able to use the type class system
in specific circumstances.
For example, `zmod p` is a field if and only if `p` is a prime number.
In order to be able to find this field instance automatically by type class search,
we have to turn `p.prime` into an instance implicit assumption.
On the other hand, making `nat.prime` a class would require a major refactoring of the library,
and it is questionable whether making `nat.prime` a class is desirable at all.
The compromise is to add the assumption `[fact p.prime]` to `zmod.field`.
In particular, this class is not intended for turning the type class system
into an automated theorem prover for first order logic. -/
@[class]
def fact (p : Prop) := p
lemma fact.elim {p : Prop} (h : fact p) : p := h
end miscellany
/-!
### Declarations about propositional connectives
-/
theorem false_ne_true : false ≠ true
| h := h.symm ▸ trivial
section propositional
variables {a b c d : Prop}
/-! ### Declarations about `implies` -/
theorem iff_of_eq (e : a = b) : a ↔ b := e ▸ iff.rfl
theorem iff_iff_eq : (a ↔ b) ↔ a = b := ⟨propext, iff_of_eq⟩
@[simp] lemma eq_iff_iff {p q : Prop} : (p = q) ↔ (p ↔ q) := iff_iff_eq.symm
@[simp] theorem imp_self : (a → a) ↔ true := iff_true_intro id
theorem imp_intro {α β : Prop} (h : α) : β → α := λ _, h
theorem imp_false : (a → false) ↔ ¬ a := iff.rfl
theorem imp_and_distrib {α} : (α → b ∧ c) ↔ (α → b) ∧ (α → c) :=
⟨λ h, ⟨λ ha, (h ha).left, λ ha, (h ha).right⟩,
λ h ha, ⟨h.left ha, h.right ha⟩⟩
@[simp] theorem and_imp : (a ∧ b → c) ↔ (a → b → c) :=
iff.intro (λ h ha hb, h ⟨ha, hb⟩) (λ h ⟨ha, hb⟩, h ha hb)
theorem iff_def : (a ↔ b) ↔ (a → b) ∧ (b → a) :=
iff_iff_implies_and_implies _ _
theorem iff_def' : (a ↔ b) ↔ (b → a) ∧ (a → b) :=
iff_def.trans and.comm
theorem imp_true_iff {α : Sort*} : (α → true) ↔ true :=
iff_true_intro $ λ_, trivial
@[simp] theorem imp_iff_right (ha : a) : (a → b) ↔ b :=
⟨λf, f ha, imp_intro⟩
/-! ### Declarations about `not` -/
/-- Ex falso for negation. From `¬ a` and `a` anything follows. This is the same as `absurd` with
the arguments flipped, but it is in the `not` namespace so that projection notation can be used. -/
def not.elim {α : Sort*} (H1 : ¬a) (H2 : a) : α := absurd H2 H1
@[reducible] theorem not.imp {a b : Prop} (H2 : ¬b) (H1 : a → b) : ¬a := mt H1 H2
theorem not_not_of_not_imp : ¬(a → b) → ¬¬a :=
mt not.elim
theorem not_of_not_imp {a : Prop} : ¬(a → b) → ¬b :=
mt imp_intro
theorem dec_em (p : Prop) [decidable p] : p ∨ ¬p := decidable.em p
theorem em (p : Prop) : p ∨ ¬ p := classical.em _
theorem or_not {p : Prop} : p ∨ ¬ p := em _
theorem by_contradiction {p} : (¬p → false) → p := decidable.by_contradiction
-- alias by_contradiction ← by_contra
theorem by_contra {p} : (¬p → false) → p := decidable.by_contradiction
/--
In most of mathlib, we use the law of excluded middle (LEM) and the axiom of choice (AC) freely.
The `decidable` namespace contains versions of lemmas from the root namespace that explicitly
attempt to avoid the axiom of choice, usually by adding decidability assumptions on the inputs.
You can check if a lemma uses the axiom of choice by using `#print axioms foo` and seeing if
`classical.choice` appears in the list.
-/
library_note "decidable namespace"
-- See Note [decidable namespace]
protected theorem decidable.not_not [decidable a] : ¬¬a ↔ a :=
iff.intro decidable.by_contradiction not_not_intro
/-- The Double Negation Theorem: `¬ ¬ P` is equivalent to `P`.
The left-to-right direction, double negation elimination (DNE),
is classically true but not constructively. -/
@[simp] theorem not_not : ¬¬a ↔ a := decidable.not_not
theorem of_not_not : ¬¬a → a := by_contra
-- See Note [decidable namespace]
protected theorem decidable.of_not_imp [decidable a] (h : ¬ (a → b)) : a :=
decidable.by_contradiction (not_not_of_not_imp h)
theorem of_not_imp : ¬ (a → b) → a := decidable.of_not_imp
-- See Note [decidable namespace]
protected theorem decidable.not_imp_symm [decidable a] (h : ¬a → b) (hb : ¬b) : a :=
decidable.by_contradiction $ hb ∘ h
theorem not.decidable_imp_symm [decidable a] : (¬a → b) → ¬b → a := decidable.not_imp_symm
theorem not.imp_symm : (¬a → b) → ¬b → a := not.decidable_imp_symm
-- See Note [decidable namespace]
protected theorem decidable.not_imp_comm [decidable a] [decidable b] : (¬a → b) ↔ (¬b → a) :=
⟨not.decidable_imp_symm, not.decidable_imp_symm⟩
theorem not_imp_comm : (¬a → b) ↔ (¬b → a) := decidable.not_imp_comm
theorem imp.swap : (a → b → c) ↔ (b → a → c) :=
⟨function.swap, function.swap⟩
theorem imp_not_comm : (a → ¬b) ↔ (b → ¬a) :=
imp.swap
/-! ### Declarations about `and` -/
theorem not_and_of_not_left (b : Prop) : ¬a → ¬(a ∧ b) :=
mt and.left
theorem not_and_of_not_right (a : Prop) {b : Prop} : ¬b → ¬(a ∧ b) :=
mt and.right
theorem and.imp_left (h : a → b) : a ∧ c → b ∧ c :=
and.imp h id
theorem and.imp_right (h : a → b) : c ∧ a → c ∧ b :=
and.imp id h
lemma and.right_comm : (a ∧ b) ∧ c ↔ (a ∧ c) ∧ b :=
by simp [and.left_comm, and.comm]
lemma and.rotate : a ∧ b ∧ c ↔ b ∧ c ∧ a :=
by simp [and.left_comm, and.comm]
theorem and_not_self_iff (a : Prop) : a ∧ ¬ a ↔ false :=
iff.intro (assume h, (h.right) (h.left)) (assume h, h.elim)
theorem not_and_self_iff (a : Prop) : ¬ a ∧ a ↔ false :=
iff.intro (assume ⟨hna, ha⟩, hna ha) false.elim
theorem and_iff_left_of_imp {a b : Prop} (h : a → b) : (a ∧ b) ↔ a :=
iff.intro and.left (λ ha, ⟨ha, h ha⟩)
theorem and_iff_right_of_imp {a b : Prop} (h : b → a) : (a ∧ b) ↔ b :=
iff.intro and.right (λ hb, ⟨h hb, hb⟩)
@[simp] theorem and_iff_left_iff_imp {a b : Prop} : ((a ∧ b) ↔ a) ↔ (a → b) :=
⟨λ h ha, (h.2 ha).2, and_iff_left_of_imp⟩
@[simp] theorem and_iff_right_iff_imp {a b : Prop} : ((a ∧ b) ↔ b) ↔ (b → a) :=
⟨λ h ha, (h.2 ha).1, and_iff_right_of_imp⟩
lemma and.congr_right_iff : (a ∧ b ↔ a ∧ c) ↔ (a → (b ↔ c)) :=
⟨λ h ha, by simp [ha] at h; exact h, and_congr_right⟩
@[simp] lemma and_self_left : a ∧ a ∧ b ↔ a ∧ b :=
⟨λ h, ⟨h.1, h.2.2⟩, λ h, ⟨h.1, h.1, h.2⟩⟩
@[simp] lemma and_self_right : (a ∧ b) ∧ b ↔ a ∧ b :=
⟨λ h, ⟨h.1.1, h.2⟩, λ h, ⟨⟨h.1, h.2⟩, h.2⟩⟩
/-! ### Declarations about `or` -/
theorem or.right_comm : (a ∨ b) ∨ c ↔ (a ∨ c) ∨ b := by rw [or_assoc, or_assoc, or_comm b]
theorem or_of_or_of_imp_of_imp (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → d) : c ∨ d :=
or.imp h₂ h₃ h₁
theorem or_of_or_of_imp_left (h₁ : a ∨ c) (h : a → b) : b ∨ c :=
or.imp_left h h₁
theorem or_of_or_of_imp_right (h₁ : c ∨ a) (h : a → b) : c ∨ b :=
or.imp_right h h₁
theorem or.elim3 (h : a ∨ b ∨ c) (ha : a → d) (hb : b → d) (hc : c → d) : d :=
or.elim h ha (assume h₂, or.elim h₂ hb hc)
theorem or_imp_distrib : (a ∨ b → c) ↔ (a → c) ∧ (b → c) :=
⟨assume h, ⟨assume ha, h (or.inl ha), assume hb, h (or.inr hb)⟩,
assume ⟨ha, hb⟩, or.rec ha hb⟩
-- See Note [decidable namespace]
protected theorem decidable.or_iff_not_imp_left [decidable a] : a ∨ b ↔ (¬ a → b) :=
⟨or.resolve_left, λ h, dite _ or.inl (or.inr ∘ h)⟩
theorem or_iff_not_imp_left : a ∨ b ↔ (¬ a → b) := decidable.or_iff_not_imp_left
-- See Note [decidable namespace]
protected theorem decidable.or_iff_not_imp_right [decidable b] : a ∨ b ↔ (¬ b → a) :=
or.comm.trans decidable.or_iff_not_imp_left
theorem or_iff_not_imp_right : a ∨ b ↔ (¬ b → a) := decidable.or_iff_not_imp_right
-- See Note [decidable namespace]
protected theorem decidable.not_imp_not [decidable a] : (¬ a → ¬ b) ↔ (b → a) :=
⟨assume h hb, decidable.by_contradiction $ assume na, h na hb, mt⟩
theorem not_imp_not : (¬ a → ¬ b) ↔ (b → a) := decidable.not_imp_not
/-! ### Declarations about distributivity -/
/-- `∧` distributes over `∨` (on the left). -/
theorem and_or_distrib_left : a ∧ (b ∨ c) ↔ (a ∧ b) ∨ (a ∧ c) :=
⟨λ ⟨ha, hbc⟩, hbc.imp (and.intro ha) (and.intro ha),
or.rec (and.imp_right or.inl) (and.imp_right or.inr)⟩
/-- `∧` distributes over `∨` (on the right). -/
theorem or_and_distrib_right : (a ∨ b) ∧ c ↔ (a ∧ c) ∨ (b ∧ c) :=
(and.comm.trans and_or_distrib_left).trans (or_congr and.comm and.comm)
/-- `∨` distributes over `∧` (on the left). -/
theorem or_and_distrib_left : a ∨ (b ∧ c) ↔ (a ∨ b) ∧ (a ∨ c) :=
⟨or.rec (λha, and.intro (or.inl ha) (or.inl ha)) (and.imp or.inr or.inr),
and.rec $ or.rec (imp_intro ∘ or.inl) (or.imp_right ∘ and.intro)⟩
/-- `∨` distributes over `∧` (on the right). -/
theorem and_or_distrib_right : (a ∧ b) ∨ c ↔ (a ∨ c) ∧ (b ∨ c) :=
(or.comm.trans or_and_distrib_left).trans (and_congr or.comm or.comm)
@[simp] lemma or_self_left : a ∨ a ∨ b ↔ a ∨ b :=
⟨λ h, h.elim or.inl id, λ h, h.elim or.inl (or.inr ∘ or.inr)⟩
@[simp] lemma or_self_right : (a ∨ b) ∨ b ↔ a ∨ b :=
⟨λ h, h.elim id or.inr, λ h, h.elim (or.inl ∘ or.inl) or.inr⟩
/-! Declarations about `iff` -/
theorem iff_of_true (ha : a) (hb : b) : a ↔ b :=
⟨λ_, hb, λ _, ha⟩
theorem iff_of_false (ha : ¬a) (hb : ¬b) : a ↔ b :=
⟨ha.elim, hb.elim⟩
theorem iff_true_left (ha : a) : (a ↔ b) ↔ b :=
⟨λ h, h.1 ha, iff_of_true ha⟩
theorem iff_true_right (ha : a) : (b ↔ a) ↔ b :=
iff.comm.trans (iff_true_left ha)
theorem iff_false_left (ha : ¬a) : (a ↔ b) ↔ ¬b :=
⟨λ h, mt h.2 ha, iff_of_false ha⟩
theorem iff_false_right (ha : ¬a) : (b ↔ a) ↔ ¬b :=
iff.comm.trans (iff_false_left ha)
-- See Note [decidable namespace]
protected theorem decidable.not_or_of_imp [decidable a] (h : a → b) : ¬ a ∨ b :=
if ha : a then or.inr (h ha) else or.inl ha
theorem not_or_of_imp : (a → b) → ¬ a ∨ b := decidable.not_or_of_imp
-- See Note [decidable namespace]
protected theorem decidable.imp_iff_not_or [decidable a] : (a → b) ↔ (¬ a ∨ b) :=
⟨decidable.not_or_of_imp, or.neg_resolve_left⟩
theorem imp_iff_not_or : (a → b) ↔ (¬ a ∨ b) := decidable.imp_iff_not_or
-- See Note [decidable namespace]
protected theorem decidable.imp_or_distrib [decidable a] : (a → b ∨ c) ↔ (a → b) ∨ (a → c) :=
by simp [decidable.imp_iff_not_or, or.comm, or.left_comm]
theorem imp_or_distrib : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := decidable.imp_or_distrib
-- See Note [decidable namespace]
protected theorem decidable.imp_or_distrib' [decidable b] : (a → b ∨ c) ↔ (a → b) ∨ (a → c) :=
by by_cases b; simp [h, or_iff_right_of_imp ((∘) false.elim)]
theorem imp_or_distrib' : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := decidable.imp_or_distrib'
theorem not_imp_of_and_not : a ∧ ¬ b → ¬ (a → b)
| ⟨ha, hb⟩ h := hb $ h ha
-- See Note [decidable namespace]
protected theorem decidable.not_imp [decidable a] : ¬(a → b) ↔ a ∧ ¬b :=
⟨λ h, ⟨decidable.of_not_imp h, not_of_not_imp h⟩, not_imp_of_and_not⟩
theorem not_imp : ¬(a → b) ↔ a ∧ ¬b := decidable.not_imp
-- for monotonicity
lemma imp_imp_imp (h₀ : c → a) (h₁ : b → d) : (a → b) → (c → d) :=
assume (h₂ : a → b), h₁ ∘ h₂ ∘ h₀
-- See Note [decidable namespace]
protected theorem decidable.peirce (a b : Prop) [decidable a] : ((a → b) → a) → a :=
if ha : a then λ h, ha else λ h, h ha.elim
theorem peirce (a b : Prop) : ((a → b) → a) → a := decidable.peirce _ _
theorem peirce' {a : Prop} (H : ∀ b : Prop, (a → b) → a) : a := H _ id
-- See Note [decidable namespace]
protected theorem decidable.not_iff_not [decidable a] [decidable b] : (¬ a ↔ ¬ b) ↔ (a ↔ b) :=
by rw [@iff_def (¬ a), @iff_def' a]; exact and_congr decidable.not_imp_not decidable.not_imp_not
theorem not_iff_not : (¬ a ↔ ¬ b) ↔ (a ↔ b) := decidable.not_iff_not
-- See Note [decidable namespace]
protected theorem decidable.not_iff_comm [decidable a] [decidable b] : (¬ a ↔ b) ↔ (¬ b ↔ a) :=
by rw [@iff_def (¬ a), @iff_def (¬ b)]; exact and_congr decidable.not_imp_comm imp_not_comm
theorem not_iff_comm : (¬ a ↔ b) ↔ (¬ b ↔ a) := decidable.not_iff_comm
-- See Note [decidable namespace]
protected theorem decidable.not_iff : ∀ [decidable b], ¬ (a ↔ b) ↔ (¬ a ↔ b) :=
by intro h; cases h; simp only [h, iff_true, iff_false]
theorem not_iff : ¬ (a ↔ b) ↔ (¬ a ↔ b) := decidable.not_iff
-- See Note [decidable namespace]
protected theorem decidable.iff_not_comm [decidable a] [decidable b] : (a ↔ ¬ b) ↔ (b ↔ ¬ a) :=
by rw [@iff_def a, @iff_def b]; exact and_congr imp_not_comm decidable.not_imp_comm
theorem iff_not_comm : (a ↔ ¬ b) ↔ (b ↔ ¬ a) := decidable.iff_not_comm
-- See Note [decidable namespace]
protected theorem decidable.iff_iff_and_or_not_and_not [decidable b] : (a ↔ b) ↔ (a ∧ b) ∨ (¬ a ∧ ¬ b) :=
by { split; intro h,
{ rw h; by_cases b; [left,right]; split; assumption },
{ cases h with h h; cases h; split; intro; { contradiction <|> assumption } } }
theorem iff_iff_and_or_not_and_not : (a ↔ b) ↔ (a ∧ b) ∨ (¬ a ∧ ¬ b) :=
decidable.iff_iff_and_or_not_and_not
lemma decidable.iff_iff_not_or_and_or_not [decidable a] [decidable b] :
(a ↔ b) ↔ ((¬a ∨ b) ∧ (a ∨ ¬b)) :=
begin
rw [iff_iff_implies_and_implies a b],
simp only [decidable.imp_iff_not_or, or.comm]
end
lemma iff_iff_not_or_and_or_not : (a ↔ b) ↔ ((¬a ∨ b) ∧ (a ∨ ¬b)) :=
decidable.iff_iff_not_or_and_or_not
-- See Note [decidable namespace]
protected theorem decidable.not_and_not_right [decidable b] : ¬(a ∧ ¬b) ↔ (a → b) :=
⟨λ h ha, h.decidable_imp_symm $ and.intro ha, λ h ⟨ha, hb⟩, hb $ h ha⟩
theorem not_and_not_right : ¬(a ∧ ¬b) ↔ (a → b) := decidable.not_and_not_right
/-- Transfer decidability of `a` to decidability of `b`, if the propositions are equivalent.
**Important**: this function should be used instead of `rw` on `decidable b`, because the
kernel will get stuck reducing the usage of `propext` otherwise,
and `dec_trivial` will not work. -/
@[inline] def decidable_of_iff (a : Prop) (h : a ↔ b) [D : decidable a] : decidable b :=
decidable_of_decidable_of_iff D h
/-- Transfer decidability of `b` to decidability of `a`, if the propositions are equivalent.
This is the same as `decidable_of_iff` but the iff is flipped. -/
@[inline] def decidable_of_iff' (b : Prop) (h : a ↔ b) [D : decidable b] : decidable a :=
decidable_of_decidable_of_iff D h.symm
/-- Prove that `a` is decidable by constructing a boolean `b` and a proof that `b ↔ a`.
(This is sometimes taken as an alternate definition of decidability.) -/
def decidable_of_bool : ∀ (b : bool) (h : b ↔ a), decidable a
| tt h := is_true (h.1 rfl)
| ff h := is_false (mt h.2 bool.ff_ne_tt)
/-! ### De Morgan's laws -/
theorem not_and_of_not_or_not (h : ¬ a ∨ ¬ b) : ¬ (a ∧ b)
| ⟨ha, hb⟩ := or.elim h (absurd ha) (absurd hb)
-- See Note [decidable namespace]
protected theorem decidable.not_and_distrib [decidable a] : ¬ (a ∧ b) ↔ ¬a ∨ ¬b :=
⟨λ h, if ha : a then or.inr (λ hb, h ⟨ha, hb⟩) else or.inl ha, not_and_of_not_or_not⟩
-- See Note [decidable namespace]
protected theorem decidable.not_and_distrib' [decidable b] : ¬ (a ∧ b) ↔ ¬a ∨ ¬b :=
⟨λ h, if hb : b then or.inl (λ ha, h ⟨ha, hb⟩) else or.inr hb, not_and_of_not_or_not⟩
/-- One of de Morgan's laws: the negation of a conjunction is logically equivalent to the
disjunction of the negations. -/
theorem not_and_distrib : ¬ (a ∧ b) ↔ ¬a ∨ ¬b := decidable.not_and_distrib
@[simp] theorem not_and : ¬ (a ∧ b) ↔ (a → ¬ b) := and_imp
theorem not_and' : ¬ (a ∧ b) ↔ b → ¬a :=
not_and.trans imp_not_comm
/-- One of de Morgan's laws: the negation of a disjunction is logically equivalent to the
conjunction of the negations. -/
theorem not_or_distrib : ¬ (a ∨ b) ↔ ¬ a ∧ ¬ b :=
⟨λ h, ⟨λ ha, h (or.inl ha), λ hb, h (or.inr hb)⟩,
λ ⟨h₁, h₂⟩ h, or.elim h h₁ h₂⟩
-- See Note [decidable namespace]
protected theorem decidable.or_iff_not_and_not [decidable a] [decidable b] : a ∨ b ↔ ¬ (¬a ∧ ¬b) :=
by rw [← not_or_distrib, decidable.not_not]
theorem or_iff_not_and_not : a ∨ b ↔ ¬ (¬a ∧ ¬b) := decidable.or_iff_not_and_not
-- See Note [decidable namespace]
protected theorem decidable.and_iff_not_or_not [decidable a] [decidable b] : a ∧ b ↔ ¬ (¬ a ∨ ¬ b) :=
by rw [← decidable.not_and_distrib, decidable.not_not]
theorem and_iff_not_or_not : a ∧ b ↔ ¬ (¬ a ∨ ¬ b) := decidable.and_iff_not_or_not
end propositional
/-! ### Declarations about equality -/
section equality
variables {α : Sort*} {a b : α}
@[simp] theorem heq_iff_eq : a == b ↔ a = b :=
⟨eq_of_heq, heq_of_eq⟩
theorem proof_irrel_heq {p q : Prop} (hp : p) (hq : q) : hp == hq :=
have p = q, from propext ⟨λ _, hq, λ _, hp⟩,
by subst q; refl
theorem ne_of_mem_of_not_mem {α β} [has_mem α β] {s : β} {a b : α}
(h : a ∈ s) : b ∉ s → a ≠ b :=
mt $ λ e, e ▸ h
theorem eq_equivalence : equivalence (@eq α) :=
⟨eq.refl, @eq.symm _, @eq.trans _⟩
/-- Transport through trivial families is the identity. -/
@[simp]
lemma eq_rec_constant {α : Sort*} {a a' : α} {β : Sort*} (y : β) (h : a = a') :
(@eq.rec α a (λ a, β) y a' h) = y :=
by { cases h, refl, }
@[simp]
lemma eq_mp_rfl {α : Sort*} {a : α} : eq.mp (eq.refl α) a = a := rfl
@[simp]
lemma eq_mpr_rfl {α : Sort*} {a : α} : eq.mpr (eq.refl α) a = a := rfl
lemma heq_of_eq_mp :
∀ {α β : Sort*} {a : α} {a' : β} (e : α = β) (h₂ : (eq.mp e a) = a'), a == a'
| α ._ a a' rfl h := eq.rec_on h (heq.refl _)
lemma rec_heq_of_heq {β} {C : α → Sort*} {x : C a} {y : β} (eq : a = b) (h : x == y) :
@eq.rec α a C x b eq == y :=
by subst eq; exact h
@[simp] lemma {u} eq_mpr_heq {α β : Sort u} (h : β = α) (x : α) : eq.mpr h x == x :=
by subst h; refl
protected lemma eq.congr {x₁ x₂ y₁ y₂ : α} (h₁ : x₁ = y₁) (h₂ : x₂ = y₂) :
(x₁ = x₂) ↔ (y₁ = y₂) :=
by { subst h₁, subst h₂ }
lemma eq.congr_left {x y z : α} (h : x = y) : x = z ↔ y = z := by rw [h]
lemma eq.congr_right {x y z : α} (h : x = y) : z = x ↔ z = y := by rw [h]
lemma congr_arg2 {α β γ : Type*} (f : α → β → γ) {x x' : α} {y y' : β}
(hx : x = x') (hy : y = y') : f x y = f x' y' :=
by { subst hx, subst hy }
end equality
/-! ### Declarations about quantifiers -/
section quantifiers
variables {α : Sort*} {β : Sort*} {p q : α → Prop} {b : Prop}
lemma forall_imp (h : ∀ a, p a → q a) : (∀ a, p a) → ∀ a, q a :=
λ h' a, h a (h' a)
lemma Exists.imp (h : ∀ a, (p a → q a)) (p : ∃ a, p a) : ∃ a, q a := exists_imp_exists h p
lemma exists_imp_exists' {p : α → Prop} {q : β → Prop} (f : α → β) (hpq : ∀ a, p a → q (f a))
(hp : ∃ a, p a) : ∃ b, q b :=
exists.elim hp (λ a hp', ⟨_, hpq _ hp'⟩)
theorem forall_swap {p : α → β → Prop} : (∀ x y, p x y) ↔ ∀ y x, p x y :=
⟨function.swap, function.swap⟩
theorem exists_swap {p : α → β → Prop} : (∃ x y, p x y) ↔ ∃ y x, p x y :=
⟨λ ⟨x, y, h⟩, ⟨y, x, h⟩, λ ⟨y, x, h⟩, ⟨x, y, h⟩⟩
@[simp] theorem exists_imp_distrib : ((∃ x, p x) → b) ↔ ∀ x, p x → b :=
⟨λ h x hpx, h ⟨x, hpx⟩, λ h ⟨x, hpx⟩, h x hpx⟩
/--
Extract an element from a existential statement, using `classical.some`.
-/
-- This enables projection notation.
@[reducible] noncomputable def Exists.some {p : α → Prop} (P : ∃ a, p a) : α := classical.some P
/--
Show that an element extracted from `P : ∃ a, p a` using `P.some` satisfies `p`.
-/
lemma Exists.some_spec {p : α → Prop} (P : ∃ a, p a) : p (P.some) := classical.some_spec P
--theorem forall_not_of_not_exists (h : ¬ ∃ x, p x) : ∀ x, ¬ p x :=
--forall_imp_of_exists_imp h
theorem not_exists_of_forall_not (h : ∀ x, ¬ p x) : ¬ ∃ x, p x :=
exists_imp_distrib.2 h
@[simp] theorem not_exists : (¬ ∃ x, p x) ↔ ∀ x, ¬ p x :=
exists_imp_distrib
theorem not_forall_of_exists_not : (∃ x, ¬ p x) → ¬ ∀ x, p x
| ⟨x, hn⟩ h := hn (h x)
-- See Note [decidable namespace]
protected theorem decidable.not_forall {p : α → Prop}
[decidable (∃ x, ¬ p x)] [∀ x, decidable (p x)] : (¬ ∀ x, p x) ↔ ∃ x, ¬ p x :=
⟨not.decidable_imp_symm $ λ nx x, nx.decidable_imp_symm $ λ h, ⟨x, h⟩,
not_forall_of_exists_not⟩
@[simp] theorem not_forall {p : α → Prop} : (¬ ∀ x, p x) ↔ ∃ x, ¬ p x := decidable.not_forall
-- See Note [decidable namespace]
protected theorem decidable.not_forall_not [decidable (∃ x, p x)] :
(¬ ∀ x, ¬ p x) ↔ ∃ x, p x :=
(@decidable.not_iff_comm _ _ _ (decidable_of_iff (¬ ∃ x, p x) not_exists)).1 not_exists
theorem not_forall_not : (¬ ∀ x, ¬ p x) ↔ ∃ x, p x := decidable.not_forall_not
-- See Note [decidable namespace]
protected theorem decidable.not_exists_not [∀ x, decidable (p x)] : (¬ ∃ x, ¬ p x) ↔ ∀ x, p x :=
by simp [decidable.not_not]
@[simp] theorem not_exists_not : (¬ ∃ x, ¬ p x) ↔ ∀ x, p x := decidable.not_exists_not
@[simp] theorem forall_true_iff : (α → true) ↔ true :=
iff_true_intro (λ _, trivial)
-- Unfortunately this causes simp to loop sometimes, so we
-- add the 2 and 3 cases as simp lemmas instead
theorem forall_true_iff' (h : ∀ a, p a ↔ true) : (∀ a, p a) ↔ true :=
iff_true_intro (λ _, of_iff_true (h _))
@[simp] theorem forall_2_true_iff {β : α → Sort*} : (∀ a, β a → true) ↔ true :=
forall_true_iff' $ λ _, forall_true_iff
@[simp] theorem forall_3_true_iff {β : α → Sort*} {γ : Π a, β a → Sort*} :
(∀ a (b : β a), γ a b → true) ↔ true :=
forall_true_iff' $ λ _, forall_2_true_iff
@[simp] theorem forall_const (α : Sort*) [i : nonempty α] : (α → b) ↔ b :=
⟨i.elim, λ hb x, hb⟩
@[simp] theorem exists_const (α : Sort*) [i : nonempty α] : (∃ x : α, b) ↔ b :=
⟨λ ⟨x, h⟩, h, i.elim exists.intro⟩
theorem forall_and_distrib : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) :=
⟨λ h, ⟨λ x, (h x).left, λ x, (h x).right⟩, λ ⟨h₁, h₂⟩ x, ⟨h₁ x, h₂ x⟩⟩
theorem exists_or_distrib : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) :=
⟨λ ⟨x, hpq⟩, hpq.elim (λ hpx, or.inl ⟨x, hpx⟩) (λ hqx, or.inr ⟨x, hqx⟩),
λ hepq, hepq.elim (λ ⟨x, hpx⟩, ⟨x, or.inl hpx⟩) (λ ⟨x, hqx⟩, ⟨x, or.inr hqx⟩)⟩
@[simp] theorem exists_and_distrib_left {q : Prop} {p : α → Prop} :
(∃x, q ∧ p x) ↔ q ∧ (∃x, p x) :=
⟨λ ⟨x, hq, hp⟩, ⟨hq, x, hp⟩, λ ⟨hq, x, hp⟩, ⟨x, hq, hp⟩⟩
@[simp] theorem exists_and_distrib_right {q : Prop} {p : α → Prop} :
(∃x, p x ∧ q) ↔ (∃x, p x) ∧ q :=
by simp [and_comm]
@[simp] theorem forall_eq {a' : α} : (∀a, a = a' → p a) ↔ p a' :=
⟨λ h, h a' rfl, λ h a e, e.symm ▸ h⟩
@[simp] theorem forall_eq' {a' : α} : (∀a, a' = a → p a) ↔ p a' :=
by simp [@eq_comm _ a']
-- this lemma is needed to simplify the output of `list.mem_cons_iff`
@[simp] theorem forall_eq_or_imp {a' : α} : (∀ a, a = a' ∨ q a → p a) ↔ p a' ∧ ∀ a, q a → p a :=
by simp only [or_imp_distrib, forall_and_distrib, forall_eq]
@[simp] theorem exists_eq {a' : α} : ∃ a, a = a' := ⟨_, rfl⟩
@[simp] theorem exists_eq' {a' : α} : ∃ a, a' = a := ⟨_, rfl⟩
@[simp] theorem exists_eq_left {a' : α} : (∃ a, a = a' ∧ p a) ↔ p a' :=
⟨λ ⟨a, e, h⟩, e ▸ h, λ h, ⟨_, rfl, h⟩⟩
@[simp] theorem exists_eq_right {a' : α} : (∃ a, p a ∧ a = a') ↔ p a' :=
(exists_congr $ by exact λ a, and.comm).trans exists_eq_left
@[simp] theorem exists_apply_eq_apply {α β : Type*} (f : α → β) (a' : α) : ∃ a, f a = f a' :=
⟨a', rfl⟩
@[simp] theorem exists_apply_eq_apply' {α β : Type*} (f : α → β) (a' : α) : ∃ a, f a' = f a :=
⟨a', rfl⟩
@[simp] theorem exists_exists_and_eq_and {f : α → β} {p : α → Prop} {q : β → Prop} :
(∃ b, (∃ a, p a ∧ f a = b) ∧ q b) ↔ ∃ a, p a ∧ q (f a) :=
⟨λ ⟨b, ⟨a, ha, hab⟩, hb⟩, ⟨a, ha, hab.symm ▸ hb⟩, λ ⟨a, hp, hq⟩, ⟨f a, ⟨a, hp, rfl⟩, hq⟩⟩
@[simp] theorem exists_exists_eq_and {f : α → β} {p : β → Prop} :
(∃ b, (∃ a, f a = b) ∧ p b) ↔ ∃ a, p (f a) :=
⟨λ ⟨b, ⟨a, ha⟩, hb⟩, ⟨a, ha.symm ▸ hb⟩, λ ⟨a, ha⟩, ⟨f a, ⟨a, rfl⟩, ha⟩⟩
@[simp] theorem forall_apply_eq_imp_iff {f : α → β} {p : β → Prop} :
(∀ a, ∀ b, f a = b → p b) ↔ (∀ a, p (f a)) :=
⟨λ h a, h a (f a) rfl, λ h a b hab, hab ▸ h a⟩
@[simp] theorem forall_apply_eq_imp_iff' {f : α → β} {p : β → Prop} :
(∀ b, ∀ a, f a = b → p b) ↔ (∀ a, p (f a)) :=
by { rw forall_swap, simp }
@[simp] theorem forall_eq_apply_imp_iff {f : α → β} {p : β → Prop} :
(∀ a, ∀ b, b = f a → p b) ↔ (∀ a, p (f a)) :=
by simp [@eq_comm _ _ (f _)]
@[simp] theorem forall_eq_apply_imp_iff' {f : α → β} {p : β → Prop} :
(∀ b, ∀ a, b = f a → p b) ↔ (∀ a, p (f a)) :=
by { rw forall_swap, simp }
@[simp] theorem exists_eq_left' {a' : α} : (∃ a, a' = a ∧ p a) ↔ p a' :=
by simp [@eq_comm _ a']
@[simp] theorem exists_eq_right' {a' : α} : (∃ a, p a ∧ a' = a) ↔ p a' :=
by simp [@eq_comm _ a']
theorem exists_comm {p : α → β → Prop} : (∃ a b, p a b) ↔ ∃ b a, p a b :=
⟨λ ⟨a, b, h⟩, ⟨b, a, h⟩, λ ⟨b, a, h⟩, ⟨a, b, h⟩⟩
theorem forall_or_of_or_forall (h : b ∨ ∀x, p x) (x) : b ∨ p x :=
h.imp_right $ λ h₂, h₂ x
-- See Note [decidable namespace]
protected theorem decidable.forall_or_distrib_left {q : Prop} {p : α → Prop} [decidable q] :
(∀x, q ∨ p x) ↔ q ∨ (∀x, p x) :=
⟨λ h, if hq : q then or.inl hq else or.inr $ λ x, (h x).resolve_left hq,
forall_or_of_or_forall⟩
theorem forall_or_distrib_left {q : Prop} {p : α → Prop} :
(∀x, q ∨ p x) ↔ q ∨ (∀x, p x) := decidable.forall_or_distrib_left
-- See Note [decidable namespace]
protected theorem decidable.forall_or_distrib_right {q : Prop} {p : α → Prop} [decidable q] :
(∀x, p x ∨ q) ↔ (∀x, p x) ∨ q :=
by simp [or_comm, decidable.forall_or_distrib_left]
theorem forall_or_distrib_right {q : Prop} {p : α → Prop} :
(∀x, p x ∨ q) ↔ (∀x, p x) ∨ q := decidable.forall_or_distrib_right
/-- A predicate holds everywhere on the image of a surjective functions iff
it holds everywhere. -/
theorem forall_iff_forall_surj
{α β : Type*} {f : α → β} (h : function.surjective f) {P : β → Prop} :
(∀ a, P (f a)) ↔ ∀ b, P b :=
⟨λ ha b, by cases h b with a hab; rw ←hab; exact ha a, λ hb a, hb $ f a⟩
@[simp] theorem exists_prop {p q : Prop} : (∃ h : p, q) ↔ p ∧ q :=
⟨λ ⟨h₁, h₂⟩, ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨h₁, h₂⟩⟩
@[simp] theorem exists_false : ¬ (∃a:α, false) := assume ⟨a, h⟩, h
theorem Exists.fst {p : b → Prop} : Exists p → b
| ⟨h, _⟩ := h
theorem Exists.snd {p : b → Prop} : ∀ h : Exists p, p h.fst
| ⟨_, h⟩ := h
@[simp] theorem forall_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∀ h' : p, q h') ↔ q h :=
@forall_const (q h) p ⟨h⟩
@[simp] theorem exists_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∃ h' : p, q h') ↔ q h :=
@exists_const (q h) p ⟨h⟩
@[simp] theorem forall_prop_of_false {p : Prop} {q : p → Prop} (hn : ¬ p) : (∀ h' : p, q h') ↔ true :=
iff_true_intro $ λ h, hn.elim h
@[simp] theorem exists_prop_of_false {p : Prop} {q : p → Prop} : ¬ p → ¬ (∃ h' : p, q h') :=
mt Exists.fst
lemma exists_unique.exists {α : Sort*} {p : α → Prop} (h : ∃! x, p x) : ∃ x, p x :=
exists.elim h (λ x hx, ⟨x, and.left hx⟩)
lemma exists_unique.unique {α : Sort*} {p : α → Prop} (h : ∃! x, p x)
{y₁ y₂ : α} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ :=
unique_of_exists_unique h py₁ py₂
@[simp] lemma exists_unique_iff_exists {α : Sort*} [subsingleton α] {p : α → Prop} :
(∃! x, p x) ↔ ∃ x, p x :=
⟨λ h, h.exists, Exists.imp $ λ x hx, ⟨hx, λ y _, subsingleton.elim y x⟩⟩
lemma exists_unique.elim2 {α : Sort*} {p : α → Sort*} [∀ x, subsingleton (p x)]
{q : Π x (h : p x), Prop} {b : Prop} (h₂ : ∃! x (h : p x), q x h)
(h₁ : ∀ x (h : p x), q x h → (∀ y (hy : p y), q y hy → y = x) → b) : b :=
begin
simp only [exists_unique_iff_exists] at h₂,
apply h₂.elim,
exact λ x ⟨hxp, hxq⟩ H, h₁ x hxp hxq (λ y hyp hyq, H y ⟨hyp, hyq⟩)
end
lemma exists_unique.intro2 {α : Sort*} {p : α → Sort*} [∀ x, subsingleton (p x)]
{q : Π (x : α) (h : p x), Prop} (w : α) (hp : p w) (hq : q w hp)
(H : ∀ y (hy : p y), q y hy → y = w) :
∃! x (hx : p x), q x hx :=
begin
simp only [exists_unique_iff_exists],
exact exists_unique.intro w ⟨hp, hq⟩ (λ y ⟨hyp, hyq⟩, H y hyp hyq)
end
lemma exists_unique.exists2 {α : Sort*} {p : α → Sort*} {q : Π (x : α) (h : p x), Prop}
(h : ∃! x (hx : p x), q x hx) :
∃ x (hx : p x), q x hx :=
h.exists.imp (λ x hx, hx.exists)
lemma exists_unique.unique2 {α : Sort*} {p : α → Sort*} [∀ x, subsingleton (p x)]
{q : Π (x : α) (hx : p x), Prop} (h : ∃! x (hx : p x), q x hx)
{y₁ y₂ : α} (hpy₁ : p y₁) (hqy₁ : q y₁ hpy₁)
(hpy₂ : p y₂) (hqy₂ : q y₂ hpy₂) : y₁ = y₂ :=
begin
simp only [exists_unique_iff_exists] at h,
exact h.unique ⟨hpy₁, hqy₁⟩ ⟨hpy₂, hqy₂⟩
end
end quantifiers
/-! ### Classical lemmas -/
namespace classical
variables {α : Sort*} {p : α → Prop}
theorem cases {p : Prop → Prop} (h1 : p true) (h2 : p false) : ∀a, p a :=
assume a, cases_on a h1 h2
/- use shortened names to avoid conflict when classical namespace is open. -/
noncomputable lemma dec (p : Prop) : decidable p := -- see Note [classical lemma]
by apply_instance
noncomputable lemma dec_pred (p : α → Prop) : decidable_pred p := -- see Note [classical lemma]
by apply_instance
noncomputable lemma dec_rel (p : α → α → Prop) : decidable_rel p := -- see Note [classical lemma]
by apply_instance
noncomputable lemma dec_eq (α : Sort*) : decidable_eq α := -- see Note [classical lemma]
by apply_instance
/--
We make decidability results that depends on `classical.choice` noncomputable lemmas.
* We have to mark them as noncomputable, because otherwise Lean will try to generate bytecode
for them, and fail because it depends on `classical.choice`.
* We make them lemmas, and not definitions, because otherwise later definitions will raise
\"failed to generate bytecode\" errors when writing something like
`letI := classical.dec_eq _`.
Cf. <https://leanprover-community.github.io/archive/113488general/08268noncomputabletheorem.html>
-/
library_note "classical lemma"
/-- Construct a function from a default value `H0`, and a function to use if there exists a value
satisfying the predicate. -/
@[elab_as_eliminator]
noncomputable def {u} exists_cases {C : Sort u} (H0 : C) (H : ∀ a, p a → C) : C :=
if h : ∃ a, p a then H (classical.some h) (classical.some_spec h) else H0
lemma some_spec2 {α : Sort*} {p : α → Prop} {h : ∃a, p a}
(q : α → Prop) (hpq : ∀a, p a → q a) : q (some h) :=
hpq _ $ some_spec _
/-- A version of classical.indefinite_description which is definitionally equal to a pair -/
noncomputable def subtype_of_exists {α : Type*} {P : α → Prop} (h : ∃ x, P x) : {x // P x} :=
⟨classical.some h, classical.some_spec h⟩
end classical
/-- This function has the same type as `exists.rec_on`, and can be used to case on an equality,
but `exists.rec_on` can only eliminate into Prop, while this version eliminates into any universe
using the axiom of choice. -/
@[elab_as_eliminator]
noncomputable def {u} exists.classical_rec_on
{α} {p : α → Prop} (h : ∃ a, p a) {C : Sort u} (H : ∀ a, p a → C) : C :=
H (classical.some h) (classical.some_spec h)
/-! ### Declarations about bounded quantifiers -/
section bounded_quantifiers
variables {α : Sort*} {r p q : α → Prop} {P Q : ∀ x, p x → Prop} {b : Prop}
theorem bex_def : (∃ x (h : p x), q x) ↔ ∃ x, p x ∧ q x :=
⟨λ ⟨x, px, qx⟩, ⟨x, px, qx⟩, λ ⟨x, px, qx⟩, ⟨x, px, qx⟩⟩
theorem bex.elim {b : Prop} : (∃ x h, P x h) → (∀ a h, P a h → b) → b
| ⟨a, h₁, h₂⟩ h' := h' a h₁ h₂
theorem bex.intro (a : α) (h₁ : p a) (h₂ : P a h₁) : ∃ x (h : p x), P x h :=
⟨a, h₁, h₂⟩
theorem ball_congr (H : ∀ x h, P x h ↔ Q x h) :
(∀ x h, P x h) ↔ (∀ x h, Q x h) :=
forall_congr $ λ x, forall_congr (H x)
theorem bex_congr (H : ∀ x h, P x h ↔ Q x h) :
(∃ x h, P x h) ↔ (∃ x h, Q x h) :=
exists_congr $ λ x, exists_congr (H x)
theorem ball.imp_right (H : ∀ x h, (P x h → Q x h))
(h₁ : ∀ x h, P x h) (x h) : Q x h :=
H _ _ $ h₁ _ _
theorem bex.imp_right (H : ∀ x h, (P x h → Q x h)) :
(∃ x h, P x h) → ∃ x h, Q x h
| ⟨x, h, h'⟩ := ⟨_, _, H _ _ h'⟩
theorem ball.imp_left (H : ∀ x, p x → q x)
(h₁ : ∀ x, q x → r x) (x) (h : p x) : r x :=
h₁ _ $ H _ h
theorem bex.imp_left (H : ∀ x, p x → q x) :
(∃ x (_ : p x), r x) → ∃ x (_ : q x), r x
| ⟨x, hp, hr⟩ := ⟨x, H _ hp, hr⟩
theorem ball_of_forall (h : ∀ x, p x) (x) : p x :=
h x
theorem forall_of_ball (H : ∀ x, p x) (h : ∀ x, p x → q x) (x) : q x :=
h x $ H x
theorem bex_of_exists (H : ∀ x, p x) : (∃ x, q x) → ∃ x (_ : p x), q x
| ⟨x, hq⟩ := ⟨x, H x, hq⟩
theorem exists_of_bex : (∃ x (_ : p x), q x) → ∃ x, q x
| ⟨x, _, hq⟩ := ⟨x, hq⟩
@[simp] theorem bex_imp_distrib : ((∃ x h, P x h) → b) ↔ (∀ x h, P x h → b) :=
by simp
theorem not_bex : (¬ ∃ x h, P x h) ↔ ∀ x h, ¬ P x h :=
bex_imp_distrib
theorem not_ball_of_bex_not : (∃ x h, ¬ P x h) → ¬ ∀ x h, P x h
| ⟨x, h, hp⟩ al := hp $ al x h
-- See Note [decidable namespace]
protected theorem decidable.not_ball [decidable (∃ x h, ¬ P x h)] [∀ x h, decidable (P x h)] :
(¬ ∀ x h, P x h) ↔ (∃ x h, ¬ P x h) :=
⟨not.decidable_imp_symm $ λ nx x h, nx.decidable_imp_symm $ λ h', ⟨x, h, h'⟩,
not_ball_of_bex_not⟩
theorem not_ball : (¬ ∀ x h, P x h) ↔ (∃ x h, ¬ P x h) := decidable.not_ball
theorem ball_true_iff (p : α → Prop) : (∀ x, p x → true) ↔ true :=
iff_true_intro (λ h hrx, trivial)
theorem ball_and_distrib : (∀ x h, P x h ∧ Q x h) ↔ (∀ x h, P x h) ∧ (∀ x h, Q x h) :=
iff.trans (forall_congr $ λ x, forall_and_distrib) forall_and_distrib
theorem bex_or_distrib : (∃ x h, P x h ∨ Q x h) ↔ (∃ x h, P x h) ∨ (∃ x h, Q x h) :=
iff.trans (exists_congr $ λ x, exists_or_distrib) exists_or_distrib
end bounded_quantifiers
namespace classical
local attribute [instance] prop_decidable
theorem not_ball {α : Sort*} {p : α → Prop} {P : Π (x : α), p x → Prop} :
(¬ ∀ x h, P x h) ↔ (∃ x h, ¬ P x h) := _root_.not_ball
end classical
lemma ite_eq_iff {α} {p : Prop} [decidable p] {a b c : α} :
(if p then a else b) = c ↔ p ∧ a = c ∨ ¬p ∧ b = c :=
by by_cases p; simp *
/-! ### Declarations about `nonempty` -/
section nonempty
universe variables u v w
variables {α : Type u} {β : Type v} {γ : α → Type w}
attribute [simp] nonempty_of_inhabited
@[priority 20]
instance has_zero.nonempty [has_zero α] : nonempty α := ⟨0⟩
@[priority 20]
instance has_one.nonempty [has_one α] : nonempty α := ⟨1⟩
lemma exists_true_iff_nonempty {α : Sort*} : (∃a:α, true) ↔ nonempty α :=
iff.intro (λ⟨a, _⟩, ⟨a⟩) (λ⟨a⟩, ⟨a, trivial⟩)
@[simp] lemma nonempty_Prop {p : Prop} : nonempty p ↔ p :=
iff.intro (assume ⟨h⟩, h) (assume h, ⟨h⟩)
lemma not_nonempty_iff_imp_false : ¬ nonempty α ↔ α → false :=
⟨λ h a, h ⟨a⟩, λ h ⟨a⟩, h a⟩
@[simp] lemma nonempty_sigma : nonempty (Σa:α, γ a) ↔ (∃a:α, nonempty (γ a)) :=
iff.intro (assume ⟨⟨a, c⟩⟩, ⟨a, ⟨c⟩⟩) (assume ⟨a, ⟨c⟩⟩, ⟨⟨a, c⟩⟩)
@[simp] lemma nonempty_subtype {α : Sort u} {p : α → Prop} : nonempty (subtype p) ↔ (∃a:α, p a) :=
iff.intro (assume ⟨⟨a, h⟩⟩, ⟨a, h⟩) (assume ⟨a, h⟩, ⟨⟨a, h⟩⟩)
@[simp] lemma nonempty_prod : nonempty (α × β) ↔ (nonempty α ∧ nonempty β) :=
iff.intro (assume ⟨⟨a, b⟩⟩, ⟨⟨a⟩, ⟨b⟩⟩) (assume ⟨⟨a⟩, ⟨b⟩⟩, ⟨⟨a, b⟩⟩)
@[simp] lemma nonempty_pprod {α : Sort u} {β : Sort v} :
nonempty (pprod α β) ↔ (nonempty α ∧ nonempty β) :=
iff.intro (assume ⟨⟨a, b⟩⟩, ⟨⟨a⟩, ⟨b⟩⟩) (assume ⟨⟨a⟩, ⟨b⟩⟩, ⟨⟨a, b⟩⟩)
@[simp] lemma nonempty_sum : nonempty (α ⊕ β) ↔ (nonempty α ∨ nonempty β) :=
iff.intro
(assume ⟨h⟩, match h with sum.inl a := or.inl ⟨a⟩ | sum.inr b := or.inr ⟨b⟩ end)
(assume h, match h with or.inl ⟨a⟩ := ⟨sum.inl a⟩ | or.inr ⟨b⟩ := ⟨sum.inr b⟩ end)
@[simp] lemma nonempty_psum {α : Sort u} {β : Sort v} :
nonempty (psum α β) ↔ (nonempty α ∨ nonempty β) :=
iff.intro
(assume ⟨h⟩, match h with psum.inl a := or.inl ⟨a⟩ | psum.inr b := or.inr ⟨b⟩ end)
(assume h, match h with or.inl ⟨a⟩ := ⟨psum.inl a⟩ | or.inr ⟨b⟩ := ⟨psum.inr b⟩ end)
@[simp] lemma nonempty_psigma {α : Sort u} {β : α → Sort v} :
nonempty (psigma β) ↔ (∃a:α, nonempty (β a)) :=
iff.intro (assume ⟨⟨a, c⟩⟩, ⟨a, ⟨c⟩⟩) (assume ⟨a, ⟨c⟩⟩, ⟨⟨a, c⟩⟩)
@[simp] lemma nonempty_empty : ¬ nonempty empty :=
assume ⟨h⟩, h.elim
@[simp] lemma nonempty_ulift : nonempty (ulift α) ↔ nonempty α :=
iff.intro (assume ⟨⟨a⟩⟩, ⟨a⟩) (assume ⟨a⟩, ⟨⟨a⟩⟩)
@[simp] lemma nonempty_plift {α : Sort u} : nonempty (plift α) ↔ nonempty α :=
iff.intro (assume ⟨⟨a⟩⟩, ⟨a⟩) (assume ⟨a⟩, ⟨⟨a⟩⟩)
@[simp] lemma nonempty.forall {α : Sort u} {p : nonempty α → Prop} :
(∀h:nonempty α, p h) ↔ (∀a, p ⟨a⟩) :=
iff.intro (assume h a, h _) (assume h ⟨a⟩, h _)
@[simp] lemma nonempty.exists {α : Sort u} {p : nonempty α → Prop} :
(∃h:nonempty α, p h) ↔ (∃a, p ⟨a⟩) :=
iff.intro (assume ⟨⟨a⟩, h⟩, ⟨a, h⟩) (assume ⟨a, h⟩, ⟨⟨a⟩, h⟩)
lemma classical.nonempty_pi {α : Sort u} {β : α → Sort v} :
nonempty (Πa:α, β a) ↔ (∀a:α, nonempty (β a)) :=
iff.intro (assume ⟨f⟩ a, ⟨f a⟩) (assume f, ⟨assume a, classical.choice $ f a⟩)
/-- Using `classical.choice`, lifts a (`Prop`-valued) `nonempty` instance to a (`Type`-valued)
`inhabited` instance. `classical.inhabited_of_nonempty` already exists, in
`core/init/classical.lean`, but the assumption is not a type class argument,
which makes it unsuitable for some applications. -/
noncomputable def classical.inhabited_of_nonempty' {α : Sort u} [h : nonempty α] : inhabited α :=
⟨classical.choice h⟩
/-- Using `classical.choice`, extracts a term from a `nonempty` type. -/
@[reducible] protected noncomputable def nonempty.some {α : Sort u} (h : nonempty α) : α :=
classical.choice h
/-- Using `classical.choice`, extracts a term from a `nonempty` type. -/
@[reducible] protected noncomputable def classical.arbitrary (α : Sort u) [h : nonempty α] : α :=
classical.choice h
/-- Given `f : α → β`, if `α` is nonempty then `β` is also nonempty.
`nonempty` cannot be a `functor`, because `functor` is restricted to `Type`. -/
lemma nonempty.map {α : Sort u} {β : Sort v} (f : α → β) : nonempty α → nonempty β
| ⟨h⟩ := ⟨f h⟩
protected lemma nonempty.map2 {α β γ : Sort*} (f : α → β → γ) : nonempty α → nonempty β → nonempty γ
| ⟨x⟩ ⟨y⟩ := ⟨f x y⟩
protected lemma nonempty.congr {α : Sort u} {β : Sort v} (f : α → β) (g : β → α) :
nonempty α ↔ nonempty β :=
⟨nonempty.map f, nonempty.map g⟩
lemma nonempty.elim_to_inhabited {α : Sort*} [h : nonempty α] {p : Prop}
(f : inhabited α → p) : p :=
h.elim $ f ∘ inhabited.mk
instance {α β} [h : nonempty α] [h2 : nonempty β] : nonempty (α × β) :=
h.elim $ λ g, h2.elim $ λ g2, ⟨⟨g, g2⟩⟩
end nonempty
section ite
/-- A function applied to a `dite` is a `dite` of that function applied to each of the branches. -/
lemma apply_dite {α β : Sort*} (f : α → β) (P : Prop) [decidable P] (x : P → α) (y : ¬P → α) :
f (dite P x y) = dite P (λ h, f (x h)) (λ h, f (y h)) :=
by { by_cases h : P; simp [h] }
/-- A function applied to a `ite` is a `ite` of that function applied to each of the branches. -/
lemma apply_ite {α β : Sort*} (f : α → β) (P : Prop) [decidable P] (x y : α) :
f (ite P x y) = ite P (f x) (f y) :=
apply_dite f P (λ _, x) (λ _, y)
/-- A two-argument function applied to two `dite`s is a `dite` of that two-argument function
applied to each of the branches. -/
lemma apply_dite2 {α β γ : Sort*} (f : α → β → γ) (P : Prop) [decidable P] (a : P → α)
(b : ¬P → α) (c : P → β) (d : ¬P → β) :
f (dite P a b) (dite P c d) = dite P (λ h, f (a h) (c h)) (λ h, f (b h) (d h)) :=
by { by_cases h : P; simp [h] }
/-- A two-argument function applied to two `ite`s is a `ite` of that two-argument function
applied to each of the branches. -/
lemma apply_ite2 {α β γ : Sort*} (f : α → β → γ) (P : Prop) [decidable P] (a b : α) (c d : β) :
f (ite P a b) (ite P c d) = ite P (f a c) (f b d) :=
apply_dite2 f P (λ _, a) (λ _, b) (λ _, c) (λ _, d)
/-- A 'dite' producing a `Pi` type `Π a, β a`, applied to a value `x : α`
is a `dite` that applies either branch to `x`. -/
lemma dite_apply {α : Sort*} {β : α → Sort*} (P : Prop) [decidable P]
(f : P → Π a, β a) (g : ¬ P → Π a, β a) (x : α) :
(dite P f g) x = dite P (λ h, f h x) (λ h, g h x) :=
by { by_cases h : P; simp [h] }
/-- A 'ite' producing a `Pi` type `Π a, β a`, applied to a value `x : α`
is a `ite` that applies either branch to `x` -/
lemma ite_apply {α : Sort*} {β : α → Sort*} (P : Prop) [decidable P]
(f g : Π a, β a) (x : α) :
(ite P f g) x = ite P (f x) (g x) :=
dite_apply P (λ _, f) (λ _, g) x
/-- Negation of the condition `P : Prop` in a `dite` is the same as swapping the branches. -/
@[simp] lemma dite_not {α : Sort*} (P : Prop) [decidable P] (x : ¬ P → α) (y : ¬¬ P → α) :
dite (¬ P) x y = dite P (λ h, y (not_not_intro h)) x :=
by { by_cases h : P; simp [h] }
/-- Negation of the condition `P : Prop` in a `ite` is the same as swapping the branches. -/
@[simp] lemma ite_not {α : Sort*} (P : Prop) [decidable P] (x y : α) :
ite (¬ P) x y = ite P y x :=
dite_not P (λ _, x) (λ _, y)
lemma ite_and {α} {p q : Prop} [decidable p] [decidable q] {x y : α} :
ite (p ∧ q) x y = ite p (ite q x y) y :=
by { by_cases hp : p; by_cases hq : q; simp [hp, hq] }
end ite
|
84824a49d51576883977cec91d427b2ba9e3c448 | 94637389e03c919023691dcd05bd4411b1034aa5 | /src/inClassNotes/higherOrderFunctions/list_map.lean | a56a239dc3148c5432ff232f5b3dc0be138315a0 | [] | no_license | kevinsullivan/complogic-s21 | 7c4eef2105abad899e46502270d9829d913e8afc | 99039501b770248c8ceb39890be5dfe129dc1082 | refs/heads/master | 1,682,985,669,944 | 1,621,126,241,000 | 1,621,126,241,000 | 335,706,272 | 0 | 38 | null | 1,618,325,669,000 | 1,612,374,118,000 | Lean | UTF-8 | Lean | false | false | 131 | lean | def list_map {α β : Type} : (α → β) → (list α) → list β
| f list.nil := list.nil
| f (h::t) := (f h)::(list_map f t)
|
14ec90612dd5e83cb82a13ff8a220c2882b5409f | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/topology/order.lean | a6f9b80351e06a62090ed7b05d595965294f5c04 | [
"Apache-2.0"
] | permissive | gebner/mathlib | eab0150cc4f79ec45d2016a8c21750244a2e7ff0 | cc6a6edc397c55118df62831e23bfbd6e6c6b4ab | refs/heads/master | 1,625,574,853,976 | 1,586,712,827,000 | 1,586,712,827,000 | 99,101,412 | 1 | 0 | Apache-2.0 | 1,586,716,389,000 | 1,501,667,958,000 | Lean | UTF-8 | Lean | false | false | 27,675 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import topology.basic
/-!
# Ordering on topologies and (co)induced topologies
Topologies on a fixed type `α` are ordered, by reverse inclusion.
That is, for topologies `t₁` and `t₂` on `α`, we write `t₁ ≤ t₂`
if every set open in `t₂` is also open in `t₁`.
(One also calls `t₁` finer than `t₂`, and `t₂` coarser than `t₁`.)
Any function `f : α → β` induces
`induced f : topological_space β → topological_space α`
and `coinduced f : topological_space α → topological_space β`.
Continuity, the ordering on topologies and (co)induced topologies are
related as follows:
* The identity map (α, t₁) → (α, t₂) is continuous iff t₁ ≤ t₂.
* A map f : (α, t) → (β, u) is continuous
iff t ≤ induced f u (`continuous_iff_le_induced`)
iff coinduced f t ≤ u (`continuous_iff_coinduced_le`).
Topologies on α form a complete lattice, with ⊥ the discrete topology
and ⊤ the indiscrete topology.
For a function f : α → β, (coinduced f, induced f) is a Galois connection
between topologies on α and topologies on β.
## Implementation notes
There is a Galois insertion between topologies on α (with the inclusion ordering)
and all collections of sets in α. The complete lattice structure on topologies
on α is defined as the reverse of the one obtained via this Galois insertion.
## Tags
finer, coarser, induced topology, coinduced topology
-/
open set filter classical
open_locale classical topological_space
universes u v w
namespace topological_space
variables {α : Type u}
/-- The open sets of the least topology containing a collection of basic sets. -/
inductive generate_open (g : set (set α)) : set α → Prop
| basic : ∀s∈g, generate_open s
| univ : generate_open univ
| inter : ∀s t, generate_open s → generate_open t → generate_open (s ∩ t)
| sUnion : ∀k, (∀s∈k, generate_open s) → generate_open (⋃₀ k)
/-- The smallest topological space containing the collection `g` of basic sets -/
def generate_from (g : set (set α)) : topological_space α :=
{ is_open := generate_open g,
is_open_univ := generate_open.univ,
is_open_inter := generate_open.inter,
is_open_sUnion := generate_open.sUnion }
lemma nhds_generate_from {g : set (set α)} {a : α} :
@nhds α (generate_from g) a = (⨅s∈{s | a ∈ s ∧ s ∈ g}, principal s) :=
by rw nhds_def; exact le_antisymm
(infi_le_infi $ assume s, infi_le_infi_const $ assume ⟨as, sg⟩, ⟨as, generate_open.basic _ sg⟩)
(le_infi $ assume s, le_infi $ assume ⟨as, hs⟩,
begin
revert as, clear_, induction hs,
case generate_open.basic : s hs
{ exact assume as, infi_le_of_le s $ infi_le _ ⟨as, hs⟩ },
case generate_open.univ
{ rw [principal_univ],
exact assume _, le_top },
case generate_open.inter : s t hs' ht' hs ht
{ exact assume ⟨has, hat⟩, calc _ ≤ principal s ⊓ principal t : le_inf (hs has) (ht hat)
... = _ : inf_principal },
case generate_open.sUnion : k hk' hk
{ exact λ ⟨t, htk, hat⟩, calc _ ≤ principal t : hk t htk hat
... ≤ _ : le_principal_iff.2 $ subset_sUnion_of_mem htk }
end)
lemma tendsto_nhds_generate_from {β : Type*} {m : α → β} {f : filter α} {g : set (set β)} {b : β}
(h : ∀s∈g, b ∈ s → m ⁻¹' s ∈ f) : tendsto m f (@nhds β (generate_from g) b) :=
by rw [nhds_generate_from]; exact
(tendsto_infi.2 $ assume s, tendsto_infi.2 $ assume ⟨hbs, hsg⟩, tendsto_principal.2 $ h s hsg hbs)
/-- Construct a topology on α given the filter of neighborhoods of each point of α. -/
protected def mk_of_nhds (n : α → filter α) : topological_space α :=
{ is_open := λs, ∀a∈s, s ∈ n a,
is_open_univ := assume x h, univ_mem_sets,
is_open_inter := assume s t hs ht x ⟨hxs, hxt⟩, inter_mem_sets (hs x hxs) (ht x hxt),
is_open_sUnion := assume s hs a ⟨x, hx, hxa⟩, mem_sets_of_superset (hs x hx _ hxa) (set.subset_sUnion_of_mem hx) }
lemma nhds_mk_of_nhds (n : α → filter α) (a : α)
(h₀ : pure ≤ n) (h₁ : ∀{a s}, s ∈ n a → ∃ t ∈ n a, t ⊆ s ∧ ∀a' ∈ t, s ∈ n a') :
@nhds α (topological_space.mk_of_nhds n) a = n a :=
begin
letI := topological_space.mk_of_nhds n,
refine le_antisymm (assume s hs, _) (assume s hs, _),
{ have h₀ : {b | s ∈ n b} ⊆ s := assume b hb, mem_pure_sets.1 $ h₀ b hb,
have h₁ : {b | s ∈ n b} ∈ 𝓝 a,
{ refine mem_nhds_sets (assume b (hb : s ∈ n b), _) hs,
rcases h₁ hb with ⟨t, ht, hts, h⟩,
exact mem_sets_of_superset ht h },
exact mem_sets_of_superset h₁ h₀ },
{ rcases (@mem_nhds_sets_iff α (topological_space.mk_of_nhds n) _ _).1 hs with ⟨t, hts, ht, hat⟩,
exact (n a).sets_of_superset (ht _ hat) hts },
end
end topological_space
section lattice
variables {α : Type u} {β : Type v}
/-- The inclusion ordering on topologies on α. We use it to get a complete
lattice instance via the Galois insertion method, but the partial order
that we will eventually impose on `topological_space α` is the reverse one. -/
def tmp_order : partial_order (topological_space α) :=
{ le := λt s, t.is_open ≤ s.is_open,
le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₁ h₂,
le_refl := assume t, le_refl t.is_open,
le_trans := assume a b c h₁ h₂, @le_trans _ _ a.is_open b.is_open c.is_open h₁ h₂ }
local attribute [instance] tmp_order
/- We'll later restate this lemma in terms of the correct order on `topological_space α`. -/
private lemma generate_from_le_iff_subset_is_open {g : set (set α)} {t : topological_space α} :
topological_space.generate_from g ≤ t ↔ g ⊆ {s | t.is_open s} :=
iff.intro
(assume ht s hs, ht _ $ topological_space.generate_open.basic s hs)
(assume hg s hs, hs.rec_on (assume v hv, hg hv)
t.is_open_univ (assume u v _ _, t.is_open_inter u v) (assume k _, t.is_open_sUnion k))
/-- If `s` equals the collection of open sets in the topology it generates,
then `s` defines a topology. -/
protected def mk_of_closure (s : set (set α))
(hs : {u | (topological_space.generate_from s).is_open u} = s) : topological_space α :=
{ is_open := λu, u ∈ s,
is_open_univ := hs ▸ topological_space.generate_open.univ,
is_open_inter := hs ▸ topological_space.generate_open.inter,
is_open_sUnion := hs ▸ topological_space.generate_open.sUnion }
lemma mk_of_closure_sets {s : set (set α)}
{hs : {u | (topological_space.generate_from s).is_open u} = s} :
mk_of_closure s hs = topological_space.generate_from s :=
topological_space_eq hs.symm
/-- The Galois insertion between `set (set α)` and `topological_space α` whose lower part
sends a collection of subsets of α to the topology they generate, and whose upper part
sends a topology to its collection of open subsets. -/
def gi_generate_from (α : Type*) :
galois_insertion topological_space.generate_from (λt:topological_space α, {s | t.is_open s}) :=
{ gc := assume g t, generate_from_le_iff_subset_is_open,
le_l_u := assume ts s hs, topological_space.generate_open.basic s hs,
choice := λg hg, mk_of_closure g
(subset.antisymm hg $ generate_from_le_iff_subset_is_open.1 $ le_refl _),
choice_eq := assume s hs, mk_of_closure_sets }
lemma generate_from_mono {α} {g₁ g₂ : set (set α)} (h : g₁ ⊆ g₂) :
topological_space.generate_from g₁ ≤ topological_space.generate_from g₂ :=
(gi_generate_from _).gc.monotone_l h
/-- The complete lattice of topological spaces, but built on the inclusion ordering. -/
def tmp_complete_lattice {α : Type u} : complete_lattice (topological_space α) :=
(gi_generate_from α).lift_complete_lattice
/-- The ordering on topologies on the type `α`.
`t ≤ s` if every set open in `s` is also open in `t` (`t` is finer than `s`). -/
instance : partial_order (topological_space α) :=
{ le := λ t s, s.is_open ≤ t.is_open,
le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₂ h₁,
le_refl := assume t, le_refl t.is_open,
le_trans := assume a b c h₁ h₂, le_trans h₂ h₁ }
lemma le_generate_from_iff_subset_is_open {g : set (set α)} {t : topological_space α} :
t ≤ topological_space.generate_from g ↔ g ⊆ {s | t.is_open s} :=
generate_from_le_iff_subset_is_open
/-- Topologies on `α` form a complete lattice, with `⊥` the discrete topology
and `⊤` the indiscrete topology. The infimum of a collection of topologies
is the topology generated by all their open sets, while the supremem is the
topology whose open sets are those sets open in every member of the collection. -/
instance : complete_lattice (topological_space α) :=
@order_dual.complete_lattice _ tmp_complete_lattice
/-- A topological space is discrete if every set is open, that is,
its topology equals the discrete topology `⊥`. -/
class discrete_topology (α : Type*) [t : topological_space α] : Prop :=
(eq_bot [] : t = ⊥)
@[simp] lemma is_open_discrete [topological_space α] [discrete_topology α] (s : set α) :
is_open s :=
(discrete_topology.eq_bot α).symm ▸ trivial
@[simp] lemma is_closed_discrete [topological_space α] [discrete_topology α] (s : set α) :
is_closed s :=
(discrete_topology.eq_bot α).symm ▸ trivial
lemma continuous_of_discrete_topology [topological_space α] [discrete_topology α] [topological_space β] {f : α → β} : continuous f :=
λs hs, is_open_discrete _
lemma nhds_bot (α : Type*) : (@nhds α ⊥) = pure :=
begin
refine le_antisymm _ (@pure_le_nhds α ⊥),
assume a s hs,
exact @mem_nhds_sets α ⊥ a s trivial hs
end
lemma nhds_discrete (α : Type*) [topological_space α] [discrete_topology α] : (@nhds α _) = pure :=
(discrete_topology.eq_bot α).symm ▸ nhds_bot α
lemma le_of_nhds_le_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₁ x ≤ @nhds α t₂ x) :
t₁ ≤ t₂ :=
assume s, show @is_open α t₂ s → @is_open α t₁ s,
by { simp only [is_open_iff_nhds, le_principal_iff], exact assume hs a ha, h _ $ hs _ ha }
lemma eq_of_nhds_eq_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₁ x = @nhds α t₂ x) :
t₁ = t₂ :=
le_antisymm
(le_of_nhds_le_nhds $ assume x, le_of_eq $ h x)
(le_of_nhds_le_nhds $ assume x, le_of_eq $ (h x).symm)
lemma eq_bot_of_singletons_open {t : topological_space α} (h : ∀ x, t.is_open {x}) : t = ⊥ :=
bot_unique $ λ s hs, bUnion_of_singleton s ▸ is_open_bUnion (λ x _, h x)
end lattice
section galois_connection
variables {α : Type*} {β : Type*} {γ : Type*}
/-- Given `f : α → β` and a topology on `β`, the induced topology on `α` is the collection of
sets that are preimages of some open set in `β`. This is the coarsest topology that
makes `f` continuous. -/
def topological_space.induced {α : Type u} {β : Type v} (f : α → β) (t : topological_space β) :
topological_space α :=
{ is_open := λs, ∃s', t.is_open s' ∧ f ⁻¹' s' = s,
is_open_univ := ⟨univ, t.is_open_univ, preimage_univ⟩,
is_open_inter := by rintro s₁ s₂ ⟨s'₁, hs₁, rfl⟩ ⟨s'₂, hs₂, rfl⟩;
exact ⟨s'₁ ∩ s'₂, t.is_open_inter _ _ hs₁ hs₂, preimage_inter⟩,
is_open_sUnion := assume s h,
begin
simp only [classical.skolem] at h,
cases h with f hf,
apply exists.intro (⋃(x : set α) (h : x ∈ s), f x h),
simp only [sUnion_eq_bUnion, preimage_Union, (λx h, (hf x h).right)], refine ⟨_, rfl⟩,
exact (@is_open_Union β _ t _ $ assume i,
show is_open (⋃h, f i h), from @is_open_Union β _ t _ $ assume h, (hf i h).left)
end }
lemma is_open_induced_iff [t : topological_space β] {s : set α} {f : α → β} :
@is_open α (t.induced f) s ↔ (∃t, is_open t ∧ f ⁻¹' t = s) :=
iff.rfl
lemma is_closed_induced_iff [t : topological_space β] {s : set α} {f : α → β} :
@is_closed α (t.induced f) s ↔ (∃t, is_closed t ∧ s = f ⁻¹' t) :=
⟨assume ⟨t, ht, heq⟩, ⟨-t, is_closed_compl_iff.2 ht,
by simp only [preimage_compl, heq, compl_compl]⟩,
assume ⟨t, ht, heq⟩, ⟨-t, ht, by simp only [preimage_compl, heq.symm]⟩⟩
/-- Given `f : α → β` and a topology on `α`, the coinduced topology on `β` is defined
such that `s:set β` is open if the preimage of `s` is open. This is the finest topology that
makes `f` continuous. -/
def topological_space.coinduced {α : Type u} {β : Type v} (f : α → β) (t : topological_space α) :
topological_space β :=
{ is_open := λs, t.is_open (f ⁻¹' s),
is_open_univ := by rw preimage_univ; exact t.is_open_univ,
is_open_inter := assume s₁ s₂ h₁ h₂, by rw preimage_inter; exact t.is_open_inter _ _ h₁ h₂,
is_open_sUnion := assume s h, by rw [preimage_sUnion]; exact (@is_open_Union _ _ t _ $ assume i,
show is_open (⋃ (H : i ∈ s), f ⁻¹' i), from
@is_open_Union _ _ t _ $ assume hi, h i hi) }
lemma is_open_coinduced {t : topological_space α} {s : set β} {f : α → β} :
@is_open β (topological_space.coinduced f t) s ↔ is_open (f ⁻¹' s) :=
iff.rfl
variables {t t₁ t₂ : topological_space α} {t' : topological_space β} {f : α → β} {g : β → α}
lemma coinduced_le_iff_le_induced {f : α → β } {tα : topological_space α} {tβ : topological_space β} :
tα.coinduced f ≤ tβ ↔ tα ≤ tβ.induced f :=
iff.intro
(assume h s ⟨t, ht, hst⟩, hst ▸ h _ ht)
(assume h s hs, show tα.is_open (f ⁻¹' s), from h _ ⟨s, hs, rfl⟩)
lemma gc_coinduced_induced (f : α → β) :
galois_connection (topological_space.coinduced f) (topological_space.induced f) :=
assume f g, coinduced_le_iff_le_induced
lemma induced_mono (h : t₁ ≤ t₂) : t₁.induced g ≤ t₂.induced g :=
(gc_coinduced_induced g).monotone_u h
lemma coinduced_mono (h : t₁ ≤ t₂) : t₁.coinduced f ≤ t₂.coinduced f :=
(gc_coinduced_induced f).monotone_l h
@[simp] lemma induced_top : (⊤ : topological_space α).induced g = ⊤ :=
(gc_coinduced_induced g).u_top
@[simp] lemma induced_inf : (t₁ ⊓ t₂).induced g = t₁.induced g ⊓ t₂.induced g :=
(gc_coinduced_induced g).u_inf
@[simp] lemma induced_infi {ι : Sort w} {t : ι → topological_space α} :
(⨅i, t i).induced g = (⨅i, (t i).induced g) :=
(gc_coinduced_induced g).u_infi
@[simp] lemma coinduced_bot : (⊥ : topological_space α).coinduced f = ⊥ :=
(gc_coinduced_induced f).l_bot
@[simp] lemma coinduced_sup : (t₁ ⊔ t₂).coinduced f = t₁.coinduced f ⊔ t₂.coinduced f :=
(gc_coinduced_induced f).l_sup
@[simp] lemma coinduced_supr {ι : Sort w} {t : ι → topological_space α} :
(⨆i, t i).coinduced f = (⨆i, (t i).coinduced f) :=
(gc_coinduced_induced f).l_supr
lemma induced_id [t : topological_space α] : t.induced id = t :=
topological_space_eq $ funext $ assume s, propext $
⟨assume ⟨s', hs, h⟩, h ▸ hs, assume hs, ⟨s, hs, rfl⟩⟩
lemma induced_compose [tγ : topological_space γ]
{f : α → β} {g : β → γ} : (tγ.induced g).induced f = tγ.induced (g ∘ f) :=
topological_space_eq $ funext $ assume s, propext $
⟨assume ⟨s', ⟨s, hs, h₂⟩, h₁⟩, h₁ ▸ h₂ ▸ ⟨s, hs, rfl⟩,
assume ⟨s, hs, h⟩, ⟨preimage g s, ⟨s, hs, rfl⟩, h ▸ rfl⟩⟩
lemma coinduced_id [t : topological_space α] : t.coinduced id = t :=
topological_space_eq rfl
lemma coinduced_compose [tα : topological_space α]
{f : α → β} {g : β → γ} : (tα.coinduced f).coinduced g = tα.coinduced (g ∘ f) :=
topological_space_eq rfl
end galois_connection
/- constructions using the complete lattice structure -/
section constructions
open topological_space
variables {α : Type u} {β : Type v}
instance inhabited_topological_space {α : Type u} : inhabited (topological_space α) :=
⟨⊤⟩
@[priority 100]
instance subsingleton.discrete_topology [topological_space α] [subsingleton α] :
discrete_topology α :=
⟨eq_bot_of_singletons_open $ λ x, subsingleton.set_cases is_open_empty is_open_univ ({x} : set α)⟩
instance : topological_space empty := ⊥
instance : discrete_topology empty := ⟨rfl⟩
instance : topological_space unit := ⊥
instance : discrete_topology unit := ⟨rfl⟩
instance : topological_space bool := ⊥
instance : discrete_topology bool := ⟨rfl⟩
instance : topological_space ℕ := ⊥
instance : discrete_topology ℕ := ⟨rfl⟩
instance : topological_space ℤ := ⊥
instance : discrete_topology ℤ := ⟨rfl⟩
instance sierpinski_space : topological_space Prop :=
generate_from {{true}}
lemma le_generate_from {t : topological_space α} { g : set (set α) } (h : ∀s∈g, is_open s) :
t ≤ generate_from g :=
le_generate_from_iff_subset_is_open.2 h
lemma induced_generate_from_eq {α β} {b : set (set β)} {f : α → β} :
(generate_from b).induced f = topological_space.generate_from (preimage f '' b) :=
le_antisymm
(le_generate_from $ ball_image_iff.2 $ assume s hs, ⟨s, generate_open.basic _ hs, rfl⟩)
(coinduced_le_iff_le_induced.1 $ le_generate_from $ assume s hs,
generate_open.basic _ $ mem_image_of_mem _ hs)
/-- This construction is left adjoint to the operation sending a topology on `α`
to its neighborhood filter at a fixed point `a : α`. -/
protected def topological_space.nhds_adjoint (a : α) (f : filter α) : topological_space α :=
{ is_open := λs, a ∈ s → s ∈ f,
is_open_univ := assume s, univ_mem_sets,
is_open_inter := assume s t hs ht ⟨has, hat⟩, inter_mem_sets (hs has) (ht hat),
is_open_sUnion := assume k hk ⟨u, hu, hau⟩, mem_sets_of_superset (hk u hu hau) (subset_sUnion_of_mem hu) }
lemma gc_nhds (a : α) :
galois_connection (topological_space.nhds_adjoint a) (λt, @nhds α t a) :=
assume f t, by { rw le_nhds_iff, exact ⟨λ H s hs has, H _ has hs, λ H s has hs, H _ hs has⟩ }
lemma nhds_mono {t₁ t₂ : topological_space α} {a : α} (h : t₁ ≤ t₂) :
@nhds α t₁ a ≤ @nhds α t₂ a := (gc_nhds a).monotone_u h
lemma nhds_infi {ι : Sort*} {t : ι → topological_space α} {a : α} :
@nhds α (infi t) a = (⨅i, @nhds α (t i) a) := (gc_nhds a).u_infi
lemma nhds_Inf {s : set (topological_space α)} {a : α} :
@nhds α (Inf s) a = (⨅t∈s, @nhds α t a) := (gc_nhds a).u_Inf
lemma nhds_inf {t₁ t₂ : topological_space α} {a : α} :
@nhds α (t₁ ⊓ t₂) a = @nhds α t₁ a ⊓ @nhds α t₂ a := (gc_nhds a).u_inf
lemma nhds_top {a : α} : @nhds α ⊤ a = ⊤ := (gc_nhds a).u_top
local notation `cont` := @continuous _ _
local notation `tspace` := topological_space
open topological_space
variables {γ : Type*} {f : α → β} {ι : Sort*}
lemma continuous_iff_coinduced_le {t₁ : tspace α} {t₂ : tspace β} :
cont t₁ t₂ f ↔ coinduced f t₁ ≤ t₂ := iff.rfl
lemma continuous_iff_le_induced {t₁ : tspace α} {t₂ : tspace β} :
cont t₁ t₂ f ↔ t₁ ≤ induced f t₂ :=
iff.trans continuous_iff_coinduced_le (gc_coinduced_induced f _ _)
theorem continuous_generated_from {t : tspace α} {b : set (set β)}
(h : ∀s∈b, is_open (f ⁻¹' s)) : cont t (generate_from b) f :=
continuous_iff_coinduced_le.2 $ le_generate_from h
lemma continuous_induced_dom {t : tspace β} : cont (induced f t) t f :=
assume s h, ⟨_, h, rfl⟩
lemma continuous_induced_rng {g : γ → α} {t₂ : tspace β} {t₁ : tspace γ}
(h : cont t₁ t₂ (f ∘ g)) : cont t₁ (induced f t₂) g :=
assume s ⟨t, ht, s_eq⟩, s_eq ▸ h t ht
lemma continuous_coinduced_rng {t : tspace α} : cont t (coinduced f t) f :=
assume s h, h
lemma continuous_coinduced_dom {g : β → γ} {t₁ : tspace α} {t₂ : tspace γ}
(h : cont t₁ t₂ (g ∘ f)) : cont (coinduced f t₁) t₂ g :=
assume s hs, h s hs
lemma continuous_le_dom {t₁ t₂ : tspace α} {t₃ : tspace β}
(h₁ : t₂ ≤ t₁) (h₂ : cont t₁ t₃ f) : cont t₂ t₃ f :=
assume s h, h₁ _ (h₂ s h)
lemma continuous_le_rng {t₁ : tspace α} {t₂ t₃ : tspace β}
(h₁ : t₂ ≤ t₃) (h₂ : cont t₁ t₂ f) : cont t₁ t₃ f :=
assume s h, h₂ s (h₁ s h)
lemma continuous_sup_dom {t₁ t₂ : tspace α} {t₃ : tspace β}
(h₁ : cont t₁ t₃ f) (h₂ : cont t₂ t₃ f) : cont (t₁ ⊔ t₂) t₃ f :=
assume s h, ⟨h₁ s h, h₂ s h⟩
lemma continuous_sup_rng_left {t₁ : tspace α} {t₃ t₂ : tspace β} :
cont t₁ t₂ f → cont t₁ (t₂ ⊔ t₃) f :=
continuous_le_rng le_sup_left
lemma continuous_sup_rng_right {t₁ : tspace α} {t₃ t₂ : tspace β} :
cont t₁ t₃ f → cont t₁ (t₂ ⊔ t₃) f :=
continuous_le_rng le_sup_right
lemma continuous_Sup_dom {t₁ : set (tspace α)} {t₂ : tspace β}
(h : ∀t∈t₁, cont t t₂ f) : cont (Sup t₁) t₂ f :=
continuous_iff_le_induced.2 $ Sup_le $ assume t ht, continuous_iff_le_induced.1 $ h t ht
lemma continuous_Sup_rng {t₁ : tspace α} {t₂ : set (tspace β)} {t : tspace β}
(h₁ : t ∈ t₂) (hf : cont t₁ t f) : cont t₁ (Sup t₂) f :=
continuous_iff_coinduced_le.2 $ le_Sup_of_le h₁ $ continuous_iff_coinduced_le.1 hf
lemma continuous_supr_dom {t₁ : ι → tspace α} {t₂ : tspace β}
(h : ∀i, cont (t₁ i) t₂ f) : cont (supr t₁) t₂ f :=
continuous_Sup_dom $ assume t ⟨i, (t_eq : t₁ i = t)⟩, t_eq ▸ h i
lemma continuous_supr_rng {t₁ : tspace α} {t₂ : ι → tspace β} {i : ι}
(h : cont t₁ (t₂ i) f) : cont t₁ (supr t₂) f :=
continuous_Sup_rng ⟨i, rfl⟩ h
lemma continuous_inf_rng {t₁ : tspace α} {t₂ t₃ : tspace β}
(h₁ : cont t₁ t₂ f) (h₂ : cont t₁ t₃ f) : cont t₁ (t₂ ⊓ t₃) f :=
continuous_iff_coinduced_le.2 $ le_inf
(continuous_iff_coinduced_le.1 h₁)
(continuous_iff_coinduced_le.1 h₂)
lemma continuous_inf_dom_left {t₁ t₂ : tspace α} {t₃ : tspace β} :
cont t₁ t₃ f → cont (t₁ ⊓ t₂) t₃ f :=
continuous_le_dom inf_le_left
lemma continuous_inf_dom_right {t₁ t₂ : tspace α} {t₃ : tspace β} :
cont t₂ t₃ f → cont (t₁ ⊓ t₂) t₃ f :=
continuous_le_dom inf_le_right
lemma continuous_Inf_dom {t₁ : set (tspace α)} {t₂ : tspace β} {t : tspace α} (h₁ : t ∈ t₁) :
cont t t₂ f → cont (Inf t₁) t₂ f :=
continuous_le_dom $ Inf_le h₁
lemma continuous_Inf_rng {t₁ : tspace α} {t₂ : set (tspace β)}
(h : ∀t∈t₂, cont t₁ t f) : cont t₁ (Inf t₂) f :=
continuous_iff_coinduced_le.2 $ le_Inf $ assume b hb, continuous_iff_coinduced_le.1 $ h b hb
lemma continuous_infi_dom {t₁ : ι → tspace α} {t₂ : tspace β} {i : ι} :
cont (t₁ i) t₂ f → cont (infi t₁) t₂ f :=
continuous_le_dom $ infi_le _ _
lemma continuous_infi_rng {t₁ : tspace α} {t₂ : ι → tspace β}
(h : ∀i, cont t₁ (t₂ i) f) : cont t₁ (infi t₂) f :=
continuous_iff_coinduced_le.2 $ le_infi $ assume i, continuous_iff_coinduced_le.1 $ h i
lemma continuous_bot {t : tspace β} : cont ⊥ t f :=
continuous_iff_le_induced.2 $ bot_le
lemma continuous_top {t : tspace α} : cont t ⊤ f :=
continuous_iff_coinduced_le.2 $ le_top
/- 𝓝 in the induced topology -/
theorem mem_nhds_induced [T : topological_space α] (f : β → α) (a : β) (s : set β) :
s ∈ @nhds β (topological_space.induced f T) a ↔ ∃ u ∈ 𝓝 (f a), f ⁻¹' u ⊆ s :=
begin
simp only [mem_nhds_sets_iff, is_open_induced_iff, exists_prop, set.mem_set_of_eq],
split,
{ rintros ⟨u, usub, ⟨v, openv, ueq⟩, au⟩,
exact ⟨v, ⟨v, set.subset.refl v, openv, by rwa ←ueq at au⟩, by rw ueq; exact usub⟩ },
rintros ⟨u, ⟨v, vsubu, openv, amem⟩, finvsub⟩,
exact ⟨f ⁻¹' v, set.subset.trans (set.preimage_mono vsubu) finvsub, ⟨⟨v, openv, rfl⟩, amem⟩⟩
end
theorem nhds_induced [T : topological_space α] (f : β → α) (a : β) :
@nhds β (topological_space.induced f T) a = comap f (𝓝 (f a)) :=
filter_eq $ by ext s; rw mem_nhds_induced; rw mem_comap_sets
lemma induced_iff_nhds_eq [tα : topological_space α] [tβ : topological_space β] (f : β → α) :
tβ = tα.induced f ↔ ∀ b, 𝓝 b = comap f (𝓝 $ f b) :=
⟨λ h a, h.symm ▸ nhds_induced f a, λ h, eq_of_nhds_eq_nhds $ λ x, by rw [h, nhds_induced]⟩
theorem map_nhds_induced_of_surjective [T : topological_space α]
{f : β → α} (hf : function.surjective f) (a : β) :
map f (@nhds β (topological_space.induced f T) a) = 𝓝 (f a) :=
by rw [nhds_induced, map_comap_of_surjective hf]
end constructions
section induced
open topological_space
variables {α : Type*} {β : Type*}
variables [t : topological_space β] {f : α → β}
theorem is_open_induced_eq {s : set α} :
@_root_.is_open _ (induced f t) s ↔ s ∈ preimage f '' {s | is_open s} :=
iff.rfl
theorem is_open_induced {s : set β} (h : is_open s) : (induced f t).is_open (f ⁻¹' s) :=
⟨s, h, rfl⟩
lemma map_nhds_induced_eq {a : α} (h : range f ∈ 𝓝 (f a)) :
map f (@nhds α (induced f t) a) = 𝓝 (f a) :=
by rw [nhds_induced, filter.map_comap h]
lemma closure_induced [t : topological_space β] {f : α → β} {a : α} {s : set α}
(hf : ∀x y, f x = f y → x = y) :
a ∈ @closure α (topological_space.induced f t) s ↔ f a ∈ closure (f '' s) :=
have comap f (𝓝 (f a) ⊓ principal (f '' s)) ≠ ⊥ ↔ 𝓝 (f a) ⊓ principal (f '' s) ≠ ⊥,
from ⟨assume h₁ h₂, h₁ $ h₂.symm ▸ comap_bot,
assume h,
forall_sets_nonempty_iff_ne_bot.mp $
assume s₁ ⟨s₂, hs₂, (hs : f ⁻¹' s₂ ⊆ s₁)⟩,
have f '' s ∈ 𝓝 (f a) ⊓ principal (f '' s),
from mem_inf_sets_of_right $ by simp [subset.refl],
have s₂ ∩ f '' s ∈ 𝓝 (f a) ⊓ principal (f '' s),
from inter_mem_sets hs₂ this,
let ⟨b, hb₁, ⟨a, ha, ha₂⟩⟩ := nonempty_of_mem_sets h this in
⟨_, hs $ by rwa [←ha₂] at hb₁⟩⟩,
calc a ∈ @closure α (topological_space.induced f t) s
↔ (@nhds α (topological_space.induced f t) a) ⊓ principal s ≠ ⊥ : by rw [closure_eq_nhds]; refl
... ↔ comap f (𝓝 (f a)) ⊓ principal (f ⁻¹' (f '' s)) ≠ ⊥ : by rw [nhds_induced, preimage_image_eq _ hf]
... ↔ comap f (𝓝 (f a) ⊓ principal (f '' s)) ≠ ⊥ : by rw [comap_inf, ←comap_principal]
... ↔ _ : by rwa [closure_eq_nhds]
end induced
section sierpinski
variables {α : Type*} [topological_space α]
@[simp] lemma is_open_singleton_true : is_open ({true} : set Prop) :=
topological_space.generate_open.basic _ (by simp)
lemma continuous_Prop {p : α → Prop} : continuous p ↔ is_open {x | p x} :=
⟨assume h : continuous p,
have is_open (p ⁻¹' {true}),
from h _ is_open_singleton_true,
by simp [preimage, eq_true] at this; assumption,
assume h : is_open {x | p x},
continuous_generated_from $ assume s (hs : s ∈ {{true}}),
by simp at hs; simp [hs, preimage, eq_true, h]⟩
end sierpinski
section infi
variables {α : Type u} {ι : Type v} {t : ι → topological_space α}
lemma is_open_supr_iff {s : set α} : @is_open _ (⨆ i, t i) s ↔ ∀ i, @is_open _ (t i) s :=
begin
-- s defines a map from α to Prop, which is continuous iff s is open.
suffices : @continuous _ _ (⨆ i, t i) _ s ↔ ∀ i, @continuous _ _ (t i) _ s,
{ simpa only [continuous_Prop] using this },
simp only [continuous_iff_le_induced, supr_le_iff]
end
lemma is_closed_infi_iff {s : set α} : @is_closed _ (⨆ i, t i) s ↔ ∀ i, @is_closed _ (t i) s :=
is_open_supr_iff
end infi
|
69e5b2c7d629d94795b008c30dda5f8bca5132e1 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/category_theory/products/basic.lean | 6b52f8703c844f89e0092b149fa3341a31107baf | [
"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 | 10,628 | 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.eq_to_hom
import category_theory.functor.const
/-!
# Cartesian products of categories
We define the category instance on `C × D` when `C` and `D` are categories.
We define:
* `sectl C Z` : the functor `C ⥤ C × D` given by `X ↦ ⟨X, Z⟩`
* `sectr Z D` : the functor `D ⥤ C × D` given by `Y ↦ ⟨Z, Y⟩`
* `fst` : the functor `⟨X, Y⟩ ↦ X`
* `snd` : the functor `⟨X, Y⟩ ↦ Y`
* `swap` : the functor `C × D ⥤ D × C` given by `⟨X, Y⟩ ↦ ⟨Y, X⟩`
(and the fact this is an equivalence)
We further define `evaluation : C ⥤ (C ⥤ D) ⥤ D` and `evaluation_uncurried : C × (C ⥤ D) ⥤ D`,
and products of functors and natural transformations, written `F.prod G` and `α.prod β`.
-/
namespace category_theory
-- declare the `v`'s first; see `category_theory.category` for an explanation
universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄
section
variables (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D]
/--
`prod C D` gives the cartesian product of two categories.
See <https://stacks.math.columbia.edu/tag/001K>.
-/
@[simps {not_recursive := []}] -- the generates simp lemmas like `id_fst` and `comp_snd`
instance prod : category.{max v₁ v₂} (C × D) :=
{ hom := λ X Y, ((X.1) ⟶ (Y.1)) × ((X.2) ⟶ (Y.2)),
id := λ X, ⟨ 𝟙 (X.1), 𝟙 (X.2) ⟩,
comp := λ _ _ _ f g, (f.1 ≫ g.1, f.2 ≫ g.2) }
/-- Two rfl lemmas that cannot be generated by `@[simps]`. -/
@[simp] lemma prod_id (X : C) (Y : D) : 𝟙 (X, Y) = (𝟙 X, 𝟙 Y) := rfl
@[simp] lemma prod_comp {P Q R : C} {S T U : D} (f : (P, S) ⟶ (Q, T)) (g : (Q, T) ⟶ (R, U)) :
f ≫ g = (f.1 ≫ g.1, f.2 ≫ g.2) := rfl
lemma is_iso_prod_iff {P Q : C} {S T : D} {f : (P, S) ⟶ (Q, T)} :
is_iso f ↔ is_iso f.1 ∧ is_iso f.2 :=
begin
split,
{ rintros ⟨g, hfg, hgf⟩,
simp at hfg hgf,
rcases hfg with ⟨hfg₁, hfg₂⟩,
rcases hgf with ⟨hgf₁, hgf₂⟩,
exact ⟨⟨⟨g.1, hfg₁, hgf₁⟩⟩, ⟨⟨g.2, hfg₂, hgf₂⟩⟩⟩ },
{ rintros ⟨⟨g₁, hfg₁, hgf₁⟩, ⟨g₂, hfg₂, hgf₂⟩⟩,
dsimp at hfg₁ hgf₁ hfg₂ hgf₂,
refine ⟨⟨(g₁, g₂), _, _⟩⟩; { simp; split; assumption } }
end
section
variables {C D}
/-- The isomorphism between `(X.1, X.2)` and `X`. -/
@[simps]
def prod.eta_iso (X : C × D) : (X.1, X.2) ≅ X := { hom := (𝟙 _, 𝟙 _), inv := (𝟙 _, 𝟙 _) }
/-- Construct an isomorphism in `C × D` out of two isomorphisms in `C` and `D`. -/
@[simps]
def iso.prod {P Q : C} {S T : D} (f : P ≅ Q) (g : S ≅ T) : (P, S) ≅ (Q, T) :=
{ hom := (f.hom, g.hom),
inv := (f.inv, g.inv), }
end
end
section
variables (C : Type u₁) [category.{v₁} C] (D : Type u₁) [category.{v₁} D]
/--
`prod.category.uniform C D` is an additional instance specialised so both factors have the same
universe levels. This helps typeclass resolution.
-/
instance uniform_prod : category (C × D) := category_theory.prod C D
end
-- Next we define the natural functors into and out of product categories. For now this doesn't
-- address the universal properties.
namespace prod
/-- `sectl C Z` is the functor `C ⥤ C × D` given by `X ↦ (X, Z)`. -/
@[simps] def sectl
(C : Type u₁) [category.{v₁} C] {D : Type u₂} [category.{v₂} D] (Z : D) : C ⥤ C × D :=
{ obj := λ X, (X, Z),
map := λ X Y f, (f, 𝟙 Z) }
/-- `sectr Z D` is the functor `D ⥤ C × D` given by `Y ↦ (Z, Y)` . -/
@[simps] def sectr
{C : Type u₁} [category.{v₁} C] (Z : C) (D : Type u₂) [category.{v₂} D] : D ⥤ C × D :=
{ obj := λ X, (Z, X),
map := λ X Y f, (𝟙 Z, f) }
variables (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D]
/-- `fst` is the functor `(X, Y) ↦ X`. -/
@[simps] def fst : C × D ⥤ C :=
{ obj := λ X, X.1,
map := λ X Y f, f.1 }
/-- `snd` is the functor `(X, Y) ↦ Y`. -/
@[simps] def snd : C × D ⥤ D :=
{ obj := λ X, X.2,
map := λ X Y f, f.2 }
/-- The functor swapping the factors of a cartesian product of categories, `C × D ⥤ D × C`. -/
@[simps] def swap : C × D ⥤ D × C :=
{ obj := λ X, (X.2, X.1),
map := λ _ _ f, (f.2, f.1) }
/--
Swapping the factors of a cartesion product of categories twice is naturally isomorphic
to the identity functor.
-/
@[simps] def symmetry : swap C D ⋙ swap D C ≅ 𝟭 (C × D) :=
{ hom := { app := λ X, 𝟙 X },
inv := { app := λ X, 𝟙 X } }
/--
The equivalence, given by swapping factors, between `C × D` and `D × C`.
-/
@[simps]
def braiding : C × D ≌ D × C :=
equivalence.mk (swap C D) (swap D C)
(nat_iso.of_components (λ X, eq_to_iso (by simp)) (by tidy))
(nat_iso.of_components (λ X, eq_to_iso (by simp)) (by tidy))
instance swap_is_equivalence : is_equivalence (swap C D) :=
(by apply_instance : is_equivalence (braiding C D).functor)
end prod
section
variables (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D]
/--
The "evaluation at `X`" functor, such that
`(evaluation.obj X).obj F = F.obj X`,
which is functorial in both `X` and `F`.
-/
@[simps] def evaluation : C ⥤ (C ⥤ D) ⥤ D :=
{ obj := λ X,
{ obj := λ F, F.obj X,
map := λ F G α, α.app X, },
map := λ X Y f,
{ app := λ F, F.map f,
naturality' := λ F G α, eq.symm (α.naturality f) } }
/--
The "evaluation of `F` at `X`" functor,
as a functor `C × (C ⥤ D) ⥤ D`.
-/
@[simps] def evaluation_uncurried : C × (C ⥤ D) ⥤ D :=
{ obj := λ p, p.2.obj p.1,
map := λ x y f, (x.2.map f.1) ≫ (f.2.app y.1),
map_comp' := λ X Y Z f g,
begin
cases g, cases f, cases Z, cases Y, cases X,
simp only [prod_comp, nat_trans.comp_app, functor.map_comp, category.assoc],
rw [←nat_trans.comp_app, nat_trans.naturality, nat_trans.comp_app,
category.assoc, nat_trans.naturality],
end }
variables {C}
/-- The constant functor followed by the evalutation functor is just the identity. -/
@[simps] def functor.const_comp_evaluation_obj (X : C) :
functor.const C ⋙ (evaluation C D).obj X ≅ 𝟭 D :=
nat_iso.of_components (λ Y, iso.refl _) (λ Y Z f, by simp)
end
variables {A : Type u₁} [category.{v₁} A]
{B : Type u₂} [category.{v₂} B]
{C : Type u₃} [category.{v₃} C]
{D : Type u₄} [category.{v₄} D]
namespace functor
/-- The cartesian product of two functors. -/
@[simps] def prod (F : A ⥤ B) (G : C ⥤ D) : A × C ⥤ B × D :=
{ obj := λ X, (F.obj X.1, G.obj X.2),
map := λ _ _ f, (F.map f.1, G.map f.2) }
/- Because of limitations in Lean 3's handling of notations, we do not setup a notation `F × G`.
You can use `F.prod G` as a "poor man's infix", or just write `functor.prod F G`. -/
/-- Similar to `prod`, but both functors start from the same category `A` -/
@[simps] def prod' (F : A ⥤ B) (G : A ⥤ C) : A ⥤ (B × C) :=
{ obj := λ a, (F.obj a, G.obj a),
map := λ x y f, (F.map f, G.map f), }
/-- The product `F.prod' G` followed by projection on the first component is isomorphic to `F` -/
@[simps]
def prod'_comp_fst (F : A ⥤ B) (G : A ⥤ C) : (F.prod' G) ⋙ (category_theory.prod.fst B C) ≅ F :=
nat_iso.of_components (λ X, iso.refl _) (λ X Y f, by simp)
/-- The product `F.prod' G` followed by projection on the second component is isomorphic to `G` -/
@[simps]
def prod'_comp_snd (F : A ⥤ B) (G : A ⥤ C) : (F.prod' G) ⋙ (category_theory.prod.snd B C) ≅ G :=
nat_iso.of_components (λ X, iso.refl _) (λ X Y f, by simp)
section
variable (C)
/-- The diagonal functor. -/
def diag : C ⥤ C × C := (𝟭 C).prod' (𝟭 C)
@[simp] lemma diag_obj (X : C) : (diag C).obj X = (X, X) := rfl
@[simp] lemma diag_map {X Y : C} (f : X ⟶ Y) : (diag C).map f = (f, f) := rfl
end
end functor
namespace nat_trans
/-- The cartesian product of two natural transformations. -/
@[simps] def prod {F G : A ⥤ B} {H I : C ⥤ D} (α : F ⟶ G) (β : H ⟶ I) :
F.prod H ⟶ G.prod I :=
{ app := λ X, (α.app X.1, β.app X.2),
naturality' := λ X Y f,
begin
cases X, cases Y,
simp only [functor.prod_map, prod.mk.inj_iff, prod_comp],
split; rw naturality
end }
/- Again, it is inadvisable in Lean 3 to setup a notation `α × β`;
use instead `α.prod β` or `nat_trans.prod α β`. -/
end nat_trans
/-- `F.flip` composed with evaluation is the same as evaluating `F`. -/
@[simps]
def flip_comp_evaluation (F : A ⥤ B ⥤ C) (a) :
F.flip ⋙ (evaluation _ _).obj a ≅ F.obj a :=
nat_iso.of_components (λ b, eq_to_iso rfl) $ by tidy
variables (A B C)
/-- The forward direction for `functor_prod_functor_equiv` -/
@[simps] def prod_functor_to_functor_prod : (A ⥤ B) × (A ⥤ C) ⥤ A ⥤ B × C :=
{ obj := λ F, F.1.prod' F.2,
map := λ F G f, { app := λ X, (f.1.app X, f.2.app X) } }
/-- The backward direction for `functor_prod_functor_equiv` -/
@[simps] def functor_prod_to_prod_functor : (A ⥤ B × C) ⥤ (A ⥤ B) × (A ⥤ C) :=
{ obj := λ F, ⟨F ⋙ (category_theory.prod.fst B C), F ⋙ (category_theory.prod.snd B C)⟩,
map := λ F G α,
⟨{ app := λ X, (α.app X).1,
naturality' := λ X Y f,
by simp only [functor.comp_map, prod.fst_map, ←prod_comp_fst, α.naturality] },
{ app := λ X, (α.app X).2,
naturality' := λ X Y f,
by simp only [functor.comp_map, prod.snd_map, ←prod_comp_snd, α.naturality] }⟩ }
/-- The unit isomorphism for `functor_prod_functor_equiv` -/
@[simps] def functor_prod_functor_equiv_unit_iso :
𝟭 _ ≅ prod_functor_to_functor_prod A B C ⋙ functor_prod_to_prod_functor A B C :=
nat_iso.of_components
(λ F, (((functor.prod'_comp_fst _ _).prod (functor.prod'_comp_snd _ _)).trans
(prod.eta_iso F)).symm) (λ F G α, by {tidy})
/-- The counit isomorphism for `functor_prod_functor_equiv` -/
@[simps] def functor_prod_functor_equiv_counit_iso :
functor_prod_to_prod_functor A B C ⋙ prod_functor_to_functor_prod A B C ≅ 𝟭 _ :=
nat_iso.of_components
(λ F, nat_iso.of_components (λ X, prod.eta_iso (F.obj X)) (by tidy)) (by tidy)
/-- The equivalence of categories between `(A ⥤ B) × (A ⥤ C)` and `A ⥤ (B × C)` -/
@[simps] def functor_prod_functor_equiv : ((A ⥤ B) × (A ⥤ C)) ≌ (A ⥤ (B × C)) :=
{ functor := prod_functor_to_functor_prod A B C,
inverse := functor_prod_to_prod_functor A B C,
unit_iso := functor_prod_functor_equiv_unit_iso A B C,
counit_iso := functor_prod_functor_equiv_counit_iso A B C }
end category_theory
|
e370bffed98cd038d0b162e974f7c7a887f81f9d | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /stage0/src/Init/Data/Nat.lean | 7afb1ce9e573267e281de32fdeeda93c179ab257 | [
"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 | 307 | 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.Data.Nat.Basic
import Init.Data.Nat.Div
import Init.Data.Nat.Gcd
import Init.Data.Nat.Bitwise
import Init.Data.Nat.Control
|
0dc5a62b58017c41df258edeecc21daa17a0f667 | 02005f45e00c7ecf2c8ca5db60251bd1e9c860b5 | /src/analysis/calculus/deriv.lean | b0de23d04659d514ff284373289b20734d7c1c92 | [
"Apache-2.0"
] | permissive | anthony2698/mathlib | 03cd69fe5c280b0916f6df2d07c614c8e1efe890 | 407615e05814e98b24b2ff322b14e8e3eb5e5d67 | refs/heads/master | 1,678,792,774,873 | 1,614,371,563,000 | 1,614,371,563,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 78,060 | lean | /-
Copyright (c) 2019 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner, Sébastien Gouëzel
-/
import analysis.calculus.fderiv
import data.polynomial.derivative
/-!
# One-dimensional derivatives
This file defines the derivative of a function `f : 𝕜 → F` where `𝕜` is a
normed field and `F` is a normed space over this field. The derivative of
such a function `f` at a point `x` is given by an element `f' : F`.
The theory is developed analogously to the [Fréchet
derivatives](./fderiv.lean). We first introduce predicates defined in terms
of the corresponding predicates for Fréchet derivatives:
- `has_deriv_at_filter f f' x L` states that the function `f` has the
derivative `f'` at the point `x` as `x` goes along the filter `L`.
- `has_deriv_within_at f f' s x` states that the function `f` has the
derivative `f'` at the point `x` within the subset `s`.
- `has_deriv_at f f' x` states that the function `f` has the derivative `f'`
at the point `x`.
- `has_strict_deriv_at f f' x` states that the function `f` has the derivative `f'`
at the point `x` in the sense of strict differentiability, i.e.,
`f y - f z = (y - z) • f' + o (y - z)` as `y, z → x`.
For the last two notions we also define a functional version:
- `deriv_within f s x` is a derivative of `f` at `x` within `s`. If the
derivative does not exist, then `deriv_within f s x` equals zero.
- `deriv f x` is a derivative of `f` at `x`. If the derivative does not
exist, then `deriv f x` equals zero.
The theorems `fderiv_within_deriv_within` and `fderiv_deriv` show that the
one-dimensional derivatives coincide with the general Fréchet derivatives.
We also show the existence and compute the derivatives of:
- constants
- the identity function
- linear maps
- addition
- sum of finitely many functions
- negation
- subtraction
- multiplication
- inverse `x → x⁻¹`
- multiplication of two functions in `𝕜 → 𝕜`
- multiplication of a function in `𝕜 → 𝕜` and of a function in `𝕜 → E`
- composition of a function in `𝕜 → F` with a function in `𝕜 → 𝕜`
- composition of a function in `F → E` with a function in `𝕜 → F`
- inverse function (assuming that it exists; the inverse function theorem is in `inverse.lean`)
- division
- polynomials
For most binary operations we also define `const_op` and `op_const` theorems for the cases when
the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier,
and they more frequently lead to the desired result.
We set up the simplifier so that it can compute the derivative of simple functions. For instance,
```lean
example (x : ℝ) : deriv (λ x, cos (sin x) * exp x) x = (cos(sin(x))-sin(sin(x))*cos(x))*exp(x) :=
by { simp, ring }
```
## Implementation notes
Most of the theorems are direct restatements of the corresponding theorems
for Fréchet derivatives.
The strategy to construct simp lemmas that give the simplifier the possibility to compute
derivatives is the same as the one for differentiability statements, as explained in `fderiv.lean`.
See the explanations there.
-/
universes u v w
noncomputable theory
open_locale classical topological_space big_operators filter ennreal
open filter asymptotics set
open continuous_linear_map (smul_right smul_right_one_eq_iff)
variables {𝕜 : Type u} [nondiscrete_normed_field 𝕜]
section
variables {F : Type v} [normed_group F] [normed_space 𝕜 F]
variables {E : Type w} [normed_group E] [normed_space 𝕜 E]
/--
`f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`.
That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges along the filter `L`.
-/
def has_deriv_at_filter (f : 𝕜 → F) (f' : F) (x : 𝕜) (L : filter 𝕜) :=
has_fderiv_at_filter f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x L
/--
`f` has the derivative `f'` at the point `x` within the subset `s`.
That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x` inside `s`.
-/
def has_deriv_within_at (f : 𝕜 → F) (f' : F) (s : set 𝕜) (x : 𝕜) :=
has_deriv_at_filter f f' x (𝓝[s] x)
/--
`f` has the derivative `f'` at the point `x`.
That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x`.
-/
def has_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) :=
has_deriv_at_filter f f' x (𝓝 x)
/-- `f` has the derivative `f'` at the point `x` in the sense of strict differentiability.
That is, `f y - f z = (y - z) • f' + o(y - z)` as `y, z → x`. -/
def has_strict_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) :=
has_strict_fderiv_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x
/--
Derivative of `f` at the point `x` within the set `s`, if it exists. Zero otherwise.
If the derivative exists (i.e., `∃ f', has_deriv_within_at f f' s x`), then
`f x' = f x + (x' - x) • deriv_within f s x + o(x' - x)` where `x'` converges to `x` inside `s`.
-/
def deriv_within (f : 𝕜 → F) (s : set 𝕜) (x : 𝕜) :=
fderiv_within 𝕜 f s x 1
/--
Derivative of `f` at the point `x`, if it exists. Zero otherwise.
If the derivative exists (i.e., `∃ f', has_deriv_at f f' x`), then
`f x' = f x + (x' - x) • deriv f x + o(x' - x)` where `x'` converges to `x`.
-/
def deriv (f : 𝕜 → F) (x : 𝕜) :=
fderiv 𝕜 f x 1
variables {f f₀ f₁ g : 𝕜 → F}
variables {f' f₀' f₁' g' : F}
variables {x : 𝕜}
variables {s t : set 𝕜}
variables {L L₁ L₂ : filter 𝕜}
/-- Expressing `has_fderiv_at_filter f f' x L` in terms of `has_deriv_at_filter` -/
lemma has_fderiv_at_filter_iff_has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} :
has_fderiv_at_filter f f' x L ↔ has_deriv_at_filter f (f' 1) x L :=
by simp [has_deriv_at_filter]
lemma has_fderiv_at_filter.has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} :
has_fderiv_at_filter f f' x L → has_deriv_at_filter f (f' 1) x L :=
has_fderiv_at_filter_iff_has_deriv_at_filter.mp
/-- Expressing `has_fderiv_within_at f f' s x` in terms of `has_deriv_within_at` -/
lemma has_fderiv_within_at_iff_has_deriv_within_at {f' : 𝕜 →L[𝕜] F} :
has_fderiv_within_at f f' s x ↔ has_deriv_within_at f (f' 1) s x :=
has_fderiv_at_filter_iff_has_deriv_at_filter
/-- Expressing `has_deriv_within_at f f' s x` in terms of `has_fderiv_within_at` -/
lemma has_deriv_within_at_iff_has_fderiv_within_at {f' : F} :
has_deriv_within_at f f' s x ↔
has_fderiv_within_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') s x :=
iff.rfl
lemma has_fderiv_within_at.has_deriv_within_at {f' : 𝕜 →L[𝕜] F} :
has_fderiv_within_at f f' s x → has_deriv_within_at f (f' 1) s x :=
has_fderiv_within_at_iff_has_deriv_within_at.mp
lemma has_deriv_within_at.has_fderiv_within_at {f' : F} :
has_deriv_within_at f f' s x → has_fderiv_within_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') s x :=
has_deriv_within_at_iff_has_fderiv_within_at.mp
/-- Expressing `has_fderiv_at f f' x` in terms of `has_deriv_at` -/
lemma has_fderiv_at_iff_has_deriv_at {f' : 𝕜 →L[𝕜] F} :
has_fderiv_at f f' x ↔ has_deriv_at f (f' 1) x :=
has_fderiv_at_filter_iff_has_deriv_at_filter
lemma has_fderiv_at.has_deriv_at {f' : 𝕜 →L[𝕜] F} :
has_fderiv_at f f' x → has_deriv_at f (f' 1) x :=
has_fderiv_at_iff_has_deriv_at.mp
lemma has_strict_fderiv_at_iff_has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} :
has_strict_fderiv_at f f' x ↔ has_strict_deriv_at f (f' 1) x :=
by simp [has_strict_deriv_at, has_strict_fderiv_at]
protected lemma has_strict_fderiv_at.has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} :
has_strict_fderiv_at f f' x → has_strict_deriv_at f (f' 1) x :=
has_strict_fderiv_at_iff_has_strict_deriv_at.mp
lemma has_strict_deriv_at_iff_has_strict_fderiv_at :
has_strict_deriv_at f f' x ↔ has_strict_fderiv_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x :=
iff.rfl
alias has_strict_deriv_at_iff_has_strict_fderiv_at ↔ has_strict_deriv_at.has_strict_fderiv_at _
/-- Expressing `has_deriv_at f f' x` in terms of `has_fderiv_at` -/
lemma has_deriv_at_iff_has_fderiv_at {f' : F} :
has_deriv_at f f' x ↔
has_fderiv_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x :=
iff.rfl
alias has_deriv_at_iff_has_fderiv_at ↔ has_deriv_at.has_fderiv_at _
lemma deriv_within_zero_of_not_differentiable_within_at
(h : ¬ differentiable_within_at 𝕜 f s x) : deriv_within f s x = 0 :=
by { unfold deriv_within, rw fderiv_within_zero_of_not_differentiable_within_at, simp, assumption }
lemma deriv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : deriv f x = 0 :=
by { unfold deriv, rw fderiv_zero_of_not_differentiable_at, simp, assumption }
theorem unique_diff_within_at.eq_deriv (s : set 𝕜) (H : unique_diff_within_at 𝕜 s x)
(h : has_deriv_within_at f f' s x) (h₁ : has_deriv_within_at f f₁' s x) : f' = f₁' :=
smul_right_one_eq_iff.mp $ unique_diff_within_at.eq H h h₁
theorem has_deriv_at_filter_iff_tendsto :
has_deriv_at_filter f f' x L ↔
tendsto (λ x' : 𝕜, ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) L (𝓝 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_deriv_within_at_iff_tendsto : has_deriv_within_at f f' s x ↔
tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (𝓝[s] x) (𝓝 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_deriv_at_iff_tendsto : has_deriv_at f f' x ↔
tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (𝓝 x) (𝓝 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_strict_deriv_at.has_deriv_at (h : has_strict_deriv_at f f' x) :
has_deriv_at f f' x :=
h.has_fderiv_at
/-- If the domain has dimension one, then Fréchet derivative is equivalent to the classical
definition with a limit. In this version we have to take the limit along the subset `-{x}`,
because for `y=x` the slope equals zero due to the convention `0⁻¹=0`. -/
lemma has_deriv_at_filter_iff_tendsto_slope {x : 𝕜} {L : filter 𝕜} :
has_deriv_at_filter f f' x L ↔
tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (L ⊓ 𝓟 {x}ᶜ) (𝓝 f') :=
begin
conv_lhs { simp only [has_deriv_at_filter_iff_tendsto, (normed_field.norm_inv _).symm,
(norm_smul _ _).symm, tendsto_zero_iff_norm_tendsto_zero.symm] },
conv_rhs { rw [← nhds_translation f', tendsto_comap_iff] },
refine (tendsto_inf_principal_nhds_iff_of_forall_eq $ by simp).symm.trans (tendsto_congr' _),
refine (eventually_principal.2 $ λ z hz, _).filter_mono inf_le_right,
simp only [(∘)],
rw [smul_sub, ← mul_smul, inv_mul_cancel (sub_ne_zero.2 hz), one_smul]
end
lemma has_deriv_within_at_iff_tendsto_slope :
has_deriv_within_at f f' s x ↔
tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (𝓝[s \ {x}] x) (𝓝 f') :=
begin
simp only [has_deriv_within_at, nhds_within, diff_eq, inf_assoc.symm, inf_principal.symm],
exact has_deriv_at_filter_iff_tendsto_slope
end
lemma has_deriv_within_at_iff_tendsto_slope' (hs : x ∉ s) :
has_deriv_within_at f f' s x ↔
tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (𝓝[s] x) (𝓝 f') :=
begin
convert ← has_deriv_within_at_iff_tendsto_slope,
exact diff_singleton_eq_self hs
end
lemma has_deriv_at_iff_tendsto_slope :
has_deriv_at f f' x ↔
tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (𝓝[{x}ᶜ] x) (𝓝 f') :=
has_deriv_at_filter_iff_tendsto_slope
@[simp] lemma has_deriv_within_at_diff_singleton :
has_deriv_within_at f f' (s \ {x}) x ↔ has_deriv_within_at f f' s x :=
by simp only [has_deriv_within_at_iff_tendsto_slope, sdiff_idem_right]
@[simp] lemma has_deriv_within_at_Ioi_iff_Ici [partial_order 𝕜] :
has_deriv_within_at f f' (Ioi x) x ↔ has_deriv_within_at f f' (Ici x) x :=
by rw [← Ici_diff_left, has_deriv_within_at_diff_singleton]
alias has_deriv_within_at_Ioi_iff_Ici ↔
has_deriv_within_at.Ici_of_Ioi has_deriv_within_at.Ioi_of_Ici
@[simp] lemma has_deriv_within_at_Iio_iff_Iic [partial_order 𝕜] :
has_deriv_within_at f f' (Iio x) x ↔ has_deriv_within_at f f' (Iic x) x :=
by rw [← Iic_diff_right, has_deriv_within_at_diff_singleton]
alias has_deriv_within_at_Iio_iff_Iic ↔
has_deriv_within_at.Iic_of_Iio has_deriv_within_at.Iio_of_Iic
theorem has_deriv_at_iff_is_o_nhds_zero : has_deriv_at f f' x ↔
is_o (λh, f (x + h) - f x - h • f') (λh, h) (𝓝 0) :=
has_fderiv_at_iff_is_o_nhds_zero
theorem has_deriv_at_filter.mono (h : has_deriv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) :
has_deriv_at_filter f f' x L₁ :=
has_fderiv_at_filter.mono h hst
theorem has_deriv_within_at.mono (h : has_deriv_within_at f f' t x) (hst : s ⊆ t) :
has_deriv_within_at f f' s x :=
has_fderiv_within_at.mono h hst
theorem has_deriv_at.has_deriv_at_filter (h : has_deriv_at f f' x) (hL : L ≤ 𝓝 x) :
has_deriv_at_filter f f' x L :=
has_fderiv_at.has_fderiv_at_filter h hL
theorem has_deriv_at.has_deriv_within_at
(h : has_deriv_at f f' x) : has_deriv_within_at f f' s x :=
has_fderiv_at.has_fderiv_within_at h
lemma has_deriv_within_at.differentiable_within_at (h : has_deriv_within_at f f' s x) :
differentiable_within_at 𝕜 f s x :=
has_fderiv_within_at.differentiable_within_at h
lemma has_deriv_at.differentiable_at (h : has_deriv_at f f' x) : differentiable_at 𝕜 f x :=
has_fderiv_at.differentiable_at h
@[simp] lemma has_deriv_within_at_univ : has_deriv_within_at f f' univ x ↔ has_deriv_at f f' x :=
has_fderiv_within_at_univ
theorem has_deriv_at.unique
(h₀ : has_deriv_at f f₀' x) (h₁ : has_deriv_at f f₁' x) : f₀' = f₁' :=
smul_right_one_eq_iff.mp $ h₀.has_fderiv_at.unique h₁
lemma has_deriv_within_at_inter' (h : t ∈ 𝓝[s] x) :
has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x :=
has_fderiv_within_at_inter' h
lemma has_deriv_within_at_inter (h : t ∈ 𝓝 x) :
has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x :=
has_fderiv_within_at_inter h
lemma has_deriv_within_at.union (hs : has_deriv_within_at f f' s x)
(ht : has_deriv_within_at f f' t x) :
has_deriv_within_at f f' (s ∪ t) x :=
begin
simp only [has_deriv_within_at, nhds_within_union],
exact hs.join ht,
end
lemma has_deriv_within_at.nhds_within (h : has_deriv_within_at f f' s x)
(ht : s ∈ 𝓝[t] x) : has_deriv_within_at f f' t x :=
(has_deriv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _))
lemma has_deriv_within_at.has_deriv_at (h : has_deriv_within_at f f' s x) (hs : s ∈ 𝓝 x) :
has_deriv_at f f' x :=
has_fderiv_within_at.has_fderiv_at h hs
lemma differentiable_within_at.has_deriv_within_at (h : differentiable_within_at 𝕜 f s x) :
has_deriv_within_at f (deriv_within f s x) s x :=
show has_fderiv_within_at _ _ _ _, by { convert h.has_fderiv_within_at, simp [deriv_within] }
lemma differentiable_at.has_deriv_at (h : differentiable_at 𝕜 f x) : has_deriv_at f (deriv f x) x :=
show has_fderiv_at _ _ _, by { convert h.has_fderiv_at, simp [deriv] }
lemma has_deriv_at.deriv (h : has_deriv_at f f' x) : deriv f x = f' :=
h.differentiable_at.has_deriv_at.unique h
lemma has_deriv_within_at.deriv_within
(h : has_deriv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within f s x = f' :=
hxs.eq_deriv _ h.differentiable_within_at.has_deriv_within_at h
lemma fderiv_within_deriv_within : (fderiv_within 𝕜 f s x : 𝕜 → F) 1 = deriv_within f s x :=
rfl
lemma deriv_within_fderiv_within :
smul_right (1 : 𝕜 →L[𝕜] 𝕜) (deriv_within f s x) = fderiv_within 𝕜 f s x :=
by simp [deriv_within]
lemma fderiv_deriv : (fderiv 𝕜 f x : 𝕜 → F) 1 = deriv f x :=
rfl
lemma deriv_fderiv :
smul_right (1 : 𝕜 →L[𝕜] 𝕜) (deriv f x) = fderiv 𝕜 f x :=
by simp [deriv]
lemma differentiable_at.deriv_within (h : differentiable_at 𝕜 f x)
(hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = deriv f x :=
by { unfold deriv_within deriv, rw h.fderiv_within hxs }
lemma deriv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x)
(h : differentiable_within_at 𝕜 f t x) :
deriv_within f s x = deriv_within f t x :=
((differentiable_within_at.has_deriv_within_at h).mono st).deriv_within ht
@[simp] lemma deriv_within_univ : deriv_within f univ = deriv f :=
by { ext, unfold deriv_within deriv, rw fderiv_within_univ }
lemma deriv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) :
deriv_within f (s ∩ t) x = deriv_within f s x :=
by { unfold deriv_within, rw fderiv_within_inter ht hs }
lemma deriv_within_of_open (hs : is_open s) (hx : x ∈ s) :
deriv_within f s x = deriv f x :=
by { unfold deriv_within, rw fderiv_within_of_open hs hx, refl }
section congr
/-! ### Congruence properties of derivatives -/
theorem filter.eventually_eq.has_deriv_at_filter_iff
(h₀ : f₀ =ᶠ[L] f₁) (hx : f₀ x = f₁ x) (h₁ : f₀' = f₁') :
has_deriv_at_filter f₀ f₀' x L ↔ has_deriv_at_filter f₁ f₁' x L :=
h₀.has_fderiv_at_filter_iff hx (by simp [h₁])
lemma has_deriv_at_filter.congr_of_eventually_eq (h : has_deriv_at_filter f f' x L)
(hL : f₁ =ᶠ[L] f) (hx : f₁ x = f x) : has_deriv_at_filter f₁ f' x L :=
by rwa hL.has_deriv_at_filter_iff hx rfl
lemma has_deriv_within_at.congr_mono (h : has_deriv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x)
(hx : f₁ x = f x) (h₁ : t ⊆ s) : has_deriv_within_at f₁ f' t x :=
has_fderiv_within_at.congr_mono h ht hx h₁
lemma has_deriv_within_at.congr (h : has_deriv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x)
(hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x :=
h.congr_mono hs hx (subset.refl _)
lemma has_deriv_within_at.congr_of_eventually_eq (h : has_deriv_within_at f f' s x)
(h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x :=
has_deriv_at_filter.congr_of_eventually_eq h h₁ hx
lemma has_deriv_within_at.congr_of_eventually_eq_of_mem (h : has_deriv_within_at f f' s x)
(h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : x ∈ s) : has_deriv_within_at f₁ f' s x :=
h.congr_of_eventually_eq h₁ (h₁.eq_of_nhds_within hx)
lemma has_deriv_at.congr_of_eventually_eq (h : has_deriv_at f f' x)
(h₁ : f₁ =ᶠ[𝓝 x] f) : has_deriv_at f₁ f' x :=
has_deriv_at_filter.congr_of_eventually_eq h h₁ (mem_of_nhds h₁ : _)
lemma filter.eventually_eq.deriv_within_eq (hs : unique_diff_within_at 𝕜 s x)
(hL : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) :
deriv_within f₁ s x = deriv_within f s x :=
by { unfold deriv_within, rw hL.fderiv_within_eq hs hx }
lemma deriv_within_congr (hs : unique_diff_within_at 𝕜 s x)
(hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) :
deriv_within f₁ s x = deriv_within f s x :=
by { unfold deriv_within, rw fderiv_within_congr hs hL hx }
lemma filter.eventually_eq.deriv_eq (hL : f₁ =ᶠ[𝓝 x] f) : deriv f₁ x = deriv f x :=
by { unfold deriv, rwa filter.eventually_eq.fderiv_eq }
end congr
section id
/-! ### Derivative of the identity -/
variables (s x L)
theorem has_deriv_at_filter_id : has_deriv_at_filter id 1 x L :=
(has_fderiv_at_filter_id x L).has_deriv_at_filter
theorem has_deriv_within_at_id : has_deriv_within_at id 1 s x :=
has_deriv_at_filter_id _ _
theorem has_deriv_at_id : has_deriv_at id 1 x :=
has_deriv_at_filter_id _ _
theorem has_deriv_at_id' : has_deriv_at (λ (x : 𝕜), x) 1 x :=
has_deriv_at_filter_id _ _
theorem has_strict_deriv_at_id : has_strict_deriv_at id 1 x :=
(has_strict_fderiv_at_id x).has_strict_deriv_at
lemma deriv_id : deriv id x = 1 :=
has_deriv_at.deriv (has_deriv_at_id x)
@[simp] lemma deriv_id' : deriv (@id 𝕜) = λ _, 1 :=
funext deriv_id
@[simp] lemma deriv_id'' : deriv (λ x : 𝕜, x) x = 1 :=
deriv_id x
lemma deriv_within_id (hxs : unique_diff_within_at 𝕜 s x) : deriv_within id s x = 1 :=
(has_deriv_within_at_id x s).deriv_within hxs
end id
section const
/-! ### Derivative of constant functions -/
variables (c : F) (s x L)
theorem has_deriv_at_filter_const : has_deriv_at_filter (λ x, c) 0 x L :=
(has_fderiv_at_filter_const c x L).has_deriv_at_filter
theorem has_strict_deriv_at_const : has_strict_deriv_at (λ x, c) 0 x :=
(has_strict_fderiv_at_const c x).has_strict_deriv_at
theorem has_deriv_within_at_const : has_deriv_within_at (λ x, c) 0 s x :=
has_deriv_at_filter_const _ _ _
theorem has_deriv_at_const : has_deriv_at (λ x, c) 0 x :=
has_deriv_at_filter_const _ _ _
lemma deriv_const : deriv (λ x, c) x = 0 :=
has_deriv_at.deriv (has_deriv_at_const x c)
@[simp] lemma deriv_const' : deriv (λ x:𝕜, c) = λ x, 0 :=
funext (λ x, deriv_const x c)
lemma deriv_within_const (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λ x, c) s x = 0 :=
(has_deriv_within_at_const _ _ _).deriv_within hxs
end const
section continuous_linear_map
/-! ### Derivative of continuous linear maps -/
variables (e : 𝕜 →L[𝕜] F)
protected lemma continuous_linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L :=
e.has_fderiv_at_filter.has_deriv_at_filter
protected lemma continuous_linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x :=
e.has_strict_fderiv_at.has_strict_deriv_at
protected lemma continuous_linear_map.has_deriv_at : has_deriv_at e (e 1) x :=
e.has_deriv_at_filter
protected lemma continuous_linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x :=
e.has_deriv_at_filter
@[simp] protected lemma continuous_linear_map.deriv : deriv e x = e 1 :=
e.has_deriv_at.deriv
protected lemma continuous_linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within e s x = e 1 :=
e.has_deriv_within_at.deriv_within hxs
end continuous_linear_map
section linear_map
/-! ### Derivative of bundled linear maps -/
variables (e : 𝕜 →ₗ[𝕜] F)
protected lemma linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L :=
e.to_continuous_linear_map₁.has_deriv_at_filter
protected lemma linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x :=
e.to_continuous_linear_map₁.has_strict_deriv_at
protected lemma linear_map.has_deriv_at : has_deriv_at e (e 1) x :=
e.has_deriv_at_filter
protected lemma linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x :=
e.has_deriv_at_filter
@[simp] protected lemma linear_map.deriv : deriv e x = e 1 :=
e.has_deriv_at.deriv
protected lemma linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within e s x = e 1 :=
e.has_deriv_within_at.deriv_within hxs
end linear_map
section analytic
variables {p : formal_multilinear_series 𝕜 𝕜 F} {r : ℝ≥0∞}
protected lemma has_fpower_series_at.has_strict_deriv_at (h : has_fpower_series_at f p x) :
has_strict_deriv_at f (p 1 (λ _, 1)) x :=
h.has_strict_fderiv_at.has_strict_deriv_at
protected lemma has_fpower_series_at.has_deriv_at (h : has_fpower_series_at f p x) :
has_deriv_at f (p 1 (λ _, 1)) x :=
h.has_strict_deriv_at.has_deriv_at
protected lemma has_fpower_series_at.deriv (h : has_fpower_series_at f p x) :
deriv f x = p 1 (λ _, 1) :=
h.has_deriv_at.deriv
end analytic
section add
/-! ### Derivative of the sum of two functions -/
theorem has_deriv_at_filter.add
(hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) :
has_deriv_at_filter (λ y, f y + g y) (f' + g') x L :=
by simpa using (hf.add hg).has_deriv_at_filter
theorem has_strict_deriv_at.add
(hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) :
has_strict_deriv_at (λ y, f y + g y) (f' + g') x :=
by simpa using (hf.add hg).has_strict_deriv_at
theorem has_deriv_within_at.add
(hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) :
has_deriv_within_at (λ y, f y + g y) (f' + g') s x :=
hf.add hg
theorem has_deriv_at.add
(hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) :
has_deriv_at (λ x, f x + g x) (f' + g') x :=
hf.add hg
lemma deriv_within_add (hxs : unique_diff_within_at 𝕜 s x)
(hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) :
deriv_within (λy, f y + g y) s x = deriv_within f s x + deriv_within g s x :=
(hf.has_deriv_within_at.add hg.has_deriv_within_at).deriv_within hxs
@[simp] lemma deriv_add
(hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) :
deriv (λy, f y + g y) x = deriv f x + deriv g x :=
(hf.has_deriv_at.add hg.has_deriv_at).deriv
theorem has_deriv_at_filter.add_const
(hf : has_deriv_at_filter f f' x L) (c : F) :
has_deriv_at_filter (λ y, f y + c) f' x L :=
add_zero f' ▸ hf.add (has_deriv_at_filter_const x L c)
theorem has_deriv_within_at.add_const
(hf : has_deriv_within_at f f' s x) (c : F) :
has_deriv_within_at (λ y, f y + c) f' s x :=
hf.add_const c
theorem has_deriv_at.add_const
(hf : has_deriv_at f f' x) (c : F) :
has_deriv_at (λ x, f x + c) f' x :=
hf.add_const c
lemma deriv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) :
deriv_within (λy, f y + c) s x = deriv_within f s x :=
by simp only [deriv_within, fderiv_within_add_const hxs]
lemma deriv_add_const (c : F) : deriv (λy, f y + c) x = deriv f x :=
by simp only [deriv, fderiv_add_const]
theorem has_deriv_at_filter.const_add (c : F) (hf : has_deriv_at_filter f f' x L) :
has_deriv_at_filter (λ y, c + f y) f' x L :=
zero_add f' ▸ (has_deriv_at_filter_const x L c).add hf
theorem has_deriv_within_at.const_add (c : F) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ y, c + f y) f' s x :=
hf.const_add c
theorem has_deriv_at.const_add (c : F) (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, c + f x) f' x :=
hf.const_add c
lemma deriv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) :
deriv_within (λy, c + f y) s x = deriv_within f s x :=
by simp only [deriv_within, fderiv_within_const_add hxs]
lemma deriv_const_add (c : F) : deriv (λy, c + f y) x = deriv f x :=
by simp only [deriv, fderiv_const_add]
end add
section sum
/-! ### Derivative of a finite sum of functions -/
open_locale big_operators
variables {ι : Type*} {u : finset ι} {A : ι → (𝕜 → F)} {A' : ι → F}
theorem has_deriv_at_filter.sum (h : ∀ i ∈ u, has_deriv_at_filter (A i) (A' i) x L) :
has_deriv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L :=
by simpa [continuous_linear_map.sum_apply] using (has_fderiv_at_filter.sum h).has_deriv_at_filter
theorem has_strict_deriv_at.sum (h : ∀ i ∈ u, has_strict_deriv_at (A i) (A' i) x) :
has_strict_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x :=
by simpa [continuous_linear_map.sum_apply] using (has_strict_fderiv_at.sum h).has_strict_deriv_at
theorem has_deriv_within_at.sum (h : ∀ i ∈ u, has_deriv_within_at (A i) (A' i) s x) :
has_deriv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x :=
has_deriv_at_filter.sum h
theorem has_deriv_at.sum (h : ∀ i ∈ u, has_deriv_at (A i) (A' i) x) :
has_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x :=
has_deriv_at_filter.sum h
lemma deriv_within_sum (hxs : unique_diff_within_at 𝕜 s x)
(h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) :
deriv_within (λ y, ∑ i in u, A i y) s x = ∑ i in u, deriv_within (A i) s x :=
(has_deriv_within_at.sum (λ i hi, (h i hi).has_deriv_within_at)).deriv_within hxs
@[simp] lemma deriv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) :
deriv (λ y, ∑ i in u, A i y) x = ∑ i in u, deriv (A i) x :=
(has_deriv_at.sum (λ i hi, (h i hi).has_deriv_at)).deriv
end sum
section pi
/-! ### Derivatives of functions `f : 𝕜 → Π i, E i` -/
variables {ι : Type*} [fintype ι] {E' : ι → Type*} [Π i, normed_group (E' i)]
[Π i, normed_space 𝕜 (E' i)] {φ : 𝕜 → Π i, E' i} {φ' : Π i, E' i}
@[simp] lemma has_strict_deriv_at_pi :
has_strict_deriv_at φ φ' x ↔ ∀ i, has_strict_deriv_at (λ x, φ x i) (φ' i) x :=
has_strict_fderiv_at_pi'
@[simp] lemma has_deriv_at_filter_pi :
has_deriv_at_filter φ φ' x L ↔
∀ i, has_deriv_at_filter (λ x, φ x i) (φ' i) x L :=
has_fderiv_at_filter_pi'
lemma has_deriv_at_pi :
has_deriv_at φ φ' x ↔ ∀ i, has_deriv_at (λ x, φ x i) (φ' i) x:=
has_deriv_at_filter_pi
lemma has_deriv_within_at_pi :
has_deriv_within_at φ φ' s x ↔ ∀ i, has_deriv_within_at (λ x, φ x i) (φ' i) s x:=
has_deriv_at_filter_pi
lemma deriv_within_pi (h : ∀ i, differentiable_within_at 𝕜 (λ x, φ x i) s x)
(hs : unique_diff_within_at 𝕜 s x) :
deriv_within φ s x = λ i, deriv_within (λ x, φ x i) s x :=
(has_deriv_within_at_pi.2 (λ i, (h i).has_deriv_within_at)).deriv_within hs
lemma deriv_pi (h : ∀ i, differentiable_at 𝕜 (λ x, φ x i) x) :
deriv φ x = λ i, deriv (λ x, φ x i) x :=
(has_deriv_at_pi.2 (λ i, (h i).has_deriv_at)).deriv
end pi
section mul_vector
/-! ### Derivative of the multiplication of a scalar function and a vector function -/
variables {c : 𝕜 → 𝕜} {c' : 𝕜}
theorem has_deriv_within_at.smul
(hc : has_deriv_within_at c c' s x) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ y, c y • f y) (c x • f' + c' • f x) s x :=
by simpa using (has_fderiv_within_at.smul hc hf).has_deriv_within_at
theorem has_deriv_at.smul
(hc : has_deriv_at c c' x) (hf : has_deriv_at f f' x) :
has_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hc.smul hf
end
theorem has_strict_deriv_at.smul
(hc : has_strict_deriv_at c c' x) (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x :=
by simpa using (hc.smul hf).has_strict_deriv_at
lemma deriv_within_smul (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) :
deriv_within (λ y, c y • f y) s x = c x • deriv_within f s x + (deriv_within c s x) • f x :=
(hc.has_deriv_within_at.smul hf.has_deriv_within_at).deriv_within hxs
lemma deriv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) :
deriv (λ y, c y • f y) x = c x • deriv f x + (deriv c x) • f x :=
(hc.has_deriv_at.smul hf.has_deriv_at).deriv
theorem has_deriv_within_at.smul_const
(hc : has_deriv_within_at c c' s x) (f : F) :
has_deriv_within_at (λ y, c y • f) (c' • f) s x :=
begin
have := hc.smul (has_deriv_within_at_const x s f),
rwa [smul_zero, zero_add] at this
end
theorem has_deriv_at.smul_const
(hc : has_deriv_at c c' x) (f : F) :
has_deriv_at (λ y, c y • f) (c' • f) x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hc.smul_const f
end
lemma deriv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (f : F) :
deriv_within (λ y, c y • f) s x = (deriv_within c s x) • f :=
(hc.has_deriv_within_at.smul_const f).deriv_within hxs
lemma deriv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) :
deriv (λ y, c y • f) x = (deriv c x) • f :=
(hc.has_deriv_at.smul_const f).deriv
theorem has_deriv_within_at.const_smul
(c : 𝕜) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ y, c • f y) (c • f') s x :=
begin
convert (has_deriv_within_at_const x s c).smul hf,
rw [zero_smul, add_zero]
end
theorem has_deriv_at.const_smul (c : 𝕜) (hf : has_deriv_at f f' x) :
has_deriv_at (λ y, c • f y) (c • f') x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hf.const_smul c
end
lemma deriv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x)
(c : 𝕜) (hf : differentiable_within_at 𝕜 f s x) :
deriv_within (λ y, c • f y) s x = c • deriv_within f s x :=
(hf.has_deriv_within_at.const_smul c).deriv_within hxs
lemma deriv_const_smul (c : 𝕜) (hf : differentiable_at 𝕜 f x) :
deriv (λ y, c • f y) x = c • deriv f x :=
(hf.has_deriv_at.const_smul c).deriv
end mul_vector
section neg
/-! ### Derivative of the negative of a function -/
theorem has_deriv_at_filter.neg (h : has_deriv_at_filter f f' x L) :
has_deriv_at_filter (λ x, -f x) (-f') x L :=
by simpa using h.neg.has_deriv_at_filter
theorem has_deriv_within_at.neg (h : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, -f x) (-f') s x :=
h.neg
theorem has_deriv_at.neg (h : has_deriv_at f f' x) : has_deriv_at (λ x, -f x) (-f') x :=
h.neg
theorem has_strict_deriv_at.neg (h : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ x, -f x) (-f') x :=
by simpa using h.neg.has_strict_deriv_at
lemma deriv_within.neg (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λy, -f y) s x = - deriv_within f s x :=
by simp only [deriv_within, fderiv_within_neg hxs, continuous_linear_map.neg_apply]
lemma deriv.neg : deriv (λy, -f y) x = - deriv f x :=
by simp only [deriv, fderiv_neg, continuous_linear_map.neg_apply]
@[simp] lemma deriv.neg' : deriv (λy, -f y) = (λ x, - deriv f x) :=
funext $ λ x, deriv.neg
end neg
section neg2
/-! ### Derivative of the negation function (i.e `has_neg.neg`) -/
variables (s x L)
theorem has_deriv_at_filter_neg : has_deriv_at_filter has_neg.neg (-1) x L :=
has_deriv_at_filter.neg $ has_deriv_at_filter_id _ _
theorem has_deriv_within_at_neg : has_deriv_within_at has_neg.neg (-1) s x :=
has_deriv_at_filter_neg _ _
theorem has_deriv_at_neg : has_deriv_at has_neg.neg (-1) x :=
has_deriv_at_filter_neg _ _
theorem has_deriv_at_neg' : has_deriv_at (λ x, -x) (-1) x :=
has_deriv_at_filter_neg _ _
theorem has_strict_deriv_at_neg : has_strict_deriv_at has_neg.neg (-1) x :=
has_strict_deriv_at.neg $ has_strict_deriv_at_id _
lemma deriv_neg : deriv has_neg.neg x = -1 :=
has_deriv_at.deriv (has_deriv_at_neg x)
@[simp] lemma deriv_neg' : deriv (has_neg.neg : 𝕜 → 𝕜) = λ _, -1 :=
funext deriv_neg
@[simp] lemma deriv_neg'' : deriv (λ x : 𝕜, -x) x = -1 :=
deriv_neg x
lemma deriv_within_neg (hxs : unique_diff_within_at 𝕜 s x) : deriv_within has_neg.neg s x = -1 :=
(has_deriv_within_at_neg x s).deriv_within hxs
lemma differentiable_neg : differentiable 𝕜 (has_neg.neg : 𝕜 → 𝕜) :=
differentiable.neg differentiable_id
lemma differentiable_on_neg : differentiable_on 𝕜 (has_neg.neg : 𝕜 → 𝕜) s :=
differentiable_on.neg differentiable_on_id
end neg2
section sub
/-! ### Derivative of the difference of two functions -/
theorem has_deriv_at_filter.sub
(hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) :
has_deriv_at_filter (λ x, f x - g x) (f' - g') x L :=
by simpa only [sub_eq_add_neg] using hf.add hg.neg
theorem has_deriv_within_at.sub
(hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) :
has_deriv_within_at (λ x, f x - g x) (f' - g') s x :=
hf.sub hg
theorem has_deriv_at.sub
(hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) :
has_deriv_at (λ x, f x - g x) (f' - g') x :=
hf.sub hg
theorem has_strict_deriv_at.sub
(hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) :
has_strict_deriv_at (λ x, f x - g x) (f' - g') x :=
by simpa only [sub_eq_add_neg] using hf.add hg.neg
lemma deriv_within_sub (hxs : unique_diff_within_at 𝕜 s x)
(hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) :
deriv_within (λy, f y - g y) s x = deriv_within f s x - deriv_within g s x :=
(hf.has_deriv_within_at.sub hg.has_deriv_within_at).deriv_within hxs
@[simp] lemma deriv_sub
(hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) :
deriv (λ y, f y - g y) x = deriv f x - deriv g x :=
(hf.has_deriv_at.sub hg.has_deriv_at).deriv
theorem has_deriv_at_filter.is_O_sub (h : has_deriv_at_filter f f' x L) :
is_O (λ x', f x' - f x) (λ x', x' - x) L :=
has_fderiv_at_filter.is_O_sub h
theorem has_deriv_at_filter.sub_const
(hf : has_deriv_at_filter f f' x L) (c : F) :
has_deriv_at_filter (λ x, f x - c) f' x L :=
by simpa only [sub_eq_add_neg] using hf.add_const (-c)
theorem has_deriv_within_at.sub_const
(hf : has_deriv_within_at f f' s x) (c : F) :
has_deriv_within_at (λ x, f x - c) f' s x :=
hf.sub_const c
theorem has_deriv_at.sub_const
(hf : has_deriv_at f f' x) (c : F) :
has_deriv_at (λ x, f x - c) f' x :=
hf.sub_const c
lemma deriv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) :
deriv_within (λy, f y - c) s x = deriv_within f s x :=
by simp only [deriv_within, fderiv_within_sub_const hxs]
lemma deriv_sub_const (c : F) : deriv (λ y, f y - c) x = deriv f x :=
by simp only [deriv, fderiv_sub_const]
theorem has_deriv_at_filter.const_sub (c : F) (hf : has_deriv_at_filter f f' x L) :
has_deriv_at_filter (λ x, c - f x) (-f') x L :=
by simpa only [sub_eq_add_neg] using hf.neg.const_add c
theorem has_deriv_within_at.const_sub (c : F) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, c - f x) (-f') s x :=
hf.const_sub c
theorem has_strict_deriv_at.const_sub (c : F) (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ x, c - f x) (-f') x :=
by simpa only [sub_eq_add_neg] using hf.neg.const_add c
theorem has_deriv_at.const_sub (c : F) (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, c - f x) (-f') x :=
hf.const_sub c
lemma deriv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) :
deriv_within (λy, c - f y) s x = -deriv_within f s x :=
by simp [deriv_within, fderiv_within_const_sub hxs]
lemma deriv_const_sub (c : F) : deriv (λ y, c - f y) x = -deriv f x :=
by simp only [← deriv_within_univ, deriv_within_const_sub unique_diff_within_at_univ]
end sub
section continuous
/-! ### Continuity of a function admitting a derivative -/
theorem has_deriv_at_filter.tendsto_nhds
(hL : L ≤ 𝓝 x) (h : has_deriv_at_filter f f' x L) :
tendsto f L (𝓝 (f x)) :=
h.tendsto_nhds hL
theorem has_deriv_within_at.continuous_within_at
(h : has_deriv_within_at f f' s x) : continuous_within_at f s x :=
has_deriv_at_filter.tendsto_nhds inf_le_left h
theorem has_deriv_at.continuous_at (h : has_deriv_at f f' x) : continuous_at f x :=
has_deriv_at_filter.tendsto_nhds (le_refl _) h
end continuous
section cartesian_product
/-! ### Derivative of the cartesian product of two functions -/
variables {G : Type w} [normed_group G] [normed_space 𝕜 G]
variables {f₂ : 𝕜 → G} {f₂' : G}
lemma has_deriv_at_filter.prod
(hf₁ : has_deriv_at_filter f₁ f₁' x L) (hf₂ : has_deriv_at_filter f₂ f₂' x L) :
has_deriv_at_filter (λ x, (f₁ x, f₂ x)) (f₁', f₂') x L :=
show has_fderiv_at_filter _ _ _ _,
by convert has_fderiv_at_filter.prod hf₁ hf₂
lemma has_deriv_within_at.prod
(hf₁ : has_deriv_within_at f₁ f₁' s x) (hf₂ : has_deriv_within_at f₂ f₂' s x) :
has_deriv_within_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') s x :=
hf₁.prod hf₂
lemma has_deriv_at.prod (hf₁ : has_deriv_at f₁ f₁' x) (hf₂ : has_deriv_at f₂ f₂' x) :
has_deriv_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') x :=
hf₁.prod hf₂
end cartesian_product
section composition
/-!
### Derivative of the composition of a vector function and a scalar function
We use `scomp` in lemmas on composition of vector valued and scalar valued functions, and `comp`
in lemmas on composition of scalar valued functions, in analogy for `smul` and `mul` (and also
because the `comp` version with the shorter name will show up much more often in applications).
The formula for the derivative involves `smul` in `scomp` lemmas, which can be reduced to
usual multiplication in `comp` lemmas.
-/
variables {h h₁ h₂ : 𝕜 → 𝕜} {h' h₁' h₂' : 𝕜}
/- For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to
get confused since there are too many possibilities for composition -/
variable (x)
theorem has_deriv_at_filter.scomp
(hg : has_deriv_at_filter g g' (h x) (L.map h))
(hh : has_deriv_at_filter h h' x L) :
has_deriv_at_filter (g ∘ h) (h' • g') x L :=
by simpa using (hg.comp x hh).has_deriv_at_filter
theorem has_deriv_within_at.scomp {t : set 𝕜}
(hg : has_deriv_within_at g g' t (h x))
(hh : has_deriv_within_at h h' s x) (hst : s ⊆ h ⁻¹' t) :
has_deriv_within_at (g ∘ h) (h' • g') s x :=
has_deriv_at_filter.scomp _ (has_deriv_at_filter.mono hg $
hh.continuous_within_at.tendsto_nhds_within hst) hh
/-- The chain rule. -/
theorem has_deriv_at.scomp
(hg : has_deriv_at g g' (h x)) (hh : has_deriv_at h h' x) :
has_deriv_at (g ∘ h) (h' • g') x :=
(hg.mono hh.continuous_at).scomp x hh
theorem has_strict_deriv_at.scomp
(hg : has_strict_deriv_at g g' (h x)) (hh : has_strict_deriv_at h h' x) :
has_strict_deriv_at (g ∘ h) (h' • g') x :=
by simpa using (hg.comp x hh).has_strict_deriv_at
theorem has_deriv_at.scomp_has_deriv_within_at
(hg : has_deriv_at g g' (h x)) (hh : has_deriv_within_at h h' s x) :
has_deriv_within_at (g ∘ h) (h' • g') s x :=
begin
rw ← has_deriv_within_at_univ at hg,
exact has_deriv_within_at.scomp x hg hh subset_preimage_univ
end
lemma deriv_within.scomp
(hg : differentiable_within_at 𝕜 g t (h x)) (hh : differentiable_within_at 𝕜 h s x)
(hs : s ⊆ h ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (g ∘ h) s x = deriv_within h s x • deriv_within g t (h x) :=
begin
apply has_deriv_within_at.deriv_within _ hxs,
exact has_deriv_within_at.scomp x (hg.has_deriv_within_at) (hh.has_deriv_within_at) hs
end
lemma deriv.scomp
(hg : differentiable_at 𝕜 g (h x)) (hh : differentiable_at 𝕜 h x) :
deriv (g ∘ h) x = deriv h x • deriv g (h x) :=
begin
apply has_deriv_at.deriv,
exact has_deriv_at.scomp x hg.has_deriv_at hh.has_deriv_at
end
/-! ### Derivative of the composition of a scalar and vector functions -/
theorem has_deriv_at_filter.comp_has_fderiv_at_filter {f : E → 𝕜} {f' : E →L[𝕜] 𝕜} (x)
{L : filter E} (hh₁ : has_deriv_at_filter h₁ h₁' (f x) (L.map f))
(hf : has_fderiv_at_filter f f' x L) :
has_fderiv_at_filter (h₁ ∘ f) (h₁' • f') x L :=
by { convert has_fderiv_at_filter.comp x hh₁ hf, ext x, simp [mul_comm] }
theorem has_strict_deriv_at.comp_has_strict_fderiv_at {f : E → 𝕜} {f' : E →L[𝕜] 𝕜} (x)
(hh₁ : has_strict_deriv_at h₁ h₁' (f x)) (hf : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at (h₁ ∘ f) (h₁' • f') x :=
by { rw has_strict_deriv_at at hh₁, convert hh₁.comp x hf, ext x, simp [mul_comm] }
theorem has_deriv_at.comp_has_fderiv_at {f : E → 𝕜} {f' : E →L[𝕜] 𝕜} (x)
(hh₁ : has_deriv_at h₁ h₁' (f x)) (hf : has_fderiv_at f f' x) :
has_fderiv_at (h₁ ∘ f) (h₁' • f') x :=
(hh₁.mono hf.continuous_at).comp_has_fderiv_at_filter x hf
theorem has_deriv_at.comp_has_fderiv_within_at {f : E → 𝕜} {f' : E →L[𝕜] 𝕜} {s} (x)
(hh₁ : has_deriv_at h₁ h₁' (f x)) (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (h₁ ∘ f) (h₁' • f') s x :=
(hh₁.mono hf.continuous_within_at).comp_has_fderiv_at_filter x hf
theorem has_deriv_within_at.comp_has_fderiv_within_at {f : E → 𝕜} {f' : E →L[𝕜] 𝕜} {s t} (x)
(hh₁ : has_deriv_within_at h₁ h₁' t (f x)) (hf : has_fderiv_within_at f f' s x)
(hst : maps_to f s t) :
has_fderiv_within_at (h₁ ∘ f) (h₁' • f') s x :=
(has_deriv_at_filter.mono hh₁ $
hf.continuous_within_at.tendsto_nhds_within hst).comp_has_fderiv_at_filter x hf
/-! ### Derivative of the composition of two scalar functions -/
theorem has_deriv_at_filter.comp
(hh₁ : has_deriv_at_filter h₁ h₁' (h₂ x) (L.map h₂))
(hh₂ : has_deriv_at_filter h₂ h₂' x L) :
has_deriv_at_filter (h₁ ∘ h₂) (h₁' * h₂') x L :=
by { rw mul_comm, exact hh₁.scomp x hh₂ }
theorem has_deriv_within_at.comp {t : set 𝕜}
(hh₁ : has_deriv_within_at h₁ h₁' t (h₂ x))
(hh₂ : has_deriv_within_at h₂ h₂' s x) (hst : s ⊆ h₂ ⁻¹' t) :
has_deriv_within_at (h₁ ∘ h₂) (h₁' * h₂') s x :=
by { rw mul_comm, exact hh₁.scomp x hh₂ hst, }
/-- The chain rule. -/
theorem has_deriv_at.comp
(hh₁ : has_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_deriv_at h₂ h₂' x) :
has_deriv_at (h₁ ∘ h₂) (h₁' * h₂') x :=
(hh₁.mono hh₂.continuous_at).comp x hh₂
theorem has_strict_deriv_at.comp
(hh₁ : has_strict_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_strict_deriv_at h₂ h₂' x) :
has_strict_deriv_at (h₁ ∘ h₂) (h₁' * h₂') x :=
by { rw mul_comm, exact hh₁.scomp x hh₂ }
theorem has_deriv_at.comp_has_deriv_within_at
(hh₁ : has_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_deriv_within_at h₂ h₂' s x) :
has_deriv_within_at (h₁ ∘ h₂) (h₁' * h₂') s x :=
begin
rw ← has_deriv_within_at_univ at hh₁,
exact has_deriv_within_at.comp x hh₁ hh₂ subset_preimage_univ
end
lemma deriv_within.comp
(hh₁ : differentiable_within_at 𝕜 h₁ t (h₂ x)) (hh₂ : differentiable_within_at 𝕜 h₂ s x)
(hs : s ⊆ h₂ ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (h₁ ∘ h₂) s x = deriv_within h₁ t (h₂ x) * deriv_within h₂ s x :=
begin
apply has_deriv_within_at.deriv_within _ hxs,
exact has_deriv_within_at.comp x (hh₁.has_deriv_within_at) (hh₂.has_deriv_within_at) hs
end
lemma deriv.comp
(hh₁ : differentiable_at 𝕜 h₁ (h₂ x)) (hh₂ : differentiable_at 𝕜 h₂ x) :
deriv (h₁ ∘ h₂) x = deriv h₁ (h₂ x) * deriv h₂ x :=
begin
apply has_deriv_at.deriv,
exact has_deriv_at.comp x hh₁.has_deriv_at hh₂.has_deriv_at
end
protected lemma has_deriv_at_filter.iterate {f : 𝕜 → 𝕜} {f' : 𝕜}
(hf : has_deriv_at_filter f f' x L) (hL : tendsto f L L) (hx : f x = x) (n : ℕ) :
has_deriv_at_filter (f^[n]) (f'^n) x L :=
begin
have := hf.iterate hL hx n,
rwa [continuous_linear_map.smul_right_one_pow] at this
end
protected lemma has_deriv_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜}
(hf : has_deriv_at f f' x) (hx : f x = x) (n : ℕ) :
has_deriv_at (f^[n]) (f'^n) x :=
begin
have := has_fderiv_at.iterate hf hx n,
rwa [continuous_linear_map.smul_right_one_pow] at this
end
protected lemma has_deriv_within_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜}
(hf : has_deriv_within_at f f' s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) :
has_deriv_within_at (f^[n]) (f'^n) s x :=
begin
have := has_fderiv_within_at.iterate hf hx hs n,
rwa [continuous_linear_map.smul_right_one_pow] at this
end
protected lemma has_strict_deriv_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜}
(hf : has_strict_deriv_at f f' x) (hx : f x = x) (n : ℕ) :
has_strict_deriv_at (f^[n]) (f'^n) x :=
begin
have := hf.iterate hx n,
rwa [continuous_linear_map.smul_right_one_pow] at this
end
end composition
section composition_vector
/-! ### Derivative of the composition of a function between vector spaces and of a function defined on `𝕜` -/
variables {l : F → E} {l' : F →L[𝕜] E}
variable (x)
/-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative within a set
equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/
theorem has_fderiv_within_at.comp_has_deriv_within_at {t : set F}
(hl : has_fderiv_within_at l l' t (f x)) (hf : has_deriv_within_at f f' s x) (hst : s ⊆ f ⁻¹' t) :
has_deriv_within_at (l ∘ f) (l' (f')) s x :=
begin
rw has_deriv_within_at_iff_has_fderiv_within_at,
convert has_fderiv_within_at.comp x hl hf hst,
ext,
simp
end
/-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative equal to the
Fréchet derivative of `l` applied to the derivative of `f`. -/
theorem has_fderiv_at.comp_has_deriv_at
(hl : has_fderiv_at l l' (f x)) (hf : has_deriv_at f f' x) :
has_deriv_at (l ∘ f) (l' (f')) x :=
begin
rw has_deriv_at_iff_has_fderiv_at,
convert has_fderiv_at.comp x hl hf,
ext,
simp
end
theorem has_fderiv_at.comp_has_deriv_within_at
(hl : has_fderiv_at l l' (f x)) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (l ∘ f) (l' (f')) s x :=
begin
rw ← has_fderiv_within_at_univ at hl,
exact has_fderiv_within_at.comp_has_deriv_within_at x hl hf subset_preimage_univ
end
lemma fderiv_within.comp_deriv_within {t : set F}
(hl : differentiable_within_at 𝕜 l t (f x)) (hf : differentiable_within_at 𝕜 f s x)
(hs : s ⊆ f ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (l ∘ f) s x = (fderiv_within 𝕜 l t (f x) : F → E) (deriv_within f s x) :=
begin
apply has_deriv_within_at.deriv_within _ hxs,
exact (hl.has_fderiv_within_at).comp_has_deriv_within_at x (hf.has_deriv_within_at) hs
end
lemma fderiv.comp_deriv
(hl : differentiable_at 𝕜 l (f x)) (hf : differentiable_at 𝕜 f x) :
deriv (l ∘ f) x = (fderiv 𝕜 l (f x) : F → E) (deriv f x) :=
begin
apply has_deriv_at.deriv _,
exact (hl.has_fderiv_at).comp_has_deriv_at x (hf.has_deriv_at)
end
end composition_vector
section mul
/-! ### Derivative of the multiplication of two scalar functions -/
variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜}
theorem has_deriv_within_at.mul
(hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) :
has_deriv_within_at (λ y, c y * d y) (c' * d x + c x * d') s x :=
begin
convert hc.smul hd using 1,
rw [smul_eq_mul, smul_eq_mul, add_comm]
end
theorem has_deriv_at.mul (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) :
has_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hc.mul hd
end
theorem has_strict_deriv_at.mul
(hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x) :
has_strict_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x :=
begin
convert hc.smul hd using 1,
rw [smul_eq_mul, smul_eq_mul, add_comm]
end
lemma deriv_within_mul (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) :
deriv_within (λ y, c y * d y) s x = deriv_within c s x * d x + c x * deriv_within d s x :=
(hc.has_deriv_within_at.mul hd.has_deriv_within_at).deriv_within hxs
@[simp] lemma deriv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) :
deriv (λ y, c y * d y) x = deriv c x * d x + c x * deriv d x :=
(hc.has_deriv_at.mul hd.has_deriv_at).deriv
theorem has_deriv_within_at.mul_const (hc : has_deriv_within_at c c' s x) (d : 𝕜) :
has_deriv_within_at (λ y, c y * d) (c' * d) s x :=
begin
convert hc.mul (has_deriv_within_at_const x s d),
rw [mul_zero, add_zero]
end
theorem has_deriv_at.mul_const (hc : has_deriv_at c c' x) (d : 𝕜) :
has_deriv_at (λ y, c y * d) (c' * d) x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hc.mul_const d
end
theorem has_strict_deriv_at.mul_const (hc : has_strict_deriv_at c c' x) (d : 𝕜) :
has_strict_deriv_at (λ y, c y * d) (c' * d) x :=
begin
convert hc.mul (has_strict_deriv_at_const x d),
rw [mul_zero, add_zero]
end
lemma deriv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) :
deriv_within (λ y, c y * d) s x = deriv_within c s x * d :=
(hc.has_deriv_within_at.mul_const d).deriv_within hxs
lemma deriv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) :
deriv (λ y, c y * d) x = deriv c x * d :=
(hc.has_deriv_at.mul_const d).deriv
theorem has_deriv_within_at.const_mul (c : 𝕜) (hd : has_deriv_within_at d d' s x) :
has_deriv_within_at (λ y, c * d y) (c * d') s x :=
begin
convert (has_deriv_within_at_const x s c).mul hd,
rw [zero_mul, zero_add]
end
theorem has_deriv_at.const_mul (c : 𝕜) (hd : has_deriv_at d d' x) :
has_deriv_at (λ y, c * d y) (c * d') x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hd.const_mul c
end
theorem has_strict_deriv_at.const_mul (c : 𝕜) (hd : has_strict_deriv_at d d' x) :
has_strict_deriv_at (λ y, c * d y) (c * d') x :=
begin
convert (has_strict_deriv_at_const _ _).mul hd,
rw [zero_mul, zero_add]
end
lemma deriv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x)
(c : 𝕜) (hd : differentiable_within_at 𝕜 d s x) :
deriv_within (λ y, c * d y) s x = c * deriv_within d s x :=
(hd.has_deriv_within_at.const_mul c).deriv_within hxs
lemma deriv_const_mul (c : 𝕜) (hd : differentiable_at 𝕜 d x) :
deriv (λ y, c * d y) x = c * deriv d x :=
(hd.has_deriv_at.const_mul c).deriv
end mul
section inverse
/-! ### Derivative of `x ↦ x⁻¹` -/
theorem has_strict_deriv_at_inv (hx : x ≠ 0) : has_strict_deriv_at has_inv.inv (-(x^2)⁻¹) x :=
begin
suffices : is_o (λ p : 𝕜 × 𝕜, (p.1 - p.2) * ((x * x)⁻¹ - (p.1 * p.2)⁻¹))
(λ (p : 𝕜 × 𝕜), (p.1 - p.2) * 1) (𝓝 (x, x)),
{ refine this.congr' _ (eventually_of_forall $ λ _, mul_one _),
refine eventually.mono (mem_nhds_sets (is_open_ne.prod is_open_ne) ⟨hx, hx⟩) _,
rintro ⟨y, z⟩ ⟨hy, hz⟩,
simp only [mem_set_of_eq] at hy hz, -- hy : y ≠ 0, hz : z ≠ 0
field_simp [hx, hy, hz], ring, },
refine (is_O_refl (λ p : 𝕜 × 𝕜, p.1 - p.2) _).mul_is_o ((is_o_one_iff _).2 _),
rw [← sub_self (x * x)⁻¹],
exact tendsto_const_nhds.sub ((continuous_mul.tendsto (x, x)).inv' $ mul_ne_zero hx hx)
end
theorem has_deriv_at_inv (x_ne_zero : x ≠ 0) :
has_deriv_at (λy, y⁻¹) (-(x^2)⁻¹) x :=
(has_strict_deriv_at_inv x_ne_zero).has_deriv_at
theorem has_deriv_within_at_inv (x_ne_zero : x ≠ 0) (s : set 𝕜) :
has_deriv_within_at (λx, x⁻¹) (-(x^2)⁻¹) s x :=
(has_deriv_at_inv x_ne_zero).has_deriv_within_at
lemma differentiable_at_inv (x_ne_zero : x ≠ 0) :
differentiable_at 𝕜 (λx, x⁻¹) x :=
(has_deriv_at_inv x_ne_zero).differentiable_at
lemma differentiable_within_at_inv (x_ne_zero : x ≠ 0) :
differentiable_within_at 𝕜 (λx, x⁻¹) s x :=
(differentiable_at_inv x_ne_zero).differentiable_within_at
lemma differentiable_on_inv : differentiable_on 𝕜 (λx:𝕜, x⁻¹) {x | x ≠ 0} :=
λx hx, differentiable_within_at_inv hx
lemma deriv_inv (x_ne_zero : x ≠ 0) :
deriv (λx, x⁻¹) x = -(x^2)⁻¹ :=
(has_deriv_at_inv x_ne_zero).deriv
lemma deriv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, x⁻¹) s x = -(x^2)⁻¹ :=
begin
rw differentiable_at.deriv_within (differentiable_at_inv x_ne_zero) hxs,
exact deriv_inv x_ne_zero
end
lemma has_fderiv_at_inv (x_ne_zero : x ≠ 0) :
has_fderiv_at (λx, x⁻¹) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) x :=
has_deriv_at_inv x_ne_zero
lemma has_fderiv_within_at_inv (x_ne_zero : x ≠ 0) :
has_fderiv_within_at (λx, x⁻¹) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) s x :=
(has_fderiv_at_inv x_ne_zero).has_fderiv_within_at
lemma fderiv_inv (x_ne_zero : x ≠ 0) :
fderiv 𝕜 (λx, x⁻¹) x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) :=
(has_fderiv_at_inv x_ne_zero).fderiv
lemma fderiv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λx, x⁻¹) s x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) :=
begin
rw differentiable_at.fderiv_within (differentiable_at_inv x_ne_zero) hxs,
exact fderiv_inv x_ne_zero
end
variables {c : 𝕜 → 𝕜} {c' : 𝕜}
lemma has_deriv_within_at.inv
(hc : has_deriv_within_at c c' s x) (hx : c x ≠ 0) :
has_deriv_within_at (λ y, (c y)⁻¹) (- c' / (c x)^2) s x :=
begin
convert (has_deriv_at_inv hx).comp_has_deriv_within_at x hc,
field_simp
end
lemma has_deriv_at.inv (hc : has_deriv_at c c' x) (hx : c x ≠ 0) :
has_deriv_at (λ y, (c y)⁻¹) (- c' / (c x)^2) x :=
begin
rw ← has_deriv_within_at_univ at *,
exact hc.inv hx
end
lemma differentiable_within_at.inv (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0) :
differentiable_within_at 𝕜 (λx, (c x)⁻¹) s x :=
(hc.has_deriv_within_at.inv hx).differentiable_within_at
@[simp] lemma differentiable_at.inv (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) :
differentiable_at 𝕜 (λx, (c x)⁻¹) x :=
(hc.has_deriv_at.inv hx).differentiable_at
lemma differentiable_on.inv (hc : differentiable_on 𝕜 c s) (hx : ∀ x ∈ s, c x ≠ 0) :
differentiable_on 𝕜 (λx, (c x)⁻¹) s :=
λx h, (hc x h).inv (hx x h)
@[simp] lemma differentiable.inv (hc : differentiable 𝕜 c) (hx : ∀ x, c x ≠ 0) :
differentiable 𝕜 (λx, (c x)⁻¹) :=
λx, (hc x).inv (hx x)
lemma deriv_within_inv' (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0)
(hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, (c x)⁻¹) s x = - (deriv_within c s x) / (c x)^2 :=
(hc.has_deriv_within_at.inv hx).deriv_within hxs
@[simp] lemma deriv_inv' (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) :
deriv (λx, (c x)⁻¹) x = - (deriv c x) / (c x)^2 :=
(hc.has_deriv_at.inv hx).deriv
end inverse
section division
/-! ### Derivative of `x ↦ c x / d x` -/
variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜}
lemma has_deriv_within_at.div
(hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) (hx : d x ≠ 0) :
has_deriv_within_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) s x :=
begin
convert hc.mul ((has_deriv_at_inv hx).comp_has_deriv_within_at x hd),
field_simp, ring
end
lemma has_strict_deriv_at.div (hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x)
(hx : d x ≠ 0) :
has_strict_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x :=
begin
convert hc.mul ((has_strict_deriv_at_inv hx).comp x hd),
field_simp, ring
end
lemma has_deriv_at.div (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) (hx : d x ≠ 0) :
has_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x :=
begin
rw ← has_deriv_within_at_univ at *,
exact hc.div hd hx
end
lemma differentiable_within_at.div
(hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) :
differentiable_within_at 𝕜 (λx, c x / d x) s x :=
((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).differentiable_within_at
@[simp] lemma differentiable_at.div
(hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) :
differentiable_at 𝕜 (λx, c x / d x) x :=
((hc.has_deriv_at).div (hd.has_deriv_at) hx).differentiable_at
lemma differentiable_on.div
(hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) (hx : ∀ x ∈ s, d x ≠ 0) :
differentiable_on 𝕜 (λx, c x / d x) s :=
λx h, (hc x h).div (hd x h) (hx x h)
@[simp] lemma differentiable.div
(hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) (hx : ∀ x, d x ≠ 0) :
differentiable 𝕜 (λx, c x / d x) :=
λx, (hc x).div (hd x) (hx x)
lemma deriv_within_div
(hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0)
(hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, c x / d x) s x
= ((deriv_within c s x) * d x - c x * (deriv_within d s x)) / (d x)^2 :=
((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).deriv_within hxs
@[simp] lemma deriv_div
(hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) :
deriv (λx, c x / d x) x = ((deriv c x) * d x - c x * (deriv d x)) / (d x)^2 :=
((hc.has_deriv_at).div (hd.has_deriv_at) hx).deriv
lemma differentiable_within_at.div_const (hc : differentiable_within_at 𝕜 c s x) {d : 𝕜} :
differentiable_within_at 𝕜 (λx, c x / d) s x :=
by simp [div_eq_inv_mul, differentiable_within_at.const_mul, hc]
@[simp] lemma differentiable_at.div_const (hc : differentiable_at 𝕜 c x) {d : 𝕜} :
differentiable_at 𝕜 (λ x, c x / d) x :=
(hc.has_deriv_at.mul_const d⁻¹).differentiable_at
lemma differentiable_on.div_const (hc : differentiable_on 𝕜 c s) {d : 𝕜} :
differentiable_on 𝕜 (λx, c x / d) s :=
by simp [div_eq_inv_mul, differentiable_on.const_mul, hc]
@[simp] lemma differentiable.div_const (hc : differentiable 𝕜 c) {d : 𝕜} :
differentiable 𝕜 (λx, c x / d) :=
by simp [div_eq_inv_mul, differentiable.const_mul, hc]
lemma deriv_within_div_const (hc : differentiable_within_at 𝕜 c s x) {d : 𝕜}
(hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, c x / d) s x = (deriv_within c s x) / d :=
by simp [div_eq_inv_mul, deriv_within_const_mul, hc, hxs]
@[simp] lemma deriv_div_const (hc : differentiable_at 𝕜 c x) {d : 𝕜} :
deriv (λx, c x / d) x = (deriv c x) / d :=
by simp [div_eq_inv_mul, deriv_const_mul, hc]
end division
theorem has_strict_deriv_at.has_strict_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜}
(hf : has_strict_deriv_at f f' x) (hf' : f' ≠ 0) :
has_strict_fderiv_at f
(continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x :=
hf
theorem has_deriv_at.has_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜}
(hf : has_deriv_at f f' x) (hf' : f' ≠ 0) :
has_fderiv_at f
(continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x :=
hf
/-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an
invertible derivative `f'` at `g a` in the strict sense, then `g` has the derivative `f'⁻¹` at `a`
in the strict sense.
This is one of the easy parts of the inverse function theorem: it assumes that we already have an
inverse function. -/
theorem has_strict_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜}
(hg : continuous_at g a) (hf : has_strict_deriv_at f f' (g a)) (hf' : f' ≠ 0)
(hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) :
has_strict_deriv_at g f'⁻¹ a :=
(hf.has_strict_fderiv_at_equiv hf').of_local_left_inverse hg hfg
/-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has a
nonzero derivative `f'` at `f.symm a` in the strict sense, then `f.symm` has the derivative `f'⁻¹`
at `a` in the strict sense.
This is one of the easy parts of the inverse function theorem: it assumes that we already have
an inverse function. -/
lemma local_homeomorph.has_strict_deriv_at_symm (f : local_homeomorph 𝕜 𝕜) {a f' : 𝕜}
(ha : a ∈ f.target) (hf' : f' ≠ 0) (htff' : has_strict_deriv_at f f' (f.symm a)) :
has_strict_deriv_at f.symm f'⁻¹ a :=
htff'.of_local_left_inverse (f.symm.continuous_at ha) hf' (f.eventually_right_inverse ha)
/-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an
invertible derivative `f'` at `g a`, then `g` has the derivative `f'⁻¹` at `a`.
This is one of the easy parts of the inverse function theorem: it assumes that we already have
an inverse function. -/
theorem has_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜}
(hg : continuous_at g a) (hf : has_deriv_at f f' (g a)) (hf' : f' ≠ 0)
(hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) :
has_deriv_at g f'⁻¹ a :=
(hf.has_fderiv_at_equiv hf').of_local_left_inverse hg hfg
/-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an
nonzero derivative `f'` at `f.symm a`, then `f.symm` has the derivative `f'⁻¹` at `a`.
This is one of the easy parts of the inverse function theorem: it assumes that we already have
an inverse function. -/
lemma local_homeomorph.has_deriv_at_symm (f : local_homeomorph 𝕜 𝕜) {a f' : 𝕜}
(ha : a ∈ f.target) (hf' : f' ≠ 0) (htff' : has_deriv_at f f' (f.symm a)) :
has_deriv_at f.symm f'⁻¹ a :=
htff'.of_local_left_inverse (f.symm.continuous_at ha) hf' (f.eventually_right_inverse ha)
lemma has_deriv_at.eventually_ne (h : has_deriv_at f f' x) (hf' : f' ≠ 0) :
∀ᶠ z in 𝓝[{x}ᶜ] x, f z ≠ f x :=
(has_deriv_at_iff_has_fderiv_at.1 h).eventually_ne
⟨∥f'∥⁻¹, λ z, by field_simp [norm_smul, mt norm_eq_zero.1 hf']⟩
theorem not_differentiable_within_at_of_local_left_inverse_has_deriv_within_at_zero
{f g : 𝕜 → 𝕜} {a : 𝕜} {s t : set 𝕜} (ha : a ∈ s) (hsu : unique_diff_within_at 𝕜 s a)
(hf : has_deriv_within_at f 0 t (g a)) (hst : maps_to g s t) (hfg : f ∘ g =ᶠ[𝓝[s] a] id) :
¬differentiable_within_at 𝕜 g s a :=
begin
intro hg,
have := (hf.comp a hg.has_deriv_within_at hst).congr_of_eventually_eq_of_mem hfg.symm ha,
simpa using hsu.eq_deriv _ this (has_deriv_within_at_id _ _)
end
theorem not_differentiable_at_of_local_left_inverse_has_deriv_at_zero
{f g : 𝕜 → 𝕜} {a : 𝕜} (hf : has_deriv_at f 0 (g a)) (hfg : f ∘ g =ᶠ[𝓝 a] id) :
¬differentiable_at 𝕜 g a :=
begin
intro hg,
have := (hf.comp a hg.has_deriv_at).congr_of_eventually_eq hfg.symm,
simpa using this.unique (has_deriv_at_id a)
end
end
namespace polynomial
/-! ### Derivative of a polynomial -/
variables {x : 𝕜} {s : set 𝕜}
variable (p : polynomial 𝕜)
/-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/
protected lemma has_strict_deriv_at (x : 𝕜) :
has_strict_deriv_at (λx, p.eval x) (p.derivative.eval x) x :=
begin
apply p.induction_on,
{ simp [has_strict_deriv_at_const] },
{ assume p q hp hq,
convert hp.add hq;
simp },
{ assume n a h,
convert h.mul (has_strict_deriv_at_id x),
{ ext y, simp [pow_add, mul_assoc] },
{ simp [pow_add], ring } }
end
/-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/
protected lemma has_deriv_at (x : 𝕜) : has_deriv_at (λx, p.eval x) (p.derivative.eval x) x :=
(p.has_strict_deriv_at x).has_deriv_at
protected theorem has_deriv_within_at (x : 𝕜) (s : set 𝕜) :
has_deriv_within_at (λx, p.eval x) (p.derivative.eval x) s x :=
(p.has_deriv_at x).has_deriv_within_at
protected lemma differentiable_at : differentiable_at 𝕜 (λx, p.eval x) x :=
(p.has_deriv_at x).differentiable_at
protected lemma differentiable_within_at : differentiable_within_at 𝕜 (λx, p.eval x) s x :=
p.differentiable_at.differentiable_within_at
protected lemma differentiable : differentiable 𝕜 (λx, p.eval x) :=
λx, p.differentiable_at
protected lemma differentiable_on : differentiable_on 𝕜 (λx, p.eval x) s :=
p.differentiable.differentiable_on
@[simp] protected lemma deriv : deriv (λx, p.eval x) x = p.derivative.eval x :=
(p.has_deriv_at x).deriv
protected lemma deriv_within (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, p.eval x) s x = p.derivative.eval x :=
begin
rw differentiable_at.deriv_within p.differentiable_at hxs,
exact p.deriv
end
protected lemma has_fderiv_at (x : 𝕜) :
has_fderiv_at (λx, p.eval x) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x)) x :=
p.has_deriv_at x
protected lemma has_fderiv_within_at (x : 𝕜) :
has_fderiv_within_at (λx, p.eval x) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x)) s x :=
(p.has_fderiv_at x).has_fderiv_within_at
@[simp] protected lemma fderiv :
fderiv 𝕜 (λx, p.eval x) x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x) :=
(p.has_fderiv_at x).fderiv
protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λx, p.eval x) s x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x) :=
(p.has_fderiv_within_at x).fderiv_within hxs
end polynomial
section pow
/-! ### Derivative of `x ↦ x^n` for `n : ℕ` -/
variables {x : 𝕜} {s : set 𝕜} {c : 𝕜 → 𝕜} {c' : 𝕜}
variable {n : ℕ }
lemma has_strict_deriv_at_pow (n : ℕ) (x : 𝕜) :
has_strict_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x :=
begin
convert (polynomial.C (1 : 𝕜) * (polynomial.X)^n).has_strict_deriv_at x,
{ simp },
{ rw [polynomial.derivative_C_mul_X_pow], simp }
end
lemma has_deriv_at_pow (n : ℕ) (x : 𝕜) : has_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x :=
(has_strict_deriv_at_pow n x).has_deriv_at
theorem has_deriv_within_at_pow (n : ℕ) (x : 𝕜) (s : set 𝕜) :
has_deriv_within_at (λx, x^n) ((n : 𝕜) * x^(n-1)) s x :=
(has_deriv_at_pow n x).has_deriv_within_at
lemma differentiable_at_pow : differentiable_at 𝕜 (λx, x^n) x :=
(has_deriv_at_pow n x).differentiable_at
lemma differentiable_within_at_pow : differentiable_within_at 𝕜 (λx, x^n) s x :=
differentiable_at_pow.differentiable_within_at
lemma differentiable_pow : differentiable 𝕜 (λx:𝕜, x^n) :=
λx, differentiable_at_pow
lemma differentiable_on_pow : differentiable_on 𝕜 (λx, x^n) s :=
differentiable_pow.differentiable_on
lemma deriv_pow : deriv (λx, x^n) x = (n : 𝕜) * x^(n-1) :=
(has_deriv_at_pow n x).deriv
@[simp] lemma deriv_pow' : deriv (λx, x^n) = λ x, (n : 𝕜) * x^(n-1) :=
funext $ λ x, deriv_pow
lemma deriv_within_pow (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, x^n) s x = (n : 𝕜) * x^(n-1) :=
(has_deriv_within_at_pow n x s).deriv_within hxs
lemma iter_deriv_pow' {k : ℕ} :
deriv^[k] (λx:𝕜, x^n) = λ x, (∏ i in finset.range k, (n - i) : ℕ) * x^(n-k) :=
begin
induction k with k ihk,
{ simp only [one_mul, finset.prod_range_zero, function.iterate_zero_apply, nat.sub_zero,
nat.cast_one] },
{ simp only [function.iterate_succ_apply', ihk, finset.prod_range_succ],
ext x,
rw [((has_deriv_at_pow (n - k) x).const_mul _).deriv, nat.cast_mul, mul_left_comm, mul_assoc,
nat.succ_eq_add_one, nat.sub_sub] }
end
lemma iter_deriv_pow {k : ℕ} :
deriv^[k] (λx:𝕜, x^n) x = (∏ i in finset.range k, (n - i) : ℕ) * x^(n-k) :=
congr_fun iter_deriv_pow' x
lemma has_deriv_within_at.pow (hc : has_deriv_within_at c c' s x) :
has_deriv_within_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') s x :=
(has_deriv_at_pow n (c x)).comp_has_deriv_within_at x hc
lemma has_deriv_at.pow (hc : has_deriv_at c c' x) :
has_deriv_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') x :=
by { rw ← has_deriv_within_at_univ at *, exact hc.pow }
lemma differentiable_within_at.pow (hc : differentiable_within_at 𝕜 c s x) :
differentiable_within_at 𝕜 (λx, (c x)^n) s x :=
hc.has_deriv_within_at.pow.differentiable_within_at
@[simp] lemma differentiable_at.pow (hc : differentiable_at 𝕜 c x) :
differentiable_at 𝕜 (λx, (c x)^n) x :=
hc.has_deriv_at.pow.differentiable_at
lemma differentiable_on.pow (hc : differentiable_on 𝕜 c s) :
differentiable_on 𝕜 (λx, (c x)^n) s :=
λx h, (hc x h).pow
@[simp] lemma differentiable.pow (hc : differentiable 𝕜 c) :
differentiable 𝕜 (λx, (c x)^n) :=
λx, (hc x).pow
lemma deriv_within_pow' (hc : differentiable_within_at 𝕜 c s x)
(hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, (c x)^n) s x = (n : 𝕜) * (c x)^(n-1) * (deriv_within c s x) :=
hc.has_deriv_within_at.pow.deriv_within hxs
@[simp] lemma deriv_pow'' (hc : differentiable_at 𝕜 c x) :
deriv (λx, (c x)^n) x = (n : 𝕜) * (c x)^(n-1) * (deriv c x) :=
hc.has_deriv_at.pow.deriv
end pow
section fpow
/-! ### Derivative of `x ↦ x^m` for `m : ℤ` -/
variables {x : 𝕜} {s : set 𝕜}
variable {m : ℤ}
lemma has_strict_deriv_at_fpow (m : ℤ) (hx : x ≠ 0) :
has_strict_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x :=
begin
have : ∀ m : ℤ, 0 < m → has_strict_deriv_at (λx, x^m) ((m:𝕜) * x^(m-1)) x,
{ assume m hm,
lift m to ℕ using (le_of_lt hm),
simp only [fpow_of_nat, int.cast_coe_nat],
convert has_strict_deriv_at_pow _ _ using 2,
rw [← int.coe_nat_one, ← int.coe_nat_sub, fpow_coe_nat],
norm_cast at hm,
exact nat.succ_le_of_lt hm },
rcases lt_trichotomy m 0 with hm|hm|hm,
{ have := (has_strict_deriv_at_inv _).scomp _ (this (-m) (neg_pos.2 hm));
[skip, exact fpow_ne_zero_of_ne_zero hx _],
simp only [(∘), fpow_neg, one_div, inv_inv', smul_eq_mul] at this,
convert this using 1,
rw [pow_two, mul_inv', inv_inv', int.cast_neg, ← neg_mul_eq_neg_mul, neg_mul_neg,
← fpow_add hx, mul_assoc, ← fpow_add hx], congr, abel },
{ simp only [hm, fpow_zero, int.cast_zero, zero_mul, has_strict_deriv_at_const] },
{ exact this m hm }
end
lemma has_deriv_at_fpow (m : ℤ) (hx : x ≠ 0) :
has_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x :=
(has_strict_deriv_at_fpow m hx).has_deriv_at
theorem has_deriv_within_at_fpow (m : ℤ) (hx : x ≠ 0) (s : set 𝕜) :
has_deriv_within_at (λx, x^m) ((m : 𝕜) * x^(m-1)) s x :=
(has_deriv_at_fpow m hx).has_deriv_within_at
lemma differentiable_at_fpow (hx : x ≠ 0) : differentiable_at 𝕜 (λx, x^m) x :=
(has_deriv_at_fpow m hx).differentiable_at
lemma differentiable_within_at_fpow (hx : x ≠ 0) :
differentiable_within_at 𝕜 (λx, x^m) s x :=
(differentiable_at_fpow hx).differentiable_within_at
lemma differentiable_on_fpow (hs : (0:𝕜) ∉ s) : differentiable_on 𝕜 (λx, x^m) s :=
λ x hxs, differentiable_within_at_fpow (λ hx, hs $ hx ▸ hxs)
-- TODO : this is true at `x=0` as well
lemma deriv_fpow (hx : x ≠ 0) : deriv (λx, x^m) x = (m : 𝕜) * x^(m-1) :=
(has_deriv_at_fpow m hx).deriv
lemma deriv_within_fpow (hxs : unique_diff_within_at 𝕜 s x) (hx : x ≠ 0) :
deriv_within (λx, x^m) s x = (m : 𝕜) * x^(m-1) :=
(has_deriv_within_at_fpow m hx s).deriv_within hxs
lemma iter_deriv_fpow {k : ℕ} (hx : x ≠ 0) :
deriv^[k] (λx:𝕜, x^m) x = (∏ i in finset.range k, (m - i) : ℤ) * x^(m-k) :=
begin
induction k with k ihk generalizing x hx,
{ simp only [one_mul, finset.prod_range_zero, function.iterate_zero_apply, int.coe_nat_zero,
sub_zero, int.cast_one] },
{ rw [function.iterate_succ', finset.prod_range_succ, int.cast_mul, mul_assoc, mul_left_comm,
int.coe_nat_succ, ← sub_sub, ← ((has_deriv_at_fpow _ hx).const_mul _).deriv],
exact filter.eventually_eq.deriv_eq (eventually.mono (mem_nhds_sets is_open_ne hx) @ihk) }
end
end fpow
/-! ### Upper estimates on liminf and limsup -/
section real
variables {f : ℝ → ℝ} {f' : ℝ} {s : set ℝ} {x : ℝ} {r : ℝ}
lemma has_deriv_within_at.limsup_slope_le (hf : has_deriv_within_at f f' s x) (hr : f' < r) :
∀ᶠ z in 𝓝[s \ {x}] x, (z - x)⁻¹ * (f z - f x) < r :=
has_deriv_within_at_iff_tendsto_slope.1 hf (mem_nhds_sets is_open_Iio hr)
lemma has_deriv_within_at.limsup_slope_le' (hf : has_deriv_within_at f f' s x)
(hs : x ∉ s) (hr : f' < r) :
∀ᶠ z in 𝓝[s] x, (z - x)⁻¹ * (f z - f x) < r :=
(has_deriv_within_at_iff_tendsto_slope' hs).1 hf (mem_nhds_sets is_open_Iio hr)
lemma has_deriv_within_at.liminf_right_slope_le
(hf : has_deriv_within_at f f' (Ici x) x) (hr : f' < r) :
∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (f z - f x) < r :=
(hf.Ioi_of_Ici.limsup_slope_le' (lt_irrefl x) hr).frequently
end real
section real_space
open metric
variables {E : Type u} [normed_group E] [normed_space ℝ E] {f : ℝ → E} {f' : E} {s : set ℝ}
{x r : ℝ}
/-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio
`∥f z - f x∥ / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`.
In other words, the limit superior of this ratio as `z` tends to `x` along `s`
is less than or equal to `∥f'∥`. -/
lemma has_deriv_within_at.limsup_norm_slope_le
(hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) :
∀ᶠ z in 𝓝[s] x, ∥z - x∥⁻¹ * ∥f z - f x∥ < r :=
begin
have hr₀ : 0 < r, from lt_of_le_of_lt (norm_nonneg f') hr,
have A : ∀ᶠ z in 𝓝[s \ {x}] x, ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r,
from (has_deriv_within_at_iff_tendsto_slope.1 hf).norm (mem_nhds_sets is_open_Iio hr),
have B : ∀ᶠ z in 𝓝[{x}] x, ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r,
from mem_sets_of_superset self_mem_nhds_within
(singleton_subset_iff.2 $ by simp [hr₀]),
have C := mem_sup_sets.2 ⟨A, B⟩,
rw [← nhds_within_union, diff_union_self, nhds_within_union, mem_sup_sets] at C,
filter_upwards [C.1],
simp only [norm_smul, mem_Iio, normed_field.norm_inv],
exact λ _, id
end
/-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio
`(∥f z∥ - ∥f x∥) / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`.
In other words, the limit superior of this ratio as `z` tends to `x` along `s`
is less than or equal to `∥f'∥`.
This lemma is a weaker version of `has_deriv_within_at.limsup_norm_slope_le`
where `∥f z∥ - ∥f x∥` is replaced by `∥f z - f x∥`. -/
lemma has_deriv_within_at.limsup_slope_norm_le
(hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) :
∀ᶠ z in 𝓝[s] x, ∥z - x∥⁻¹ * (∥f z∥ - ∥f x∥) < r :=
begin
apply (hf.limsup_norm_slope_le hr).mono,
assume z hz,
refine lt_of_le_of_lt (mul_le_mul_of_nonneg_left (norm_sub_norm_le _ _) _) hz,
exact inv_nonneg.2 (norm_nonneg _)
end
/-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio
`∥f z - f x∥ / ∥z - x∥` is frequently less than `r` as `z → x+0`.
In other words, the limit inferior of this ratio as `z` tends to `x+0`
is less than or equal to `∥f'∥`. See also `has_deriv_within_at.limsup_norm_slope_le`
for a stronger version using limit superior and any set `s`. -/
lemma has_deriv_within_at.liminf_right_norm_slope_le
(hf : has_deriv_within_at f f' (Ici x) x) (hr : ∥f'∥ < r) :
∃ᶠ z in 𝓝[Ioi x] x, ∥z - x∥⁻¹ * ∥f z - f x∥ < r :=
(hf.Ioi_of_Ici.limsup_norm_slope_le hr).frequently
/-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio
`(∥f z∥ - ∥f x∥) / (z - x)` is frequently less than `r` as `z → x+0`.
In other words, the limit inferior of this ratio as `z` tends to `x+0`
is less than or equal to `∥f'∥`.
See also
* `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using
limit superior and any set `s`;
* `has_deriv_within_at.liminf_right_norm_slope_le` for a stronger version using
`∥f z - f x∥` instead of `∥f z∥ - ∥f x∥`. -/
lemma has_deriv_within_at.liminf_right_slope_norm_le
(hf : has_deriv_within_at f f' (Ici x) x) (hr : ∥f'∥ < r) :
∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (∥f z∥ - ∥f x∥) < r :=
begin
have := (hf.Ioi_of_Ici.limsup_slope_norm_le hr).frequently,
refine this.mp (eventually.mono self_mem_nhds_within _),
assume z hxz hz,
rwa [real.norm_eq_abs, abs_of_pos (sub_pos_of_lt hxz)] at hz
end
end real_space
|
2c5b2cd00361d1f189ddaeb71ed32e66d998ea8a | 77c5b91fae1b966ddd1db969ba37b6f0e4901e88 | /src/data/zmod/basic.lean | d97578ef65e46af98e1dd957c65bce84156bd726 | [
"Apache-2.0"
] | permissive | dexmagic/mathlib | ff48eefc56e2412429b31d4fddd41a976eb287ce | 7a5d15a955a92a90e1d398b2281916b9c41270b2 | refs/heads/master | 1,693,481,322,046 | 1,633,360,193,000 | 1,633,360,193,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 32,233 | 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 algebra.char_p.basic
import ring_theory.ideal.operations
import tactic.fin_cases
/-!
# Integers mod `n`
Definition of the integers mod n, and the field structure on the integers mod p.
## Definitions
* `zmod n`, which is for integers modulo a nat `n : ℕ`
* `val a` is defined as a natural number:
- for `a : zmod 0` it is the absolute value of `a`
- for `a : zmod n` with `0 < n` it is the least natural number in the equivalence class
* `val_min_abs` returns the integer closest to zero in the equivalence class.
* A coercion `cast` is defined from `zmod n` into any ring.
This is a ring hom if the ring has characteristic dividing `n`
-/
namespace fin
/-!
## Ring structure on `fin n`
We define a commutative ring structure on `fin n`, but we do not register it as instance.
Afterwords, when we define `zmod n` in terms of `fin n`, we use these definitions
to register the ring structure on `zmod n` as type class instance.
-/
open nat.modeq int
/-- Multiplicative commutative semigroup structure on `fin (n+1)`. -/
instance (n : ℕ) : comm_semigroup (fin (n+1)) :=
{ mul_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq
(calc ((a * b) % (n+1) * c) ≡ a * b * c [MOD (n+1)] : (nat.mod_modeq _ _).mul_right _
... ≡ a * (b * c) [MOD (n+1)] : by rw mul_assoc
... ≡ a * (b * c % (n+1)) [MOD (n+1)] : (nat.mod_modeq _ _).symm.mul_left _),
mul_comm := λ ⟨a, _⟩ ⟨b, _⟩,
fin.eq_of_veq (show (a * b) % (n+1) = (b * a) % (n+1), by rw mul_comm),
..fin.has_mul }
private lemma left_distrib_aux (n : ℕ) : ∀ a b c : fin (n+1), a * (b + c) = a * b + a * c :=
λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq
(calc a * ((b + c) % (n+1)) ≡ a * (b + c) [MOD (n+1)] : (nat.mod_modeq _ _).mul_left _
... ≡ a * b + a * c [MOD (n+1)] : by rw mul_add
... ≡ (a * b) % (n+1) + (a * c) % (n+1) [MOD (n+1)] :
(nat.mod_modeq _ _).symm.add (nat.mod_modeq _ _).symm)
/-- Commutative ring structure on `fin (n+1)`. -/
instance (n : ℕ) : comm_ring (fin (n+1)) :=
{ one_mul := fin.one_mul,
mul_one := fin.mul_one,
left_distrib := left_distrib_aux n,
right_distrib := λ a b c, by rw [mul_comm, left_distrib_aux, mul_comm _ b, mul_comm]; refl,
..fin.has_one,
..fin.add_comm_group n,
..fin.comm_semigroup n }
end fin
/-- The integers modulo `n : ℕ`. -/
def zmod : ℕ → Type
| 0 := ℤ
| (n+1) := fin (n+1)
namespace zmod
instance fintype : Π (n : ℕ) [fact (0 < n)], fintype (zmod n)
| 0 h := false.elim $ nat.not_lt_zero 0 h.1
| (n+1) _ := fin.fintype (n+1)
@[simp] lemma card (n : ℕ) [fact (0 < n)] : fintype.card (zmod n) = n :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 (fact.out _) },
{ exact fintype.card_fin (n+1) }
end
instance decidable_eq : Π (n : ℕ), decidable_eq (zmod n)
| 0 := int.decidable_eq
| (n+1) := fin.decidable_eq _
instance has_repr : Π (n : ℕ), has_repr (zmod n)
| 0 := int.has_repr
| (n+1) := fin.has_repr _
instance comm_ring : Π (n : ℕ), comm_ring (zmod n)
| 0 := int.comm_ring
| (n+1) := fin.comm_ring n
instance inhabited (n : ℕ) : inhabited (zmod n) := ⟨0⟩
/-- `val a` is a natural number defined as:
- for `a : zmod 0` it is the absolute value of `a`
- for `a : zmod n` with `0 < n` it is the least natural number in the equivalence class
See `zmod.val_min_abs` for a variant that takes values in the integers.
-/
def val : Π {n : ℕ}, zmod n → ℕ
| 0 := int.nat_abs
| (n+1) := (coe : fin (n + 1) → ℕ)
lemma val_lt {n : ℕ} [fact (0 < n)] (a : zmod n) : a.val < n :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 (fact.out _) },
exact fin.is_lt a
end
lemma val_le {n : ℕ} [fact (0 < n)] (a : zmod n) : a.val ≤ n :=
a.val_lt.le
@[simp] lemma val_zero : ∀ {n}, (0 : zmod n).val = 0
| 0 := rfl
| (n+1) := rfl
@[simp] lemma val_one' : (1 : zmod 0).val = 1 := rfl
@[simp] lemma val_neg' {n : zmod 0} : (-n).val = n.val := by simp [val]
@[simp] lemma val_mul' {m n : zmod 0} : (m * n).val = m.val * n.val :=
by simp [val, int.nat_abs_mul]
lemma val_nat_cast {n : ℕ} (a : ℕ) : (a : zmod n).val = a % n :=
begin
casesI n,
{ rw [nat.mod_zero, int.nat_cast_eq_coe_nat],
exact int.nat_abs_of_nat a, },
rw ← fin.of_nat_eq_coe,
refl
end
instance (n : ℕ) : char_p (zmod n) n :=
{ cast_eq_zero_iff :=
begin
intro k,
cases n,
{ simp only [int.nat_cast_eq_coe_nat, zero_dvd_iff, int.coe_nat_eq_zero], },
rw [fin.eq_iff_veq],
show (k : zmod (n+1)).val = (0 : zmod (n+1)).val ↔ _,
rw [val_nat_cast, val_zero, nat.dvd_iff_mod_eq_zero],
end }
@[simp] lemma nat_cast_self (n : ℕ) : (n : zmod n) = 0 :=
char_p.cast_eq_zero (zmod n) n
@[simp] lemma nat_cast_self' (n : ℕ) : (n + 1 : zmod (n + 1)) = 0 :=
by rw [← nat.cast_add_one, nat_cast_self (n + 1)]
section universal_property
variables {n : ℕ} {R : Type*}
section
variables [has_zero R] [has_one R] [has_add R] [has_neg R]
/-- Cast an integer modulo `n` to another semiring.
This function is a morphism if the characteristic of `R` divides `n`.
See `zmod.cast_hom` for a bundled version. -/
def cast : Π {n : ℕ}, zmod n → R
| 0 := int.cast
| (n+1) := λ i, i.val
-- see Note [coercion into rings]
@[priority 900] instance (n : ℕ) : has_coe_t (zmod n) R := ⟨cast⟩
@[simp] lemma cast_zero : ((0 : zmod n) : R) = 0 :=
by { cases n; refl }
variables {S : Type*} [has_zero S] [has_one S] [has_add S] [has_neg S]
@[simp] lemma _root_.prod.fst_zmod_cast (a : zmod n) : (a : R × S).fst = a :=
by cases n; simp
@[simp] lemma _root_.prod.snd_zmod_cast (a : zmod n) : (a : R × S).snd = a :=
by cases n; simp
end
/-- So-named because the coercion is `nat.cast` into `zmod`. For `nat.cast` into an arbitrary ring,
see `zmod.nat_cast_val`. -/
lemma nat_cast_zmod_val {n : ℕ} [fact (0 < n)] (a : zmod n) : (a.val : zmod n) = a :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 (fact.out _) },
{ apply fin.coe_coe_eq_self }
end
lemma nat_cast_right_inverse [fact (0 < n)] : function.right_inverse val (coe : ℕ → zmod n) :=
nat_cast_zmod_val
lemma nat_cast_zmod_surjective [fact (0 < n)] : function.surjective (coe : ℕ → zmod n) :=
nat_cast_right_inverse.surjective
/-- So-named because the outer coercion is `int.cast` into `zmod`. For `int.cast` into an arbitrary
ring, see `zmod.int_cast_cast`. -/
lemma int_cast_zmod_cast (a : zmod n) : ((a : ℤ) : zmod n) = a :=
begin
cases n,
{ rw [int.cast_id a, int.cast_id a], },
{ rw [coe_coe, int.nat_cast_eq_coe_nat, int.cast_coe_nat, fin.coe_coe_eq_self] }
end
lemma int_cast_right_inverse : function.right_inverse (coe : zmod n → ℤ) (coe : ℤ → zmod n) :=
int_cast_zmod_cast
lemma int_cast_surjective : function.surjective (coe : ℤ → zmod n) :=
int_cast_right_inverse.surjective
@[norm_cast]
lemma cast_id : ∀ n (i : zmod n), ↑i = i
| 0 i := int.cast_id i
| (n+1) i := nat_cast_zmod_val i
@[simp]
lemma cast_id' : (coe : zmod n → zmod n) = id := funext (cast_id n)
variables (R) [ring R]
/-- The coercions are respectively `nat.cast` and `zmod.cast`. -/
@[simp] lemma nat_cast_comp_val [fact (0 < n)] :
(coe : ℕ → R) ∘ (val : zmod n → ℕ) = coe :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 (fact.out _) },
refl
end
/-- The coercions are respectively `int.cast`, `zmod.cast`, and `zmod.cast`. -/
@[simp] lemma int_cast_comp_cast : (coe : ℤ → R) ∘ (coe : zmod n → ℤ) = coe :=
begin
cases n,
{ exact congr_arg ((∘) int.cast) zmod.cast_id', },
{ ext, simp }
end
variables {R}
@[simp] lemma nat_cast_val [fact (0 < n)] (i : zmod n) : (i.val : R) = i :=
congr_fun (nat_cast_comp_val R) i
@[simp] lemma int_cast_cast (i : zmod n) : ((i : ℤ) : R) = i :=
congr_fun (int_cast_comp_cast R) i
lemma coe_add_eq_ite {n : ℕ} (a b : zmod n) :
(↑(a + b) : ℤ) = if (n : ℤ) ≤ a + b then a + b - n else a + b :=
begin
cases n,
{ simp },
simp only [coe_coe, fin.coe_add_eq_ite, int.nat_cast_eq_coe_nat,
← int.coe_nat_add, ← int.coe_nat_succ, int.coe_nat_le],
split_ifs with h,
{ exact int.coe_nat_sub h },
{ refl }
end
section char_dvd
/-! If the characteristic of `R` divides `n`, then `cast` is a homomorphism. -/
variables {n} {m : ℕ} [char_p R m]
@[simp] lemma cast_one (h : m ∣ n) : ((1 : zmod n) : R) = 1 :=
begin
casesI n,
{ exact int.cast_one },
show ((1 % (n+1) : ℕ) : R) = 1,
cases n, { rw [nat.dvd_one] at h, substI m, apply subsingleton.elim },
rw nat.mod_eq_of_lt,
{ exact nat.cast_one },
exact nat.lt_of_sub_eq_succ rfl
end
lemma cast_add (h : m ∣ n) (a b : zmod n) : ((a + b : zmod n) : R) = a + b :=
begin
casesI n,
{ apply int.cast_add },
simp only [coe_coe],
symmetry,
erw [fin.coe_add, ← nat.cast_add, ← sub_eq_zero, ← nat.cast_sub (nat.mod_le _ _),
@char_p.cast_eq_zero_iff R _ _ m],
exact h.trans (nat.dvd_sub_mod _),
end
lemma cast_mul (h : m ∣ n) (a b : zmod n) : ((a * b : zmod n) : R) = a * b :=
begin
casesI n,
{ apply int.cast_mul },
simp only [coe_coe],
symmetry,
erw [fin.coe_mul, ← nat.cast_mul, ← sub_eq_zero, ← nat.cast_sub (nat.mod_le _ _),
@char_p.cast_eq_zero_iff R _ _ m],
exact h.trans (nat.dvd_sub_mod _),
end
/-- The canonical ring homomorphism from `zmod n` to a ring of characteristic `n`.
See also `zmod.lift` (in `data.zmod.quotient`) for a generalized version working in `add_group`s.
-/
def cast_hom (h : m ∣ n) (R : Type*) [ring R] [char_p R m] : zmod n →+* R :=
{ to_fun := coe,
map_zero' := cast_zero,
map_one' := cast_one h,
map_add' := cast_add h,
map_mul' := cast_mul h }
@[simp] lemma cast_hom_apply {h : m ∣ n} (i : zmod n) : cast_hom h R i = i := rfl
@[simp, norm_cast]
lemma cast_sub (h : m ∣ n) (a b : zmod n) : ((a - b : zmod n) : R) = a - b :=
(cast_hom h R).map_sub a b
@[simp, norm_cast]
lemma cast_neg (h : m ∣ n) (a : zmod n) : ((-a : zmod n) : R) = -a :=
(cast_hom h R).map_neg a
@[simp, norm_cast]
lemma cast_pow (h : m ∣ n) (a : zmod n) (k : ℕ) : ((a ^ k : zmod n) : R) = a ^ k :=
(cast_hom h R).map_pow a k
@[simp, norm_cast]
lemma cast_nat_cast (h : m ∣ n) (k : ℕ) : ((k : zmod n) : R) = k :=
(cast_hom h R).map_nat_cast k
@[simp, norm_cast]
lemma cast_int_cast (h : m ∣ n) (k : ℤ) : ((k : zmod n) : R) = k :=
(cast_hom h R).map_int_cast k
end char_dvd
section char_eq
/-! Some specialised simp lemmas which apply when `R` has characteristic `n`. -/
variable [char_p R n]
@[simp] lemma cast_one' : ((1 : zmod n) : R) = 1 :=
cast_one dvd_rfl
@[simp] lemma cast_add' (a b : zmod n) : ((a + b : zmod n) : R) = a + b :=
cast_add dvd_rfl a b
@[simp] lemma cast_mul' (a b : zmod n) : ((a * b : zmod n) : R) = a * b :=
cast_mul dvd_rfl a b
@[simp] lemma cast_sub' (a b : zmod n) : ((a - b : zmod n) : R) = a - b :=
cast_sub dvd_rfl a b
@[simp] lemma cast_pow' (a : zmod n) (k : ℕ) : ((a ^ k : zmod n) : R) = a ^ k :=
cast_pow dvd_rfl a k
@[simp, norm_cast]
lemma cast_nat_cast' (k : ℕ) : ((k : zmod n) : R) = k :=
cast_nat_cast dvd_rfl k
@[simp, norm_cast]
lemma cast_int_cast' (k : ℤ) : ((k : zmod n) : R) = k :=
cast_int_cast dvd_rfl k
variables (R)
lemma cast_hom_injective : function.injective (zmod.cast_hom (dvd_refl n) R) :=
begin
rw ring_hom.injective_iff,
intro x,
obtain ⟨k, rfl⟩ := zmod.int_cast_surjective x,
rw [ring_hom.map_int_cast, char_p.int_cast_eq_zero_iff R n,
char_p.int_cast_eq_zero_iff (zmod n) n],
exact id
end
lemma cast_hom_bijective [fintype R] (h : fintype.card R = n) :
function.bijective (zmod.cast_hom (dvd_refl n) R) :=
begin
haveI : fact (0 < n) :=
⟨begin
rw [pos_iff_ne_zero],
intro hn,
rw hn at h,
exact (fintype.card_eq_zero_iff.mp h).elim' 0
end⟩,
rw [fintype.bijective_iff_injective_and_card, zmod.card, h, eq_self_iff_true, and_true],
apply zmod.cast_hom_injective
end
/-- The unique ring isomorphism between `zmod n` and a ring `R`
of characteristic `n` and cardinality `n`. -/
noncomputable def ring_equiv [fintype R] (h : fintype.card R = n) : zmod n ≃+* R :=
ring_equiv.of_bijective _ (zmod.cast_hom_bijective R h)
end char_eq
end universal_property
lemma int_coe_eq_int_coe_iff (a b : ℤ) (c : ℕ) :
(a : zmod c) = (b : zmod c) ↔ a ≡ b [ZMOD c] :=
char_p.int_coe_eq_int_coe_iff (zmod c) c a b
lemma int_coe_eq_int_coe_iff' (a b : ℤ) (c : ℕ) :
(a : zmod c) = (b : zmod c) ↔ a % c = b % c :=
zmod.int_coe_eq_int_coe_iff a b c
lemma nat_coe_eq_nat_coe_iff (a b c : ℕ) :
(a : zmod c) = (b : zmod c) ↔ a ≡ b [MOD c] :=
begin
convert zmod.int_coe_eq_int_coe_iff a b c,
simp [nat.modeq_iff_dvd, int.modeq_iff_dvd],
end
lemma int_coe_zmod_eq_zero_iff_dvd (a : ℤ) (b : ℕ) : (a : zmod b) = 0 ↔ (b : ℤ) ∣ a :=
begin
change (a : zmod b) = ((0 : ℤ) : zmod b) ↔ (b : ℤ) ∣ a,
rw [zmod.int_coe_eq_int_coe_iff, int.modeq_zero_iff_dvd],
end
lemma nat_coe_zmod_eq_zero_iff_dvd (a b : ℕ) : (a : zmod b) = 0 ↔ b ∣ a :=
begin
change (a : zmod b) = ((0 : ℕ) : zmod b) ↔ b ∣ a,
rw [zmod.nat_coe_eq_nat_coe_iff, nat.modeq_zero_iff_dvd],
end
@[push_cast, simp]
lemma int_cast_mod (a : ℤ) (b : ℕ) : ((a % b : ℤ) : zmod b) = (a : zmod b) :=
begin
rw zmod.int_coe_eq_int_coe_iff,
apply int.mod_modeq,
end
lemma ker_int_cast_add_hom (n : ℕ) :
(int.cast_add_hom (zmod n)).ker = add_subgroup.gmultiples n :=
by { ext, rw [int.mem_gmultiples_iff, add_monoid_hom.mem_ker,
int.coe_cast_add_hom, int_coe_zmod_eq_zero_iff_dvd] }
lemma ker_int_cast_ring_hom (n : ℕ) :
(int.cast_ring_hom (zmod n)).ker = ideal.span ({n} : set ℤ) :=
by { ext, rw [ideal.mem_span_singleton, ring_hom.mem_ker,
int.coe_cast_ring_hom, int_coe_zmod_eq_zero_iff_dvd] }
local attribute [semireducible] int.nonneg
@[simp] lemma nat_cast_to_nat (p : ℕ) :
∀ {z : ℤ} (h : 0 ≤ z), (z.to_nat : zmod p) = z
| (n : ℕ) h := by simp only [int.cast_coe_nat, int.to_nat_coe_nat]
| -[1+n] h := false.elim h
lemma val_injective (n : ℕ) [fact (0 < n)] :
function.injective (zmod.val : zmod n → ℕ) :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 (fact.out _) },
assume a b h,
ext,
exact h
end
lemma val_one_eq_one_mod (n : ℕ) : (1 : zmod n).val = 1 % n :=
by rw [← nat.cast_one, val_nat_cast]
lemma val_one (n : ℕ) [fact (1 < n)] : (1 : zmod n).val = 1 :=
by { rw val_one_eq_one_mod, exact nat.mod_eq_of_lt (fact.out _) }
lemma val_add {n : ℕ} [fact (0 < n)] (a b : zmod n) : (a + b).val = (a.val + b.val) % n :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 (fact.out _) },
{ apply fin.val_add }
end
lemma val_mul {n : ℕ} (a b : zmod n) : (a * b).val = (a.val * b.val) % n :=
begin
cases n,
{ rw nat.mod_zero, apply int.nat_abs_mul },
{ apply fin.val_mul }
end
instance nontrivial (n : ℕ) [fact (1 < n)] : nontrivial (zmod n) :=
⟨⟨0, 1, assume h, zero_ne_one $
calc 0 = (0 : zmod n).val : by rw val_zero
... = (1 : zmod n).val : congr_arg zmod.val h
... = 1 : val_one n ⟩⟩
/-- The inversion on `zmod n`.
It is setup in such a way that `a * a⁻¹` is equal to `gcd a.val n`.
In particular, if `a` is coprime to `n`, and hence a unit, `a * a⁻¹ = 1`. -/
def inv : Π (n : ℕ), zmod n → zmod n
| 0 i := int.sign i
| (n+1) i := nat.gcd_a i.val (n+1)
instance (n : ℕ) : has_inv (zmod n) := ⟨inv n⟩
lemma inv_zero : ∀ (n : ℕ), (0 : zmod n)⁻¹ = 0
| 0 := int.sign_zero
| (n+1) := show (nat.gcd_a _ (n+1) : zmod (n+1)) = 0,
by { rw val_zero, unfold nat.gcd_a nat.xgcd nat.xgcd_aux, refl }
lemma mul_inv_eq_gcd {n : ℕ} (a : zmod n) :
a * a⁻¹ = nat.gcd a.val n :=
begin
cases n,
{ calc a * a⁻¹ = a * int.sign a : rfl
... = a.nat_abs : by rw [int.mul_sign, int.nat_cast_eq_coe_nat]
... = a.val.gcd 0 : by rw nat.gcd_zero_right; refl },
{ set k := n.succ,
calc a * a⁻¹ = a * a⁻¹ + k * nat.gcd_b (val a) k : by rw [nat_cast_self, zero_mul, add_zero]
... = ↑(↑a.val * nat.gcd_a (val a) k + k * nat.gcd_b (val a) k) :
by { push_cast, rw nat_cast_zmod_val, refl }
... = nat.gcd a.val k : (congr_arg coe (nat.gcd_eq_gcd_ab a.val k)).symm, }
end
@[simp] lemma nat_cast_mod (n : ℕ) (a : ℕ) : ((a % n : ℕ) : zmod n) = a :=
by conv {to_rhs, rw ← nat.mod_add_div a n}; simp
lemma eq_iff_modeq_nat (n : ℕ) {a b : ℕ} : (a : zmod n) = b ↔ a ≡ b [MOD n] :=
begin
cases n,
{ simp only [nat.modeq, int.coe_nat_inj', nat.mod_zero, int.nat_cast_eq_coe_nat], },
{ rw [fin.ext_iff, nat.modeq, ← val_nat_cast, ← val_nat_cast], exact iff.rfl, }
end
lemma coe_mul_inv_eq_one {n : ℕ} (x : ℕ) (h : nat.coprime x n) :
(x * x⁻¹ : zmod n) = 1 :=
begin
rw [nat.coprime, nat.gcd_comm, nat.gcd_rec] at h,
rw [mul_inv_eq_gcd, val_nat_cast, h, nat.cast_one],
end
/-- `unit_of_coprime` makes an element of `units (zmod n)` given
a natural number `x` and a proof that `x` is coprime to `n` -/
def unit_of_coprime {n : ℕ} (x : ℕ) (h : nat.coprime x n) : units (zmod n) :=
⟨x, x⁻¹, coe_mul_inv_eq_one x h, by rw [mul_comm, coe_mul_inv_eq_one x h]⟩
@[simp] lemma coe_unit_of_coprime {n : ℕ} (x : ℕ) (h : nat.coprime x n) :
(unit_of_coprime x h : zmod n) = x := rfl
lemma val_coe_unit_coprime {n : ℕ} (u : units (zmod n)) :
nat.coprime (u : zmod n).val n :=
begin
cases n,
{ rcases int.units_eq_one_or u with rfl|rfl; simp },
apply nat.coprime_of_mul_modeq_one ((u⁻¹ : units (zmod (n+1))) : zmod (n+1)).val,
have := units.ext_iff.1 (mul_right_inv u),
rw [units.coe_one] at this,
rw [← eq_iff_modeq_nat, nat.cast_one, ← this], clear this,
rw [← nat_cast_zmod_val ((u * u⁻¹ : units (zmod (n+1))) : zmod (n+1))],
rw [units.coe_mul, val_mul, nat_cast_mod],
end
@[simp] lemma inv_coe_unit {n : ℕ} (u : units (zmod n)) :
(u : zmod n)⁻¹ = (u⁻¹ : units (zmod n)) :=
begin
have := congr_arg (coe : ℕ → zmod n) (val_coe_unit_coprime u),
rw [← mul_inv_eq_gcd, nat.cast_one] at this,
let u' : units (zmod n) := ⟨u, (u : zmod n)⁻¹, this, by rwa mul_comm⟩,
have h : u = u', { apply units.ext, refl },
rw h,
refl
end
lemma mul_inv_of_unit {n : ℕ} (a : zmod n) (h : is_unit a) :
a * a⁻¹ = 1 :=
begin
rcases h with ⟨u, rfl⟩,
rw [inv_coe_unit, u.mul_inv],
end
lemma inv_mul_of_unit {n : ℕ} (a : zmod n) (h : is_unit a) :
a⁻¹ * a = 1 :=
by rw [mul_comm, mul_inv_of_unit a h]
/-- Equivalence between the units of `zmod n` and
the subtype of terms `x : zmod n` for which `x.val` is comprime to `n` -/
def units_equiv_coprime {n : ℕ} [fact (0 < n)] :
units (zmod n) ≃ {x : zmod n // nat.coprime x.val n} :=
{ to_fun := λ x, ⟨x, val_coe_unit_coprime x⟩,
inv_fun := λ x, unit_of_coprime x.1.val x.2,
left_inv := λ ⟨_, _, _, _⟩, units.ext (nat_cast_zmod_val _),
right_inv := λ ⟨_, _⟩, by simp }
/-- The **Chinese remainder theorem**. For a pair of coprime natural numbers, `m` and `n`,
the rings `zmod (m * n)` and `zmod m × zmod n` are isomorphic.
See `ideal.quotient_inf_ring_equiv_pi_quotient` for the Chinese remainder theorem for ideals in any
ring.
-/
def chinese_remainder {m n : ℕ} (h : m.coprime n) :
zmod (m * n) ≃+* zmod m × zmod n :=
let to_fun : zmod (m * n) → zmod m × zmod n :=
zmod.cast_hom (show m.lcm n ∣ m * n, by simp [nat.lcm_dvd_iff]) (zmod m × zmod n) in
let inv_fun : zmod m × zmod n → zmod (m * n) :=
λ x, if m * n = 0
then if m = 1
then ring_hom.snd _ _ x
else ring_hom.fst _ _ x
else nat.chinese_remainder h x.1.val x.2.val in
have inv : function.left_inverse inv_fun to_fun ∧ function.right_inverse inv_fun to_fun :=
if hmn0 : m * n = 0
then begin
rcases h.eq_of_mul_eq_zero hmn0 with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩;
simp [inv_fun, to_fun, function.left_inverse, function.right_inverse,
ring_hom.eq_int_cast, prod.ext_iff]
end
else
begin
haveI : fact (0 < (m * n)) := ⟨nat.pos_of_ne_zero hmn0⟩,
haveI : fact (0 < m) := ⟨nat.pos_of_ne_zero $ left_ne_zero_of_mul hmn0⟩,
haveI : fact (0 < n) := ⟨nat.pos_of_ne_zero $ right_ne_zero_of_mul hmn0⟩,
have left_inv : function.left_inverse inv_fun to_fun,
{ intro x,
dsimp only [dvd_mul_left, dvd_mul_right, zmod.cast_hom_apply, coe_coe, inv_fun, to_fun],
conv_rhs { rw ← zmod.nat_cast_zmod_val x },
rw [if_neg hmn0, zmod.eq_iff_modeq_nat, ← nat.modeq_and_modeq_iff_modeq_mul h,
prod.fst_zmod_cast, prod.snd_zmod_cast],
refine
⟨(nat.chinese_remainder h (x : zmod m).val (x : zmod n).val).2.left.trans _,
(nat.chinese_remainder h (x : zmod m).val (x : zmod n).val).2.right.trans _⟩,
{ rw [← zmod.eq_iff_modeq_nat, zmod.nat_cast_zmod_val, zmod.nat_cast_val] },
{ rw [← zmod.eq_iff_modeq_nat, zmod.nat_cast_zmod_val, zmod.nat_cast_val] } },
exact ⟨left_inv, fintype.right_inverse_of_left_inverse_of_card_le left_inv (by simp)⟩,
end,
{ to_fun := to_fun,
inv_fun := inv_fun,
map_mul' := ring_hom.map_mul _,
map_add' := ring_hom.map_add _,
left_inv := inv.1,
right_inv := inv.2 }
instance subsingleton_units : subsingleton (units (zmod 2)) :=
⟨λ x y, begin
ext1,
cases x with x xi hx1 hx2,
cases y with y yi hy1 hy2,
revert hx1 hx2 hy1 hy2,
fin_cases x; fin_cases y; simp
end⟩
lemma le_div_two_iff_lt_neg (n : ℕ) [hn : fact ((n : ℕ) % 2 = 1)]
{x : zmod n} (hx0 : x ≠ 0) : x.val ≤ (n / 2 : ℕ) ↔ (n / 2 : ℕ) < (-x).val :=
begin
haveI npos : fact (0 < n) := ⟨by
{ apply (nat.eq_zero_or_pos n).resolve_left,
unfreezingI { rintro rfl },
simpa [fact_iff] using hn, }⟩,
have hn2 : (n : ℕ) / 2 < n := nat.div_lt_of_lt_mul
((lt_mul_iff_one_lt_left npos.1).2 dec_trivial),
have hn2' : (n : ℕ) - n / 2 = n / 2 + 1,
{ conv {to_lhs, congr, rw [← nat.succ_sub_one n, nat.succ_sub npos.1]},
rw [← nat.two_mul_odd_div_two hn.1, two_mul, ← nat.succ_add, nat.add_sub_cancel], },
have hxn : (n : ℕ) - x.val < n,
{ rw [nat.sub_lt_iff x.val_le le_rfl, nat.sub_self],
rw ← zmod.nat_cast_zmod_val x at hx0,
exact nat.pos_of_ne_zero (λ h, by simpa [h] using hx0) },
by conv {to_rhs, rw [← nat.succ_le_iff, nat.succ_eq_add_one, ← hn2', ← zero_add (- x),
← zmod.nat_cast_self, ← sub_eq_add_neg, ← zmod.nat_cast_zmod_val x,
← nat.cast_sub x.val_le,
zmod.val_nat_cast, nat.mod_eq_of_lt hxn, nat.sub_le_sub_left_iff x.val_le] }
end
lemma ne_neg_self (n : ℕ) [hn : fact ((n : ℕ) % 2 = 1)] {a : zmod n} (ha : a ≠ 0) : a ≠ -a :=
λ h, have a.val ≤ n / 2 ↔ (n : ℕ) / 2 < (-a).val := le_div_two_iff_lt_neg n ha,
by rwa [← h, ← not_lt, not_iff_self] at this
lemma neg_one_ne_one {n : ℕ} [fact (2 < n)] :
(-1 : zmod n) ≠ 1 :=
char_p.neg_one_ne_one (zmod n) n
@[simp] lemma neg_eq_self_mod_two (a : zmod 2) : -a = a :=
by fin_cases a; ext; simp [fin.coe_neg, int.nat_mod]; norm_num
@[simp] lemma nat_abs_mod_two (a : ℤ) : (a.nat_abs : zmod 2) = a :=
begin
cases a,
{ simp only [int.nat_abs_of_nat, int.cast_coe_nat, int.of_nat_eq_coe] },
{ simp only [neg_eq_self_mod_two, nat.cast_succ, int.nat_abs, int.cast_neg_succ_of_nat] }
end
@[simp] lemma val_eq_zero : ∀ {n : ℕ} (a : zmod n), a.val = 0 ↔ a = 0
| 0 a := int.nat_abs_eq_zero
| (n+1) a := by { rw fin.ext_iff, exact iff.rfl }
lemma val_cast_of_lt {n : ℕ} {a : ℕ} (h : a < n) : (a : zmod n).val = a :=
by rw [val_nat_cast, nat.mod_eq_of_lt h]
lemma neg_val' {n : ℕ} [fact (0 < n)] (a : zmod n) : (-a).val = (n - a.val) % n :=
calc (-a).val = val (-a) % n : by rw nat.mod_eq_of_lt ((-a).val_lt)
... = (n - val a) % n : nat.modeq.add_right_cancel' _ (by rw [nat.modeq, ←val_add,
add_left_neg, nat.sub_add_cancel a.val_le, nat.mod_self, val_zero])
lemma neg_val {n : ℕ} [fact (0 < n)] (a : zmod n) : (-a).val = if a = 0 then 0 else n - a.val :=
begin
rw neg_val',
by_cases h : a = 0, { rw [if_pos h, h, val_zero, nat.sub_zero, nat.mod_self] },
rw if_neg h,
apply nat.mod_eq_of_lt,
apply nat.sub_lt (fact.out (0 < n)),
contrapose! h,
rwa [nat.le_zero_iff, val_eq_zero] at h,
end
/-- `val_min_abs x` returns the integer in the same equivalence class as `x` that is closest to `0`,
The result will be in the interval `(-n/2, n/2]`. -/
def val_min_abs : Π {n : ℕ}, zmod n → ℤ
| 0 x := x
| n@(_+1) x := if x.val ≤ n / 2 then x.val else (x.val : ℤ) - n
@[simp] lemma val_min_abs_def_zero (x : zmod 0) : val_min_abs x = x := rfl
lemma val_min_abs_def_pos {n : ℕ} [fact (0 < n)] (x : zmod n) :
val_min_abs x = if x.val ≤ n / 2 then x.val else x.val - n :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 (fact.out (0 < 0)) },
{ refl }
end
@[simp] lemma coe_val_min_abs : ∀ {n : ℕ} (x : zmod n), (x.val_min_abs : zmod n) = x
| 0 x := int.cast_id x
| k@(n+1) x :=
begin
rw val_min_abs_def_pos,
split_ifs,
{ rw [int.cast_coe_nat, nat_cast_zmod_val] },
{ rw [int.cast_sub, int.cast_coe_nat, nat_cast_zmod_val, int.cast_coe_nat, nat_cast_self,
sub_zero] }
end
lemma nat_abs_val_min_abs_le {n : ℕ} [fact (0 < n)] (x : zmod n) : x.val_min_abs.nat_abs ≤ n / 2 :=
begin
rw zmod.val_min_abs_def_pos,
split_ifs with h, { exact h },
have : (x.val - n : ℤ) ≤ 0,
{ rw [sub_nonpos, int.coe_nat_le], exact x.val_le, },
rw [← int.coe_nat_le, int.of_nat_nat_abs_of_nonpos this, neg_sub],
conv_lhs { congr, rw [← nat.mod_add_div n 2, int.coe_nat_add, int.coe_nat_mul,
int.coe_nat_bit0, int.coe_nat_one] },
suffices : ((n % 2 : ℕ) + (n / 2) : ℤ) ≤ (val x),
{ rw ← sub_nonneg at this ⊢, apply le_trans this (le_of_eq _), ring_nf, ring },
norm_cast,
calc (n : ℕ) % 2 + n / 2 ≤ 1 + n / 2 :
nat.add_le_add_right (nat.le_of_lt_succ (nat.mod_lt _ dec_trivial)) _
... ≤ x.val :
by { rw add_comm, exact nat.succ_le_of_lt (lt_of_not_ge h) }
end
@[simp] lemma val_min_abs_zero : ∀ n, (0 : zmod n).val_min_abs = 0
| 0 := by simp only [val_min_abs_def_zero]
| (n+1) := by simp only [val_min_abs_def_pos, if_true, int.coe_nat_zero, zero_le, val_zero]
@[simp] lemma val_min_abs_eq_zero {n : ℕ} (x : zmod n) :
x.val_min_abs = 0 ↔ x = 0 :=
begin
cases n, { simp },
split,
{ simp only [val_min_abs_def_pos, int.coe_nat_succ],
split_ifs with h h; assume h0,
{ apply val_injective, rwa [int.coe_nat_eq_zero] at h0, },
{ apply absurd h0, rw sub_eq_zero, apply ne_of_lt, exact_mod_cast x.val_lt } },
{ rintro rfl, rw val_min_abs_zero }
end
lemma nat_cast_nat_abs_val_min_abs {n : ℕ} [fact (0 < n)] (a : zmod n) :
(a.val_min_abs.nat_abs : zmod n) = if a.val ≤ (n : ℕ) / 2 then a else -a :=
begin
have : (a.val : ℤ) - n ≤ 0,
by { erw [sub_nonpos, int.coe_nat_le], exact a.val_le, },
rw [zmod.val_min_abs_def_pos],
split_ifs,
{ rw [int.nat_abs_of_nat, nat_cast_zmod_val] },
{ rw [← int.cast_coe_nat, int.of_nat_nat_abs_of_nonpos this, int.cast_neg, int.cast_sub],
rw [int.cast_coe_nat, int.cast_coe_nat, nat_cast_self, sub_zero, nat_cast_zmod_val], }
end
@[simp] lemma nat_abs_val_min_abs_neg {n : ℕ} (a : zmod n) :
(-a).val_min_abs.nat_abs = a.val_min_abs.nat_abs :=
begin
cases n, { simp only [int.nat_abs_neg, val_min_abs_def_zero], },
by_cases ha0 : a = 0, { rw [ha0, neg_zero] },
by_cases haa : -a = a, { rw [haa] },
suffices hpa : (n+1 : ℕ) - a.val ≤ (n+1) / 2 ↔ (n+1 : ℕ) / 2 < a.val,
{ rw [val_min_abs_def_pos, val_min_abs_def_pos],
rw ← not_le at hpa,
simp only [if_neg ha0, neg_val, hpa, int.coe_nat_sub a.val_le],
split_ifs,
all_goals { rw [← int.nat_abs_neg], congr' 1, ring } },
suffices : (((n+1 : ℕ) % 2) + 2 * ((n + 1) / 2)) - a.val ≤ (n+1) / 2 ↔ (n+1 : ℕ) / 2 < a.val,
by rwa [nat.mod_add_div] at this,
suffices : (n + 1) % 2 + (n + 1) / 2 ≤ val a ↔ (n + 1) / 2 < val a,
by rw [nat.sub_le_iff, two_mul, ← add_assoc, nat.add_sub_cancel, this],
cases (n + 1 : ℕ).mod_two_eq_zero_or_one with hn0 hn1,
{ split,
{ assume h,
apply lt_of_le_of_ne (le_trans (nat.le_add_left _ _) h),
contrapose! haa,
rw [← zmod.nat_cast_zmod_val a, ← haa, neg_eq_iff_add_eq_zero, ← nat.cast_add],
rw [char_p.cast_eq_zero_iff (zmod (n+1)) (n+1)],
rw [← two_mul, ← zero_add (2 * _), ← hn0, nat.mod_add_div] },
{ rw [hn0, zero_add], exact le_of_lt } },
{ rw [hn1, add_comm, nat.succ_le_iff] }
end
lemma val_eq_ite_val_min_abs {n : ℕ} [fact (0 < n)] (a : zmod n) :
(a.val : ℤ) = a.val_min_abs + if a.val ≤ n / 2 then 0 else n :=
by { rw [zmod.val_min_abs_def_pos], split_ifs; simp only [add_zero, sub_add_cancel] }
lemma prime_ne_zero (p q : ℕ) [hp : fact p.prime] [hq : fact q.prime] (hpq : p ≠ q) :
(q : zmod p) ≠ 0 :=
by rwa [← nat.cast_zero, ne.def, eq_iff_modeq_nat, nat.modeq_zero_iff_dvd,
← hp.1.coprime_iff_not_dvd, nat.coprime_primes hp.1 hq.1]
end zmod
namespace zmod
variables (p : ℕ) [fact p.prime]
private lemma mul_inv_cancel_aux (a : zmod p) (h : a ≠ 0) : a * a⁻¹ = 1 :=
begin
obtain ⟨k, rfl⟩ := nat_cast_zmod_surjective a,
apply coe_mul_inv_eq_one,
apply nat.coprime.symm,
rwa [nat.prime.coprime_iff_not_dvd (fact.out p.prime), ← char_p.cast_eq_zero_iff (zmod p)]
end
/-- Field structure on `zmod p` if `p` is prime. -/
instance : field (zmod p) :=
{ mul_inv_cancel := mul_inv_cancel_aux p,
inv_zero := inv_zero p,
.. zmod.comm_ring p,
.. zmod.has_inv p,
.. zmod.nontrivial p }
end zmod
lemma ring_hom.ext_zmod {n : ℕ} {R : Type*} [semiring R] (f g : (zmod n) →+* R) : f = g :=
begin
ext a,
obtain ⟨k, rfl⟩ := zmod.int_cast_surjective a,
let φ : ℤ →+* R := f.comp (int.cast_ring_hom (zmod n)),
let ψ : ℤ →+* R := g.comp (int.cast_ring_hom (zmod n)),
show φ k = ψ k,
rw φ.ext_int ψ,
end
namespace zmod
variables {n : ℕ} {R : Type*}
instance subsingleton_ring_hom [semiring R] : subsingleton ((zmod n) →+* R) :=
⟨ring_hom.ext_zmod⟩
instance subsingleton_ring_equiv [semiring R] : subsingleton (zmod n ≃+* R) :=
⟨λ f g, by { rw ring_equiv.coe_ring_hom_inj_iff, apply ring_hom.ext_zmod _ _ }⟩
@[simp] lemma ring_hom_map_cast [ring R] (f : R →+* (zmod n)) (k : zmod n) :
f k = k :=
by { cases n; simp }
lemma ring_hom_right_inverse [ring R] (f : R →+* (zmod n)) :
function.right_inverse (coe : zmod n → R) f :=
ring_hom_map_cast f
lemma ring_hom_surjective [ring R] (f : R →+* (zmod n)) : function.surjective f :=
(ring_hom_right_inverse f).surjective
lemma ring_hom_eq_of_ker_eq [comm_ring R] (f g : R →+* (zmod n))
(h : f.ker = g.ker) : f = g :=
begin
have := f.lift_of_right_inverse_comp _ (zmod.ring_hom_right_inverse f) ⟨g, le_of_eq h⟩,
rw subtype.coe_mk at this,
rw [←this, ring_hom.ext_zmod (f.lift_of_right_inverse _ _ _) (ring_hom.id _), ring_hom.id_comp],
end
section lift
variables (n) {A : Type*} [add_group A]
/-- The map from `zmod n` induced by `f : ℤ →+ A` that maps `n` to `0`. -/
@[simps]
def lift : {f : ℤ →+ A // f n = 0} ≃ (zmod n →+ A) :=
(equiv.subtype_equiv_right $ begin
intro f,
rw ker_int_cast_add_hom,
split,
{ rintro hf _ ⟨x, rfl⟩,
simp only [f.map_gsmul, gsmul_zero, f.mem_ker, hf] },
{ intro h,
refine h (add_subgroup.mem_gmultiples _) }
end).trans $ ((int.cast_add_hom (zmod n)).lift_of_right_inverse coe int_cast_zmod_cast)
variables (f : {f : ℤ →+ A // f n = 0})
@[simp] lemma lift_coe (x : ℤ) :
lift n f (x : zmod n) = f x :=
add_monoid_hom.lift_of_right_inverse_comp_apply _ _ _ _ _
lemma lift_cast_add_hom (x : ℤ) :
lift n f (int.cast_add_hom (zmod n) x) = f x :=
add_monoid_hom.lift_of_right_inverse_comp_apply _ _ _ _ _
@[simp] lemma lift_comp_coe : zmod.lift n f ∘ coe = f :=
funext $ lift_coe _ _
@[simp] lemma lift_comp_cast_add_hom :
(zmod.lift n f).comp (int.cast_add_hom (zmod n)) = f :=
add_monoid_hom.ext $ lift_cast_add_hom _ _
end lift
end zmod
|
e5bfaa89f215353e2e649acc8cf67e38fae1a75a | 037dba89703a79cd4a4aec5e959818147f97635d | /src/2021/sets/sheet5.lean | 38e5a64bbf529ceffbd8c6ad1f5a12eda51522f7 | [] | no_license | ImperialCollegeLondon/M40001_lean | 3a6a09298da395ab51bc220a535035d45bbe919b | 62a76fa92654c855af2b2fc2bef8e60acd16ccec | refs/heads/master | 1,666,750,403,259 | 1,665,771,117,000 | 1,665,771,117,000 | 209,141,835 | 115 | 12 | null | 1,640,270,596,000 | 1,568,749,174,000 | Lean | UTF-8 | Lean | false | false | 3,729 | lean | /-
Copyright (c) 2021 Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author : Kevin Buzzard
-/
import tactic -- imports all the Lean tactics
/-!
# Sets in Lean, sheet 5 : subset (`⊆`), union (`∪`) and intersection (`∩`)
In this sheet we learn how to manipulate `⊆`, `∪` and `∩` in Lean.
Here are some mathematical facts:
`A ⊆ B` is equivalent to `∀ x, x ∈ A → x ∈ B`;
`x ∈ A ∪ B` is equivalent to `x ∈ A ∨ x ∈ B`;
`x ∈ A ∩ B` is equivalent to `x ∈ A ∧ x ∈ B`.
All of these things are true *by definition* in Lean, which means
that you can switch from one to the other with `change`, or you
can just treat something on the left hand side as if it said
what it said on the right hand side.
For example if your goal is `⊢ x ∈ A ∩ B` then you could write
`change x ∈ A ∧ x ∈ B,` to change the goal to `⊢ x ∈ A ∧ x ∈ B`, but you can
also use the `split,` tactic directly, and this will immediately turn the goal
into two goals `⊢ x ∈ A` and `⊢ x ∈ B`.
## New tactics you will need
You don't need to know any new tactics to solve this sheet. I've mentioned
the `change` tactic. You don't have to use it, and if you use it your
proofs will get longer. So in return I'll tell you about two other
tactics, `rcases` and `rintro`, which you don't have to use either
but if you use them they'll make your proofs shorter.
### The `rcases` tactic
`rcases` is a souped-up version of `cases`. It has slightly different
syntax. If you have a hypothesis `h : P ∧ Q` then `cases h with hP hQ,`
and `rcases h with ⟨hP, hQ⟩,` do the same thing. However, if you
have a hypothesis `h : P ∧ Q ∧ R` then Lean interprets it as `P ∧ (Q ∧ R)`
so if you want to destruct it with `cases` you have to do
```
cases h with hP hQR,
cases hQR with hQ hR
```
You can do this all in one go with `rcases h with ⟨hP, hQ, hR⟩,`. The
name `rcases` stands for "recursive cases".
`rcases` can also be used for `or` hypotheses too; here the syntax is that if
we have
```
h : P ∨ Q
```
then `rcases h with (hP | hQ),` will turn our goal into two goals, one with
`hP : P` and the other with `hQ : Q`.
Even better, `rcases` works on `h : false`. Here there are no cases at all!
So `rcases h with ⟨⟩,` solves the goal.
### The `rintro` tactic
It's quite common to find yourself doing `intro` then `cases` or,
more generally, `intro` then `rcases`. The `rintro` tactic does
these both at once! So for example if your goal is
```
⊢ (P ∧ Q) → R
```
then `rintro ⟨hP, hQ⟩,` leaves you at
```
hP : P
hQ : Q
⊢ R
```
i.e. the same as `intro h, cases h with hP hQ,`
You can introduce more than one hypothesis at once -- `rintro` generalises
`intros` as well. For example if your goal is
```
⊢ P → Q ∧ R → S
```
then `rintro hP ⟨hQ, hR⟩,` turns it into
```
hP : P
hQ : Q
hR : R
⊢ S
```
-/
open set
variables
(X : Type) -- Everything will be a subset of `X`
(A B C D E : set X) -- A,B,C,D,E are subsets of `X`
(x y z : X) -- x,y,z are elements of `X` or, more precisely, terms of type `X`
example : A ⊆ A :=
begin
sorry,
end
example : ∅ ⊆ A :=
begin
sorry,
end
example : A ⊆ univ :=
begin
sorry,
end
example : A ⊆ B → B ⊆ C → A ⊆ C :=
begin
sorry,
end
example : A ⊆ A ∪ B :=
begin
sorry,
end
example : A ∩ B ⊆ A :=
begin
sorry,
end
example : A ⊆ B → A ⊆ C → A ⊆ (B ∩ C) :=
begin
sorry,
end
example : B ⊆ A → C ⊆ A → B ∪ C ⊆ A :=
begin
sorry,
end
example : A ⊆ B → C ⊆ D → A ∪ C ⊆ B ∪ D :=
begin
sorry,
end
example : A ⊆ B → C ⊆ D → A ∩ C ⊆ B ∩ D :=
begin
sorry,
end
|
772799bd606f483cfee98ca5ebad0ed9e71d1b62 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/number_theory/cyclotomic/gal.lean | 7b4245028d3764663f48a891f930e00a0bb51909 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 7,580 | lean | /-
Copyright (c) 2022 Eric Rodriguez. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Rodriguez
-/
import number_theory.cyclotomic.primitive_roots
import field_theory.polynomial_galois_group
/-!
# Galois group of cyclotomic extensions
In this file, we show the relationship between the Galois group of `K(ζₙ)` and `(zmod n)ˣ`;
it is always a subgroup, and if the `n`th cyclotomic polynomial is irreducible, they are isomorphic.
## Main results
* `is_primitive_root.aut_to_pow_injective`: `is_primitive_root.aut_to_pow` is injective
in the case that it's considered over a cyclotomic field extension, where `n` does not divide
the characteristic of K.
* `is_cyclotomic_extension.aut_equiv_pow`: If, additionally, the `n`th cyclotomic polynomial is
irreducible in K, then `aut_to_pow` is a `mul_equiv` (for example, in ℚ and certain 𝔽ₚ).
* `gal_X_pow_equiv_units_zmod`, `gal_cyclotomic_equiv_units_zmod`: Repackage `aut_equiv_pow` in
terms of `polynomial.gal`.
* `is_cyclotomic_extension.aut.comm_group`: Cyclotomic extensions are abelian.
## References
* https://kconrad.math.uconn.edu/blurbs/galoistheory/cyclotomic.pdf
## TODO
* We currently can get away with the fact that the power of a primitive root is a primitive root,
but the correct long-term solution for computing other explicit Galois groups is creating
`power_basis.map_conjugate`; but figuring out the exact correct assumptions + proof for this is
mathematically nontrivial. (Current thoughts: the correct condition is that the annihilating
ideal of both elements is equal. This may not hold in an ID, and definitely holds in an ICD.)
-/
local attribute [instance] pnat.fact_pos
variables {n : ℕ+} (K : Type*) [field K] {L : Type*} [field L] {μ : L} (hμ : is_primitive_root μ n)
[algebra K L] [is_cyclotomic_extension {n} K L]
open polynomial ne_zero is_cyclotomic_extension
open_locale cyclotomic
namespace is_primitive_root
/-- `is_primitive_root.aut_to_pow` is injective in the case that it's considered over a cyclotomic
field extension, where `n` does not divide the characteristic of K. -/
lemma aut_to_pow_injective : function.injective $ hμ.aut_to_pow K :=
begin
intros f g hfg,
apply_fun units.val at hfg,
simp only [is_primitive_root.coe_aut_to_pow_apply, units.val_eq_coe] at hfg,
generalize_proofs hf' hg' at hfg,
have hf := hf'.some_spec,
have hg := hg'.some_spec,
generalize_proofs hζ at hf hg,
suffices : f hμ.to_roots_of_unity = g hμ.to_roots_of_unity,
{ apply alg_equiv.coe_alg_hom_injective,
apply (hμ.power_basis K).alg_hom_ext,
exact this },
rw zmod.eq_iff_modeq_nat at hfg,
refine (hf.trans _).trans hg.symm,
rw [←roots_of_unity.coe_pow _ hf'.some, ←roots_of_unity.coe_pow _ hg'.some],
congr' 1,
rw [pow_eq_pow_iff_modeq],
convert hfg,
rw [hμ.eq_order_of],
rw [←hμ.coe_to_roots_of_unity_coe] {occs := occurrences.pos [2]},
rw [order_of_units, order_of_subgroup]
end
end is_primitive_root
namespace is_cyclotomic_extension
/-- Cyclotomic extensions are abelian. -/
noncomputable def aut.comm_group [ne_zero ((n : ℕ) : K)] : comm_group (L ≃ₐ[K] L) :=
let _ := of_no_zero_smul_divisors K L n in by exactI
((zeta_primitive_root n K L).aut_to_pow_injective K).comm_group _
(map_one _) (map_mul _) (map_inv _) (map_div _) (map_pow _) (map_zpow _)
variables (h : irreducible (cyclotomic n K)) {K} (L)
include h
/-- The `mul_equiv` that takes an automorphism `f` to the element `k : (zmod n)ˣ` such that
`f μ = μ ^ k`. A stronger version of `is_primitive_root.aut_to_pow`. -/
@[simps] noncomputable def aut_equiv_pow [ne_zero ((n : ℕ) : K)] : (L ≃ₐ[K] L) ≃* (zmod n)ˣ :=
let hn := of_no_zero_smul_divisors K L n in
by exactI
let hζ := zeta_primitive_root n K L,
hμ := λ t, hζ.pow_of_coprime _ (zmod.val_coe_unit_coprime t) in
{ inv_fun := λ t, (hζ.power_basis K).equiv_of_minpoly ((hμ t).power_basis K)
begin
simp only [is_primitive_root.power_basis_gen],
have hr := is_primitive_root.minpoly_eq_cyclotomic_of_irreducible
((zeta_primitive_root n K L).pow_of_coprime _ (zmod.val_coe_unit_coprime t)) h,
exact ((zeta_primitive_root n K L).minpoly_eq_cyclotomic_of_irreducible h).symm.trans hr
end,
left_inv := λ f, begin
simp only [monoid_hom.to_fun_eq_coe],
apply alg_equiv.coe_alg_hom_injective,
apply (hζ.power_basis K).alg_hom_ext,
simp only [alg_equiv.coe_alg_hom, alg_equiv.map_pow],
rw power_basis.equiv_of_minpoly_gen,
simp only [is_primitive_root.power_basis_gen, is_primitive_root.aut_to_pow_spec],
end,
right_inv := λ x, begin
simp only [monoid_hom.to_fun_eq_coe],
generalize_proofs _ _ _ h,
have key := hζ.aut_to_pow_spec K ((hζ.power_basis K).equiv_of_minpoly
((hμ x).power_basis K) h),
have := (hζ.power_basis K).equiv_of_minpoly_gen ((hμ x).power_basis K) h,
rw hζ.power_basis_gen K at this,
rw [this, is_primitive_root.power_basis_gen] at key,
rw ← hζ.coe_to_roots_of_unity_coe at key {occs := occurrences.pos [1, 5]},
simp only [←coe_coe, ←roots_of_unity.coe_pow] at key,
replace key := roots_of_unity.coe_injective key,
rw [pow_eq_pow_iff_modeq, ←order_of_subgroup, ←order_of_units, hζ.coe_to_roots_of_unity_coe,
←(zeta_primitive_root n K L).eq_order_of, ←zmod.eq_iff_modeq_nat] at key,
simp only [zmod.nat_cast_val, zmod.cast_id', id.def] at key,
exact units.ext key
end,
.. (zeta_primitive_root n K L).aut_to_pow K }
include hμ
variables {L}
/-- Maps `μ` to the `alg_equiv` that sends `is_cyclotomic_extension.zeta` to `μ`. -/
noncomputable def from_zeta_aut [ne_zero ((n : ℕ) : K)] : L ≃ₐ[K] L :=
have _ := of_no_zero_smul_divisors K L n, by exactI
let hζ := (zeta_primitive_root n K L).eq_pow_of_pow_eq_one hμ.pow_eq_one n.pos in
(aut_equiv_pow L h).symm $ zmod.unit_of_coprime hζ.some $
((zeta_primitive_root n K L).pow_iff_coprime n.pos hζ.some).mp $ hζ.some_spec.some_spec.symm ▸ hμ
lemma from_zeta_aut_spec [ne_zero ((n : ℕ) : K)] : from_zeta_aut hμ h (zeta n K L) = μ :=
begin
simp_rw [from_zeta_aut, aut_equiv_pow_symm_apply],
generalize_proofs _ hζ h _ hμ _,
rw [←hζ.power_basis_gen K] {occs := occurrences.pos [4]},
rw [power_basis.equiv_of_minpoly_gen, hμ.power_basis_gen K],
convert h.some_spec.some_spec,
exact zmod.val_cast_of_lt h.some_spec.some
end
end is_cyclotomic_extension
section gal
variables (h : irreducible (cyclotomic n K)) {K}
/-- `is_cyclotomic_extension.aut_equiv_pow` repackaged in terms of `gal`. Asserts that the
Galois group of `cyclotomic n K` is equivalent to `(zmod n)ˣ` if `n` does not divide the
characteristic of `K`, and `cyclotomic n K` is irreducible in the base field. -/
noncomputable def gal_cyclotomic_equiv_units_zmod [ne_zero ((n : ℕ) : K)] :
(cyclotomic n K).gal ≃* (zmod n)ˣ :=
(alg_equiv.aut_congr (is_splitting_field.alg_equiv _ _)).symm.trans
(is_cyclotomic_extension.aut_equiv_pow L h)
/-- `is_cyclotomic_extension.aut_equiv_pow` repackaged in terms of `gal`. Asserts that the
Galois group of `X ^ n - 1` is equivalent to `(zmod n)ˣ` if `n` does not divide the characteristic
of `K`, and `cyclotomic n K` is irreducible in the base field. -/
noncomputable def gal_X_pow_equiv_units_zmod [ne_zero ((n : ℕ) : K)] :
(X ^ (n : ℕ) - 1).gal ≃* (zmod n)ˣ :=
(alg_equiv.aut_congr (is_splitting_field.alg_equiv _ _)).symm.trans
(is_cyclotomic_extension.aut_equiv_pow L h)
end gal
|
56177e405a55a6ae05f27f853cdefc73c15deada | 7850aae797be6c31052ce4633d86f5991178d3df | /src/Lean/Server/FileWorker.lean | dfbff63e09886d282ed9cc4fa7f86fa1e0d99d35 | [
"Apache-2.0"
] | permissive | miriamgoetze/lean4 | 4dc24d4dbd360cc969713647c2958c6691947d16 | 062cc5d5672250be456a168e9c7b9299a9c69bdb | refs/heads/master | 1,685,865,971,011 | 1,624,107,703,000 | 1,624,107,703,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 17,484 | 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 Std.Data.RBMap
import Lean.Environment
import Lean.Data.Lsp
import Lean.Data.Json.FromToJson
import Lean.Server.Utils
import Lean.Server.Snapshots
import Lean.Server.AsyncList
import Lean.Server.FileWorker.Utils
import Lean.Server.FileWorker.RequestHandling
/-!
For general server architecture, see `README.md`. For details of IPC communication, see `Watchdog.lean`.
This module implements per-file worker processes.
File processing and requests+notifications against a file should be concurrent for two reasons:
- By the LSP standard, requests should be cancellable.
- Since Lean allows arbitrary user code to be executed during elaboration via the tactic framework,
elaboration can be extremely slow and even not halt in some cases. Users should be able to
work with the file while this is happening, e.g. make new changes to the file or send requests.
To achieve these goals, elaboration is executed in a chain of tasks, where each task corresponds to
the elaboration of one command. When the elaboration of one command is done, the next task is spawned.
On didChange notifications, we search for the task in which the change occured. If we stumble across
a task that has not yet finished before finding the task we're looking for, we terminate it
and start the elaboration there, otherwise we start the elaboration at the task where the change occured.
Requests iterate over tasks until they find the command that they need to answer the request.
In order to not block the main thread, this is done in a request task.
If a task that the request task waits for is terminated, a change occured somewhere before the
command that the request is looking for and the request sends a "content changed" error.
-/
namespace Lean.Server.FileWorker
open Lsp
open IO
open Snapshots
open Std (RBMap RBMap.empty)
open JsonRpc
/- Asynchronous snapshot elaboration. -/
section Elab
/-- Elaborates the next command after `parentSnap` and emits diagnostics into `hOut`. -/
private def nextCmdSnap (m : DocumentMeta) (parentSnap : Snapshot) (cancelTk : CancelToken) (hOut : FS.Stream)
: ExceptT ElabTaskError IO Snapshot := do
cancelTk.check
publishProgressAtPos m parentSnap.endPos hOut
let maybeSnap ← compileNextCmd m.text.source parentSnap
-- TODO(MH): check for interrupt with increased precision
cancelTk.check
match maybeSnap with
| Sum.inl snap =>
/- NOTE(MH): This relies on the client discarding old diagnostics upon receiving new ones
while prefering newer versions over old ones. The former is necessary because we do
not explicitly clear older diagnostics, while the latter is necessary because we do
not guarantee that diagnostics are emitted in order. Specifically, it may happen that
we interrupted this elaboration task right at this point and a newer elaboration task
emits diagnostics, after which we emit old diagnostics because we did not yet detect
the interrupt. Explicitly clearing diagnostics is difficult for a similar reason,
because we cannot guarantee that no further diagnostics are emitted after clearing
them. -/
publishMessages m snap.msgLog hOut
snap
| Sum.inr msgLog =>
publishMessages m msgLog hOut
publishProgressDone m hOut
throw ElabTaskError.eof
/-- Elaborates all commands after `initSnap`, emitting the diagnostics into `hOut`. -/
def unfoldCmdSnaps (m : DocumentMeta) (initSnap : Snapshot) (cancelTk : CancelToken) (hOut : FS.Stream)
(initial : Bool) :
IO (AsyncList ElabTaskError Snapshot) := do
if initial && initSnap.msgLog.hasErrors then
-- treat header processing errors as fatal so users aren't swamped with followup errors
AsyncList.nil
else
AsyncList.unfoldAsync (nextCmdSnap m . cancelTk hOut) initSnap
end Elab
-- Pending requests are tracked so they can be cancelled
abbrev PendingRequestMap := RBMap RequestID (Task (Except IO.Error Unit)) compare
structure WorkerContext where
hIn : FS.Stream
hOut : FS.Stream
hLog : FS.Stream
srcSearchPath : SearchPath
docRef : IO.Ref EditableDocument
pendingRequestsRef : IO.Ref PendingRequestMap
abbrev WorkerM := ReaderT WorkerContext IO
/- Worker initialization sequence. -/
section Initialization
/-- Use `leanpkg print-paths` to compile dependencies on the fly and add them to `LEAN_PATH`.
Compilation progress is reported to `hOut` via LSP notifications. Return the search path for
source files. -/
partial def leanpkgSetupSearchPath (leanpkgPath : System.FilePath) (m : DocumentMeta) (imports : Array Import) (hOut : FS.Stream) : IO SearchPath := do
let leanpkgProc ← Process.spawn {
stdin := Process.Stdio.null
stdout := Process.Stdio.piped
stderr := Process.Stdio.piped
cmd := leanpkgPath.toString
args := #["print-paths"] ++ imports.map (toString ·.module)
}
-- progress notification: report latest stderr line
let rec processStderr (acc : String) : IO String := do
let line ← leanpkgProc.stderr.getLine
if line == "" then
return acc
else
publishDiagnostics m #[{ range := ⟨⟨0, 0⟩, ⟨0, 0⟩⟩, severity? := DiagnosticSeverity.information, message := line }] hOut
processStderr (acc ++ line)
let stderr ← IO.asTask (processStderr "") Task.Priority.dedicated
let stdout := String.trim (← leanpkgProc.stdout.readToEnd)
let stderr ← IO.ofExcept stderr.get
if (← leanpkgProc.wait) == 0 then
let leanpkgLines := stdout.split (· == '\n')
-- ignore any output up to the last two lines
-- TODO: leanpkg should instead redirect nested stdout output to stderr
let leanpkgLines := leanpkgLines.drop (leanpkgLines.length - 2)
match leanpkgLines with
| [""] => pure [] -- e.g. no leanpkg.toml
| [leanPath, leanSrcPath] => let sp ← getBuiltinSearchPath
let sp ← addSearchPathFromEnv sp
let sp := System.SearchPath.parse leanPath ++ sp
searchPathRef.set sp
let srcPath := System.SearchPath.parse leanSrcPath
srcPath.mapM realPathNormalized
| _ => throwServerError s!"unexpected output from `leanpkg print-paths`:\n{stdout}\nstderr:\n{stderr}"
else
throwServerError s!"`leanpkg print-paths` failed:\n{stdout}\nstderr:\n{stderr}"
def compileHeader (m : DocumentMeta) (hOut : FS.Stream) : IO (Snapshot × SearchPath) := do
let opts := {} -- TODO
let inputCtx := Parser.mkInputContext m.text.source "<input>"
let (headerStx, headerParserState, msgLog) ← Parser.parseHeader inputCtx
let leanpkgPath ← match ← IO.getEnv "LEAN_SYSROOT" with
| some path => pure <| System.FilePath.mk path / "bin" / "leanpkg"
| _ => pure <| (← appDir) / "leanpkg"
let leanpkgPath := leanpkgPath.withExtension System.FilePath.exeExtension
let mut srcSearchPath := [(← appDir) / ".." / "lib" / "lean" / "src"]
if let some p := (← IO.getEnv "LEAN_SRC_PATH") then
srcSearchPath := srcSearchPath ++ System.SearchPath.parse p
let (headerEnv, msgLog) ← try
-- NOTE: leanpkg does not exist in stage 0 (yet?)
if (← System.FilePath.pathExists leanpkgPath) then
let pkgSearchPath ← leanpkgSetupSearchPath leanpkgPath m (Lean.Elab.headerToImports headerStx).toArray hOut
srcSearchPath := srcSearchPath ++ pkgSearchPath
Elab.processHeader headerStx opts msgLog inputCtx
catch e => -- should be from `leanpkg print-paths`
let msgs := MessageLog.empty.add { fileName := "<ignored>", pos := ⟨0, 0⟩, data := e.toString }
pure (← mkEmptyEnvironment, msgs)
publishMessages m msgLog hOut
let cmdState := Elab.Command.mkState headerEnv msgLog opts
let cmdState := { cmdState with infoState.enabled := true, scopes := [{ header := "", opts := opts }] }
let headerSnap := {
beginPos := 0
stx := headerStx
mpState := headerParserState
cmdState := cmdState
}
return (headerSnap, srcSearchPath)
def initializeWorker (meta : DocumentMeta) (i o e : FS.Stream)
: IO WorkerContext := do
/- 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. -/
let (headerSnap, srcSearchPath) ← compileHeader meta o
let cancelTk ← CancelToken.new
let cmdSnaps ← unfoldCmdSnaps meta headerSnap cancelTk o (initial := true)
let doc : EditableDocument := ⟨meta, headerSnap, cmdSnaps, cancelTk⟩
return {
hIn := i
hOut := o
hLog := e
srcSearchPath := srcSearchPath
docRef := ←IO.mkRef doc
pendingRequestsRef := ←IO.mkRef RBMap.empty
}
end Initialization
section Updates
def updatePendingRequests (map : PendingRequestMap → PendingRequestMap) : WorkerM Unit := do
(←read).pendingRequestsRef.modify map
/-- Given the new document and `changePos`, the UTF-8 offset of a change into the pre-change source,
updates editable doc state. -/
def updateDocument (newMeta : DocumentMeta) (changePos : String.Pos) : WorkerM Unit := do
-- The watchdog only restarts the file worker when the syntax tree of the header changes.
-- If e.g. a newline is deleted, it will not restart this file worker, but we still
-- need to reparse the header so that the offsets are correct.
let st ← read
let oldDoc ← st.docRef.get
let newHeaderSnap ← reparseHeader newMeta.text.source oldDoc.headerSnap
if newHeaderSnap.stx != oldDoc.headerSnap.stx then
throwServerError "Internal server error: header changed but worker wasn't restarted."
let ⟨cmdSnaps, e?⟩ ← oldDoc.cmdSnaps.updateFinishedPrefix
match e? with
-- This case should not be possible. only the main task aborts tasks and ensures that aborted tasks
-- do not show up in `snapshots` of an EditableDocument.
| some ElabTaskError.aborted =>
throwServerError "Internal server error: elab task was aborted while still in use."
| some (ElabTaskError.ioError ioError) => throw ioError
| _ => -- No error or EOF
oldDoc.cancelTk.set
-- NOTE(WN): we invalidate eagerly as `endPos` consumes input greedily. To re-elaborate only
-- when really necessary, we could do a whitespace-aware `Syntax` comparison instead.
let mut validSnaps := cmdSnaps.finishedPrefix.takeWhile (fun s => s.endPos < changePos)
if validSnaps.length = 0 then
let cancelTk ← CancelToken.new
let newCmdSnaps ← unfoldCmdSnaps newMeta newHeaderSnap cancelTk st.hOut (initial := true)
st.docRef.set ⟨newMeta, newHeaderSnap, newCmdSnaps, cancelTk⟩
else
/- When at least one valid non-header snap exists, it may happen that a change does not fall
within the syntactic range of that last snap but still modifies it by appending tokens.
We check for this here. We do not currently handle crazy grammars in which an appended
token can merge two or more previous commands into one. To do so would require reparsing
the entire file. -/
let mut lastSnap := validSnaps.getLast!
let preLastSnap :=
if validSnaps.length ≥ 2
then validSnaps.get! (validSnaps.length - 2)
else newHeaderSnap
let newLastStx ← parseNextCmd newMeta.text.source preLastSnap
if newLastStx != lastSnap.stx then
validSnaps ← validSnaps.dropLast
lastSnap ← preLastSnap
let cancelTk ← CancelToken.new
let newSnaps ← unfoldCmdSnaps newMeta lastSnap cancelTk st.hOut (initial := false)
let newCmdSnaps := AsyncList.ofList validSnaps ++ newSnaps
st.docRef.set ⟨newMeta, newHeaderSnap, newCmdSnaps, cancelTk⟩
end Updates
/- Notifications are handled in the main thread. They may change global worker state
such as the current file contents. -/
section NotificationHandling
def handleDidChange (p : DidChangeTextDocumentParams) : WorkerM Unit := do
let docId := p.textDocument
let changes := p.contentChanges
let oldDoc ← (←read).docRef.get
let some newVersion ← pure docId.version?
| throwServerError "Expected version number"
if newVersion ≤ oldDoc.meta.version then
-- TODO(WN): This happens on restart sometimes.
IO.eprintln s!"Got outdated version number: {newVersion} ≤ {oldDoc.meta.version}"
else if ¬ changes.isEmpty then
let (newDocText, minStartOff) := foldDocumentChanges changes oldDoc.meta.text
updateDocument ⟨docId.uri, newVersion, newDocText⟩ minStartOff
def handleCancelRequest (p : CancelParams) : WorkerM Unit := do
updatePendingRequests (fun pendingRequests => pendingRequests.erase p.id)
end NotificationHandling
section MessageHandling
def parseParams (paramType : Type) [FromJson paramType] (params : Json) : WorkerM paramType :=
match fromJson? params with
| Except.ok parsed => pure parsed
| Except.error inner => throwServerError s!"Got param with wrong structure: {params.compress}\n{inner}"
def handleNotification (method : String) (params : Json) : WorkerM Unit := do
let handle := fun paramType [FromJson paramType] (handler : paramType → WorkerM Unit) =>
parseParams paramType params >>= handler
match method with
| "textDocument/didChange" => handle DidChangeTextDocumentParams handleDidChange
| "$/cancelRequest" => handle CancelParams handleCancelRequest
| _ => throwServerError s!"Got unsupported notification method: {method}"
def queueRequest (id : RequestID) (requestTask : Task (Except IO.Error Unit))
: WorkerM Unit := do
updatePendingRequests (fun pendingRequests => pendingRequests.insert id requestTask)
def handleRequest (id : RequestID) (method : String) (params : Json)
: WorkerM Unit := do
let st ← read
let rc : Requests.RequestContext := { srcSearchPath := st.srcSearchPath, docRef := st.docRef }
let t? ← (ExceptT.run <| Requests.handleLspRequest method params rc : IO _)
let t₁ ← match t? with
| Except.error e =>
IO.asTask do
st.hOut.writeLspResponseError <| e.toLspResponseError id
| Except.ok t => (IO.mapTask · t) fun
| Except.ok resp =>
st.hOut.writeLspResponse ⟨id, resp⟩
| Except.error e =>
st.hOut.writeLspResponseError <| e.toLspResponseError id
queueRequest id t₁
end MessageHandling
section MainLoop
partial def mainLoop : WorkerM Unit := do
let st ← read
let msg ← st.hIn.readLspMessage
let pendingRequests ← st.pendingRequestsRef.get
let filterFinishedTasks (acc : PendingRequestMap) (id : RequestID) (task : Task (Except IO.Error Unit))
: WorkerM PendingRequestMap := do
if (←hasFinished task) then
/- Handler tasks are constructed so that the only possible errors here
are failures of writing a response into the stream. -/
if let Except.error e := task.get then
throwServerError s!"Failed responding to request {id}: {e}"
acc.erase id
else acc
let pendingRequests ← pendingRequests.foldM filterFinishedTasks pendingRequests
st.pendingRequestsRef.set pendingRequests
match msg with
| Message.request id method (some params) =>
handleRequest id method (toJson params)
mainLoop
| Message.notification "exit" none =>
let doc ← st.docRef.get
doc.cancelTk.set
return ()
| Message.notification method (some params) =>
handleNotification method (toJson params)
mainLoop
| _ => throwServerError "Got invalid JSON-RPC message"
end MainLoop
def initAndRunWorker (i o e : FS.Stream) : IO UInt32 := do
let i ← maybeTee "fwIn.txt" false i
let o ← maybeTee "fwOut.txt" true o
let _ ← i.readLspRequestAs "initialize" InitializeParams
let ⟨_, param⟩ ← i.readLspNotificationAs "textDocument/didOpen" DidOpenTextDocumentParams
let doc := param.textDocument
let meta : DocumentMeta := ⟨doc.uri, doc.version, doc.text.toFileMap⟩
let e ← e.withPrefix s!"[{param.textDocument.uri}] "
let _ ← IO.setStderr e
try
let ctx ← initializeWorker meta i o e
ReaderT.run (r := ctx) mainLoop
return 0
catch e =>
IO.eprintln e
publishDiagnostics meta #[{ range := ⟨⟨0, 0⟩, ⟨0, 0⟩⟩, severity? := DiagnosticSeverity.error, message := e.toString }] o
return 1
@[export lean_server_worker_main]
def workerMain : IO UInt32 := do
let i ← IO.getStdin
let o ← IO.getStdout
let e ← IO.getStderr
try
initAndRunWorker i o e
catch err =>
e.putStrLn s!"worker initialization error: {err}"
return (1 : UInt32)
end Lean.Server.FileWorker
|
1977e83a6f472d2d1e7644bddf6ffd15c25c0cc6 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/topology/algebra/infinite_sum/module.lean | ad9f0b35f7f745afbdaa1d4394e2db468369b936 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 4,121 | lean | /-
Copyright (c) 2020 Heather Macbeth. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Heather Macbeth, Yury Kudryashov, Frédéric Dupuis
-/
import topology.algebra.infinite_sum.basic
import topology.algebra.module.basic
/-! # Infinite sums in topological vector spaces
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.-/
variables {ι R R₂ M M₂ : Type*}
section smul_const
variables [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [module R M]
[has_continuous_smul R M] {f : ι → R}
lemma has_sum.smul_const {r : R} (hf : has_sum f r) (a : M) : has_sum (λ z, f z • a) (r • a) :=
hf.map ((smul_add_hom R M).flip a) (continuous_id.smul continuous_const)
lemma summable.smul_const (hf : summable f) (a : M) : summable (λ z, f z • a) :=
(hf.has_sum.smul_const _).summable
lemma tsum_smul_const [t2_space M] (hf : summable f) (a : M) : ∑' z, f z • a = (∑' z, f z) • a :=
(hf.has_sum.smul_const _).tsum_eq
end smul_const
section has_sum
-- Results in this section hold for continuous additive monoid homomorphisms or equivalences but we
-- don't have bundled continuous additive homomorphisms.
variables [semiring R] [semiring R₂] [add_comm_monoid M] [module R M]
[add_comm_monoid M₂] [module R₂ M₂] [topological_space M] [topological_space M₂]
{σ : R →+* R₂} {σ' : R₂ →+* R} [ring_hom_inv_pair σ σ'] [ring_hom_inv_pair σ' σ]
/-- Applying a continuous linear map commutes with taking an (infinite) sum. -/
protected lemma continuous_linear_map.has_sum {f : ι → M} (φ : M →SL[σ] M₂) {x : M}
(hf : has_sum f x) :
has_sum (λ (b:ι), φ (f b)) (φ x) :=
by simpa only using hf.map φ.to_linear_map.to_add_monoid_hom φ.continuous
alias continuous_linear_map.has_sum ← has_sum.mapL
protected lemma continuous_linear_map.summable {f : ι → M} (φ : M →SL[σ] M₂) (hf : summable f) :
summable (λ b:ι, φ (f b)) :=
(hf.has_sum.mapL φ).summable
alias continuous_linear_map.summable ← summable.mapL
protected lemma continuous_linear_map.map_tsum [t2_space M₂] {f : ι → M}
(φ : M →SL[σ] M₂) (hf : summable f) : φ (∑' z, f z) = ∑' z, φ (f z) :=
(hf.has_sum.mapL φ).tsum_eq.symm
include σ'
/-- Applying a continuous linear map commutes with taking an (infinite) sum. -/
protected lemma continuous_linear_equiv.has_sum {f : ι → M} (e : M ≃SL[σ] M₂) {y : M₂} :
has_sum (λ (b:ι), e (f b)) y ↔ has_sum f (e.symm y) :=
⟨λ h, by simpa only [e.symm.coe_coe, e.symm_apply_apply] using h.mapL (e.symm : M₂ →SL[σ'] M),
λ h, by simpa only [e.coe_coe, e.apply_symm_apply] using (e : M →SL[σ] M₂).has_sum h⟩
/-- Applying a continuous linear map commutes with taking an (infinite) sum. -/
protected lemma continuous_linear_equiv.has_sum' {f : ι → M} (e : M ≃SL[σ] M₂) {x : M} :
has_sum (λ (b:ι), e (f b)) (e x) ↔ has_sum f x :=
by rw [e.has_sum, continuous_linear_equiv.symm_apply_apply]
protected lemma continuous_linear_equiv.summable {f : ι → M} (e : M ≃SL[σ] M₂) :
summable (λ b:ι, e (f b)) ↔ summable f :=
⟨λ hf, (e.has_sum.1 hf.has_sum).summable, (e : M →SL[σ] M₂).summable⟩
lemma continuous_linear_equiv.tsum_eq_iff [t2_space M] [t2_space M₂] {f : ι → M}
(e : M ≃SL[σ] M₂) {y : M₂} : ∑' z, e (f z) = y ↔ ∑' z, f z = e.symm y :=
begin
by_cases hf : summable f,
{ exact ⟨λ h, (e.has_sum.mp ((e.summable.mpr hf).has_sum_iff.mpr h)).tsum_eq,
λ h, (e.has_sum.mpr (hf.has_sum_iff.mpr h)).tsum_eq⟩ },
{ have hf' : ¬summable (λ z, e (f z)) := λ h, hf (e.summable.mp h),
rw [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable hf'],
exact ⟨by { rintro rfl, simp }, λ H, by simpa using (congr_arg (λ z, e z) H)⟩ }
end
protected lemma continuous_linear_equiv.map_tsum [t2_space M] [t2_space M₂] {f : ι → M}
(e : M ≃SL[σ] M₂) : e (∑' z, f z) = ∑' z, e (f z) :=
by { refine symm (e.tsum_eq_iff.mpr _), rw e.symm_apply_apply _ }
end has_sum
|
84ac24234b70f365d15296a513dd0f82603bfe9a | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /src/Lean/Data/Format.lean | ebec3626d78ba9c7e56e86108e9c2db0d0ea1de1 | [
"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 | 1,696 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
import Lean.Data.Options
universes u v
namespace Std
namespace Format
open Lean
def getWidth (o : Options) : Nat := o.get `format.width defWidth
def getIndent (o : Options) : Nat := o.get `format.indent defIndent
def getUnicode (o : Options) : Bool := o.get `format.unicode defUnicode
register_builtin_option format.width : Nat := {
defValue := defWidth
descr := "indentation"
}
register_builtin_option format.unicode : Bool := {
defValue := defUnicode
descr := "unicode characters"
}
register_builtin_option format.indent : Nat := {
defValue := defIndent
descr := "indentation"
}
def pretty' (f : Format) (o : Options := {}) : String :=
pretty f (format.width.get o)
end Format
end Std
namespace Lean
open Std
export Std
(Format ToFormat fmt Format.nest Format.nil Format.joinSep Format.line
Format.sbracket Format.bracket Format.group Format.pretty Format.fill Format.paren Format.join)
export Std.ToFormat (format)
instance : ToFormat Name where
format n := n.toString
instance : ToFormat DataValue where
format
| DataValue.ofString v => format (repr v)
| DataValue.ofBool v => format v
| DataValue.ofName v => "`" ++ format v
| DataValue.ofNat v => format v
| DataValue.ofInt v => format v
instance : ToFormat (Name × DataValue) where
format
| (n, v) => format n ++ " := " ++ format v
open Std.Format
def formatKVMap (m : KVMap) : Format :=
sbracket (Format.joinSep m.entries ", ")
instance : ToFormat KVMap := ⟨formatKVMap⟩
end Lean
|
8f94dc8c44541e285993fa5779e915b4b246d0c7 | 0bd6c950c82dcba3e46dc8d8acb5ecc60b917520 | /Schroder_Bernstein.lean | 19093e38060d4312f3ca992960d2118eb9fae202 | [] | no_license | truonghoangle/formalabstracts | 976dbbdede5c71346a3c534a8f319456248d4610 | b889ec60143315053a51b1829a5dc4d82ba503b3 | refs/heads/master | 1,584,899,948,798 | 1,537,184,894,000 | 1,537,184,894,000 | 140,428,980 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 285 | lean |
import data.set.function
open set
variables α β : Type
variables A :set α
variables B :set β
variable f:α → β
variable g:β → α
theorem Schroder_Bernstein:
inj_on f A ∧ inj_on g B ∧ maps_to f A B ∧ maps_to g B A → ∃ h:α → β, bij_on h A B
:=
sorry
|
2614130c0273210d5079155a3c2569414c4934ea | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/category_theory/limits/shapes/wide_pullbacks.lean | 3ed9f987f14aa2c51cc33bd4d90b54bcbdf44ae2 | [
"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 | 16,849 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta, Jakob von Raumer
-/
import category_theory.limits.has_limits
import category_theory.thin
/-!
# Wide pullbacks
We define the category `wide_pullback_shape`, (resp. `wide_pushout_shape`) which is the category
obtained from a discrete category of type `J` by adjoining a terminal (resp. initial) element.
Limits of this shape are wide pullbacks (pushouts).
The convenience method `wide_cospan` (`wide_span`) constructs a functor from this category, hitting
the given morphisms.
We use `wide_pullback_shape` to define ordinary pullbacks (pushouts) by using `J := walking_pair`,
which allows easy proofs of some related lemmas.
Furthermore, wide pullbacks are used to show the existence of limits in the slice category.
Namely, if `C` has wide pullbacks then `C/B` has limits for any object `B` in `C`.
Typeclasses `has_wide_pullbacks` and `has_finite_wide_pullbacks` assert the existence of wide
pullbacks and finite wide pullbacks.
-/
universes w w' v u
open category_theory category_theory.limits opposite
namespace category_theory.limits
variable (J : Type w)
/-- A wide pullback shape for any type `J` can be written simply as `option J`. -/
@[derive inhabited]
def wide_pullback_shape := option J
/-- A wide pushout shape for any type `J` can be written simply as `option J`. -/
@[derive inhabited]
def wide_pushout_shape := option J
namespace wide_pullback_shape
variable {J}
/-- The type of arrows for the shape indexing a wide pullback. -/
@[derive decidable_eq]
inductive hom : wide_pullback_shape J → wide_pullback_shape J → Type w
| id : Π X, hom X X
| term : Π (j : J), hom (some j) none
attribute [nolint unused_arguments] hom.decidable_eq
instance struct : category_struct (wide_pullback_shape J) :=
{ hom := hom,
id := λ j, hom.id j,
comp := λ j₁ j₂ j₃ f g,
begin
cases f,
exact g,
cases g,
apply hom.term _
end }
instance hom.inhabited : inhabited (hom none none) := ⟨hom.id (none : wide_pullback_shape J)⟩
local attribute [tidy] tactic.case_bash
instance subsingleton_hom (j j' : wide_pullback_shape J) : subsingleton (j ⟶ j') :=
⟨by tidy⟩
instance category : small_category (wide_pullback_shape J) := thin_category
@[simp] lemma hom_id (X : wide_pullback_shape J) : hom.id X = 𝟙 X := rfl
variables {C : Type u} [category.{v} C]
/--
Construct a functor out of the wide pullback shape given a J-indexed collection of arrows to a
fixed object.
-/
@[simps]
def wide_cospan (B : C) (objs : J → C) (arrows : Π (j : J), objs j ⟶ B) :
wide_pullback_shape J ⥤ C :=
{ obj := λ j, option.cases_on j B objs,
map := λ X Y f,
begin
cases f with _ j,
{ apply (𝟙 _) },
{ exact arrows j }
end,
map_comp' := λ _ _ _ f g,
begin
cases f,
{ simpa },
cases g,
simp
end }
/-- Every diagram is naturally isomorphic (actually, equal) to a `wide_cospan` -/
def diagram_iso_wide_cospan (F : wide_pullback_shape J ⥤ C) :
F ≅ wide_cospan (F.obj none) (λ j, F.obj (some j)) (λ j, F.map (hom.term j)) :=
nat_iso.of_components (λ j, eq_to_iso $ by tidy) $ by tidy
/-- Construct a cone over a wide cospan. -/
@[simps]
def mk_cone {F : wide_pullback_shape J ⥤ C} {X : C}
(f : X ⟶ F.obj none) (π : Π j, X ⟶ F.obj (some j))
(w : ∀ j, π j ≫ F.map (hom.term j) = f) : cone F :=
{ X := X,
π :=
{ app := λ j, match j with
| none := f
| (some j) := π j
end,
naturality' := λ j j' f, by { cases j; cases j'; cases f; unfold_aux; dsimp; simp [w], }, } }
/-- Wide pullback diagrams of equivalent index types are equivlent. -/
def equivalence_of_equiv (J' : Type w') (h : J ≃ J') :
wide_pullback_shape J ≌ wide_pullback_shape J' :=
{ functor := wide_cospan none (λ j, some (h j)) (λ j, hom.term (h j)),
inverse := wide_cospan none (λ j, some (h.inv_fun j)) (λ j, hom.term (h.inv_fun j)),
unit_iso := nat_iso.of_components (λ j, by cases j; simp)
(λ j k f, by { simp only [eq_iff_true_of_subsingleton]}),
counit_iso := nat_iso.of_components (λ j, by cases j; simp)
(λ j k f, by { simp only [eq_iff_true_of_subsingleton]}) }
/-- Lifting universe and morphism levels preserves wide pullback diagrams. -/
def ulift_equivalence :
ulift_hom.{w'} (ulift.{w'} (wide_pullback_shape J)) ≌ wide_pullback_shape (ulift J) :=
(ulift_hom_ulift_category.equiv.{w' w' w w} (wide_pullback_shape J)).symm.trans
(equivalence_of_equiv _ (equiv.ulift.{w' w}.symm : J ≃ ulift.{w'} J))
end wide_pullback_shape
namespace wide_pushout_shape
variable {J}
/-- The type of arrows for the shape indexing a wide psuhout. -/
@[derive decidable_eq]
inductive hom : wide_pushout_shape J → wide_pushout_shape J → Type w
| id : Π X, hom X X
| init : Π (j : J), hom none (some j)
attribute [nolint unused_arguments] hom.decidable_eq
instance struct : category_struct (wide_pushout_shape J) :=
{ hom := hom,
id := λ j, hom.id j,
comp := λ j₁ j₂ j₃ f g,
begin
cases f,
exact g,
cases g,
apply hom.init _
end }
instance hom.inhabited : inhabited (hom none none) := ⟨hom.id (none : wide_pushout_shape J)⟩
local attribute [tidy] tactic.case_bash
instance subsingleton_hom (j j' : wide_pushout_shape J) : subsingleton (j ⟶ j') :=
⟨by tidy⟩
instance category : small_category (wide_pushout_shape J) := thin_category
@[simp] lemma hom_id (X : wide_pushout_shape J) : hom.id X = 𝟙 X := rfl
variables {C : Type u} [category.{v} C]
/--
Construct a functor out of the wide pushout shape given a J-indexed collection of arrows from a
fixed object.
-/
@[simps]
def wide_span (B : C) (objs : J → C) (arrows : Π (j : J), B ⟶ objs j) : wide_pushout_shape J ⥤ C :=
{ obj := λ j, option.cases_on j B objs,
map := λ X Y f,
begin
cases f with _ j,
{ apply (𝟙 _) },
{ exact arrows j }
end,
map_comp' := by { rintros (_|_) (_|_) (_|_) (_|_) (_|_); simpa <|> simp } }
/-- Every diagram is naturally isomorphic (actually, equal) to a `wide_span` -/
def diagram_iso_wide_span (F : wide_pushout_shape J ⥤ C) :
F ≅ wide_span (F.obj none) (λ j, F.obj (some j)) (λ j, F.map (hom.init j)) :=
nat_iso.of_components (λ j, eq_to_iso $ by tidy) $ by tidy
/-- Construct a cocone over a wide span. -/
@[simps]
def mk_cocone {F : wide_pushout_shape J ⥤ C} {X : C}
(f : F.obj none ⟶ X) (ι : Π j, F.obj (some j) ⟶ X)
(w : ∀ j, F.map (hom.init j) ≫ ι j = f) : cocone F :=
{ X := X,
ι :=
{ app := λ j, match j with
| none := f
| (some j) := ι j
end,
naturality' := λ j j' f, by { cases j; cases j'; cases f; unfold_aux; dsimp; simp [w], }, } }
end wide_pushout_shape
variables (C : Type u) [category.{v} C]
/-- `has_wide_pullbacks` represents a choice of wide pullback for every collection of morphisms -/
abbreviation has_wide_pullbacks : Prop :=
Π (J : Type w), has_limits_of_shape (wide_pullback_shape J) C
/-- `has_wide_pushouts` represents a choice of wide pushout for every collection of morphisms -/
abbreviation has_wide_pushouts : Prop :=
Π (J : Type w), has_colimits_of_shape (wide_pushout_shape J) C
variables {C J}
/-- `has_wide_pullback B objs arrows` means that `wide_cospan B objs arrows` has a limit. -/
abbreviation has_wide_pullback (B : C) (objs : J → C)
(arrows : Π (j : J), objs j ⟶ B) : Prop :=
has_limit (wide_pullback_shape.wide_cospan B objs arrows)
/-- `has_wide_pushout B objs arrows` means that `wide_span B objs arrows` has a colimit. -/
abbreviation has_wide_pushout (B : C) (objs : J → C)
(arrows : Π (j : J), B ⟶ objs j) : Prop :=
has_colimit (wide_pushout_shape.wide_span B objs arrows)
/-- A choice of wide pullback. -/
noncomputable
abbreviation wide_pullback (B : C) (objs : J → C) (arrows : Π (j : J), objs j ⟶ B)
[has_wide_pullback B objs arrows] : C :=
limit (wide_pullback_shape.wide_cospan B objs arrows)
/-- A choice of wide pushout. -/
noncomputable
abbreviation wide_pushout (B : C) (objs : J → C) (arrows : Π (j : J), B ⟶ objs j)
[has_wide_pushout B objs arrows] : C :=
colimit (wide_pushout_shape.wide_span B objs arrows)
variable (C)
namespace wide_pullback
variables {C} {B : C} {objs : J → C} (arrows : Π (j : J), objs j ⟶ B)
variables [has_wide_pullback B objs arrows]
/-- The `j`-th projection from the pullback. -/
noncomputable
abbreviation π (j : J) : wide_pullback _ _ arrows ⟶ objs j :=
limit.π (wide_pullback_shape.wide_cospan _ _ _) (option.some j)
/-- The unique map to the base from the pullback. -/
noncomputable
abbreviation base : wide_pullback _ _ arrows ⟶ B :=
limit.π (wide_pullback_shape.wide_cospan _ _ _) option.none
@[simp, reassoc]
lemma π_arrow (j : J) : π arrows j ≫ arrows _ = base arrows :=
by apply limit.w (wide_pullback_shape.wide_cospan _ _ _) (wide_pullback_shape.hom.term j)
variables {arrows}
/-- Lift a collection of morphisms to a morphism to the pullback. -/
noncomputable
abbreviation lift {X : C} (f : X ⟶ B) (fs : Π (j : J), X ⟶ objs j)
(w : ∀ j, fs j ≫ arrows j = f) : X ⟶ wide_pullback _ _ arrows :=
limit.lift (wide_pullback_shape.wide_cospan _ _ _)
(wide_pullback_shape.mk_cone f fs $ by exact w)
variables (arrows)
variables {X : C} (f : X ⟶ B) (fs : Π (j : J), X ⟶ objs j)
(w : ∀ j, fs j ≫ arrows j = f)
@[simp, reassoc]
lemma lift_π (j : J) : lift f fs w ≫ π arrows j = fs _ :=
by { simp, refl }
@[simp, reassoc]
lemma lift_base : lift f fs w ≫ base arrows = f :=
by { simp, refl }
lemma eq_lift_of_comp_eq (g : X ⟶ wide_pullback _ _ arrows) :
(∀ j : J, g ≫ π arrows j = fs j) → g ≫ base arrows = f → g = lift f fs w :=
begin
intros h1 h2,
apply (limit.is_limit (wide_pullback_shape.wide_cospan B objs arrows)).uniq
(wide_pullback_shape.mk_cone f fs $ by exact w),
rintro (_|_),
{ apply h2 },
{ apply h1 }
end
lemma hom_eq_lift (g : X ⟶ wide_pullback _ _ arrows) :
g = lift (g ≫ base arrows) (λ j, g ≫ π arrows j) (by tidy) :=
begin
apply eq_lift_of_comp_eq,
tidy,
end
@[ext]
lemma hom_ext (g1 g2 : X ⟶ wide_pullback _ _ arrows) :
(∀ j : J, g1 ≫ π arrows j = g2 ≫ π arrows j) →
g1 ≫ base arrows = g2 ≫ base arrows → g1 = g2 :=
begin
intros h1 h2,
apply limit.hom_ext,
rintros (_|_),
{ apply h2 },
{ apply h1 },
end
end wide_pullback
namespace wide_pushout
variables {C} {B : C} {objs : J → C} (arrows : Π (j : J), B ⟶ objs j)
variables [has_wide_pushout B objs arrows]
/-- The `j`-th inclusion to the pushout. -/
noncomputable
abbreviation ι (j : J) : objs j ⟶ wide_pushout _ _ arrows :=
colimit.ι (wide_pushout_shape.wide_span _ _ _) (option.some j)
/-- The unique map from the head to the pushout. -/
noncomputable
abbreviation head : B ⟶ wide_pushout B objs arrows :=
colimit.ι (wide_pushout_shape.wide_span _ _ _) option.none
@[simp, reassoc]
lemma arrow_ι (j : J) : arrows j ≫ ι arrows j = head arrows :=
by apply colimit.w (wide_pushout_shape.wide_span _ _ _) (wide_pushout_shape.hom.init j)
variables {arrows}
/-- Descend a collection of morphisms to a morphism from the pushout. -/
noncomputable
abbreviation desc {X : C} (f : B ⟶ X) (fs : Π (j : J), objs j ⟶ X)
(w : ∀ j, arrows j ≫ fs j = f) : wide_pushout _ _ arrows ⟶ X :=
colimit.desc (wide_pushout_shape.wide_span B objs arrows)
(wide_pushout_shape.mk_cocone f fs $ by exact w)
variables (arrows)
variables {X : C} (f : B ⟶ X) (fs : Π (j : J), objs j ⟶ X)
(w : ∀ j, arrows j ≫ fs j = f)
@[simp, reassoc]
lemma ι_desc (j : J) : ι arrows j ≫ desc f fs w = fs _ :=
by { simp, refl }
@[simp, reassoc]
lemma head_desc : head arrows ≫ desc f fs w = f :=
by { simp, refl }
lemma eq_desc_of_comp_eq (g : wide_pushout _ _ arrows ⟶ X) :
(∀ j : J, ι arrows j ≫ g = fs j) → head arrows ≫ g = f → g = desc f fs w :=
begin
intros h1 h2,
apply (colimit.is_colimit (wide_pushout_shape.wide_span B objs arrows)).uniq
(wide_pushout_shape.mk_cocone f fs $ by exact w),
rintro (_|_),
{ apply h2 },
{ apply h1 }
end
lemma hom_eq_desc (g : wide_pushout _ _ arrows ⟶ X) :
g = desc (head arrows ≫ g) (λ j, ι arrows j ≫ g) (λ j, by { rw ← category.assoc, simp }) :=
begin
apply eq_desc_of_comp_eq,
tidy,
end
@[ext]
lemma hom_ext (g1 g2 : wide_pushout _ _ arrows ⟶ X) :
(∀ j : J, ι arrows j ≫ g1 = ι arrows j ≫ g2) →
head arrows ≫ g1 = head arrows ≫ g2 → g1 = g2 :=
begin
intros h1 h2,
apply colimit.hom_ext,
rintros (_|_),
{ apply h2 },
{ apply h1 },
end
end wide_pushout
variable (J)
/-- The action on morphisms of the obvious functor
`wide_pullback_shape_op : wide_pullback_shape J ⥤ (wide_pushout_shape J)ᵒᵖ`-/
def wide_pullback_shape_op_map : Π (X Y : wide_pullback_shape J),
(X ⟶ Y) → ((op X : (wide_pushout_shape J)ᵒᵖ) ⟶ (op Y : (wide_pushout_shape J)ᵒᵖ))
| _ _ (wide_pullback_shape.hom.id X) := quiver.hom.op (wide_pushout_shape.hom.id _)
| _ _ (wide_pullback_shape.hom.term j) := quiver.hom.op (wide_pushout_shape.hom.init _)
/-- The obvious functor `wide_pullback_shape J ⥤ (wide_pushout_shape J)ᵒᵖ` -/
@[simps]
def wide_pullback_shape_op : wide_pullback_shape J ⥤ (wide_pushout_shape J)ᵒᵖ :=
{ obj := λ X, op X,
map := wide_pullback_shape_op_map J, }
/-- The action on morphisms of the obvious functor
`wide_pushout_shape_op : `wide_pushout_shape J ⥤ (wide_pullback_shape J)ᵒᵖ` -/
def wide_pushout_shape_op_map : Π (X Y : wide_pushout_shape J),
(X ⟶ Y) → ((op X : (wide_pullback_shape J)ᵒᵖ) ⟶ (op Y : (wide_pullback_shape J)ᵒᵖ))
| _ _ (wide_pushout_shape.hom.id X) := quiver.hom.op (wide_pullback_shape.hom.id _)
| _ _ (wide_pushout_shape.hom.init j) := quiver.hom.op (wide_pullback_shape.hom.term _)
/-- The obvious functor `wide_pushout_shape J ⥤ (wide_pullback_shape J)ᵒᵖ` -/
@[simps]
def wide_pushout_shape_op : wide_pushout_shape J ⥤ (wide_pullback_shape J)ᵒᵖ :=
{ obj := λ X, op X,
map := wide_pushout_shape_op_map J, }
/-- The obvious functor `(wide_pullback_shape J)ᵒᵖ ⥤ wide_pushout_shape J`-/
@[simps]
def wide_pullback_shape_unop : (wide_pullback_shape J)ᵒᵖ ⥤ wide_pushout_shape J :=
(wide_pullback_shape_op J).left_op
/-- The obvious functor `(wide_pushout_shape J)ᵒᵖ ⥤ wide_pullback_shape J` -/
@[simps]
def wide_pushout_shape_unop : (wide_pushout_shape J)ᵒᵖ ⥤ wide_pullback_shape J :=
(wide_pushout_shape_op J).left_op
/-- The inverse of the unit isomorphism of the equivalence
`wide_pushout_shape_op_equiv : (wide_pushout_shape J)ᵒᵖ ≌ wide_pullback_shape J` -/
def wide_pushout_shape_op_unop : wide_pushout_shape_unop J ⋙ wide_pullback_shape_op J ≅ 𝟭 _ :=
nat_iso.of_components (λ X, iso.refl _) (λ X Y f, dec_trivial)
/-- The counit isomorphism of the equivalence
`wide_pullback_shape_op_equiv : (wide_pullback_shape J)ᵒᵖ ≌ wide_pushout_shape J` -/
def wide_pushout_shape_unop_op : wide_pushout_shape_op J ⋙ wide_pullback_shape_unop J ≅ 𝟭 _ :=
nat_iso.of_components (λ X, iso.refl _) (λ X Y f, dec_trivial)
/-- The inverse of the unit isomorphism of the equivalence
`wide_pullback_shape_op_equiv : (wide_pullback_shape J)ᵒᵖ ≌ wide_pushout_shape J` -/
def wide_pullback_shape_op_unop : wide_pullback_shape_unop J ⋙ wide_pushout_shape_op J ≅ 𝟭 _ :=
nat_iso.of_components (λ X, iso.refl _) (λ X Y f, dec_trivial)
/-- The counit isomorphism of the equivalence
`wide_pushout_shape_op_equiv : (wide_pushout_shape J)ᵒᵖ ≌ wide_pullback_shape J` -/
def wide_pullback_shape_unop_op : wide_pullback_shape_op J ⋙ wide_pushout_shape_unop J ≅ 𝟭 _ :=
nat_iso.of_components (λ X, iso.refl _) (λ X Y f, dec_trivial)
/-- The duality equivalence `(wide_pushout_shape J)ᵒᵖ ≌ wide_pullback_shape J` -/
@[simps]
def wide_pushout_shape_op_equiv : (wide_pushout_shape J)ᵒᵖ ≌ wide_pullback_shape J :=
{ functor := wide_pushout_shape_unop J,
inverse := wide_pullback_shape_op J,
unit_iso := (wide_pushout_shape_op_unop J).symm,
counit_iso := wide_pullback_shape_unop_op J, }
/-- The duality equivalence `(wide_pullback_shape J)ᵒᵖ ≌ wide_pushout_shape J` -/
@[simps]
def wide_pullback_shape_op_equiv : (wide_pullback_shape J)ᵒᵖ ≌ wide_pushout_shape J :=
{ functor := wide_pullback_shape_unop J,
inverse := wide_pushout_shape_op J,
unit_iso := (wide_pullback_shape_op_unop J).symm,
counit_iso := wide_pushout_shape_unop_op J, }
/-- If a category has wide pullbacks on a higher universe level it also has wide pullbacks
on a lower universe level. -/
lemma has_wide_pullbacks_shrink [has_wide_pullbacks.{max w w'} C] : has_wide_pullbacks.{w} C :=
λ J, has_limits_of_shape_of_equivalence
(wide_pullback_shape.equivalence_of_equiv _ equiv.ulift.{w'})
end category_theory.limits
|
53d0b9e3ebfe04acb9175b0dd9bb220480c71556 | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/data/option/basic.lean | a1a27ae0de13d65029a91fdb20aba7326a4bbf3f | [
"Apache-2.0"
] | permissive | hikari0108/mathlib | b7ea2b7350497ab1a0b87a09d093ecc025a50dfa | a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901 | refs/heads/master | 1,690,483,608,260 | 1,631,541,580,000 | 1,631,541,580,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 17,323 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import tactic.basic
import logic.is_empty
/-!
# Option of a type
This file develops the basic theory of option types.
If `α` is a type, then `option α` can be understood as the type with one more element than `α`.
`option α` has terms `some a`, where `a : α`, and `none`, which is the added element.
This is useful in multiple ways:
* It is the prototype of addition of terms to a type. See for example `with_bot α` which uses
`none` as an element smaller than all others.
* It can be used to define failsafe partial functions, which return `some the_result_we_expect`
if we can find `the_result_we_expect`, and `none` if there is no meaningful result. This forces
any subsequent use of the partial function to explicitly deal with the exceptions that make it
return `none`.
* `option` is a monad. We love monads.
`part` is an alternative to `option` that can be seen as the type of `true`/`false` values
along with a term `a : α` if the value is `true`.
## Implementation notes
`option` is currently defined in core Lean, but this will change in Lean 4.
-/
namespace option
variables {α : Type*} {β : Type*} {γ : Type*}
lemma coe_def : (coe : α → option α) = some := rfl
lemma some_ne_none (x : α) : some x ≠ none := λ h, option.no_confusion h
protected lemma «forall» {p : option α → Prop} : (∀ x, p x) ↔ p none ∧ ∀ x, p (some x) :=
⟨λ h, ⟨h _, λ x, h _⟩, λ h x, option.cases_on x h.1 h.2⟩
protected lemma «exists» {p : option α → Prop} : (∃ x, p x) ↔ p none ∨ ∃ x, p (some x) :=
⟨λ ⟨x, hx⟩, (option.cases_on x or.inl $ λ x hx, or.inr ⟨x, hx⟩) hx,
λ h, h.elim (λ h, ⟨_, h⟩) (λ ⟨x, hx⟩, ⟨_, hx⟩)⟩
@[simp] theorem get_mem : ∀ {o : option α} (h : is_some o), option.get h ∈ o
| (some a) _ := rfl
theorem get_of_mem {a : α} : ∀ {o : option α} (h : is_some o), a ∈ o → option.get h = a
| _ _ rfl := rfl
@[simp] lemma not_mem_none (a : α) : a ∉ (none : option α) :=
λ h, option.no_confusion h
@[simp] lemma some_get : ∀ {x : option α} (h : is_some x), some (option.get h) = x
| (some x) hx := rfl
@[simp] lemma get_some (x : α) (h : is_some (some x)) : option.get h = x := rfl
@[simp] lemma get_or_else_some (x y : α) : option.get_or_else (some x) y = x := rfl
@[simp] lemma get_or_else_none (x : α) : option.get_or_else none x = x := rfl
@[simp] lemma get_or_else_coe (x y : α) : option.get_or_else ↑x y = x := rfl
lemma get_or_else_of_ne_none {x : option α} (hx : x ≠ none) (y : α) : some (x.get_or_else y) = x :=
by cases x; [contradiction, rw get_or_else_some]
theorem mem_unique {o : option α} {a b : α} (ha : a ∈ o) (hb : b ∈ o) : a = b :=
option.some.inj $ ha.symm.trans hb
theorem mem.left_unique : relator.left_unique ((∈) : α → option α → Prop) :=
⟨λ a o b, mem_unique⟩
theorem some_injective (α : Type*) : function.injective (@some α) :=
λ _ _, some_inj.mp
/-- `option.map f` is injective if `f` is injective. -/
theorem map_injective {f : α → β} (Hf : function.injective f) : function.injective (option.map f)
| none none H := rfl
| (some a₁) (some a₂) H := by rw Hf (option.some.inj H)
@[ext] theorem ext : ∀ {o₁ o₂ : option α}, (∀ a, a ∈ o₁ ↔ a ∈ o₂) → o₁ = o₂
| none none H := rfl
| (some a) o H := ((H _).1 rfl).symm
| o (some b) H := (H _).2 rfl
theorem eq_none_iff_forall_not_mem {o : option α} :
o = none ↔ (∀ a, a ∉ o) :=
⟨λ e a h, by rw e at h; cases h, λ h, ext $ by simpa⟩
@[simp] theorem none_bind {α β} (f : α → option β) : none >>= f = none := rfl
@[simp] theorem some_bind {α β} (a : α) (f : α → option β) : some a >>= f = f a := rfl
@[simp] theorem none_bind' (f : α → option β) : none.bind f = none := rfl
@[simp] theorem some_bind' (a : α) (f : α → option β) : (some a).bind f = f a := rfl
@[simp] theorem bind_some : ∀ x : option α, x >>= some = x :=
@bind_pure α option _ _
@[simp] theorem bind_eq_some {α β} {x : option α} {f : α → option β} {b : β} :
x >>= f = some b ↔ ∃ a, x = some a ∧ f a = some b :=
by cases x; simp
@[simp] theorem bind_eq_some' {x : option α} {f : α → option β} {b : β} :
x.bind f = some b ↔ ∃ a, x = some a ∧ f a = some b :=
by cases x; simp
@[simp] theorem bind_eq_none' {o : option α} {f : α → option β} :
o.bind f = none ↔ (∀ b a, a ∈ o → b ∉ f a) :=
by simp only [eq_none_iff_forall_not_mem, not_exists, not_and, mem_def, bind_eq_some']
@[simp] theorem bind_eq_none {α β} {o : option α} {f : α → option β} :
o >>= f = none ↔ (∀ b a, a ∈ o → b ∉ f a) :=
bind_eq_none'
lemma bind_comm {α β γ} {f : α → β → option γ} (a : option α) (b : option β) :
a.bind (λx, b.bind (f x)) = b.bind (λy, a.bind (λx, f x y)) :=
by cases a; cases b; refl
lemma bind_assoc (x : option α) (f : α → option β) (g : β → option γ) :
(x.bind f).bind g = x.bind (λ y, (f y).bind g) := by cases x; refl
lemma join_eq_some {x : option (option α)} {a : α} : x.join = some a ↔ x = some (some a) := by simp
lemma join_ne_none {x : option (option α)} : x.join ≠ none ↔ ∃ z, x = some (some z) := by simp
lemma join_ne_none' {x : option (option α)} : ¬(x.join = none) ↔ ∃ z, x = some (some z) := by simp
lemma join_eq_none {o : option (option α)} : o.join = none ↔ o = none ∨ o = some none :=
by rcases o with _|_|_; simp
lemma bind_id_eq_join {x : option (option α)} : x >>= id = x.join := by simp
lemma join_eq_join : mjoin = @join α :=
funext (λ x, by rw [mjoin, bind_id_eq_join])
lemma bind_eq_bind {α β : Type*} {f : α → option β} {x : option α} :
x >>= f = x.bind f := rfl
@[simp] lemma map_eq_map {α β} {f : α → β} :
(<$>) f = option.map f := rfl
theorem map_none {α β} {f : α → β} : f <$> none = none := rfl
theorem map_some {α β} {a : α} {f : α → β} : f <$> some a = some (f a) := rfl
@[simp] theorem map_none' {f : α → β} : option.map f none = none := rfl
@[simp] theorem map_some' {a : α} {f : α → β} : option.map f (some a) = some (f a) := rfl
theorem map_eq_some {α β} {x : option α} {f : α → β} {b : β} :
f <$> x = some b ↔ ∃ a, x = some a ∧ f a = b :=
by cases x; simp
@[simp] theorem map_eq_some' {x : option α} {f : α → β} {b : β} :
x.map f = some b ↔ ∃ a, x = some a ∧ f a = b :=
by cases x; simp
lemma map_eq_none {α β} {x : option α} {f : α → β} :
f <$> x = none ↔ x = none :=
by { cases x; simp only [map_none, map_some, eq_self_iff_true] }
@[simp] lemma map_eq_none' {x : option α} {f : α → β} :
x.map f = none ↔ x = none :=
by { cases x; simp only [map_none', map_some', eq_self_iff_true] }
lemma map_congr {f g : α → β} {x : option α} (h : ∀ a ∈ x, f a = g a) :
option.map f x = option.map g x :=
by { cases x; simp only [map_none', map_some', h, mem_def] }
@[simp] theorem map_id' : option.map (@id α) = id := map_id
@[simp] lemma map_map (h : β → γ) (g : α → β) (x : option α) :
option.map h (option.map g x) = option.map (h ∘ g) x :=
by { cases x; simp only [map_none', map_some'] }
lemma comp_map (h : β → γ) (g : α → β) (x : option α) :
option.map (h ∘ g) x = option.map h (option.map g x) := (map_map _ _ _).symm
@[simp] lemma map_comp_map (f : α → β) (g : β → γ) :
option.map g ∘ option.map f = option.map (g ∘ f) :=
by { ext x, rw comp_map }
lemma mem_map_of_mem {α β : Type*} {a : α} {x : option α} (g : α → β) (h : a ∈ x) : g a ∈ x.map g :=
mem_def.mpr ((mem_def.mp h).symm ▸ map_some')
lemma bind_map_comm {α β} {x : option (option α) } {f : α → β} :
x >>= option.map f = x.map (option.map f) >>= id :=
by { cases x; simp }
lemma join_map_eq_map_join {f : α → β} {x : option (option α)} :
(x.map (option.map f)).join = x.join.map f :=
by { rcases x with _ | _ | x; simp }
lemma join_join {x : option (option (option α))} :
x.join.join = (x.map join).join :=
by { rcases x with _ | _ | _ | x; simp }
lemma mem_of_mem_join {a : α} {x : option (option α)} (h : a ∈ x.join) : some a ∈ x :=
mem_def.mpr ((mem_def.mp h).symm ▸ join_eq_some.mp h)
section pmap
variables {p : α → Prop} (f : Π (a : α), p a → β) (x : option α)
@[simp] lemma pbind_eq_bind (f : α → option β) (x : option α) :
x.pbind (λ a _, f a) = x.bind f :=
by { cases x; simp only [pbind, none_bind', some_bind'] }
lemma map_bind {α β γ} (f : β → γ) (x : option α) (g : α → option β) :
option.map f (x >>= g) = (x >>= λ a, option.map f (g a)) :=
by simp_rw [←map_eq_map, ←bind_pure_comp_eq_map,is_lawful_monad.bind_assoc]
lemma map_bind' (f : β → γ) (x : option α) (g : α → option β) :
option.map f (x.bind g) = x.bind (λ a, option.map f (g a)) :=
by { cases x; simp }
lemma map_pbind (f : β → γ) (x : option α) (g : Π a, a ∈ x → option β) :
option.map f (x.pbind g) = (x.pbind (λ a H, option.map f (g a H))) :=
by { cases x; simp only [pbind, map_none'] }
lemma pbind_map (f : α → β) (x : option α) (g : Π (b : β), b ∈ x.map f → option γ) :
pbind (option.map f x) g = x.pbind (λ a h, g (f a) (mem_map_of_mem _ h)) :=
by { cases x; refl }
@[simp] lemma pmap_none (f : Π (a : α), p a → β) {H} : pmap f (@none α) H = none := rfl
@[simp] lemma pmap_some (f : Π (a : α), p a → β) {x : α} (h : p x) :
pmap f (some x) = λ _, some (f x h) := rfl
lemma mem_pmem {a : α} (h : ∀ a ∈ x, p a) (ha : a ∈ x) :
f a (h a ha) ∈ pmap f x h :=
by { rw mem_def at ha ⊢, subst ha, refl }
lemma pmap_map (g : γ → α) (x : option γ) (H) :
pmap f (x.map g) H = pmap (λ a h, f (g a) h) x (λ a h, H _ (mem_map_of_mem _ h)) :=
by { cases x; simp only [map_none', map_some', pmap] }
lemma map_pmap (g : β → γ) (f : Π a, p a → β) (x H) :
option.map g (pmap f x H) = pmap (λ a h, g (f a h)) x H :=
by { cases x; simp only [map_none', map_some', pmap] }
@[simp] lemma pmap_eq_map (p : α → Prop) (f : α → β) (x H) :
@pmap _ _ p (λ a _, f a) x H = option.map f x :=
by { cases x; simp only [map_none', map_some', pmap] }
lemma pmap_bind {α β γ} {x : option α} {g : α → option β} {p : β → Prop} {f : Π b, p b → γ}
(H) (H' : ∀ (a : α) b ∈ g a, b ∈ x >>= g) :
pmap f (x >>= g) H = (x >>= λa, pmap f (g a) (λ b h, H _ (H' a _ h))) :=
by { cases x; simp only [pmap, none_bind, some_bind] }
lemma bind_pmap {α β γ} {p : α → Prop} (f : Π a, p a → β) (x : option α) (g : β → option γ) (H) :
(pmap f x H) >>= g = x.pbind (λ a h, g (f a (H _ h))) :=
by { cases x; simp only [pmap, none_bind, some_bind, pbind] }
variables {f x}
lemma pbind_eq_none {f : Π (a : α), a ∈ x → option β}
(h' : ∀ a ∈ x, f a H = none → x = none) :
x.pbind f = none ↔ x = none :=
begin
cases x,
{ simp },
{ simp only [pbind, iff_false],
intro h,
cases h' x rfl h }
end
lemma pbind_eq_some {f : Π (a : α), a ∈ x → option β} {y : β} :
x.pbind f = some y ↔ ∃ (z ∈ x), f z H = some y :=
begin
cases x,
{ simp },
{ simp only [pbind],
split,
{ intro h,
use x,
simpa only [mem_def, exists_prop_of_true] using h },
{ rintro ⟨z, H, hz⟩,
simp only [mem_def] at H,
simpa only [H] using hz } }
end
@[simp] lemma pmap_eq_none_iff {h} :
pmap f x h = none ↔ x = none :=
by { cases x; simp }
@[simp] lemma pmap_eq_some_iff {hf} {y : β} :
pmap f x hf = some y ↔ ∃ (a : α) (H : x = some a), f a (hf a H) = y :=
begin
cases x,
{ simp only [not_mem_none, exists_false, pmap, not_false_iff, exists_prop_of_false] },
{ split,
{ intro h,
simp only [pmap] at h,
exact ⟨x, rfl, h⟩ },
{ rintro ⟨a, H, rfl⟩,
simp only [mem_def] at H,
simp only [H, pmap] } }
end
@[simp] lemma join_pmap_eq_pmap_join {f : Π a, p a → β} {x : option (option α)} (H) :
(pmap (pmap f) x H).join = pmap f x.join (λ a h, H (some a) (mem_of_mem_join h) _ rfl) :=
by { rcases x with _ | _ | x; simp }
end pmap
@[simp] theorem seq_some {α β} {a : α} {f : α → β} : some f <*> some a = some (f a) := rfl
@[simp] theorem some_orelse' (a : α) (x : option α) : (some a).orelse x = some a := rfl
@[simp] theorem some_orelse (a : α) (x : option α) : (some a <|> x) = some a := rfl
@[simp] theorem none_orelse' (x : option α) : none.orelse x = x :=
by cases x; refl
@[simp] theorem none_orelse (x : option α) : (none <|> x) = x := none_orelse' x
@[simp] theorem orelse_none' (x : option α) : x.orelse none = x :=
by cases x; refl
@[simp] theorem orelse_none (x : option α) : (x <|> none) = x := orelse_none' x
@[simp] theorem is_some_none : @is_some α none = ff := rfl
@[simp] theorem is_some_some {a : α} : is_some (some a) = tt := rfl
theorem is_some_iff_exists {x : option α} : is_some x ↔ ∃ a, x = some a :=
by cases x; simp [is_some]; exact ⟨_, rfl⟩
@[simp] theorem is_none_none : @is_none α none = tt := rfl
@[simp] theorem is_none_some {a : α} : is_none (some a) = ff := rfl
@[simp] theorem not_is_some {a : option α} : is_some a = ff ↔ a.is_none = tt :=
by cases a; simp
lemma eq_some_iff_get_eq {o : option α} {a : α} :
o = some a ↔ ∃ h : o.is_some, option.get h = a :=
by cases o; simp
lemma not_is_some_iff_eq_none {o : option α} : ¬o.is_some ↔ o = none :=
by cases o; simp
lemma ne_none_iff_is_some {o : option α} : o ≠ none ↔ o.is_some :=
by cases o; simp
lemma ne_none_iff_exists {o : option α} : o ≠ none ↔ ∃ (x : α), some x = o :=
by {cases o; simp}
lemma ne_none_iff_exists' {o : option α} : o ≠ none ↔ ∃ (x : α), o = some x :=
ne_none_iff_exists.trans $ exists_congr $ λ _, eq_comm
lemma bex_ne_none {p : option α → Prop} :
(∃ x ≠ none, p x) ↔ ∃ x, p (some x) :=
⟨λ ⟨x, hx, hp⟩, ⟨get $ ne_none_iff_is_some.1 hx, by rwa [some_get]⟩,
λ ⟨x, hx⟩, ⟨some x, some_ne_none x, hx⟩⟩
lemma ball_ne_none {p : option α → Prop} :
(∀ x ≠ none, p x) ↔ ∀ x, p (some x) :=
⟨λ h x, h (some x) (some_ne_none x),
λ h x hx, by simpa only [some_get] using h (get $ ne_none_iff_is_some.1 hx)⟩
theorem iget_mem [inhabited α] : ∀ {o : option α}, is_some o → o.iget ∈ o
| (some a) _ := rfl
theorem iget_of_mem [inhabited α] {a : α} : ∀ {o : option α}, a ∈ o → o.iget = a
| _ rfl := rfl
@[simp] theorem guard_eq_some {p : α → Prop} [decidable_pred p] {a b : α} :
guard p a = some b ↔ a = b ∧ p a :=
by by_cases p a; simp [option.guard, h]; intro; contradiction
@[simp] theorem guard_eq_some' {p : Prop} [decidable p] :
∀ u, _root_.guard p = some u ↔ p
| () := by by_cases p; simp [guard, h, pure]; intro; contradiction
theorem lift_or_get_choice {f : α → α → α} (h : ∀ a b, f a b = a ∨ f a b = b) :
∀ o₁ o₂, lift_or_get f o₁ o₂ = o₁ ∨ lift_or_get f o₁ o₂ = o₂
| none none := or.inl rfl
| (some a) none := or.inl rfl
| none (some b) := or.inr rfl
| (some a) (some b) := by simpa [lift_or_get] using h a b
@[simp] lemma lift_or_get_none_left {f} {b : option α} : lift_or_get f none b = b :=
by cases b; refl
@[simp] lemma lift_or_get_none_right {f} {a : option α} : lift_or_get f a none = a :=
by cases a; refl
@[simp] lemma lift_or_get_some_some {f} {a b : α} :
lift_or_get f (some a) (some b) = f a b := rfl
/-- Given an element of `a : option α`, a default element `b : β` and a function `α → β`, apply this
function to `a` if it comes from `α`, and return `b` otherwise. -/
def cases_on' : option α → β → (α → β) → β
| none n s := n
| (some a) n s := s a
@[simp] lemma cases_on'_none (x : β) (f : α → β) : cases_on' none x f = x := rfl
@[simp] lemma cases_on'_some (x : β) (f : α → β) (a : α) : cases_on' (some a) x f = f a := rfl
@[simp] lemma cases_on'_coe (x : β) (f : α → β) (a : α) : cases_on' (a : option α) x f = f a := rfl
@[simp] lemma cases_on'_none_coe (f : option α → β) (o : option α) :
cases_on' o (f none) (f ∘ coe) = f o :=
by cases o; refl
@[simp] lemma get_or_else_map (f : α → β) (x : α) (o : option α) :
get_or_else (o.map f) (f x) = f (get_or_else o x) :=
by cases o; refl
section
open_locale classical
/-- An arbitrary `some a` with `a : α` if `α` is nonempty, and otherwise `none`. -/
noncomputable def choice (α : Type*) : option α :=
if h : nonempty α then
some h.some
else
none
lemma choice_eq {α : Type*} [subsingleton α] (a : α) : choice α = some a :=
begin
dsimp [choice],
rw dif_pos (⟨a⟩ : nonempty α),
congr,
end
lemma choice_eq_none (α : Type*) [is_empty α] : choice α = none :=
dif_neg (not_nonempty_iff_imp_false.mpr is_empty_elim)
lemma choice_is_some_iff_nonempty {α : Type*} : (choice α).is_some ↔ nonempty α :=
begin
fsplit,
{ intro h, exact ⟨option.get h⟩, },
{ intro h,
dsimp only [choice],
rw dif_pos h,
exact is_some_some },
end
end
@[simp] lemma to_list_some (a : α) : (a : option α).to_list = [a] :=
rfl
@[simp] lemma to_list_none (α : Type*) : (none : option α).to_list = [] :=
rfl
end option
|
1aeb83ea13bd8f81877517c4f9d3e84d9a86b1c5 | a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7 | /src/measure_theory/lebesgue_measure.lean | 07055e50777e168bf95e5100eb10005ff8cbe53d | [
"Apache-2.0"
] | permissive | kmill/mathlib | ea5a007b67ae4e9e18dd50d31d8aa60f650425ee | 1a419a9fea7b959317eddd556e1bb9639f4dcc05 | refs/heads/master | 1,668,578,197,719 | 1,593,629,163,000 | 1,593,629,163,000 | 276,482,939 | 0 | 0 | null | 1,593,637,960,000 | 1,593,637,959,000 | null | UTF-8 | Lean | false | false | 12,268 | 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
Lebesgue measure on the real line
-/
import measure_theory.measure_space
import measure_theory.borel_space
noncomputable theory
open classical set filter
open nnreal (of_real)
open_locale big_operators
namespace measure_theory
/-- Length of an interval. This is the largest monotonic function which correctly
measures all intervals. -/
def lebesgue_length (s : set ℝ) : ennreal := ⨅a b (h : s ⊆ Ico a b), of_real (b - a)
@[simp] lemma lebesgue_length_empty : lebesgue_length ∅ = 0 :=
le_zero_iff_eq.1 $ infi_le_of_le 0 $ infi_le_of_le 0 $ by simp
@[simp] lemma lebesgue_length_Ico (a b : ℝ) :
lebesgue_length (Ico a b) = of_real (b - a) :=
begin
refine le_antisymm (infi_le_of_le a $ infi_le_of_le b $ infi_le _ (by refl))
(le_infi $ λ a', le_infi $ λ b', le_infi $ λ h, ennreal.coe_le_coe.2 _),
cases le_or_lt b a with ab ab,
{ rw nnreal.of_real_of_nonpos (sub_nonpos.2 ab), simp },
cases (Ico_subset_Ico_iff ab).1 h with h₁ h₂,
exact nnreal.of_real_le_of_real (sub_le_sub h₂ h₁)
end
lemma lebesgue_length_mono {s₁ s₂ : set ℝ} (h : s₁ ⊆ s₂) : lebesgue_length s₁ ≤ lebesgue_length s₂ :=
infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h', ⟨subset.trans h h', le_refl _⟩
lemma lebesgue_length_eq_infi_Ioo (s) : lebesgue_length s = ⨅a b (h : s ⊆ Ioo a b), of_real (b - a) :=
begin
refine le_antisymm
(infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h,
⟨subset.trans h Ioo_subset_Ico_self, le_refl _⟩) _,
refine le_infi (λ a, le_infi $ λ b, le_infi $ λ h, _),
refine ennreal.le_of_forall_epsilon_le (λ ε ε0 _, _),
refine infi_le_of_le (a - ε) (infi_le_of_le b $ infi_le_of_le
(subset.trans h $ Ico_subset_Ioo_left $ (sub_lt_self_iff _).2 ε0) _),
rw [← sub_add, ← ennreal.coe_add, ennreal.coe_le_coe],
apply le_trans nnreal.of_real_add_le _,
simp,
end
@[simp] lemma lebesgue_length_Ioo (a b : ℝ) :
lebesgue_length (Ioo a b) = of_real (b - a) :=
begin
rw ← lebesgue_length_Ico,
refine le_antisymm (lebesgue_length_mono Ioo_subset_Ico_self) _,
rw lebesgue_length_eq_infi_Ioo (Ioo a b),
refine (le_infi $ λ a', le_infi $ λ b', le_infi $ λ h, _),
cases le_or_lt b a with ab ab, {simp [ab]},
cases (Ioo_subset_Ioo_iff ab).1 h with h₁ h₂,
rw [lebesgue_length_Ico, ennreal.coe_le_coe],
exact nnreal.of_real_le_of_real (sub_le_sub h₂ h₁)
end
lemma lebesgue_length_eq_infi_Icc (s) : lebesgue_length s = ⨅a b (h : s ⊆ Icc a b), of_real (b - a) :=
begin
refine le_antisymm _
(infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h,
⟨subset.trans h Ico_subset_Icc_self, le_refl _⟩),
refine le_infi (λ a, le_infi $ λ b, le_infi $ λ h, _),
refine ennreal.le_of_forall_epsilon_le (λ ε ε0 _, _),
refine infi_le_of_le a (infi_le_of_le (b + ε) $ infi_le_of_le
(subset.trans h $ Icc_subset_Ico_right $ (lt_add_iff_pos_right _).2 ε0) _),
rw [sub_eq_add_neg, add_right_comm, ←ennreal.coe_add, ennreal.coe_le_coe],
apply le_trans nnreal.of_real_add_le,
simp [sub_eq_add_neg]
end
@[simp] lemma lebesgue_length_Icc (a b : ℝ) :
lebesgue_length (Icc a b) = of_real (b - a) :=
begin
rw ← lebesgue_length_Ico,
refine le_antisymm _ (lebesgue_length_mono Ico_subset_Icc_self),
rw lebesgue_length_eq_infi_Icc (Icc a b),
exact infi_le_of_le a (infi_le_of_le b $ infi_le_of_le (by refl) (by simp))
end
/-- The Lebesgue outer measure, as an outer measure of ℝ. -/
def lebesgue_outer : outer_measure ℝ :=
outer_measure.of_function lebesgue_length lebesgue_length_empty
lemma lebesgue_outer_le_length (s : set ℝ) : lebesgue_outer s ≤ lebesgue_length s :=
outer_measure.of_function_le _ _ _
lemma lebesgue_length_subadditive {a b : ℝ} {c d : ℕ → ℝ}
(ss : Icc a b ⊆ ⋃i, Ioo (c i) (d i)) :
(of_real (b - a) : ennreal) ≤ ∑' i, of_real (d i - c i) :=
begin
suffices : ∀ (s:finset ℕ) b
(cv : Icc a b ⊆ ⋃ i ∈ (↑s:set ℕ), Ioo (c i) (d i)),
(of_real (b - a) : ennreal) ≤ ∑ i in s, of_real (d i - c i),
{ rcases compact_Icc.elim_finite_subcover_image (λ (i : ℕ) (_ : i ∈ univ),
@is_open_Ioo _ _ _ _ (c i) (d i)) (by simpa using ss) with ⟨s, su, hf, hs⟩,
have e : (⋃ i ∈ (↑hf.to_finset:set ℕ),
Ioo (c i) (d i)) = (⋃ i ∈ s, Ioo (c i) (d i)), {simp [set.ext_iff]},
rw ennreal.tsum_eq_supr_sum,
refine le_trans _ (le_supr _ hf.to_finset),
exact this hf.to_finset _ (by simpa [e]) },
clear ss b,
refine λ s, finset.strong_induction_on s (λ s IH b cv, _),
cases le_total b a with ab ab,
{ rw nnreal.of_real_of_nonpos (sub_nonpos.2 ab), simp },
have := cv ⟨ab, le_refl _⟩, simp at this,
rcases this with ⟨i, is, cb, bd⟩,
rw [← finset.insert_erase is] at cv ⊢,
rw [finset.coe_insert, bUnion_insert] at cv,
rw [finset.sum_insert (finset.not_mem_erase _ _)],
refine le_trans _ (add_le_add_left' (IH _ (finset.erase_ssubset is) (c i) _)),
{ rw [← ennreal.coe_add, ennreal.coe_le_coe],
refine le_trans (nnreal.of_real_le_of_real _) nnreal.of_real_add_le,
rw sub_add_sub_cancel,
exact sub_le_sub_right (le_of_lt bd) _ },
{ rintro x ⟨h₁, h₂⟩,
refine (cv ⟨h₁, le_trans h₂ (le_of_lt cb)⟩).resolve_left
(mt and.left (not_lt_of_le h₂)) }
end
@[simp] lemma lebesgue_outer_Icc (a b : ℝ) :
lebesgue_outer (Icc a b) = of_real (b - a) :=
begin
refine le_antisymm (by rw ← lebesgue_length_Icc; apply lebesgue_outer_le_length)
(le_infi $ λ f, le_infi $ λ hf,
ennreal.le_of_forall_epsilon_le $ λ ε ε0 h, _),
rcases ennreal.exists_pos_sum_of_encodable
(ennreal.zero_lt_coe_iff.2 ε0) ℕ with ⟨ε', ε'0, hε⟩,
refine le_trans _ (add_le_add_left' (le_of_lt hε)),
rw ← ennreal.tsum_add,
choose g hg using show
∀ i, ∃ p:ℝ×ℝ, f i ⊆ Ioo p.1 p.2 ∧ (of_real (p.2 - p.1) : ennreal) < lebesgue_length (f i) + ε' i,
{ intro i,
have := (ennreal.lt_add_right (lt_of_le_of_lt (ennreal.le_tsum i) h)
(ennreal.zero_lt_coe_iff.2 (ε'0 i))),
conv at this {to_lhs, rw lebesgue_length_eq_infi_Ioo},
simpa [infi_lt_iff] },
refine le_trans _ (ennreal.tsum_le_tsum $ λ i, le_of_lt (hg i).2),
exact lebesgue_length_subadditive (subset.trans hf $
Union_subset_Union $ λ i, (hg i).1)
end
@[simp] lemma lebesgue_outer_singleton (a : ℝ) : lebesgue_outer {a} = 0 :=
by simpa using lebesgue_outer_Icc a a
@[simp] lemma lebesgue_outer_Ico (a b : ℝ) :
lebesgue_outer (Ico a b) = of_real (b - a) :=
begin
refine le_antisymm (by rw ← lebesgue_length_Ico; apply lebesgue_outer_le_length)
(ennreal.le_of_forall_epsilon_le $ λ ε ε0 h, _),
have := @nnreal.of_real_add_le (b - a - ε) ε,
rw [← ennreal.coe_le_coe, ennreal.coe_add, sub_add_cancel, sub_right_comm,
← lebesgue_outer_Icc a (b-ε), nnreal.of_real_coe] at this,
exact le_trans this (add_le_add_right' $ lebesgue_outer.mono $
Icc_subset_Ico_right $ (sub_lt_self_iff _).2 ε0)
end
@[simp] lemma lebesgue_outer_Ioo (a b : ℝ) :
lebesgue_outer (Ioo a b) = of_real (b - a) :=
begin
refine le_antisymm (by rw ← lebesgue_length_Ioo; apply lebesgue_outer_le_length)
(ennreal.le_of_forall_epsilon_le $ λ ε ε0 h, _),
have := @nnreal.of_real_add_le (b - a - ε) ε,
rw [← ennreal.coe_le_coe, ennreal.coe_add, sub_add_cancel, sub_sub,
← lebesgue_outer_Ico (a+ε) b, nnreal.of_real_coe] at this,
exact le_trans this (add_le_add_right' $ lebesgue_outer.mono $
Ico_subset_Ioo_left $ (lt_add_iff_pos_right _).2 ε0)
end
lemma is_lebesgue_measurable_Iio {c : ℝ} :
lebesgue_outer.caratheodory.is_measurable (Iio c) :=
outer_measure.caratheodory_is_measurable $ λ t,
le_infi $ λ a, le_infi $ λ b, le_infi $ λ h, begin
refine le_trans (add_le_add
(lebesgue_length_mono $ inter_subset_inter_left _ h)
(lebesgue_length_mono $ diff_subset_diff_left h)) _,
cases le_total a c with hac hca; cases le_total b c with hbc hcb;
simp [*, -sub_eq_add_neg, sub_add_sub_cancel'];
rw [← ennreal.coe_add, ennreal.coe_le_coe],
{ simp [*, -nnreal.of_real_add, nnreal.of_real_add_of_real,
-sub_eq_add_neg, sub_add_sub_cancel'] },
{ rw nnreal.of_real_of_nonpos,
{ simp },
exact sub_nonpos.2 (le_trans hbc hca) }
end
theorem lebesgue_outer_trim : lebesgue_outer.trim = lebesgue_outer :=
begin
refine le_antisymm (λ s, _) (outer_measure.trim_ge _),
rw outer_measure.trim_eq_infi,
refine le_infi (λ f, le_infi $ λ hf,
ennreal.le_of_forall_epsilon_le $ λ ε ε0 h, _),
rcases ennreal.exists_pos_sum_of_encodable
(ennreal.zero_lt_coe_iff.2 ε0) ℕ with ⟨ε', ε'0, hε⟩,
refine le_trans _ (add_le_add_left' (le_of_lt hε)),
rw ← ennreal.tsum_add,
choose g hg using show
∀ i, ∃ s, f i ⊆ s ∧ is_measurable s ∧ lebesgue_outer s ≤ lebesgue_length (f i) + of_real (ε' i),
{ intro i,
have := (ennreal.lt_add_right (lt_of_le_of_lt (ennreal.le_tsum i) h)
(ennreal.zero_lt_coe_iff.2 (ε'0 i))),
conv at this {to_lhs, rw lebesgue_length},
simp only [infi_lt_iff] at this,
rcases this with ⟨a, b, h₁, h₂⟩,
rw ← lebesgue_outer_Ico at h₂,
exact ⟨_, h₁, is_measurable_Ico, le_of_lt $ by simpa using h₂⟩ },
simp at hg,
apply infi_le_of_le (Union g) _,
apply infi_le_of_le (subset.trans hf $ Union_subset_Union (λ i, (hg i).1)) _,
apply infi_le_of_le (is_measurable.Union (λ i, (hg i).2.1)) _,
exact le_trans (lebesgue_outer.Union _) (ennreal.tsum_le_tsum $ λ i, (hg i).2.2)
end
/-- Lebesgue measure on the Borel sets
The outer Lebesgue measure is the completion of this measure. (TODO: proof this)
-/
instance : measure_space ℝ :=
⟨{to_outer_measure := lebesgue_outer,
m_Union :=
have borel ℝ ≤ lebesgue_outer.caratheodory,
by rw real.borel_eq_generate_from_Iio_rat;
refine measurable_space.generate_from_le _;
simp [is_lebesgue_measurable_Iio] {contextual := tt},
λ f hf, lebesgue_outer.Union_eq_of_caratheodory (λ i, this _ (hf i)),
trimmed := lebesgue_outer_trim }⟩
@[simp] theorem lebesgue_to_outer_measure :
(volume : measure ℝ).to_outer_measure = lebesgue_outer := rfl
end measure_theory
open measure_theory
section volume
open_locale interval
theorem real.volume_val (s) : volume s = lebesgue_outer s := rfl
local attribute [simp] real.volume_val
@[simp] lemma real.volume_Ico {a b : ℝ} : volume (Ico a b) = of_real (b - a) := by simp
@[simp] lemma real.volume_Icc {a b : ℝ} : volume (Icc a b) = of_real (b - a) := by simp
@[simp] lemma real.volume_Ioo {a b : ℝ} : volume (Ioo a b) = of_real (b - a) := by simp
@[simp] lemma real.volume_singleton {a : ℝ} : volume ({a} : set ℝ) = 0 := by simp
@[simp] lemma real.volume_interval {a b : ℝ} : volume [a, b] = of_real (abs (b - a)) :=
begin
rw [interval, real.volume_Icc],
congr,
exact max_sub_min_eq_abs _ _
end
open metric
lemma real.volume_lt_top_of_bounded {s : set ℝ} (h : bounded s) : volume s < ⊤ :=
begin
rw [real.bounded_iff_bdd_below_bdd_above, bdd_below_bdd_above_iff_subset_interval] at h,
rcases h with ⟨a, b, h⟩,
calc volume s ≤ volume [a, b] : measure_mono h
... < ⊤ : by { rw real.volume_interval, exact ennreal.coe_lt_top }
end
lemma real.volume_lt_top_of_compact {s : set ℝ} (h : compact s) : volume s < ⊤ :=
real.volume_lt_top_of_bounded (bounded_of_compact h)
end volume
/-
section vitali
def vitali_aux_h (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) :
∃ y ∈ Icc (0:ℝ) 1, ∃ q:ℚ, ↑q = x - y :=
⟨x, h, 0, by simp⟩
def vitali_aux (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) : ℝ :=
classical.some (vitali_aux_h x h)
theorem vitali_aux_mem (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) : vitali_aux x h ∈ Icc (0:ℝ) 1 :=
Exists.fst (classical.some_spec (vitali_aux_h x h):_)
theorem vitali_aux_rel (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) :
∃ q:ℚ, ↑q = x - vitali_aux x h :=
Exists.snd (classical.some_spec (vitali_aux_h x h):_)
def vitali : set ℝ := {x | ∃ h, x = vitali_aux x h}
theorem vitali_nonmeasurable : ¬ is_null_measurable measure_space.μ vitali :=
sorry
end vitali
-/
|
3b916e6afd87a779bd8aaf41e3ec1415b1bc9f56 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /docs/tutorial/category_theory/intro.lean | f792d4364b26b77d9fb644b59a0f0dfb499f7dd7 | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 9,298 | lean | import category_theory.functor_category -- this transitively imports
-- category_theory.category
-- category_theory.functor
-- category_theory.natural_transformation
/-!
# An introduction to category theory in Lean
This is an introduction to the basic usage of category theory (in the mathematical sense) in Lean.
We cover how the basic theory of categories, functors and natural transformations is set up in Lean.
Most of the below is not hard to read off from the files `category_theory/category.lean`,
`category_theory/functor.lean` and `category_theory/natural_transformation.lean`.
## Overview
A category is a collection of objects, and a collection of morphisms (also known as arrows) between
the objects. The objects and morphisms have some extra structure and satisfy some axioms -- see the
[definition on Wikipedia](https://en.wikipedia.org/wiki/Category_%28mathematics%29#Definition) for
details.
One important thing to note is that a morphism in an abstract category may not be an actual function
between two types. In particular, there is new notation `⟶` , typed as `\h` or `\hom` in VS Code,
for a morphism. Nevertheless, in most of the "concrete" categories like `Top` and `Ab`, it is still
possible to write `f x` when `x : X` and `f : X ⟶ Y` is a morphism, as there is an automatic
coercion from morphisms to functions. (If the coercion doesn't fire automatically, sometimes it is
necessary to write `(f : X → Y) x`.)
In some fonts the `⟶` morphism arrow can be virtually indistinguishable from the standard function
arrow `→` . You may want to install the [Deja Vu Sans Mono](https://dejavu-fonts.github.io/) and put
that at the beginning of the `Font Family` setting in VSCode, to get a nice readable font with
excellent unicode coverage.
Another point of confusion can be universe issues. Following Lean's conventions for universe
polymorphism, the objects of a category might live in one universe `u` and the morphisms in another
universe `v`. Note that in many categories showing up in "set-theoretic mathematics", the morphisms
between two objects often form a set, but the objects themselves may or may not form a set. In Lean
this corresponds to the two possibilities `u=v` and `u=v+1`, known as `small_category` and
`large_category` respectively. In order to avoid proving the same statements for both small and
large categories, we usually stick to the general polymorphic situation with `u` and `v` independent
universes, and we do this below.
## Getting started with categories
The structure of a category on a type `C` in Lean is done using typeclasses; terms of `C` then
correspond to objects in the category. The convention in the category theory library is to use
universes prefixed with `u` (e.g. `u`, `u₁`, `u₂`) for the objects, and universes prefixed with `v`
for morphisms. Thus we have `C : Type u`, and if `X : C` and `Y : C` then morphisms `X ⟶ Y : Type v`
(note the non-standard arrow).
We set this up as follows:
-/
open category_theory
section category
universes v u -- the order matters (see below)
variables (C : Type u) [category.{v} C]
variables {W X Y Z : C}
variables (f : W ⟶ X) (g : X ⟶ Y) (h : Y ⟶ Z)
/-!
This says "let `C` be a category, let `W`, `X`, `Y`, `Z` be objects of `C`, and let `f : W ⟶ X`, `g
: X ⟶ Y` and `h : Y ⟶ Z` be morphisms in `C` (with the specified source and targets)".
Note that we need to explicitly tell Lean the universe that the morphisms live in, by writing `category.{v} C`, because Lean cannot guess this from `C` alone.
The order in which universes are introduced at the top of the file matters: we put the universes for
morphisms first (typically `v`, `v₁` and so on), and then universes for objects (typically `u`, `u₁`
and so on). This ensures that in any new definition we make the universe variables for morphisms
come first, so that they can be explicitly specified while still allowing the universe levels of the
objects to be inferred automatically.
## Basic notation
In categories one has morphisms between objects, such as the identity morphism from an object to
itself. One can compose morphisms, and there are standard facts about the composition of a morphism
with the identity morphism, and the fact that morphism composition is associative. In Lean all of
this looks like the following:
-/
-- The identity morphism from `X` to `X` (remember that this is the `\h` arrow):
example : X ⟶ X := 𝟙 X -- type `𝟙` as `\bb1`
-- Function composition `h ∘ g`, a morphism from `X` to `Z`:
example : X ⟶ Z := g ≫ h
/-
Note in particular the order! The "maps on the right" convention was chosen; `g ≫ h` means "`g` then
`h`". Type `≫` with `\gg` in VS Code. Here are the theorems which ensure that we have a category.
-/
open category_theory.category
example : 𝟙 X ≫ g = g := id_comp g
example : g ≫ 𝟙 Y = g := comp_id g
example : (f ≫ g) ≫ h = f ≫ (g ≫ h) := assoc f g h
example : (f ≫ g) ≫ h = f ≫ g ≫ h := assoc f g h -- note \gg is right associative
-- All four examples above can also be proved with `simp`.
-- Monomorphisms and epimorphisms are predicates on morphisms and are implemented as typeclasses.
variables (f' : W ⟶ X) (h' : Y ⟶ Z)
example [mono g] : f ≫ g = f' ≫ g → f = f' := mono.right_cancellation f f'
example [epi g] : g ≫ h = g ≫ h' → h = h' := epi.left_cancellation h h'
end category -- end of section
/-!
## Getting started with functors
A functor is a map between categories. It is implemented as a structure. The notation for a functor
from `C` to `D` is `C ⥤ D`. Type `\func` in VS Code for the symbol. Here we demonstrate how to
evaluate functors on objects and on morphisms, how to show functors preserve the identity morphism
and composition of morphisms, how to compose functors, and show the notation `𝟭` for the identity
functor.
-/
section functor
-- recall we put morphism universes (`vᵢ`) before object universes (`uᵢ`)
universes v₁ v₂ v₃ u₁ u₂ u₃
variables (C : Type u₁) [category.{v₁} C]
variables (D : Type u₂) [category.{v₂} D]
variables (E : Type u₃) [category.{v₃} E]
variables {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z)
-- functors
variables (F : C ⥤ D) (G : D ⥤ E)
example : D := F.obj X -- functor F on objects
example : F.obj Y ⟶ F.obj Z := F.map g -- functor F on morphisms
-- A functor sends identity objects to identity objects
example : F.map (𝟙 X) = 𝟙 (F.obj X) := F.map_id X
-- and preserves compositions
example : F.map (f ≫ g) = (F.map f) ≫ (F.map g) := F.map_comp f g
-- The identity functor is `𝟭`, which you can write as `\sb1`.
example : C ⥤ C := 𝟭 C
-- The identity functor is (definitionally) the identity on objects and morphisms:
example : (𝟭 C).obj X = X := category_theory.functor.id_obj X
example : (𝟭 C).map f = f := category_theory.functor.id_map f
-- Composition of functors; note order:
example : C ⥤ E := F ⋙ G -- typeset with `\ggg`
-- Composition of the identity either way does nothing:
example : F ⋙ 𝟭 D = F := F.comp_id
example : 𝟭 C ⋙ F = F := F.id_comp
-- Composition of functors definitionally does the right thing on objects and morphisms:
example : (F ⋙ G).obj X = G.obj (F.obj X) := F.comp_obj G X -- or rfl
example : (F ⋙ G).map f = G.map (F.map f) := rfl -- or F.comp_map G X Y f
end functor -- end of section
/-!
One can also check that associativity of composition of functors is definitionally true,
although we've observed that relying on this can result in slow proofs. (One should
rather use the natural isomorphisms provided in `src/category_theory/whiskering.lean`.)
## Getting started with natural transformations
A natural transformation is a morphism between functors. If `F` and `G` are functors from `C` to `D`
then a natural transformation is a map `F X ⟶ G X` for each object `X : C` plus the theorem that if
`f : X ⟶ Y` is a morphism then the two routes from `F X` to `G Y` are the same. One might imagine
that this is now another layer of notation, but fortunately the `category_theory.functor_category`
import gives the type of functors from `C` to `D` a category structure, which means that we can just
use morphism notation for natural transformations.
-/
section nat_trans
universes v₁ v₂ u₁ u₂
variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D]
variables (X Y : C)
variable (f : X ⟶ Y)
variables (F G H : C ⥤ D)
variables (α : F ⟶ G) (β : G ⟶ H) -- natural transformations (note it's the usual `\hom` arrow here)
-- Composition of natural transformations is just composition of morphisms:
example : F ⟶ H := α ≫ β
-- Applying natural transformation to an object:
example (X : C) : F.obj X ⟶ G.obj X := α.app X
/- The diagram coming from g and α
F(f)
F X ---> F Y
| |
|α(X) |α(Y)
v v
G X ---> G Y
G(f)
commutes.
-/
example : F.map f ≫ α.app Y = (α.app X) ≫ G.map f := α.naturality f
end nat_trans -- section
/-!
## What next?
There are several lean files in the [category theory docs directory of
mathlib](https://github.com/leanprover-community/mathlib/tree/master/docs/tutorial/category_theory)
which give further examples of using the category theory library in Lean.
-/
|
3c8ea5eb08fc5384f8fcead4ad749e9696c1015b | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/analysis/calculus/fderiv_analytic.lean | 42afc7b3f235324db56ab4cce0ae23f9d1ac7dcc | [
"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 | 7,194 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import analysis.calculus.deriv
import analysis.analytic.basic
import analysis.calculus.cont_diff
/-!
# Frechet derivatives of analytic functions.
A function expressible as a power series at a point has a Frechet derivative there.
Also the special case in terms of `deriv` when the domain is 1-dimensional.
-/
open filter asymptotics
open_locale ennreal
variables {𝕜 : Type*} [nontrivially_normed_field 𝕜]
variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E]
variables {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F]
section fderiv
variables {p : formal_multilinear_series 𝕜 E F} {r : ℝ≥0∞}
variables {f : E → F} {x : E} {s : set E}
lemma has_fpower_series_at.has_strict_fderiv_at (h : has_fpower_series_at f p x) :
has_strict_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p 1)) x :=
begin
refine h.is_O_image_sub_norm_mul_norm_sub.trans_is_o (is_o.of_norm_right _),
refine is_o_iff_exists_eq_mul.2 ⟨λ y, ∥y - (x, x)∥, _, eventually_eq.rfl⟩,
refine (continuous_id.sub continuous_const).norm.tendsto' _ _ _,
rw [_root_.id, sub_self, norm_zero]
end
lemma has_fpower_series_at.has_fderiv_at (h : has_fpower_series_at f p x) :
has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p 1)) x :=
h.has_strict_fderiv_at.has_fderiv_at
lemma has_fpower_series_at.differentiable_at (h : has_fpower_series_at f p x) :
differentiable_at 𝕜 f x :=
h.has_fderiv_at.differentiable_at
lemma analytic_at.differentiable_at : analytic_at 𝕜 f x → differentiable_at 𝕜 f x
| ⟨p, hp⟩ := hp.differentiable_at
lemma analytic_at.differentiable_within_at (h : analytic_at 𝕜 f x) :
differentiable_within_at 𝕜 f s x :=
h.differentiable_at.differentiable_within_at
lemma has_fpower_series_at.fderiv_eq (h : has_fpower_series_at f p x) :
fderiv 𝕜 f x = continuous_multilinear_curry_fin1 𝕜 E F (p 1) :=
h.has_fderiv_at.fderiv
lemma has_fpower_series_on_ball.differentiable_on [complete_space F]
(h : has_fpower_series_on_ball f p x r) :
differentiable_on 𝕜 f (emetric.ball x r) :=
λ y hy, (h.analytic_at_of_mem hy).differentiable_within_at
lemma analytic_on.differentiable_on (h : analytic_on 𝕜 f s) :
differentiable_on 𝕜 f s :=
λ y hy, (h y hy).differentiable_within_at
lemma has_fpower_series_on_ball.has_fderiv_at [complete_space F]
(h : has_fpower_series_on_ball f p x r) {y : E} (hy : (∥y∥₊ : ℝ≥0∞) < r) :
has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p.change_origin y 1)) (x + y) :=
(h.change_origin hy).has_fpower_series_at.has_fderiv_at
lemma has_fpower_series_on_ball.fderiv_eq [complete_space F]
(h : has_fpower_series_on_ball f p x r) {y : E} (hy : (∥y∥₊ : ℝ≥0∞) < r) :
fderiv 𝕜 f (x + y) = continuous_multilinear_curry_fin1 𝕜 E F (p.change_origin y 1) :=
(h.has_fderiv_at hy).fderiv
/-- If a function has a power series on a ball, then so does its derivative. -/
lemma has_fpower_series_on_ball.fderiv [complete_space F]
(h : has_fpower_series_on_ball f p x r) :
has_fpower_series_on_ball (fderiv 𝕜 f)
((continuous_multilinear_curry_fin1 𝕜 E F : (E [×1]→L[𝕜] F) →L[𝕜] (E →L[𝕜] F))
.comp_formal_multilinear_series (p.change_origin_series 1)) x r :=
begin
suffices A : has_fpower_series_on_ball
(λ z, continuous_multilinear_curry_fin1 𝕜 E F (p.change_origin (z - x) 1))
((continuous_multilinear_curry_fin1 𝕜 E F : (E [×1]→L[𝕜] F) →L[𝕜] (E →L[𝕜] F))
.comp_formal_multilinear_series (p.change_origin_series 1)) x r,
{ apply A.congr,
assume z hz,
dsimp,
rw [← h.fderiv_eq, add_sub_cancel'_right],
simpa only [edist_eq_coe_nnnorm_sub, emetric.mem_ball] using hz},
suffices B : has_fpower_series_on_ball (λ z, p.change_origin (z - x) 1)
(p.change_origin_series 1) x r,
from (continuous_multilinear_curry_fin1 𝕜 E F).to_continuous_linear_equiv
.to_continuous_linear_map.comp_has_fpower_series_on_ball B,
simpa using ((p.has_fpower_series_on_ball_change_origin 1 (h.r_pos.trans_le h.r_le)).mono
h.r_pos h.r_le).comp_sub x,
end
/-- If a function is analytic on a set `s`, so is its Fréchet derivative. -/
lemma analytic_on.fderiv [complete_space F] (h : analytic_on 𝕜 f s) :
analytic_on 𝕜 (fderiv 𝕜 f) s :=
begin
assume y hy,
rcases h y hy with ⟨p, r, hp⟩,
exact hp.fderiv.analytic_at,
end
/-- If a function is analytic on a set `s`, so are its successive Fréchet derivative. -/
lemma analytic_on.iterated_fderiv [complete_space F] (h : analytic_on 𝕜 f s) (n : ℕ) :
analytic_on 𝕜 (iterated_fderiv 𝕜 n f) s :=
begin
induction n with n IH,
{ rw iterated_fderiv_zero_eq_comp,
exact ((continuous_multilinear_curry_fin0 𝕜 E F).symm : F →L[𝕜] (E [×0]→L[𝕜] F))
.comp_analytic_on h },
{ rw iterated_fderiv_succ_eq_comp_left,
apply (continuous_multilinear_curry_left_equiv 𝕜 (λ (i : fin (n + 1)), E) F)
.to_continuous_linear_equiv.to_continuous_linear_map.comp_analytic_on,
exact IH.fderiv }
end
/-- An analytic function is infinitely differentiable. -/
lemma analytic_on.cont_diff_on [complete_space F] (h : analytic_on 𝕜 f s) {n : ℕ∞} :
cont_diff_on 𝕜 n f s :=
begin
let t := {x | analytic_at 𝕜 f x},
suffices : cont_diff_on 𝕜 n f t, from this.mono h,
have H : analytic_on 𝕜 f t := λ x hx, hx,
have t_open : is_open t := is_open_analytic_at 𝕜 f,
apply cont_diff_on_of_continuous_on_differentiable_on,
{ assume m hm,
apply (H.iterated_fderiv m).continuous_on.congr,
assume x hx,
exact iterated_fderiv_within_of_is_open _ t_open hx },
{ assume m hm,
apply (H.iterated_fderiv m).differentiable_on.congr,
assume x hx,
exact iterated_fderiv_within_of_is_open _ t_open hx }
end
end fderiv
section deriv
variables {p : formal_multilinear_series 𝕜 𝕜 F} {r : ℝ≥0∞}
variables {f : 𝕜 → F} {x : 𝕜} {s : set 𝕜}
protected lemma has_fpower_series_at.has_strict_deriv_at (h : has_fpower_series_at f p x) :
has_strict_deriv_at f (p 1 (λ _, 1)) x :=
h.has_strict_fderiv_at.has_strict_deriv_at
protected lemma has_fpower_series_at.has_deriv_at (h : has_fpower_series_at f p x) :
has_deriv_at f (p 1 (λ _, 1)) x :=
h.has_strict_deriv_at.has_deriv_at
protected lemma has_fpower_series_at.deriv (h : has_fpower_series_at f p x) :
deriv f x = p 1 (λ _, 1) :=
h.has_deriv_at.deriv
/-- If a function is analytic on a set `s`, so is its derivative. -/
lemma analytic_on.deriv [complete_space F] (h : analytic_on 𝕜 f s) :
analytic_on 𝕜 (deriv f) s :=
(continuous_linear_map.apply 𝕜 F (1 : 𝕜)).comp_analytic_on h.fderiv
/-- If a function is analytic on a set `s`, so are its successive derivatives. -/
lemma analytic_on.iterated_deriv [complete_space F] (h : analytic_on 𝕜 f s) (n : ℕ) :
analytic_on 𝕜 (deriv^[n] f) s :=
begin
induction n with n IH,
{ exact h },
{ simpa only [function.iterate_succ', function.comp_app] using IH.deriv }
end
end deriv
|
d4f0d3492a46a6a3a751c64d1f76b3c182bce551 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/algebra/group/type_tags.lean | ece9c96213499128fb93c3f50bfb0e0cd04af24a | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 11,620 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import algebra.group.hom
import data.equiv.basic
/-!
# Type tags that turn additive structures into multiplicative, and vice versa
We define two type tags:
* `additive α`: turns any multiplicative structure on `α` into the corresponding
additive structure on `additive α`;
* `multiplicative α`: turns any additive structure on `α` into the corresponding
multiplicative structure on `multiplicative α`.
We also define instances `additive.*` and `multiplicative.*` that actually transfer the structures.
-/
universes u v
variables {α : Type u} {β : Type v}
/-- If `α` carries some multiplicative structure, then `additive α` carries the corresponding
additive structure. -/
def additive (α : Type*) := α
/-- If `α` carries some additive structure, then `multiplicative α` carries the corresponding
multiplicative structure. -/
def multiplicative (α : Type*) := α
namespace additive
/-- Reinterpret `x : α` as an element of `additive α`. -/
def of_mul : α ≃ additive α := ⟨λ x, x, λ x, x, λ x, rfl, λ x, rfl⟩
/-- Reinterpret `x : additive α` as an element of `α`. -/
def to_mul : additive α ≃ α := of_mul.symm
@[simp] lemma of_mul_symm_eq : (@of_mul α).symm = to_mul := rfl
@[simp] lemma to_mul_symm_eq : (@to_mul α).symm = of_mul := rfl
end additive
namespace multiplicative
/-- Reinterpret `x : α` as an element of `multiplicative α`. -/
def of_add : α ≃ multiplicative α := ⟨λ x, x, λ x, x, λ x, rfl, λ x, rfl⟩
/-- Reinterpret `x : multiplicative α` as an element of `α`. -/
def to_add : multiplicative α ≃ α := of_add.symm
@[simp] lemma of_add_symm_eq : (@of_add α).symm = to_add := rfl
@[simp] lemma to_add_symm_eq : (@to_add α).symm = of_add := rfl
end multiplicative
@[simp] lemma to_add_of_add (x : α) : (multiplicative.of_add x).to_add = x := rfl
@[simp] lemma of_add_to_add (x : multiplicative α) : multiplicative.of_add x.to_add = x := rfl
@[simp] lemma to_mul_of_mul (x : α) : (additive.of_mul x).to_mul = x := rfl
@[simp] lemma of_mul_to_mul (x : additive α) : additive.of_mul x.to_mul = x := rfl
instance [inhabited α] : inhabited (additive α) := ⟨additive.of_mul (default α)⟩
instance [inhabited α] : inhabited (multiplicative α) := ⟨multiplicative.of_add (default α)⟩
instance [nontrivial α] : nontrivial (additive α) :=
additive.of_mul.injective.nontrivial
instance [nontrivial α] : nontrivial (multiplicative α) :=
multiplicative.of_add.injective.nontrivial
instance additive.has_add [has_mul α] : has_add (additive α) :=
{ add := λ x y, additive.of_mul (x.to_mul * y.to_mul) }
instance [has_add α] : has_mul (multiplicative α) :=
{ mul := λ x y, multiplicative.of_add (x.to_add + y.to_add) }
@[simp] lemma of_add_add [has_add α] (x y : α) :
multiplicative.of_add (x + y) = multiplicative.of_add x * multiplicative.of_add y :=
rfl
@[simp] lemma to_add_mul [has_add α] (x y : multiplicative α) :
(x * y).to_add = x.to_add + y.to_add :=
rfl
@[simp] lemma of_mul_mul [has_mul α] (x y : α) :
additive.of_mul (x * y) = additive.of_mul x + additive.of_mul y :=
rfl
@[simp] lemma to_mul_add [has_mul α] (x y : additive α) :
(x + y).to_mul = x.to_mul * y.to_mul :=
rfl
instance [semigroup α] : add_semigroup (additive α) :=
{ add_assoc := @mul_assoc α _,
..additive.has_add }
instance [add_semigroup α] : semigroup (multiplicative α) :=
{ mul_assoc := @add_assoc α _,
..multiplicative.has_mul }
instance [comm_semigroup α] : add_comm_semigroup (additive α) :=
{ add_comm := @mul_comm _ _,
..additive.add_semigroup }
instance [add_comm_semigroup α] : comm_semigroup (multiplicative α) :=
{ mul_comm := @add_comm _ _,
..multiplicative.semigroup }
instance [left_cancel_semigroup α] : add_left_cancel_semigroup (additive α) :=
{ add_left_cancel := @mul_left_cancel _ _,
..additive.add_semigroup }
instance [add_left_cancel_semigroup α] : left_cancel_semigroup (multiplicative α) :=
{ mul_left_cancel := @add_left_cancel _ _,
..multiplicative.semigroup }
instance [right_cancel_semigroup α] : add_right_cancel_semigroup (additive α) :=
{ add_right_cancel := @mul_right_cancel _ _,
..additive.add_semigroup }
instance [add_right_cancel_semigroup α] : right_cancel_semigroup (multiplicative α) :=
{ mul_right_cancel := @add_right_cancel _ _,
..multiplicative.semigroup }
instance [has_one α] : has_zero (additive α) := ⟨additive.of_mul 1⟩
@[simp] lemma of_mul_one [has_one α] : @additive.of_mul α 1 = 0 := rfl
@[simp] lemma of_mul_eq_zero {A : Type*} [has_one A] {x : A} :
additive.of_mul x = 0 ↔ x = 1 := iff.rfl
@[simp] lemma to_mul_zero [has_one α] : (0 : additive α).to_mul = 1 := rfl
instance [has_zero α] : has_one (multiplicative α) := ⟨multiplicative.of_add 0⟩
@[simp] lemma of_add_zero [has_zero α] : @multiplicative.of_add α 0 = 1 := rfl
@[simp] lemma of_add_eq_one {A : Type*} [has_zero A] {x : A} :
multiplicative.of_add x = 1 ↔ x = 0 := iff.rfl
@[simp] lemma to_add_one [has_zero α] : (1 : multiplicative α).to_add = 0 := rfl
instance [mul_one_class α] : add_zero_class (additive α) :=
{ zero := 0,
add := (+),
zero_add := one_mul,
add_zero := mul_one }
instance [add_zero_class α] : mul_one_class (multiplicative α) :=
{ one := 1,
mul := (*),
one_mul := zero_add,
mul_one := add_zero }
instance [monoid α] : add_monoid (additive α) :=
{ zero := 0,
add := (+),
..additive.add_zero_class,
..additive.add_semigroup }
instance [add_monoid α] : monoid (multiplicative α) :=
{ one := 1,
mul := (*),
..multiplicative.mul_one_class,
..multiplicative.semigroup }
instance [left_cancel_monoid α] : add_left_cancel_monoid (additive α) :=
{ .. additive.add_monoid, .. additive.add_left_cancel_semigroup }
instance [add_left_cancel_monoid α] : left_cancel_monoid (multiplicative α) :=
{ .. multiplicative.monoid, .. multiplicative.left_cancel_semigroup }
instance [right_cancel_monoid α] : add_right_cancel_monoid (additive α) :=
{ .. additive.add_monoid, .. additive.add_right_cancel_semigroup }
instance [add_right_cancel_monoid α] : right_cancel_monoid (multiplicative α) :=
{ .. multiplicative.monoid, .. multiplicative.right_cancel_semigroup }
instance [comm_monoid α] : add_comm_monoid (additive α) :=
{ .. additive.add_monoid, .. additive.add_comm_semigroup }
instance [add_comm_monoid α] : comm_monoid (multiplicative α) :=
{ ..multiplicative.monoid, .. multiplicative.comm_semigroup }
instance [has_inv α] : has_neg (additive α) := ⟨λ x, multiplicative.of_add x.to_mul⁻¹⟩
@[simp] lemma of_mul_inv [has_inv α] (x : α) : additive.of_mul x⁻¹ = -(additive.of_mul x) := rfl
@[simp] lemma to_mul_neg [has_inv α] (x : additive α) : (-x).to_mul = x.to_mul⁻¹ := rfl
instance [has_neg α] : has_inv (multiplicative α) := ⟨λ x, additive.of_mul (-x.to_add)⟩
@[simp] lemma of_add_neg [has_neg α] (x : α) :
multiplicative.of_add (-x) = (multiplicative.of_add x)⁻¹ := rfl
@[simp] lemma to_add_inv [has_neg α] (x : multiplicative α) :
(x⁻¹).to_add = -x.to_add := rfl
instance additive.has_sub [has_div α] : has_sub (additive α) :=
{ sub := λ x y, additive.of_mul (x.to_mul / y.to_mul) }
instance multiplicative.has_div [has_sub α] : has_div (multiplicative α) :=
{ div := λ x y, multiplicative.of_add (x.to_add - y.to_add) }
@[simp] lemma of_add_sub [has_sub α] (x y : α) :
multiplicative.of_add (x - y) = multiplicative.of_add x / multiplicative.of_add y :=
rfl
@[simp] lemma to_add_div [has_sub α] (x y : multiplicative α) :
(x / y).to_add = x.to_add - y.to_add :=
rfl
@[simp] lemma of_mul_div [has_div α] (x y : α) :
additive.of_mul (x / y) = additive.of_mul x - additive.of_mul y :=
rfl
@[simp] lemma to_mul_sub [has_div α] (x y : additive α) :
(x - y).to_mul = x.to_mul / y.to_mul :=
rfl
instance [div_inv_monoid α] : sub_neg_monoid (additive α) :=
{ sub_eq_add_neg := @div_eq_mul_inv α _,
.. additive.has_neg, .. additive.has_sub, .. additive.add_monoid }
instance [sub_neg_monoid α] : div_inv_monoid (multiplicative α) :=
{ div_eq_mul_inv := @sub_eq_add_neg α _,
.. multiplicative.has_inv, .. multiplicative.has_div, .. multiplicative.monoid }
instance [group α] : add_group (additive α) :=
{ add_left_neg := @mul_left_inv α _,
.. additive.sub_neg_monoid }
instance [add_group α] : group (multiplicative α) :=
{ mul_left_inv := @add_left_neg α _,
.. multiplicative.div_inv_monoid }
instance [comm_group α] : add_comm_group (additive α) :=
{ .. additive.add_group, .. additive.add_comm_monoid }
instance [add_comm_group α] : comm_group (multiplicative α) :=
{ .. multiplicative.group, .. multiplicative.comm_monoid }
/-- Reinterpret `α →+ β` as `multiplicative α →* multiplicative β`. -/
def add_monoid_hom.to_multiplicative [add_zero_class α] [add_zero_class β] :
(α →+ β) ≃ (multiplicative α →* multiplicative β) :=
⟨λ f, ⟨f.1, f.2, f.3⟩, λ f, ⟨f.1, f.2, f.3⟩, λ x, by { ext, refl, }, λ x, by { ext, refl, }⟩
/-- Reinterpret `α →* β` as `additive α →+ additive β`. -/
def monoid_hom.to_additive [mul_one_class α] [mul_one_class β] :
(α →* β) ≃ (additive α →+ additive β) :=
⟨λ f, ⟨f.1, f.2, f.3⟩, λ f, ⟨f.1, f.2, f.3⟩, λ x, by { ext, refl, }, λ x, by { ext, refl, }⟩
/-- Reinterpret `additive α →+ β` as `α →* multiplicative β`. -/
def add_monoid_hom.to_multiplicative' [mul_one_class α] [add_zero_class β] :
(additive α →+ β) ≃ (α →* multiplicative β) :=
⟨λ f, ⟨f.1, f.2, f.3⟩, λ f, ⟨f.1, f.2, f.3⟩, λ x, by { ext, refl, }, λ x, by { ext, refl, }⟩
/-- Reinterpret `α →* multiplicative β` as `additive α →+ β`. -/
def monoid_hom.to_additive' [mul_one_class α] [add_zero_class β] :
(α →* multiplicative β) ≃ (additive α →+ β) :=
add_monoid_hom.to_multiplicative'.symm
/-- Reinterpret `α →+ additive β` as `multiplicative α →* β`. -/
def add_monoid_hom.to_multiplicative'' [add_zero_class α] [mul_one_class β] :
(α →+ additive β) ≃ (multiplicative α →* β) :=
⟨λ f, ⟨f.1, f.2, f.3⟩, λ f, ⟨f.1, f.2, f.3⟩, λ x, by { ext, refl, }, λ x, by { ext, refl, }⟩
/-- Reinterpret `multiplicative α →* β` as `α →+ additive β`. -/
def monoid_hom.to_additive'' [add_zero_class α] [mul_one_class β] :
(multiplicative α →* β) ≃ (α →+ additive β) :=
add_monoid_hom.to_multiplicative''.symm
/-- If `α` has some multiplicative structure and coerces to a function,
then `additive α` should also coerce to the same function.
This allows `additive` to be used on bundled function types with a multiplicative structure, which
is often used for composition, without affecting the behavior of the function itself.
-/
instance additive.has_coe_to_fun {α : Type*} [has_coe_to_fun α] :
has_coe_to_fun (additive α) :=
⟨λ a, has_coe_to_fun.F a.to_mul, λ a, coe_fn a.to_mul⟩
/-- If `α` has some additive structure and coerces to a function,
then `multiplicative α` should also coerce to the same function.
This allows `multiplicative` to be used on bundled function types with an additive structure, which
is often used for composition, without affecting the behavior of the function itself.
-/
instance multiplicative.has_coe_to_fun {α : Type*} [has_coe_to_fun α] :
has_coe_to_fun (multiplicative α) :=
⟨λ a, has_coe_to_fun.F a.to_add, λ a, coe_fn a.to_add⟩
|
37386ef5918d07521cd25a5f7a1c51a71a93b901 | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/field_theory/algebraic_closure.lean | a102c520b092cc083ac2da734907e6c02cdef048 | [
"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 | 12,111 | lean | /-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import algebra.direct_limit
import field_theory.splitting_field
import analysis.complex.polynomial
/-!
# Algebraic Closure
In this file we define the typeclass for algebraically closed fields and algebraic closures.
We also construct an algebraic closure for any field.
## Main Definitions
- `is_alg_closed k` is the typeclass saying `k` is an algebraically closed field, i.e. every
polynomial in `k` splits.
- `is_alg_closure k K` is the typeclass saying `K` is an algebraic closure of `k`.
- `algebraic_closure k` is an algebraic closure of `k` (in the same universe).
It is constructed by taking the polynomial ring generated by indeterminates `x_f`
corresponding to monic irreducible polynomials `f` with coefficients in `k`, and quotienting
out by a maximal ideal containing every `f(x_f)`, and then repeating this step countably
many times. See Exercise 1.13 in Atiyah--Macdonald.
## TODO
Show that any algebraic extension embeds into any algebraically closed extension (via Zorn's lemma).
## Tags
algebraic closure, algebraically closed
-/
universes u v w
noncomputable theory
open_locale classical big_operators
open polynomial
variables (k : Type u) [field k]
/-- Typeclass for algebraically closed fields. -/
class is_alg_closed : Prop :=
(splits : ∀ p : polynomial k, p.splits $ ring_hom.id k)
theorem polynomial.splits' {k K : Type*} [field k] [is_alg_closed k] [field K] {f : k →+* K}
(p : polynomial k) : p.splits f :=
polynomial.splits_of_splits_id _ $ is_alg_closed.splits _
namespace is_alg_closed
theorem of_exists_root (H : ∀ p : polynomial k, p.monic → irreducible p → ∃ x, p.eval x = 0) :
is_alg_closed k :=
⟨λ p, or.inr $ λ q hq hqp,
have irreducible (q * C (leading_coeff q)⁻¹),
by { rw ← coe_norm_unit hq.ne_zero, exact irreducible_of_associated associated_normalize hq },
let ⟨x, hx⟩ := H (q * C (leading_coeff q)⁻¹) (monic_mul_leading_coeff_inv hq.ne_zero) this in
degree_mul_leading_coeff_inv q hq.ne_zero ▸ degree_eq_one_of_irreducible_of_root this hx⟩
lemma degree_eq_one_of_irreducible [is_alg_closed k] {p : polynomial k} (h_nz : p ≠ 0) (hp : irreducible p) :
p.degree = 1 :=
degree_eq_one_of_irreducible_of_splits h_nz hp (polynomial.splits' _)
end is_alg_closed
instance complex.is_alg_closed : is_alg_closed ℂ :=
is_alg_closed.of_exists_root _ $ λ p _ hp, complex.exists_root $ degree_pos_of_irreducible hp
/-- Typeclass for an extension being an algebraic closure. -/
@[class] def is_alg_closure (K : Type v) [field K] [algebra k K] : Prop :=
is_alg_closed K ∧ algebra.is_algebraic k K
namespace algebraic_closure
open mv_polynomial
/-- The subtype of monic irreducible polynomials -/
@[reducible] def monic_irreducible : Type u :=
{ f : polynomial k // monic f ∧ irreducible f }
/-- Sends a monic irreducible polynomial `f` to `f(x_f)` where `x_f` is a formal indeterminate. -/
def eval_X_self (f : monic_irreducible k) : mv_polynomial (monic_irreducible k) k :=
polynomial.eval₂ mv_polynomial.C (X f) f
/-- The span of `f(x_f)` across monic irreducible polynomials `f` where `x_f` is an indeterminate. -/
def span_eval : ideal (mv_polynomial (monic_irreducible k) k) :=
ideal.span $ set.range $ eval_X_self k
/-- Given a finset of monic irreducible polynomials, construct an algebra homomorphism to the
splitting field of the product of the polynomials sending each indeterminate `x_f` represented by
the polynomial `f` in the finset to a root of `f`. -/
def to_splitting_field (s : finset (monic_irreducible k)) :
mv_polynomial (monic_irreducible k) k →ₐ[k] splitting_field (∏ x in s, x : polynomial k) :=
mv_polynomial.aeval $ λ f,
if hf : f ∈ s
then root_of_splits _
((splits_prod_iff _ $ λ (j : monic_irreducible k) _, j.2.2.ne_zero).1
(splitting_field.splits _) f hf)
(mt is_unit_iff_degree_eq_zero.2 f.2.2.not_unit)
else 37
theorem to_splitting_field_eval_X_self {s : finset (monic_irreducible k)} {f} (hf : f ∈ s) :
to_splitting_field k s (eval_X_self k f) = 0 :=
by { rw [to_splitting_field, eval_X_self, ← alg_hom.coe_to_ring_hom, hom_eval₂,
alg_hom.coe_to_ring_hom, mv_polynomial.aeval_X, dif_pos hf,
← algebra_map_eq, alg_hom.comp_algebra_map],
exact map_root_of_splits _ _ _ }
theorem span_eval_ne_top : span_eval k ≠ ⊤ :=
begin
rw [ideal.ne_top_iff_one, span_eval, ideal.span, ← set.image_univ, finsupp.mem_span_iff_total],
rintros ⟨v, _, hv⟩,
replace hv := congr_arg (to_splitting_field k v.support) hv,
rw [alg_hom.map_one, finsupp.total_apply, finsupp.sum, alg_hom.map_sum, finset.sum_eq_zero] at hv,
{ exact zero_ne_one hv },
intros j hj,
rw [smul_eq_mul, alg_hom.map_mul, to_splitting_field_eval_X_self k hj, mul_zero]
end
/-- A random maximal ideal that contains `span_eval k` -/
def max_ideal : ideal (mv_polynomial (monic_irreducible k) k) :=
classical.some $ ideal.exists_le_maximal _ $ span_eval_ne_top k
instance max_ideal.is_maximal : (max_ideal k).is_maximal :=
(classical.some_spec $ ideal.exists_le_maximal _ $ span_eval_ne_top k).1
theorem le_max_ideal : span_eval k ≤ max_ideal k :=
(classical.some_spec $ ideal.exists_le_maximal _ $ span_eval_ne_top k).2
/-- The first step of constructing `algebraic_closure`: adjoin a root of all monic polynomials -/
def adjoin_monic : Type u :=
(max_ideal k).quotient
instance adjoin_monic.field : field (adjoin_monic k) :=
ideal.quotient.field _
instance adjoin_monic.inhabited : inhabited (adjoin_monic k) := ⟨37⟩
/-- The canonical ring homomorphism to `adjoin_monic k`. -/
def to_adjoin_monic : k →+* adjoin_monic k :=
(ideal.quotient.mk _).comp C
instance adjoin_monic.algebra : algebra k (adjoin_monic k) :=
(to_adjoin_monic k).to_algebra
theorem adjoin_monic.algebra_map : algebra_map k (adjoin_monic k) = (ideal.quotient.mk _).comp C :=
rfl
theorem adjoin_monic.is_integral (z : adjoin_monic k) : is_integral k z :=
let ⟨p, hp⟩ := ideal.quotient.mk_surjective z in hp ▸
mv_polynomial.induction_on p (λ x, is_integral_algebra_map) (λ p q, is_integral_add)
(λ p f ih, @is_integral_mul _ _ _ _ _ _ (ideal.quotient.mk _ _) ih ⟨f, f.2.1,
by { erw [adjoin_monic.algebra_map, ← hom_eval₂,
ideal.quotient.eq_zero_iff_mem],
exact le_max_ideal k (ideal.subset_span ⟨f, rfl⟩) }⟩)
theorem adjoin_monic.exists_root {f : polynomial k} (hfm : f.monic) (hfi : irreducible f) :
∃ x : adjoin_monic k, f.eval₂ (to_adjoin_monic k) x = 0 :=
⟨ideal.quotient.mk _ $ X (⟨f, hfm, hfi⟩ : monic_irreducible k),
by { rw [to_adjoin_monic, ← hom_eval₂, ideal.quotient.eq_zero_iff_mem],
exact le_max_ideal k (ideal.subset_span $ ⟨_, rfl⟩) }⟩
/-- The `n`th step of constructing `algebraic_closure`, together with its `field` instance. -/
def step_aux (n : ℕ) : Σ α : Type u, field α :=
nat.rec_on n ⟨k, infer_instance⟩ $ λ n ih, ⟨@adjoin_monic ih.1 ih.2, @adjoin_monic.field ih.1 ih.2⟩
/-- The `n`th step of constructing `algebraic_closure`. -/
def step (n : ℕ) : Type u :=
(step_aux k n).1
instance step.field (n : ℕ) : field (step k n) :=
(step_aux k n).2
instance step.inhabited (n) : inhabited (step k n) := ⟨37⟩
/-- The canonical inclusion to the `0`th step. -/
def to_step_zero : k →+* step k 0 :=
ring_hom.id k
/-- The canonical ring homomorphism to the next step. -/
def to_step_succ (n : ℕ) : step k n →+* step k (n + 1) :=
@to_adjoin_monic (step k n) (step.field k n)
instance step.algebra_succ (n) : algebra (step k n) (step k (n + 1)) :=
(to_step_succ k n).to_algebra
theorem to_step_succ.exists_root {n} {f : polynomial (step k n)}
(hfm : f.monic) (hfi : irreducible f) :
∃ x : step k (n + 1), f.eval₂ (to_step_succ k n) x = 0 :=
@adjoin_monic.exists_root _ (step.field k n) _ hfm hfi
/-- The canonical ring homomorphism to a step with a greater index. -/
def to_step_of_le (m n : ℕ) (h : m ≤ n) : step k m →+* step k n :=
{ to_fun := nat.le_rec_on h (λ n, to_step_succ k n),
map_one' := begin
induction h with n h ih, { exact nat.le_rec_on_self 1 },
rw [nat.le_rec_on_succ h, ih, ring_hom.map_one]
end,
map_mul' := λ x y, begin
induction h with n h ih, { simp_rw nat.le_rec_on_self },
simp_rw [nat.le_rec_on_succ h, ih, ring_hom.map_mul]
end,
map_zero' := begin
induction h with n h ih, { exact nat.le_rec_on_self 0 },
rw [nat.le_rec_on_succ h, ih, ring_hom.map_zero]
end,
map_add' := λ x y, begin
induction h with n h ih, { simp_rw nat.le_rec_on_self },
simp_rw [nat.le_rec_on_succ h, ih, ring_hom.map_add]
end }
@[simp] lemma coe_to_step_of_le (m n : ℕ) (h : m ≤ n) :
(to_step_of_le k m n h : step k m → step k n) = nat.le_rec_on h (λ n, to_step_succ k n) :=
rfl
instance step.algebra (n) : algebra k (step k n) :=
(to_step_of_le k 0 n n.zero_le).to_algebra
instance step.scalar_tower (n) : is_scalar_tower k (step k n) (step k (n + 1)) :=
is_scalar_tower.of_algebra_map_eq $ λ z,
@nat.le_rec_on_succ (step k) 0 n n.zero_le (n + 1).zero_le (λ n, to_step_succ k n) z
theorem step.is_integral (n) : ∀ z : step k n, is_integral k z :=
nat.rec_on n (λ z, is_integral_algebra_map) $ λ n ih z,
is_integral_trans ih _ (adjoin_monic.is_integral (step k n) z : _)
instance to_step_of_le.directed_system :
directed_system (step k) (λ i j h, to_step_of_le k i j h) :=
⟨λ i x h, nat.le_rec_on_self x, λ i₁ i₂ i₃ h₁₂ h₂₃ x, (nat.le_rec_on_trans h₁₂ h₂₃ x).symm⟩
end algebraic_closure
/-- The canonical algebraic closure of a field, the direct limit of adding roots to the field for each polynomial over the field. -/
def algebraic_closure : Type u :=
ring.direct_limit (algebraic_closure.step k) (λ i j h, algebraic_closure.to_step_of_le k i j h)
namespace algebraic_closure
instance : field (algebraic_closure k) :=
field.direct_limit.field _ _
instance : inhabited (algebraic_closure k) := ⟨37⟩
/-- The canonical ring embedding from the `n`th step to the algebraic closure. -/
def of_step (n : ℕ) : step k n →+* algebraic_closure k :=
ring_hom.of $ ring.direct_limit.of _ _ _
instance algebra_of_step (n) : algebra (step k n) (algebraic_closure k) :=
(of_step k n).to_algebra
theorem of_step_succ (n : ℕ) : (of_step k (n + 1)).comp (to_step_succ k n) = of_step k n :=
ring_hom.ext $ λ x, show ring.direct_limit.of (step k) (λ i j h, to_step_of_le k i j h) _ _ = _,
by { convert ring.direct_limit.of_f n.le_succ x, ext x, exact (nat.le_rec_on_succ' x).symm }
theorem exists_of_step (z : algebraic_closure k) : ∃ n x, of_step k n x = z :=
ring.direct_limit.exists_of z
-- slow
theorem exists_root {f : polynomial (algebraic_closure k)}
(hfm : f.monic) (hfi : irreducible f) :
∃ x : algebraic_closure k, f.eval x = 0 :=
begin
have : ∃ n p, polynomial.map (of_step k n) p = f,
{ convert ring.direct_limit.polynomial.exists_of f },
unfreezingI { obtain ⟨n, p, rfl⟩ := this },
rw monic_map_iff at hfm,
have := irreducible_of_irreducible_map (of_step k n) p hfm hfi,
obtain ⟨x, hx⟩ := to_step_succ.exists_root k hfm this,
refine ⟨of_step k (n + 1) x, _⟩,
rw [← of_step_succ k n, eval_map, ← hom_eval₂, hx, ring_hom.map_zero]
end
instance : is_alg_closed (algebraic_closure k) :=
is_alg_closed.of_exists_root _ $ λ f, exists_root k
instance : algebra k (algebraic_closure k) :=
(of_step k 0).to_algebra
/-- Canonical algebra embedding from the `n`th step to the algebraic closure. -/
def of_step_hom (n) : step k n →ₐ[k] algebraic_closure k :=
{ commutes' := λ x, ring.direct_limit.of_f n.zero_le x,
.. of_step k n }
theorem is_algebraic : algebra.is_algebraic k (algebraic_closure k) :=
λ z, (is_algebraic_iff_is_integral _).2 $ let ⟨n, x, hx⟩ := exists_of_step k z in
hx ▸ is_integral_alg_hom (of_step_hom k n) (step.is_integral k n x)
instance : is_alg_closure k (algebraic_closure k) :=
⟨algebraic_closure.is_alg_closed k, is_algebraic k⟩
end algebraic_closure
|
cf1d761f5791ea4baf431c539617540fb2105406 | 3963b5943679836674f6eaad619c3add9b54cdf3 | /leanprover/leftpad.lean | 7e1f614a8ce4ede7836b1cbed0ca2682f9e69770 | [
"LicenseRef-scancode-unknown-license-reference",
"CC0-1.0"
] | permissive | hwayne/lets-prove-leftpad | f67dba7edf25c624b0b2df14e341a94815b5e01b | 6a1457fd190b2b44db049176663dcbef514fd16a | refs/heads/master | 1,693,274,833,535 | 1,692,309,655,000 | 1,692,309,655,000 | 132,528,683 | 568 | 64 | NOASSERTION | 1,694,694,020,000 | 1,525,736,917,000 | SystemVerilog | UTF-8 | Lean | false | false | 677 | lean | import data.nat.basic
import data.list
open list
universes u
variables {α : Type u}
def leftpad (n : ℕ) (a : α) (l : list α) : list α :=
repeat a (n - length l) ++ l
#eval list.as_string (leftpad 5 'b' (string.to_list "ac"))
theorem leftpad_length (n : ℕ) (a : α) (l : list α) :
length (leftpad n a l) = max n (length l) :=
begin
rw leftpad, simp,
rw [add_comm, nat.sub_add_eq_max]
end
theorem leftpad_prefix [decidable_eq α] (n : ℕ) (a : α) (l : list α) :
(repeat a (n - length l)) <+: (leftpad n a l) := by {rw leftpad, simp}
theorem leftpad_suffix [decidable_eq α] (n : ℕ) (a : α) (l : list α) :
l <:+ (leftpad n a l) := by {rw leftpad, simp}
|
99837bb0881145d97f00a1ba0b593b9cf789d021 | 7c2dd01406c42053207061adb11703dc7ce0b5e5 | /src/solutions/tuto_lib.lean | 3cc334627bcfda3c61a7e04704d63feab611dc71 | [
"Apache-2.0"
] | permissive | leanprover-community/tutorials | 50ec79564cbf2ad1afd1ac43d8ee3c592c2883a8 | 79a6872a755c4ae0c2aca57e1adfdac38b1d8bb1 | refs/heads/master | 1,687,466,144,386 | 1,672,061,276,000 | 1,672,061,276,000 | 189,169,918 | 186 | 81 | Apache-2.0 | 1,686,350,300,000 | 1,559,113,678,000 | Lean | UTF-8 | Lean | false | false | 6,781 | lean | import analysis.specific_limits.basic
import data.int.parity
import topology.sequences
attribute [instance] classical.prop_decidable
/-
Lemmas from that file were hidden in my course, or restating things which
were proved without name in previous files.
-/
notation `|`x`|` := abs x
-- The mathlib version is unusable because it is stated in terms of ≤
lemma ge_max_iff {α : Type*} [linear_order α] {p q r : α} : r ≥ max p q ↔ r ≥ p ∧ r ≥ q :=
max_le_iff
/- No idea why this is not in mathlib-/
lemma eq_of_abs_sub_le_all (x y : ℝ) : (∀ ε > 0, |x - y| ≤ ε) → x = y :=
begin
intro h,
apply eq_of_abs_sub_nonpos,
by_contradiction H,
push_neg at H,
specialize h ( |x-y|/2) (by linarith),
linarith,
end
def seq_limit (u : ℕ → ℝ) (l : ℝ) : Prop :=
∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| ≤ ε
lemma unique_limit {u l l'} : seq_limit u l → seq_limit u l' → l = l' :=
begin
intros hl hl',
apply eq_of_abs_sub_le_all,
intros ε ε_pos,
specialize hl (ε/2) (by linarith),
cases hl with N hN,
specialize hl' (ε/2) (by linarith),
cases hl' with N' hN',
specialize hN (max N N') (le_max_left _ _),
specialize hN' (max N N') (le_max_right _ _),
calc |l - l'| = |(l-u (max N N')) + (u (max N N') -l')| : by ring_nf
... ≤ |l - u (max N N')| + |u (max N N') - l'| : by apply abs_add
... = |u (max N N') - l| + |u (max N N') - l'| : by rw abs_sub_comm
... ≤ ε/2 + ε/2 : by linarith
... = ε : by ring,
end
lemma le_of_le_add_all {x y : ℝ} :
(∀ ε > 0, y ≤ x + ε) → y ≤ x :=
begin
contrapose!,
intro h,
use (y-x)/2,
split ; linarith,
end
def upper_bound (A : set ℝ) (x : ℝ) := ∀ a ∈ A, a ≤ x
def is_sup (A : set ℝ) (x : ℝ) := upper_bound A x ∧ ∀ y, upper_bound A y → x ≤ y
lemma lt_sup {A : set ℝ} {x : ℝ} (hx : is_sup A x) :
∀ y, y < x → ∃ a ∈ A, y < a :=
begin
intro y,
contrapose!,
exact hx.right y,
end
lemma squeeze {u v w : ℕ → ℝ} {l} (hu : seq_limit u l) (hw : seq_limit w l)
(h : ∀ n, u n ≤ v n)
(h' : ∀ n, v n ≤ w n) : seq_limit v l :=
begin
intros ε ε_pos,
cases hu ε ε_pos with N hN,
cases hw ε ε_pos with N' hN',
use max N N',
intros n hn,
rw ge_max_iff at hn,
specialize hN n (by linarith),
specialize hN' n (by linarith),
specialize h n,
specialize h' n,
rw abs_le at *,
split ; linarith
end
def extraction (φ : ℕ → ℕ) := ∀ n m, n < m → φ n < φ m
def tendsto_infinity (u : ℕ → ℝ) := ∀ A, ∃ N, ∀ n ≥ N, u n ≥ A
lemma lim_le {x y : ℝ} {u : ℕ → ℝ} (hu : seq_limit u x)
(ineg : ∀ n, u n ≤ y) : x ≤ y :=
begin
apply le_of_le_add_all,
intros ε ε_pos,
cases hu ε ε_pos with N hN,
specialize hN N (by linarith),
specialize ineg N,
rw abs_le at hN,
linarith,
end
lemma inv_succ_le_all : ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, 1/(n + 1 : ℝ) ≤ ε :=
begin
convert metric.tendsto_at_top.mp (tendsto_one_div_add_at_top_nhds_0_nat),
apply propext,
simp only [real.dist_eq, sub_zero],
split,
intros h ε ε_pos,
cases h (ε/2) (by linarith) with N hN,
use N,
intros n hn,
rw abs_of_pos (nat.one_div_pos_of_nat : 1/(n+1 : ℝ) > 0),
specialize hN n hn,
linarith,
intros h ε ε_pos,
cases h ε (by linarith) with N hN,
use N,
intros n hn,
specialize hN n hn,
rw abs_of_pos (@nat.one_div_pos_of_nat ℝ _ n) at hN,
linarith,
end
lemma limit_const (x : ℝ) : seq_limit (λ n, x) x :=
λ ε ε_pos, ⟨0, λ _ _, by simp [le_of_lt ε_pos]⟩
lemma limit_of_sub_le_inv_succ {u : ℕ → ℝ} {x : ℝ} (h : ∀ n, |u n - x| ≤ 1/(n+1)) :
seq_limit u x :=
begin
intros ε ε_pos,
rcases inv_succ_le_all ε ε_pos with ⟨N, hN⟩,
use N,
intros n hn,
specialize h n,
specialize hN n hn,
linarith,
end
lemma limit_const_add_inv_succ (x : ℝ) : seq_limit (λ n, x + 1/(n+1)) x :=
limit_of_sub_le_inv_succ (λ n, by rw abs_of_pos ; linarith [@nat.one_div_pos_of_nat ℝ _ n])
lemma limit_const_sub_inv_succ (x : ℝ) : seq_limit (λ n, x - 1/(n+1)) x :=
begin
refine limit_of_sub_le_inv_succ (λ n, _),
rw [show x - 1 / (n + 1) - x = -(1/(n+1)), by ring, abs_neg, abs_of_pos],
linarith [@nat.one_div_pos_of_nat ℝ _ n]
end
lemma id_le_extraction {φ}: extraction φ → ∀ n, n ≤ φ n :=
begin
intros hyp n,
induction n with n hn,
{ exact nat.zero_le _ },
{ exact nat.succ_le_of_lt (by linarith [hyp n (n+1) (by linarith)]) },
end
lemma seq_limit_id : tendsto_infinity (λ n, n) :=
begin
intros A,
cases exists_nat_gt A with N hN,
use N,
intros n hn,
have : (n : ℝ) ≥ N, exact_mod_cast hn,
linarith,
end
variables {u : ℕ → ℝ} {l : ℝ} {φ : ℕ → ℕ}
open set filter
def cluster_point (u : ℕ → ℝ) (a : ℝ) :=
∃ φ, extraction φ ∧ seq_limit (u ∘ φ) a
lemma bolzano_weierstrass {a b : ℝ} {u : ℕ → ℝ} (h : ∀ n, u n ∈ Icc a b) :
∃ c ∈ Icc a b, cluster_point u c :=
begin
rcases (is_compact_Icc : is_compact (Icc a b)).tendsto_subseq h with ⟨c, c_in, φ, hφ, lim⟩,
use [c, c_in, φ, hφ],
simp_rw [metric.tendsto_nhds, eventually_at_top, real.dist_eq] at lim,
intros ε ε_pos,
rcases lim ε ε_pos with ⟨N, hN⟩,
use N,
intros n hn,
exact le_of_lt (hN n hn)
end
lemma not_seq_limit_of_tendstoinfinity {u : ℕ → ℝ} :
tendsto_infinity u → ∀ x, ¬ seq_limit u x :=
begin
intros lim_infinie x lim_x,
cases lim_x 1 (by linarith) with N hN,
cases lim_infinie (x+2) with N' hN',
let N₀ := max N N',
specialize hN N₀ (le_max_left _ _),
specialize hN' N₀ (le_max_right _ _),
rw abs_le at hN,
linarith,
end
open real
lemma sup_segment {a b : ℝ} {A : set ℝ} (hnonvide : ∃ x, x ∈ A) (h : A ⊆ Icc a b) :
∃ x ∈ Icc a b, is_sup A x :=
begin
have b_maj : ∀ (y : ℝ), y ∈ A → y ≤ b,
from λ y y_in, (h y_in).2,
have Sup_maj : upper_bound A (Sup A),
{ intro x,
apply le_cSup,
use [b, b_maj] } ,
refine ⟨Sup A, _, _⟩,
{ split,
{ cases hnonvide with x x_in,
exact le_trans (h x_in).1 (Sup_maj _ x_in) },
{ apply cSup_le hnonvide b_maj } },
{ exact ⟨Sup_maj, λ y, cSup_le hnonvide⟩ },
end
lemma subseq_tendsto_of_tendsto (h : seq_limit u l) (hφ : extraction φ) :
seq_limit (u ∘ φ) l :=
begin
intros ε ε_pos,
cases h ε ε_pos with N hN,
use N,
intros n hn,
apply hN,
calc N ≤ n : hn
... ≤ φ n : id_le_extraction hφ n,
end
namespace tactic.interactive
open tactic
meta def check_me : tactic unit :=
`[ { repeat { unfold seq_limit},
repeat { unfold continue_en },
push_neg,
try { simp only [exists_prop] },
try { exact iff.rfl },
done } <|> fail "That's not quite right. Please try again." ]
end tactic.interactive
|
4af8a3199e8c9a441c9db7d4832838ee218d984f | 6094e25ea0b7699e642463b48e51b2ead6ddc23f | /tests/lean/run/blast_grind1.lean | 08c382c1069c897c5866529b6048bdc9d352b2a3 | [
"Apache-2.0"
] | permissive | gbaz/lean | a7835c4e3006fbbb079e8f8ffe18aacc45adebfb | a501c308be3acaa50a2c0610ce2e0d71becf8032 | refs/heads/master | 1,611,198,791,433 | 1,451,339,111,000 | 1,451,339,111,000 | 48,713,797 | 0 | 0 | null | 1,451,338,939,000 | 1,451,338,939,000 | null | UTF-8 | Lean | false | false | 916 | lean | set_option blast.strategy "core_grind"
example (a b c : nat) : a = b ∨ a = c → b = c → b = a :=
by blast
example (f : nat → nat) (a b c : nat) : f a = f b ∨ f a = f c → f b = f c → f b = f a :=
by blast
definition ex1 (a : nat) : a = 0 → (λ x, x + a) = (λ x, x + 0) :=
by blast
print ex1
attribute Exists.intro [intro!] -- grind and core_grind only process [intro!] declarations
example (p q : nat → Prop) : (∃ x, p x ∧ q x) → (∃ x, q x) ∧ (∃ x, p x) :=
by blast
set_option blast.strategy "grind"
example (a b c : nat) : a = b ∨ a = c → b = c → b = a :=
by blast
example (f : nat → nat) (a b c : nat) : f a = f b ∨ f a = f c → f b = f c → f b = f a :=
by blast
example (a : nat) : a = 0 → (λ x, x + a) = (λ x, x + 0) :=
by blast
set_option trace.blast true
example (p q : nat → Prop) : (∃ x, p x ∧ q x) → (∃ x, q x) ∧ (∃ x, p x) :=
by blast
|
f65fef62aa5cb932017e86996752f0624d387423 | 958488bc7f3c2044206e0358e56d7690b6ae696c | /lean/tutorials/tutorial2.lean | 80ec0607feb35d4502a54fc5352e3a0415dc023a | [] | no_license | possientis/Prog | a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4 | d4b3debc37610a88e0dac3ac5914903604fd1d1f | refs/heads/master | 1,692,263,717,723 | 1,691,757,179,000 | 1,691,757,179,000 | 40,361,602 | 3 | 0 | null | 1,679,896,438,000 | 1,438,953,859,000 | Coq | UTF-8 | Lean | false | false | 4,279 | lean | import data.real.basic
example : ∀ (a b c : ℝ), a ≤ b → c + a ≤ c + b :=
begin
intros a b c H₁, rw ← sub_nonneg,
have H₂ : c + b - (c + a) = b - a, by ring,
rw [H₂, sub_nonneg], assumption
end
example : ∀ (a b : ℝ), a ≤ b → ∀ (c : ℝ), a + c ≤ b + c :=
begin
intros a b H₁ c, rw ← sub_nonneg,
have H₂ : b + c - (a + c) = b - a, by ring,
rw [H₂, sub_nonneg], assumption
end
example : ∀ (a b : ℝ), 0 ≤ a → b ≤ a + b :=
begin
intros a b H₁,
calc
b = 0 + b : by rw zero_add
... ≤ a + b : add_le_add_right H₁ b
end
example : ∀ (a b : ℝ), 0 ≤ b → a ≤ a + b :=
begin
intros a b H₁,
calc
a = a + 0 : by rw add_zero
... ≤ a + b : add_le_add_left H₁ a
end
example : ∀ (a b : ℝ), 0 ≤ a → 0 ≤ b → 0 ≤ a + b :=
begin
intros a b H₁ H₂,
calc
0 = 0 + 0 : by rw add_zero
... ≤ a + 0 : add_le_add_right H₁ 0
... ≤ a + b : add_le_add_left H₂ a
end
example : ∀ (a b c d : ℝ), a ≤ b → c ≤ d → a + c ≤ b + d :=
begin
intros a b c d H₁ H₂,
calc
a + c ≤ b + c : add_le_add_right H₁ c
... ≤ b + d : add_le_add_left H₂ b
end
example : ∀ (a b c : ℝ), 0 ≤ c → a ≤ b → a*c ≤ b*c :=
begin
intros a b c H₁ H₂, rw ← sub_nonneg,
have H₃ : b*c - a*c = (b - a)*c, by ring,
rw H₃, apply mul_nonneg; try {assumption},
rw sub_nonneg, assumption
end
example : ∀ (a b c : ℝ), 0 ≤ c → a ≤ b → a*c ≤ b*c :=
begin
intros a b c H₁ H₂,
have H₃ : 0 ≤ b - a ,{ rw sub_nonneg, assumption },
have H₄ : 0 ≤ (b - a)*c ,{ apply mul_nonneg; assumption },
have H₅ : (b - a)*c = b*c - a*c ,{ ring },
have H₆ : 0 ≤ b*c - a*c ,{ rw ← H₅, assumption },
rw ← sub_nonneg, assumption
end
-- Slightly shorter using 'rwa' tactic
example : ∀ (a b c : ℝ), 0 ≤ c → a ≤ b → a*c ≤ b*c :=
begin
intros a b c H₁ H₂,
have H₃ : 0 ≤ b - a ,{ rwa sub_nonneg },
have H₄ : 0 ≤ (b -a)*c ,{ apply mul_nonneg; assumption },
have H₅ : (b - a)*c = b*c - a*c ,{ ring },
have H₆ : 0 ≤ b*c - a*c ,{ rwa ← H₅ },
rwa ← sub_nonneg
end
example : ∀ (a b c : ℝ), 0 ≤ c → a ≤ b → a*c ≤ b*c :=
begin
intros a b c H₁ H₂, rw ← sub_nonneg, calc
0 ≤ (b - a)*c : mul_nonneg (by rwa sub_nonneg) H₁
... = b*c - a*c : by ring,
end
-- Backward reasoning
example : ∀ (a b c : ℝ), c ≤ 0 → a ≤ b → b*c ≤ a*c :=
begin
intros a b c H₁ H₂, rw ← sub_nonneg,
have H₃ : a*c - b*c = (a - b)*c, { ring },
rw H₃,
apply mul_nonneg_of_nonpos_of_nonpos; try { assumption },
rwa sub_nonpos
end
-- Forward reasoning
example : ∀ (a b c : ℝ), c ≤ 0 → a ≤ b → b*c ≤ a*c :=
begin
intros a b c H₁ H₂,
have H₃ : a - b ≤ 0, { rwa sub_nonpos },
have H₄ : 0 ≤ (a - b)*c, { apply mul_nonneg_of_nonpos_of_nonpos; assumption },
have H₅ : (a - b)*c = a*c - b*c, { ring },
have H₆ : 0 ≤ a*c - b*c, { rwa ← H₅ },
rwa ← sub_nonneg
end
example : ∀ (a b c : ℝ), c ≤ 0 → a ≤ b → b*c ≤ a*c :=
begin
intros a b c H₁ H₂, rw ← sub_nonneg, calc
0 ≤ (a - b)*c : mul_nonneg_of_nonpos_of_nonpos (by rwa sub_nonpos) H₁
... = a * c - b* c : by ring
end
example : ∀ (P Q R : Prop), (P ∧ Q → R) ↔ (P → Q → R) :=
begin
intros P Q R, split; intros H₁,
{ intros H₂ H₃, apply H₁, split; assumption },
{ rintros ⟨H₂,H₃⟩, apply H₁; assumption }
end
example : ∀ (a b : ℝ), 0 ≤ b → a ≤ a + b :=
begin
intros a b H₁, linarith
end
example : ∀ (a b : ℝ), 0 ≤ a → 0 ≤ b → 0 ≤ a + b :=
begin
intros a b H₁ H₂, linarith
end
example : ∀ (a b c d : ℝ), a ≤ b → c ≤ d → a + c ≤ b + d :=
begin
intros a b c d H₁ H₂, linarith
end
open nat
example : ∀ (a b : ℕ), a ∣ b ↔ gcd a b = a := -- '∣' is \| ... not just |
begin
intros a b, split; intros H₁,
{ apply dvd_antisymm,
{ apply gcd_dvd_left },
{ rw dvd_gcd_iff, split,
{ apply dvd_refl},
{ assumption }}},
{ rw ← H₁, apply gcd_dvd_right }
end
|
479e610b0eef922091e4ae8d6eb76bfa048e72dc | 94e33a31faa76775069b071adea97e86e218a8ee | /src/category_theory/limits/shapes/finite_limits.lean | 56b4bc4ccb4c0d835e5a57f03cc009865bd771bf | [
"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 | 8,521 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.fin_category
import category_theory.limits.shapes.binary_products
import category_theory.limits.shapes.equalizers
import category_theory.limits.shapes.wide_pullbacks
import category_theory.limits.shapes.pullbacks
import data.fintype.basic
/-!
# Categories with finite limits.
A typeclass for categories with all finite (co)limits.
-/
universes w' w v' u' v u
noncomputable theory
open category_theory
namespace category_theory.limits
variables (C : Type u) [category.{v} C]
/--
A category has all finite limits if every functor `J ⥤ C` with a `fin_category J`
instance and `J : Type` has a limit.
This is often called 'finitely complete'.
-/
-- We can't just made this an `abbreviation`
-- because of https://github.com/leanprover-community/lean/issues/429
class has_finite_limits : Prop :=
(out (J : Type) [𝒥 : small_category J] [@fin_category J 𝒥] : @has_limits_of_shape J 𝒥 C _)
@[priority 100]
instance has_limits_of_shape_of_has_finite_limits
(J : Type w) [small_category J] [fin_category J] [has_finite_limits C] :
has_limits_of_shape J C :=
begin
apply has_limits_of_shape_of_equivalence (fin_category.equiv_as_type J),
apply has_finite_limits.out
end
@[priority 100]
instance has_finite_limits_of_has_limits_of_size [has_limits_of_size.{v' u'} C] :
has_finite_limits C :=
⟨λ J hJ hJ', by { haveI := has_limits_of_size_shrink.{0 0} C,
exact has_limits_of_shape_of_equivalence (fin_category.equiv_as_type J) }⟩
/-- If `C` has all limits, it has finite limits. -/
@[priority 100]
instance has_finite_limits_of_has_limits [has_limits C] : has_finite_limits C :=
infer_instance
/-- We can always derive `has_finite_limits C` by providing limits at an
arbitrary universe. -/
lemma has_finite_limits_of_has_finite_limits_of_size
(h : ∀ (J : Type w) {𝒥 : small_category J} (hJ : @fin_category J 𝒥),
by { resetI, exact has_limits_of_shape J C }) :
has_finite_limits C :=
⟨λ J hJ hhJ,
begin
resetI,
letI : category.{w w} (ulift_hom.{w} (ulift.{w 0} J)),
{ apply ulift_hom.category.{0}, exact category_theory.ulift_category J },
haveI := h (ulift_hom.{w} (ulift.{w} J)) category_theory.fin_category_ulift,
exact has_limits_of_shape_of_equivalence (ulift_hom_ulift_category.equiv.{w w} J).symm
end ⟩
/--
A category has all finite colimits if every functor `J ⥤ C` with a `fin_category J`
instance and `J : Type` has a colimit.
This is often called 'finitely cocomplete'.
-/
class has_finite_colimits : Prop :=
(out (J : Type) [𝒥 : small_category J] [@fin_category J 𝒥] : @has_colimits_of_shape J 𝒥 C _)
@[priority 100]
instance has_colimits_of_shape_of_has_finite_colimits
(J : Type w) [small_category J] [fin_category J] [has_finite_colimits C] :
has_colimits_of_shape J C :=
begin
apply has_colimits_of_shape_of_equivalence (fin_category.equiv_as_type J),
apply has_finite_colimits.out
end
@[priority 100]
instance has_finite_colimits_of_has_colimits_of_size [has_colimits_of_size.{v' u'} C] :
has_finite_colimits C :=
⟨λ J hJ hJ', by { haveI := has_colimits_of_size_shrink.{0 0} C,
exact has_colimits_of_shape_of_equivalence (fin_category.equiv_as_type J) }⟩
/-- We can always derive `has_finite_colimits C` by providing colimits at an
arbitrary universe. -/
lemma has_finite_colimits_of_has_finite_colimits_of_size
(h : ∀ (J : Type w) {𝒥 : small_category J} (hJ : @fin_category J 𝒥),
by { resetI, exact has_colimits_of_shape J C }) :
has_finite_colimits C :=
⟨λ J hJ hhJ,
begin
resetI,
letI : category.{w w} (ulift_hom.{w} (ulift.{w 0} J)),
{ apply ulift_hom.category.{0}, exact category_theory.ulift_category J },
haveI := h (ulift_hom.{w} (ulift.{w} J)) category_theory.fin_category_ulift,
exact has_colimits_of_shape_of_equivalence (ulift_hom_ulift_category.equiv.{w w} J).symm
end ⟩
section
open walking_parallel_pair walking_parallel_pair_hom
instance fintype_walking_parallel_pair : fintype walking_parallel_pair :=
{ elems := [walking_parallel_pair.zero, walking_parallel_pair.one].to_finset,
complete := λ x, by { cases x; simp } }
local attribute [tidy] tactic.case_bash
instance (j j' : walking_parallel_pair) : fintype (walking_parallel_pair_hom j j') :=
{ elems := walking_parallel_pair.rec_on j
(walking_parallel_pair.rec_on j' [walking_parallel_pair_hom.id zero].to_finset
[left, right].to_finset)
(walking_parallel_pair.rec_on j' ∅ [walking_parallel_pair_hom.id one].to_finset),
complete := by tidy }
end
instance : fin_category walking_parallel_pair := { }
/-- Equalizers are finite limits, so if `C` has all finite limits, it also has all equalizers -/
example [has_finite_limits C] : has_equalizers C := by apply_instance
/-- Coequalizers are finite colimits, of if `C` has all finite colimits, it also has all
coequalizers -/
example [has_finite_colimits C] : has_coequalizers C := by apply_instance
variables {J : Type v}
local attribute [tidy] tactic.case_bash
namespace wide_pullback_shape
instance fintype_obj [fintype J] : fintype (wide_pullback_shape J) :=
by { rw wide_pullback_shape, apply_instance }
instance fintype_hom (j j' : wide_pullback_shape J) : fintype (j ⟶ j') :=
{ elems :=
begin
cases j',
{ cases j,
{ exact {hom.id none} },
{ exact {hom.term j} } },
{ by_cases some j' = j,
{ rw h,
exact {hom.id j} },
{ exact ∅ } }
end,
complete := by tidy }
end wide_pullback_shape
namespace wide_pushout_shape
instance fintype_obj [fintype J] : fintype (wide_pushout_shape J) :=
by { rw wide_pushout_shape, apply_instance }
instance fintype_hom (j j' : wide_pushout_shape J) : fintype (j ⟶ j') :=
{ elems :=
begin
cases j,
{ cases j',
{ exact {hom.id none} },
{ exact {hom.init j'} } },
{ by_cases some j = j',
{ rw h,
exact {hom.id j'} },
{ exact ∅ } }
end,
complete := by tidy }
end wide_pushout_shape
instance fin_category_wide_pullback [fintype J] : fin_category (wide_pullback_shape J) :=
{ fintype_hom := wide_pullback_shape.fintype_hom }
instance fin_category_wide_pushout [fintype J] :
fin_category (wide_pushout_shape J) :=
{ fintype_hom := wide_pushout_shape.fintype_hom }
/--
`has_finite_wide_pullbacks` represents a choice of wide pullback
for every finite collection of morphisms
-/
-- We can't just made this an `abbreviation`
-- because of https://github.com/leanprover-community/lean/issues/429
class has_finite_wide_pullbacks : Prop :=
(out (J : Type) [fintype J] : has_limits_of_shape (wide_pullback_shape J) C)
instance has_limits_of_shape_wide_pullback_shape
(J : Type) [fintype J] [has_finite_wide_pullbacks C] :
has_limits_of_shape (wide_pullback_shape J) C :=
by { haveI := @has_finite_wide_pullbacks.out C _ _ J, apply_instance }
/--
`has_finite_wide_pushouts` represents a choice of wide pushout
for every finite collection of morphisms
-/
class has_finite_wide_pushouts : Prop :=
(out (J : Type) [fintype J] : has_colimits_of_shape (wide_pushout_shape J) C)
instance has_colimits_of_shape_wide_pushout_shape
(J : Type) [fintype J] [has_finite_wide_pushouts C] :
has_colimits_of_shape (wide_pushout_shape J) C :=
by { haveI := @has_finite_wide_pushouts.out C _ _ J, apply_instance }
/--
Finite wide pullbacks are finite limits, so if `C` has all finite limits,
it also has finite wide pullbacks
-/
lemma has_finite_wide_pullbacks_of_has_finite_limits [has_finite_limits C] :
has_finite_wide_pullbacks C :=
⟨λ J _, by exactI has_finite_limits.out _⟩
/--
Finite wide pushouts are finite colimits, so if `C` has all finite colimits,
it also has finite wide pushouts
-/
lemma has_finite_wide_pushouts_of_has_finite_limits [has_finite_colimits C] :
has_finite_wide_pushouts C :=
⟨λ J _, by exactI has_finite_colimits.out _⟩
instance fintype_walking_pair : fintype walking_pair :=
{ elems := {walking_pair.left, walking_pair.right},
complete := λ x, by { cases x; simp } }
/-- Pullbacks are finite limits, so if `C` has all finite limits, it also has all pullbacks -/
example [has_finite_wide_pullbacks C] : has_pullbacks C := by apply_instance
/-- Pushouts are finite colimits, so if `C` has all finite colimits, it also has all pushouts -/
example [has_finite_wide_pushouts C] : has_pushouts C := by apply_instance
end category_theory.limits
|
d86a2ec59a0eb18a1676eea3e81e129b6d076db7 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/interactive/complete_import.lean | 186a8e012311621c5714b7c56cbe0862c49c2c75 | [
"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 | 655 | lean | import -- should not trigger
--^ "command": "complete", "skip_completions": true
import
--^ "command": "complete", "skip_completions": true
import .
--^ "command": "complete", "skip_completions": true
import ..
--^ "command": "complete", "skip_completions": true
import foo
--^ "command": "complete", "skip_completions": true
import foo.
--^ "command": "complete", "skip_completions": true
import .foo
--^ "command": "complete", "skip_completions": true
import foo
--^ "command": "complete", "skip_completions": true
import foo bar
--^ "command": "complete", "skip_completions": true
|
1aead9d313ff770d9af41d9733d1654217a83ab4 | f3849be5d845a1cb97680f0bbbe03b85518312f0 | /tests/lean/utf8.lean | 8455ee9cac7b1bee6ae4534bfb58126093e14c17 | [
"Apache-2.0"
] | permissive | bjoeris/lean | 0ed95125d762b17bfcb54dad1f9721f953f92eeb | 4e496b78d5e73545fa4f9a807155113d8e6b0561 | refs/heads/master | 1,611,251,218,281 | 1,495,337,658,000 | 1,495,337,658,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 248 | lean | open list
#eval length "α₁"
#eval length "α₁ → β₁"
#eval length "∀ α : nat → nat, α 0 ≥ 0"
#print "------------"
#eval utf8_length "α₁"
#eval utf8_length "α₁ → β₁"
#eval utf8_length "∀ α : nat → nat, α 0 ≥ 0"
|
4a6529084d11e57bcfe5b16a2891bec70a80b24a | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/tactic/omega/prove_unsats.lean | ed0252b8b541636af2b5c606078c6b0aed2b6551 | [
"Apache-2.0"
] | permissive | gebner/mathlib | eab0150cc4f79ec45d2016a8c21750244a2e7ff0 | cc6a6edc397c55118df62831e23bfbd6e6c6b4ab | refs/heads/master | 1,625,574,853,976 | 1,586,712,827,000 | 1,586,712,827,000 | 99,101,412 | 1 | 0 | Apache-2.0 | 1,586,716,389,000 | 1,501,667,958,000 | Lean | UTF-8 | Lean | false | false | 2,079 | lean | /- Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Seul Baek
A tactic which constructs exprs to discharge
goals of the form `clauses.unsat cs`. -/
import tactic.omega.find_ees
import tactic.omega.find_scalars
import tactic.omega.lin_comb
namespace omega
open tactic
/-- Return expr of proof that given int is negative -/
meta def prove_neg : int → tactic expr
| (int.of_nat _) := failed
| -[1+ m] := return `(int.neg_succ_lt_zero %%`(m))
lemma forall_mem_repeat_zero_eq_zero (m : nat) :
(∀ x ∈ (list.repeat (0 : int) m), x = (0 : int)) :=
λ x, list.eq_of_mem_repeat
/-- Return expr of proof that elements of (repeat 0 is.length) are all 0 -/
meta def prove_forall_mem_eq_zero (is : list int) : tactic expr :=
return `(forall_mem_repeat_zero_eq_zero is.length)
/-- Return expr of proof that the combination of linear constraints
represented by ks and ts is unsatisfiable -/
meta def prove_unsat_lin_comb (ks : list nat) (ts : list term) : tactic expr :=
let ⟨b,as⟩ := lin_comb ks ts in
do x1 ← prove_neg b,
x2 ← prove_forall_mem_eq_zero as,
to_expr ``(unsat_lin_comb_of %%`(ks) %%`(ts) %%x1 %%x2)
/-- Given a (([],les) : clause), return the expr of a term (t : clause.unsat ([],les)). -/
meta def prove_unsat_ef : clause → tactic expr
| ((_::_), _) := failed
| ([], les) :=
do ks ← find_scalars les,
x ← prove_unsat_lin_comb ks les,
return `(unsat_of_unsat_lin_comb %%`(ks) %%`(les) %%x)
/-- Given a (c : clause), return the expr of a term (t : clause.unsat c) -/
meta def prove_unsat (c : clause) : tactic expr :=
do ee ← find_ees c,
x ← prove_unsat_ef (eq_elim ee c),
return `(unsat_of_unsat_eq_elim %%`(ee) %%`(c) %%x)
/-- Given a (cs : list clause), return the expr of a term (t : clauses.unsat cs) -/
meta def prove_unsats : list clause → tactic expr
| [] := return `(clauses.unsat_nil)
| (p::ps) :=
do x ← prove_unsat p,
xs ← prove_unsats ps,
to_expr ``(clauses.unsat_cons %%`(p) %%`(ps) %%x %%xs)
end omega
|
b75a11b3378fa83b9a754fed45448633840fe456 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/linear_algebra/bilinear_map.lean | 84cd7d4333f226e6bd890ea4db078cd91c4b39d6 | [
"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 | 15,333 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Mario Carneiro
-/
import linear_algebra.basic
import linear_algebra.basis
/-!
# Basics on bilinear maps
This file provides basics on bilinear maps. The most general form considered are maps that are
semilinear in both arguments. They are of type `M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P`, where `M` and `N`
are modules over `R` and `S` respectively, `P` is a module over both `R₂` and `S₂` with
commuting actions, and `ρ₁₂ : R →+* R₂` and `σ₁₂ : S →+* S₂`.
## Main declarations
* `linear_map.mk₂`: a constructor for bilinear maps,
taking an unbundled function together with proof witnesses of bilinearity
* `linear_map.flip`: turns a bilinear map `M × N → P` into `N × M → P`
* `linear_map.lcomp` and `linear_map.llcomp`: composition of linear maps as a bilinear map
* `linear_map.compl₂`: composition of a bilinear map `M × N → P` with a linear map `Q → M`
* `linear_map.compr₂`: composition of a bilinear map `M × N → P` with a linear map `Q → N`
* `linear_map.lsmul`: scalar multiplication as a bilinear map `R × M → M`
## Tags
bilinear
-/
variables {ι₁ ι₂ : Type*}
namespace linear_map
section semiring
-- the `ₗ` subscript variables are for special cases about linear (as opposed to semilinear) maps
variables {R : Type*} [semiring R] {S : Type*} [semiring S]
variables {R₂ : Type*} [semiring R₂] {S₂ : Type*} [semiring S₂]
variables {M : Type*} {N : Type*} {P : Type*}
variables {M₂ : Type*} {N₂ : Type*} {P₂ : Type*}
variables {Nₗ : Type*} {Pₗ : Type*}
variables {M' : Type*} {N' : Type*} {P' : Type*}
variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P]
variables [add_comm_monoid M₂] [add_comm_monoid N₂] [add_comm_monoid P₂]
variables [add_comm_monoid Nₗ] [add_comm_monoid Pₗ]
variables [add_comm_group M'] [add_comm_group N'] [add_comm_group P']
variables [module R M] [module S N] [module R₂ P] [module S₂ P]
variables [module R M₂] [module S N₂] [module R P₂] [module S₂ P₂]
variables [module R Pₗ] [module S Pₗ]
variables [module R M'] [module S N'] [module R₂ P'] [module S₂ P']
variables [smul_comm_class S₂ R₂ P] [smul_comm_class S R Pₗ] [smul_comm_class S₂ R₂ P']
variables [smul_comm_class S₂ R P₂]
variables {ρ₁₂ : R →+* R₂} {σ₁₂ : S →+* S₂}
variables (ρ₁₂ σ₁₂)
/-- Create a bilinear map from a function that is semilinear in each component.
See `mk₂'` and `mk₂` for the linear case. -/
def mk₂'ₛₗ (f : M → N → P)
(H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n)
(H2 : ∀ (c:R) m n, f (c • m) n = (ρ₁₂ c) • f m n)
(H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂)
(H4 : ∀ (c:S) m n, f m (c • n) = (σ₁₂ c) • f m n) : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P :=
{ to_fun := λ m, { to_fun := f m, map_add' := H3 m, map_smul' := λ c, H4 c m},
map_add' := λ m₁ m₂, linear_map.ext $ H1 m₁ m₂,
map_smul' := λ c m, linear_map.ext $ H2 c m }
variables {ρ₁₂ σ₁₂}
@[simp] theorem mk₂'ₛₗ_apply
(f : M → N → P) {H1 H2 H3 H4} (m : M) (n : N) :
(mk₂'ₛₗ ρ₁₂ σ₁₂ f H1 H2 H3 H4 : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) m n = f m n := rfl
variables (R S)
/-- Create a bilinear map from a function that is linear in each component.
See `mk₂` for the special case where both arguments come from modules over the same ring. -/
def mk₂' (f : M → N → Pₗ)
(H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n)
(H2 : ∀ (c:R) m n, f (c • m) n = c • f m n)
(H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂)
(H4 : ∀ (c:S) m n, f m (c • n) = c • f m n) : M →ₗ[R] N →ₗ[S] Pₗ :=
mk₂'ₛₗ (ring_hom.id R) (ring_hom.id S) f H1 H2 H3 H4
variables {R S}
@[simp] theorem mk₂'_apply
(f : M → N → Pₗ) {H1 H2 H3 H4} (m : M) (n : N) :
(mk₂' R S f H1 H2 H3 H4 : M →ₗ[R] N →ₗ[S] Pₗ) m n = f m n := rfl
theorem ext₂ {f g : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P}
(H : ∀ m n, f m n = g m n) : f = g :=
linear_map.ext (λ m, linear_map.ext $ λ n, H m n)
lemma congr_fun₂ {f g : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P} (h : f = g) (x y) : f x y = g x y :=
linear_map.congr_fun (linear_map.congr_fun h x) y
section
local attribute [instance] smul_comm_class.symm
/-- Given a linear map from `M` to linear maps from `N` to `P`, i.e., a bilinear map from `M × N` to
`P`, change the order of variables and get a linear map from `N` to linear maps from `M` to `P`. -/
def flip (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) : N →ₛₗ[σ₁₂] M →ₛₗ[ρ₁₂] P :=
mk₂'ₛₗ σ₁₂ ρ₁₂ (λ n m, f m n)
(λ n₁ n₂ m, (f m).map_add _ _)
(λ c n m, (f m).map_smulₛₗ _ _)
(λ n m₁ m₂, by rw f.map_add; refl)
(λ c n m, by rw f.map_smulₛₗ; refl)
end
@[simp] theorem flip_apply (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (m : M) (n : N) : flip f n m = f m n := rfl
@[simp] lemma flip_flip [smul_comm_class R₂ S₂ P] (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) :
f.flip.flip = f := linear_map.ext₂ (λ x y, ((f.flip).flip_apply _ _).trans (f.flip_apply _ _))
open_locale big_operators
variables {R}
theorem flip_inj {f g : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P} (H : flip f = flip g) : f = g :=
ext₂ $ λ m n, show flip f n m = flip g n m, by rw H
theorem map_zero₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (y) : f 0 y = 0 :=
(flip f y).map_zero
theorem map_neg₂ (f : M' →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P') (x y) : f (-x) y = -f x y :=
(flip f y).map_neg _
theorem map_sub₂ (f : M' →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P') (x y z) : f (x - y) z = f x z - f y z :=
(flip f z).map_sub _ _
theorem map_add₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (x₁ x₂ y) : f (x₁ + x₂) y = f x₁ y + f x₂ y :=
(flip f y).map_add _ _
theorem map_smul₂ (f : M₂ →ₗ[R] N₂ →ₛₗ[σ₁₂] P₂) (r : R) (x y) : f (r • x) y = r • f x y :=
(flip f y).map_smul _ _
theorem map_smulₛₗ₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (r : R) (x y) : f (r • x) y = (ρ₁₂ r) • f x y :=
(flip f y).map_smulₛₗ _ _
theorem map_sum₂ {ι : Type*} (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (t : finset ι) (x : ι → M) (y) :
f (∑ i in t, x i) y = ∑ i in t, f (x i) y :=
(flip f y).map_sum
/-- Restricting a bilinear map in the second entry -/
def dom_restrict₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (q : submodule S N) :
M →ₛₗ[ρ₁₂] q →ₛₗ[σ₁₂] P :=
{ to_fun := λ m, (f m).dom_restrict q,
map_add' := λ m₁ m₂, linear_map.ext $ λ _, by simp only [map_add, dom_restrict_apply, add_apply],
map_smul' := λ c m, linear_map.ext $ λ _, by simp only [map_smulₛₗ, dom_restrict_apply,
smul_apply]}
lemma dom_restrict₂_apply (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (q : submodule S N) (x : M) (y : q) :
f.dom_restrict₂ q x y = f x y := rfl
/-- Restricting a bilinear map in both components -/
def dom_restrict₁₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (p : submodule R M) (q : submodule S N) :
p →ₛₗ[ρ₁₂] q →ₛₗ[σ₁₂] P := (f.dom_restrict p).dom_restrict₂ q
lemma dom_restrict₁₂_apply (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (p : submodule R M) (q : submodule S N)
(x : p) (y : q) : f.dom_restrict₁₂ p q x y = f x y := rfl
end semiring
section comm_semiring
variables {R : Type*} [comm_semiring R] {R₂ : Type*} [comm_semiring R₂]
variables {R₃ : Type*} [comm_semiring R₃] {R₄ : Type*} [comm_semiring R₄]
variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*}
variables {Mₗ : Type*} {Nₗ : Type*} {Pₗ : Type*} {Qₗ Qₗ': Type*}
variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q]
variables [add_comm_monoid Mₗ] [add_comm_monoid Nₗ] [add_comm_monoid Pₗ]
variables [add_comm_monoid Qₗ] [add_comm_monoid Qₗ']
variables [module R M] [module R₂ N] [module R₃ P] [module R₄ Q]
variables [module R Mₗ] [module R Nₗ] [module R Pₗ] [module R Qₗ] [module R Qₗ']
variables {σ₁₂ : R →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R →+* R₃}
variables {σ₄₂ : R₄ →+* R₂} {σ₄₃ : R₄ →+* R₃}
variables [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] [ring_hom_comp_triple σ₄₂ σ₂₃ σ₄₃]
variables (R)
/-- Create a bilinear map from a function that is linear in each component.
This is a shorthand for `mk₂'` for the common case when `R = S`. -/
def mk₂ (f : M → Nₗ → Pₗ)
(H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n)
(H2 : ∀ (c:R) m n, f (c • m) n = c • f m n)
(H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂)
(H4 : ∀ (c:R) m n, f m (c • n) = c • f m n) : M →ₗ[R] Nₗ →ₗ[R] Pₗ :=
mk₂' R R f H1 H2 H3 H4
@[simp] theorem mk₂_apply
(f : M → Nₗ → Pₗ) {H1 H2 H3 H4} (m : M) (n : Nₗ) :
(mk₂ R f H1 H2 H3 H4 : M →ₗ[R] Nₗ →ₗ[R] Pₗ) m n = f m n := rfl
variables (R M N P)
/-- Given a linear map from `M` to linear maps from `N` to `P`, i.e., a bilinear map `M → N → P`,
change the order of variables and get a linear map from `N` to linear maps from `M` to `P`. -/
def lflip : (M →ₛₗ[σ₁₃] N →ₛₗ[σ₂₃] P) →ₗ[R₃] N →ₛₗ[σ₂₃] M →ₛₗ[σ₁₃] P :=
{ to_fun := flip, map_add' := λ _ _, rfl, map_smul' := λ _ _, rfl }
variables {R M N P}
variables (f : M →ₛₗ[σ₁₃] N →ₛₗ[σ₂₃] P)
@[simp] theorem lflip_apply (m : M) (n : N) : lflip R M N P f n m = f m n := rfl
variables (R Pₗ)
/-- Composing a linear map `M → N` and a linear map `N → P` to form a linear map `M → P`. -/
def lcomp (f : M →ₗ[R] Nₗ) : (Nₗ →ₗ[R] Pₗ) →ₗ[R] M →ₗ[R] Pₗ :=
flip $ linear_map.comp (flip id) f
variables {R Pₗ}
@[simp] theorem lcomp_apply (f : M →ₗ[R] Nₗ) (g : Nₗ →ₗ[R] Pₗ) (x : M) :
lcomp R Pₗ f g x = g (f x) := rfl
theorem lcomp_apply' (f : M →ₗ[R] Nₗ) (g : Nₗ →ₗ[R] Pₗ) :
lcomp R Pₗ f g = g ∘ₗ f := rfl
variables (P σ₂₃)
/-- Composing a semilinear map `M → N` and a semilinear map `N → P` to form a semilinear map
`M → P` is itself a linear map. -/
def lcompₛₗ (f : M →ₛₗ[σ₁₂] N) : (N →ₛₗ[σ₂₃] P) →ₗ[R₃] M →ₛₗ[σ₁₃] P :=
flip $ linear_map.comp (flip id) f
variables {P σ₂₃}
include σ₁₃
@[simp] theorem lcompₛₗ_apply (f : M →ₛₗ[σ₁₂] N) (g : N →ₛₗ[σ₂₃] P) (x : M) :
lcompₛₗ P σ₂₃ f g x = g (f x) := rfl
omit σ₁₃
variables (R M Nₗ Pₗ)
/-- Composing a linear map `M → N` and a linear map `N → P` to form a linear map `M → P`. -/
def llcomp : (Nₗ →ₗ[R] Pₗ) →ₗ[R] (M →ₗ[R] Nₗ) →ₗ[R] M →ₗ[R] Pₗ :=
flip { to_fun := lcomp R Pₗ,
map_add' := λ f f', ext₂ $ λ g x, g.map_add _ _,
map_smul' := λ (c : R) f, ext₂ $ λ g x, g.map_smul _ _ }
variables {R M Nₗ Pₗ}
section
@[simp] theorem llcomp_apply (f : Nₗ →ₗ[R] Pₗ) (g : M →ₗ[R] Nₗ) (x : M) :
llcomp R M Nₗ Pₗ f g x = f (g x) := rfl
theorem llcomp_apply' (f : Nₗ →ₗ[R] Pₗ) (g : M →ₗ[R] Nₗ) :
llcomp R M Nₗ Pₗ f g = f ∘ₗ g := rfl
end
/-- Composing a linear map `Q → N` and a bilinear map `M → N → P` to
form a bilinear map `M → Q → P`. -/
def compl₂ (g : Q →ₛₗ[σ₄₂] N) : M →ₛₗ[σ₁₃] Q →ₛₗ[σ₄₃] P := (lcompₛₗ _ _ g).comp f
include σ₄₃
@[simp] theorem compl₂_apply (g : Q →ₛₗ[σ₄₂] N) (m : M) (q : Q) :
f.compl₂ g m q = f m (g q) := rfl
omit σ₄₃
/-- Composing linear maps `Q → M` and `Q' → N` with a bilinear map `M → N → P` to
form a bilinear map `Q → Q' → P`. -/
def compl₁₂ (f : Mₗ →ₗ[R] Nₗ →ₗ[R] Pₗ) (g : Qₗ →ₗ[R] Mₗ) (g' : Qₗ' →ₗ[R] Nₗ) :
Qₗ →ₗ[R] Qₗ' →ₗ[R] Pₗ :=
(f.comp g).compl₂ g'
@[simp] theorem compl₁₂_apply (f : Mₗ →ₗ[R] Nₗ →ₗ[R] Pₗ) (g : Qₗ →ₗ[R] Mₗ) (g' : Qₗ' →ₗ[R] Nₗ)
(x : Qₗ) (y : Qₗ') : f.compl₁₂ g g' x y = f (g x) (g' y) := rfl
lemma compl₁₂_inj {f₁ f₂ : Mₗ →ₗ[R] Nₗ →ₗ[R] Pₗ} {g : Qₗ →ₗ[R] Mₗ} {g' : Qₗ' →ₗ[R] Nₗ}
(hₗ : function.surjective g) (hᵣ : function.surjective g') :
f₁.compl₁₂ g g' = f₂.compl₁₂ g g' ↔ f₁ = f₂ :=
begin
split; intros h,
{ -- B₁.comp l r = B₂.comp l r → B₁ = B₂
ext x y,
cases hₗ x with x' hx, subst hx,
cases hᵣ y with y' hy, subst hy,
convert linear_map.congr_fun₂ h x' y' },
{ -- B₁ = B₂ → B₁.comp l r = B₂.comp l r
subst h },
end
/-- Composing a linear map `P → Q` and a bilinear map `M → N → P` to
form a bilinear map `M → N → Q`. -/
def compr₂ (f : M →ₗ[R] Nₗ →ₗ[R] Pₗ) (g : Pₗ →ₗ[R] Qₗ) : M →ₗ[R] Nₗ →ₗ[R] Qₗ :=
(llcomp R Nₗ Pₗ Qₗ g) ∘ₗ f
@[simp] theorem compr₂_apply (f : M →ₗ[R] Nₗ →ₗ[R] Pₗ) (g : Pₗ →ₗ[R] Qₗ) (m : M) (n : Nₗ) :
f.compr₂ g m n = g (f m n) := rfl
variables (R M)
/-- Scalar multiplication as a bilinear map `R → M → M`. -/
def lsmul : R →ₗ[R] M →ₗ[R] M :=
mk₂ R (•) add_smul (λ _ _ _, mul_smul _ _ _) smul_add
(λ r s m, by simp only [smul_smul, smul_eq_mul, mul_comm])
variables {R M}
@[simp] theorem lsmul_apply (r : R) (m : M) : lsmul R M r m = r • m := rfl
end comm_semiring
section comm_ring
variables {R R₂ S S₂ M N P : Type*}
variables [comm_ring R] [comm_ring S] [comm_ring R₂] [comm_ring S₂]
variables [add_comm_group M] [add_comm_group N] [add_comm_group P]
variables [module R M] [module S N] [module R₂ P] [module S₂ P]
variables [smul_comm_class S₂ R₂ P]
variables {ρ₁₂ : R →+* R₂} {σ₁₂ : S →+* S₂}
variables (b₁ : basis ι₁ R M) (b₂ : basis ι₂ S N)
lemma lsmul_injective [no_zero_smul_divisors R M] {x : R} (hx : x ≠ 0) :
function.injective (lsmul R M x) :=
smul_right_injective _ hx
lemma ker_lsmul [no_zero_smul_divisors R M] {a : R} (ha : a ≠ 0) :
(linear_map.lsmul R M a).ker = ⊥ :=
linear_map.ker_eq_bot_of_injective (linear_map.lsmul_injective ha)
/-- Two bilinear maps are equal when they are equal on all basis vectors. -/
lemma ext_basis {B B' : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P}
(h : ∀ i j, B (b₁ i) (b₂ j) = B' (b₁ i) (b₂ j)) : B = B' :=
b₁.ext $ λ i, b₂.ext $ λ j, h i j
/-- Write out `B x y` as a sum over `B (b i) (b j)` if `b` is a basis. -/
lemma sum_repr_mul_repr_mul {B : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P} (x y) :
(b₁.repr x).sum (λ i xi, (b₂.repr y).sum (λ j yj, (ρ₁₂ xi) • (σ₁₂ yj) • B (b₁ i) (b₂ j))) =
B x y :=
begin
conv_rhs { rw [← b₁.total_repr x, ← b₂.total_repr y] },
simp_rw [finsupp.total_apply, finsupp.sum, map_sum₂, map_sum, map_smulₛₗ₂, map_smulₛₗ],
end
end comm_ring
end linear_map
|
3f8507372d67c893eb2ba9cec1c65200d999b4d7 | c45b34bfd44d8607a2e8762c926e3cfaa7436201 | /uexp/src/uexp/u_semiring.lean | fbf75eb2b882c22466b3d7ef6ee2357c34a8ce64 | [
"BSD-2-Clause"
] | permissive | Shamrock-Frost/Cosette | b477c442c07e45082348a145f19ebb35a7f29392 | 24cbc4adebf627f13f5eac878f04ffa20d1209af | refs/heads/master | 1,619,721,304,969 | 1,526,082,841,000 | 1,526,082,841,000 | 121,695,605 | 1 | 0 | null | 1,518,737,210,000 | 1,518,737,210,000 | null | UTF-8 | Lean | false | false | 6,743 | lean | -- definition of u-semiring
class denotation (A: Type) (B:Type) :=
(denote : A → B)
--def denote {A B: Type} [denotation A B] : A → B := @denotation.denote
constant datatype: Type
inductive tree (A:Type)
| node : tree → tree → tree
| leaf : A → tree
| empty {} : tree
definition Schema := tree datatype
constant denote : datatype → Type
def Tuple : Schema → Type
| (tree.node t0 t1) := (Tuple t0) × (Tuple t1)
| (tree.leaf A) := denote A
| tree.empty := unit
constant usr : Type
constant usr.one : usr
constant usr.zero : usr
constant usr.plus : usr → usr → usr
constant usr.time : usr → usr → usr
constant usr.sig {s: Schema}: (Tuple s → usr) → usr
constant usr.squash : usr → usr
constant usr.not : usr → usr
constant usr.ueq {s : Schema} : Tuple s → Tuple s → usr
notation `∑` binders `, ` r:(scoped p, usr.sig p) := r
notation `∥` u `∥` := usr.squash u
noncomputable instance : has_append Schema := ⟨tree.node⟩
infix `≃`:50 := usr.ueq
noncomputable instance usr_has_add : has_add usr := ⟨usr.plus⟩
noncomputable instance usr_has_mul : has_mul usr := ⟨usr.time⟩
noncomputable instance usr_has_zero : has_zero usr := ⟨usr.zero⟩
noncomputable instance usr_has_one : has_one usr := ⟨usr.one⟩
-- commutative semiring axioms
@[simp] axiom plus_comm (a b : usr) : a + b = b + a
@[simp] axiom plus_zero (a : usr) : a + 0 = a
@[simp] axiom plus_assoc (a b c : usr) : a + b + c = a + (b + c)
@[simp] axiom time_comm (a b : usr) : a * b = b * a
@[simp] axiom time_assoc (a b c : usr) : a * b * c = a * (b * c)
@[simp] axiom time_distrib_l (a b c : usr) : a * (b + c) = a * b + a * c
@[simp] axiom time_distrib_r (a b c : usr) : (a + b) * c = a * c + b * c
@[simp] axiom time_zero (a : usr): a * 0 = 0
@[simp] axiom time_one (a : usr): a * 1 = a
noncomputable instance : comm_semiring usr := {
add_assoc := plus_assoc,
add_zero := plus_zero,
zero_add := by intros; rw plus_comm; simp,
add_comm := plus_comm,
mul_assoc := time_assoc,
mul_one := time_one,
one_mul := by intros; rw time_comm; simp,
left_distrib := time_distrib_l,
right_distrib := time_distrib_r,
mul_zero := time_zero,
zero_mul := by intros; rw time_comm; simp,
mul_comm := time_comm,
..usr_has_add,
..usr_has_mul,
..usr_has_zero,
..usr_has_one
}
@[simp] axiom sig_distr_plus {s : Schema} (f₁ f₂ : Tuple s → usr) :
(∑ t, f₁ t + f₂ t) = (∑ t, f₁ t) + (∑ t, f₂ t)
-- adding the sig_commute to the set of simplification lemma
-- will make it run forever
axiom sig_commute {s t: Schema} (f: Tuple s → Tuple t → usr):
(∑ t₁ t₂, f t₁ t₂) = (∑ t₂ t₁, f t₁ t₂)
@[simp] axiom sig_distr_time {s : Schema} (a: usr) (f: Tuple s → usr):
a * (∑ t, f t) = (∑ t, a * (f t))
@[simp] axiom sig_pair_split {s₁ s₂: Schema} (f: Tuple (s₁ ++ s₂) → usr):
(∑ t, (f t)) = (∑ t₁ t₂, (f (t₁, t₂)))
@[simp] axiom squash_zero : usr.squash 0 = 0
@[simp] axiom squash_one : usr.squash 1 = 1
@[simp] axiom squash_add_squash (x y : usr) : ∥ ∥ x ∥ + y ∥ = ∥ x + y ∥
@[simp] axiom squash_time (x y : usr) : ∥ x ∥ * ∥ y ∥ = ∥ x * y ∥
@[simp] axiom squash_squared (x : usr) : ∥ x ∥ * ∥ x ∥ = ∥ x ∥
@[simp] axiom squash_eq_if_square_eq (x : usr) : x * x = x → ∥ x ∥ = x
@[simp] lemma squash_idempotent (x: usr): ∥ ∥ x ∥ ∥ = ∥ x ∥ :=
begin
rewrite <- (@plus_zero (∥ x ∥)),
rewrite squash_add_squash,
rewrite plus_zero,
rewrite plus_zero,
end
@[simp] lemma squash_time_squash (x y: usr): ∥ ∥ x ∥ * y ∥ = ∥ x * y ∥ :=
begin
rewrite <- squash_time,
rewrite squash_idempotent,
rewrite squash_time,
end
@[simp] axiom not_zero : usr.not 0 = 1
@[simp] axiom not_time (x y : usr) : usr.not (x * y) = ∥ usr.not x + usr.not y ∥
@[simp] axiom not_plus (x y : usr) : usr.not (x + y) = usr.not x * usr.not y
@[simp] axiom not_squash (x : usr) : usr.not ∥ x ∥ = ∥ usr.not x ∥
@[simp] axiom squash_not (x : usr) : ∥ usr.not x ∥ = usr.not x
-- axioms about predicates
@[simp] axiom eq_unit {s: Schema} (t₁: Tuple s): (t₁ ≃ t₁) = 1
@[simp] axiom eq_subst_l {s: Schema} (t₁ t₂: Tuple s) (R: Tuple s → usr): (t₁ ≃ t₂) * (R t₁) = (t₁ ≃ t₂) * (R t₂)
@[simp] axiom eq_subst_r {s: Schema} (t₁ t₂: Tuple s) (R: Tuple s → usr):
(R t₁) * (t₁ ≃ t₂) = (R t₂) * (t₁ ≃ t₂)
@[simp] axiom em {s: Schema} (t₁ t₂ : Tuple s) : (t₁ ≃ t₂) + usr.not (t₁ ≃ t₂) = 1
@[simp] axiom eq_unique {s: Schema} (t' : Tuple s) : (∑ t, t ≃ t') = 1
@[simp] axiom eq_symm {s: Schema} (t₁ t₂ : Tuple s):
(t₁ ≃ t₂) = (t₂ ≃ t₁)
axiom eq_pair {s₁ s₂: Schema} (t₁: Tuple s₁) (t₂: Tuple s₂) (t: Tuple (s₁ ++ s₂)):
(t ≃ (t₁, t₂)) = (t.1 ≃ t₁ ) * (t.2 ≃ t₂)
axiom eq_trans {s: Schema} (t₁ t₂ t₃ : Tuple s):
(t₁ ≃ t₂) * (t₂ ≃ t₃) = (t₁ ≃ t₂) * (t₂ ≃ t₃) * (t₁ ≃ t₃)
-- TODO: the following could be a lemma
@[simp] axiom eq_cancel {s: Schema} (t₁ t₂ : Tuple s):
(t₁ ≃ t₂) * (t₁ ≃ t₂) = (t₁ ≃ t₂)
-- lemmas
lemma sig_eq_subst_r {s: Schema} (t': Tuple s) (R: Tuple s → usr): (∑ t, (t ≃ t') * (R t)) = R t' :=
begin
have hq: (∑ t, ((t ≃ t') * (R t))) = (∑ t, (t ≃ t') * R t'),
{ congr, funext, apply eq_subst_l },
rw hq,
have hq1: (∑ t, (t ≃ t') * R t') = (∑ t, R t' * (t ≃ t')),
{ congr, funext, rw time_comm},
rw hq1,
rw ← sig_distr_time,
rw eq_unique,
rw time_one,
end
lemma sig_eq_subst_l {s: Schema} (t': Tuple s) (R: Tuple s → usr): (∑ t, (t' ≃ t) * (R t)) = R t' :=
begin
have hq: (∑ t, ((t' ≃ t) * (R t))) = (∑ t, (t ≃ t') * R t),
{ congr, funext, rw eq_symm, },
rw hq,
apply sig_eq_subst_r,
end
attribute [irreducible]
def pair {s1 s2: Schema} (t1 : Tuple s1) (t2:Tuple s2) : Tuple (s1 ++ s2) := (t1, t2)
lemma eq_pair' {s₁ s₂: Schema} (t₁: Tuple s₁) (t₂: Tuple s₂)
(t: Tuple (s₁ ++ s₂)) :
((pair t₁ t₂) ≃ t) = (t₁ ≃ t.1) * (t₂ ≃ t.2) :=
begin
unfold pair,
rw eq_symm,
rw (@eq_symm _ t₁),
rw (@eq_symm _ t₂),
apply eq_pair,
end
lemma eq_pair1 {s₁ s₂: Schema} (t₁: Tuple s₁) (t₂: Tuple s₂)
(t: Tuple (s₁ ++ s₂)) :
(t ≃ (pair t₁ t₂)) = (t.1 ≃ t₁) * (t.2 ≃ t₂) :=
begin
unfold pair,
apply eq_pair,
end
@[simp] lemma sig_distr_time_r {s : Schema} (a: usr) (f: Tuple s → usr):
(∑ t, f t) * a = (∑ t, (f t) * a) :=
begin
rw time_comm,
rw sig_distr_time,
apply congr_arg,
funext,
apply time_comm,
end
|
bf015d47815c4df177abbddbbd0e1fa75ed68d4f | 86f6f4f8d827a196a32bfc646234b73328aeb306 | /examples/logic/unnamed_1056.lean | 076e47ca46040ef837265a2f8dbcb08d97ca5c85 | [] | 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 | 181 | lean | import data.real.basic
variables a b : ℝ
-- BEGIN
example (h : a < b) : ¬ b < a :=
begin
intro h',
have : a < a,
from lt_trans h h',
apply lt_irrefl a this
end
-- END |
b769266629a914bbed9155f8a077b0706a3caa76 | c3f2fcd060adfa2ca29f924839d2d925e8f2c685 | /hott/init/hedberg.hlean | f22be3193e30c0040aed1b7d598f21af3a656b2e | [
"Apache-2.0"
] | permissive | respu/lean | 6582d19a2f2838a28ecd2b3c6f81c32d07b5341d | 8c76419c60b63d0d9f7bc04ebb0b99812d0ec654 | refs/heads/master | 1,610,882,451,231 | 1,427,747,084,000 | 1,427,747,429,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,498 | hlean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
Hedberg's Theorem: every type with decidable equality is a hset
-/
prelude
import init.trunc
open eq eq.ops nat is_trunc sigma
-- TODO(Leo): move const coll and path_coll to a different file?
private definition const {A B : Type} (f : A → B) := ∀ x y, f x = f y
private definition coll (A : Type) := Σ f : A → A, const f
private definition path_coll (A : Type) := ∀ x y : A, coll (x = y)
context
parameter {A : Type}
hypothesis [h : decidable_eq A]
variables {x y : A}
private definition pc [reducible] : path_coll A :=
λ a b, decidable.rec_on (h a b)
(λ p : a = b, ⟨(λ q, p), λ q r, rfl⟩)
(λ np : ¬ a = b, ⟨(λ q, q), λ q r, absurd q np⟩)
private definition f [reducible] : x = y → x = y :=
sigma.rec_on (pc x y) (λ f c, f)
private definition f_const (p q : x = y) : f p = f q :=
sigma.rec_on (pc x y) (λ f c, c p q)
private definition aux (p : x = y) : p = (f (refl x))⁻¹ ⬝ (f p) :=
have aux : refl x = (f (refl x))⁻¹ ⬝ (f (refl x)), from
eq.rec_on (f (refl x)) rfl,
eq.rec_on p aux
definition is_hset_of_decidable_eq : is_hset A :=
is_hset.mk A (λ x y p q, calc
p = (f (refl x))⁻¹ ⬝ (f p) : aux
... = (f (refl x))⁻¹ ⬝ (f q) : f_const
... = q : aux)
end
attribute is_hset_of_decidable_eq [instance]
|
4b63d904a8f9647efdb2b655e350315aa223cbe9 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/linear_algebra/pi.lean | d7126156e85c67c90d5aa22f8c984b5d0c843095 | [
"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 | 19,030 | 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, Eric Wieser
-/
import linear_algebra.basic
import logic.equiv.fin
/-!
# Pi types of modules
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines constructors for linear maps whose domains or codomains are pi types.
It contains theorems relating these to each other, as well as to `linear_map.ker`.
## Main definitions
- pi types in the codomain:
- `linear_map.pi`
- `linear_map.single`
- pi types in the domain:
- `linear_map.proj`
- `linear_map.diag`
-/
universes u v w x y z u' v' w' x' y'
variables {R : Type u} {K : Type u'} {M : Type v} {V : Type v'} {M₂ : Type w} {V₂ : Type w'}
variables {M₃ : Type y} {V₃ : Type y'} {M₄ : Type z} {ι : Type x} {ι' : Type x'}
open function submodule
open_locale big_operators
namespace linear_map
universe i
variables [semiring R] [add_comm_monoid M₂] [module R M₂] [add_comm_monoid M₃] [module R M₃]
{φ : ι → Type i} [∀i, add_comm_monoid (φ i)] [∀i, module R (φ i)]
/-- `pi` construction for linear functions. From a family of linear functions it produces a linear
function into a family of modules. -/
def pi (f : Π i, M₂ →ₗ[R] φ i) : M₂ →ₗ[R] (Π i, φ i) :=
{ to_fun := λ c i, f i c,
map_smul' := λ c d, funext $ λ i, (f i).map_smul _ _,
.. pi.add_hom (λ i, (f i).to_add_hom) }
@[simp] lemma pi_apply (f : Πi, M₂ →ₗ[R] φ i) (c : M₂) (i : ι) :
pi f c i = f i c := rfl
lemma ker_pi (f : Πi, M₂ →ₗ[R] φ i) : ker (pi f) = (⨅i:ι, ker (f i)) :=
by ext c; simp [funext_iff]; refl
lemma pi_eq_zero (f : Πi, M₂ →ₗ[R] φ i) : pi f = 0 ↔ (∀i, f i = 0) :=
by simp only [linear_map.ext_iff, pi_apply, funext_iff]; exact ⟨λh a b, h b a, λh a b, h b a⟩
lemma pi_zero : pi (λi, 0 : Πi, M₂ →ₗ[R] φ i) = 0 :=
by ext; refl
lemma pi_comp (f : Πi, M₂ →ₗ[R] φ i) (g : M₃ →ₗ[R] M₂) : (pi f).comp g = pi (λi, (f i).comp g) :=
rfl
/-- The projections from a family of modules are linear maps.
Note: known here as `linear_map.proj`, this construction is in other categories called `eval`, for
example `pi.eval_monoid_hom`, `pi.eval_ring_hom`. -/
def proj (i : ι) : (Πi, φ i) →ₗ[R] φ i :=
{ to_fun := function.eval i, map_add' := λ f g, rfl, map_smul' := λ c f, rfl }
@[simp] lemma coe_proj (i : ι) : ⇑(proj i : (Πi, φ i) →ₗ[R] φ i) = function.eval i := rfl
lemma proj_apply (i : ι) (b : Πi, φ i) : (proj i : (Πi, φ i) →ₗ[R] φ i) b = b i := rfl
lemma proj_pi (f : Πi, M₂ →ₗ[R] φ i) (i : ι) : (proj i).comp (pi f) = f i :=
ext $ assume c, rfl
lemma infi_ker_proj : (⨅i, ker (proj i : (Πi, φ i) →ₗ[R] φ i) : submodule R (Πi, φ i)) = ⊥ :=
bot_unique $ set_like.le_def.2 $ assume a h,
begin
simp only [mem_infi, mem_ker, proj_apply] at h,
exact (mem_bot _).2 (funext $ assume i, h i)
end
/-- Linear map between the function spaces `I → M₂` and `I → M₃`, induced by a linear map `f`
between `M₂` and `M₃`. -/
@[simps] protected def comp_left (f : M₂ →ₗ[R] M₃) (I : Type*) : (I → M₂) →ₗ[R] (I → M₃) :=
{ to_fun := λ h, f ∘ h,
map_smul' := λ c h, by { ext x, exact f.map_smul' c (h x) },
.. f.to_add_monoid_hom.comp_left I }
lemma apply_single [add_comm_monoid M] [module R M] [decidable_eq ι]
(f : Π i, φ i →ₗ[R] M) (i j : ι) (x : φ i) :
f j (pi.single i x j) = pi.single i (f i x) j :=
pi.apply_single (λ i, f i) (λ i, (f i).map_zero) _ _ _
/-- The `linear_map` version of `add_monoid_hom.single` and `pi.single`. -/
def single [decidable_eq ι] (i : ι) : φ i →ₗ[R] (Πi, φ i) :=
{ to_fun := pi.single i,
map_smul' := pi.single_smul i,
.. add_monoid_hom.single φ i}
@[simp] lemma coe_single [decidable_eq ι] (i : ι) :
⇑(single i : φ i →ₗ[R] (Π i, φ i)) = pi.single i := rfl
variables (R φ)
/-- The linear equivalence between linear functions on a finite product of modules and
families of functions on these modules. See note [bundled maps over different rings]. -/
@[simps] def lsum (S) [add_comm_monoid M] [module R M] [fintype ι] [decidable_eq ι]
[semiring S] [module S M] [smul_comm_class R S M] :
(Π i, φ i →ₗ[R] M) ≃ₗ[S] ((Π i, φ i) →ₗ[R] M) :=
{ to_fun := λ f, ∑ i : ι, (f i).comp (proj i),
inv_fun := λ f i, f.comp (single i),
map_add' := λ f g, by simp only [pi.add_apply, add_comp, finset.sum_add_distrib],
map_smul' := λ c f, by simp only [pi.smul_apply, smul_comp, finset.smul_sum, ring_hom.id_apply],
left_inv := λ f, by { ext i x, simp [apply_single] },
right_inv := λ f,
begin
ext,
suffices : f (∑ j, pi.single j (x j)) = f x, by simpa [apply_single],
rw finset.univ_sum_single
end }
@[simp] lemma lsum_single {ι R : Type*} [fintype ι] [decidable_eq ι] [comm_ring R]
{M : ι → Type*} [∀ i, add_comm_group (M i)] [∀ i, module R (M i)] :
linear_map.lsum R M R linear_map.single = linear_map.id :=
linear_map.ext (λ x, by simp [finset.univ_sum_single])
variables {R φ}
section ext
variables [finite ι] [decidable_eq ι] [add_comm_monoid M] [module R M]
{f g : (Π i, φ i) →ₗ[R] M}
lemma pi_ext (h : ∀ i x, f (pi.single i x) = g (pi.single i x)) :
f = g :=
to_add_monoid_hom_injective $ add_monoid_hom.functions_ext _ _ _ h
lemma pi_ext_iff : f = g ↔ ∀ i x, f (pi.single i x) = g (pi.single i x) :=
⟨λ h i x, h ▸ rfl, pi_ext⟩
/-- This is used as the ext lemma instead of `linear_map.pi_ext` for reasons explained in
note [partially-applied ext lemmas]. -/
@[ext] lemma pi_ext' (h : ∀ i, f.comp (single i) = g.comp (single i)) : f = g :=
begin
refine pi_ext (λ i x, _),
convert linear_map.congr_fun (h i) x
end
lemma pi_ext'_iff : f = g ↔ ∀ i, f.comp (single i) = g.comp (single i) :=
⟨λ h i, h ▸ rfl, pi_ext'⟩
end ext
section
variables (R φ)
/-- If `I` and `J` are disjoint index sets, the product of the kernels of the `J`th projections of
`φ` is linearly equivalent to the product over `I`. -/
def infi_ker_proj_equiv {I J : set ι} [decidable_pred (λi, i ∈ I)]
(hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) :
(⨅i ∈ J, ker (proj i : (Πi, φ i) →ₗ[R] φ i) : submodule R (Πi, φ i)) ≃ₗ[R] (Πi:I, φ i) :=
begin
refine linear_equiv.of_linear
(pi $ λi, (proj (i:ι)).comp (submodule.subtype _))
(cod_restrict _ (pi $ λi, if h : i ∈ I then proj (⟨i, h⟩ : I) else 0) _) _ _,
{ assume b,
simp only [mem_infi, mem_ker, funext_iff, proj_apply, pi_apply],
assume j hjJ,
have : j ∉ I := assume hjI, hd.le_bot ⟨hjI, hjJ⟩,
rw [dif_neg this, zero_apply] },
{ simp only [pi_comp, comp_assoc, subtype_comp_cod_restrict, proj_pi, subtype.coe_prop],
ext b ⟨j, hj⟩,
simp only [dif_pos, function.comp_app, function.eval_apply, linear_map.cod_restrict_apply,
linear_map.coe_comp, linear_map.coe_proj, linear_map.pi_apply, submodule.subtype_apply,
subtype.coe_prop], refl },
{ ext1 ⟨b, hb⟩,
apply subtype.ext,
ext j,
have hb : ∀i ∈ J, b i = 0,
{ simpa only [mem_infi, mem_ker, proj_apply] using (mem_infi _).1 hb },
simp only [comp_apply, pi_apply, id_apply, proj_apply, subtype_apply, cod_restrict_apply],
split_ifs,
{ refl },
{ exact (hb _ $ (hu trivial).resolve_left h).symm } }
end
end
section
variable [decidable_eq ι]
/-- `diag i j` is the identity map if `i = j`. Otherwise it is the constant 0 map. -/
def diag (i j : ι) : φ i →ₗ[R] φ j :=
@function.update ι (λj, φ i →ₗ[R] φ j) _ 0 i id j
lemma update_apply (f : Πi, M₂ →ₗ[R] φ i) (c : M₂) (i j : ι) (b : M₂ →ₗ[R] φ i) :
(update f i b j) c = update (λi, f i c) i (b c) j :=
begin
by_cases j = i,
{ rw [h, update_same, update_same] },
{ rw [update_noteq h, update_noteq h] }
end
end
end linear_map
namespace submodule
variables [semiring R] {φ : ι → Type*} [∀ i, add_comm_monoid (φ i)] [∀ i, module R (φ i)]
open linear_map
/-- A version of `set.pi` for submodules. Given an index set `I` and a family of submodules
`p : Π i, submodule R (φ i)`, `pi I s` is the submodule of dependent functions `f : Π i, φ i`
such that `f i` belongs to `p a` whenever `i ∈ I`. -/
def pi (I : set ι) (p : Π i, submodule R (φ i)) : submodule R (Π i, φ i) :=
{ carrier := set.pi I (λ i, p i),
zero_mem' := λ i hi, (p i).zero_mem,
add_mem' := λ x y hx hy i hi, (p i).add_mem (hx i hi) (hy i hi),
smul_mem' := λ c x hx i hi, (p i).smul_mem c (hx i hi) }
variables {I : set ι} {p q : Π i, submodule R (φ i)} {x : Π i, φ i}
@[simp] lemma mem_pi : x ∈ pi I p ↔ ∀ i ∈ I, x i ∈ p i := iff.rfl
@[simp, norm_cast] lemma coe_pi : (pi I p : set (Π i, φ i)) = set.pi I (λ i, p i) := rfl
@[simp] lemma pi_empty (p : Π i, submodule R (φ i)) : pi ∅ p = ⊤ :=
set_like.coe_injective $ set.empty_pi _
@[simp] lemma pi_top (s : set ι) : pi s (λ i : ι, (⊤ : submodule R (φ i))) = ⊤ :=
set_like.coe_injective $ set.pi_univ _
lemma pi_mono {s : set ι} (h : ∀ i ∈ s, p i ≤ q i) : pi s p ≤ pi s q :=
set.pi_mono h
lemma binfi_comap_proj : (⨅ i ∈ I, comap (proj i : (Πi, φ i) →ₗ[R] φ i) (p i)) = pi I p :=
by { ext x, simp }
lemma infi_comap_proj : (⨅ i, comap (proj i : (Πi, φ i) →ₗ[R] φ i) (p i)) = pi set.univ p :=
by { ext x, simp }
lemma supr_map_single [decidable_eq ι] [finite ι] :
(⨆ i, map (linear_map.single i : φ i →ₗ[R] (Πi, φ i)) (p i)) = pi set.univ p :=
begin
casesI nonempty_fintype ι,
refine (supr_le $ λ i, _).antisymm _,
{ rintro _ ⟨x, hx : x ∈ p i, rfl⟩ j -,
rcases em (j = i) with rfl|hj; simp * },
{ intros x hx,
rw [← finset.univ_sum_single x],
exact sum_mem_supr (λ i, mem_map_of_mem (hx i trivial)) }
end
lemma le_comap_single_pi [decidable_eq ι] (p : Π i, submodule R (φ i)) {i} :
p i ≤ submodule.comap (linear_map.single i : φ i →ₗ[R] _) (submodule.pi set.univ p) :=
begin
intros x hx,
rw [submodule.mem_comap, submodule.mem_pi],
rintros j -,
by_cases h : j = i,
{ rwa [h, linear_map.coe_single, pi.single_eq_same] },
{ rw [linear_map.coe_single, pi.single_eq_of_ne h], exact (p j).zero_mem }
end
end submodule
namespace linear_equiv
variables [semiring R] {φ ψ χ : ι → Type*} [∀ i, add_comm_monoid (φ i)] [∀ i, module R (φ i)]
variables [∀ i, add_comm_monoid (ψ i)] [∀ i, module R (ψ i)]
variables [∀ i, add_comm_monoid (χ i)] [∀ i, module R (χ i)]
/-- Combine a family of linear equivalences into a linear equivalence of `pi`-types.
This is `equiv.Pi_congr_right` as a `linear_equiv` -/
@[simps apply] def Pi_congr_right (e : Π i, φ i ≃ₗ[R] ψ i) : (Π i, φ i) ≃ₗ[R] (Π i, ψ i) :=
{ to_fun := λ f i, e i (f i),
inv_fun := λ f i, (e i).symm (f i),
map_smul' := λ c f, by { ext, simp },
.. add_equiv.Pi_congr_right (λ j, (e j).to_add_equiv) }
@[simp]
lemma Pi_congr_right_refl : Pi_congr_right (λ j, refl R (φ j)) = refl _ _ := rfl
@[simp]
lemma Pi_congr_right_symm (e : Π i, φ i ≃ₗ[R] ψ i) :
(Pi_congr_right e).symm = (Pi_congr_right $ λ i, (e i).symm) := rfl
@[simp]
lemma Pi_congr_right_trans (e : Π i, φ i ≃ₗ[R] ψ i) (f : Π i, ψ i ≃ₗ[R] χ i) :
(Pi_congr_right e).trans (Pi_congr_right f) = (Pi_congr_right $ λ i, (e i).trans (f i)) :=
rfl
variables (R φ)
/-- Transport dependent functions through an equivalence of the base space.
This is `equiv.Pi_congr_left'` as a `linear_equiv`. -/
@[simps {simp_rhs := tt}]
def Pi_congr_left' (e : ι ≃ ι') : (Π i', φ i') ≃ₗ[R] (Π i, φ $ e.symm i) :=
{ map_add' := λ x y, rfl, map_smul' := λ x y, rfl, .. equiv.Pi_congr_left' φ e }
/-- Transporting dependent functions through an equivalence of the base,
expressed as a "simplification".
This is `equiv.Pi_congr_left` as a `linear_equiv` -/
def Pi_congr_left (e : ι' ≃ ι) : (Π i', φ (e i')) ≃ₗ[R] (Π i, φ i) :=
(Pi_congr_left' R φ e.symm).symm
/-- This is `equiv.pi_option_equiv_prod` as a `linear_equiv` -/
def pi_option_equiv_prod {ι : Type*} {M : option ι → Type*}
[Π i, add_comm_group (M i)] [Π i, module R (M i)] :
(Π i : option ι, M i) ≃ₗ[R] (M none × Π i : ι, M (some i)) :=
{ map_add' := by simp [function.funext_iff],
map_smul' := by simp [function.funext_iff],
..equiv.pi_option_equiv_prod }
variables (ι R M) (S : Type*) [fintype ι] [decidable_eq ι] [semiring S]
[add_comm_monoid M] [module R M] [module S M] [smul_comm_class R S M]
/-- Linear equivalence between linear functions `Rⁿ → M` and `Mⁿ`. The spaces `Rⁿ` and `Mⁿ`
are represented as `ι → R` and `ι → M`, respectively, where `ι` is a finite type.
This as an `S`-linear equivalence, under the assumption that `S` acts on `M` commuting with `R`.
When `R` is commutative, we can take this to be the usual action with `S = R`.
Otherwise, `S = ℕ` shows that the equivalence is additive.
See note [bundled maps over different rings]. -/
def pi_ring : ((ι → R) →ₗ[R] M) ≃ₗ[S] (ι → M) :=
(linear_map.lsum R (λ i : ι, R) S).symm.trans
(Pi_congr_right $ λ i, linear_map.ring_lmap_equiv_self R S M)
variables {ι R M}
@[simp] lemma pi_ring_apply (f : (ι → R) →ₗ[R] M) (i : ι) :
pi_ring R M ι S f i = f (pi.single i 1) :=
rfl
@[simp] lemma pi_ring_symm_apply (f : ι → M) (g : ι → R) :
(pi_ring R M ι S).symm f g = ∑ i, g i • f i :=
by simp [pi_ring, linear_map.lsum]
/--
`equiv.sum_arrow_equiv_prod_arrow` as a linear equivalence.
-/
-- TODO additive version?
def sum_arrow_lequiv_prod_arrow (α β R M : Type*) [semiring R] [add_comm_monoid M] [module R M] :
((α ⊕ β) → M) ≃ₗ[R] (α → M) × (β → M) :=
{ map_add' := by { intros f g, ext; refl },
map_smul' := by { intros r f, ext; refl, },
.. equiv.sum_arrow_equiv_prod_arrow α β M, }
@[simp] lemma sum_arrow_lequiv_prod_arrow_apply_fst {α β} (f : (α ⊕ β) → M) (a : α) :
(sum_arrow_lequiv_prod_arrow α β R M f).1 a = f (sum.inl a) := rfl
@[simp] lemma sum_arrow_lequiv_prod_arrow_apply_snd {α β} (f : (α ⊕ β) → M) (b : β) :
(sum_arrow_lequiv_prod_arrow α β R M f).2 b = f (sum.inr b) := rfl
@[simp] lemma sum_arrow_lequiv_prod_arrow_symm_apply_inl {α β} (f : α → M) (g : β → M) (a : α) :
((sum_arrow_lequiv_prod_arrow α β R M).symm (f, g)) (sum.inl a) = f a := rfl
@[simp] lemma sum_arrow_lequiv_prod_arrow_symm_apply_inr {α β} (f : α → M) (g : β → M) (b : β) :
((sum_arrow_lequiv_prod_arrow α β R M).symm (f, g)) (sum.inr b) = g b := rfl
/-- If `ι` has a unique element, then `ι → M` is linearly equivalent to `M`. -/
@[simps { simp_rhs := tt, fully_applied := ff }]
def fun_unique (ι R M : Type*) [unique ι] [semiring R] [add_comm_monoid M] [module R M] :
(ι → M) ≃ₗ[R] M :=
{ map_add' := λ f g, rfl,
map_smul' := λ c f, rfl,
.. equiv.fun_unique ι M }
variables (R M)
/-- Linear equivalence between dependent functions `Π i : fin 2, M i` and `M 0 × M 1`. -/
@[simps { simp_rhs := tt, fully_applied := ff }]
def pi_fin_two (M : fin 2 → Type v) [Π i, add_comm_monoid (M i)] [Π i, module R (M i)] :
(Π i, M i) ≃ₗ[R] M 0 × M 1 :=
{ map_add' := λ f g, rfl,
map_smul' := λ c f, rfl,
.. pi_fin_two_equiv M }
/-- Linear equivalence between vectors in `M² = fin 2 → M` and `M × M`. -/
@[simps { simp_rhs := tt, fully_applied := ff }]
def fin_two_arrow : (fin 2 → M) ≃ₗ[R] M × M :=
{ .. fin_two_arrow_equiv M, .. pi_fin_two R (λ _, M) }
end linear_equiv
section extend
variables (R) {η : Type x} [semiring R] (s : ι → η)
/-- `function.extend s f 0` as a bundled linear map. -/
@[simps]
noncomputable def function.extend_by_zero.linear_map : (ι → R) →ₗ[R] (η → R) :=
{ to_fun := λ f, function.extend s f 0,
map_smul' := λ r f, by { simpa using function.extend_smul r s f 0 },
..function.extend_by_zero.hom R s }
end extend
/-! ### Bundled versions of `matrix.vec_cons` and `matrix.vec_empty`
The idea of these definitions is to be able to define a map as `x ↦ ![f₁ x, f₂ x, f₃ x]`, where
`f₁ f₂ f₃` are already linear maps, as `f₁.vec_cons $ f₂.vec_cons $ f₃.vec_cons $ vec_empty`.
While the same thing could be achieved using `linear_map.pi ![f₁, f₂, f₃]`, this is not
definitionally equal to the result using `linear_map.vec_cons`, as `fin.cases` and function
application do not commute definitionally.
Versions for when `f₁ f₂ f₃` are bilinear maps are also provided.
-/
section fin
section semiring
variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃]
variables [module R M] [module R M₂] [module R M₃]
/-- The linear map defeq to `matrix.vec_empty` -/
def linear_map.vec_empty : M →ₗ[R] (fin 0 → M₃) :=
{ to_fun := λ m, matrix.vec_empty,
map_add' := λ x y, subsingleton.elim _ _,
map_smul' := λ r x, subsingleton.elim _ _ }
@[simp]
lemma linear_map.vec_empty_apply (m : M) :
(linear_map.vec_empty : M →ₗ[R] (fin 0 → M₃)) m = ![] := rfl
/-- A linear map into `fin n.succ → M₃` can be built out of a map into `M₃` and a map into
`fin n → M₃`. -/
def linear_map.vec_cons {n} (f : M →ₗ[R] M₂) (g : M →ₗ[R] (fin n → M₂)) :
M →ₗ[R] (fin n.succ → M₂) :=
{ to_fun := λ m, matrix.vec_cons (f m) (g m),
map_add' := λ x y, begin
rw [f.map_add, g.map_add, matrix.cons_add_cons (f x)]
end,
map_smul' := λ c x, by rw [f.map_smul, g.map_smul, ring_hom.id_apply, matrix.smul_cons c (f x)] }
@[simp]
lemma linear_map.vec_cons_apply {n} (f : M →ₗ[R] M₂) (g : M →ₗ[R] (fin n → M₂)) (m : M) :
f.vec_cons g m = matrix.vec_cons (f m) (g m) := rfl
end semiring
section comm_semiring
variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃]
variables [module R M] [module R M₂] [module R M₃]
/-- The empty bilinear map defeq to `matrix.vec_empty` -/
@[simps]
def linear_map.vec_empty₂ : M →ₗ[R] M₂ →ₗ[R] (fin 0 → M₃) :=
{ to_fun := λ m, linear_map.vec_empty,
map_add' := λ x y, linear_map.ext $ λ z, subsingleton.elim _ _,
map_smul' := λ r x, linear_map.ext $ λ z, subsingleton.elim _ _, }
/-- A bilinear map into `fin n.succ → M₃` can be built out of a map into `M₃` and a map into
`fin n → M₃` -/
@[simps]
def linear_map.vec_cons₂ {n} (f : M →ₗ[R] M₂ →ₗ[R] M₃) (g : M →ₗ[R] M₂ →ₗ[R] (fin n → M₃)) :
M →ₗ[R] M₂ →ₗ[R] (fin n.succ → M₃) :=
{ to_fun := λ m, linear_map.vec_cons (f m) (g m),
map_add' := λ x y, linear_map.ext $ λ z, by
simp only [f.map_add, g.map_add, linear_map.add_apply, linear_map.vec_cons_apply,
matrix.cons_add_cons (f x z)],
map_smul' := λ r x, linear_map.ext $ λ z, by simp [matrix.smul_cons r (f x z)], }
end comm_semiring
end fin
|
c905bee2a90051a978be65c3228572e8d326486b | aa5a655c05e5359a70646b7154e7cac59f0b4132 | /tests/lean/run/funext.lean | 9d97ef1344436089a4604d81ebff597e80838658 | [
"Apache-2.0"
] | permissive | lambdaxymox/lean4 | ae943c960a42247e06eff25c35338268d07454cb | 278d47c77270664ef29715faab467feac8a0f446 | refs/heads/master | 1,677,891,867,340 | 1,612,500,005,000 | 1,612,500,005,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 820 | lean | theorem ex1 : (fun y => y + 0) = (fun x => 0 + x) := by
funext x
rw [Nat.zeroAdd]
rfl
theorem ex2 : (fun y x => y + x + 0) = (fun x y => y + x) := by
funext x y
rw [Nat.addZero, Nat.addComm]
theorem ex3 : (fun (x : Nat × Nat) => x.1 + x.2) = (fun (x : Nat × Nat) => x.2 + x.1) := by
funext (a, b)
show a + b = b + a
rw [Nat.addComm]
theorem ex4 : (fun (x : Nat × Nat) (y : Nat × Nat) => x.1 + y.2) = (fun (x : Nat × Nat) (z : Nat × Nat) => z.2 + x.1) := by
funext (a, b) (c, d)
show a + d = d + a
rw [Nat.addComm]
theorem ex5 : (fun (x : Id Nat) => x.succ + 0) = (fun (x : Id Nat) => 0 + x.succ) := by
funext (x : Nat)
let! y := x + 1 -- if `(x : Nat)` is not used at `funext`, then `x+1` would fail to be elaborated since we don't have the instance `Add (Id Nat)`
rw [Nat.addComm]
|
911748cf129d3ab15f4e134c3bbaaf2ce89f0249 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/struct_class.lean | 1cd37eb1ee8c6098143cdbad5aecd0bcdb6279f8 | [
"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 | 170 | lean | structure [class] point (A : Type*) (B : Type*) :=
mk :: (x : A) (y : B)
print classes
structure point2 (A : Type*) (B : Type*) :=
mk :: (x : A) (y : B)
print classes
|
806ea92aaca36e1b8859c2fa9e96c2be38db4699 | 64874bd1010548c7f5a6e3e8902efa63baaff785 | /tests/lean/run/eq13.lean | 92f25ee9dfc1841a7d2a89337b31cfabef3ad58c | [
"Apache-2.0"
] | permissive | tjiaqi/lean | 4634d729795c164664d10d093f3545287c76628f | d0ce4cf62f4246b0600c07e074d86e51f2195e30 | refs/heads/master | 1,622,323,796,480 | 1,422,643,069,000 | 1,422,643,069,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 320 | lean | open nat
definition f : nat → nat → nat,
f _ 0 := 0,
f 0 _ := 1,
f _ _ := arbitrary nat
theorem f_zero_right : ∀ a, f a 0 = 0,
f_zero_right 0 := rfl,
f_zero_right (succ _) := rfl
theorem f_zero_succ (a : nat) : f 0 (a+1) = 1 :=
rfl
theorem f_succ_succ (a b : nat) : f (a+1) (b+1) = arbitrary nat :=
rfl
|
ba8ed4708d5b6698d793f3b8d5bb1394754b5ece | ea97c777e51529c97caac532f9a6bbea417eca7a | /04_simplifier_lists.lean | 21c0701d487837f28e22eadebdf9f5d34975da39 | [] | no_license | gebner/avm2017_tutorial | 0fcd023fbcefd6e46384ca4919b90a0f6118368e | 3954983cdc8aef0e58e1a5809c0b3e217057ac4c | refs/heads/master | 1,624,860,271,990 | 1,505,717,496,000 | 1,505,717,496,000 | 103,569,052 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,799 | lean | universes u v w
-- We can typically set up the simplifier so that most theorems
-- can be proven by induction + simp
@[simp]
lemma reverse_nil {α : Type u} : [].reverse = ([] : list α) :=
rfl
lemma reverse_core {α : Type u} (xs ys : list α) :
list.reverse_core xs ys = xs.reverse ++ ys :=
by induction xs generalizing ys;
simp [list.reverse_core, list.reverse]; simp *
@[simp]
lemma reverse_cons {α : Type u} (x : α) (xs : list α) :
(x :: xs).reverse = xs.reverse ++ [x] :=
by simp [list.reverse, list.reverse_core]; simp [reverse_core]
@[simp]
lemma reverse_concat {α : Type u} (xs ys : list α) :
(xs ++ ys).reverse = ys.reverse ++ xs.reverse :=
by induction xs generalizing ys; simp *
@[simp]
lemma reverse_reverse {α : Type u} (xs : list α) : xs.reverse.reverse = xs :=
by induction xs; simp *
example {α : Type u} (xs ys : list α) :
(xs.reverse ++ ys).reverse = ys.reverse ++ xs :=
by simp
@[simp]
lemma map_reverse {α : Type u} {β : Type v} (f : α → β) (xs : list α) :
list.map f (list.reverse xs) = list.reverse (list.map f xs) :=
by induction xs; simp [*, list.map]
@[simp]
lemma map_id {α : Type u} (xs : list α) : list.map (λ x, x) xs = xs :=
by apply list.map_id
@[simp]
lemma map_map {α : Type u} {β : Type v} {γ : Type w} (f : α → β) (g : β → γ) (xs : list α) :
list.map g (list.map f xs) = list.map (g ∘ f) xs :=
by apply list.map_map
example (xs : list ℕ) :
(list.reverse $
list.map (λ x, x - 2) $
list.reverse $
list.map (λ x, x + 2) xs)
= xs :=
by simp [(∘)]
-- What lemmas do we need to add to prove the following?
example (xs : list ℕ) :
let xs := xs.filter (λ x, x > 0) in
let xs := xs.map (λ x, 3 * x / x) in
∀ x ∈ xs, x = 3 :=
by simp {contextual := tt} |
d3d8f059da8300f3e3b4513285ed8e677084f95f | 91b8df3b248df89472cc0b753fbe2bac750aefea | /experiments/lean/src/ddl/host/evaluation.lean | 3d62120f3a0b3ccaed66a14e81da75b91f867778 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | yeslogic/fathom | eabe5c4112d3b4d5ec9096a57bb502254ddbdf15 | 3960a9466150d392c2cb103c5cb5fcffa0200814 | refs/heads/main | 1,685,349,769,736 | 1,675,998,621,000 | 1,675,998,621,000 | 28,993,871 | 214 | 11 | Apache-2.0 | 1,694,044,276,000 | 1,420,764,938,000 | Rust | UTF-8 | Lean | false | false | 987 | lean | import ddl.host.basic
namespace ddl.host
variables {ℓ : Type}
/- 'Stuck' values -/
inductive value : expr ℓ → Prop
| bool (bv : bool) : value (expr.bool bv)
| nat (nv : ℕ) : value (expr.nat nv)
reserve infixl ` ⟹ `:50
reserve infixl ` ⟹* `:50
inductive step : expr ℓ → expr ℓ → Prop
infixl ` ⟹ ` := step
| value {e} :
value e →
e ⟹ e
| binop_rec_l {op e₁ e₁' e₂} :
e₁ ⟹ e₁' →
expr.app_binop op e₁ e₂ ⟹ expr.app_binop op e₁' e₂
| binop_rec_r {op e₁ e₂ e₂'} :
value e₁ →
e₂ ⟹ e₂' →
expr.app_binop op e₁ e₂ ⟹ expr.app_binop op e₁ e₂'
| binop_add {nv₁ nv₂} :
expr.nat nv₁ + expr.nat nv₂ ⟹ expr.nat (nv₁ + nv₂)
| binop_mul {nv₁ nv₂} :
expr.nat nv₁ * expr.nat nv₂ ⟹ expr.nat (nv₁ * nv₂)
infixl ` ⟹ ` := step
infixl ` ⟹* ` := ddl.multi step
end ddl.host
|
b615c37cb4f48b5d3e4ffa6d95ee76ca445c79bb | 5e3548e65f2c037cb94cd5524c90c623fbd6d46a | /src_icannos_totilas/topologie-espaces-normés/cpge_ten_05b.lean | e213fd2128ef2cd5ebd74f3565c4b8d165c2695e | [] | no_license | ahayat16/lean_exos | d4f08c30adb601a06511a71b5ffb4d22d12ef77f | 682f2552d5b04a8c8eb9e4ab15f875a91b03845c | refs/heads/main | 1,693,101,073,585 | 1,636,479,336,000 | 1,636,479,336,000 | 415,000,441 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 700 | lean | import data.set.basic
import topology.basic
import algebra.module.basic
import algebra.module.submodule
import order.complete_lattice
import analysis.normed_space.basic
-- Soit E une espace vectoriel normé.
-- (b) Soient F et G deux fermés non vides et disjoints de E. Montrer qu'il existe deux ouverts U et V tels que
-- F ⊂ U, G ⊂ V et U ∩ V = ∅ .
theorem b {R E: Type*} [normed_field R] [normed_group E] [normed_space R E] :
forall (F G: set E),
(set.nonempty F) ->
(set.nonempty G) ->
set.inter F G = ∅ ->
exists (U V: set E),
(is_open U)
/\ (is_open V)
/\ set.subset F U
/\ set.subset G V
/\ set.inter F G = ∅
:= sorry
|
1a313cfc1515a9ed30486e04a665efb66564e745 | 853df553b1d6ca524e3f0a79aedd32dde5d27ec3 | /src/topology/metric_space/closeds.lean | 8488d332117acfe92a5ff598fb766e68e31ea7f4 | [
"Apache-2.0"
] | permissive | DanielFabian/mathlib | efc3a50b5dde303c59eeb6353ef4c35a345d7112 | f520d07eba0c852e96fe26da71d85bf6d40fcc2a | refs/heads/master | 1,668,739,922,971 | 1,595,201,756,000 | 1,595,201,756,000 | 279,469,476 | 0 | 0 | null | 1,594,696,604,000 | 1,594,696,604,000 | null | UTF-8 | Lean | false | false | 21,413 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Sébastien Gouëzel
-/
import topology.metric_space.hausdorff_distance
import analysis.specific_limits
/-!
# Closed subsets
This file defines the metric and emetric space structure on the types of closed subsets and nonempty compact
subsets of a metric or emetric space.
The Hausdorff distance induces an emetric space structure on the type of closed subsets
of an emetric space, called `closeds`. Its completeness, resp. compactness, resp.
second-countability, follow from the corresponding properties of the original space.
In a metric space, the type of nonempty compact subsets (called `nonempty_compacts`) also
inherits a metric space structure from the Hausdorff distance, as the Hausdorff edistance is
always finite in this context.
-/
noncomputable theory
open_locale classical
open_locale topological_space
universe u
open classical set function topological_space filter
namespace emetric
section
variables {α : Type u} [emetric_space α] {s : set α}
/-- In emetric spaces, the Hausdorff edistance defines an emetric space structure
on the type of closed subsets -/
instance closeds.emetric_space : emetric_space (closeds α) :=
{ edist := λs t, Hausdorff_edist s.val t.val,
edist_self := λs, Hausdorff_edist_self,
edist_comm := λs t, Hausdorff_edist_comm,
edist_triangle := λs t u, Hausdorff_edist_triangle,
eq_of_edist_eq_zero :=
λs t h, subtype.eq ((Hausdorff_edist_zero_iff_eq_of_closed s.property t.property).1 h) }
/-- The edistance to a closed set depends continuously on the point and the set -/
lemma continuous_inf_edist_Hausdorff_edist :
continuous (λp : α × (closeds α), inf_edist p.1 (p.2).val) :=
begin
refine continuous_of_le_add_edist 2 (by simp) _,
rintros ⟨x, s⟩ ⟨y, t⟩,
calc inf_edist x (s.val) ≤ inf_edist x (t.val) + Hausdorff_edist (t.val) (s.val) :
inf_edist_le_inf_edist_add_Hausdorff_edist
... ≤ (inf_edist y (t.val) + edist x y) + Hausdorff_edist (t.val) (s.val) :
add_le_add_right inf_edist_le_inf_edist_add_edist _
... = inf_edist y (t.val) + (edist x y + Hausdorff_edist (s.val) (t.val)) :
by simp [add_comm, add_left_comm, Hausdorff_edist_comm, -subtype.val_eq_coe]
... ≤ inf_edist y (t.val) + (edist (x, s) (y, t) + edist (x, s) (y, t)) :
add_le_add_left (add_le_add (le_max_left _ _) (le_max_right _ _)) _
... = inf_edist y (t.val) + 2 * edist (x, s) (y, t) :
by rw [← mul_two, mul_comm]
end
/-- Subsets of a given closed subset form a closed set -/
lemma is_closed_subsets_of_is_closed (hs : is_closed s) :
is_closed {t : closeds α | t.val ⊆ s} :=
begin
refine is_closed_of_closure_subset (λt ht x hx, _),
-- t : closeds α, ht : t ∈ closure {t : closeds α | t.val ⊆ s},
-- x : α, hx : x ∈ t.val
-- goal : x ∈ s
have : x ∈ closure s,
{ refine mem_closure_iff.2 (λε εpos, _),
rcases mem_closure_iff.1 ht ε εpos with ⟨u, hu, Dtu⟩,
-- u : closeds α, hu : u ∈ {t : closeds α | t.val ⊆ s}, hu' : edist t u < ε
rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dtu with ⟨y, hy, Dxy⟩,
-- y : α, hy : y ∈ u.val, Dxy : edist x y < ε
exact ⟨y, hu hy, Dxy⟩ },
rwa hs.closure_eq at this,
end
/-- By definition, the edistance on `closeds α` is given by the Hausdorff edistance -/
lemma closeds.edist_eq {s t : closeds α} : edist s t = Hausdorff_edist s.val t.val := rfl
/-- In a complete space, the type of closed subsets is complete for the
Hausdorff edistance. -/
instance closeds.complete_space [complete_space α] : complete_space (closeds α) :=
begin
/- We will show that, if a sequence of sets `s n` satisfies
`edist (s n) (s (n+1)) < 2^{-n}`, then it converges. This is enough to guarantee
completeness, by a standard completeness criterion.
We use the shorthand `B n = 2^{-n}` in ennreal. -/
let B : ℕ → ennreal := λ n, (2⁻¹)^n,
have B_pos : ∀ n, (0:ennreal) < B n,
by simp [B, ennreal.pow_pos],
have B_ne_top : ∀ n, B n ≠ ⊤,
by simp [B, ennreal.div_def, ennreal.pow_ne_top],
/- Consider a sequence of closed sets `s n` with `edist (s n) (s (n+1)) < B n`.
We will show that it converges. The limit set is t0 = ⋂n, closure (⋃m≥n, s m).
We will have to show that a point in `s n` is close to a point in `t0`, and a point
in `t0` is close to a point in `s n`. The completeness then follows from a
standard criterion. -/
refine complete_of_convergent_controlled_sequences B B_pos (λs hs, _),
let t0 := ⋂n, closure (⋃m≥n, (s m).val),
let t : closeds α := ⟨t0, is_closed_Inter (λ_, is_closed_closure)⟩,
use t,
-- The inequality is written this way to agree with `edist_le_of_edist_le_geometric_of_tendsto₀`
have I1 : ∀n:ℕ, ∀x ∈ (s n).val, ∃y ∈ t0, edist x y ≤ 2 * B n,
{ /- This is the main difficulty of the proof. Starting from `x ∈ s n`, we want
to find a point in `t0` which is close to `x`. Define inductively a sequence of
points `z m` with `z n = x` and `z m ∈ s m` and `edist (z m) (z (m+1)) ≤ B m`. This is
possible since the Hausdorff distance between `s m` and `s (m+1)` is at most `B m`.
This sequence is a Cauchy sequence, therefore converging as the space is complete, to
a limit which satisfies the required properties. -/
assume n x hx,
obtain ⟨z, hz₀, hz⟩ : ∃ z : Π l, (s (n+l)).val, (z 0:α) = x ∧
∀ k, edist (z k:α) (z (k+1):α) ≤ B n / 2^k,
{ -- We prove existence of the sequence by induction.
have : ∀ (l : ℕ) (z : (s (n+l)).val), ∃ z' : (s (n+l+1)).val, edist (z:α) z' ≤ B n / 2^l,
{ assume l z,
obtain ⟨z', z'_mem, hz'⟩ : ∃ z' ∈ (s (n+l+1)).val, edist (z:α) z' < B n / 2^l,
{ apply exists_edist_lt_of_Hausdorff_edist_lt z.2,
simp only [B, ennreal.div_def, ennreal.inv_pow],
rw [← pow_add],
apply hs; simp },
exact ⟨⟨z', z'_mem⟩, le_of_lt hz'⟩ },
use [λ k, nat.rec_on k ⟨x, hx⟩ (λl z, some (this l z)), rfl],
exact λ k, some_spec (this k _) },
-- it follows from the previous bound that `z` is a Cauchy sequence
have : cauchy_seq (λ k, ((z k):α)),
from cauchy_seq_of_edist_le_geometric_two (B n) (B_ne_top n) hz,
-- therefore, it converges
rcases cauchy_seq_tendsto_of_complete this with ⟨y, y_lim⟩,
use y,
-- the limit point `y` will be the desired point, in `t0` and close to our initial point `x`.
-- First, we check it belongs to `t0`.
have : y ∈ t0 := mem_Inter.2 (λk, mem_closure_of_tendsto (by simp) y_lim
begin
simp only [exists_prop, set.mem_Union, filter.eventually_at_top, set.mem_preimage, set.preimage_Union],
exact ⟨k, λ m hm, ⟨n+m, zero_add k ▸ add_le_add (zero_le n) hm, (z m).2⟩⟩
end),
use this,
-- Then, we check that `y` is close to `x = z n`. This follows from the fact that `y`
-- is the limit of `z k`, and the distance between `z n` and `z k` has already been estimated.
rw [← hz₀],
exact edist_le_of_edist_le_geometric_two_of_tendsto₀ (B n) hz y_lim },
have I2 : ∀n:ℕ, ∀x ∈ t0, ∃y ∈ (s n).val, edist x y ≤ 2 * B n,
{ /- For the (much easier) reverse inequality, we start from a point `x ∈ t0` and we want
to find a point `y ∈ s n` which is close to `x`.
`x` belongs to `t0`, the intersection of the closures. In particular, it is well
approximated by a point `z` in `⋃m≥n, s m`, say in `s m`. Since `s m` and
`s n` are close, this point is itself well approximated by a point `y` in `s n`,
as required. -/
assume n x xt0,
have : x ∈ closure (⋃m≥n, (s m).val), by apply mem_Inter.1 xt0 n,
rcases mem_closure_iff.1 this (B n) (B_pos n) with ⟨z, hz, Dxz⟩,
-- z : α, Dxz : edist x z < B n,
simp only [exists_prop, set.mem_Union] at hz,
rcases hz with ⟨m, ⟨m_ge_n, hm⟩⟩,
-- m : ℕ, m_ge_n : m ≥ n, hm : z ∈ (s m).val
have : Hausdorff_edist (s m).val (s n).val < B n := hs n m n m_ge_n (le_refl n),
rcases exists_edist_lt_of_Hausdorff_edist_lt hm this with ⟨y, hy, Dzy⟩,
-- y : α, hy : y ∈ (s n).val, Dzy : edist z y < B n
exact ⟨y, hy, calc
edist x y ≤ edist x z + edist z y : edist_triangle _ _ _
... ≤ B n + B n : add_le_add (le_of_lt Dxz) (le_of_lt Dzy)
... = 2 * B n : (two_mul _).symm ⟩ },
-- Deduce from the above inequalities that the distance between `s n` and `t0` is at most `2 B n`.
have main : ∀n:ℕ, edist (s n) t ≤ 2 * B n := λn, Hausdorff_edist_le_of_mem_edist (I1 n) (I2 n),
-- from this, the convergence of `s n` to `t0` follows.
refine (tendsto_at_top _).2 (λε εpos, _),
have : tendsto (λn, 2 * B n) at_top (𝓝 (2 * 0)),
from ennreal.tendsto.const_mul
(ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 $ by simp [ennreal.one_lt_two])
(or.inr $ by simp),
rw mul_zero at this,
obtain ⟨N, hN⟩ : ∃ N, ∀ b ≥ N, ε > 2 * B b,
from ((tendsto_order.1 this).2 ε εpos).exists_forall_of_at_top,
exact ⟨N, λn hn, lt_of_le_of_lt (main n) (hN n hn)⟩
end
/-- In a compact space, the type of closed subsets is compact. -/
instance closeds.compact_space [compact_space α] : compact_space (closeds α) :=
⟨begin
/- by completeness, it suffices to show that it is totally bounded,
i.e., for all ε>0, there is a finite set which is ε-dense.
start from a set `s` which is ε-dense in α. Then the subsets of `s`
are finitely many, and ε-dense for the Hausdorff distance. -/
refine compact_of_totally_bounded_is_closed (emetric.totally_bounded_iff.2 (λε εpos, _)) is_closed_univ,
rcases dense εpos with ⟨δ, δpos, δlt⟩,
rcases emetric.totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 (@compact_univ α _ _)).1 δ δpos
with ⟨s, fs, hs⟩,
-- s : set α, fs : finite s, hs : univ ⊆ ⋃ (y : α) (H : y ∈ s), eball y δ
-- we first show that any set is well approximated by a subset of `s`.
have main : ∀ u : set α, ∃v ⊆ s, Hausdorff_edist u v ≤ δ,
{ assume u,
let v := {x : α | x ∈ s ∧ ∃y∈u, edist x y < δ},
existsi [v, ((λx hx, hx.1) : v ⊆ s)],
refine Hausdorff_edist_le_of_mem_edist _ _,
{ assume x hx,
have : x ∈ ⋃y ∈ s, ball y δ := hs (by simp),
rcases mem_bUnion_iff.1 this with ⟨y, ys, dy⟩,
have : edist y x < δ := by simp at dy; rwa [edist_comm] at dy,
exact ⟨y, ⟨ys, ⟨x, hx, this⟩⟩, le_of_lt dy⟩ },
{ rintros x ⟨hx1, ⟨y, yu, hy⟩⟩,
exact ⟨y, yu, le_of_lt hy⟩ }},
-- introduce the set F of all subsets of `s` (seen as members of `closeds α`).
let F := {f : closeds α | f.val ⊆ s},
use F,
split,
-- `F` is finite
{ apply @finite_of_finite_image _ _ F (λf, f.val),
{ exact subtype.val_injective.inj_on F },
{ refine fs.finite_subsets.subset (λb, _),
simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib],
assume x hx hx',
rwa hx' at hx }},
-- `F` is ε-dense
{ assume u _,
rcases main u.val with ⟨t0, t0s, Dut0⟩,
have : is_closed t0 := (fs.subset t0s).is_compact.is_closed,
let t : closeds α := ⟨t0, this⟩,
have : t ∈ F := t0s,
have : edist u t < ε := lt_of_le_of_lt Dut0 δlt,
apply mem_bUnion_iff.2,
exact ⟨t, ‹t ∈ F›, this⟩ }
end⟩
/-- In an emetric space, the type of non-empty compact subsets is an emetric space,
where the edistance is the Hausdorff edistance -/
instance nonempty_compacts.emetric_space : emetric_space (nonempty_compacts α) :=
{ edist := λs t, Hausdorff_edist s.val t.val,
edist_self := λs, Hausdorff_edist_self,
edist_comm := λs t, Hausdorff_edist_comm,
edist_triangle := λs t u, Hausdorff_edist_triangle,
eq_of_edist_eq_zero := λs t h, subtype.eq $ begin
have : closure (s.val) = closure (t.val) := Hausdorff_edist_zero_iff_closure_eq_closure.1 h,
rwa [s.property.2.is_closed.closure_eq,
t.property.2.is_closed.closure_eq] at this,
end }
/-- `nonempty_compacts.to_closeds` is a uniform embedding (as it is an isometry) -/
lemma nonempty_compacts.to_closeds.uniform_embedding :
uniform_embedding (@nonempty_compacts.to_closeds α _ _) :=
isometry.uniform_embedding $ λx y, rfl
/-- The range of `nonempty_compacts.to_closeds` is closed in a complete space -/
lemma nonempty_compacts.is_closed_in_closeds [complete_space α] :
is_closed (range $ @nonempty_compacts.to_closeds α _ _) :=
begin
have : range nonempty_compacts.to_closeds = {s : closeds α | s.val.nonempty ∧ is_compact s.val},
from range_inclusion _,
rw this,
refine is_closed_of_closure_subset (λs hs, ⟨_, _⟩),
{ -- take a set set t which is nonempty and at a finite distance of s
rcases mem_closure_iff.1 hs ⊤ ennreal.coe_lt_top with ⟨t, ht, Dst⟩,
rw edist_comm at Dst,
-- since `t` is nonempty, so is `s`
exact nonempty_of_Hausdorff_edist_ne_top ht.1 (ne_of_lt Dst) },
{ refine compact_iff_totally_bounded_complete.2 ⟨_, s.property.is_complete⟩,
refine totally_bounded_iff.2 (λε εpos, _),
-- we have to show that s is covered by finitely many eballs of radius ε
-- pick a nonempty compact set t at distance at most ε/2 of s
rcases mem_closure_iff.1 hs (ε/2) (ennreal.half_pos εpos) with ⟨t, ht, Dst⟩,
-- cover this space with finitely many balls of radius ε/2
rcases totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 ht.2).1 (ε/2) (ennreal.half_pos εpos)
with ⟨u, fu, ut⟩,
refine ⟨u, ⟨fu, λx hx, _⟩⟩,
-- u : set α, fu : finite u, ut : t.val ⊆ ⋃ (y : α) (H : y ∈ u), eball y (ε / 2)
-- then s is covered by the union of the balls centered at u of radius ε
rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dst with ⟨z, hz, Dxz⟩,
rcases mem_bUnion_iff.1 (ut hz) with ⟨y, hy, Dzy⟩,
have : edist x y < ε := calc
edist x y ≤ edist x z + edist z y : edist_triangle _ _ _
... < ε/2 + ε/2 : ennreal.add_lt_add Dxz Dzy
... = ε : ennreal.add_halves _,
exact mem_bUnion hy this },
end
/-- In a complete space, the type of nonempty compact subsets is complete. This follows
from the same statement for closed subsets -/
instance nonempty_compacts.complete_space [complete_space α] :
complete_space (nonempty_compacts α) :=
(complete_space_iff_is_complete_range nonempty_compacts.to_closeds.uniform_embedding).2 $
nonempty_compacts.is_closed_in_closeds.is_complete
/-- In a compact space, the type of nonempty compact subsets is compact. This follows from
the same statement for closed subsets -/
instance nonempty_compacts.compact_space [compact_space α] : compact_space (nonempty_compacts α) :=
⟨begin
rw embedding.compact_iff_compact_image nonempty_compacts.to_closeds.uniform_embedding.embedding,
rw [image_univ],
exact nonempty_compacts.is_closed_in_closeds.compact
end⟩
/-- In a second countable space, the type of nonempty compact subsets is second countable -/
instance nonempty_compacts.second_countable_topology [second_countable_topology α] :
second_countable_topology (nonempty_compacts α) :=
begin
haveI : separable_space (nonempty_compacts α) :=
begin
/- To obtain a countable dense subset of `nonempty_compacts α`, start from
a countable dense subset `s` of α, and then consider all its finite nonempty subsets.
This set is countable and made of nonempty compact sets. It turns out to be dense:
by total boundedness, any compact set `t` can be covered by finitely many small balls, and
approximations in `s` of the centers of these balls give the required finite approximation
of `t`. -/
have : separable_space α := by apply_instance,
rcases this.exists_countable_closure_eq_univ with ⟨s, cs, s_dense⟩,
let v0 := {t : set α | finite t ∧ t ⊆ s},
let v : set (nonempty_compacts α) := {t : nonempty_compacts α | t.val ∈ v0},
refine ⟨⟨v, ⟨_, _⟩⟩⟩,
{ have : countable (subtype.val '' v),
{ refine (countable_set_of_finite_subset cs).mono (λx hx, _),
rcases (mem_image _ _ _).1 hx with ⟨y, ⟨hy, yx⟩⟩,
rw ← yx,
exact hy },
apply countable_of_injective_of_countable_image _ this,
apply subtype.val_injective.inj_on },
{ refine subset.antisymm (subset_univ _) (λt ht, mem_closure_iff.2 (λε εpos, _)),
-- t is a compact nonempty set, that we have to approximate uniformly by a a set in `v`.
rcases dense εpos with ⟨δ, δpos, δlt⟩,
-- construct a map F associating to a point in α an approximating point in s, up to δ/2.
have Exy : ∀x, ∃y, y ∈ s ∧ edist x y < δ/2,
{ assume x,
have : x ∈ closure s := by rw s_dense; exact mem_univ _,
rcases mem_closure_iff.1 this (δ/2) (ennreal.half_pos δpos) with ⟨y, ys, hy⟩,
exact ⟨y, ⟨ys, hy⟩⟩ },
let F := λx, some (Exy x),
have Fspec : ∀x, F x ∈ s ∧ edist x (F x) < δ/2 := λx, some_spec (Exy x),
-- cover `t` with finitely many balls. Their centers form a set `a`
have : totally_bounded t.val := (compact_iff_totally_bounded_complete.1 t.property.2).1,
rcases totally_bounded_iff.1 this (δ/2) (ennreal.half_pos δpos) with ⟨a, af, ta⟩,
-- a : set α, af : finite a, ta : t.val ⊆ ⋃ (y : α) (H : y ∈ a), eball y (δ / 2)
-- replace each center by a nearby approximation in `s`, giving a new set `b`
let b := F '' a,
have : finite b := af.image _,
have tb : ∀x ∈ t.val, ∃y ∈ b, edist x y < δ,
{ assume x hx,
rcases mem_bUnion_iff.1 (ta hx) with ⟨z, za, Dxz⟩,
existsi [F z, mem_image_of_mem _ za],
calc edist x (F z) ≤ edist x z + edist z (F z) : edist_triangle _ _ _
... < δ/2 + δ/2 : ennreal.add_lt_add Dxz (Fspec z).2
... = δ : ennreal.add_halves _ },
-- keep only the points in `b` that are close to point in `t`, yielding a new set `c`
let c := {y ∈ b | ∃x∈t.val, edist x y < δ},
have : finite c := ‹finite b›.subset (λx hx, hx.1),
-- points in `t` are well approximated by points in `c`
have tc : ∀x ∈ t.val, ∃y ∈ c, edist x y ≤ δ,
{ assume x hx,
rcases tb x hx with ⟨y, yv, Dxy⟩,
have : y ∈ c := by simp [c, -mem_image]; exact ⟨yv, ⟨x, hx, Dxy⟩⟩,
exact ⟨y, this, le_of_lt Dxy⟩ },
-- points in `c` are well approximated by points in `t`
have ct : ∀y ∈ c, ∃x ∈ t.val, edist y x ≤ δ,
{ rintros y ⟨hy1, ⟨x, xt, Dyx⟩⟩,
have : edist y x ≤ δ := calc
edist y x = edist x y : edist_comm _ _
... ≤ δ : le_of_lt Dyx,
exact ⟨x, xt, this⟩ },
-- it follows that their Hausdorff distance is small
have : Hausdorff_edist t.val c ≤ δ :=
Hausdorff_edist_le_of_mem_edist tc ct,
have Dtc : Hausdorff_edist t.val c < ε := lt_of_le_of_lt this δlt,
-- the set `c` is not empty, as it is well approximated by a nonempty set
have hc : c.nonempty,
from nonempty_of_Hausdorff_edist_ne_top t.property.1 (ne_top_of_lt Dtc),
-- let `d` be the version of `c` in the type `nonempty_compacts α`
let d : nonempty_compacts α := ⟨c, ⟨hc, ‹finite c›.is_compact⟩⟩,
have : c ⊆ s,
{ assume x hx,
rcases (mem_image _ _ _).1 hx.1 with ⟨y, ⟨ya, yx⟩⟩,
rw ← yx,
exact (Fspec y).1 },
have : d ∈ v := ⟨‹finite c›, this⟩,
-- we have proved that `d` is a good approximation of `t` as requested
exact ⟨d, ‹d ∈ v›, Dtc⟩ },
end,
apply second_countable_of_separable,
end
end --section
end emetric --namespace
namespace metric
section
variables {α : Type u} [metric_space α]
/-- `nonempty_compacts α` inherits a metric space structure, as the Hausdorff
edistance between two such sets is finite. -/
instance nonempty_compacts.metric_space : metric_space (nonempty_compacts α) :=
emetric_space.to_metric_space $ λx y, Hausdorff_edist_ne_top_of_nonempty_of_bounded x.2.1 y.2.1
(bounded_of_compact x.2.2) (bounded_of_compact y.2.2)
/-- The distance on `nonempty_compacts α` is the Hausdorff distance, by construction -/
lemma nonempty_compacts.dist_eq {x y : nonempty_compacts α} :
dist x y = Hausdorff_dist x.val y.val := rfl
lemma lipschitz_inf_dist_set (x : α) :
lipschitz_with 1 (λ s : nonempty_compacts α, inf_dist x s.val) :=
lipschitz_with.of_le_add $ assume s t,
by { rw dist_comm,
exact inf_dist_le_inf_dist_add_Hausdorff_dist (edist_ne_top t s) }
lemma lipschitz_inf_dist :
lipschitz_with 2 (λ p : α × (nonempty_compacts α), inf_dist p.1 p.2.val) :=
@lipschitz_with.uncurry _ _ _ _ _ _ (λ (x : α) (s : nonempty_compacts α), inf_dist x s.val) 1 1
(λ s, lipschitz_inf_dist_pt s.val) lipschitz_inf_dist_set
lemma uniform_continuous_inf_dist_Hausdorff_dist :
uniform_continuous (λp : α × (nonempty_compacts α), inf_dist p.1 (p.2).val) :=
lipschitz_inf_dist.uniform_continuous
end --section
end metric --namespace
|
43bd605c98043d1389ca7a575c209b3bab37431e | 2a70b774d16dbdf5a533432ee0ebab6838df0948 | /_target/deps/mathlib/src/analysis/specific_limits.lean | 1c199fa4d0bfc2838ebdf0a38f43f6fe454ab8d3 | [
"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 | 29,432 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import algebra.geom_sum
import order.filter.archimedean
import order.iterate
import topology.instances.ennreal
import tactic.ring_exp
import analysis.asymptotics
/-!
# A collection of specific limit computations
-/
noncomputable theory
open classical set function filter finset metric asymptotics
open_locale classical topological_space nat big_operators uniformity nnreal
variables {α : Type*} {β : Type*} {ι : Type*}
lemma tendsto_norm_at_top_at_top : tendsto (norm : ℝ → ℝ) at_top at_top :=
tendsto_abs_at_top_at_top
lemma summable_of_absolute_convergence_real {f : ℕ → ℝ} :
(∃r, tendsto (λn, (∑ i in range n, abs (f i))) at_top (𝓝 r)) → summable f
| ⟨r, hr⟩ :=
begin
refine summable_of_summable_norm ⟨r, (has_sum_iff_tendsto_nat_of_nonneg _ _).2 _⟩,
exact assume i, norm_nonneg _,
simpa only using hr
end
lemma tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ)⁻¹) at_top (𝓝 0) :=
tendsto_inv_at_top_zero.comp tendsto_coe_nat_at_top_at_top
lemma tendsto_const_div_at_top_nhds_0_nat (C : ℝ) : tendsto (λ n : ℕ, C / n) at_top (𝓝 0) :=
by simpa only [mul_zero] using tendsto_const_nhds.mul tendsto_inverse_at_top_nhds_0_nat
lemma nnreal.tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ≥0)⁻¹) at_top (𝓝 0) :=
by { rw ← nnreal.tendsto_coe, convert tendsto_inverse_at_top_nhds_0_nat, simp }
lemma nnreal.tendsto_const_div_at_top_nhds_0_nat (C : ℝ≥0) :
tendsto (λ n : ℕ, C / n) at_top (𝓝 0) :=
by simpa using tendsto_const_nhds.mul nnreal.tendsto_inverse_at_top_nhds_0_nat
lemma tendsto_one_div_add_at_top_nhds_0_nat :
tendsto (λ n : ℕ, 1 / ((n : ℝ) + 1)) at_top (𝓝 0) :=
suffices tendsto (λ n : ℕ, 1 / (↑(n + 1) : ℝ)) at_top (𝓝 0), by simpa,
(tendsto_add_at_top_iff_nat 1).2 (tendsto_const_div_at_top_nhds_0_nat 1)
/-! ### Powers -/
lemma tendsto_add_one_pow_at_top_at_top_of_pos [linear_ordered_semiring α] [archimedean α] {r : α}
(h : 0 < r) :
tendsto (λ n:ℕ, (r + 1)^n) at_top at_top :=
tendsto_at_top_at_top_of_monotone' (λ n m, pow_le_pow (le_add_of_nonneg_left (le_of_lt h))) $
not_bdd_above_iff.2 $ λ x, set.exists_range_iff.2 $ add_one_pow_unbounded_of_pos _ h
lemma tendsto_pow_at_top_at_top_of_one_lt [linear_ordered_ring α] [archimedean α]
{r : α} (h : 1 < r) :
tendsto (λn:ℕ, r ^ n) at_top at_top :=
sub_add_cancel r 1 ▸ tendsto_add_one_pow_at_top_at_top_of_pos (sub_pos.2 h)
lemma nat.tendsto_pow_at_top_at_top_of_one_lt {m : ℕ} (h : 1 < m) :
tendsto (λn:ℕ, m ^ n) at_top at_top :=
nat.sub_add_cancel (le_of_lt h) ▸
tendsto_add_one_pow_at_top_at_top_of_pos (nat.sub_pos_of_lt h)
lemma tendsto_norm_zero' {𝕜 : Type*} [normed_group 𝕜] :
tendsto (norm : 𝕜 → ℝ) (𝓝[{x | x ≠ 0}] 0) (𝓝[set.Ioi 0] 0) :=
tendsto_norm_zero.inf $ tendsto_principal_principal.2 $ λ x hx, norm_pos_iff.2 hx
lemma normed_field.tendsto_norm_inverse_nhds_within_0_at_top {𝕜 : Type*} [normed_field 𝕜] :
tendsto (λ x:𝕜, ∥x⁻¹∥) (𝓝[{x | x ≠ 0}] 0) at_top :=
(tendsto_inv_zero_at_top.comp tendsto_norm_zero').congr $ λ x, (normed_field.norm_inv x).symm
lemma tendsto_pow_at_top_nhds_0_of_lt_1 {𝕜 : Type*} [linear_ordered_field 𝕜] [archimedean 𝕜]
[topological_space 𝕜] [order_topology 𝕜] {r : 𝕜} (h₁ : 0 ≤ r) (h₂ : r < 1) :
tendsto (λn:ℕ, r^n) at_top (𝓝 0) :=
h₁.eq_or_lt.elim
(assume : 0 = r, (tendsto_add_at_top_iff_nat 1).mp $ by simp [pow_succ, ← this, tendsto_const_nhds])
(assume : 0 < r,
have tendsto (λn, (r⁻¹ ^ n)⁻¹) at_top (𝓝 0),
from tendsto_inv_at_top_zero.comp
(tendsto_pow_at_top_at_top_of_one_lt $ one_lt_inv this h₂),
this.congr (λ n, by simp))
lemma tendsto_pow_at_top_nhds_within_0_of_lt_1 {𝕜 : Type*} [linear_ordered_field 𝕜] [archimedean 𝕜]
[topological_space 𝕜] [order_topology 𝕜] {r : 𝕜} (h₁ : 0 < r) (h₂ : r < 1) :
tendsto (λn:ℕ, r^n) at_top (𝓝[Ioi 0] 0) :=
tendsto_inf.2 ⟨tendsto_pow_at_top_nhds_0_of_lt_1 h₁.le h₂,
tendsto_principal.2 $ eventually_of_forall $ λ n, pow_pos h₁ _⟩
lemma is_o_pow_pow_of_lt_left {r₁ r₂ : ℝ} (h₁ : 0 ≤ r₁) (h₂ : r₁ < r₂) :
is_o (λ n : ℕ, r₁ ^ n) (λ n, r₂ ^ n) at_top :=
have H : 0 < r₂ := h₁.trans_lt h₂,
is_o_of_tendsto (λ n hn, false.elim $ H.ne' $ pow_eq_zero hn) $
(tendsto_pow_at_top_nhds_0_of_lt_1 (div_nonneg h₁ (h₁.trans h₂.le)) ((div_lt_one H).2 h₂)).congr
(λ n, div_pow _ _ _)
lemma is_O_pow_pow_of_le_left {r₁ r₂ : ℝ} (h₁ : 0 ≤ r₁) (h₂ : r₁ ≤ r₂) :
is_O (λ n : ℕ, r₁ ^ n) (λ n, r₂ ^ n) at_top :=
h₂.eq_or_lt.elim (λ h, h ▸ is_O_refl _ _) (λ h, (is_o_pow_pow_of_lt_left h₁ h).is_O)
lemma is_o_pow_pow_of_abs_lt_left {r₁ r₂ : ℝ} (h : abs r₁ < abs r₂) :
is_o (λ n : ℕ, r₁ ^ n) (λ n, r₂ ^ n) at_top :=
begin
refine (is_o.of_norm_left _).of_norm_right,
exact (is_o_pow_pow_of_lt_left (abs_nonneg r₁) h).congr (pow_abs r₁) (pow_abs r₂)
end
/-- Various statements equivalent to the fact that `f n` grows exponentially slower than `R ^ n`.
* 0: $f n = o(a ^ n)$ for some $-R < a < R$;
* 1: $f n = o(a ^ n)$ for some $0 < a < R$;
* 2: $f n = O(a ^ n)$ for some $-R < a < R$;
* 3: $f n = O(a ^ n)$ for some $0 < a < R$;
* 4: there exist `a < R` and `C` such that one of `C` and `R` is positive and $|f n| ≤ Ca^n$
for all `n`;
* 5: there exists `0 < a < R` and a positive `C` such that $|f n| ≤ Ca^n$ for all `n`;
* 6: there exists `a < R` such that $|f n| ≤ a ^ n$ for sufficiently large `n`;
* 7: there exists `0 < a < R` such that $|f n| ≤ a ^ n$ for sufficiently large `n`.
NB: For backwards compatibility, if you add more items to the list, please append them at the end of
the list. -/
lemma tfae_exists_lt_is_o_pow (f : ℕ → ℝ) (R : ℝ) :
tfae [∃ a ∈ Ioo (-R) R, is_o f (pow a) at_top,
∃ a ∈ Ioo 0 R, is_o f (pow a) at_top,
∃ a ∈ Ioo (-R) R, is_O f (pow a) at_top,
∃ a ∈ Ioo 0 R, is_O f (pow a) at_top,
∃ (a < R) C (h₀ : 0 < C ∨ 0 < R), ∀ n, abs (f n) ≤ C * a ^ n,
∃ (a ∈ Ioo 0 R) (C > 0), ∀ n, abs (f n) ≤ C * a ^ n,
∃ a < R, ∀ᶠ n in at_top, abs (f n) ≤ a ^ n,
∃ a ∈ Ioo 0 R, ∀ᶠ n in at_top, abs (f n) ≤ a ^ n] :=
begin
have A : Ico 0 R ⊆ Ioo (-R) R,
from λ x hx, ⟨(neg_lt_zero.2 (hx.1.trans_lt hx.2)).trans_le hx.1, hx.2⟩,
have B : Ioo 0 R ⊆ Ioo (-R) R := subset.trans Ioo_subset_Ico_self A,
-- First we prove that 1-4 are equivalent using 2 → 3 → 4, 1 → 3, and 2 → 1
tfae_have : 1 → 3, from λ ⟨a, ha, H⟩, ⟨a, ha, H.is_O⟩,
tfae_have : 2 → 1, from λ ⟨a, ha, H⟩, ⟨a, B ha, H⟩,
tfae_have : 3 → 2,
{ rintro ⟨a, ha, H⟩,
rcases exists_between (abs_lt.2 ha) with ⟨b, hab, hbR⟩,
exact ⟨b, ⟨(abs_nonneg a).trans_lt hab, hbR⟩,
H.trans_is_o (is_o_pow_pow_of_abs_lt_left (hab.trans_le (le_abs_self b)))⟩ },
tfae_have : 2 → 4, from λ ⟨a, ha, H⟩, ⟨a, ha, H.is_O⟩,
tfae_have : 4 → 3, from λ ⟨a, ha, H⟩, ⟨a, B ha, H⟩,
-- Add 5 and 6 using 4 → 6 → 5 → 3
tfae_have : 4 → 6,
{ rintro ⟨a, ha, H⟩,
rcases bound_of_is_O_nat_at_top H with ⟨C, hC₀, hC⟩,
refine ⟨a, ha, C, hC₀, λ n, _⟩,
simpa only [real.norm_eq_abs, abs_pow, abs_of_nonneg ha.1.le]
using hC (pow_ne_zero n ha.1.ne') },
tfae_have : 6 → 5, from λ ⟨a, ha, C, H₀, H⟩, ⟨a, ha.2, C, or.inl H₀, H⟩,
tfae_have : 5 → 3,
{ rintro ⟨a, ha, C, h₀, H⟩,
rcases sign_cases_of_C_mul_pow_nonneg (λ n, (abs_nonneg _).trans (H n)) with rfl | ⟨hC₀, ha₀⟩,
{ obtain rfl : f = 0, by { ext n, simpa using H n },
simp only [lt_irrefl, false_or] at h₀,
exact ⟨0, ⟨neg_lt_zero.2 h₀, h₀⟩, is_O_zero _ _⟩ },
exact ⟨a, A ⟨ha₀, ha⟩,
is_O_of_le' _ (λ n, (H n).trans $ mul_le_mul_of_nonneg_left (le_abs_self _) hC₀.le)⟩ },
-- Add 7 and 8 using 2 → 8 → 7 → 3
tfae_have : 2 → 8,
{ rintro ⟨a, ha, H⟩,
refine ⟨a, ha, (H.def zero_lt_one).mono (λ n hn, _)⟩,
rwa [real.norm_eq_abs, real.norm_eq_abs, one_mul, abs_pow, abs_of_pos ha.1] at hn },
tfae_have : 8 → 7, from λ ⟨a, ha, H⟩, ⟨a, ha.2, H⟩,
tfae_have : 7 → 3,
{ rintro ⟨a, ha, H⟩,
have : 0 ≤ a, from nonneg_of_eventually_pow_nonneg (H.mono $ λ n, (abs_nonneg _).trans),
refine ⟨a, A ⟨this, ha⟩, is_O.of_bound 1 _⟩,
simpa only [real.norm_eq_abs, one_mul, abs_pow, abs_of_nonneg this] },
tfae_finish
end
lemma uniformity_basis_dist_pow_of_lt_1 {α : Type*} [metric_space α]
{r : ℝ} (h₀ : 0 < r) (h₁ : r < 1) :
(𝓤 α).has_basis (λ k : ℕ, true) (λ k, {p : α × α | dist p.1 p.2 < r ^ k}) :=
metric.mk_uniformity_basis (λ i _, pow_pos h₀ _) $ λ ε ε0,
(exists_pow_lt_of_lt_one ε0 h₁).imp $ λ k hk, ⟨trivial, hk.le⟩
lemma geom_lt {u : ℕ → ℝ} {c : ℝ} (hc : 0 ≤ c) {n : ℕ} (hn : 0 < n)
(h : ∀ k < n, c * u k < u (k + 1)) :
c ^ n * u 0 < u n :=
(monotone_mul_left_of_nonneg hc).seq_pos_lt_seq_of_le_of_lt hn (by simp)
(λ k hk, by simp [pow_succ, mul_assoc]) h
lemma geom_le {u : ℕ → ℝ} {c : ℝ} (hc : 0 ≤ c) (n : ℕ) (h : ∀ k < n, c * u k ≤ u (k + 1)) :
c ^ n * u 0 ≤ u n :=
by refine (monotone_mul_left_of_nonneg hc).seq_le_seq n _ _ h; simp [pow_succ, mul_assoc, le_refl]
/-- If a sequence `v` of real numbers satisfies `k * v n ≤ v (n+1)` with `1 < k`,
then it goes to +∞. -/
lemma tendsto_at_top_of_geom_le {v : ℕ → ℝ} {c : ℝ} (h₀ : 0 < v 0) (hc : 1 < c)
(hu : ∀ n, c * v n ≤ v (n + 1)) : tendsto v at_top at_top :=
tendsto_at_top_mono (λ n, geom_le (zero_le_one.trans hc.le) n (λ k hk, hu k)) $
(tendsto_pow_at_top_at_top_of_one_lt hc).at_top_mul_const h₀
lemma nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ≥0} (hr : r < 1) :
tendsto (λ n:ℕ, r^n) at_top (𝓝 0) :=
nnreal.tendsto_coe.1 $ by simp only [nnreal.coe_pow, nnreal.coe_zero,
tendsto_pow_at_top_nhds_0_of_lt_1 r.coe_nonneg hr]
lemma ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : ennreal} (hr : r < 1) :
tendsto (λ n:ℕ, r^n) at_top (𝓝 0) :=
begin
rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩,
rw [← ennreal.coe_zero],
norm_cast at *,
apply nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 hr
end
/-- In a normed ring, the powers of an element x with `∥x∥ < 1` tend to zero. -/
lemma tendsto_pow_at_top_nhds_0_of_norm_lt_1 {R : Type*} [normed_ring R] {x : R}
(h : ∥x∥ < 1) : tendsto (λ (n : ℕ), x ^ n) at_top (𝓝 0) :=
begin
apply squeeze_zero_norm' (eventually_norm_pow_le x),
exact tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg _) h,
end
lemma tendsto_pow_at_top_nhds_0_of_abs_lt_1 {r : ℝ} (h : abs r < 1) :
tendsto (λn:ℕ, r^n) at_top (𝓝 0) :=
tendsto_pow_at_top_nhds_0_of_norm_lt_1 h
/-! ### Geometric series-/
section geometric
lemma has_sum_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) :
has_sum (λn:ℕ, r ^ n) (1 - r)⁻¹ :=
have r ≠ 1, from ne_of_lt h₂,
have tendsto (λn, (r ^ n - 1) * (r - 1)⁻¹) at_top (𝓝 ((0 - 1) * (r - 1)⁻¹)),
from ((tendsto_pow_at_top_nhds_0_of_lt_1 h₁ h₂).sub tendsto_const_nhds).mul tendsto_const_nhds,
have (λ n, (∑ i in range n, r ^ i)) = (λ n, geom_series r n) := rfl,
(has_sum_iff_tendsto_nat_of_nonneg (pow_nonneg h₁) _).mpr $
by simp [neg_inv, geom_sum, div_eq_mul_inv, *] at *
lemma summable_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : summable (λn:ℕ, r ^ n) :=
⟨_, has_sum_geometric_of_lt_1 h₁ h₂⟩
lemma tsum_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : (∑'n:ℕ, r ^ n) = (1 - r)⁻¹ :=
(has_sum_geometric_of_lt_1 h₁ h₂).tsum_eq
lemma has_sum_geometric_two : has_sum (λn:ℕ, ((1:ℝ)/2) ^ n) 2 :=
by convert has_sum_geometric_of_lt_1 _ _; norm_num
lemma summable_geometric_two : summable (λn:ℕ, ((1:ℝ)/2) ^ n) :=
⟨_, has_sum_geometric_two⟩
lemma tsum_geometric_two : (∑'n:ℕ, ((1:ℝ)/2) ^ n) = 2 :=
has_sum_geometric_two.tsum_eq
lemma sum_geometric_two_le (n : ℕ) : ∑ (i : ℕ) in range n, (1 / (2 : ℝ)) ^ i ≤ 2 :=
begin
have : ∀ i, 0 ≤ (1 / (2 : ℝ)) ^ i,
{ intro i, apply pow_nonneg, norm_num },
convert sum_le_tsum (range n) (λ i _, this i) summable_geometric_two,
exact tsum_geometric_two.symm
end
lemma has_sum_geometric_two' (a : ℝ) : has_sum (λn:ℕ, (a / 2) / 2 ^ n) a :=
begin
convert has_sum.mul_left (a / 2) (has_sum_geometric_of_lt_1
(le_of_lt one_half_pos) one_half_lt_one),
{ funext n, simp, refl, },
{ norm_num }
end
lemma summable_geometric_two' (a : ℝ) : summable (λ n:ℕ, (a / 2) / 2 ^ n) :=
⟨a, has_sum_geometric_two' a⟩
lemma tsum_geometric_two' (a : ℝ) : (∑' n:ℕ, (a / 2) / 2^n) = a :=
(has_sum_geometric_two' a).tsum_eq
lemma nnreal.has_sum_geometric {r : ℝ≥0} (hr : r < 1) :
has_sum (λ n : ℕ, r ^ n) (1 - r)⁻¹ :=
begin
apply nnreal.has_sum_coe.1,
push_cast,
rw [nnreal.coe_sub (le_of_lt hr)],
exact has_sum_geometric_of_lt_1 r.coe_nonneg hr
end
lemma nnreal.summable_geometric {r : ℝ≥0} (hr : r < 1) : summable (λn:ℕ, r ^ n) :=
⟨_, nnreal.has_sum_geometric hr⟩
lemma tsum_geometric_nnreal {r : ℝ≥0} (hr : r < 1) : (∑'n:ℕ, r ^ n) = (1 - r)⁻¹ :=
(nnreal.has_sum_geometric hr).tsum_eq
/-- The series `pow r` converges to `(1-r)⁻¹`. For `r < 1` the RHS is a finite number,
and for `1 ≤ r` the RHS equals `∞`. -/
lemma ennreal.tsum_geometric (r : ennreal) : (∑'n:ℕ, r ^ n) = (1 - r)⁻¹ :=
begin
cases lt_or_le r 1 with hr hr,
{ rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩,
norm_cast at *,
convert ennreal.tsum_coe_eq (nnreal.has_sum_geometric hr),
rw [ennreal.coe_inv $ ne_of_gt $ nnreal.sub_pos.2 hr] },
{ rw [ennreal.sub_eq_zero_of_le hr, ennreal.inv_zero, ennreal.tsum_eq_supr_nat, supr_eq_top],
refine λ a ha, (ennreal.exists_nat_gt (lt_top_iff_ne_top.1 ha)).imp
(λ n hn, lt_of_lt_of_le hn _),
have : ∀ k:ℕ, 1 ≤ r^k, by simpa using canonically_ordered_semiring.pow_le_pow_of_le_left hr,
calc (n:ennreal) = (∑ i in range n, 1) : by rw [sum_const, nsmul_one, card_range]
... ≤ ∑ i in range n, r ^ i : sum_le_sum (λ k _, this k) }
end
variables {K : Type*} [normed_field K] {ξ : K}
lemma has_sum_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : has_sum (λn:ℕ, ξ ^ n) (1 - ξ)⁻¹ :=
begin
have xi_ne_one : ξ ≠ 1, by { contrapose! h, simp [h] },
have A : tendsto (λn, (ξ ^ n - 1) * (ξ - 1)⁻¹) at_top (𝓝 ((0 - 1) * (ξ - 1)⁻¹)),
from ((tendsto_pow_at_top_nhds_0_of_norm_lt_1 h).sub tendsto_const_nhds).mul tendsto_const_nhds,
have B : (λ n, (∑ i in range n, ξ ^ i)) = (λ n, geom_series ξ n) := rfl,
rw [has_sum_iff_tendsto_nat_of_summable_norm, B],
{ simpa [geom_sum, xi_ne_one, neg_inv] using A },
{ simp [normed_field.norm_pow, summable_geometric_of_lt_1 (norm_nonneg _) h] }
end
lemma summable_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : summable (λn:ℕ, ξ ^ n) :=
⟨_, has_sum_geometric_of_norm_lt_1 h⟩
lemma tsum_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : (∑'n:ℕ, ξ ^ n) = (1 - ξ)⁻¹ :=
(has_sum_geometric_of_norm_lt_1 h).tsum_eq
lemma has_sum_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : has_sum (λn:ℕ, r ^ n) (1 - r)⁻¹ :=
has_sum_geometric_of_norm_lt_1 h
lemma summable_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : summable (λn:ℕ, r ^ n) :=
summable_geometric_of_norm_lt_1 h
lemma tsum_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : (∑'n:ℕ, r ^ n) = (1 - r)⁻¹ :=
tsum_geometric_of_norm_lt_1 h
/-- A geometric series in a normed field is summable iff the norm of the common ratio is less than
one. -/
@[simp] lemma summable_geometric_iff_norm_lt_1 : summable (λ n : ℕ, ξ ^ n) ↔ ∥ξ∥ < 1 :=
begin
refine ⟨λ h, _, summable_geometric_of_norm_lt_1⟩,
obtain ⟨k : ℕ, hk : dist (ξ ^ k) 0 < 1⟩ :=
(h.tendsto_cofinite_zero.eventually (ball_mem_nhds _ zero_lt_one)).exists,
simp only [normed_field.norm_pow, dist_zero_right] at hk,
rw [← one_pow k] at hk,
exact lt_of_pow_lt_pow _ zero_le_one hk
end
end geometric
/-!
### Sequences with geometrically decaying distance in metric spaces
In this paragraph, we discuss sequences in metric spaces or emetric spaces for which the distance
between two consecutive terms decays geometrically. We show that such sequences are Cauchy
sequences, and bound their distances to the limit. We also discuss series with geometrically
decaying terms.
-/
section edist_le_geometric
variables [emetric_space α] (r C : ennreal) (hr : r < 1) (hC : C ≠ ⊤) {f : ℕ → α}
(hu : ∀n, edist (f n) (f (n+1)) ≤ C * r^n)
include hr hC hu
/-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, `C ≠ ∞`, `r < 1`,
then `f` is a Cauchy sequence.-/
lemma cauchy_seq_of_edist_le_geometric : cauchy_seq f :=
begin
refine cauchy_seq_of_edist_le_of_tsum_ne_top _ hu _,
rw [ennreal.tsum_mul_left, ennreal.tsum_geometric],
refine ennreal.mul_ne_top hC (ennreal.inv_ne_top.2 _),
exact ne_of_gt (ennreal.zero_lt_sub_iff_lt.2 hr)
end
omit hr hC
/-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from
`f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/
lemma edist_le_of_edist_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) :
edist (f n) a ≤ (C * r^n) / (1 - r) :=
begin
convert edist_le_tsum_of_edist_le_of_tendsto _ hu ha _,
simp only [pow_add, ennreal.tsum_mul_left, ennreal.tsum_geometric, ennreal.div_def, mul_assoc]
end
/-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from
`f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/
lemma edist_le_of_edist_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) :
edist (f 0) a ≤ C / (1 - r) :=
by simpa only [pow_zero, mul_one] using edist_le_of_edist_le_geometric_of_tendsto r C hu ha 0
end edist_le_geometric
section edist_le_geometric_two
variables [emetric_space α] (C : ennreal) (hC : C ≠ ⊤) {f : ℕ → α}
(hu : ∀n, edist (f n) (f (n+1)) ≤ C / 2^n) {a : α} (ha : tendsto f at_top (𝓝 a))
include hC hu
/-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then `f` is a Cauchy sequence.-/
lemma cauchy_seq_of_edist_le_geometric_two : cauchy_seq f :=
begin
simp only [ennreal.div_def, ennreal.inv_pow] at hu,
refine cauchy_seq_of_edist_le_geometric 2⁻¹ C _ hC hu,
simp [ennreal.one_lt_two]
end
omit hC
include ha
/-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from
`f n` to the limit of `f` is bounded above by `2 * C * 2^-n`. -/
lemma edist_le_of_edist_le_geometric_two_of_tendsto (n : ℕ) :
edist (f n) a ≤ 2 * C / 2^n :=
begin
simp only [ennreal.div_def, ennreal.inv_pow] at hu,
rw [ennreal.div_def, mul_assoc, mul_comm, ennreal.inv_pow],
convert edist_le_of_edist_le_geometric_of_tendsto 2⁻¹ C hu ha n,
rw [ennreal.one_sub_inv_two, ennreal.inv_inv]
end
/-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from
`f 0` to the limit of `f` is bounded above by `2 * C`. -/
lemma edist_le_of_edist_le_geometric_two_of_tendsto₀: edist (f 0) a ≤ 2 * C :=
by simpa only [pow_zero, ennreal.div_def, ennreal.inv_one, mul_one]
using edist_le_of_edist_le_geometric_two_of_tendsto C hu ha 0
end edist_le_geometric_two
section le_geometric
variables [metric_space α] {r C : ℝ} (hr : r < 1) {f : ℕ → α}
(hu : ∀n, dist (f n) (f (n+1)) ≤ C * r^n)
include hr hu
lemma aux_has_sum_of_le_geometric : has_sum (λ n : ℕ, C * r^n) (C / (1 - r)) :=
begin
rcases sign_cases_of_C_mul_pow_nonneg (λ n, dist_nonneg.trans (hu n)) with rfl | ⟨C₀, r₀⟩,
{ simp [has_sum_zero] },
{ refine has_sum.mul_left C _,
simpa using has_sum_geometric_of_lt_1 r₀ hr }
end
variables (r C)
/-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then `f` is a Cauchy sequence.
Note that this lemma does not assume `0 ≤ C` or `0 ≤ r`. -/
lemma cauchy_seq_of_le_geometric : cauchy_seq f :=
cauchy_seq_of_dist_le_of_summable _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩
/-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from
`f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/
lemma dist_le_of_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) :
dist (f 0) a ≤ C / (1 - r) :=
(aux_has_sum_of_le_geometric hr hu).tsum_eq ▸
dist_le_tsum_of_dist_le_of_tendsto₀ _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩ ha
/-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from
`f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/
lemma dist_le_of_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) :
dist (f n) a ≤ (C * r^n) / (1 - r) :=
begin
have := aux_has_sum_of_le_geometric hr hu,
convert dist_le_tsum_of_dist_le_of_tendsto _ hu ⟨_, this⟩ ha n,
simp only [pow_add, mul_left_comm C, mul_div_right_comm],
rw [mul_comm],
exact (this.mul_left _).tsum_eq.symm
end
omit hr hu
variable (hu₂ : ∀ n, dist (f n) (f (n+1)) ≤ (C / 2) / 2^n)
/-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then `f` is a Cauchy sequence. -/
lemma cauchy_seq_of_le_geometric_two : cauchy_seq f :=
cauchy_seq_of_dist_le_of_summable _ hu₂ $ ⟨_, has_sum_geometric_two' C⟩
/-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from
`f 0` to the limit of `f` is bounded above by `C`. -/
lemma dist_le_of_le_geometric_two_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) :
dist (f 0) a ≤ C :=
(tsum_geometric_two' C) ▸ dist_le_tsum_of_dist_le_of_tendsto₀ _ hu₂ (summable_geometric_two' C) ha
include hu₂
/-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from
`f n` to the limit of `f` is bounded above by `C / 2^n`. -/
lemma dist_le_of_le_geometric_two_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) :
dist (f n) a ≤ C / 2^n :=
begin
convert dist_le_tsum_of_dist_le_of_tendsto _ hu₂ (summable_geometric_two' C) ha n,
simp only [add_comm n, pow_add, (div_div_eq_div_mul _ _ _).symm],
symmetry,
exact ((has_sum_geometric_two' C).mul_right _).tsum_eq
end
end le_geometric
section summable_le_geometric
variables [normed_group α] {r C : ℝ} {f : ℕ → α}
lemma dist_partial_sum_le_of_le_geometric (hf : ∀n, ∥f n∥ ≤ C * r^n) (n : ℕ) :
dist (∑ i in range n, f i) (∑ i in range (n+1), f i) ≤ C * r ^ n :=
begin
rw [sum_range_succ, dist_eq_norm, ← norm_neg],
convert hf n,
rw [neg_sub, add_sub_cancel]
end
/-- If `∥f n∥ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` form a
Cauchy sequence. This lemma does not assume `0 ≤ r` or `0 ≤ C`. -/
lemma cauchy_seq_finset_of_geometric_bound (hr : r < 1) (hf : ∀n, ∥f n∥ ≤ C * r^n) :
cauchy_seq (λ s : finset (ℕ), ∑ x in s, f x) :=
cauchy_seq_finset_of_norm_bounded _
(aux_has_sum_of_le_geometric hr (dist_partial_sum_le_of_le_geometric hf)).summable hf
/-- If `∥f n∥ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` are within
distance `C * r ^ n / (1 - r)` of the sum of the series. This lemma does not assume `0 ≤ r` or
`0 ≤ C`. -/
lemma norm_sub_le_of_geometric_bound_of_has_sum (hr : r < 1) (hf : ∀n, ∥f n∥ ≤ C * r^n)
{a : α} (ha : has_sum f a) (n : ℕ) :
∥(∑ x in finset.range n, f x) - a∥ ≤ (C * r ^ n) / (1 - r) :=
begin
rw ← dist_eq_norm,
apply dist_le_of_le_geometric_of_tendsto r C hr (dist_partial_sum_le_of_le_geometric hf),
exact ha.tendsto_sum_nat
end
end summable_le_geometric
section normed_ring_geometric
variables {R : Type*} [normed_ring R] [complete_space R]
open normed_space
/-- A geometric series in a complete normed ring is summable.
Proved above (same name, different namespace) for not-necessarily-complete normed fields. -/
lemma normed_ring.summable_geometric_of_norm_lt_1
(x : R) (h : ∥x∥ < 1) : summable (λ (n:ℕ), x ^ n) :=
begin
have h1 : summable (λ (n:ℕ), ∥x∥ ^ n) := summable_geometric_of_lt_1 (norm_nonneg _) h,
refine summable_of_norm_bounded_eventually _ h1 _,
rw nat.cofinite_eq_at_top,
exact eventually_norm_pow_le x,
end
/-- Bound for the sum of a geometric series in a normed ring. This formula does not assume that the
normed ring satisfies the axiom `∥1∥ = 1`. -/
lemma normed_ring.tsum_geometric_of_norm_lt_1
(x : R) (h : ∥x∥ < 1) : ∥(∑' (n:ℕ), x ^ n)∥ ≤ ∥(1:R)∥ - 1 + (1 - ∥x∥)⁻¹ :=
begin
rw tsum_eq_zero_add (normed_ring.summable_geometric_of_norm_lt_1 x h),
simp only [pow_zero],
refine le_trans (norm_add_le _ _) _,
have : ∥(∑' (b : ℕ), (λ n, x ^ (n + 1)) b)∥ ≤ (1 - ∥x∥)⁻¹ - 1,
{ refine tsum_of_norm_bounded _ (λ b, norm_pow_le' _ (nat.succ_pos b)),
convert (has_sum_nat_add_iff' 1).mpr (has_sum_geometric_of_lt_1 (norm_nonneg x) h),
simp },
linarith
end
lemma geom_series_mul_neg (x : R) (h : ∥x∥ < 1) :
(∑' (i:ℕ), x ^ i) * (1 - x) = 1 :=
begin
have := ((normed_ring.summable_geometric_of_norm_lt_1 x h).has_sum.mul_right (1 - x)),
refine tendsto_nhds_unique this.tendsto_sum_nat _,
have : tendsto (λ (n : ℕ), 1 - x ^ n) at_top (𝓝 1),
{ simpa using tendsto_const_nhds.sub (tendsto_pow_at_top_nhds_0_of_norm_lt_1 h) },
convert ← this,
ext n,
rw [←geom_sum_mul_neg, geom_series_def, finset.sum_mul],
end
lemma mul_neg_geom_series (x : R) (h : ∥x∥ < 1) :
(1 - x) * (∑' (i:ℕ), x ^ i) = 1 :=
begin
have := (normed_ring.summable_geometric_of_norm_lt_1 x h).has_sum.mul_left (1 - x),
refine tendsto_nhds_unique this.tendsto_sum_nat _,
have : tendsto (λ (n : ℕ), 1 - x ^ n) at_top (nhds 1),
{ simpa using tendsto_const_nhds.sub
(tendsto_pow_at_top_nhds_0_of_norm_lt_1 h) },
convert ← this,
ext n,
rw [←mul_neg_geom_sum, geom_series_def, finset.mul_sum]
end
end normed_ring_geometric
/-! ### Positive sequences with small sums on encodable types -/
/-- For any positive `ε`, define on an encodable type a positive sequence with sum less than `ε` -/
def pos_sum_of_encodable {ε : ℝ} (hε : 0 < ε)
(ι) [encodable ι] : {ε' : ι → ℝ // (∀ i, 0 < ε' i) ∧ ∃ c, has_sum ε' c ∧ c ≤ ε} :=
begin
let f := λ n, (ε / 2) / 2 ^ n,
have hf : has_sum f ε := has_sum_geometric_two' _,
have f0 : ∀ n, 0 < f n := λ n, div_pos (half_pos hε) (pow_pos zero_lt_two _),
refine ⟨f ∘ encodable.encode, λ i, f0 _, _⟩,
rcases hf.summable.comp_injective (@encodable.encode_injective ι _) with ⟨c, hg⟩,
refine ⟨c, hg, has_sum_le_inj _ (@encodable.encode_injective ι _) _ _ hg hf⟩,
{ assume i _, exact le_of_lt (f0 _) },
{ assume n, exact le_refl _ }
end
namespace nnreal
theorem exists_pos_sum_of_encodable {ε : ℝ≥0} (hε : 0 < ε) (ι) [encodable ι] :
∃ ε' : ι → ℝ≥0, (∀ i, 0 < ε' i) ∧ ∃c, has_sum ε' c ∧ c < ε :=
let ⟨a, a0, aε⟩ := exists_between hε in
let ⟨ε', hε', c, hc, hcε⟩ := pos_sum_of_encodable a0 ι in
⟨ λi, ⟨ε' i, le_of_lt $ hε' i⟩, assume i, nnreal.coe_lt_coe.2 $ hε' i,
⟨c, has_sum_le (assume i, le_of_lt $ hε' i) has_sum_zero hc ⟩, nnreal.has_sum_coe.1 hc,
lt_of_le_of_lt (nnreal.coe_le_coe.1 hcε) aε ⟩
end nnreal
namespace ennreal
theorem exists_pos_sum_of_encodable {ε : ennreal} (hε : 0 < ε) (ι) [encodable ι] :
∃ ε' : ι → ℝ≥0, (∀ i, 0 < ε' i) ∧ (∑' i, (ε' i : ennreal)) < ε :=
begin
rcases exists_between hε with ⟨r, h0r, hrε⟩,
rcases lt_iff_exists_coe.1 hrε with ⟨x, rfl, hx⟩,
rcases nnreal.exists_pos_sum_of_encodable (coe_lt_coe.1 h0r) ι with ⟨ε', hp, c, hc, hcr⟩,
exact ⟨ε', hp, (ennreal.tsum_coe_eq hc).symm ▸ lt_trans (coe_lt_coe.2 hcr) hrε⟩
end
end ennreal
/-!
### Factorial
-/
lemma factorial_tendsto_at_top : tendsto nat.factorial at_top at_top :=
tendsto_at_top_at_top_of_monotone nat.monotone_factorial (λ n, ⟨n, n.self_le_factorial⟩)
lemma tendsto_factorial_div_pow_self_at_top : tendsto (λ n, n! / n^n : ℕ → ℝ) at_top (𝓝 0) :=
tendsto_of_tendsto_of_tendsto_of_le_of_le'
tendsto_const_nhds
(tendsto_const_div_at_top_nhds_0_nat 1)
(eventually_of_forall $ λ n, div_nonneg (by exact_mod_cast n.factorial_pos.le)
(pow_nonneg (by exact_mod_cast n.zero_le) _))
begin
refine (eventually_gt_at_top 0).mono (λ n hn, _),
rcases nat.exists_eq_succ_of_ne_zero hn.ne.symm with ⟨k, rfl⟩,
rw [← prod_range_add_one_eq_factorial, pow_eq_prod_const, div_eq_mul_inv, ← inv_eq_one_div,
prod_nat_cast, nat.cast_succ, ← prod_inv_distrib', ← prod_mul_distrib,
finset.prod_range_succ'],
simp only [prod_range_succ', one_mul, nat.cast_add, zero_add, nat.cast_one],
refine mul_le_of_le_one_left (inv_nonneg.mpr $ by exact_mod_cast hn.le) (prod_le_one _ _);
intros x hx; rw finset.mem_range at hx,
{ refine mul_nonneg _ (inv_nonneg.mpr _); norm_cast; linarith },
{ refine (div_le_one $ by exact_mod_cast hn).mpr _, norm_cast, linarith }
end
|
af37191c29a3c4e20a01334cb9ecdb6462db8cee | 367134ba5a65885e863bdc4507601606690974c1 | /src/linear_algebra/matrix.lean | 9e675d7bbc1f902ef38aeedf577fb3c2ba3b13e4 | [
"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 | 58,693 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl, Patrick Massot, Casper Putz
-/
import linear_algebra.finite_dimensional
import linear_algebra.nonsingular_inverse
import linear_algebra.multilinear
import linear_algebra.dual
/-!
# Linear maps and matrices
This file defines the maps to send matrices to a linear map,
and to send linear maps between modules with a finite bases
to matrices. This defines a linear equivalence between linear maps
between finite-dimensional vector spaces and matrices indexed by
the respective bases.
It also defines the trace of an endomorphism, and the determinant of a family of vectors with
respect to some basis.
Some results are proved about the linear map corresponding to a
diagonal matrix (`range`, `ker` and `rank`).
Some results are proved for determinants of block triangular matrices.
## Main definitions
In the list below, and in all this file, `R` is a commutative ring (semiring
is sometimes enough), `M` and its variations are `R`-modules, `ι`, `κ`, `n` and `m` are finite
types used for indexing.
* `linear_map.to_matrix`: given bases `v₁ : ι → M₁` and `v₂ : κ → M₂`,
the `R`-linear equivalence from `M₁ →ₗ[R] M₂` to `matrix κ ι R`
* `matrix.to_lin`: the inverse of `linear_map.to_matrix`
* `linear_map.to_matrix'`: the `R`-linear equivalence from `(n → R) →ₗ[R] (m → R)`
to `matrix n m R` (with the standard basis on `n → R` and `m → R`)
* `matrix.to_lin'`: the inverse of `linear_map.to_matrix'`
* `alg_equiv_matrix`: given a basis indexed by `n`, the `R`-algebra equivalence between
`R`-endomorphisms of `M` and `matrix n n R`
* `matrix.trace`: the trace of a square matrix
* `linear_map.trace`: the trace of an endomorphism
* `is_basis.to_matrix`: the matrix whose columns are a given family of vectors in a given basis
* `is_basis.to_matrix_equiv`: given a basis, the linear equivalence between families of vectors
and matrices arising from `is_basis.to_matrix`
* `is_basis.det`: the determinant of a family of vectors with respect to a basis, as a multilinear
map
## Tags
linear_map, matrix, linear_equiv, diagonal, det, trace
-/
noncomputable theory
open linear_map matrix set submodule
open_locale big_operators
open_locale matrix
universes u v w
section to_matrix'
variables {R : Type*} [comm_ring R]
variables {l m n : Type*} [fintype l] [fintype m] [fintype n]
instance [decidable_eq m] [decidable_eq n] (R) [fintype R] : fintype (matrix m n R) :=
by unfold matrix; apply_instance
/-- `matrix.mul_vec M` is a linear map. -/
def matrix.mul_vec_lin (M : matrix m n R) : (n → R) →ₗ[R] (m → R) :=
{ to_fun := M.mul_vec,
map_add' := λ v w, funext (λ i, dot_product_add _ _ _),
map_smul' := λ c v, funext (λ i, dot_product_smul _ _ _) }
@[simp] lemma matrix.mul_vec_lin_apply (M : matrix m n R) (v : n → R) :
matrix.mul_vec_lin M v = M.mul_vec v := rfl
variables [decidable_eq n]
@[simp] lemma matrix.mul_vec_std_basis (M : matrix m n R) (i j) :
M.mul_vec (std_basis R (λ _, R) j 1) i = M i j :=
begin
have : (∑ j', M i j' * if j = j' then 1 else 0) = M i j,
{ simp_rw [mul_boole, finset.sum_ite_eq, finset.mem_univ, if_true] },
convert this,
ext,
split_ifs with h; simp only [std_basis_apply],
{ rw [h, function.update_same] },
{ rw [function.update_noteq (ne.symm h), pi.zero_apply] }
end
/-- Linear maps `(n → R) →ₗ[R] (m → R)` are linearly equivalent to `matrix m n R`. -/
def linear_map.to_matrix' : ((n → R) →ₗ[R] (m → R)) ≃ₗ[R] matrix m n R :=
{ to_fun := λ f i j, f (std_basis R (λ _, R) j 1) i,
inv_fun := matrix.mul_vec_lin,
right_inv := λ M, by { ext i j, simp only [matrix.mul_vec_std_basis, matrix.mul_vec_lin_apply] },
left_inv := λ f, begin
apply (pi.is_basis_fun R n).ext,
intro j, ext i,
simp only [matrix.mul_vec_std_basis, matrix.mul_vec_lin_apply]
end,
map_add' := λ f g, by { ext i j, simp only [pi.add_apply, linear_map.add_apply] },
map_smul' := λ c f, by { ext i j, simp only [pi.smul_apply, linear_map.smul_apply] } }
/-- A `matrix m n R` is linearly equivalent to a linear map `(n → R) →ₗ[R] (m → R)`. -/
def matrix.to_lin' : matrix m n R ≃ₗ[R] ((n → R) →ₗ[R] (m → R)) :=
linear_map.to_matrix'.symm
@[simp] lemma linear_map.to_matrix'_symm :
(linear_map.to_matrix'.symm : matrix m n R ≃ₗ[R] _) = matrix.to_lin' :=
rfl
@[simp] lemma matrix.to_lin'_symm :
(matrix.to_lin'.symm : ((n → R) →ₗ[R] (m → R)) ≃ₗ[R] _) = linear_map.to_matrix' :=
rfl
@[simp] lemma linear_map.to_matrix'_to_lin' (M : matrix m n R) :
linear_map.to_matrix' (matrix.to_lin' M) = M :=
linear_map.to_matrix'.apply_symm_apply M
@[simp] lemma matrix.to_lin'_to_matrix' (f : (n → R) →ₗ[R] (m → R)) :
matrix.to_lin' (linear_map.to_matrix' f) = f :=
matrix.to_lin'.apply_symm_apply f
@[simp] lemma linear_map.to_matrix'_apply (f : (n → R) →ₗ[R] (m → R)) (i j) :
linear_map.to_matrix' f i j = f (λ j', if j' = j then 1 else 0) i :=
begin
simp only [linear_map.to_matrix', linear_equiv.coe_mk],
congr,
ext j',
split_ifs with h,
{ rw [h, std_basis_same] },
apply std_basis_ne _ _ _ _ h
end
@[simp] lemma matrix.to_lin'_apply (M : matrix m n R) (v : n → R) :
matrix.to_lin' M v = M.mul_vec v := rfl
@[simp] lemma matrix.to_lin'_one :
matrix.to_lin' (1 : matrix n n R) = id :=
by { ext, simp [linear_map.one_apply, std_basis_apply] }
@[simp] lemma linear_map.to_matrix'_id :
(linear_map.to_matrix' (linear_map.id : (n → R) →ₗ[R] (n → R))) = 1 :=
by { ext, rw [matrix.one_apply, linear_map.to_matrix'_apply, id_apply] }
@[simp] lemma matrix.to_lin'_mul [decidable_eq m] (M : matrix l m R) (N : matrix m n R) :
matrix.to_lin' (M ⬝ N) = (matrix.to_lin' M).comp (matrix.to_lin' N) :=
by { ext, simp }
lemma linear_map.to_matrix'_comp [decidable_eq l]
(f : (n → R) →ₗ[R] (m → R)) (g : (l → R) →ₗ[R] (n → R)) :
(f.comp g).to_matrix' = f.to_matrix' ⬝ g.to_matrix' :=
suffices (f.comp g) = (f.to_matrix' ⬝ g.to_matrix').to_lin',
by rw [this, linear_map.to_matrix'_to_lin'],
by rw [matrix.to_lin'_mul, matrix.to_lin'_to_matrix', matrix.to_lin'_to_matrix']
lemma linear_map.to_matrix'_mul [decidable_eq m]
(f g : (m → R) →ₗ[R] (m → R)) :
(f * g).to_matrix' = f.to_matrix' ⬝ g.to_matrix' :=
linear_map.to_matrix'_comp f g
/-- Linear maps `(n → R) →ₗ[R] (n → R)` are algebra equivalent to `matrix n n R`. -/
def linear_map.to_matrix_alg_equiv' : ((n → R) →ₗ[R] (n → R)) ≃ₐ[R] matrix n n R :=
alg_equiv.of_linear_equiv linear_map.to_matrix' linear_map.to_matrix'_mul
(by simp [module.algebra_map_End_eq_smul_id])
/-- A `matrix n n R` is algebra equivalent to a linear map `(n → R) →ₗ[R] (n → R)`. -/
def matrix.to_lin_alg_equiv' : matrix n n R ≃ₐ[R] ((n → R) →ₗ[R] (n → R)) :=
linear_map.to_matrix_alg_equiv'.symm
@[simp] lemma linear_map.to_matrix_alg_equiv'_symm :
(linear_map.to_matrix_alg_equiv'.symm : matrix n n R ≃ₐ[R] _) = matrix.to_lin_alg_equiv' :=
rfl
@[simp] lemma matrix.to_lin_alg_equiv'_symm :
(matrix.to_lin_alg_equiv'.symm : ((n → R) →ₗ[R] (n → R)) ≃ₐ[R] _) =
linear_map.to_matrix_alg_equiv' :=
rfl
@[simp] lemma linear_map.to_matrix_alg_equiv'_to_lin_alg_equiv' (M : matrix n n R) :
linear_map.to_matrix_alg_equiv' (matrix.to_lin_alg_equiv' M) = M :=
linear_map.to_matrix_alg_equiv'.apply_symm_apply M
@[simp] lemma matrix.to_lin_alg_equiv'_to_matrix_alg_equiv' (f : (n → R) →ₗ[R] (n → R)) :
matrix.to_lin_alg_equiv' (linear_map.to_matrix_alg_equiv' f) = f :=
matrix.to_lin_alg_equiv'.apply_symm_apply f
@[simp] lemma linear_map.to_matrix_alg_equiv'_apply (f : (n → R) →ₗ[R] (n → R)) (i j) :
linear_map.to_matrix_alg_equiv' f i j = f (λ j', if j' = j then 1 else 0) i :=
by simp [linear_map.to_matrix_alg_equiv']
@[simp] lemma matrix.to_lin_alg_equiv'_apply (M : matrix n n R) (v : n → R) :
matrix.to_lin_alg_equiv' M v = M.mul_vec v := rfl
@[simp] lemma matrix.to_lin_alg_equiv'_one :
matrix.to_lin_alg_equiv' (1 : matrix n n R) = id :=
by { ext, simp [matrix.one_apply, std_basis_apply] }
@[simp] lemma linear_map.to_matrix_alg_equiv'_id :
(linear_map.to_matrix_alg_equiv' (linear_map.id : (n → R) →ₗ[R] (n → R))) = 1 :=
by { ext, rw [matrix.one_apply, linear_map.to_matrix_alg_equiv'_apply, id_apply] }
@[simp] lemma matrix.to_lin_alg_equiv'_mul (M N : matrix n n R) :
matrix.to_lin_alg_equiv' (M ⬝ N) =
(matrix.to_lin_alg_equiv' M).comp (matrix.to_lin_alg_equiv' N) :=
by { ext, simp }
lemma linear_map.to_matrix_alg_equiv'_comp (f g : (n → R) →ₗ[R] (n → R)) :
(f.comp g).to_matrix_alg_equiv' = f.to_matrix_alg_equiv' ⬝ g.to_matrix_alg_equiv' :=
suffices (f.comp g) = (f.to_matrix_alg_equiv' ⬝ g.to_matrix_alg_equiv').to_lin_alg_equiv',
by rw [this, linear_map.to_matrix_alg_equiv'_to_lin_alg_equiv'],
by rw [matrix.to_lin_alg_equiv'_mul, matrix.to_lin_alg_equiv'_to_matrix_alg_equiv',
matrix.to_lin_alg_equiv'_to_matrix_alg_equiv']
lemma linear_map.to_matrix_alg_equiv'_mul
(f g : (n → R) →ₗ[R] (n → R)) :
(f * g).to_matrix_alg_equiv' = f.to_matrix_alg_equiv' ⬝ g.to_matrix_alg_equiv' :=
linear_map.to_matrix_alg_equiv'_comp f g
end to_matrix'
section to_matrix
variables {R : Type*} [comm_ring R]
variables {l m n : Type*} [fintype l] [fintype m] [fintype n] [decidable_eq n]
variables {M₁ M₂ : Type*} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂]
variables {v₁ : n → M₁} (hv₁ : is_basis R v₁) {v₂ : m → M₂} (hv₂ : is_basis R v₂)
/-- Given bases of two modules `M₁` and `M₂` over a commutative ring `R`, we get a linear
equivalence between linear maps `M₁ →ₗ M₂` and matrices over `R` indexed by the bases. -/
def linear_map.to_matrix : (M₁ →ₗ[R] M₂) ≃ₗ[R] matrix m n R :=
linear_equiv.trans (linear_equiv.arrow_congr hv₁.equiv_fun hv₂.equiv_fun) linear_map.to_matrix'
/-- Given bases of two modules `M₁` and `M₂` over a commutative ring `R`, we get a linear
equivalence between matrices over `R` indexed by the bases and linear maps `M₁ →ₗ M₂`. -/
def matrix.to_lin : matrix m n R ≃ₗ[R] (M₁ →ₗ[R] M₂) :=
(linear_map.to_matrix hv₁ hv₂).symm
@[simp] lemma linear_map.to_matrix_symm :
(linear_map.to_matrix hv₁ hv₂).symm = matrix.to_lin hv₁ hv₂ :=
rfl
@[simp] lemma matrix.to_lin_symm :
(matrix.to_lin hv₁ hv₂).symm = linear_map.to_matrix hv₁ hv₂ :=
rfl
@[simp] lemma matrix.to_lin_to_matrix (f : M₁ →ₗ[R] M₂) :
matrix.to_lin hv₁ hv₂ (linear_map.to_matrix hv₁ hv₂ f) = f :=
by rw [← matrix.to_lin_symm, linear_equiv.apply_symm_apply]
@[simp] lemma linear_map.to_matrix_to_lin (M : matrix m n R) :
linear_map.to_matrix hv₁ hv₂ (matrix.to_lin hv₁ hv₂ M) = M :=
by rw [← matrix.to_lin_symm, linear_equiv.symm_apply_apply]
lemma linear_map.to_matrix_apply (f : M₁ →ₗ[R] M₂) (i : m) (j : n) :
linear_map.to_matrix hv₁ hv₂ f i j = hv₂.equiv_fun (f (v₁ j)) i :=
begin
rw [linear_map.to_matrix, linear_equiv.trans_apply, linear_map.to_matrix'_apply,
linear_equiv.arrow_congr_apply, is_basis.equiv_fun_symm_apply, finset.sum_eq_single j,
if_pos rfl, one_smul],
{ intros j' _ hj',
rw [if_neg hj', zero_smul] },
{ intro hj,
have := finset.mem_univ j,
contradiction }
end
lemma linear_map.to_matrix_transpose_apply (f : M₁ →ₗ[R] M₂) (j : n) :
(linear_map.to_matrix hv₁ hv₂ f)ᵀ j = hv₂.equiv_fun (f (v₁ j)) :=
funext $ λ i, f.to_matrix_apply _ _ i j
lemma linear_map.to_matrix_apply' (f : M₁ →ₗ[R] M₂) (i : m) (j : n) :
linear_map.to_matrix hv₁ hv₂ f i j = hv₂.repr (f (v₁ j)) i :=
linear_map.to_matrix_apply hv₁ hv₂ f i j
lemma linear_map.to_matrix_transpose_apply' (f : M₁ →ₗ[R] M₂) (j : n) :
(linear_map.to_matrix hv₁ hv₂ f)ᵀ j = hv₂.repr (f (v₁ j)) :=
linear_map.to_matrix_transpose_apply hv₁ hv₂ f j
lemma matrix.to_lin_apply (M : matrix m n R) (v : M₁) :
matrix.to_lin hv₁ hv₂ M v = ∑ j, M.mul_vec (hv₁.equiv_fun v) j • v₂ j :=
show hv₂.equiv_fun.symm (matrix.to_lin' M (hv₁.equiv_fun v)) = _,
by rw [matrix.to_lin'_apply, hv₂.equiv_fun_symm_apply]
@[simp] lemma matrix.to_lin_self (M : matrix m n R) (i : n) :
matrix.to_lin hv₁ hv₂ M (v₁ i) = ∑ j, M j i • v₂ j :=
by simp only [matrix.to_lin_apply, matrix.mul_vec, dot_product, hv₁.equiv_fun_self, mul_boole,
finset.sum_ite_eq, finset.mem_univ, if_true]
/-- This will be a special case of `linear_map.to_matrix_id_eq_basis_to_matrix`. -/
lemma linear_map.to_matrix_id : linear_map.to_matrix hv₁ hv₁ id = 1 :=
begin
ext i j,
simp [linear_map.to_matrix_apply, is_basis.equiv_fun, matrix.one_apply, finsupp.single, eq_comm]
end
@[simp]
lemma matrix.to_lin_one : matrix.to_lin hv₁ hv₁ 1 = id :=
by rw [← linear_map.to_matrix_id hv₁, matrix.to_lin_to_matrix]
theorem linear_map.to_matrix_range [decidable_eq M₁] [decidable_eq M₂]
(f : M₁ →ₗ[R] M₂) (k : m) (i : n) :
linear_map.to_matrix hv₁.range hv₂.range f ⟨v₂ k, mem_range_self k⟩ ⟨v₁ i, mem_range_self i⟩ =
linear_map.to_matrix hv₁ hv₂ f k i :=
by simp_rw [linear_map.to_matrix_apply, subtype.coe_mk, is_basis.equiv_fun_apply, hv₂.range_repr]
variables {M₃ : Type*} [add_comm_group M₃] [module R M₃] {v₃ : l → M₃} (hv₃ : is_basis R v₃)
lemma linear_map.to_matrix_comp [decidable_eq m] (f : M₂ →ₗ[R] M₃) (g : M₁ →ₗ[R] M₂) :
linear_map.to_matrix hv₁ hv₃ (f.comp g) =
linear_map.to_matrix hv₂ hv₃ f ⬝ linear_map.to_matrix hv₁ hv₂ g :=
by simp_rw [linear_map.to_matrix, linear_equiv.trans_apply,
linear_equiv.arrow_congr_comp _ hv₂.equiv_fun, linear_map.to_matrix'_comp]
lemma linear_map.to_matrix_mul (f g : M₁ →ₗ[R] M₁) :
linear_map.to_matrix hv₁ hv₁ (f * g) =
linear_map.to_matrix hv₁ hv₁ f ⬝ linear_map.to_matrix hv₁ hv₁ g :=
by { rw [show (@has_mul.mul (M₁ →ₗ[R] M₁) _) = linear_map.comp, from rfl,
linear_map.to_matrix_comp hv₁ hv₁ hv₁ f g] }
lemma matrix.to_lin_mul [decidable_eq m] (A : matrix l m R) (B : matrix m n R) :
matrix.to_lin hv₁ hv₃ (A ⬝ B) =
(matrix.to_lin hv₂ hv₃ A).comp (matrix.to_lin hv₁ hv₂ B) :=
begin
apply (linear_map.to_matrix hv₁ hv₃).injective,
haveI : decidable_eq l := λ _ _, classical.prop_decidable _,
rw linear_map.to_matrix_comp hv₁ hv₂ hv₃,
repeat { rw linear_map.to_matrix_to_lin },
end
/-- Given a basis of a module `M₁` over a commutative ring `R`, we get an algebra
equivalence between linear maps `M₁ →ₗ M₁` and square matrices over `R` indexed by the basis. -/
def linear_map.to_matrix_alg_equiv :
(M₁ →ₗ[R] M₁) ≃ₐ[R] matrix n n R :=
alg_equiv.of_linear_equiv (linear_map.to_matrix hv₁ hv₁) (linear_map.to_matrix_mul hv₁)
(by simp [module.algebra_map_End_eq_smul_id, linear_map.to_matrix_id])
/-- Given a basis of a module `M₁` over a commutative ring `R`, we get an algebra
equivalence between square matrices over `R` indexed by the basis and linear maps `M₁ →ₗ M₁`. -/
def matrix.to_lin_alg_equiv : matrix n n R ≃ₐ[R] (M₁ →ₗ[R] M₁) :=
(linear_map.to_matrix_alg_equiv hv₁).symm
@[simp] lemma linear_map.to_matrix_alg_equiv_symm :
(linear_map.to_matrix_alg_equiv hv₁).symm = matrix.to_lin_alg_equiv hv₁ :=
rfl
@[simp] lemma matrix.to_lin_alg_equiv_symm :
(matrix.to_lin_alg_equiv hv₁).symm = linear_map.to_matrix_alg_equiv hv₁ :=
rfl
@[simp] lemma matrix.to_lin_alg_equiv_to_matrix_alg_equiv (f : M₁ →ₗ[R] M₁) :
matrix.to_lin_alg_equiv hv₁ (linear_map.to_matrix_alg_equiv hv₁ f) = f :=
by rw [← matrix.to_lin_alg_equiv_symm, alg_equiv.apply_symm_apply]
@[simp] lemma linear_map.to_matrix_alg_equiv_to_lin_alg_equiv (M : matrix n n R) :
linear_map.to_matrix_alg_equiv hv₁ (matrix.to_lin_alg_equiv hv₁ M) = M :=
by rw [← matrix.to_lin_alg_equiv_symm, alg_equiv.symm_apply_apply]
lemma linear_map.to_matrix_alg_equiv_apply (f : M₁ →ₗ[R] M₁) (i j : n) :
linear_map.to_matrix_alg_equiv hv₁ f i j = hv₁.equiv_fun (f (v₁ j)) i :=
by simp [linear_map.to_matrix_alg_equiv, linear_map.to_matrix_apply]
lemma linear_map.to_matrix_alg_equiv_transpose_apply (f : M₁ →ₗ[R] M₁) (j : n) :
(linear_map.to_matrix_alg_equiv hv₁ f)ᵀ j = hv₁.equiv_fun (f (v₁ j)) :=
funext $ λ i, f.to_matrix_apply _ _ i j
lemma linear_map.to_matrix_alg_equiv_apply' (f : M₁ →ₗ[R] M₁) (i j : n) :
linear_map.to_matrix_alg_equiv hv₁ f i j = hv₁.repr (f (v₁ j)) i :=
linear_map.to_matrix_alg_equiv_apply hv₁ f i j
lemma linear_map.to_matrix_alg_equiv_transpose_apply' (f : M₁ →ₗ[R] M₁) (j : n) :
(linear_map.to_matrix_alg_equiv hv₁ f)ᵀ j = hv₁.repr (f (v₁ j)) :=
linear_map.to_matrix_alg_equiv_transpose_apply hv₁ f j
lemma matrix.to_lin_alg_equiv_apply (M : matrix n n R) (v : M₁) :
matrix.to_lin_alg_equiv hv₁ M v = ∑ j, M.mul_vec (hv₁.equiv_fun v) j • v₁ j :=
show hv₁.equiv_fun.symm (matrix.to_lin_alg_equiv' M (hv₁.equiv_fun v)) = _,
by rw [matrix.to_lin_alg_equiv'_apply, hv₁.equiv_fun_symm_apply]
@[simp] lemma matrix.to_lin_alg_equiv_self (M : matrix n n R) (i : n) :
matrix.to_lin_alg_equiv hv₁ M (v₁ i) = ∑ j, M j i • v₁ j :=
by simp only [matrix.to_lin_alg_equiv_apply, matrix.mul_vec, dot_product, hv₁.equiv_fun_self,
mul_boole, finset.sum_ite_eq, finset.mem_univ, if_true]
lemma linear_map.to_matrix_alg_equiv_id : linear_map.to_matrix_alg_equiv hv₁ id = 1 :=
by simp_rw [linear_map.to_matrix_alg_equiv, alg_equiv.of_linear_equiv_apply,
linear_map.to_matrix_id]
@[simp]
lemma matrix.to_lin_alg_equiv_one : matrix.to_lin_alg_equiv hv₁ 1 = id :=
by rw [← linear_map.to_matrix_alg_equiv_id hv₁, matrix.to_lin_alg_equiv_to_matrix_alg_equiv]
theorem linear_map.to_matrix_alg_equiv_range [decidable_eq M₁]
(f : M₁ →ₗ[R] M₁) (k i : n) :
linear_map.to_matrix_alg_equiv hv₁.range f ⟨v₁ k, mem_range_self k⟩ ⟨v₁ i, mem_range_self i⟩ =
linear_map.to_matrix_alg_equiv hv₁ f k i :=
by simp_rw [linear_map.to_matrix_alg_equiv_apply, subtype.coe_mk, is_basis.equiv_fun_apply,
hv₁.range_repr]
lemma linear_map.to_matrix_alg_equiv_comp (f g : M₁ →ₗ[R] M₁) :
linear_map.to_matrix_alg_equiv hv₁ (f.comp g) =
linear_map.to_matrix_alg_equiv hv₁ f ⬝ linear_map.to_matrix_alg_equiv hv₁ g :=
by simp [linear_map.to_matrix_alg_equiv, linear_map.to_matrix_comp hv₁ hv₁ hv₁ f g]
lemma linear_map.to_matrix_alg_equiv_mul (f g : M₁ →ₗ[R] M₁) :
linear_map.to_matrix_alg_equiv hv₁ (f * g) =
linear_map.to_matrix_alg_equiv hv₁ f ⬝ linear_map.to_matrix_alg_equiv hv₁ g :=
by { rw [show (@has_mul.mul (M₁ →ₗ[R] M₁) _) = linear_map.comp, from rfl,
linear_map.to_matrix_alg_equiv_comp hv₁ f g] }
lemma matrix.to_lin_alg_equiv_mul (A B : matrix n n R) :
matrix.to_lin_alg_equiv hv₁ (A ⬝ B) =
(matrix.to_lin_alg_equiv hv₁ A).comp (matrix.to_lin_alg_equiv hv₁ B) :=
by convert matrix.to_lin_mul hv₁ hv₁ hv₁ A B
end to_matrix
section is_basis_to_matrix
variables {ι ι' κ κ' : Type*} [fintype ι] [fintype ι'] [fintype κ] [fintype κ']
variables {R M : Type*} [comm_ring R] [add_comm_group M] [module R M]
open function matrix
/-- From a basis `e : ι → M` and a family of vectors `v : ι' → M`, make the matrix whose columns
are the vectors `v i` written in the basis `e`. -/
def is_basis.to_matrix {e : ι → M} (he : is_basis R e) (v : ι' → M) : matrix ι ι' R :=
λ i j, he.equiv_fun (v j) i
variables {e : ι → M} (he : is_basis R e) (v : ι' → M) (i : ι) (j : ι')
namespace is_basis
lemma to_matrix_apply : he.to_matrix v i j = he.equiv_fun (v j) i :=
rfl
lemma to_matrix_transpose_apply : (he.to_matrix v)ᵀ j = he.repr (v j) :=
funext $ (λ _, rfl)
lemma to_matrix_eq_to_matrix_constr [decidable_eq ι] (v : ι → M) :
he.to_matrix v = linear_map.to_matrix he he (he.constr v) :=
by { ext, simp [is_basis.to_matrix_apply, linear_map.to_matrix_apply] }
@[simp] lemma to_matrix_self [decidable_eq ι] : he.to_matrix e = 1 :=
begin
rw is_basis.to_matrix,
ext i j,
simp [is_basis.equiv_fun, matrix.one_apply, finsupp.single, eq_comm]
end
lemma to_matrix_update [decidable_eq ι'] (x : M) :
he.to_matrix (function.update v j x) = matrix.update_column (he.to_matrix v) j (he.repr x) :=
begin
ext i' k,
rw [is_basis.to_matrix, matrix.update_column_apply, he.to_matrix_apply],
split_ifs,
{ rw [h, update_same j x v, he.equiv_fun_apply] },
{ rw update_noteq h },
end
@[simp] lemma sum_to_matrix_smul_self : ∑ (i : ι), he.to_matrix v i j • e i = v j :=
begin
conv_rhs { rw ← he.total_repr (v j) },
rw [finsupp.total_apply, finsupp.sum_fintype],
{ refl },
simp
end
@[simp] lemma to_lin_to_matrix [decidable_eq ι'] (hv : is_basis R v) :
matrix.to_lin hv he (he.to_matrix v) = id :=
hv.ext (λ i, by rw [to_lin_self, id_apply, he.sum_to_matrix_smul_self])
/-- From a basis `e : ι → M`, build a linear equivalence between families of vectors `v : ι → M`,
and matrices, making the matrix whose columns are the vectors `v i` written in the basis `e`. -/
def to_matrix_equiv {e : ι → M} (he : is_basis R e) : (ι → M) ≃ₗ[R] matrix ι ι R :=
{ to_fun := he.to_matrix,
map_add' := λ v w, begin
ext i j,
change _ = _ + _,
simp [he.to_matrix_apply]
end,
map_smul' := begin
intros c v,
ext i j,
simp [he.to_matrix_apply]
end,
inv_fun := λ m j, ∑ i, (m i j) • e i,
left_inv := begin
intro v,
ext j,
simp [he.to_matrix_apply, he.equiv_fun_total (v j)]
end,
right_inv := begin
intros x,
ext k l,
simp [he.to_matrix_apply, he.equiv_fun.map_sum, he.equiv_fun.map_smul,
fintype.sum_apply k (λ i, x i l • he.equiv_fun (e i)),
he.equiv_fun_self]
end }
end is_basis
section mul_linear_map_to_matrix
variables {N : Type*} [add_comm_group N] [module R N]
variables {b : ι → M} {b' : ι' → M} {c : κ → N} {c' : κ' → N}
variables (hb : is_basis R b) (hb' : is_basis R b') (hc : is_basis R c) (hc' : is_basis R c')
variables (f : M →ₗ[R] N)
open linear_map
@[simp] lemma is_basis_to_matrix_mul_linear_map_to_matrix [decidable_eq ι'] :
hc.to_matrix c' ⬝ linear_map.to_matrix hb' hc' f = linear_map.to_matrix hb' hc f :=
(matrix.to_lin hb' hc).injective
(by haveI := classical.dec_eq κ';
rw [to_lin_to_matrix, to_lin_mul hb' hc' hc, to_lin_to_matrix, hc.to_lin_to_matrix, id_comp])
@[simp] lemma linear_map_to_matrix_mul_is_basis_to_matrix [decidable_eq ι] [decidable_eq ι'] :
linear_map.to_matrix hb' hc' f ⬝ hb'.to_matrix b = linear_map.to_matrix hb hc' f :=
(matrix.to_lin hb hc').injective
(by rw [to_lin_to_matrix, to_lin_mul hb hb' hc', to_lin_to_matrix, hb'.to_lin_to_matrix, comp_id])
/-- A generalization of `linear_map.to_matrix_id`. -/
@[simp] lemma linear_map.to_matrix_id_eq_basis_to_matrix [decidable_eq ι] :
linear_map.to_matrix hb hb' id = hb'.to_matrix b :=
by { haveI := classical.dec_eq ι',
rw [← is_basis_to_matrix_mul_linear_map_to_matrix hb hb', to_matrix_id, matrix.mul_one] }
/-- A generalization of `is_basis.to_matrix_self`, in the opposite direction. -/
@[simp] lemma is_basis.to_matrix_mul_to_matrix
{ι'' : Type*} [fintype ι''] {b'' : ι'' → M} (hb'' : is_basis R b'') :
hb.to_matrix b' ⬝ hb'.to_matrix b'' = hb.to_matrix b'' :=
begin
haveI := classical.dec_eq ι,
haveI := classical.dec_eq ι',
haveI := classical.dec_eq ι'',
rw [← linear_map.to_matrix_id_eq_basis_to_matrix hb' hb,
← linear_map.to_matrix_id_eq_basis_to_matrix hb'' hb',
← to_matrix_comp, id_comp, linear_map.to_matrix_id_eq_basis_to_matrix],
end
end mul_linear_map_to_matrix
end is_basis_to_matrix
open_locale matrix
section det
open linear_map matrix
variables {R : Type*} [comm_ring R]
variables {M : Type*} [add_comm_group M] [module R M]
variables {M' : Type*} [add_comm_group M'] [module R M']
variables {ι : Type*} [decidable_eq ι] [fintype ι] {v : ι → M} {v' : ι → M'}
lemma linear_equiv.is_unit_det (f : M ≃ₗ[R] M') (hv : is_basis R v) (hv' : is_basis R v') :
is_unit (linear_map.to_matrix hv hv' f).det :=
begin
apply is_unit_det_of_left_inverse,
simpa using (linear_map.to_matrix_comp hv hv' hv f.symm f).symm
end
/-- Builds a linear equivalence from a linear map whose determinant in some bases is a unit. -/
def linear_equiv.of_is_unit_det {f : M →ₗ[R] M'} {hv : is_basis R v} {hv' : is_basis R v'}
(h : is_unit (linear_map.to_matrix hv hv' f).det) : M ≃ₗ[R] M' :=
{ to_fun := f,
map_add' := f.map_add,
map_smul' := f.map_smul,
inv_fun := to_lin hv' hv (to_matrix hv hv' f)⁻¹,
left_inv := λ x,
calc to_lin hv' hv (to_matrix hv hv' f)⁻¹ (f x)
= to_lin hv hv ((to_matrix hv hv' f)⁻¹ ⬝ to_matrix hv hv' f) x :
by { rw [to_lin_mul hv hv' hv, to_lin_to_matrix, linear_map.comp_apply] }
... = x : by simp [h],
right_inv := λ x,
calc f (to_lin hv' hv (to_matrix hv hv' f)⁻¹ x)
= to_lin hv' hv' (to_matrix hv hv' f ⬝ (to_matrix hv hv' f)⁻¹) x :
by { rw [to_lin_mul hv' hv hv', linear_map.comp_apply, to_lin_to_matrix hv hv'] }
... = x : by simp [h],
}
variables {e : ι → M} (he : is_basis R e)
/-- The determinant of a family of vectors with respect to some basis, as an alternating
multilinear map. -/
def is_basis.det : alternating_map R M R ι :=
{ to_fun := λ v, det (he.to_matrix v),
map_add' := begin
intros v i x y,
simp only [he.to_matrix_update, linear_map.map_add],
apply det_update_column_add
end,
map_smul' := begin
intros u i c x,
simp only [he.to_matrix_update, algebra.id.smul_eq_mul, map_smul_of_tower],
apply det_update_column_smul
end,
map_eq_zero_of_eq' := begin
intros v i j h hij,
rw [←function.update_eq_self i v, h, ←det_transpose, he.to_matrix_update,
←update_row_transpose, ←he.to_matrix_transpose_apply],
apply det_zero_of_row_eq hij,
rw [update_row_ne hij.symm, update_row_self],
end }
lemma is_basis.det_apply (v : ι → M) : he.det v = det (he.to_matrix v) := rfl
lemma is_basis.det_self : he.det e = 1 :=
by simp [he.det_apply]
lemma is_basis.iff_det {v : ι → M} : is_basis R v ↔ is_unit (he.det v) :=
begin
split,
{ intro hv,
suffices :
is_unit (linear_map.to_matrix he he (linear_equiv_of_is_basis he hv $ equiv.refl ι)).det,
{ rw [is_basis.det_apply, is_basis.to_matrix_eq_to_matrix_constr],
exact this },
apply linear_equiv.is_unit_det },
{ intro h,
rw [is_basis.det_apply, is_basis.to_matrix_eq_to_matrix_constr] at h,
convert linear_equiv.is_basis he (linear_equiv.of_is_unit_det h),
ext i,
exact (constr_basis he).symm },
end
end det
section transpose
variables {K V₁ V₂ ι₁ ι₂ : Type*} [field K]
[add_comm_group V₁] [vector_space K V₁]
[add_comm_group V₂] [vector_space K V₂]
[fintype ι₁] [fintype ι₂] [decidable_eq ι₁] [decidable_eq ι₂]
{B₁ : ι₁ → V₁} (h₁ : is_basis K B₁)
{B₂ : ι₂ → V₂} (h₂ : is_basis K B₂)
@[simp] lemma linear_map.to_matrix_transpose (u : V₁ →ₗ[K] V₂) :
linear_map.to_matrix h₂.dual_basis_is_basis h₁.dual_basis_is_basis (module.dual.transpose u) =
(linear_map.to_matrix h₁ h₂ u)ᵀ :=
begin
ext i j,
simp only [linear_map.to_matrix_apply, module.dual.transpose_apply, h₁.dual_basis_equiv_fun,
h₂.dual_basis_apply, matrix.transpose_apply, linear_map.comp_apply]
end
lemma linear_map.to_matrix_symm_transpose (M : matrix ι₁ ι₂ K) :
(linear_map.to_matrix h₁.dual_basis_is_basis h₂.dual_basis_is_basis).symm Mᵀ =
module.dual.transpose (matrix.to_lin h₂ h₁ M) :=
begin
apply (linear_map.to_matrix h₁.dual_basis_is_basis h₂.dual_basis_is_basis).injective,
rw [linear_equiv.apply_symm_apply],
ext i j,
simp only [linear_map.to_matrix_apply, module.dual.transpose_apply, h₂.dual_basis_equiv_fun,
h₁.dual_basis_apply, matrix.transpose_apply, linear_map.comp_apply, if_true,
matrix.to_lin_apply, linear_equiv.map_smul, mul_boole, algebra.id.smul_eq_mul,
linear_equiv.map_sum, is_basis.equiv_fun_self, fintype.sum_apply, finset.sum_ite_eq',
finset.sum_ite_eq, is_basis.equiv_fun_symm_apply, pi.smul_apply, matrix.to_lin_apply,
matrix.mul_vec, matrix.dot_product, is_basis.equiv_fun_self, finset.mem_univ]
end
end transpose
namespace matrix
section trace
variables {m : Type*} [fintype m] (n : Type*) [fintype n]
variables (R : Type v) (M : Type w) [semiring R] [add_comm_monoid M] [semimodule R M]
/--
The diagonal of a square matrix.
-/
def diag : (matrix n n M) →ₗ[R] n → M :=
{ to_fun := λ A i, A i i,
map_add' := by { intros, ext, refl, },
map_smul' := by { intros, ext, refl, } }
variables {n} {R} {M}
@[simp] lemma diag_apply (A : matrix n n M) (i : n) : diag n R M A i = A i i := rfl
@[simp] lemma diag_one [decidable_eq n] :
diag n R R 1 = λ i, 1 := by { dunfold diag, ext, simp [one_apply_eq] }
@[simp] lemma diag_transpose (A : matrix n n M) : diag n R M Aᵀ = diag n R M A := rfl
variables (n) (R) (M)
/--
The trace of a square matrix.
-/
def trace : (matrix n n M) →ₗ[R] M :=
{ to_fun := λ A, ∑ i, diag n R M A i,
map_add' := by { intros, apply finset.sum_add_distrib, },
map_smul' := by { intros, simp [finset.smul_sum], } }
variables {n} {R} {M}
@[simp] lemma trace_diag (A : matrix n n M) : trace n R M A = ∑ i, diag n R M A i := rfl
@[simp] lemma trace_one [decidable_eq n] :
trace n R R 1 = fintype.card n :=
have h : trace n R R 1 = ∑ i, diag n R R 1 i := rfl,
by simp_rw [h, diag_one, finset.sum_const, nsmul_one]; refl
@[simp] lemma trace_transpose (A : matrix n n M) : trace n R M Aᵀ = trace n R M A := rfl
@[simp] lemma trace_transpose_mul (A : matrix m n R) (B : matrix n m R) :
trace n R R (Aᵀ ⬝ Bᵀ) = trace m R R (A ⬝ B) := finset.sum_comm
lemma trace_mul_comm {S : Type v} [comm_ring S] (A : matrix m n S) (B : matrix n m S) :
trace n S S (B ⬝ A) = trace m S S (A ⬝ B) :=
by rw [←trace_transpose, ←trace_transpose_mul, transpose_mul]
end trace
section ring
variables {n : Type*} [fintype n] [decidable_eq n] {R : Type v} [comm_ring R]
open linear_map matrix
lemma proj_diagonal (i : n) (w : n → R) :
(proj i).comp (to_lin' (diagonal w)) = (w i) • proj i :=
by ext j; simp [mul_vec_diagonal]
lemma diagonal_comp_std_basis (w : n → R) (i : n) :
(diagonal w).to_lin'.comp (std_basis R (λ_:n, R) i) = (w i) • std_basis R (λ_:n, R) i :=
begin
ext j,
simp_rw [linear_map.comp_apply, to_lin'_apply, mul_vec_diagonal, linear_map.smul_apply,
pi.smul_apply, algebra.id.smul_eq_mul],
by_cases i = j,
{ subst h },
{ rw [std_basis_ne R (λ_:n, R) _ _ (ne.symm h), _root_.mul_zero, _root_.mul_zero] }
end
lemma diagonal_to_lin' (w : n → R) :
(diagonal w).to_lin' = linear_map.pi (λi, w i • linear_map.proj i) :=
by ext v j; simp [mul_vec_diagonal]
/-- An invertible matrix yields a linear equivalence from the free module to itself. -/
def to_linear_equiv (P : matrix n n R) (h : is_unit P) : (n → R) ≃ₗ[R] (n → R) :=
have h' : is_unit P.det := P.is_unit_iff_is_unit_det.mp h,
{ inv_fun := P⁻¹.to_lin',
left_inv := λ v,
show (P⁻¹.to_lin'.comp P.to_lin') v = v,
by rw [← matrix.to_lin'_mul, P.nonsing_inv_mul h', matrix.to_lin'_one, linear_map.id_apply],
right_inv := λ v,
show (P.to_lin'.comp P⁻¹.to_lin') v = v,
by rw [← matrix.to_lin'_mul, P.mul_nonsing_inv h', matrix.to_lin'_one, linear_map.id_apply],
..P.to_lin' }
@[simp] lemma to_linear_equiv_apply (P : matrix n n R) (h : is_unit 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 : is_unit P) :
(↑(P.to_linear_equiv h).symm : module.End R (n → R)) = P⁻¹.to_lin' := rfl
end ring
section vector_space
variables {m n : Type*} [fintype m] [fintype n]
variables {K : Type u} [field K] -- maybe try to relax the universe constraint
open linear_map matrix
lemma rank_vec_mul_vec {m n : Type u} [fintype m] [fintype n] [decidable_eq n]
(w : m → K) (v : n → K) :
rank (vec_mul_vec w v).to_lin' ≤ 1 :=
begin
rw [vec_mul_vec_eq, to_lin'_mul],
refine le_trans (rank_comp_le1 _ _) _,
refine le_trans (rank_le_domain _) _,
rw [dim_fun', ← cardinal.lift_eq_nat_iff.mpr (cardinal.fintype_card unit), cardinal.mk_unit],
exact le_of_eq (cardinal.lift_one)
end
lemma ker_diagonal_to_lin' [decidable_eq m] (w : m → K) :
ker (diagonal w).to_lin' = (⨆i∈{i | w i = 0 }, range (std_basis K (λi, K) i)) :=
begin
rw [← comap_bot, ← infi_ker_proj],
simp only [comap_infi, (ker_comp _ _).symm, proj_diagonal, ker_smul'],
have : univ ⊆ {i : m | w i = 0} ∪ {i : m | w i = 0}ᶜ, { rw set.union_compl_self },
exact (supr_range_std_basis_eq_infi_ker_proj K (λi:m, K)
disjoint_compl_right this (finite.of_fintype _)).symm
end
lemma range_diagonal [decidable_eq m] (w : m → K) :
(diagonal w).to_lin'.range = (⨆ i ∈ {i | w i ≠ 0}, (std_basis K (λi, K) i).range) :=
begin
dsimp only [mem_set_of_eq],
rw [← map_top, ← supr_range_std_basis, map_supr],
congr, funext i,
rw [← linear_map.range_comp, diagonal_comp_std_basis, ← range_smul']
end
lemma rank_diagonal [decidable_eq m] [decidable_eq K] (w : m → K) :
rank (diagonal w).to_lin' = fintype.card { i // w i ≠ 0 } :=
begin
have hu : univ ⊆ {i : m | w i = 0}ᶜ ∪ {i : m | w i = 0}, { rw set.compl_union_self },
have hd : disjoint {i : m | w i ≠ 0} {i : m | w i = 0} := disjoint_compl_left,
have h₁ := supr_range_std_basis_eq_infi_ker_proj K (λi:m, K) hd hu (finite.of_fintype _),
have h₂ := @infi_ker_proj_equiv K _ _ (λi:m, K) _ _ _ _ (by simp; apply_instance) hd hu,
rw [rank, range_diagonal, h₁, ←@dim_fun' K],
apply linear_equiv.dim_eq,
apply h₂,
end
end vector_space
section finite_dimensional
variables {m n : Type*} [fintype m] [fintype n]
variables {R : Type v} [field R]
instance : finite_dimensional R (matrix m n R) :=
linear_equiv.finite_dimensional (linear_equiv.uncurry R m n).symm
/--
The dimension of the space of finite dimensional matrices
is the product of the number of rows and columns.
-/
@[simp] lemma findim_matrix :
finite_dimensional.findim R (matrix m n R) = fintype.card m * fintype.card n :=
by rw [@linear_equiv.findim_eq R (matrix m n R) _ _ _ _ _ _ (linear_equiv.uncurry R m n),
finite_dimensional.findim_fintype_fun_eq_card, fintype.card_prod]
end finite_dimensional
section reindexing
variables {l m n : Type*} [fintype l] [fintype m] [fintype n]
variables {l' m' n' : Type*} [fintype l'] [fintype m'] [fintype n']
variables {R : Type v}
/-- The natural map that reindexes a matrix's rows and columns with equivalent types is an
equivalence. -/
def reindex (eₘ : m ≃ m') (eₙ : n ≃ n') : matrix m n R ≃ matrix m' n' R :=
{ to_fun := λ M i j, M (eₘ.symm i) (eₙ.symm j),
inv_fun := λ M i j, M (eₘ i) (eₙ j),
left_inv := λ M, by simp,
right_inv := λ M, by simp, }
@[simp] lemma reindex_apply (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m n R) :
reindex eₘ eₙ M = λ i j, M (eₘ.symm i) (eₙ.symm j) :=
rfl
@[simp] lemma reindex_symm_apply (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m' n' R) :
(reindex eₘ eₙ).symm M = λ i j, M (eₘ i) (eₙ j) :=
rfl
@[simp] lemma reindex_refl_refl (A : matrix m n R) :
(reindex (equiv.refl _) (equiv.refl _) A) = A :=
by { ext, simp only [reindex_apply, equiv.refl_symm, equiv.refl_apply] }
/-- The natural map that reindexes a matrix's rows and columns with equivalent types is a linear
equivalence. -/
def reindex_linear_equiv [semiring R] (eₘ : m ≃ m') (eₙ : n ≃ n') :
matrix m n R ≃ₗ[R] matrix m' n' R :=
{ map_add' := λ M N, rfl,
map_smul' := λ M N, rfl,
..(reindex eₘ eₙ)}
@[simp] lemma coe_reindex_linear_equiv [semiring R]
(eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m n R) :
reindex_linear_equiv eₘ eₙ M = λ i j, M (eₘ.symm i) (eₙ.symm j) :=
rfl
lemma reindex_linear_equiv_apply [semiring R]
(eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m n R) (i j) :
reindex_linear_equiv eₘ eₙ M i j = M (eₘ.symm i) (eₙ.symm j) :=
rfl
@[simp] lemma coe_reindex_linear_equiv_symm [semiring R]
(eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m' n' R) :
(reindex_linear_equiv eₘ eₙ).symm M = λ i j, M (eₘ i) (eₙ j) :=
rfl
lemma reindex_linear_equiv_symm_apply [semiring R]
(eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m' n' R) (i j) :
(reindex_linear_equiv eₘ eₙ).symm M i j = M (eₘ i) (eₙ j) :=
rfl
@[simp] lemma reindex_linear_equiv_refl_refl [semiring R] (A : matrix m n R) :
(reindex_linear_equiv (equiv.refl _) (equiv.refl _) A) = A :=
reindex_refl_refl A
lemma reindex_mul [semiring R]
(eₘ : m ≃ m') (eₙ : n ≃ n') (eₗ : l ≃ l') (M : matrix m n R) (N : matrix n l R) :
(reindex_linear_equiv eₘ eₙ M) ⬝ (reindex_linear_equiv eₙ eₗ N) =
reindex_linear_equiv eₘ eₗ (M ⬝ N) :=
begin
ext i j,
dsimp only [matrix.mul, matrix.dot_product],
rw [←finset.univ_map_equiv_to_embedding eₙ, finset.sum_map finset.univ eₙ.to_embedding],
simp,
end
/-- For square matrices, the natural map that reindexes a matrix's rows and columns with equivalent
types is an equivalence of algebras. -/
def reindex_alg_equiv [comm_semiring R] [decidable_eq m] [decidable_eq n]
(e : m ≃ n) : matrix m m R ≃ₐ[R] matrix n n R :=
{ map_mul' := λ M N, by simp only [reindex_mul, linear_equiv.to_fun_eq_coe, mul_eq_mul],
commutes' := λ r,
by { ext, simp [algebra_map, algebra.to_ring_hom], by_cases h : i = j; simp [h], },
..(reindex_linear_equiv e e) }
@[simp] lemma coe_reindex_alg_equiv [comm_semiring R] [decidable_eq m] [decidable_eq n]
(e : m ≃ n) (M : matrix m m R) :
reindex_alg_equiv e M = λ i j, M (e.symm i) (e.symm j) :=
rfl
@[simp] lemma reindex_alg_equiv_apply [comm_semiring R] [decidable_eq m] [decidable_eq n]
(e : m ≃ n) (M : matrix m m R) (i j) :
reindex_alg_equiv e M i j = M (e.symm i) (e.symm j) :=
rfl
@[simp] lemma coe_reindex_alg_equiv_symm [comm_semiring R] [decidable_eq m] [decidable_eq n]
(e : m ≃ n) (M : matrix n n R) :
(reindex_alg_equiv e).symm M = λ i j, M (e i) (e j) :=
rfl
@[simp] lemma reindex_alg_equiv_symm_apply [comm_semiring R] [decidable_eq m] [decidable_eq n]
(e : m ≃ n) (M : matrix n n R) (i j):
(reindex_alg_equiv e).symm M i j = M (e i) (e j) :=
rfl
@[simp] lemma reindex_alg_equiv_refl [comm_semiring R] [decidable_eq m]
(A : matrix m m R) : (reindex_alg_equiv (equiv.refl m) A) = A :=
reindex_linear_equiv_refl_refl A
lemma reindex_transpose (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m n R) :
(reindex eₘ eₙ M)ᵀ = (reindex eₙ eₘ Mᵀ) :=
rfl
/-- `simp` version of `det_reindex_self`
`det_reindex_self` is not a good simp lemma because `reindex_apply` fires before.
So we have this lemma to continue from there. -/
@[simp]
lemma det_reindex_self' [decidable_eq m] [decidable_eq n] [comm_ring R]
(e : m ≃ n) (A : matrix m m R) :
det (λ i j, A (e.symm i) (e.symm j)) = det A :=
begin
unfold det,
apply finset.sum_bij' (λ σ _, equiv.perm_congr e.symm σ) _ _ (λ σ _, equiv.perm_congr e σ),
{ intros σ _, ext, simp only [equiv.symm_symm, equiv.perm_congr_apply, equiv.apply_symm_apply] },
{ intros σ _, ext, simp only [equiv.symm_symm, equiv.perm_congr_apply, equiv.symm_apply_apply] },
{ intros σ _, apply finset.mem_univ },
{ intros σ _, apply finset.mem_univ },
intros σ _,
simp_rw [equiv.perm_congr_apply, equiv.symm_symm],
congr,
{ convert (equiv.perm.sign_perm_congr e.symm σ).symm },
apply finset.prod_bij' (λ i _, e.symm i) _ _ (λ i _, e i),
{ intros, simp_rw equiv.apply_symm_apply },
{ intros, simp_rw equiv.symm_apply_apply },
{ intros, apply finset.mem_univ },
{ intros, apply finset.mem_univ },
{ intros, simp_rw equiv.apply_symm_apply },
end
/-- Reindexing both indices along the same equivalence preserves the determinant.
For the `simp` version of this lemma, see `det_reindex_self'`.
-/
lemma det_reindex_self [decidable_eq m] [decidable_eq n] [comm_ring R]
(e : m ≃ n) (A : matrix m m R) :
det (reindex e e A) = det A :=
det_reindex_self' e A
/-- Reindexing both indices along the same equivalence preserves the determinant.
For the `simp` version of this lemma, see `det_reindex_self'`.
-/
lemma det_reindex_linear_equiv_self [decidable_eq m] [decidable_eq n] [comm_ring R]
(e : m ≃ n) (A : matrix m m R) :
det (reindex_linear_equiv e e A) = det A :=
det_reindex_self' e A
/-- Reindexing both indices along the same equivalence preserves the determinant.
For the `simp` version of this lemma, see `det_reindex_self'`.
-/
lemma det_reindex_alg_equiv [decidable_eq m] [decidable_eq n] [comm_ring R]
(e : m ≃ n) (A : matrix m m R) :
det (reindex_alg_equiv e A) = det A :=
det_reindex_self' e A
end reindexing
end matrix
namespace linear_map
open_locale matrix
/-- The trace of an endomorphism given a basis. -/
def trace_aux (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M]
{ι : Type w} [decidable_eq ι] [fintype ι] {b : ι → M} (hb : is_basis R b) :
(M →ₗ[R] M) →ₗ[R] R :=
(matrix.trace ι R R).comp $ linear_map.to_matrix hb hb
@[simp] lemma trace_aux_def (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M]
{ι : Type w} [decidable_eq ι] [fintype ι] {b : ι → M} (hb : is_basis R b) (f : M →ₗ[R] M) :
trace_aux R hb f = matrix.trace ι R R (linear_map.to_matrix hb hb f) :=
rfl
theorem trace_aux_eq' (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M]
{ι : Type w} [decidable_eq ι] [fintype ι] {b : ι → M} (hb : is_basis R b)
{κ : Type w} [decidable_eq κ] [fintype κ] {c : κ → M} (hc : is_basis R c) :
trace_aux R hb = trace_aux R hc :=
linear_map.ext $ λ f,
calc matrix.trace ι R R (linear_map.to_matrix hb hb f)
= matrix.trace ι R R (linear_map.to_matrix hb hb ((linear_map.id.comp f).comp linear_map.id)) :
by rw [linear_map.id_comp, linear_map.comp_id]
... = matrix.trace ι R R (linear_map.to_matrix hc hb linear_map.id ⬝
linear_map.to_matrix hc hc f ⬝
linear_map.to_matrix hb hc linear_map.id) :
by rw [linear_map.to_matrix_comp _ hc, linear_map.to_matrix_comp _ hc]
... = matrix.trace κ R R (linear_map.to_matrix hc hc f ⬝
linear_map.to_matrix hb hc linear_map.id ⬝
linear_map.to_matrix hc hb linear_map.id) :
by rw [matrix.mul_assoc, matrix.trace_mul_comm]
... = matrix.trace κ R R (linear_map.to_matrix hc hc ((f.comp linear_map.id).comp linear_map.id)) :
by rw [linear_map.to_matrix_comp _ hb, linear_map.to_matrix_comp _ hc]
... = matrix.trace κ R R (linear_map.to_matrix hc hc f) :
by rw [linear_map.comp_id, linear_map.comp_id]
open_locale classical
theorem trace_aux_range (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M]
{ι : Type w} [decidable_eq ι] [fintype ι] {b : ι → M} (hb : is_basis R b) :
trace_aux R hb.range = trace_aux R hb :=
linear_map.ext $ λ f, if H : 0 = 1 then eq_of_zero_eq_one H _ _ else
begin
haveI : nontrivial R := ⟨⟨0, 1, H⟩⟩,
change ∑ i : set.range b, _ = ∑ i : ι, _, simp_rw [matrix.diag_apply], symmetry,
convert (equiv.of_injective _ hb.injective).sum_comp _, ext i,
exact (linear_map.to_matrix_range hb hb f i i).symm
end
/-- where `ι` and `κ` can reside in different universes -/
theorem trace_aux_eq (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M]
{ι : Type*} [decidable_eq ι] [fintype ι] {b : ι → M} (hb : is_basis R b)
{κ : Type*} [decidable_eq κ] [fintype κ] {c : κ → M} (hc : is_basis R c) :
trace_aux R hb = trace_aux R hc :=
calc trace_aux R hb
= trace_aux R hb.range : by rw trace_aux_range R hb
... = trace_aux R hc.range : trace_aux_eq' _ _ _
... = trace_aux R hc : by rw trace_aux_range R hc
/-- Trace of an endomorphism independent of basis. -/
def trace (R : Type u) [comm_ring R] (M : Type v) [add_comm_group M] [module R M] :
(M →ₗ[R] M) →ₗ[R] R :=
if H : ∃ s : finset M, is_basis R (λ x, x : (↑s : set M) → M)
then trace_aux R (classical.some_spec H)
else 0
theorem trace_eq_matrix_trace (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M]
[module R M] {ι : Type w} [fintype ι] [decidable_eq ι] {b : ι → M} (hb : is_basis R b)
(f : M →ₗ[R] M) : trace R M f = matrix.trace ι R R (linear_map.to_matrix hb hb f) :=
have ∃ s : finset M, is_basis R (λ x, x : (↑s : set M) → M),
from ⟨finset.univ.image b,
by { rw [finset.coe_image, finset.coe_univ, set.image_univ], exact hb.range }⟩,
by { rw [trace, dif_pos this, ← trace_aux_def], congr' 1, apply trace_aux_eq }
theorem trace_mul_comm (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M]
(f g : M →ₗ[R] M) : trace R M (f * g) = trace R M (g * f) :=
if H : ∃ s : finset M, is_basis R (λ x, x : (↑s : set M) → M) then let ⟨s, hb⟩ := H in
by { simp_rw [trace_eq_matrix_trace R hb, linear_map.to_matrix_mul], apply matrix.trace_mul_comm }
else by rw [trace, dif_neg H, linear_map.zero_apply, linear_map.zero_apply]
section finite_dimensional
variables {K : Type*} [field K]
variables {V : Type*} [add_comm_group V] [vector_space K V] [finite_dimensional K V]
variables {W : Type*} [add_comm_group W] [vector_space K W] [finite_dimensional K W]
instance : finite_dimensional K (V →ₗ[K] W) :=
begin
classical,
cases finite_dimensional.exists_is_basis_finset K V with bV hbV,
cases finite_dimensional.exists_is_basis_finset K W with bW hbW,
apply linear_equiv.finite_dimensional (linear_map.to_matrix hbV hbW).symm,
end
/--
The dimension of the space of linear transformations is the product of the dimensions of the
domain and codomain.
-/
@[simp] lemma findim_linear_map :
finite_dimensional.findim K (V →ₗ[K] W) =
(finite_dimensional.findim K V) * (finite_dimensional.findim K W) :=
begin
classical,
cases finite_dimensional.exists_is_basis_finset K V with bV hbV,
cases finite_dimensional.exists_is_basis_finset K W with bW hbW,
rw [linear_equiv.findim_eq (linear_map.to_matrix hbV hbW), matrix.findim_matrix,
finite_dimensional.findim_eq_card_basis hbV, finite_dimensional.findim_eq_card_basis hbW,
mul_comm],
end
end finite_dimensional
end linear_map
/-- The natural equivalence between linear endomorphisms of finite free modules and square matrices
is compatible with the algebra structures. -/
def alg_equiv_matrix' {R : Type v} [comm_ring R] {n : Type*} [fintype n] [decidable_eq n] :
module.End R (n → R) ≃ₐ[R] matrix n n R :=
{ map_mul' := linear_map.to_matrix'_comp,
map_add' := linear_map.to_matrix'.map_add,
commutes' := λ r, by { change (r • (linear_map.id : module.End R _)).to_matrix' = r • 1,
rw ←linear_map.to_matrix'_id, refl, },
..linear_map.to_matrix' }
/-- A linear equivalence of two modules induces an equivalence of algebras of their
endomorphisms. -/
def linear_equiv.alg_conj {R : Type v} [comm_ring R] {M₁ M₂ : Type*}
[add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] (e : M₁ ≃ₗ[R] M₂) :
module.End R M₁ ≃ₐ[R] module.End R M₂ :=
{ map_mul' := λ f g, by apply e.arrow_congr_comp,
map_add' := e.conj.map_add,
commutes' := λ r, by { change e.conj (r • linear_map.id) = r • linear_map.id,
rw [linear_equiv.map_smul, linear_equiv.conj_id], },
..e.conj }
/-- A basis of a module induces an equivalence of algebras from the endomorphisms of the module to
square matrices. -/
def alg_equiv_matrix {R : Type v} {M : Type w} {n : Type*} [fintype n]
[comm_ring R] [add_comm_group M] [module R M] [decidable_eq n] {b : n → M} (h : is_basis R b) :
module.End R M ≃ₐ[R] matrix n n R :=
h.equiv_fun.alg_conj.trans alg_equiv_matrix'
section
variables {R : Type v} [semiring R] {n : Type w} [fintype n]
@[simp] lemma matrix.dot_product_std_basis_eq_mul [decidable_eq n] (v : n → R) (c : R) (i : n) :
matrix.dot_product v (linear_map.std_basis R (λ _, R) i c) = v i * c :=
begin
rw [matrix.dot_product, finset.sum_eq_single i, linear_map.std_basis_same],
exact λ _ _ hb, by rw [linear_map.std_basis_ne _ _ _ _ hb, mul_zero],
exact λ hi, false.elim (hi $ finset.mem_univ _)
end
@[simp] lemma matrix.dot_product_std_basis_one [decidable_eq n] (v : n → R) (i : n) :
matrix.dot_product v (linear_map.std_basis R (λ _, R) i 1) = v i :=
by rw [matrix.dot_product_std_basis_eq_mul, mul_one]
lemma matrix.dot_product_eq
(v w : n → R) (h : ∀ u, matrix.dot_product v u = matrix.dot_product w u) : v = w :=
begin
funext x,
classical,
rw [← matrix.dot_product_std_basis_one v x, ← matrix.dot_product_std_basis_one w x, h],
end
lemma matrix.dot_product_eq_iff {v w : n → R} :
(∀ u, matrix.dot_product v u = matrix.dot_product w u) ↔ v = w :=
⟨λ h, matrix.dot_product_eq v w h, λ h _, h ▸ rfl⟩
lemma matrix.dot_product_eq_zero (v : n → R) (h : ∀ w, matrix.dot_product v w = 0) : v = 0 :=
matrix.dot_product_eq _ _ $ λ u, (h u).symm ▸ (zero_dot_product u).symm
lemma matrix.dot_product_eq_zero_iff {v : n → R} : (∀ w, matrix.dot_product v w = 0) ↔ v = 0 :=
⟨λ h, matrix.dot_product_eq_zero v h, λ h w, h.symm ▸ zero_dot_product w⟩
end
namespace matrix
variables {m n : Type*} [decidable_eq n] [fintype n] [decidable_eq m] [fintype m]
variables {R : Type v} [comm_ring R]
lemma det_to_block (M : matrix m m R) (p : m → Prop) [decidable_pred p] :
M.det = (matrix.from_blocks (to_block M p p) (to_block M p (λ j, ¬p j))
(to_block M (λ j, ¬p j) p) (to_block M (λ j, ¬p j) (λ j, ¬p j))).det :=
begin
rw ← matrix.det_reindex_self (equiv.sum_compl p).symm M,
unfold det,
congr, ext σ, congr, ext,
generalize hy : σ x = y,
cases x; cases y;
simp only [matrix.reindex_apply, to_block_apply, equiv.symm_symm,
equiv.sum_compl_apply_inr, equiv.sum_compl_apply_inl,
from_blocks_apply₁₁, from_blocks_apply₁₂, from_blocks_apply₂₁, from_blocks_apply₂₂],
end
lemma det_to_square_block (M : matrix m m R) {n : nat} (b : m → fin n) (k : fin n) :
(to_square_block M b k).det = (to_square_block_prop M (λ i, b i = k)).det :=
by simp
lemma det_to_square_block' (M : matrix m m R) (b : m → ℕ) (k : ℕ) :
(to_square_block' M b k).det = (to_square_block_prop M (λ i, b i = k)).det :=
by simp
lemma two_block_triangular_det (M : matrix m m R) (p : m → Prop) [decidable_pred p]
(h : ∀ i (h1 : ¬p i) j (h2 : p j), M i j = 0) :
M.det = (to_square_block_prop M p).det * (to_square_block_prop M (λ i, ¬p i)).det :=
begin
rw det_to_block M p,
convert upper_two_block_triangular_det (to_block M p p) (to_block M p (λ j, ¬p j))
(to_block M (λ j, ¬p j) (λ j, ¬p j)),
ext,
exact h ↑i i.2 ↑j j.2
end
lemma equiv_block_det (M : matrix m m R) {p q : m → Prop} [decidable_pred p] [decidable_pred q]
(e : ∀x, q x ↔ p x) : (to_square_block_prop M p).det = (to_square_block_prop M q).det :=
by convert matrix.det_reindex_self (equiv.subtype_equiv_right e) (to_square_block_prop M q)
lemma to_square_block_det'' (M : matrix m m R) {n : nat} (b : m → fin n) (k : fin n) :
(to_square_block M b k).det = (to_square_block' M (λ i, ↑(b i)) ↑k).det :=
begin
rw [to_square_block_def', to_square_block_def],
apply equiv_block_det,
intro x,
apply (fin.ext_iff _ _).symm
end
/-- Let `b` map rows and columns of a square matrix `M` to `n` blocks. Then
`block_triangular_matrix' M n b` says the matrix is block triangular. -/
def block_triangular_matrix' {o : Type*} [fintype o] (M : matrix o o R) {n : ℕ}
(b : o → fin n) : Prop :=
∀ i j, b j < b i → M i j = 0
lemma upper_two_block_triangular' {m n : Type*} [fintype m] [fintype n]
(A : matrix m m R) (B : matrix m n R) (D : matrix n n R) :
block_triangular_matrix' (from_blocks A B 0 D) (sum.elim (λ i, (0 : fin 2)) (λ j, 1)) :=
begin
intros k1 k2 hk12,
have h0 : ∀ (k : m ⊕ n), sum.elim (λ i, (0 : fin 2)) (λ j, 1) k = 0 → ∃ i, k = sum.inl i,
{ simp },
have h1 : ∀ (k : m ⊕ n), sum.elim (λ i, (0 : fin 2)) (λ j, 1) k = 1 → ∃ j, k = sum.inr j,
{ simp },
set mk1 := (sum.elim (λ i, (0 : fin 2)) (λ j, 1)) k1 with hmk1,
set mk2 := (sum.elim (λ i, (0 : fin 2)) (λ j, 1)) k2 with hmk2,
fin_cases mk1; fin_cases mk2; rw [h, h_1] at hk12,
{ exact absurd hk12 (nat.not_lt_zero 0) },
{ exact absurd hk12 (nat.not_lt_zero 1) },
{ rw hmk1 at h,
obtain ⟨i, hi⟩ := h1 k1 h,
rw hmk2 at h_1,
obtain ⟨j, hj⟩ := h0 k2 h_1,
rw [hi, hj], simp },
{ exact absurd hk12 (irrefl 1) }
end
/-- Let `b` map rows and columns of a square matrix `M` to blocks indexed by `ℕ`s. Then
`block_triangular_matrix M n b` says the matrix is block triangular. -/
def block_triangular_matrix {o : Type*} [fintype o] (M : matrix o o R) (b : o → ℕ) : Prop :=
∀ i j, b j < b i → M i j = 0
lemma upper_two_block_triangular {m n : Type*} [fintype m] [fintype n]
(A : matrix m m R) (B : matrix m n R) (D : matrix n n R) :
block_triangular_matrix (from_blocks A B 0 D) (sum.elim (λ i, 0) (λ j, 1)) :=
begin
intros k1 k2 hk12,
have h01 : ∀ (k : m ⊕ n), sum.elim (λ i, 0) (λ j, 1) k = 0 ∨ sum.elim (λ i, 0) (λ j, 1) k = 1,
{ simp },
have h0 : ∀ (k : m ⊕ n), sum.elim (λ i, 0) (λ j, 1) k = 0 → ∃ i, k = sum.inl i, { simp },
have h1 : ∀ (k : m ⊕ n), sum.elim (λ i, 0) (λ j, 1) k = 1 → ∃ j, k = sum.inr j, { simp },
cases (h01 k1) with hk1 hk1; cases (h01 k2) with hk2 hk2; rw [hk1, hk2] at hk12,
{ exact absurd hk12 (nat.not_lt_zero 0) },
{ exact absurd hk12 (nat.not_lt_zero 1) },
{ obtain ⟨i, hi⟩ := h1 k1 hk1,
obtain ⟨j, hj⟩ := h0 k2 hk2,
rw [hi, hj], simp },
{ exact absurd hk12 (irrefl 1) }
end
lemma det_of_block_triangular_matrix (M : matrix m m R) (b : m → ℕ)
(h : block_triangular_matrix M b) :
∀ (n : ℕ) (hn : ∀ i, b i < n), M.det = ∏ k in finset.range n, (to_square_block' M b k).det :=
begin
intros n hn,
tactic.unfreeze_local_instances,
induction n with n hi generalizing m M b,
{ rw finset.prod_range_zero,
apply det_eq_one_of_card_eq_zero,
apply fintype.card_eq_zero_iff.mpr,
intro i,
exact nat.not_lt_zero (b i) (hn i) },
{ rw finset.prod_range_succ,
have h2 : (M.to_square_block_prop (λ (i : m), b i = n.succ)).det =
(M.to_square_block' b n.succ).det,
{ dunfold to_square_block', dunfold to_square_block_prop, refl },
rw two_block_triangular_det M (λ i, ¬(b i = n)),
{ rw mul_comm,
apply congr (congr_arg has_mul.mul _),
{ let m' := {a // ¬b a = n },
let b' := (λ (i : m'), b ↑i),
have h' :
block_triangular_matrix (M.to_square_block_prop (λ (i : m), ¬b i = n)) b',
{ intros i j, apply h ↑i ↑j },
have hni : ∀ (i : {a // ¬b a = n}), b' i < n,
{ exact λ i, (ne.le_iff_lt i.property).mp (nat.lt_succ_iff.mp (hn ↑i)) },
have h1 := hi (M.to_square_block_prop (λ (i : m), ¬b i = n)) b' h' hni,
rw ←fin.prod_univ_eq_prod_range at h1 ⊢,
convert h1,
ext k,
simp only [to_square_block_def', to_square_block_def],
let he : {a // b' a = ↑k} ≃ {a // b a = ↑k},
{ have hc : ∀ (i : m), (λ a, b a = ↑k) i → (λ a, ¬b a = n) i,
{ intros i hbi, rw hbi, exact ne_of_lt (fin.is_lt k) },
exact equiv.subtype_subtype_equiv_subtype hc },
exact matrix.det_reindex_self he (λ (i j : {a // b' a = ↑k}), M ↑i ↑j) },
{ rw det_to_square_block' M b n,
have hh : ∀ a, b a = n ↔ ¬(λ (i : m), ¬b i = n) a,
{ intro i, simp only [not_not] },
exact equiv_block_det M hh }},
{ intros i hi j hj,
apply (h i), simp only [not_not] at hi,
rw hi,
exact (ne.le_iff_lt hj).mp (nat.lt_succ_iff.mp (hn j)) }}
end
lemma det_of_block_triangular_matrix'' (M : matrix m m R) (b : m → ℕ)
(h : block_triangular_matrix M b) :
M.det = ∏ k in finset.image b finset.univ, (to_square_block' M b k).det :=
begin
let n : ℕ := (Sup (finset.image b finset.univ : set ℕ)).succ,
have hn : ∀ i, b i < n,
{ have hbi : ∀ i, b i ∈ finset.image b finset.univ, { simp },
intro i,
dsimp only [n],
apply nat.lt_succ_iff.mpr,
exact le_cSup (finset.bdd_above _) (hbi i) },
rw det_of_block_triangular_matrix M b h n hn,
refine (finset.prod_subset _ _).symm,
{ intros a ha, apply finset.mem_range.mpr,
obtain ⟨i, ⟨hi, hbi⟩⟩ := finset.mem_image.mp ha,
rw ←hbi,
exact hn i },
{ intros k hk hbk,
apply det_eq_one_of_card_eq_zero,
apply fintype.card_eq_zero_iff.mpr,
simp only [subtype.forall],
intros a hba, apply hbk,
apply finset.mem_image.mpr,
use a,
exact ⟨finset.mem_univ a, hba⟩ }
end
lemma det_of_block_triangular_matrix' (M : matrix m m R) {n : ℕ} (b : m → fin n)
(h : block_triangular_matrix' M b) :
M.det = ∏ (k : fin n), (to_square_block M b k).det :=
begin
let b2 : m → ℕ := λ i, ↑(b i),
simp_rw to_square_block_det'',
rw fin.prod_univ_eq_prod_range (λ (k : ℕ), (M.to_square_block' b2 k).det) n,
apply det_of_block_triangular_matrix,
{ intros i j hij, exact h i j (fin.coe_fin_lt.mp hij) },
{ intro i, exact fin.is_lt (b i) }
end
lemma det_of_upper_triangular {n : ℕ} (M : matrix (fin n) (fin n) R)
(h : ∀ (i j : fin n), j < i → M i j = 0) :
M.det = ∏ i : (fin n), M i i :=
begin
convert det_of_block_triangular_matrix' M id h,
ext i,
have h2 : ∀ (j : {a // id a = i}), j = ⟨i, rfl⟩ :=
λ (j : {a // id a = i}), subtype.ext j.property,
haveI : unique {a // id a = i} := ⟨⟨⟨i, rfl⟩⟩, h2⟩,
simp [h2 (default {a // id a = i})]
end
lemma det_of_lower_triangular {n : ℕ} (M : matrix (fin n) (fin n) R)
(h : ∀ (i j : fin n), i < j → M i j = 0) :
M.det = ∏ i : (fin n), M i i :=
begin
rw ← det_transpose,
exact det_of_upper_triangular _ (λ (i j : fin n) (hji : j < i), h j i hji)
end
end matrix
|
688e6f68cf75633f9897a606d5b578f6e79b3e73 | 947b78d97130d56365ae2ec264df196ce769371a | /stage0/src/Lean/Elab/PreDefinition/WF.lean | 42d9fe9907d32328223f23d54112cdf96a09e415 | [
"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 | 395 | 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.PreDefinition.Basic
namespace Lean
namespace Elab
open Meta
def WFRecursion (preDefs : Array PreDefinition) : TermElabM Unit :=
throwError "well founded recursion has not been implemented yet"
end Elab
end Lean
|
6fee70b3c86d5f97e70de606e0ff09ed3c552ae6 | 217bb195841a8be2d1b4edd2084d6b69ccd62f50 | /library/init/lean/parser/syntax.lean | d152243eaeeb66c5810787b5dc4580360a3d372c | [
"Apache-2.0"
] | permissive | frank-lesser/lean4 | 717f56c9bacd5bf3a67542d2f5cea721d4743a30 | 79e2abe33f73162f773ea731265e456dbfe822f9 | refs/heads/master | 1,589,741,267,933 | 1,556,424,200,000 | 1,556,424,281,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,482 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Sebastian Ullrich
-/
prelude
import init.lean.name init.lean.parser.parsec
namespace Lean
namespace Parser
--TODO(Sebastian): move
structure Substring :=
(start : String.OldIterator)
(stop : String.OldIterator)
structure SourceInfo :=
/- Will be inferred after parsing by `Syntax.updateLeading`. During parsing,
it is not at all clear what the preceding token was, especially with backtracking. -/
(leading : Substring)
(pos : Parsec.Position)
(trailing : Substring)
structure SyntaxAtom :=
(info : Option SourceInfo := none) (val : String)
/-- A simple wrapper that should remind you to use the static Declaration instead
of hard-coding the Node Name. -/
structure SyntaxNodeKind :=
-- should be equal to the Name of the Declaration this structure instance was bound to
(name : Name)
/-- Signifies ambiguous Syntax to be disambiguated by the Elaborator. Should have at least two children.
This Node kind is special-cased by `Syntax.reprint` since its children's outputs should not be concatenated. -/
@[pattern] def choice : SyntaxNodeKind := ⟨`Lean.Parser.choice⟩
/-- A nondescriptive kind that can be used for merely grouping Syntax trees into a Node.
This Node kind is special-cased by `Syntax.Format` to be printed as brackets `[...]` without a Node kind. -/
@[pattern] def noKind : SyntaxNodeKind := ⟨`Lean.Parser.noKind⟩
/-- A hygiene marker introduced by a macro expansion. -/
@[derive DecidableEq HasToFormat]
def MacroScope := Nat
abbrev macroScopes := List MacroScope
/-
Parsers create `SyntaxNode`'s with the following properties (see implementation of `Combinators.Node`):
- If `args` contains a `Syntax.missing`, then all subsequent elements are also `Syntax.missing`.
- The first argument in `args` is not `Syntax.missing`
Remark: We do create `SyntaxNode`'s with an Empty `args` field (e.g. for representing `Option.none`).
-/
structure SyntaxNode (Syntax : Type) :=
(kind : SyntaxNodeKind)
(args : List Syntax)
-- Lazily propagated scopes. Scopes are pushed inwards when a Node is destructed via `Syntax.asNode`,
-- until an ident or an atom (in which the scopes vanish) is reached.
-- Scopes are stored in a stack with the most recent Scope at the top.
(scopes : macroScopes := [])
structure SyntaxIdent :=
(info : Option SourceInfo := none)
(rawVal : Substring)
(val : Name)
/- A List of overloaded, global names that this identifier could have referred to in the lexical context
where it was parsed.
If the identifier does not resolve to a local binding, it should instead resolve to one of
these preresolved constants. -/
(preresolved : List Name := [])
(scopes : macroScopes := [])
inductive Syntax
| atom (val : SyntaxAtom)
| ident (val : SyntaxIdent)
-- note: use `Syntax.asNode` instead of matching against this Constructor so that
-- macro scopes are propagated
| rawNode (val : SyntaxNode Syntax)
| missing
instance : Inhabited Syntax :=
⟨Syntax.missing⟩
def Substring.toString (s : Substring) : String :=
s.start.extract s.stop
def Substring.ofString (s : String) : Substring :=
⟨s.mkOldIterator, s.mkOldIterator.toEnd⟩
instance Substring.HasToString : HasToString Substring :=
⟨Substring.toString⟩
-- TODO(Sebastian): exhaustively argue why (if?) this is correct
-- The basic idea is List concatenation with elimination of adjacent identical scopes
def macroScopes.flip : macroScopes → macroScopes → macroScopes
| ys (x::xs) := (match macroScopes.flip ys xs with
| y::ys := if x = y then ys else x::y::ys
| [] := [x])
| ys [] := ys
namespace Syntax
open Lean.Format
def flipScopes (scopes : macroScopes) : Syntax → Syntax
| (Syntax.ident n) := Syntax.ident {n with scopes := n.scopes.flip scopes}
| (Syntax.rawNode n) := Syntax.rawNode {n with scopes := n.scopes.flip scopes}
| stx := stx
def mkNode (kind : SyntaxNodeKind) (args : List Syntax) :=
Syntax.rawNode { kind := kind, args := args }
/-- Match against `Syntax.rawNode`, propagating lazy macro scopes. -/
def asNode : Syntax → Option (SyntaxNode Syntax)
| (Syntax.rawNode n) := some {n with args := n.args.map (flipScopes n.scopes), scopes := []}
| _ := none
protected def list (args : List Syntax) :=
mkNode noKind args
def kind : Syntax → Option SyntaxNodeKind
| (Syntax.rawNode n) := some n.kind
| _ := none
def isOfKind (k : SyntaxNodeKind) : Syntax → Bool
| (Syntax.rawNode n) := k.name = n.kind.name
| _ := false
section
variables {m : Type → Type} [Monad m] (r : Syntax → m (Option Syntax))
local attribute [instance] monadInhabited
partial def mreplace : Syntax → m Syntax
| stx@(rawNode n) := do
o ← r stx,
(match o with
| some stx' := pure stx'
| none := do args' ← n.args.mmap mreplace, pure $ rawNode {n with args := args'})
| stx := do
o ← r stx,
pure $ o.getOrElse stx
def replace := @mreplace Id _
end
/- Remark: the State `String.Iterator` is the `SourceInfo.trailing.stop` of the previous token,
or the beginning of the String. -/
private def updateLeadingAux : Syntax → State String.OldIterator (Option Syntax)
| (atom a@{info := some info, ..}) := do
last ← get,
set info.trailing.stop,
pure $ some $ atom {a with info := some {info with leading := ⟨last, last.nextn (info.pos - last.offset)⟩}}
| (ident id@{info := some info, ..}) := do
last ← get,
set info.trailing.stop,
pure $ some $ ident {id with info := some {info with leading := ⟨last, last.nextn (info.pos - last.offset)⟩}}
| _ := pure none
/-- Set `SourceInfo.leading` according to the trailing stop of the preceding token.
The Result is a round-tripping Syntax tree IF, in the input Syntax tree,
* all leading stops, atom contents, and trailing starts are correct
* trailing stops are between the trailing start and the next leading stop.
Remark: after parsing all `SourceInfo.leading` fields are Empty.
The Syntax argument is the output produced by the Parser for `source`.
This Function "fixes" the `source.leanding` field.
Note that, the `SourceInfo.trailing` fields are correct.
The implementation of this Function relies on this property. -/
def updateLeading (source : String) : Syntax → Syntax :=
λ stx, Prod.fst $ (mreplace updateLeadingAux stx).run source.mkOldIterator
/-- Retrieve the left-most leaf's info in the Syntax tree. -/
partial def getHeadInfo : Syntax → Option SourceInfo
| (atom a) := a.info
| (ident id) := id.info
| (rawNode n) := n.args.foldr (λ s r, getHeadInfo s <|> r) none
| _ := none
def getPos (stx : Syntax) : Option Parsec.Position :=
do i ← stx.getHeadInfo,
pure i.pos
def reprintAtom : SyntaxAtom → String
| ⟨some info, s⟩ := info.leading.toString ++ s ++ info.trailing.toString
| ⟨none, s⟩ := s
partial def reprint : Syntax → Option String
| (atom ⟨some info, s⟩) := pure $ info.leading.toString ++ s ++ info.trailing.toString
| (atom ⟨none, s⟩) := pure s
| (ident id@{info := some info, ..}) := pure $ info.leading.toString ++ id.rawVal.toString ++ info.trailing.toString
| (ident id@{info := none, ..}) := pure id.rawVal.toString
| (rawNode n) :=
if n.kind.name = choice.name then match n.args with
-- should never happen
| [] := failure
-- check that every choice prints the same
| n::ns := do
s ← reprint n,
ss ← ns.mmap reprint,
guard $ ss.all (= s),
pure s
else String.join <$> n.args.mmap reprint
| missing := ""
protected partial def toFormat : Syntax → Format
| (atom ⟨_, s⟩) := toFmt $ repr s
| (ident id) :=
let scopes := id.preresolved.map toFmt ++ id.scopes.reverse.map toFmt in
let scopes := match scopes with [] := toFmt "" | _ := bracket "{" (joinSep scopes ", ") "}" in
toFmt "`" ++ toFmt id.val ++ scopes
| stx@(rawNode n) :=
let scopes := match n.scopes with [] := toFmt "" | _ := bracket "{" (joinSep n.scopes.reverse ", ") "}" in
if n.kind.name = `Lean.Parser.noKind then sbracket $ scopes ++ joinSep (n.args.map toFormat) line
else let shorterName := n.kind.name.replacePrefix `Lean.Parser Name.anonymous
in paren $ joinSep ((toFmt shorterName ++ scopes) :: n.args.map toFormat) line
| missing := "<missing>"
instance : HasToFormat Syntax := ⟨Syntax.toFormat⟩
instance : HasToString Syntax := ⟨toString ∘ toFmt⟩
end Syntax
end Parser
end Lean
|
c31ae6273e6f613d9d3405d816cf8b4d684c4689 | e0f9ba56b7fedc16ef8697f6caeef5898b435143 | /src/tactic/converter/apply_congr.lean | fcf5084d8e6d2c9e29c5b0d6f1635c3830d33d39 | [
"Apache-2.0"
] | permissive | anrddh/mathlib | 6a374da53c7e3a35cb0298b0cd67824efef362b4 | a4266a01d2dcb10de19369307c986d038c7bb6a6 | refs/heads/master | 1,656,710,827,909 | 1,589,560,456,000 | 1,589,560,456,000 | 264,271,800 | 0 | 0 | Apache-2.0 | 1,589,568,062,000 | 1,589,568,061,000 | null | UTF-8 | Lean | false | false | 3,347 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Lucas Allen, Scott Morrison
-/
import tactic.interactive
import tactic.converter.interactive
/-!
## Introduce the `apply_congr` conv mode tactic.
`apply_congr` will apply congruence lemmas inside `conv` mode.
It is particularly useful when the automatically generated congruence lemmas
are not of the optimal shape. An example, described in the doc-string is
rewriting inside the operand of a `finset.sum`.
-/
open tactic
namespace conv.interactive
open interactive interactive.types lean.parser
local postfix `?`:9001 := optional
/--
Apply a congruence lemma inside `conv` mode.
When called without an argument `apply_congr` will try applying all lemmas marked with `@[congr]`.
Otherwise `apply_congr e` will apply the lemma `e`.
Recall that a goal that appears as `∣ X` in `conv` mode
represents a goal of `⊢ X = ?m`,
i.e. an equation with a metavariable for the right hand side.
To successfully use `apply_congr e`, `e` will need to be an equation
(possibly after function arguments),
which can be unified with a goal of the form `X = ?m`.
The right hand side of `e` will then determine the metavariable,
and `conv` will subsequently replace `X` with that right hand side.
As usual, `apply_congr` can create new goals;
any of these which are _not_ equations with a metavariable on the right hand side
will be hard to deal with in `conv` mode.
Thus `apply_congr` automatically calls `intros` on any new goals,
and fails if they are not then equations.
In particular it is useful for rewriting inside the operand of a `finset.sum`,
as it provides an extra hypothesis asserting we are inside the domain.
For example:
```lean
example (f g : ℤ → ℤ) (S : finset ℤ) (h : ∀ m ∈ S, f m = g m) :
finset.sum S f = finset.sum S g :=
begin
conv_lhs {
-- If we just call `congr` here, in the second goal we're helpless,
-- because we are only given the opportunity to rewrite `f`.
-- However `apply_congr` uses the appropriate `@[congr]` lemma,
-- so we get to rewrite `f x`, in the presence of the crucial `H : x ∈ S` hypothesis.
apply_congr,
skip,
simp [h, H],
}
end
```
In the above example, when the `apply_congr` tactic is called it gives the hypothesis `H : x ∈ S`
which is then used to rewrite the `f x` to `g x`.
-/
meta def apply_congr (q : parse texpr?) : conv unit :=
do
congr_lemmas ← match q with
-- If the user specified a lemma, use that one,
| some e := do
gs ← get_goals,
e ← to_expr e, -- to_expr messes with the goals? (see tests)
set_goals gs,
return [e]
-- otherwise, look up everything tagged `@[congr]`
| none := do
congr_lemma_names ← attribute.get_instances `congr,
congr_lemma_names.mmap mk_const
end,
-- For every lemma:
congr_lemmas.any_of (λ n,
-- Call tactic.eapply
seq (tactic.eapply n >> tactic.skip)
-- and then call `intros` on each resulting goal, and require that afterwards it's an equation.
(tactic.intros >> (do `(_ = _) ← target, tactic.skip)))
add_tactic_doc {
name := "apply_congr",
category := doc_category.tactic,
decl_names := [`conv.interactive.apply_congr],
tags := ["conv", "congruence", "rewriting"]
}
end conv.interactive
|
b4b2814386fec4cdf1a0f6a4471dd89236e6d362 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/topology/uniform_space/cauchy.lean | ac31a3cdfac01e766d4bbd71af4bd35ade22f7b1 | [
"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 | 33,876 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import topology.bases
import topology.uniform_space.basic
/-!
# Theory of Cauchy filters in uniform spaces. Complete uniform spaces. Totally bounded subsets.
-/
universes u v
open filter topological_space set classical uniform_space function
open_locale classical uniformity topological_space filter
variables {α : Type u} {β : Type v} [uniform_space α]
/-- A filter `f` is Cauchy if for every entourage `r`, there exists an
`s ∈ f` such that `s × s ⊆ r`. This is a generalization of Cauchy
sequences, because if `a : ℕ → α` then the filter of sets containing
cofinitely many of the `a n` is Cauchy iff `a` is a Cauchy sequence. -/
def cauchy (f : filter α) := ne_bot f ∧ f ×ᶠ f ≤ (𝓤 α)
/-- A set `s` is called *complete*, if any Cauchy filter `f` such that `s ∈ f`
has a limit in `s` (formally, it satisfies `f ≤ 𝓝 x` for some `x ∈ s`). -/
def is_complete (s : set α) := ∀f, cauchy f → f ≤ 𝓟 s → ∃x∈s, f ≤ 𝓝 x
lemma filter.has_basis.cauchy_iff {ι} {p : ι → Prop} {s : ι → set (α × α)} (h : (𝓤 α).has_basis p s)
{f : filter α} :
cauchy f ↔ (ne_bot f ∧ (∀ i, p i → ∃ t ∈ f, ∀ x y ∈ t, (x, y) ∈ s i)) :=
and_congr iff.rfl $ (f.basis_sets.prod_self.le_basis_iff h).trans $
by simp only [subset_def, prod.forall, mem_prod_eq, and_imp, id, ball_mem_comm]
lemma cauchy_iff' {f : filter α} :
cauchy f ↔ (ne_bot f ∧ (∀ s ∈ 𝓤 α, ∃t∈f, ∀ x y ∈ t, (x, y) ∈ s)) :=
(𝓤 α).basis_sets.cauchy_iff
lemma cauchy_iff {f : filter α} :
cauchy f ↔ (ne_bot f ∧ (∀ s ∈ 𝓤 α, ∃t∈f, t ×ˢ t ⊆ s)) :=
cauchy_iff'.trans $ by simp only [subset_def, prod.forall, mem_prod_eq, and_imp, id, ball_mem_comm]
lemma cauchy.ultrafilter_of {l : filter α} (h : cauchy l) :
cauchy (@ultrafilter.of _ l h.1 : filter α) :=
begin
haveI := h.1,
have := ultrafilter.of_le l,
exact ⟨ultrafilter.ne_bot _, (filter.prod_mono this this).trans h.2⟩
end
lemma cauchy_map_iff {l : filter β} {f : β → α} :
cauchy (l.map f) ↔ (ne_bot l ∧ tendsto (λp:β×β, (f p.1, f p.2)) (l ×ᶠ l) (𝓤 α)) :=
by rw [cauchy, map_ne_bot_iff, prod_map_map_eq, tendsto]
lemma cauchy_map_iff' {l : filter β} [hl : ne_bot l] {f : β → α} :
cauchy (l.map f) ↔ tendsto (λp:β×β, (f p.1, f p.2)) (l ×ᶠ l) (𝓤 α) :=
cauchy_map_iff.trans $ and_iff_right hl
lemma cauchy.mono {f g : filter α} [hg : ne_bot g] (h_c : cauchy f) (h_le : g ≤ f) : cauchy g :=
⟨hg, le_trans (filter.prod_mono h_le h_le) h_c.right⟩
lemma cauchy.mono' {f g : filter α} (h_c : cauchy f) (hg : ne_bot g) (h_le : g ≤ f) : cauchy g :=
h_c.mono h_le
lemma cauchy_nhds {a : α} : cauchy (𝓝 a) :=
⟨nhds_ne_bot, nhds_prod_eq.symm.trans_le (nhds_le_uniformity a)⟩
lemma cauchy_pure {a : α} : cauchy (pure a) :=
cauchy_nhds.mono (pure_le_nhds a)
lemma filter.tendsto.cauchy_map {l : filter β} [ne_bot l] {f : β → α} {a : α}
(h : tendsto f l (𝓝 a)) :
cauchy (map f l) :=
cauchy_nhds.mono h
lemma cauchy.prod [uniform_space β] {f : filter α} {g : filter β} (hf : cauchy f) (hg : cauchy g) :
cauchy (f ×ᶠ g) :=
begin
refine ⟨hf.1.prod hg.1, _⟩,
simp only [uniformity_prod, le_inf_iff, ← map_le_iff_le_comap, ← prod_map_map_eq],
exact ⟨le_trans (prod_mono tendsto_fst tendsto_fst) hf.2,
le_trans (prod_mono tendsto_snd tendsto_snd) hg.2⟩
end
/-- The common part of the proofs of `le_nhds_of_cauchy_adhp` and
`sequentially_complete.le_nhds_of_seq_tendsto_nhds`: if for any entourage `s`
one can choose a set `t ∈ f` of diameter `s` such that it contains a point `y`
with `(x, y) ∈ s`, then `f` converges to `x`. -/
lemma le_nhds_of_cauchy_adhp_aux {f : filter α} {x : α}
(adhs : ∀ s ∈ 𝓤 α, ∃ t ∈ f, (t ×ˢ t ⊆ s) ∧ ∃ y, (x, y) ∈ s ∧ y ∈ t) :
f ≤ 𝓝 x :=
begin
-- Consider a neighborhood `s` of `x`
assume s hs,
-- Take an entourage twice smaller than `s`
rcases comp_mem_uniformity_sets (mem_nhds_uniformity_iff_right.1 hs) with ⟨U, U_mem, hU⟩,
-- Take a set `t ∈ f`, `t × t ⊆ U`, and a point `y ∈ t` such that `(x, y) ∈ U`
rcases adhs U U_mem with ⟨t, t_mem, ht, y, hxy, hy⟩,
apply mem_of_superset t_mem,
-- Given a point `z ∈ t`, we have `(x, y) ∈ U` and `(y, z) ∈ t × t ⊆ U`, hence `z ∈ s`
exact (λ z hz, hU (prod_mk_mem_comp_rel hxy (ht $ mk_mem_prod hy hz)) rfl)
end
/-- If `x` is an adherent (cluster) point for a Cauchy filter `f`, then it is a limit point
for `f`. -/
lemma le_nhds_of_cauchy_adhp {f : filter α} {x : α} (hf : cauchy f)
(adhs : cluster_pt x f) : f ≤ 𝓝 x :=
le_nhds_of_cauchy_adhp_aux
begin
assume s hs,
obtain ⟨t, t_mem, ht⟩ : ∃ t ∈ f, t ×ˢ t ⊆ s,
from (cauchy_iff.1 hf).2 s hs,
use [t, t_mem, ht],
exact (forall_mem_nonempty_iff_ne_bot.2 adhs _
(inter_mem_inf (mem_nhds_left x hs) t_mem ))
end
lemma le_nhds_iff_adhp_of_cauchy {f : filter α} {x : α} (hf : cauchy f) :
f ≤ 𝓝 x ↔ cluster_pt x f :=
⟨assume h, cluster_pt.of_le_nhds' h hf.1, le_nhds_of_cauchy_adhp hf⟩
lemma cauchy.map [uniform_space β] {f : filter α} {m : α → β}
(hf : cauchy f) (hm : uniform_continuous m) : cauchy (map m f) :=
⟨hf.1.map _,
calc map m f ×ᶠ map m f = map (λp:α×α, (m p.1, m p.2)) (f ×ᶠ f) : filter.prod_map_map_eq
... ≤ map (λp:α×α, (m p.1, m p.2)) (𝓤 α) : map_mono hf.right
... ≤ 𝓤 β : hm⟩
lemma cauchy.comap [uniform_space β] {f : filter β} {m : α → β}
(hf : cauchy f) (hm : comap (λp:α×α, (m p.1, m p.2)) (𝓤 β) ≤ 𝓤 α)
[ne_bot (comap m f)] : cauchy (comap m f) :=
⟨‹_›,
calc comap m f ×ᶠ comap m f = comap (λp:α×α, (m p.1, m p.2)) (f ×ᶠ f) : filter.prod_comap_comap_eq
... ≤ comap (λp:α×α, (m p.1, m p.2)) (𝓤 β) : comap_mono hf.right
... ≤ 𝓤 α : hm⟩
lemma cauchy.comap' [uniform_space β] {f : filter β} {m : α → β}
(hf : cauchy f) (hm : comap (λp:α×α, (m p.1, m p.2)) (𝓤 β) ≤ 𝓤 α)
(hb : ne_bot (comap m f)) : cauchy (comap m f) :=
hf.comap hm
/-- Cauchy sequences. Usually defined on ℕ, but often it is also useful to say that a function
defined on ℝ is Cauchy at +∞ to deduce convergence. Therefore, we define it in a type class that
is general enough to cover both ℕ and ℝ, which are the main motivating examples. -/
def cauchy_seq [semilattice_sup β] (u : β → α) := cauchy (at_top.map u)
lemma cauchy_seq.tendsto_uniformity [semilattice_sup β] {u : β → α} (h : cauchy_seq u) :
tendsto (prod.map u u) at_top (𝓤 α) :=
by simpa only [tendsto, prod_map_map_eq', prod_at_top_at_top_eq] using h.right
lemma cauchy_seq.nonempty [semilattice_sup β] {u : β → α} (hu : cauchy_seq u) : nonempty β :=
@nonempty_of_ne_bot _ _ $ (map_ne_bot_iff _).1 hu.1
lemma cauchy_seq.mem_entourage {β : Type*} [semilattice_sup β] {u : β → α}
(h : cauchy_seq u) {V : set (α × α)} (hV : V ∈ 𝓤 α) :
∃ k₀, ∀ i j, k₀ ≤ i → k₀ ≤ j → (u i, u j) ∈ V :=
begin
haveI := h.nonempty,
have := h.tendsto_uniformity, rw ← prod_at_top_at_top_eq at this,
simpa [maps_to] using at_top_basis.prod_self.tendsto_left_iff.1 this V hV
end
lemma filter.tendsto.cauchy_seq [semilattice_sup β] [nonempty β] {f : β → α} {x}
(hx : tendsto f at_top (𝓝 x)) :
cauchy_seq f :=
hx.cauchy_map
lemma cauchy_seq_const [semilattice_sup β] [nonempty β] (x : α) : cauchy_seq (λ n : β, x) :=
tendsto_const_nhds.cauchy_seq
lemma cauchy_seq_iff_tendsto [nonempty β] [semilattice_sup β] {u : β → α} :
cauchy_seq u ↔ tendsto (prod.map u u) at_top (𝓤 α) :=
cauchy_map_iff'.trans $ by simp only [prod_at_top_at_top_eq, prod.map_def]
lemma cauchy_seq.comp_tendsto {γ} [semilattice_sup β] [semilattice_sup γ] [nonempty γ]
{f : β → α} (hf : cauchy_seq f) {g : γ → β} (hg : tendsto g at_top at_top) :
cauchy_seq (f ∘ g) :=
cauchy_seq_iff_tendsto.2 $ hf.tendsto_uniformity.comp (hg.prod_at_top hg)
lemma cauchy_seq.comp_injective [semilattice_sup β] [no_max_order β] [nonempty β]
{u : ℕ → α} (hu : cauchy_seq u) {f : β → ℕ} (hf : injective f) :
cauchy_seq (u ∘ f) :=
hu.comp_tendsto $ nat.cofinite_eq_at_top ▸ hf.tendsto_cofinite.mono_left at_top_le_cofinite
lemma function.bijective.cauchy_seq_comp_iff {f : ℕ → ℕ} (hf : bijective f) (u : ℕ → α) :
cauchy_seq (u ∘ f) ↔ cauchy_seq u :=
begin
refine ⟨λ H, _, λ H, H.comp_injective hf.injective⟩,
lift f to ℕ ≃ ℕ using hf,
simpa only [(∘), f.apply_symm_apply] using H.comp_injective f.symm.injective
end
lemma cauchy_seq.subseq_subseq_mem {V : ℕ → set (α × α)} (hV : ∀ n, V n ∈ 𝓤 α)
{u : ℕ → α} (hu : cauchy_seq u)
{f g : ℕ → ℕ} (hf : tendsto f at_top at_top) (hg : tendsto g at_top at_top) :
∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, ((u ∘ f ∘ φ) n, (u ∘ g ∘ φ) n) ∈ V n :=
begin
rw cauchy_seq_iff_tendsto at hu,
exact ((hu.comp $ hf.prod_at_top hg).comp tendsto_at_top_diagonal).subseq_mem hV,
end
lemma cauchy_seq_iff' {u : ℕ → α} :
cauchy_seq u ↔ ∀ V ∈ 𝓤 α, ∀ᶠ k in at_top, k ∈ (prod.map u u) ⁻¹' V :=
by simpa only [cauchy_seq_iff_tendsto]
lemma cauchy_seq_iff {u : ℕ → α} :
cauchy_seq u ↔ ∀ V ∈ 𝓤 α, ∃ N, ∀ k ≥ N, ∀ l ≥ N, (u k, u l) ∈ V :=
by simp [cauchy_seq_iff', filter.eventually_at_top_prod_self', prod_map]
lemma cauchy_seq.prod_map {γ δ} [uniform_space β] [semilattice_sup γ] [semilattice_sup δ]
{u : γ → α} {v : δ → β}
(hu : cauchy_seq u) (hv : cauchy_seq v) : cauchy_seq (prod.map u v) :=
by simpa only [cauchy_seq, prod_map_map_eq', prod_at_top_at_top_eq] using hu.prod hv
lemma cauchy_seq.prod {γ} [uniform_space β] [semilattice_sup γ] {u : γ → α} {v : γ → β}
(hu : cauchy_seq u) (hv : cauchy_seq v) : cauchy_seq (λ x, (u x, v x)) :=
begin
haveI := hu.nonempty,
exact (hu.prod hv).mono (tendsto.prod_mk le_rfl le_rfl)
end
lemma cauchy_seq.eventually_eventually [semilattice_sup β] {u : β → α} (hu : cauchy_seq u)
{V : set (α × α)} (hV : V ∈ 𝓤 α) :
∀ᶠ k in at_top, ∀ᶠ l in at_top, (u k, u l) ∈ V :=
eventually_at_top_curry $ hu.tendsto_uniformity hV
lemma uniform_continuous.comp_cauchy_seq {γ} [uniform_space β] [semilattice_sup γ]
{f : α → β} (hf : uniform_continuous f) {u : γ → α} (hu : cauchy_seq u) :
cauchy_seq (f ∘ u) :=
hu.map hf
lemma cauchy_seq.subseq_mem {V : ℕ → set (α × α)} (hV : ∀ n, V n ∈ 𝓤 α)
{u : ℕ → α} (hu : cauchy_seq u) :
∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, (u $ φ (n + 1), u $ φ n) ∈ V n :=
begin
have : ∀ n, ∃ N, ∀ k ≥ N, ∀ l ≥ k, (u l, u k) ∈ V n,
{ intro n,
rw [cauchy_seq_iff] at hu,
rcases hu _ (hV n) with ⟨N, H⟩,
exact ⟨N, λ k hk l hl, H _ (le_trans hk hl) _ hk ⟩ },
obtain ⟨φ : ℕ → ℕ, φ_extr : strict_mono φ, hφ : ∀ n, ∀ l ≥ φ n, (u l, u $ φ n) ∈ V n⟩ :=
extraction_forall_of_eventually' this,
exact ⟨φ, φ_extr, λ n, hφ _ _ (φ_extr $ lt_add_one n).le⟩,
end
lemma filter.tendsto.subseq_mem_entourage {V : ℕ → set (α × α)} (hV : ∀ n, V n ∈ 𝓤 α)
{u : ℕ → α} {a : α} (hu : tendsto u at_top (𝓝 a)) :
∃ φ : ℕ → ℕ, strict_mono φ ∧ (u (φ 0), a) ∈ V 0 ∧ ∀ n, (u $ φ (n + 1), u $ φ n) ∈ V (n + 1) :=
begin
rcases mem_at_top_sets.1 (hu (ball_mem_nhds a (symm_le_uniformity $ hV 0))) with ⟨n, hn⟩,
rcases (hu.comp (tendsto_add_at_top_nat n)).cauchy_seq.subseq_mem (λ n, hV (n + 1))
with ⟨φ, φ_mono, hφV⟩,
exact ⟨λ k, φ k + n, φ_mono.add_const _, hn _ le_add_self, hφV⟩
end
/-- If a Cauchy sequence has a convergent subsequence, then it converges. -/
lemma tendsto_nhds_of_cauchy_seq_of_subseq
[semilattice_sup β] {u : β → α} (hu : cauchy_seq u)
{ι : Type*} {f : ι → β} {p : filter ι} [ne_bot p]
(hf : tendsto f p at_top) {a : α} (ha : tendsto (u ∘ f) p (𝓝 a)) :
tendsto u at_top (𝓝 a) :=
le_nhds_of_cauchy_adhp hu (map_cluster_pt_of_comp hf ha)
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma filter.has_basis.cauchy_seq_iff {γ} [nonempty β] [semilattice_sup β] {u : β → α}
{p : γ → Prop} {s : γ → set (α × α)} (h : (𝓤 α).has_basis p s) :
cauchy_seq u ↔ ∀ i, p i → ∃N, ∀m n≥N, (u m, u n) ∈ s i :=
begin
rw [cauchy_seq_iff_tendsto, ← prod_at_top_at_top_eq],
refine (at_top_basis.prod_self.tendsto_iff h).trans _,
simp only [exists_prop, true_and, maps_to, preimage, subset_def, prod.forall,
mem_prod_eq, mem_set_of_eq, mem_Ici, and_imp, prod.map, ge_iff_le, @forall_swap (_ ≤ _) β]
end
lemma filter.has_basis.cauchy_seq_iff' {γ} [nonempty β] [semilattice_sup β] {u : β → α}
{p : γ → Prop} {s : γ → set (α × α)} (H : (𝓤 α).has_basis p s) :
cauchy_seq u ↔ ∀ i, p i → ∃N, ∀n≥N, (u n, u N) ∈ s i :=
begin
refine H.cauchy_seq_iff.trans ⟨λ h i hi, _, λ h i hi, _⟩,
{ exact (h i hi).imp (λ N hN n hn, hN n hn N le_rfl) },
{ rcases comp_symm_of_uniformity (H.mem_of_mem hi) with ⟨t, ht, ht', hts⟩,
rcases H.mem_iff.1 ht with ⟨j, hj, hjt⟩,
refine (h j hj).imp (λ N hN m hm n hn, hts ⟨u N, hjt _, ht' $ hjt _⟩),
{ exact hN m hm },
{ exact hN n hn } }
end
lemma cauchy_seq_of_controlled [semilattice_sup β] [nonempty β]
(U : β → set (α × α)) (hU : ∀ s ∈ 𝓤 α, ∃ n, U n ⊆ s)
{f : β → α} (hf : ∀ {N m n : β}, N ≤ m → N ≤ n → (f m, f n) ∈ U N) :
cauchy_seq f :=
cauchy_seq_iff_tendsto.2
begin
assume s hs,
rw [mem_map, mem_at_top_sets],
cases hU s hs with N hN,
refine ⟨(N, N), λ mn hmn, _⟩,
cases mn with m n,
exact hN (hf hmn.1 hmn.2)
end
lemma is_complete_iff_cluster_pt {s : set α} :
is_complete s ↔ ∀ l, cauchy l → l ≤ 𝓟 s → ∃ x ∈ s, cluster_pt x l :=
forall₃_congr $ λ l hl hls, exists₂_congr $ λ x hx, le_nhds_iff_adhp_of_cauchy hl
lemma is_complete_iff_ultrafilter {s : set α} :
is_complete s ↔ ∀ l : ultrafilter α, cauchy (l : filter α) → ↑l ≤ 𝓟 s → ∃ x ∈ s, ↑l ≤ 𝓝 x :=
begin
refine ⟨λ h l, h l, λ H, is_complete_iff_cluster_pt.2 $ λ l hl hls, _⟩,
haveI := hl.1,
rcases H (ultrafilter.of l) hl.ultrafilter_of ((ultrafilter.of_le l).trans hls)
with ⟨x, hxs, hxl⟩,
exact ⟨x, hxs, (cluster_pt.of_le_nhds hxl).mono (ultrafilter.of_le l)⟩
end
lemma is_complete_iff_ultrafilter' {s : set α} :
is_complete s ↔ ∀ l : ultrafilter α, cauchy (l : filter α) → s ∈ l → ∃ x ∈ s, ↑l ≤ 𝓝 x :=
is_complete_iff_ultrafilter.trans $ by simp only [le_principal_iff, ultrafilter.mem_coe]
protected lemma is_complete.union {s t : set α} (hs : is_complete s) (ht : is_complete t) :
is_complete (s ∪ t) :=
begin
simp only [is_complete_iff_ultrafilter', ultrafilter.union_mem_iff, or_imp_distrib] at *,
exact λ l hl, ⟨λ hsl, (hs l hl hsl).imp $ λ x hx, ⟨or.inl hx.fst, hx.snd⟩,
λ htl, (ht l hl htl).imp $ λ x hx, ⟨or.inr hx.fst, hx.snd⟩⟩
end
lemma is_complete_Union_separated {ι : Sort*} {s : ι → set α} (hs : ∀ i, is_complete (s i))
{U : set (α × α)} (hU : U ∈ 𝓤 α) (hd : ∀ (i j : ι) (x ∈ s i) (y ∈ s j), (x, y) ∈ U → i = j) :
is_complete (⋃ i, s i) :=
begin
set S := ⋃ i, s i,
intros l hl hls,
rw le_principal_iff at hls,
casesI cauchy_iff.1 hl with hl_ne hl',
obtain ⟨t, htS, htl, htU⟩ : ∃ t ⊆ S, t ∈ l ∧ t ×ˢ t ⊆ U,
{ rcases hl' U hU with ⟨t, htl, htU⟩,
exact ⟨t ∩ S, inter_subset_right _ _, inter_mem htl hls,
(set.prod_mono (inter_subset_left _ _) (inter_subset_left _ _)).trans htU⟩ },
obtain ⟨i, hi⟩ : ∃ i, t ⊆ s i,
{ rcases filter.nonempty_of_mem htl with ⟨x, hx⟩,
rcases mem_Union.1 (htS hx) with ⟨i, hi⟩,
refine ⟨i, λ y hy, _⟩,
rcases mem_Union.1 (htS hy) with ⟨j, hj⟩,
convert hj, exact hd i j x hi y hj (htU $ mk_mem_prod hx hy) },
rcases hs i l hl (le_principal_iff.2 $ mem_of_superset htl hi) with ⟨x, hxs, hlx⟩,
exact ⟨x, mem_Union.2 ⟨i, hxs⟩, hlx⟩
end
/-- A complete space is defined here using uniformities. A uniform space
is complete if every Cauchy filter converges. -/
class complete_space (α : Type u) [uniform_space α] : Prop :=
(complete : ∀{f:filter α}, cauchy f → ∃x, f ≤ 𝓝 x)
lemma complete_univ {α : Type u} [uniform_space α] [complete_space α] :
is_complete (univ : set α) :=
begin
assume f hf _,
rcases complete_space.complete hf with ⟨x, hx⟩,
exact ⟨x, mem_univ x, hx⟩
end
instance complete_space.prod [uniform_space β] [complete_space α] [complete_space β] :
complete_space (α × β) :=
{ complete := λ f hf,
let ⟨x1, hx1⟩ := complete_space.complete $ hf.map uniform_continuous_fst in
let ⟨x2, hx2⟩ := complete_space.complete $ hf.map uniform_continuous_snd in
⟨(x1, x2), by rw [nhds_prod_eq, filter.prod_def];
from filter.le_lift (λ s hs, filter.le_lift' $ λ t ht,
have H1 : prod.fst ⁻¹' s ∈ f.sets := hx1 hs,
have H2 : prod.snd ⁻¹' t ∈ f.sets := hx2 ht,
filter.inter_mem H1 H2)⟩ }
/--If `univ` is complete, the space is a complete space -/
lemma complete_space_of_is_complete_univ (h : is_complete (univ : set α)) : complete_space α :=
⟨λ f hf, let ⟨x, _, hx⟩ := h f hf ((@principal_univ α).symm ▸ le_top) in ⟨x, hx⟩⟩
lemma complete_space_iff_is_complete_univ :
complete_space α ↔ is_complete (univ : set α) :=
⟨@complete_univ α _, complete_space_of_is_complete_univ⟩
lemma complete_space_iff_ultrafilter :
complete_space α ↔ ∀ l : ultrafilter α, cauchy (l : filter α) → ∃ x : α, ↑l ≤ 𝓝 x :=
by simp [complete_space_iff_is_complete_univ, is_complete_iff_ultrafilter]
lemma cauchy_iff_exists_le_nhds [complete_space α] {l : filter α} [ne_bot l] :
cauchy l ↔ (∃x, l ≤ 𝓝 x) :=
⟨complete_space.complete, assume ⟨x, hx⟩, cauchy_nhds.mono hx⟩
lemma cauchy_map_iff_exists_tendsto [complete_space α] {l : filter β} {f : β → α} [ne_bot l] :
cauchy (l.map f) ↔ (∃x, tendsto f l (𝓝 x)) :=
cauchy_iff_exists_le_nhds
/-- A Cauchy sequence in a complete space converges -/
theorem cauchy_seq_tendsto_of_complete [semilattice_sup β] [complete_space α]
{u : β → α} (H : cauchy_seq u) : ∃x, tendsto u at_top (𝓝 x) :=
complete_space.complete H
/-- If `K` is a complete subset, then any cauchy sequence in `K` converges to a point in `K` -/
lemma cauchy_seq_tendsto_of_is_complete [semilattice_sup β] {K : set α} (h₁ : is_complete K)
{u : β → α} (h₂ : ∀ n, u n ∈ K) (h₃ : cauchy_seq u) : ∃ v ∈ K, tendsto u at_top (𝓝 v) :=
h₁ _ h₃ $ le_principal_iff.2 $ mem_map_iff_exists_image.2 ⟨univ, univ_mem,
by { simp only [image_univ], rintros _ ⟨n, rfl⟩, exact h₂ n }⟩
theorem cauchy.le_nhds_Lim [complete_space α] [nonempty α] {f : filter α} (hf : cauchy f) :
f ≤ 𝓝 (Lim f) :=
le_nhds_Lim (complete_space.complete hf)
theorem cauchy_seq.tendsto_lim [semilattice_sup β] [complete_space α] [nonempty α] {u : β → α}
(h : cauchy_seq u) :
tendsto u at_top (𝓝 $ lim at_top u) :=
h.le_nhds_Lim
lemma is_closed.is_complete [complete_space α] {s : set α}
(h : is_closed s) : is_complete s :=
λ f cf fs, let ⟨x, hx⟩ := complete_space.complete cf in
⟨x, is_closed_iff_cluster_pt.mp h x (cf.left.mono (le_inf hx fs)), hx⟩
/-- A set `s` is totally bounded if for every entourage `d` there is a finite
set of points `t` such that every element of `s` is `d`-near to some element of `t`. -/
def totally_bounded (s : set α) : Prop :=
∀d ∈ 𝓤 α, ∃t : set α, t.finite ∧ s ⊆ (⋃ y ∈ t, {x | (x, y) ∈ d})
theorem totally_bounded.exists_subset {s : set α} (hs : totally_bounded s) {U : set (α × α)}
(hU : U ∈ 𝓤 α) :
∃ t ⊆ s, set.finite t ∧ s ⊆ ⋃ y ∈ t, {x | (x, y) ∈ U} :=
begin
rcases comp_symm_of_uniformity hU with ⟨r, hr, rs, rU⟩,
rcases hs r hr with ⟨k, fk, ks⟩,
let u := k ∩ {y | ∃ x ∈ s, (x, y) ∈ r},
choose hk f hfs hfr using λ x : u, x.coe_prop,
refine ⟨range f, _, _, _⟩,
{ exact range_subset_iff.2 hfs },
{ haveI : fintype u := (fk.inter_of_left _).fintype,
exact finite_range f },
{ intros x xs,
obtain ⟨y, hy, xy⟩ : ∃ y ∈ k, (x, y) ∈ r, from mem_Union₂.1 (ks xs),
rw [bUnion_range, mem_Union],
set z : ↥u := ⟨y, hy, ⟨x, xs, xy⟩⟩,
exact ⟨z, rU $ mem_comp_rel.2 ⟨y, xy, rs (hfr z)⟩⟩ }
end
theorem totally_bounded_iff_subset {s : set α} : totally_bounded s ↔
∀d ∈ 𝓤 α, ∃t ⊆ s, set.finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) :=
⟨λ H d hd, H.exists_subset hd, λ H d hd, let ⟨t, _, ht⟩ := H d hd in ⟨t, ht⟩⟩
lemma filter.has_basis.totally_bounded_iff {ι} {p : ι → Prop} {U : ι → set (α × α)}
(H : (𝓤 α).has_basis p U) {s : set α} :
totally_bounded s ↔ ∀ i, p i → ∃ t : set α, set.finite t ∧ s ⊆ ⋃ y ∈ t, {x | (x, y) ∈ U i} :=
H.forall_iff $ λ U V hUV h, h.imp $ λ t ht, ⟨ht.1, ht.2.trans $ Union₂_mono $ λ x hx y hy, hUV hy⟩
lemma totally_bounded_of_forall_symm {s : set α}
(h : ∀ V ∈ 𝓤 α, symmetric_rel V → ∃ t : set α, set.finite t ∧ s ⊆ ⋃ y ∈ t, ball y V) :
totally_bounded s :=
uniform_space.has_basis_symmetric.totally_bounded_iff.2 $ λ V hV,
by simpa only [ball_eq_of_symmetry hV.2] using h V hV.1 hV.2
lemma totally_bounded_subset {s₁ s₂ : set α} (hs : s₁ ⊆ s₂)
(h : totally_bounded s₂) : totally_bounded s₁ :=
assume d hd, let ⟨t, ht₁, ht₂⟩ := h d hd in ⟨t, ht₁, subset.trans hs ht₂⟩
lemma totally_bounded_empty : totally_bounded (∅ : set α) :=
λ d hd, ⟨∅, finite_empty, empty_subset _⟩
/-- The closure of a totally bounded set is totally bounded. -/
lemma totally_bounded.closure {s : set α} (h : totally_bounded s) :
totally_bounded (closure s) :=
uniformity_has_basis_closed.totally_bounded_iff.2 $ λ V hV, let ⟨t, htf, hst⟩ := h V hV.1
in ⟨t, htf, closure_minimal hst $ is_closed_bUnion htf $
λ y hy, hV.2.preimage (continuous_id.prod_mk continuous_const)⟩
/-- The image of a totally bounded set under a uniformly continuous map is totally bounded. -/
lemma totally_bounded.image [uniform_space β] {f : α → β} {s : set α}
(hs : totally_bounded s) (hf : uniform_continuous f) : totally_bounded (f '' s) :=
assume t ht,
have {p:α×α | (f p.1, f p.2) ∈ t} ∈ 𝓤 α,
from hf ht,
let ⟨c, hfc, hct⟩ := hs _ this in
⟨f '' c, hfc.image f,
begin
simp [image_subset_iff],
simp [subset_def] at hct,
intros x hx, simp,
exact hct x hx
end⟩
lemma ultrafilter.cauchy_of_totally_bounded {s : set α} (f : ultrafilter α)
(hs : totally_bounded s) (h : ↑f ≤ 𝓟 s) : cauchy (f : filter α) :=
⟨f.ne_bot', assume t ht,
let ⟨t', ht'₁, ht'_symm, ht'_t⟩ := comp_symm_of_uniformity ht in
let ⟨i, hi, hs_union⟩ := hs t' ht'₁ in
have (⋃y∈i, {x | (x,y) ∈ t'}) ∈ f,
from mem_of_superset (le_principal_iff.mp h) hs_union,
have ∃y∈i, {x | (x,y) ∈ t'} ∈ f,
from (ultrafilter.finite_bUnion_mem_iff hi).1 this,
let ⟨y, hy, hif⟩ := this in
have {x | (x,y) ∈ t'} ×ˢ {x | (x,y) ∈ t'} ⊆ comp_rel t' t',
from assume ⟨x₁, x₂⟩ ⟨(h₁ : (x₁, y) ∈ t'), (h₂ : (x₂, y) ∈ t')⟩,
⟨y, h₁, ht'_symm h₂⟩,
mem_of_superset (prod_mem_prod hif hif) (subset.trans this ht'_t)⟩
lemma totally_bounded_iff_filter {s : set α} :
totally_bounded s ↔ (∀f, ne_bot f → f ≤ 𝓟 s → ∃c ≤ f, cauchy c) :=
begin
split,
{ introsI H f hf hfs,
exact ⟨ultrafilter.of f, ultrafilter.of_le f,
(ultrafilter.of f).cauchy_of_totally_bounded H ((ultrafilter.of_le f).trans hfs)⟩ },
{ intros H d hd,
contrapose! H with hd_cover,
set f := ⨅ t : finset α, 𝓟 (s \ ⋃ y ∈ t, {x | (x, y) ∈ d}),
have : ne_bot f,
{ refine infi_ne_bot_of_directed' (directed_of_sup _) _,
{ intros t₁ t₂ h,
exact principal_mono.2 (diff_subset_diff_right $ bUnion_subset_bUnion_left h) },
{ intro t,
simpa [nonempty_diff] using hd_cover t t.finite_to_set } },
have : f ≤ 𝓟 s, from infi_le_of_le ∅ (by simp),
refine ⟨f, ‹_›, ‹_›, λ c hcf hc, _⟩,
rcases mem_prod_same_iff.1 (hc.2 hd) with ⟨m, hm, hmd⟩,
have : m ∩ s ∈ c, from inter_mem hm (le_principal_iff.mp (hcf.trans ‹_›)),
rcases hc.1.nonempty_of_mem this with ⟨y, hym, hys⟩,
set ys := ⋃ y' ∈ ({y} : finset α), {x | (x, y') ∈ d},
have : m ⊆ ys, by simpa [ys] using λ x hx, hmd (mk_mem_prod hx hym),
have : c ≤ 𝓟 (s \ ys) := hcf.trans (infi_le_of_le {y} le_rfl),
refine hc.1.ne (empty_mem_iff_bot.mp _),
filter_upwards [le_principal_iff.1 this, hm],
refine λ x hx hxm, hx.2 _,
simpa [ys] using hmd (mk_mem_prod hxm hym) }
end
lemma totally_bounded_iff_ultrafilter {s : set α} :
totally_bounded s ↔ (∀f : ultrafilter α, ↑f ≤ 𝓟 s → cauchy (f : filter α)) :=
begin
refine ⟨λ hs f, f.cauchy_of_totally_bounded hs, λ H, totally_bounded_iff_filter.2 _⟩,
introsI f hf hfs,
exact ⟨ultrafilter.of f, ultrafilter.of_le f, H _ ((ultrafilter.of_le f).trans hfs)⟩
end
lemma compact_iff_totally_bounded_complete {s : set α} :
is_compact s ↔ totally_bounded s ∧ is_complete s :=
⟨λ hs, ⟨totally_bounded_iff_ultrafilter.2 (λ f hf,
let ⟨x, xs, fx⟩ := is_compact_iff_ultrafilter_le_nhds.1 hs f hf in cauchy_nhds.mono fx),
λ f fc fs,
let ⟨a, as, fa⟩ := @hs f fc.1 fs in
⟨a, as, le_nhds_of_cauchy_adhp fc fa⟩⟩,
λ ⟨ht, hc⟩, is_compact_iff_ultrafilter_le_nhds.2
(λf hf, hc _ (totally_bounded_iff_ultrafilter.1 ht f hf) hf)⟩
protected lemma is_compact.totally_bounded {s : set α} (h : is_compact s) : totally_bounded s :=
(compact_iff_totally_bounded_complete.1 h).1
protected lemma is_compact.is_complete {s : set α} (h : is_compact s) : is_complete s :=
(compact_iff_totally_bounded_complete.1 h).2
@[priority 100] -- see Note [lower instance priority]
instance complete_of_compact {α : Type u} [uniform_space α] [compact_space α] : complete_space α :=
⟨λf hf, by simpa using (compact_iff_totally_bounded_complete.1 compact_univ).2 f hf⟩
lemma compact_of_totally_bounded_is_closed [complete_space α] {s : set α}
(ht : totally_bounded s) (hc : is_closed s) : is_compact s :=
(@compact_iff_totally_bounded_complete α _ s).2 ⟨ht, hc.is_complete⟩
/-!
### Sequentially complete space
In this section we prove that a uniform space is complete provided that it is sequentially complete
(i.e., any Cauchy sequence converges) and its uniformity filter admits a countable generating set.
In particular, this applies to (e)metric spaces, see the files `topology/metric_space/emetric_space`
and `topology/metric_space/basic`.
More precisely, we assume that there is a sequence of entourages `U_n` such that any other
entourage includes one of `U_n`. Then any Cauchy filter `f` generates a decreasing sequence of
sets `s_n ∈ f` such that `s_n × s_n ⊆ U_n`. Choose a sequence `x_n∈s_n`. It is easy to show
that this is a Cauchy sequence. If this sequence converges to some `a`, then `f ≤ 𝓝 a`. -/
namespace sequentially_complete
variables {f : filter α} (hf : cauchy f) {U : ℕ → set (α × α)}
(U_mem : ∀ n, U n ∈ 𝓤 α) (U_le : ∀ s ∈ 𝓤 α, ∃ n, U n ⊆ s)
open set finset
noncomputable theory
/-- An auxiliary sequence of sets approximating a Cauchy filter. -/
def set_seq_aux (n : ℕ) : {s : set α // ∃ (_ : s ∈ f), s ×ˢ s ⊆ U n } :=
indefinite_description _ $ (cauchy_iff.1 hf).2 (U n) (U_mem n)
/-- Given a Cauchy filter `f` and a sequence `U` of entourages, `set_seq` provides
an antitone sequence of sets `s n ∈ f` such that `s n ×ˢ s n ⊆ U`. -/
def set_seq (n : ℕ) : set α := ⋂ m ∈ set.Iic n, (set_seq_aux hf U_mem m).val
lemma set_seq_mem (n : ℕ) : set_seq hf U_mem n ∈ f :=
(bInter_mem (finite_le_nat n)).2 (λ m _, (set_seq_aux hf U_mem m).2.fst)
lemma set_seq_mono ⦃m n : ℕ⦄ (h : m ≤ n) : set_seq hf U_mem n ⊆ set_seq hf U_mem m :=
bInter_subset_bInter_left (λ k hk, le_trans hk h)
lemma set_seq_sub_aux (n : ℕ) : set_seq hf U_mem n ⊆ set_seq_aux hf U_mem n :=
bInter_subset_of_mem right_mem_Iic
lemma set_seq_prod_subset {N m n} (hm : N ≤ m) (hn : N ≤ n) :
set_seq hf U_mem m ×ˢ set_seq hf U_mem n ⊆ U N :=
begin
assume p hp,
refine (set_seq_aux hf U_mem N).2.snd ⟨_, _⟩;
apply set_seq_sub_aux,
exact set_seq_mono hf U_mem hm hp.1,
exact set_seq_mono hf U_mem hn hp.2
end
/-- A sequence of points such that `seq n ∈ set_seq n`. Here `set_seq` is an antitone
sequence of sets `set_seq n ∈ f` with diameters controlled by a given sequence
of entourages. -/
def seq (n : ℕ) : α := some $ hf.1.nonempty_of_mem (set_seq_mem hf U_mem n)
lemma seq_mem (n : ℕ) : seq hf U_mem n ∈ set_seq hf U_mem n :=
some_spec $ hf.1.nonempty_of_mem (set_seq_mem hf U_mem n)
lemma seq_pair_mem ⦃N m n : ℕ⦄ (hm : N ≤ m) (hn : N ≤ n) :
(seq hf U_mem m, seq hf U_mem n) ∈ U N :=
set_seq_prod_subset hf U_mem hm hn ⟨seq_mem hf U_mem m, seq_mem hf U_mem n⟩
include U_le
theorem seq_is_cauchy_seq : cauchy_seq $ seq hf U_mem :=
cauchy_seq_of_controlled U U_le $ seq_pair_mem hf U_mem
/-- If the sequence `sequentially_complete.seq` converges to `a`, then `f ≤ 𝓝 a`. -/
theorem le_nhds_of_seq_tendsto_nhds ⦃a : α⦄ (ha : tendsto (seq hf U_mem) at_top (𝓝 a)) :
f ≤ 𝓝 a :=
le_nhds_of_cauchy_adhp_aux
begin
assume s hs,
rcases U_le s hs with ⟨m, hm⟩,
rcases tendsto_at_top'.1 ha _ (mem_nhds_left a (U_mem m)) with ⟨n, hn⟩,
refine ⟨set_seq hf U_mem (max m n), set_seq_mem hf U_mem _, _,
seq hf U_mem (max m n), _, seq_mem hf U_mem _⟩,
{ have := le_max_left m n,
exact set.subset.trans (set_seq_prod_subset hf U_mem this this) hm },
{ exact hm (hn _ $ le_max_right m n) }
end
end sequentially_complete
namespace uniform_space
open sequentially_complete
variables [is_countably_generated (𝓤 α)]
/-- A uniform space is complete provided that (a) its uniformity filter has a countable basis;
(b) any sequence satisfying a "controlled" version of the Cauchy condition converges. -/
theorem complete_of_convergent_controlled_sequences (U : ℕ → set (α × α)) (U_mem : ∀ n, U n ∈ 𝓤 α)
(HU : ∀ u : ℕ → α, (∀ N m n, N ≤ m → N ≤ n → (u m, u n) ∈ U N) → ∃ a, tendsto u at_top (𝓝 a)) :
complete_space α :=
begin
obtain ⟨U', U'_mono, hU'⟩ := (𝓤 α).exists_antitone_seq,
have Hmem : ∀ n, U n ∩ U' n ∈ 𝓤 α,
from λ n, inter_mem (U_mem n) (hU'.2 ⟨n, subset.refl _⟩),
refine ⟨λ f hf, (HU (seq hf Hmem) (λ N m n hm hn, _)).imp $
le_nhds_of_seq_tendsto_nhds _ _ (λ s hs, _)⟩,
{ rcases (hU'.1 hs) with ⟨N, hN⟩,
exact ⟨N, subset.trans (inter_subset_right _ _) hN⟩ },
{ exact inter_subset_left _ _ (seq_pair_mem hf Hmem hm hn) }
end
/-- A sequentially complete uniform space with a countable basis of the uniformity filter is
complete. -/
theorem complete_of_cauchy_seq_tendsto
(H' : ∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) :
complete_space α :=
let ⟨U', U'_mono, hU'⟩ := (𝓤 α).exists_antitone_seq in
complete_of_convergent_controlled_sequences U' (λ n, hU'.2 ⟨n, subset.refl _⟩)
(λ u hu, H' u $ cauchy_seq_of_controlled U' (λ s hs, hU'.1 hs) hu)
variable (α)
@[priority 100]
instance first_countable_topology : first_countable_topology α :=
⟨λ a, by { rw nhds_eq_comap_uniformity, apply_instance }⟩
/-- A separable uniform space with countably generated uniformity filter is second countable:
one obtains a countable basis by taking the balls centered at points in a dense subset,
and with rational "radii" from a countable open symmetric antitone basis of `𝓤 α`. We do not
register this as an instance, as there is already an instance going in the other direction
from second countable spaces to separable spaces, and we want to avoid loops. -/
lemma second_countable_of_separable [separable_space α] : second_countable_topology α :=
begin
rcases exists_countable_dense α with ⟨s, hsc, hsd⟩,
obtain ⟨t : ℕ → set (α × α),
hto : ∀ (i : ℕ), t i ∈ (𝓤 α).sets ∧ is_open (t i) ∧ symmetric_rel (t i),
h_basis : (𝓤 α).has_antitone_basis t⟩ :=
(@uniformity_has_basis_open_symmetric α _).exists_antitone_subbasis,
choose ht_mem hto hts using hto,
refine ⟨⟨⋃ (x ∈ s), range (λ k, ball x (t k)), hsc.bUnion (λ x hx, countable_range _), _⟩⟩,
refine (is_topological_basis_of_open_of_nhds _ _).eq_generate_from,
{ simp only [mem_Union₂, mem_range],
rintros _ ⟨x, hxs, k, rfl⟩,
exact is_open_ball x (hto k) },
{ intros x V hxV hVo,
simp only [mem_Union₂, mem_range, exists_prop],
rcases uniform_space.mem_nhds_iff.1 (is_open.mem_nhds hVo hxV) with ⟨U, hU, hUV⟩,
rcases comp_symm_of_uniformity hU with ⟨U', hU', hsymm, hUU'⟩,
rcases h_basis.to_has_basis.mem_iff.1 hU' with ⟨k, -, hk⟩,
rcases hsd.inter_open_nonempty (ball x $ t k) (is_open_ball x (hto k))
⟨x, uniform_space.mem_ball_self _ (ht_mem k)⟩ with ⟨y, hxy, hys⟩,
refine ⟨_, ⟨y, hys, k, rfl⟩, (hts k).subset hxy, λ z hz, _⟩,
exact hUV (ball_subset_of_comp_subset (hk hxy) hUU' (hk hz)) }
end
end uniform_space
|
6816264cb3892619b610b34e57099313e264f600 | f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58 | /tactic/rcases.lean | fd3580dfe47c1fa446fb272c589b2ce9ce873564 | [
"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 | 12,305 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.dlist tactic.cache
open lean lean.parser
namespace tactic
/-
These synonyms for `list` are used to clarify the meanings of the many
usages of lists in this module.
- `listΣ` is used where a list represents a disjunction, such as the
list of possible constructors of an inductive type.
- `listΠ` is used where a list represents a conjunction, such as the
list of arguments of an individual constructor.
These are merely type synonyms, and so are not checked for consistency
by the compiler.
The `def`/`local notation` combination makes Lean retain these
annotations in reported types.
-/
@[reducible] def list_Sigma := list
@[reducible] def list_Pi := list
local notation `listΣ` := list_Sigma
local notation `listΠ` := list_Pi
@[reducible] meta def goals := list expr
meta inductive rcases_patt : Type
| one : name → rcases_patt
| many : listΣ (listΠ rcases_patt) → rcases_patt
meta instance rcases_patt.inhabited : inhabited rcases_patt :=
⟨rcases_patt.one `_⟩
meta def rcases_patt.name : rcases_patt → name
| (rcases_patt.one n) := n
| _ := `_
meta instance rcases_patt.has_reflect : has_reflect rcases_patt
| (rcases_patt.one n) := `(_)
| (rcases_patt.many l) := `(λ l, rcases_patt.many l).subst $
by haveI := rcases_patt.has_reflect; exact list.reflect l
/--
The parser/printer uses an "inverted" meaning for the `many` constructor:
rather than representing a sum of products, here it represents a
product of sums. We fix this by applying `invert`, defined below, to
the result.
-/
meta inductive rcases_patt_inverted : Type
| one : name → rcases_patt_inverted
| many : listΠ (listΣ rcases_patt_inverted) → rcases_patt_inverted
meta instance rcases_patt_inverted.inhabited : inhabited rcases_patt_inverted :=
⟨rcases_patt_inverted.one `_⟩
meta instance rcases_patt_inverted.has_reflect : has_reflect rcases_patt_inverted
| (rcases_patt_inverted.one n) := `(_)
| (rcases_patt_inverted.many l) := `(λ l, rcases_patt_inverted.many l).subst $
by haveI := rcases_patt_inverted.has_reflect; exact list.reflect l
meta mutual def rcases_patt_inverted.invert, rcases_patt_inverted.invert_list
with rcases_patt_inverted.invert : listΣ rcases_patt_inverted → rcases_patt
| [rcases_patt_inverted.one n] := rcases_patt.one n
| l := rcases_patt.many (rcases_patt_inverted.invert_list l)
with rcases_patt_inverted.invert_list : listΣ rcases_patt_inverted → listΣ (listΠ rcases_patt)
| l := l.map $ λ p,
match p with
| rcases_patt_inverted.one n := [rcases_patt.one n]
| rcases_patt_inverted.many l := rcases_patt_inverted.invert <$> l
end
meta mutual def rcases_patt.invert, rcases_patt.invert_many, rcases_patt.invert_list, rcases_patt.invert'
with rcases_patt.invert : rcases_patt → listΣ rcases_patt_inverted
| (rcases_patt.one n) := [rcases_patt_inverted.one n]
| (rcases_patt.many ls) := rcases_patt.invert_many ls
with rcases_patt.invert_many : listΣ (listΠ rcases_patt) → listΣ rcases_patt_inverted
| [] := []
| [[rcases_patt.many ls@(_::_::_)]] := rcases_patt.invert_many ls
| (l::ls) := rcases_patt.invert' l :: rcases_patt.invert_many ls
with rcases_patt.invert_list : listΠ rcases_patt → listΠ (listΣ rcases_patt_inverted)
| [] := []
| [rcases_patt.many [l@(_::_::_)]] := rcases_patt.invert_list l
| (p::l) := rcases_patt.invert p :: rcases_patt.invert_list l
with rcases_patt.invert' : listΠ rcases_patt → rcases_patt_inverted
| [rcases_patt.one n] := rcases_patt_inverted.one n
| [] := rcases_patt_inverted.one `_
| ls := rcases_patt_inverted.many (rcases_patt.invert_list ls)
meta mutual def rcases_patt_inverted.format, rcases_patt_inverted.format_list
with rcases_patt_inverted.format : rcases_patt_inverted → format
| (rcases_patt_inverted.one n) := to_fmt n
| (rcases_patt_inverted.many []) := "⟨⟩"
| (rcases_patt_inverted.many ls) := "⟨" ++ format.group (format.nest 1 $
format.join $ list.intersperse ("," ++ format.line) $
ls.map (format.group ∘ rcases_patt_inverted.format_list)) ++ "⟩"
with rcases_patt_inverted.format_list : listΣ rcases_patt_inverted → opt_param bool ff → format
| [] br := "⟨⟩"
| [p] br := rcases_patt_inverted.format p
| (p::l) br :=
let fmt := rcases_patt_inverted.format p ++ " |" ++ format.space ++
rcases_patt_inverted.format_list l in
if br then format.bracket "(" ")" fmt else fmt
meta instance rcases_patt_inverted.has_to_format :
has_to_format rcases_patt_inverted := ⟨rcases_patt_inverted.format⟩
meta def rcases_patt.format (p : rcases_patt) (br := ff) : format :=
rcases_patt_inverted.format_list p.invert br
meta instance rcases_patt.has_to_format : has_to_format rcases_patt := ⟨rcases_patt.format⟩
/--
Takes the number of fields of a single constructor and patterns to
match its fields against (not necessarily the same number). The
returned lists each contain one element per field of the
constructor. The `name` is the name which will be used in the
top-level `cases` tactic, and the `rcases_patt` is the pattern which
the field will be matched against by subsequent `cases` tactics.
-/
meta def rcases.process_constructor :
nat → listΠ rcases_patt → listΠ name × listΠ rcases_patt
| 0 ids := ([], [])
| 1 [] := ([`_], [default _])
| 1 [id] := ([id.name], [id])
-- The interesting case: we matched the last field against multiple
-- patterns, so split off the remaining patterns into a subsequent
-- match. This handles matching `α × β × γ` against `⟨a, b, c⟩`.
| 1 ids := ([`_], [rcases_patt.many [ids]])
| (n+1) ids :=
let (ns, ps) := rcases.process_constructor n ids.tail,
p := ids.head in
(p.name :: ns, p :: ps)
meta def rcases.process_constructors (params : nat) :
listΣ name → listΣ (listΠ rcases_patt) →
tactic (dlist name × listΣ (name × listΠ rcases_patt))
| [] ids := pure (dlist.empty, [])
| (c::cs) ids := do
n ← mk_const c >>= get_arity,
let (h, t) := (match cs, ids.tail with
-- We matched the last constructor against multiple patterns,
-- so split off the remaining constructors. This handles matching
-- `α ⊕ β ⊕ γ` against `a|b|c`.
| [], _::_ := ([rcases_patt.many ids], [])
| _, _ := (ids.head, ids.tail)
end : _),
let (ns, ps) := rcases.process_constructor (n - params) h,
(l, r) ← rcases.process_constructors cs t,
pure (dlist.of_list ns ++ l, (c, ps) :: r)
private def align {α β} (p : α → β → Prop) [∀ a b, decidable (p a b)] :
list α → list β → list (α × β)
| (a::as) (b::bs) :=
if p a b then (a, b) :: align as bs else align as (b::bs)
| _ _ := []
private meta def get_local_and_type (e : expr) : tactic (expr × expr) :=
(do t ← infer_type e, pure (t, e)) <|> (do
e ← get_local e.local_pp_name,
t ← infer_type e, pure (t, e))
meta mutual def rcases_core, rcases.continue
with rcases_core : listΣ (listΠ rcases_patt) → expr → tactic goals
| ids e := do
(t, e) ← get_local_and_type e,
t ← whnf t,
env ← get_env,
let I := t.get_app_fn.const_name,
when (¬env.is_inductive I) $
fail format!"rcases tactic failed, {e} is not an inductive datatype",
let params := env.inductive_num_params I,
let c := env.constructors_of I,
(ids, r) ← rcases.process_constructors params c ids,
l ← cases_core e ids.to_list,
gs ← get_goals,
-- `cases_core` may not generate a new goal for every constructor,
-- as some constructors may be impossible for type reasons. (See its
-- documentation.) Match up the new goals with our remaining work
-- by constructor name.
list.join <$> (align (λ (a : name × _) (b : _ × name × _), a.1 = b.2.1) r (gs.zip l)).mmap
(λ⟨⟨_, ps⟩, g, _, hs, _⟩,
set_goals [g] >> rcases.continue (ps.zip hs))
with rcases.continue : listΠ (rcases_patt × expr) → tactic goals
| [] := get_goals
| ((rcases_patt.many ids, e) :: l) := do
gs ← rcases_core ids e,
list.join <$> gs.mmap (λ g, set_goals [g] >> rcases.continue l)
| ((rcases_patt.one `rfl, e) :: l) := do
(t, e) ← get_local_and_type e,
subst e,
rcases.continue l
-- If the pattern is any other name, we already bound the name in the
-- top-level `cases` tactic, so there is no more work to do for it.
| (_ :: l) := rcases.continue l
meta def rcases (p : pexpr) (ids : listΣ (listΠ rcases_patt)) : tactic unit :=
do e ← i_to_expr p,
if e.is_local_constant then
focus1 (rcases_core ids e >>= set_goals)
else do
x ← mk_fresh_name,
n ← revert_kdependencies e semireducible,
(tactic.generalize e x)
<|>
(do t ← infer_type e,
tactic.assertv x t e,
get_local x >>= tactic.revert,
return ()),
h ← tactic.intro1,
focus1 (rcases_core ids h >>= set_goals)
meta def rintro (ids : listΠ rcases_patt) : tactic unit :=
do l ← ids.mmap (λ id, do
e ← intro id.name,
return (id, e)),
focus1 (rcases.continue l >>= set_goals)
def merge_list {α} (m : α → α → α) : list α → list α → list α
| [] l₂ := l₂
| l₁ [] := l₁
| (a :: l₁) (b :: l₂) := m a b :: merge_list l₁ l₂
meta def rcases_patt.merge : rcases_patt → rcases_patt → rcases_patt
| (rcases_patt.many ids₁) (rcases_patt.many ids₂) :=
rcases_patt.many (merge_list (merge_list rcases_patt.merge) ids₁ ids₂)
| (rcases_patt.one `rfl) (rcases_patt.many ids₂) :=
rcases_patt.many (merge_list (merge_list rcases_patt.merge) [[]] ids₂)
| (rcases_patt.many ids₁) (rcases_patt.one `rfl) :=
rcases_patt.many (merge_list (merge_list rcases_patt.merge) ids₁ [[]])
| (rcases_patt.one `rfl) (rcases_patt.one `rfl) := rcases_patt.one `rfl
| (rcases_patt.one `_) p := p
| p (rcases_patt.one `_) := p
| (rcases_patt.one n) _ := rcases_patt.one n
| _ (rcases_patt.one n) := rcases_patt.one n
meta mutual def rcases_hint_core, rcases_hint.process_constructors, rcases_hint.continue
with rcases_hint_core : ℕ → expr → tactic (rcases_patt × goals)
| depth e := do
(t, e) ← get_local_and_type e,
t ← whnf t,
env ← get_env,
some l ← try_core (guard (depth ≠ 0) >> cases_core e) |
prod.mk (rcases_patt.one e.local_pp_name) <$> get_goals,
let I := t.get_app_fn.const_name,
if I = ``eq then
prod.mk (rcases_patt.one `rfl) <$> get_goals
else do
let c := env.constructors_of I,
gs ← get_goals,
(ps, gs') ← rcases_hint.process_constructors (depth - 1) c (gs.zip l),
pure (rcases_patt.many ps, gs')
with rcases_hint.process_constructors : ℕ → listΣ name →
list (expr × name × listΠ expr × list (name × expr)) →
tactic (listΣ (listΠ rcases_patt) × goals)
| depth [] _ := pure ([], [])
| depth cs [] := pure (cs.map (λ _, []), [])
| depth (c::cs) ((g, c', hs, _) :: l) :=
if c ≠ c' then do
(ps, gs) ← rcases_hint.process_constructors depth cs l,
pure ([] :: ps, gs)
else do
(p, gs) ← set_goals [g] >> rcases_hint.continue depth hs,
(ps, gs') ← rcases_hint.process_constructors depth cs l,
pure (p :: ps, gs ++ gs')
with rcases_hint.continue : ℕ → listΠ expr → tactic (listΠ rcases_patt × goals)
| depth [] := prod.mk [] <$> get_goals
| depth (e :: l) := do
(p, gs) ← rcases_hint_core depth e,
(ps, gs') ← gs.mfoldl (λ (r : listΠ rcases_patt × goals) g,
do (ps, gs') ← set_goals [g] >> rcases_hint.continue depth l,
pure (merge_list rcases_patt.merge r.1 ps, r.2 ++ gs')) ([], []),
pure (p :: ps, gs')
meta def rcases_hint (p : pexpr) (depth : nat) : tactic rcases_patt :=
do e ← i_to_expr p,
if e.is_local_constant then
focus1 $ do (p, gs) ← rcases_hint_core depth e, set_goals gs, pure p
else do
x ← mk_fresh_name,
n ← revert_kdependencies e semireducible,
(tactic.generalize e x)
<|>
(do t ← infer_type e,
tactic.assertv x t e,
get_local x >>= tactic.revert,
pure ()),
h ← tactic.intro1,
focus1 $ do (p, gs) ← rcases_hint_core depth h, set_goals gs, pure p
meta def rintro_hint (depth : nat) : tactic (listΠ rcases_patt) :=
do l ← intros,
focus1 $ do
(p, gs) ← rcases_hint.continue depth l,
set_goals gs,
pure p
end tactic
|
8ecbf14d6bccbc82be9033500695121ca7debff1 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/W/basic.lean | c359b858fd78825ae8fa2726e22090063e4b7d77 | [
"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 | 6,714 | lean | /-
Copyright (c) 2019 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
-/
import logic.equiv.list
/-!
# W types
Given `α : Type` and `β : α → Type`, the W type determined by this data, `W_type β`, is the
inductively defined type of trees where the nodes are labeled by elements of `α` and the children of
a node labeled `a` are indexed by elements of `β a`.
This file is currently a stub, awaiting a full development of the theory. Currently, the main result
is that if `α` is an encodable fintype and `β a` is encodable for every `a : α`, then `W_type β` is
encodable. This can be used to show the encodability of other inductive types, such as those that
are commonly used to formalize syntax, e.g. terms and expressions in a given language. The strategy
is illustrated in the example found in the file `prop_encodable` in the `archive/examples` folder of
mathlib.
## Implementation details
While the name `W_type` is somewhat verbose, it is preferable to putting a single character
identifier `W` in the root namespace.
-/
/--
Given `β : α → Type*`, `W_type β` is the type of finitely branching trees where nodes are labeled by
elements of `α` and the children of a node labeled `a` are indexed by elements of `β a`.
-/
inductive W_type {α : Type*} (β : α → Type*)
| mk (a : α) (f : β a → W_type) : W_type
instance : inhabited (W_type (λ (_ : unit), empty)) :=
⟨W_type.mk unit.star empty.elim⟩
namespace W_type
variables {α : Type*} {β : α → Type*}
/-- The canonical map to the corresponding sigma type, returning the label of a node as an
element `a` of `α`, and the children of the node as a function `β a → W_type β`. -/
def to_sigma : W_type β → Σ a : α, β a → W_type β
| ⟨a, f⟩ := ⟨a, f⟩
/-- The canonical map from the sigma type into a `W_type`. Given a node `a : α`, and
its children as a function `β a → W_type β`, return the corresponding tree. -/
def of_sigma : (Σ a : α, β a → W_type β) → W_type β
| ⟨a, f⟩ := W_type.mk a f
@[simp] lemma of_sigma_to_sigma : Π (w : W_type β),
of_sigma (to_sigma w) = w
| ⟨a, f⟩ := rfl
@[simp] lemma to_sigma_of_sigma : Π (s : Σ a : α, β a → W_type β),
to_sigma (of_sigma s) = s
| ⟨a, f⟩ := rfl
variable (β)
/-- The canonical bijection with the sigma type, showing that `W_type` is a fixed point of
the polynomial functor `X ↦ Σ a : α, β a → X`. -/
@[simps] def equiv_sigma : W_type β ≃ Σ a : α, β a → W_type β :=
{ to_fun := to_sigma,
inv_fun := of_sigma,
left_inv := of_sigma_to_sigma,
right_inv := to_sigma_of_sigma }
variable {β}
/-- The canonical map from `W_type β` into any type `γ` given a map `(Σ a : α, β a → γ) → γ`. -/
def elim (γ : Type*) (fγ : (Σ a : α, β a → γ) → γ) : W_type β → γ
| ⟨a, f⟩ := fγ ⟨a, λ b, elim (f b)⟩
lemma elim_injective (γ : Type*) (fγ : (Σ a : α, β a → γ) → γ)
(fγ_injective : function.injective fγ) :
function.injective (elim γ fγ)
| ⟨a₁, f₁⟩ ⟨a₂, f₂⟩ h := begin
obtain ⟨rfl, h⟩ := sigma.mk.inj (fγ_injective h),
congr' with x,
exact elim_injective (congr_fun (eq_of_heq h) x : _),
end
instance [hα : is_empty α] : is_empty (W_type β) :=
⟨λ w, W_type.rec_on w (is_empty.elim hα)⟩
lemma infinite_of_nonempty_of_is_empty (a b : α) [ha : nonempty (β a)]
[he : is_empty (β b)] : infinite (W_type β) :=
⟨begin
introsI hf,
have hba : b ≠ a, from λ h, ha.elim (is_empty.elim' (show is_empty (β a), from h ▸ he)),
refine not_injective_infinite_fintype
(λ n : ℕ, show W_type β, from nat.rec_on n
⟨b, is_empty.elim' he⟩
(λ n ih, ⟨a, λ _, ih⟩)) _,
intros n m h,
induction n with n ih generalizing m h,
{ cases m with m; simp * at * },
{ cases m with m,
{ simp * at * },
{ refine congr_arg nat.succ (ih _),
simp [function.funext_iff, *] at * } }
end⟩
variables [Π a : α, fintype (β a)]
/-- The depth of a finitely branching tree. -/
def depth : W_type β → ℕ
| ⟨a, f⟩ := finset.sup finset.univ (λ n, depth (f n)) + 1
lemma depth_pos (t : W_type β) : 0 < t.depth :=
by { cases t, apply nat.succ_pos }
lemma depth_lt_depth_mk (a : α) (f : β a → W_type β) (i : β a) :
depth (f i) < depth ⟨a, f⟩ :=
nat.lt_succ_of_le (finset.le_sup (finset.mem_univ i))
/-
Show that W types are encodable when `α` is an encodable fintype and for every `a : α`, `β a` is
encodable.
We define an auxiliary type `W_type' β n` of trees of depth at most `n`, and then we show by
induction on `n` that these are all encodable. These auxiliary constructions are not interesting in
and of themselves, so we mark them as `private`.
-/
@[reducible] private def W_type' {α : Type*} (β : α → Type*)
[Π a : α, fintype (β a)] [Π a : α, encodable (β a)] (n : ℕ) :=
{ t : W_type β // t.depth ≤ n}
variables [Π a : α, encodable (β a)]
private def encodable_zero : encodable (W_type' β 0) :=
let f : W_type' β 0 → empty := λ ⟨x, h⟩, false.elim $ not_lt_of_ge h (W_type.depth_pos _),
finv : empty → W_type' β 0 := by { intro x, cases x} in
have ∀ x, finv (f x) = x, from λ ⟨x, h⟩, false.elim $ not_lt_of_ge h (W_type.depth_pos _),
encodable.of_left_inverse f finv this
private def f (n : ℕ) : W_type' β (n + 1) → Σ a : α, β a → W_type' β n
| ⟨t, h⟩ :=
begin
cases t with a f,
have h₀ : ∀ i : β a, W_type.depth (f i) ≤ n,
from λ i, nat.le_of_lt_succ (lt_of_lt_of_le (W_type.depth_lt_depth_mk a f i) h),
exact ⟨a, λ i : β a, ⟨f i, h₀ i⟩⟩
end
private def finv (n : ℕ) :
(Σ a : α, β a → W_type' β n) → W_type' β (n + 1)
| ⟨a, f⟩ :=
let f' := λ i : β a, (f i).val in
have W_type.depth ⟨a, f'⟩ ≤ n + 1,
from add_le_add_right (finset.sup_le (λ b h, (f b).2)) 1,
⟨⟨a, f'⟩, this⟩
variables [encodable α]
private def encodable_succ (n : nat) (h : encodable (W_type' β n)) :
encodable (W_type' β (n + 1)) :=
encodable.of_left_inverse (f n) (finv n) (by { rintro ⟨⟨_, _⟩, _⟩, refl })
/-- `W_type` is encodable when `α` is an encodable fintype and for every `a : α`, `β a` is
encodable. -/
instance : encodable (W_type β) :=
begin
haveI h' : Π n, encodable (W_type' β n) :=
λ n, nat.rec_on n encodable_zero encodable_succ,
let f : W_type β → Σ n, W_type' β n := λ t, ⟨t.depth, ⟨t, le_rfl⟩⟩,
let finv : (Σ n, W_type' β n) → W_type β := λ p, p.2.1,
have : ∀ t, finv (f t) = t, from λ t, rfl,
exact encodable.of_left_inverse f finv this
end
end W_type
|
721a283a84aeb3f6c92d3acf356119cb248b94dd | 58d00ddf42e87fdba91a6057c0b803d889c85901 | /src/solutions/thursday/linear_algebra.lean | 6320ea784dab427e825cd9cc91501f4c09d9e98a | [] | no_license | zeta1999/lftcm2020 | 213d0324ec8d4425bd3320a631e906da1c28e230 | a2eea082d479d82e300ca85d77b87b597e6330d6 | refs/heads/master | 1,671,857,495,610 | 1,602,037,058,000 | 1,602,037,058,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,288 | lean | import analysis.normed_space.inner_product
import data.matrix.notation
import linear_algebra.bilinear_form
import linear_algebra.matrix
import tactic
universes u v
section exercise1
namespace semimodule
variables (R M : Type*) [comm_semiring R] [add_comm_monoid M] [semimodule R M]
/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Exercise 1: defining modules and submodules
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -/
/-- The endomorphisms of an `R`-semimodule `M` are the `R`-linear maps from `M` to `M`. -/
def End := M →ₗ[R] M
/-- The following line tells Lean we can apply `f : End R M` as if it was a function. -/
instance : has_coe_to_fun (End R M) := { F := λ _, M → M, coe := linear_map.to_fun }
/-- Endomorphisms inherit the pointwise addition operator from linear maps. -/
instance : add_comm_monoid (End R M) := linear_map.add_comm_monoid
/- Define the identity endomorphism `id`. -/
def End.id : End R M :=
-- sorry
{ to_fun := λ x, x,
map_add' := λ x y, rfl,
map_smul' := λ s x, rfl }
-- sorry
/-
Show that the endomorphisms of `M` form a semimodule over `R`.
Hint: we can re-use the scalar multiplication of linear maps using the `refine` tactic:
```
refine { smul := linear_map.has_scalar.smul, .. },
```
This will fill in the `smul` field of the `semimodule` structure with the given value.
The remaining fields become goals that you can fill in yourself.
Hint: Prove the equalities using the semimodule structure on `M`.
If `f` and `g` are linear maps, the `ext` tactic turns the goal `f = g` into `∀ x, f x = g x`.
-/
instance : semimodule R (End R M) :=
begin
-- sorry
refine { smul := linear_map.has_scalar.smul, ..},
{ intros f, ext x, apply one_smul },
{ intros a b f, ext x, apply mul_smul },
{ intros a f g, ext x, apply smul_add },
{ intros a, ext x, apply smul_zero },
{ intros a b f, ext x, apply add_smul },
{ intros f, ext x, apply zero_smul }
-- or:
-- refine { smul := linear_map.has_scalar.smul, ..}; intros; ext; simp
-- sorry
end
variables {R M}
/- Bonus exercise: define the submodule of `End R M` consisting of the scalar multiplications.
That is, `f ∈ homothety R M` iff `f` is of the form `λ (x : M), s • x` for some `s : R`.
Hints:
* You could specify the carrier subset and show it is closed under the operations.
* You could instead use library functions: try `submodule.map` or `linear_map.range`.
-/
def homothety : submodule R (End R M) :=
-- sorry
{ carrier := { f | ∃ (s : R), (∀ (x : M), f x = s • x) },
zero_mem' := ⟨0, by simp⟩,
add_mem' := λ f g hf hg, begin
obtain ⟨r, hr⟩ := hf,
obtain ⟨s, hs⟩ := hg,
use r + s,
intro x,
simp [hr, hs, add_smul]
end,
smul_mem' := λ c f hf, begin
obtain ⟨r, hr⟩ := hf,
use c * r,
simp [hr, mul_smul]
end }
-- or:
def smulₗ (s : R) : End R M :=
{ to_fun := λ x, s • x,
map_smul' := by simp [smul_comm],
map_add' := by simp [smul_add] }
def to_homothety : R →ₗ[R] End R M :=
{ to_fun := smulₗ,
map_smul' := by { intros, ext, simp [smulₗ, mul_smul] },
map_add' := by { intros, ext, simp [smulₗ, add_smul] } }
def homothety' : submodule R (End R M) :=
linear_map.range to_homothety
-- sorry
end semimodule
end exercise1
section exercise2
namespace matrix
variables {m n R M : Type} [fintype m] [fintype n] [comm_ring R] [add_comm_group M] [module R M]
/- The following line allows us to write `⬝` (`\cdot`) and `ᵀ` (`\^T`) for
matrix multiplication and transpose. -/
open_locale matrix
/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Exercise 2: working with matrices
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -/
/-- Prove the following four lemmas, that were missing from `mathlib`.
Hints:
* Look up the definition of `vec_mul` and `mul_vec`.
* Search the library for useful lemmas about the function used in that definition.
-/
@[simp] lemma add_vec_mul (v w : m → R) (M : matrix m n R) :
vec_mul (v + w) M = vec_mul v M + vec_mul w M :=
-- sorry
by { ext, apply add_dot_product }
-- sorry
@[simp] lemma smul_vec_mul (x : R) (v : m → R) (M : matrix m n R) :
vec_mul (x • v) M = x • vec_mul v M :=
-- sorry
by { ext, apply smul_dot_product }
-- sorry
@[simp] lemma mul_vec_add (M : matrix m n R) (v w : n → R) :
mul_vec M (v + w) = mul_vec M v + mul_vec M w :=
-- sorry
by { ext, apply dot_product_add }
-- sorry
@[simp] lemma mul_vec_smul (M : matrix m n R) (x : R) (v : n → R) :
mul_vec M (x • v) = x • mul_vec M v :=
-- sorry
by { ext, apply dot_product_smul }
-- sorry
/- Define the canonical map from bilinear forms to matrices.
We assume `R` has a basis `v` indexed by `ι`.
Hint: Follow your nose, the types will guide you.
A matrix `A : matrix ι ι R` is not much more than a function `ι → ι → R`,
and a bilinear form is not much more than a function `M → M → R`. -/
def bilin_form_to_matrix {ι : Type*} [fintype ι] (v : ι → M)
(B : bilin_form R M) : matrix ι ι R :=
-- sorry
λ i j, B (v i) (v j)
-- sorry
/-- Define the canonical map from matrices to bilinear forms.
For a matrix `A`, `to_bilin_form A` should take two vectors `v`, `w`
and multiply `A` by `v` on the left and `v` on the right.
-/
def matrix_to_bilin_form (A : matrix n n R) : bilin_form R (n → R) :=
-- sorry
{ bilin := λ v w, dot_product v (mul_vec A w),
bilin_add_left := by { intros, rw [add_dot_product] },
bilin_add_right := by { intros, rw [mul_vec_add, dot_product_add] },
bilin_smul_left := by { intros, rw [smul_dot_product] },
bilin_smul_right := by { intros, rw [mul_vec_smul, dot_product_smul] } }
-- sorry
/- Can you define a bilinear form directly that is equivalent to this matrix `A`?
Don't use `bilin_form_to_matrix`, give the map explicitly in the form `λ v w, _`.
Check your definition by putting your cursor on the lines starting with `#eval`.
Hints:
* Use the `simp` tactic to simplify `(x + y) i` to `x i + y i` and `(s • x) i` to `s * x i`.
* To deal with equalities containing many `+` and `*` symbols, use the `ring` tactic.
-/
def A : matrix (fin 2) (fin 2) R := ![![1, 0], ![-2, 1]]
def your_bilin_form : bilin_form R (fin 2 → R) :=
-- sorry
{ bilin := λ v w, v 0 * w 0 + v 1 * w 1 - 2 * v 1 * w 0,
bilin_add_left := by { intros, simp, ring },
bilin_add_right := by { intros, simp, ring },
bilin_smul_left := by { intros, simp, ring },
bilin_smul_right := by { intros, simp, ring } }
-- sorry
/- Check your definition here, by uncommenting the #eval lines: -/
def v : fin 2 → ℤ := ![1, 3]
def w : fin 2 → ℤ := ![2, 4]
-- #eval matrix_to_bilin_form A v w
-- #eval your_bilin_form v w
end matrix
end exercise2
section exercise3
namespace pi
variables {n : Type*} [fintype n]
open matrix
/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Exercise 3: inner product spaces
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -/
/- Use the `dot_product` function to put an inner product on `n → R`.
Hints:
* Try the lemmas `finset.sum_nonneg`, `finset.sum_eq_zero_iff_of_nonneg`,
`mul_self_nonneg` and `mul_self_eq_zero`.
-/
noncomputable instance : inner_product_space ℝ (n → ℝ) :=
inner_product_space.of_core
-- sorry
{ inner := dot_product,
nonneg_re := λ x, finset.sum_nonneg (λ i _, mul_self_nonneg _),
nonneg_im := λ x, by simp,
definite := λ x hx, funext (λ i, mul_self_eq_zero.mp
((finset.sum_eq_zero_iff_of_nonneg (λ i _, mul_self_nonneg (x i))).mp hx i (finset.mem_univ i))),
conj_sym := λ x y, dot_product_comm _ _,
add_left := λ x y z, add_dot_product _ _ _,
smul_left := λ s x y, smul_dot_product _ _ _ }
-- sorry
end pi
end exercise3
section exercise4
namespace pi
variables (R n : Type) [comm_ring R] [fintype n] [decidable_eq n]
/- Enable sum and product notation with `∑` and `∏`. -/
open_locale big_operators
/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Exercise 4: basis and dimension
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -/
/-- The `i`'th vector in the standard basis of `n → R` is `1` at the `i`th entry
and `0` otherwise. -/
def std_basis (i : n) : (n → R) := λ j, if i = j then 1 else 0
/- Bonus exercise: Show the standard basis of `n → R` is a basis.
This is a difficult exercise, so feel free to skip some parts.
Hints for showing linear independence:
* Try using the lemma `linear_independent_iff` or `linear_independent_iff'`.
* To derive `f x = 0` from `h : f = 0`, use a tactic `have := congr_fun h x`.
* Take a term out of a sum by combining `finset.insert_erase` and `finset.sum_insert`.
Hints for showing it spans the whole module:
* To show equality of set-like terms, apply the `ext` tactic.
* First show `x = ∑ i, x i • std_basis R n i`, then rewrite with this equality.
-/
lemma std_basis_is_basis : is_basis R (std_basis R n) :=
-- sorry
begin
split,
{ apply linear_independent_iff'.mpr,
intros s v hs i hi,
have hs : s.sum (λ (i : n), v i • std_basis R n i) i = 0 := congr_fun hs i,
unfold std_basis at hs,
rw [←finset.insert_erase hi, finset.sum_insert (finset.not_mem_erase i s)] at hs,
simpa using hs },
{ ext,
simp only [submodule.mem_top, iff_true],
rw (show x = ∑ i, x i • std_basis R n i, by { ext, simp [std_basis] }),
refine submodule.sum_mem _ (λ i _, _),
refine submodule.smul_mem _ _ _,
apply submodule.subset_span,
apply set.mem_range_self }
end
-- sorry
variables {K : Type} [field K]
/-
Conclude `n → K` is a finite dimensional vector space for each field `K`
and the dimension of `n → K` over `K` is the cardinality of `n`.
You don't need to complete `std_basis_is_basis` to prove these two lemmas.
Hint: search the library for appropriate lemmas.
-/
lemma finite_dimensional : finite_dimensional K (n → K) :=
-- sorry
finite_dimensional.of_finite_basis (std_basis_is_basis K n)
-- sorry
lemma findim_eq : finite_dimensional.findim K (n → K) = fintype.card n :=
-- sorry
finite_dimensional.findim_eq_card_basis (std_basis_is_basis K n)
-- sorry
end pi
end exercise4
|
b714c5e005a9e082ea21973841c6b217cdf9f192 | 618003631150032a5676f229d13a079ac875ff77 | /src/data/set/countable.lean | 9b785262fe7885685ca209a4e80782c703b4f243 | [
"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,334 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl
-/
import data.equiv.list
import data.set.finite
/-!
# Countable sets
-/
noncomputable theory
open function set encodable
open classical (hiding some)
open_locale classical
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
namespace set
/-- A set is countable if there exists an encoding of the set into the natural numbers.
An encoding is an injection with a partial inverse, which can be viewed as a
constructive analogue of countability. (For the most part, theorems about
`countable` will be classical and `encodable` will be constructive.)
-/
def countable (s : set α) : Prop := nonempty (encodable s)
lemma countable_iff_exists_injective {s : set α} :
countable s ↔ ∃f:s → ℕ, injective f :=
⟨λ ⟨h⟩, by exactI ⟨encode, encode_injective⟩,
λ ⟨f, h⟩, ⟨⟨f, partial_inv f, partial_inv_left h⟩⟩⟩
lemma countable_iff_exists_inj_on {s : set α} :
countable s ↔ ∃ f : α → ℕ, inj_on f s :=
countable_iff_exists_injective.trans
⟨λ ⟨f, hf⟩, ⟨λ a, if h : a ∈ s then f ⟨a, h⟩ else 0,
λ a b as bs h, congr_arg subtype.val $
hf $ by simpa [as, bs] using h⟩,
λ ⟨f, hf⟩, ⟨_, inj_on_iff_injective.1 hf⟩⟩
lemma countable_iff_exists_surjective [ne : nonempty α] {s : set α} :
countable s ↔ ∃f:ℕ → α, s ⊆ range f :=
⟨λ ⟨h⟩, by inhabit α; exactI ⟨λ n, ((decode s n).map subtype.val).iget,
λ a as, ⟨encode (⟨a, as⟩ : s), by simp [encodek]⟩⟩,
λ ⟨f, hf⟩, ⟨⟨
λ x, inv_fun f x.1,
λ n, if h : f n ∈ s then some ⟨f n, h⟩ else none,
λ ⟨x, hx⟩, begin
have := inv_fun_eq (hf hx), dsimp at this ⊢,
simp [this, hx]
end⟩⟩⟩
/--
A non-empty set is countable iff there exists a surjection from the
natural numbers onto the subtype induced by the set.
-/
lemma countable_iff_exists_surjective_to_subtype {s : set α} (hs : s.nonempty) :
countable s ↔ ∃ f : ℕ → s, surjective f :=
have inhabited s, from ⟨classical.choice hs.to_subtype⟩,
have countable s → ∃ f : ℕ → s, surjective f, from assume ⟨h⟩,
by exactI ⟨λ n, (decode s n).iget, λ a, ⟨encode a, by simp [encodek]⟩⟩,
have (∃ f : ℕ → s, surjective f) → countable s, from assume ⟨f, fsurj⟩,
⟨⟨inv_fun f, option.some ∘ f,
by intro h; simp [(inv_fun_eq (fsurj h) : f (inv_fun f h) = h)]⟩⟩,
by split; assumption
/-- Convert `countable s` to `encodable s` (noncomputable). -/
def countable.to_encodable {s : set α} : countable s → encodable s :=
classical.choice
lemma countable_encodable' (s : set α) [H : encodable s] : countable s :=
⟨H⟩
lemma countable_encodable [encodable α] (s : set α) : countable s :=
⟨by apply_instance⟩
/-- If `s : set α` is a nonempty countable set, then there exists a map
`f : ℕ → α` such that `s = range f`. -/
lemma countable.exists_surjective {s : set α} (hc : countable s) (hs : s.nonempty) :
∃f:ℕ → α, s = range f :=
begin
rcases hs with ⟨x, hx⟩,
letI : encodable s := countable.to_encodable hc,
letI : inhabited s := ⟨⟨x, hx⟩⟩,
have : countable (univ : set s) := countable_encodable _,
rcases countable_iff_exists_surjective.1 this with ⟨g, hg⟩,
have : range g = univ := univ_subset_iff.1 hg,
use coe ∘ g,
rw [range_comp, this],
simp
end
@[simp] lemma countable_empty : countable (∅ : set α) :=
⟨⟨λ x, x.2.elim, λ n, none, λ x, x.2.elim⟩⟩
@[simp] lemma countable_singleton (a : α) : countable ({a} : set α) :=
⟨of_equiv _ (equiv.set.singleton a)⟩
lemma countable.mono {s₁ s₂ : set α} (h : s₁ ⊆ s₂) : countable s₂ → countable s₁
| ⟨H⟩ := ⟨@of_inj _ _ H _ (embedding_of_subset _ _ h).2⟩
lemma countable.image {s : set α} (hs : countable s) (f : α → β) : countable (f '' s) :=
let f' : s → f '' s := λ⟨a, ha⟩, ⟨f a, mem_image_of_mem f ha⟩ in
have hf' : surjective f', from assume ⟨b, a, ha, hab⟩, ⟨⟨a, ha⟩, subtype.eq hab⟩,
⟨@encodable.of_inj _ _ hs.to_encodable (surj_inv hf') (injective_surj_inv hf')⟩
lemma countable_range [encodable α] (f : α → β) : countable (range f) :=
by rw ← image_univ; exact (countable_encodable _).image _
lemma countable_of_injective_of_countable_image {s : set α} {f : α → β}
(hf : inj_on f s) (hs : countable (f '' s)) : countable s :=
let ⟨g, hg⟩ := countable_iff_exists_inj_on.1 hs in
countable_iff_exists_inj_on.2 ⟨g ∘ f, hg.comp hf (maps_to_image _ _)⟩
lemma countable_Union {t : α → set β} [encodable α] (ht : ∀a, countable (t a)) :
countable (⋃a, t a) :=
by haveI := (λ a, (ht a).to_encodable);
rw Union_eq_range_sigma; apply countable_range
lemma countable.bUnion {s : set α} {t : α → set β} (hs : countable s) (ht : ∀a∈s, countable (t a)) :
countable (⋃a∈s, t a) :=
begin
rw bUnion_eq_Union,
haveI := hs.to_encodable,
exact countable_Union (by simpa using ht)
end
lemma countable.sUnion {s : set (set α)} (hs : countable s) (h : ∀a∈s, countable a) :
countable (⋃₀ s) :=
by rw sUnion_eq_bUnion; exact hs.bUnion h
lemma countable_Union_Prop {p : Prop} {t : p → set β} (ht : ∀h:p, countable (t h)) :
countable (⋃h:p, t h) :=
by by_cases p; simp [h, ht]
lemma countable.union {s₁ s₂ : set α} (h₁ : countable s₁) (h₂ : countable s₂) : countable (s₁ ∪ s₂) :=
by rw union_eq_Union; exact
countable_Union (bool.forall_bool.2 ⟨h₂, h₁⟩)
lemma countable.insert {s : set α} (a : α) (h : countable s) : countable (insert a s) :=
by { rw [set.insert_eq], exact (countable_singleton _).union h }
lemma finite.countable {s : set α} : finite s → countable s
| ⟨h⟩ := nonempty_of_trunc (by exactI trunc_encodable_of_fintype s)
/-- The set of finite subsets of a countable set is countable. -/
lemma countable_set_of_finite_subset {s : set α} : countable s →
countable {t | finite t ∧ t ⊆ s} | ⟨h⟩ :=
begin
resetI,
refine countable.mono _ (countable_range
(λ t : finset s, {a | ∃ h:a ∈ s, subtype.mk a h ∈ t})),
rintro t ⟨⟨ht⟩, ts⟩,
refine ⟨finset.univ.map (embedding_of_subset _ _ ts),
set.ext $ λ a, _⟩,
suffices : a ∈ s ∧ a ∈ t ↔ a ∈ t, by simpa,
exact ⟨and.right, λ h, ⟨ts h, h⟩⟩
end
lemma countable_pi {π : α → Type*} [fintype α] {s : Πa, set (π a)} (hs : ∀a, countable (s a)) :
countable {f : Πa, π a | ∀a, f a ∈ s a} :=
countable.mono
(show {f : Πa, π a | ∀a, f a ∈ s a} ⊆ range (λf : Πa, s a, λa, (f a).1), from
assume f hf, ⟨λa, ⟨f a, hf a⟩, funext $ assume a, rfl⟩) $
have trunc (encodable (Π (a : α), s a)), from
@encodable.fintype_pi α _ _ _ (assume a, (hs a).to_encodable),
trunc.induction_on this $ assume h,
@countable_range _ _ h _
lemma countable_prod {s : set α} {t : set β} (hs : countable s) (ht : countable t) :
countable (set.prod s t) :=
begin
haveI : encodable s := hs.to_encodable,
haveI : encodable t := ht.to_encodable,
haveI : encodable (s × t) := by apply_instance,
have : range (λp, ⟨p.1, p.2⟩ : s × t → α × β) = set.prod s t,
{ ext z,
rcases z with ⟨x, y⟩,
simp only [exists_prop, set.mem_range, set_coe.exists, prod.mk.inj_iff,
set.prod_mk_mem_set_prod_eq, subtype.coe_mk, prod.exists],
split,
{ rintros ⟨x', x's, y', y't, x'x, y'y⟩,
simp [x'x.symm, y'y.symm, x's, y't] },
{ rintros ⟨xs, yt⟩,
exact ⟨x, xs, y, yt, rfl, rfl⟩ }},
rw ← this,
exact countable_range _
end
section enumerate
/-- Enumerate elements in a countable set.-/
def enumerate_countable {s : set α} (h : countable s) (default : α) : ℕ → α :=
assume n, match @encodable.decode s (h.to_encodable) n with
| (some y) := y
| (none) := default
end
lemma subset_range_enumerate {s : set α} (h : countable s) (default : α) :
s ⊆ range (enumerate_countable h default) :=
assume x hx,
⟨@encodable.encode s h.to_encodable ⟨x, hx⟩,
by simp [enumerate_countable, encodable.encodek]⟩
end enumerate
end set
lemma finset.countable_to_set (s : finset α) : set.countable (↑s : set α) :=
s.finite_to_set.countable
|
b211d1ccf5af88240354c3d50e4010240b7a30da | cc62cd292c1acc80a10b1c645915b70d2cdee661 | /src/category_theory/presheaves/sheaves.lean | e586a477828ec9f0a43fd1b4dcfcb17cf9d73a5d | [] | no_license | RitaAhmadi/lean-category-theory | 4afb881c4b387ee2c8ce706c454fbf9db8897a29 | a27b4ae5eac978e9188d2e867c3d11d9a5b87a9e | refs/heads/master | 1,651,786,183,402 | 1,565,604,314,000 | 1,565,604,314,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,021 | lean | -- import category_theory.opposites
-- import category_theory.full_subcategory
-- import category_theory.limits.types
-- import topology.Top.basic
-- import category_theory.limits.obviously
-- open category_theory
-- open category_theory.limits
-- open topological_space
-- universes u v u₁ v₁ u₂ v₂
-- variable (X : Top.{v})
-- local attribute [back] topological_space.is_open_inter
-- -- local attribute [back] opens.property
-- instance has_inter_open_set : has_inter (opens X) :=
-- { inter := λ U V, ⟨ U.val ∩ V.val, by obviously ⟩ }
-- instance has_inter_open_set_op : has_inter ((opens X)ᵒᵖ) := sorry -- has_inter_open_set X
-- -- def cover_intersections_index (I : Type v) : grothendieck_category (ParallelPair_functor (@prod.fst I I) (@prod.snd I I))
-- -- def cover_intersections (c : cover X) : (cover_intersections_index c.I) ⥤ open_set X :=
-- -- { obj := λ p, match p.1 with
-- -- | _1 := c.U p.2.1 ∩ c.U p.2.2
-- -- | _2 := c.U p.2
-- -- end,
-- -- map := λ p q f, sorry
-- -- }
-- -- @[tidy] meta def sbe := `[solve_by_elim [sum.inl, sum.inr, ulift.up, plift.up, trivial] {max_rep := 5}]
-- -- instance (I : Type v) : category (I × I ⊕ I) :=
-- -- { hom := λ X Y, match (X, Y) with
-- -- | (sum.inl (i, j), sum.inr k) := ulift (plift (i = k)) ⊕ ulift (plift (j = k))
-- -- | (sum.inl (i, j), sum.inl (i', j')) := ulift (plift (i = i' ∧ j = j'))
-- -- | (sum.inr k, sum.inr k') := ulift (plift (k = k'))
-- -- | (sum.inr k, sum.inl (i, j)) := pempty
-- -- end,
-- -- id := by tidy,
-- -- comp := by tidy,
-- -- }
-- structure cover :=
-- (I : Type v)
-- (U : I → (opens X))
-- variables {X}
-- def cover.union (c : cover X) : opens X :=
-- ⟨ set.Union (λ i : c.I, (c.U i).1),
-- begin
-- apply topological_space.is_open_sUnion,
-- tidy,
-- subst H_h,
-- exact (c.U H_w).2
-- end ⟩
-- def cover.sub (c : cover X) (i : c.I) : c.U i ⟶ c.union := sorry
-- definition cover.left (c : cover X) (i j : c.I) : (c.U i ∩ c.U j) ⟶ (c.U i) := by obviously
-- definition cover.right (c : cover X) (i j : c.I) : (c.U i ∩ c.U j) ⟶ (c.U j) := by obviously
-- section
-- variables {D : Type u₂} [𝒟 : category.{u₂ v₂} D]
-- variables {c : cover X} (i j : c.I) (F : (opens X)ᵒᵖ ⥤ D)
-- include 𝒟
-- definition res_left : (F.obj (c.U i)) ⟶ (F.obj ((c.U i) ∩ (c.U j))) :=
-- F.map (c.left i j)
-- definition res_right :=
-- F.map (c.right i j)
-- definition res_union : (F.obj (c.union)) ⟶ (F.obj ((c.U i))) :=
-- F.map (c.sub i)
-- @[simp] lemma res_left_right : res_union i F ≫ res_left i j F = res_union j F ≫ res_right i j F :=
-- begin
-- dsimp [res_union, res_left, res_right],
-- rw ← functor.map_comp,
-- rw ← functor.map_comp,
-- refl,
-- end
-- end
-- section
-- variables {V : Type u} [𝒱 : category.{u v} V] [has_products.{u v} V]
-- include 𝒱
-- variables (c : cover X) (F : (opens X)ᵒᵖ ⥤ V)
-- def sections : V :=
-- limits.pi.{u v} (λ i : c.I, F.obj (c.U i))
-- def overlaps : V :=
-- limits.pi.{u v} (λ p : c.I × c.I, F.obj (c.U p.1 ∩ c.U p.2))
-- def left : (sections c F) ⟶ (overlaps c F) :=
-- pi.pre _ (λ p : c.I × c.I, p.1) ≫ pi.map (λ p, res_left p.1 p.2 F)
-- def right : (sections c F) ⟶ (overlaps c F) :=
-- pi.pre _ (λ p : c.I × c.I, p.2) ≫ pi.map (λ p, res_right p.1 p.2 F)
-- def res : F.obj (c.union) ⟶ (sections c F) :=
-- pi.lift (λ i, res_union i F)
-- @[simp] lemma res_left_right' : res c F ≫ left c F = res c F ≫ right c F :=
-- begin
-- dsimp [left, right, res],
-- rw ← category.assoc,
-- simp,
-- rw ← category.assoc,
-- simp,
-- end
-- def cover_fork : fork (left c F) (right c F) :=
-- fork.of_ι (res c F) (by tidy)
-- class is_sheaf (presheaf : (opens X)ᵒᵖ ⥤ V) :=
-- (sheaf_condition : Π (c : cover X), is_equalizer (cover_fork c presheaf))
-- variables (X V)
-- structure sheaf :=
-- (presheaf : (opens X)ᵒᵖ ⥤ V)
-- (sheaf_condition : is_sheaf presheaf)
-- end
|
ef92368b6a7dcb5f30d7b001551bf62288cc8381 | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/category_theory/core.lean | 8b3274969ae29b56e3fdb9cb2c25cffad47763b7 | [
"Apache-2.0"
] | permissive | ChrisHughes24/mathlib | 98322577c460bc6b1fe5c21f42ce33ad1c3e5558 | a2a867e827c2a6702beb9efc2b9282bd801d5f9a | refs/heads/master | 1,583,848,251,477 | 1,565,164,247,000 | 1,565,164,247,000 | 129,409,993 | 0 | 1 | Apache-2.0 | 1,565,164,817,000 | 1,523,628,059,000 | Lean | UTF-8 | Lean | false | false | 1,546 | lean | /-
Copyright (c) 2019 Scott Morrison All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
The core of a category C is the groupoid whose morphisms are all the
isomorphisms of C.
-/
import category_theory.groupoid
import category_theory.whiskering
namespace category_theory
universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation
def core (C : Type u₁) := C
variables {C : Type u₁} [𝒞 : category.{v₁} C]
include 𝒞
instance core_category : groupoid.{(max v₁ 1)} (core C) :=
{ hom := λ X Y : C, X ≅ Y,
inv := λ X Y f, iso.symm f,
id := λ X, iso.refl X,
comp := λ X Y Z f g, iso.trans f g }
namespace core
@[simp] lemma id_hom (X : core C) : iso.hom (𝟙 X) = 𝟙 X := rfl
@[simp] lemma comp_hom {X Y Z : core C} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).hom = f.hom ≫ g.hom :=
rfl
def inclusion : core C ⥤ C :=
{ obj := id,
map := λ X Y f, f.hom }
variables {G : Type u₂} [𝒢 : groupoid.{v₂} G]
include 𝒢
/-- A functor from a groupoid to a category C factors through the core of C. -/
-- Note that this function is not functorial
-- (consider the two functors from [0] to [1], and the natural transformation between them).
def functor_to_core (F : G ⥤ C) : G ⥤ core C :=
{ obj := λ X, F.obj X,
map := λ X Y f, ⟨F.map f, F.map (inv f)⟩ }
def forget_functor_to_core : (G ⥤ core C) ⥤ (G ⥤ C) := (whiskering_right _ _ _).obj inclusion
end core
end category_theory
|
b91bca5b7309c680a894826a667319ed0ef53832 | df7bb3acd9623e489e95e85d0bc55590ab0bc393 | /lean/love06_monads_exercise_solution.lean | 03cb9908561d3c4f63fc457aa20b25c782fa77a7 | [] | no_license | MaschavanderMarel/logical_verification_2020 | a41c210b9237c56cb35f6cd399e3ac2fe42e775d | 7d562ef174cc6578ca6013f74db336480470b708 | refs/heads/master | 1,692,144,223,196 | 1,634,661,675,000 | 1,634,661,675,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,015 | lean | import .love06_monads_demo
/- # LoVe Exercise 6: Monads -/
set_option pp.beta true
set_option pp.generalized_field_notation false
namespace LoVe
/- ## Question 1: A State Monad with Failure
We introduce a richer notion of lawful monad that provides an `orelse`
operator `<|>` satisfying some laws, given below. `emp` denotes failure.
`x <|> y` tries `x` first, falling back on `y` on failure. -/
@[class] structure lawful_monad_with_orelse (m : Type → Type)
extends lawful_monad m, has_orelse m : Type 1 :=
(emp {} {α : Type} : m α)
(emp_orelse {α : Type} (a : m α) :
(emp <|> a) = a)
(orelse_emp {α : Type} (a : m α) :
(a <|> emp) = a)
(orelse_assoc {α : Type} (a b c : m α) :
((a <|> b) <|> c) = (a <|> (b <|> c)))
(emp_bind {α β : Type} (f : α → m β) :
(emp >>= f) = emp)
(bind_emp {α β : Type} (f : m α) :
(f >>= (λa, emp : α → m β)) = emp)
/- 1.1. We set up the `option` type constructor to be a
`lawful_monad_with_orelse`. Complete the proofs. -/
def option.orelse {α : Type} : option α → option α → option α
| option.none ma' := ma'
| (option.some a) _ := option.some a
@[instance] def lawful_monad_with_orelse_option :
lawful_monad_with_orelse option :=
{ emp := λα, option.none,
orelse := @option.orelse,
emp_orelse :=
begin
intros α a,
refl
end,
orelse_emp :=
begin
intros α a,
cases' a,
{ refl },
{ refl }
end,
orelse_assoc :=
begin
intros α a b c,
cases' a,
{ refl },
{ refl }
end,
emp_bind :=
begin
intros α β f,
refl
end,
bind_emp :=
begin
intros α β g,
cases' g,
{ refl },
{ refl }
end,
.. option.lawful_monad }
@[simp] lemma option.some_bind {α β : Type} (a : α) (g : α → option β) :
(option.some a >>= g) = g a :=
by refl
/- Let us enable some convenient pattern matching syntax, by instantiating
Lean's `monad_fail` type class. (Do not worry if you do not understand what
we are referring to.) -/
@[instance] def lawful_monad_with_orelse.monad_fail {m : Type → Type}
[lawful_monad_with_orelse m] : monad_fail m :=
{ fail := λα msg, lawful_monad_with_orelse.emp }
/- Now we can write definitions such as the following: -/
def first_of_three {m : Type → Type} [lawful_monad_with_orelse m]
(c : m (list ℕ)) : m ℕ :=
do
[n, _, _] ← c,
pure n
#eval first_of_three (option.some [1])
#eval first_of_three (option.some [1, 2, 3])
#eval first_of_three (option.some [1, 2, 3, 4])
/- Using `lawful_monad_with_orelse` and the `monad_fail` syntax, we can give a
concise definition for the `sum_2_5_7` function seen in the lecture. -/
def sum_2_5_7₇ {m : Type → Type} [lawful_monad_with_orelse m]
(c : m (list ℕ)) : m ℕ :=
do
(_ :: n2 :: _ :: _ :: n5 :: _ :: n7 :: _) ← c,
pure (n2 + n5 + n7)
/- 1.2. Now we are ready to define `faction σ` ("eff action"): a monad with an
internal state of type `σ` that can fail (unlike `action σ`).
We start with defining `faction σ α`, where `σ` is the type of the internal
state, and `α` is the type of the value stored in the monad. We use `option` to
model failure. This means we can also use the monadic behavior of `option` when
defining the monadic operations on `faction`.
Hints:
* Remember that `faction σ α` is an alias for a function type, so you can use
pattern matching and `λs, …` to define values of type `faction σ α`.
* `faction` is very similar to `action` from the lecture's demo. You can look
there for inspiration. -/
def faction (σ : Type) (α : Type) :=
σ → option (α × σ)
/- 1.3. Define the `get` and `set` function for `faction`, where `get` returns
the state passed along the state monad and `set s` changes the state to `s`. -/
def get {σ : Type} : faction σ σ
| s := option.some (s, s)
def set {σ : Type} (s : σ) : faction σ unit
| _ := option.some ((), s)
/- We set up the `>>=` syntax on `faction`: -/
def faction.bind {σ α β : Type} (f : faction σ α) (g : α → faction σ β) :
faction σ β
| s := f s >>= (λas, g (prod.fst as) (prod.snd as))
@[instance] def faction.has_bind {σ : Type} : has_bind (faction σ) :=
{ bind := @faction.bind σ }
lemma faction.bind_apply {σ α β : Type} (f : faction σ α) (g : α → faction σ β)
(s : σ) :
(f >>= g) s = (f s >>= (λas, g (prod.fst as) (prod.snd as))) :=
by refl
/- 1.4. Define the monadic operator `pure` for `faction`, in such a way that it
will satisfy the monad laws. -/
def faction.pure {σ α : Type} (a : α) : faction σ α
| s := option.some (a, s)
/- We set up the syntax for `pure` on `faction`: -/
@[instance] def faction.has_pure {σ : Type} : has_pure (faction σ) :=
{ pure := @faction.pure σ }
lemma faction.pure_apply {σ α : Type} (a : α) (s : σ) :
(pure a : faction σ α) s = option.some (a, s) :=
by refl
/- 1.3. Register `faction` as a monad.
Hints:
* The `funext` lemma is useful when you need to prove equality between two
functions.
* `cases' f s` only works when `f s` appears in your goal, so you may need to
unfold some constants before you can invoke `cases'`. -/
@[instance] def faction.lawful_monad {σ : Type} : lawful_monad (faction σ) :=
{ pure_bind :=
begin
intros α β a f,
apply funext,
intro s,
refl
end,
bind_pure :=
begin
intros α ma,
apply funext,
intro s,
simp [faction.bind_apply, faction.pure_apply],
apply lawful_monad.bind_pure
end,
bind_assoc :=
begin
intros α β γ f g ma,
apply funext,
intro s,
simp [faction.bind_apply],
cases' ma s,
{ refl },
{ cases' val,
refl }
end,
.. faction.has_bind,
.. faction.has_pure }
/- ## Question 2: Kleisli Operator
The Kleisli operator `>=>` (not to be confused with `>>=`) is useful for
pipelining monadic operations. Note that `λa, f a >>= g` is to be parsed as
`λa, (f a >>= g)`, not as `(λa, f a) >>= g`. -/
def kleisli {m : Type → Type} [lawful_monad m] {α β γ : Type} (f : α → m β)
(g : β → m γ) : α → m γ :=
λa, f a >>= g
infixr ` >=> ` : 90 := kleisli
/- 2.1. Prove that `pure` is a left and right unit for the Kleisli operator. -/
lemma pure_kleisli {m : Type → Type} [lawful_monad m] {α β : Type}
(f : α → m β) :
(pure >=> f) = f :=
begin
apply funext,
intro a,
exact lawful_monad.pure_bind a f
end
lemma kleisli_pure {m : Type → Type} [lawful_monad m] {α β : Type}
(f : α → m β) :
(f >=> pure) = f :=
begin
apply funext,
intro a,
exact lawful_monad.bind_pure (f a)
end
/- 2.2. Prove associativity of the Kleisli operator. -/
lemma kleisli_assoc {m : Type → Type} [lawful_monad m] {α β γ δ : Type}
(f : α → m β) (g : β → m γ) (h : γ → m δ) :
((f >=> g) >=> h) = (f >=> (g >=> h)) :=
begin
apply funext,
intro a,
exact lawful_monad.bind_assoc g h (f a)
end
end LoVe
|
d6cc43106ec00f5acffe7475a2db90b986b50501 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/category_theory/idempotents/homological_complex.lean | bbfffb7bf85cad9c907f91756cab0503c46d8b4e | [
"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,269 | lean | /-
Copyright (c) 2022 Joël Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joël Riou
-/
import algebra.homology.additive
import category_theory.idempotents.karoubi
/-!
# Idempotent completeness and homological complexes
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file contains simplifications lemmas for categories
`karoubi (homological_complex C c)` and the construction of an equivalence
of categories `karoubi (homological_complex C c) ≌ homological_complex (karoubi C) c`.
When the category `C` is idempotent complete, it is shown that
`homological_complex (karoubi C) c` is also idempotent complete.
-/
namespace category_theory
open category
variables {C : Type*} [category C] [preadditive C] {ι : Type*} {c : complex_shape ι}
namespace idempotents
namespace karoubi
namespace homological_complex
variables {P Q : karoubi (homological_complex C c)} (f : P ⟶ Q) (n : ι)
@[simp, reassoc]
lemma p_comp_d : P.p.f n ≫ f.f.f n = f.f.f n :=
homological_complex.congr_hom (p_comp f) n
@[simp, reassoc]
lemma comp_p_d : f.f.f n ≫ Q.p.f n = f.f.f n :=
homological_complex.congr_hom (comp_p f) n
@[reassoc]
lemma p_comm_f : P.p.f n ≫ f.f.f n = f.f.f n ≫ Q.p.f n :=
homological_complex.congr_hom (p_comm f) n
variable (P)
@[simp, reassoc]
lemma p_idem : P.p.f n ≫ P.p.f n = P.p.f n :=
homological_complex.congr_hom P.idem n
end homological_complex
end karoubi
open karoubi
namespace karoubi_homological_complex_equivalence
namespace functor
/-- The functor `karoubi (homological_complex C c) ⥤ homological_complex (karoubi C) c`,
on objects. -/
@[simps]
def obj (P : karoubi (homological_complex C c)) : homological_complex (karoubi C) c :=
{ X := λ n, ⟨P.X.X n, P.p.f n, by simpa only [homological_complex.comp_f]
using homological_complex.congr_hom P.idem n⟩,
d := λ i j,
{ f := P.p.f i ≫ P.X.d i j,
comm := by tidy, },
shape' := λ i j hij, by simp only [hom_eq_zero_iff,
P.X.shape i j hij, limits.comp_zero], }
/-- The functor `karoubi (homological_complex C c) ⥤ homological_complex (karoubi C) c`,
on morphisms. -/
@[simps]
def map {P Q : karoubi (homological_complex C c)} (f : P ⟶ Q) : obj P ⟶ obj Q :=
{ f:= λ n,
{ f:= f.f.f n,
comm := by simp, }, }
end functor
/-- The functor `karoubi (homological_complex C c) ⥤ homological_complex (karoubi C) c`. -/
@[simps]
def functor : karoubi (homological_complex C c) ⥤ homological_complex (karoubi C) c :=
{ obj := functor.obj,
map := λ P Q f, functor.map f, }
namespace inverse
/-- The functor `homological_complex (karoubi C) c ⥤ karoubi (homological_complex C c)`,
on objects -/
@[simps]
def obj (K : homological_complex (karoubi C) c) : karoubi (homological_complex C c) :=
{ X :=
{ X := λ n, (K.X n).X,
d := λ i j, (K.d i j).f,
shape' := λ i j hij, hom_eq_zero_iff.mp (K.shape i j hij),
d_comp_d' := λ i j k hij hjk, by { simpa only [comp_f]
using hom_eq_zero_iff.mp (K.d_comp_d i j k), }, },
p :=
{ f := λ n, (K.X n).p,
comm' := by simp, },
idem := by tidy, }
/-- The functor `homological_complex (karoubi C) c ⥤ karoubi (homological_complex C c)`,
on morphisms -/
@[simps]
def map {K L : homological_complex (karoubi C) c} (f : K ⟶ L) : obj K ⟶ obj L :=
{ f:=
{ f := λ n, (f.f n).f,
comm' := λ i j hij, by simpa only [comp_f]
using hom_ext.mp (f.comm' i j hij), },
comm := by tidy, }
end inverse
/-- The functor `homological_complex (karoubi C) c ⥤ karoubi (homological_complex C c)`. -/
@[simps]
def inverse :
homological_complex (karoubi C) c ⥤ karoubi (homological_complex C c) :=
{ obj := inverse.obj,
map := λ K L f, inverse.map f, }
/-- The counit isomorphism of the equivalence
`karoubi (homological_complex C c) ≌ homological_complex (karoubi C) c`. -/
@[simps]
def counit_iso : inverse ⋙ functor ≅ 𝟭 (homological_complex (karoubi C) c) :=
eq_to_iso (functor.ext (λ P, homological_complex.ext (by tidy) (by tidy)) (by tidy))
/-- The unit isomorphism of the equivalence
`karoubi (homological_complex C c) ≌ homological_complex (karoubi C) c`. -/
@[simps]
def unit_iso : 𝟭 (karoubi (homological_complex C c)) ≅ functor ⋙ inverse :=
{ hom :=
{ app := λ P,
{ f :=
{ f := λ n, P.p.f n,
comm' := λ i j hij, begin
dsimp,
simp only [homological_complex.hom.comm, homological_complex.hom.comm_assoc,
homological_complex.p_idem],
end },
comm := by { ext n, dsimp, simp only [homological_complex.p_idem], }, },
naturality' := λ P Q φ, begin
ext,
dsimp,
simp only [comp_f, homological_complex.comp_f, homological_complex.comp_p_d,
inverse.map_f_f, functor.map_f_f, homological_complex.p_comp_d],
end, },
inv :=
{ app := λ P,
{ f :=
{ f := λ n, P.p.f n,
comm' := λ i j hij, begin
dsimp,
simp only [homological_complex.hom.comm, assoc, homological_complex.p_idem],
end },
comm := by { ext n, dsimp, simp only [homological_complex.p_idem], }, },
naturality' := λ P Q φ, begin
ext,
dsimp,
simp only [comp_f, homological_complex.comp_f, inverse.map_f_f, functor.map_f_f,
homological_complex.comp_p_d, homological_complex.p_comp_d],
end, },
hom_inv_id' := begin
ext,
dsimp,
simp only [homological_complex.p_idem, comp_f, homological_complex.comp_f, id_eq],
end,
inv_hom_id' := begin
ext,
dsimp,
simp only [homological_complex.p_idem, comp_f, homological_complex.comp_f, id_eq,
inverse.obj_p_f, functor.obj_X_p],
end, }
end karoubi_homological_complex_equivalence
variables (C) (c)
/-- The equivalence `karoubi (homological_complex C c) ≌ homological_complex (karoubi C) c`. -/
@[simps]
def karoubi_homological_complex_equivalence :
karoubi (homological_complex C c) ≌ homological_complex (karoubi C) c :=
{ functor := karoubi_homological_complex_equivalence.functor,
inverse := karoubi_homological_complex_equivalence.inverse,
unit_iso := karoubi_homological_complex_equivalence.unit_iso,
counit_iso := karoubi_homological_complex_equivalence.counit_iso, }
variables (α : Type*) [add_right_cancel_semigroup α] [has_one α]
/-- The equivalence `karoubi (chain_complex C α) ≌ chain_complex (karoubi C) α`. -/
@[simps]
def karoubi_chain_complex_equivalence :
karoubi (chain_complex C α) ≌ chain_complex (karoubi C) α :=
karoubi_homological_complex_equivalence C (complex_shape.down α)
/-- The equivalence `karoubi (cochain_complex C α) ≌ cochain_complex (karoubi C) α`. -/
@[simps]
def karoubi_cochain_complex_equivalence :
karoubi (cochain_complex C α) ≌ cochain_complex (karoubi C) α :=
karoubi_homological_complex_equivalence C (complex_shape.up α)
instance [is_idempotent_complete C] : is_idempotent_complete (homological_complex C c) :=
begin
rw [is_idempotent_complete_iff_of_equivalence
((to_karoubi_equivalence C).map_homological_complex c),
← is_idempotent_complete_iff_of_equivalence (karoubi_homological_complex_equivalence C c)],
apply_instance,
end
end idempotents
end category_theory
|
65940acdaf13f3fef389c51f4d2e083c9fa92f77 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/geometry/euclidean/monge_point.lean | f6e741a38b2878a5d8b85034de6f46a7415df092 | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 38,046 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers
-/
import geometry.euclidean.circumcenter
/-!
# Monge point and orthocenter
This file defines the orthocenter of a triangle, via its n-dimensional
generalization, the Monge point of a simplex.
## Main definitions
* `monge_point` is the Monge point of a simplex, defined in terms of
its position on the Euler line and then shown to be the point of
concurrence of the Monge planes.
* `monge_plane` is a Monge plane of an (n+2)-simplex, which is the
(n+1)-dimensional affine subspace of the subspace spanned by the
simplex that passes through the centroid of an n-dimensional face
and is orthogonal to the opposite edge (in 2 dimensions, this is the
same as an altitude).
* `altitude` is the line that passes through a vertex of a simplex and
is orthogonal to the opposite face.
* `orthocenter` is defined, for the case of a triangle, to be the same
as its Monge point, then shown to be the point of concurrence of the
altitudes.
* `orthocentric_system` is a predicate on sets of points that says
whether they are four points, one of which is the orthocenter of the
other three (in which case various other properties hold, including
that each is the orthocenter of the other three).
## References
* <https://en.wikipedia.org/wiki/Altitude_(triangle)>
* <https://en.wikipedia.org/wiki/Monge_point>
* <https://en.wikipedia.org/wiki/Orthocentric_system>
* Małgorzata Buba-Brzozowa, [The Monge Point and the 3(n+1) Point
Sphere of an
n-Simplex](https://pdfs.semanticscholar.org/6f8b/0f623459c76dac2e49255737f8f0f4725d16.pdf)
-/
noncomputable theory
open_locale big_operators
open_locale classical
open_locale real_inner_product_space
namespace affine
namespace simplex
open finset affine_subspace euclidean_geometry points_with_circumcenter_index
variables {V : Type*} {P : Type*}
[normed_add_comm_group V] [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P]
include V
/-- The Monge point of a simplex (in 2 or more dimensions) is a
generalization of the orthocenter of a triangle. It is defined to be
the intersection of the Monge planes, where a Monge plane is the
(n-1)-dimensional affine subspace of the subspace spanned by the
simplex that passes through the centroid of an (n-2)-dimensional face
and is orthogonal to the opposite edge (in 2 dimensions, this is the
same as an altitude). The circumcenter O, centroid G and Monge point
M are collinear in that order on the Euler line, with OG : GM = (n-1)
: 2. Here, we use that ratio to define the Monge point (so resulting
in a point that equals the centroid in 0 or 1 dimensions), and then
show in subsequent lemmas that the point so defined lies in the Monge
planes and is their unique point of intersection. -/
def monge_point {n : ℕ} (s : simplex ℝ P n) : P :=
(((n + 1 : ℕ) : ℝ) / (((n - 1) : ℕ) : ℝ)) •
((univ : finset (fin (n + 1))).centroid ℝ s.points -ᵥ s.circumcenter) +ᵥ
s.circumcenter
/-- The position of the Monge point in relation to the circumcenter
and centroid. -/
lemma monge_point_eq_smul_vsub_vadd_circumcenter {n : ℕ} (s : simplex ℝ P n) :
s.monge_point = (((n + 1 : ℕ) : ℝ) / (((n - 1) : ℕ) : ℝ)) •
((univ : finset (fin (n + 1))).centroid ℝ s.points -ᵥ s.circumcenter) +ᵥ
s.circumcenter :=
rfl
/-- The Monge point lies in the affine span. -/
lemma monge_point_mem_affine_span {n : ℕ} (s : simplex ℝ P n) :
s.monge_point ∈ affine_span ℝ (set.range s.points) :=
smul_vsub_vadd_mem _ _
(centroid_mem_affine_span_of_card_eq_add_one ℝ _ (card_fin (n + 1)))
s.circumcenter_mem_affine_span
s.circumcenter_mem_affine_span
/-- Two simplices with the same points have the same Monge point. -/
lemma monge_point_eq_of_range_eq {n : ℕ} {s₁ s₂ : simplex ℝ P n}
(h : set.range s₁.points = set.range s₂.points) : s₁.monge_point = s₂.monge_point :=
by simp_rw [monge_point_eq_smul_vsub_vadd_circumcenter, centroid_eq_of_range_eq h,
circumcenter_eq_of_range_eq h]
omit V
/-- The weights for the Monge point of an (n+2)-simplex, in terms of
`points_with_circumcenter`. -/
def monge_point_weights_with_circumcenter (n : ℕ) : points_with_circumcenter_index (n + 2) → ℝ
| (point_index i) := (((n + 1) : ℕ) : ℝ)⁻¹
| circumcenter_index := (-2 / (((n + 1) : ℕ) : ℝ))
/-- `monge_point_weights_with_circumcenter` sums to 1. -/
@[simp] lemma sum_monge_point_weights_with_circumcenter (n : ℕ) :
∑ i, monge_point_weights_with_circumcenter n i = 1 :=
begin
simp_rw [sum_points_with_circumcenter, monge_point_weights_with_circumcenter, sum_const,
card_fin, nsmul_eq_mul],
have hn1 : (n + 1 : ℝ) ≠ 0,
{ exact_mod_cast nat.succ_ne_zero _ },
field_simp [hn1],
ring
end
include V
/-- The Monge point of an (n+2)-simplex, in terms of
`points_with_circumcenter`. -/
lemma monge_point_eq_affine_combination_of_points_with_circumcenter {n : ℕ}
(s : simplex ℝ P (n + 2)) :
s.monge_point = (univ : finset (points_with_circumcenter_index (n + 2))).affine_combination ℝ
s.points_with_circumcenter (monge_point_weights_with_circumcenter n) :=
begin
rw [monge_point_eq_smul_vsub_vadd_circumcenter,
centroid_eq_affine_combination_of_points_with_circumcenter,
circumcenter_eq_affine_combination_of_points_with_circumcenter,
affine_combination_vsub, ←linear_map.map_smul,
weighted_vsub_vadd_affine_combination],
congr' with i,
rw [pi.add_apply, pi.smul_apply, smul_eq_mul, pi.sub_apply],
have hn1 : (n + 1 : ℝ) ≠ 0,
{ exact_mod_cast nat.succ_ne_zero _ },
cases i;
simp_rw [centroid_weights_with_circumcenter, circumcenter_weights_with_circumcenter,
monge_point_weights_with_circumcenter];
rw [add_tsub_assoc_of_le (dec_trivial : 1 ≤ 2), (dec_trivial : 2 - 1 = 1)],
{ rw [if_pos (mem_univ _), sub_zero, add_zero, card_fin],
have hn3 : (n + 2 + 1 : ℝ) ≠ 0,
{ exact_mod_cast nat.succ_ne_zero _ },
field_simp [hn1, hn3, mul_comm] },
{ field_simp [hn1],
ring }
end
omit V
/-- The weights for the Monge point of an (n+2)-simplex, minus the
centroid of an n-dimensional face, in terms of
`points_with_circumcenter`. This definition is only valid when `i₁ ≠ i₂`. -/
def monge_point_vsub_face_centroid_weights_with_circumcenter {n : ℕ} (i₁ i₂ : fin (n + 3)) :
points_with_circumcenter_index (n + 2) → ℝ
| (point_index i) := if i = i₁ ∨ i = i₂ then (((n + 1) : ℕ) : ℝ)⁻¹ else 0
| circumcenter_index := (-2 / (((n + 1) : ℕ) : ℝ))
/-- `monge_point_vsub_face_centroid_weights_with_circumcenter` is the
result of subtracting `centroid_weights_with_circumcenter` from
`monge_point_weights_with_circumcenter`. -/
lemma monge_point_vsub_face_centroid_weights_with_circumcenter_eq_sub {n : ℕ}
{i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) :
monge_point_vsub_face_centroid_weights_with_circumcenter i₁ i₂ =
monge_point_weights_with_circumcenter n -
centroid_weights_with_circumcenter ({i₁, i₂}ᶜ) :=
begin
ext i,
cases i,
{ rw [pi.sub_apply, monge_point_weights_with_circumcenter, centroid_weights_with_circumcenter,
monge_point_vsub_face_centroid_weights_with_circumcenter],
have hu : card ({i₁, i₂}ᶜ : finset (fin (n + 3))) = n + 1,
{ simp [card_compl, fintype.card_fin, h] },
rw hu,
by_cases hi : i = i₁ ∨ i = i₂;
simp [compl_eq_univ_sdiff, hi] },
{ simp [monge_point_weights_with_circumcenter, centroid_weights_with_circumcenter,
monge_point_vsub_face_centroid_weights_with_circumcenter] }
end
/-- `monge_point_vsub_face_centroid_weights_with_circumcenter` sums to 0. -/
@[simp] lemma sum_monge_point_vsub_face_centroid_weights_with_circumcenter {n : ℕ}
{i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) :
∑ i, monge_point_vsub_face_centroid_weights_with_circumcenter i₁ i₂ i = 0 :=
begin
rw monge_point_vsub_face_centroid_weights_with_circumcenter_eq_sub h,
simp_rw [pi.sub_apply, sum_sub_distrib, sum_monge_point_weights_with_circumcenter],
rw [sum_centroid_weights_with_circumcenter, sub_self],
simp [←card_pos, card_compl, h]
end
include V
/-- The Monge point of an (n+2)-simplex, minus the centroid of an
n-dimensional face, in terms of `points_with_circumcenter`. -/
lemma monge_point_vsub_face_centroid_eq_weighted_vsub_of_points_with_circumcenter {n : ℕ}
(s : simplex ℝ P (n + 2)) {i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) :
s.monge_point -ᵥ ({i₁, i₂}ᶜ : finset (fin (n + 3))).centroid ℝ s.points =
(univ : finset (points_with_circumcenter_index (n + 2))).weighted_vsub
s.points_with_circumcenter (monge_point_vsub_face_centroid_weights_with_circumcenter i₁ i₂) :=
by simp_rw [monge_point_eq_affine_combination_of_points_with_circumcenter,
centroid_eq_affine_combination_of_points_with_circumcenter,
affine_combination_vsub,
monge_point_vsub_face_centroid_weights_with_circumcenter_eq_sub h]
/-- The Monge point of an (n+2)-simplex, minus the centroid of an
n-dimensional face, is orthogonal to the difference of the two
vertices not in that face. -/
lemma inner_monge_point_vsub_face_centroid_vsub {n : ℕ} (s : simplex ℝ P (n + 2))
{i₁ i₂ : fin (n + 3)} :
⟪s.monge_point -ᵥ ({i₁, i₂}ᶜ : finset (fin (n + 3))).centroid ℝ s.points,
s.points i₁ -ᵥ s.points i₂⟫ = 0 :=
begin
by_cases h : i₁ = i₂,
{ simp [h], },
simp_rw [monge_point_vsub_face_centroid_eq_weighted_vsub_of_points_with_circumcenter s h,
point_eq_affine_combination_of_points_with_circumcenter,
affine_combination_vsub],
have hs : ∑ i, (point_weights_with_circumcenter i₁ - point_weights_with_circumcenter i₂) i = 0,
{ simp },
rw [inner_weighted_vsub _ (sum_monge_point_vsub_face_centroid_weights_with_circumcenter h) _ hs,
sum_points_with_circumcenter, points_with_circumcenter_eq_circumcenter],
simp only [monge_point_vsub_face_centroid_weights_with_circumcenter,
points_with_circumcenter_point],
let fs : finset (fin (n + 3)) := {i₁, i₂},
have hfs : ∀ i : fin (n + 3),
i ∉ fs → (i ≠ i₁ ∧ i ≠ i₂),
{ intros i hi,
split ; { intro hj, simpa [←hj] using hi } },
rw ←sum_subset fs.subset_univ _,
{ simp_rw [sum_points_with_circumcenter, points_with_circumcenter_eq_circumcenter,
points_with_circumcenter_point, pi.sub_apply, point_weights_with_circumcenter],
rw [←sum_subset fs.subset_univ _],
{ simp_rw [sum_insert (not_mem_singleton.2 h), sum_singleton],
repeat { rw ←sum_subset fs.subset_univ _ },
{ simp_rw [sum_insert (not_mem_singleton.2 h), sum_singleton],
simp [h, ne.symm h, dist_comm (s.points i₁)] },
all_goals { intros i hu hi, simp [hfs i hi] } },
{ intros i hu hi,
simp [hfs i hi, point_weights_with_circumcenter] } },
{ intros i hu hi,
simp [hfs i hi] }
end
/-- A Monge plane of an (n+2)-simplex is the (n+1)-dimensional affine
subspace of the subspace spanned by the simplex that passes through
the centroid of an n-dimensional face and is orthogonal to the
opposite edge (in 2 dimensions, this is the same as an altitude).
This definition is only intended to be used when `i₁ ≠ i₂`. -/
def monge_plane {n : ℕ} (s : simplex ℝ P (n + 2)) (i₁ i₂ : fin (n + 3)) :
affine_subspace ℝ P :=
mk' (({i₁, i₂}ᶜ : finset (fin (n + 3))).centroid ℝ s.points)
(ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ ⊓
affine_span ℝ (set.range s.points)
/-- The definition of a Monge plane. -/
lemma monge_plane_def {n : ℕ} (s : simplex ℝ P (n + 2)) (i₁ i₂ : fin (n + 3)) :
s.monge_plane i₁ i₂ = mk' (({i₁, i₂}ᶜ : finset (fin (n + 3))).centroid ℝ s.points)
(ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ ⊓
affine_span ℝ (set.range s.points) :=
rfl
/-- The Monge plane associated with vertices `i₁` and `i₂` equals that
associated with `i₂` and `i₁`. -/
lemma monge_plane_comm {n : ℕ} (s : simplex ℝ P (n + 2)) (i₁ i₂ : fin (n + 3)) :
s.monge_plane i₁ i₂ = s.monge_plane i₂ i₁ :=
begin
simp_rw monge_plane_def,
congr' 3,
{ congr' 1,
exact pair_comm _ _ },
{ ext,
simp_rw submodule.mem_span_singleton,
split,
all_goals { rintros ⟨r, rfl⟩, use -r, rw [neg_smul, ←smul_neg, neg_vsub_eq_vsub_rev] } }
end
/-- The Monge point lies in the Monge planes. -/
lemma monge_point_mem_monge_plane {n : ℕ} (s : simplex ℝ P (n + 2)) {i₁ i₂ : fin (n + 3)} :
s.monge_point ∈ s.monge_plane i₁ i₂ :=
begin
rw [monge_plane_def, mem_inf_iff, ←vsub_right_mem_direction_iff_mem (self_mem_mk' _ _),
direction_mk', submodule.mem_orthogonal'],
refine ⟨_, s.monge_point_mem_affine_span⟩,
intros v hv,
rcases submodule.mem_span_singleton.mp hv with ⟨r, rfl⟩,
rw [inner_smul_right, s.inner_monge_point_vsub_face_centroid_vsub, mul_zero]
end
/-- The direction of a Monge plane. -/
lemma direction_monge_plane {n : ℕ} (s : simplex ℝ P (n + 2)) {i₁ i₂ : fin (n + 3)} :
(s.monge_plane i₁ i₂).direction = (ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ ⊓
vector_span ℝ (set.range s.points) :=
by rw [monge_plane_def, direction_inf_of_mem_inf s.monge_point_mem_monge_plane, direction_mk',
direction_affine_span]
/-- The Monge point is the only point in all the Monge planes from any
one vertex. -/
lemma eq_monge_point_of_forall_mem_monge_plane {n : ℕ} {s : simplex ℝ P (n + 2)}
{i₁ : fin (n + 3)} {p : P} (h : ∀ i₂, i₁ ≠ i₂ → p ∈ s.monge_plane i₁ i₂) :
p = s.monge_point :=
begin
rw ←@vsub_eq_zero_iff_eq V,
have h' : ∀ i₂, i₁ ≠ i₂ → p -ᵥ s.monge_point ∈
(ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ ⊓ vector_span ℝ (set.range s.points),
{ intros i₂ hne,
rw [←s.direction_monge_plane,
vsub_right_mem_direction_iff_mem s.monge_point_mem_monge_plane],
exact h i₂ hne },
have hi : p -ᵥ s.monge_point ∈ ⨅ (i₂ : {i // i₁ ≠ i}),
(ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ,
{ rw submodule.mem_infi,
exact λ i, (submodule.mem_inf.1 (h' i i.property)).1 },
rw [submodule.infi_orthogonal, ←submodule.span_Union] at hi,
have hu : (⋃ (i : {i // i₁ ≠ i}), ({s.points i₁ -ᵥ s.points i} : set V)) =
(-ᵥ) (s.points i₁) '' (s.points '' (set.univ \ {i₁})),
{ rw [set.image_image],
ext x,
simp_rw [set.mem_Union, set.mem_image, set.mem_singleton_iff, set.mem_diff_singleton],
split,
{ rintros ⟨i, rfl⟩,
use [i, ⟨set.mem_univ _, i.property.symm⟩] },
{ rintros ⟨i, ⟨hiu, hi⟩, rfl⟩,
use [⟨i, hi.symm⟩, rfl] } },
rw [hu, ←vector_span_image_eq_span_vsub_set_left_ne ℝ _ (set.mem_univ _),
set.image_univ] at hi,
have hv : p -ᵥ s.monge_point ∈ vector_span ℝ (set.range s.points),
{ let s₁ : finset (fin (n + 3)) := univ.erase i₁,
obtain ⟨i₂, h₂⟩ :=
card_pos.1 (show 0 < card s₁, by simp [card_erase_of_mem]),
have h₁₂ : i₁ ≠ i₂ := (ne_of_mem_erase h₂).symm,
exact (submodule.mem_inf.1 (h' i₂ h₁₂)).2 },
exact submodule.disjoint_def.1 ((vector_span ℝ (set.range s.points)).orthogonal_disjoint)
_ hv hi,
end
/-- An altitude of a simplex is the line that passes through a vertex
and is orthogonal to the opposite face. -/
def altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) : affine_subspace ℝ P :=
mk' (s.points i) (affine_span ℝ (s.points '' ↑(univ.erase i))).directionᗮ ⊓
affine_span ℝ (set.range s.points)
/-- The definition of an altitude. -/
lemma altitude_def {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) :
s.altitude i = mk' (s.points i)
(affine_span ℝ (s.points '' ↑(univ.erase i))).directionᗮ ⊓
affine_span ℝ (set.range s.points) :=
rfl
/-- A vertex lies in the corresponding altitude. -/
lemma mem_altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) :
s.points i ∈ s.altitude i :=
(mem_inf_iff _ _ _).2 ⟨self_mem_mk' _ _, mem_affine_span ℝ (set.mem_range_self _)⟩
/-- The direction of an altitude. -/
lemma direction_altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) :
(s.altitude i).direction = (vector_span ℝ (s.points '' ↑(finset.univ.erase i)))ᗮ ⊓
vector_span ℝ (set.range s.points) :=
by rw [altitude_def,
direction_inf_of_mem (self_mem_mk' (s.points i) _)
(mem_affine_span ℝ (set.mem_range_self _)), direction_mk', direction_affine_span,
direction_affine_span]
/-- The vector span of the opposite face lies in the direction
orthogonal to an altitude. -/
lemma vector_span_is_ortho_altitude_direction {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) :
vector_span ℝ (s.points '' ↑(finset.univ.erase i)) ⟂ (s.altitude i).direction :=
begin
rw direction_altitude,
exact (submodule.is_ortho_orthogonal_right _).mono_right inf_le_left,
end
open finite_dimensional
/-- An altitude is finite-dimensional. -/
instance finite_dimensional_direction_altitude {n : ℕ} (s : simplex ℝ P (n + 1))
(i : fin (n + 2)) : finite_dimensional ℝ ((s.altitude i).direction) :=
begin
rw direction_altitude,
apply_instance
end
/-- An altitude is one-dimensional (i.e., a line). -/
@[simp] lemma finrank_direction_altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) :
finrank ℝ ((s.altitude i).direction) = 1 :=
begin
rw direction_altitude,
have h := submodule.finrank_add_inf_finrank_orthogonal
(vector_span_mono ℝ (set.image_subset_range s.points ↑(univ.erase i))),
have hc : card (univ.erase i) = n + 1, { rw card_erase_of_mem (mem_univ _), simp },
refine add_left_cancel (trans h _),
rw [s.independent.finrank_vector_span (fintype.card_fin _),
← finset.coe_image, s.independent.finrank_vector_span_image_finset hc]
end
/-- A line through a vertex is the altitude through that vertex if and
only if it is orthogonal to the opposite face. -/
lemma affine_span_pair_eq_altitude_iff {n : ℕ} (s : simplex ℝ P (n + 1))
(i : fin (n + 2)) (p : P) :
line[ℝ, p, s.points i] = s.altitude i ↔ (p ≠ s.points i ∧
p ∈ affine_span ℝ (set.range s.points) ∧
p -ᵥ s.points i ∈ (affine_span ℝ (s.points '' ↑(finset.univ.erase i))).directionᗮ) :=
begin
rw [eq_iff_direction_eq_of_mem
(mem_affine_span ℝ (set.mem_insert_of_mem _ (set.mem_singleton _))) (s.mem_altitude _),
←vsub_right_mem_direction_iff_mem (mem_affine_span ℝ (set.mem_range_self i)) p,
direction_affine_span, direction_affine_span, direction_affine_span],
split,
{ intro h,
split,
{ intro heq,
rw [heq, set.pair_eq_singleton, vector_span_singleton] at h,
have hd : finrank ℝ (s.altitude i).direction = 0,
{ rw [←h, finrank_bot] },
simpa using hd },
{ rw [←submodule.mem_inf, _root_.inf_comm, ←direction_altitude, ←h],
exact vsub_mem_vector_span ℝ (set.mem_insert _ _)
(set.mem_insert_of_mem _ (set.mem_singleton _)) } },
{ rintro ⟨hne, h⟩,
rw [←submodule.mem_inf, _root_.inf_comm, ←direction_altitude] at h,
rw [vector_span_eq_span_vsub_set_left_ne ℝ (set.mem_insert _ _),
set.insert_diff_of_mem _ (set.mem_singleton _),
set.diff_singleton_eq_self (λ h, hne (set.mem_singleton_iff.1 h)), set.image_singleton],
refine eq_of_le_of_finrank_eq _ _,
{ rw submodule.span_le,
simpa using h },
{ rw [finrank_direction_altitude, finrank_span_set_eq_card],
{ simp },
{ refine linear_independent_singleton _,
simpa using hne } } }
end
end simplex
namespace triangle
open euclidean_geometry finset simplex affine_subspace finite_dimensional
variables {V : Type*} {P : Type*}
[normed_add_comm_group V] [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P]
include V
/-- The orthocenter of a triangle is the intersection of its
altitudes. It is defined here as the 2-dimensional case of the
Monge point. -/
def orthocenter (t : triangle ℝ P) : P := t.monge_point
/-- The orthocenter equals the Monge point. -/
lemma orthocenter_eq_monge_point (t : triangle ℝ P) : t.orthocenter = t.monge_point := rfl
/-- The position of the orthocenter in relation to the circumcenter
and centroid. -/
lemma orthocenter_eq_smul_vsub_vadd_circumcenter (t : triangle ℝ P) :
t.orthocenter = (3 : ℝ) •
((univ : finset (fin 3)).centroid ℝ t.points -ᵥ t.circumcenter : V) +ᵥ t.circumcenter :=
begin
rw [orthocenter_eq_monge_point, monge_point_eq_smul_vsub_vadd_circumcenter],
norm_num
end
/-- The orthocenter lies in the affine span. -/
lemma orthocenter_mem_affine_span (t : triangle ℝ P) :
t.orthocenter ∈ affine_span ℝ (set.range t.points) :=
t.monge_point_mem_affine_span
/-- Two triangles with the same points have the same orthocenter. -/
lemma orthocenter_eq_of_range_eq {t₁ t₂ : triangle ℝ P}
(h : set.range t₁.points = set.range t₂.points) : t₁.orthocenter = t₂.orthocenter :=
monge_point_eq_of_range_eq h
/-- In the case of a triangle, altitudes are the same thing as Monge
planes. -/
lemma altitude_eq_monge_plane (t : triangle ℝ P) {i₁ i₂ i₃ : fin 3} (h₁₂ : i₁ ≠ i₂)
(h₁₃ : i₁ ≠ i₃) (h₂₃ : i₂ ≠ i₃) : t.altitude i₁ = t.monge_plane i₂ i₃ :=
begin
have hs : ({i₂, i₃}ᶜ : finset (fin 3)) = {i₁}, by dec_trivial!,
have he : univ.erase i₁ = {i₂, i₃}, by dec_trivial!,
rw [monge_plane_def, altitude_def, direction_affine_span, hs, he, centroid_singleton,
coe_insert, coe_singleton,
vector_span_image_eq_span_vsub_set_left_ne ℝ _ (set.mem_insert i₂ _)],
simp [h₂₃, submodule.span_insert_eq_span]
end
/-- The orthocenter lies in the altitudes. -/
lemma orthocenter_mem_altitude (t : triangle ℝ P) {i₁ : fin 3} :
t.orthocenter ∈ t.altitude i₁ :=
begin
obtain ⟨i₂, i₃, h₁₂, h₂₃, h₁₃⟩ : ∃ i₂ i₃, i₁ ≠ i₂ ∧ i₂ ≠ i₃ ∧ i₁ ≠ i₃, by dec_trivial!,
rw [orthocenter_eq_monge_point, t.altitude_eq_monge_plane h₁₂ h₁₃ h₂₃],
exact t.monge_point_mem_monge_plane
end
/-- The orthocenter is the only point lying in any two of the
altitudes. -/
lemma eq_orthocenter_of_forall_mem_altitude {t : triangle ℝ P} {i₁ i₂ : fin 3} {p : P}
(h₁₂ : i₁ ≠ i₂) (h₁ : p ∈ t.altitude i₁) (h₂ : p ∈ t.altitude i₂) : p = t.orthocenter :=
begin
obtain ⟨i₃, h₂₃, h₁₃⟩ : ∃ i₃, i₂ ≠ i₃ ∧ i₁ ≠ i₃, { clear h₁ h₂, dec_trivial! },
rw t.altitude_eq_monge_plane h₁₃ h₁₂ h₂₃.symm at h₁,
rw t.altitude_eq_monge_plane h₂₃ h₁₂.symm h₁₃.symm at h₂,
rw orthocenter_eq_monge_point,
have ha : ∀ i, i₃ ≠ i → p ∈ t.monge_plane i₃ i,
{ intros i hi,
have hi₁₂ : i₁ = i ∨ i₂ = i, { clear h₁ h₂, dec_trivial! },
cases hi₁₂,
{ exact hi₁₂ ▸ h₂ },
{ exact hi₁₂ ▸ h₁ } },
exact eq_monge_point_of_forall_mem_monge_plane ha
end
/-- The distance from the orthocenter to the reflection of the
circumcenter in a side equals the circumradius. -/
lemma dist_orthocenter_reflection_circumcenter (t : triangle ℝ P) {i₁ i₂ : fin 3} (h : i₁ ≠ i₂) :
dist t.orthocenter (reflection (affine_span ℝ (t.points '' {i₁, i₂})) t.circumcenter) =
t.circumradius :=
begin
rw [←mul_self_inj_of_nonneg dist_nonneg t.circumradius_nonneg,
t.reflection_circumcenter_eq_affine_combination_of_points_with_circumcenter h,
t.orthocenter_eq_monge_point,
monge_point_eq_affine_combination_of_points_with_circumcenter,
dist_affine_combination t.points_with_circumcenter
(sum_monge_point_weights_with_circumcenter _)
(sum_reflection_circumcenter_weights_with_circumcenter h)],
simp_rw [sum_points_with_circumcenter, pi.sub_apply, monge_point_weights_with_circumcenter,
reflection_circumcenter_weights_with_circumcenter],
have hu : ({i₁, i₂} : finset (fin 3)) ⊆ univ := subset_univ _,
obtain ⟨i₃, hi₃, hi₃₁, hi₃₂⟩ :
∃ i₃, univ \ ({i₁, i₂} : finset (fin 3)) = {i₃} ∧ i₃ ≠ i₁ ∧ i₃ ≠ i₂, by dec_trivial!,
simp_rw [←sum_sdiff hu, hi₃],
simp [hi₃₁, hi₃₂],
norm_num
end
/-- The distance from the orthocenter to the reflection of the
circumcenter in a side equals the circumradius, variant using a
`finset`. -/
lemma dist_orthocenter_reflection_circumcenter_finset (t : triangle ℝ P) {i₁ i₂ : fin 3}
(h : i₁ ≠ i₂) :
dist t.orthocenter (reflection (affine_span ℝ (t.points '' ↑({i₁, i₂} : finset (fin 3))))
t.circumcenter) =
t.circumradius :=
by { convert dist_orthocenter_reflection_circumcenter _ h, simp }
/-- The affine span of the orthocenter and a vertex is contained in
the altitude. -/
lemma affine_span_orthocenter_point_le_altitude (t : triangle ℝ P) (i : fin 3) :
line[ℝ, t.orthocenter, t.points i] ≤ t.altitude i :=
begin
refine span_points_subset_coe_of_subset_coe _,
rw [set.insert_subset, set.singleton_subset_iff],
exact ⟨t.orthocenter_mem_altitude, t.mem_altitude i⟩
end
/-- Suppose we are given a triangle `t₁`, and replace one of its
vertices by its orthocenter, yielding triangle `t₂` (with vertices not
necessarily listed in the same order). Then an altitude of `t₂` from
a vertex that was not replaced is the corresponding side of `t₁`. -/
lemma altitude_replace_orthocenter_eq_affine_span {t₁ t₂ : triangle ℝ P} {i₁ i₂ i₃ j₁ j₂ j₃ : fin 3}
(hi₁₂ : i₁ ≠ i₂) (hi₁₃ : i₁ ≠ i₃) (hi₂₃ : i₂ ≠ i₃) (hj₁₂ : j₁ ≠ j₂) (hj₁₃ : j₁ ≠ j₃)
(hj₂₃ : j₂ ≠ j₃) (h₁ : t₂.points j₁ = t₁.orthocenter) (h₂ : t₂.points j₂ = t₁.points i₂)
(h₃ : t₂.points j₃ = t₁.points i₃) :
t₂.altitude j₂ = line[ℝ, t₁.points i₁, t₁.points i₂] :=
begin
symmetry,
rw [←h₂, t₂.affine_span_pair_eq_altitude_iff],
rw [h₂],
use t₁.independent.injective.ne hi₁₂,
have he : affine_span ℝ (set.range t₂.points) = affine_span ℝ (set.range t₁.points),
{ refine ext_of_direction_eq _
⟨t₁.points i₃, mem_affine_span ℝ ⟨j₃, h₃⟩, mem_affine_span ℝ (set.mem_range_self _)⟩,
refine eq_of_le_of_finrank_eq (direction_le (span_points_subset_coe_of_subset_coe _)) _,
{ have hu : (finset.univ : finset (fin 3)) = {j₁, j₂, j₃}, { clear h₁ h₂ h₃, dec_trivial! },
rw [←set.image_univ, ←finset.coe_univ, hu, finset.coe_insert, finset.coe_insert,
finset.coe_singleton, set.image_insert_eq, set.image_insert_eq, set.image_singleton,
h₁, h₂, h₃, set.insert_subset, set.insert_subset, set.singleton_subset_iff],
exact ⟨t₁.orthocenter_mem_affine_span,
mem_affine_span ℝ (set.mem_range_self _),
mem_affine_span ℝ (set.mem_range_self _)⟩ },
{ rw [direction_affine_span, direction_affine_span,
t₁.independent.finrank_vector_span (fintype.card_fin _),
t₂.independent.finrank_vector_span (fintype.card_fin _)] } },
rw he,
use mem_affine_span ℝ (set.mem_range_self _),
have hu : finset.univ.erase j₂ = {j₁, j₃}, { clear h₁ h₂ h₃, dec_trivial! },
rw [hu, finset.coe_insert, finset.coe_singleton, set.image_insert_eq, set.image_singleton,
h₁, h₃],
have hle : (t₁.altitude i₃).directionᗮ ≤
line[ℝ, t₁.orthocenter, t₁.points i₃].directionᗮ :=
submodule.orthogonal_le (direction_le (affine_span_orthocenter_point_le_altitude _ _)),
refine hle ((t₁.vector_span_is_ortho_altitude_direction i₃) _),
have hui : finset.univ.erase i₃ = {i₁, i₂}, { clear hle h₂ h₃, dec_trivial! },
rw [hui, finset.coe_insert, finset.coe_singleton, set.image_insert_eq, set.image_singleton],
refine vsub_mem_vector_span ℝ (set.mem_insert _ _)
(set.mem_insert_of_mem _ (set.mem_singleton _))
end
/-- Suppose we are given a triangle `t₁`, and replace one of its
vertices by its orthocenter, yielding triangle `t₂` (with vertices not
necessarily listed in the same order). Then the orthocenter of `t₂`
is the vertex of `t₁` that was replaced. -/
lemma orthocenter_replace_orthocenter_eq_point {t₁ t₂ : triangle ℝ P} {i₁ i₂ i₃ j₁ j₂ j₃ : fin 3}
(hi₁₂ : i₁ ≠ i₂) (hi₁₃ : i₁ ≠ i₃) (hi₂₃ : i₂ ≠ i₃) (hj₁₂ : j₁ ≠ j₂) (hj₁₃ : j₁ ≠ j₃)
(hj₂₃ : j₂ ≠ j₃) (h₁ : t₂.points j₁ = t₁.orthocenter) (h₂ : t₂.points j₂ = t₁.points i₂)
(h₃ : t₂.points j₃ = t₁.points i₃) :
t₂.orthocenter = t₁.points i₁ :=
begin
refine (triangle.eq_orthocenter_of_forall_mem_altitude hj₂₃ _ _).symm,
{ rw altitude_replace_orthocenter_eq_affine_span hi₁₂ hi₁₃ hi₂₃ hj₁₂ hj₁₃ hj₂₃ h₁ h₂ h₃,
exact mem_affine_span ℝ (set.mem_insert _ _) },
{ rw altitude_replace_orthocenter_eq_affine_span hi₁₃ hi₁₂ hi₂₃.symm hj₁₃ hj₁₂ hj₂₃.symm h₁ h₃ h₂,
exact mem_affine_span ℝ (set.mem_insert _ _) }
end
end triangle
end affine
namespace euclidean_geometry
open affine affine_subspace finite_dimensional
variables {V : Type*} {P : Type*}
[normed_add_comm_group V] [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P]
include V
/-- Four points form an orthocentric system if they consist of the
vertices of a triangle and its orthocenter. -/
def orthocentric_system (s : set P) : Prop :=
∃ t : triangle ℝ P,
t.orthocenter ∉ set.range t.points ∧ s = insert t.orthocenter (set.range t.points)
/-- This is an auxiliary lemma giving information about the relation
of two triangles in an orthocentric system; it abstracts some
reasoning, with no geometric content, that is common to some other
lemmas. Suppose the orthocentric system is generated by triangle `t`,
and we are given three points `p` in the orthocentric system. Then
either we can find indices `i₁`, `i₂` and `i₃` for `p` such that `p
i₁` is the orthocenter of `t` and `p i₂` and `p i₃` are points `j₂`
and `j₃` of `t`, or `p` has the same points as `t`. -/
lemma exists_of_range_subset_orthocentric_system {t : triangle ℝ P}
(ho : t.orthocenter ∉ set.range t.points) {p : fin 3 → P}
(hps : set.range p ⊆ insert t.orthocenter (set.range t.points)) (hpi : function.injective p) :
(∃ (i₁ i₂ i₃ j₂ j₃ : fin 3), i₁ ≠ i₂ ∧ i₁ ≠ i₃ ∧ i₂ ≠ i₃ ∧
(∀ i : fin 3, i = i₁ ∨ i = i₂ ∨ i = i₃) ∧ p i₁ = t.orthocenter ∧ j₂ ≠ j₃ ∧
t.points j₂ = p i₂ ∧ t.points j₃ = p i₃) ∨ set.range p = set.range t.points :=
begin
by_cases h : t.orthocenter ∈ set.range p,
{ left,
rcases h with ⟨i₁, h₁⟩,
obtain ⟨i₂, i₃, h₁₂, h₁₃, h₂₃, h₁₂₃⟩ :
∃ (i₂ i₃ : fin 3), i₁ ≠ i₂ ∧ i₁ ≠ i₃ ∧ i₂ ≠ i₃ ∧ ∀ i : fin 3, i = i₁ ∨ i = i₂ ∨ i = i₃,
{ clear h₁, dec_trivial! },
have h : ∀ i, i₁ ≠ i → ∃ (j : fin 3), t.points j = p i,
{ intros i hi,
replace hps := set.mem_of_mem_insert_of_ne
(set.mem_of_mem_of_subset (set.mem_range_self i) hps) (h₁ ▸ hpi.ne hi.symm),
exact hps },
rcases h i₂ h₁₂ with ⟨j₂, h₂⟩,
rcases h i₃ h₁₃ with ⟨j₃, h₃⟩,
have hj₂₃ : j₂ ≠ j₃,
{ intro he,
rw [he, h₃] at h₂,
exact h₂₃.symm (hpi h₂) },
exact ⟨i₁, i₂, i₃, j₂, j₃, h₁₂, h₁₃, h₂₃, h₁₂₃, h₁, hj₂₃, h₂, h₃⟩ },
{ right,
have hs := set.subset_diff_singleton hps h,
rw set.insert_diff_self_of_not_mem ho at hs,
refine set.eq_of_subset_of_card_le hs _,
rw [set.card_range_of_injective hpi,
set.card_range_of_injective t.independent.injective] }
end
/-- For any three points in an orthocentric system generated by
triangle `t`, there is a point in the subspace spanned by the triangle
from which the distance of all those three points equals the circumradius. -/
lemma exists_dist_eq_circumradius_of_subset_insert_orthocenter {t : triangle ℝ P}
(ho : t.orthocenter ∉ set.range t.points) {p : fin 3 → P}
(hps : set.range p ⊆ insert t.orthocenter (set.range t.points)) (hpi : function.injective p) :
∃ c ∈ affine_span ℝ (set.range t.points), ∀ p₁ ∈ set.range p, dist p₁ c = t.circumradius :=
begin
rcases exists_of_range_subset_orthocentric_system ho hps hpi with
⟨i₁, i₂, i₃, j₂, j₃, h₁₂, h₁₃, h₂₃, h₁₂₃, h₁, hj₂₃, h₂, h₃⟩ | hs,
{ use [reflection (affine_span ℝ (t.points '' {j₂, j₃})) t.circumcenter,
reflection_mem_of_le_of_mem (affine_span_mono ℝ (set.image_subset_range _ _))
t.circumcenter_mem_affine_span],
intros p₁ hp₁,
rcases hp₁ with ⟨i, rfl⟩,
replace h₁₂₃ := h₁₂₃ i,
repeat { cases h₁₂₃ },
{ rw h₁,
exact triangle.dist_orthocenter_reflection_circumcenter t hj₂₃ },
{ rw [←h₂,
dist_reflection_eq_of_mem _
(mem_affine_span ℝ (set.mem_image_of_mem _ (set.mem_insert _ _)))],
exact t.dist_circumcenter_eq_circumradius _ },
{ rw [←h₃,
dist_reflection_eq_of_mem _
(mem_affine_span ℝ (set.mem_image_of_mem _
(set.mem_insert_of_mem _ (set.mem_singleton _))))],
exact t.dist_circumcenter_eq_circumradius _ } },
{ use [t.circumcenter, t.circumcenter_mem_affine_span],
intros p₁ hp₁,
rw hs at hp₁,
rcases hp₁ with ⟨i, rfl⟩,
exact t.dist_circumcenter_eq_circumradius _ }
end
/-- Any three points in an orthocentric system are affinely independent. -/
lemma orthocentric_system.affine_independent {s : set P} (ho : orthocentric_system s)
{p : fin 3 → P} (hps : set.range p ⊆ s) (hpi : function.injective p) :
affine_independent ℝ p :=
begin
rcases ho with ⟨t, hto, hst⟩,
rw hst at hps,
rcases exists_dist_eq_circumradius_of_subset_insert_orthocenter hto hps hpi with ⟨c, hcs, hc⟩,
exact cospherical.affine_independent ⟨c, t.circumradius, hc⟩ set.subset.rfl hpi
end
/-- Any three points in an orthocentric system span the same subspace
as the whole orthocentric system. -/
lemma affine_span_of_orthocentric_system {s : set P} (ho : orthocentric_system s)
{p : fin 3 → P} (hps : set.range p ⊆ s) (hpi : function.injective p) :
affine_span ℝ (set.range p) = affine_span ℝ s :=
begin
have ha := ho.affine_independent hps hpi,
rcases ho with ⟨t, hto, hts⟩,
have hs : affine_span ℝ s = affine_span ℝ (set.range t.points),
{ rw [hts, affine_span_insert_eq_affine_span ℝ t.orthocenter_mem_affine_span] },
refine ext_of_direction_eq _
⟨p 0, mem_affine_span ℝ (set.mem_range_self _), mem_affine_span ℝ (hps (set.mem_range_self _))⟩,
have hfd : finite_dimensional ℝ (affine_span ℝ s).direction, { rw hs, apply_instance },
haveI := hfd,
refine eq_of_le_of_finrank_eq (direction_le (affine_span_mono ℝ hps)) _,
rw [hs, direction_affine_span, direction_affine_span,
ha.finrank_vector_span (fintype.card_fin _),
t.independent.finrank_vector_span (fintype.card_fin _)]
end
/-- All triangles in an orthocentric system have the same circumradius. -/
lemma orthocentric_system.exists_circumradius_eq {s : set P} (ho : orthocentric_system s) :
∃ r : ℝ, ∀ t : triangle ℝ P, set.range t.points ⊆ s → t.circumradius = r :=
begin
rcases ho with ⟨t, hto, hts⟩,
use t.circumradius,
intros t₂ ht₂,
have ht₂s := ht₂,
rw hts at ht₂,
rcases exists_dist_eq_circumradius_of_subset_insert_orthocenter hto ht₂
t₂.independent.injective with ⟨c, hc, h⟩,
rw set.forall_range_iff at h,
have hs : set.range t.points ⊆ s,
{ rw hts,
exact set.subset_insert _ _ },
rw [affine_span_of_orthocentric_system ⟨t, hto, hts⟩ hs
t.independent.injective,
←affine_span_of_orthocentric_system ⟨t, hto, hts⟩ ht₂s
t₂.independent.injective] at hc,
exact (t₂.eq_circumradius_of_dist_eq hc h).symm
end
/-- Given any triangle in an orthocentric system, the fourth point is
its orthocenter. -/
lemma orthocentric_system.eq_insert_orthocenter {s : set P} (ho : orthocentric_system s)
{t : triangle ℝ P} (ht : set.range t.points ⊆ s) :
s = insert t.orthocenter (set.range t.points) :=
begin
rcases ho with ⟨t₀, ht₀o, ht₀s⟩,
rw ht₀s at ht,
rcases exists_of_range_subset_orthocentric_system ht₀o ht
t.independent.injective with
⟨i₁, i₂, i₃, j₂, j₃, h₁₂, h₁₃, h₂₃, h₁₂₃, h₁, hj₂₃, h₂, h₃⟩ | hs,
{ obtain ⟨j₁, hj₁₂, hj₁₃, hj₁₂₃⟩ :
∃ j₁ : fin 3, j₁ ≠ j₂ ∧ j₁ ≠ j₃ ∧ ∀ j : fin 3, j = j₁ ∨ j = j₂ ∨ j = j₃,
{ clear h₂ h₃, dec_trivial! },
suffices h : t₀.points j₁ = t.orthocenter,
{ have hui : (set.univ : set (fin 3)) = {i₁, i₂, i₃}, { ext x, simpa using h₁₂₃ x },
have huj : (set.univ : set (fin 3)) = {j₁, j₂, j₃}, { ext x, simpa using hj₁₂₃ x },
rw [←h, ht₀s, ←set.image_univ, huj, ←set.image_univ, hui],
simp_rw [set.image_insert_eq, set.image_singleton, h₁, ←h₂, ←h₃],
rw set.insert_comm },
exact (triangle.orthocenter_replace_orthocenter_eq_point
hj₁₂ hj₁₃ hj₂₃ h₁₂ h₁₃ h₂₃ h₁ h₂.symm h₃.symm).symm },
{ rw hs,
convert ht₀s using 2,
exact triangle.orthocenter_eq_of_range_eq hs }
end
end euclidean_geometry
|
ad6745e92ff047b0bd935223e1070c4e64f62353 | 618003631150032a5676f229d13a079ac875ff77 | /src/category_theory/action.lean | 4c330c84d59dc8a2f7d45e6380d0342a3ecf0c9e | [
"Apache-2.0"
] | permissive | awainverse/mathlib | 939b68c8486df66cfda64d327ad3d9165248c777 | ea76bd8f3ca0a8bf0a166a06a475b10663dec44a | refs/heads/master | 1,659,592,962,036 | 1,590,987,592,000 | 1,590,987,592,000 | 268,436,019 | 1 | 0 | Apache-2.0 | 1,590,990,500,000 | 1,590,990,500,000 | null | UTF-8 | Lean | false | false | 3,165 | lean | /-
Copyright (c) 2020 David Wärn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: David Wärn
-/
import category_theory.elements
import category_theory.single_obj
/-!
# Actions as functors and as categories
From a multiplicative action M ↻ X, we can construct a functor from M to the category of
types, mapping the single object of M to X and an element `m : M` to map `X → X` given by
multiplication by `m`.
This functor induces a category structure on X -- a special case of the category of elements.
A morphism `x → y` in this category is simply a scalar `m : M` such that `m • x = y`. In the case
where M is a group, this category is a groupoid -- the `action groupoid'.
-/
open mul_action
namespace category_theory
universes u
variables (M : Type*) [monoid M] (X : Type u) [𝒜 : mul_action M X]
include 𝒜
/-- A multiplicative action M ↻ X viewed as a functor mapping the single object of M to X
and an element `m : M` to the map `X → X` given by multiplication by `m`. -/
@[simps]
def action_as_functor : single_obj M ⥤ Type u :=
{ obj := λ _, X,
map := λ _ _, (•),
map_id' := λ _, funext $ mul_action.one_smul,
map_comp' := λ _ _ _ f g, funext $ λ x, (smul_smul g f x).symm }
/-- A multiplicative action M ↻ X induces a category strucure on X, where a morphism
from x to y is a scalar taking x to y. Due to implementation details, the object type
of this category is not equal to X, but is in bijection with X. -/
@[derive category]
def action_category := (action_as_functor M X).elements
namespace action_category
omit 𝒜
instance (G : Type*) [group G] [mul_action G X] : groupoid (action_category G X) :=
category_theory.groupoid_of_elements _
include 𝒜
/-- The projection from the action category to the monoid, mapping a morphism to its
label. -/
def π : action_category M X ⥤ single_obj M :=
category_of_elements.π _
@[simp]
lemma π_map (p q : action_category M X) (f : p ⟶ q) : (π M X).map f = f.val := rfl
@[simp]
lemma π_obj (p : action_category M X) : (π M X).obj p = single_obj.star M :=
@subsingleton.elim unit _ _ _
/-- An object of the action category given by M ↻ X corresponds to an element of X. -/
def obj_equiv : X ≃ action_category M X :=
{ to_fun := λ x, ⟨single_obj.star M, x⟩,
inv_fun := λ p, p.2,
left_inv := by tidy,
right_inv := by tidy }
lemma hom_as_subtype (p q : action_category M X) :
(p ⟶ q) = { m : M // m • (obj_equiv M X).symm p = (obj_equiv M X).symm q } := rfl
instance [inhabited X] : inhabited (action_category M X) :=
{ default := obj_equiv M X (default X) }
variables {X} (x : X)
/-- The stabilizer of a point is isomorphic to the endomorphism monoid at the
corresponding point. In fact they are definitionally equivalent. -/
def stabilizer_iso_End : stabilizer M x ≃* End (obj_equiv M X x) :=
mul_equiv.refl _
@[simp]
lemma stabilizer_iso_End_apply (f : stabilizer M x) :
(stabilizer_iso_End M x).to_fun f = f := rfl
@[simp]
lemma stabilizer_iso_End_symm_apply (f : End _) :
(stabilizer_iso_End M x).inv_fun f = f := rfl
end action_category
end category_theory
|
35fe33d8444dba74cc4c26a326fb490a00e80bea | 65b579fba1b0b66add04cccd4529add645eff597 | /test1.lean | 337dfe72c99bacf5627612b295879bb9bdf5fbdb | [] | no_license | teodorov/sf_lean | ba637ca8ecc538aece4d02c8442d03ef713485db | cd4832d6bee9c606014c977951f6aebc4c8d611b | refs/heads/master | 1,632,890,232,054 | 1,543,005,745,000 | 1,543,005,745,000 | 108,566,115 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,529 | lean |
--debrujin indices, a fancy natural number
inductive IN {A : Type} (x : A) : list A → Type
| zero : ∀ {xs}, IN (x::xs)
| succ : ∀ {y xs}, IN (x::xs) → IN (y::xs)
#check (IN.zero [1, 2, 3])
#check (IN.succ (IN.zero [1, 2, 3]))
#reduce (IN 2 [2 , 3])
#eval (IN (20) [2 , 3])
-- the environment which has elements of different types
-- at different indices, corresponding to the types in Γ
inductive All {A : Type} (P : A → Type) : list A → Type
| empty : All []
| cons : ∀ {x xs}, P x → All xs → All (x::xs)
open All
inductive Any {A : Type} (P : A → Prop) : list A → Type
| zero : ∀ {x xs}, P x → Any (x::xs)
| succ : ∀ {x xs}, Any xs → Any (x::xs).
def IN' {A : Type} (x : A) (xs : list A) : Type := Any (λ y, eq x y) xs
def lookup : ∀ {A} { P : A → Type} {x xs}, IN' x xs → All P xs → P x
| _ _ _ _ (Any.zero (eq.refl _)) (cons w ps) := w
| _ _ _ _ (Any.succ i) (cons w ps) := lookup i ps
-- def lookup : ∀ {A} { P : A → Type} {x xs}, All P xs → IN x xs → P x
-- | aType aP ax axs (All.cons w ps) (IN.zero) := w
-- | aType aP ax axs (All.cons w ps) (IN.succ i) := lookup ps i.
inductive EType
| enat
| ebool
open EType
def Value : EType → Type
| EType.enat := nat
| EType.ebool := bool
def Ctx := list EType
def Env : Ctx → Type := λ Γ, All Value Γ
def Γ₀ : Ctx := ebool :: [].
def ρ₀ : Env Γ₀ := cons ff (empty Value).
def Γ₁ : Ctx := enat :: ebool :: [].
def ρ₁ : Env Γ₁ := cons (2:ℕ) (cons ff (empty Value)). |
01ebcefaed5a859e8e33fd3e5112f88c87c21db3 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/find.lean | 82a6d8424618fa5fca1b0d9311d83527787927fc | [] | 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 | 620 | lean | /-
Copyright (c) 2017 Sebastian Ullrich. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.core
import Mathlib.PostPort
namespace Mathlib
/--
The `find` command from `tactic.find` allows to find definitions lemmas using
pattern matching on the type. For instance:
```lean
import tactic.find
run_cmd tactic.skip
#find _ + _ = _ + _
#find (_ : ℕ) + _ = _ + _
#find ℕ → ℕ
```
The tactic `library_search` is an alternate way to find lemmas in the library.
-/
|
60630237064dddbc729ce965462a74b716ec5173 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/mvar_fvar.lean | 804b5a179490d759498555dd5663225bceff9be9 | [
"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 | 393 | lean | import Lean
open Lean
instance : Coe Name FVarId where
coe n := { name := n }
instance : Coe Name MVarId where
coe n := { name := n }
#eval (mkFVar `a).hasFVar
#eval (mkApp (mkConst `foo) (mkFVar `a)).hasFVar
#eval (mkApp (mkConst `foo) (mkConst `a)).hasFVar
#eval (mkMVar `a).hasMVar
#eval (mkApp (mkConst `foo) (mkMVar `a)).hasMVar
#eval (mkApp (mkConst `foo) (mkConst `a)).hasMVar
|
d0cd1b53c79f9c679c721067f487cf39af4f873f | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/order/conditionally_complete_lattice.lean | 29a9e2fc4f52d9419a1c8c656394aff5d367b47a | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 39,052 | lean | /-
Copyright (c) 2018 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import data.nat.enat
import data.set.intervals.ord_connected
/-!
# Theory of conditionally complete lattices.
A conditionally complete lattice is a lattice in which every non-empty bounded subset s
has a least upper bound and a greatest lower bound, denoted below by Sup s and Inf s.
Typical examples are real, nat, int with their usual orders.
The theory is very comparable to the theory of complete lattices, except that suitable
boundedness and nonemptiness assumptions have to be added to most statements.
We introduce two predicates bdd_above and bdd_below to express this boundedness, prove
their basic properties, and then go on to prove most useful properties of Sup and Inf
in conditionally complete lattices.
To differentiate the statements between complete lattices and conditionally complete
lattices, we prefix Inf and Sup in the statements by c, giving cInf and cSup. For instance,
Inf_le is a statement in complete lattices ensuring Inf s ≤ x, while cInf_le is the same
statement in conditionally complete lattices with an additional assumption that s is
bounded below.
-/
set_option old_structure_cmd true
open set
variables {α β : Type*} {ι : Sort*}
section
/-!
Extension of Sup and Inf from a preorder `α` to `with_top α` and `with_bot α`
-/
open_locale classical
noncomputable instance {α : Type*} [preorder α] [has_Sup α] : has_Sup (with_top α) :=
⟨λ S, if ⊤ ∈ S then ⊤ else
if bdd_above (coe ⁻¹' S : set α) then ↑(Sup (coe ⁻¹' S : set α)) else ⊤⟩
noncomputable instance {α : Type*} [has_Inf α] : has_Inf (with_top α) :=
⟨λ S, if S ⊆ {⊤} then ⊤ else ↑(Inf (coe ⁻¹' S : set α))⟩
noncomputable instance {α : Type*} [has_Sup α] : has_Sup (with_bot α) :=
⟨(@with_top.has_Inf (order_dual α) _).Inf⟩
noncomputable instance {α : Type*} [preorder α] [has_Inf α] : has_Inf (with_bot α) :=
⟨(@with_top.has_Sup (order_dual α) _ _).Sup⟩
end -- section
/-- A conditionally complete lattice is a lattice in which
every nonempty subset which is bounded above has a supremum, and
every nonempty subset which is bounded below has an infimum.
Typical examples are real numbers or natural numbers.
To differentiate the statements from the corresponding statements in (unconditional)
complete lattices, we prefix Inf and Sup by a c everywhere. The same statements should
hold in both worlds, sometimes with additional assumptions of nonemptiness or
boundedness.-/
class conditionally_complete_lattice (α : Type*) extends lattice α, has_Sup α, has_Inf α :=
(le_cSup : ∀s a, bdd_above s → a ∈ s → a ≤ Sup s)
(cSup_le : ∀ s a, set.nonempty s → a ∈ upper_bounds s → Sup s ≤ a)
(cInf_le : ∀s a, bdd_below s → a ∈ s → Inf s ≤ a)
(le_cInf : ∀s a, set.nonempty s → a ∈ lower_bounds s → a ≤ Inf s)
/-- A conditionally complete linear order is a linear order in which
every nonempty subset which is bounded above has a supremum, and
every nonempty subset which is bounded below has an infimum.
Typical examples are real numbers or natural numbers.
To differentiate the statements from the corresponding statements in (unconditional)
complete linear orders, we prefix Inf and Sup by a c everywhere. The same statements should
hold in both worlds, sometimes with additional assumptions of nonemptiness or
boundedness.-/
class conditionally_complete_linear_order (α : Type*)
extends conditionally_complete_lattice α, linear_order α
/-- A conditionally complete linear order with `bot` is a linear order with least element, in which
every nonempty subset which is bounded above has a supremum, and every nonempty subset (necessarily
bounded below) has an infimum. A typical example is the natural numbers.
To differentiate the statements from the corresponding statements in (unconditional)
complete linear orders, we prefix Inf and Sup by a c everywhere. The same statements should
hold in both worlds, sometimes with additional assumptions of nonemptiness or
boundedness.-/
class conditionally_complete_linear_order_bot (α : Type*)
extends conditionally_complete_linear_order α, order_bot α :=
(cSup_empty : Sup ∅ = ⊥)
/- A complete lattice is a conditionally complete lattice, as there are no restrictions
on the properties of Inf and Sup in a complete lattice.-/
@[priority 100] -- see Note [lower instance priority]
instance conditionally_complete_lattice_of_complete_lattice [complete_lattice α]:
conditionally_complete_lattice α :=
{ le_cSup := by intros; apply le_Sup; assumption,
cSup_le := by intros; apply Sup_le; assumption,
cInf_le := by intros; apply Inf_le; assumption,
le_cInf := by intros; apply le_Inf; assumption,
..‹complete_lattice α› }
@[priority 100] -- see Note [lower instance priority]
instance conditionally_complete_linear_order_of_complete_linear_order [complete_linear_order α]:
conditionally_complete_linear_order α :=
{ ..conditionally_complete_lattice_of_complete_lattice, .. ‹complete_linear_order α› }
section conditionally_complete_lattice
variables [conditionally_complete_lattice α] {s t : set α} {a b : α}
theorem le_cSup (h₁ : bdd_above s) (h₂ : a ∈ s) : a ≤ Sup s :=
conditionally_complete_lattice.le_cSup s a h₁ h₂
theorem cSup_le (h₁ : s.nonempty) (h₂ : ∀b∈s, b ≤ a) : Sup s ≤ a :=
conditionally_complete_lattice.cSup_le s a h₁ h₂
theorem cInf_le (h₁ : bdd_below s) (h₂ : a ∈ s) : Inf s ≤ a :=
conditionally_complete_lattice.cInf_le s a h₁ h₂
theorem le_cInf (h₁ : s.nonempty) (h₂ : ∀b∈s, a ≤ b) : a ≤ Inf s :=
conditionally_complete_lattice.le_cInf s a h₁ h₂
theorem le_cSup_of_le (_ : bdd_above s) (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s :=
le_trans h (le_cSup ‹bdd_above s› hb)
theorem cInf_le_of_le (_ : bdd_below s) (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a :=
le_trans (cInf_le ‹bdd_below s› hb) h
theorem cSup_le_cSup (_ : bdd_above t) (_ : s.nonempty) (h : s ⊆ t) : Sup s ≤ Sup t :=
cSup_le ‹_› (assume (a) (ha : a ∈ s), le_cSup ‹bdd_above t› (h ha))
theorem cInf_le_cInf (_ : bdd_below t) (_ : s.nonempty) (h : s ⊆ t) : Inf t ≤ Inf s :=
le_cInf ‹_› (assume (a) (ha : a ∈ s), cInf_le ‹bdd_below t› (h ha))
lemma is_lub_cSup (ne : s.nonempty) (H : bdd_above s) : is_lub s (Sup s) :=
⟨assume x, le_cSup H, assume x, cSup_le ne⟩
lemma is_glb_cInf (ne : s.nonempty) (H : bdd_below s) : is_glb s (Inf s) :=
⟨assume x, cInf_le H, assume x, le_cInf ne⟩
lemma is_lub.cSup_eq (H : is_lub s a) (ne : s.nonempty) : Sup s = a :=
(is_lub_cSup ne ⟨a, H.1⟩).unique H
/-- A greatest element of a set is the supremum of this set. -/
lemma is_greatest.cSup_eq (H : is_greatest s a) : Sup s = a :=
H.is_lub.cSup_eq H.nonempty
lemma is_glb.cInf_eq (H : is_glb s a) (ne : s.nonempty) : Inf s = a :=
(is_glb_cInf ne ⟨a, H.1⟩).unique H
/-- A least element of a set is the infimum of this set. -/
lemma is_least.cInf_eq (H : is_least s a) : Inf s = a :=
H.is_glb.cInf_eq H.nonempty
lemma subset_Icc_cInf_cSup (hb : bdd_below s) (ha : bdd_above s) :
s ⊆ Icc (Inf s) (Sup s) :=
λ x hx, ⟨cInf_le hb hx, le_cSup ha hx⟩
theorem cSup_le_iff (hb : bdd_above s) (ne : s.nonempty) : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) :=
is_lub_le_iff (is_lub_cSup ne hb)
theorem le_cInf_iff (hb : bdd_below s) (ne : s.nonempty) : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) :=
le_is_glb_iff (is_glb_cInf ne hb)
lemma cSup_lower_bounds_eq_cInf {s : set α} (h : bdd_below s) (hs : s.nonempty) :
Sup (lower_bounds s) = Inf s :=
(is_lub_cSup h $ hs.mono $ λ x hx y hy, hy hx).unique (is_glb_cInf hs h).is_lub
lemma cInf_upper_bounds_eq_cSup {s : set α} (h : bdd_above s) (hs : s.nonempty) :
Inf (upper_bounds s) = Sup s :=
(is_glb_cInf h $ hs.mono $ λ x hx y hy, hy hx).unique (is_lub_cSup hs h).is_glb
/--Introduction rule to prove that b is the supremum of s: it suffices to check that b
is larger than all elements of s, and that this is not the case of any `w<b`.-/
theorem cSup_intro (_ : s.nonempty) (_ : ∀a∈s, a ≤ b) (H : ∀w, w < b → (∃a∈s, w < a)) : Sup s = b :=
have bdd_above s := ⟨b, by assumption⟩,
have (Sup s < b) ∨ (Sup s = b) := lt_or_eq_of_le (cSup_le ‹_› ‹∀a∈s, a ≤ b›),
have ¬(Sup s < b) :=
assume: Sup s < b,
let ⟨a, _, _⟩ := (H (Sup s) ‹Sup s < b›) in /- a ∈ s, Sup s < a-/
have Sup s < Sup s := lt_of_lt_of_le ‹Sup s < a› (le_cSup ‹bdd_above s› ‹a ∈ s›),
show false, by finish [lt_irrefl (Sup s)],
show Sup s = b, by finish
/--Introduction rule to prove that b is the infimum of s: it suffices to check that b
is smaller than all elements of s, and that this is not the case of any `w>b`.-/
theorem cInf_intro (_ : s.nonempty) (_ : ∀a∈s, b ≤ a) (H : ∀w, b < w → (∃a∈s, a < w)) : Inf s = b :=
have bdd_below s := ⟨b, by assumption⟩,
have (b < Inf s) ∨ (b = Inf s) := lt_or_eq_of_le (le_cInf ‹_› ‹∀a∈s, b ≤ a›),
have ¬(b < Inf s) :=
assume: b < Inf s,
let ⟨a, _, _⟩ := (H (Inf s) ‹b < Inf s›) in /- a ∈ s, a < Inf s-/
have Inf s < Inf s := lt_of_le_of_lt (cInf_le ‹bdd_below s› ‹a ∈ s›) ‹a < Inf s› ,
show false, by finish [lt_irrefl (Inf s)],
show Inf s = b, by finish
/--b < Sup s when there is an element a in s with b < a, when s is bounded above.
This is essentially an iff, except that the assumptions for the two implications are
slightly different (one needs boundedness above for one direction, nonemptiness and linear
order for the other one), so we formulate separately the two implications, contrary to
the complete_lattice case.-/
lemma lt_cSup_of_lt (_ : bdd_above s) (_ : a ∈ s) (_ : b < a) : b < Sup s :=
lt_of_lt_of_le ‹b < a› (le_cSup ‹bdd_above s› ‹a ∈ s›)
/--Inf s < b when there is an element a in s with a < b, when s is bounded below.
This is essentially an iff, except that the assumptions for the two implications are
slightly different (one needs boundedness below for one direction, nonemptiness and linear
order for the other one), so we formulate separately the two implications, contrary to
the complete_lattice case.-/
lemma cInf_lt_of_lt (_ : bdd_below s) (_ : a ∈ s) (_ : a < b) : Inf s < b :=
lt_of_le_of_lt (cInf_le ‹bdd_below s› ‹a ∈ s›) ‹a < b›
/-- If all elements of a nonempty set `s` are less than or equal to all elements
of a nonempty set `t`, then there exists an element between these sets. -/
lemma exists_between_of_forall_le (sne : s.nonempty) (tne : t.nonempty)
(hst : ∀ (x ∈ s) (y ∈ t), x ≤ y) :
(upper_bounds s ∩ lower_bounds t).nonempty :=
⟨Inf t, λ x hx, le_cInf tne $ hst x hx, λ y hy, cInf_le (sne.mono hst) hy⟩
/--The supremum of a singleton is the element of the singleton-/
@[simp] theorem cSup_singleton (a : α) : Sup {a} = a :=
is_greatest_singleton.cSup_eq
/--The infimum of a singleton is the element of the singleton-/
@[simp] theorem cInf_singleton (a : α) : Inf {a} = a :=
is_least_singleton.cInf_eq
/--If a set is bounded below and above, and nonempty, its infimum is less than or equal to
its supremum.-/
theorem cInf_le_cSup (hb : bdd_below s) (ha : bdd_above s) (ne : s.nonempty) : Inf s ≤ Sup s :=
is_glb_le_is_lub (is_glb_cInf ne hb) (is_lub_cSup ne ha) ne
/--The sup of a union of two sets is the max of the suprema of each subset, under the assumptions
that all sets are bounded above and nonempty.-/
theorem cSup_union (hs : bdd_above s) (sne : s.nonempty) (ht : bdd_above t) (tne : t.nonempty) :
Sup (s ∪ t) = Sup s ⊔ Sup t :=
((is_lub_cSup sne hs).union (is_lub_cSup tne ht)).cSup_eq sne.inl
/--The inf of a union of two sets is the min of the infima of each subset, under the assumptions
that all sets are bounded below and nonempty.-/
theorem cInf_union (hs : bdd_below s) (sne : s.nonempty) (ht : bdd_below t) (tne : t.nonempty) :
Inf (s ∪ t) = Inf s ⊓ Inf t :=
((is_glb_cInf sne hs).union (is_glb_cInf tne ht)).cInf_eq sne.inl
/--The supremum of an intersection of two sets is bounded by the minimum of the suprema of each
set, if all sets are bounded above and nonempty.-/
theorem cSup_inter_le (_ : bdd_above s) (_ : bdd_above t) (hst : (s ∩ t).nonempty) :
Sup (s ∩ t) ≤ Sup s ⊓ Sup t :=
begin
apply cSup_le hst, simp only [le_inf_iff, and_imp, set.mem_inter_eq], intros b _ _, split,
apply le_cSup ‹bdd_above s› ‹b ∈ s›,
apply le_cSup ‹bdd_above t› ‹b ∈ t›
end
/--The infimum of an intersection of two sets is bounded below by the maximum of the
infima of each set, if all sets are bounded below and nonempty.-/
theorem le_cInf_inter (_ : bdd_below s) (_ : bdd_below t) (hst : (s ∩ t).nonempty) :
Inf s ⊔ Inf t ≤ Inf (s ∩ t) :=
begin
apply le_cInf hst, simp only [and_imp, set.mem_inter_eq, sup_le_iff], intros b _ _, split,
apply cInf_le ‹bdd_below s› ‹b ∈ s›,
apply cInf_le ‹bdd_below t› ‹b ∈ t›
end
/-- The supremum of insert a s is the maximum of a and the supremum of s, if s is
nonempty and bounded above.-/
theorem cSup_insert (hs : bdd_above s) (sne : s.nonempty) : Sup (insert a s) = a ⊔ Sup s :=
((is_lub_cSup sne hs).insert a).cSup_eq (insert_nonempty a s)
/-- The infimum of insert a s is the minimum of a and the infimum of s, if s is
nonempty and bounded below.-/
theorem cInf_insert (hs : bdd_below s) (sne : s.nonempty) : Inf (insert a s) = a ⊓ Inf s :=
((is_glb_cInf sne hs).insert a).cInf_eq (insert_nonempty a s)
@[simp] lemma cInf_Ici : Inf (Ici a) = a := is_least_Ici.cInf_eq
@[simp] lemma cSup_Iic : Sup (Iic a) = a := is_greatest_Iic.cSup_eq
/--The indexed supremum of two functions are comparable if the functions are pointwise comparable-/
lemma csupr_le_csupr {f g : ι → α} (B : bdd_above (range g)) (H : ∀x, f x ≤ g x) :
supr f ≤ supr g :=
begin
classical, by_cases hι : nonempty ι,
{ have Rf : (range f).nonempty, { exactI range_nonempty _ },
apply cSup_le Rf,
rintros y ⟨x, rfl⟩,
have : g x ∈ range g := ⟨x, rfl⟩,
exact le_cSup_of_le B this (H x) },
{ have Rf : range f = ∅, from range_eq_empty.2 hι,
have Rg : range g = ∅, from range_eq_empty.2 hι,
unfold supr, rw [Rf, Rg] }
end
/--The indexed supremum of a function is bounded above by a uniform bound-/
lemma csupr_le [nonempty ι] {f : ι → α} {c : α} (H : ∀x, f x ≤ c) : supr f ≤ c :=
cSup_le (range_nonempty f) (by rwa forall_range_iff)
/--The indexed supremum of a function is bounded below by the value taken at one point-/
lemma le_csupr {f : ι → α} (H : bdd_above (range f)) (c : ι) : f c ≤ supr f :=
le_cSup H (mem_range_self _)
/--The indexed infimum of two functions are comparable if the functions are pointwise comparable-/
lemma cinfi_le_cinfi {f g : ι → α} (B : bdd_below (range f)) (H : ∀x, f x ≤ g x) :
infi f ≤ infi g :=
begin
classical, by_cases hι : nonempty ι,
{ have Rg : (range g).nonempty, { exactI range_nonempty _ },
apply le_cInf Rg,
rintros y ⟨x, rfl⟩,
have : f x ∈ range f := ⟨x, rfl⟩,
exact cInf_le_of_le B this (H x) },
{ have Rf : range f = ∅, from range_eq_empty.2 hι,
have Rg : range g = ∅, from range_eq_empty.2 hι,
unfold infi, rw [Rf, Rg] }
end
/--The indexed minimum of a function is bounded below by a uniform lower bound-/
lemma le_cinfi [nonempty ι] {f : ι → α} {c : α} (H : ∀x, c ≤ f x) : c ≤ infi f :=
le_cInf (range_nonempty f) (by rwa forall_range_iff)
/--The indexed infimum of a function is bounded above by the value taken at one point-/
lemma cinfi_le {f : ι → α} (H : bdd_below (range f)) (c : ι) : infi f ≤ f c :=
cInf_le H (mem_range_self _)
@[simp] theorem cinfi_const [hι : nonempty ι] {a : α} : (⨅ b:ι, a) = a :=
by rw [infi, range_const, cInf_singleton]
@[simp] theorem csupr_const [hι : nonempty ι] {a : α} : (⨆ b:ι, a) = a :=
by rw [supr, range_const, cSup_singleton]
/-- Nested intervals lemma: if `f` is a monotonically increasing sequence, `g` is a monotonically
decreasing sequence, and `f n ≤ g n` for all `n`, then `⨆ n, f n` belongs to all the intervals
`[f n, g n]`. -/
lemma csupr_mem_Inter_Icc_of_mono_incr_of_mono_decr [nonempty β] [semilattice_sup β]
{f g : β → α} (hf : monotone f) (hg : ∀ ⦃m n⦄, m ≤ n → g n ≤ g m) (h : ∀ n, f n ≤ g n) :
(⨆ n, f n) ∈ ⋂ n, Icc (f n) (g n) :=
begin
inhabit β,
refine mem_Inter.2 (λ n, ⟨le_csupr ⟨g $ default β, forall_range_iff.2 $ λ m, _⟩ _,
csupr_le $ λ m, _⟩); exact forall_le_of_monotone_of_mono_decr hf hg h _ _
end
/-- Nested intervals lemma: if `[f n, g n]` is a monotonically decreasing sequence of nonempty
closed intervals, then `⨆ n, f n` belongs to all the intervals `[f n, g n]`. -/
lemma csupr_mem_Inter_Icc_of_mono_decr_Icc [nonempty β] [semilattice_sup β]
{f g : β → α} (h : ∀ ⦃m n⦄, m ≤ n → Icc (f n) (g n) ⊆ Icc (f m) (g m)) (h' : ∀ n, f n ≤ g n) :
(⨆ n, f n) ∈ ⋂ n, Icc (f n) (g n) :=
csupr_mem_Inter_Icc_of_mono_incr_of_mono_decr (λ m n hmn, ((Icc_subset_Icc_iff (h' n)).1 (h hmn)).1)
(λ m n hmn, ((Icc_subset_Icc_iff (h' n)).1 (h hmn)).2) h'
/-- Nested intervals lemma: if `[f n, g n]` is a monotonically decreasing sequence of nonempty
closed intervals, then `⨆ n, f n` belongs to all the intervals `[f n, g n]`. -/
lemma csupr_mem_Inter_Icc_of_mono_decr_Icc_nat
{f g : ℕ → α} (h : ∀ n, Icc (f (n + 1)) (g (n + 1)) ⊆ Icc (f n) (g n)) (h' : ∀ n, f n ≤ g n) :
(⨆ n, f n) ∈ ⋂ n, Icc (f n) (g n) :=
csupr_mem_Inter_Icc_of_mono_decr_Icc
(@monotone_of_monotone_nat (order_dual $ set α) _ (λ n, Icc (f n) (g n)) h) h'
end conditionally_complete_lattice
instance pi.conditionally_complete_lattice {ι : Type*} {α : Π i : ι, Type*}
[Π i, conditionally_complete_lattice (α i)] :
conditionally_complete_lattice (Π i, α i) :=
{ le_cSup := λ s f ⟨g, hg⟩ hf i, le_cSup ⟨g i, set.forall_range_iff.2 $ λ ⟨f', hf'⟩, hg hf' i⟩
⟨⟨f, hf⟩, rfl⟩,
cSup_le := λ s f hs hf i, cSup_le (by haveI := hs.to_subtype; apply range_nonempty) $
λ b ⟨⟨g, hg⟩, hb⟩, hb ▸ hf hg i,
cInf_le := λ s f ⟨g, hg⟩ hf i, cInf_le ⟨g i, set.forall_range_iff.2 $ λ ⟨f', hf'⟩, hg hf' i⟩
⟨⟨f, hf⟩, rfl⟩,
le_cInf := λ s f hs hf i, le_cInf (by haveI := hs.to_subtype; apply range_nonempty) $
λ b ⟨⟨g, hg⟩, hb⟩, hb ▸ hf hg i,
.. pi.lattice, .. pi.has_Sup, .. pi.has_Inf }
section conditionally_complete_linear_order
variables [conditionally_complete_linear_order α] {s t : set α} {a b : α}
/-- When b < Sup s, there is an element a in s with b < a, if s is nonempty and the order is
a linear order. -/
lemma exists_lt_of_lt_cSup (hs : s.nonempty) (hb : b < Sup s) : ∃a∈s, b < a :=
begin
classical, contrapose! hb,
exact cSup_le hs hb
end
/--
Indexed version of the above lemma `exists_lt_of_lt_cSup`.
When `b < supr f`, there is an element `i` such that `b < f i`.
-/
lemma exists_lt_of_lt_csupr [nonempty ι] {f : ι → α} (h : b < supr f) :
∃i, b < f i :=
let ⟨_, ⟨i, rfl⟩, h⟩ := exists_lt_of_lt_cSup (range_nonempty f) h in ⟨i, h⟩
/--When Inf s < b, there is an element a in s with a < b, if s is nonempty and the order is
a linear order.-/
lemma exists_lt_of_cInf_lt (hs : s.nonempty) (hb : Inf s < b) : ∃a∈s, a < b :=
begin
classical, contrapose! hb,
exact le_cInf hs hb
end
/--
Indexed version of the above lemma `exists_lt_of_cInf_lt`
When `infi f < a`, there is an element `i` such that `f i < a`.
-/
lemma exists_lt_of_cinfi_lt [nonempty ι] {f : ι → α} (h : infi f < a) :
(∃i, f i < a) :=
let ⟨_, ⟨i, rfl⟩, h⟩ := exists_lt_of_cInf_lt (range_nonempty f) h in ⟨i, h⟩
/--Introduction rule to prove that b is the supremum of s: it suffices to check that
1) b is an upper bound
2) every other upper bound b' satisfies b ≤ b'.-/
theorem cSup_intro' (_ : s.nonempty)
(h_is_ub : ∀ a ∈ s, a ≤ b) (h_b_le_ub : ∀ub, (∀ a ∈ s, a ≤ ub) → (b ≤ ub)) : Sup s = b :=
le_antisymm
(show Sup s ≤ b, from cSup_le ‹s.nonempty› h_is_ub)
(show b ≤ Sup s, from h_b_le_ub _ $ assume a, le_cSup ⟨b, h_is_ub⟩)
end conditionally_complete_linear_order
section conditionally_complete_linear_order_bot
lemma cSup_empty [conditionally_complete_linear_order_bot α] : (Sup ∅ : α) = ⊥ :=
conditionally_complete_linear_order_bot.cSup_empty
end conditionally_complete_linear_order_bot
namespace nat
open_locale classical
noncomputable instance : has_Inf ℕ :=
⟨λs, if h : ∃n, n ∈ s then @nat.find (λn, n ∈ s) _ h else 0⟩
noncomputable instance : has_Sup ℕ :=
⟨λs, if h : ∃n, ∀a∈s, a ≤ n then @nat.find (λn, ∀a∈s, a ≤ n) _ h else 0⟩
lemma Inf_def {s : set ℕ} (h : s.nonempty) : Inf s = @nat.find (λn, n ∈ s) _ h :=
dif_pos _
lemma Sup_def {s : set ℕ} (h : ∃n, ∀a∈s, a ≤ n) :
Sup s = @nat.find (λn, ∀a∈s, a ≤ n) _ h :=
dif_pos _
@[simp] lemma Inf_eq_zero {s : set ℕ} : Inf s = 0 ↔ 0 ∈ s ∨ s = ∅ :=
begin
cases eq_empty_or_nonempty s,
{ subst h, simp only [or_true, eq_self_iff_true, iff_true, Inf, has_Inf.Inf,
mem_empty_eq, exists_false, dif_neg, not_false_iff] },
{ have := ne_empty_iff_nonempty.mpr h,
simp only [this, or_false, nat.Inf_def, h, nat.find_eq_zero] }
end
lemma Inf_mem {s : set ℕ} (h : s.nonempty) : Inf s ∈ s :=
by { rw [nat.Inf_def h], exact nat.find_spec h }
lemma not_mem_of_lt_Inf {s : set ℕ} {m : ℕ} (hm : m < Inf s) : m ∉ s :=
begin
cases eq_empty_or_nonempty s,
{ subst h, apply not_mem_empty },
{ rw [nat.Inf_def h] at hm, exact nat.find_min h hm }
end
protected lemma Inf_le {s : set ℕ} {m : ℕ} (hm : m ∈ s) : Inf s ≤ m :=
by { rw [nat.Inf_def ⟨m, hm⟩], exact nat.find_min' ⟨m, hm⟩ hm }
/-- This instance is necessary, otherwise the lattice operations would be derived via
conditionally_complete_linear_order_bot and marked as noncomputable. -/
instance : lattice ℕ := lattice_of_linear_order
noncomputable instance : conditionally_complete_linear_order_bot ℕ :=
{ Sup := Sup, Inf := Inf,
le_cSup := assume s a hb ha, by rw [Sup_def hb]; revert a ha; exact @nat.find_spec _ _ hb,
cSup_le := assume s a hs ha, by rw [Sup_def ⟨a, ha⟩]; exact nat.find_min' _ ha,
le_cInf := assume s a hs hb,
by rw [Inf_def hs]; exact hb (@nat.find_spec (λn, n ∈ s) _ _),
cInf_le := assume s a hb ha, by rw [Inf_def ⟨a, ha⟩]; exact nat.find_min' _ ha,
cSup_empty :=
begin
simp only [Sup_def, set.mem_empty_eq, forall_const, forall_prop_of_false, not_false_iff, exists_const],
apply bot_unique (nat.find_min' _ _),
trivial
end,
.. (infer_instance : order_bot ℕ), .. (lattice_of_linear_order : lattice ℕ),
.. (infer_instance : linear_order ℕ) }
end nat
namespace with_top
open_locale classical
variables [conditionally_complete_linear_order_bot α]
/-- The Sup of a non-empty set is its least upper bound for a conditionally
complete lattice with a top. -/
lemma is_lub_Sup' {β : Type*} [conditionally_complete_lattice β]
{s : set (with_top β)} (hs : s.nonempty) : is_lub s (Sup s) :=
begin
split,
{ show ite _ _ _ ∈ _,
split_ifs,
{ intros _ _, exact le_top },
{ rintro (⟨⟩|a) ha,
{ contradiction },
apply some_le_some.2,
exact le_cSup h_1 ha },
{ intros _ _, exact le_top } },
{ show ite _ _ _ ∈ _,
split_ifs,
{ rintro (⟨⟩|a) ha,
{ exact _root_.le_refl _ },
{ exact false.elim (not_top_le_coe a (ha h)) } },
{ rintro (⟨⟩|b) hb,
{ exact le_top },
refine some_le_some.2 (cSup_le _ _),
{ rcases hs with ⟨⟨⟩|b, hb⟩,
{ exact absurd hb h },
{ exact ⟨b, hb⟩ } },
{ intros a ha, exact some_le_some.1 (hb ha) } },
{ rintro (⟨⟩|b) hb,
{ exact _root_.le_refl _ },
{ exfalso, apply h_1, use b, intros a ha, exact some_le_some.1 (hb ha) } } }
end
lemma is_lub_Sup (s : set (with_top α)) : is_lub s (Sup s) :=
begin
cases s.eq_empty_or_nonempty with hs hs,
{ rw hs,
show is_lub ∅ (ite _ _ _),
split_ifs,
{ cases h },
{ rw [preimage_empty, cSup_empty], exact is_lub_empty },
{ exfalso, apply h_1, use ⊥, rintro a ⟨⟩ } },
exact is_lub_Sup' hs,
end
/-- The Inf of a bounded-below set is its greatest lower bound for a conditionally
complete lattice with a top. -/
lemma is_glb_Inf' {β : Type*} [conditionally_complete_lattice β]
{s : set (with_top β)} (hs : bdd_below s) : is_glb s (Inf s) :=
begin
split,
{ show ite _ _ _ ∈ _,
split_ifs,
{ intros a ha, exact top_le_iff.2 (set.mem_singleton_iff.1 (h ha)) },
{ rintro (⟨⟩|a) ha,
{ exact le_top },
refine some_le_some.2 (cInf_le _ ha),
rcases hs with ⟨⟨⟩|b, hb⟩,
{ exfalso,
apply h,
intros c hc,
rw [mem_singleton_iff, ←top_le_iff],
exact hb hc },
use b,
intros c hc,
exact some_le_some.1 (hb hc) } },
{ show ite _ _ _ ∈ _,
split_ifs,
{ intros _ _, exact le_top },
{ rintro (⟨⟩|a) ha,
{ exfalso, apply h, intros b hb, exact set.mem_singleton_iff.2 (top_le_iff.1 (ha hb)) },
{ refine some_le_some.2 (le_cInf _ _),
{ classical, contrapose! h,
rintros (⟨⟩|a) ha,
{ exact mem_singleton ⊤ },
{ exact (h ⟨a, ha⟩).elim }},
{ intros b hb,
rw ←some_le_some,
exact ha hb } } } }
end
lemma is_glb_Inf (s : set (with_top α)) : is_glb s (Inf s) :=
begin
by_cases hs : bdd_below s,
{ exact is_glb_Inf' hs },
{ exfalso, apply hs, use ⊥, intros _ _, exact bot_le },
end
noncomputable instance : complete_linear_order (with_top α) :=
{ Sup := Sup, le_Sup := assume s, (is_lub_Sup s).1, Sup_le := assume s, (is_lub_Sup s).2,
Inf := Inf, le_Inf := assume s, (is_glb_Inf s).2, Inf_le := assume s, (is_glb_Inf s).1,
decidable_le := classical.dec_rel _,
.. with_top.linear_order, ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot }
lemma coe_Sup {s : set α} (hb : bdd_above s) : (↑(Sup s) : with_top α) = (⨆a∈s, ↑a) :=
begin
cases s.eq_empty_or_nonempty with hs hs,
{ rw [hs, cSup_empty], simp only [set.mem_empty_eq, supr_bot, supr_false], refl },
apply le_antisymm,
{ refine ((coe_le_iff _ _).2 $ assume b hb, cSup_le hs $ assume a has, coe_le_coe.1 $ hb ▸ _),
exact (le_supr_of_le a $ le_supr_of_le has $ _root_.le_refl _) },
{ exact (supr_le $ assume a, supr_le $ assume ha, coe_le_coe.2 $ le_cSup hb ha) }
end
lemma coe_Inf {s : set α} (hs : s.nonempty) : (↑(Inf s) : with_top α) = (⨅a∈s, ↑a) :=
let ⟨x, hx⟩ := hs in
have (⨅a∈s, ↑a : with_top α) ≤ x, from infi_le_of_le x $ infi_le_of_le hx $ _root_.le_refl _,
let ⟨r, r_eq, hr⟩ := (le_coe_iff _ _).1 this in
le_antisymm
(le_infi $ assume a, le_infi $ assume ha, coe_le_coe.2 $ cInf_le (order_bot.bdd_below s) ha)
begin
refine (r_eq.symm ▸ coe_le_coe.2 $ le_cInf hs $ assume a has, coe_le_coe.1 $ _),
refine (r_eq ▸ infi_le_of_le a _),
exact (infi_le_of_le has $ _root_.le_refl _),
end
end with_top
namespace enat
open_locale classical
noncomputable instance : complete_linear_order enat :=
{ Sup := λ s, with_top_equiv.symm $ Sup (with_top_equiv '' s),
Inf := λ s, with_top_equiv.symm $ Inf (with_top_equiv '' s),
le_Sup := by intros; rw ← with_top_equiv_le; simp; apply le_Sup _; simpa,
Inf_le := by intros; rw ← with_top_equiv_le; simp; apply Inf_le _; simpa,
Sup_le := begin
intros s a h1,
rw [← with_top_equiv_le, with_top_equiv.right_inverse_symm],
apply Sup_le _,
rintros b ⟨x, h2, rfl⟩,
rw with_top_equiv_le,
apply h1,
assumption
end,
le_Inf := begin
intros s a h1,
rw [← with_top_equiv_le, with_top_equiv.right_inverse_symm],
apply le_Inf _,
rintros b ⟨x, h2, rfl⟩,
rw with_top_equiv_le,
apply h1,
assumption
end,
..enat.linear_order,
..enat.bounded_lattice }
end enat
section order_dual
instance (α : Type*) [conditionally_complete_lattice α] :
conditionally_complete_lattice (order_dual α) :=
{ le_cSup := @cInf_le α _,
cSup_le := @le_cInf α _,
le_cInf := @cSup_le α _,
cInf_le := @le_cSup α _,
..order_dual.has_Inf α,
..order_dual.has_Sup α,
..order_dual.lattice α }
instance (α : Type*) [conditionally_complete_linear_order α] :
conditionally_complete_linear_order (order_dual α) :=
{ ..order_dual.conditionally_complete_lattice α,
..order_dual.linear_order α }
end order_dual
namespace monotone
variables [preorder α] [conditionally_complete_lattice β] {f : α → β} (h_mono : monotone f)
/-! A monotone function into a conditionally complete lattice preserves the ordering properties of
`Sup` and `Inf`. -/
lemma le_cSup_image {s : set α} {c : α} (hcs : c ∈ s) (h_bdd : bdd_above s) :
f c ≤ Sup (f '' s) :=
le_cSup (map_bdd_above h_mono h_bdd) (mem_image_of_mem f hcs)
lemma cSup_image_le {s : set α} (hs : s.nonempty) {B : α} (hB: B ∈ upper_bounds s) :
Sup (f '' s) ≤ f B :=
cSup_le (nonempty.image f hs) (h_mono.mem_upper_bounds_image hB)
lemma cInf_image_le {s : set α} {c : α} (hcs : c ∈ s) (h_bdd : bdd_below s) :
Inf (f '' s) ≤ f c :=
@le_cSup_image (order_dual α) (order_dual β) _ _ _ (λ x y hxy, h_mono hxy) _ _ hcs h_bdd
lemma le_cInf_image {s : set α} (hs : s.nonempty) {B : α} (hB: B ∈ lower_bounds s) :
f B ≤ Inf (f '' s) :=
@cSup_image_le (order_dual α) (order_dual β) _ _ _ (λ x y hxy, h_mono hxy) _ hs _ hB
end monotone
section with_top_bot
/-!
### Complete lattice structure on `with_top (with_bot α)`
If `α` is a `conditionally_complete_lattice`, then we show that `with_top α` and `with_bot α`
also inherit the structure of conditionally complete lattices. Furthermore, we show
that `with_top (with_bot α)` naturally inherits the structure of a complete lattice. Note that
for α a conditionally complete lattice, `Sup` and `Inf` both return junk values
for sets which are empty or unbounded. The extension of `Sup` to `with_top α` fixes
the unboundedness problem and the extension to `with_bot α` fixes the problem with
the empty set.
This result can be used to show that the extended reals [-∞, ∞] are a complete lattice.
-/
open_locale classical
/-- Adding a top element to a conditionally complete lattice gives a conditionally complete lattice -/
noncomputable instance with_top.conditionally_complete_lattice
{α : Type*} [conditionally_complete_lattice α] :
conditionally_complete_lattice (with_top α) :=
{ le_cSup := λ S a hS haS, (with_top.is_lub_Sup' ⟨a, haS⟩).1 haS,
cSup_le := λ S a hS haS, (with_top.is_lub_Sup' hS).2 haS,
cInf_le := λ S a hS haS, (with_top.is_glb_Inf' hS).1 haS,
le_cInf := λ S a hS haS, (with_top.is_glb_Inf' ⟨a, haS⟩).2 haS,
..with_top.lattice,
..with_top.has_Sup,
..with_top.has_Inf }
/-- Adding a bottom element to a conditionally complete lattice gives a conditionally complete lattice -/
noncomputable instance with_bot.conditionally_complete_lattice
{α : Type*} [conditionally_complete_lattice α] :
conditionally_complete_lattice (with_bot α) :=
{ le_cSup := (@with_top.conditionally_complete_lattice (order_dual α) _).cInf_le,
cSup_le := (@with_top.conditionally_complete_lattice (order_dual α) _).le_cInf,
cInf_le := (@with_top.conditionally_complete_lattice (order_dual α) _).le_cSup,
le_cInf := (@with_top.conditionally_complete_lattice (order_dual α) _).cSup_le,
..with_bot.lattice,
..with_bot.has_Sup,
..with_bot.has_Inf }
/-- Adding a bottom and a top to a conditionally complete lattice gives a bounded lattice-/
noncomputable instance with_top.with_bot.bounded_lattice {α : Type*}
[conditionally_complete_lattice α] : bounded_lattice (with_top (with_bot α)) :=
{ ..with_top.order_bot,
..with_top.order_top,
..conditionally_complete_lattice.to_lattice _ }
theorem with_bot.cSup_empty {α : Type*} [conditionally_complete_lattice α] :
Sup (∅ : set (with_bot α)) = ⊥ :=
begin
show ite _ _ _ = ⊥,
split_ifs; finish,
end
noncomputable instance with_top.with_bot.complete_lattice {α : Type*}
[conditionally_complete_lattice α] : complete_lattice (with_top (with_bot α)) :=
{ le_Sup := λ S a haS, (with_top.is_lub_Sup' ⟨a, haS⟩).1 haS,
Sup_le := λ S a ha,
begin
cases S.eq_empty_or_nonempty with h,
{ show ite _ _ _ ≤ a,
split_ifs,
{ rw h at h_1, cases h_1 },
{ convert bot_le, convert with_bot.cSup_empty, rw h, refl },
{ exfalso, apply h_2, use ⊥, rw h, rintro b ⟨⟩ } },
{ refine (with_top.is_lub_Sup' h).2 ha }
end,
Inf_le := λ S a haS,
show ite _ _ _ ≤ a,
begin
split_ifs,
{ cases a with a, exact _root_.le_refl _,
cases (h haS); tauto },
{ cases a,
{ exact le_top },
{ apply with_top.some_le_some.2, refine cInf_le _ haS, use ⊥, intros b hb, exact bot_le } }
end,
le_Inf := λ S a haS, (with_top.is_glb_Inf' ⟨a, haS⟩).2 haS,
..with_top.has_Inf,
..with_top.has_Sup,
..with_top.with_bot.bounded_lattice }
end with_top_bot
section subtype
variables (s : set α)
/-! ### Subtypes of conditionally complete linear orders
In this section we give conditions on a subset of a conditionally complete linear order, to ensure
that the subtype is itself conditionally complete.
We check that an `ord_connected` set satisfies these conditions.
TODO There are several possible variants; the `conditionally_complete_linear_order` could be changed
to `conditionally_complete_linear_order_bot` or `complete_linear_order`.
-/
open_locale classical
section has_Sup
variables [has_Sup α]
/-- `has_Sup` structure on a nonempty subset `s` of an object with `has_Sup`. This definition is
non-canonical (it uses `default s`); it should be used only as here, as an auxiliary instance in the
construction of the `conditionally_complete_linear_order` structure. -/
noncomputable def subset_has_Sup [inhabited s] : has_Sup s := {Sup := λ t,
if ht : Sup (coe '' t : set α) ∈ s then ⟨Sup (coe '' t : set α), ht⟩ else default s}
local attribute [instance] subset_has_Sup
@[simp] lemma subset_Sup_def [inhabited s] :
@Sup s _ = λ t,
if ht : Sup (coe '' t : set α) ∈ s then ⟨Sup (coe '' t : set α), ht⟩ else default s :=
rfl
lemma subset_Sup_of_within [inhabited s] {t : set s} (h : Sup (coe '' t : set α) ∈ s) :
Sup (coe '' t : set α) = (@Sup s _ t : α) :=
by simp [dif_pos h]
end has_Sup
section has_Inf
variables [has_Inf α]
/-- `has_Inf` structure on a nonempty subset `s` of an object with `has_Inf`. This definition is
non-canonical (it uses `default s`); it should be used only as here, as an auxiliary instance in the
construction of the `conditionally_complete_linear_order` structure. -/
noncomputable def subset_has_Inf [inhabited s] : has_Inf s := {Inf := λ t,
if ht : Inf (coe '' t : set α) ∈ s then ⟨Inf (coe '' t : set α), ht⟩ else default s}
local attribute [instance] subset_has_Inf
@[simp] lemma subset_Inf_def [inhabited s] :
@Inf s _ = λ t,
if ht : Inf (coe '' t : set α) ∈ s then ⟨Inf (coe '' t : set α), ht⟩ else default s :=
rfl
lemma subset_Inf_of_within [inhabited s] {t : set s} (h : Inf (coe '' t : set α) ∈ s) :
Inf (coe '' t : set α) = (@Inf s _ t : α) :=
by simp [dif_pos h]
end has_Inf
variables [conditionally_complete_linear_order α]
local attribute [instance] subset_has_Sup
local attribute [instance] subset_has_Inf
/-- For a nonempty subset of a conditionally complete linear order to be a conditionally complete
linear order, it suffices that it contain the `Sup` of all its nonempty bounded-above subsets, and
the `Inf` of all its nonempty bounded-below subsets. -/
noncomputable def subset_conditionally_complete_linear_order [inhabited s]
(h_Sup : ∀ {t : set s} (ht : t.nonempty) (h_bdd : bdd_above t), Sup (coe '' t : set α) ∈ s)
(h_Inf : ∀ {t : set s} (ht : t.nonempty) (h_bdd : bdd_below t), Inf (coe '' t : set α) ∈ s) :
conditionally_complete_linear_order s :=
{ le_cSup := begin
rintros t c h_bdd hct,
-- The following would be a more natural way to finish, but gives a "deep recursion" error:
-- simpa [subset_Sup_of_within (h_Sup t)] using (strict_mono_coe s).monotone.le_cSup_image hct h_bdd,
have := (strict_mono_coe s).monotone.le_cSup_image hct h_bdd,
rwa subset_Sup_of_within s (h_Sup ⟨c, hct⟩ h_bdd) at this,
end,
cSup_le := begin
rintros t B ht hB,
have := (strict_mono_coe s).monotone.cSup_image_le ht hB,
rwa subset_Sup_of_within s (h_Sup ht ⟨B, hB⟩) at this,
end,
le_cInf := begin
intros t B ht hB,
have := (strict_mono_coe s).monotone.le_cInf_image ht hB,
rwa subset_Inf_of_within s (h_Inf ht ⟨B, hB⟩) at this,
end,
cInf_le := begin
rintros t c h_bdd hct,
have := (strict_mono_coe s).monotone.cInf_image_le hct h_bdd,
rwa subset_Inf_of_within s (h_Inf ⟨c, hct⟩ h_bdd) at this,
end,
..subset_has_Sup s,
..subset_has_Inf s,
..distrib_lattice.to_lattice s,
..(infer_instance : linear_order s) }
section ord_connected
/-- The `Sup` function on a nonempty `ord_connected` set `s` in a conditionally complete linear
order takes values within `s`, for all nonempty bounded-above subsets of `s`. -/
lemma Sup_within_of_ord_connected
{s : set α} [hs : ord_connected s] ⦃t : set s⦄ (ht : t.nonempty) (h_bdd : bdd_above t) :
Sup (coe '' t : set α) ∈ s :=
begin
obtain ⟨c, hct⟩ : ∃ c, c ∈ t := ht,
obtain ⟨B, hB⟩ : ∃ B, B ∈ upper_bounds t := h_bdd,
refine hs c.2 B.2 ⟨_, _⟩,
{ exact (strict_mono_coe s).monotone.le_cSup_image hct ⟨B, hB⟩ },
{ exact (strict_mono_coe s).monotone.cSup_image_le ⟨c, hct⟩ hB },
end
/-- The `Inf` function on a nonempty `ord_connected` set `s` in a conditionally complete linear
order takes values within `s`, for all nonempty bounded-below subsets of `s`. -/
lemma Inf_within_of_ord_connected
{s : set α} [hs : ord_connected s] ⦃t : set s⦄ (ht : t.nonempty) (h_bdd : bdd_below t) :
Inf (coe '' t : set α) ∈ s :=
begin
obtain ⟨c, hct⟩ : ∃ c, c ∈ t := ht,
obtain ⟨B, hB⟩ : ∃ B, B ∈ lower_bounds t := h_bdd,
refine hs B.2 c.2 ⟨_, _⟩,
{ exact (strict_mono_coe s).monotone.le_cInf_image ⟨c, hct⟩ hB },
{ exact (strict_mono_coe s).monotone.cInf_image_le hct ⟨B, hB⟩ },
end
/-- A nonempty `ord_connected` set in a conditionally complete linear order is naturally a
conditionally complete linear order. -/
noncomputable instance ord_connected_subset_conditionally_complete_linear_order
[inhabited s] [ord_connected s] :
conditionally_complete_linear_order s :=
subset_conditionally_complete_linear_order s Sup_within_of_ord_connected Inf_within_of_ord_connected
end ord_connected
end subtype
|
841ec23c99414a4b9cc03dd824deeccde28539f6 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/analysis/normed_space/lp_space.lean | 63ebebb327537fbf26bb57b2d33106b37f508581 | [
"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 | 42,897 | lean | /-
Copyright (c) 2021 Heather Macbeth. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Heather Macbeth
-/
import analysis.mean_inequalities
import analysis.mean_inequalities_pow
import analysis.normed.group.pointwise
import topology.algebra.order.liminf_limsup
/-!
# ℓp space
This file describes properties of elements `f` of a pi-type `Π i, E i` with finite "norm",
defined for `p:ℝ≥0∞` as the size of the support of `f` if `p=0`, `(∑' a, ∥f a∥^p) ^ (1/p)` for
`0 < p < ∞` and `⨆ a, ∥f a∥` for `p=∞`.
The Prop-valued `mem_ℓp f p` states that a function `f : Π i, E i` has finite norm according
to the above definition; that is, `f` has finite support if `p = 0`, `summable (λ a, ∥f a∥^p)` if
`0 < p < ∞`, and `bdd_above (norm '' (set.range f))` if `p = ∞`.
The space `lp E p` is the subtype of elements of `Π i : α, E i` which satisfy `mem_ℓp f p`. For
`1 ≤ p`, the "norm" is genuinely a norm and `lp` is a complete metric space.
## Main definitions
* `mem_ℓp f p` : property that the function `f` satisfies, as appropriate, `f` finitely supported
if `p = 0`, `summable (λ a, ∥f a∥^p)` if `0 < p < ∞`, and `bdd_above (norm '' (set.range f))` if
`p = ∞`.
* `lp E p` : elements of `Π i : α, E i` such that `mem_ℓp f p`. Defined as an `add_subgroup` of
a type synonym `pre_lp` for `Π i : α, E i`, and equipped with a `normed_add_comm_group` structure.
Under appropriate conditions, this is also equipped with the instances `lp.normed_space`,
`lp.complete_space`. For `p=∞`, there is also `lp.infty_normed_ring`,
`lp.infty_normed_algebra`, `lp.infty_star_ring` and `lp.infty_cstar_ring`.
## Main results
* `mem_ℓp.of_exponent_ge`: For `q ≤ p`, a function which is `mem_ℓp` for `q` is also `mem_ℓp` for
`p`
* `lp.mem_ℓp_of_tendsto`, `lp.norm_le_of_tendsto`: A pointwise limit of functions in `lp`, all with
`lp` norm `≤ C`, is itself in `lp` and has `lp` norm `≤ C`.
* `lp.tsum_mul_le_mul_norm`: basic form of Hölder's inequality
## Implementation
Since `lp` is defined as an `add_subgroup`, dot notation does not work. Use `lp.norm_neg f` to
say that `∥-f∥ = ∥f∥`, instead of the non-working `f.norm_neg`.
## TODO
* More versions of Hölder's inequality (for example: the case `p = 1`, `q = ∞`; a version for normed
rings which has `∥∑' i, f i * g i∥` rather than `∑' i, ∥f i∥ * g i∥` on the RHS; a version for
three exponents satisfying `1 / r = 1 / p + 1 / q`)
* Equivalence with `pi_Lp`, for `α` finite
* Equivalence with `measure_theory.Lp`, for `f : α → E` (i.e., functions rather than pi-types) and
the counting measure on `α`
* Equivalence with `bounded_continuous_function`, for `f : α → E` (i.e., functions rather than
pi-types) and `p = ∞`, and the discrete topology on `α`
-/
noncomputable theory
open_locale nnreal ennreal big_operators
variables {α : Type*} {E : α → Type*} {p q : ℝ≥0∞} [Π i, normed_add_comm_group (E i)]
/-!
### `mem_ℓp` predicate
-/
/-- The property that `f : Π i : α, E i`
* is finitely supported, if `p = 0`, or
* admits an upper bound for `set.range (λ i, ∥f i∥)`, if `p = ∞`, or
* has the series `∑' i, ∥f i∥ ^ p` be summable, if `0 < p < ∞`. -/
def mem_ℓp (f : Π i, E i) (p : ℝ≥0∞) : Prop :=
if p = 0 then (set.finite {i | f i ≠ 0}) else
(if p = ∞ then bdd_above (set.range (λ i, ∥f i∥)) else summable (λ i, ∥f i∥ ^ p.to_real))
lemma mem_ℓp_zero_iff {f : Π i, E i} : mem_ℓp f 0 ↔ set.finite {i | f i ≠ 0} :=
by dsimp [mem_ℓp]; rw [if_pos rfl]
lemma mem_ℓp_zero {f : Π i, E i} (hf : set.finite {i | f i ≠ 0}) : mem_ℓp f 0 :=
mem_ℓp_zero_iff.2 hf
lemma mem_ℓp_infty_iff {f : Π i, E i} : mem_ℓp f ∞ ↔ bdd_above (set.range (λ i, ∥f i∥)) :=
by dsimp [mem_ℓp]; rw [if_neg ennreal.top_ne_zero, if_pos rfl]
lemma mem_ℓp_infty {f : Π i, E i} (hf : bdd_above (set.range (λ i, ∥f i∥))) : mem_ℓp f ∞ :=
mem_ℓp_infty_iff.2 hf
lemma mem_ℓp_gen_iff (hp : 0 < p.to_real) {f : Π i, E i} :
mem_ℓp f p ↔ summable (λ i, ∥f i∥ ^ p.to_real) :=
begin
rw ennreal.to_real_pos_iff at hp,
dsimp [mem_ℓp],
rw [if_neg hp.1.ne', if_neg hp.2.ne],
end
lemma mem_ℓp_gen {f : Π i, E i} (hf : summable (λ i, ∥f i∥ ^ p.to_real)) :
mem_ℓp f p :=
begin
rcases p.trichotomy with rfl | rfl | hp,
{ apply mem_ℓp_zero,
have H : summable (λ i : α, (1:ℝ)) := by simpa using hf,
exact (finite_of_summable_const (by norm_num) H).subset (set.subset_univ _) },
{ apply mem_ℓp_infty,
have H : summable (λ i : α, (1:ℝ)) := by simpa using hf,
simpa using ((finite_of_summable_const (by norm_num) H).image (λ i, ∥f i∥)).bdd_above },
exact (mem_ℓp_gen_iff hp).2 hf
end
lemma mem_ℓp_gen' {C : ℝ} {f : Π i, E i} (hf : ∀ s : finset α, ∑ i in s, ∥f i∥ ^ p.to_real ≤ C) :
mem_ℓp f p :=
begin
apply mem_ℓp_gen,
use ⨆ s : finset α, ∑ i in s, ∥f i∥ ^ p.to_real,
apply has_sum_of_is_lub_of_nonneg,
{ intros b,
exact real.rpow_nonneg_of_nonneg (norm_nonneg _) _ },
apply is_lub_csupr,
use C,
rintros - ⟨s, rfl⟩,
exact hf s
end
lemma zero_mem_ℓp : mem_ℓp (0 : Π i, E i) p :=
begin
rcases p.trichotomy with rfl | rfl | hp,
{ apply mem_ℓp_zero,
simp },
{ apply mem_ℓp_infty,
simp only [norm_zero, pi.zero_apply],
exact bdd_above_singleton.mono set.range_const_subset, },
{ apply mem_ℓp_gen,
simp [real.zero_rpow hp.ne', summable_zero], }
end
lemma zero_mem_ℓp' : mem_ℓp (λ i : α, (0 : E i)) p := zero_mem_ℓp
namespace mem_ℓp
lemma finite_dsupport {f : Π i, E i} (hf : mem_ℓp f 0) : set.finite {i | f i ≠ 0} :=
mem_ℓp_zero_iff.1 hf
lemma bdd_above {f : Π i, E i} (hf : mem_ℓp f ∞) : bdd_above (set.range (λ i, ∥f i∥)) :=
mem_ℓp_infty_iff.1 hf
lemma summable (hp : 0 < p.to_real) {f : Π i, E i} (hf : mem_ℓp f p) :
summable (λ i, ∥f i∥ ^ p.to_real) :=
(mem_ℓp_gen_iff hp).1 hf
lemma neg {f : Π i, E i} (hf : mem_ℓp f p) : mem_ℓp (-f) p :=
begin
rcases p.trichotomy with rfl | rfl | hp,
{ apply mem_ℓp_zero,
simp [hf.finite_dsupport] },
{ apply mem_ℓp_infty,
simpa using hf.bdd_above },
{ apply mem_ℓp_gen,
simpa using hf.summable hp },
end
@[simp] lemma neg_iff {f : Π i, E i} : mem_ℓp (-f) p ↔ mem_ℓp f p :=
⟨λ h, neg_neg f ▸ h.neg, mem_ℓp.neg⟩
lemma of_exponent_ge {p q : ℝ≥0∞} {f : Π i, E i}
(hfq : mem_ℓp f q) (hpq : q ≤ p) :
mem_ℓp f p :=
begin
rcases ennreal.trichotomy₂ hpq with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩ | ⟨rfl, hp⟩ | ⟨rfl, rfl⟩ | ⟨hq, rfl⟩
| ⟨hq, hp, hpq'⟩,
{ exact hfq },
{ apply mem_ℓp_infty,
obtain ⟨C, hC⟩ := (hfq.finite_dsupport.image (λ i, ∥f i∥)).bdd_above,
use max 0 C,
rintros x ⟨i, rfl⟩,
by_cases hi : f i = 0,
{ simp [hi] },
{ exact (hC ⟨i, hi, rfl⟩).trans (le_max_right _ _) } },
{ apply mem_ℓp_gen,
have : ∀ i ∉ hfq.finite_dsupport.to_finset, ∥f i∥ ^ p.to_real = 0,
{ intros i hi,
have : f i = 0 := by simpa using hi,
simp [this, real.zero_rpow hp.ne'] },
exact summable_of_ne_finset_zero this },
{ exact hfq },
{ apply mem_ℓp_infty,
obtain ⟨A, hA⟩ := (hfq.summable hq).tendsto_cofinite_zero.bdd_above_range_of_cofinite,
use A ^ (q.to_real⁻¹),
rintros x ⟨i, rfl⟩,
have : 0 ≤ ∥f i∥ ^ q.to_real := real.rpow_nonneg_of_nonneg (norm_nonneg _) _,
simpa [← real.rpow_mul, mul_inv_cancel hq.ne'] using
real.rpow_le_rpow this (hA ⟨i, rfl⟩) (inv_nonneg.mpr hq.le) },
{ apply mem_ℓp_gen,
have hf' := hfq.summable hq,
refine summable_of_norm_bounded_eventually _ hf' (@set.finite.subset _ {i | 1 ≤ ∥f i∥} _ _ _),
{ have H : {x : α | 1 ≤ ∥f x∥ ^ q.to_real}.finite,
{ simpa using eventually_lt_of_tendsto_lt (by norm_num : (0:ℝ) < 1)
hf'.tendsto_cofinite_zero },
exact H.subset (λ i hi, real.one_le_rpow hi hq.le) },
{ show ∀ i, ¬ (|∥f i∥ ^ p.to_real| ≤ ∥f i∥ ^ q.to_real) → 1 ≤ ∥f i∥,
intros i hi,
have : 0 ≤ ∥f i∥ ^ p.to_real := real.rpow_nonneg_of_nonneg (norm_nonneg _) p.to_real,
simp only [abs_of_nonneg, this] at hi,
contrapose! hi,
exact real.rpow_le_rpow_of_exponent_ge' (norm_nonneg _) hi.le hq.le hpq' } }
end
lemma add {f g : Π i, E i} (hf : mem_ℓp f p) (hg : mem_ℓp g p) : mem_ℓp (f + g) p :=
begin
rcases p.trichotomy with rfl | rfl | hp,
{ apply mem_ℓp_zero,
refine (hf.finite_dsupport.union hg.finite_dsupport).subset (λ i, _),
simp only [pi.add_apply, ne.def, set.mem_union_eq, set.mem_set_of_eq],
contrapose!,
rintros ⟨hf', hg'⟩,
simp [hf', hg'] },
{ apply mem_ℓp_infty,
obtain ⟨A, hA⟩ := hf.bdd_above,
obtain ⟨B, hB⟩ := hg.bdd_above,
refine ⟨A + B, _⟩,
rintros a ⟨i, rfl⟩,
exact le_trans (norm_add_le _ _) (add_le_add (hA ⟨i, rfl⟩) (hB ⟨i, rfl⟩)) },
apply mem_ℓp_gen,
let C : ℝ := if p.to_real < 1 then 1 else 2 ^ (p.to_real - 1),
refine summable_of_nonneg_of_le _ (λ i, _) (((hf.summable hp).add (hg.summable hp)).mul_left C),
{ exact λ b, real.rpow_nonneg_of_nonneg (norm_nonneg (f b + g b)) p.to_real },
{ refine (real.rpow_le_rpow (norm_nonneg _) (norm_add_le _ _) hp.le).trans _,
dsimp [C],
split_ifs with h h,
{ simpa using nnreal.coe_le_coe.2 (nnreal.rpow_add_le_add_rpow (∥f i∥₊) (∥g i∥₊) hp.le h.le) },
{ let F : fin 2 → ℝ≥0 := ![∥f i∥₊, ∥g i∥₊],
have : ∀ i, (0:ℝ) ≤ F i := λ i, (F i).coe_nonneg,
simp only [not_lt] at h,
simpa [F, fin.sum_univ_succ] using
real.rpow_sum_le_const_mul_sum_rpow_of_nonneg (finset.univ : finset (fin 2)) h
(λ i _, (F i).coe_nonneg) } }
end
lemma sub {f g : Π i, E i} (hf : mem_ℓp f p) (hg : mem_ℓp g p) : mem_ℓp (f - g) p :=
by { rw sub_eq_add_neg, exact hf.add hg.neg }
lemma finset_sum {ι} (s : finset ι) {f : ι → Π i, E i} (hf : ∀ i ∈ s, mem_ℓp (f i) p) :
mem_ℓp (λ a, ∑ i in s, f i a) p :=
begin
haveI : decidable_eq ι := classical.dec_eq _,
revert hf,
refine finset.induction_on s _ _,
{ simp only [zero_mem_ℓp', finset.sum_empty, implies_true_iff], },
{ intros i s his ih hf,
simp only [his, finset.sum_insert, not_false_iff],
exact (hf i (s.mem_insert_self i)).add (ih (λ j hj, hf j (finset.mem_insert_of_mem hj))), },
end
section normed_space
variables {𝕜 : Type*} [normed_field 𝕜] [Π i, normed_space 𝕜 (E i)]
lemma const_smul {f : Π i, E i} (hf : mem_ℓp f p) (c : 𝕜) : mem_ℓp (c • f) p :=
begin
rcases p.trichotomy with rfl | rfl | hp,
{ apply mem_ℓp_zero,
refine hf.finite_dsupport.subset (λ i, (_ : ¬c • f i = 0 → ¬f i = 0)),
exact not_imp_not.mpr (λ hf', hf'.symm ▸ (smul_zero c)) },
{ obtain ⟨A, hA⟩ := hf.bdd_above,
refine mem_ℓp_infty ⟨∥c∥ * A, _⟩,
rintros a ⟨i, rfl⟩,
simpa [norm_smul] using mul_le_mul_of_nonneg_left (hA ⟨i, rfl⟩) (norm_nonneg c) },
{ apply mem_ℓp_gen,
convert (hf.summable hp).mul_left (∥c∥ ^ p.to_real),
ext i,
simp [norm_smul, real.mul_rpow (norm_nonneg c) (norm_nonneg (f i))] },
end
lemma const_mul {f : α → 𝕜} (hf : mem_ℓp f p) (c : 𝕜) : mem_ℓp (λ x, c * f x) p :=
@mem_ℓp.const_smul α (λ i, 𝕜) _ _ 𝕜 _ _ _ hf c
end normed_space
end mem_ℓp
/-!
### lp space
The space of elements of `Π i, E i` satisfying the predicate `mem_ℓp`.
-/
/-- We define `pre_lp E` to be a type synonym for `Π i, E i` which, importantly, does not inherit
the `pi` topology on `Π i, E i` (otherwise this topology would descend to `lp E p` and conflict
with the normed group topology we will later equip it with.)
We choose to deal with this issue by making a type synonym for `Π i, E i` rather than for the `lp`
subgroup itself, because this allows all the spaces `lp E p` (for varying `p`) to be subgroups of
the same ambient group, which permits lemma statements like `lp.monotone` (below). -/
@[derive add_comm_group, nolint unused_arguments]
def pre_lp (E : α → Type*) [Π i, normed_add_comm_group (E i)] : Type* := Π i, E i
instance pre_lp.unique [is_empty α] : unique (pre_lp E) := pi.unique_of_is_empty E
/-- lp space -/
def lp (E : α → Type*) [Π i, normed_add_comm_group (E i)]
(p : ℝ≥0∞) : add_subgroup (pre_lp E) :=
{ carrier := {f | mem_ℓp f p},
zero_mem' := zero_mem_ℓp,
add_mem' := λ f g, mem_ℓp.add,
neg_mem' := λ f, mem_ℓp.neg }
namespace lp
instance : has_coe (lp E p) (Π i, E i) := coe_subtype
instance : has_coe_to_fun (lp E p) (λ _, Π i, E i) := ⟨λ f, ((f : Π i, E i) : Π i, E i)⟩
@[ext] lemma ext {f g : lp E p} (h : (f : Π i, E i) = g) : f = g :=
subtype.ext h
protected lemma ext_iff {f g : lp E p} : f = g ↔ (f : Π i, E i) = g :=
subtype.ext_iff
lemma eq_zero' [is_empty α] (f : lp E p) : f = 0 := subsingleton.elim f 0
protected lemma monotone {p q : ℝ≥0∞} (hpq : q ≤ p) : lp E q ≤ lp E p :=
λ f hf, mem_ℓp.of_exponent_ge hf hpq
protected lemma mem_ℓp (f : lp E p) : mem_ℓp f p := f.prop
variables (E p)
@[simp] lemma coe_fn_zero : ⇑(0 : lp E p) = 0 := rfl
variables {E p}
@[simp] lemma coe_fn_neg (f : lp E p) : ⇑(-f) = -f := rfl
@[simp] lemma coe_fn_add (f g : lp E p) : ⇑(f + g) = f + g := rfl
@[simp] lemma coe_fn_sum {ι : Type*} (f : ι → lp E p) (s : finset ι) :
⇑(∑ i in s, f i) = ∑ i in s, ⇑(f i) :=
begin
classical,
refine finset.induction _ _ s,
{ simp },
intros i s his,
simp [finset.sum_insert his],
end
@[simp] lemma coe_fn_sub (f g : lp E p) : ⇑(f - g) = f - g := rfl
instance : has_norm (lp E p) :=
{ norm := λ f, if hp : p = 0 then by subst hp; exact (lp.mem_ℓp f).finite_dsupport.to_finset.card
else (if p = ∞ then ⨆ i, ∥f i∥ else (∑' i, ∥f i∥ ^ p.to_real) ^ (1/p.to_real)) }
lemma norm_eq_card_dsupport (f : lp E 0) : ∥f∥ = (lp.mem_ℓp f).finite_dsupport.to_finset.card :=
dif_pos rfl
lemma norm_eq_csupr (f : lp E ∞) : ∥f∥ = ⨆ i, ∥f i∥ :=
begin
dsimp [norm],
rw [dif_neg ennreal.top_ne_zero, if_pos rfl]
end
lemma is_lub_norm [nonempty α] (f : lp E ∞) : is_lub (set.range (λ i, ∥f i∥)) ∥f∥ :=
begin
rw lp.norm_eq_csupr,
exact is_lub_csupr (lp.mem_ℓp f)
end
lemma norm_eq_tsum_rpow (hp : 0 < p.to_real) (f : lp E p) :
∥f∥ = (∑' i, ∥f i∥ ^ p.to_real) ^ (1/p.to_real) :=
begin
dsimp [norm],
rw ennreal.to_real_pos_iff at hp,
rw [dif_neg hp.1.ne', if_neg hp.2.ne],
end
lemma norm_rpow_eq_tsum (hp : 0 < p.to_real) (f : lp E p) :
∥f∥ ^ p.to_real = ∑' i, ∥f i∥ ^ p.to_real :=
begin
rw [norm_eq_tsum_rpow hp, ← real.rpow_mul],
{ field_simp [hp.ne'] },
apply tsum_nonneg,
intros i,
calc (0:ℝ) = 0 ^ p.to_real : by rw real.zero_rpow hp.ne'
... ≤ _ : real.rpow_le_rpow rfl.le (norm_nonneg (f i)) hp.le
end
lemma has_sum_norm (hp : 0 < p.to_real) (f : lp E p) :
has_sum (λ i, ∥f i∥ ^ p.to_real) (∥f∥ ^ p.to_real) :=
begin
rw norm_rpow_eq_tsum hp,
exact ((lp.mem_ℓp f).summable hp).has_sum
end
lemma norm_nonneg' (f : lp E p) : 0 ≤ ∥f∥ :=
begin
rcases p.trichotomy with rfl | rfl | hp,
{ simp [lp.norm_eq_card_dsupport f] },
{ cases is_empty_or_nonempty α with _i _i; resetI,
{ rw lp.norm_eq_csupr,
simp [real.csupr_empty] },
inhabit α,
exact (norm_nonneg (f default)).trans ((lp.is_lub_norm f).1 ⟨default, rfl⟩) },
{ rw lp.norm_eq_tsum_rpow hp f,
refine real.rpow_nonneg_of_nonneg (tsum_nonneg _) _,
exact λ i, real.rpow_nonneg_of_nonneg (norm_nonneg _) _ },
end
@[simp] lemma norm_zero : ∥(0 : lp E p)∥ = 0 :=
begin
rcases p.trichotomy with rfl | rfl | hp,
{ simp [lp.norm_eq_card_dsupport] },
{ simp [lp.norm_eq_csupr] },
{ rw lp.norm_eq_tsum_rpow hp,
have hp' : 1 / p.to_real ≠ 0 := one_div_ne_zero hp.ne',
simpa [real.zero_rpow hp.ne'] using real.zero_rpow hp' }
end
lemma norm_eq_zero_iff ⦃f : lp E p⦄ : ∥f∥ = 0 ↔ f = 0 :=
begin
classical,
refine ⟨λ h, _, by { rintros rfl, exact norm_zero }⟩,
rcases p.trichotomy with rfl | rfl | hp,
{ ext i,
have : {i : α | ¬f i = 0} = ∅ := by simpa [lp.norm_eq_card_dsupport f] using h,
have : (¬ (f i = 0)) = false := congr_fun this i,
tauto },
{ cases is_empty_or_nonempty α with _i _i; resetI,
{ simp },
have H : is_lub (set.range (λ i, ∥f i∥)) 0,
{ simpa [h] using lp.is_lub_norm f },
ext i,
have : ∥f i∥ = 0 := le_antisymm (H.1 ⟨i, rfl⟩) (norm_nonneg _),
simpa using this },
{ have hf : has_sum (λ (i : α), ∥f i∥ ^ p.to_real) 0,
{ have := lp.has_sum_norm hp f,
rwa [h, real.zero_rpow hp.ne'] at this },
have : ∀ i, 0 ≤ ∥f i∥ ^ p.to_real := λ i, real.rpow_nonneg_of_nonneg (norm_nonneg _) _,
rw has_sum_zero_iff_of_nonneg this at hf,
ext i,
have : f i = 0 ∧ p.to_real ≠ 0,
{ simpa [real.rpow_eq_zero_iff_of_nonneg (norm_nonneg (f i))] using congr_fun hf i },
exact this.1 },
end
lemma eq_zero_iff_coe_fn_eq_zero {f : lp E p} : f = 0 ↔ ⇑f = 0 :=
by rw [lp.ext_iff, coe_fn_zero]
@[simp] lemma norm_neg ⦃f : lp E p⦄ : ∥-f∥ = ∥f∥ :=
begin
rcases p.trichotomy with rfl | rfl | hp,
{ simp [lp.norm_eq_card_dsupport] },
{ cases is_empty_or_nonempty α; resetI,
{ simp [lp.eq_zero' f], },
apply (lp.is_lub_norm (-f)).unique,
simpa using lp.is_lub_norm f },
{ suffices : ∥-f∥ ^ p.to_real = ∥f∥ ^ p.to_real,
{ exact real.rpow_left_inj_on hp.ne' (norm_nonneg' _) (norm_nonneg' _) this },
apply (lp.has_sum_norm hp (-f)).unique,
simpa using lp.has_sum_norm hp f }
end
instance [hp : fact (1 ≤ p)] : normed_add_comm_group (lp E p) :=
normed_add_comm_group.of_core _
{ norm_eq_zero_iff := norm_eq_zero_iff,
triangle := λ f g, begin
unfreezingI { rcases p.dichotomy with rfl | hp' },
{ casesI is_empty_or_nonempty α,
{ simp [lp.eq_zero' f] },
refine (lp.is_lub_norm (f + g)).2 _,
rintros x ⟨i, rfl⟩,
refine le_trans _ (add_mem_upper_bounds_add (lp.is_lub_norm f).1 (lp.is_lub_norm g).1
⟨_, _, ⟨i, rfl⟩, ⟨i, rfl⟩, rfl⟩),
exact norm_add_le (f i) (g i) },
{ have hp'' : 0 < p.to_real := zero_lt_one.trans_le hp',
have hf₁ : ∀ i, 0 ≤ ∥f i∥ := λ i, norm_nonneg _,
have hg₁ : ∀ i, 0 ≤ ∥g i∥ := λ i, norm_nonneg _,
have hf₂ := lp.has_sum_norm hp'' f,
have hg₂ := lp.has_sum_norm hp'' g,
-- apply Minkowski's inequality
obtain ⟨C, hC₁, hC₂, hCfg⟩ :=
real.Lp_add_le_has_sum_of_nonneg hp' hf₁ hg₁ (norm_nonneg' _) (norm_nonneg' _) hf₂ hg₂,
refine le_trans _ hC₂,
rw ← real.rpow_le_rpow_iff (norm_nonneg' (f + g)) hC₁ hp'',
refine has_sum_le _ (lp.has_sum_norm hp'' (f + g)) hCfg,
intros i,
exact real.rpow_le_rpow (norm_nonneg _) (norm_add_le _ _) hp''.le },
end,
norm_neg := norm_neg }
-- TODO: define an `ennreal` version of `is_conjugate_exponent`, and then express this inequality
-- in a better version which also covers the case `p = 1, q = ∞`.
/-- Hölder inequality -/
protected lemma tsum_mul_le_mul_norm {p q : ℝ≥0∞}
(hpq : p.to_real.is_conjugate_exponent q.to_real) (f : lp E p) (g : lp E q) :
summable (λ i, ∥f i∥ * ∥g i∥) ∧ ∑' i, ∥f i∥ * ∥g i∥ ≤ ∥f∥ * ∥g∥ :=
begin
have hf₁ : ∀ i, 0 ≤ ∥f i∥ := λ i, norm_nonneg _,
have hg₁ : ∀ i, 0 ≤ ∥g i∥ := λ i, norm_nonneg _,
have hf₂ := lp.has_sum_norm hpq.pos f,
have hg₂ := lp.has_sum_norm hpq.symm.pos g,
obtain ⟨C, -, hC', hC⟩ :=
real.inner_le_Lp_mul_Lq_has_sum_of_nonneg hpq (norm_nonneg' _) (norm_nonneg' _) hf₁ hg₁ hf₂ hg₂,
rw ← hC.tsum_eq at hC',
exact ⟨hC.summable, hC'⟩
end
protected lemma summable_mul {p q : ℝ≥0∞}
(hpq : p.to_real.is_conjugate_exponent q.to_real) (f : lp E p) (g : lp E q) :
summable (λ i, ∥f i∥ * ∥g i∥) :=
(lp.tsum_mul_le_mul_norm hpq f g).1
protected lemma tsum_mul_le_mul_norm' {p q : ℝ≥0∞}
(hpq : p.to_real.is_conjugate_exponent q.to_real) (f : lp E p) (g : lp E q) :
∑' i, ∥f i∥ * ∥g i∥ ≤ ∥f∥ * ∥g∥ :=
(lp.tsum_mul_le_mul_norm hpq f g).2
section compare_pointwise
lemma norm_apply_le_norm (hp : p ≠ 0) (f : lp E p) (i : α) : ∥f i∥ ≤ ∥f∥ :=
begin
rcases eq_or_ne p ∞ with rfl | hp',
{ haveI : nonempty α := ⟨i⟩,
exact (is_lub_norm f).1 ⟨i, rfl⟩ },
have hp'' : 0 < p.to_real := ennreal.to_real_pos hp hp',
have : ∀ i, 0 ≤ ∥f i∥ ^ p.to_real,
{ exact λ i, real.rpow_nonneg_of_nonneg (norm_nonneg _) _ },
rw ← real.rpow_le_rpow_iff (norm_nonneg _) (norm_nonneg' _) hp'',
convert le_has_sum (has_sum_norm hp'' f) i (λ i hi, this i),
end
lemma sum_rpow_le_norm_rpow (hp : 0 < p.to_real) (f : lp E p) (s : finset α) :
∑ i in s, ∥f i∥ ^ p.to_real ≤ ∥f∥ ^ p.to_real :=
begin
rw lp.norm_rpow_eq_tsum hp f,
have : ∀ i, 0 ≤ ∥f i∥ ^ p.to_real,
{ exact λ i, real.rpow_nonneg_of_nonneg (norm_nonneg _) _ },
refine sum_le_tsum _ (λ i hi, this i) _,
exact (lp.mem_ℓp f).summable hp
end
lemma norm_le_of_forall_le' [nonempty α] {f : lp E ∞} (C : ℝ) (hCf : ∀ i, ∥f i∥ ≤ C) : ∥f∥ ≤ C :=
begin
refine (is_lub_norm f).2 _,
rintros - ⟨i, rfl⟩,
exact hCf i,
end
lemma norm_le_of_forall_le {f : lp E ∞} {C : ℝ} (hC : 0 ≤ C) (hCf : ∀ i, ∥f i∥ ≤ C) : ∥f∥ ≤ C :=
begin
casesI is_empty_or_nonempty α,
{ simpa [eq_zero' f] using hC, },
{ exact norm_le_of_forall_le' C hCf },
end
lemma norm_le_of_tsum_le (hp : 0 < p.to_real) {C : ℝ} (hC : 0 ≤ C) {f : lp E p}
(hf : ∑' i, ∥f i∥ ^ p.to_real ≤ C ^ p.to_real) :
∥f∥ ≤ C :=
begin
rw [← real.rpow_le_rpow_iff (norm_nonneg' _) hC hp, norm_rpow_eq_tsum hp],
exact hf,
end
lemma norm_le_of_forall_sum_le (hp : 0 < p.to_real) {C : ℝ} (hC : 0 ≤ C) {f : lp E p}
(hf : ∀ s : finset α, ∑ i in s, ∥f i∥ ^ p.to_real ≤ C ^ p.to_real) :
∥f∥ ≤ C :=
norm_le_of_tsum_le hp hC (tsum_le_of_sum_le ((lp.mem_ℓp f).summable hp) hf)
end compare_pointwise
section normed_space
variables {𝕜 : Type*} [normed_field 𝕜] [Π i, normed_space 𝕜 (E i)]
instance : module 𝕜 (pre_lp E) := pi.module α E 𝕜
lemma mem_lp_const_smul (c : 𝕜) (f : lp E p) : c • (f : pre_lp E) ∈ lp E p :=
(lp.mem_ℓp f).const_smul c
variables (E p 𝕜)
/-- The `𝕜`-submodule of elements of `Π i : α, E i` whose `lp` norm is finite. This is `lp E p`,
with extra structure. -/
def _root_.lp_submodule : submodule 𝕜 (pre_lp E) :=
{ smul_mem' := λ c f hf, by simpa using mem_lp_const_smul c ⟨f, hf⟩,
.. lp E p }
variables {E p 𝕜}
lemma coe_lp_submodule : (lp_submodule E p 𝕜).to_add_subgroup = lp E p := rfl
instance : module 𝕜 (lp E p) :=
{ .. (lp_submodule E p 𝕜).module }
@[simp] lemma coe_fn_smul (c : 𝕜) (f : lp E p) : ⇑(c • f) = c • f := rfl
lemma norm_const_smul (hp : p ≠ 0) {c : 𝕜} (f : lp E p) : ∥c • f∥ = ∥c∥ * ∥f∥ :=
begin
rcases p.trichotomy with rfl | rfl | hp,
{ exact absurd rfl hp },
{ cases is_empty_or_nonempty α; resetI,
{ simp [lp.eq_zero' f], },
apply (lp.is_lub_norm (c • f)).unique,
convert (lp.is_lub_norm f).mul_left (norm_nonneg c),
ext a,
simp [coe_fn_smul, norm_smul] },
{ suffices : ∥c • f∥ ^ p.to_real = (∥c∥ * ∥f∥) ^ p.to_real,
{ refine real.rpow_left_inj_on hp.ne' _ _ this,
{ exact norm_nonneg' _ },
{ exact mul_nonneg (norm_nonneg _) (norm_nonneg' _) } },
apply (lp.has_sum_norm hp (c • f)).unique,
convert (lp.has_sum_norm hp f).mul_left (∥c∥ ^ p.to_real),
{ simp [coe_fn_smul, norm_smul, real.mul_rpow (norm_nonneg c) (norm_nonneg _)] },
have hf : 0 ≤ ∥f∥ := lp.norm_nonneg' f,
simp [coe_fn_smul, norm_smul, real.mul_rpow (norm_nonneg c) hf] }
end
instance [fact (1 ≤ p)] : normed_space 𝕜 (lp E p) :=
{ norm_smul_le := λ c f, begin
have hp : 0 < p := ennreal.zero_lt_one.trans_le (fact.out _),
simp [norm_const_smul hp.ne']
end }
variables {𝕜' : Type*} [normed_field 𝕜']
instance [Π i, normed_space 𝕜' (E i)] [has_smul 𝕜' 𝕜] [Π i, is_scalar_tower 𝕜' 𝕜 (E i)] :
is_scalar_tower 𝕜' 𝕜 (lp E p) :=
begin
refine ⟨λ r c f, _⟩,
ext1,
exact (lp.coe_fn_smul _ _).trans (smul_assoc _ _ _)
end
end normed_space
section normed_star_group
variables [Π i, star_add_monoid (E i)] [Π i, normed_star_group (E i)]
lemma _root_.mem_ℓp.star_mem {f : Π i, E i}
(hf : mem_ℓp f p) : mem_ℓp (star f) p :=
begin
rcases p.trichotomy with rfl | rfl | hp,
{ apply mem_ℓp_zero,
simp [hf.finite_dsupport] },
{ apply mem_ℓp_infty,
simpa using hf.bdd_above },
{ apply mem_ℓp_gen,
simpa using hf.summable hp },
end
@[simp] lemma _root_.mem_ℓp.star_iff {f : Π i, E i} : mem_ℓp (star f) p ↔ mem_ℓp f p :=
⟨λ h, star_star f ▸ mem_ℓp.star_mem h ,mem_ℓp.star_mem⟩
instance : has_star (lp E p) :=
{ star := λ f, ⟨(star f : Π i, E i), f.property.star_mem⟩}
@[simp] lemma coe_fn_star (f : lp E p) : ⇑(star f) = star f := rfl
@[simp] protected theorem star_apply (f : lp E p) (i : α) : star f i = star (f i) := rfl
instance : has_involutive_star (lp E p) := { star_involutive := λ x, by {ext, simp} }
instance : star_add_monoid (lp E p) := { star_add := λ f g, ext $ star_add _ _ }
instance [hp : fact (1 ≤ p)] : normed_star_group (lp E p) :=
{ norm_star := λ f,
begin
unfreezingI { rcases p.trichotomy with rfl | rfl | h },
{ exfalso,
have := ennreal.to_real_mono ennreal.zero_ne_top hp.elim,
norm_num at this,},
{ simp only [lp.norm_eq_csupr, lp.star_apply, norm_star] },
{ simp only [lp.norm_eq_tsum_rpow h, lp.star_apply, norm_star] }
end }
variables {𝕜 : Type*} [has_star 𝕜] [normed_field 𝕜]
variables [Π i, normed_space 𝕜 (E i)] [Π i, star_module 𝕜 (E i)]
instance : star_module 𝕜 (lp E p) := { star_smul := λ r f, ext $ star_smul _ _ }
end normed_star_group
section non_unital_normed_ring
variables {I : Type*} {B : I → Type*} [Π i, non_unital_normed_ring (B i)]
lemma _root_.mem_ℓp.infty_mul {f g : Π i, B i} (hf : mem_ℓp f ∞) (hg : mem_ℓp g ∞) :
mem_ℓp (f * g) ∞ :=
begin
rw mem_ℓp_infty_iff,
obtain ⟨⟨Cf, hCf⟩, ⟨Cg, hCg⟩⟩ := ⟨hf.bdd_above, hg.bdd_above⟩,
refine ⟨Cf * Cg, _⟩,
rintros _ ⟨i, rfl⟩,
calc ∥(f * g) i∥ ≤ ∥f i∥ * ∥g i∥ : norm_mul_le (f i) (g i)
... ≤ Cf * Cg : mul_le_mul (hCf ⟨i, rfl⟩) (hCg ⟨i, rfl⟩) (norm_nonneg _)
((norm_nonneg _).trans (hCf ⟨i, rfl⟩))
end
instance : has_mul (lp B ∞) :=
{ mul := λ f g, ⟨(f * g : Π i, B i) , f.property.infty_mul g.property⟩}
@[simp] lemma infty_coe_fn_mul (f g : lp B ∞) : ⇑(f * g) = f * g := rfl
instance : non_unital_ring (lp B ∞) :=
function.injective.non_unital_ring lp.has_coe_to_fun.coe (subtype.coe_injective)
(lp.coe_fn_zero B ∞) lp.coe_fn_add infty_coe_fn_mul lp.coe_fn_neg lp.coe_fn_sub
(λ _ _, rfl) (λ _ _,rfl)
instance : non_unital_normed_ring (lp B ∞) :=
{ norm_mul := λ f g, lp.norm_le_of_forall_le (mul_nonneg (norm_nonneg f) (norm_nonneg g))
(λ i, calc ∥(f * g) i∥ ≤ ∥f i∥ * ∥g i∥ : norm_mul_le _ _
... ≤ ∥f∥ * ∥g∥
: mul_le_mul (lp.norm_apply_le_norm ennreal.top_ne_zero f i)
(lp.norm_apply_le_norm ennreal.top_ne_zero g i) (norm_nonneg _) (norm_nonneg _)),
.. lp.normed_add_comm_group }
-- we also want a `non_unital_normed_comm_ring` instance, but this has to wait for #13719
instance infty_is_scalar_tower {𝕜} [normed_field 𝕜] [Π i, normed_space 𝕜 (B i)]
[Π i, is_scalar_tower 𝕜 (B i) (B i)] :
is_scalar_tower 𝕜 (lp B ∞) (lp B ∞) :=
⟨λ r f g, lp.ext $ smul_assoc r ⇑f ⇑g⟩
instance infty_smul_comm_class {𝕜} [normed_field 𝕜] [Π i, normed_space 𝕜 (B i)]
[Π i, smul_comm_class 𝕜 (B i) (B i)] :
smul_comm_class 𝕜 (lp B ∞) (lp B ∞) :=
⟨λ r f g, lp.ext $ smul_comm r ⇑f ⇑g⟩
section star_ring
variables [Π i, star_ring (B i)] [Π i, normed_star_group (B i)]
instance infty_star_ring : star_ring (lp B ∞) :=
{ star_mul := λ f g, ext $ star_mul (_ : Π i, B i) _,
.. (show star_add_monoid (lp B ∞),
by { letI : Π i, star_add_monoid (B i) := λ i, infer_instance, apply_instance }) }
instance infty_cstar_ring [∀ i, cstar_ring (B i)] : cstar_ring (lp B ∞) :=
{ norm_star_mul_self := λ f,
begin
apply le_antisymm,
{ rw ←sq,
refine lp.norm_le_of_forall_le (sq_nonneg ∥ f ∥) (λ i, _),
simp only [lp.star_apply, cstar_ring.norm_star_mul_self, ←sq, infty_coe_fn_mul, pi.mul_apply],
refine sq_le_sq' _ (lp.norm_apply_le_norm ennreal.top_ne_zero _ _),
linarith [norm_nonneg (f i), norm_nonneg f] },
{ rw [←sq, ←real.le_sqrt (norm_nonneg _) (norm_nonneg _)],
refine lp.norm_le_of_forall_le (∥star f * f∥.sqrt_nonneg) (λ i, _),
rw [real.le_sqrt (norm_nonneg _) (norm_nonneg _), sq, ←cstar_ring.norm_star_mul_self],
exact lp.norm_apply_le_norm ennreal.top_ne_zero (star f * f) i, }
end }
end star_ring
end non_unital_normed_ring
section normed_ring
variables {I : Type*} {B : I → Type*} [Π i, normed_ring (B i)]
instance _root_.pre_lp.ring : ring (pre_lp B) := pi.ring
variables [Π i, norm_one_class (B i)]
lemma _root_.one_mem_ℓp_infty : mem_ℓp (1 : Π i, B i) ∞ :=
⟨1, by { rintros i ⟨i, rfl⟩, exact norm_one.le,}⟩
variables (B)
/-- The `𝕜`-subring of elements of `Π i : α, B i` whose `lp` norm is finite. This is `lp E ∞`,
with extra structure. -/
def _root_.lp_infty_subring : subring (pre_lp B) :=
{ carrier := {f | mem_ℓp f ∞},
one_mem' := one_mem_ℓp_infty,
mul_mem' := λ f g hf hg, hf.infty_mul hg,
.. lp B ∞ }
variables {B}
instance infty_ring : ring (lp B ∞) := (lp_infty_subring B).to_ring
lemma _root_.mem_ℓp.infty_pow {f : Π i, B i} (hf : mem_ℓp f ∞) (n : ℕ) : mem_ℓp (f ^ n) ∞ :=
(lp_infty_subring B).pow_mem hf n
lemma _root_.nat_cast_mem_ℓp_infty (n : ℕ) : mem_ℓp (n : Π i, B i) ∞ :=
nat_cast_mem (lp_infty_subring B) n
lemma _root_.int_cast_mem_ℓp_infty (z : ℤ) : mem_ℓp (z : Π i, B i) ∞ :=
coe_int_mem (lp_infty_subring B) z
@[simp] lemma infty_coe_fn_one : ⇑(1 : lp B ∞) = 1 := rfl
@[simp] lemma infty_coe_fn_pow (f : lp B ∞) (n : ℕ) : ⇑(f ^ n) = f ^ n := rfl
@[simp] lemma infty_coe_fn_nat_cast (n : ℕ) : ⇑(n : lp B ∞) = n := rfl
@[simp] lemma infty_coe_fn_int_cast (z : ℤ) : ⇑(z : lp B ∞) = z := rfl
instance [nonempty I] : norm_one_class (lp B ∞) :=
{ norm_one := by simp_rw [lp.norm_eq_csupr, infty_coe_fn_one, pi.one_apply, norm_one, csupr_const]}
instance infty_normed_ring : normed_ring (lp B ∞) :=
{ .. lp.infty_ring, .. lp.non_unital_normed_ring }
end normed_ring
section normed_comm_ring
variables {I : Type*} {B : I → Type*} [Π i, normed_comm_ring (B i)] [∀ i, norm_one_class (B i)]
instance infty_comm_ring : comm_ring (lp B ∞) :=
{ mul_comm := λ f g, by { ext, simp only [lp.infty_coe_fn_mul, pi.mul_apply, mul_comm] },
.. lp.infty_ring }
instance infty_normed_comm_ring : normed_comm_ring (lp B ∞) :=
{ .. lp.infty_comm_ring, .. lp.infty_normed_ring }
end normed_comm_ring
section algebra
variables {I : Type*} {𝕜 : Type*} {B : I → Type*}
variables [normed_field 𝕜] [Π i, normed_ring (B i)] [Π i, normed_algebra 𝕜 (B i)]
/-- A variant of `pi.algebra` that lean can't find otherwise. -/
instance _root_.pi.algebra_of_normed_algebra : algebra 𝕜 (Π i, B i) :=
@pi.algebra I 𝕜 B _ _ $ λ i, normed_algebra.to_algebra
instance _root_.pre_lp.algebra : algebra 𝕜 (pre_lp B) := _root_.pi.algebra_of_normed_algebra
variables [∀ i, norm_one_class (B i)]
lemma _root_.algebra_map_mem_ℓp_infty (k : 𝕜) : mem_ℓp (algebra_map 𝕜 (Π i, B i) k) ∞ :=
begin
rw algebra.algebra_map_eq_smul_one,
exact (one_mem_ℓp_infty.const_smul k : mem_ℓp (k • 1 : Π i, B i) ∞)
end
variables (𝕜 B)
/-- The `𝕜`-subalgebra of elements of `Π i : α, B i` whose `lp` norm is finite. This is `lp E ∞`,
with extra structure. -/
def _root_.lp_infty_subalgebra : subalgebra 𝕜 (pre_lp B) :=
{ carrier := {f | mem_ℓp f ∞},
algebra_map_mem' := algebra_map_mem_ℓp_infty,
.. lp_infty_subring B }
variables {𝕜 B}
instance infty_normed_algebra : normed_algebra 𝕜 (lp B ∞) :=
{ ..(lp_infty_subalgebra 𝕜 B).algebra,
..(lp.normed_space : normed_space 𝕜 (lp B ∞)) }
end algebra
section single
variables {𝕜 : Type*} [normed_field 𝕜] [Π i, normed_space 𝕜 (E i)]
variables [decidable_eq α]
/-- The element of `lp E p` which is `a : E i` at the index `i`, and zero elsewhere. -/
protected def single (p) (i : α) (a : E i) : lp E p :=
⟨ λ j, if h : j = i then eq.rec a h.symm else 0,
begin
refine (mem_ℓp_zero _).of_exponent_ge (zero_le p),
refine (set.finite_singleton i).subset _,
intros j,
simp only [forall_exists_index, set.mem_singleton_iff, ne.def, dite_eq_right_iff,
set.mem_set_of_eq, not_forall],
rintros rfl,
simp,
end ⟩
protected lemma single_apply (p) (i : α) (a : E i) (j : α) :
lp.single p i a j = if h : j = i then eq.rec a h.symm else 0 :=
rfl
protected lemma single_apply_self (p) (i : α) (a : E i) :
lp.single p i a i = a :=
by rw [lp.single_apply, dif_pos rfl]
protected lemma single_apply_ne (p) (i : α) (a : E i) {j : α} (hij : j ≠ i) :
lp.single p i a j = 0 :=
by rw [lp.single_apply, dif_neg hij]
@[simp] protected lemma single_neg (p) (i : α) (a : E i) :
lp.single p i (- a) = - lp.single p i a :=
begin
ext j,
by_cases hi : j = i,
{ subst hi,
simp [lp.single_apply_self] },
{ simp [lp.single_apply_ne p i _ hi] }
end
@[simp] protected lemma single_smul (p) (i : α) (a : E i) (c : 𝕜) :
lp.single p i (c • a) = c • lp.single p i a :=
begin
ext j,
by_cases hi : j = i,
{ subst hi,
simp [lp.single_apply_self] },
{ simp [lp.single_apply_ne p i _ hi] }
end
protected lemma norm_sum_single (hp : 0 < p.to_real) (f : Π i, E i) (s : finset α) :
∥∑ i in s, lp.single p i (f i)∥ ^ p.to_real = ∑ i in s, ∥f i∥ ^ p.to_real :=
begin
refine (has_sum_norm hp (∑ i in s, lp.single p i (f i))).unique _,
simp only [lp.single_apply, coe_fn_sum, finset.sum_apply, finset.sum_dite_eq],
have h : ∀ i ∉ s, ∥ite (i ∈ s) (f i) 0∥ ^ p.to_real = 0,
{ intros i hi,
simp [if_neg hi, real.zero_rpow hp.ne'], },
have h' : ∀ i ∈ s, ∥f i∥ ^ p.to_real = ∥ite (i ∈ s) (f i) 0∥ ^ p.to_real,
{ intros i hi,
rw if_pos hi },
simpa [finset.sum_congr rfl h'] using has_sum_sum_of_ne_finset_zero h,
end
protected lemma norm_single (hp : 0 < p.to_real) (f : Π i, E i) (i : α) :
∥lp.single p i (f i)∥ = ∥f i∥ :=
begin
refine real.rpow_left_inj_on hp.ne' (norm_nonneg' _) (norm_nonneg _) _,
simpa using lp.norm_sum_single hp f {i},
end
protected lemma norm_sub_norm_compl_sub_single (hp : 0 < p.to_real) (f : lp E p) (s : finset α) :
∥f∥ ^ p.to_real - ∥f - ∑ i in s, lp.single p i (f i)∥ ^ p.to_real = ∑ i in s, ∥f i∥ ^ p.to_real :=
begin
refine ((has_sum_norm hp f).sub (has_sum_norm hp (f - ∑ i in s, lp.single p i (f i)))).unique _,
let F : α → ℝ := λ i, ∥f i∥ ^ p.to_real - ∥(f - ∑ i in s, lp.single p i (f i)) i∥ ^ p.to_real,
have hF : ∀ i ∉ s, F i = 0,
{ intros i hi,
suffices : ∥f i∥ ^ p.to_real - ∥f i - ite (i ∈ s) (f i) 0∥ ^ p.to_real = 0,
{ simpa [F, coe_fn_sum, lp.single_apply] using this, },
simp [if_neg hi] },
have hF' : ∀ i ∈ s, F i = ∥f i∥ ^ p.to_real,
{ intros i hi,
simp [F, coe_fn_sum, lp.single_apply, if_pos hi, real.zero_rpow hp.ne'] },
have : has_sum F (∑ i in s, F i) := has_sum_sum_of_ne_finset_zero hF,
rwa [finset.sum_congr rfl hF'] at this,
end
protected lemma norm_compl_sum_single (hp : 0 < p.to_real) (f : lp E p) (s : finset α) :
∥f - ∑ i in s, lp.single p i (f i)∥ ^ p.to_real = ∥f∥ ^ p.to_real - ∑ i in s, ∥f i∥ ^ p.to_real :=
by linarith [lp.norm_sub_norm_compl_sub_single hp f s]
/-- The canonical finitely-supported approximations to an element `f` of `lp` converge to it, in the
`lp` topology. -/
protected lemma has_sum_single [fact (1 ≤ p)] (hp : p ≠ ⊤) (f : lp E p) :
has_sum (λ i : α, lp.single p i (f i : E i)) f :=
begin
have hp₀ : 0 < p := ennreal.zero_lt_one.trans_le (fact.out _),
have hp' : 0 < p.to_real := ennreal.to_real_pos hp₀.ne' hp,
have := lp.has_sum_norm hp' f,
dsimp [has_sum] at this ⊢,
rw metric.tendsto_nhds at this ⊢,
intros ε hε,
refine (this _ (real.rpow_pos_of_pos hε p.to_real)).mono _,
intros s hs,
rw ← real.rpow_lt_rpow_iff dist_nonneg (le_of_lt hε) hp',
rw dist_comm at hs,
simp only [dist_eq_norm, real.norm_eq_abs] at hs ⊢,
have H : ∥∑ i in s, lp.single p i (f i : E i) - f∥ ^ p.to_real
= ∥f∥ ^ p.to_real - ∑ i in s, ∥f i∥ ^ p.to_real,
{ simpa using lp.norm_compl_sum_single hp' (-f) s },
rw ← H at hs,
have : |∥∑ i in s, lp.single p i (f i : E i) - f∥ ^ p.to_real|
= ∥∑ i in s, lp.single p i (f i : E i) - f∥ ^ p.to_real,
{ simp [real.abs_rpow_of_nonneg (norm_nonneg _)] },
linarith
end
end single
section topology
open filter
open_locale topological_space uniformity
/-- The coercion from `lp E p` to `Π i, E i` is uniformly continuous. -/
lemma uniform_continuous_coe [_i : fact (1 ≤ p)] : uniform_continuous (coe : lp E p → Π i, E i) :=
begin
have hp : p ≠ 0 := (ennreal.zero_lt_one.trans_le _i.elim).ne',
rw uniform_continuous_pi,
intros i,
rw normed_add_comm_group.uniformity_basis_dist.uniform_continuous_iff
normed_add_comm_group.uniformity_basis_dist,
intros ε hε,
refine ⟨ε, hε, _⟩,
rintros f g (hfg : ∥f - g∥ < ε),
have : ∥f i - g i∥ ≤ ∥f - g∥ := norm_apply_le_norm hp (f - g) i,
exact this.trans_lt hfg,
end
variables {ι : Type*} {l : filter ι} [filter.ne_bot l]
lemma norm_apply_le_of_tendsto {C : ℝ} {F : ι → lp E ∞} (hCF : ∀ᶠ k in l, ∥F k∥ ≤ C)
{f : Π a, E a} (hf : tendsto (id (λ i, F i) : ι → Π a, E a) l (𝓝 f)) (a : α) :
∥f a∥ ≤ C :=
begin
have : tendsto (λ k, ∥F k a∥) l (𝓝 ∥f a∥) :=
(tendsto.comp (continuous_apply a).continuous_at hf).norm,
refine le_of_tendsto this (hCF.mono _),
intros k hCFk,
exact (norm_apply_le_norm ennreal.top_ne_zero (F k) a).trans hCFk,
end
variables [_i : fact (1 ≤ p)]
include _i
lemma sum_rpow_le_of_tendsto (hp : p ≠ ∞) {C : ℝ} {F : ι → lp E p} (hCF : ∀ᶠ k in l, ∥F k∥ ≤ C)
{f : Π a, E a} (hf : tendsto (id (λ i, F i) : ι → Π a, E a) l (𝓝 f)) (s : finset α) :
∑ (i : α) in s, ∥f i∥ ^ p.to_real ≤ C ^ p.to_real :=
begin
have hp' : p ≠ 0 := (ennreal.zero_lt_one.trans_le _i.elim).ne',
have hp'' : 0 < p.to_real := ennreal.to_real_pos hp' hp,
let G : (Π a, E a) → ℝ := λ f, ∑ a in s, ∥f a∥ ^ p.to_real,
have hG : continuous G,
{ refine continuous_finset_sum s _,
intros a ha,
have : continuous (λ f : Π a, E a, f a):= continuous_apply a,
exact this.norm.rpow_const (λ _, or.inr hp''.le) },
refine le_of_tendsto (hG.continuous_at.tendsto.comp hf) _,
refine hCF.mono _,
intros k hCFk,
refine (lp.sum_rpow_le_norm_rpow hp'' (F k) s).trans _,
exact real.rpow_le_rpow (norm_nonneg _) hCFk hp''.le,
end
/-- "Semicontinuity of the `lp` norm": If all sufficiently large elements of a sequence in `lp E p`
have `lp` norm `≤ C`, then the pointwise limit, if it exists, also has `lp` norm `≤ C`. -/
lemma norm_le_of_tendsto {C : ℝ} {F : ι → lp E p} (hCF : ∀ᶠ k in l, ∥F k∥ ≤ C) {f : lp E p}
(hf : tendsto (id (λ i, F i) : ι → Π a, E a) l (𝓝 f)) :
∥f∥ ≤ C :=
begin
obtain ⟨i, hi⟩ := hCF.exists,
have hC : 0 ≤ C := (norm_nonneg _).trans hi,
unfreezingI { rcases eq_top_or_lt_top p with rfl | hp },
{ apply norm_le_of_forall_le hC,
exact norm_apply_le_of_tendsto hCF hf, },
{ have : 0 < p := ennreal.zero_lt_one.trans_le _i.elim,
have hp' : 0 < p.to_real := ennreal.to_real_pos this.ne' hp.ne,
apply norm_le_of_forall_sum_le hp' hC,
exact sum_rpow_le_of_tendsto hp.ne hCF hf, }
end
/-- If `f` is the pointwise limit of a bounded sequence in `lp E p`, then `f` is in `lp E p`. -/
lemma mem_ℓp_of_tendsto {F : ι → lp E p} (hF : metric.bounded (set.range F)) {f : Π a, E a}
(hf : tendsto (id (λ i, F i) : ι → Π a, E a) l (𝓝 f)) :
mem_ℓp f p :=
begin
obtain ⟨C, hC, hCF'⟩ := hF.exists_pos_norm_le,
have hCF : ∀ k, ∥F k∥ ≤ C := λ k, hCF' _ ⟨k, rfl⟩,
unfreezingI { rcases eq_top_or_lt_top p with rfl | hp },
{ apply mem_ℓp_infty,
use C,
rintros _ ⟨a, rfl⟩,
refine norm_apply_le_of_tendsto (eventually_of_forall hCF) hf a, },
{ apply mem_ℓp_gen',
exact sum_rpow_le_of_tendsto hp.ne (eventually_of_forall hCF) hf },
end
/-- If a sequence is Cauchy in the `lp E p` topology and pointwise convergent to a element `f` of
`lp E p`, then it converges to `f` in the `lp E p` topology. -/
lemma tendsto_lp_of_tendsto_pi {F : ℕ → lp E p} (hF : cauchy_seq F) {f : lp E p}
(hf : tendsto (id (λ i, F i) : ℕ → Π a, E a) at_top (𝓝 f)) :
tendsto F at_top (𝓝 f) :=
begin
rw metric.nhds_basis_closed_ball.tendsto_right_iff,
intros ε hε,
have hε' : {p : (lp E p) × (lp E p) | ∥p.1 - p.2∥ < ε} ∈ 𝓤 (lp E p),
{ exact normed_add_comm_group.uniformity_basis_dist.mem_of_mem hε },
refine (hF.eventually_eventually hε').mono _,
rintros n (hn : ∀ᶠ l in at_top, ∥(λ f, F n - f) (F l)∥ < ε),
refine norm_le_of_tendsto (hn.mono (λ k hk, hk.le)) _,
rw tendsto_pi_nhds,
intros a,
exact (hf.apply a).const_sub (F n a),
end
variables [Π a, complete_space (E a)]
instance : complete_space (lp E p) :=
metric.complete_of_cauchy_seq_tendsto
begin
intros F hF,
-- A Cauchy sequence in `lp E p` is pointwise convergent; let `f` be the pointwise limit.
obtain ⟨f, hf⟩ := cauchy_seq_tendsto_of_complete (uniform_continuous_coe.comp_cauchy_seq hF),
-- Since the Cauchy sequence is bounded, its pointwise limit `f` is in `lp E p`.
have hf' : mem_ℓp f p := mem_ℓp_of_tendsto hF.bounded_range hf,
-- And therefore `f` is its limit in the `lp E p` topology as well as pointwise.
exact ⟨⟨f, hf'⟩, tendsto_lp_of_tendsto_pi hF hf⟩
end
end topology
end lp
|
02cf3700ac0b3b3a5c235cac5847123d1ad44657 | c678b448c073e84fd00f1777ac278c36a7bb9a83 | /data/containers/rbtree/delete.lean | 2fd30f152c0c4aeacca0a1e6800e415710498cfe | [] | no_license | GaloisInc/lean-containers | 9d714d9a355381d66f4bf9b686589a85ce7afcc4 | c3359c6e439a611926168e2c86496d0d90a67f9b | refs/heads/master | 1,587,884,399,036 | 1,548,187,422,000 | 1,548,187,422,000 | 173,382,186 | 0 | 0 | null | 1,551,483,637,000 | 1,551,483,637,000 | null | UTF-8 | Lean | false | false | 26,876 | lean | import .basic
namespace data.containers
namespace rbtree
namespace delete
lemma cancel_plus (k x y:ℕ) :
x + k = y + k →
x = y :=
begin
induction k; simp
end.
open color
open rbtree
universe u
inductive delete_result (E:Type u)
-- The deleted node and a tree result with black-height equal to the original tree.
| tree_result : E -> rbtree E -> delete_result
-- The deleted node and a black-colored tree result with black-height one less than
-- the original tree. The resulting tree is always colored black.
| extra_black_result : E -> rbtree E -> delete_result
-- The element to delete wasn't in the tree at all. Tree is unchanged.
| unchanged : delete_result
.
namespace delete_result
open delete_result
variable {E:Type u}.
variable [has_preordering E].
@[simp] def has_black_height : delete_result E → ℕ → Prop
| (tree_result _ t) := λ n, t.black_height = n
| (extra_black_result _ t) := λ n, t.black_height + 1 = n
| (unchanged _) := λ_, true
.
@[simp] def is_black : delete_result E → Prop
| (tree_result _ t) := t.tree_color = black
| (extra_black_result _ _) := true
| (unchanged _) := true
.
@[simp] def well_formed : delete_result E → Prop
| (extra_black_result _ t) := t.well_formed ∧ t.tree_color = black
| (tree_result _ t) := t.well_formed
| (unchanged _) := true
.
@[simp] def is_ordered : delete_result E → Prop
| (extra_black_result _ t) := t.is_ordered
| (tree_result _ t) := t.is_ordered
| (unchanged _) := true
.
@[simp] def all_lt : delete_result E → E → Prop
| (tree_result _ t) x := t.all_lt x
| (extra_black_result _ t) x := t.all_lt x
| (unchanged _ ) x := true
.
@[simp] def all_gt : delete_result E → E → Prop
| (tree_result _ t) x := t.all_gt x
| (extra_black_result _ t) x := t.all_gt x
| (unchanged _ ) x := true
.
@[simp] def mergeL : color -> delete_result E -> E -> rbtree E -> delete_result E
| _ (unchanged _) _ _
:= unchanged E
-- NB, we assume subtrees are properly colored...
| cl (tree_result q l) x r
:= tree_result q (bin cl l x r)
| _ (extra_black_result q l) x empty
:= unchanged E -- impossible!
| red (extra_black_result q l) x (bin _ a y b) -- must be black
:= match a with
| bin red c z d
:= tree_result q (bin red (bin black l x c) z (bin black d y b))
| _ := tree_result q (bin black (bin red l x a) y b)
end
| black (extra_black_result q l) x (bin black a y b)
:= match a with
| bin red c z d
:= tree_result q (bin black (bin black l x c) z (bin black d y b))
| _ := extra_black_result q (bin black (bin red l x a) y b)
end
| black (extra_black_result q l) x (bin red a y b)
:= match a with
| bin black c z d :=
match c with
| bin red f w g :=
tree_result q (bin black (bin red (bin black l x f) w (bin black g z d)) y b)
| _ :=
tree_result q (bin black (bin black (bin red l x c) z d) y b)
end
| _ := unchanged E -- impossible!
end
.
-- NB! the arguments are in a strange order. This makes the equation compiler
-- produce code that is easier to reason about
@[simp] def mergeR : color -> delete_result E -> rbtree E -> E -> delete_result E
| _ (unchanged _) _ _
:= unchanged E
-- NB, we assume subtrees are properly colored...
| cl (tree_result q r) l x
:= tree_result q (bin cl l x r)
| _ (extra_black_result q r) empty x
:= unchanged E -- impossible!
| red (extra_black_result q r) (bin _ a y b) x -- tree must be black
:= match b with
| bin red c z d
:= tree_result q (bin red (bin black a y c) z (bin black d x r))
| _ := tree_result q (bin black a y (bin red b x r))
end
| black (extra_black_result q r) (bin black a y b) x
:= match b with
| bin red c z d
:= tree_result q (bin black (bin black a y c) z (bin black d x r))
| _ := extra_black_result q (bin black a y (bin red b x r))
end
| black (extra_black_result q r) (bin red a y b) x
:= match b with
| bin black c z d :=
match d with
| bin red f w g :=
tree_result q (bin black a y (bin red (bin black c z f) w (bin black g x r)))
| _ := tree_result q (bin black a y (bin black c z (bin red d x r)))
end
| _ := unchanged E -- impossible!
end
.
attribute [simp] rbtree.black_height rbtree.well_formed rbtree.tree_color rbtree.is_ordered
rbtree.all_lt rbtree.all_gt.
lemma mergeL_is_ordered (co:color) (l:delete_result E) (x:E) (r:rbtree E) :
l.all_lt x →
r.all_gt x →
l.is_ordered →
r.is_ordered →
(mergeL co l x r).is_ordered :=
begin
cases l with q t q t,
case unchanged { cases r; cases co; simp },
case tree_result { cases r; cases co; simp; cc },
case extra_black_result {
cases r,
case empty { cases co; simp },
case bin : co' a y b {
cases co,
case black {
cases co',
case black { cases a with co_a; simp, cc, cases co_a; simp; cc },
case red {
cases a with co_a c z d; simp, cases co_a; simp, cases c; simp, cc, cases c_a; simp; try {cc},
intros, repeat{ split }; try {cc},
apply (has_preordering.lt_of_lt_of_lt _ z _); assumption
}
},
case red { cases a with co_a; simp, cc, cases co_a; simp; cc }
}
}
end.
lemma mergeL_preserves_lt (co:color) (l:delete_result E) (x:E) (r:rbtree E) (q:E) :
l.all_lt q →
has_preordering.cmp x q = ordering.lt →
r.all_lt q →
r.is_ordered →
(mergeL co l x r).all_lt q :=
begin
cases l,
case unchanged{ cases r; cases co; simp },
case tree_result : w t { cases r; cases co; simp; cc },
case extra_black_result : w t {
cases r,
case empty { cases co; simp },
case bin : co' a y b {
cases co,
case black {
cases co'; cases a with co_a c z d; simp; try{cc}; cases co_a; simp; try{cc},
{ cases c with co_c, {simp, cc}, cases co_c; simp; cc },
{ intros; repeat{split}; try{cc}, apply (has_preordering.lt_of_lt_of_lt _ y _); assumption }
},
case red {
cases co'; cases a with co_a c z d; simp; try{cc},
cases co_a; simp; try{cc},
{ intros; repeat{split}; try{cc}, apply (has_preordering.lt_of_lt_of_lt _ y _); assumption },
{ cases co_a; simp; intros; repeat{split}; try{cc},
apply (has_preordering.lt_of_lt_of_lt _ y _); assumption },
}
}
},
end.
lemma mergeL_preserves_gt (co:color) (l:delete_result E) (x:E) (r:rbtree E) (q:E) :
l.all_gt q →
has_preordering.cmp q x = ordering.lt →
r.all_gt q →
(mergeL co l x r).all_gt q :=
begin
cases l,
case unchanged{ cases r; cases co; simp },
case tree_result : w t { cases r; cases co; simp; cc },
case extra_black_result : w t {
cases r,
case empty { cases co; simp },
case bin : co' a y b {
cases co,
case black {
cases co'; cases a with co_a c z d; simp; try{cc}; cases co_a; simp; try{cc},
{ cases c with co_c, {simp, cc}, cases co_c; simp; cc }
},
case red { cases co'; cases a with co_a c z d; simp; try{cc}; cases co_a; simp; try{cc} }
}
}
end.
lemma mergeR_preserves_lt (co:color) (l:rbtree E) (x:E) (r:delete_result E) (q:E) :
l.all_lt q →
has_preordering.cmp x q = ordering.lt →
r.all_lt q →
(mergeR co r l x).all_lt q :=
begin
cases r,
case unchanged { cases l; cases co; simp },
case tree_result : w t { cases l; cases co; simp; cc },
case extra_black_result : w t {
cases l,
case empty { cases co; simp },
case bin : co' a y b {
cases co,
case black {
simp, cases co'; cases b with co'' c z d ; simp; try {cc},
{ cases co'', { simp }, cases d with co_d ; simp, cc, cases co_d; simp; cc },
{ cases co'', { simp, cc }, cases d with co_d; {simp, cc} }
},
case red { simp, cases co'; cases b with co'' c z d; simp; try{cc},
{ cases co'', { simp, cc }, cases d; simp; cc },
{ cases co'', { simp, cc }, cases d; simp; cc }
}
}
}
end.
lemma mergeR_preserves_gt (co:color) (l:rbtree E) (x:E) (r:delete_result E) (q:E) :
l.is_ordered →
l.all_gt q →
has_preordering.cmp q x = ordering.lt →
r.all_gt q →
(mergeR co r l x).all_gt q :=
begin
cases r,
case unchanged { cases l; cases co; simp },
case tree_result : w t { cases l; cases co; simp; cc },
case extra_black_result : w t {
cases l,
case empty { cases co; simp },
case bin : co' a y b {
cases co,
case black {
simp, cases co'; cases b with co'' c z d ; simp; try {cc},
{ cases co'', { simp }, cases d with co_d ; simp, cc, cases co_d; simp; cc },
{ cases co'', { simp, intros; repeat {split}; try{cc},
apply (has_preordering.lt_of_lt_of_lt _ y _); assumption },
cases d with co_d; {simp, cc}
}
},
case red { simp, cases co'; cases b with co'' c z d; simp; try{cc},
{ cases co'', { simp, intros; repeat{split}; try{cc},
apply (has_preordering.lt_of_lt_of_lt _ y _); assumption },
cases d; simp; cc
},
{ cases co'', { simp, intros; repeat{split}; try{cc},
apply (has_preordering.lt_of_lt_of_lt _ y _); assumption },
cases d; simp; cc
}
}
}
},
end.
lemma mergeR_is_ordered (co:color) (l:rbtree E) (x:E) (r:delete_result E) :
l.all_lt x →
r.all_gt x →
l.is_ordered →
r.is_ordered →
(mergeR co r l x).is_ordered :=
begin
cases r with q t q t,
case unchanged { cases l; cases co; simp },
case tree_result { cases l; cases co; simp; cc },
case extra_black_result {
cases l,
case empty { cases co; simp },
case bin : co' a y b {
cases co,
case black {
cases co',
case black { cases b with co_b; simp, cc, cases co_b; simp; cc },
case red {
cases b with co_b c z d; simp, cases co_b; simp, cases d; simp, cc,
cases d_a; simp; try { cc },
intros; repeat { split }; try { cc },
apply (has_preordering.lt_of_lt_of_lt _ z _); assumption
}
},
case red { cases b with co_b; simp, cc, cases co_b; simp; cc }
}
},
end.
lemma mergeL_black_bh (l:delete_result E) (x:E) (r:rbtree E) :
l.has_black_height (r.black_height) →
(mergeL black l x r).has_black_height (r.black_height + 1) :=
begin
cases l,
case unchanged { simp },
case tree_result : q t {
cases t,
case empty { simp, intro H, rw <- H },
case bin { simp, intro H, rw <- H, simp }
},
case extra_black_result : q t {
cases r,
case empty { simp },
case bin : cl a y b {
cases cl,
case red {
cases a; simp,
case bin : cl c z d {
cases cl; simp, cases c with cl'; simp,
{ intro H, rewrite H },
{ cases cl'; simp, intro H, rewrite H }
},
},
case black {
cases a with cl; simp,
{ intro H, change (black_height t + 1 + 1 = 2), rewrite H },
{ cases cl; simp, intro H, change (t.black_height + 1 + 1 = black_height a_a + 3), rewrite H }
}
}
},
end.
lemma mergeL_red_bh (l:delete_result E) (x:E) (r:rbtree E) :
l.has_black_height (r.black_height) →
(mergeL red l x r).has_black_height (r.black_height) :=
begin
cases l,
case unchanged { simp },
case tree_result : q t {
cases t,
case empty { simp },
case bin : c a y b { cases c; simp }
},
case extra_black_result : q t {
cases t,
case empty {
simp, cases r,
case empty { simp },
case bin : c' c z d {
simp, cases c,
case empty { simp },
case bin : c'' _ _ _ { cases c''; simp }
}
},
case bin : c a y b {
cases r,
case empty { simp },
case bin : c' c z d { cases c with cl; simp, cases cl; simp }
}
},
end.
lemma mergeR_black_bh (l:rbtree E) (x:E) (r:delete_result E) :
r.has_black_height (l.black_height) →
(mergeR black r l x).has_black_height (l.black_height + 1) :=
begin
cases r,
case unchanged { simp },
case tree_result : q t { cases t; simp },
case extra_black_result : q t {
simp, intro Ht,
cases l,
case empty { simp },
case bin : co a y b {
cases co,
case red {
simp, cases b,
case empty { simp },
case bin : co' c z d {
cases co'; simp,
cases d,
case empty { simp },
case bin : co'' f w g { cases co''; simp }
}
},
case black {
simp, cases b,
case empty{ simp },
case bin : co' c z d { cases co'; simp }
}
}
},
end.
lemma mergeR_red_bh (l:rbtree E) (x:E) (r:delete_result E) :
l.tree_color = black →
r.has_black_height (l.black_height) →
(mergeR red r l x).has_black_height (l.black_height) :=
begin
cases r,
case unchanged { simp },
case tree_result { simp },
case extra_black_result : q t {
cases l,
case empty { simp },
case bin : co a y b {
simp, cases co; simp; cases b,
case empty { simp },
case bin : co' c z d { cases co'; simp }
}
}
end.
lemma mergeR_red_wf (l:rbtree E) (x:E) (r:delete_result E) :
l.well_formed →
r.well_formed →
l.tree_color = black →
r.is_black →
r.has_black_height (l.black_height) →
(mergeR red r l x).well_formed :=
begin
cases r,
case unchanged{ simp },
case tree_result : q t { simp, cc },
case extra_black_result : q t {
cases l,
case empty { simp },
case bin : cl a y b {
cases cl,
case black {
cases b,
case empty { simp, cc },
case bin : cl' c z d { cases cl'; simp; cc }
},
case red { simp }
}
}
end.
lemma mergeR_black_wf (l:rbtree E) (x:E) (r:delete_result E) :
l.well_formed →
r.well_formed →
r.has_black_height (l.black_height) →
(mergeR black r l x).well_formed :=
begin
cases r,
case unchanged{ simp },
case tree_result { simp, cc },
case extra_black_result : q t {
cases l,
case empty { simp },
case bin : cl a y b {
cases cl,
case black {
simp, cases b,
case empty { simp, cc },
case bin : cl' c z d {
cases cl',
case black { simp, cc },
case red { simp, cc }
}
},
case red {
simp, cases b,
case empty { simp },
case bin : cl' c z d {
cases cl',
case red { simp },
case black {
simp,
cases d,
case empty { simp, intros,
have Ht : t.black_height = 0, { apply (cancel_plus 1), simp,
rewrite a_8, rewrite a_5, rewrite a_4 }, cc
},
case bin : cl'' f w g {
cases cl'',
case black { simp, intros, repeat {split}; try {cc},
rewrite <- a_7, rewrite a_8 at a_11, apply (cancel_plus 1), cc },
case red { simp, intros, repeat {split}; try {cc},
rewrite <- a_8, rewrite <- a_9, rewrite a_10 at a_13,
apply (cancel_plus 1), cc
}
}
}
}
}
}
}
end.
lemma mergeL_black_wf (l:delete_result E) (x:E) (r:rbtree E) :
l.well_formed →
r.well_formed →
l.has_black_height (r.black_height) →
(mergeL black l x r).well_formed :=
begin
cases l,
case unchanged { intros, trivial },
case tree_result : q t { simp, cc },
case extra_black_result : q t {
cases r,
case empty { simp },
case bin : cl a y b {
cases cl,
case black {
simp,
cases a,
case empty { simp, intros, cc },
case bin : cl' c z d {
cases cl',
case red { simp, intros, cc },
case black { simp, intros, cc }
}
},
case red {
simp,
cases a,
case empty { simp },
case bin : cl' c z d {
simp, intros, subst cl', simp,
cases c,
case empty {
simp at *,
have Ht : t.black_height = 0, { apply (cancel_plus 1), assumption }, cc
},
case bin : cl'' f w g {
cases cl'',
case black {
simp at *,
have Ht : t.black_height = f.black_height + 1, { apply (cancel_plus 1), assumption }, cc
},
case red { simp at *, cc }
}
}
},
}
},
end.
lemma mergeL_red_wf (l:delete_result E) (x:E) (r:rbtree E) :
l.well_formed →
r.well_formed →
l.has_black_height (r.black_height) →
l.is_black →
r.tree_color = black →
(mergeL red l x r).well_formed :=
begin
cases l,
case unchanged { intros; trivial },
case tree_result : q t {
cases t,
case empty { simp, cc },
case bin : c a y b { cases c; simp; cc }
},
case extra_black_result : q t {
cases r; simp,
case bin : c a y b {
cases c,
case red {
unfold rbtree.tree_color rbtree.well_formed, intros,
cases a,
case bin : c' c z d { cases c'; simp; cc },
case empty { simp; cc }
},
case black {
cases a,
case empty {
simp, intros,
have Ht : t.black_height = 0, { apply (cancel_plus 1), assumption }, cc
},
case bin : c' c z d {
cases c'; simp; intros,
{ cc },
{ have Htc : t.black_height = c.black_height + 1, { apply (cancel_plus 1), assumption }, cc }
}
}
}
},
end.
lemma mergeL_is_black (l:delete_result E) (x:E) (r:rbtree E) :
(mergeL black l x r).is_black :=
begin
cases l,
case tree_result : q t { simp },
case extra_black_result : q t {
cases r,
case empty{ simp },
case bin : cl a y b {
cases cl,
case black {
cases a,
case empty { simp },
case bin : cl' _ _ _ { cases cl'; simp }
},
case red {
cases a,
case empty { simp },
case bin : cl' f w g { cases cl'; simp, cases f, simp, cases f_a; simp }
}
}
},
case unchanged : { simp }
end.
lemma mergeR_is_black (l:rbtree E) (x:E) (r:delete_result E) :
(mergeR black r l x).is_black :=
begin
cases r,
case unchanged { simp },
case tree_result : q t { simp },
case extra_black_result : q t {
cases l,
case empty{ simp },
case bin : cl a y b {
cases cl,
case black {
cases b,
case empty { simp },
case bin : co_b c z d { cases co_b; simp }
},
case red {
cases b,
case empty { simp },
case bin : co_b c z d { cases co_b; simp,
cases d,
case empty{ simp },
case bin : d_a { cases d_a; simp }
}
}
}
}
end.
@[simp] def delete_min : rbtree E -> delete_result E
| empty := unchanged E
| (bin red empty x r) := tree_result x r
| (bin black empty x (bin red a y b)) := tree_result x (bin black a y b)
| (bin black empty x r) := extra_black_result x r
| (bin c l x r) := mergeL c (delete_min l) x r
.
lemma delete_min_bh (x:rbtree E) :
x.well_formed →
(delete_min x).has_black_height (x.black_height) :=
begin
induction x,
case empty { intros, simp },
case bin : cl l x r IHl IHr {
cases l,
case empty {
cases cl; simp; try { cc },
cases r,
case empty { simp },
case bin : cl a y b {
cases cl; simp,
{ intros, rewrite <- a_6 },
{ intros, change (black_height a + 1 + 1 = 1), rewrite <- a_4 }
},
},
case bin : cl' a y b {
cases cl,
case red {
simp, intros, subst cl', simp at *,
rw a_5,
apply mergeL_red_bh,
rw <- a_5,
apply IHl; cc
},
case black {
cases cl',
case red {
simp, intros, rw a_7,
apply mergeL_black_bh,
simp at *,
rw <- a_7,
apply IHl; assumption
},
case black {
simp at *, intros, change (black_height a + 2) with (black_height a + 1 + 1),
rewrite a_5,
apply mergeL_black_bh,
rewrite <- a_5, apply IHl; assumption
}
}
}
}
end.
lemma delete_min_is_black (l:rbtree E) (x:E) (r:rbtree E) :
l.black_height = r.black_height →
(delete_min (bin black l x r)).is_black :=
begin
induction l,
case empty { simp,
cases r,
case bin : cl a y b { cases cl; simp },
case empty { simp }
},
case bin : {
simp, intros,
apply mergeL_is_black
}
end.
lemma delete_min_well_formed (x:rbtree E) :
x.well_formed → (delete_min x).well_formed :=
begin
induction x,
case empty { simp },
case bin : cl l x r IHl IHr {
cases l,
case empty {
cases cl,
case red { simp, cc },
case black {
cases r,
case empty { simp },
case bin : cl' a y b {
cases cl'; simp; cc
}
}
},
case bin : cl' a y b {
cases cl; simp; intros,
{ apply mergeL_red_wf; try { cc },
rw <- a_5, apply delete_min_bh, assumption,
subst cl', apply delete_min_is_black,
simp at *, cc
},
{ apply mergeL_black_wf; try { cc },
rw <- a_3, apply delete_min_bh, assumption
}
}
}
end.
lemma delete_min_is_ordered (t:rbtree E) :
t.is_ordered →
((delete_min t).is_ordered) ∧
(∀ q, t.all_lt q → (delete_min t).all_lt q) ∧
(∀ q, t.all_gt q → (delete_min t).all_gt q) :=
begin
induction t,
case empty { simp },
case bin : co a x b IHl IHr {
cases a,
case empty {
cases co; simp,
{ intros; repeat {split;intros}; try{cc}, apply (all_gt_congr b q x), assumption, rewrite a_2,
(do t <- tactic.target, t' <- tactic.whnf t, tactic.change t'), trivial
},
{ cases b,
case empty{ simp, },
case bin : co_b c z d { simp,
cases co_b; simp; intros; repeat{split;intros}; try{cc},
{ apply (all_gt_congr c q x), assumption, rewrite a_6,
(do t <- tactic.target, t' <- tactic.whnf t, tactic.change t'), trivial },
{ apply (has_preordering.lt_of_lt_of_lt _ x _); assumption },
{ apply (all_gt_congr c q x), assumption, rewrite a_6,
(do t <- tactic.target, t' <- tactic.whnf t, tactic.change t'), trivial },
{ apply (has_preordering.lt_of_lt_of_lt _ x _); assumption },
}
}
},
case bin : co_a c z d IHa {
cases co,
case black { simp; intros, split,
{ apply mergeL_is_ordered; try {simp at *, cc},
have Hczd : (bin co_a c z d).is_ordered, { simp, cc },
destruct (IHa Hczd); simp; intros IH1 IH2 IH3, apply IH2; assumption },
split,
{ intros; apply mergeL_preserves_lt; try{assumption},
have Hczd : (bin co_a c z d).is_ordered, { simp, cc },
destruct (IHa Hczd); simp; intros IH1 IH2 IH3, apply IH2,
{ apply (has_preordering.lt_of_lt_of_lt _ x _); assumption },
{ apply (all_lt_congr d x q), assumption,
rewrite a_8,
(do t <- tactic.target, t' <- tactic.whnf t, tactic.change t'), trivial }
},
{ intros; apply mergeL_preserves_gt; try{assumption},
have Hczd : (bin co_a c z d).is_ordered, { simp, cc },
destruct (IHa Hczd); simp; intros IH1 IH2 IH3, apply IH3; try{assumption},
apply (all_gt_congr b q x), assumption,
rewrite a_10,
(do t <- tactic.target, t' <- tactic.whnf t, tactic.change t'), trivial }
},
case red { sorry }
}
}
end.
@[simp] def merge (co:color) (x:E) (l:rbtree E) (r:rbtree E) : delete_result E :=
match delete_min r with
| unchanged _ :=
match co with
| red := tree_result x l
| black := extra_black_result x l
end
| tree_result q r' := mergeR co (tree_result x r') l q
| extra_black_result q r' := mergeR co (extra_black_result x r') l q
end.
lemma merge_black_bh (x:E) (l:rbtree E) (r:rbtree E) :
l.black_height = r.black_height →
r.well_formed →
(merge black x l r).has_black_height (l.black_height + 1) :=
begin
unfold merge, intros Hlr Hr_wf,
destruct (delete_min r),
{ intros q t Hr, rw Hr, simp },
{ intros q t Hr, rw Hr, simp, apply mergeR_black_bh, simp,
have Hr_bh := (delete_min_bh r Hr_wf),
rewrite Hr at Hr_bh, simp at *, cc
},
{ intro Hr, rw Hr, simp }
end.
lemma merge_red_bh (x:E) (l:rbtree E) (r:rbtree E) :
l.black_height = r.black_height →
l.tree_color = black →
r.well_formed →
(merge red x l r).has_black_height (l.black_height) :=
begin
unfold merge, intros Hl_blk Hlr Hr_wf,
destruct (delete_min r),
{ intros q t Hr, rw Hr, simp,
},
{ intros q t Hr, rw Hr, simp, apply mergeR_red_bh, try {assumption},
have Hr_bh := (delete_min_bh r Hr_wf),
rewrite Hr at Hr_bh, rewrite Hl_blk, simp at *, assumption
},
{ intro Hr, rw Hr, simp }
end.
@[simp] def delete_core (p:E -> ordering) : rbtree E -> delete_result E
| empty := delete_result.unchanged E
| (bin c l x r) :=
match p x with
| ordering.lt := mergeL c (delete_core l) x r
| ordering.eq := merge c x l r
| ordering.gt := mergeR c (delete_core r) l x
end
.
lemma delete_core_bh (p : E -> ordering) (t:rbtree E) :
t.well_formed →
(delete_core p t).has_black_height (t.black_height) :=
begin
induction t,
case empty { simp },
case bin : co l x r IHl IHr {
unfold delete_core, cases (p x),
case ordering.lt {
simp, cases co,
case red {
simp, intros Hl_b Hr_b Hl_wf Hr_wf Hrl,
rewrite Hrl, apply mergeL_red_bh, rewrite <- Hrl, cc
},
case black {
simp, intros Hl_wf Hr_wf Hrl,
rewrite Hrl, apply mergeL_black_bh, rewrite <- Hrl, cc
}
},
case ordering.gt {
simp, cases co,
case red { simp, intros, apply mergeR_red_bh, cc, rewrite a_4; cc },
case black { simp, intros, apply mergeR_black_bh, rewrite a_2; cc }
},
case ordering.eq {
cases co,
case red { simp; intros, apply merge_red_bh; assumption },
case black{ simp; intros, apply merge_black_bh; assumption }
}
}
end.
def delete (p:E -> ordering) (t:rbtree E) : option (E × rbtree E) :=
match delete_core p t with
| unchanged _ := none
| tree_result q t' := some (q,t')
| extra_black_result q t' := some (q,t')
end.
end delete_result.
end delete.
end rbtree.
end data.containers.
|
4e23c9fe0110ad2d180eba38fe3bf3332ecf1f38 | ce6917c5bacabee346655160b74a307b4a5ab620 | /src/ch3/ex0301.lean | 773c849f519ad70d62dcfd013cdcd5aa9e2e4417 | [] | no_license | Ailrun/Theorem_Proving_in_Lean | ae6a23f3c54d62d401314d6a771e8ff8b4132db2 | 2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68 | refs/heads/master | 1,609,838,270,467 | 1,586,846,743,000 | 1,586,846,743,000 | 240,967,761 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 103 | lean | variables p q : Prop
#check p → q → p ∧ q
#check ¬p → p ↔ false
#check p ∨ q → q ∨ p
|
d9d35c897222f30e60f336bf81abba3069810b8e | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/algebraic_geometry/prime_spectrum/is_open_comap_C.lean | 6df1e5afccdf6cf6a010787057078af229f329b7 | [
"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 | 3,042 | lean | /-
Copyright (c) 2021 Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Damiano Testa
-/
import algebraic_geometry.prime_spectrum.basic
import ring_theory.polynomial.basic
/-!
The morphism `Spec R[x] --> Spec R` induced by the natural inclusion `R --> R[x]` is an open map.
The main result is the first part of the statement of Lemma 00FB in the Stacks Project.
https://stacks.math.columbia.edu/tag/00FB
-/
open ideal polynomial prime_spectrum set
namespace algebraic_geometry
namespace polynomial
variables {R : Type*} [comm_ring R] {f : polynomial R}
/-- Given a polynomial `f ∈ R[x]`, `image_of_Df` is the subset of `Spec R` where at least one
of the coefficients of `f` does not vanish. Lemma `image_of_Df_eq_comap_C_compl_zero_locus`
proves that `image_of_Df` is the image of `(zero_locus {f})ᶜ` under the morphism
`comap C : Spec R[x] → Spec R`. -/
def image_of_Df (f) : set (prime_spectrum R) :=
{p : prime_spectrum R | ∃ i : ℕ , (coeff f i) ∉ p.as_ideal}
lemma is_open_image_of_Df : is_open (image_of_Df f) :=
begin
rw [image_of_Df, set_of_exists (λ i (x : prime_spectrum R), coeff f i ∉ x.val)],
exact is_open_Union (λ i, is_open_basic_open),
end
/-- If a point of `Spec R[x]` is not contained in the vanishing set of `f`, then its image in
`Spec R` is contained in the open set where at least one of the coefficients of `f` is non-zero.
This lemma is a reformulation of `exists_coeff_not_mem_C_inverse`. -/
lemma comap_C_mem_image_of_Df {I : prime_spectrum (polynomial R)}
(H : I ∈ (zero_locus {f} : set (prime_spectrum (polynomial R)))ᶜ ) :
comap (polynomial.C : R →+* polynomial R) I ∈ image_of_Df f :=
exists_coeff_not_mem_C_inverse (mem_compl_zero_locus_iff_not_mem.mp H)
/-- The open set `image_of_Df f` coincides with the image of `basic_open f` under the
morphism `C⁺ : Spec R[x] → Spec R`. -/
lemma image_of_Df_eq_comap_C_compl_zero_locus :
image_of_Df f = comap C '' (zero_locus {f})ᶜ :=
begin
refine ext (λ x, ⟨λ hx, ⟨⟨map C x.val, (is_prime_map_C_of_is_prime x.property)⟩, ⟨_, _⟩⟩, _⟩),
{ rw [mem_compl_eq, mem_zero_locus, singleton_subset_iff],
cases hx with i hi,
exact λ a, hi (mem_map_C_iff.mp a i) },
{ refine subtype.ext (ext (λ x, ⟨λ h, _, λ h, subset_span (mem_image_of_mem C.1 h)⟩)),
rw ← @coeff_C_zero R x _,
exact mem_map_C_iff.mp h 0 },
{ rintro ⟨xli, complement, rfl⟩,
exact comap_C_mem_image_of_Df complement }
end
/-- The morphism `C⁺ : Spec R[x] → Spec R` is open.
Stacks Project "Lemma 00FB", first part.
https://stacks.math.columbia.edu/tag/00FB
-/
theorem is_open_map_comap_C :
is_open_map (comap (C : R →+* polynomial R)) :=
begin
rintros U ⟨s, z⟩,
rw [← compl_compl U, ← z, ← Union_of_singleton_coe s, zero_locus_Union, compl_Inter, image_Union],
simp_rw [← image_of_Df_eq_comap_C_compl_zero_locus],
exact is_open_Union (λ f, is_open_image_of_Df),
end
end polynomial
end algebraic_geometry
|
881c76c4758d9ea9304a3b80eb10979db4db4fc2 | 54f4ad05b219d444b709f56c2f619dd87d14ec29 | /my_project/src/love05_inductive_predicates_demo.lean | 55f73034485b8251806502cd8942dbf81b315d49 | [] | no_license | yizhou7/learning-lean | 8efcf838c7276e235a81bd291f467fa43ce56e0a | 91fb366c624df6e56e19555b2e482ce767cd8224 | refs/heads/master | 1,675,649,087,737 | 1,609,022,281,000 | 1,609,022,281,000 | 272,072,779 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,899 | lean | import .love03_forward_proofs_demo
import .love04_functional_programming_demo
/-! # LoVe Demo 5: Inductive Predicates
__Inductive predicates__, or inductively defined propositions, are a convenient
way to specify functions of type `⋯ → Prop`. They are reminiscent of formal
systems and of the Horn clauses of Prolog, the logic programming language par
excellence.
A possible view of Lean:
Lean = typed functional programming + logic programming + more logic -/
set_option pp.beta true
namespace LoVe
/-! ## Introductory Examples
### Even Numbers
Mathematicians often define sets as the smallest that meets some criteria. For
example:
The set `E` of even natural numbers is defined as the smallest set closed
under the following rules: (1) `0 ∈ E` and (2) for every `k ∈ ℕ`, if
`k ∈ E`, then `k + 2 ∈ E`.
In Lean, we can define the corresponding "is even" predicate as follows: -/
inductive even : ℕ → Prop
| zero : even 0
| add_two : ∀k : ℕ, even k → even (k + 2)
/-! This should look familiar. We have used the same syntax, except with `Type`
instead of `Prop`, for inductive types.
The above command introduces a new unary predicate `even` as well as two
constructors, `even.zero` and `even.add_two`, which can be used to build proof
terms. Thanks to the "no junk" guarantee of inductive definitions, `even.zero`
and `even.add_two` are the only two ways to construct proofs of `even`.
By the Curry–Howard correspondence, `even` can be seen as a data type, the
values being the proof terms. -/
lemma even_4 :
even 4 :=
have even_0 : even 0 :=
even.zero,
have even_2 : even 2 :=
even.add_two _ even_0,
show even 4, from
even.add_two _ even_2
/-! Why cannot we simply define `even` recursively? Indeed, why not? -/
def even₂ : ℕ → bool
| 0 := tt
| 1 := ff
| (k + 2) := even₂ k
/-! There are advantages and disadvantages to both styles.
The recursive version requires us to specify a false case (1), and it requires
us to worry about termination. On the other hand, because it is computational,
it works well with `refl`, `simp`, `#reduce`, and `#eval`.
The inductive version is often considered more abstract and elegant. Each rule
is stated independently of the others.
Yet another way to define `even` is as a nonrecursive definition: -/
def even₃ (k : ℕ) : bool :=
k % 2 = 0
/-! Mathematicians would probably find this the most satisfactory definition.
But the inductive version is a convenient, intuitive example that is typical of
many realistic inductive definitions.
### Tennis Games
Transition systems consists of transition rules, which together specify a
binary predicate connecting a "before" and an "after" state. As a simple
specimen of a transition system, we consider the possible transitions, in a game
of tennis, starting from 0–0. -/
inductive score : Type
| vs : ℕ → ℕ → score
| adv_srv : score
| adv_rcv : score
| game_srv : score
| game_rcv : score
infixr ` – ` : 10 := score.vs
inductive step : score → score → Prop
| srv_0_15 : ∀n, step (0–n) (15–n)
| srv_15_30 : ∀n, step (15–n) (30–n)
| srv_30_40 : ∀n, step (30–n) (40–n)
| srv_40_game : ∀n, n < 40 → step (40–n) score.game_srv
| srv_40_adv : step (40–40) score.adv_srv
| rcv_0_15 : ∀n, step (n–0) (n–15)
| rcv_15_30 : ∀n, step (n–15) (n–30)
| rcv_30_40 : ∀n, step (n–30) (n–40)
| rcv_40_game : ∀n, n < 40 → step (n–40) score.game_rcv
| rcv_40_adv : step (40–40) score.adv_rcv
infixr ` ⇒ ` := step
/-! We can ask—and formally answer—questions such as: Is this transition system
confluent? Does it always terminate? Can the score 65–15 be reached from 0–0?
### Reflexive Transitive Closure
Our last introductory example is the reflexive transitive closure of a
relation `r`, modeled as a binary predicate `star r`. -/
inductive star {α : Type} (r : α → α → Prop) : α → α → Prop
| base (a b : α) : r a b → star a b
| refl (a : α) : star a a
| trans (a b c : α) : star a b → star b c → star a c
/-! The first rule embeds `r` into `star r`. The second rule achieves the
reflexive closure. The third rule achieves the transitive closure.
The definition is truly elegant. If you doubt this, try implementing `star` as a
recursive function: -/
def star₂ {α : Type} (r : α → α → Prop) : α → α → Prop :=
sorry
/-! ### A Nonexample
Not all inductive definitions admit a least solution. -/
-- fails
inductive illegal : Prop
| intro : ¬ illegal → illegal
/-! ## Logical Symbols
The truth values `false` and `true`, the connectives `∧` and `∨`, the
`∃`-quantifier, and the equality predicate `=` are all defined as inductive
propositions or predicates. In contrast, `∀` (= `Π`) and `→` are built into
the logic.
Syntactic sugar:
`∃x : α, p` := `Exists (λx : α, p)`
`x = y` := `eq x y` -/
namespace logical_symbols
inductive and (a b : Prop) : Prop
| intro : a → b → and
inductive or (a b : Prop) : Prop
| intro_left : a → or
| intro_right : b → or
inductive iff (a b : Prop) : Prop
| intro : (a → b) → (b → a) → iff
inductive Exists {α : Type} (p : α → Prop) : Prop
| intro : ∀a : α, p a → Exists
inductive true : Prop
| intro : true
inductive false : Prop
inductive eq {α : Type} : α → α → Prop
| refl : ∀a : α, eq a a
end logical_symbols
#print and
#print or
#print iff
#print Exists
#print true
#print false
#print eq
/-! ## Rule Induction
Just as we can perform induction on a term, we can perform induction on a proof
term.
This is called __rule induction__, because the induction is on the introduction
rules (i.e., the constructors of the proof term). Thanks to the Curry–Howard
correspondence, this works as expected. -/
lemma mod_two_eq_zero_of_even (n : ℕ) (h : even n) :
n % 2 = 0 :=
begin
induction h,
case even.zero {
refl },
case even.add_two : k hk ih {
simp [ih] }
end
lemma star_star_iff_star {α : Type} (r : α → α → Prop)
(a b : α) :
star (star r) a b ↔ star r a b :=
begin
apply iff.intro,
{ intro h,
induction h,
case star.base : a b hab {
exact hab },
case star.refl : a {
apply star.refl },
case star.trans : a b c hab hbc ihab ihbc {
apply star.trans a b,
{ exact ihab },
{ exact ihbc } } },
{ intro h,
apply star.base,
exact h }
end
@[simp] lemma star_star_eq_star {α : Type}
(r : α → α → Prop) :
star (star r) = star r :=
begin
apply funext,
intro a,
apply funext,
intro b,
apply propext,
apply star_star_iff_star
end
#check funext
#check propext
/-! ## Rule Induction Pitfalls
Inductive predicates often have arguments that evolve through the induction.
Some care is necessary. -/
lemma p_of_even (p : ℕ → Prop) (n : ℕ) :
even n → p n :=
begin
intro h,
induction h,
case even.zero {
sorry }, -- looks reasonable
case even.add_two {
sorry } -- looks reasonable
end
lemma not_even_2_mul_add_1_sorry (n : ℕ) :
¬ even (2 * n + 1) :=
begin
intro h,
induction h,
case even.zero {
sorry }, -- unprovable
case even.add_two : k hk ih {
exact ih }
end
lemma not_even_2_mul_add_1_sorry₂ (n : ℕ) :
¬ even (2 * n + 1) :=
begin
generalize hx : 2 * n + 1 = x,
intro h,
induction h,
case even.zero {
cases hx },
case even.add_two : k hk ih {
apply ih,
rewrite hx,
sorry } -- unprovable
end
lemma not_even_2_mul_add_1 (n : ℕ) :
¬ even (2 * n + 1) :=
begin
generalize hx : 2 * n + 1 = x,
intro h,
induction h generalizing n,
case even.zero {
cases hx },
case even.add_two : k hk ih {
apply ih (n - 1),
cases n,
case nat.zero {
linarith },
case nat.succ : m {
simp [nat.succ_eq_add_one] at *,
linarith } }
end
/-! `linarith` proves goals involving linear arithmetic equalities or
inequalities. "Linear" means it works only with `+` and `-`, not `*` and `/`
(but multiplication by a constant is supported). -/
lemma linarith_example (i : ℤ) (hi : i > 5) :
2 * i + 3 > 11 :=
by linarith
/-! ## Elimination
Given an inductive predicate `p`, its introduction rules typically have the form
`∀…, ⋯ → p …` and can be used to prove goals of the form `⊢ p …`.
Elimination works the other way around: It extracts information from a lemma or
hypothesis of the form `p …`. Elimination takes various forms: pattern matching,
the `cases` and `induction` tactics, and custom elimination rules (e.g.,
`and.elim_left`).
* `cases` works roughly like `induction` but without induction hypothesis.
* `match` is available as well, but it corresponds to dependently typed pattern
matching (cf. `vector` in lecture 4).
Now we can finally analyze how `cases h`, where `h : l = r`, and how
`cases classical.em h` work. -/
#print eq
lemma cases_eq_example {α : Type} (l r : α) (h : l = r)
(p : α → α → Prop) :
p l r :=
begin
cases h,
sorry
end
#check classical.em
#print or
lemma cases_classical_em_example {α : Type} (a : α)
(p q : α → Prop) :
q a :=
begin
have h : p a ∨ ¬ p a :=
classical.em (p a),
cases h,
case or.inl {
sorry },
case or.inr {
sorry }
end
/-! Often it is convenient to rewrite concrete terms of the form `p (c …)`,
where `c` is typically a constructor. We can state and prove an
__inversion rule__ to support such eliminative reasoning.
Typical inversion rule:
`∀x y, p (c x y) → (∃…, ⋯ ∧ ⋯) ∨ ⋯ ∨ (∃…, ⋯ ∧ ⋯)`
It can be useful to combine introduction and elimination into a single lemma,
which can be used for rewriting both the hypotheses and conclusions of goals:
`∀x y, p (c x y) ↔ (∃…, ⋯ ∧ ⋯) ∨ ⋯ ∨ (∃…, ⋯ ∧ ⋯)` -/
lemma even_iff (n : ℕ) :
even n ↔ n = 0 ∨ (∃m : ℕ, n = m + 2 ∧ even m) :=
begin
apply iff.intro,
{ intro hn,
cases hn,
case even.zero {
simp },
case even.add_two : k hk {
apply or.intro_right,
apply exists.intro k,
simp [hk] } },
{ intro hor,
cases hor,
case or.inl : heq {
simp [heq, even.zero] },
case or.inr : hex {
cases hex with k hand,
cases hand with heq hk,
simp [heq, even.add_two _ hk] } }
end
lemma even_iff₂ (n : ℕ) :
even n ↔ n = 0 ∨ (∃m : ℕ, n = m + 2 ∧ even m) :=
iff.intro
(assume hn : even n,
match n, hn with
| _, even.zero :=
show 0 = 0 ∨ _, from
by simp
| _, even.add_two k hk :=
show _ ∨ (∃m, k + 2 = m + 2 ∧ even m), from
or.intro_right _ (exists.intro k (by simp [*]))
end)
(assume hor : n = 0 ∨ (∃m, n = m + 2 ∧ even m),
match hor with
| or.intro_left _ heq :=
show even n, from
by simp [heq, even.zero]
| or.intro_right _ hex :=
match hex with
| Exists.intro m hand :=
match hand with
| and.intro heq hm :=
show even n, from
by simp [heq, even.add_two _ hm]
end
end
end)
/-! ## Further Examples
### Sorted Lists -/
inductive sorted : list ℕ → Prop
| nil : sorted []
| single {x : ℕ} : sorted [x]
| two_or_more {x y : ℕ} {zs : list ℕ} (hle : x ≤ y)
(hsorted : sorted (y :: zs)) :
sorted (x :: y :: zs)
lemma sorted_nil :
sorted [] :=
sorted.nil
lemma sorted_2 :
sorted [2] :=
sorted.single
lemma sorted_3_5 :
sorted [3, 5] :=
begin
apply sorted.two_or_more,
{ exact dec_trivial },
{ exact sorted.single }
end
lemma sorted_3_5₂ :
sorted [3, 5] :=
sorted.two_or_more dec_trivial sorted.single
lemma sorted_7_9_9_11 :
sorted [7, 9, 9, 11] :=
sorted.two_or_more dec_trivial
(sorted.two_or_more dec_trivial
(sorted.two_or_more dec_trivial
sorted.single))
lemma not_sorted_17_13 :
¬ sorted [17, 13] :=
assume h : sorted [17, 13],
have 17 ≤ 13 :=
match h with
| sorted.two_or_more hle _ := hle
end,
have ¬ 17 ≤ 13 :=
dec_trivial,
show false, from
by cc
/-! ### Palindromes -/
inductive palindrome {α : Type} : list α → Prop
| nil : palindrome []
| single (x : α) : palindrome [x]
| sandwich (x : α) (xs : list α) (hxs : palindrome xs) :
palindrome ([x] ++ xs ++ [x])
-- fails
def palindrome₂ {α : Type} : list α → Prop
| [] := true
| [_] := true
| ([x] ++ xs ++ [x]) := palindrome₂ xs
| _ := false
lemma palindrome_aa {α : Type} (a : α) :
palindrome [a, a] :=
palindrome.sandwich a _ palindrome.nil
lemma palindrome_aba {α : Type} (a b : α) :
palindrome [a, b, a] :=
palindrome.sandwich a _ (palindrome.single b)
lemma reverse_palindrome {α : Type} (xs : list α)
(hxs : palindrome xs) :
palindrome (reverse xs) :=
begin
induction hxs,
case palindrome.nil {
exact palindrome.nil },
case palindrome.single : x {
exact palindrome.single x },
case palindrome.sandwich : x xs hxs ih {
simp [reverse, reverse_append],
exact palindrome.sandwich _ _ ih }
end
/-! ### Full Binary Trees -/
#check btree
inductive is_full {α : Type} : btree α → Prop
| empty : is_full btree.empty
| node (a : α) (l r : btree α)
(hl : is_full l) (hr : is_full r)
(hiff : l = btree.empty ↔ r = btree.empty) :
is_full (btree.node a l r)
lemma is_full_singleton {α : Type} (a : α) :
is_full (btree.node a btree.empty btree.empty) :=
begin
apply is_full.node,
{ exact is_full.empty },
{ exact is_full.empty },
{ refl }
end
lemma is_full_mirror {α : Type} (t : btree α)
(ht : is_full t) :
is_full (mirror t) :=
begin
induction ht,
case is_full.empty {
exact is_full.empty },
case is_full.node : a l r hl hr hiff ih_l ih_r {
rewrite mirror,
apply is_full.node,
{ exact ih_r },
{ exact ih_l },
{ simp [mirror_eq_empty_iff, *] } }
end
lemma is_full_mirror₂ {α : Type} :
∀t : btree α, is_full t → is_full (mirror t)
| btree.empty :=
begin
intro ht,
exact ht
end
| (btree.node a l r) :=
begin
intro ht,
cases ht with _ _ _ hl hr hiff,
rewrite mirror,
apply is_full.node,
{ exact is_full_mirror₂ _ hr },
{ apply is_full_mirror₂ _ hl },
{ simp [mirror_eq_empty_iff, *] }
end
/-! ### First-Order Terms -/
inductive term (α β : Type) : Type
| var {} : β → term
| fn : α → list term → term
inductive well_formed {α β : Type} (arity : α → ℕ) :
term α β → Prop
| var (x : β) : well_formed (term.var x)
| fn (f : α) (ts : list (term α β))
(hargs : ∀t ∈ ts, well_formed t)
(hlen : list.length ts = arity f) :
well_formed (term.fn f ts)
inductive variable_free {α β : Type} : term α β → Prop
| fn (f : α) (ts : list (term α β))
(hargs : ∀t ∈ ts, variable_free t) :
variable_free (term.fn f ts)
end LoVe
|
11386e23f35c69561cbdab459661215fb5c48e97 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/ring_theory/fintype_auto.lean | e233355d73e14fe94d775999ff99b950c49fda70 | [] | 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 | 590 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.associated
import Mathlib.data.fintype.basic
import Mathlib.PostPort
universes u_1
namespace Mathlib
/-!
# Some facts about finite rings
-/
theorem card_units_lt (R : Type u_1) [semiring R] [nontrivial R] [fintype R] :
fintype.card (units R) < fintype.card R :=
card_lt_card_of_injective_of_not_mem coe units.ext not_is_unit_zero
end Mathlib |
44e52d156f7ad3bb2e7c943f8c89127a2dea482f | 46125763b4dbf50619e8846a1371029346f4c3db | /src/tactic/tidy.lean | e1ee2c0c475a774f440e92f70ce30101166c6022 | [
"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 | 3,378 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import tactic.ext
import tactic.auto_cases
import tactic.chain
import tactic.solve_by_elim
import tactic.norm_cast
import tactic.hint
import tactic.interactive
namespace tactic
namespace tidy
meta def tidy_attribute : user_attribute := {
name := `tidy,
descr := "A tactic that should be called by `tidy`."
}
run_cmd attribute.register ``tidy_attribute
meta def run_tactics : tactic string :=
do names ← attribute.get_instances `tidy,
first (names.map name_to_tactic) <|> fail "no @[tidy] tactics succeeded"
@[hint_tactic]
meta def ext1_wrapper : tactic string :=
do ng ← num_goals,
ext1 [] {apply_cfg . new_goals := new_goals.all},
ng' ← num_goals,
return $ if ng' > ng then
"tactic.ext1 [] {new_goals := tactic.new_goals.all}"
else "ext1"
meta def default_tactics : list (tactic string) :=
[ reflexivity >> pure "refl",
`[exact dec_trivial] >> pure "exact dec_trivial",
propositional_goal >> assumption >> pure "assumption",
intros1 >>= λ ns, pure ("intros " ++ (" ".intercalate (ns.map (λ e, e.to_string)))),
auto_cases,
`[apply_auto_param] >> pure "apply_auto_param",
`[dsimp at *] >> pure "dsimp at *",
`[simp at *] >> pure "simp at *",
ext1_wrapper,
fsplit >> pure "fsplit",
injections_and_clear >> pure "injections_and_clear",
propositional_goal >> (`[solve_by_elim]) >> pure "solve_by_elim",
`[norm_cast] >> pure "norm_cast",
`[unfold_coes] >> pure "unfold_coes",
`[unfold_aux] >> pure "unfold_aux",
tidy.run_tactics ]
meta structure cfg :=
(trace_result : bool := ff)
(trace_result_prefix : string := "Try this: ")
(tactics : list (tactic string) := default_tactics)
declare_trace tidy
meta def core (cfg : cfg := {}) : tactic (list string) :=
do
results ← chain cfg.tactics,
when (cfg.trace_result ∨ is_trace_enabled_for `tidy) $
trace (cfg.trace_result_prefix ++ (", ".intercalate results)),
return results
end tidy
meta def tidy (cfg : tidy.cfg := {}) := tactic.tidy.core cfg >> skip
namespace interactive
open lean.parser interactive
/-- Use a variety of conservative tactics to solve goals.
`tidy?` reports back the tactic script it found.
The default list of tactics is stored in `tactic.tidy.default_tidy_tactics`.
This list can be overridden using `tidy { tactics := ... }`.
(The list must be a `list` of `tactic string`, so that `tidy?`
can report a usable tactic script.)
Tactics can also be added to the list by tagging them (locally) with the
`[tidy]` attribute. -/
meta def tidy (trace : parse $ optional (tk "?")) (cfg : tidy.cfg := {}) :=
tactic.tidy { trace_result := trace.is_some, ..cfg }
end interactive
@[hole_command] meta def tidy_hole_cmd : hole_command :=
{ name := "tidy",
descr := "Use `tidy` to complete the goal.",
action := λ _, do script ← tidy.core, return [("begin " ++ (", ".intercalate script) ++ " end", "by tidy")] }
end tactic
|
cc054666513d355bd143ec0cc007db24d30e5f2f | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/tactic/core.lean | 3cfe7562dfd38ef582d383e43ecf5db2fe396358 | [
"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 | 92,513 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek
-/
import data.dlist.basic
import logic.function.basic
import control.basic
import meta.expr
import meta.rb_map
import data.bool
import tactic.binder_matching
import tactic.lean_core_docs
import tactic.interactive_expr
import system.io
universe variable u
attribute [derive [has_reflect, decidable_eq]] tactic.transparency
instance : has_lt pos :=
{ lt := λ x y, (x.line, x.column) < (y.line, y.column) }
namespace expr
open tactic
/-- Given an expr `α` representing a type with numeral structure,
`of_nat α n` creates the `α`-valued numeral expression corresponding to `n`. -/
protected meta def of_nat (α : expr) : ℕ → tactic expr :=
nat.binary_rec
(tactic.mk_mapp ``has_zero.zero [some α, none])
(λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else
do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e])
/-- Given an expr `α` representing a type with numeral structure,
`of_int α n` creates the `α`-valued numeral expression corresponding to `n`.
The output is either a numeral or the negation of a numeral. -/
protected meta def of_int (α : expr) : ℤ → tactic expr
| (n : ℕ) := expr.of_nat α n
| -[1+ n] := do
e ← expr.of_nat α (n+1),
tactic.mk_app ``has_neg.neg [e]
/-- Generates an expression of the form `∃(args), inner`. `args` is assumed to be a list of local
constants. When possible, `p ∧ q` is used instead of `∃(_ : p), q`. -/
meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr :=
args.mfoldr (λarg i:expr, do
t ← infer_type arg,
sort l ← infer_type t,
return $ if arg.occurs i ∨ l ≠ level.zero
then (const `Exists [l] : expr) t (i.lambdas [arg])
else (const `and [] : expr) t i)
inner
/-- `traverse f e` applies the monadic function `f` to the direct descendants of `e`. -/
meta def traverse {m : Type → Type u} [applicative m]
{elab elab' : bool} (f : expr elab → m (expr elab')) :
expr elab → m (expr elab')
| (var v) := pure $ var v
| (sort l) := pure $ sort l
| (const n ls) := pure $ const n ls
| (mvar n n' e) := mvar n n' <$> f e
| (local_const n n' bi e) := local_const n n' bi <$> f e
| (app e₀ e₁) := app <$> f e₀ <*> f e₁
| (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁
| (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁
| (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂
| (macro mac es) := macro mac <$> list.traverse f es
/-- `mfoldl f a e` folds the monadic function `f` over the subterms of the expression `e`,
with initial value `a`. -/
meta def mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α
| x e := prod.snd <$> (state_t.run (e.traverse $ λ e',
(get >>= monad_lift ∘ flip f e' >>= put) $> e') x : m _)
/-- `kreplace e old new` replaces all occurrences of the expression `old` in `e`
with `new`. The occurrences of `old` in `e` are determined using keyed matching
with transparency `md`; see `kabstract` for details. If `unify` is true,
we may assign metavariables in `e` as we match subterms of `e` against `old`. -/
meta def kreplace (e old new : expr) (md := semireducible) (unify := tt)
: tactic expr := do
e ← kabstract e old md unify,
pure $ e.instantiate_var new
end expr
namespace interaction_monad
open result
variables {σ : Type} {α : Type u}
/-- `get_state` returns the underlying state inside an interaction monad, from within that monad. -/
-- Note that this is a generalization of `tactic.read` in core.
meta def get_state : interaction_monad σ σ :=
λ state, success state state
/-- `set_state` sets the underlying state inside an interaction monad, from within that monad. -/
-- Note that this is a generalization of `tactic.write` in core.
meta def set_state (state : σ) : interaction_monad σ unit :=
λ _, success () state
/--
`run_with_state state tac` applies `tac` to the given state `state` and returns the result,
subsequently restoring the original state.
If `tac` fails, then `run_with_state` does too.
-/
meta def run_with_state (state : σ) (tac : interaction_monad σ α) : interaction_monad σ α :=
λ s, match tac state with
| success val _ := success val s
| exception fn pos _ := exception fn pos s
end
end interaction_monad
namespace format
/-- `join' [a,b,c]` produces the format object `abc`.
It differs from `format.join` by using `format.nil` instead of `""` for the empty list. -/
meta def join' (xs : list format) : format :=
xs.foldl compose nil
/-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`,
where `.` represents `format.join`. -/
meta def intercalate (x : format) : list format → format :=
join' ∘ list.intersperse x
/-- `soft_break` is similar to `line`. Whereas in `group (x ++ line ++ y ++ line ++ z)`
the result either fits on one line or in three, `x ++ soft_break ++ y ++ soft_break ++ z`
each line break is decided independently -/
meta def soft_break : format :=
group line
/-- Format a list as a comma separated list, without any brackets. -/
meta def comma_separated {α : Type*} [has_to_format α] : list α → format
| [] := nil
| xs := group (nest 1 $ intercalate ("," ++ soft_break) $ xs.map to_fmt)
end format
section format
open format
/-- format a `list` by separating elements with `soft_break` instead of `line` -/
meta def list.to_line_wrap_format {α : Type u} [has_to_format α] (l : list α) : format :=
bracket "[" "]" (comma_separated l)
end format
namespace tactic
open function
/-- Private work function for `add_local_consts_as_local_hyps`: given
`mappings : list (expr × expr)` corresponding to pairs `(var, hyp)` of variables and the local
hypothesis created as a result and `(var :: rest) : list expr` of more local variables we
examine `var` to see if it contains any other variables in `rest`. If it does, we put it to the
back of the queue and recurse. If it does not, then we perform replacements inside the type of
`var` using the `mappings`, create a new associate local hypothesis, add this to the list of
mappings, and recurse. We are done once all local hypotheses have been processed.
If the list of passed local constants have types which depend on one another (which can only
happen by hand-crafting the `expr`s manually), this function will loop forever. -/
private meta def add_local_consts_as_local_hyps_aux
: list (expr × expr) → list expr → tactic (list (expr × expr))
| mappings [] := return mappings
| mappings (var :: rest) := do
/- Determine if `var` contains any local variables in the lift `rest`. -/
let is_dependent := var.local_type.fold ff $ λ e n b,
if b then b else e ∈ rest,
/- If so, then skip it---add it to the end of the variable queue. -/
if is_dependent then
add_local_consts_as_local_hyps_aux mappings (rest ++ [var])
else do
/- Otherwise, replace all of the local constants referenced by the type of `var` with the
respective new corresponding local hypotheses as recorded in the list `mappings`. -/
let new_type := var.local_type.replace_subexprs mappings,
/- Introduce a new local new local hypothesis `hyp` for `var`, with the correct type. -/
hyp ← assertv var.local_pp_name new_type (var.local_const_set_type new_type),
/- Process the next variable in the queue, with the mapping list updated to include the local
hypothesis which we just created. -/
add_local_consts_as_local_hyps_aux ((var, hyp) :: mappings) rest
/-- `add_local_consts_as_local_hyps vars` add the given list `vars` of `expr.local_const`s to the
tactic state. This is harder than it sounds, since the list of local constants which we have
been passed can have dependencies between their types.
For example, suppose we have two local constants `n : ℕ` and `h : n = 3`. Then we cannot blindly
add `h` as a local hypothesis, since we need the `n` to which it refers to be the `n` created as
a new local hypothesis, not the old local constant `n` with the same name. Of course, these
dependencies can be nested arbitrarily deep.
If the list of passed local constants have types which depend on one another (which can only
happen by hand-crafting the `expr`s manually), this function will loop forever. -/
meta def add_local_consts_as_local_hyps (vars : list expr) : tactic (list (expr × expr)) :=
/- The `list.reverse` below is a performance optimisation since the list of available variables
reported by the system is often mostly the reverse of the order in which they are dependent. -/
add_local_consts_as_local_hyps_aux [] vars.reverse.erase_dup
private meta def get_expl_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_expl_pi_arity_aux new_b,
if bi = binder_info.default then
return (r + 1)
else
return r
| e := return 0
/-- Compute the arity of explicit arguments of `type`. -/
meta def get_expl_pi_arity (type : expr) : tactic nat :=
whnf type >>= get_expl_pi_arity_aux
/-- Compute the arity of explicit arguments of `fn`'s type. -/
meta def get_expl_arity (fn : expr) : tactic nat :=
infer_type fn >>= get_expl_pi_arity
private meta def get_app_fn_args_whnf_aux (md : transparency)
(unfold_ginductive : bool) : list expr → expr → tactic (expr × list expr) :=
λ args e, do
e ← whnf e md unfold_ginductive,
match e with
| (expr.app t u) := get_app_fn_args_whnf_aux (u :: args) t
| _ := pure (e, args)
end
/--
For `e = f x₁ ... xₙ`, `get_app_fn_args_whnf e` returns `(f, [x₁, ..., xₙ])`. `e`
is normalised as necessary; for example:
```
get_app_fn_args_whnf `(let f := g x in f y) = (`(g), [`(x), `(y)])
```
The returned expression is in whnf, but the arguments are generally not.
-/
meta def get_app_fn_args_whnf (e : expr) (md := semireducible)
(unfold_ginductive := tt) : tactic (expr × list expr) :=
get_app_fn_args_whnf_aux md unfold_ginductive [] e
/--
`get_app_fn_whnf e md unfold_ginductive` is like `expr.get_app_fn e` but `e` is
normalised as necessary (with transparency `md`). `unfold_ginductive` controls
whether constructors of generalised inductive types are unfolded. The returned
expression is in whnf.
-/
meta def get_app_fn_whnf : expr → opt_param _ semireducible → opt_param _ tt → tactic expr
| e md unfold_ginductive := do
e ← whnf e md unfold_ginductive,
match e with
| (expr.app f _) := get_app_fn_whnf f md unfold_ginductive
| _ := pure e
end
/--
`get_app_fn_const_whnf e md unfold_ginductive` expects that `e = C x₁ ... xₙ`,
where `C` is a constant, after normalisation with transparency `md`. If so, the
name of `C` is returned. Otherwise the tactic fails. `unfold_ginductive`
controls whether constructors of generalised inductive types are unfolded.
-/
meta def get_app_fn_const_whnf (e : expr) (md := semireducible)
(unfold_ginductive := tt) : tactic name := do
f ← get_app_fn_whnf e md unfold_ginductive,
match f with
| (expr.const n _) := pure n
| _ := fail format!
"expected a constant (possibly applied to some arguments), but got:\n{e}"
end
/--
`get_app_args_whnf e md unfold_ginductive` is like `expr.get_app_args e` but `e`
is normalised as necessary (with transparency `md`). `unfold_ginductive`
controls whether constructors of generalised inductive types are unfolded. The
returned expressions are not necessarily in whnf.
-/
meta def get_app_args_whnf (e : expr) (md := semireducible)
(unfold_ginductive := tt) : tactic (list expr) :=
prod.snd <$> get_app_fn_args_whnf e md unfold_ginductive
/-- `pis loc_consts f` is used to create a pi expression whose body is `f`.
`loc_consts` should be a list of local constants. The function will abstract these local
constants from `f` and bind them with pi binders.
For example, if `a, b` are local constants with types `Ta, Tb`,
``pis [a, b] `(f a b)`` will return the expression
`Π (a : Ta) (b : Tb), f a b`. -/
meta def pis : list expr → expr → tactic expr
| (e@(expr.local_const uniq pp info _) :: es) f := do
t ← infer_type e,
f' ← pis es f,
pure $ expr.pi pp info t (expr.abstract_local f' uniq)
| _ f := pure f
/-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`.
`loc_consts` should be a list of local constants. The function will abstract these local
constants from `f` and bind them with lambda binders.
For example, if `a, b` are local constants with types `Ta, Tb`,
``lambdas [a, b] `(f a b)`` will return the expression
`λ (a : Ta) (b : Tb), f a b`. -/
meta def lambdas : list expr → expr → tactic expr
| (e@(expr.local_const uniq pp info _) :: es) f := do
t ← infer_type e,
f' ← lambdas es f,
pure $ expr.lam pp info t (expr.abstract_local f' uniq)
| _ f := pure f
-- TODO: move to `declaration` namespace in `meta/expr.lean`
/-- `mk_theorem n ls t e` creates a theorem declaration with name `n`, universe parameters named
`ls`, type `t`, and body `e`. -/
meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration :=
declaration.thm n ls t (task.pure e)
/-- `add_theorem_by n ls type tac` uses `tac` to synthesize a term with type `type`, and adds this
to the environment as a theorem with name `n` and universe parameters `ls`. -/
meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) :
tactic expr :=
do ((), body) ← solve_aux type tac,
body ← instantiate_mvars body,
add_decl $ mk_theorem n ls type body,
return $ expr.const n $ ls.map level.param
/-- `eval_expr' α e` attempts to evaluate the expression `e` in the type `α`.
This is a variant of `eval_expr` in core. Due to unexplained behavior in the VM, in rare
situations the latter will fail but the former will succeed. -/
meta def eval_expr' (α : Type*) [_inst_1 : reflected α] (e : expr) : tactic α :=
mk_app ``id [e] >>= eval_expr α
/-- `mk_fresh_name` returns identifiers starting with underscores,
which are not legal when emitted by tactic programs. `mk_user_fresh_name`
turns the useful source of random names provided by `mk_fresh_name` into
names which are usable by tactic programs.
The returned name has four components which are all strings. -/
meta def mk_user_fresh_name : tactic name :=
do nm ← mk_fresh_name,
return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__
/-- `has_attribute' attr_name decl_name` checks
whether `decl_name` exists and has attribute `attr_name`. -/
meta def has_attribute' (attr_name decl_name : name) : tactic bool :=
succeeds (has_attribute attr_name decl_name)
/-- Checks whether the name is a simp lemma -/
meta def is_simp_lemma : name → tactic bool :=
has_attribute' `simp
/-- Checks whether the name is an instance. -/
meta def is_instance : name → tactic bool :=
has_attribute' `instance
/-- `local_decls` returns a dictionary mapping names to their corresponding declarations.
Covers all declarations from the current file. -/
meta def local_decls : tactic (name_map declaration) :=
do e ← tactic.get_env,
let xs := e.fold native.mk_rb_map
(λ d s, if environment.in_current_file e d.to_name
then s.insert d.to_name d else s),
pure xs
/-- `get_decls_from` returns a dictionary mapping names to their
corresponding declarations. Covers all declarations the files listed
in `fs`, with the current file listed as `none`.
The path of the file names is expected to be relative to
the root of the project (i.e. the location of `leanpkg.toml` when it
is present); e.g. `"src/tactic/core.lean"`
Possible issue: `get_decls_from` uses `get_cwd`, the current working
directory, which may not always point at the root of the project.
It would work better if it searched for the root directory or,
better yet, if Lean exposed its path information.
-/
meta def get_decls_from (fs : list (option string)) : tactic (name_map declaration) :=
do root ← unsafe_run_io $ io.env.get_cwd,
let fs := fs.map (option.map $ λ path, root ++ "/" ++ path),
err ← unsafe_run_io $ (fs.filter_map id).mfilter $ (<$>) bnot ∘ io.fs.file_exists,
guard (err = []) <|> fail format!"File not found: {err}",
e ← tactic.get_env,
let xs := e.fold native.mk_rb_map
(λ d s,
let source := e.decl_olean d.to_name in
if source ∈ fs ∧ (source = none → e.in_current_file d.to_name)
then s.insert d.to_name d else s),
pure xs
/-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/
meta def get_unused_decl_name_aux (e : environment) (nm : name) : ℕ → tactic name | n :=
let nm' := nm.append_suffix ("_" ++ to_string n) in
if e.contains nm' then get_unused_decl_name_aux (n+1) else return nm'
/-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it
returns that, otherwise it tries `nm_2`, `nm_3`, ... -/
meta def get_unused_decl_name (nm : name) : tactic name :=
get_env >>= λ e, if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm
/--
Returns a pair `(e, t)`, where `e ← mk_const d.to_name`, and `t = d.type`
but with universe params updated to match the fresh universe metavariables in `e`.
This should have the same effect as just
```lean
do e ← mk_const d.to_name,
t ← infer_type e,
return (e, t)
```
but is hopefully faster.
-/
meta def decl_mk_const (d : declaration) : tactic (expr × expr) :=
do subst ← d.univ_params.mmap $ λ u, prod.mk u <$> mk_meta_univ,
let e : expr := expr.const d.to_name (prod.snd <$> subst),
return (e, d.type.instantiate_univ_params subst)
/--
Replace every universe metavariable in an expression with a universe parameter.
(This is useful when making new declarations.)
-/
meta def replace_univ_metas_with_univ_params (e : expr) : tactic expr :=
do
e.list_univ_meta_vars.enum.mmap (λ n, do
let n' := (`u).append_suffix ("_" ++ to_string (n.1+1)),
unify (expr.sort (level.mvar n.2)) (expr.sort (level.param n'))),
instantiate_mvars e
/-- `mk_local n` creates a dummy local variable with name `n`.
The type of this local constant is a constant with name `n`, so it is very unlikely to be
a meaningful expression. -/
meta def mk_local (n : name) : expr :=
expr.local_const n n binder_info.default (expr.const n [])
/-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`,
`y : ty x` and `z : tz x y`, creates an expression of sigma type:
`⟨x,y,z⟩ : Σ' (x : tx) (y : ty x), tz x y`.
-/
meta def mk_psigma : list expr → tactic expr
| [] := mk_const ``punit
| [x@(expr.local_const _ _ _ _)] := pure x
| (x@(expr.local_const _ _ _ _) :: xs) :=
do y ← mk_psigma xs,
α ← infer_type x,
β ← infer_type y,
t ← lambdas [x] β >>= instantiate_mvars,
r ← mk_mapp ``psigma.mk [α,t],
pure $ r x y
| _ := fail "mk_psigma expects a list of local constants"
/--
Update the type of a local constant or metavariable. For local constants and
metavariables obtained via, for example, `tactic.get_local`, the type stored in
the expression is not necessarily the same as the type returned by `infer_type`.
This tactic, given a local constant or metavariable, updates the stored type to
match the output of `infer_type`. If the input is not a local constant or
metavariable, `update_type` does nothing.
-/
meta def update_type : expr → tactic expr
| e@(expr.local_const ppname uname binfo _) :=
expr.local_const ppname uname binfo <$> infer_type e
| e@(expr.mvar ppname uname _) :=
expr.mvar ppname uname <$> infer_type e
| e := pure e
/-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n`
times and uses `ns` to name the resulting variables. Returns a triple: list of new variables,
remaining term and unused variable names.
-/
meta def elim_gen_prod : nat → expr → list expr → list name → tactic (list expr × expr × list name)
| 0 e hs ns := return (hs.reverse, e, ns)
| (n + 1) e hs ns := do
t ← infer_type e,
if t.is_app_of `eq then return (hs.reverse, e, ns)
else do
[(_, [h, h'], _)] ← cases_core e (ns.take 1),
elim_gen_prod n h' (h :: hs) (ns.drop 1)
private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr)
| 0 e hs := return (hs, e)
| (n + 1) e hs := do
[(_, [h], _), (_, [h'], _)] ← induction e [],
swap,
elim_gen_sum_aux n h' (h::hs)
/-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose
type is a (nested) sum `⊕`. Returns the list of local constants representing the components of `e`.
-/
meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do
(hs, h') ← elim_gen_sum_aux n e [],
gs ← get_goals,
set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1),
return $ hs.reverse ++ [h']
/-- Given `elab_def`, a tactic to solve the current goal,
`extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it
to close the goal. If `trusted` is false, it will be a meta definition. -/
meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit :=
do cxt ← list.map expr.to_implicit_local_const <$> local_context,
t ← target,
(eqns,d) ← solve_aux t elab_def,
d ← instantiate_mvars d,
t' ← pis cxt t,
d' ← lambdas cxt d,
let univ := t'.collect_univ_params,
add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted,
applyc n
/-- Attempts to close the goal with `dec_trivial`. -/
meta def exact_dec_trivial : tactic unit := `[exact dec_trivial]
/-- Runs a tactic for a result, reverting the state after completion. -/
meta def retrieve {α} (tac : tactic α) : tactic α :=
λ s, result.cases_on (tac s)
(λ a s', result.success a s)
result.exception
/-- Runs a tactic for a result, reverting the state after completion or error. -/
meta def retrieve' {α} (tac : tactic α) : tactic α :=
λ s, result.cases_on (tac s)
(λ a s', result.success a s)
(λ msg pos s', result.exception msg pos s)
/-- Repeat a tactic at least once, calling it recursively on all subgoals,
until it fails. This tactic fails if the first invocation fails. -/
meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t
/-- `iterate_range m n t`: Repeat the given tactic at least `m` times and
at most `n` times or until `t` fails. Fails if `t` does not run at least `m` times. -/
meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit
| 0 0 t := skip
| 0 (n+1) t := try (t >> iterate_range 0 n t)
| (m+1) n t := t >> iterate_range m (n-1) t
/--
Given a tactic `tac` that takes an expression
and returns a new expression and a proof of equality,
use that tactic to change the type of the hypotheses listed in `hs`,
as well as the goal if `tgt = tt`.
Returns `tt` if any types were successfully changed.
-/
meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) :
tactic bool :=
do to_remove ← hs.mfilter $ λ h, do {
h_type ← infer_type h,
succeeds $ do
(new_h_type, pr) ← tac h_type,
assert h.local_pp_name new_h_type,
mk_eq_mp pr h >>= tactic.exact },
goal_simplified ← succeeds $ do {
guard tgt,
(new_t, pr) ← target >>= tac,
replace_target new_t pr },
to_remove.mmap' (λ h, try (clear h)),
return (¬ to_remove.empty ∨ goal_simplified)
/-- `revert_after e` reverts all local constants after local constant `e`. -/
meta def revert_after (e : expr) : tactic ℕ := do
l ← local_context,
[pos] ← return $ l.indexes_of e | pp e >>= λ s, fail format!"No such local constant {s}",
let l := l.drop pos.succ, -- all local hypotheses after `e`
revert_lst l
/-- `revert_target_deps` reverts all local constants on which the target depends (recursively).
Returns the number of local constants that have been reverted. -/
meta def revert_target_deps : tactic ℕ :=
do tgt ← target,
ctx ← local_context,
l ← ctx.mfilter (kdepends_on tgt),
n ← revert_lst l,
if l = [] then return n
else do m ← revert_target_deps, return (m + n)
/-- `generalize' e n` generalizes the target with respect to `e`. It creates a new local constant
with name `n` of the same type as `e` and replaces all occurrences of `e` by `n`.
`generalize'` is similar to `generalize` but also succeeds when `e` does not occur in the
goal, in which case it just calls `assert`.
In contrast to `generalize` it already introduces the generalized variable. -/
meta def generalize' (e : expr) (n : name) : tactic expr :=
(generalize e n >> intro n) <|> note n none e
/--
`intron_no_renames n` calls `intro` `n` times, using the pretty-printing name
provided by the binder to name the new local constant.
Unlike `intron`, it does not rename introduced constants if the names shadow existing constants.
-/
meta def intron_no_renames : ℕ → tactic unit
| 0 := pure ()
| (n+1) := do
expr.pi pp_n _ _ _ ← target,
intro pp_n,
intron_no_renames n
/-- `get_univ_level t` returns the universe level of a type `t` -/
meta def get_univ_level (t : expr) (md := semireducible) (unfold_ginductive := tt) :
tactic level :=
do expr.sort u ← infer_type t >>= λ s, whnf s md unfold_ginductive |
fail "get_univ_level: argument is not a type",
return u
/-!
### Various tactics related to local definitions (local constants of the form `x : α := t`)
We call `t` the value of `x`.
-/
/-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined
locally using a `let` expression. Otherwise it fails. -/
meta def local_def_value (e : expr) : tactic expr :=
pp e >>= λ s, -- running `pp` here, because we cannot access it in the `type_context` monad.
tactic.unsafe.type_context.run $ do
lctx <- tactic.unsafe.type_context.get_local_context,
some ldecl <- return $ lctx.get_local_decl e.local_uniq_name |
tactic.unsafe.type_context.fail format!"No such hypothesis {s}.",
some let_val <- return ldecl.value |
tactic.unsafe.type_context.fail format!"Variable {e} is not a local definition.",
return let_val
/-- `is_local_def e` succeeds when `e` is a local definition (a local constant of the form
`e : α := t`) and otherwise fails. -/
meta def is_local_def (e : expr) : tactic unit :=
retrieve $ do revert e, expr.elet _ _ _ _ ← target, skip
/-- like `split_on_p p xs`, `partition_local_deps_aux vs xs acc` searches for matches in `xs`
(using membership to `vs` instead of a predicate) and breaks `xs` when matches are found.
whereas `split_on_p p xs` removes the matches, `partition_local_deps_aux vs xs acc` includes
them in the following partition. Also, `partition_local_deps_aux vs xs acc` discards the partition
running up to the first match. -/
private def partition_local_deps_aux {α} [decidable_eq α] (vs : list α) :
list α → list α → list (list α)
| [] acc := [acc.reverse]
| (l :: ls) acc :=
if l ∈ vs then acc.reverse :: partition_local_deps_aux ls [l]
else partition_local_deps_aux ls (l :: acc)
/-- `partition_local_deps vs`, with `vs` a list of local constants,
reorders `vs` in the order they appear in the local context together
with the variables that follow them. If local context is `[a,b,c,d,e,f]`,
and that we call `partition_local_deps [d,b]`, we get `[[d,e,f], [b,c]]`.
The head of each list is one of the variables given as a parameter. -/
meta def partition_local_deps (vs : list expr) : tactic (list (list expr)) :=
do ls ← local_context,
pure (partition_local_deps_aux vs ls []).tail.reverse
/-- `clear_value [e₀, e₁, e₂, ...]` clears the body of the local definitions `e₀`, `e₁`, `e₂`, ...
changing them into regular hypotheses. A hypothesis `e : α := t` is changed to `e : α`. The order of
locals `e₀`, `e₁`, `e₂` does not matter as a permutation will be chosen so as to preserve type
correctness. This tactic is called `clearbody` in Coq. -/
meta def clear_value (vs : list expr) : tactic unit := do
ls ← partition_local_deps vs,
ls.mmap' $ λ vs, do
{ revert_lst vs,
(expr.elet v t d b) ← target |
fail format!"Cannot clear the body of {vs.head}. It is not a local definition.",
let e := expr.pi v binder_info.default t b,
type_check e <|>
fail format!"Cannot clear the body of {vs.head}. The resulting goal is not type correct.",
g ← mk_meta_var e,
h ← note `h none g,
tactic.exact $ h d,
gs ← get_goals,
set_goals $ g :: gs },
ls.reverse.mmap' $ λ vs, intro_lst $ vs.map expr.local_pp_name
/--
`context_has_local_def` is true iff there is at least one local definition in
the context.
-/
meta def context_has_local_def : tactic bool := do
ctx ← local_context,
ctx.many (succeeds ∘ local_def_value)
/--
`context_upto_hyp_has_local_def h` is true iff any of the hypotheses in the
context up to and including `h` is a local definition.
-/
meta def context_upto_hyp_has_local_def (h : expr) : tactic bool := do
ff ← succeeds (local_def_value h) | pure tt,
ctx ← local_context,
let ctx := ctx.take_while (≠ h),
ctx.many (succeeds ∘ local_def_value)
/-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions,
`simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting
expression and a proof of equality. -/
meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) :
tactic (expr × expr) :=
prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg
/-- Caches unary type classes on a type `α : Type.{univ}`. -/
meta structure instance_cache :=
(α : expr)
(univ : level)
(inst : name_map expr)
/-- Creates an `instance_cache` for the type `α`. -/
meta def mk_instance_cache (α : expr) : tactic instance_cache :=
do u ← mk_meta_univ,
infer_type α >>= unify (expr.sort (level.succ u)),
u ← get_univ_assignment u,
return ⟨α, u, mk_name_map⟩
namespace instance_cache
/-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of
`n c.α` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance
via type class resolution, and updates the cache. -/
meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) :=
match c.inst.find n with
| some i := return (c, i)
| none := do e ← mk_app n [c.α] >>= mk_instance,
return (⟨c.α, c.univ, c.inst.insert n e⟩, e)
end
open expr
/-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`,
`append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/
meta def append_typeclasses : expr → instance_cache → list expr →
tactic (instance_cache × list expr)
| (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l :=
do (c, p) ← c.get n, return (c, p :: l)
| _ c l := return (c, l)
/-- Creates the application `n c.α p l`, where `p` is a type class instance found in the cache `c`.
-/
meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) :=
do d ← get_decl n,
(c, l) ← append_typeclasses d.type.binding_body c l,
return (c, (expr.const n [c.univ]).mk_app (c.α :: l))
/-- `c.of_nat n` creates the `c.α`-valued numeral expression corresponding to `n`. -/
protected meta def of_nat (c : instance_cache) (n : ℕ) : tactic (instance_cache × expr) :=
if n = 0 then c.mk_app ``has_zero.zero [] else do
(c, ai) ← c.get ``has_add,
(c, oi) ← c.get ``has_one,
(c, one) ← c.mk_app ``has_one.one [],
return (c, n.binary_rec one $ λ b n e,
if n = 0 then one else
cond b
((expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e])
((expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e]))
/-- `c.of_int n` creates the `c.α`-valued numeral expression corresponding to `n`.
The output is either a numeral or the negation of a numeral. -/
protected meta def of_int (c : instance_cache) : ℤ → tactic (instance_cache × expr)
| (n : ℕ) := c.of_nat n
| -[1+ n] := do
(c, e) ← c.of_nat (n+1),
c.mk_app ``has_neg.neg [e]
end instance_cache
/-- A variation on `assert` where a (possibly incomplete)
proof of the assertion is provided as a parameter.
``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and
use `tac` to (partially) construct a proof for it. `gs` is the
list of remaining goals in the proof of `h`.
The benefits over assert are:
- unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`;
- when `tac` does not complete the proof of `h`, returning the list
of goals allows one to write a tactic using `h` and with the confidence
that a proof will not boil over to goals left over from the proof of `h`,
unlike what would be the case when using `tactic.swap`.
-/
meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) :
tactic (expr × list expr) :=
focus1 $
do h' ← assert h p,
[g₀,g₁] ← get_goals,
set_goals [g₀], tac₀,
gs ← get_goals,
set_goals [g₁],
return (h', gs)
/-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/
meta def var_names : expr → list name
| (expr.pi n _ _ b) := n :: var_names b
| _ := []
/-- When `struct_n` is the name of a structure type,
`subobject_names struct_n` returns two lists of names `(instances, fields)`.
The names in `instances` are the projections from `struct_n` to the structures that it extends
(assuming it was defined with `old_structure_cmd false`).
The names in `fields` are the standard fields of `struct_n`. -/
meta def subobject_names (struct_n : name) : tactic (list name × list name) :=
do env ← get_env,
c ← match env.constructors_of struct_n with
| [c] := pure c
| [] :=
if env.is_inductive struct_n
then fail format!"{struct_n} does not have constructors"
else fail format!"{struct_n} is not an inductive type"
| _ := fail "too many constructors"
end,
vs ← var_names <$> (mk_const c >>= infer_type),
fields ← env.structure_fields struct_n,
return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs)
private meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n :=
do (so,fs) ← subobject_names struct_n,
ts ← so.mmap (λ n, do
(_, e) ← mk_const (n.update_prefix struct_n) >>= infer_type >>= open_pis,
expanded_field_list' $ e.get_app_fn.const_name),
return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n)
open functor function
/-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure
named `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name
of the projection is `prefix.name`.
`struct_n` cannot be a synonym for a `structure`, it must be itself a `structure` -/
meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) :=
dlist.to_list <$> expanded_field_list' struct_n
/--
Return a list of all type classes which can be instantiated
for the given expression.
-/
meta def get_classes (e : expr) : tactic (list name) :=
attribute.get_instances `class >>= list.mfilter (λ n,
succeeds $ mk_app n [e] >>= mk_instance)
/--
Finds an instance of an implication `cond → tgt`.
Returns a pair of a local constant `e` of type `cond`, and an instance of `tgt` that can mention
`e`. The local constant `e` is added as an hypothesis to the tactic state, but should not be used,
since it has been "proven" by a metavariable.
-/
meta def mk_conditional_instance (cond tgt : expr) : tactic (expr × expr) := do
f ← mk_meta_var cond,
e ← assertv `c cond f, swap,
reset_instance_cache,
inst ← mk_instance tgt,
return (e, inst)
open nat
/-- Create a list of `n` fresh metavariables. -/
meta def mk_mvar_list : ℕ → tactic (list expr)
| 0 := pure []
| (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n
/-- Returns the only goal, or fails if there isn't just one goal. -/
meta def get_goal : tactic expr :=
do gs ← get_goals,
match gs with
| [a] := return a
| [] := fail "there are no goals"
| _ := fail "there are too many goals"
end
/-- `iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals,
or until it fails. Always succeeds. -/
meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit
| 0 tac := trace "maximal iterations reached"
| (succ n) tac := tactic.all_goals' $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip
/-- `iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first
goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on
current goal. -/
meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit
| 0 tac := trace "maximal iterations reached"
| (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac)
/-- This makes sure that the execution of the tactic does not change the tactic state.
This can be helpful while using rewrite, apply, or expr munging.
Remember to instantiate your metavariables before you're done! -/
meta def lock_tactic_state {α} (t : tactic α) : tactic α
| s := match t s with
| result.success a s' := result.success a s
| result.exception msg pos s' := result.exception msg pos s
end
/--
`apply_list l`, for `l : list (tactic expr)`,
tries to apply the lemmas generated by the tactics in `l` on the first goal, and
fail if none succeeds.
-/
meta def apply_list_expr (opt : apply_cfg) : list (tactic expr) → tactic unit
| [] := fail "no matching rule"
| (h::t) := (do e ← h, interactive.concat_tags (apply e opt)) <|> apply_list_expr t
/--
Constructs a list of `tactic expr` given a list of p-expressions, as follows:
- if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it
- if the p-expression is a user attribute, add all the theorems with this attribute
to the list.
We need to return a list of `tactic expr`, rather than just `expr`, because these expressions
will be repeatedly applied against goals, and we need to ensure that metavariables don't get stuck.
-/
meta def build_list_expr_for_apply : list pexpr → tactic (list (tactic expr))
| [] := return []
| (h::t) := do
tail ← build_list_expr_for_apply t,
a ← i_to_expr_for_apply h,
(do l ← attribute.get_instances (expr.const_name a),
m ← l.mmap (λ n, _root_.to_pexpr <$> mk_const n),
-- We reverse the list of lemmas marked with an attribute,
-- on the assumption that lemmas proved earlier are more often applicable
-- than lemmas proved later. This is a performance optimization.
build_list_expr_for_apply (m.reverse ++ t))
<|> return ((i_to_expr_for_apply h) :: tail)
/--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the
first goal and the resulting subgoals, iteratively, at most `n` times.
Unlike `solve_by_elim`, `apply_rules` does not do any backtracking, and just greedily applies
a lemma from the list until it can't.
-/
meta def apply_rules (hs : list pexpr) (n : nat) (opt : apply_cfg) : tactic unit :=
do l ← lock_tactic_state $ build_list_expr_for_apply hs,
iterate_at_most_on_subgoals n (assumption <|> apply_list_expr opt l)
/-- `replace h p` elaborates the pexpr `p`, clears the existing hypothesis named `h` from the local
context, and adds a new hypothesis named `h`. The type of this hypothesis is the type of `p`.
Fails if there is nothing named `h` in the local context. -/
meta def replace (h : name) (p : pexpr) : tactic unit :=
do h' ← get_local h,
p ← to_expr p,
note h none p,
clear h'
/-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp``
or `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an
`iff`, returns an expression with the `iff` converted to either the forwards or backwards
implication, as requested. -/
meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → option expr
| (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n))
| `(%%a ↔ %%b) f := some $ @expr.const tt iffmp [] a b (f 0)
| _ f := none
/-- `iff_mp_core e ty` assumes that `ty` is the type of `e`.
If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., A → B`. -/
meta def iff_mp_core (e ty: expr) : option expr :=
mk_iff_mp_app `iff.mp ty (λ_, e)
/-- `iff_mpr_core e ty` assumes that `ty` is the type of `e`.
If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., B → A`. -/
meta def iff_mpr_core (e ty: expr) : option expr :=
mk_iff_mp_app `iff.mpr ty (λ_, e)
/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,
create the expression which is the forward implication. -/
meta def iff_mp (e : expr) : tactic expr :=
do t ← infer_type e,
iff_mp_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`"
/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,
create the expression which is the reverse implication. -/
meta def iff_mpr (e : expr) : tactic expr :=
do t ← infer_type e,
iff_mpr_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`"
/--
Attempts to apply `e`, and if that fails, if `e` is an `iff`,
try applying both directions separately.
-/
meta def apply_iff (e : expr) : tactic (list (name × expr)) :=
let ap e := tactic.apply e {new_goals := new_goals.non_dep_only} in
ap e <|> (iff_mp e >>= ap) <|> (iff_mpr e >>= ap)
/--
Configuration options for `apply_any`:
* `use_symmetry`: if `apply_any` fails to apply any lemma, call `symmetry` and try again.
* `use_exfalso`: if `apply_any` fails to apply any lemma, call `exfalso` and try again.
* `apply`: specify an alternative to `tactic.apply`; usually `apply := tactic.eapply`.
-/
meta structure apply_any_opt extends apply_cfg :=
(use_symmetry : bool := tt)
(use_exfalso : bool := tt)
/--
This is a version of `apply_any` that takes a list of `tactic expr`s instead of `expr`s,
and evaluates these as thunks before trying to apply them.
We need to do this to avoid metavariables getting stuck during subsequent rounds of `apply`.
-/
meta def apply_any_thunk
(lemmas : list (tactic expr))
(opt : apply_any_opt := {})
(tac : tactic unit := skip)
(on_success : expr → tactic unit := (λ _, skip))
(on_failure : tactic unit := skip) : tactic unit :=
do
let modes := [skip]
++ (if opt.use_symmetry then [symmetry] else [])
++ (if opt.use_exfalso then [exfalso] else []),
modes.any_of (λ m, do m,
lemmas.any_of (λ H, H >>= (λ e, do apply e opt.to_apply_cfg, on_success e, tac))) <|>
(on_failure >> fail "apply_any tactic failed; no lemma could be applied")
/--
`apply_any lemmas` tries to apply one of the list `lemmas` to the current goal.
`apply_any lemmas opt` allows control over how lemmas are applied.
`opt` has fields:
* `use_symmetry`: if no lemma applies, call `symmetry` and try again. (Defaults to `tt`.)
* `use_exfalso`: if no lemma applies, call `exfalso` and try again. (Defaults to `tt`.)
* `apply`: use a tactic other than `tactic.apply` (e.g. `tactic.fapply` or `tactic.eapply`).
`apply_any lemmas tac` calls the tactic `tac` after a successful application.
Defaults to `skip`. This is used, for example, by `solve_by_elim` to arrange
recursive invocations of `apply_any`.
-/
meta def apply_any
(lemmas : list expr)
(opt : apply_any_opt := {})
(tac : tactic unit := skip) : tactic unit :=
apply_any_thunk (lemmas.map pure) opt tac
/-- Try to apply a hypothesis from the local context to the goal. -/
meta def apply_assumption : tactic unit :=
local_context >>= apply_any
/-- `change_core e none` is equivalent to `change e`. It tries to change the goal to `e` and fails
if this is not a definitional equality.
`change_core e (some h)` assumes `h` is a local constant, and tries to change the type of `h` to `e`
by reverting `h`, changing the goal, and reintroducing hypotheses. -/
meta def change_core (e : expr) : option expr → tactic unit
| none := tactic.change e
| (some h) :=
do num_reverted : ℕ ← revert h,
expr.pi n bi d b ← target,
tactic.change $ expr.pi n bi e b,
intron num_reverted
/--
`change_with_at olde newe hyp` replaces occurences of `olde` with `newe` at hypothesis `hyp`,
assuming `olde` and `newe` are defeq when elaborated.
-/
meta def change_with_at (olde newe : pexpr) (hyp : name) : tactic unit :=
do h ← get_local hyp,
tp ← infer_type h,
olde ← to_expr olde, newe ← to_expr newe,
let repl_tp := tp.replace (λ a n, if a = olde then some newe else none),
when (repl_tp ≠ tp) $ change_core repl_tp (some h)
/-- Returns a list of all metavariables in the current partial proof. This can differ from
the list of goals, since the goals can be manually edited. -/
meta def metavariables : tactic (list expr) :=
expr.list_meta_vars <$> result
/--
`sorry_if_contains_sorry` will solve any goal already containing `sorry` in its type with `sorry`,
and fail otherwise.
-/
meta def sorry_if_contains_sorry : tactic unit :=
do
g ← target,
guard g.contains_sorry <|> fail "goal does not contain `sorrry`",
tactic.admit
/-- Fail if the target contains a metavariable. -/
meta def no_mvars_in_target : tactic unit :=
expr.has_meta_var <$> target >>= guardb ∘ bnot
/-- Succeeds only if the current goal is a proposition. -/
meta def propositional_goal : tactic unit :=
do g :: _ ← get_goals,
is_proof g >>= guardb
/-- Succeeds only if we can construct an instance showing the
current goal is a subsingleton type. -/
meta def subsingleton_goal : tactic unit :=
do g :: _ ← get_goals,
ty ← infer_type g >>= instantiate_mvars,
to_expr ``(subsingleton %%ty) >>= mk_instance >> skip
/--
Succeeds only if the current goal is "terminal",
in the sense that no other goals depend on it
(except possibly through shared metavariables; see `independent_goal`).
-/
meta def terminal_goal : tactic unit :=
propositional_goal <|> subsingleton_goal <|>
do g₀ :: _ ← get_goals,
mvars ← (λ L, list.erase L g₀) <$> metavariables,
mvars.mmap' $ λ g, do
t ← infer_type g >>= instantiate_mvars,
d ← kdepends_on t g₀,
monad.whenb d $
pp t >>= λ s, fail ("The current goal is not terminal: " ++ s.to_string ++ " depends on it.")
/--
Succeeds only if the current goal is "independent", in the sense
that no other goals depend on it, even through shared meta-variables.
-/
meta def independent_goal : tactic unit :=
no_mvars_in_target >> terminal_goal
/-- `triv'` tries to close the first goal with the proof `trivial : true`. Unlike `triv`,
it only unfolds reducible definitions, so it sometimes fails faster. -/
meta def triv' : tactic unit := do c ← mk_const `trivial, exact c reducible
variable {α : Type}
/-- Apply a tactic as many times as possible, collecting the results in a list.
Fail if the tactic does not succeed at least once. -/
meta def iterate1 (t : tactic α) : tactic (list α) :=
do r ← decorate_ex "iterate1 failed: tactic did not succeed" t,
L ← iterate t,
return (r :: L)
/-- Introduces one or more variables and returns the new local constants.
Fails if `intro` cannot be applied. -/
meta def intros1 : tactic (list expr) :=
iterate1 intro1
/-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/
meta def under_binders {α : Type} (t : tactic α) : tactic α :=
do
v ← intros,
r ← t,
revert_lst v,
return r
namespace interactive
/-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/
meta def under_binders (i : itactic) : itactic := tactic.under_binders i
end interactive
/-- `successes` invokes each tactic in turn, returning the list of successful results. -/
meta def successes (tactics : list (tactic α)) : tactic (list α) :=
list.filter_map id <$> monad.sequence (tactics.map (λ t, try_core t))
/--
Try all the tactics in a list, each time starting at the original `tactic_state`,
returning the list of successful results,
and reverting to the original `tactic_state`.
-/
-- Note this is not the same as `successes`, which keeps track of the evolving `tactic_state`.
meta def try_all {α : Type} (tactics : list (tactic α)) : tactic (list α) :=
λ s, result.success
(tactics.map $
λ t : tactic α,
match t s with
| result.success a s' := [a]
| _ := []
end).join s
/--
Try all the tactics in a list, each time starting at the original `tactic_state`,
returning the list of successful results sorted by
the value produced by a subsequent execution of the `sort_by` tactic,
and reverting to the original `tactic_state`.
-/
meta def try_all_sorted {α : Type} (tactics : list (tactic α)) (sort_by : tactic ℕ := num_goals) :
tactic (list (α × ℕ)) :=
λ s, result.success
((tactics.map $
λ t : tactic α,
match (do a ← t, n ← sort_by, return (a, n)) s with
| result.success a s' := [a]
| _ := []
end).join.qsort (λ p q : α × ℕ, p.2 < q.2)) s
/-- Return target after instantiating metavars and whnf. -/
private meta def target' : tactic expr :=
target >>= instantiate_mvars >>= whnf
/--
Just like `split`, `fsplit` applies the constructor when the type of the target is
an inductive data type with one constructor.
However it does not reorder goals or invoke `auto_param` tactics.
-/
-- FIXME check if we can remove `auto_param := ff`
meta def fsplit : tactic unit :=
do [c] ← target' >>= get_constructors_for |
fail "fsplit tactic failed, target is not an inductive datatype with only one constructor",
mk_const c >>= λ e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip
run_cmd add_interactive [`fsplit]
add_tactic_doc
{ name := "fsplit",
category := doc_category.tactic,
decl_names := [`tactic.interactive.fsplit],
tags := ["logic", "goal management"] }
/-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection`
succeeds, clears the old hypothesis. -/
meta def injections_and_clear : tactic unit :=
do l ← local_context,
results ← successes $ l.map $ λ e, injection e >> clear e,
when (results.empty) (fail "could not use `injection` then `clear` on any hypothesis")
run_cmd add_interactive [`injections_and_clear]
add_tactic_doc
{ name := "injections_and_clear",
category := doc_category.tactic,
decl_names := [`tactic.interactive.injections_and_clear],
tags := ["context management"] }
/-- Calls `cases` on every local hypothesis, succeeding if
it succeeds on at least one hypothesis. -/
meta def case_bash : tactic unit :=
do l ← local_context,
r ← successes (l.reverse.map (λ h, cases h >> skip)),
when (r.empty) failed
/--
`note_anon t v`, given a proof `v : t`,
adds `h : t` to the current context, where the name `h` is fresh.
`note_anon none v` will infer the type `t` from `v`.
-/
-- While `note` provides a default value for `t`, it doesn't seem this could ever be used.
meta def note_anon (t : option expr) (v : expr) : tactic expr :=
do h ← get_unused_name `h none,
note h t v
/-- `find_local t` returns a local constant with type t, or fails if none exists. -/
meta def find_local (t : pexpr) : tactic expr :=
do t' ← to_expr t,
(prod.snd <$> solve_aux t' assumption >>= instantiate_mvars) <|>
fail format!"No hypothesis found of the form: {t'}"
/-- `dependent_pose_core l`: introduce dependent hypotheses, where the proofs depend on the values
of the previous local constants. `l` is a list of local constants and their values. -/
meta def dependent_pose_core (l : list (expr × expr)) : tactic unit := do
let lc := l.map prod.fst,
let lm := l.map (λ⟨l, v⟩, (l.local_uniq_name, v)),
old::other_goals ← get_goals,
t ← infer_type old,
new_goal ← mk_meta_var (t.pis lc),
set_goals (old :: new_goal :: other_goals),
exact ((new_goal.mk_app lc).instantiate_locals lm),
return ()
/--
Instantiates metavariables that appear in the current goal.
-/
meta def instantiate_mvars_in_target : tactic unit :=
target >>= instantiate_mvars >>= change
/--
Instantiates metavariables in all goals.
-/
meta def instantiate_mvars_in_goals : tactic unit :=
all_goals' $ instantiate_mvars_in_target
/-- Protect the declaration `n` -/
meta def mk_protected (n : name) : tactic unit :=
do env ← get_env, set_env (env.mk_protected n)
end tactic
namespace lean.parser
open tactic interaction_monad
/-- `emit_command_here str` behaves as if the string `str` were placed as a user command at the
current line. -/
meta def emit_command_here (str : string) : lean.parser string :=
do (_, left) ← with_input command_like str,
return left
/-- Inner recursion for `emit_code_here`. -/
meta def emit_code_here_aux : string → ℕ → lean.parser unit
| str slen := do
left ← emit_command_here str,
let llen := left.length,
when (llen < slen ∧ llen ≠ 0) (emit_code_here_aux left llen)
/-- `emit_code_here str` behaves as if the string `str` were placed at the current location in
source code. -/
meta def emit_code_here (s : string) : lean.parser unit := emit_code_here_aux s s.length
/-- `run_parser p` is like `run_cmd` but for the parser monad. It executes parser `p` at the
top level, giving access to operations like `emit_code_here`. -/
@[user_command]
meta def run_parser_cmd (_ : interactive.parse $ tk "run_parser") : lean.parser unit :=
do e ← lean.parser.pexpr 0,
p ← eval_pexpr (lean.parser unit) e,
p
add_tactic_doc
{ name := "run_parser",
category := doc_category.cmd,
decl_names := [``run_parser_cmd],
tags := ["parsing"] }
/-- `get_current_namespace` returns the current namespace (it could be `name.anonymous`).
This function deserves a C++ implementation in core lean, and will fail if it is not called from
the body of a command (i.e. anywhere else that the `lean.parser` monad can be invoked). -/
meta def get_current_namespace : lean.parser name :=
do n ← tactic.mk_user_fresh_name,
emit_code_here $ sformat!"def {n} := ()",
nfull ← tactic.resolve_constant n,
return $ nfull.get_nth_prefix n.components.length
/-- `get_variables` returns a list of existing variable names, along with their types and binder
info. -/
meta def get_variables : lean.parser (list (name × binder_info × expr)) :=
list.map expr.get_local_const_kind <$> list_available_include_vars
/-- `get_included_variables` returns those variables `v` returned by `get_variables` which have been
"included" by an `include v` statement and are not (yet) `omit`ed. -/
meta def get_included_variables : lean.parser (list (name × binder_info × expr)) :=
do ns ← list_include_var_names,
list.filter (λ v, v.1 ∈ ns) <$> get_variables
/-- From the `lean.parser` monad, synthesize a `tactic_state` which includes all of the local
variables referenced in `es : list pexpr`, and those variables which have been `include`ed in the
local context---precisely those variables which would be ambiently accessible if we were in a
tactic-mode block where the goals had types `es.mmap to_expr`, for example.
Returns a new `ts : tactic_state` with these local variables added, and
`mappings : list (expr × expr)`, for which pairs `(var, hyp)` correspond to an existing variable
`var` and the local hypothesis `hyp` which was added to the tactic state `ts` as a result. -/
meta def synthesize_tactic_state_with_variables_as_hyps (es : list pexpr)
: lean.parser (tactic_state × list (expr × expr)) :=
do /- First, in order to get `to_expr e` to resolve declared `variables`, we add all of the
declared variables to a fake `tactic_state`, and perform the resolution. At the end,
`to_expr e` has done the work of determining which variables were actually referenced, which
we then obtain from `fe` via `expr.list_local_consts` (which, importantly, is not defined for
`pexpr`s). -/
vars ← list_available_include_vars,
fake_es ← lean.parser.of_tactic $ lock_tactic_state $ do {
/- Note that `add_local_consts_as_local_hyps` returns the mappings it generated, but we discard
them on this first pass. (We return the mappings generated by our second invocation of this
function below.) -/
add_local_consts_as_local_hyps vars,
es.mmap to_expr
},
/- Now calculate lists of a) the explicitly `include`ed variables and b) the variables which were
referenced in `e` when it was resolved to `fake_e`.
It is important that we include variables of the kind a) because we want `simp` to have access
to declared local instances, and it is important that we only restrict to variables of kind a)
and b) together since we do not to recognise a hypothesis which is posited as a `variable`
in the environment but not referenced in the `pexpr` we were passed.
One use case for this behaviour is running `simp` on the passed `pexpr`, since we do not want
simp to use arbitrary hypotheses which were declared as `variables` in the local environment
but not referenced in the expression to simplify (as one would be expect generally in tactic
mode). -/
included_vars ← list_include_var_names,
let referenced_vars := list.join $ fake_es.map $ λ e, e.list_local_consts.map expr.local_pp_name,
/- Look up the explicit `included_vars` and the `referenced_vars` (which have appeared in the
`pexpr` list which we were passed.) -/
let directly_included_vars := vars.filter $ λ var,
(var.local_pp_name ∈ included_vars) ∨ (var.local_pp_name ∈ referenced_vars),
/- Inflate the list `directly_included_vars` to include those variables which are "implicitly
included" by virtue of reference to one or multiple others. For example, given
`variables (n : ℕ) [prime n] [ih : even n]`, a reference to `n` implies that the typeclass
instance `prime n` should be included, but `ih : even n` should not. -/
let all_implicitly_included_vars :=
expr.all_implicitly_included_variables vars directly_included_vars,
/- Capture a tactic state where both of these kinds of variables have been added as local
hypotheses, and resolve `e` against this state with `to_expr`, this time for real. -/
lean.parser.of_tactic $ do {
mappings ← add_local_consts_as_local_hyps all_implicitly_included_vars,
ts ← get_state,
return (ts, mappings)
}
end lean.parser
namespace tactic
variables {α : Type}
/--
Hole command used to fill in a structure's field when specifying an instance.
In the following:
```lean
instance : monad id :=
{! !}
```
invoking the hole command "Instance Stub" ("Generate a skeleton for the structure under
construction.") produces:
```lean
instance : monad id :=
{ map := _,
map_const := _,
pure := _,
seq := _,
seq_left := _,
seq_right := _,
bind := _ }
```
-/
@[hole_command] meta def instance_stub : hole_command :=
{ name := "Instance Stub",
descr := "Generate a skeleton for the structure under construction.",
action := λ _,
do tgt ← target >>= whnf,
let cl := tgt.get_app_fn.const_name,
env ← get_env,
fs ← expanded_field_list cl,
let fs := fs.map prod.snd,
let fs := format.intercalate (",\n " : format) $ fs.map (λ fn, format!"{fn} := _"),
let out := format.to_string format!"{{ {fs} }",
return [(out,"")] }
add_tactic_doc
{ name := "instance_stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.instance_stub],
tags := ["instances"] }
/-- Like `resolve_name` except when the list of goals is
empty. In that situation `resolve_name` fails whereas
`resolve_name'` simply proceeds on a dummy goal -/
meta def resolve_name' (n : name) : tactic pexpr :=
do [] ← get_goals | resolve_name n,
g ← mk_mvar,
set_goals [g],
resolve_name n <* set_goals []
private meta def strip_prefix' (n : name) : list string → name → tactic name
| s name.anonymous := pure $ s.foldl (flip name.mk_string) name.anonymous
| s (name.mk_string a p) :=
do let n' := s.foldl (flip name.mk_string) name.anonymous,
do { n'' ← tactic.resolve_constant n',
if n'' = n
then pure n'
else strip_prefix' (a :: s) p }
<|> strip_prefix' (a :: s) p
| s n@(name.mk_numeral a p) := pure $ s.foldl (flip name.mk_string) n
/-- Strips unnecessary prefixes from a name, e.g. if a namespace is open. -/
meta def strip_prefix : name → tactic name
| n@(name.mk_string a a_1) :=
if (`_private).is_prefix_of n
then let n' := n.update_prefix name.anonymous in
n' <$ resolve_name' n' <|> pure n
else strip_prefix' n [a] a_1
| n := pure n
/-- Used to format return strings for the hole commands `match_stub` and `eqn_stub`. -/
meta def mk_patterns (t : expr) : tactic (list format) :=
do let cl := t.get_app_fn.const_name,
env ← get_env,
let fs := env.constructors_of cl,
fs.mmap $ λ f,
do { (vs,_) ← mk_const f >>= infer_type >>= open_pis,
let vs := vs.filter (λ v, v.is_default_local),
vs ← vs.mmap (λ v,
do v' ← get_unused_name v.local_pp_name,
pose v' none `(()),
pure v' ),
vs.mmap' $ λ v, get_local v >>= clear,
let args := list.intersperse (" " : format) $ vs.map to_fmt,
f ← strip_prefix f,
if args.empty
then pure $ format!"| {f} := _\n"
else pure format!"| ({f} {format.join args}) := _\n" }
/--
Hole command used to generate a `match` expression.
In the following:
```lean
meta def foo (e : expr) : tactic unit :=
{! e !}
```
invoking hole command "Match Stub" ("Generate a list of equations for a `match` expression")
produces:
```lean
meta def foo (e : expr) : tactic unit :=
match e with
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
end
```
-/
@[hole_command] meta def match_stub : hole_command :=
{ name := "Match Stub",
descr := "Generate a list of equations for a `match` expression.",
action := λ es,
do [e] ← pure es | fail "expecting one expression",
e ← to_expr e,
t ← infer_type e >>= whnf,
fs ← mk_patterns t,
e ← pp e,
let out := format.to_string format!"match {e} with\n{format.join fs}end\n",
return [(out,"")] }
add_tactic_doc
{ name := "Match Stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.match_stub],
tags := ["pattern matching"] }
/--
Invoking hole command "Equations Stub" ("Generate a list of equations for a recursive definition")
in the following:
```lean
meta def foo : {! expr → tactic unit !} -- `:=` is omitted
```
produces:
```lean
meta def foo : expr → tactic unit
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
```
A similar result can be obtained by invoking "Equations Stub" on the following:
```lean
meta def foo : expr → tactic unit := -- do not forget to write `:=`!!
{! !}
```
```lean
meta def foo : expr → tactic unit := -- don't forget to erase `:=`!!
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
```
-/
@[hole_command] meta def eqn_stub : hole_command :=
{ name := "Equations Stub",
descr := "Generate a list of equations for a recursive definition.",
action := λ es,
do t ← match es with
| [t] := to_expr t
| [] := target
| _ := fail "expecting one type"
end,
e ← whnf t,
(v :: _,_) ← open_pis e | fail "expecting a Pi-type",
t' ← infer_type v,
fs ← mk_patterns t',
t ← pp t,
let out :=
if es.empty then
format.to_string format!"-- do not forget to erase `:=`!!\n{format.join fs}"
else format.to_string format!"{t}\n{format.join fs}",
return [(out,"")] }
add_tactic_doc
{ name := "Equations Stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.eqn_stub],
tags := ["pattern matching"] }
/--
This command lists the constructors that can be used to satisfy the expected type.
Invoking "List Constructors" ("Show the list of constructors of the expected type")
in the following hole:
```lean
def foo : ℤ ⊕ ℕ :=
{! !}
```
produces:
```lean
def foo : ℤ ⊕ ℕ :=
{! sum.inl, sum.inr !}
```
and will display:
```lean
sum.inl : ℤ → ℤ ⊕ ℕ
sum.inr : ℕ → ℤ ⊕ ℕ
```
-/
@[hole_command] meta def list_constructors_hole : hole_command :=
{ name := "List Constructors",
descr := "Show the list of constructors of the expected type.",
action := λ es,
do t ← target >>= whnf,
(_,t) ← open_pis t,
let cl := t.get_app_fn.const_name,
let args := t.get_app_args,
env ← get_env,
let cs := env.constructors_of cl,
ts ← cs.mmap $ λ c,
do { e ← mk_const c,
t ← infer_type (e.mk_app args) >>= pp,
c ← strip_prefix c,
pure format!"\n{c} : {t}\n" },
fs ← format.intercalate ", " <$> cs.mmap (strip_prefix >=> pure ∘ to_fmt),
let out := format.to_string format!"{{! {fs} !}",
trace (format.join ts).to_string,
return [(out,"")] }
add_tactic_doc
{ name := "List Constructors",
category := doc_category.hole_cmd,
decl_names := [`tactic.list_constructors_hole],
tags := ["goal information"] }
/-- Makes the declaration `classical.prop_decidable` available to type class inference.
This asserts that all propositions are decidable, but does not have computational content. -/
meta def classical : tactic unit :=
do h ← get_unused_name `_inst,
mk_const `classical.prop_decidable >>= note h none,
reset_instance_cache
open expr
/-- `mk_comp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so,
returns the expression `f ∘ g ∘ h`. -/
meta def mk_comp (v : expr) : expr → tactic expr
| (app f e) :=
if e = v then pure f
else do
guard (¬ v.occurs f) <|> fail "bad guard",
e' ← mk_comp e >>= instantiate_mvars,
f ← instantiate_mvars f,
mk_mapp ``function.comp [none,none,none,f,e']
| e :=
do guard (e = v),
t ← infer_type e,
mk_mapp ``id [t]
/-- Given two expressions `e₀` and `e₁`, return the expression `` `(%%e₀ ↔ %%e₁)``. -/
meta def mk_iff (e₀ : expr) (e₁ : expr) : expr := `(%%e₀ ↔ %%e₁)
/--
From a lemma of the shape `∀ x, f (g x) = h x`
derive an auxiliary lemma of the form `f ∘ g = h`
for reasoning about higher-order functions.
-/
meta def mk_higher_order_type : expr → tactic expr
| (pi n bi d b@(pi _ _ _ _)) :=
do v ← mk_local_def n d,
let b' := (b.instantiate_var v),
(pi n bi d ∘ flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b'
| (pi n bi d b) :=
do v ← mk_local_def n d,
let b' := (b.instantiate_var v),
(l,r) ← match_eq b' <|> fail format!"not an equality {b'}",
l' ← mk_comp v l,
r' ← mk_comp v r,
mk_app ``eq [l',r']
| e := failed
open lean.parser interactive.types
/-- A user attribute that applies to lemmas of the shape `∀ x, f (g x) = h x`.
It derives an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions.
-/
@[user_attribute]
meta def higher_order_attr : user_attribute unit (option name) :=
{ name := `higher_order,
parser := optional ident,
descr :=
"From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the
form `f ∘ g = h` for reasoning about higher-order functions.",
after_set := some $ λ lmm _ _,
do env ← get_env,
decl ← env.get lmm,
let num := decl.univ_params.length,
let lvls := (list.iota num).map (`l).append_after,
let l : expr := expr.const lmm $ lvls.map level.param,
t ← infer_type l >>= instantiate_mvars,
t' ← mk_higher_order_type t,
(_,pr) ← solve_aux t' $ do {
intros, applyc ``_root_.funext, intro1, applyc lmm; assumption },
pr ← instantiate_mvars pr,
lmm' ← higher_order_attr.get_param lmm,
lmm' ← (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure lmm.add_prime,
add_decl $ declaration.thm lmm' lvls t' (pure pr),
copy_attribute `simp lmm lmm',
copy_attribute `functor_norm lmm lmm' }
add_tactic_doc
{ name := "higher_order",
category := doc_category.attr,
decl_names := [`tactic.higher_order_attr],
tags := ["lemma derivation"] }
attribute [higher_order map_comp_pure] map_pure
/--
Copies a definition into the `tactic.interactive` namespace to make it usable
in proof scripts. It allows one to write
```lean
@[interactive]
meta def my_tactic := ...
```
instead of
```lean
meta def my_tactic := ...
run_cmd add_interactive [``my_tactic]
```
-/
@[user_attribute]
meta def interactive_attr : user_attribute :=
{ name := `interactive,
descr :=
"Put a definition in the `tactic.interactive` namespace to make it usable
in proof scripts.",
after_set := some $ λ tac _ _, add_interactive [tac] }
add_tactic_doc
{ name := "interactive",
category := doc_category.attr,
decl_names := [``tactic.interactive_attr],
tags := ["environment"] }
/--
Use `refine` to partially discharge the goal,
or call `fconstructor` and try again.
-/
private meta def use_aux (h : pexpr) : tactic unit :=
(focus1 (refine h >> done)) <|> (fconstructor >> use_aux)
/-- Similar to `existsi`, `use l` will use entries in `l` to instantiate existential obligations
at the beginning of a target. Unlike `existsi`, the pexprs in `l` are elaborated with respect to
the expected type.
```lean
example : ∃ x : ℤ, x = x :=
by tactic.use ``(42)
```
See the doc string for `tactic.interactive.use` for more information.
-/
protected meta def use (l : list pexpr) : tactic unit :=
focus1 $ seq' (l.mmap' $ λ h, use_aux h <|> fail format!"failed to instantiate goal with {h}")
instantiate_mvars_in_target
/-- `clear_aux_decl_aux l` clears all expressions in `l` that represent aux decls from the
local context. -/
meta def clear_aux_decl_aux : list expr → tactic unit
| [] := skip
| (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l
/-- `clear_aux_decl` clears all expressions from the local context that represent aux decls. -/
meta def clear_aux_decl : tactic unit :=
local_context >>= clear_aux_decl_aux
/-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`)
finds a list of expressions `vs` and returns `(e.mk_args (vs ++ [h]), vs)`. -/
meta def apply_at_aux (arg t : expr) : list expr → expr → expr → tactic (expr × list expr)
| vs e (pi n bi d b) :=
do { v ← mk_meta_var d,
apply_at_aux (v :: vs) (e v) (b.instantiate_var v) } <|>
(e arg, vs) <$ unify d t
| vs e _ := failed
/-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result. -/
meta def apply_at (e h : expr) : tactic unit :=
do ht ← infer_type h,
et ← infer_type e,
(h', gs') ← apply_at_aux h ht [] e et,
note h.local_pp_name none h',
clear h,
gs' ← gs'.mfilter is_assigned,
(g :: gs) ← get_goals,
set_goals (g :: gs' ++ gs)
/-- `symmetry_hyp h` applies `symmetry` on hypothesis `h`. -/
meta def symmetry_hyp (h : expr) (md := semireducible) : tactic unit :=
do tgt ← infer_type h,
env ← get_env,
let r := get_app_fn tgt,
match env.symm_for (const_name r) with
| (some symm) := do s ← mk_const symm,
apply_at s h
| none := fail
"symmetry tactic failed, target is not a relation application with the expected property."
end
/-- `setup_tactic_parser` is a user command that opens the namespaces used in writing
interactive tactics, and declares the local postfix notation `?` for `optional` and `*` for `many`.
It does *not* use the `namespace` command, so it will typically be used after
`namespace tactic.interactive`.
-/
@[user_command]
meta def setup_tactic_parser_cmd (_ : interactive.parse $ tk "setup_tactic_parser") :
lean.parser unit :=
emit_code_here "
open lean
open lean.parser
open interactive interactive.types
local postfix `?`:9001 := optional
local postfix *:9001 := many .
"
/-- `finally tac finalizer` runs `tac` first, then runs `finalizer` even if
`tac` fails. `finally tac finalizer` fails if either `tac` or `finalizer` fails. -/
meta def finally {β} (tac : tactic α) (finalizer : tactic β) : tactic α :=
λ s, match tac s with
| (result.success r s') := (finalizer >> pure r) s'
| (result.exception msg p s') := (finalizer >> result.exception msg p) s'
end
/--
`on_exception handler tac` runs `tac` first, and then runs `handler` only if `tac` failed.
-/
meta def on_exception {β} (handler : tactic β) (tac : tactic α) : tactic α | s :=
match tac s with
| result.exception msg p s' := (handler *> result.exception msg p) s'
| ok := ok
end
/-- `decorate_error add_msg tac` prepends `add_msg` to an exception produced by `tac` -/
meta def decorate_error (add_msg : string) (tac : tactic α) : tactic α | s :=
match tac s with
| result.exception msg p s :=
let msg (_ : unit) : format := match msg with
| some msg := add_msg ++ format.line ++ msg ()
| none := add_msg
end in
result.exception msg p s
| ok := ok
end
/-- Applies tactic `t`. If it succeeds, revert the state, and return the value. If it fails,
returns the error message. -/
meta def retrieve_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) :=
λ s, match t s with
| (interaction_monad.result.success a s') := result.success (sum.inl a) s
| (interaction_monad.result.exception msg' _ s') :=
result.success (sum.inr (msg'.iget ()).to_string) s
end
/-- Applies tactic `t`. If it succeeds, return the value. If it fails, returns the error message. -/
meta def try_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) :=
λ s, match t s with
| (interaction_monad.result.success a s') := result.success (sum.inl a) s'
| (interaction_monad.result.exception msg' _ s') :=
result.success (sum.inr (msg'.iget ()).to_string) s
end
/-- This tactic succeeds if `t` succeeds or fails with message `msg` such that `p msg` is `tt`.
-/
meta def succeeds_or_fails_with_msg {α : Type} (t : tactic α) (p : string → bool) : tactic unit :=
do x ← retrieve_or_report_error t,
match x with
| (sum.inl _) := skip
| (sum.inr msg) := if p msg then skip else fail msg
end
add_tactic_doc
{ name := "setup_tactic_parser",
category := doc_category.cmd,
decl_names := [`tactic.setup_tactic_parser_cmd],
tags := ["parsing", "notation"] }
/-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message
of `t`. -/
meta def trace_error (msg : string) (t : tactic α) : tactic α
| s := match t s with
| (result.success r s') := result.success r s'
| (result.exception (some msg') p s') := (trace msg >> trace (msg' ()) >> result.exception
(some msg') p) s'
| (result.exception none p s') := result.exception none p s'
end
/--
``trace_if_enabled `n msg`` traces the message `msg`
only if tracing is enabled for the name `n`.
Create new names registered for tracing with `declare_trace n`.
Then use `set_option trace.n true/false` to enable or disable tracing for `n`.
-/
meta def trace_if_enabled
(n : name) {α : Type u} [has_to_tactic_format α] (msg : α) : tactic unit :=
when_tracing n (trace msg)
/--
``trace_state_if_enabled `n msg`` prints the tactic state,
preceded by the optional string `msg`,
only if tracing is enabled for the name `n`.
-/
meta def trace_state_if_enabled
(n : name) (msg : string := "") : tactic unit :=
when_tracing n ((if msg = "" then skip else trace msg) >> trace_state)
/--
This combinator is for testing purposes. It succeeds if `t` fails with message `msg`,
and fails otherwise.
-/
meta def success_if_fail_with_msg {α : Type u} (t : tactic α) (msg : string) : tactic unit :=
λ s, match t s with
| (interaction_monad.result.exception msg' _ s') :=
let expected_msg := (msg'.iget ()).to_string in
if msg = expected_msg then result.success () s
else mk_exception format!"failure messages didn't match. Expected:\n{expected_msg}" none s
| (interaction_monad.result.success a s) :=
mk_exception "success_if_fail_with_msg combinator failed, given tactic succeeded" none s
end
/--
Construct a `Try this: refine ...` or `Try this: exact ...` string which would construct `g`.
-/
meta def tactic_statement (g : expr) : tactic string :=
do g ← instantiate_mvars g,
g ← head_beta g,
r ← pp (replace_mvars g),
if g.has_meta_var
then return (sformat!"Try this: refine {r}")
else return (sformat!"Try this: exact {r}")
/-- `with_local_goals gs tac` runs `tac` on the goals `gs` and then restores the
initial goals and returns the goals `tac` ended on. -/
meta def with_local_goals {α} (gs : list expr) (tac : tactic α) : tactic (α × list expr) :=
do gs' ← get_goals,
set_goals gs,
finally (prod.mk <$> tac <*> get_goals) (set_goals gs')
/-- like `with_local_goals` but discards the resulting goals -/
meta def with_local_goals' {α} (gs : list expr) (tac : tactic α) : tactic α :=
prod.fst <$> with_local_goals gs tac
/-- Representation of a proof goal that lends itself to comparison. The
following goal:
```lean
l₀ : T,
l₁ : T
⊢ ∀ v : T, foo
```
is represented as
```
(2, ∀ l₀ l₁ v : T, foo)
```
The number 2 indicates that first the two bound variables of the
`∀` are actually local constant. Comparing two such goals with `=`
rather than `=ₐ` or `is_def_eq` tells us that proof script should
not see the difference between the two.
-/
meta def packaged_goal := ℕ × expr
/-- proof state made of multiple `goal` meant for comparing
the result of running different tactics -/
meta def proof_state := list packaged_goal
meta instance goal.inhabited : inhabited packaged_goal := ⟨(0,var 0)⟩
meta instance proof_state.inhabited : inhabited proof_state :=
(infer_instance : inhabited (list packaged_goal))
/-- create a `packaged_goal` corresponding to the current goal -/
meta def get_packaged_goal : tactic packaged_goal := do
ls ← local_context,
tgt ← target >>= instantiate_mvars,
tgt ← pis ls tgt,
pure (ls.length, tgt)
/-- `goal_of_mvar g`, with `g` a meta variable, creates a
`packaged_goal` corresponding to `g` interpretted as a proof goal -/
meta def goal_of_mvar (g : expr) : tactic packaged_goal :=
with_local_goals' [g] get_packaged_goal
/-- `get_proof_state` lists the user visible goal for each goal
of the current state and for each goal, abstracts all of the
meta variables of the other gaols.
This produces a list of goals in the form of `ℕ × expr` where
the `expr` encodes the following proof state:
```lean
2 goals
l₁ : t₁,
l₂ : t₂,
l₃ : t₃
⊢ tgt₁
⊢ tgt₂
```
as
```lean
[ (3, ∀ (mv : tgt₁) (mv : tgt₂) (l₁ : t₁) (l₂ : t₂) (l₃ : t₃), tgt₁),
(0, ∀ (mv : tgt₁) (mv : tgt₂), tgt₂) ]
```
with 2 goals, the first 2 bound variables encode the meta variable
of all the goals, the next 3 (in the first goal) and 0 (in the second goal)
are the local constants.
This representation allows us to compare goals and proof states while
ignoring information like the unique name of local constants and
the equality or difference of meta variables that encode the same goal.
-/
meta def get_proof_state : tactic proof_state :=
do gs ← get_goals,
gs.mmap $ λ g, do
⟨n,g⟩ ← goal_of_mvar g,
g ← gs.mfoldl (λ g v, do
g ← kabstract g v reducible ff,
pure $ pi `goal binder_info.default `(true) g ) g,
pure (n,g)
/--
Run `tac` in a disposable proof state and return the state.
See `proof_state`, `goal` and `get_proof_state`.
-/
meta def get_proof_state_after (tac : tactic unit) : tactic (option proof_state) :=
try_core $ retrieve $ tac >> get_proof_state
open lean interactive
/-- A type alias for `tactic format`, standing for "pretty print format". -/
meta def pformat := tactic format
/-- `mk` lifts `fmt : format` to the tactic monad (`pformat`). -/
meta def pformat.mk (fmt : format) : pformat := pure fmt
/-- an alias for `pp`. -/
meta def to_pfmt {α} [has_to_tactic_format α] (x : α) : pformat :=
pp x
meta instance pformat.has_to_tactic_format : has_to_tactic_format pformat :=
⟨ id ⟩
meta instance : has_append pformat :=
⟨ λ x y, (++) <$> x <*> y ⟩
meta instance tactic.has_to_tactic_format [has_to_tactic_format α] :
has_to_tactic_format (tactic α) :=
⟨ λ x, x >>= to_pfmt ⟩
private meta def parse_pformat : string → list char → parser pexpr
| acc [] := pure ``(to_pfmt %%(reflect acc))
| acc ('\n'::s) :=
do f ← parse_pformat "" s,
pure ``(to_pfmt %%(reflect acc) ++ pformat.mk format.line ++ %%f)
| acc ('{'::'{'::s) := parse_pformat (acc ++ "{") s
| acc ('{'::s) :=
do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string,
'}'::s ← return s.to_list | fail "'}' expected",
f ← parse_pformat "" s,
pure ``(to_pfmt %%(reflect acc) ++ to_pfmt %%e ++ %%f)
| acc (c::s) := parse_pformat (acc.str c) s
/-- See `format!` in `init/meta/interactive_base.lean`.
The main differences are that `pp` is called instead of `to_fmt` and that we can use
arguments of type `tactic α` in the quotations.
Now, consider the following:
```lean
e ← to_expr ``(3 + 7),
trace format!"{e}" -- outputs `has_add.add.{0} nat nat.has_add
-- (bit1.{0} nat nat.has_one nat.has_add (has_one.one.{0} nat nat.has_one)) ...`
trace pformat!"{e}" -- outputs `3 + 7`
```
The difference is significant. And now, the following is expressible:
```lean
e ← to_expr ``(3 + 7),
trace pformat!"{e} : {infer_type e}" -- outputs `3 + 7 : ℕ`
```
See also: `trace!` and `fail!`
-/
@[user_notation]
meta def pformat_macro (_ : parse $ tk "pformat!") (s : string) : parser pexpr :=
do e ← parse_pformat "" s.to_list,
return ``(%%e : pformat)
/--
The combination of `pformat` and `fail`.
-/
@[user_notation]
meta def fail_macro (_ : parse $ tk "fail!") (s : string) : parser pexpr :=
do e ← pformat_macro () s,
pure ``((%%e : pformat) >>= fail)
/--
The combination of `pformat` and `trace`.
-/
@[user_notation]
meta def trace_macro (_ : parse $ tk "trace!") (s : string) : parser pexpr :=
do e ← pformat_macro () s,
pure ``((%%e : pformat) >>= trace)
/-- A hackish way to get the `src` directory of mathlib. -/
meta def get_mathlib_dir : tactic string :=
do e ← get_env,
s ← e.decl_olean `tactic.reset_instance_cache,
return $ s.popn_back 17
/-- Checks whether a declaration with the given name is declared in mathlib.
If you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead,
since it is expensive to execute `get_mathlib_dir` many times. -/
meta def is_in_mathlib (n : name) : tactic bool :=
do ml ← get_mathlib_dir, e ← get_env, return $ e.is_prefix_of_file ml n
/--
Runs a tactic by name.
If it is a `tactic string`, return whatever string it returns.
If it is a `tactic unit`, return the name.
(This is mostly used in invoking "self-reporting tactics", e.g. by `tidy` and `hint`.)
-/
meta def name_to_tactic (n : name) : tactic string :=
do d ← get_decl n,
e ← mk_const n,
let t := d.type,
if (t =ₐ `(tactic unit)) then
(eval_expr (tactic unit) e) >>= (λ t, t >> (name.to_string <$> strip_prefix n))
else if (t =ₐ `(tactic string)) then
(eval_expr (tactic string) e) >>= (λ t, t)
else fail!"name_to_tactic cannot take `{n} as input: its type must be `tactic string` or `tactic unit`"
/-- auxiliary function for `apply_under_n_pis` -/
private meta def apply_under_n_pis_aux (func arg : pexpr) : ℕ → ℕ → expr → pexpr
| n 0 _ :=
let vars := ((list.range n).reverse.map (@expr.var ff)),
bd := vars.foldl expr.app arg.mk_explicit in
func bd
| n (k+1) (expr.pi nm bi tp bd) := expr.pi nm bi (pexpr.of_expr tp)
(apply_under_n_pis_aux (n+1) k bd)
| n (k+1) t := apply_under_n_pis_aux n 0 t
/--
Assumes `pi_expr` is of the form `Π x1 ... xn xn+1..., _`.
Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`.
All arguments (implicit and explicit) to `arg` should be supplied. -/
meta def apply_under_n_pis (func arg : pexpr) (pi_expr : expr) (n : ℕ) : pexpr :=
apply_under_n_pis_aux func arg 0 n pi_expr
/--
Assumes `pi_expr` is of the form `Π x1 ... xn, _`.
Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`.
All arguments (implicit and explicit) to `arg` should be supplied. -/
meta def apply_under_pis (func arg : pexpr) (pi_expr : expr) : pexpr :=
apply_under_n_pis func arg pi_expr pi_expr.pi_arity
/--
If `func` is a `pexpr` representing a function that takes an argument `a`,
`get_pexpr_arg_arity_with_tgt func tgt` returns the arity of `a`.
When `tgt` is a `pi` expr, `func` is elaborated in a context
with the domain of `tgt`.
Examples:
* ```get_pexpr_arg_arity ``(ring) `(true)``` returns 0, since `ring` takes one non-function
argument.
* ```get_pexpr_arg_arity_with_tgt ``(monad) `(true)``` returns 1, since `monad` takes one argument
of type `α → α`.
* ```get_pexpr_arg_arity_with_tgt ``(module R) `(Π (R : Type), comm_ring R → true)``` returns 0
-/
meta def get_pexpr_arg_arity_with_tgt (func : pexpr) (tgt : expr) : tactic ℕ :=
lock_tactic_state $ do
mv ← mk_mvar,
solve_aux tgt $ intros >> to_expr ``(%%func %%mv),
expr.pi_arity <$> (infer_type mv >>= instantiate_mvars)
/-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files.
`find_private_decl n (some m)` finds a private declaration named `n` in the same file where a
declaration named `m` can be found. -/
meta def find_private_decl (n : name) (fr : option name) : tactic name :=
do env ← get_env,
fn ← option_t.run (do
fr ← option_t.mk (return fr),
d ← monad_lift $ get_decl fr,
option_t.mk (return $ env.decl_olean d.to_name) ),
let p : string → bool :=
match fn with
| (some fn) := λ x, fn = x
| none := λ _, tt
end,
let xs := env.decl_filter_map (λ d,
do fn ← env.decl_olean d.to_name,
guard ((`_private).is_prefix_of d.to_name ∧ p fn ∧
d.to_name.update_prefix name.anonymous = n),
pure d.to_name),
match xs with
| [n] := pure n
| [] := fail "no such private found"
| _ := fail "many matches found"
end
open lean.parser interactive
/-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar`
and creates a local notation to refer to it.
`import_private foo` looks for `foo` in all imported files.
When possible, make `foo` non-private rather than using this feature.
-/
@[user_command]
meta def import_private_cmd (_ : parse $ tk "import_private") : lean.parser unit :=
do n ← ident,
fr ← optional (tk "from" *> ident),
n ← find_private_decl n fr,
c ← resolve_constant n,
d ← get_decl n,
let c := @expr.const tt c d.univ_levels,
new_n ← new_aux_decl_name,
add_decl $ declaration.defn new_n d.univ_params d.type c reducibility_hints.abbrev d.is_trusted,
let new_not := sformat!"local notation `{n.update_prefix name.anonymous}` := {new_n}",
emit_command_here $ new_not,
skip .
add_tactic_doc
{ name := "import_private",
category := doc_category.cmd,
decl_names := [`tactic.import_private_cmd],
tags := ["renaming"] }
/--
The command `mk_simp_attribute simp_name "description"` creates a simp set with name `simp_name`.
Lemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called.
`mk_simp_attribute simp_name none` will use a default description.
Appending the command with `with attr1 attr2 ...` will include all declarations tagged with
`attr1`, `attr2`, ... in the new simp set.
This command is preferred to using ``run_cmd mk_simp_attr `simp_name`` since it adds a doc string
to the attribute that is defined. If you need to create a simp set in a file where this command is
not available, you should use
```lean
run_cmd mk_simp_attr `simp_name
run_cmd add_doc_string `simp_attr.simp_name "Description of the simp set here"
```
-/
@[user_command]
meta def mk_simp_attribute_cmd (_ : parse $ tk "mk_simp_attribute") : lean.parser unit :=
do n ← ident,
d ← parser.pexpr,
d ← to_expr ``(%%d : option string),
descr ← eval_expr (option string) d,
with_list ← types.with_ident_list <|> return [],
mk_simp_attr n with_list,
add_doc_string (name.append `simp_attr n) $ descr.get_or_else $ "simp set for " ++ to_string n
add_tactic_doc
{ name := "mk_simp_attribute",
category := doc_category.cmd,
decl_names := [`tactic.mk_simp_attribute_cmd],
tags := ["simplification"] }
/--
Given a user attribute name `attr_name`, `get_user_attribute_name attr_name` returns
the name of the declaration that defines this attribute.
Fails if there is no user attribute with this name.
Example: ``get_user_attribute_name `norm_cast`` returns `` `norm_cast.norm_cast_attr`` -/
meta def get_user_attribute_name (attr_name : name) : tactic name := do
ns ← attribute.get_instances `user_attribute,
ns.mfirst (λ nm, do
d ← get_decl nm,
e ← mk_app `user_attribute.name [d.value],
attr_nm ← eval_expr name e,
guard $ attr_nm = attr_name,
return nm) <|> fail!"'{attr_name}' is not a user attribute."
/-- A tactic to set either a basic attribute or a user attribute.
If the the user attribute has a parameter, the default value will be used.
This tactic raises an error if there is no `inhabited` instance for the parameter type. -/
meta def set_attribute (attr_name : name) (c_name : name) (persistent := tt)
(prio : option nat := none) : tactic unit := do
get_decl c_name <|> fail!"unknown declaration {c_name}",
s ← try_or_report_error (set_basic_attribute attr_name c_name persistent prio),
sum.inr msg ← return s | skip,
if msg =
(format!"set_basic_attribute tactic failed, '{attr_name}' is not a basic attribute").to_string
then do
user_attr_nm ← get_user_attribute_name attr_name,
user_attr_const ← mk_const user_attr_nm,
tac ← eval_pexpr (tactic unit)
``(user_attribute.set %%user_attr_const %%c_name (default _) %%persistent) <|>
fail!"Cannot set attribute @[{attr_name}]. The corresponding user attribute {user_attr_nm} has a parameter without a default value.
Solution: provide an `inhabited` instance.",
tac
else fail msg
end tactic
/--
`find_defeq red m e` looks for a key in `m` that is defeq to `e` (up to transparency `red`),
and returns the value associated with this key if it exists.
Otherwise, it fails.
-/
meta def list.find_defeq (red : tactic.transparency) {v} (m : list (expr × v)) (e : expr) :
tactic (expr × v) :=
m.mfind $ λ ⟨e', val⟩, tactic.is_def_eq e e' red
|
edc91649f7f624b98852939a8196ac61ee25ae96 | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/algebra/char_zero.lean | 72396151061de31b44d20fe4b4a30c6467f4630a | [
"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 | 6,046 | lean | /-
Copyright (c) 2014 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.nat.cast
import data.fintype.basic
import tactic.wlog
/-!
# Characteristic zero
A ring `R` is called of characteristic zero if every natural number `n` is non-zero when considered
as an element of `R`. Since this definition doesn't mention the multiplicative structure of `R`
except for the existence of `1` in this file characteristic zero is defined for additive monoids
with `1`.
## Main definition
`char_zero` is the typeclass of an additive monoid with one such that the natural homomorphism
from the natural numbers into it is injective.
## Main statements
* A linearly ordered semiring has characteristic zero.
* Characteristic zero implies that the additive monoid is infinite.
## TODO
* Once order of a group is defined for infinite additive monoids redefine or at least connect to
order of `1` in the additive monoid with one.
* Unify with `char_p` (possibly using an out-parameter)
-/
/-- Typeclass for monoids with characteristic zero.
(This is usually stated on fields but it makes sense for any additive monoid with 1.) -/
class char_zero (R : Type*) [add_monoid R] [has_one R] : Prop :=
(cast_injective : function.injective (coe : ℕ → R))
theorem char_zero_of_inj_zero {R : Type*} [add_left_cancel_monoid R] [has_one R]
(H : ∀ n:ℕ, (n:R) = 0 → n = 0) : char_zero R :=
⟨λ m n, begin
assume h,
wlog hle : m ≤ n,
rcases nat.le.dest hle with ⟨k, rfl⟩,
rw [nat.cast_add, eq_comm, add_right_eq_self] at h,
rw [H k h, add_zero]
end⟩
/-- Note this is not an instance as `char_zero` implies `nontrivial`,
and this would risk forming a loop. -/
lemma ordered_semiring.to_char_zero {R : Type*} [ordered_semiring R] [nontrivial R] :
char_zero R :=
⟨nat.strict_mono_cast.injective⟩
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_semiring.to_char_zero {R : Type*}
[linear_ordered_semiring R] : char_zero R :=
ordered_semiring.to_char_zero
namespace nat
variables {R : Type*} [add_monoid R] [has_one R] [char_zero R]
theorem cast_injective : function.injective (coe : ℕ → R) :=
char_zero.cast_injective
@[simp, norm_cast] theorem cast_inj {m n : ℕ} : (m : R) = n ↔ m = n :=
cast_injective.eq_iff
@[simp, norm_cast] theorem cast_eq_zero {n : ℕ} : (n : R) = 0 ↔ n = 0 :=
by rw [← cast_zero, cast_inj]
@[norm_cast] theorem cast_ne_zero {n : ℕ} : (n : R) ≠ 0 ↔ n ≠ 0 :=
not_congr cast_eq_zero
lemma cast_add_one_ne_zero (n : ℕ) : (n + 1 : R) ≠ 0 :=
by exact_mod_cast n.succ_ne_zero
@[simp, norm_cast]
theorem cast_dvd_char_zero {k : Type*} [field k] [char_zero k] {m n : ℕ}
(n_dvd : n ∣ m) : ((m / n : ℕ) : k) = m / n :=
begin
by_cases hn : n = 0,
{ subst hn,
simp },
{ exact cast_dvd n_dvd (cast_ne_zero.mpr hn), },
end
end nat
section
variables (M : Type*) [add_monoid M] [has_one M] [char_zero M]
@[priority 100] -- see Note [lower instance priority]
instance char_zero.infinite : infinite M :=
infinite.of_injective coe nat.cast_injective
variable {M}
@[field_simps] lemma two_ne_zero' : (2:M) ≠ 0 :=
have ((2:ℕ):M) ≠ 0, from nat.cast_ne_zero.2 dec_trivial,
by rwa [nat.cast_two] at this
end
section
variables {R : Type*} [semiring R] [no_zero_divisors R] [char_zero R]
@[simp]
lemma add_self_eq_zero {a : R} : a + a = 0 ↔ a = 0 :=
by simp only [(two_mul a).symm, mul_eq_zero, two_ne_zero', false_or]
@[simp]
lemma bit0_eq_zero {a : R} : bit0 a = 0 ↔ a = 0 := add_self_eq_zero
@[simp]
lemma zero_eq_bit0 {a : R} : 0 = bit0 a ↔ a = 0 :=
by { rw [eq_comm], exact bit0_eq_zero }
end
section
variables {R : Type*} [ring R] [no_zero_divisors R] [char_zero R]
lemma nat_mul_inj {n : ℕ} {a b : R} (h : (n : R) * a = (n : R) * b) : n = 0 ∨ a = b :=
begin
rw [←sub_eq_zero, ←mul_sub, mul_eq_zero, sub_eq_zero] at h,
exact_mod_cast h,
end
lemma nat_mul_inj' {n : ℕ} {a b : R} (h : (n : R) * a = (n : R) * b) (w : n ≠ 0) : a = b :=
by simpa [w] using nat_mul_inj h
lemma bit0_injective : function.injective (bit0 : R → R) :=
λ a b h, begin
dsimp [bit0] at h,
simp only [(two_mul a).symm, (two_mul b).symm] at h,
refine nat_mul_inj' _ two_ne_zero,
exact_mod_cast h,
end
lemma bit1_injective : function.injective (bit1 : R → R) :=
λ a b h, begin
simp only [bit1, add_left_inj] at h,
exact bit0_injective h,
end
@[simp] lemma bit0_eq_bit0 {a b : R} : bit0 a = bit0 b ↔ a = b :=
bit0_injective.eq_iff
@[simp] lemma bit1_eq_bit1 {a b : R} : bit1 a = bit1 b ↔ a = b :=
bit1_injective.eq_iff
@[simp]
lemma bit1_eq_one {a : R} : bit1 a = 1 ↔ a = 0 :=
by rw [show (1 : R) = bit1 0, by simp, bit1_eq_bit1]
@[simp]
lemma one_eq_bit1 {a : R} : 1 = bit1 a ↔ a = 0 :=
by { rw [eq_comm], exact bit1_eq_one }
end
section
variables {R : Type*} [division_ring R] [char_zero R]
@[simp] lemma half_add_self (a : R) : (a + a) / 2 = a :=
by rw [← mul_two, mul_div_cancel a two_ne_zero']
@[simp] lemma add_halves' (a : R) : a / 2 + a / 2 = a :=
by rw [← add_div, half_add_self]
lemma sub_half (a : R) : a - a / 2 = a / 2 :=
by rw [sub_eq_iff_eq_add, add_halves']
lemma half_sub (a : R) : a / 2 - a = - (a / 2) :=
by rw [← neg_sub, sub_half]
end
namespace with_top
instance {R : Type*} [add_monoid R] [has_one R] [char_zero R] : char_zero (with_top R) :=
{ cast_injective := λ m n h, by rwa [← coe_nat, ← coe_nat n, coe_eq_coe, nat.cast_inj] at h }
end with_top
section ring_hom
variables {R S : Type*} [semiring R] [semiring S]
lemma ring_hom.char_zero (ϕ : R →+* S) [hS : char_zero S] : char_zero R :=
⟨λ a b h, char_zero.cast_injective (by rw [←ϕ.map_nat_cast, ←ϕ.map_nat_cast, h])⟩
lemma ring_hom.char_zero_iff {ϕ : R →+* S} (hϕ : function.injective ϕ) :
char_zero R ↔ char_zero S :=
⟨λ hR, ⟨λ a b h, by rwa [←@nat.cast_inj R _ _ hR, ←hϕ.eq_iff, ϕ.map_nat_cast, ϕ.map_nat_cast]⟩,
λ hS, by exactI ϕ.char_zero⟩
end ring_hom
|
709f2a9bbe2da412bb3a55f3467b51a4ffc5e923 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/polynomial/integral_normalization_auto.lean | 6d809a779520f3fac7a2520a251a7e31551577a5 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,095 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.polynomial.algebra_map
import Mathlib.data.polynomial.monic
import Mathlib.PostPort
universes u v
namespace Mathlib
/-!
# Theory of monic polynomials
We define `integral_normalization`, which relate arbitrary polynomials to monic ones.
-/
namespace polynomial
/-- If `f : polynomial R` is a nonzero polynomial with root `z`, `integral_normalization f` is
a monic polynomial with root `leading_coeff f * z`.
Moreover, `integral_normalization 0 = 0`.
-/
def integral_normalization {R : Type u} [semiring R] (f : polynomial R) : polynomial R :=
finsupp.on_finset (finsupp.support f)
(fun (i : ℕ) => ite (degree f = ↑i) 1 (coeff f i * leading_coeff f ^ (nat_degree f - 1 - i)))
sorry
theorem integral_normalization_coeff_degree {R : Type u} [semiring R] {f : polynomial R} {i : ℕ}
(hi : degree f = ↑i) : coeff (integral_normalization f) i = 1 :=
if_pos hi
theorem integral_normalization_coeff_nat_degree {R : Type u} [semiring R] {f : polynomial R}
(hf : f ≠ 0) : coeff (integral_normalization f) (nat_degree f) = 1 :=
integral_normalization_coeff_degree (degree_eq_nat_degree hf)
theorem integral_normalization_coeff_ne_degree {R : Type u} [semiring R] {f : polynomial R} {i : ℕ}
(hi : degree f ≠ ↑i) :
coeff (integral_normalization f) i = coeff f i * leading_coeff f ^ (nat_degree f - 1 - i) :=
if_neg hi
theorem integral_normalization_coeff_ne_nat_degree {R : Type u} [semiring R] {f : polynomial R}
{i : ℕ} (hi : i ≠ nat_degree f) :
coeff (integral_normalization f) i = coeff f i * leading_coeff f ^ (nat_degree f - 1 - i) :=
integral_normalization_coeff_ne_degree (degree_ne_of_nat_degree_ne (ne.symm hi))
theorem monic_integral_normalization {R : Type u} [semiring R] {f : polynomial R} (hf : f ≠ 0) :
monic (integral_normalization f) :=
sorry
@[simp] theorem support_integral_normalization {R : Type u} [integral_domain R] {f : polynomial R}
(hf : f ≠ 0) : finsupp.support (integral_normalization f) = finsupp.support f :=
sorry
theorem integral_normalization_eval₂_eq_zero {R : Type u} {S : Type v} [integral_domain R]
[comm_ring S] {p : polynomial R} (hp : p ≠ 0) (f : R →+* S) {z : S} (hz : eval₂ f z p = 0)
(inj : ∀ (x : R), coe_fn f x = 0 → x = 0) :
eval₂ f (z * coe_fn f (leading_coeff p)) (integral_normalization p) = 0 :=
sorry
theorem integral_normalization_aeval_eq_zero {R : Type u} {S : Type v} [integral_domain R]
[comm_ring S] [algebra R S] {f : polynomial R} (hf : f ≠ 0) {z : S}
(hz : coe_fn (aeval z) f = 0) (inj : ∀ (x : R), coe_fn (algebra_map R S) x = 0 → x = 0) :
coe_fn (aeval (z * coe_fn (algebra_map R S) (leading_coeff f))) (integral_normalization f) =
0 :=
integral_normalization_eval₂_eq_zero hf (algebra_map R S) hz inj
end Mathlib |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.