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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7ed161001bc584dec9d96dcc4507d66b493443d7 | 75c54c8946bb4203e0aaf196f918424a17b0de99 | /old/cohen_poset.lean | ab4f0e5c1be9bc24b61ebe355f96770eb33ed6b7 | [
"Apache-2.0"
] | permissive | urkud/flypitch | 261e2a45f1038130178575406df8aea78255ba77 | 2250f5eda14b6ef9fc3e4e1f4a9ac4005634de5c | refs/heads/master | 1,653,266,469,246 | 1,577,819,679,000 | 1,577,819,679,000 | 259,862,235 | 1 | 0 | Apache-2.0 | 1,588,147,244,000 | 1,588,147,244,000 | null | UTF-8 | Lean | false | false | 36,739 | lean | /-
Copyright (c) 2019 The Flypitch Project. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jesse Han, Floris van Doorn
-/
import .to_mathlib .pSet_ordinal data.pfun
-- local attribute [instance] classical.prop_decidable
/- The Cohen poset of finite partial functions (2^(2^ω)) × ω → 2 -/
/- The underlying type of the Cohen poset is the type of finite partial functions from (set $ set ω) × ω → Prop -/
variable {η : cardinal}
def cohen_poset := {f : ((pSet.ordinal.mk η.ord).type × ℕ) →. Prop | set.finite (pfun.dom f)}
-- TODO replace all instances of set $ set ℕ with a generic "B"
noncomputable instance B_decidable_eq : decidable_eq (set $ set ℕ) := λ _ _, classical.prop_decidable _
namespace pfun
/- Two partial functions are equal if their graphs are equal -/
lemma ext_graph {α β : Type*} (f g : α →. β) (h_graph : f.graph = g.graph) : f = g :=
pfun.ext $ λ _ _, iff_of_eq (congr_fun h_graph (_,_))
lemma graph_empty_iff_dom_empty {α β : Type*} (f : α →. β) : f.graph = ∅ ↔ f.dom = ∅ :=
begin
have := dom_iff_graph f,
split; intro; ext; safe, apply this, tidy
end
/- A functional graph is a univalent graph -/
def functional {α β : Type*} (Γ : set (α × β)) : Prop :=
∀ a b₁ b₂, (a, b₁) ∈ Γ → (a, b₂) ∈ Γ → b₁ = b₂
lemma congr_arg {α β : Type*} (f : α →. β) : ∀ {x} {y} (h₁ : x ∈ f.dom) (h₂ : y ∈ f.dom)
(h_eq : x = y), fn f x h₁ = fn f y h₂ :=
by intros; congr; assumption
lemma functional_subset {α β : Type*} (Γ Γ': set (α × β)) (h_Γ' : Γ' ⊆ Γ) (h_Γ : functional Γ) : functional Γ' :=
λ _ _ _ _ _, by apply h_Γ; tidy
/-- The graph of a pfun is always functional -/
lemma graph_functional {α β : Type*} (f : α →. β) : functional f.graph := by tidy
/-- Given a partial functional relation, turn it into a pfun -/
noncomputable def of_graph {α β : Type*} (Γ : set (α × β)) (h_Γ : functional Γ) : α →. β :=
λ a, ⟨∃ c ∈ Γ, (prod.fst c) = a, λ h, @prod.snd α β $ (classical.indefinite_description _ h).val⟩
lemma of_graph_property {α β : Type*} (Γ : set $ α × β) (h_Γ : functional Γ) (a : α) (h : ∃ c ∈ Γ, (prod.fst c) = a) : ∃ (H : Γ (classical.indefinite_description _ h)), (classical.indefinite_description _ h).val.fst = a :=
by apply (classical.indefinite_description _ h).property
lemma of_graph_get {α β : Type*} (Γ : set $ α × β) (h_Γ : functional Γ) (a : α) : ∀ h,
(of_graph Γ h_Γ a).get h = (classical.indefinite_description _ h).val.snd :=
by intro; refl
lemma of_graph_val {α β : Type*} (Γ : set $ α × β) (h_Γ : functional Γ) (a : α) (h : ∃ c ∈ Γ, (prod.fst c) = a) (c' ∈ Γ) (h' : c'.1 = a) :
@prod.snd α β (classical.indefinite_description _ h).val = c'.snd :=
begin
let c'', swap, change (prod.snd c'' = c'.snd),
apply h_Γ a, swap, convert H, ext, rwa[h'], refl,
have := (classical.indefinite_description _ h).property,
cases this with this1 this2, rw[<-this2], convert this1, ext; refl
end
@[simp]lemma graph_of_graph {α β : Type*} (Γ : set $ α × β) (h_Γ : functional Γ) : (of_graph Γ h_Γ).graph = Γ :=
begin
ext, rcases x with ⟨a,b⟩, dsimp[graph],
split; intro H, {cases H, induction H_h, cases H_w, cases H_w_h, induction H_w_h_h,
convert H_w_h_w, ext, refl, rw[of_graph_get], apply of_graph_val; try{assumption}; refl},
fsplit, {tidy}, rw[of_graph_get], apply @of_graph_val _ _ Γ _ a _ (a,b) _;
try{assumption}; refl
end
@[simp]lemma of_graph_graph {α β : Type*} {f : α →. β} : of_graph (f.graph) (graph_functional f) = f :=
by apply ext_graph; rw[graph_of_graph]
@[simp]lemma dom_of_graph {α β : Type*} (Γ : set $ α × β) (h_Γ : functional Γ) : (of_graph Γ h_Γ).dom = (prod.fst '' Γ) :=
begin
ext, split; intros, {tidy},
{cases a, cases a_h, cases a_w, induction a_h_right, dsimp at *, fsplit,
work_on_goal 0 { fsplit }, work_on_goal 2 {fsplit,
work_on_goal 0 { assumption }, refl }}
end
@[simp]lemma dom_of_graph_union {α β : Type*} (Γ : set $ α × β) (p : α × β) (h_Γ : functional Γ) (h_Γ' : functional $ Γ ∪ {p}) : (of_graph (Γ ∪ {p}) h_Γ').dom = (of_graph Γ h_Γ).dom ∪ {p.fst} :=
by simp[dom_of_graph, set.image_insert_eq]
lemma in_dom_of_in_graph {α β : Type*} {f : α →. β} : ∀ {a} {b}, (a,b) ∈ f.graph → a ∈ f.dom :=
by {intros a b H, apply (pfun.dom_iff_graph _ a).mpr, exact ⟨b,H⟩}
lemma lift_graph' {α β : Type*} {f : α →. β} {a : α} {b : β} (h_a : a ∈ f.dom) : (a,b) ∈ f.graph ↔ pfun.fn f a h_a = b := by tidy
end pfun
/- Partial order structure on the Cohen poset -/
instance partial_order_cohen_poset : partial_order (@cohen_poset η) :=
{ le := λ f g, g.val.graph ⊆ f.val.graph,
lt := λ f g, g.val.graph ⊆ f.val.graph ∧ ¬ f.val.graph ⊆ g.val.graph,
le_refl := λ _, by unfold has_le.le,
le_trans := by {intros, apply set.subset.trans, exact a_2, assumption},
lt_iff_le_not_le := λ _ _, iff.refl _,
le_antisymm := λ a b h1 h2, by {have := @set.subset.antisymm _ _ _ h2 h1, cases a, cases b,
congr, apply pfun.ext_graph, exact this}}
def incompatible {α : Type*} [partial_order α] (a b : α) := ¬ ∃ c, c ≤ a ∧ c ≤ b
def antichain {α : Type*} [partial_order α] (s : set α) := ∀ x ∈ s, ∀ y ∈ s, (x ≠ y) → incompatible x y
lemma antichain_subset {α : Type*} [partial_order α] {s s' : set α} {h : s' ⊆ s} {hs : antichain s} : antichain s' :=
by {intros _ _ _ _, intro H, apply hs _ _ _ _, tidy}
def countable_chain_condition (α : Type*) [partial_order α] := ∀ s : set α, antichain s → set.countable s
@[simp]lemma univ_singletons {α : Type*} : set.Union (λ a, {a}) = (set.univ : set α) :=
by tidy
lemma set_is_union_of_fibers {α β : Type*} (f : α → β) (s : set α) : s = set.Union (λ b, f ⁻¹'{b} ∩ s) := by ext; simp
lemma univ_is_union_of_fibers {α β : Type*} (f : α → β) : @set.univ α = set.Union (λ b, f⁻¹' {b}) :=
begin [smt] eblast_using [set.preimage_Union, @set.preimage_univ α β f, univ_singletons] end
lemma countable_of_injection_to_countable {α β : Type*} {s : set α} {s' : set β} (f : s → s') {hf : function.injective f} (h' : set.countable s') : set.countable s :=
begin
have := set.countable_iff_exists_injective.mp h', apply set.countable_iff_exists_injective.mpr,
cases this, refine ⟨this_w ∘ f,_⟩, exact function.injective_comp (this_h) hf
end
lemma countable_of_bijection_with_countable {α β : Type*} {s : set α} {s' : set β} {f : s → s'}
{hf : function.bijective f} {h' : set.countable s'} : set.countable s :=
begin
apply countable_of_injection_to_countable f, exact h', exact hf.left
end
lemma countable_of_equiv_with_countable {α β : Type*} {s : set α} {s' : set β}
{h : equiv s s'} {h' : set.countable s'} : set.countable s :=
by {apply countable_of_bijection_with_countable, apply h.bijective, exact h'}
lemma equiv_set_set_univ {α : Type*} (s : set α) : equiv s (@set.univ s) :=
by {refine ⟨λ x, ⟨x, (by trivial)⟩, λ x, x.val, _, _⟩, tidy}
/- an (s : set α) is countable if (set.univ : set s) is countable -/
lemma countable_of_countable_univ {α : Type*} (s : set α) : set.countable s ↔ set.countable (set.univ : set s) :=
begin
split; apply countable_of_equiv_with_countable, symmetry,
all_goals{apply equiv_set_set_univ}
end
lemma countable_of_countable_underlying_set {α : Type*} {s' : set α} {s : set α} {t : set s'} (h : s = (subtype.val '' t)) {h_ctbl : set.countable s} : set.countable t :=
begin
let f : t → s := λ x,
begin refine ⟨x.val, _⟩, rw[h], cases x, cases x_val, simp at *, fsplit; assumption end,
refine countable_of_injection_to_countable f (by assumption),
intros a₁ a₂ a, cases a₂, cases a₁, cases a₁_val, cases a₂_val, simp at *, assumption
end
lemma countable_of_countable_fibers {α β : Type*} (s : set α) (f : s → β) [encodable β] (H : ∀ b : β, set.countable (f ⁻¹' {b})) : set.countable s :=
by simp[countable_of_countable_univ, univ_is_union_of_fibers f, set.countable_Union H]
lemma countable_of_countable_fibers' {α β : Type*} (s : set α) (f : α → β) [encodable β] (H : ∀ b : β, set.countable ((f ⁻¹' {b}) ∩ s)) : set.countable s :=
by {rw[set_is_union_of_fibers f s], exact set.countable_Union H}
lemma countable_of_countable_fibers'' {α β : Type*} (s : set α) (f : s → β) [encodable β] (H : ∀ b : β, set.countable ((f ⁻¹' {b}))) : set.countable s :=
by simp[countable_of_countable_univ, univ_is_union_of_fibers f, set.countable_Union H]
lemma eq_true_of_provable {p : Prop} (h : p) : (p = true) := by simp[h]
lemma eq_false_of_provable_neg {p : Prop} (h : ¬ p) : (p = false) := by finish
@[reducible, simp]noncomputable def Prop_to_bool (p : Prop) : bool :=
by {haveI := classical.prop_decidable p, by_cases p, exact true, exact false}
@[simp]lemma Prop_to_bool_true : Prop_to_bool true = tt := by simp
@[simp]lemma Prop_to_bool_false : Prop_to_bool false = ff := by simp
noncomputable lemma equiv_Prop_bool : equiv Prop bool :=
begin
refine ⟨Prop_to_bool,by {intro b, cases b, exact false, exact true},_,_⟩,
{unfold function.left_inverse, intro p, haveI := classical.prop_decidable p, by_cases p,
rw[eq_true_of_provable h, Prop_to_bool_true],
rw[eq_false_of_provable_neg h, Prop_to_bool_false],},
{intro x, cases x; finish}
end
noncomputable instance Prop_encodable : encodable Prop :=
@encodable.of_equiv _ _ (by apply_instance) equiv_Prop_bool
noncomputable def size_of_domain : (@cohen_poset η) → ℕ :=
λ p, finset.card $ set.finite.to_finset p.property
lemma size_of_domain_fiber {n} {p : @cohen_poset η} (h : p ∈ @size_of_domain η ⁻¹' {n}) : size_of_domain p = n := by finish
/-- The partial function p is defined at b and m if (b,m) is in the domain of p -/
def is_defined (p : (@cohen_poset η)) (b) (m) := (b,m) ∈ (pfun.dom p.val)
/-- p is defined at m if there exists a b such that p is defined at b and m -/
def is_defined_at (m : ℕ) : set (@cohen_poset η) :=
{p : (@cohen_poset η) | ∃ b, is_defined p b m}
namespace finset
lemma empty_of_empty {α : Type*} {s : set α} {h : set.finite s} : set.finite.to_finset h = ∅ → s = ∅ :=
begin
intro H, rw[set.eq_empty_iff_forall_not_mem], intros x Hx,
suffices : x ∈ set.finite.to_finset h, by rw[H] at this; cases this, simpa[finset.mem_coe]
end
end finset
lemma empty_of_size_of_domain_0 {p : (@cohen_poset η)} (h : size_of_domain p = 0) : p.val.dom = ∅ :=
begin
have : set.finite.to_finset p.property = ∅, from finset.card_eq_zero.mp h,
exact finset.empty_of_empty this
end
lemma nonempty_of_size_of_domain_ne_zero {p : (@cohen_poset η)} (h : size_of_domain p ≠ 0) : nonempty p.val.dom :=
begin
have : set.finite.to_finset p.property ≠ ∅, by {intro h, suffices : (set.finite.to_finset p.property).card = 0,
by {apply (_root_.not_and_self ((set.finite.to_finset p.property).card = 0)).mp,refine ⟨(by assumption), this⟩},
exact finset.card_eq_zero.mpr h},
have := finset.exists_mem_of_ne_empty this, cases this, apply nonempty.intro,
refine ⟨this_w,_⟩, cases this_w, cases p, simp at this_h, assumption
end
lemma nonempty_domain_defined (p : (@cohen_poset η)) (h : 0 < size_of_domain p) : ∃ m,
is_defined_at m p :=
begin
suffices : nonempty p.val.dom, by {have := classical.choice this, cases this,
refine ⟨this_val.2, ⟨this_val.1,_⟩⟩, tidy}, apply nonempty_of_size_of_domain_ne_zero,
intro h', rw[h'] at h, cases h
end
-- def is_defined_at_covers {n} {h : 0 < n} : @size_of_domain η ⁻¹' {n} ⊆ ⋃ m, is_defined_at m :=
-- begin
-- intros p Hp, simp[set.mem_preimage_eq] at *,
-- suffices : nonempty p.val.dom,
-- by {have := classical.choice this, exact ⟨this.val.snd, ⟨this.val.fst, (by tidy)⟩⟩},
-- apply nonempty_of_size_of_domain_ne_zero, intro H, have : 0 < 0, by cc, cases this
-- end
instance size_of_domain_0_subsingleton : subsingleton $ @size_of_domain η ⁻¹' {0} :=
begin
refine ⟨λ a b, _⟩, rcases a with ⟨⟨p_a, H_f_a⟩, H_a⟩, rcases b with ⟨⟨p_b, H_f_b⟩, H_b⟩, congr,
have := (pfun.graph_empty_iff_dom_empty _).mpr (@empty_of_size_of_domain_0 η _
(by {simp[set.mem_preimage_eq] at H_b, exact H_b})),
have := (pfun.graph_empty_iff_dom_empty _).mpr (@empty_of_size_of_domain_0 η _
(by {simp[set.mem_preimage_eq] at H_a, exact H_a})),
exact pfun.ext_graph _ _ (by cc)
end
lemma subsingleton_of_subset_of_subsingleton {α : Type*} {s s' : set α} (h_sub : s ⊆ s') [subsingleton s'] : subsingleton s :=
begin
refine ⟨λ a b, _⟩, have : ∀ a b : s', a = b, by apply subsingleton.elim,
let f : s → s' := λ x, ⟨x.val, h_sub _⟩,
suffices : f a = f b, by tidy, apply this, exact x.property
end
lemma size_of_domain_0_inter_subsingleton : ∀ (a : set (@cohen_poset η)), subsingleton ↥((size_of_domain ⁻¹' {0}) ∩ a) :=
λ a, subsingleton_of_subset_of_subsingleton
(by apply set.inter_subset_left : size_of_domain ⁻¹' {0} ∩ a ⊆ size_of_domain ⁻¹' {0})
lemma countable_subsingleton {α : Type*} (s : set α) (h : subsingleton s) : set.countable s :=
set.countable_iff_exists_injective.mpr $ ⟨λ _, 0, λ _ _, dec_trivial⟩
-- lemma cover_Union_eq {α ι : Type*} {s : set α} {t : ι → set α} {h : s ⊆ (⋃ (i : ι), t i)} :
-- s = ⋃ i, s ∩ t i :=
-- by {rw[<-set.inter_Union_left], ext, split; intros, exact ⟨a, h a⟩, exact a.left}
lemma inter_subset_left' {α : Type*} {s t u : set α} {h : t ⊆ u} : s ∩ t ⊆ u :=
λ _ ⟨_,_⟩, by solve_by_elim
lemma inter_subset_right' {α : Type*} {s t u : set α} {h : t ⊆ u} : t ∩ s ⊆ u :=
λ _ ⟨_,_⟩, by solve_by_elim
section one_point_restriction
/- Given x : α, return the set λ a, a ≠ x -/
@[simp, reducible]def not_x {α : Type*} (x : α) : set α := λ a, a ≠ x
def finite_of_inter_not_x {α : Type*} {s : set α} (h : set.finite s) {x : α} : set.finite $ s ∩ not_x x := by {apply set.finite_subset, exact h, apply inter_subset_right', trivial}
def roption_indicator {α : Type*} (s : set α) : α → roption α :=
λ x, ⟨x ∈ s, λ _, x⟩
def pfun.restriction {α β : Type*} (f : α →. β) (s : set α) : α →. β
:= λ x, do y <- roption_indicator s x, f y
lemma pfun.domain_restriction {α β : Type*} {f : α →. β} {s : set α} : (pfun.restriction f s).dom = f.dom ∩ s :=
by ext; split; intro a; cases a; fsplit; assumption
end one_point_restriction
-- def one_point_restriction (p : (@cohen_poset η)) : ∀(x), x ∈ p.val.dom → (@cohen_poset η) :=
-- λ x H, ⟨pfun.restriction p.val (not_x x),
-- by {change set.finite (pfun.restriction p.val (not_x x)).dom,
-- rw[pfun.domain_restriction], apply finite_of_inter_not_x, apply p.property}⟩
-- def one_point_restriction' (p : (@cohen_poset η)) : ∀ (x), (@cohen_poset η) :=
-- λ x, ⟨pfun.restriction p.val (not_x x),
-- by {change set.finite (pfun.restriction p.val (not_x x)).dom,
-- rw[pfun.domain_restriction], apply finite_of_inter_not_x, apply p.property}⟩
-- lemma one_point_restriction_domain {p : (@cohen_poset η)} {x} (h : x ∈ p.val.dom) : (one_point_restriction p x h).val.dom = p.val.dom ∩ not_x x :=
-- begin
-- ext, split; {intros a, auto_cases, fsplit; assumption}
-- end
-- lemma one_point_restriction_domain' {p : (@cohen_poset η)} {x} : (one_point_restriction' p x).val.dom = p.val.dom ∩ not_x x :=
-- begin
-- ext, split; {intros a, auto_cases, fsplit; assumption}
-- end
-- lemma one_point_restriction_graph {p : (@cohen_poset η)} {x} {h_x : x ∈ p.val.dom} : ∀ y, y ∈ (one_point_restriction p x h_x).val.graph ↔ (y ∈ p.val.graph ∧ (prod.fst y ≠ x)) := sorry
-- -- lemma one_point_restriction_graph' {p : (@cohen_poset η)} {x} : (one_point_restriction' p x).val.graph = {y ∈ p.val.graph | y.fst ∈ not_x x} :=
-- -- begin
-- -- ext, split; intros,
-- -- end
-- @[simp]lemma in_one_point_restriction_of_in_dom_and_not_x {p : (@cohen_poset η)} {x} {h : x ∈ p.val.dom} {y} : y ∈ (one_point_restriction p x h).val.dom ↔ (y ∈ p.val.dom) ∧ y ≠ x :=
-- by simp[one_point_restriction_domain, not_x]; finish
-- @[simp]lemma in_one_point_restriction'_of_in_dom_and_not_x {p : (@cohen_poset η)} {x} {y} : y ∈ (one_point_restriction' p x ).val.dom ↔ (y ∈ p.val.dom) ∧ y ≠ x :=
-- by simp[one_point_restriction_domain', not_x]; finish
-- lemma one_point_restriction_domain'_subset {p : (@cohen_poset η)} {x} : (one_point_restriction' p x).val.dom ⊆ p.val.dom :=
-- λ y, by finish
-- lemma one_point_restriction_domain_subset {p : (@cohen_poset η)} {x} {h_x : x ∈ p.val.dom} : (one_point_restriction p x h_x).val.dom ⊆ p.val.dom :=
-- λ y, by finish
-- lemma one_point_restriction_domain_coe {p : (@cohen_poset η)} {x} {h : x ∈ p.val.dom} : p.val.dom = ↑(set.finite.to_finset p.property) := by simp
-- lemma one_point_restriction_finset_rewrite {p : (@cohen_poset η)} {x} {h : x ∈ p.val.dom} : set.finite.to_finset (one_point_restriction p x h).property = set.finite.to_finset (by {apply finite_of_inter_not_x, exact p.property} : set.finite $ p.val.dom ∩ not_x x) := by simp[one_point_restriction_domain]
-- lemma one_point_restriction_finset_rewrite_property {p : (@cohen_poset η)} {x} {h : x ∈ p.val.dom} : ∀ y, y ∈ set.finite.to_finset ((one_point_restriction p x h).property-- by {apply finite_of_inter_not_x, exact p.property} : set.finite $ p.val.dom ∩ not_x x
-- ) ↔ y ≠ x ∧ y ∈ p.val.dom :=
-- begin
-- intro y, split; intros, rw[one_point_restriction_finset_rewrite] at a, split,
-- {tidy, apply a_right, refl},
-- {finish},
-- {apply finset.mem_coe.mp, rw[<-one_point_restriction_domain_coe],
-- rw[one_point_restriction_domain], refine ⟨a.right,_⟩, apply a.left, swap, exact y, simp*}
-- end
-- lemma one_point_restriction_erase {p : (@cohen_poset η)} {x} {h : x ∈ p.val.dom} : set.finite.to_finset (one_point_restriction p x h).property = finset.erase (set.finite.to_finset p.property) x :=
-- begin
-- ext, rw[one_point_restriction_finset_rewrite,finset.mem_erase], conv {to_rhs,rw[<-finset.mem_coe]}, split; intros, {rw[<-one_point_restriction_domain_coe], apply (one_point_restriction_finset_rewrite_property a).mp, show set (set ℕ) × ℕ, exact x, rw[one_point_restriction_finset_rewrite], repeat{assumption}},
-- {rw[<-one_point_restriction_finset_rewrite],
-- apply (one_point_restriction_finset_rewrite_property a).mpr,
-- convert a_1, simp, assumption}
-- end
-- lemma one_point_restriction_decrease_size {n} (p : (@cohen_poset η)) (h : size_of_domain p = n + 1) (x) (h_x : x ∈ p.val.dom) :
-- size_of_domain (one_point_restriction p x h_x) = n :=
-- begin
-- unfold size_of_domain at *, have : n = nat.pred (n+1), by refl,
-- rw[this, one_point_restriction_erase, <-h], apply finset.card_erase_of_mem,
-- apply finset.mem_coe.mp, rwa[finset.coe_to_finset]
-- end
-- def aux_c'' {p₁ p₂ : (@cohen_poset η)} {t₁ t₂ : (set $ set ℕ) × ℕ} (h_t₁ : t₁ ∈ p₁.val.dom) (h_t₂ : t₂ ∈ p₂.val.dom) (q : Prop) (h_val₁ : pfun.fn p₁.val t₁ h_t₁ = q) (h_val₂ : pfun.fn p₂.val t₂ h_t₂ = q) (c : (@cohen_poset η)) : (@cohen_poset η) :=
-- (one_point_restriction' (one_point_restriction' c t₁) t₂)
-- lemma aux_c''_dom {p₁ p₂ : (@cohen_poset η)} {t₁ t₂ : (set $ set ℕ) × ℕ} {h_t₁ : t₁ ∈ p₁.val.dom} {h_t₂ : t₂ ∈ p₂.val.dom} {q : Prop} {h_val₁ : pfun.fn p₁.val t₁ h_t₁ = q} {h_val₂ : pfun.fn p₂.val t₂ h_t₂ = q} {c : (@cohen_poset η)} : ∀ (x), x ∈ (aux_c'' h_t₁ h_t₂ q h_val₁ h_val₂ c).val.dom → x ≠ t₁ ∧ x ≠ t₂ :=
-- λ x Hx, ⟨by {apply ((in_one_point_restriction'_of_in_dom_and_not_x).mp _).right, exact c,
-- apply one_point_restriction_domain'_subset, swap, exact t₂, exact Hx},
-- by {apply ((in_one_point_restriction'_of_in_dom_and_not_x).mp _).right, exact (one_point_restriction' c t₁), exact Hx}⟩
-- lemma aux_c''_dom_of {p₁ p₂ : (@cohen_poset η)} {t₁ t₂ : (set $ set ℕ) × ℕ} {h_t₁ : t₁ ∈ p₁.val.dom} {h_t₂ : t₂ ∈ p₂.val.dom} {q : Prop} {h_val₁ : pfun.fn p₁.val t₁ h_t₁ = q} {h_val₂ : pfun.fn p₂.val t₂ h_t₂ = q} {c : (@cohen_poset η)} : ∀ (x), x ≠ t₁ ∧ x ≠ t₂ → x ∈ c.val.dom → x ∈ (aux_c'' h_t₁ h_t₂ q h_val₁ h_val₂ c).val.dom :=
-- begin
-- intros x Hx H'x, rcases Hx with ⟨Hx_r, Hx_l⟩, dsimp[aux_c''],
-- repeat{rw[one_point_restriction_domain']}, finish
-- end
-- lemma aux_c''_graph_of {p₁ p₂ : (@cohen_poset η)} {t₁ t₂ : (set $ set ℕ) × ℕ} {h_t₁ : t₁ ∈ p₁.val.dom} {h_t₂ : t₂ ∈ p₂.val.dom} {q : Prop} {h_val₁ : pfun.fn p₁.val t₁ h_t₁ = q} {h_val₂ : pfun.fn p₂.val t₂ h_t₂ = q} {c : (@cohen_poset η)} : ∀ x, (x ∈ c.val.graph ∧ (prod.fst x ≠ t₁ ) ∧ (prod.fst x ≠ t₂)) ↔ x ∈ (aux_c'' h_t₁ h_t₂ q h_val₁ h_val₂ c).val.graph := sorry
-- lemma aux_c''_dom_finite {p₁ p₂ : (@cohen_poset η)} {t₁ t₂ : (set $ set ℕ) × ℕ} {h_t₁ : t₁ ∈ p₁.val.dom} {h_t₂ : t₂ ∈ p₂.val.dom} {q : Prop} {h_val₁ : pfun.fn p₁.val t₁ h_t₁ = q} {h_val₂ : pfun.fn p₂.val t₂ h_t₂ = q} {c : (@cohen_poset η)} : set.finite (aux_c'' h_t₁ h_t₂ q h_val₁ h_val₂ c).val.dom :=
-- begin
-- dsimp[aux_c''], repeat{rw[one_point_restriction_domain']}, repeat{apply finite_of_inter_not_x},
-- exact c.property
-- end
-- -- λ x Hx, ⟨by {apply ((in_one_point_restriction'_of_in_dom_and_not_x).mp _).right, exact c,
-- -- apply one_point_restriction_domain'_subset, swap, exact t₂, exact Hx},
-- -- by {apply ((in_one_point_restriction'_of_in_dom_and_not_x).mp _).right, exact (one_point_restriction' c t₁), exact Hx}⟩
-- /- Let p₁ and p₂ be two partial functions such that there is a point (b₁,m) for p₁ and a point (b₂, m) for p₂ where p₁ and p₂ have the same value.
-- Suppose that the one-point restrictions of p₁ and p₂ with respect to (b₁,m) and (b₂,m) have a common refinement c.
-- Then c (after making sure (b₁, m) and (b₂,m) are not in its domain) extended by (b₁,m) and (b₂,m) is a common refinement for p₁ and p₂. -/
-- /-- the graph of the extension of c by (b₁,m) and (b₂,m) -/
-- def one_point_restriction_refinement_extension_graph {p₁ p₂ : (@cohen_poset η)} {t₁ t₂ : (set $ set ℕ) × ℕ} (h_t₁ : t₁ ∈ p₁.val.dom) (h_t₂ : t₂ ∈ p₂.val.dom) (q : Prop) (h_val₁ : pfun.fn p₁.val t₁ h_t₁ = q) (h_val₂ : pfun.fn p₂.val t₂ h_t₂ = q) (c : (@cohen_poset η)) :=
-- ((aux_c'' h_t₁ h_t₂ q h_val₁ h_val₂ c).val.graph ∪ {(t₁,q)} ∪ {(t₂,q)})
-- lemma one_point_restriction_refinement_extension_graph_functional {p₁ p₂ : (@cohen_poset η)} {t₁ t₂ : (set $ set ℕ) × ℕ} (h_t₁ : t₁ ∈ p₁.val.dom) (h_t₂ : t₂ ∈ p₂.val.dom) (q : Prop) (h_val₁ : pfun.fn p₁.val t₁ h_t₁ = q) (h_val₂ : pfun.fn p₂.val t₂ h_t₂ = q) (c : (@cohen_poset η)) (h_c_left : c ≤ (one_point_restriction p₁ t₁ h_t₁)) (h_c_right : c ≤ (one_point_restriction p₂ t₂ h_t₂)) :
-- pfun.functional $ one_point_restriction_refinement_extension_graph h_t₁ h_t₂ q h_val₁ h_val₂ c :=
-- begin
-- intros x q₁ q₂ H₁ H₂, let c' := (aux_c'' h_t₁ h_t₂ q h_val₁ h_val₂ c), cases H₁; cases H₂; cases H₁; cases H₂,
-- apply pfun.graph_functional (aux_c'' h_t₁ h_t₂ q h_val₁ h_val₂ c).val, exact H₁, exact H₂,
-- {have : x ∈ c'.val.dom,
-- by {apply (pfun.dom_iff_graph c'.val x).mpr, exact ⟨q₁, H₁⟩}, have := (aux_c''_dom x this).left, suffices : x = t₁, by contradiction, repeat{cases H₂}, refl},
-- {repeat{cases H₁}, suffices : t₁ ≠ t₁, by contradiction, have : t₁ ∈ c'.val.dom,
-- by {apply (pfun.dom_iff_graph c'.val t₁).mpr, exact ⟨q₂, H₂⟩},
-- exact (aux_c''_dom t₁ this).left},
-- {cases H₁; cases H₁; cases H₂; cases H₂, cc},
-- {repeat{cases H₂}, suffices : t₂ ≠ t₂, by contradiction, have : t₂ ∈ c'.val.dom,
-- by {apply (pfun.dom_iff_graph c'.val t₂).mpr, exact ⟨q₁, H₁⟩},
-- exact (aux_c''_dom t₂ this).right},
-- {cases H₂},
-- {repeat{cases H₁}, cases H₂, refl},
-- {cases H₂},
-- {repeat{cases H₁}, suffices : t₂ ≠ t₂, by contradiction, have : t₂ ∈ c'.val.dom,
-- by {apply (pfun.dom_iff_graph c'.val t₂).mpr, refine ⟨_,_⟩, exact q₂, exact H₂},
-- exact (aux_c''_dom t₂ this).right}, {repeat{cases H₂}, cases H₁, refl},
-- {cases H₁}, {cases H₁}, {cc}, {cases H₂}, {cases H₁}, {cases H₁},
-- end
-- /-- the graph of the extension of c by (b₁,m) and (b₂,m) contains the graphs of p₁ and p₂ -/
-- lemma one_point_restriction_refinement_extension_graph_extends {p₁ p₂ : (@cohen_poset η)} {t₁ t₂ : (set $ set ℕ) × ℕ} (h_t₁ : t₁ ∈ p₁.val.dom) (h_t₂ : t₂ ∈ p₂.val.dom) (q : Prop) (h_val₁ : pfun.fn p₁.val t₁ h_t₁ = q) (h_val₂ : pfun.fn p₂.val t₂ h_t₂ = q) (c : (@cohen_poset η)) (h_c_left : c ≤ (one_point_restriction p₁ t₁ h_t₁)) (h_c_right : c ≤ (one_point_restriction p₂ t₂ h_t₂)) : p₁.val.graph ⊆ (one_point_restriction_refinement_extension_graph h_t₁ h_t₂ q h_val₁ h_val₂ c) ∧ p₂.val.graph ⊆ (one_point_restriction_refinement_extension_graph h_t₁ h_t₂ q h_val₁ h_val₂ c) :=
-- begin
-- split; intros x Hx; rcases x with ⟨x, q'⟩;
-- dsimp[one_point_restriction_refinement_extension_graph],
-- suffices : ((x, q') ∈ pfun.graph ((aux_c'' h_t₁ h_t₂ q h_val₁ h_val₂ c).val)) ∨ ((x, q') ∈ {(t₁, q)} ∨
-- (x, q') ∈ {(t₂, q)}), by rwa[or_assoc],
-- let H, swap, change _ ∨ H, haveI : decidable H := by apply classical.prop_decidable _,
-- by_cases H,
-- {apply or.elim h, exact λ A, or.inr $ or.inl $ A,
-- exact λ A, or.inr $ or.inr $ A},
-- {-- dsimp[H] at h, rw[not_or_distrib] at h, apply or.inl,
-- repeat{sorry}
-- -- apply (aux_c''_graph_of (x,q')).mp,
-- -- refine ⟨_, _⟩,
-- -- dsimp[H] at h, rw[not_or_distrib] at h,
-- -- have Hx' : (x,q') ∈ (c.val).graph,
-- -- by {apply h_c_left, apply (one_point_restriction_graph (x,q')).mpr,
-- -- refine ⟨(by assumption), _⟩, change x ≠ t₁, cases h, intro hx, apply h_left, rw[hx], simp,
-- -- apply (pfun.graph_functional p₁.val), exact Hx,
-- -- rw[hx], apply (pfun.lift_graph' _).mpr, exact h_val₁},
-- -- apply or.inl, have : x ∈ p₁.val.dom, by apply (pfun.dom_iff_graph _ x).mpr; exact ⟨q', Hx⟩,
-- -- have : x ∈ ((aux_c'' h_t₁ h_t₂ q h_val₁ h_val₂ c).val).dom,
-- -- by {apply aux_c''_dom_of, {split, {change x ≠ t₁, cases h, intro hx,
-- -- apply h_left, rw[hx], simp, apply (pfun.graph_functional p₁.val), exact Hx,
-- -- rw[hx], apply (pfun.lift_graph' _).mpr, exact h_val₁}, {change x ≠ t₂, cases h, intro hx, apply h_right, rw[hx], simp, apply (pfun.graph_functional p₂.val), repeat{sorry} -- exact Hx, rw[hx], apply (pfun.lift_graph' _).mpr, exact h_val₂
-- -- }}, {apply (pfun.dom_iff_graph _ x).mpr, exact ⟨q', Hx'⟩}},
-- },
-- -- by_cases H, repeat{sorry}
-- -- have : ((x, q') ∈ {(t₁, q)} ∨ (x, q') ∈ {(t₂, q)}) → (x,q') ∉ pfun.graph ((aux_c'' h_t₁ h_t₂ q h_val₁ h_val₂ c).val),
-- -- by {intros H₁ H₂, have : x ∈ (aux_c'' h_t₁ h_t₂ q h_val₁ h_val₂ c).val.dom,
-- -- by {apply (pfun.dom_iff_graph _ x).mpr, exact ⟨q', H₂⟩}, have := aux_c''_dom x this,
-- -- cases H₁, have : (x,q') = (t₁, q), from set.eq_of_mem_singleton (by assumption), finish,
-- -- have : (x,q') = (t₂, q), from set.eq_of_mem_singleton (by assumption), finish},
-- repeat{sorry}
-- end
-- /-- the extension of c by (b₁, m) and (b₂,m) has finite domain -/
-- lemma one_point_restriction_refinement_extension_finite {p₁ p₂ : (@cohen_poset η)} {t₁ t₂ : (set $ set ℕ) × ℕ} (h_t₁ : t₁ ∈ p₁.val.dom) (h_t₂ : t₂ ∈ p₂.val.dom) (q : Prop) (h_val₁ : pfun.fn p₁.val t₁ h_t₁ = q) (h_val₂ : pfun.fn p₂.val t₂ h_t₂ = q) (c : (@cohen_poset η)) (h_c_left : c ≤ (one_point_restriction p₁ t₁ h_t₁)) (h_c_right : c ≤ (one_point_restriction p₂ t₂ h_t₂)) : set.finite (pfun.of_graph (one_point_restriction_refinement_extension_graph h_t₁ h_t₂ q h_val₁ h_val₂ c) (by {apply one_point_restriction_refinement_extension_graph_functional, repeat{assumption}})).dom :=
-- begin
-- unfold one_point_restriction_refinement_extension_graph,
-- rw[pfun.dom_of_graph_union], swap,
-- apply pfun.functional_subset (one_point_restriction_refinement_extension_graph h_t₁ h_t₂ q h_val₁ h_val₂ c),
-- by {unfold one_point_restriction_refinement_extension_graph, finish},
-- apply one_point_restriction_refinement_extension_graph_functional, repeat{assumption},
-- rw[pfun.dom_of_graph_union, pfun.of_graph_graph], simp only [set.union_singleton], repeat{apply set.finite_insert}, apply aux_c''_dom_finite
-- end
-- noncomputable def one_point_restriction_refinement_extension {p₁ p₂ : (@cohen_poset η)} {t₁ t₂ : (set $ set ℕ) × ℕ} (h_t₁ : t₁ ∈ p₁.val.dom) (h_t₂ : t₂ ∈ p₂.val.dom) (q : Prop) (h_val₁ : pfun.fn p₁.val t₁ h_t₁ = q) (h_val₂ : pfun.fn p₂.val t₂ h_t₂ = q) (c : (@cohen_poset η)) (h_c_left : c ≤ (one_point_restriction p₁ t₁ h_t₁)) (h_c_right : c ≤ (one_point_restriction p₂ t₂ h_t₂)) : (@cohen_poset η) :=
-- ⟨pfun.of_graph (one_point_restriction_refinement_extension_graph h_t₁ h_t₂ q h_val₁ h_val₂ c) (by {apply one_point_restriction_refinement_extension_graph_functional, repeat{assumption}}),
-- (by {apply one_point_restriction_refinement_extension_finite, repeat{assumption}})⟩
-- lemma one_point_restriction_refinement_extension_spec (p₁ p₂ : (@cohen_poset η)) {t₁ t₂ : (set $ set ℕ) × ℕ} {h_t₁ : t₁ ∈ p₁.val.dom} {h_t₂ : t₂ ∈ p₂.val.dom} {q : Prop} {h_val₁ : pfun.fn p₁.val t₁ h_t₁ = q} {h_val₂ : pfun.fn p₂.val t₂ h_t₂ = q} {c : (@cohen_poset η)} (h_c_left : c ≤ (one_point_restriction p₁ t₁ h_t₁)) (h_c_right : c ≤ (one_point_restriction p₂ t₂ h_t₂)) : ∃ c' : (@cohen_poset η), c' ≤ p₁ ∧ c' ≤ p₂ :=
-- begin
-- refine ⟨by {fapply one_point_restriction_refinement_extension h_t₁ h_t₂ q h_val₁ h_val₂ c,
-- repeat{assumption}}, _⟩,
-- have := one_point_restriction_refinement_extension_graph_extends h_t₁ h_t₂ q h_val₁ h_val₂ c h_c_left h_c_right,
-- convert this; convert rfl; simp[one_point_restriction_refinement_extension, one_point_restriction_refinement_extension_graph, pfun.graph_of_graph]
-- end
-- lemma wit_incompatible {p₁ p₂ : (@cohen_poset η)} (h_incompat : incompatible p₁ p₂) : ∃ w ∈ p₁.val.dom ∩ p₂.val.dom, pfun.fn (p₁.val) w (by exact H.left) ≠ pfun.fn (p₂.val) w H.right :=
-- begin
-- sorry
-- -- let p, swap, change p, haveI : decidable p := by apply classical.prop_decidable _,
-- -- by_contra, dsimp[p] at a, clear _inst p,
-- -- simp at a, sorry
-- end
-- lemma wit_incompatible' {p₁ p₂ : (@cohen_poset η)} (h_incompat : incompatible p₁ p₂) : ∃ w q₁ q₂, (w,q₁) ∈ p₁.val.graph ∧ (w,q₂) ∈ p₂.val.graph ∧ q₁ ≠ q₂ := sorry
-- end one_point_restriction
-- lemma congr_neq {α β : Type*} {f : α → β} {x' y' : α} {x y : β} {h_x : f x' = x} {h_y : f y' = y} {h_neq : x ≠ y} : x' ≠ y' := λ _, by {cc}
-- lemma coe_subtype_injective {α : Type*} {s : set α} {x y : s} : (↑x = (↑y : α)) → x = y :=
-- λ h, by {cases x, cases y, dsimp at h, subst h}
-- -- /- The Cohen poset has the countable chain condition -/
-- -- lemma (@cohen_poset η)_ccc : countable_chain_condition (@cohen_poset η) :=
-- -- begin
-- -- intros a Ha, apply countable_of_countable_fibers' a size_of_domain,
-- -- intro n, induction n with n ih generalizing a,
-- -- {apply countable_subsingleton, apply size_of_domain_0_inter_subsingleton},
-- -- {let A_n, swap, change set.countable A_n,
-- -- have : A_n ⊆ ⋃ m, is_defined_at m, by {dsimp[A_n], apply inter_subset_right',
-- -- apply is_defined_at_covers, apply nat.zero_lt_succ},
-- -- rw[@cover_Union_eq _ _ A_n is_defined_at this], apply set.countable_Union,
-- -- intro m, let A_n_m, swap, change set.countable A_n_m,
-- -- have choice_aux : ∀ p : A_n_m, ∃ b : (set $ set ℕ), (b,m) ∈ (pfun.dom p.val.val),
-- -- by {intros p, cases p, cases p_property, cases p_val, assumption},
-- -- have := classical.axiom_of_choice choice_aux, cases this with wit wit_spec,
-- -- let eval : A_n_m → Prop :=
-- -- λ (p : ↥A_n_m), pfun.fn ((p.val).val) (wit p, m) (by apply wit_spec),
-- -- apply countable_of_countable_fibers'' _ eval, intro q,
-- -- let A_n_m_q, swap, change set.countable A_n_m_q,
-- -- let red : A_n_m → (@cohen_poset η) :=
-- -- λ X, one_point_restriction X.val (wit X, m) (by apply wit_spec),
-- -- have h_anti : antichain (red '' A_n_m_q) :=
-- -- by {intros x H_x y H_y H_neq H_compat, rcases H_compat with ⟨c, ⟨H_cx,H_cy⟩⟩,
-- -- rcases H_x with ⟨x', H_x'⟩, rcases H_y with ⟨y', H_y'⟩,
-- -- have h_neq : x' ≠ y',
-- -- by {apply congr_neq, exact H_x'.right, exact H_y'.right, exact H_neq},
-- -- have : ↑x' ≠ ↑y', by {intro, apply h_neq, exact coe_subtype_injective a_1},
-- -- have h_incompat := Ha x' (x'.property.left.right) y' (y'.property.left.right) this,
-- -- have := wit_incompatible' h_incompat, rcases this with ⟨w,q₁,q₂, ⟨H₁,⟨H₂,H₃⟩⟩⟩,
-- -- have w_not_t₁ : w ≠ (wit (x'), m),
-- -- by {intro H_eq, have := pfun.congr_arg (subtype.val (↑x'))
-- -- (pfun.in_dom_of_in_graph (by assumption))
-- -- (pfun.in_dom_of_in_graph (sorry)) H_eq, repeat{sorry}
-- -- },
-- -- have w_not_t₂ : w.fst ≠ wit (y'), by sorry,
-- -- have w_in_red_1 : (w,q₁) ∈ (x).val.graph, by sorry,
-- -- have w_in_red_2 : (w,q₂) ∈ (y).val.graph, by sorry,
-- -- have w_in_c_1 : (w,q₁) ∈ c.val.graph, from H_cx w_in_red_1,
-- -- have w_in_c_2 : (w,q₂) ∈ c.val.graph, from H_cy w_in_red_2,
-- -- suffices : q₁ = q₂, by contradiction,
-- -- apply pfun.graph_functional c.val, exacts [w_in_c_1, w_in_c_2]
-- -- },
-- -- have ih_rewrite : size_of_domain ⁻¹' {n} ∩ red '' A_n_m_q = red '' A_n_m_q,
-- -- by {apply set.inter_eq_self_of_subset_right, intros x H_x,
-- -- simp only [set.mem_singleton_iff, set.mem_preimage_eq],
-- -- dsimp[red] at H_x, cases H_x, rw[<-H_x_h.right],
-- -- apply one_point_restriction_decrease_size,
-- -- apply size_of_domain_fiber H_x_w.property.left.left},
-- -- have h_inj : set.inj_on red A_n_m_q,
-- -- by {intros x' y' H_x' H_y',
-- -- haveI : decidable_eq ↥A_n_m := λ _ _, classical.prop_decidable _,
-- -- by_cases x' = y', exact λ _, ‹x' = y'›, rename h h_neq,
-- -- intro H, exfalso,
-- -- refine Ha x' (x'.property.left.right) y' (y'.property.left.right)
-- -- (by {intro, apply h_neq, exact coe_subtype_injective a_1}) _,
-- -- apply one_point_restriction_refinement_extension_spec (↑x') (↑y'),
-- -- have : red x' ≤ red x', by {apply le_of_eq rfl},
-- -- convert this, convert (le_of_eq H), exact q,
-- -- cases H_x', convert H_x', cases H_x',
-- -- cases H_y', convert H_y', cases H_y'},
-- -- have ih' := ih (red '' A_n_m_q) h_anti,
-- -- exact set.countable_of_injective_of_countable_image h_inj (by rwa[<-ih_rewrite])}
-- end
|
d0180401780493517ef0c46d8d7e7fcd11bc1e7e | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/algebra/linear_recurrence.lean | a7feb17cbca3b85dff017b80b397cabb8115d9ab | [
"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 | 8,263 | lean | /-
Copyright (c) 2020 Anatole Dedecker. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anatole Dedecker
-/
import data.polynomial.ring_division
import linear_algebra.dimension
import algebra.polynomial.big_operators
/-!
# Linear recurrence
Informally, a "linear recurrence" is an assertion of the form
`∀ n : ℕ, u (n + d) = a 0 * u n + a 1 * u (n+1) + ... + a (d-1) * u (n+d-1)`,
where `u` is a sequence, `d` is the *order* of the recurrence and the `a i`
are its *coefficients*.
In this file, we define the structure `linear_recurrence` so that
`linear_recurrence.mk d a` represents the above relation, and we call
a sequence `u` which verifies it a *solution* of the linear recurrence.
We prove a few basic lemmas about this concept, such as :
* the space of solutions is a submodule of `(ℕ → α)` (i.e a vector space if `α`
is a field)
* the function that maps a solution `u` to its first `d` terms builds a `linear_equiv`
between the solution space and `fin d → α`, aka `α ^ d`. As a consequence, two
solutions are equal if and only if their first `d` terms are equals.
* a geometric sequence `q ^ n` is solution iff `q` is a root of a particular polynomial,
which we call the *characteristic polynomial* of the recurrence
Of course, although we can inductively generate solutions (cf `mk_sol`), the
interesting part would be to determinate closed-forms for the solutions.
This is currently *not implemented*, as we are waiting for definition and
properties of eigenvalues and eigenvectors.
-/
noncomputable theory
open finset
open_locale big_operators
/-- A "linear recurrence relation" over a commutative semiring is given by its
order `n` and `n` coefficients. -/
structure linear_recurrence (α : Type*) [comm_semiring α] := (order : ℕ) (coeffs : fin order → α)
instance (α : Type*) [comm_semiring α] : inhabited (linear_recurrence α) :=
⟨⟨0, default _⟩⟩
namespace linear_recurrence
section comm_semiring
variables {α : Type*} [comm_semiring α] (E : linear_recurrence α)
/-- We say that a sequence `u` is solution of `linear_recurrence order coeffs` when we have
`u (n + order) = ∑ i : fin order, coeffs i * u (n + i)` for any `n`. -/
def is_solution (u : ℕ → α) :=
∀ n, u (n + E.order) = ∑ i, E.coeffs i * u (n + i)
/-- A solution of a `linear_recurrence` which satisfies certain initial conditions.
We will prove this is the only such solution. -/
def mk_sol (init : fin E.order → α) : ℕ → α
| n := if h : n < E.order then init ⟨n, h⟩ else
∑ k : fin E.order,
have n - E.order + k < n :=
begin
rw [add_comm, ← nat.add_sub_assoc (not_lt.mp h), nat.sub_lt_left_iff_lt_add],
{ exact add_lt_add_right k.is_lt n },
{ convert add_le_add (zero_le (k : ℕ)) (not_lt.mp h),
simp only [zero_add] }
end,
E.coeffs k * mk_sol (n - E.order + k)
/-- `E.mk_sol` indeed gives solutions to `E`. -/
lemma is_sol_mk_sol (init : fin E.order → α) : E.is_solution (E.mk_sol init) :=
λ n, by rw mk_sol; simp
/-- `E.mk_sol init`'s first `E.order` terms are `init`. -/
lemma mk_sol_eq_init (init : fin E.order → α) : ∀ n : fin E.order, E.mk_sol init n = init n :=
λ n, by { rw mk_sol, simp only [n.is_lt, dif_pos, fin.mk_coe, fin.eta] }
/-- If `u` is a solution to `E` and `init` designates its first `E.order` values,
then `∀ n, u n = E.mk_sol init n`. -/
lemma eq_mk_of_is_sol_of_eq_init {u : ℕ → α} {init : fin E.order → α}
(h : E.is_solution u) (heq : ∀ n : fin E.order, u n = init n) :
∀ n, u n = E.mk_sol init n
| n := if h' : n < E.order
then by rw mk_sol; simp only [h', dif_pos]; exact_mod_cast heq ⟨n, h'⟩
else begin
rw [mk_sol, ← nat.sub_add_cancel (le_of_not_lt h'), h (n-E.order)],
simp [h'],
congr' with k,
exact have wf : n - E.order + k < n :=
begin
rw [add_comm, ← nat.add_sub_assoc (not_lt.mp h'), nat.sub_lt_left_iff_lt_add],
{ exact add_lt_add_right k.is_lt n },
{ convert add_le_add (zero_le (k : ℕ)) (not_lt.mp h'),
simp only [zero_add] }
end,
by rw eq_mk_of_is_sol_of_eq_init
end
/-- If `u` is a solution to `E` and `init` designates its first `E.order` values,
then `u = E.mk_sol init`. This proves that `E.mk_sol init` is the only solution
of `E` whose first `E.order` values are given by `init`. -/
lemma eq_mk_of_is_sol_of_eq_init' {u : ℕ → α} {init : fin E.order → α}
(h : E.is_solution u) (heq : ∀ n : fin E.order, u n = init n) : u = E.mk_sol init :=
funext (E.eq_mk_of_is_sol_of_eq_init h heq)
/-- The space of solutions of `E`, as a `submodule` over `α` of the semimodule `ℕ → α`. -/
def sol_space : submodule α (ℕ → α) :=
{ carrier := {u | E.is_solution u},
zero_mem' := λ n, by simp,
add_mem' := λ u v hu hv n, by simp [mul_add, sum_add_distrib, hu n, hv n],
smul_mem' := λ a u hu n, by simp [hu n, mul_sum]; congr'; ext; ac_refl }
/-- Defining property of the solution space : `u` is a solution
iff it belongs to the solution space. -/
lemma is_sol_iff_mem_sol_space (u : ℕ → α) : E.is_solution u ↔ u ∈ E.sol_space :=
iff.rfl
/-- The function that maps a solution `u` of `E` to its first
`E.order` terms as a `linear_equiv`. -/
def to_init :
E.sol_space ≃ₗ[α] (fin E.order → α) :=
{ to_fun := λ u x, (u : ℕ → α) x,
map_add' := λ u v, by { ext, simp },
map_smul' := λ a u, by { ext, simp },
inv_fun := λ u, ⟨E.mk_sol u, E.is_sol_mk_sol u⟩,
left_inv := λ u, by ext n; symmetry; apply E.eq_mk_of_is_sol_of_eq_init u.2; intros k; refl,
right_inv := λ u, function.funext_iff.mpr (λ n, E.mk_sol_eq_init u n) }
/-- Two solutions are equal iff they are equal on `range E.order`. -/
lemma sol_eq_of_eq_init (u v : ℕ → α) (hu : E.is_solution u) (hv : E.is_solution v) :
u = v ↔ set.eq_on u v ↑(range E.order) :=
begin
refine iff.intro (λ h x hx, h ▸ rfl) _,
intro h,
set u' : ↥(E.sol_space) := ⟨u, hu⟩,
set v' : ↥(E.sol_space) := ⟨v, hv⟩,
change u'.val = v'.val,
suffices h' : u' = v', from h' ▸ rfl,
rw [← E.to_init.to_equiv.apply_eq_iff_eq, linear_equiv.coe_to_equiv],
ext x,
exact_mod_cast h (mem_range.mpr x.2)
end
/-! `E.tuple_succ` maps `![s₀, s₁, ..., sₙ]` to `![s₁, ..., sₙ, ∑ (E.coeffs i) * sᵢ]`,
where `n := E.order`. This operation is quite useful for determining closed-form
solutions of `E`. -/
/-- `E.tuple_succ` maps `![s₀, s₁, ..., sₙ]` to `![s₁, ..., sₙ, ∑ (E.coeffs i) * sᵢ]`,
where `n := E.order`. -/
def tuple_succ : (fin E.order → α) →ₗ[α] (fin E.order → α) :=
{ to_fun := λ X i, if h : (i : ℕ) + 1 < E.order then X ⟨i+1, h⟩ else (∑ i, E.coeffs i * X i),
map_add' := λ x y,
begin
ext i,
split_ifs ; simp [h, mul_add, sum_add_distrib],
end,
map_smul' := λ x y,
begin
ext i,
split_ifs ; simp [h, mul_sum],
exact sum_congr rfl (λ x _, by ac_refl),
end }
end comm_semiring
section field
variables {α : Type*} [field α] (E : linear_recurrence α)
/-- The dimension of `E.sol_space` is `E.order`. -/
lemma sol_space_dim : vector_space.dim α E.sol_space = E.order :=
@dim_fin_fun α _ E.order ▸ E.to_init.dim_eq
end field
section comm_ring
variables {α : Type*} [comm_ring α] (E : linear_recurrence α)
/-- The characteristic polynomial of `E` is
`X ^ E.order - ∑ i : fin E.order, (E.coeffs i) * X ^ i`. -/
def char_poly : polynomial α :=
polynomial.monomial E.order 1 - (∑ i : fin E.order, polynomial.monomial i (E.coeffs i))
/-- The geometric sequence `q^n` is a solution of `E` iff
`q` is a root of `E`'s characteristic polynomial. -/
lemma geom_sol_iff_root_char_poly (q : α) : E.is_solution (λ n, q^n) ↔ E.char_poly.is_root q :=
begin
rw [char_poly, polynomial.is_root.def, polynomial.eval],
simp only [polynomial.eval₂_finset_sum, one_mul,
ring_hom.id_apply, polynomial.eval₂_monomial, polynomial.eval₂_sub],
split,
{ intro h,
simpa [sub_eq_zero] using h 0 },
{ intros h n,
simp only [pow_add, sub_eq_zero.mp h, mul_sum],
exact sum_congr rfl (λ _ _, by ring) }
end
end comm_ring
end linear_recurrence
|
42d2ea178f8e6ac7db8e4d9f91c5f859b837764b | d1a52c3f208fa42c41df8278c3d280f075eb020c | /src/Lean/Meta/Reduce.lean | d371a1296be05c71f8d0e67901e20f78ed430c66 | [
"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,497 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Basic
import Lean.Meta.FunInfo
import Lean.Util.MonadCache
namespace Lean.Meta
partial def reduce (e : Expr) (explicitOnly skipTypes skipProofs := true) : MetaM Expr :=
let rec visit (e : Expr) : MonadCacheT Expr Expr MetaM Expr :=
checkCache e fun _ => Core.withIncRecDepth do
if (← (skipTypes <&&> isType e)) then
return e
else if (← (skipProofs <&&> isProof e)) then
return e
else
let e ← whnf e
match e with
| Expr.app .. =>
let f ← visit e.getAppFn
let nargs := e.getAppNumArgs
let finfo ← getFunInfoNArgs f nargs
let mut args := e.getAppArgs
for i in [:args.size] do
if i < finfo.paramInfo.size then
let info := finfo.paramInfo[i]
if !explicitOnly || info.isExplicit then
args ← args.modifyM i visit
else
args ← args.modifyM i visit
pure (mkAppN f args)
| Expr.lam .. => lambdaTelescope e fun xs b => do mkLambdaFVars xs (← visit b)
| Expr.forallE .. => forallTelescope e fun xs b => do mkForallFVars xs (← visit b)
| Expr.proj n i s .. => return mkProj n i (← visit s)
| _ => return e
visit e |>.run
end Lean.Meta
|
e4a1382a675fedd4ed4072b94f8d81c3f4ed0c74 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/set_theory/game/birthday.lean | db7a1616b365ca00bf1e3501d55f3dc3f8210a4c | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 4,674 | lean | /-
Copyright (c) 2022 Violeta Hernández Palacios. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Violeta Hernández Palacios
-/
import set_theory.game.ordinal
import set_theory.ordinal.arithmetic
/-!
# Birthdays of games
The birthday of a game is an ordinal that represents at which "step" the game was constructed. We
define it recursively as the least ordinal larger than the birthdays of its left and right games. We
prove the basic properties about these.
# Main declarations
- `pgame.birthday`: The birthday of a pre-game.
# Todo
- Define the birthdays of `game`s and `surreal`s.
- Characterize the birthdays of basic arithmetical operations.
-/
universe u
open ordinal
namespace pgame
/-- The birthday of a pre-game is inductively defined as the least strict upper bound of the
birthdays of its left and right games. It may be thought as the "step" in which a certain game is
constructed. -/
noncomputable def birthday : pgame.{u} → ordinal.{u}
| ⟨xl, xr, xL, xR⟩ :=
max (lsub.{u u} $ λ i, birthday (xL i)) (lsub.{u u} $ λ i, birthday (xR i))
theorem birthday_def (x : pgame) : birthday x = max
(lsub.{u u} (λ i, birthday (x.move_left i)))
(lsub.{u u} (λ i, birthday (x.move_right i))) :=
by { cases x, rw birthday, refl }
theorem birthday_move_left_lt {x : pgame} (i : x.left_moves) :
(x.move_left i).birthday < x.birthday :=
by { cases x, rw birthday, exact lt_max_of_lt_left (lt_lsub _ i) }
theorem birthday_move_right_lt {x : pgame} (i : x.right_moves) :
(x.move_right i).birthday < x.birthday :=
by { cases x, rw birthday, exact lt_max_of_lt_right (lt_lsub _ i) }
theorem lt_birthday_iff {x : pgame} {o : ordinal} : o < x.birthday ↔
(∃ i : x.left_moves, o ≤ (x.move_left i).birthday) ∨
(∃ i : x.right_moves, o ≤ (x.move_right i).birthday) :=
begin
split,
{ rw birthday_def,
intro h,
cases lt_max_iff.1 h with h' h',
{ left,
rwa lt_lsub_iff at h' },
{ right,
rwa lt_lsub_iff at h' } },
{ rintro (⟨i, hi⟩ | ⟨i, hi⟩),
{ exact hi.trans_lt (birthday_move_left_lt i) },
{ exact hi.trans_lt (birthday_move_right_lt i) } }
end
theorem relabelling.birthday_congr : ∀ {x y : pgame.{u}}, relabelling x y → birthday x = birthday y
| ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ ⟨L, R, hL, hR⟩ := begin
rw [birthday, birthday],
congr' 1,
all_goals
{ apply lsub_eq_of_range_eq.{u u u},
ext i,
split },
{ rintro ⟨j, rfl⟩,
exact ⟨L j, (relabelling.birthday_congr (hL j)).symm⟩ },
{ rintro ⟨j, rfl⟩,
refine ⟨L.symm j, relabelling.birthday_congr _⟩,
convert hL (L.symm j),
rw L.apply_symm_apply },
{ rintro ⟨j, rfl⟩,
refine ⟨R j, (relabelling.birthday_congr _).symm⟩,
convert hR (R j),
rw R.symm_apply_apply },
{ rintro ⟨j, rfl⟩,
exact ⟨R.symm j, relabelling.birthday_congr (hR j)⟩ }
end
using_well_founded { dec_tac := pgame_wf_tac }
@[simp] theorem birthday_add_zero (x : pgame) : birthday (x + 0) = birthday x :=
(add_zero_relabelling x).birthday_congr
@[simp] theorem birthday_zero_add (x : pgame) : birthday (0 + x) = birthday x :=
(zero_add_relabelling x).birthday_congr
@[simp] theorem birthday_eq_zero (x : pgame) :
birthday x = 0 ↔ is_empty x.left_moves ∧ is_empty x.right_moves :=
by rw [birthday_def, max_eq_zero, lsub_eq_zero_iff, lsub_eq_zero_iff]
@[simp] theorem birthday_zero : birthday 0 = 0 :=
by { rw birthday_eq_zero, split; apply_instance }
@[simp] theorem birthday_one : birthday 1 = 1 :=
begin
have : (λ i, (move_left 1 i).birthday) = λ i, 0 := funext (λ x, by simp),
rw [birthday_def, @lsub_empty (right_moves 1), this, lsub_const, succ_zero, max_zero_right]
end
@[simp] theorem neg_birthday : ∀ x : pgame, (-x).birthday = x.birthday
| ⟨xl, xr, xL, xR⟩ := begin
rw [birthday_def, birthday_def, max_comm],
congr; funext; apply neg_birthday
end
@[simp] theorem to_pgame_birthday (o : ordinal) : o.to_pgame.birthday = o :=
begin
induction o using ordinal.induction with o IH,
rw [to_pgame_def, pgame.birthday],
convert max_eq_left_iff.2 (ordinal.zero_le _),
{ apply lsub_empty },
{ nth_rewrite 0 ←lsub_typein o,
congr,
exact funext (λ x, (IH _ (typein_lt_self x)).symm) }
end
theorem le_birthday : ∀ x : pgame, x ≤ x.birthday.to_pgame
| ⟨xl, _, xL, _⟩ :=
le_def.2 ⟨λ i, or.inl ⟨to_left_moves_to_pgame ⟨_, birthday_move_left_lt i⟩,
by simp [le_birthday (xL i)]⟩, is_empty_elim⟩
theorem neg_birthday_le (x : pgame) : -x.birthday.to_pgame ≤ x :=
let h := le_birthday (-x) in by rwa [neg_birthday, le_iff_neg_ge, neg_neg] at h
end pgame
|
60fc53ea35c13be1f668d4eb814d9a91f630a247 | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /src/Lean/Meta/DiscrTree.lean | 5919548d53c1fdb4c2f6bc24f33029ed78cc2de8 | [
"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 | 18,232 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Basic
import Lean.Meta.FunInfo
import Lean.Meta.InferType
namespace Lean.Meta.DiscrTree
/-
(Imperfect) discrimination trees.
We use a hybrid representation.
- A `PersistentHashMap` for the root node which usually contains many children.
- A sorted array of key/node pairs for inner nodes.
The edges are labeled by keys:
- Constant names (and arity). Universe levels are ignored.
- Free variables (and arity). Thus, an entry in the discrimination tree
may reference hypotheses from the local context.
- Literals
- Star/Wildcard. We use them to represent metavariables and terms
we want to ignore. We ignore implicit arguments and proofs.
- Other. We use to represent other kinds of terms (e.g., nested lambda, forall, sort, etc).
We reduce terms using `TransparencyMode.reducible`. Thus, all reducible
definitions in an expression `e` are unfolded before we insert it into the
discrimination tree.
Recall that projections from classes are **NOT** reducible.
For example, the expressions `Add.add α (ringAdd ?α ?s) ?x ?x`
and `Add.add Nat Nat.hasAdd a b` generates paths with the following keys
respctively
```
⟨Add.add, 4⟩, *, *, *, *
⟨Add.add, 4⟩, *, *, ⟨a,0⟩, ⟨b,0⟩
```
That is, we don't reduce `Add.add Nat inst a b` into `Nat.add a b`.
We say the `Add.add` applications are the de-facto canonical forms in
the metaprogramming framework.
Moreover, it is the metaprogrammer's responsibility to re-pack applications such as
`Nat.add a b` into `Add.add Nat inst a b`.
Remark: we store the arity in the keys
1- To be able to implement the "skip" operation when retrieving "candidate"
unifiers.
2- Distinguish partial applications `f a`, `f a b`, and `f a b c`.
-/
def Key.ctorIdx : Key → Nat
| Key.star => 0
| Key.other => 1
| Key.lit _ => 2
| Key.fvar _ _ => 3
| Key.const _ _ => 4
| Key.arrow => 5
def Key.lt : Key → Key → Bool
| Key.lit v₁, Key.lit v₂ => v₁ < v₂
| Key.fvar n₁ a₁, Key.fvar n₂ a₂ => Name.quickLt n₁ n₂ || (n₁ == n₂ && a₁ < a₂)
| Key.const n₁ a₁, Key.const n₂ a₂ => Name.quickLt n₁ n₂ || (n₁ == n₂ && a₁ < a₂)
| k₁, k₂ => k₁.ctorIdx < k₂.ctorIdx
instance : LT Key := ⟨fun a b => Key.lt a b⟩
instance (a b : Key) : Decidable (a < b) := inferInstanceAs (Decidable (Key.lt a b))
def Key.format : Key → Format
| Key.star => "*"
| Key.other => "◾"
| Key.lit (Literal.natVal v) => fmt v
| Key.lit (Literal.strVal v) => repr v
| Key.const k _ => fmt k
| Key.fvar k _ => fmt k
| Key.arrow => "→"
instance : ToFormat Key := ⟨Key.format⟩
def Key.arity : Key → Nat
| Key.const _ a => a
| Key.fvar _ a => a
| Key.arrow => 2
| _ => 0
instance : Inhabited (Trie α) := ⟨Trie.node #[] #[]⟩
def empty : DiscrTree α := { root := {} }
partial def Trie.format [ToFormat α] : Trie α → Format
| Trie.node vs cs => Format.group $ Format.paren $
"node" ++ (if vs.isEmpty then Format.nil else " " ++ fmt vs)
++ Format.join (cs.toList.map $ fun ⟨k, c⟩ => Format.line ++ Format.paren (fmt k ++ " => " ++ format c))
instance [ToFormat α] : ToFormat (Trie α) := ⟨Trie.format⟩
partial def format [ToFormat α] (d : DiscrTree α) : Format :=
let (_, r) := d.root.foldl
(fun (p : Bool × Format) k c =>
(false, p.2 ++ (if p.1 then Format.nil else Format.line) ++ Format.paren (fmt k ++ " => " ++ fmt c)))
(true, Format.nil)
Format.group r
instance [ToFormat α] : ToFormat (DiscrTree α) := ⟨format⟩
/- The discrimination tree ignores implicit arguments and proofs.
We use the following auxiliary id as a "mark". -/
private def tmpMVarId : MVarId := `_discr_tree_tmp
private def tmpStar := mkMVar tmpMVarId
instance : Inhabited (DiscrTree α) where
default := {}
/--
Return true iff the argument should be treated as a "wildcard" by the discrimination tree.
- We ignore proofs because of proof irrelevance. It doesn't make sense to try to
index their structure.
- We ignore instance implicit arguments (e.g., `[Add α]`) because they are "morally" canonical.
Moreover, we may have many definitionally equal terms floating around.
Example: `Ring.hasAdd Int Int.isRing` and `Int.hasAdd`.
- We considered ignoring implicit arguments (e.g., `{α : Type}`) since users don't "see" them,
and may not even understand why some simplification rule is not firing.
However, in type class resolution, we have instance such as `Decidable (@Eq Nat x y)`,
where `Nat` is an implicit argument. Thus, we would add the path
```
Decidable -> Eq -> * -> * -> * -> [Nat.decEq]
```
to the discrimination tree IF we ignored the implict `Nat` argument.
This would be BAD since **ALL** decidable equality instances would be in the same path.
So, we index implicit arguments if they are types.
This setting seems sensible for simplification lemmas such as:
```
forall (x y : Unit), (@Eq Unit x y) = true
```
If we ignore the implicit argument `Unit`, the `DiscrTree` will say it is a candidate
simplification lemma for any equality in our goal.
Remark: if users have problems with the solution above, we may provide a `noIndexing` annotation,
and `ignoreArg` would return true for any term of the form `noIndexing t`.
-/
private def ignoreArg (a : Expr) (i : Nat) (infos : Array ParamInfo) : MetaM Bool := do
if h : i < infos.size then
let info := infos.get ⟨i, h⟩
if info.instImplicit then
return true
else if info.implicit then
return not (← isType a)
else
isProof a
else
isProof a
private partial def pushArgsAux (infos : Array ParamInfo) : Nat → Expr → Array Expr → MetaM (Array Expr)
| i, Expr.app f a _, todo => do
if (← ignoreArg a i infos) then
pushArgsAux infos (i-1) f (todo.push tmpStar)
else
pushArgsAux infos (i-1) f (todo.push a)
| _, _, todo => return todo
private partial def whnfEta (e : Expr) : MetaM Expr := do
let e ← whnf e
match e.etaExpandedStrict? with
| some e => whnfEta e
| none => return e
/--
Return true if `e` is one of the following
- A nat literal (numeral)
- `Nat.zero`
- `Nat.succ x` where `isNumeral x`
- `OfNat.ofNat _ x _` where `isNumeral x` -/
private partial def isNumeral (e : Expr) : Bool :=
if e.isNatLit then true
else
let f := e.getAppFn
if !f.isConst then false
else
let fName := f.constName!
if fName == ``Nat.succ && e.getAppNumArgs == 1 then isNumeral e.appArg!
else if fName == ``OfNat.ofNat && e.getAppNumArgs == 3 then isNumeral (e.getArg! 1)
else if fName == ``Nat.zero && e.getAppNumArgs == 0 then true
else false
private def isNatType (e : Expr) : MetaM Bool :=
return (← whnf e).isConstOf ``Nat
/--
Return true if `e` is one of the following
- `Nat.add _ k` where `isNumeral k`
- `Add.add Nat _ _ k` where `isNumeral k`
- `HAdd.hAdd _ Nat _ _ k` where `isNumeral k`
- `Nat.succ _`
This function assumes `e.isAppOf fName`
-/
private def isOffset (fName : Name) (e : Expr) : MetaM Bool := do
if fName == ``Nat.add && e.getAppNumArgs == 2 then
return isNumeral e.appArg!
else if fName == ``Add.add && e.getAppNumArgs == 4 then
if (← isNatType (e.getArg! 0)) then return isNumeral e.appArg! else return false
else if fName == ``HAdd.hAdd && e.getAppNumArgs == 6 then
if (← isNatType (e.getArg! 1)) then return isNumeral e.appArg! else return false
else
return fName == ``Nat.succ && e.getAppNumArgs == 1
/-
TODO: add hook for users adding their own functions for controlling `shouldAddAsStar`
Different `DiscrTree` users may populate this set using, for example, attributes.
Remark: we currently tag `Nat.zero` and "offset" terms to avoid having to add special
support for `Expr.lit` and offset terms.
Example, suppose the discrimination tree contains the entry
`Nat.succ ?m |-> v`, and we are trying to retrieve the matches for `Expr.lit (Literal.natVal 1) _`.
In this scenario, we want to retrieve `Nat.succ ?m |-> v` -/
private def shouldAddAsStar (fName : Name) (e : Expr) : MetaM Bool := do
if fName == `Nat.zero then
return true
else
isOffset fName e
def mkNoindexAnnotation (e : Expr) : Expr :=
mkAnnotation `noindex e
def hasNoindexAnnotation (e : Expr) : Bool :=
annotation? `noindex e |>.isSome
/- Remark: we use `shouldAddAsStar` only for nested terms, and `root == false` for nested terms -/
private def pushArgs (root : Bool) (todo : Array Expr) (e : Expr) : MetaM (Key × Array Expr) := do
if hasNoindexAnnotation e then
return (Key.star, todo)
else
let e ← whnfEta e
let fn := e.getAppFn
let push (k : Key) (nargs : Nat) : MetaM (Key × Array Expr) := do
let info ← getFunInfoNArgs fn nargs
let todo ← pushArgsAux info.paramInfo (nargs-1) e todo
return (k, todo)
match fn with
| Expr.lit v _ => return (Key.lit v, todo)
| Expr.const c _ _ =>
unless root do
if (← shouldAddAsStar c e) then
return (Key.star, todo)
let nargs := e.getAppNumArgs
push (Key.const c nargs) nargs
| Expr.fvar fvarId _ =>
let nargs := e.getAppNumArgs
push (Key.fvar fvarId nargs) nargs
| Expr.mvar mvarId _ =>
if mvarId == tmpMVarId then
-- We use `tmp to mark implicit arguments and proofs
return (Key.star, todo)
else if (← isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then
return (Key.other, todo)
else
return (Key.star, todo)
| Expr.forallE _ d b _ =>
if b.hasLooseBVars then
return (Key.other, todo)
else
return (Key.arrow, todo.push d |>.push b)
| _ =>
return (Key.other, todo)
partial def mkPathAux (root : Bool) (todo : Array Expr) (keys : Array Key) : MetaM (Array Key) := do
if todo.isEmpty then
return keys
else
let e := todo.back
let todo := todo.pop
let (k, todo) ← pushArgs root todo e
mkPathAux false todo (keys.push k)
private def initCapacity := 8
def mkPath (e : Expr) : MetaM (Array Key) := do
withReducible do
let todo : Array Expr := Array.mkEmpty initCapacity
let keys : Array Key := Array.mkEmpty initCapacity
mkPathAux (root := true) (todo.push e) keys
private partial def createNodes (keys : Array Key) (v : α) (i : Nat) : Trie α :=
if h : i < keys.size then
let k := keys.get ⟨i, h⟩
let c := createNodes keys v (i+1)
Trie.node #[] #[(k, c)]
else
Trie.node #[v] #[]
private def insertVal [BEq α] (vs : Array α) (v : α) : Array α :=
if vs.contains v then vs else vs.push v
private partial def insertAux [BEq α] (keys : Array Key) (v : α) : Nat → Trie α → Trie α
| i, Trie.node vs cs =>
if h : i < keys.size then
let k := keys.get ⟨i, h⟩
let c := Id.run $ cs.binInsertM
(fun a b => a.1 < b.1)
(fun ⟨_, s⟩ => let c := insertAux keys v (i+1) s; (k, c)) -- merge with existing
(fun _ => let c := createNodes keys v (i+1); (k, c))
(k, arbitrary)
Trie.node vs c
else
Trie.node (insertVal vs v) cs
def insertCore [BEq α] (d : DiscrTree α) (keys : Array Key) (v : α) : DiscrTree α :=
if keys.isEmpty then panic! "invalid key sequence"
else
let k := keys[0]
match d.root.find? k with
| none =>
let c := createNodes keys v 1
{ root := d.root.insert k c }
| some c =>
let c := insertAux keys v 1 c
{ root := d.root.insert k c }
def insert [BEq α] (d : DiscrTree α) (e : Expr) (v : α) : MetaM (DiscrTree α) := do
let keys ← mkPath e
return d.insertCore keys v
private def getKeyArgs (e : Expr) (isMatch : Bool) : MetaM (Key × Array Expr) := do
let e ← whnfEta e
match e.getAppFn with
| Expr.lit v _ => return (Key.lit v, #[])
| Expr.const c _ _ =>
let nargs := e.getAppNumArgs
return (Key.const c nargs, e.getAppRevArgs)
| Expr.fvar fvarId _ =>
let nargs := e.getAppNumArgs
return (Key.fvar fvarId nargs, e.getAppRevArgs)
| Expr.mvar mvarId _ =>
if isMatch then
return (Key.other, #[])
else do
let ctx ← read
if ctx.config.isDefEqStuckEx then
/-
When the configuration flag `isDefEqStuckEx` is set to true,
we want `isDefEq` to throw an exception whenever it tries to assign
a read-only metavariable.
This feature is useful for type class resolution where
we may want to notify the caller that the TC problem may be solveable
later after it assigns `?m`.
The method `DiscrTree.getUnify e` returns candidates `c` that may "unify" with `e`.
That is, `isDefEq c e` may return true. Now, consider `DiscrTree.getUnify d (Add ?m)`
where `?m` is a read-only metavariable, and the discrimination tree contains the keys
`HadAdd Nat` and `Add Int`. If `isDefEqStuckEx` is set to true, we must treat `?m` as
a regular metavariable here, otherwise we return the empty set of candidates.
This is incorrect because it is equivalent to saying that there is no solution even if
the caller assigns `?m` and try again. -/
return (Key.star, #[])
else if (← isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then
return (Key.other, #[])
else
return (Key.star, #[])
| Expr.forallE _ d b _ =>
if b.hasLooseBVars then
return (Key.other, #[])
else
return (Key.arrow, #[d, b])
| _ =>
return (Key.other, #[])
private abbrev getMatchKeyArgs (e : Expr) : MetaM (Key × Array Expr) :=
getKeyArgs e (isMatch := true)
private abbrev getUnifyKeyArgs (e : Expr) : MetaM (Key × Array Expr) :=
getKeyArgs e (isMatch := false)
private def getStarResult (d : DiscrTree α) : Array α :=
let result : Array α := Array.mkEmpty initCapacity
match d.root.find? Key.star with
| none => result
| some (Trie.node vs _) => result ++ vs
private abbrev findKey (cs : Array (Key × Trie α)) (k : Key) : Option (Key × Trie α) :=
cs.binSearch (k, arbitrary) (fun a b => a.1 < b.1)
partial def getMatch (d : DiscrTree α) (e : Expr) : MetaM (Array α) :=
withReducible do
let result := getStarResult d
let (k, args) ← getMatchKeyArgs e
match k with
| Key.star => return result
| _ =>
match d.root.find? k with
| none => return result
| some c => process args c result
where
process (todo : Array Expr) (c : Trie α) (result : Array α) : MetaM (Array α) := do
match c with
| Trie.node vs cs =>
if todo.isEmpty then
return result ++ vs
else if cs.isEmpty then
return result
else
let e := todo.back
let todo := todo.pop
let first := cs[0] /- Recall that `Key.star` is the minimal key -/
let (k, args) ← getMatchKeyArgs e
/- We must always visit `Key.star` edges since they are wildcards.
Thus, `todo` is not used linearly when there is `Key.star` edge
and there is an edge for `k` and `k != Key.star`. -/
let visitStar (result : Array α) : MetaM (Array α) :=
if first.1 == Key.star then
process todo first.2 result
else
return result
let visitNonStar (k : Key) (args : Array Expr) (result : Array α) : MetaM (Array α) :=
match findKey cs k with
| none => result
| some c => process (todo ++ args) c.2 result
let result ← visitStar result
match k with
| Key.star => result
/-
Recall that dependent arrows are `(Key.other, #[])`, and non-dependent arrows are `(Key.arrow, #[a, b])`.
A non-dependent arrow may be an instance of a dependent arrow (stored at `DiscrTree`). Thus, we also visit the `Key.other` child.
-/
| Key.arrow => visitNonStar Key.other #[] (← visitNonStar k args result)
| _ => visitNonStar k args result
partial def getUnify (d : DiscrTree α) (e : Expr) : MetaM (Array α) :=
withReducible do
let (k, args) ← getUnifyKeyArgs e
match k with
| Key.star => d.root.foldlM (init := #[]) fun result k c => process k.arity #[] c result
| _ =>
let result := getStarResult d
match d.root.find? k with
| none => return result
| some c => process 0 args c result
where
process (skip : Nat) (todo : Array Expr) (c : Trie α) (result : Array α) : MetaM (Array α) := do
match skip, c with
| skip+1, Trie.node vs cs =>
if cs.isEmpty then
return result
else
cs.foldlM (init := result) fun result ⟨k, c⟩ => process (skip + k.arity) todo c result
| 0, Trie.node vs cs => do
if todo.isEmpty then
return result ++ vs
else if cs.isEmpty then
return result
else
let e := todo.back
let todo := todo.pop
let (k, args) ← getUnifyKeyArgs e
let visitStar (result : Array α) : MetaM (Array α) :=
let first := cs[0]
if first.1 == Key.star then
process 0 todo first.2 result
else
return result
let visitNonStar (k : Key) (args : Array Expr) (result : Array α) : MetaM (Array α) :=
match findKey cs k with
| none => result
| some c => process 0 (todo ++ args) c.2 result
match k with
| Key.star => cs.foldlM (init := result) fun result ⟨k, c⟩ => process k.arity todo c result
-- See comment a `getMatch` regarding non-dependent arrows vs dependent arrows
| Key.arrow => visitNonStar Key.other #[] (← visitNonStar k args (← visitStar result))
| _ => visitNonStar k args (← visitStar result)
end Lean.Meta.DiscrTree
|
f42b7016756992d7e6a2db9fa13cb3c32750c1f5 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/combinatorics/set_family/compression/uv.lean | 453c48e94f14e63b748d8a2fe7ae84eb2e3a4d92 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 8,898 | lean | /-
Copyright (c) 2021 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies, Bhavik Mehta
-/
import data.finset.card
/-!
# UV-compressions
This file defines UV-compression. It is an operation on a set family that reduces its shadow.
UV-compressing `a : α` along `u v : α` means replacing `a` by `(a ⊔ u) \ v` if `a` and `u` are
disjoint and `v ≤ a`. In some sense, it's moving `a` from `v` to `u`.
UV-compressions are immensely useful to prove the Kruskal-Katona theorem. The idea is that
compressing a set family might decrease the size of its shadow, so iterated compressions hopefully
minimise the shadow.
## Main declarations
* `uv.compress`: `compress u v a` is `a` compressed along `u` and `v`.
* `uv.compression`: `compression u v s` is the compression of the set family `s` along `u` and `v`.
It is the compressions of the elements of `s` whose compression is not already in `s` along with
the element whose compression is already in `s`. This way of splitting into what moves and what
does not ensures the compression doesn't squash the set family, which is proved by
`uv.card_compress`.
## Notation
`𝓒` (typed with `\MCC`) is notation for `uv.compression` in locale `finset_family`.
## Notes
Even though our emphasis is on `finset α`, we define UV-compressions more generally in a generalized
boolean algebra, so that one can use it for `set α`.
## TODO
Prove that compressing reduces the size of shadow. This result and some more already exist on the
branch `combinatorics`.
## References
* https://github.com/b-mehta/maths-notes/blob/master/iii/mich/combinatorics.pdf
## Tags
compression, UV-compression, shadow
-/
open finset
variable {α : Type*}
/-- UV-compression is injective on the elements it moves. See `uv.compress`. -/
lemma sup_sdiff_inj_on [generalized_boolean_algebra α] (u v : α) :
{x | disjoint u x ∧ v ≤ x}.inj_on (λ x, (x ⊔ u) \ v) :=
begin
rintro a ha b hb hab,
have h : (a ⊔ u) \ v \ u ⊔ v = (b ⊔ u) \ v \ u ⊔ v,
{ dsimp at hab,
rw hab },
rwa [sdiff_sdiff_comm, ha.1.symm.sup_sdiff_cancel_right, sdiff_sdiff_comm,
hb.1.symm.sup_sdiff_cancel_right, sdiff_sup_cancel ha.2, sdiff_sup_cancel hb.2] at h,
end
-- The namespace is here to distinguish from other compressions.
namespace uv
/-! ### UV-compression in generalized boolean algebras -/
section generalized_boolean_algebra
variables [generalized_boolean_algebra α] [decidable_rel (@disjoint α _ _)]
[decidable_rel ((≤) : α → α → Prop)] {s : finset α} {u v a b : α}
local attribute [instance] decidable_eq_of_decidable_le
/-- To UV-compress `a`, if it doesn't touch `U` and does contain `V`, we remove `V` and
put `U` in. We'll only really use this when `|U| = |V|` and `U ∩ V = ∅`. -/
def compress (u v a : α) : α := if disjoint u a ∧ v ≤ a then (a ⊔ u) \ v else a
/-- To UV-compress a set family, we compress each of its elements, except that we don't want to
reduce the cardinality, so we keep all elements whose compression is already present. -/
def compression (u v : α) (s : finset α) :=
s.filter (λ a, compress u v a ∈ s) ∪ (s.image $ compress u v).filter (λ a, a ∉ s)
localized "notation (name := uv.compression) `𝓒 ` := uv.compression" in finset_family
/-- `is_compressed u v s` expresses that `s` is UV-compressed. -/
def is_compressed (u v : α) (s : finset α) := 𝓒 u v s = s
lemma compress_of_disjoint_of_le (hua : disjoint u a) (hva : v ≤ a) :
compress u v a = (a ⊔ u) \ v :=
if_pos ⟨hua, hva⟩
/-- `a` is in the UV-compressed family iff it's in the original and its compression is in the
original, or it's not in the original but it's the compression of something in the original. -/
lemma mem_compression :
a ∈ 𝓒 u v s ↔ a ∈ s ∧ compress u v a ∈ s ∨ a ∉ s ∧ ∃ b ∈ s, compress u v b = a :=
by simp_rw [compression, mem_union, mem_filter, mem_image, and_comm (a ∉ s)]
@[simp] lemma compress_self (u a : α) : compress u u a = a :=
begin
unfold compress,
split_ifs,
{ exact h.1.symm.sup_sdiff_cancel_right },
{ refl }
end
@[simp] lemma compression_self (u : α) (s : finset α) : 𝓒 u u s = s :=
begin
unfold compression,
convert union_empty s,
{ ext a,
rw [mem_filter, compress_self, and_self] },
{ refine eq_empty_of_forall_not_mem (λ a ha, _),
simp_rw [mem_filter, mem_image, compress_self] at ha,
obtain ⟨⟨b, hb, rfl⟩, hb'⟩ := ha,
exact hb' hb }
end
/-- Any family is compressed along two identical elements. -/
lemma is_compressed_self (u : α) (s : finset α) : is_compressed u u s := compression_self u s
lemma compress_disjoint (u v : α) :
disjoint (s.filter (λ a, compress u v a ∈ s)) ((s.image $ compress u v).filter (λ a, a ∉ s)) :=
disjoint_left.2 $ λ a ha₁ ha₂, (mem_filter.1 ha₂).2 (mem_filter.1 ha₁).1
/-- Compressing an element is idempotent. -/
@[simp] lemma compress_idem (u v a : α) : compress u v (compress u v a) = compress u v a :=
begin
unfold compress,
split_ifs with h h',
{ rw [le_sdiff_iff.1 h'.2, sdiff_bot, sdiff_bot, sup_assoc, sup_idem] },
{ refl },
{ refl }
end
lemma compress_mem_compression (ha : a ∈ s) : compress u v a ∈ 𝓒 u v s :=
begin
rw mem_compression,
by_cases compress u v a ∈ s,
{ rw compress_idem,
exact or.inl ⟨h, h⟩ },
{ exact or.inr ⟨h, a, ha, rfl⟩ }
end
-- This is a special case of `compress_mem_compression` once we have `compression_idem`.
lemma compress_mem_compression_of_mem_compression (ha : a ∈ 𝓒 u v s) : compress u v a ∈ 𝓒 u v s :=
begin
rw mem_compression at ⊢ ha,
simp only [compress_idem, exists_prop],
obtain ⟨_, ha⟩ | ⟨_, b, hb, rfl⟩ := ha,
{ exact or.inl ⟨ha, ha⟩ },
{ exact or.inr ⟨by rwa compress_idem, b, hb, (compress_idem _ _ _).symm⟩ }
end
/-- Compressing a family is idempotent. -/
@[simp] lemma compression_idem (u v : α) (s : finset α) : 𝓒 u v (𝓒 u v s) = 𝓒 u v s :=
begin
have h : filter (λ a, compress u v a ∉ 𝓒 u v s) (𝓒 u v s) = ∅ :=
filter_false_of_mem (λ a ha h, h $ compress_mem_compression_of_mem_compression ha),
rw [compression, image_filter, h, image_empty, ←h],
exact filter_union_filter_neg_eq _ (compression u v s),
end
/-- Compressing a family doesn't change its size. -/
lemma card_compression (u v : α) (s : finset α) : (𝓒 u v s).card = s.card :=
begin
rw [compression, card_disjoint_union (compress_disjoint _ _), image_filter, card_image_of_inj_on,
←card_disjoint_union, filter_union_filter_neg_eq],
{ rw disjoint_iff_inter_eq_empty,
exact filter_inter_filter_neg_eq _ _ },
intros a ha b hb hab,
dsimp at hab,
rw [mem_coe, mem_filter, function.comp_app] at ha hb,
rw compress at ha hab,
split_ifs at ha hab with has,
{ rw compress at hb hab,
split_ifs at hb hab with hbs,
{ exact sup_sdiff_inj_on u v has hbs hab },
{ exact (hb.2 hb.1).elim } },
{ exact (ha.2 ha.1).elim }
end
/-- If `a` is in the family compression and can be compressed, then its compression is in the
original family. -/
lemma sup_sdiff_mem_of_mem_compression (ha : a ∈ 𝓒 u v s) (hva : v ≤ a) (hua : disjoint u a) :
(a ⊔ u) \ v ∈ s :=
begin
rw [mem_compression, compress_of_disjoint_of_le hua hva] at ha,
obtain ⟨_, ha⟩ | ⟨_, b, hb, rfl⟩ := ha,
{ exact ha },
have hu : u = ⊥,
{ suffices : disjoint u (u \ v),
{ rwa [(hua.mono_right hva).sdiff_eq_left, disjoint_self] at this },
refine hua.mono_right _,
rw [←compress_idem, compress_of_disjoint_of_le hua hva],
exact sdiff_le_sdiff_right le_sup_right },
have hv : v = ⊥,
{ rw ←disjoint_self,
apply disjoint.mono_right hva,
rw [←compress_idem, compress_of_disjoint_of_le hua hva],
exact disjoint_sdiff_self_right },
rwa [hu, hv, compress_self, sup_bot_eq, sdiff_bot],
end
/-- If `a` is in the `u, v`-compression but `v ≤ a`, then `a` must have been in the original
family. -/
lemma mem_of_mem_compression (ha : a ∈ 𝓒 u v s) (hva : v ≤ a) (hvu : v = ⊥ → u = ⊥) : a ∈ s :=
begin
rw mem_compression at ha,
obtain ha | ⟨_, b, hb, h⟩ := ha,
{ exact ha.1 },
unfold compress at h,
split_ifs at h,
{ rw [←h, le_sdiff_iff] at hva,
rw [hvu hva, hva, sup_bot_eq, sdiff_bot] at h,
rwa ←h },
{ rwa ←h }
end
end generalized_boolean_algebra
/-! ### UV-compression on finsets -/
open_locale finset_family
variables [decidable_eq α] {𝒜 : finset (finset α)} {U V A : finset α}
/-- Compressing a finset doesn't change its size. -/
lemma card_compress (hUV : U.card = V.card) (A : finset α) : (compress U V A).card = A.card :=
begin
unfold compress,
split_ifs,
{ rw [card_sdiff (h.2.trans le_sup_left), sup_eq_union, card_disjoint_union h.1.symm, hUV,
add_tsub_cancel_right] },
{ refl }
end
end uv
|
542ddff16d7db140fe681c8dab9641eeadadf897 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/data/multiset/bind.lean | 7e04601843c552c23abe2564ffd4fefa4b3ccd19 | [
"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 | 9,161 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import algebra.big_operators.multiset
/-!
# Bind operation for multisets
This file defines a few basic operations on `multiset`, notably the monadic bind.
## Main declarations
* `multiset.join`: The join, aka union or sum, of multisets.
* `multiset.bind`: The bind of a multiset-indexed family of multisets.
* `multiset.product`: Cartesian product of two multisets.
* `multiset.sigma`: Disjoint sum of multisets in a sigma type.
-/
variables {α β γ δ : Type*}
namespace multiset
/-! ### Join -/
/-- `join S`, where `S` is a multiset of multisets, is the lift of the list join
operation, that is, the union of all the sets.
join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/
def join : multiset (multiset α) → multiset α := sum
lemma coe_join : ∀ L : list (list α),
join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join
| [] := rfl
| (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L)
@[simp] lemma join_zero : @join α 0 = 0 := rfl
@[simp] lemma join_cons (s S) : @join α (s ::ₘ S) = s + join S := sum_cons _ _
@[simp] lemma join_add (S T) : @join α (S + T) = join S + join T := sum_add _ _
@[simp] lemma singleton_join (a) : join ({a} : multiset (multiset α)) = a := sum_singleton _
@[simp] lemma mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s :=
multiset.induction_on S (by simp) $
by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt}
@[simp] lemma card_join (S) : card (@join α S) = sum (map card S) :=
multiset.induction_on S (by simp) (by simp)
lemma rel_join {r : α → β → Prop} {s t} (h : rel (rel r) s t) : rel r s.join t.join :=
begin
induction h,
case rel.zero { simp },
case rel.cons : a b s t hab hst ih { simpa using hab.add ih }
end
/-! ### Bind -/
section bind
variables (a : α) (s t : multiset α) (f g : α → multiset β)
/-- `s.bind f` is the monad bind operation, defined as `(s.map f).join`. It is the union of `f a` as
`a` ranges over `s`. -/
def bind (s : multiset α) (f : α → multiset β) : multiset β := (s.map f).join
@[simp] lemma coe_bind (l : list α) (f : α → list β) : @bind α β l (λ a, f a) = l.bind f :=
by rw [list.bind, ←coe_join, list.map_map]; refl
@[simp] lemma zero_bind : bind 0 f = 0 := rfl
@[simp] lemma cons_bind : (a ::ₘ s).bind f = f a + s.bind f := by simp [bind]
@[simp] lemma singleton_bind : bind {a} f = f a := by simp [bind]
@[simp] lemma add_bind : (s + t).bind f = s.bind f + t.bind f := by simp [bind]
@[simp] lemma bind_zero : s.bind (λ a, 0 : α → multiset β) = 0 := by simp [bind, join, nsmul_zero]
@[simp] lemma bind_add : s.bind (λ a, f a + g a) = s.bind f + s.bind g := by simp [bind, join]
@[simp] lemma bind_cons (f : α → β) (g : α → multiset β) :
s.bind (λ a, f a ::ₘ g a) = map f s + s.bind g :=
multiset.induction_on s (by simp) (by simp [add_comm, add_left_comm] {contextual := tt})
@[simp] lemma bind_singleton (f : α → β) : s.bind (λ x, ({f x} : multiset β)) = map f s :=
multiset.induction_on s (by rw [zero_bind, map_zero]) (by simp [singleton_add])
@[simp] lemma mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a :=
by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm];
rw exists_swap; simp [and_assoc]
@[simp] lemma card_bind : (s.bind f).card = (s.map (card ∘ f)).sum := by simp [bind]
lemma bind_congr {f g : α → multiset β} {m : multiset α} :
(∀ a ∈ m, f a = g a) → bind m f = bind m g :=
by simp [bind] {contextual := tt}
lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'}
(h : β = β') (hf : ∀a ∈ m, f a == f' a) :
bind m f == bind m f' :=
begin subst h, simp at hf, simp [bind_congr hf] end
lemma map_bind (m : multiset α) (n : α → multiset β) (f : β → γ) :
map f (bind m n) = bind m (λ a, map f (n a)) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_map (m : multiset α) (n : β → multiset γ) (f : α → β) :
bind (map f m) n = bind m (λ a, n (f a)) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_assoc {s : multiset α} {f : α → multiset β} {g : β → multiset γ} :
(s.bind f).bind g = s.bind (λ a, (f a).bind g) :=
multiset.induction_on s (by simp) (by simp {contextual := tt})
lemma bind_bind (m : multiset α) (n : multiset β) {f : α → β → multiset γ} :
(bind m $ λ a, bind n $ λ b, f a b) = (bind n $ λ b, bind m $ λ a, f a b) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_map_comm (m : multiset α) (n : multiset β) {f : α → β → γ} :
(bind m $ λ a, n.map $ λ b, f a b) = (bind n $ λ b, m.map $ λ a, f a b) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
@[simp, to_additive]
lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) :
(s.bind t).prod = (s.map $ λ a, (t a).prod).prod :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind])
lemma rel_bind {r : α → β → Prop} {p : γ → δ → Prop} {s t} {f : α → multiset γ} {g : β → multiset δ}
(h : (r ⇒ rel p) f g) (hst : rel r s t) :
rel p (s.bind f) (t.bind g) :=
by { apply rel_join, rw rel_map, exact hst.mono (λ a ha b hb hr, h hr) }
lemma count_sum [decidable_eq α] {m : multiset β} {f : β → multiset α} {a : α} :
count a (map f m).sum = sum (m.map $ λ b, count a $ f b) :=
multiset.induction_on m (by simp) ( by simp)
lemma count_bind [decidable_eq α] {m : multiset β} {f : β → multiset α} {a : α} :
count a (bind m f) = sum (m.map $ λ b, count a $ f b) := count_sum
lemma le_bind {α β : Type*} {f : α → multiset β} (S : multiset α) {x : α} (hx : x ∈ S) :
f x ≤ S.bind f :=
begin
classical,
rw le_iff_count, intro a,
rw count_bind, apply le_sum_of_mem,
rw mem_map, exact ⟨x, hx, rfl⟩
end
end bind
/-! ### Product of two multisets -/
section product
variables (a : α) (b : β) (s : multiset α) (t : multiset β)
/-- The multiplicity of `(a, b)` in `s.product t` is
the product of the multiplicity of `a` in `s` and `b` in `t`. -/
def product (s : multiset α) (t : multiset β) : multiset (α × β) := s.bind $ λ a, t.map $ prod.mk a
@[simp] lemma coe_product (l₁ : list α) (l₂ : list β) : @product α β l₁ l₂ = l₁.product l₂ :=
by { rw [product, list.product, ←coe_bind], simp }
@[simp] lemma zero_product : @product α β 0 t = 0 := rfl
--TODO: Add `product_zero`
@[simp] lemma cons_product : (a ::ₘ s).product t = map (prod.mk a) t + s.product t :=
by simp [product]
@[simp] lemma product_singleton : ({a} : multiset α).product ({b} : multiset β) = {(a, b)} :=
by simp only [product, bind_singleton, map_singleton]
@[simp] lemma add_product (s t : multiset α) (u : multiset β) :
(s + t).product u = s.product u + product t u :=
by simp [product]
@[simp] lemma product_add (s : multiset α) : ∀ t u : multiset β,
s.product (t + u) = s.product t + s.product u :=
multiset.induction_on s (λ t u, rfl) $ λ a s IH t u,
by rw [cons_product, IH]; simp; cc
@[simp] lemma mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t
| (a, b) := by simp [product, and.left_comm]
@[simp] lemma card_product : (s.product t).card = s.card * t.card :=
by simp [product, repeat, (∘), mul_comm]
end product
/-! ### Disjoint sum of multisets -/
section sigma
variables {σ : α → Type*} (a : α) (s : multiset α) (t : Π a, multiset (σ a))
/-- `sigma s t` is the dependent version of `product`. It is the sum of
`(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/
protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) :=
s.bind $ λ a, (t a).map $ sigma.mk a
@[simp] lemma coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) :
@multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ :=
by rw [multiset.sigma, list.sigma, ←coe_bind]; simp
@[simp] lemma zero_sigma : @multiset.sigma α σ 0 t = 0 := rfl
@[simp] lemma cons_sigma : (a ::ₘ s).sigma t = (t a).map (sigma.mk a) + s.sigma t :=
by simp [multiset.sigma]
@[simp] lemma sigma_singleton (b : α → β) :
({a} : multiset α).sigma (λ a, ({b a} : multiset β)) = {⟨a, b a⟩} := rfl
@[simp] lemma add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) :
(s + t).sigma u = s.sigma u + t.sigma u :=
by simp [multiset.sigma]
@[simp] lemma sigma_add : ∀ t u : Π a, multiset (σ a),
s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u :=
multiset.induction_on s (λ t u, rfl) $ λ a s IH t u,
by rw [cons_sigma, IH]; simp; cc
@[simp] lemma mem_sigma {s t} : ∀ {p : Σ a, σ a},
p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1
| ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm]
@[simp] lemma card_sigma :
card (s.sigma t) = sum (map (λ a, card (t a)) s) :=
by simp [multiset.sigma, (∘)]
end sigma
end multiset
|
bef0acdb802b81c1acba42beff7b6af77271e325 | c37c89b934e368a90005cf2a72457da4d59a48a1 | /fixedpoint/src/Fixedpoint.lean | 3cc526ff7a6e48378233c24f2a095608c709e697 | [
"Apache-2.0"
] | permissive | mukeshtiwari/Leanplayground | aa1cd9c69d4f1db6c824778a560c72f1e5aeaf65 | 773deaf73fbb677cdf518d0db34ad62a79bad642 | refs/heads/master | 1,667,860,698,346 | 1,664,052,419,000 | 1,664,052,419,000 | 209,532,791 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,285 | lean | import data.fintype data.list
namespace Fixedpoint
universes u
variables (A : Type u)
variables [finA : fintype A]
include finA
/- Boolean function representing set -/
def predicate := A -> bool
/- Subset set relation -/
def rel_subset (fSet sSet : predicate A) : Prop :=
∀ (x : A), fSet x = tt -> sSet x = tt
/- Subset equality -/
def eq_set (fSet sSet : predicate A) :=
and (rel_subset A fSet sSet)
(rel_subset A sSet fSet)
/- Subset relation is reflexive -/
lemma rel_subset_equal :
∀ (p : predicate A), rel_subset A p p :=
begin
intros _ _ Hp;
exact Hp
end
/- Subset relation is antisymmteric-/
lemma rel_subset_antisymmetric :
∀ (p q : predicate A), rel_subset A p q ->
rel_subset A q p -> eq_set A p q :=
begin
intros p q Hp Hq;
split; intros x Hx,
apply Hp, exact Hx,
apply Hq, exact Hx,
end
/- Subset relation is transitive-/
lemma subset_transitive :
∀ (p q r : predicate A), rel_subset A p q ->
rel_subset A q r -> rel_subset A p r :=
begin
intros p q r Hp Hq x Hx;
apply Hq; apply Hp; exact Hx,
end
/- subset relation is Partial order-/
lemma eq_subset_refl :
∀ (p : predicate A), eq_set A p p :=
begin
intro _; split;
intros _ Hp; exact Hp,
end
lemma eq_subset_symmetric :
∀ (p q : predicate A), eq_set A p q -> eq_set A q p :=
begin
intros p q Hp,
have Hpl : rel_subset A p q, from and.left Hp,
have Hpr : rel_subset A q p, from and.right Hp,
exact (and.intro Hpr Hpl)
end
def complement_set (p : predicate A) : predicate A :=
λ (x : A), bnot (p x)
def empty_set : predicate A :=
λ (x : A), ff
lemma empty_set_subset :
∀ (p : predicate A), rel_subset A (empty_set A) p :=
begin
intros _ _ Hx,
cases Hx
end
/- Subset relation is decidable on finite types -/
lemma decidable_equality_rel_set :
∀ (fSet sSet : predicate A), decidable (rel_subset A fSet sSet) :=
begin
intros fSet sSet,
apply fintype.decidable_forall_fintype
end
/- Equality is decidable on finite set -/
lemma decidable_equality_set :
∀ (fSet sSet : predicate A), decidable (eq_set A fSet sSet) :=
begin
intros fSet sSet,
have H₁ : decidable (rel_subset _ fSet sSet),
from (decidable_equality_rel_set _ fSet sSet),
have H₂ : decidable (rel_subset _ sSet fSet),
from (decidable_equality_rel_set _ sSet fSet),
apply (@and.decidable _ _ H₁ H₂),
end
lemma finite_type_list_ex :
∀ (fSet sSet : predicate A) (l : list A),
¬(∀ x : A, x ∈ l -> fSet x = sSet x) ->
∃ x : A, x ∈ l /\ fSet x ≠ sSet x :=
begin
intros fSet sSet l H,
induction l,
have H₁ : false,
apply H, intros,
cases a,
cases H₁,
have H₁ : fSet l_hd ≠ sSet l_hd ∨
fSet l_hd = sSet l_hd,
destruct (fSet l_hd);
destruct (sSet l_hd); intros,
right, rw [a, a_1],
left, intro, rw [a, a_1] at a_2,
cases a_2,
left, intro, rw [a, a_1] at a_2,
cases a_2,
right, rw [a, a_1],
destruct H₁; intros,
/- give l_hd as witness -/
have H₂ : l_hd ∈ (list.cons l_hd l_tl),
simp,
exact (exists.intro l_hd (and.intro H₂ h)),
have H₁ : ¬ (∀ x : A, x ∈ l_tl → fSet x = sSet x),
intro, apply H, intros, cases a_1,
rw a_1, assumption,
apply a, assumption,
let rw := l_ih H₁,
destruct rw, intros,
destruct h_1, intros,
have H₂ : w ∈ (list.cons l_hd l_tl),
simp, right, assumption,
exact (exists.intro w (and.intro H₂ right)),
end
lemma adding_new_element :
∀ (fSet sSet : predicate A), rel_subset _ fSet sSet ->
¬(∀ x : A, fSet x = sSet x) ->
∃ y : A, fSet y = ff ∧ sSet y = tt :=
begin
destruct (fintype.exists_univ_list A),
unfold rel_subset,
intros w Hl fSet sSet Hx Hnx,
let rw := finite_type_list_ex A fSet sSet w,
have H₁ : ¬(∀ x : A, x ∈ w -> fSet x = sSet x),
intro, apply Hnx,
intro, apply a, destruct Hl, intros,
apply right,
let an := rw H₁,
destruct an, intros,
destruct h, intros,
destruct (fSet w_1);
destruct (sSet w_1); intros,
rw [a, a_1] at right,
cases (right rfl),
exact (exists.intro w_1 (and.intro a_1 a)),
let hwt := Hx w_1 a_1,
rw hwt at a, cases a,
rw [a, a_1] at right,
cases (right rfl),
end
end Fixedpoint
|
7a6434bd3a168664cb53d882fc1f1c3c9226c43f | b00eb947a9c4141624aa8919e94ce6dcd249ed70 | /src/Lean/Parser/Syntax.lean | 381fe5d4d52d0cd1089b8a0873bc112729520719 | [
"Apache-2.0"
] | permissive | gebner/lean4-old | a4129a041af2d4d12afb3a8d4deedabde727719b | ee51cdfaf63ee313c914d83264f91f414a0e3b6e | refs/heads/master | 1,683,628,606,745 | 1,622,651,300,000 | 1,622,654,405,000 | 142,608,821 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,807 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
import Lean.Parser.Command
import Lean.Parser.Tactic
namespace Lean
namespace Parser
builtin_initialize
registerBuiltinParserAttribute `builtinSyntaxParser `stx LeadingIdentBehavior.both
registerBuiltinDynamicParserAttribute `stxParser `stx
builtin_initialize
registerBuiltinParserAttribute `builtinPrecParser `prec LeadingIdentBehavior.both
registerBuiltinDynamicParserAttribute `precParser `prec
@[inline] def precedenceParser (rbp : Nat := 0) : Parser :=
categoryParser `prec rbp
@[inline] def syntaxParser (rbp : Nat := 0) : Parser :=
categoryParser `stx rbp
def «precedence» := leading_parser ":" >> precedenceParser maxPrec
def optPrecedence := optional (atomic «precedence»)
namespace Syntax
@[builtinPrecParser] def numPrec := checkPrec maxPrec >> numLit
@[builtinSyntaxParser] def paren := leading_parser "(" >> many1 syntaxParser >> ")"
@[builtinSyntaxParser] def cat := leading_parser ident >> optPrecedence
@[builtinSyntaxParser] def unary := leading_parser ident >> checkNoWsBefore >> "(" >> many1 syntaxParser >> ")"
@[builtinSyntaxParser] def binary := leading_parser ident >> checkNoWsBefore >> "(" >> many1 syntaxParser >> ", " >> many1 syntaxParser >> ")"
@[builtinSyntaxParser] def sepBy := leading_parser "sepBy(" >> many1 syntaxParser >> ", " >> strLit >> optional (", " >> many1 syntaxParser) >> optional (", " >> nonReservedSymbol "allowTrailingSep") >> ")"
@[builtinSyntaxParser] def sepBy1 := leading_parser "sepBy1(" >> many1 syntaxParser >> ", " >> strLit >> optional (", " >> many1 syntaxParser) >> optional (", " >> nonReservedSymbol "allowTrailingSep") >> ")"
@[builtinSyntaxParser] def atom := leading_parser strLit
@[builtinSyntaxParser] def nonReserved := leading_parser "&" >> strLit
end Syntax
namespace Term
@[builtinTermParser] def stx.quot : Parser := leading_parser "`(stx|" >> incQuotDepth syntaxParser >> ")"
@[builtinTermParser] def prec.quot : Parser := leading_parser "`(prec|" >> incQuotDepth precedenceParser >> ")"
@[builtinTermParser] def prio.quot : Parser := leading_parser "`(prio|" >> incQuotDepth priorityParser >> ")"
end Term
namespace Command
def namedName := leading_parser (atomic ("(" >> nonReservedSymbol "name") >> " := " >> ident >> ")")
def optNamedName := optional namedName
def «prefix» := leading_parser "prefix"
def «infix» := leading_parser "infix"
def «infixl» := leading_parser "infixl"
def «infixr» := leading_parser "infixr"
def «postfix» := leading_parser "postfix"
def mixfixKind := «prefix» <|> «infix» <|> «infixl» <|> «infixr» <|> «postfix»
@[builtinCommandParser] def «mixfix» := leading_parser Term.attrKind >> mixfixKind >> optPrecedence >> optNamedName >> optNamedPrio >> ppSpace >> strLit >> darrow >> termParser
-- NOTE: We use `suppressInsideQuot` in the following parsers because quotations inside them are evaluated in the same stage and
-- thus should be ignored when we use `checkInsideQuot` to prepare the next stage for a builtin syntax change
def identPrec := leading_parser ident >> optPrecedence
def optKind : Parser := optional ("(" >> nonReservedSymbol "kind" >> ":=" >> ident >> ")")
def notationItem := ppSpace >> withAntiquot (mkAntiquot "notationItem" `Lean.Parser.Command.notationItem) (strLit <|> identPrec)
@[builtinCommandParser] def «notation» := leading_parser Term.attrKind >> "notation" >> optPrecedence >> optNamedName >> optNamedPrio >> many notationItem >> darrow >> termParser
@[builtinCommandParser] def «macro_rules» := suppressInsideQuot (leading_parser Term.attrKind >> "macro_rules" >> optKind >> Term.matchAlts)
@[builtinCommandParser] def «syntax» := leading_parser Term.attrKind >> "syntax " >> optPrecedence >> optNamedName >> optNamedPrio >> many1 syntaxParser >> " : " >> ident
@[builtinCommandParser] def syntaxAbbrev := leading_parser "syntax " >> ident >> " := " >> many1 syntaxParser
@[builtinCommandParser] def syntaxCat := leading_parser "declare_syntax_cat " >> ident
def macroArgSimple := leading_parser ident >> checkNoWsBefore "no space before ':'" >> ":" >> syntaxParser maxPrec
def macroArgSymbol := leading_parser strLit >> optional (atomic <| checkNoWsBefore >> "%" >> checkNoWsBefore >> ident)
def macroArg := macroArgSymbol <|> atomic macroArgSimple
def macroHead := macroArg
def macroTailTactic : Parser := atomic (" : " >> identEq "tactic") >> darrow >> ("`(" >> incQuotDepth Tactic.seq1 >> ")" <|> termParser)
def macroTailCommand : Parser := atomic (" : " >> identEq "command") >> darrow >> ("`(" >> incQuotDepth (many1Unbox commandParser) >> ")" <|> termParser)
def macroTailDefault : Parser := atomic (" : " >> ident) >> darrow >> (("`(" >> incQuotDepth (categoryParserOfStack 2) >> ")") <|> termParser)
def macroTail := macroTailTactic <|> macroTailCommand <|> macroTailDefault
@[builtinCommandParser] def «macro» := leading_parser suppressInsideQuot (Term.attrKind >> "macro " >> optPrecedence >> optNamedName >> optNamedPrio >> macroHead >> many macroArg >> macroTail)
@[builtinCommandParser] def «elab_rules» := leading_parser suppressInsideQuot ("elab_rules" >> optKind >> optional (" : " >> ident) >> Term.matchAlts)
def elabHead := macroHead
def elabArg := macroArg
def elabTail := atomic (" : " >> ident >> optional (" <= " >> ident)) >> darrow >> termParser
@[builtinCommandParser] def «elab» := leading_parser suppressInsideQuot (Term.attrKind >> "elab " >> optPrecedence >> optNamedName >> optNamedPrio >> elabHead >> many elabArg >> elabTail)
end Command
end Parser
end Lean
|
18ba151cdec25770055cc41e2bc7a326027456ee | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/nat/hyperoperation.lean | 739603bb2df950e4ac7fcd4390ed7c958a0a101e | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 3,526 | lean | /-
Copyright (c) 2023 Mark Andrew Gerads. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mark Andrew Gerads, Junyan Xu, Eric Wieser
-/
import tactic.ring
import data.nat.parity
/-!
# Hyperoperation sequence
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines the Hyperoperation sequence.
`hyperoperation 0 m k = k + 1`
`hyperoperation 1 m k = m + k`
`hyperoperation 2 m k = m * k`
`hyperoperation 3 m k = m ^ k`
`hyperoperation (n + 3) m 0 = 1`
`hyperoperation (n + 1) m (k + 1) = hyperoperation n m (hyperoperation (n + 1) m k)`
## References
* <https://en.wikipedia.org/wiki/Hyperoperation>
## Tags
hyperoperation
-/
/--
Implementation of the hyperoperation sequence
where `hyperoperation n m k` is the `n`th hyperoperation between `m` and `k`.
-/
def hyperoperation : ℕ → ℕ → ℕ → ℕ
| 0 _ k := k + 1
| 1 m 0 := m
| 2 _ 0 := 0
| (n + 3) _ 0 := 1
| (n + 1) m (k + 1) := hyperoperation n m (hyperoperation (n + 1) m k)
-- Basic hyperoperation lemmas
@[simp] lemma hyperoperation_zero (m : ℕ) : hyperoperation 0 m = nat.succ :=
funext $ λ k, by rw [hyperoperation, nat.succ_eq_add_one]
lemma hyperoperation_ge_three_eq_one (n m : ℕ) : hyperoperation (n + 3) m 0 = 1 :=
by rw hyperoperation
lemma hyperoperation_recursion (n m k : ℕ) :
hyperoperation (n + 1) m (k + 1) = hyperoperation n m (hyperoperation (n + 1) m k) :=
by obtain (_|_|_) := n; rw hyperoperation
-- Interesting hyperoperation lemmas
@[simp] lemma hyperoperation_one : hyperoperation 1 = (+) :=
begin
ext m k,
induction k with bn bih,
{ rw [nat_add_zero m, hyperoperation], },
{ rw [hyperoperation_recursion, bih, hyperoperation_zero],
exact nat.add_assoc m bn 1, },
end
@[simp] lemma hyperoperation_two : hyperoperation 2 = (*) :=
begin
ext m k,
induction k with bn bih,
{ rw hyperoperation,
exact (nat.mul_zero m).symm, },
{ rw [hyperoperation_recursion, hyperoperation_one, bih],
ring, },
end
@[simp] lemma hyperoperation_three : hyperoperation 3 = (^) :=
begin
ext m k,
induction k with bn bih,
{ rw hyperoperation_ge_three_eq_one,
exact (pow_zero m).symm, },
{ rw [hyperoperation_recursion, hyperoperation_two, bih],
exact (pow_succ m bn).symm, },
end
lemma hyperoperation_ge_two_eq_self (n m : ℕ) : hyperoperation (n + 2) m 1 = m :=
begin
induction n with nn nih,
{ rw hyperoperation_two,
ring, },
{ rw [hyperoperation_recursion, hyperoperation_ge_three_eq_one, nih], },
end
lemma hyperoperation_two_two_eq_four (n : ℕ) : hyperoperation (n + 1) 2 2 = 4 :=
begin
induction n with nn nih,
{ rw hyperoperation_one, },
{ rw [hyperoperation_recursion, hyperoperation_ge_two_eq_self, nih], },
end
lemma hyperoperation_ge_three_one (n : ℕ) : ∀ (k : ℕ), hyperoperation (n + 3) 1 k = 1 :=
begin
induction n with nn nih,
{ intros k,
rw [hyperoperation_three, one_pow], },
{ intros k,
cases k,
{ rw hyperoperation_ge_three_eq_one, },
{ rw [hyperoperation_recursion, nih], }, },
end
lemma hyperoperation_ge_four_zero (n k : ℕ) :
hyperoperation (n + 4) 0 k = if (even k) then 1 else 0 :=
begin
induction k with kk kih,
{ rw hyperoperation_ge_three_eq_one,
simp only [even_zero, if_true], },
{ rw hyperoperation_recursion,
rw kih,
simp_rw nat.even_add_one,
split_ifs,
{ exact hyperoperation_ge_two_eq_self (n + 1) 0, },
{ exact hyperoperation_ge_three_eq_one n 0, }, },
end
|
c04a98a6856a08da09d137b4f386c475357546ca | 86f6f4f8d827a196a32bfc646234b73328aeb306 | /examples/logic/unnamed_1503.lean | 311757685b3bce2fcd1ba0d4fa91f2b76aa2f834 | [] | 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 | 190 | lean | import data.real.basic
-- BEGIN
example {x y : ℝ} (h₀ : x ≤ y) (h₁ : ¬ y ≤ x) : x ≤ y ∧ x ≠ y :=
begin
split,
{ assumption },
intro h,
apply h₁,
rw h
end
-- END |
edd53b7ed0879985af3280da0ca507e3ad401163 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/mv_polynomial/derivation.lean | 161fbbc4fd518ff1087632ea156b2fa1ee487c73 | [
"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,211 | 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 data.mv_polynomial.supported
import ring_theory.derivation
/-!
# Derivations of multivariate polynomials
In this file we prove that a derivation of `mv_polynomial σ R` is determined by its values on all
monomials `mv_polynomial.X i`. We also provide a constructor `mv_polynomial.mk_derivation` that
builds a derivation from its values on `X i`s and a linear equivalence
`mv_polynomial.equiv_derivation` between `σ → A` and `derivation (mv_polynomial σ R) A`.
-/
namespace mv_polynomial
open_locale big_operators
noncomputable theory
variables {σ R A : Type*} [comm_semiring R] [add_comm_monoid A]
[module R A] [module (mv_polynomial σ R) A]
section
variable (R)
/-- The derivation on `mv_polynomial σ R` that takes value `f i` on `X i`, as a linear map.
Use `mv_polynomial.mk_derivation` instead. -/
def mk_derivationₗ (f : σ → A) : mv_polynomial σ R →ₗ[R] A :=
finsupp.lsum R $ λ xs : σ →₀ ℕ, (linear_map.ring_lmap_equiv_self R R A).symm $
xs.sum $ λ i k, monomial (xs - finsupp.single i 1) (k : R) • f i
end
lemma mk_derivationₗ_monomial (f : σ → A) (s : σ →₀ ℕ) (r : R) :
mk_derivationₗ R f (monomial s r) =
r • (s.sum $ λ i k, monomial (s - finsupp.single i 1) (k : R) • f i) :=
sum_monomial_eq $ linear_map.map_zero _
lemma mk_derivationₗ_C (f : σ → A) (r : R) : mk_derivationₗ R f (C r) = 0 :=
(mk_derivationₗ_monomial f _ _).trans (smul_zero _)
lemma mk_derivationₗ_X (f : σ → A) (i : σ) : mk_derivationₗ R f (X i) = f i :=
(mk_derivationₗ_monomial f _ _).trans $ by simp
@[simp] lemma derivation_C (D : derivation R (mv_polynomial σ R) A) (a : R) : D (C a) = 0 :=
D.map_algebra_map a
@[simp] lemma derivation_C_mul (D : derivation R (mv_polynomial σ R) A) (a : R)
(f : mv_polynomial σ R) : D (C a * f) = a • D f :=
by rw [C_mul', D.map_smul]
/-- If two derivations agree on `X i`, `i ∈ s`, then they agree on all polynomials from
`mv_polynomial.supported R s`. -/
lemma derivation_eq_on_supported {D₁ D₂ : derivation R (mv_polynomial σ R) A} {s : set σ}
(h : set.eq_on (D₁ ∘ X) (D₂ ∘ X) s) {f : mv_polynomial σ R} (hf : f ∈ supported R s) :
D₁ f = D₂ f :=
derivation.eq_on_adjoin (set.ball_image_iff.2 h) hf
lemma derivation_eq_of_forall_mem_vars {D₁ D₂ : derivation R (mv_polynomial σ R) A}
{f : mv_polynomial σ R} (h : ∀ i ∈ f.vars, D₁ (X i) = D₂ (X i)) :
D₁ f = D₂ f :=
derivation_eq_on_supported h f.mem_supported_vars
lemma derivation_eq_zero_of_forall_mem_vars {D : derivation R (mv_polynomial σ R) A}
{f : mv_polynomial σ R} (h : ∀ i ∈ f.vars, D (X i) = 0) : D f = 0 :=
show D f = (0 : derivation R (mv_polynomial σ R) A) f,
from derivation_eq_of_forall_mem_vars h
@[ext] lemma derivation_ext {D₁ D₂ : derivation R (mv_polynomial σ R) A}
(h : ∀ i, D₁ (X i) = D₂ (X i)) :
D₁ = D₂ :=
derivation.ext $ λ f, derivation_eq_of_forall_mem_vars (λ i _, h i)
variables [is_scalar_tower R (mv_polynomial σ R) A]
lemma leibniz_iff_X (D : mv_polynomial σ R →ₗ[R] A) (h₁ : D 1 = 0) :
(∀ p q, D (p * q) = p • D q + q • D p) ↔
(∀ s i, D (monomial s 1 * X i) = (monomial s 1 : mv_polynomial σ R) • D (X i) +
(X i : mv_polynomial σ R) • D (monomial s 1)) :=
begin
refine ⟨λ H p i, H _ _, λ H, _⟩,
have hC : ∀ r, D (C r) = 0,
{ intro r, rw [C_eq_smul_one, D.map_smul, h₁, smul_zero] },
have : ∀ p i, D (p * X i) = p • D (X i) + (X i : mv_polynomial σ R) • D p,
{ intros p i,
induction p using mv_polynomial.induction_on' with s r p q hp hq,
{ rw [← mul_one r, ← C_mul_monomial, mul_assoc, C_mul', D.map_smul, H, C_mul', smul_assoc,
smul_add, D.map_smul, smul_comm r (X i)], apply_instance },
{ rw [add_mul, map_add, map_add, hp, hq, add_smul, smul_add, add_add_add_comm] } },
intros p q,
induction q using mv_polynomial.induction_on,
case h_C : c { rw [mul_comm, C_mul', hC, smul_zero, zero_add, D.map_smul,
C_eq_smul_one, smul_one_smul] },
case h_add : q₁ q₂ h₁ h₂ { simp only [mul_add, map_add, h₁, h₂, smul_add, add_smul], abel },
case h_X : q i hq { simp only [this, ← mul_assoc, hq, mul_smul, smul_add, smul_comm (X i),
add_assoc] }
end
variables (R)
/-- The derivation on `mv_polynomial σ R` that takes value `f i` on `X i`. -/
def mk_derivation (f : σ → A) : derivation R (mv_polynomial σ R) A :=
{ to_linear_map := mk_derivationₗ R f,
map_one_eq_zero' := mk_derivationₗ_C _ 1,
leibniz' := (leibniz_iff_X (mk_derivationₗ R f) (mk_derivationₗ_C _ 1)).2 $ λ s i,
begin
simp only [mk_derivationₗ_monomial, X, monomial_mul, one_smul, one_mul],
rw [finsupp.sum_add_index];
[skip, by simp, by { intros, simp only [nat.cast_add, (monomial _).map_add, add_smul] }],
rw [finsupp.sum_single_index, finsupp.sum_single_index]; [skip, by simp, by simp],
rw [tsub_self, add_tsub_cancel_right, nat.cast_one, ← C_apply, C_1, one_smul,
add_comm, finsupp.smul_sum],
refine congr_arg2 (+) rfl (finset.sum_congr rfl (λ j hj, _)), dsimp only,
rw [smul_smul, monomial_mul, one_mul, add_comm s, add_tsub_assoc_of_le],
rwa [finsupp.single_le_iff, nat.succ_le_iff, pos_iff_ne_zero, ← finsupp.mem_support_iff]
end }
@[simp] lemma mk_derivation_X (f : σ → A) (i : σ) : mk_derivation R f (X i) = f i :=
mk_derivationₗ_X f i
lemma mk_derivation_monomial (f : σ → A) (s : σ →₀ ℕ) (r : R) :
mk_derivation R f (monomial s r) =
r • (s.sum $ λ i k, monomial (s - finsupp.single i 1) (k : R) • f i) :=
mk_derivationₗ_monomial f s r
/-- `mv_polynomial.mk_derivation` as a linear equivalence. -/
def mk_derivation_equiv : (σ → A) ≃ₗ[R] derivation R (mv_polynomial σ R) A :=
linear_equiv.symm $
{ inv_fun := mk_derivation R,
to_fun := λ D i, D (X i),
map_add' := λ D₁ D₂, rfl,
map_smul' := λ c D, rfl,
left_inv := λ D, derivation_ext $ mk_derivation_X _ _,
right_inv := λ f, funext $ mk_derivation_X _ _ }
end mv_polynomial
|
5668d9c0421fd1e0a675b4f324cd1f6063c987de | 74a02dffce22907d2b61b8e226f1d9aa8384c7c0 | /Cli.lean | 418fa3a1f9baf43206d854520ca7df2278ca385b | [
"MIT"
] | permissive | mhuisi/lean4-cli-docker-test | 7e0566c7397746701162e2e22fbad38afcf1e9c4 | 6b3881eaa22596f6f430654f61fc03719ee18c62 | refs/heads/main | 1,680,104,973,886 | 1,616,975,353,000 | 1,616,975,353,000 | 352,411,347 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 38 | lean | import Cli.Basic
import Cli.Extensions |
47ae57da3a82b639956904f564c14e368069adb6 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Data/Lsp/Utf16.lean | 8f263ab1c0ab721b80875b131db958708439de00 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 2,998 | 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.Data.String
import Init.Data.Array
import Lean.Data.Lsp.Basic
import Lean.Data.Position
/-! LSP uses UTF-16 for indexing, so we need to provide some primitives
to interact with Lean strings using UTF-16 indices. -/
namespace Char
def utf16Size (c : Char) : UInt32 :=
if c.val ≤ 0xFFFF then 1 else 2
end Char
namespace String
private def csize16 (c : Char) : Nat :=
c.utf16Size.toNat
def utf16Length (s : String) : Nat :=
s.foldr (fun c acc => csize16 c + acc) 0
private def codepointPosToUtf16PosFromAux (s : String) : Nat → Pos → Nat → Nat
| 0, _, utf16pos => utf16pos
| cp+1, utf8pos, utf16pos => codepointPosToUtf16PosFromAux s cp (s.next utf8pos) (utf16pos + csize16 (s.get utf8pos))
/-- Computes the UTF-16 offset of the `n`-th Unicode codepoint
in the substring of `s` starting at UTF-8 offset `off`.
Yes, this is actually useful.-/
def codepointPosToUtf16PosFrom (s : String) (n : Nat) (off : Pos) : Nat :=
codepointPosToUtf16PosFromAux s n off 0
def codepointPosToUtf16Pos (s : String) (pos : Nat) : Nat :=
codepointPosToUtf16PosFrom s pos 0
private partial def utf16PosToCodepointPosFromAux (s : String) : Nat → Pos → Nat → Nat
| 0, _, cp => cp
| utf16pos, utf8pos, cp => utf16PosToCodepointPosFromAux s (utf16pos - csize16 (s.get utf8pos)) (s.next utf8pos) (cp + 1)
/-- Computes the position of the Unicode codepoint at UTF-16 offset
`utf16pos` in the substring of `s` starting at UTF-8 offset `off`. -/
def utf16PosToCodepointPosFrom (s : String) (utf16pos : Nat) (off : Pos) : Nat :=
utf16PosToCodepointPosFromAux s utf16pos off 0
def utf16PosToCodepointPos (s : String) (pos : Nat) : Nat :=
utf16PosToCodepointPosFrom s pos 0
/-- Starting at `utf8pos`, finds the UTF-8 offset of the `p`-th codepoint. -/
def codepointPosToUtf8PosFrom (s : String) : String.Pos → Nat → String.Pos
| utf8pos, 0 => utf8pos
| utf8pos, p+1 => codepointPosToUtf8PosFrom s (s.next utf8pos) p
end String
namespace Lean
namespace FileMap
/-- Computes an UTF-8 offset into `text.source`
from an LSP-style 0-indexed (ln, col) position. -/
def lspPosToUtf8Pos (text : FileMap) (pos : Lsp.Position) : String.Pos :=
let colPos :=
if h : pos.line < text.positions.size then
text.positions.get ⟨pos.line, h⟩
else if text.positions.isEmpty then
0
else
text.positions.back
let chr := text.source.utf16PosToCodepointPosFrom pos.character colPos
text.source.codepointPosToUtf8PosFrom colPos chr
def leanPosToLspPos (text : FileMap) : Lean.Position → Lsp.Position
| ⟨ln, col⟩ => ⟨ln-1, text.source.codepointPosToUtf16PosFrom col (text.positions.get! $ ln - 1)⟩
def utf8PosToLspPos (text : FileMap) (pos : String.Pos) : Lsp.Position :=
text.leanPosToLspPos (text.toPosition pos)
end FileMap
end Lean
|
ac95d7eded2c41f5d2ef69ec94ac7e94208c3075 | cb1829c15cd3d28210f93507f96dfb1f56ec0128 | /theorem_proving/06-interacting_with_lean.lean | 3dceb1585b2a796fcdf1bc8ba41ba1f3607395d4 | [] | no_license | williamdemeo/LEAN_wjd | 69f9f76e35092b89e4479a320be2fa3c18aed6fe | 13826c75c06ef435166a26a72e76fe984c15bad7 | refs/heads/master | 1,609,516,630,137 | 1,518,123,893,000 | 1,518,123,893,000 | 97,740,278 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,392 | lean | -- 6. Interacting with Lean
/- Not all of the information in this section will be useful right away.
Skim this section to get a sense of Lean's features, and return later, as necessary. -/
#print "========================================"
#print "Section 6.1. Importing Files"
#print " "
namespace Sec_6_1
/- When Lean starts, it automatically imports the contents of the library init folder,
which includes a number of fundamental definitions and constructions. If you want to
use additional files, they need to be imported manually.
The command `import foo bar.baz.blah` imports the files `foo.lean` and `bar/baz/blah.lean`,
where the descriptions are interpreted relative to the Lean search path.
One can also specify imports relative to the current directory; for example,
`import .foo ..bar.baz` tells Lean to import `foo.lean` from the current directory
and `bar/baz.lean` relative to the parent of the current directory. -/
end Sec_6_1
#print "========================================"
#print "Section 6.2. More on Sections"
#print " "
namespace Sec_6_2
/- The `section` command makes it possible not only to group together elements of a
theory that go together, but also to declare variables that are inserted as arguments
to theorems and definitions, as necessary. Remember that the point of the variable
command is to declare variables for use in theorems, as in the following example: -/
section
variables x y : ℕ
def double := x + x
#check double y
#check double (2 * x)
theorem t₁ : double (x + y) = double x + double y :=
by simp [double]
end
/- Note that double does not have y as argument. Variables are only included in
declarations where they are actually mentioned. -/
end Sec_6_2
#print "========================================"
#print "Section 6.3. More on Namespaces"
#print " "
/- The command `namespace foo` causes foo to be prepended to the name of each definition
and theorem until `end foo` is encountered. The command `open foo` then creates
temporary aliases to definitions and theorems that begin with prefix `foo`. -/
namespace Sec_6_3
namespace foo
def bar : ℕ := 1
end foo
open foo
#check bar
#check foo.bar
end Sec_6_3
#print "========================================"
#print "Section 6.4. Attributes"
#print " "
namespace Sec_6_4
end Sec_6_4
#print "========================================"
#print "Section 6.5. More on Implicit Arguments"
#print " "
namespace Sec_6_5
end Sec_6_5
#print "========================================"
#print "Section 6.6. Notation"
#print " "
namespace Sec_6_6
end Sec_6_6
#print "========================================"
#print "Section 6.7. Coercions"
#print " "
namespace Sec_6_7
end Sec_6_7
#print "========================================"
#print "Section 6.8. Displaying Information"
#print " "
namespace Sec_6_8
end Sec_6_8
#print "========================================"
#print "Section 6.9. Setting Options"
#print " "
namespace Sec_6_9
end Sec_6_9
#print "========================================"
#print "Section 6.10. Elaboration Hints"
#print " "
namespace Sec_6_10
end Sec_6_10
#print "========================================"
#print "Section 6.11. Using the Library"
#print " "
namespace Sec_6_11
end Sec_6_11
|
cd842c6f6e6d1311cfc7a7c18044cf9c652f153a | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/linear_algebra/matrix/dot_product.lean | c6b916b3ff7ebb8934a96e23580f7e8ca55e7802 | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 2,050 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Patrick Massot, Casper Putz, Anne Baanen
-/
import data.matrix.basic
import linear_algebra.std_basis
/-!
# Dot product of two vectors
This file contains some results on the map `matrix.dot_product`, which maps two
vectors `v w : n → R` to the sum of the entrywise products `v i * w i`.
## Main results
* `matrix.dot_product_std_basis_one`: the dot product of `v` with the `i`th
standard basis vector is `v i`
* `matrix.dot_product_eq_zero_iff`: if `v`'s' dot product with all `w` is zero,
then `v` is zero
## Tags
matrix, reindex
-/
universes v w
namespace matrix
variables {R : Type v} [semiring R] {n : Type w} [fintype n]
@[simp] lemma dot_product_std_basis_eq_mul [decidable_eq n] (v : n → R) (c : R) (i : n) :
dot_product v (linear_map.std_basis R (λ _, R) i c) = v i * c :=
begin
rw [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 dot_product_std_basis_one [decidable_eq n] (v : n → R) (i : n) :
dot_product v (linear_map.std_basis R (λ _, R) i 1) = v i :=
by rw [dot_product_std_basis_eq_mul, mul_one]
lemma dot_product_eq
(v w : n → R) (h : ∀ u, dot_product v u = dot_product w u) : v = w :=
begin
funext x,
classical,
rw [← dot_product_std_basis_one v x, ← dot_product_std_basis_one w x, h],
end
lemma dot_product_eq_iff {v w : n → R} :
(∀ u, dot_product v u = dot_product w u) ↔ v = w :=
⟨λ h, dot_product_eq v w h, λ h _, h ▸ rfl⟩
lemma dot_product_eq_zero (v : n → R) (h : ∀ w, dot_product v w = 0) : v = 0 :=
dot_product_eq _ _ $ λ u, (h u).symm ▸ (zero_dot_product u).symm
lemma dot_product_eq_zero_iff {v : n → R} : (∀ w, dot_product v w = 0) ↔ v = 0 :=
⟨λ h, dot_product_eq_zero v h, λ h w, h.symm ▸ zero_dot_product w⟩
end matrix
|
510d00f26301358a3fb1d0d3c0358714a05c4d20 | 3dd1b66af77106badae6edb1c4dea91a146ead30 | /tests/lean/run/n3.lean | 8498d81fc04a253b3577d30e97f8a3321e0de6ae | [
"Apache-2.0"
] | permissive | silky/lean | 79c20c15c93feef47bb659a2cc139b26f3614642 | df8b88dca2f8da1a422cb618cd476ef5be730546 | refs/heads/master | 1,610,737,587,697 | 1,406,574,534,000 | 1,406,574,534,000 | 22,362,176 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 616 | lean | definition Prop [inline] : Type.{1} := Type.{0}
variable N : Type.{1}
variable and : Prop → Prop → Prop
infixr `∧`:35 := and
variable le : N → N → Prop
variable lt : N → N → Prop
variable f : N → N
variable add : N → N → N
infixl `+`:65 := add
precedence `≤`:50
precedence `<`:50
infixl ≤ := le
infixl < := lt
notation A ≤ B:prev ≤ C:prev := A ≤ B ∧ B ≤ C
notation A ≤ B:prev < C:prev := A ≤ B ∧ B < C
notation A < B:prev ≤ C:prev := A < B ∧ B ≤ C
variables a b c d e : N
check a ≤ b ≤ f c + b ∧ a < b
check a ≤ d
check a < b ≤ c
check a ≤ b < c
check a < b
|
5acd3e43c25bb4589ba52e42b6864d325aefa400 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Data/PersistentArray.lean | 995a80e9a9c0aa265d868a834e429c3f1f5def5a | [
"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 | 14,184 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
universe u v w
namespace Lean
inductive PersistentArrayNode (α : Type u) where
| node (cs : Array (PersistentArrayNode α)) : PersistentArrayNode α
| leaf (vs : Array α) : PersistentArrayNode α
deriving Inhabited
namespace PersistentArrayNode
def isNode {α} : PersistentArrayNode α → Bool
| node _ => true
| leaf _ => false
end PersistentArrayNode
abbrev PersistentArray.initShift : USize := 5
abbrev PersistentArray.branching : USize := USize.ofNat (2 ^ PersistentArray.initShift.toNat)
structure PersistentArray (α : Type u) where
/- Recall that we run out of memory if we have more than `usizeSz/8` elements.
So, we can stop adding elements at `root` after `size > usizeSz`, and
keep growing the `tail`. This modification allow us to use `USize` instead
of `Nat` when traversing `root`. -/
root : PersistentArrayNode α := PersistentArrayNode.node (Array.mkEmpty PersistentArray.branching.toNat)
tail : Array α := Array.mkEmpty PersistentArray.branching.toNat
size : Nat := 0
shift : USize := PersistentArray.initShift
tailOff : Nat := 0
deriving Inhabited
abbrev PArray (α : Type u) := PersistentArray α
namespace PersistentArray
/- TODO: use proofs for showing that array accesses are not out of bounds.
We can do it after we reimplement the tactic framework. -/
variable {α : Type u}
open PersistentArrayNode
def empty : PersistentArray α := {}
def isEmpty (a : PersistentArray α) : Bool := a.size == 0
def mkEmptyArray : Array α := Array.mkEmpty branching.toNat
abbrev mul2Shift (i : USize) (shift : USize) : USize := i.shiftLeft shift
abbrev div2Shift (i : USize) (shift : USize) : USize := i.shiftRight shift
abbrev mod2Shift (i : USize) (shift : USize) : USize := USize.land i ((USize.shiftLeft 1 shift) - 1)
partial def getAux [Inhabited α] : PersistentArrayNode α → USize → USize → α
| node cs, i, shift => getAux cs[(div2Shift i shift).toNat]! (mod2Shift i shift) (shift - initShift)
| leaf cs, i, _ => cs[i.toNat]!
def get! [Inhabited α] (t : PersistentArray α) (i : Nat) : α :=
if i >= t.tailOff then
t.tail.get! (i - t.tailOff)
else
getAux t.root (USize.ofNat i) t.shift
-- TODO: remove [Inhabited α]
instance [Inhabited α] : GetElem (PersistentArray α) Nat α fun as i => i < as.size where
getElem xs i _ := xs.get! i
partial def setAux : PersistentArrayNode α → USize → USize → α → PersistentArrayNode α
| node cs, i, shift, a =>
let j := div2Shift i shift
let i := mod2Shift i shift
let shift := shift - initShift
node <| cs.modify j.toNat fun c => setAux c i shift a
| leaf cs, i, _, a => leaf (cs.set! i.toNat a)
def set (t : PersistentArray α) (i : Nat) (a : α) : PersistentArray α :=
if i >= t.tailOff then
{ t with tail := t.tail.set! (i - t.tailOff) a }
else
{ t with root := setAux t.root (USize.ofNat i) t.shift a }
@[specialize] partial def modifyAux [Inhabited α] (f : α → α) : PersistentArrayNode α → USize → USize → PersistentArrayNode α
| node cs, i, shift =>
let j := div2Shift i shift
let i := mod2Shift i shift
let shift := shift - initShift
node <| cs.modify j.toNat fun c => modifyAux f c i shift
| leaf cs, i, _ => leaf (cs.modify i.toNat f)
@[specialize] def modify [Inhabited α] (t : PersistentArray α) (i : Nat) (f : α → α) : PersistentArray α :=
if i >= t.tailOff then
{ t with tail := t.tail.modify (i - t.tailOff) f }
else
{ t with root := modifyAux f t.root (USize.ofNat i) t.shift }
partial def mkNewPath (shift : USize) (a : Array α) : PersistentArrayNode α :=
if shift == 0 then
leaf a
else
node (mkEmptyArray.push (mkNewPath (shift - initShift) a))
partial def insertNewLeaf : PersistentArrayNode α → USize → USize → Array α → PersistentArrayNode α
| node cs, i, shift, a =>
if i < branching then
node (cs.push (leaf a))
else
let j := div2Shift i shift
let i := mod2Shift i shift
let shift := shift - initShift
if j.toNat < cs.size then
node <| cs.modify j.toNat fun c => insertNewLeaf c i shift a
else
node <| cs.push <| mkNewPath shift a
| n, _, _, _ => n -- unreachable
def mkNewTail (t : PersistentArray α) : PersistentArray α :=
if t.size <= (mul2Shift 1 (t.shift + initShift)).toNat then
{ t with
tail := mkEmptyArray, root := insertNewLeaf t.root (USize.ofNat (t.size - 1)) t.shift t.tail,
tailOff := t.size }
else
{ t with
tail := #[],
root := let n := mkEmptyArray.push t.root;
node (n.push (mkNewPath t.shift t.tail)),
shift := t.shift + initShift,
tailOff := t.size }
def tooBig : Nat := USize.size / 8
def push (t : PersistentArray α) (a : α) : PersistentArray α :=
let r := { t with tail := t.tail.push a, size := t.size + 1 }
if r.tail.size < branching.toNat || t.size >= tooBig then
r
else
mkNewTail r
private def emptyArray {α : Type u} : Array (PersistentArrayNode α) :=
Array.mkEmpty PersistentArray.branching.toNat
partial def popLeaf : PersistentArrayNode α → Option (Array α) × Array (PersistentArrayNode α)
| node cs =>
if h : cs.size ≠ 0 then
let idx : Fin cs.size := ⟨cs.size - 1, by exact Nat.pred_lt h⟩
let last := cs.get idx
let cs' := cs.set idx default
match popLeaf last with
| (none, _) => (none, emptyArray)
| (some l, newLast) =>
if newLast.size == 0 then
let cs' := cs'.pop
if cs'.isEmpty then (some l, emptyArray) else (some l, cs')
else
(some l, cs'.set (Array.size_set cs idx _ ▸ idx) (node newLast))
else
(none, emptyArray)
| leaf vs => (some vs, emptyArray)
def pop (t : PersistentArray α) : PersistentArray α :=
if t.tail.size > 0 then
{ t with tail := t.tail.pop, size := t.size - 1 }
else
match popLeaf t.root with
| (none, _) => t
| (some last, newRoots) =>
let last := last.pop
let newSize := t.size - 1
let newTailOff := newSize - last.size
if newRoots.size == 1 && (newRoots.get! 0).isNode then
{ root := newRoots.get! 0,
shift := t.shift - initShift,
size := newSize,
tail := last,
tailOff := newTailOff }
else
{ t with
root := node newRoots,
size := newSize,
tail := last,
tailOff := newTailOff }
section
variable {m : Type v → Type w} [Monad m]
variable {β : Type v}
@[specialize] private partial def foldlMAux (f : β → α → m β) : PersistentArrayNode α → β → m β
| node cs, b => cs.foldlM (fun b c => foldlMAux f c b) b
| leaf vs, b => vs.foldlM f b
@[specialize] private partial def foldlFromMAux (f : β → α → m β) : PersistentArrayNode α → USize → USize → β → m β
| node cs, i, shift, b => do
let j := (div2Shift i shift).toNat
let b ← foldlFromMAux f (cs.get! j) (mod2Shift i shift) (shift - initShift) b
cs.foldlM (init := b) (start := j+1) fun b c => foldlMAux f c b
| leaf vs, i, _, b => vs.foldlM (init := b) (start := i.toNat) f
@[specialize] def foldlM (t : PersistentArray α) (f : β → α → m β) (init : β) (start : Nat := 0) : m β := do
if start == 0 then
let b ← foldlMAux f t.root init
t.tail.foldlM f b
else if start >= t.tailOff then
t.tail.foldlM (init := init) (start := start - t.tailOff) f
else do
let b ← foldlFromMAux f t.root (USize.ofNat start) t.shift init
t.tail.foldlM f b
@[specialize] private partial def foldrMAux [Monad m] (f : α → β → m β) : PersistentArrayNode α → β → m β
| node cs, b => cs.foldrM (fun c b => foldrMAux f c b) b
| leaf vs, b => vs.foldrM f b
@[specialize] def foldrM [Monad m] (t : PersistentArray α) (f : α → β → m β) (init : β) : m β := do
foldrMAux f t.root (← t.tail.foldrM f init)
set_option linter.unusedVariables.funArgs false in
@[specialize]
partial def forInAux {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] [inh : Inhabited β]
(f : α → β → m (ForInStep β)) (n : PersistentArrayNode α) (b : β) : m (ForInStep β) := do
let mut b := b
match n with
| leaf vs =>
for v in vs do
match (← f v b) with
| r@(ForInStep.done _) => return r
| ForInStep.yield bNew => b := bNew
return ForInStep.yield b
| node cs =>
for c in cs do
match (← forInAux f c b) with
| r@(ForInStep.done _) => return r
| ForInStep.yield bNew => b := bNew
return ForInStep.yield b
@[specialize] protected def forIn (t : PersistentArray α) (init : β) (f : α → β → m (ForInStep β)) : m β := do
match (← forInAux (inh := ⟨init⟩) f t.root init) with
| ForInStep.done b => pure b
| ForInStep.yield b =>
let mut b := b
for v in t.tail do
match (← f v b) with
| ForInStep.done r => return r
| ForInStep.yield bNew => b := bNew
return b
instance : ForIn m (PersistentArray α) α where
forIn := PersistentArray.forIn
@[specialize] partial def findSomeMAux (f : α → m (Option β)) : PersistentArrayNode α → m (Option β)
| node cs => cs.findSomeM? (fun c => findSomeMAux f c)
| leaf vs => vs.findSomeM? f
@[specialize] def findSomeM? (t : PersistentArray α) (f : α → m (Option β)) : m (Option β) := do
match (← findSomeMAux f t.root) with
| none => t.tail.findSomeM? f
| some b => pure (some b)
@[specialize] partial def findSomeRevMAux (f : α → m (Option β)) : PersistentArrayNode α → m (Option β)
| node cs => cs.findSomeRevM? (fun c => findSomeRevMAux f c)
| leaf vs => vs.findSomeRevM? f
@[specialize] def findSomeRevM? (t : PersistentArray α) (f : α → m (Option β)) : m (Option β) := do
match (← t.tail.findSomeRevM? f) with
| none => findSomeRevMAux f t.root
| some b => pure (some b)
@[specialize] partial def forMAux (f : α → m PUnit) : PersistentArrayNode α → m PUnit
| node cs => cs.forM (fun c => forMAux f c)
| leaf vs => vs.forM f
@[specialize] def forM (t : PersistentArray α) (f : α → m PUnit) : m PUnit :=
forMAux f t.root *> t.tail.forM f
end
@[inline] def foldl (t : PersistentArray α) (f : β → α → β) (init : β) (start : Nat := 0) : β :=
Id.run <| t.foldlM f init start
@[inline] def foldr (t : PersistentArray α) (f : α → β → β) (init : β) : β :=
Id.run <| t.foldrM f init
@[inline] def filter (as : PersistentArray α) (p : α → Bool) : PersistentArray α :=
as.foldl (init := {}) fun asNew a => if p a then asNew.push a else asNew
def toArray (t : PersistentArray α) : Array α :=
t.foldl Array.push #[]
def append (t₁ t₂ : PersistentArray α) : PersistentArray α :=
if t₁.isEmpty then
t₂
else
t₂.foldl PersistentArray.push t₁
instance : Append (PersistentArray α) := ⟨append⟩
@[inline] def findSome? {β} (t : PersistentArray α) (f : α → (Option β)) : Option β :=
Id.run $ t.findSomeM? f
@[inline] def findSomeRev? {β} (t : PersistentArray α) (f : α → (Option β)) : Option β :=
Id.run $ t.findSomeRevM? f
def toList (t : PersistentArray α) : List α :=
(t.foldl (init := []) fun xs x => x :: xs).reverse
section
variable {m : Type → Type w} [Monad m]
@[specialize] partial def anyMAux (p : α → m Bool) : PersistentArrayNode α → m Bool
| node cs => cs.anyM fun c => anyMAux p c
| leaf vs => vs.anyM p
@[specialize] def anyM (t : PersistentArray α) (p : α → m Bool) : m Bool :=
anyMAux p t.root <||> t.tail.anyM p
@[inline] def allM (a : PersistentArray α) (p : α → m Bool) : m Bool := do
let b ← anyM a (fun v => do let b ← p v; pure (not b))
pure (not b)
end
@[inline] def any (a : PersistentArray α) (p : α → Bool) : Bool :=
Id.run $ anyM a p
@[inline] def all (a : PersistentArray α) (p : α → Bool) : Bool :=
!any a fun v => !p v
section
variable {m : Type u → Type v} [Monad m]
variable {β : Type u}
@[specialize] partial def mapMAux (f : α → m β) : PersistentArrayNode α → m (PersistentArrayNode β)
| node cs => node <$> cs.mapM (fun c => mapMAux f c)
| leaf vs => leaf <$> vs.mapM f
@[specialize] def mapM (f : α → m β) (t : PersistentArray α) : m (PersistentArray β) := do
let root ← mapMAux f t.root
let tail ← t.tail.mapM f
pure { t with tail := tail, root := root }
end
@[inline] def map {β} (f : α → β) (t : PersistentArray α) : PersistentArray β :=
Id.run $ t.mapM f
structure Stats where
numNodes : Nat
depth : Nat
tailSize : Nat
partial def collectStats : PersistentArrayNode α → Stats → Nat → Stats
| node cs, s, d =>
cs.foldl (fun s c => collectStats c s (d+1))
{ s with
numNodes := s.numNodes + 1,
depth := Nat.max d s.depth }
| leaf _, s, d => { s with numNodes := s.numNodes + 1, depth := Nat.max d s.depth }
def stats (r : PersistentArray α) : Stats :=
collectStats r.root { numNodes := 0, depth := 0, tailSize := r.tail.size } 0
def Stats.toString (s : Stats) : String :=
s!"\{nodes := {s.numNodes}, depth := {s.depth}, tail size := {s.tailSize}}"
instance : ToString Stats := ⟨Stats.toString⟩
end PersistentArray
def mkPersistentArray {α : Type u} (n : Nat) (v : α) : PArray α :=
n.fold (init := PersistentArray.empty) fun _ p => p.push v
@[inline] def mkPArray {α : Type u} (n : Nat) (v : α) : PArray α :=
mkPersistentArray n v
end Lean
open Lean (PersistentArray)
def List.toPArray' {α : Type u} (xs : List α) : PersistentArray α :=
let rec loop : List α → PersistentArray α → PersistentArray α
| [], t => t
| x::xs, t => loop xs (t.push x)
loop xs {}
def Array.toPArray' {α : Type u} (xs : Array α) : PersistentArray α :=
xs.foldl (init := .empty) fun p x => p.push x
|
a115f94f9400c5e5cf9d90e7719f322be7623c3b | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /tests/bench/rbmap.lean | 01492d07491e31771151d43e5eaff465ace112c4 | [
"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 | 2,903 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Data.Option.Basic
import Init.Data.List.BasicAux
import Init.Data.String
import Init.System.IO
universes u v w w'
inductive color
| Red | Black
inductive Tree
| Leaf {} : Tree
| Node (color : color) (lchild : Tree) (key : Nat) (val : Bool) (rchild : Tree) : Tree
variable {σ : Type w}
open color Nat Tree
def fold (f : Nat → Bool → σ → σ) : Tree → σ → σ
| Leaf, b => b
| Node _ l k v r, b => fold f r (f k v (fold f l b))
@[inline]
def balance1 : Nat → Bool → Tree → Tree → Tree
| kv, vv, t, Node _ (Node Red l kx vx r₁) ky vy r₂ => Node Red (Node Black l kx vx r₁) ky vy (Node Black r₂ kv vv t)
| kv, vv, t, Node _ l₁ ky vy (Node Red l₂ kx vx r) => Node Red (Node Black l₁ ky vy l₂) kx vx (Node Black r kv vv t)
| kv, vv, t, Node _ l ky vy r => Node Black (Node Red l ky vy r) kv vv t
| _, _, _, _ => Leaf
@[inline]
def balance2 : Tree → Nat → Bool → Tree → Tree
| t, kv, vv, Node _ (Node Red l kx₁ vx₁ r₁) ky vy r₂ => Node Red (Node Black t kv vv l) kx₁ vx₁ (Node Black r₁ ky vy r₂)
| t, kv, vv, Node _ l₁ ky vy (Node Red l₂ kx₂ vx₂ r₂) => Node Red (Node Black t kv vv l₁) ky vy (Node Black l₂ kx₂ vx₂ r₂)
| t, kv, vv, Node _ l ky vy r => Node Black t kv vv (Node Red l ky vy r)
| _, _, _, _ => Leaf
def isRed : Tree → Bool
| Node Red _ _ _ _ => true
| _ => false
def ins : Tree → Nat → Bool → Tree
| Leaf, kx, vx => Node Red Leaf kx vx Leaf
| Node Red a ky vy b, kx, vx =>
(if kx < ky then Node Red (ins a kx vx) ky vy b
else if kx = ky then Node Red a kx vx b
else Node Red a ky vy (ins b kx vx))
| Node Black a ky vy b, kx, vx =>
if kx < ky then
(if isRed a then balance1 ky vy b (ins a kx vx)
else Node Black (ins a kx vx) ky vy b)
else if kx = ky then Node Black a kx vx b
else if isRed b then balance2 a ky vy (ins b kx vx)
else Node Black a ky vy (ins b kx vx)
def setBlack : Tree → Tree
| Node _ l k v r => Node Black l k v r
| e => e
def insert (t : Tree) (k : Nat) (v : Bool) : Tree :=
if isRed t then setBlack (ins t k v)
else ins t k v
def mkMapAux : Nat → Tree → Tree
| 0, m => m
| n+1, m => mkMapAux n (insert m n (n % 10 = 0))
def mkMap (n : Nat) :=
mkMapAux n Leaf
def main (xs : List String) : IO UInt32 :=
let m := mkMap xs.head!.toNat!;
let v := fold (fun (k : Nat) (v : Bool) (r : Nat) => if v then r + 1 else r) m 0;
IO.println (toString v) *>
pure 0
|
871ae5cc22d19745355340d4560ff3e267611879 | 32a2d1642d7519c99693bc1d3b24069e4853dd1f | /tactic/basic.lean | 76c159b88c2c9abb3a1491dac1dd07dc221951c7 | [
"Apache-2.0"
] | permissive | Cedric0099/mathlib | 7edb81d5d68e280b4d21f6c0377dad1f9b8c0d71 | a97101d2df5d186848075a2d0452f6a04d8a13eb | refs/heads/master | 1,584,201,847,599 | 1,524,979,632,000 | 1,524,979,632,000 | 131,690,350 | 0 | 0 | null | 1,525,162,341,000 | 1,525,162,341,000 | null | UTF-8 | Lean | false | false | 4,992 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
namespace expr
open tactic
protected meta def to_pos_nat : expr → option ℕ
| `(has_one.one _) := some 1
| `(bit0 %%e) := bit0 <$> e.to_pos_nat
| `(bit1 %%e) := bit1 <$> e.to_pos_nat
| _ := none
protected meta def to_nat : expr → option ℕ
| `(has_zero.zero _) := some 0
| e := e.to_pos_nat
protected meta def to_int : expr → option ℤ
| `(has_neg.neg %%e) := do n ← e.to_nat, some (-n)
| e := do n ← e.to_nat, return 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])
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]
end expr
namespace tactic
meta definition mk_local (n : name) : expr :=
expr.local_const n n binder_info.default (expr.const n [])
meta def exact_dec_trivial : tactic unit := `[exact dec_trivial]
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,
(do (new_h_type, pr) ← tac h_type,
assert h.local_pp_name new_h_type,
mk_eq_mp pr h >>= tactic.exact >> return tt)
<|>
(return ff) },
goal_simplified ← if tgt then (do
(new_t, pr) ← target >>= tac,
replace_target new_t pr,
return tt) <|> return ff else return ff,
to_remove.mmap' (λ h, try (clear h)),
return (¬ to_remove.empty ∨ goal_simplified)
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
meta structure instance_cache :=
(α : expr)
(univ : level)
(inst : name_map expr)
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
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
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)
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))
end instance_cache
/-- Reset the instance cache for the main goal. -/
meta def reset_instance_cache : tactic unit := unfreeze_local_instances
meta def match_head (e : expr) : expr → tactic unit
| e' :=
unify e e'
<|> do `(_ → %%e') ← whnf e',
v ← mk_mvar,
match_head (e'.instantiate_var v)
meta def find_matching_head : expr → list expr → tactic (list expr)
| e [] := return []
| e (H :: Hs) :=
do t ← infer_type H,
((::) H <$ match_head e t <|> pure id) <*> find_matching_head e Hs
meta def subst_locals (s : list (expr × expr)) (e : expr) : expr :=
(e.abstract_locals (s.map (expr.local_uniq_name ∘ prod.fst)).reverse).instantiate_vars (s.map prod.snd)
meta def set_binder : expr → list binder_info → expr
| e [] := e
| (expr.pi v _ d b) (bi :: bs) := expr.pi v bi d (set_binder b bs)
| e _ := e
/-- 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)
end tactic
|
12ea802b557cf4c31fa84bb951020ed93cfb99e3 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/no_confusion1.lean | 190fd090826a98f66f44e72026e07f6ce1c9acbc | [
"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 | 430 | lean | open nat
theorem ex1 (n : nat) : bit0 n ≠ 1 :=
nat.cases_on n
(show 0 ≠ 1, from ne.symm nat.one_ne_zero)
(λ m h1,
have h2 : succ (succ (m + m)) = 1, from nat.succ_add m m ▸ h1,
nat.no_confusion h2 (λ h3, absurd h3 (nat.succ_ne_zero (m + m))))
theorem ex2 (n : nat) : succ n ≠ 0 :=
λ h, nat.no_confusion h
theorem ex3 (n : nat) : succ (succ n) ≠ 1 :=
λ h, nat.no_confusion h (λ h, nat.no_confusion h)
|
e0d772dcd91fda0543ed072120aba9f56fc9e269 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/category_theory/limits/has_limits.lean | d2d87212c65e4a94b4ade41c2c9a408bc383c23f | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 43,176 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton, Mario Carneiro, Scott Morrison, Floris van Doorn
-/
import category_theory.limits.is_limit
import category_theory.category.ulift
/-!
# Existence of limits and colimits
In `category_theory.limits.is_limit` we defined `is_limit c`,
the data showing that a cone `c` is a limit cone.
The two main structures defined in this file are:
* `limit_cone F`, which consists of a choice of cone for `F` and the fact it is a limit cone, and
* `has_limit F`, asserting the mere existence of some limit cone for `F`.
`has_limit` is a propositional typeclass
(it's important that it is a proposition merely asserting the existence of a limit,
as otherwise we would have non-defeq problems from incompatible instances).
While `has_limit` only asserts the existence of a limit cone,
we happily use the axiom of choice in mathlib,
so there are convenience functions all depending on `has_limit F`:
* `limit F : C`, producing some limit object (of course all such are isomorphic)
* `limit.π F j : limit F ⟶ F.obj j`, the morphisms out of the limit,
* `limit.lift F c : c.X ⟶ limit F`, the universal morphism from any other `c : cone F`, etc.
Key to using the `has_limit` interface is that there is an `@[ext]` lemma stating that
to check `f = g`, for `f g : Z ⟶ limit F`, it suffices to check `f ≫ limit.π F j = g ≫ limit.π F j`
for every `j`.
This, combined with `@[simp]` lemmas, makes it possible to prove many easy facts about limits using
automation (e.g. `tidy`).
There are abbreviations `has_limits_of_shape J C` and `has_limits C`
asserting the existence of classes of limits.
Later more are introduced, for finite limits, special shapes of limits, etc.
Ideally, many results about limits should be stated first in terms of `is_limit`,
and then a result in terms of `has_limit` derived from this.
At this point, however, this is far from uniformly achieved in mathlib ---
often statements are only written in terms of `has_limit`.
## Implementation
At present we simply say everything twice, in order to handle both limits and colimits.
It would be highly desirable to have some automation support,
e.g. a `@[dualize]` attribute that behaves similarly to `@[to_additive]`.
## References
* [Stacks: Limits and colimits](https://stacks.math.columbia.edu/tag/002D)
-/
noncomputable theory
open category_theory category_theory.category category_theory.functor opposite
namespace category_theory.limits
-- morphism levels before object levels. See note [category_theory universes].
universes v₁ u₁ v₂ u₂ v₃ u₃ v v' v'' u u' u''
variables {J : Type u₁} [category.{v₁} J] {K : Type u₂} [category.{v₂} K]
variables {C : Type u} [category.{v} C]
variables {F : J ⥤ C}
section limit
/-- `limit_cone F` contains a cone over `F` together with the information that it is a limit. -/
@[nolint has_nonempty_instance]
structure limit_cone (F : J ⥤ C) :=
(cone : cone F)
(is_limit : is_limit cone)
/-- `has_limit F` represents the mere existence of a limit for `F`. -/
class has_limit (F : J ⥤ C) : Prop :=
mk' :: (exists_limit : nonempty (limit_cone F))
lemma has_limit.mk {F : J ⥤ C} (d : limit_cone F) : has_limit F :=
⟨nonempty.intro d⟩
/-- Use the axiom of choice to extract explicit `limit_cone F` from `has_limit F`. -/
def get_limit_cone (F : J ⥤ C) [has_limit F] : limit_cone F :=
classical.choice $ has_limit.exists_limit
variables (J C)
/-- `C` has limits of shape `J` if there exists a limit for every functor `F : J ⥤ C`. -/
class has_limits_of_shape : Prop :=
(has_limit : Π F : J ⥤ C, has_limit F . tactic.apply_instance)
/--
`C` has all limits of size `v₁ u₁` (`has_limits_of_size.{v₁ u₁} C`)
if it has limits of every shape `J : Type u₁` with `[category.{v₁} J]`.
-/
class has_limits_of_size (C : Type u) [category.{v} C] : Prop :=
(has_limits_of_shape :
Π (J : Type u₁) [𝒥 : category.{v₁} J], has_limits_of_shape J C . tactic.apply_instance)
/-- `C` has all (small) limits if it has limits of every shape that is as big as its hom-sets. -/
abbreviation has_limits (C : Type u) [category.{v} C] : Prop := has_limits_of_size.{v v} C
lemma has_limits.has_limits_of_shape {C : Type u} [category.{v} C] [has_limits C]
(J : Type v) [category.{v} J] :
has_limits_of_shape J C := has_limits_of_size.has_limits_of_shape J
variables {J C}
@[priority 100] -- see Note [lower instance priority]
instance has_limit_of_has_limits_of_shape
{J : Type u₁} [category.{v₁} J] [H : has_limits_of_shape J C] (F : J ⥤ C) : has_limit F :=
has_limits_of_shape.has_limit F
@[priority 100] -- see Note [lower instance priority]
instance has_limits_of_shape_of_has_limits
{J : Type u₁} [category.{v₁} J] [H : has_limits_of_size.{v₁ u₁} C] : has_limits_of_shape J C :=
has_limits_of_size.has_limits_of_shape J
/- Interface to the `has_limit` class. -/
/-- An arbitrary choice of limit cone for a functor. -/
def limit.cone (F : J ⥤ C) [has_limit F] : cone F := (get_limit_cone F).cone
/-- An arbitrary choice of limit object of a functor. -/
def limit (F : J ⥤ C) [has_limit F] := (limit.cone F).X
/-- The projection from the limit object to a value of the functor. -/
def limit.π (F : J ⥤ C) [has_limit F] (j : J) : limit F ⟶ F.obj j :=
(limit.cone F).π.app j
@[simp] lemma limit.cone_X {F : J ⥤ C} [has_limit F] :
(limit.cone F).X = limit F := rfl
@[simp] lemma limit.cone_π {F : J ⥤ C} [has_limit F] :
(limit.cone F).π.app = limit.π _ := rfl
@[simp, reassoc] lemma limit.w (F : J ⥤ C) [has_limit F] {j j' : J} (f : j ⟶ j') :
limit.π F j ≫ F.map f = limit.π F j' := (limit.cone F).w f
/-- Evidence that the arbitrary choice of cone provied by `limit.cone F` is a limit cone. -/
def limit.is_limit (F : J ⥤ C) [has_limit F] : is_limit (limit.cone F) :=
(get_limit_cone F).is_limit
/-- The morphism from the cone point of any other cone to the limit object. -/
def limit.lift (F : J ⥤ C) [has_limit F] (c : cone F) : c.X ⟶ limit F :=
(limit.is_limit F).lift c
@[simp] lemma limit.is_limit_lift {F : J ⥤ C} [has_limit F] (c : cone F) :
(limit.is_limit F).lift c = limit.lift F c := rfl
@[simp, reassoc] lemma limit.lift_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) :
limit.lift F c ≫ limit.π F j = c.π.app j :=
is_limit.fac _ c j
/--
Functoriality of limits.
Usually this morphism should be accessed through `lim.map`,
but may be needed separately when you have specified limits for the source and target functors,
but not necessarily for all functors of shape `J`.
-/
def lim_map {F G : J ⥤ C} [has_limit F] [has_limit G] (α : F ⟶ G) : limit F ⟶ limit G :=
is_limit.map _ (limit.is_limit G) α
@[simp, reassoc] lemma lim_map_π {F G : J ⥤ C} [has_limit F] [has_limit G] (α : F ⟶ G) (j : J) :
lim_map α ≫ limit.π G j = limit.π F j ≫ α.app j :=
limit.lift_π _ j
/-- The cone morphism from any cone to the arbitrary choice of limit cone. -/
def limit.cone_morphism {F : J ⥤ C} [has_limit F] (c : cone F) :
c ⟶ limit.cone F :=
(limit.is_limit F).lift_cone_morphism c
@[simp] lemma limit.cone_morphism_hom {F : J ⥤ C} [has_limit F] (c : cone F) :
(limit.cone_morphism c).hom = limit.lift F c := rfl
lemma limit.cone_morphism_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) :
(limit.cone_morphism c).hom ≫ limit.π F j = c.π.app j :=
by simp
@[simp, reassoc] lemma limit.cone_point_unique_up_to_iso_hom_comp {F : J ⥤ C} [has_limit F]
{c : cone F} (hc : is_limit c) (j : J) :
(is_limit.cone_point_unique_up_to_iso hc (limit.is_limit _)).hom ≫ limit.π F j = c.π.app j :=
is_limit.cone_point_unique_up_to_iso_hom_comp _ _ _
@[simp, reassoc] lemma limit.cone_point_unique_up_to_iso_inv_comp {F : J ⥤ C} [has_limit F]
{c : cone F} (hc : is_limit c) (j : J) :
(is_limit.cone_point_unique_up_to_iso (limit.is_limit _) hc).inv ≫ limit.π F j = c.π.app j :=
is_limit.cone_point_unique_up_to_iso_inv_comp _ _ _
lemma limit.exists_unique {F : J ⥤ C} [has_limit F] (t : cone F) :
∃! (l : t.X ⟶ limit F), ∀ j, l ≫ limit.π F j = t.π.app j :=
(limit.is_limit F).exists_unique _
/--
Given any other limit cone for `F`, the chosen `limit F` is isomorphic to the cone point.
-/
def limit.iso_limit_cone {F : J ⥤ C} [has_limit F] (t : limit_cone F) :
limit F ≅ t.cone.X :=
is_limit.cone_point_unique_up_to_iso (limit.is_limit F) t.is_limit
@[simp, reassoc] lemma limit.iso_limit_cone_hom_π
{F : J ⥤ C} [has_limit F] (t : limit_cone F) (j : J) :
(limit.iso_limit_cone t).hom ≫ t.cone.π.app j = limit.π F j :=
by { dsimp [limit.iso_limit_cone, is_limit.cone_point_unique_up_to_iso], tidy, }
@[simp, reassoc] lemma limit.iso_limit_cone_inv_π
{F : J ⥤ C} [has_limit F] (t : limit_cone F) (j : J) :
(limit.iso_limit_cone t).inv ≫ limit.π F j = t.cone.π.app j :=
by { dsimp [limit.iso_limit_cone, is_limit.cone_point_unique_up_to_iso], tidy, }
@[ext] lemma limit.hom_ext {F : J ⥤ C} [has_limit F] {X : C} {f f' : X ⟶ limit F}
(w : ∀ j, f ≫ limit.π F j = f' ≫ limit.π F j) : f = f' :=
(limit.is_limit F).hom_ext w
@[simp] lemma limit.lift_map {F G : J ⥤ C} [has_limit F] [has_limit G] (c : cone F) (α : F ⟶ G) :
limit.lift F c ≫ lim_map α = limit.lift G ((cones.postcompose α).obj c) :=
by { ext, rw [assoc, lim_map_π, limit.lift_π_assoc, limit.lift_π], refl }
@[simp] lemma limit.lift_cone {F : J ⥤ C} [has_limit F] :
limit.lift F (limit.cone F) = 𝟙 (limit F) :=
(limit.is_limit _).lift_self
/--
The isomorphism (in `Type`) between
morphisms from a specified object `W` to the limit object,
and cones with cone point `W`.
-/
def limit.hom_iso (F : J ⥤ C) [has_limit F] (W : C) :
ulift.{u₁} (W ⟶ limit F : Type v) ≅ (F.cones.obj (op W)) :=
(limit.is_limit F).hom_iso W
@[simp] lemma limit.hom_iso_hom (F : J ⥤ C) [has_limit F] {W : C} (f : ulift (W ⟶ limit F)) :
(limit.hom_iso F W).hom f = (const J).map f.down ≫ (limit.cone F).π :=
(limit.is_limit F).hom_iso_hom f
/--
The isomorphism (in `Type`) between
morphisms from a specified object `W` to the limit object,
and an explicit componentwise description of cones with cone point `W`.
-/
def limit.hom_iso' (F : J ⥤ C) [has_limit F] (W : C) :
ulift.{u₁} ((W ⟶ limit F) : Type v) ≅
{ p : Π j, W ⟶ F.obj j // ∀ {j j' : J} (f : j ⟶ j'), p j ≫ F.map f = p j' } :=
(limit.is_limit F).hom_iso' W
lemma limit.lift_extend {F : J ⥤ C} [has_limit F] (c : cone F) {X : C} (f : X ⟶ c.X) :
limit.lift F (c.extend f) = f ≫ limit.lift F c :=
by obviously
/--
If a functor `F` has a limit, so does any naturally isomorphic functor.
-/
lemma has_limit_of_iso {F G : J ⥤ C} [has_limit F] (α : F ≅ G) : has_limit G :=
has_limit.mk
{ cone := (cones.postcompose α.hom).obj (limit.cone F),
is_limit :=
{ lift := λ s, limit.lift F ((cones.postcompose α.inv).obj s),
fac' := λ s j,
begin
rw [cones.postcompose_obj_π, nat_trans.comp_app, limit.cone_π, ←category.assoc, limit.lift_π],
simp
end,
uniq' := λ s m w,
begin
apply limit.hom_ext, intro j,
rw [limit.lift_π, cones.postcompose_obj_π, nat_trans.comp_app, ←nat_iso.app_inv,
iso.eq_comp_inv],
simpa using w j
end } }
/-- If a functor `G` has the same collection of cones as a functor `F`
which has a limit, then `G` also has a limit. -/
-- See the construction of limits from products and equalizers
-- for an example usage.
lemma has_limit.of_cones_iso {J K : Type u₁} [category.{v₁} J] [category.{v₂} K] (F : J ⥤ C)
(G : K ⥤ C) (h : F.cones ≅ G.cones) [has_limit F] : has_limit G :=
has_limit.mk ⟨_, is_limit.of_nat_iso ((is_limit.nat_iso (limit.is_limit F)) ≪≫ h)⟩
/--
The limits of `F : J ⥤ C` and `G : J ⥤ C` are isomorphic,
if the functors are naturally isomorphic.
-/
def has_limit.iso_of_nat_iso {F G : J ⥤ C} [has_limit F] [has_limit G] (w : F ≅ G) :
limit F ≅ limit G :=
is_limit.cone_points_iso_of_nat_iso (limit.is_limit F) (limit.is_limit G) w
@[simp, reassoc]
lemma has_limit.iso_of_nat_iso_hom_π {F G : J ⥤ C} [has_limit F] [has_limit G]
(w : F ≅ G) (j : J) :
(has_limit.iso_of_nat_iso w).hom ≫ limit.π G j = limit.π F j ≫ w.hom.app j :=
is_limit.cone_points_iso_of_nat_iso_hom_comp _ _ _ _
@[simp, reassoc]
lemma has_limit.iso_of_nat_iso_inv_π {F G : J ⥤ C} [has_limit F] [has_limit G]
(w : F ≅ G) (j : J) :
(has_limit.iso_of_nat_iso w).inv ≫ limit.π F j = limit.π G j ≫ w.inv.app j :=
is_limit.cone_points_iso_of_nat_iso_inv_comp _ _ _ _
@[simp, reassoc]
lemma has_limit.lift_iso_of_nat_iso_hom {F G : J ⥤ C} [has_limit F] [has_limit G] (t : cone F)
(w : F ≅ G) :
limit.lift F t ≫ (has_limit.iso_of_nat_iso w).hom =
limit.lift G ((cones.postcompose w.hom).obj _) :=
is_limit.lift_comp_cone_points_iso_of_nat_iso_hom _ _ _
@[simp, reassoc]
lemma has_limit.lift_iso_of_nat_iso_inv {F G : J ⥤ C} [has_limit F] [has_limit G] (t : cone G)
(w : F ≅ G) :
limit.lift G t ≫ (has_limit.iso_of_nat_iso w).inv =
limit.lift F ((cones.postcompose w.inv).obj _) :=
is_limit.lift_comp_cone_points_iso_of_nat_iso_inv _ _ _
/--
The limits of `F : J ⥤ C` and `G : K ⥤ C` are isomorphic,
if there is an equivalence `e : J ≌ K` making the triangle commute up to natural isomorphism.
-/
def has_limit.iso_of_equivalence {F : J ⥤ C} [has_limit F] {G : K ⥤ C} [has_limit G]
(e : J ≌ K) (w : e.functor ⋙ G ≅ F) : limit F ≅ limit G :=
is_limit.cone_points_iso_of_equivalence (limit.is_limit F) (limit.is_limit G) e w
@[simp]
lemma has_limit.iso_of_equivalence_hom_π {F : J ⥤ C} [has_limit F] {G : K ⥤ C} [has_limit G]
(e : J ≌ K) (w : e.functor ⋙ G ≅ F) (k : K) :
(has_limit.iso_of_equivalence e w).hom ≫ limit.π G k =
limit.π F (e.inverse.obj k) ≫ w.inv.app (e.inverse.obj k) ≫ G.map (e.counit.app k) :=
begin
simp only [has_limit.iso_of_equivalence, is_limit.cone_points_iso_of_equivalence_hom],
dsimp,
simp,
end
@[simp]
lemma has_limit.iso_of_equivalence_inv_π {F : J ⥤ C} [has_limit F] {G : K ⥤ C} [has_limit G]
(e : J ≌ K) (w : e.functor ⋙ G ≅ F) (j : J) :
(has_limit.iso_of_equivalence e w).inv ≫ limit.π F j =
limit.π G (e.functor.obj j) ≫ w.hom.app j :=
begin
simp only [has_limit.iso_of_equivalence, is_limit.cone_points_iso_of_equivalence_hom],
dsimp,
simp,
end
section pre
variables (F) [has_limit F] (E : K ⥤ J) [has_limit (E ⋙ F)]
/--
The canonical morphism from the limit of `F` to the limit of `E ⋙ F`.
-/
def limit.pre : limit F ⟶ limit (E ⋙ F) :=
limit.lift (E ⋙ F) ((limit.cone F).whisker E)
@[simp, reassoc] lemma limit.pre_π (k : K) :
limit.pre F E ≫ limit.π (E ⋙ F) k = limit.π F (E.obj k) :=
by { erw is_limit.fac, refl }
@[simp] lemma limit.lift_pre (c : cone F) :
limit.lift F c ≫ limit.pre F E = limit.lift (E ⋙ F) (c.whisker E) :=
by ext; simp
variables {L : Type u₃} [category.{v₃} L]
variables (D : L ⥤ K) [has_limit (D ⋙ E ⋙ F)]
@[simp] lemma limit.pre_pre : limit.pre F E ≫ limit.pre (E ⋙ F) D = limit.pre F (D ⋙ E) :=
by ext j; erw [assoc, limit.pre_π, limit.pre_π, limit.pre_π]; refl
variables {E F}
/---
If we have particular limit cones available for `E ⋙ F` and for `F`,
we obtain a formula for `limit.pre F E`.
-/
lemma limit.pre_eq (s : limit_cone (E ⋙ F)) (t : limit_cone F) :
limit.pre F E =
(limit.iso_limit_cone t).hom ≫ s.is_limit.lift ((t.cone).whisker E) ≫
(limit.iso_limit_cone s).inv :=
by tidy
end pre
section post
variables {D : Type u'} [category.{v'} D]
variables (F) [has_limit F] (G : C ⥤ D) [has_limit (F ⋙ G)]
/--
The canonical morphism from `G` applied to the limit of `F` to the limit of `F ⋙ G`.
-/
def limit.post : G.obj (limit F) ⟶ limit (F ⋙ G) :=
limit.lift (F ⋙ G) (G.map_cone (limit.cone F))
@[simp, reassoc] lemma limit.post_π (j : J) :
limit.post F G ≫ limit.π (F ⋙ G) j = G.map (limit.π F j) :=
by { erw is_limit.fac, refl }
@[simp] lemma limit.lift_post (c : cone F) :
G.map (limit.lift F c) ≫ limit.post F G = limit.lift (F ⋙ G) (G.map_cone c) :=
by { ext, rw [assoc, limit.post_π, ←G.map_comp, limit.lift_π, limit.lift_π], refl }
@[simp] lemma limit.post_post
{E : Type u''} [category.{v''} E] (H : D ⥤ E) [has_limit ((F ⋙ G) ⋙ H)] :
/- H G (limit F) ⟶ H (limit (F ⋙ G)) ⟶ limit ((F ⋙ G) ⋙ H) equals -/
/- H G (limit F) ⟶ limit (F ⋙ (G ⋙ H)) -/
H.map (limit.post F G) ≫ limit.post (F ⋙ G) H = limit.post F (G ⋙ H) :=
by ext; erw [assoc, limit.post_π, ←H.map_comp, limit.post_π, limit.post_π]; refl
end post
lemma limit.pre_post {D : Type u'} [category.{v'} D]
(E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D)
[has_limit F] [has_limit (E ⋙ F)] [has_limit (F ⋙ G)] [has_limit ((E ⋙ F) ⋙ G)] :
/- G (limit F) ⟶ G (limit (E ⋙ F)) ⟶ limit ((E ⋙ F) ⋙ G) vs -/
/- G (limit F) ⟶ limit F ⋙ G ⟶ limit (E ⋙ (F ⋙ G)) or -/
G.map (limit.pre F E) ≫ limit.post (E ⋙ F) G = limit.post F G ≫ limit.pre (F ⋙ G) E :=
by ext; erw [assoc, limit.post_π, ←G.map_comp, limit.pre_π, assoc, limit.pre_π, limit.post_π]; refl
open category_theory.equivalence
instance has_limit_equivalence_comp (e : K ≌ J) [has_limit F] : has_limit (e.functor ⋙ F) :=
has_limit.mk { cone := cone.whisker e.functor (limit.cone F),
is_limit := is_limit.whisker_equivalence (limit.is_limit F) e, }
local attribute [elab_simple] inv_fun_id_assoc -- not entirely sure why this is needed
/--
If a `E ⋙ F` has a limit, and `E` is an equivalence, we can construct a limit of `F`.
-/
lemma has_limit_of_equivalence_comp (e : K ≌ J) [has_limit (e.functor ⋙ F)] : has_limit F :=
begin
haveI : has_limit (e.inverse ⋙ e.functor ⋙ F) := limits.has_limit_equivalence_comp e.symm,
apply has_limit_of_iso (e.inv_fun_id_assoc F),
end
-- `has_limit_comp_equivalence` and `has_limit_of_comp_equivalence`
-- are proved in `category_theory/adjunction/limits.lean`.
section lim_functor
variables [has_limits_of_shape J C]
section
/-- `limit F` is functorial in `F`, when `C` has all limits of shape `J`. -/
@[simps obj]
def lim : (J ⥤ C) ⥤ C :=
{ obj := λ F, limit F,
map := λ F G α, lim_map α,
map_id' := λ F, by { ext, erw [lim_map_π, category.id_comp, category.comp_id] },
map_comp' := λ F G H α β,
by ext; erw [assoc, is_limit.fac, is_limit.fac, ←assoc, is_limit.fac, assoc]; refl }
end
variables {F} {G : J ⥤ C} (α : F ⟶ G)
-- We generate this manually since `simps` gives it a weird name.
@[simp] lemma lim_map_eq_lim_map : lim.map α = lim_map α := rfl
lemma limit.map_pre [has_limits_of_shape K C] (E : K ⥤ J) :
lim.map α ≫ limit.pre G E = limit.pre F E ≫ lim.map (whisker_left E α) :=
by { ext, simp }
lemma limit.map_pre' [has_limits_of_shape K C]
(F : J ⥤ C) {E₁ E₂ : K ⥤ J} (α : E₁ ⟶ E₂) :
limit.pre F E₂ = limit.pre F E₁ ≫ lim.map (whisker_right α F) :=
by ext1; simp [← category.assoc]
lemma limit.id_pre (F : J ⥤ C) :
limit.pre F (𝟭 _) = lim.map (functor.left_unitor F).inv := by tidy
lemma limit.map_post {D : Type u'} [category.{v'} D] [has_limits_of_shape J D] (H : C ⥤ D) :
/- H (limit F) ⟶ H (limit G) ⟶ limit (G ⋙ H) vs
H (limit F) ⟶ limit (F ⋙ H) ⟶ limit (G ⋙ H) -/
H.map (lim_map α) ≫ limit.post G H = limit.post F H ≫ lim_map (whisker_right α H) :=
begin
ext,
simp only [whisker_right_app, lim_map_π, assoc, limit.post_π_assoc, limit.post_π, ← H.map_comp],
end
/--
The isomorphism between
morphisms from `W` to the cone point of the limit cone for `F`
and cones over `F` with cone point `W`
is natural in `F`.
-/
def lim_yoneda : lim ⋙ yoneda ⋙ (whiskering_right _ _ _).obj ulift_functor.{u₁}
≅ category_theory.cones J C :=
nat_iso.of_components (λ F, nat_iso.of_components (λ W, limit.hom_iso F (unop W)) (by tidy))
(by tidy)
end lim_functor
/--
We can transport limits of shape `J` along an equivalence `J ≌ J'`.
-/
lemma has_limits_of_shape_of_equivalence {J' : Type u₂} [category.{v₂} J']
(e : J ≌ J') [has_limits_of_shape J C] : has_limits_of_shape J' C :=
by { constructor, intro F, apply has_limit_of_equivalence_comp e, apply_instance }
variable (C)
/--
`has_limits_of_size_shrink.{v u} C` tries to obtain `has_limits_of_size.{v u} C`
from some other `has_limits_of_size C`.
-/
lemma has_limits_of_size_shrink [has_limits_of_size.{(max v₁ v₂) (max u₁ u₂)} C] :
has_limits_of_size.{v₁ u₁} C :=
⟨λ J hJ, by exactI has_limits_of_shape_of_equivalence
(ulift_hom_ulift_category.equiv.{v₂ u₂} J).symm⟩
@[priority 100]
instance has_smallest_limits_of_has_limits [has_limits C] :
has_limits_of_size.{0 0} C := has_limits_of_size_shrink.{0 0} C
end limit
section colimit
/-- `colimit_cocone F` contains a cocone over `F` together with the information that it is a
colimit. -/
@[nolint has_nonempty_instance]
structure colimit_cocone (F : J ⥤ C) :=
(cocone : cocone F)
(is_colimit : is_colimit cocone)
/-- `has_colimit F` represents the mere existence of a colimit for `F`. -/
class has_colimit (F : J ⥤ C) : Prop :=
mk' :: (exists_colimit : nonempty (colimit_cocone F))
lemma has_colimit.mk {F : J ⥤ C} (d : colimit_cocone F) : has_colimit F :=
⟨nonempty.intro d⟩
/-- Use the axiom of choice to extract explicit `colimit_cocone F` from `has_colimit F`. -/
def get_colimit_cocone (F : J ⥤ C) [has_colimit F] : colimit_cocone F :=
classical.choice $ has_colimit.exists_colimit
variables (J C)
/-- `C` has colimits of shape `J` if there exists a colimit for every functor `F : J ⥤ C`. -/
class has_colimits_of_shape : Prop :=
(has_colimit : Π F : J ⥤ C, has_colimit F . tactic.apply_instance)
/--
`C` has all colimits of size `v₁ u₁` (`has_colimits_of_size.{v₁ u₁} C`)
if it has colimits of every shape `J : Type u₁` with `[category.{v₁} J]`.
-/
class has_colimits_of_size (C : Type u) [category.{v} C] : Prop :=
(has_colimits_of_shape :
Π (J : Type u₁) [𝒥 : category.{v₁} J], has_colimits_of_shape J C . tactic.apply_instance)
/--
`C` has all (small) colimits if it has colimits of every shape that is as big as its hom-sets.
-/
abbreviation has_colimits (C : Type u) [category.{v} C] : Prop := has_colimits_of_size.{v v} C
lemma has_colimits.has_colimits_of_shape {C : Type u} [category.{v} C] [has_colimits C]
(J : Type v) [category.{v} J] :
has_colimits_of_shape J C := has_colimits_of_size.has_colimits_of_shape J
variables {J C}
@[priority 100] -- see Note [lower instance priority]
instance has_colimit_of_has_colimits_of_shape
{J : Type u₁} [category.{v₁} J] [H : has_colimits_of_shape J C] (F : J ⥤ C) : has_colimit F :=
has_colimits_of_shape.has_colimit F
@[priority 100] -- see Note [lower instance priority]
instance has_colimits_of_shape_of_has_colimits_of_size {J : Type u₁} [category.{v₁} J]
[H : has_colimits_of_size.{v₁ u₁} C] : has_colimits_of_shape J C :=
has_colimits_of_size.has_colimits_of_shape J
/- Interface to the `has_colimit` class. -/
/-- An arbitrary choice of colimit cocone of a functor. -/
def colimit.cocone (F : J ⥤ C) [has_colimit F] : cocone F := (get_colimit_cocone F).cocone
/-- An arbitrary choice of colimit object of a functor. -/
def colimit (F : J ⥤ C) [has_colimit F] := (colimit.cocone F).X
/-- The coprojection from a value of the functor to the colimit object. -/
def colimit.ι (F : J ⥤ C) [has_colimit F] (j : J) : F.obj j ⟶ colimit F :=
(colimit.cocone F).ι.app j
@[simp] lemma colimit.cocone_ι {F : J ⥤ C} [has_colimit F] (j : J) :
(colimit.cocone F).ι.app j = colimit.ι _ j := rfl
@[simp] lemma colimit.cocone_X {F : J ⥤ C} [has_colimit F] :
(colimit.cocone F).X = colimit F := rfl
@[simp, reassoc] lemma colimit.w (F : J ⥤ C) [has_colimit F] {j j' : J} (f : j ⟶ j') :
F.map f ≫ colimit.ι F j' = colimit.ι F j := (colimit.cocone F).w f
/-- Evidence that the arbitrary choice of cocone is a colimit cocone. -/
def colimit.is_colimit (F : J ⥤ C) [has_colimit F] : is_colimit (colimit.cocone F) :=
(get_colimit_cocone F).is_colimit
/-- The morphism from the colimit object to the cone point of any other cocone. -/
def colimit.desc (F : J ⥤ C) [has_colimit F] (c : cocone F) : colimit F ⟶ c.X :=
(colimit.is_colimit F).desc c
@[simp] lemma colimit.is_colimit_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) :
(colimit.is_colimit F).desc c = colimit.desc F c := rfl
/--
We have lots of lemmas describing how to simplify `colimit.ι F j ≫ _`,
and combined with `colimit.ext` we rely on these lemmas for many calculations.
However, since `category.assoc` is a `@[simp]` lemma, often expressions are
right associated, and it's hard to apply these lemmas about `colimit.ι`.
We thus use `reassoc` to define additional `@[simp]` lemmas, with an arbitrary extra morphism.
(see `tactic/reassoc_axiom.lean`)
-/
@[simp, reassoc] lemma colimit.ι_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) :
colimit.ι F j ≫ colimit.desc F c = c.ι.app j :=
is_colimit.fac _ c j
/--
Functoriality of colimits.
Usually this morphism should be accessed through `colim.map`,
but may be needed separately when you have specified colimits for the source and target functors,
but not necessarily for all functors of shape `J`.
-/
def colim_map {F G : J ⥤ C} [has_colimit F] [has_colimit G] (α : F ⟶ G) : colimit F ⟶ colimit G :=
is_colimit.map (colimit.is_colimit F) _ α
@[simp, reassoc]
lemma ι_colim_map {F G : J ⥤ C} [has_colimit F] [has_colimit G] (α : F ⟶ G) (j : J) :
colimit.ι F j ≫ colim_map α = α.app j ≫ colimit.ι G j :=
colimit.ι_desc _ j
/-- The cocone morphism from the arbitrary choice of colimit cocone to any cocone. -/
def colimit.cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) :
(colimit.cocone F) ⟶ c :=
(colimit.is_colimit F).desc_cocone_morphism c
@[simp] lemma colimit.cocone_morphism_hom {F : J ⥤ C} [has_colimit F] (c : cocone F) :
(colimit.cocone_morphism c).hom = colimit.desc F c := rfl
lemma colimit.ι_cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) :
colimit.ι F j ≫ (colimit.cocone_morphism c).hom = c.ι.app j :=
by simp
@[simp, reassoc] lemma colimit.comp_cocone_point_unique_up_to_iso_hom {F : J ⥤ C} [has_colimit F]
{c : cocone F} (hc : is_colimit c) (j : J) :
colimit.ι F j ≫ (is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) hc).hom =
c.ι.app j :=
is_colimit.comp_cocone_point_unique_up_to_iso_hom _ _ _
@[simp, reassoc] lemma colimit.comp_cocone_point_unique_up_to_iso_inv {F : J ⥤ C} [has_colimit F]
{c : cocone F} (hc : is_colimit c) (j : J) :
colimit.ι F j ≫ (is_colimit.cocone_point_unique_up_to_iso hc (colimit.is_colimit _)).inv =
c.ι.app j :=
is_colimit.comp_cocone_point_unique_up_to_iso_inv _ _ _
lemma colimit.exists_unique {F : J ⥤ C} [has_colimit F] (t : cocone F) :
∃! (d : colimit F ⟶ t.X), ∀ j, colimit.ι F j ≫ d = t.ι.app j :=
(colimit.is_colimit F).exists_unique _
/--
Given any other colimit cocone for `F`, the chosen `colimit F` is isomorphic to the cocone point.
-/
def colimit.iso_colimit_cocone {F : J ⥤ C} [has_colimit F] (t : colimit_cocone F) :
colimit F ≅ t.cocone.X :=
is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit F) t.is_colimit
@[simp, reassoc] lemma colimit.iso_colimit_cocone_ι_hom
{F : J ⥤ C} [has_colimit F] (t : colimit_cocone F) (j : J) :
colimit.ι F j ≫ (colimit.iso_colimit_cocone t).hom = t.cocone.ι.app j :=
by { dsimp [colimit.iso_colimit_cocone, is_colimit.cocone_point_unique_up_to_iso], tidy, }
@[simp, reassoc] lemma colimit.iso_colimit_cocone_ι_inv
{F : J ⥤ C} [has_colimit F] (t : colimit_cocone F) (j : J) :
t.cocone.ι.app j ≫ (colimit.iso_colimit_cocone t).inv = colimit.ι F j :=
by { dsimp [colimit.iso_colimit_cocone, is_colimit.cocone_point_unique_up_to_iso], tidy, }
@[ext] lemma colimit.hom_ext {F : J ⥤ C} [has_colimit F] {X : C} {f f' : colimit F ⟶ X}
(w : ∀ j, colimit.ι F j ≫ f = colimit.ι F j ≫ f') : f = f' :=
(colimit.is_colimit F).hom_ext w
@[simp] lemma colimit.desc_cocone {F : J ⥤ C} [has_colimit F] :
colimit.desc F (colimit.cocone F) = 𝟙 (colimit F) :=
(colimit.is_colimit _).desc_self
/--
The isomorphism (in `Type`) between
morphisms from the colimit object to a specified object `W`,
and cocones with cone point `W`.
-/
def colimit.hom_iso (F : J ⥤ C) [has_colimit F] (W : C) :
ulift.{u₁} (colimit F ⟶ W : Type v) ≅ (F.cocones.obj W) :=
(colimit.is_colimit F).hom_iso W
@[simp] lemma colimit.hom_iso_hom (F : J ⥤ C) [has_colimit F] {W : C} (f : ulift (colimit F ⟶ W)) :
(colimit.hom_iso F W).hom f = (colimit.cocone F).ι ≫ (const J).map f.down :=
(colimit.is_colimit F).hom_iso_hom f
/--
The isomorphism (in `Type`) between
morphisms from the colimit object to a specified object `W`,
and an explicit componentwise description of cocones with cone point `W`.
-/
def colimit.hom_iso' (F : J ⥤ C) [has_colimit F] (W : C) :
ulift.{u₁} ((colimit F ⟶ W) : Type v) ≅
{ p : Π j, F.obj j ⟶ W // ∀ {j j'} (f : j ⟶ j'), F.map f ≫ p j' = p j } :=
(colimit.is_colimit F).hom_iso' W
lemma colimit.desc_extend (F : J ⥤ C) [has_colimit F] (c : cocone F) {X : C} (f : c.X ⟶ X) :
colimit.desc F (c.extend f) = colimit.desc F c ≫ f :=
begin
ext1, rw [←category.assoc], simp
end
/--
If `F` has a colimit, so does any naturally isomorphic functor.
-/
-- This has the isomorphism pointing in the opposite direction than in `has_limit_of_iso`.
-- This is intentional; it seems to help with elaboration.
lemma has_colimit_of_iso {F G : J ⥤ C} [has_colimit F] (α : G ≅ F) : has_colimit G :=
has_colimit.mk
{ cocone := (cocones.precompose α.hom).obj (colimit.cocone F),
is_colimit :=
{ desc := λ s, colimit.desc F ((cocones.precompose α.inv).obj s),
fac' := λ s j,
begin
rw [cocones.precompose_obj_ι, nat_trans.comp_app, colimit.cocone_ι],
rw [category.assoc, colimit.ι_desc, ←nat_iso.app_hom, ←iso.eq_inv_comp], refl
end,
uniq' := λ s m w,
begin
apply colimit.hom_ext, intro j,
rw [colimit.ι_desc, cocones.precompose_obj_ι, nat_trans.comp_app, ←nat_iso.app_inv,
iso.eq_inv_comp],
simpa using w j
end } }
/-- If a functor `G` has the same collection of cocones as a functor `F`
which has a colimit, then `G` also has a colimit. -/
lemma has_colimit.of_cocones_iso {K : Type u₁} [category.{v₂} K] (F : J ⥤ C)
(G : K ⥤ C) (h : F.cocones ≅ G.cocones)
[has_colimit F] : has_colimit G :=
has_colimit.mk ⟨_, is_colimit.of_nat_iso (is_colimit.nat_iso (colimit.is_colimit F) ≪≫ h)⟩
/--
The colimits of `F : J ⥤ C` and `G : J ⥤ C` are isomorphic,
if the functors are naturally isomorphic.
-/
def has_colimit.iso_of_nat_iso {F G : J ⥤ C} [has_colimit F] [has_colimit G] (w : F ≅ G) :
colimit F ≅ colimit G :=
is_colimit.cocone_points_iso_of_nat_iso (colimit.is_colimit F) (colimit.is_colimit G) w
@[simp, reassoc]
lemma has_colimit.iso_of_nat_iso_ι_hom {F G : J ⥤ C} [has_colimit F] [has_colimit G]
(w : F ≅ G) (j : J) :
colimit.ι F j ≫ (has_colimit.iso_of_nat_iso w).hom = w.hom.app j ≫ colimit.ι G j :=
is_colimit.comp_cocone_points_iso_of_nat_iso_hom _ _ _ _
@[simp, reassoc]
lemma has_colimit.iso_of_nat_iso_ι_inv {F G : J ⥤ C} [has_colimit F] [has_colimit G]
(w : F ≅ G) (j : J) :
colimit.ι G j ≫ (has_colimit.iso_of_nat_iso w).inv = w.inv.app j ≫ colimit.ι F j :=
is_colimit.comp_cocone_points_iso_of_nat_iso_inv _ _ _ _
@[simp, reassoc]
lemma has_colimit.iso_of_nat_iso_hom_desc {F G : J ⥤ C} [has_colimit F] [has_colimit G]
(t : cocone G) (w : F ≅ G) :
(has_colimit.iso_of_nat_iso w).hom ≫ colimit.desc G t =
colimit.desc F ((cocones.precompose w.hom).obj _) :=
is_colimit.cocone_points_iso_of_nat_iso_hom_desc _ _ _
@[simp, reassoc]
lemma has_colimit.iso_of_nat_iso_inv_desc {F G : J ⥤ C} [has_colimit F] [has_colimit G]
(t : cocone F) (w : F ≅ G) :
(has_colimit.iso_of_nat_iso w).inv ≫ colimit.desc F t =
colimit.desc G ((cocones.precompose w.inv).obj _) :=
is_colimit.cocone_points_iso_of_nat_iso_inv_desc _ _ _
/--
The colimits of `F : J ⥤ C` and `G : K ⥤ C` are isomorphic,
if there is an equivalence `e : J ≌ K` making the triangle commute up to natural isomorphism.
-/
def has_colimit.iso_of_equivalence {F : J ⥤ C} [has_colimit F] {G : K ⥤ C} [has_colimit G]
(e : J ≌ K) (w : e.functor ⋙ G ≅ F) : colimit F ≅ colimit G :=
is_colimit.cocone_points_iso_of_equivalence (colimit.is_colimit F) (colimit.is_colimit G) e w
@[simp]
lemma has_colimit.iso_of_equivalence_hom_π {F : J ⥤ C} [has_colimit F] {G : K ⥤ C} [has_colimit G]
(e : J ≌ K) (w : e.functor ⋙ G ≅ F) (j : J) :
colimit.ι F j ≫ (has_colimit.iso_of_equivalence e w).hom =
F.map (e.unit.app j) ≫ w.inv.app _ ≫ colimit.ι G _ :=
begin
simp [has_colimit.iso_of_equivalence, is_colimit.cocone_points_iso_of_equivalence_inv],
dsimp,
simp,
end
@[simp]
lemma has_colimit.iso_of_equivalence_inv_π {F : J ⥤ C} [has_colimit F] {G : K ⥤ C} [has_colimit G]
(e : J ≌ K) (w : e.functor ⋙ G ≅ F) (k : K) :
colimit.ι G k ≫ (has_colimit.iso_of_equivalence e w).inv =
G.map (e.counit_inv.app k) ≫ w.hom.app (e.inverse.obj k) ≫ colimit.ι F (e.inverse.obj k) :=
begin
simp [has_colimit.iso_of_equivalence, is_colimit.cocone_points_iso_of_equivalence_inv],
dsimp,
simp,
end
section pre
variables (F) [has_colimit F] (E : K ⥤ J) [has_colimit (E ⋙ F)]
/--
The canonical morphism from the colimit of `E ⋙ F` to the colimit of `F`.
-/
def colimit.pre : colimit (E ⋙ F) ⟶ colimit F :=
colimit.desc (E ⋙ F) ((colimit.cocone F).whisker E)
@[simp, reassoc] lemma colimit.ι_pre (k : K) :
colimit.ι (E ⋙ F) k ≫ colimit.pre F E = colimit.ι F (E.obj k) :=
by { erw is_colimit.fac, refl, }
@[simp, reassoc] lemma colimit.pre_desc (c : cocone F) :
colimit.pre F E ≫ colimit.desc F c = colimit.desc (E ⋙ F) (c.whisker E) :=
by ext; rw [←assoc, colimit.ι_pre]; simp
variables {L : Type u₃} [category.{v₃} L]
variables (D : L ⥤ K) [has_colimit (D ⋙ E ⋙ F)]
@[simp] lemma colimit.pre_pre : colimit.pre (E ⋙ F) D ≫ colimit.pre F E = colimit.pre F (D ⋙ E) :=
begin
ext j,
rw [←assoc, colimit.ι_pre, colimit.ι_pre],
letI : has_colimit ((D ⋙ E) ⋙ F) := show has_colimit (D ⋙ E ⋙ F), by apply_instance,
exact (colimit.ι_pre F (D ⋙ E) j).symm
end
variables {E F}
/---
If we have particular colimit cocones available for `E ⋙ F` and for `F`,
we obtain a formula for `colimit.pre F E`.
-/
lemma colimit.pre_eq (s : colimit_cocone (E ⋙ F)) (t : colimit_cocone F) :
colimit.pre F E =
(colimit.iso_colimit_cocone s).hom ≫ s.is_colimit.desc ((t.cocone).whisker E) ≫
(colimit.iso_colimit_cocone t).inv :=
by tidy
end pre
section post
variables {D : Type u'} [category.{v'} D]
variables (F) [has_colimit F] (G : C ⥤ D) [has_colimit (F ⋙ G)]
/--
The canonical morphism from `G` applied to the colimit of `F ⋙ G`
to `G` applied to the colimit of `F`.
-/
def colimit.post : colimit (F ⋙ G) ⟶ G.obj (colimit F) :=
colimit.desc (F ⋙ G) (G.map_cocone (colimit.cocone F))
@[simp, reassoc] lemma colimit.ι_post (j : J) :
colimit.ι (F ⋙ G) j ≫ colimit.post F G = G.map (colimit.ι F j) :=
by { erw is_colimit.fac, refl, }
@[simp] lemma colimit.post_desc (c : cocone F) :
colimit.post F G ≫ G.map (colimit.desc F c) = colimit.desc (F ⋙ G) (G.map_cocone c) :=
by { ext, rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_desc, colimit.ι_desc], refl }
@[simp] lemma colimit.post_post
{E : Type u''} [category.{v''} E] (H : D ⥤ E) [has_colimit ((F ⋙ G) ⋙ H)] :
/- H G (colimit F) ⟶ H (colimit (F ⋙ G)) ⟶ colimit ((F ⋙ G) ⋙ H) equals -/
/- H G (colimit F) ⟶ colimit (F ⋙ (G ⋙ H)) -/
colimit.post (F ⋙ G) H ≫ H.map (colimit.post F G) = colimit.post F (G ⋙ H) :=
begin
ext,
rw [←assoc, colimit.ι_post, ←H.map_comp, colimit.ι_post],
exact (colimit.ι_post F (G ⋙ H) j).symm
end
end post
lemma colimit.pre_post {D : Type u'} [category.{v'} D]
(E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D)
[has_colimit F] [has_colimit (E ⋙ F)] [has_colimit (F ⋙ G)] [H : has_colimit ((E ⋙ F) ⋙ G)] :
/- G (colimit F) ⟶ G (colimit (E ⋙ F)) ⟶ colimit ((E ⋙ F) ⋙ G) vs -/
/- G (colimit F) ⟶ colimit F ⋙ G ⟶ colimit (E ⋙ (F ⋙ G)) or -/
colimit.post (E ⋙ F) G ≫ G.map (colimit.pre F E) =
(@@colimit.pre _ _ _ (F ⋙ G) _ E H ≫ colimit.post F G : _) :=
begin
ext,
rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_pre, ←assoc],
letI : has_colimit (E ⋙ F ⋙ G) := show has_colimit ((E ⋙ F) ⋙ G), by apply_instance,
erw [colimit.ι_pre (F ⋙ G) E j, colimit.ι_post]
end
open category_theory.equivalence
instance has_colimit_equivalence_comp (e : K ≌ J) [has_colimit F] : has_colimit (e.functor ⋙ F) :=
has_colimit.mk { cocone := cocone.whisker e.functor (colimit.cocone F),
is_colimit := is_colimit.whisker_equivalence (colimit.is_colimit F) e, }
/--
If a `E ⋙ F` has a colimit, and `E` is an equivalence, we can construct a colimit of `F`.
-/
lemma has_colimit_of_equivalence_comp (e : K ≌ J) [has_colimit (e.functor ⋙ F)] : has_colimit F :=
begin
haveI : has_colimit (e.inverse ⋙ e.functor ⋙ F) := limits.has_colimit_equivalence_comp e.symm,
apply has_colimit_of_iso (e.inv_fun_id_assoc F).symm,
end
section colim_functor
variables [has_colimits_of_shape J C]
section
local attribute [simp] colim_map
/-- `colimit F` is functorial in `F`, when `C` has all colimits of shape `J`. -/
@[simps obj]
def colim : (J ⥤ C) ⥤ C :=
{ obj := λ F, colimit F,
map := λ F G α, colim_map α,
map_id' := λ F, by { ext, erw [ι_colim_map, id_comp, comp_id] },
map_comp' := λ F G H α β,
by { ext, erw [←assoc, is_colimit.fac, is_colimit.fac, assoc, is_colimit.fac, ←assoc], refl } }
end
variables {F} {G : J ⥤ C} (α : F ⟶ G)
@[simp, reassoc] lemma colimit.ι_map (j : J) :
colimit.ι F j ≫ colim.map α = α.app j ≫ colimit.ι G j :=
by apply is_colimit.fac
@[simp] lemma colimit.map_desc (c : cocone G) :
colim.map α ≫ colimit.desc G c = colimit.desc F ((cocones.precompose α).obj c) :=
by ext; rw [←assoc, colimit.ι_map, assoc, colimit.ι_desc, colimit.ι_desc]; refl
lemma colimit.pre_map [has_colimits_of_shape K C] (E : K ⥤ J) :
colimit.pre F E ≫ colim.map α = colim.map (whisker_left E α) ≫ colimit.pre G E :=
by ext; rw [←assoc, colimit.ι_pre, colimit.ι_map, ←assoc, colimit.ι_map, assoc, colimit.ι_pre]; refl
lemma colimit.pre_map' [has_colimits_of_shape K C]
(F : J ⥤ C) {E₁ E₂ : K ⥤ J} (α : E₁ ⟶ E₂) :
colimit.pre F E₁ = colim.map (whisker_right α F) ≫ colimit.pre F E₂ :=
by ext1; simp [← category.assoc]
lemma colimit.pre_id (F : J ⥤ C) :
colimit.pre F (𝟭 _) = colim.map (functor.left_unitor F).hom := by tidy
lemma colimit.map_post {D : Type u'} [category.{v'} D] [has_colimits_of_shape J D] (H : C ⥤ D) :
/- H (colimit F) ⟶ H (colimit G) ⟶ colimit (G ⋙ H) vs
H (colimit F) ⟶ colimit (F ⋙ H) ⟶ colimit (G ⋙ H) -/
colimit.post F H ≫ H.map (colim.map α) = colim.map (whisker_right α H) ≫ colimit.post G H:=
begin
ext,
rw [←assoc, colimit.ι_post, ←H.map_comp, colimit.ι_map, H.map_comp],
rw [←assoc, colimit.ι_map, assoc, colimit.ι_post],
refl
end
/--
The isomorphism between
morphisms from the cone point of the colimit cocone for `F` to `W`
and cocones over `F` with cone point `W`
is natural in `F`.
-/
def colim_coyoneda : colim.op ⋙ coyoneda ⋙ (whiskering_right _ _ _).obj ulift_functor.{u₁} ≅
category_theory.cocones J C :=
nat_iso.of_components (λ F, nat_iso.of_components (colimit.hom_iso (unop F)) (by tidy))
(by tidy)
end colim_functor
/--
We can transport colimits of shape `J` along an equivalence `J ≌ J'`.
-/
lemma has_colimits_of_shape_of_equivalence {J' : Type u₂} [category.{v₂} J']
(e : J ≌ J') [has_colimits_of_shape J C] : has_colimits_of_shape J' C :=
by { constructor, intro F, apply has_colimit_of_equivalence_comp e, apply_instance }
variable (C)
/--
`has_colimits_of_size_shrink.{v u} C` tries to obtain `has_colimits_of_size.{v u} C`
from some other `has_colimits_of_size C`.
-/
lemma has_colimits_of_size_shrink [has_colimits_of_size.{(max v₁ v₂) (max u₁ u₂)} C] :
has_colimits_of_size.{v₁ u₁} C :=
⟨λ J hJ, by exactI has_colimits_of_shape_of_equivalence
(ulift_hom_ulift_category.equiv.{v₂ u₂} J).symm⟩
@[priority 100]
instance has_smallest_colimits_of_has_colimits [has_colimits C] :
has_colimits_of_size.{0 0} C := has_colimits_of_size_shrink.{0 0} C
end colimit
section opposite
/--
If `t : cone F` is a limit cone, then `t.op : cocone F.op` is a colimit cocone.
-/
def is_limit.op {t : cone F} (P : is_limit t) : is_colimit t.op :=
{ desc := λ s, (P.lift s.unop).op,
fac' := λ s j, congr_arg quiver.hom.op (P.fac s.unop (unop j)),
uniq' := λ s m w,
begin
rw ← P.uniq s.unop m.unop,
{ refl, },
{ dsimp, intro j, rw ← w, refl, }
end }
/--
If `t : cocone F` is a colimit cocone, then `t.op : cone F.op` is a limit cone.
-/
def is_colimit.op {t : cocone F} (P : is_colimit t) : is_limit t.op :=
{ lift := λ s, (P.desc s.unop).op,
fac' := λ s j, congr_arg quiver.hom.op (P.fac s.unop (unop j)),
uniq' := λ s m w,
begin
rw ← P.uniq s.unop m.unop,
{ refl, },
{ dsimp, intro j, rw ← w, refl, }
end }
/--
If `t : cone F.op` is a limit cone, then `t.unop : cocone F` is a colimit cocone.
-/
def is_limit.unop {t : cone F.op} (P : is_limit t) : is_colimit t.unop :=
{ desc := λ s, (P.lift s.op).unop,
fac' := λ s j, congr_arg quiver.hom.unop (P.fac s.op (op j)),
uniq' := λ s m w,
begin
rw ← P.uniq s.op m.op,
{ refl, },
{ dsimp, intro j, rw ← w, refl, }
end }
/--
If `t : cocone F.op` is a colimit cocone, then `t.unop : cone F.` is a limit cone.
-/
def is_colimit.unop {t : cocone F.op} (P : is_colimit t) : is_limit t.unop :=
{ lift := λ s, (P.desc s.op).unop,
fac' := λ s j, congr_arg quiver.hom.unop (P.fac s.op (op j)),
uniq' := λ s m w,
begin
rw ← P.uniq s.op m.op,
{ refl, },
{ dsimp, intro j, rw ← w, refl, }
end }
/--
`t : cone F` is a limit cone if and only is `t.op : cocone F.op` is a colimit cocone.
-/
def is_limit_equiv_is_colimit_op {t : cone F} : is_limit t ≃ is_colimit t.op :=
equiv_of_subsingleton_of_subsingleton
is_limit.op (λ P, P.unop.of_iso_limit (cones.ext (iso.refl _) (by tidy)))
/--
`t : cocone F` is a colimit cocone if and only is `t.op : cone F.op` is a limit cone.
-/
def is_colimit_equiv_is_limit_op {t : cocone F} : is_colimit t ≃ is_limit t.op :=
equiv_of_subsingleton_of_subsingleton
is_colimit.op (λ P, P.unop.of_iso_colimit (cocones.ext (iso.refl _) (by tidy)))
end opposite
end category_theory.limits
|
99ad7c623b3f166ad6d0064d35a79ce301cb6a66 | 8c9f90127b78cbeb5bb17fd6b5db1db2ffa3cbc4 | /kennys_stuff.lean | 5eb82eccf7a996c060f67e3ee45770fe4188217b | [] | no_license | picrin/lean | 420f4d08bb3796b911d56d0938e4410e1da0e072 | 3d10c509c79704aa3a88ebfb24d08b30ce1137cc | refs/heads/master | 1,611,166,610,726 | 1,536,671,438,000 | 1,536,671,438,000 | 60,029,899 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,161 | lean | def even : ℕ → Prop
| 0 := true
| 1 := false
| (n+2) := even n
def even2 : ℕ → Prop :=
λ n, ∃ k, n = 2 * k
inductive even3 : ℕ → Prop
| zero : even3 0
| add_two : ∀ n, even3 n → even3 (n+2)
example : even3 4 :=
even3.add_two 2 $ even3.add_two 0 even3.zero
example : ∀ n, even3 n ↔ even2 n :=
λ n,
⟨λ H, even3.rec_on H ⟨0, rfl⟩ $ λ n H ⟨k, ih⟩,
⟨k + 1, @eq.rec_on nat (2 * k) (λ z, z + 2 = 2 * (k + 1)) n ih.symm rfl⟩,
λ ⟨k, H⟩, H.symm ▸ (nat.rec_on k even3.zero $ λ n, even3.add_two (2 * n))⟩
example : ∀ n, even3 n ↔ even2 n :=
begin
intro n,
constructor,
{ intro H,
induction H with n H ih,
{ existsi 0, refl },
cases ih with k ih,
rw ih,
existsi (k+1),
refl },
intro H,
cases H with k H,
rw H,
clear H n,
induction k with k ih,
{ constructor },
constructor,
assumption
end
variables (A : Type) (p q : A → Prop)
variable a : A
variable r : Prop
theorem distributiveForAll : (∀ (x : A), r ∨ p x) ↔ (r ∨ ∀ (x : A), p x) :=
⟨λ H, or.cases_on (classical.em r) or.inl $ λ h1,
or.inr $ λ x, or.resolve_left (H x) h1,
λ H, or.cases_on H (λ h1 x, or.inl h1) $ λ h1 x, or.inr $ h1 x⟩
|
2010fdd164e0d75a5aca8aa9082d595662e60fb6 | d450724ba99f5b50b57d244eb41fef9f6789db81 | /src/mywork/lectures/lecture_11.lean | bb5bc2deeb9963a17b23c4cad444509283884d3d | [] | no_license | jakekauff/CS2120F21 | 4f009adeb4ce4a148442b562196d66cc6c04530c | e69529ec6f5d47a554291c4241a3d8ec4fe8f5ad | refs/heads/main | 1,693,841,880,030 | 1,637,604,848,000 | 1,637,604,848,000 | 399,946,698 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,464 | lean | /-
In this lecture we began to pull together the big
picture of the language of predicate logic, proofs,
reasoning principles (axioms, theorems proved from
them). For each logical connective and quantifier,
we have zero or more introduction and elimination
rules. You absolutely have to understand all of
them and be sufficiently practiced in their use so
as to employ them when solving new proof problems.
-/
/-
In this lecture, we continue to fill in our chart
with a sharp focus on on negation elimination, a
topic new for us here. Negation elimination is a
bit of a misnomer, in the sense allow us to cancel
double negations. In this sense it is the heart of
what we call proof by contradiction.
Recall that in a proof by negation, your goal is
to prove ¬P, for some proposition, P. To do so,
you assume P, show that that leads to some kind
of contradiction, and conclude P → false. This
is the precondition for deducting ¬P.
Proof by contradition is different. Here you want
to prove P. You do this by assuming ¬P, and then
you show that the assumption yields a contradiction,
thus showing ¬¬P. Negation elimination is the used
to deduce P (from ¬¬P).
The interesting fact, however, is that ¬¬P → P is
not a theorem in the constructive logic of the Lean
Prover. Rather, if this inference rule is to be used
in reasoning (and most mathematicians use it freely)
it has to be added as an axiom, or in the form of
another axiom that his this one as a consequence.
Here we accept a different axiom, the so-called law
of the excluded middle. It's really not a law, it's
just a useful axiom that we can add to our logic
without causing any inconsistencies/contradictions.
It's the use of the excluded middle (em) that makes
it possible to derive ¬¬P → P as a theorem. (The
truth is that you can assume either and derive the
other, so the turn out to be equivalent.)
-/
/-
The first two examples/problems from the homework
gave us material to review the concepts of negation,
false, and case analysis on values of uninhabited
types as a way to complete proofs "for free." (This
is false elimination.)
-/
/-
0 ≠ 1 is just notation for
¬(0 = 1), and that is just notation for
(0 = 1) → false
The proposition to be proved is thus an implication
We assume the premise
The proof is then completed by case analysis on that assumption
As there are zero ways to construct a proof of 0 = 1, we're done
-/
example : 0 ≠ 1 :=
begin
assume h,
cases h,
end
/-
From a false premise, anything follows. The proof here is
more interesting. As we're to prove an implication, we first
assume the premise, 0 ≠ 0, and then need to show 2 = 3.
Now 0 ≠ 0 means ¬(0 = 0), and that means (0 = 0) → false.
In other words, if we have a proof of 0 = 0, we can derive
a proof of false from it. But of course it's trivial to get
a proof of 0 = 0; it's just (eq.refl 0). We thus have what
we need to derive a proof of false, at which point we use
false elimination to be done.
-/
example : 0 ≠ 0 → 2 = 3 :=
begin
assume h,
exact false.elim (h (eq.refl 0)),
end
/-
As a warmup to proving our main theorem, ¬¬P → P, here
we prove its converse, P → ¬¬P. This proof turns out to
be pretty easy and well within reach in the logic of Lean
without any additional axioms.
-/
example : ∀ (P : Prop), P → ¬¬P :=
begin
assume P,
assume (p : P),
-- ¬¬P
-- ¬P → false
-- (P → false) → false
assume h,
have f : false := h p,
exact f,
end
/-
Finally we come to the principle of negation
elimination and the directly related strategy
of proof by contradiction. Remember: you want
to prove P, so you assume ¬P, then show that
this leads to a contradiction, proving ¬¬P,
at which point you "go classical" and apply
the theorem/axiom of negation elimination to
conclude P.
-/
/-
Remarkably, this principle is neither an axiom
or a theorem in Lean. Nither is a related axiom,
the axiom of the excluded middle. Adding it is
easy: we declare this universal generalization
to have a proof, em, which makes it applicable
to *any* proposition, P, whatsoever. When so
applied, it yields is a *proof* of the r*elated*
proposition, P ∨ ¬P.
-/
axiom em : ∀ (P : Prop), P ∨ ¬P
/-
The "law" (axiom) of the excluded middle is a key
to proving many intuitive theorems in logic and
mathematics. But it also has a cost in that the
proofs it produces are "uninformative", where a
proof of P ∨ ¬P in Lean's constructive logic would
include a detailed proof one way or the other, all
the way down to the basic axioms of the logic. In
cases where code is to be extracted from proofs,
you can imagine that having uninformative proofs
makes that task impossible, and you'd be right.
-/
theorem neg_elim : ∀ (P : Prop), ¬¬P → P :=
begin
assume P,
assume h,
have pornp := classical.em P,
cases pornp with p pn,
assumption,
contradiction,
end
/-
Remember, proof by contradiction is really (and
literally) just applying the axiom of negation
elimination. You can see this priciple in action
right here.
-/
axiom P : Prop
theorem p : P :=
begin -- goal is to prove P
apply neg_elim _, -- with neg_elim it will suffice to prove ¬¬P
assume np, -- this entails assuming ¬P and deriving a contradiction
-- that's the essence of proof by contradiction
-- of course we have no information to finish this proof
end |
7cc81f116434ccec7098f544acbb9074c09e8c95 | 08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4 | /src/Init/System/IO.lean | db703115134c4762ceb386a8140b80c7be60f981 | [
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"Apache-2.0",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | gebner/lean4 | d51c4922640a52a6f7426536ea669ef18a1d9af5 | 8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f | refs/heads/master | 1,685,732,780,391 | 1,672,962,627,000 | 1,673,459,398,000 | 373,307,283 | 0 | 0 | Apache-2.0 | 1,691,316,730,000 | 1,622,669,271,000 | Lean | UTF-8 | Lean | false | false | 25,726 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Luke Nelson, Jared Roesch, Leonardo de Moura, Sebastian Ullrich
-/
prelude
import Init.Control.EState
import Init.Control.Reader
import Init.Data.String
import Init.Data.ByteArray
import Init.System.IOError
import Init.System.FilePath
import Init.System.ST
import Init.Data.ToString.Macro
import Init.Data.Ord
open System
/-- Like https://hackage.haskell.org/package/ghc-Prim-0.5.2.0/docs/GHC-Prim.html#t:RealWorld.
Makes sure we never reorder `IO` operations.
TODO: mark opaque -/
def IO.RealWorld : Type := Unit
/- TODO(Leo): mark it as an opaque definition. Reason: prevent
functions defined in other modules from accessing `IO.RealWorld`.
We don't want action such as
```
def getWorld : IO (IO.RealWorld) := get
```
-/
def EIO (ε : Type) : Type → Type := EStateM ε IO.RealWorld
instance : Monad (EIO ε) := inferInstanceAs (Monad (EStateM ε IO.RealWorld))
instance : MonadFinally (EIO ε) := inferInstanceAs (MonadFinally (EStateM ε IO.RealWorld))
instance : MonadExceptOf ε (EIO ε) := inferInstanceAs (MonadExceptOf ε (EStateM ε IO.RealWorld))
instance : OrElse (EIO ε α) := ⟨MonadExcept.orElse⟩
instance [Inhabited ε] : Inhabited (EIO ε α) := inferInstanceAs (Inhabited (EStateM ε IO.RealWorld α))
/-- An `EIO` monad that cannot throw exceptions. -/
def BaseIO := EIO Empty
instance : Monad BaseIO := inferInstanceAs (Monad (EIO Empty))
instance : MonadFinally BaseIO := inferInstanceAs (MonadFinally (EIO Empty))
@[always_inline, inline]
def BaseIO.toEIO (act : BaseIO α) : EIO ε α :=
fun s => match act s with
| EStateM.Result.ok a s => EStateM.Result.ok a s
instance : MonadLift BaseIO (EIO ε) := ⟨BaseIO.toEIO⟩
@[always_inline, inline]
def EIO.toBaseIO (act : EIO ε α) : BaseIO (Except ε α) :=
fun s => match act s with
| EStateM.Result.ok a s => EStateM.Result.ok (Except.ok a) s
| EStateM.Result.error ex s => EStateM.Result.ok (Except.error ex) s
@[always_inline, inline]
def EIO.catchExceptions (act : EIO ε α) (h : ε → BaseIO α) : BaseIO α :=
fun s => match act s with
| EStateM.Result.ok a s => EStateM.Result.ok a s
| EStateM.Result.error ex s => h ex s
open IO (Error) in
abbrev IO : Type → Type := EIO Error
@[inline] def BaseIO.toIO (act : BaseIO α) : IO α :=
act
@[inline] def EIO.toIO (f : ε → IO.Error) (act : EIO ε α) : IO α :=
act.adaptExcept f
@[inline] def EIO.toIO' (act : EIO ε α) : IO (Except ε α) :=
act.toBaseIO
@[inline] def IO.toEIO (f : IO.Error → ε) (act : IO α) : EIO ε α :=
act.adaptExcept f
/- After we inline `EState.run'`, the closed term `((), ())` is generated, where the second `()`
represents the "initial world". We don't want to cache this closed term. So, we disable
the "extract closed terms" optimization. -/
set_option compiler.extract_closed false in
@[inline] unsafe def unsafeBaseIO (fn : BaseIO α) : α :=
match fn.run () with
| EStateM.Result.ok a _ => a
@[inline] unsafe def unsafeEIO (fn : EIO ε α) : Except ε α :=
unsafeBaseIO fn.toBaseIO
@[inline] unsafe def unsafeIO (fn : IO α) : Except IO.Error α :=
unsafeEIO fn
@[extern "lean_io_timeit"] opaque timeit (msg : @& String) (fn : IO α) : IO α
@[extern "lean_io_allocprof"] opaque allocprof (msg : @& String) (fn : IO α) : IO α
/-- Programs can execute IO actions during initialization that occurs before
the `main` function is executed. The attribute `[init <action>]` specifies
which IO action is executed to set the value of an opaque constant.
The action `initializing` returns `true` iff it is invoked during initialization. -/
@[extern "lean_io_initializing"] opaque IO.initializing : BaseIO Bool
namespace BaseIO
/--
Run `act` in a separate `Task`.
This is similar to Haskell's [`unsafeInterleaveIO`](http://hackage.haskell.org/package/base-4.14.0.0/docs/System-IO-Unsafe.html#v:unsafeInterleaveIO),
except that the `Task` is started eagerly as usual. Thus pure accesses to the `Task` do not influence the impure `act`
computation.
Unlike with pure tasks created by `Task.spawn`, tasks created by this function will be run even if the last reference
to the task is dropped. The `act` should manually check for cancellation via `IO.checkCanceled` if it wants to react
to that. -/
@[extern "lean_io_as_task"]
opaque asTask (act : BaseIO α) (prio := Task.Priority.default) : BaseIO (Task α) :=
Task.pure <$> act
/-- See `BaseIO.asTask`. -/
@[extern "lean_io_map_task"]
opaque mapTask (f : α → BaseIO β) (t : Task α) (prio := Task.Priority.default) : BaseIO (Task β) :=
Task.pure <$> f t.get
/-- See `BaseIO.asTask`. -/
@[extern "lean_io_bind_task"]
opaque bindTask (t : Task α) (f : α → BaseIO (Task β)) (prio := Task.Priority.default) : BaseIO (Task β) :=
f t.get
def mapTasks (f : List α → BaseIO β) (tasks : List (Task α)) (prio := Task.Priority.default) : BaseIO (Task β) :=
go tasks []
where
go
| t::ts, as =>
BaseIO.bindTask t (fun a => go ts (a :: as)) prio
| [], as => f as.reverse |>.asTask prio
end BaseIO
namespace EIO
/-- `EIO` specialization of `BaseIO.asTask`. -/
@[inline] def asTask (act : EIO ε α) (prio := Task.Priority.default) : BaseIO (Task (Except ε α)) :=
act.toBaseIO.asTask prio
/-- `EIO` specialization of `BaseIO.mapTask`. -/
@[inline] def mapTask (f : α → EIO ε β) (t : Task α) (prio := Task.Priority.default) : BaseIO (Task (Except ε β)) :=
BaseIO.mapTask (fun a => f a |>.toBaseIO) t prio
/-- `EIO` specialization of `BaseIO.bindTask`. -/
@[inline] def bindTask (t : Task α) (f : α → EIO ε (Task (Except ε β))) (prio := Task.Priority.default) : BaseIO (Task (Except ε β)) :=
BaseIO.bindTask t (fun a => f a |>.catchExceptions fun e => return Task.pure <| Except.error e) prio
/-- `EIO` specialization of `BaseIO.mapTasks`. -/
@[inline] def mapTasks (f : List α → EIO ε β) (tasks : List (Task α)) (prio := Task.Priority.default) : BaseIO (Task (Except ε β)) :=
BaseIO.mapTasks (fun as => f as |>.toBaseIO) tasks prio
end EIO
namespace IO
def ofExcept [ToString ε] (e : Except ε α) : IO α :=
match e with
| Except.ok a => pure a
| Except.error e => throw (IO.userError (toString e))
def lazyPure (fn : Unit → α) : IO α :=
pure (fn ())
/-- Monotonically increasing time since an unspecified past point in milliseconds. No relation to wall clock time. -/
@[extern "lean_io_mono_ms_now"] opaque monoMsNow : BaseIO Nat
/-- Monotonically increasing time since an unspecified past point in nanoseconds. No relation to wall clock time. -/
@[extern "lean_io_mono_nanos_now"] opaque monoNanosNow : BaseIO Nat
/-- Read bytes from a system entropy source. Not guaranteed to be cryptographically secure.
If `nBytes = 0`, return immediately with an empty buffer. -/
@[extern "lean_io_get_random_bytes"] opaque getRandomBytes (nBytes : USize) : IO ByteArray
def sleep (ms : UInt32) : BaseIO Unit :=
-- TODO: add a proper primitive for IO.sleep
fun s => dbgSleep ms fun _ => EStateM.Result.ok () s
/-- `IO` specialization of `EIO.asTask`. -/
@[inline] def asTask (act : IO α) (prio := Task.Priority.default) : BaseIO (Task (Except IO.Error α)) :=
EIO.asTask act prio
/-- `IO` specialization of `EIO.mapTask`. -/
@[inline] def mapTask (f : α → IO β) (t : Task α) (prio := Task.Priority.default) : BaseIO (Task (Except IO.Error β)) :=
EIO.mapTask f t prio
/-- `IO` specialization of `EIO.bindTask`. -/
@[inline] def bindTask (t : Task α) (f : α → IO (Task (Except IO.Error β))) (prio := Task.Priority.default) : BaseIO (Task (Except IO.Error β)) :=
EIO.bindTask t f prio
/-- `IO` specialization of `EIO.mapTasks`. -/
@[inline] def mapTasks (f : List α → IO β) (tasks : List (Task α)) (prio := Task.Priority.default) : BaseIO (Task (Except IO.Error β)) :=
EIO.mapTasks f tasks prio
/-- Check if the task's cancellation flag has been set by calling `IO.cancel` or dropping the last reference to the task. -/
@[extern "lean_io_check_canceled"] opaque checkCanceled : BaseIO Bool
/-- Request cooperative cancellation of the task. The task must explicitly call `IO.checkCanceled` to react to the cancellation. -/
@[extern "lean_io_cancel"] opaque cancel : @& Task α → BaseIO Unit
/-- Check if the task has finished execution, at which point calling `Task.get` will return immediately. -/
@[extern "lean_io_has_finished"] opaque hasFinished : @& Task α → BaseIO Bool
/-- Wait for the task to finish, then return its result. -/
@[extern "lean_io_wait"] opaque wait (t : Task α) : BaseIO α :=
return t.get
local macro "nonempty_list" : tactic =>
`(tactic| exact Nat.zero_lt_succ _)
/-- Wait until any of the tasks in the given list has finished, then return its result. -/
@[extern "lean_io_wait_any"] opaque waitAny (tasks : @& List (Task α))
(h : tasks.length > 0 := by nonempty_list) : BaseIO α :=
return tasks[0].get
/-- Helper method for implementing "deterministic" timeouts. It is the number of "small" memory allocations performed by the current execution thread. -/
@[extern "lean_io_get_num_heartbeats"] opaque getNumHeartbeats : BaseIO Nat
inductive FS.Mode where
| read | write | readWrite | append
opaque FS.Handle : Type := Unit
/--
A pure-Lean abstraction of POSIX streams. We use `Stream`s for the standard streams stdin/stdout/stderr so we can
capture output of `#eval` commands into memory. -/
structure FS.Stream where
flush : IO Unit
/--
Read up to the given number of bytes from the stream.
If the returned array is empty, an end-of-file marker has been reached.
Note that EOF does not actually close a stream, so further reads may block and return more data.
-/
read : USize → IO ByteArray
write : ByteArray → IO Unit
/--
Read text up to (including) the next line break from the stream.
If the returned string is empty, an end-of-file marker has been reached.
Note that EOF does not actually close a stream, so further reads may block and return more data.
-/
getLine : IO String
putStr : String → IO Unit
deriving Inhabited
open FS
@[extern "lean_get_stdin"] opaque getStdin : BaseIO FS.Stream
@[extern "lean_get_stdout"] opaque getStdout : BaseIO FS.Stream
@[extern "lean_get_stderr"] opaque getStderr : BaseIO FS.Stream
/-- Replaces the stdin stream of the current thread and returns its previous value. -/
@[extern "lean_get_set_stdin"] opaque setStdin : FS.Stream → BaseIO FS.Stream
/-- Replaces the stdout stream of the current thread and returns its previous value. -/
@[extern "lean_get_set_stdout"] opaque setStdout : FS.Stream → BaseIO FS.Stream
/-- Replaces the stderr stream of the current thread and returns its previous value. -/
@[extern "lean_get_set_stderr"] opaque setStderr : FS.Stream → BaseIO FS.Stream
@[specialize] partial def iterate (a : α) (f : α → IO (Sum α β)) : IO β := do
let v ← f a
match v with
| Sum.inl a => iterate a f
| Sum.inr b => pure b
namespace FS
namespace Handle
private def fopenFlags (m : FS.Mode) (b : Bool) : String :=
let mode :=
match m with
| FS.Mode.read => "r"
| FS.Mode.write => "w"
| FS.Mode.readWrite => "r+"
| FS.Mode.append => "a" ;
let bin := if b then "b" else "t"
mode ++ bin
@[extern "lean_io_prim_handle_mk"] opaque mkPrim (fn : @& FilePath) (mode : @& String) : IO Handle
def mk (fn : FilePath) (Mode : Mode) (bin : Bool := true) : IO Handle :=
mkPrim fn (fopenFlags Mode bin)
@[extern "lean_io_prim_handle_flush"] opaque flush (h : @& Handle) : IO Unit
/--
Read up to the given number of bytes from the handle.
If the returned array is empty, an end-of-file marker has been reached.
Note that EOF does not actually close a handle, so further reads may block and return more data.
-/
@[extern "lean_io_prim_handle_read"] opaque read (h : @& Handle) (bytes : USize) : IO ByteArray
@[extern "lean_io_prim_handle_write"] opaque write (h : @& Handle) (buffer : @& ByteArray) : IO Unit
/--
Read text up to (including) the next line break from the handle.
If the returned string is empty, an end-of-file marker has been reached.
Note that EOF does not actually close a handle, so further reads may block and return more data.
-/
@[extern "lean_io_prim_handle_get_line"] opaque getLine (h : @& Handle) : IO String
@[extern "lean_io_prim_handle_put_str"] opaque putStr (h : @& Handle) (s : @& String) : IO Unit
end Handle
@[extern "lean_io_realpath"] opaque realPath (fname : FilePath) : IO FilePath
@[extern "lean_io_remove_file"] opaque removeFile (fname : @& FilePath) : IO Unit
/-- Remove given directory. Fails if not empty; see also `IO.FS.removeDirAll`. -/
@[extern "lean_io_remove_dir"] opaque removeDir : @& FilePath → IO Unit
@[extern "lean_io_create_dir"] opaque createDir : @& FilePath → IO Unit
end FS
@[extern "lean_io_getenv"] opaque getEnv (var : @& String) : BaseIO (Option String)
@[extern "lean_io_app_path"] opaque appPath : IO FilePath
@[extern "lean_io_current_dir"] opaque currentDir : IO FilePath
namespace FS
@[inline]
def withFile (fn : FilePath) (mode : Mode) (f : Handle → IO α) : IO α :=
Handle.mk fn mode >>= f
def Handle.putStrLn (h : Handle) (s : String) : IO Unit :=
h.putStr (s.push '\n')
partial def Handle.readBinToEnd (h : Handle) : IO ByteArray := do
let rec loop (acc : ByteArray) : IO ByteArray := do
let buf ← h.read 1024
if buf.isEmpty then
return acc
else
loop (acc ++ buf)
loop ByteArray.empty
partial def Handle.readToEnd (h : Handle) : IO String := do
let rec loop (s : String) := do
let line ← h.getLine
if line.isEmpty then
return s
else
loop (s ++ line)
loop ""
def readBinFile (fname : FilePath) : IO ByteArray := do
let h ← Handle.mk fname Mode.read true
h.readBinToEnd
def readFile (fname : FilePath) : IO String := do
let h ← Handle.mk fname Mode.read false
h.readToEnd
partial def lines (fname : FilePath) : IO (Array String) := do
let h ← Handle.mk fname Mode.read false
let rec read (lines : Array String) := do
let line ← h.getLine
if line.length == 0 then
pure lines
else if line.back == '\n' then
let line := line.dropRight 1
let line := if System.Platform.isWindows && line.back == '\x0d' then line.dropRight 1 else line
read <| lines.push line
else
pure <| lines.push line
read #[]
def writeBinFile (fname : FilePath) (content : ByteArray) : IO Unit := do
let h ← Handle.mk fname Mode.write true
h.write content
def writeFile (fname : FilePath) (content : String) : IO Unit := do
let h ← Handle.mk fname Mode.write false
h.putStr content
def Stream.putStrLn (strm : FS.Stream) (s : String) : IO Unit :=
strm.putStr (s.push '\n')
structure DirEntry where
root : FilePath
fileName : String
deriving Repr
def DirEntry.path (entry : DirEntry) : FilePath :=
entry.root / entry.fileName
inductive FileType where
| dir
| file
| symlink
| other
deriving Repr, BEq
structure SystemTime where
sec : Int
nsec : UInt32
deriving Repr, BEq, Ord, Inhabited
instance : LT SystemTime := ltOfOrd
instance : LE SystemTime := leOfOrd
structure Metadata where
--permissions : ...
accessed : SystemTime
modified : SystemTime
byteSize : UInt64
type : FileType
deriving Repr
end FS
end IO
namespace System.FilePath
open IO
@[extern "lean_io_read_dir"]
opaque readDir : @& FilePath → IO (Array IO.FS.DirEntry)
@[extern "lean_io_metadata"]
opaque metadata : @& FilePath → IO IO.FS.Metadata
def isDir (p : FilePath) : BaseIO Bool := do
match (← p.metadata.toBaseIO) with
| Except.ok m => return m.type == IO.FS.FileType.dir
| Except.error _ => return false
def pathExists (p : FilePath) : BaseIO Bool :=
return (← p.metadata.toBaseIO).toBool
/--
Return all filesystem entries of a preorder traversal of all directories satisfying `enter`, starting at `p`.
Symbolic links are visited as well by default. -/
partial def walkDir (p : FilePath) (enter : FilePath → IO Bool := fun _ => pure true) : IO (Array FilePath) :=
Prod.snd <$> StateT.run (go p) #[]
where
go p := do
if !(← enter p) then
return ()
for d in (← p.readDir) do
modify (·.push d.path)
let m ← d.path.metadata
match m.type with
| FS.FileType.symlink =>
let p' ← FS.realPath d.path
if (← p'.isDir) then
-- do not call `enter` on a non-directory symlink
if (← enter p) then
go p'
| FS.FileType.dir => go d.path
| _ => pure ()
end System.FilePath
namespace IO
def withStdin [Monad m] [MonadFinally m] [MonadLiftT BaseIO m] (h : FS.Stream) (x : m α) : m α := do
let prev ← setStdin h
try x finally discard <| setStdin prev
def withStdout [Monad m] [MonadFinally m] [MonadLiftT BaseIO m] (h : FS.Stream) (x : m α) : m α := do
let prev ← setStdout h
try
x
finally
discard <| setStdout prev
def withStderr [Monad m] [MonadFinally m] [MonadLiftT BaseIO m] (h : FS.Stream) (x : m α) : m α := do
let prev ← setStderr h
try x finally discard <| setStderr prev
def print [ToString α] (s : α) : IO Unit := do
let out ← getStdout
out.putStr <| toString s
def println [ToString α] (s : α) : IO Unit :=
print ((toString s).push '\n')
def eprint [ToString α] (s : α) : IO Unit := do
let out ← getStderr
out.putStr <| toString s
def eprintln [ToString α] (s : α) : IO Unit :=
eprint <| toString s |>.push '\n'
@[export lean_io_eprint]
private def eprintAux (s : String) : IO Unit :=
eprint s
@[export lean_io_eprintln]
private def eprintlnAux (s : String) : IO Unit :=
eprintln s
def appDir : IO FilePath := do
let p ← appPath
let some p ← pure p.parent
| throw <| IO.userError s!"System.IO.appDir: unexpected filename '{p}'"
FS.realPath p
/-- Create given path and all missing parents as directories. -/
partial def FS.createDirAll (p : FilePath) : IO Unit := do
if ← p.isDir then
return ()
if let some parent := p.parent then
createDirAll parent
try
createDir p
catch
| e =>
if ← p.isDir then
pure () -- I guess someone else was faster
else
throw e
/--
Fully remove given directory by deleting all contained files and directories in an unspecified order.
Fails if any contained entry cannot be deleted or was newly created during execution. -/
partial def FS.removeDirAll (p : FilePath) : IO Unit := do
for ent in (← p.readDir) do
if (← ent.path.isDir : Bool) then
removeDirAll ent.path
else
removeFile ent.path
removeDir p
namespace Process
inductive Stdio where
| piped
| inherit
| null
def Stdio.toHandleType : Stdio → Type
| Stdio.piped => FS.Handle
| Stdio.inherit => Unit
| Stdio.null => Unit
structure StdioConfig where
/-- Configuration for the process' stdin handle. -/
stdin := Stdio.inherit
/-- Configuration for the process' stdout handle. -/
stdout := Stdio.inherit
/-- Configuration for the process' stderr handle. -/
stderr := Stdio.inherit
structure SpawnArgs extends StdioConfig where
/-- Command name. -/
cmd : String
/-- Arguments for the process -/
args : Array String := #[]
/-- Working directory for the process. Inherit from current process if `none`. -/
cwd : Option FilePath := none
/-- Add or remove environment variables for the process. -/
env : Array (String × Option String) := #[]
-- TODO(Sebastian): constructor must be private
structure Child (cfg : StdioConfig) where
stdin : cfg.stdin.toHandleType
stdout : cfg.stdout.toHandleType
stderr : cfg.stderr.toHandleType
@[extern "lean_io_process_spawn"] opaque spawn (args : SpawnArgs) : IO (Child args.toStdioConfig)
@[extern "lean_io_process_child_wait"] opaque Child.wait {cfg : @& StdioConfig} : @& Child cfg → IO UInt32
/--
Extract the `stdin` field from a `Child` object, allowing them to be freed independently.
This operation is necessary for closing the child process' stdin while still holding on to a process handle,
e.g. for `Child.wait`. A file handle is closed when all references to it are dropped, which without this
operation includes the `Child` object.
-/
@[extern "lean_io_process_child_take_stdin"] opaque Child.takeStdin {cfg : @& StdioConfig} : Child cfg →
IO (cfg.stdin.toHandleType × Child { cfg with stdin := Stdio.null })
structure Output where
exitCode : UInt32
stdout : String
stderr : String
/-- Run process to completion and capture output. -/
def output (args : SpawnArgs) : IO Output := do
let child ← spawn { args with stdout := Stdio.piped, stderr := Stdio.piped }
let stdout ← IO.asTask child.stdout.readToEnd Task.Priority.dedicated
let stderr ← child.stderr.readToEnd
let exitCode ← child.wait
let stdout ← IO.ofExcept stdout.get
pure { exitCode := exitCode, stdout := stdout, stderr := stderr }
/-- Run process to completion and return stdout on success. -/
def run (args : SpawnArgs) : IO String := do
let out ← output args
if out.exitCode != 0 then
throw <| IO.userError <| "process '" ++ args.cmd ++ "' exited with code " ++ toString out.exitCode
pure out.stdout
@[extern "lean_io_exit"] opaque exit : UInt8 → IO α
end Process
structure AccessRight where
read : Bool := false
write : Bool := false
execution : Bool := false
def AccessRight.flags (acc : AccessRight) : UInt32 :=
let r : UInt32 := if acc.read then 0x4 else 0
let w : UInt32 := if acc.write then 0x2 else 0
let x : UInt32 := if acc.execution then 0x1 else 0
r.lor <| w.lor x
structure FileRight where
user : AccessRight := {}
group : AccessRight := {}
other : AccessRight := {}
def FileRight.flags (acc : FileRight) : UInt32 :=
let u : UInt32 := acc.user.flags.shiftLeft 6
let g : UInt32 := acc.group.flags.shiftLeft 3
let o : UInt32 := acc.other.flags
u.lor <| g.lor o
@[extern "lean_chmod"] opaque Prim.setAccessRights (filename : @& FilePath) (mode : UInt32) : IO Unit
def setAccessRights (filename : FilePath) (mode : FileRight) : IO Unit :=
Prim.setAccessRights filename mode.flags
/-- References -/
abbrev Ref (α : Type) := ST.Ref IO.RealWorld α
instance : MonadLift (ST IO.RealWorld) BaseIO := ⟨id⟩
def mkRef (a : α) : BaseIO (IO.Ref α) :=
ST.mkRef a
namespace FS
namespace Stream
@[export lean_stream_of_handle]
def ofHandle (h : Handle) : Stream := {
flush := Handle.flush h,
read := Handle.read h,
write := Handle.write h,
getLine := Handle.getLine h,
putStr := Handle.putStr h,
}
structure Buffer where
data : ByteArray := ByteArray.empty
pos : Nat := 0
def ofBuffer (r : Ref Buffer) : Stream := {
flush := pure (),
read := fun n => r.modifyGet fun b =>
let data := b.data.extract b.pos (b.pos + n.toNat)
(data, { b with pos := b.pos + data.size }),
write := fun data => r.modify fun b =>
-- set `exact` to `false` so that repeatedly writing to the stream does not impose quadratic run time
{ b with data := data.copySlice 0 b.data b.pos data.size false, pos := b.pos + data.size },
getLine := r.modifyGet fun b =>
let pos := match b.data.findIdx? (start := b.pos) fun u => u == 0 || u = '\n'.toNat.toUInt8 with
-- include '\n', but not '\0'
| some pos => if b.data.get! pos == 0 then pos else pos + 1
| none => b.data.size
(String.fromUTF8Unchecked <| b.data.extract b.pos pos, { b with pos := pos }),
putStr := fun s => r.modify fun b =>
let data := s.toUTF8
{ b with data := data.copySlice 0 b.data b.pos data.size false, pos := b.pos + data.size },
}
end Stream
/-- Run action with `stdin` emptied and `stdout+stderr` captured into a `String`. -/
def withIsolatedStreams [Monad m] [MonadFinally m] [MonadLiftT BaseIO m] (x : m α)
(isolateStderr := true) : m (String × α) := do
let bIn ← mkRef { : Stream.Buffer }
let bOut ← mkRef { : Stream.Buffer }
let r ← withStdin (Stream.ofBuffer bIn) <|
withStdout (Stream.ofBuffer bOut) <|
(if isolateStderr then withStderr (Stream.ofBuffer bOut) else id) <|
x
let bOut ← liftM (m := BaseIO) bOut.get
let out := String.fromUTF8Unchecked bOut.data
pure (out, r)
end FS
end IO
universe u
namespace Lean
/-- Typeclass used for presenting the output of an `#eval` command. -/
class Eval (α : Type u) where
-- We default `hideUnit` to `true`, but set it to `false` in the direct call from `#eval`
-- so that `()` output is hidden in chained instances such as for some `IO Unit`.
-- We take `Unit → α` instead of `α` because ‵α` may contain effectful debugging primitives (e.g., `dbg_trace`)
eval : (Unit → α) → (hideUnit : Bool := true) → IO Unit
instance [ToString α] : Eval α where
eval a _ := IO.println (toString (a ()))
instance [Repr α] : Eval α where
eval a _ := IO.println (repr (a ()))
instance : Eval Unit where
eval u hideUnit := if hideUnit then pure () else IO.println (repr (u ()))
instance [Eval α] : Eval (IO α) where
eval x _ := do
let a ← x ()
Eval.eval fun _ => a
instance [Eval α] : Eval (BaseIO α) where
eval x _ := do
let a ← x ()
Eval.eval fun _ => a
def runEval [Eval α] (a : Unit → α) : IO (String × Except IO.Error Unit) :=
IO.FS.withIsolatedStreams (Eval.eval a false |>.toBaseIO)
end Lean
syntax "println! " (interpolatedStr(term) <|> term) : term
macro_rules
| `(println! $msg:interpolatedStr) => `((IO.println (s! $msg) : IO Unit))
| `(println! $msg:term) => `((IO.println $msg : IO Unit))
|
88959051e21b066f2413c7aa3c01f163fdfdedb1 | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/data/setoid/basic.lean | 645b9f3119f63ab2ddb2db3999df574104d62f14 | [
"Apache-2.0"
] | permissive | ayush1801/mathlib | 78949b9f789f488148142221606bf15c02b960d2 | ce164e28f262acbb3de6281b3b03660a9f744e3c | refs/heads/master | 1,692,886,907,941 | 1,635,270,866,000 | 1,635,270,866,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 18,494 | lean | /-
Copyright (c) 2019 Amelia Livingston. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Amelia Livingston, Bryan Gin-ge Chen
-/
import order.galois_connection
/-!
# Equivalence relations
This file defines the complete lattice of equivalence relations on a type, results about the
inductively defined equivalence closure of a binary relation, and the analogues of some isomorphism
theorems for quotients of arbitrary types.
## Implementation notes
The function `rel` and lemmas ending in ' make it easier to talk about different
equivalence relations on the same type.
The complete lattice instance for equivalence relations could have been defined by lifting
the Galois insertion of equivalence relations on α into binary relations on α, and then using
`complete_lattice.copy` to define a complete lattice instance with more appropriate
definitional equalities (a similar example is `filter.complete_lattice` in
`order/filter/basic.lean`). This does not save space, however, and is less clear.
Partitions are not defined as a separate structure here; users are encouraged to
reason about them using the existing `setoid` and its infrastructure.
## Tags
setoid, equivalence, iseqv, relation, equivalence relation
-/
variables {α : Type*} {β : Type*}
/-- A version of `setoid.r` that takes the equivalence relation as an explicit argument. -/
def setoid.rel (r : setoid α) : α → α → Prop := @setoid.r _ r
/-- A version of `quotient.eq'` compatible with `setoid.rel`, to make rewriting possible. -/
lemma quotient.eq_rel {r : setoid α} {x y} :
(quotient.mk' x : quotient r) = quotient.mk' y ↔ r.rel x y := quotient.eq
namespace setoid
@[ext] lemma ext' {r s : setoid α} (H : ∀ a b, r.rel a b ↔ s.rel a b) :
r = s := ext H
lemma ext_iff {r s : setoid α} : r = s ↔ ∀ a b, r.rel a b ↔ s.rel a b :=
⟨λ h a b, h ▸ iff.rfl, ext'⟩
/-- Two equivalence relations are equal iff their underlying binary operations are equal. -/
theorem eq_iff_rel_eq {r₁ r₂ : setoid α} : r₁ = r₂ ↔ r₁.rel = r₂.rel :=
⟨λ h, h ▸ rfl, λ h, setoid.ext' $ λ x y, h ▸ iff.rfl⟩
/-- Defining `≤` for equivalence relations. -/
instance : has_le (setoid α) := ⟨λ r s, ∀ ⦃x y⦄, r.rel x y → s.rel x y⟩
theorem le_def {r s : setoid α} : r ≤ s ↔ ∀ {x y}, r.rel x y → s.rel x y := iff.rfl
@[refl] lemma refl' (r : setoid α) (x) : r.rel x x := r.2.1 x
@[symm] lemma symm' (r : setoid α) : ∀ {x y}, r.rel x y → r.rel y x := λ _ _ h, r.2.2.1 h
@[trans] lemma trans' (r : setoid α) : ∀ {x y z}, r.rel x y → r.rel y z → r.rel x z :=
λ _ _ _ hx, r.2.2.2 hx
lemma comm' (s : setoid α) {x y} : s.rel x y ↔ s.rel y x :=
⟨s.symm', s.symm'⟩
/-- The kernel of a function is an equivalence relation. -/
def ker (f : α → β) : setoid α :=
⟨λ x y, f x = f y, ⟨λ _, rfl, λ _ _ h, h.symm, λ _ _ _ h, h.trans⟩⟩
/-- The kernel of the quotient map induced by an equivalence relation r equals r. -/
@[simp] lemma ker_mk_eq (r : setoid α) : ker (@quotient.mk _ r) = r :=
ext' $ λ x y, quotient.eq
lemma ker_apply_mk_out {f : α → β} (a : α) :
f (by haveI := setoid.ker f; exact ⟦a⟧.out) = f a :=
@quotient.mk_out _ (setoid.ker f) a
lemma ker_apply_mk_out' {f : α → β} (a : α) :
f ((quotient.mk' a : quotient $ setoid.ker f).out') = f a :=
@quotient.mk_out' _ (setoid.ker f) a
lemma ker_def {f : α → β} {x y : α} : (ker f).rel x y ↔ f x = f y := iff.rfl
/-- Given types `α`, `β`, the product of two equivalence relations `r` on `α` and `s` on `β`:
`(x₁, x₂), (y₁, y₂) ∈ α × β` are related by `r.prod s` iff `x₁` is related to `y₁`
by `r` and `x₂` is related to `y₂` by `s`. -/
protected def prod (r : setoid α) (s : setoid β) : setoid (α × β) :=
{ r := λ x y, r.rel x.1 y.1 ∧ s.rel x.2 y.2,
iseqv := ⟨λ x, ⟨r.refl' x.1, s.refl' x.2⟩, λ _ _ h, ⟨r.symm' h.1, s.symm' h.2⟩,
λ _ _ _ h1 h2, ⟨r.trans' h1.1 h2.1, s.trans' h1.2 h2.2⟩⟩ }
/-- The infimum of two equivalence relations. -/
instance : has_inf (setoid α) :=
⟨λ r s, ⟨λ x y, r.rel x y ∧ s.rel x y, ⟨λ x, ⟨r.refl' x, s.refl' x⟩,
λ _ _ h, ⟨r.symm' h.1, s.symm' h.2⟩,
λ _ _ _ h1 h2, ⟨r.trans' h1.1 h2.1, s.trans' h1.2 h2.2⟩⟩⟩⟩
/-- The infimum of 2 equivalence relations r and s is the same relation as the infimum
of the underlying binary operations. -/
lemma inf_def {r s : setoid α} : (r ⊓ s).rel = r.rel ⊓ s.rel := rfl
theorem inf_iff_and {r s : setoid α} {x y} :
(r ⊓ s).rel x y ↔ r.rel x y ∧ s.rel x y := iff.rfl
/-- The infimum of a set of equivalence relations. -/
instance : has_Inf (setoid α) :=
⟨λ S, ⟨λ x y, ∀ r ∈ S, rel r x y,
⟨λ x r hr, r.refl' x, λ _ _ h r hr, r.symm' $ h r hr,
λ _ _ _ h1 h2 r hr, r.trans' (h1 r hr) $ h2 r hr⟩⟩⟩
/-- The underlying binary operation of the infimum of a set of equivalence relations
is the infimum of the set's image under the map to the underlying binary operation. -/
theorem Inf_def {s : set (setoid α)} : (Inf s).rel = Inf (rel '' s) :=
by { ext, simp only [Inf_image, infi_apply, infi_Prop_eq], refl }
instance : partial_order (setoid α) :=
{ le := (≤),
lt := λ r s, r ≤ s ∧ ¬s ≤ r,
le_refl := λ _ _ _, id,
le_trans := λ _ _ _ hr hs _ _ h, hs $ hr h,
lt_iff_le_not_le := λ _ _, iff.rfl,
le_antisymm := λ r s h1 h2, setoid.ext' $ λ x y, ⟨λ h, h1 h, λ h, h2 h⟩ }
/-- The complete lattice of equivalence relations on a type, with bottom element `=`
and top element the trivial equivalence relation. -/
instance complete_lattice : complete_lattice (setoid α) :=
{ inf := has_inf.inf,
inf_le_left := λ _ _ _ _ h, h.1,
inf_le_right := λ _ _ _ _ h, h.2,
le_inf := λ _ _ _ h1 h2 _ _ h, ⟨h1 h, h2 h⟩,
top := ⟨λ _ _, true, ⟨λ _, trivial, λ _ _ h, h, λ _ _ _ h1 h2, h1⟩⟩,
le_top := λ _ _ _ _, trivial,
bot := ⟨(=), ⟨λ _, rfl, λ _ _ h, h.symm, λ _ _ _ h1 h2, h1.trans h2⟩⟩,
bot_le := λ r x y h, h ▸ r.2.1 x,
.. complete_lattice_of_Inf (setoid α) $ assume s,
⟨λ r hr x y h, h _ hr, λ r hr x y h r' hr', hr hr' h⟩ }
@[simp]
lemma top_def : (⊤ : setoid α).rel = ⊤ := rfl
@[simp]
lemma bot_def : (⊥ : setoid α).rel = (=) := rfl
lemma eq_top_iff {s : setoid α} : s = (⊤ : setoid α) ↔ ∀ x y : α, s.rel x y :=
by simp [eq_top_iff, setoid.le_def, setoid.top_def, pi.top_apply]
/-- The inductively defined equivalence closure of a binary relation r is the infimum
of the set of all equivalence relations containing r. -/
theorem eqv_gen_eq (r : α → α → Prop) :
eqv_gen.setoid r = Inf {s : setoid α | ∀ ⦃x y⦄, r x y → s.rel x y} :=
le_antisymm
(λ _ _ H, eqv_gen.rec (λ _ _ h _ hs, hs h) (refl' _)
(λ _ _ _, symm' _) (λ _ _ _ _ _, trans' _) H)
(Inf_le $ λ _ _ h, eqv_gen.rel _ _ h)
/-- The supremum of two equivalence relations r and s is the equivalence closure of the binary
relation `x is related to y by r or s`. -/
lemma sup_eq_eqv_gen (r s : setoid α) :
r ⊔ s = eqv_gen.setoid (λ x y, r.rel x y ∨ s.rel x y) :=
begin
rw eqv_gen_eq,
apply congr_arg Inf,
simp only [le_def, or_imp_distrib, ← forall_and_distrib]
end
/-- The supremum of 2 equivalence relations r and s is the equivalence closure of the
supremum of the underlying binary operations. -/
lemma sup_def {r s : setoid α} : r ⊔ s = eqv_gen.setoid (r.rel ⊔ s.rel) :=
by rw sup_eq_eqv_gen; refl
/-- The supremum of a set S of equivalence relations is the equivalence closure of the binary
relation `there exists r ∈ S relating x and y`. -/
lemma Sup_eq_eqv_gen (S : set (setoid α)) :
Sup S = eqv_gen.setoid (λ x y, ∃ r : setoid α, r ∈ S ∧ r.rel x y) :=
begin
rw eqv_gen_eq,
apply congr_arg Inf,
simp only [upper_bounds, le_def, and_imp, exists_imp_distrib],
ext,
exact ⟨λ H x y r hr, H hr, λ H r hr x y, H r hr⟩
end
/-- The supremum of a set of equivalence relations is the equivalence closure of the
supremum of the set's image under the map to the underlying binary operation. -/
lemma Sup_def {s : set (setoid α)} : Sup s = eqv_gen.setoid (Sup (rel '' s)) :=
begin
rw [Sup_eq_eqv_gen, Sup_image],
congr' with x y,
simp only [supr_apply, supr_Prop_eq, exists_prop]
end
/-- The equivalence closure of an equivalence relation r is r. -/
@[simp] lemma eqv_gen_of_setoid (r : setoid α) : eqv_gen.setoid r.r = r :=
le_antisymm (by rw eqv_gen_eq; exact Inf_le (λ _ _, id)) eqv_gen.rel
/-- Equivalence closure is idempotent. -/
@[simp] lemma eqv_gen_idem (r : α → α → Prop) :
eqv_gen.setoid (eqv_gen.setoid r).rel = eqv_gen.setoid r :=
eqv_gen_of_setoid _
/-- The equivalence closure of a binary relation r is contained in any equivalence
relation containing r. -/
theorem eqv_gen_le {r : α → α → Prop} {s : setoid α} (h : ∀ x y, r x y → s.rel x y) :
eqv_gen.setoid r ≤ s :=
by rw eqv_gen_eq; exact Inf_le h
/-- Equivalence closure of binary relations is monotone. -/
theorem eqv_gen_mono {r s : α → α → Prop} (h : ∀ x y, r x y → s x y) :
eqv_gen.setoid r ≤ eqv_gen.setoid s :=
eqv_gen_le $ λ _ _ hr, eqv_gen.rel _ _ $ h _ _ hr
/-- There is a Galois insertion of equivalence relations on α into binary relations
on α, with equivalence closure the lower adjoint. -/
def gi : @galois_insertion (α → α → Prop) (setoid α) _ _ eqv_gen.setoid rel :=
{ choice := λ r h, eqv_gen.setoid r,
gc := λ r s, ⟨λ H _ _ h, H $ eqv_gen.rel _ _ h, λ H, eqv_gen_of_setoid s ▸ eqv_gen_mono H⟩,
le_l_u := λ x, (eqv_gen_of_setoid x).symm ▸ le_refl x,
choice_eq := λ _ _, rfl }
open function
/-- A function from α to β is injective iff its kernel is the bottom element of the complete lattice
of equivalence relations on α. -/
theorem injective_iff_ker_bot (f : α → β) :
injective f ↔ ker f = ⊥ :=
(@eq_bot_iff (setoid α) _ (ker f)).symm
/-- The elements related to x ∈ α by the kernel of f are those in the preimage of f(x) under f. -/
lemma ker_iff_mem_preimage {f : α → β} {x y} : (ker f).rel x y ↔ x ∈ f ⁻¹' {f y} :=
iff.rfl
/-- Equivalence between functions `α → β` such that `r x y → f x = f y` and functions
`quotient r → β`. -/
def lift_equiv (r : setoid α) : {f : α → β // r ≤ ker f} ≃ (quotient r → β) :=
{ to_fun := λ f, quotient.lift (f : α → β) f.2,
inv_fun := λ f, ⟨f ∘ quotient.mk, λ x y h, by simp [ker_def, quotient.sound h]⟩,
left_inv := λ ⟨f, hf⟩, subtype.eq $ funext $ λ x, rfl,
right_inv := λ f, funext $ λ x, quotient.induction_on' x $ λ x, rfl }
/-- The uniqueness part of the universal property for quotients of an arbitrary type. -/
theorem lift_unique {r : setoid α} {f : α → β} (H : r ≤ ker f) (g : quotient r → β)
(Hg : f = g ∘ quotient.mk) : quotient.lift f H = g :=
begin
ext ⟨x⟩,
erw [quotient.lift_mk f H, Hg],
refl
end
/-- Given a map f from α to β, the natural map from the quotient of α by the kernel of f is
injective. -/
lemma ker_lift_injective (f : α → β) : injective (@quotient.lift _ _ (ker f) f (λ _ _ h, h)) :=
λ x y, quotient.induction_on₂' x y $ λ a b h, quotient.sound' h
/-- Given a map f from α to β, the kernel of f is the unique equivalence relation on α whose
induced map from the quotient of α to β is injective. -/
lemma ker_eq_lift_of_injective {r : setoid α} (f : α → β) (H : ∀ x y, r.rel x y → f x = f y)
(h : injective (quotient.lift f H)) : ker f = r :=
le_antisymm
(λ x y hk, quotient.exact $ h $ show quotient.lift f H ⟦x⟧ = quotient.lift f H ⟦y⟧, from hk)
H
variables (r : setoid α) (f : α → β)
/-- The first isomorphism theorem for sets: the quotient of α by the kernel of a function f
bijects with f's image. -/
noncomputable def quotient_ker_equiv_range :
quotient (ker f) ≃ set.range f :=
equiv.of_bijective (@quotient.lift _ (set.range f) (ker f)
(λ x, ⟨f x, set.mem_range_self x⟩) $ λ _ _ h, subtype.ext_val h)
⟨λ x y h, ker_lift_injective f $ by rcases x; rcases y; injections,
λ ⟨w, z, hz⟩, ⟨@quotient.mk _ (ker f) z, by rw quotient.lift_mk; exact subtype.ext_iff_val.2 hz⟩⟩
/-- If `f` has a computable right-inverse, then the quotient by its kernel is equivalent to its
domain. -/
@[simps]
def quotient_ker_equiv_of_right_inverse (g : β → α) (hf : function.right_inverse g f) :
quotient (ker f) ≃ β :=
{ to_fun := λ a, quotient.lift_on' a f $ λ _ _, id,
inv_fun := λ b, quotient.mk' (g b),
left_inv := λ a, quotient.induction_on' a $ λ a, quotient.sound' $ by exact hf (f a),
right_inv := hf }
/-- The quotient of α by the kernel of a surjective function f bijects with f's codomain.
If a specific right-inverse of `f` is known, `setoid.quotient_ker_equiv_of_right_inverse` can be
definitionally more useful. -/
noncomputable def quotient_ker_equiv_of_surjective (hf : surjective f) :
quotient (ker f) ≃ β :=
quotient_ker_equiv_of_right_inverse _ (function.surj_inv hf) (right_inverse_surj_inv hf)
variables {r f}
/-- Given a function `f : α → β` and equivalence relation `r` on `α`, the equivalence
closure of the relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are
related to the elements of `f⁻¹(y)` by `r`.' -/
def map (r : setoid α) (f : α → β) : setoid β :=
eqv_gen.setoid $ λ x y, ∃ a b, f a = x ∧ f b = y ∧ r.rel a b
/-- Given a surjective function f whose kernel is contained in an equivalence relation r, the
equivalence relation on f's codomain defined by x ≈ y ↔ the elements of f⁻¹(x) are related to
the elements of f⁻¹(y) by r. -/
def map_of_surjective (r) (f : α → β) (h : ker f ≤ r) (hf : surjective f) :
setoid β :=
⟨λ x y, ∃ a b, f a = x ∧ f b = y ∧ r.rel a b,
⟨λ x, let ⟨y, hy⟩ := hf x in ⟨y, y, hy, hy, r.refl' y⟩,
λ _ _ ⟨x, y, hx, hy, h⟩, ⟨y, x, hy, hx, r.symm' h⟩,
λ _ _ _ ⟨x, y, hx, hy, h₁⟩ ⟨y', z, hy', hz, h₂⟩,
⟨x, z, hx, hz, r.trans' h₁ $ r.trans' (h $ by rwa ←hy' at hy) h₂⟩⟩⟩
/-- A special case of the equivalence closure of an equivalence relation r equalling r. -/
lemma map_of_surjective_eq_map (h : ker f ≤ r) (hf : surjective f) :
map r f = map_of_surjective r f h hf :=
by rw ←eqv_gen_of_setoid (map_of_surjective r f h hf); refl
/-- Given a function `f : α → β`, an equivalence relation `r` on `β` induces an equivalence
relation on `α` defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `r`'. -/
def comap (f : α → β) (r : setoid β) : setoid α :=
⟨λ x y, r.rel (f x) (f y), ⟨λ _, r.refl' _, λ _ _ h, r.symm' h, λ _ _ _ h1, r.trans' h1⟩⟩
lemma comap_rel (f : α → β) (r : setoid β) (x y : α) : (comap f r).rel x y ↔ r.rel (f x) (f y) :=
iff.rfl
/-- Given a map `f : N → M` and an equivalence relation `r` on `β`, the equivalence relation
induced on `α` by `f` equals the kernel of `r`'s quotient map composed with `f`. -/
lemma comap_eq {f : α → β} {r : setoid β} : comap f r = ker (@quotient.mk _ r ∘ f) :=
ext $ λ x y, show _ ↔ ⟦_⟧ = ⟦_⟧, by rw quotient.eq; refl
/-- The second isomorphism theorem for sets. -/
noncomputable def comap_quotient_equiv (f : α → β) (r : setoid β) :
quotient (comap f r) ≃ set.range (@quotient.mk _ r ∘ f) :=
(quotient.congr_right $ ext_iff.1 comap_eq).trans $ quotient_ker_equiv_range $ quotient.mk ∘ f
variables (r f)
/-- The third isomorphism theorem for sets. -/
def quotient_quotient_equiv_quotient (s : setoid α) (h : r ≤ s) :
quotient (ker (quot.map_right h)) ≃ quotient s :=
{ to_fun := λ x, quotient.lift_on' x (λ w, quotient.lift_on' w (@quotient.mk _ s) $
λ x y H, quotient.sound $ h H) $ λ x y, quotient.induction_on₂' x y $ λ w z H,
show @quot.mk _ _ _ = @quot.mk _ _ _, from H,
inv_fun := λ x, quotient.lift_on' x
(λ w, @quotient.mk _ (ker $ quot.map_right h) $ @quotient.mk _ r w) $
λ x y H, quotient.sound' $ show @quot.mk _ _ _ = @quot.mk _ _ _, from quotient.sound H,
left_inv := λ x, quotient.induction_on' x $ λ y, quotient.induction_on' y $
λ w, by show ⟦_⟧ = _; refl,
right_inv := λ x, quotient.induction_on' x $ λ y, by show ⟦_⟧ = _; refl }
variables {r f}
open quotient
/-- Given an equivalence relation `r` on `α`, the order-preserving bijection between the set of
equivalence relations containing `r` and the equivalence relations on the quotient of `α` by `r`. -/
def correspondence (r : setoid α) : {s // r ≤ s} ≃o setoid (quotient r) :=
{ to_fun := λ s, map_of_surjective s.1 quotient.mk ((ker_mk_eq r).symm ▸ s.2) exists_rep,
inv_fun := λ s, ⟨comap quotient.mk' s, λ x y h, by rw [comap_rel, eq_rel.2 h]⟩,
left_inv := λ s, subtype.ext_iff_val.2 $ ext' $ λ _ _,
⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in
s.1.trans' (s.1.symm' $ s.2 $ eq_rel.1 hx) $ s.1.trans' H $ s.2 $ eq_rel.1 hy,
λ h, ⟨_, _, rfl, rfl, h⟩⟩,
right_inv := λ s, let Hm : ker quotient.mk' ≤ comap quotient.mk' s :=
λ x y h, by rw [comap_rel, (@eq_rel _ r x y).2 ((ker_mk_eq r) ▸ h)] in
ext' $ λ x y, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in hx ▸ hy ▸ H,
quotient.induction_on₂ x y $ λ w z h, ⟨w, z, rfl, rfl, h⟩⟩,
map_rel_iff' := λ s t, ⟨λ h x y hs, let ⟨a, b, hx, hy, ht⟩ := h ⟨x, y, rfl, rfl, hs⟩ in
t.1.trans' (t.1.symm' $ t.2 $ eq_rel.1 hx) $ t.1.trans' ht $ t.2 $ eq_rel.1 hy,
λ h x y hs, let ⟨a, b, hx, hy, Hs⟩ := hs in ⟨a, b, hx, hy, h Hs⟩⟩ }
end setoid
@[simp]
lemma quotient.subsingleton_iff {s : setoid α} :
subsingleton (quotient s) ↔ s = ⊤ :=
begin
simp only [subsingleton_iff, eq_top_iff, setoid.le_def, setoid.top_def,
pi.top_apply, forall_const],
refine (surjective_quotient_mk _).forall.trans (forall_congr $ λ a, _),
refine (surjective_quotient_mk _).forall.trans (forall_congr $ λ b, _),
exact quotient.eq',
end
lemma quot.subsingleton_iff (r : α → α → Prop) : subsingleton (quot r) ↔ eqv_gen r = ⊤ :=
begin
simp only [subsingleton_iff, _root_.eq_top_iff, pi.le_def, pi.top_apply, forall_const],
refine (surjective_quot_mk _).forall.trans (forall_congr $ λ a, _),
refine (surjective_quot_mk _).forall.trans (forall_congr $ λ b, _),
rw quot.eq,
simp only [forall_const, le_Prop_eq],
end
|
4b234373c3168c0dc619eb45a9cd375b521eee40 | 12dabd587ce2621d9a4eff9f16e354d02e206c8e | /world03/level05.lean | 90e61058046d103f6d4afad296bca18c0298d9c5 | [] | no_license | abdelq/natural-number-game | a1b5b8f1d52625a7addcefc97c966d3f06a48263 | bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2 | refs/heads/master | 1,668,606,478,691 | 1,594,175,058,000 | 1,594,175,058,000 | 278,673,209 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 163 | lean | lemma mul_assoc (a b c : mynat) : (a * b) * c = a * (b * c) :=
begin
induction c with h hd,
repeat {rw mul_zero},
rw mul_succ,
rw mul_succ,
rwa [hd, mul_add],
end
|
df4fad570f6ed7712e8d7c96a95f2f9eb596cab4 | f20db13587f4dd28a4b1fbd31953afd491691fa0 | /tests/lean/run/check_constants.lean | 21317a80fee12250df62b1f14d934ba703294795 | [
"Apache-2.0"
] | permissive | AHartNtkn/lean | 9a971edfc6857c63edcbf96bea6841b9a84cf916 | 0d83a74b26541421fc1aa33044c35b03759710ed | refs/heads/master | 1,620,592,591,236 | 1,516,749,881,000 | 1,516,749,881,000 | 118,697,288 | 1 | 0 | null | 1,516,759,470,000 | 1,516,759,470,000 | null | UTF-8 | Lean | false | false | 15,462 | lean | -- DO NOT EDIT, automatically generated file, generator scripts/gen_constants_cpp.py
import smt system.io
open tactic
meta def script_check_id (n : name) : tactic unit :=
do env ← get_env, (env^.get n >> return ()) <|> (guard $ env^.is_namespace n) <|> (attribute.get_instances n >> return ()) <|> fail ("identifier '" ++ to_string n ++ "' is not a constant, namespace nor attribute")
run_cmd script_check_id `abs
run_cmd script_check_id `absurd
run_cmd script_check_id `acc.cases_on
run_cmd script_check_id `acc.rec
run_cmd script_check_id `add_comm_group
run_cmd script_check_id `add_comm_semigroup
run_cmd script_check_id `add_group
run_cmd script_check_id `add_monoid
run_cmd script_check_id `and
run_cmd script_check_id `and.elim_left
run_cmd script_check_id `and.elim_right
run_cmd script_check_id `and.intro
run_cmd script_check_id `and.rec
run_cmd script_check_id `and.cases_on
run_cmd script_check_id `auto_param
run_cmd script_check_id `bit0
run_cmd script_check_id `bit1
run_cmd script_check_id `bin_tree.empty
run_cmd script_check_id `bin_tree.leaf
run_cmd script_check_id `bin_tree.node
run_cmd script_check_id `bool
run_cmd script_check_id `bool.ff
run_cmd script_check_id `bool.tt
run_cmd script_check_id `combinator.K
run_cmd script_check_id `cast
run_cmd script_check_id `cast_heq
run_cmd script_check_id `char
run_cmd script_check_id `char.mk
run_cmd script_check_id `char.ne_of_vne
run_cmd script_check_id `char.of_nat
run_cmd script_check_id `char.of_nat_ne_of_ne
run_cmd script_check_id `is_valid_char_range_1
run_cmd script_check_id `is_valid_char_range_2
run_cmd script_check_id `classical.prop_decidable
run_cmd script_check_id `classical.type_decidable_eq
run_cmd script_check_id `coe
run_cmd script_check_id `coe_fn
run_cmd script_check_id `coe_sort
run_cmd script_check_id `coe_to_lift
run_cmd script_check_id `congr
run_cmd script_check_id `congr_arg
run_cmd script_check_id `congr_fun
run_cmd script_check_id `decidable
run_cmd script_check_id `decidable.to_bool
run_cmd script_check_id `distrib
run_cmd script_check_id `dite
run_cmd script_check_id `empty
run_cmd script_check_id `Exists
run_cmd script_check_id `eq
run_cmd script_check_id `eq.cases_on
run_cmd script_check_id `eq.drec
run_cmd script_check_id `eq.mp
run_cmd script_check_id `eq.mpr
run_cmd script_check_id `eq.rec
run_cmd script_check_id `eq.refl
run_cmd script_check_id `eq.subst
run_cmd script_check_id `eq.symm
run_cmd script_check_id `eq.trans
run_cmd script_check_id `eq_of_heq
run_cmd script_check_id `eq_rec_heq
run_cmd script_check_id `eq_true_intro
run_cmd script_check_id `eq_false_intro
run_cmd script_check_id `eq_self_iff_true
run_cmd script_check_id `expr
run_cmd script_check_id `expr.subst
run_cmd script_check_id `format
run_cmd script_check_id `false
run_cmd script_check_id `false_of_true_iff_false
run_cmd script_check_id `false_of_true_eq_false
run_cmd script_check_id `true_eq_false_of_false
run_cmd script_check_id `false.rec
run_cmd script_check_id `field
run_cmd script_check_id `fin.mk
run_cmd script_check_id `fin.ne_of_vne
run_cmd script_check_id `forall_congr
run_cmd script_check_id `forall_congr_eq
run_cmd script_check_id `forall_not_of_not_exists
run_cmd script_check_id `funext
run_cmd script_check_id `ge
run_cmd script_check_id `gt
run_cmd script_check_id `has_add
run_cmd script_check_id `has_add.add
run_cmd script_check_id `andthen
run_cmd script_check_id `has_bind.and_then
run_cmd script_check_id `has_bind.bind
run_cmd script_check_id `has_bind.seq
run_cmd script_check_id `has_div
run_cmd script_check_id `has_div.div
run_cmd script_check_id `has_emptyc.emptyc
run_cmd script_check_id `has_mod.mod
run_cmd script_check_id `has_mul
run_cmd script_check_id `has_mul.mul
run_cmd script_check_id `has_insert.insert
run_cmd script_check_id `has_inv
run_cmd script_check_id `has_inv.inv
run_cmd script_check_id `has_le
run_cmd script_check_id `has_le.le
run_cmd script_check_id `has_lt
run_cmd script_check_id `has_lt.lt
run_cmd script_check_id `has_neg
run_cmd script_check_id `has_neg.neg
run_cmd script_check_id `has_one
run_cmd script_check_id `has_one.one
run_cmd script_check_id `has_orelse.orelse
run_cmd script_check_id `has_sep.sep
run_cmd script_check_id `has_sizeof
run_cmd script_check_id `has_sizeof.mk
run_cmd script_check_id `has_sub
run_cmd script_check_id `has_sub.sub
run_cmd script_check_id `has_to_format
run_cmd script_check_id `has_repr
run_cmd script_check_id `has_well_founded
run_cmd script_check_id `has_well_founded.r
run_cmd script_check_id `has_well_founded.wf
run_cmd script_check_id `has_zero
run_cmd script_check_id `has_zero.zero
run_cmd script_check_id `has_coe_t
run_cmd script_check_id `heq
run_cmd script_check_id `heq.refl
run_cmd script_check_id `heq.symm
run_cmd script_check_id `heq.trans
run_cmd script_check_id `heq_of_eq
run_cmd script_check_id `hole_command
run_cmd script_check_id `id
run_cmd script_check_id `id_rhs
run_cmd script_check_id `id_delta
run_cmd script_check_id `if_neg
run_cmd script_check_id `if_pos
run_cmd script_check_id `iff
run_cmd script_check_id `iff_false_intro
run_cmd script_check_id `iff.intro
run_cmd script_check_id `iff.mp
run_cmd script_check_id `iff.mpr
run_cmd script_check_id `iff.refl
run_cmd script_check_id `iff.symm
run_cmd script_check_id `iff.trans
run_cmd script_check_id `iff_true_intro
run_cmd script_check_id `imp_congr
run_cmd script_check_id `imp_congr_eq
run_cmd script_check_id `imp_congr_ctx
run_cmd script_check_id `imp_congr_ctx_eq
run_cmd script_check_id `implies
run_cmd script_check_id `implies_of_if_neg
run_cmd script_check_id `implies_of_if_pos
run_cmd script_check_id `int
run_cmd script_check_id `int.has_add
run_cmd script_check_id `int.has_mul
run_cmd script_check_id `int.has_sub
run_cmd script_check_id `int.has_div
run_cmd script_check_id `int.has_le
run_cmd script_check_id `int.has_lt
run_cmd script_check_id `int.has_neg
run_cmd script_check_id `int.has_mod
run_cmd script_check_id `int.bit0_nonneg
run_cmd script_check_id `int.bit1_nonneg
run_cmd script_check_id `int.one_nonneg
run_cmd script_check_id `int.zero_nonneg
run_cmd script_check_id `int.bit0_pos
run_cmd script_check_id `int.bit1_pos
run_cmd script_check_id `int.one_pos
run_cmd script_check_id `int.nat_abs_zero
run_cmd script_check_id `int.nat_abs_one
run_cmd script_check_id `int.nat_abs_bit0_step
run_cmd script_check_id `int.nat_abs_bit1_nonneg_step
run_cmd script_check_id `int.ne_of_nat_ne_nonneg_case
run_cmd script_check_id `int.ne_neg_of_ne
run_cmd script_check_id `int.neg_ne_of_pos
run_cmd script_check_id `int.ne_neg_of_pos
run_cmd script_check_id `int.neg_ne_zero_of_ne
run_cmd script_check_id `int.zero_ne_neg_of_ne
run_cmd script_check_id `int.decidable_linear_ordered_comm_group
run_cmd script_check_id `interactive.param_desc
run_cmd script_check_id `interactive.parse
run_cmd script_check_id `io_core
run_cmd script_check_id `monad_io_impl
run_cmd script_check_id `monad_io_terminal_impl
run_cmd script_check_id `monad_io_file_system_impl
run_cmd script_check_id `monad_io_environment_impl
run_cmd script_check_id `monad_io_process_impl
run_cmd script_check_id `io
run_cmd script_check_id `is_associative
run_cmd script_check_id `is_associative.assoc
run_cmd script_check_id `is_commutative
run_cmd script_check_id `is_commutative.comm
run_cmd script_check_id `ite
run_cmd script_check_id `lean.parser
run_cmd script_check_id `lean.parser.pexpr
run_cmd script_check_id `lean.parser.tk
run_cmd script_check_id `left_distrib
run_cmd script_check_id `left_comm
run_cmd script_check_id `le_refl
run_cmd script_check_id `linear_ordered_ring
run_cmd script_check_id `linear_ordered_semiring
run_cmd script_check_id `list
run_cmd script_check_id `list.nil
run_cmd script_check_id `list.cons
run_cmd script_check_id `match_failed
run_cmd script_check_id `monad
run_cmd script_check_id `monad_fail
run_cmd script_check_id `monoid
run_cmd script_check_id `mul_one
run_cmd script_check_id `mul_zero
run_cmd script_check_id `mul_zero_class
run_cmd script_check_id `name.anonymous
run_cmd script_check_id `name.mk_numeral
run_cmd script_check_id `name.mk_string
run_cmd script_check_id `nat
run_cmd script_check_id `nat.succ
run_cmd script_check_id `nat.zero
run_cmd script_check_id `nat.has_zero
run_cmd script_check_id `nat.has_one
run_cmd script_check_id `nat.has_add
run_cmd script_check_id `nat.add
run_cmd script_check_id `nat.cases_on
run_cmd script_check_id `nat.bit0_ne
run_cmd script_check_id `nat.bit0_ne_bit1
run_cmd script_check_id `nat.bit0_ne_zero
run_cmd script_check_id `nat.bit0_ne_one
run_cmd script_check_id `nat.bit1_ne
run_cmd script_check_id `nat.bit1_ne_bit0
run_cmd script_check_id `nat.bit1_ne_zero
run_cmd script_check_id `nat.bit1_ne_one
run_cmd script_check_id `nat.zero_ne_one
run_cmd script_check_id `nat.zero_ne_bit0
run_cmd script_check_id `nat.zero_ne_bit1
run_cmd script_check_id `nat.one_ne_zero
run_cmd script_check_id `nat.one_ne_bit0
run_cmd script_check_id `nat.one_ne_bit1
run_cmd script_check_id `nat.bit0_lt
run_cmd script_check_id `nat.bit1_lt
run_cmd script_check_id `nat.bit0_lt_bit1
run_cmd script_check_id `nat.bit1_lt_bit0
run_cmd script_check_id `nat.zero_lt_one
run_cmd script_check_id `nat.zero_lt_bit1
run_cmd script_check_id `nat.zero_lt_bit0
run_cmd script_check_id `nat.one_lt_bit0
run_cmd script_check_id `nat.one_lt_bit1
run_cmd script_check_id `nat.le_of_lt
run_cmd script_check_id `nat.le_refl
run_cmd script_check_id `ne
run_cmd script_check_id `neq_of_not_iff
run_cmd script_check_id `norm_num.add1
run_cmd script_check_id `norm_num.add1_bit0
run_cmd script_check_id `norm_num.add1_bit1_helper
run_cmd script_check_id `norm_num.add1_one
run_cmd script_check_id `norm_num.add1_zero
run_cmd script_check_id `norm_num.add_div_helper
run_cmd script_check_id `norm_num.bin_add_zero
run_cmd script_check_id `norm_num.bin_zero_add
run_cmd script_check_id `norm_num.bit0_add_bit0_helper
run_cmd script_check_id `norm_num.bit0_add_bit1_helper
run_cmd script_check_id `norm_num.bit0_add_one
run_cmd script_check_id `norm_num.bit1_add_bit0_helper
run_cmd script_check_id `norm_num.bit1_add_bit1_helper
run_cmd script_check_id `norm_num.bit1_add_one_helper
run_cmd script_check_id `norm_num.div_add_helper
run_cmd script_check_id `norm_num.div_eq_div_helper
run_cmd script_check_id `norm_num.div_helper
run_cmd script_check_id `norm_num.div_mul_helper
run_cmd script_check_id `norm_num.mk_cong
run_cmd script_check_id `norm_num.mul_bit0_helper
run_cmd script_check_id `norm_num.mul_bit1_helper
run_cmd script_check_id `norm_num.mul_div_helper
run_cmd script_check_id `norm_num.neg_add_neg_helper
run_cmd script_check_id `norm_num.neg_add_pos_helper1
run_cmd script_check_id `norm_num.neg_add_pos_helper2
run_cmd script_check_id `norm_num.neg_mul_neg_helper
run_cmd script_check_id `norm_num.neg_mul_pos_helper
run_cmd script_check_id `norm_num.neg_neg_helper
run_cmd script_check_id `norm_num.neg_zero_helper
run_cmd script_check_id `norm_num.nonneg_bit0_helper
run_cmd script_check_id `norm_num.nonneg_bit1_helper
run_cmd script_check_id `norm_num.nonzero_of_div_helper
run_cmd script_check_id `norm_num.nonzero_of_neg_helper
run_cmd script_check_id `norm_num.nonzero_of_pos_helper
run_cmd script_check_id `norm_num.one_add_bit0
run_cmd script_check_id `norm_num.one_add_bit1_helper
run_cmd script_check_id `norm_num.one_add_one
run_cmd script_check_id `norm_num.pos_add_neg_helper
run_cmd script_check_id `norm_num.pos_bit0_helper
run_cmd script_check_id `norm_num.pos_bit1_helper
run_cmd script_check_id `norm_num.pos_mul_neg_helper
run_cmd script_check_id `norm_num.sub_nat_zero_helper
run_cmd script_check_id `norm_num.sub_nat_pos_helper
run_cmd script_check_id `norm_num.subst_into_div
run_cmd script_check_id `norm_num.subst_into_prod
run_cmd script_check_id `norm_num.subst_into_subtr
run_cmd script_check_id `norm_num.subst_into_sum
run_cmd script_check_id `not
run_cmd script_check_id `not_of_iff_false
run_cmd script_check_id `not_of_eq_false
run_cmd script_check_id `of_eq_true
run_cmd script_check_id `of_iff_true
run_cmd script_check_id `opt_param
run_cmd script_check_id `or
run_cmd script_check_id `out_param
run_cmd script_check_id `punit
run_cmd script_check_id `punit.star
run_cmd script_check_id `prod.mk
run_cmd script_check_id `pprod
run_cmd script_check_id `pprod.mk
run_cmd script_check_id `pprod.fst
run_cmd script_check_id `pprod.snd
run_cmd script_check_id `propext
run_cmd script_check_id `to_pexpr
run_cmd script_check_id `quot.mk
run_cmd script_check_id `quot.lift
run_cmd script_check_id `real
run_cmd script_check_id `real.of_int
run_cmd script_check_id `real.to_int
run_cmd script_check_id `real.is_int
run_cmd script_check_id `real.has_neg
run_cmd script_check_id `real.has_div
run_cmd script_check_id `real.has_add
run_cmd script_check_id `real.has_mul
run_cmd script_check_id `real.has_sub
run_cmd script_check_id `real.has_lt
run_cmd script_check_id `real.has_le
run_cmd script_check_id `reflected
run_cmd script_check_id `reflected.subst
run_cmd script_check_id `repr
run_cmd script_check_id `rfl
run_cmd script_check_id `right_distrib
run_cmd script_check_id `ring
run_cmd script_check_id `scope_trace
run_cmd script_check_id `set_of
run_cmd script_check_id `semiring
run_cmd script_check_id `psigma
run_cmd script_check_id `psigma.cases_on
run_cmd script_check_id `psigma.mk
run_cmd script_check_id `psigma.fst
run_cmd script_check_id `psigma.snd
run_cmd script_check_id `singleton
run_cmd script_check_id `sizeof
run_cmd script_check_id `smt.array
run_cmd script_check_id `smt.select
run_cmd script_check_id `smt.store
run_cmd script_check_id `smt.prove
run_cmd script_check_id `string
run_cmd script_check_id `string.empty
run_cmd script_check_id `string.str
run_cmd script_check_id `string.empty_ne_str
run_cmd script_check_id `string.str_ne_empty
run_cmd script_check_id `string.str_ne_str_left
run_cmd script_check_id `string.str_ne_str_right
run_cmd script_check_id `subsingleton
run_cmd script_check_id `subsingleton.elim
run_cmd script_check_id `subsingleton.helim
run_cmd script_check_id `subtype
run_cmd script_check_id `subtype.mk
run_cmd script_check_id `subtype.val
run_cmd script_check_id `subtype.rec
run_cmd script_check_id `psum
run_cmd script_check_id `psum.cases_on
run_cmd script_check_id `psum.inl
run_cmd script_check_id `psum.inr
run_cmd script_check_id `tactic
run_cmd script_check_id `tactic.try
run_cmd script_check_id `tactic.triv
run_cmd script_check_id `tactic.mk_inj_eq
run_cmd script_check_id `thunk
run_cmd script_check_id `to_fmt
run_cmd script_check_id `trans_rel_left
run_cmd script_check_id `trans_rel_right
run_cmd script_check_id `true
run_cmd script_check_id `true.intro
run_cmd script_check_id `unification_hint
run_cmd script_check_id `unification_hint.mk
run_cmd script_check_id `unit
run_cmd script_check_id `unit.cases_on
run_cmd script_check_id `unit.star
run_cmd script_check_id `unsafe_monad_from_pure_bind
run_cmd script_check_id `user_attribute
run_cmd script_check_id `user_attribute.parse_reflect
run_cmd script_check_id `vm_monitor
run_cmd script_check_id `partial_order
run_cmd script_check_id `well_founded.fix
run_cmd script_check_id `well_founded.fix_eq
run_cmd script_check_id `well_founded_tactics
run_cmd script_check_id `well_founded_tactics.default
run_cmd script_check_id `well_founded_tactics.rel_tac
run_cmd script_check_id `well_founded_tactics.dec_tac
run_cmd script_check_id `xor
run_cmd script_check_id `zero_le_one
run_cmd script_check_id `zero_lt_one
run_cmd script_check_id `zero_mul
|
1f825052f8a66b2dc3efc97db9f56dc579d37797 | 037dba89703a79cd4a4aec5e959818147f97635d | /src/2022/logic/sheet6.lean | a99aab7e1aae48283420d2259d09687a602bb713 | [] | 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 | 1,626 | lean | /-
Copyright (c) 2022 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
/-!
# Logic in Lean, example sheet 6 : "or" (∨`)
We learn about how to manipulate `P ∨ Q` in Lean.
## Tactics
You'll need to know about the tactics from the previous sheets,
and also the following tactics
* `left` and `right`
* `cases` (new functionality)
### The `left` and `right` tactics.
If your goal is `⊢ P ∨ Q` then `left,` will change it to `⊢ P`
and `right,` will change it to `⊢ Q`.
### The `cases` tactic again
If we have `h : P ∨ Q` as a hypothesis then `cases h with hP hQ`
will turn your goal into two goals, one with `hP : P` as a hypothesis
and the other with `hQ : Q`.
-/
-- Throughout this sheet, `P`, `Q`, `R` and `S` will denote propositions.
variables (P Q R S : Prop)
example : P → P ∨ Q :=
begin
sorry
end
example : Q → P ∨ Q :=
begin
sorry,
end
example : P ∨ Q → (P → R) → (Q → R) → R :=
begin
sorry
end
-- symmetry of `or`
example : P ∨ Q → Q ∨ P :=
begin
sorry
end
-- associativity of `or`
example : (P ∨ Q) ∨ R ↔ P ∨ (Q ∨ R) :=
begin
sorry,
end
example : (P → R) → (Q → S) → P ∨ Q → R ∨ S :=
begin
sorry,
end
example : (P → Q) → P ∨ R → Q ∨ R :=
begin
sorry,
end
example : (P ↔ R) → (Q ↔ S) → (P ∨ Q ↔ R ∨ S) :=
begin
sorry,
end
-- de Morgan's laws
example : ¬ (P ∨ Q) ↔ ¬ P ∧ ¬ Q :=
begin
sorry
end
example : ¬ (P ∧ Q) ↔ ¬ P ∨ ¬ Q :=
begin
sorry
end
|
f5fa640a2161e6bae5bec0d64b8343b7189bd4ad | 206422fb9edabf63def0ed2aa3f489150fb09ccb | /src/algebra/lie/classical.lean | 7d3504e82260c6f4012830a020a964e2cfa3b102 | [
"Apache-2.0"
] | permissive | hamdysalah1/mathlib | b915f86b2503feeae268de369f1b16932321f097 | 95454452f6b3569bf967d35aab8d852b1ddf8017 | refs/heads/master | 1,677,154,116,545 | 1,611,797,994,000 | 1,611,797,994,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,510 | lean | /-
Copyright (c) 2020 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import algebra.invertible
import algebra.lie.skew_adjoint
import linear_algebra.matrix
/-!
# Classical Lie algebras
This file is the place to find definitions and basic properties of the classical Lie algebras:
* Aₗ = sl(l+1)
* Bₗ ≃ so(l+1, l) ≃ so(2l+1)
* Cₗ = sp(l)
* Dₗ ≃ so(l, l) ≃ so(2l)
## Main definitions
* `lie_algebra.special_linear.sl`
* `lie_algebra.symplectic.sp`
* `lie_algebra.orthogonal.so`
* `lie_algebra.orthogonal.so'`
* `lie_algebra.orthogonal.so_indefinite_equiv`
* `lie_algebra.orthogonal.type_D`
* `lie_algebra.orthogonal.type_B`
* `lie_algebra.orthogonal.type_D_equiv_so'`
* `lie_algebra.orthogonal.type_B_equiv_so'`
## Implementation notes
### Matrices or endomorphisms
Given a finite type and a commutative ring, the corresponding square matrices are equivalent to the
endomorphisms of the corresponding finite-rank free module as Lie algebras, see `lie_equiv_matrix'`.
We can thus define the classical Lie algebras as Lie subalgebras either of matrices or of
endomorphisms. We have opted for the former. At the time of writing (August 2020) it is unclear
which approach should be preferred so the choice should be assumed to be somewhat arbitrary.
### Diagonal quadratic form or diagonal Cartan subalgebra
For the algebras of type `B` and `D`, there are two natural definitions. For example since the
the `2l × 2l` matrix:
$$
J = \left[\begin{array}{cc}
0_l & 1_l\\\\
1_l & 0_l
\end{array}\right]
$$
defines a symmetric bilinear form equivalent to that defined by the identity matrix `I`, we can
define the algebras of type `D` to be the Lie subalgebra of skew-adjoint matrices either for `J` or
for `I`. Both definitions have their advantages (in particular the `J`-skew-adjoint matrices define
a Lie algebra for which the diagonal matrices form a Cartan subalgebra) and so we provide both.
We thus also provide equivalences `type_D_equiv_so'`, `so_indefinite_equiv` which show the two
definitions are equivalent. Similarly for the algebras of type `B`.
## Tags
classical lie algebra, special linear, symplectic, orthogonal
-/
universes u₁ u₂
namespace lie_algebra
open_locale matrix
variables (n p q l : Type*) (R : Type u₂)
variables [fintype n] [fintype l] [fintype p] [fintype q]
variables [decidable_eq n] [decidable_eq p] [decidable_eq q] [decidable_eq l]
variables [comm_ring R]
@[simp] lemma matrix_trace_commutator_zero (X Y : matrix n n R) : matrix.trace n R R ⁅X, Y⁆ = 0 :=
begin
-- TODO: if we use matrix.mul here, we get a timeout
change matrix.trace n R R (X * Y - Y * X) = 0,
erw [linear_map.map_sub, matrix.trace_mul_comm, sub_self]
end
namespace special_linear
/-- The special linear Lie algebra: square matrices of trace zero. -/
def sl : lie_subalgebra R (matrix n n R) :=
{ lie_mem' := λ X Y _ _, linear_map.mem_ker.2 $ matrix_trace_commutator_zero _ _ _ _,
..linear_map.ker (matrix.trace n R R) }
lemma sl_bracket (A B : sl n R) : ⁅A, B⁆.val = A.val ⬝ B.val - B.val ⬝ A.val := rfl
section elementary_basis
variables {n} (i j : n)
/-- It is useful to define these matrices for explicit calculations in sl n R. -/
abbreviation E : matrix n n R := λ i' j', if i = i' ∧ j = j' then 1 else 0
@[simp] lemma E_apply_one : E R i j i j = 1 := if_pos (and.intro rfl rfl)
@[simp] lemma E_apply_zero (i' j' : n) (h : ¬(i = i' ∧ j = j')) : E R i j i' j' = 0 := if_neg h
@[simp] lemma E_diag_zero (h : j ≠ i) : matrix.diag n R R (E R i j) = 0 :=
begin
ext k, rw matrix.diag_apply,
suffices : ¬(i = k ∧ j = k), by exact if_neg this,
rintros ⟨e₁, e₂⟩, apply h, subst e₁, exact e₂,
end
lemma E_trace_zero (h : j ≠ i) : matrix.trace n R R (E R i j) = 0 := by simp [h]
/-- When j ≠ i, the elementary matrices are elements of sl n R, in fact they are part of a natural
basis of sl n R. -/
def Eb (h : j ≠ i) : sl n R :=
⟨E R i j, by { change E R i j ∈ linear_map.ker (matrix.trace n R R), simp [E_trace_zero R i j h], }⟩
@[simp] lemma Eb_val (h : j ≠ i) : (Eb R i j h).val = E R i j := rfl
end elementary_basis
lemma sl_non_abelian [nontrivial R] (h : 1 < fintype.card n) : ¬is_lie_abelian ↥(sl n R) :=
begin
rcases fintype.exists_pair_of_one_lt_card h with ⟨j, i, hij⟩,
let A := Eb R i j hij,
let B := Eb R j i hij.symm,
intros c,
have c' : A.val ⬝ B.val = B.val ⬝ A.val, by { rw [← sub_eq_zero, ← sl_bracket, c.trivial], refl },
have : (1 : R) = 0 := by simpa [matrix.mul_apply, hij] using (congr_fun (congr_fun c' i) i),
exact one_ne_zero this,
end
end special_linear
namespace symplectic
/-- The matrix defining the canonical skew-symmetric bilinear form. -/
def J : matrix (l ⊕ l) (l ⊕ l) R := matrix.from_blocks 0 (-1) 1 0
/-- The symplectic Lie algebra: skew-adjoint matrices with respect to the canonical skew-symmetric
bilinear form. -/
def sp : lie_subalgebra R (matrix (l ⊕ l) (l ⊕ l) R) :=
skew_adjoint_matrices_lie_subalgebra (J l R)
end symplectic
namespace orthogonal
/-- The definite orthogonal Lie subalgebra: skew-adjoint matrices with respect to the symmetric
bilinear form defined by the identity matrix. -/
def so : lie_subalgebra R (matrix n n R) :=
skew_adjoint_matrices_lie_subalgebra (1 : matrix n n R)
@[simp] lemma mem_so (A : matrix n n R) : A ∈ so n R ↔ Aᵀ = -A :=
begin
erw mem_skew_adjoint_matrices_submodule,
simp only [matrix.is_skew_adjoint, matrix.is_adjoint_pair, matrix.mul_one, matrix.one_mul],
end
/-- The indefinite diagonal matrix with `p` 1s and `q` -1s. -/
def indefinite_diagonal : matrix (p ⊕ q) (p ⊕ q) R :=
matrix.diagonal $ sum.elim (λ _, 1) (λ _, -1)
/-- The indefinite orthogonal Lie subalgebra: skew-adjoint matrices with respect to the symmetric
bilinear form defined by the indefinite diagonal matrix. -/
def so' : lie_subalgebra R (matrix (p ⊕ q) (p ⊕ q) R) :=
skew_adjoint_matrices_lie_subalgebra $ indefinite_diagonal p q R
/-- A matrix for transforming the indefinite diagonal bilinear form into the definite one, provided
the parameter `i` is a square root of -1. -/
def Pso (i : R) : matrix (p ⊕ q) (p ⊕ q) R :=
matrix.diagonal $ sum.elim (λ _, 1) (λ _, i)
lemma Pso_inv {i : R} (hi : i*i = -1) : (Pso p q R i) * (Pso p q R (-i)) = 1 :=
begin
ext x y, rcases x; rcases y,
{ -- x y : p
by_cases h : x = y; simp [Pso, indefinite_diagonal, h], },
{ -- x : p, y : q
simp [Pso, indefinite_diagonal], },
{ -- x : q, y : p
simp [Pso, indefinite_diagonal], },
{ -- x y : q
by_cases h : x = y; simp [Pso, indefinite_diagonal, h, hi], },
end
lemma is_unit_Pso {i : R} (hi : i*i = -1) : is_unit (Pso p q R i) :=
⟨{ val := Pso p q R i,
inv := Pso p q R (-i),
val_inv := Pso_inv p q R hi,
inv_val := by { apply matrix.nonsing_inv_left_right, exact Pso_inv p q R hi, }, },
rfl⟩
lemma indefinite_diagonal_transform {i : R} (hi : i*i = -1) :
(Pso p q R i)ᵀ ⬝ (indefinite_diagonal p q R) ⬝ (Pso p q R i) = 1 :=
begin
ext x y, rcases x; rcases y,
{ -- x y : p
by_cases h : x = y; simp [Pso, indefinite_diagonal, h], },
{ -- x : p, y : q
simp [Pso, indefinite_diagonal], },
{ -- x : q, y : p
simp [Pso, indefinite_diagonal], },
{ -- x y : q
by_cases h : x = y; simp [Pso, indefinite_diagonal, h, hi], },
end
/-- An equivalence between the indefinite and definite orthogonal Lie algebras, over a ring
containing a square root of -1. -/
noncomputable def so_indefinite_equiv {i : R} (hi : i*i = -1) : so' p q R ≃ₗ⁅R⁆ so (p ⊕ q) R :=
begin
apply (skew_adjoint_matrices_lie_subalgebra_equiv
(indefinite_diagonal p q R) (Pso p q R i) (is_unit_Pso p q R hi)).trans,
apply lie_algebra.equiv.of_eq,
ext A, rw indefinite_diagonal_transform p q R hi, refl,
end
lemma so_indefinite_equiv_apply {i : R} (hi : i*i = -1) (A : so' p q R) :
(so_indefinite_equiv p q R hi A : matrix (p ⊕ q) (p ⊕ q) R) =
(Pso p q R i)⁻¹ ⬝ (A : matrix (p ⊕ q) (p ⊕ q) R) ⬝ (Pso p q R i) :=
by erw [lie_algebra.equiv.trans_apply, lie_algebra.equiv.of_eq_apply,
skew_adjoint_matrices_lie_subalgebra_equiv_apply]
/-- A matrix defining a canonical even-rank symmetric bilinear form.
It looks like this as a `2l x 2l` matrix of `l x l` blocks:
[ 0 1 ]
[ 1 0 ]
-/
def JD : matrix (l ⊕ l) (l ⊕ l) R := matrix.from_blocks 0 1 1 0
/-- The classical Lie algebra of type D as a Lie subalgebra of matrices associated to the matrix
`JD`. -/
def type_D := skew_adjoint_matrices_lie_subalgebra (JD l R)
/-- A matrix transforming the bilinear form defined by the matrix `JD` into a split-signature
diagonal matrix.
It looks like this as a `2l x 2l` matrix of `l x l` blocks:
[ 1 -1 ]
[ 1 1 ]
-/
def PD : matrix (l ⊕ l) (l ⊕ l) R := matrix.from_blocks 1 (-1) 1 1
/-- The split-signature diagonal matrix. -/
def S := indefinite_diagonal l l R
lemma S_as_blocks : S l R = matrix.from_blocks 1 0 0 (-1) :=
begin
rw [← matrix.diagonal_one, matrix.diagonal_neg, matrix.from_blocks_diagonal],
refl,
end
lemma JD_transform : (PD l R)ᵀ ⬝ (JD l R) ⬝ (PD l R) = (2 : R) • (S l R) :=
begin
have h : (PD l R)ᵀ ⬝ (JD l R) = matrix.from_blocks 1 1 1 (-1) := by
{ simp [PD, JD, matrix.from_blocks_transpose, matrix.from_blocks_multiply], },
erw [h, S_as_blocks, matrix.from_blocks_multiply, matrix.from_blocks_smul],
congr; simp [two_smul],
end
lemma PD_inv [invertible (2 : R)] : (PD l R) * (⅟(2 : R) • (PD l R)ᵀ) = 1 :=
begin
have h : ⅟(2 : R) • (1 : matrix l l R) + ⅟(2 : R) • 1 = 1 := by
rw [← smul_add, ← (two_smul R _), smul_smul, inv_of_mul_self, one_smul],
erw [matrix.from_blocks_transpose, matrix.from_blocks_smul, matrix.mul_eq_mul,
matrix.from_blocks_multiply],
simp [h],
end
lemma is_unit_PD [invertible (2 : R)] : is_unit (PD l R) :=
⟨{ val := PD l R,
inv := ⅟(2 : R) • (PD l R)ᵀ,
val_inv := PD_inv l R,
inv_val := by { apply matrix.nonsing_inv_left_right, exact PD_inv l R, }, },
rfl⟩
/-- An equivalence between two possible definitions of the classical Lie algebra of type D. -/
noncomputable def type_D_equiv_so' [invertible (2 : R)] :
type_D l R ≃ₗ⁅R⁆ so' l l R :=
begin
apply (skew_adjoint_matrices_lie_subalgebra_equiv (JD l R) (PD l R) (is_unit_PD l R)).trans,
apply lie_algebra.equiv.of_eq,
ext A,
rw [JD_transform, ← unit_of_invertible_val (2 : R), lie_subalgebra.mem_coe,
mem_skew_adjoint_matrices_lie_subalgebra_unit_smul],
refl,
end
/-- A matrix defining a canonical odd-rank symmetric bilinear form.
It looks like this as a `(2l+1) x (2l+1)` matrix of blocks:
[ 2 0 0 ]
[ 0 0 1 ]
[ 0 1 0 ]
where sizes of the blocks are:
[`1 x 1` `1 x l` `1 x l`]
[`l x 1` `l x l` `l x l`]
[`l x 1` `l x l` `l x l`]
-/
def JB := matrix.from_blocks ((2 : R) • 1 : matrix unit unit R) 0 0 (JD l R)
/-- The classical Lie algebra of type B as a Lie subalgebra of matrices associated to the matrix
`JB`. -/
def type_B := skew_adjoint_matrices_lie_subalgebra (JB l R)
/-- A matrix transforming the bilinear form defined by the matrix `JB` into an
almost-split-signature diagonal matrix.
It looks like this as a `(2l+1) x (2l+1)` matrix of blocks:
[ 1 0 0 ]
[ 0 1 -1 ]
[ 0 1 1 ]
where sizes of the blocks are:
[`1 x 1` `1 x l` `1 x l`]
[`l x 1` `l x l` `l x l`]
[`l x 1` `l x l` `l x l`]
-/
def PB := matrix.from_blocks (1 : matrix unit unit R) 0 0 (PD l R)
lemma PB_inv [invertible (2 : R)] : (PB l R) * (matrix.from_blocks 1 0 0 (PD l R)⁻¹) = 1 :=
begin
simp [PB, matrix.from_blocks_multiply, (PD l R).mul_nonsing_inv, is_unit_PD,
← (PD l R).is_unit_iff_is_unit_det]
end
lemma is_unit_PB [invertible (2 : R)] : is_unit (PB l R) :=
⟨{ val := PB l R,
inv := matrix.from_blocks 1 0 0 (PD l R)⁻¹,
val_inv := PB_inv l R,
inv_val := by { apply matrix.nonsing_inv_left_right, exact PB_inv l R, }, },
rfl⟩
lemma JB_transform : (PB l R)ᵀ ⬝ (JB l R) ⬝ (PB l R) = (2 : R) • matrix.from_blocks 1 0 0 (S l R) :=
by simp [PB, JB, JD_transform, matrix.from_blocks_transpose, matrix.from_blocks_multiply,
matrix.from_blocks_smul]
lemma indefinite_diagonal_assoc :
indefinite_diagonal (unit ⊕ l) l R =
matrix.reindex_lie_equiv (equiv.sum_assoc unit l l).symm
(matrix.from_blocks 1 0 0 (indefinite_diagonal l l R)) :=
begin
ext i j,
rcases i with ⟨⟨i₁ | i₂⟩ | i₃⟩;
rcases j with ⟨⟨j₁ | j₂⟩ | j₃⟩;
simp [indefinite_diagonal, matrix.diagonal],
end
/-- An equivalence between two possible definitions of the classical Lie algebra of type B. -/
noncomputable def type_B_equiv_so' [invertible (2 : R)] :
type_B l R ≃ₗ⁅R⁆ so' (unit ⊕ l) l R :=
begin
apply (skew_adjoint_matrices_lie_subalgebra_equiv (JB l R) (PB l R) (is_unit_PB l R)).trans,
symmetry,
apply (skew_adjoint_matrices_lie_subalgebra_equiv_transpose
(indefinite_diagonal (unit ⊕ l) l R)
(matrix.reindex_alg_equiv (equiv.sum_assoc punit l l)) (matrix.reindex_transpose _ _)).trans,
apply lie_algebra.equiv.of_eq,
ext A,
rw [JB_transform, ← unit_of_invertible_val (2 : R), lie_subalgebra.mem_coe,
lie_subalgebra.mem_coe, mem_skew_adjoint_matrices_lie_subalgebra_unit_smul],
simpa [indefinite_diagonal_assoc],
end
end orthogonal
end lie_algebra
|
12d624d04525abbd328765702cfa2d81dcac36e2 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/ring_theory/subsemiring/basic.lean | e693a75715df0ab47bd873c2b9dac76d0ab4e6f6 | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 44,234 | lean | /-
Copyright (c) 2020 Yury Kudryashov All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import algebra.module.basic
import algebra.ring.equiv
import algebra.ring.prod
import data.set.finite
import group_theory.submonoid.centralizer
import group_theory.submonoid.membership
/-!
# Bundled subsemirings
We define bundled subsemirings and some standard constructions: `complete_lattice` structure,
`subtype` and `inclusion` ring homomorphisms, subsemiring `map`, `comap` and range (`srange`) of
a `ring_hom` etc.
-/
open_locale big_operators
universes u v w
section add_submonoid_with_one_class
/-- `add_submonoid_with_one_class S R` says `S` is a type of subsets `s ≤ R` that contain `0`, `1`,
and are closed under `(+)` -/
class add_submonoid_with_one_class (S : Type*) (R : out_param $ Type*)
[add_monoid_with_one R] [set_like S R]
extends add_submonoid_class S R, one_mem_class S R
variables {S R : Type*} [add_monoid_with_one R] [set_like S R] (s : S)
lemma nat_cast_mem [add_submonoid_with_one_class S R] (n : ℕ) : (n : R) ∈ s :=
by induction n; simp [zero_mem, add_mem, one_mem, *]
@[priority 74]
instance add_submonoid_with_one_class.to_add_monoid_with_one [add_submonoid_with_one_class S R] :
add_monoid_with_one s :=
{ one := ⟨_, one_mem s⟩,
nat_cast := λ n, ⟨n, nat_cast_mem s n⟩,
nat_cast_zero := subtype.ext nat.cast_zero,
nat_cast_succ := λ n, subtype.ext (nat.cast_succ _),
.. add_submonoid_class.to_add_monoid s }
end add_submonoid_with_one_class
variables {R : Type u} {S : Type v} {T : Type w} [non_assoc_semiring R] (M : submonoid R)
section subsemiring_class
/-- `subsemiring_class S R` states that `S` is a type of subsets `s ⊆ R` that
are both a multiplicative and an additive submonoid. -/
class subsemiring_class (S : Type*) (R : out_param $ Type u) [non_assoc_semiring R] [set_like S R]
extends submonoid_class S R :=
(add_mem : ∀ {s : S} {a b : R}, a ∈ s → b ∈ s → a + b ∈ s)
(zero_mem : ∀ (s : S), (0 : R) ∈ s)
@[priority 100] -- See note [lower instance priority]
instance subsemiring_class.add_submonoid_with_one_class (S : Type*) (R : out_param $ Type u)
[non_assoc_semiring R] [set_like S R] [h : subsemiring_class S R] :
add_submonoid_with_one_class S R :=
{ .. h }
variables [set_like S R] [hSR : subsemiring_class S R] (s : S)
include hSR
lemma coe_nat_mem (n : ℕ) : (n : R) ∈ s :=
by { rw ← nsmul_one, exact nsmul_mem (one_mem _) _ }
namespace subsemiring_class
/-- A subsemiring of a `non_assoc_semiring` inherits a `non_assoc_semiring` structure -/
@[priority 75] -- Prefer subclasses of `non_assoc_semiring` over subclasses of `subsemiring_class`.
instance to_non_assoc_semiring : non_assoc_semiring s :=
subtype.coe_injective.non_assoc_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl)
(λ _, rfl)
instance nontrivial [nontrivial R] : nontrivial s :=
nontrivial_of_ne 0 1 $ λ H, zero_ne_one (congr_arg subtype.val H)
instance no_zero_divisors [no_zero_divisors R] : no_zero_divisors s :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ x y h,
or.cases_on (eq_zero_or_eq_zero_of_mul_eq_zero $ subtype.ext_iff.mp h)
(λ h, or.inl $ subtype.eq h) (λ h, or.inr $ subtype.eq h) }
/-- The natural ring hom from a subsemiring of semiring `R` to `R`. -/
def subtype : s →+* R :=
{ to_fun := coe, .. submonoid_class.subtype s, .. add_submonoid_class.subtype s }
@[simp] theorem coe_subtype : (subtype s : s → R) = coe := rfl
omit hSR
/-- A subsemiring of a `semiring` is a `semiring`. -/
@[priority 75] -- Prefer subclasses of `semiring` over subclasses of `subsemiring_class`.
instance to_semiring {R} [semiring R] [set_like S R] [subsemiring_class S R] : semiring s :=
subtype.coe_injective.semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl)
(λ _, rfl)
@[simp, norm_cast] lemma coe_pow {R} [semiring R] [set_like S R] [subsemiring_class S R]
(x : s) (n : ℕ) :
((x^n : s) : R) = (x^n : R) :=
begin
induction n with n ih,
{ simp, },
{ simp [pow_succ, ih], },
end
/-- A subsemiring of a `comm_semiring` is a `comm_semiring`. -/
instance to_comm_semiring {R} [comm_semiring R] [set_like S R] [subsemiring_class S R] :
comm_semiring s :=
subtype.coe_injective.comm_semiring coe
rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl)
/-- A subsemiring of an `ordered_semiring` is an `ordered_semiring`. -/
instance to_ordered_semiring {R} [ordered_semiring R] [set_like S R] [subsemiring_class S R] :
ordered_semiring s :=
subtype.coe_injective.ordered_semiring coe
rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl)
/-- A subsemiring of an `ordered_comm_semiring` is an `ordered_comm_semiring`. -/
instance to_ordered_comm_semiring {R} [ordered_comm_semiring R] [set_like S R]
[subsemiring_class S R] : ordered_comm_semiring s :=
subtype.coe_injective.ordered_comm_semiring coe
rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl)
/-- A subsemiring of a `linear_ordered_semiring` is a `linear_ordered_semiring`. -/
instance to_linear_ordered_semiring {R} [linear_ordered_semiring R] [set_like S R]
[subsemiring_class S R] : linear_ordered_semiring s :=
subtype.coe_injective.linear_ordered_semiring coe
rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl)
/-! Note: currently, there is no `linear_ordered_comm_semiring`. -/
end subsemiring_class
end subsemiring_class
variables [non_assoc_semiring S] [non_assoc_semiring T]
set_option old_structure_cmd true
/-- A subsemiring of a semiring `R` is a subset `s` that is both a multiplicative and an additive
submonoid. -/
structure subsemiring (R : Type u) [non_assoc_semiring R] extends submonoid R, add_submonoid R
/-- Reinterpret a `subsemiring` as a `submonoid`. -/
add_decl_doc subsemiring.to_submonoid
/-- Reinterpret a `subsemiring` as an `add_submonoid`. -/
add_decl_doc subsemiring.to_add_submonoid
namespace subsemiring
instance : set_like (subsemiring R) R :=
{ coe := subsemiring.carrier,
coe_injective' := λ p q h, by cases p; cases q; congr' }
instance : subsemiring_class (subsemiring R) R :=
{ zero_mem := zero_mem',
add_mem := add_mem',
one_mem := one_mem',
mul_mem := mul_mem' }
@[simp]
lemma mem_carrier {s : subsemiring R} {x : R} : x ∈ s.carrier ↔ x ∈ s := iff.rfl
/-- Two subsemirings are equal if they have the same elements. -/
@[ext] theorem ext {S T : subsemiring R} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h
/-- Copy of a subsemiring with a new `carrier` equal to the old one. Useful to fix definitional
equalities.-/
protected def copy (S : subsemiring R) (s : set R) (hs : s = ↑S) : subsemiring R :=
{ carrier := s,
..S.to_add_submonoid.copy s hs,
..S.to_submonoid.copy s hs }
@[simp] lemma coe_copy (S : subsemiring R) (s : set R) (hs : s = ↑S) :
(S.copy s hs : set R) = s := rfl
lemma copy_eq (S : subsemiring R) (s : set R) (hs : s = ↑S) : S.copy s hs = S :=
set_like.coe_injective hs
lemma to_submonoid_injective : function.injective (to_submonoid : subsemiring R → submonoid R)
| r s h := ext (set_like.ext_iff.mp h : _)
@[mono] lemma to_submonoid_strict_mono : strict_mono (to_submonoid : subsemiring R → submonoid R) :=
λ _ _, id
@[mono] lemma to_submonoid_mono : monotone (to_submonoid : subsemiring R → submonoid R) :=
to_submonoid_strict_mono.monotone
lemma to_add_submonoid_injective :
function.injective (to_add_submonoid : subsemiring R → add_submonoid R)
| r s h := ext (set_like.ext_iff.mp h : _)
@[mono] lemma to_add_submonoid_strict_mono :
strict_mono (to_add_submonoid : subsemiring R → add_submonoid R) := λ _ _, id
@[mono]
lemma to_add_submonoid_mono : monotone (to_add_submonoid : subsemiring R → add_submonoid R) :=
to_add_submonoid_strict_mono.monotone
/-- Construct a `subsemiring R` from a set `s`, a submonoid `sm`, and an additive
submonoid `sa` such that `x ∈ s ↔ x ∈ sm ↔ x ∈ sa`. -/
protected def mk' (s : set R) (sm : submonoid R) (hm : ↑sm = s)
(sa : add_submonoid R) (ha : ↑sa = s) :
subsemiring R :=
{ carrier := s,
zero_mem' := ha ▸ sa.zero_mem,
one_mem' := hm ▸ sm.one_mem,
add_mem' := λ x y, by simpa only [← ha] using sa.add_mem,
mul_mem' := λ x y, by simpa only [← hm] using sm.mul_mem }
@[simp] lemma coe_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_submonoid R} (ha : ↑sa = s) :
(subsemiring.mk' s sm hm sa ha : set R) = s := rfl
@[simp] lemma mem_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_submonoid R} (ha : ↑sa = s) {x : R} :
x ∈ subsemiring.mk' s sm hm sa ha ↔ x ∈ s :=
iff.rfl
@[simp] lemma mk'_to_submonoid {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_submonoid R} (ha : ↑sa = s) :
(subsemiring.mk' s sm hm sa ha).to_submonoid = sm :=
set_like.coe_injective hm.symm
@[simp] lemma mk'_to_add_submonoid {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_submonoid R} (ha : ↑sa =s) :
(subsemiring.mk' s sm hm sa ha).to_add_submonoid = sa :=
set_like.coe_injective ha.symm
end subsemiring
namespace subsemiring
variables (s : subsemiring R)
/-- A subsemiring contains the semiring's 1. -/
protected theorem one_mem : (1 : R) ∈ s := one_mem s
/-- A subsemiring contains the semiring's 0. -/
protected theorem zero_mem : (0 : R) ∈ s := zero_mem s
/-- A subsemiring is closed under multiplication. -/
protected theorem mul_mem {x y : R} : x ∈ s → y ∈ s → x * y ∈ s := mul_mem
/-- A subsemiring is closed under addition. -/
protected theorem add_mem {x y : R} : x ∈ s → y ∈ s → x + y ∈ s := add_mem
/-- Product of a list of elements in a `subsemiring` is in the `subsemiring`. -/
lemma list_prod_mem {R : Type*} [semiring R] (s : subsemiring R) {l : list R} :
(∀x ∈ l, x ∈ s) → l.prod ∈ s :=
list_prod_mem
/-- Sum of a list of elements in a `subsemiring` is in the `subsemiring`. -/
protected lemma list_sum_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.sum ∈ s := list_sum_mem
/-- Product of a multiset of elements in a `subsemiring` of a `comm_semiring`
is in the `subsemiring`. -/
protected lemma multiset_prod_mem {R} [comm_semiring R] (s : subsemiring R) (m : multiset R) :
(∀a ∈ m, a ∈ s) → m.prod ∈ s :=
multiset_prod_mem m
/-- Sum of a multiset of elements in a `subsemiring` of a `semiring` is
in the `add_subsemiring`. -/
protected lemma multiset_sum_mem (m : multiset R) :
(∀a ∈ m, a ∈ s) → m.sum ∈ s :=
multiset_sum_mem m
/-- Product of elements of a subsemiring of a `comm_semiring` indexed by a `finset` is in the
subsemiring. -/
protected lemma prod_mem {R : Type*} [comm_semiring R] (s : subsemiring R)
{ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) :
∏ i in t, f i ∈ s :=
prod_mem h
/-- Sum of elements in an `subsemiring` of an `semiring` indexed by a `finset`
is in the `add_subsemiring`. -/
protected lemma sum_mem (s : subsemiring R)
{ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) :
∑ i in t, f i ∈ s :=
sum_mem h
/-- A subsemiring of a `non_assoc_semiring` inherits a `non_assoc_semiring` structure -/
instance to_non_assoc_semiring : non_assoc_semiring s :=
{ mul_zero := λ x, subtype.eq $ mul_zero x,
zero_mul := λ x, subtype.eq $ zero_mul x,
right_distrib := λ x y z, subtype.eq $ right_distrib x y z,
left_distrib := λ x y z, subtype.eq $ left_distrib x y z,
nat_cast := λ n, ⟨n, coe_nat_mem s n⟩,
nat_cast_zero := by simp [nat.cast]; refl,
nat_cast_succ := λ _, by simp [nat.cast]; refl,
.. s.to_submonoid.to_mul_one_class, .. s.to_add_submonoid.to_add_comm_monoid }
@[simp, norm_cast] lemma coe_one : ((1 : s) : R) = (1 : R) := rfl
@[simp, norm_cast] lemma coe_zero : ((0 : s) : R) = (0 : R) := rfl
@[simp, norm_cast] lemma coe_add (x y : s) : ((x + y : s) : R) = (x + y : R) := rfl
@[simp, norm_cast] lemma coe_mul (x y : s) : ((x * y : s) : R) = (x * y : R) := rfl
instance nontrivial [nontrivial R] : nontrivial s :=
nontrivial_of_ne 0 1 $ λ H, zero_ne_one (congr_arg subtype.val H)
protected lemma pow_mem {R : Type*} [semiring R] (s : subsemiring R) {x : R} (hx : x ∈ s) (n : ℕ) :
x^n ∈ s := pow_mem hx n
instance no_zero_divisors [no_zero_divisors R] : no_zero_divisors s :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ x y h,
or.cases_on (eq_zero_or_eq_zero_of_mul_eq_zero $ subtype.ext_iff.mp h)
(λ h, or.inl $ subtype.eq h) (λ h, or.inr $ subtype.eq h) }
/-- A subsemiring of a `semiring` is a `semiring`. -/
instance to_semiring {R} [semiring R] (s : subsemiring R) : semiring s :=
{ ..s.to_non_assoc_semiring, ..s.to_submonoid.to_monoid }
@[simp, norm_cast] lemma coe_pow {R} [semiring R] (s : subsemiring R) (x : s) (n : ℕ) :
((x^n : s) : R) = (x^n : R) :=
begin
induction n with n ih,
{ simp, },
{ simp [pow_succ, ih], },
end
/-- A subsemiring of a `comm_semiring` is a `comm_semiring`. -/
instance to_comm_semiring {R} [comm_semiring R] (s : subsemiring R) : comm_semiring s :=
{ mul_comm := λ _ _, subtype.eq $ mul_comm _ _, ..s.to_semiring}
/-- The natural ring hom from a subsemiring of semiring `R` to `R`. -/
def subtype : s →+* R :=
{ to_fun := coe, .. s.to_submonoid.subtype, .. s.to_add_submonoid.subtype }
@[simp] theorem coe_subtype : ⇑s.subtype = coe := rfl
/-- A subsemiring of an `ordered_semiring` is an `ordered_semiring`. -/
instance to_ordered_semiring {R} [ordered_semiring R] (s : subsemiring R) : ordered_semiring s :=
subtype.coe_injective.ordered_semiring coe
rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl)
/-- A subsemiring of an `ordered_comm_semiring` is an `ordered_comm_semiring`. -/
instance to_ordered_comm_semiring {R} [ordered_comm_semiring R] (s : subsemiring R) :
ordered_comm_semiring s :=
subtype.coe_injective.ordered_comm_semiring coe
rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl)
/-- A subsemiring of a `linear_ordered_semiring` is a `linear_ordered_semiring`. -/
instance to_linear_ordered_semiring {R} [linear_ordered_semiring R] (s : subsemiring R) :
linear_ordered_semiring s :=
subtype.coe_injective.linear_ordered_semiring coe
rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl)
/-! Note: currently, there is no `linear_ordered_comm_semiring`. -/
protected lemma nsmul_mem {x : R} (hx : x ∈ s) (n : ℕ) :
n • x ∈ s := nsmul_mem hx n
@[simp] lemma mem_to_submonoid {s : subsemiring R} {x : R} : x ∈ s.to_submonoid ↔ x ∈ s := iff.rfl
@[simp] lemma coe_to_submonoid (s : subsemiring R) : (s.to_submonoid : set R) = s := rfl
@[simp] lemma mem_to_add_submonoid {s : subsemiring R} {x : R} :
x ∈ s.to_add_submonoid ↔ x ∈ s := iff.rfl
@[simp] lemma coe_to_add_submonoid (s : subsemiring R) : (s.to_add_submonoid : set R) = s := rfl
/-- The subsemiring `R` of the semiring `R`. -/
instance : has_top (subsemiring R) :=
⟨{ .. (⊤ : submonoid R), .. (⊤ : add_submonoid R) }⟩
@[simp] lemma mem_top (x : R) : x ∈ (⊤ : subsemiring R) := set.mem_univ x
@[simp] lemma coe_top : ((⊤ : subsemiring R) : set R) = set.univ := rfl
/-- The preimage of a subsemiring along a ring homomorphism is a subsemiring. -/
def comap (f : R →+* S) (s : subsemiring S) : subsemiring R :=
{ carrier := f ⁻¹' s,
.. s.to_submonoid.comap (f : R →* S), .. s.to_add_submonoid.comap (f : R →+ S) }
@[simp] lemma coe_comap (s : subsemiring S) (f : R →+* S) : (s.comap f : set R) = f ⁻¹' s := rfl
@[simp]
lemma mem_comap {s : subsemiring S} {f : R →+* S} {x : R} : x ∈ s.comap f ↔ f x ∈ s := iff.rfl
lemma comap_comap (s : subsemiring T) (g : S →+* T) (f : R →+* S) :
(s.comap g).comap f = s.comap (g.comp f) :=
rfl
/-- The image of a subsemiring along a ring homomorphism is a subsemiring. -/
def map (f : R →+* S) (s : subsemiring R) : subsemiring S :=
{ carrier := f '' s,
.. s.to_submonoid.map (f : R →* S), .. s.to_add_submonoid.map (f : R →+ S) }
@[simp] lemma coe_map (f : R →+* S) (s : subsemiring R) : (s.map f : set S) = f '' s := rfl
@[simp] lemma mem_map {f : R →+* S} {s : subsemiring R} {y : S} :
y ∈ s.map f ↔ ∃ x ∈ s, f x = y :=
set.mem_image_iff_bex
@[simp] lemma map_id : s.map (ring_hom.id R) = s :=
set_like.coe_injective $ set.image_id _
lemma map_map (g : S →+* T) (f : R →+* S) : (s.map f).map g = s.map (g.comp f) :=
set_like.coe_injective $ set.image_image _ _ _
lemma map_le_iff_le_comap {f : R →+* S} {s : subsemiring R} {t : subsemiring S} :
s.map f ≤ t ↔ s ≤ t.comap f :=
set.image_subset_iff
lemma gc_map_comap (f : R →+* S) : galois_connection (map f) (comap f) :=
λ S T, map_le_iff_le_comap
/-- A subsemiring is isomorphic to its image under an injective function -/
noncomputable def equiv_map_of_injective
(f : R →+* S) (hf : function.injective f) : s ≃+* s.map f :=
{ map_mul' := λ _ _, subtype.ext (f.map_mul _ _),
map_add' := λ _ _, subtype.ext (f.map_add _ _),
..equiv.set.image f s hf }
@[simp] lemma coe_equiv_map_of_injective_apply
(f : R →+* S) (hf : function.injective f) (x : s) :
(equiv_map_of_injective s f hf x : S) = f x := rfl
end subsemiring
namespace ring_hom
variables (g : S →+* T) (f : R →+* S)
/-- The range of a ring homomorphism is a subsemiring. See Note [range copy pattern]. -/
def srange : subsemiring S :=
((⊤ : subsemiring R).map f).copy (set.range f) set.image_univ.symm
@[simp] lemma coe_srange : (f.srange : set S) = set.range f := rfl
@[simp] lemma mem_srange {f : R →+* S} {y : S} : y ∈ f.srange ↔ ∃ x, f x = y :=
iff.rfl
lemma srange_eq_map (f : R →+* S) : f.srange = (⊤ : subsemiring R).map f :=
by { ext, simp }
lemma mem_srange_self (f : R →+* S) (x : R) : f x ∈ f.srange :=
mem_srange.mpr ⟨x, rfl⟩
lemma map_srange : f.srange.map g = (g.comp f).srange :=
by simpa only [srange_eq_map] using (⊤ : subsemiring R).map_map g f
/-- The range of a morphism of semirings is a fintype, if the domain is a fintype.
Note: this instance can form a diamond with `subtype.fintype` in the
presence of `fintype S`.-/
instance fintype_srange [fintype R] [decidable_eq S] (f : R →+* S) : fintype (srange f) :=
set.fintype_range f
end ring_hom
namespace subsemiring
instance : has_bot (subsemiring R) := ⟨(nat.cast_ring_hom R).srange⟩
instance : inhabited (subsemiring R) := ⟨⊥⟩
lemma coe_bot : ((⊥ : subsemiring R) : set R) = set.range (coe : ℕ → R) :=
(nat.cast_ring_hom R).coe_srange
lemma mem_bot {x : R} : x ∈ (⊥ : subsemiring R) ↔ ∃ n : ℕ, ↑n=x := ring_hom.mem_srange
/-- The inf of two subsemirings is their intersection. -/
instance : has_inf (subsemiring R) :=
⟨λ s t,
{ carrier := s ∩ t,
.. s.to_submonoid ⊓ t.to_submonoid,
.. s.to_add_submonoid ⊓ t.to_add_submonoid }⟩
@[simp] lemma coe_inf (p p' : subsemiring R) : ((p ⊓ p' : subsemiring R) : set R) = p ∩ p' := rfl
@[simp] lemma mem_inf {p p' : subsemiring R} {x : R} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl
instance : has_Inf (subsemiring R) :=
⟨λ s, subsemiring.mk' (⋂ t ∈ s, ↑t) (⨅ t ∈ s, subsemiring.to_submonoid t) (by simp)
(⨅ t ∈ s, subsemiring.to_add_submonoid t) (by simp)⟩
@[simp, norm_cast] lemma coe_Inf (S : set (subsemiring R)) :
((Inf S : subsemiring R) : set R) = ⋂ s ∈ S, ↑s := rfl
lemma mem_Inf {S : set (subsemiring R)} {x : R} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_Inter₂
@[simp] lemma Inf_to_submonoid (s : set (subsemiring R)) :
(Inf s).to_submonoid = ⨅ t ∈ s, subsemiring.to_submonoid t :=
mk'_to_submonoid _ _
@[simp] lemma Inf_to_add_submonoid (s : set (subsemiring R)) :
(Inf s).to_add_submonoid = ⨅ t ∈ s, subsemiring.to_add_submonoid t :=
mk'_to_add_submonoid _ _
/-- Subsemirings of a semiring form a complete lattice. -/
instance : complete_lattice (subsemiring R) :=
{ bot := (⊥),
bot_le := λ s x hx, let ⟨n, hn⟩ := mem_bot.1 hx in hn ▸ coe_nat_mem s n,
top := (⊤),
le_top := λ s x hx, trivial,
inf := (⊓),
inf_le_left := λ s t x, and.left,
inf_le_right := λ s t x, and.right,
le_inf := λ s t₁ t₂ h₁ h₂ x hx, ⟨h₁ hx, h₂ hx⟩,
.. complete_lattice_of_Inf (subsemiring R)
(λ s, is_glb.of_image (λ s t,
show (s : set R) ≤ t ↔ s ≤ t, from set_like.coe_subset_coe) is_glb_binfi)}
lemma eq_top_iff' (A : subsemiring R) : A = ⊤ ↔ ∀ x : R, x ∈ A :=
eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩
section center
/-- The center of a semiring `R` is the set of elements that commute with everything in `R` -/
def center (R) [semiring R] : subsemiring R :=
{ carrier := set.center R,
zero_mem' := set.zero_mem_center R,
add_mem' := λ a b, set.add_mem_center,
.. submonoid.center R }
lemma coe_center (R) [semiring R] : ↑(center R) = set.center R := rfl
@[simp]
lemma center_to_submonoid (R) [semiring R] : (center R).to_submonoid = submonoid.center R := rfl
lemma mem_center_iff {R} [semiring R] {z : R} : z ∈ center R ↔ ∀ g, g * z = z * g :=
iff.rfl
instance decidable_mem_center {R} [semiring R] [decidable_eq R] [fintype R] :
decidable_pred (∈ center R) :=
λ _, decidable_of_iff' _ mem_center_iff
@[simp] lemma center_eq_top (R) [comm_semiring R] : center R = ⊤ :=
set_like.coe_injective (set.center_eq_univ R)
/-- The center is commutative. -/
instance {R} [semiring R] : comm_semiring (center R) :=
{ ..submonoid.center.comm_monoid,
..(center R).to_semiring}
end center
section centralizer
/-- The centralizer of a set as subsemiring. -/
def centralizer {R} [semiring R] (s : set R) : subsemiring R :=
{ carrier := s.centralizer,
zero_mem' := set.zero_mem_centralizer _,
add_mem' := λ x y hx hy, set.add_mem_centralizer hx hy,
..submonoid.centralizer s }
@[simp, norm_cast]
lemma coe_centralizer {R} [semiring R] (s : set R) : (centralizer s : set R) = s.centralizer := rfl
lemma centralizer_to_submonoid {R} [semiring R] (s : set R) :
(centralizer s).to_submonoid = submonoid.centralizer s := rfl
lemma mem_centralizer_iff {R} [semiring R] {s : set R} {z : R} :
z ∈ centralizer s ↔ ∀ g ∈ s, g * z = z * g :=
iff.rfl
lemma centralizer_le {R} [semiring R] (s t : set R) (h : s ⊆ t) :
centralizer t ≤ centralizer s :=
set.centralizer_subset h
@[simp]
lemma centralizer_univ {R} [semiring R] : centralizer set.univ = center R :=
set_like.ext' (set.centralizer_univ R)
end centralizer
/-- The `subsemiring` generated by a set. -/
def closure (s : set R) : subsemiring R := Inf {S | s ⊆ S}
lemma mem_closure {x : R} {s : set R} : x ∈ closure s ↔ ∀ S : subsemiring R, s ⊆ S → x ∈ S :=
mem_Inf
/-- The subsemiring generated by a set includes the set. -/
@[simp] lemma subset_closure {s : set R} : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx
lemma not_mem_of_not_mem_closure {s : set R} {P : R} (hP : P ∉ closure s) : P ∉ s :=
λ h, hP (subset_closure h)
/-- A subsemiring `S` includes `closure s` if and only if it includes `s`. -/
@[simp]
lemma closure_le {s : set R} {t : subsemiring R} : closure s ≤ t ↔ s ⊆ t :=
⟨set.subset.trans subset_closure, λ h, Inf_le h⟩
/-- Subsemiring closure of a set is monotone in its argument: if `s ⊆ t`,
then `closure s ≤ closure t`. -/
lemma closure_mono ⦃s t : set R⦄ (h : s ⊆ t) : closure s ≤ closure t :=
closure_le.2 $ set.subset.trans h subset_closure
lemma closure_eq_of_le {s : set R} {t : subsemiring R} (h₁ : s ⊆ t) (h₂ : t ≤ closure s) :
closure s = t :=
le_antisymm (closure_le.2 h₁) h₂
lemma mem_map_equiv {f : R ≃+* S} {K : subsemiring R} {x : S} :
x ∈ K.map (f : R →+* S) ↔ f.symm x ∈ K :=
@set.mem_image_equiv _ _ ↑K f.to_equiv x
lemma map_equiv_eq_comap_symm (f : R ≃+* S) (K : subsemiring R) :
K.map (f : R →+* S) = K.comap f.symm :=
set_like.coe_injective (f.to_equiv.image_eq_preimage K)
lemma comap_equiv_eq_map_symm (f : R ≃+* S) (K : subsemiring S) :
K.comap (f : R →+* S) = K.map f.symm :=
(map_equiv_eq_comap_symm f.symm K).symm
end subsemiring
namespace submonoid
/-- The additive closure of a submonoid is a subsemiring. -/
def subsemiring_closure (M : submonoid R) : subsemiring R :=
{ one_mem' := add_submonoid.mem_closure.mpr (λ y hy, hy M.one_mem),
mul_mem' := λ x y, mul_mem_class.mul_mem_add_closure,
..add_submonoid.closure (M : set R)}
lemma subsemiring_closure_coe :
(M.subsemiring_closure : set R) = add_submonoid.closure (M : set R) := rfl
lemma subsemiring_closure_to_add_submonoid :
M.subsemiring_closure.to_add_submonoid = add_submonoid.closure (M : set R) := rfl
/-- The `subsemiring` generated by a multiplicative submonoid coincides with the
`subsemiring.closure` of the submonoid itself . -/
lemma subsemiring_closure_eq_closure : M.subsemiring_closure = subsemiring.closure (M : set R) :=
begin
ext,
refine ⟨λ hx, _, λ hx, (subsemiring.mem_closure.mp hx) M.subsemiring_closure (λ s sM, _)⟩;
rintros - ⟨H1, rfl⟩;
rintros - ⟨H2, rfl⟩,
{ exact add_submonoid.mem_closure.mp hx H1.to_add_submonoid H2 },
{ exact H2 sM }
end
end submonoid
namespace subsemiring
@[simp]
lemma closure_submonoid_closure (s : set R) : closure ↑(submonoid.closure s) = closure s :=
le_antisymm
(closure_le.mpr (λ y hy, (submonoid.mem_closure.mp hy) (closure s).to_submonoid subset_closure))
(closure_mono (submonoid.subset_closure))
/-- The elements of the subsemiring closure of `M` are exactly the elements of the additive closure
of a multiplicative submonoid `M`. -/
lemma coe_closure_eq (s : set R) :
(closure s : set R) = add_submonoid.closure (submonoid.closure s : set R) :=
by simp [← submonoid.subsemiring_closure_to_add_submonoid, submonoid.subsemiring_closure_eq_closure]
lemma mem_closure_iff {s : set R} {x} :
x ∈ closure s ↔ x ∈ add_submonoid.closure (submonoid.closure s : set R) :=
set.ext_iff.mp (coe_closure_eq s) x
@[simp]
lemma closure_add_submonoid_closure {s : set R} : closure ↑(add_submonoid.closure s) = closure s :=
begin
ext x,
refine ⟨λ hx, _, λ hx, closure_mono add_submonoid.subset_closure hx⟩,
rintros - ⟨H, rfl⟩,
rintros - ⟨J, rfl⟩,
refine (add_submonoid.mem_closure.mp (mem_closure_iff.mp hx)) H.to_add_submonoid (λ y hy, _),
refine (submonoid.mem_closure.mp hy) H.to_submonoid (λ z hz, _),
exact (add_submonoid.mem_closure.mp hz) H.to_add_submonoid (λ w hw, J hw),
end
/-- An induction principle for closure membership. If `p` holds for `0`, `1`, and all elements
of `s`, and is preserved under addition and multiplication, then `p` holds for all elements
of the closure of `s`. -/
@[elab_as_eliminator]
lemma closure_induction {s : set R} {p : R → Prop} {x} (h : x ∈ closure s)
(Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : p 1)
(Hadd : ∀ x y, p x → p y → p (x + y)) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x :=
(@closure_le _ _ _ ⟨p, Hmul, H1, Hadd, H0⟩).2 Hs h
/-- An induction principle for closure membership for predicates with two arguments. -/
@[elab_as_eliminator]
lemma closure_induction₂ {s : set R} {p : R → R → Prop} {x} {y : R} (hx : x ∈ closure s)
(hy : y ∈ closure s)
(Hs : ∀ (x ∈ s) (y ∈ s), p x y)
(H0_left : ∀ x, p 0 x)
(H0_right : ∀ x, p x 0)
(H1_left : ∀ x, p 1 x)
(H1_right : ∀ x, p x 1)
(Hadd_left : ∀ x₁ x₂ y, p x₁ y → p x₂ y → p (x₁ + x₂) y)
(Hadd_right : ∀ x y₁ y₂, p x y₁ → p x y₂ → p x (y₁ + y₂))
(Hmul_left : ∀ x₁ x₂ y, p x₁ y → p x₂ y → p (x₁ * x₂) y)
(Hmul_right : ∀ x y₁ y₂, p x y₁ → p x y₂ → p x (y₁ * y₂))
: p x y :=
closure_induction hx
(λ x₁ x₁s, closure_induction hy (Hs x₁ x₁s) (H0_right x₁) (H1_right x₁) (Hadd_right x₁)
(Hmul_right x₁))
(H0_left y) (H1_left y) (λ z z', Hadd_left z z' y) (λ z z', Hmul_left z z' y)
lemma mem_closure_iff_exists_list {R} [semiring R] {s : set R} {x} : x ∈ closure s ↔
∃ L : list (list R), (∀ t ∈ L, ∀ y ∈ t, y ∈ s) ∧ (L.map list.prod).sum = x :=
⟨λ hx, add_submonoid.closure_induction (mem_closure_iff.1 hx)
(λ x hx, suffices ∃ t : list R, (∀ y ∈ t, y ∈ s) ∧ t.prod = x,
from let ⟨t, ht1, ht2⟩ := this in ⟨[t], list.forall_mem_singleton.2 ht1,
by rw [list.map_singleton, list.sum_singleton, ht2]⟩,
submonoid.closure_induction hx
(λ x hx, ⟨[x], list.forall_mem_singleton.2 hx, one_mul x⟩)
⟨[], list.forall_mem_nil _, rfl⟩
(λ x y ⟨t, ht1, ht2⟩ ⟨u, hu1, hu2⟩, ⟨t ++ u, list.forall_mem_append.2 ⟨ht1, hu1⟩,
by rw [list.prod_append, ht2, hu2]⟩))
⟨[], list.forall_mem_nil _, rfl⟩
(λ x y ⟨L, HL1, HL2⟩ ⟨M, HM1, HM2⟩, ⟨L ++ M, list.forall_mem_append.2 ⟨HL1, HM1⟩,
by rw [list.map_append, list.sum_append, HL2, HM2]⟩),
λ ⟨L, HL1, HL2⟩, HL2 ▸ list_sum_mem (λ r hr, let ⟨t, ht1, ht2⟩ := list.mem_map.1 hr in
ht2 ▸ list_prod_mem _ (λ y hy, subset_closure $ HL1 t ht1 y hy))⟩
variable (R)
/-- `closure` forms a Galois insertion with the coercion to set. -/
protected def gi : galois_insertion (@closure R _) coe :=
{ choice := λ s _, closure s,
gc := λ s t, closure_le,
le_l_u := λ s, subset_closure,
choice_eq := λ s h, rfl }
variable {R}
/-- Closure of a subsemiring `S` equals `S`. -/
lemma closure_eq (s : subsemiring R) : closure (s : set R) = s := (subsemiring.gi R).l_u_eq s
@[simp] lemma closure_empty : closure (∅ : set R) = ⊥ := (subsemiring.gi R).gc.l_bot
@[simp] lemma closure_univ : closure (set.univ : set R) = ⊤ := @coe_top R _ ▸ closure_eq ⊤
lemma closure_union (s t : set R) : closure (s ∪ t) = closure s ⊔ closure t :=
(subsemiring.gi R).gc.l_sup
lemma closure_Union {ι} (s : ι → set R) : closure (⋃ i, s i) = ⨆ i, closure (s i) :=
(subsemiring.gi R).gc.l_supr
lemma closure_sUnion (s : set (set R)) : closure (⋃₀ s) = ⨆ t ∈ s, closure t :=
(subsemiring.gi R).gc.l_Sup
lemma map_sup (s t : subsemiring R) (f : R →+* S) : (s ⊔ t).map f = s.map f ⊔ t.map f :=
(gc_map_comap f).l_sup
lemma map_supr {ι : Sort*} (f : R →+* S) (s : ι → subsemiring R) :
(supr s).map f = ⨆ i, (s i).map f :=
(gc_map_comap f).l_supr
lemma comap_inf (s t : subsemiring S) (f : R →+* S) : (s ⊓ t).comap f = s.comap f ⊓ t.comap f :=
(gc_map_comap f).u_inf
lemma comap_infi {ι : Sort*} (f : R →+* S) (s : ι → subsemiring S) :
(infi s).comap f = ⨅ i, (s i).comap f :=
(gc_map_comap f).u_infi
@[simp] lemma map_bot (f : R →+* S) : (⊥ : subsemiring R).map f = ⊥ :=
(gc_map_comap f).l_bot
@[simp] lemma comap_top (f : R →+* S) : (⊤ : subsemiring S).comap f = ⊤ :=
(gc_map_comap f).u_top
/-- Given `subsemiring`s `s`, `t` of semirings `R`, `S` respectively, `s.prod t` is `s × t`
as a subsemiring of `R × S`. -/
def prod (s : subsemiring R) (t : subsemiring S) : subsemiring (R × S) :=
{ carrier := s ×ˢ t,
.. s.to_submonoid.prod t.to_submonoid, .. s.to_add_submonoid.prod t.to_add_submonoid}
@[norm_cast]
lemma coe_prod (s : subsemiring R) (t : subsemiring S) : (s.prod t : set (R × S)) = s ×ˢ t :=
rfl
lemma mem_prod {s : subsemiring R} {t : subsemiring S} {p : R × S} :
p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl
@[mono] lemma prod_mono ⦃s₁ s₂ : subsemiring R⦄ (hs : s₁ ≤ s₂) ⦃t₁ t₂ : subsemiring S⦄
(ht : t₁ ≤ t₂) : s₁.prod t₁ ≤ s₂.prod t₂ :=
set.prod_mono hs ht
lemma prod_mono_right (s : subsemiring R) : monotone (λ t : subsemiring S, s.prod t) :=
prod_mono (le_refl s)
lemma prod_mono_left (t : subsemiring S) : monotone (λ s : subsemiring R, s.prod t) :=
λ s₁ s₂ hs, prod_mono hs (le_refl t)
lemma prod_top (s : subsemiring R) :
s.prod (⊤ : subsemiring S) = s.comap (ring_hom.fst R S) :=
ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst]
lemma top_prod (s : subsemiring S) :
(⊤ : subsemiring R).prod s = s.comap (ring_hom.snd R S) :=
ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd]
@[simp]
lemma top_prod_top : (⊤ : subsemiring R).prod (⊤ : subsemiring S) = ⊤ :=
(top_prod _).trans $ comap_top _
/-- Product of subsemirings is isomorphic to their product as monoids. -/
def prod_equiv (s : subsemiring R) (t : subsemiring S) : s.prod t ≃+* s × t :=
{ map_mul' := λ x y, rfl, map_add' := λ x y, rfl, .. equiv.set.prod ↑s ↑t }
lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subsemiring R} (hS : directed (≤) S)
{x : R} :
x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i :=
begin
refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr S i) hi⟩,
let U : subsemiring R := subsemiring.mk' (⋃ i, (S i : set R))
(⨆ i, (S i).to_submonoid) (submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id))
(⨆ i, (S i).to_add_submonoid) (add_submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)),
suffices : (⨆ i, S i) ≤ U, by simpa using @this x,
exact supr_le (λ i x hx, set.mem_Union.2 ⟨i, hx⟩),
end
lemma coe_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subsemiring R} (hS : directed (≤) S) :
((⨆ i, S i : subsemiring R) : set R) = ⋃ i, ↑(S i) :=
set.ext $ λ x, by simp [mem_supr_of_directed hS]
lemma mem_Sup_of_directed_on {S : set (subsemiring R)} (Sne : S.nonempty)
(hS : directed_on (≤) S) {x : R} :
x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s :=
begin
haveI : nonempty S := Sne.to_subtype,
simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk]
end
lemma coe_Sup_of_directed_on {S : set (subsemiring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) :
(↑(Sup S) : set R) = ⋃ s ∈ S, ↑s :=
set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS]
end subsemiring
namespace ring_hom
variables [non_assoc_semiring T] {s : subsemiring R}
variables {σR σS : Type*}
variables [set_like σR R] [set_like σS S] [subsemiring_class σR R] [subsemiring_class σS S]
open subsemiring
/-- Restriction of a ring homomorphism to a subsemiring of the domain. -/
def restrict (f : R →+* S) (s : σR) : s →+* S := f.comp $ subsemiring_class.subtype s
@[simp] lemma restrict_apply (f : R →+* S) {s : σR} (x : s) : f.restrict s x = f x := rfl
/-- Restriction of a ring homomorphism to a subsemiring of the codomain. -/
def cod_restrict (f : R →+* S) (s : σS) (h : ∀ x, f x ∈ s) : R →+* s :=
{ to_fun := λ n, ⟨f n, h n⟩,
.. (f : R →* S).cod_restrict s h,
.. (f : R →+ S).cod_restrict s h }
/-- Restriction of a ring homomorphism to its range interpreted as a subsemiring.
This is the bundled version of `set.range_factorization`. -/
def srange_restrict (f : R →+* S) : R →+* f.srange :=
f.cod_restrict f.srange f.mem_srange_self
@[simp] lemma coe_srange_restrict (f : R →+* S) (x : R) :
(f.srange_restrict x : S) = f x :=
rfl
lemma srange_restrict_surjective (f : R →+* S) : function.surjective f.srange_restrict :=
λ ⟨y, hy⟩, let ⟨x, hx⟩ := mem_srange.mp hy in ⟨x, subtype.ext hx⟩
lemma srange_top_iff_surjective {f : R →+* S} :
f.srange = (⊤ : subsemiring S) ↔ function.surjective f :=
set_like.ext'_iff.trans $ iff.trans (by rw [coe_srange, coe_top]) set.range_iff_surjective
/-- The range of a surjective ring homomorphism is the whole of the codomain. -/
lemma srange_top_of_surjective (f : R →+* S) (hf : function.surjective f) :
f.srange = (⊤ : subsemiring S) :=
srange_top_iff_surjective.2 hf
/-- The subsemiring of elements `x : R` such that `f x = g x` -/
def eq_slocus (f g : R →+* S) : subsemiring R :=
{ carrier := {x | f x = g x}, .. (f : R →* S).eq_mlocus g, .. (f : R →+ S).eq_mlocus g }
/-- If two ring homomorphisms are equal on a set, then they are equal on its subsemiring closure. -/
lemma eq_on_sclosure {f g : R →+* S} {s : set R} (h : set.eq_on f g s) :
set.eq_on f g (closure s) :=
show closure s ≤ f.eq_slocus g, from closure_le.2 h
lemma eq_of_eq_on_stop {f g : R →+* S} (h : set.eq_on f g (⊤ : subsemiring R)) :
f = g :=
ext $ λ x, h trivial
lemma eq_of_eq_on_sdense {s : set R} (hs : closure s = ⊤) {f g : R →+* S} (h : s.eq_on f g) :
f = g :=
eq_of_eq_on_stop $ hs ▸ eq_on_sclosure h
lemma sclosure_preimage_le (f : R →+* S) (s : set S) :
closure (f ⁻¹' s) ≤ (closure s).comap f :=
closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx
/-- The image under a ring homomorphism of the subsemiring generated by a set equals
the subsemiring generated by the image of the set. -/
lemma map_sclosure (f : R →+* S) (s : set R) :
(closure s).map f = closure (f '' s) :=
le_antisymm
(map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _)
(sclosure_preimage_le _ _))
(closure_le.2 $ set.image_subset _ subset_closure)
end ring_hom
namespace subsemiring
open ring_hom
/-- The ring homomorphism associated to an inclusion of subsemirings. -/
def inclusion {S T : subsemiring R} (h : S ≤ T) : S →+* T :=
S.subtype.cod_restrict _ (λ x, h x.2)
@[simp] lemma srange_subtype (s : subsemiring R) : s.subtype.srange = s :=
set_like.coe_injective $ (coe_srange _).trans subtype.range_coe
@[simp]
lemma range_fst : (fst R S).srange = ⊤ :=
(fst R S).srange_top_of_surjective $ prod.fst_surjective
@[simp]
lemma range_snd : (snd R S).srange = ⊤ :=
(snd R S).srange_top_of_surjective $ prod.snd_surjective
@[simp]
lemma prod_bot_sup_bot_prod (s : subsemiring R) (t : subsemiring S) :
(s.prod ⊥) ⊔ (prod ⊥ t) = s.prod t :=
le_antisymm (sup_le (prod_mono_right s bot_le) (prod_mono_left t bot_le)) $
assume p hp, prod.fst_mul_snd p ▸ mul_mem
((le_sup_left : s.prod ⊥ ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨hp.1, set_like.mem_coe.2 $ one_mem ⊥⟩)
((le_sup_right : prod ⊥ t ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨set_like.mem_coe.2 $ one_mem ⊥, hp.2⟩)
end subsemiring
namespace ring_equiv
variables {s t : subsemiring R}
/-- Makes the identity isomorphism from a proof two subsemirings of a multiplicative
monoid are equal. -/
def subsemiring_congr (h : s = t) : s ≃+* t :=
{ map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h }
/-- Restrict a ring homomorphism with a left inverse to a ring isomorphism to its
`ring_hom.srange`. -/
def sof_left_inverse {g : S → R} {f : R →+* S} (h : function.left_inverse g f) :
R ≃+* f.srange :=
{ to_fun := λ x, f.srange_restrict x,
inv_fun := λ x, (g ∘ f.srange.subtype) x,
left_inv := h,
right_inv := λ x, subtype.ext $
let ⟨x', hx'⟩ := ring_hom.mem_srange.mp x.prop in
show f (g x) = x, by rw [←hx', h x'],
..f.srange_restrict }
@[simp] lemma sof_left_inverse_apply
{g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : R) :
↑(sof_left_inverse h x) = f x := rfl
@[simp] lemma sof_left_inverse_symm_apply
{g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : f.srange) :
(sof_left_inverse h).symm x = g x := rfl
/-- Given an equivalence `e : R ≃+* S` of semirings and a subsemiring `s` of `R`,
`subsemiring_map e s` is the induced equivalence between `s` and `s.map e` -/
@[simps] def subsemiring_map (e : R ≃+* S) (s : subsemiring R) :
s ≃+* s.map e.to_ring_hom :=
{ ..e.to_add_equiv.add_submonoid_map s.to_add_submonoid,
..e.to_mul_equiv.submonoid_map s.to_submonoid }
end ring_equiv
/-! ### Actions by `subsemiring`s
These are just copies of the definitions about `submonoid` starting from `submonoid.mul_action`.
The only new result is `subsemiring.module`.
When `R` is commutative, `algebra.of_subsemiring` provides a stronger result than those found in
this file, which uses the same scalar action.
-/
section actions
namespace subsemiring
variables {R' α β : Type*}
section non_assoc_semiring
variables [non_assoc_semiring R']
/-- The action by a subsemiring is the action by the underlying semiring. -/
instance [has_smul R' α] (S : subsemiring R') : has_smul S α := S.to_submonoid.has_smul
lemma smul_def [has_smul R' α] {S : subsemiring R'} (g : S) (m : α) : g • m = (g : R') • m := rfl
instance smul_comm_class_left
[has_smul R' β] [has_smul α β] [smul_comm_class R' α β] (S : subsemiring R') :
smul_comm_class S α β :=
S.to_submonoid.smul_comm_class_left
instance smul_comm_class_right
[has_smul α β] [has_smul R' β] [smul_comm_class α R' β] (S : subsemiring R') :
smul_comm_class α S β :=
S.to_submonoid.smul_comm_class_right
/-- Note that this provides `is_scalar_tower S R R` which is needed by `smul_mul_assoc`. -/
instance [has_smul α β] [has_smul R' α] [has_smul R' β] [is_scalar_tower R' α β]
(S : subsemiring R') :
is_scalar_tower S α β :=
S.to_submonoid.is_scalar_tower
instance [has_smul R' α] [has_faithful_smul R' α] (S : subsemiring R') :
has_faithful_smul S α :=
S.to_submonoid.has_faithful_smul
/-- The action by a subsemiring is the action by the underlying semiring. -/
instance [has_zero α] [smul_with_zero R' α] (S : subsemiring R') : smul_with_zero S α :=
smul_with_zero.comp_hom _ S.subtype.to_monoid_with_zero_hom.to_zero_hom
end non_assoc_semiring
variables [semiring R']
/-- The action by a subsemiring is the action by the underlying semiring. -/
instance [mul_action R' α] (S : subsemiring R') : mul_action S α :=
S.to_submonoid.mul_action
/-- The action by a subsemiring is the action by the underlying semiring. -/
instance [add_monoid α] [distrib_mul_action R' α] (S : subsemiring R') : distrib_mul_action S α :=
S.to_submonoid.distrib_mul_action
/-- The action by a subsemiring is the action by the underlying semiring. -/
instance [monoid α] [mul_distrib_mul_action R' α] (S : subsemiring R') :
mul_distrib_mul_action S α :=
S.to_submonoid.mul_distrib_mul_action
/-- The action by a subsemiring is the action by the underlying semiring. -/
instance [has_zero α] [mul_action_with_zero R' α] (S : subsemiring R') : mul_action_with_zero S α :=
mul_action_with_zero.comp_hom _ S.subtype.to_monoid_with_zero_hom
/-- The action by a subsemiring is the action by the underlying semiring. -/
instance [add_comm_monoid α] [module R' α] (S : subsemiring R') : module S α :=
{ smul := (•), .. module.comp_hom _ S.subtype }
/-- The center of a semiring acts commutatively on that semiring. -/
instance center.smul_comm_class_left : smul_comm_class (center R') R' R' :=
submonoid.center.smul_comm_class_left
/-- The center of a semiring acts commutatively on that semiring. -/
instance center.smul_comm_class_right : smul_comm_class R' (center R') R' :=
submonoid.center.smul_comm_class_right
/-- If all the elements of a set `s` commute, then `closure s` is a commutative monoid. -/
def closure_comm_semiring_of_comm {s : set R'} (hcomm : ∀ (a ∈ s) (b ∈ s), a * b = b * a) :
comm_semiring (closure s) :=
{ mul_comm := λ x y,
begin
ext,
simp only [subsemiring.coe_mul],
refine closure_induction₂ x.prop y.prop hcomm
(λ x, by simp only [zero_mul, mul_zero])
(λ x, by simp only [zero_mul, mul_zero])
(λ x, by simp only [one_mul, mul_one])
(λ x, by simp only [one_mul, mul_one])
(λ x y z h₁ h₂, by simp only [add_mul, mul_add, h₁, h₂])
(λ x y z h₁ h₂, by simp only [add_mul, mul_add, h₁, h₂])
(λ x y z h₁ h₂, by rw [mul_assoc, h₂, ←mul_assoc, h₁, mul_assoc])
(λ x y z h₁ h₂, by rw [←mul_assoc, h₁, mul_assoc, h₂, ←mul_assoc])
end,
..(closure s).to_semiring }
end subsemiring
end actions
-- While this definition is not about `subsemiring`s, this is the earliest we have
-- both `ordered_semiring` and `submonoid` available.
/-- Submonoid of positive elements of an ordered semiring. -/
def pos_submonoid (R : Type*) [ordered_semiring R] [nontrivial R] : submonoid R :=
{ carrier := {x | 0 < x},
one_mem' := show (0 : R) < 1, from zero_lt_one,
mul_mem' := λ x y (hx : 0 < x) (hy : 0 < y), mul_pos hx hy }
@[simp] lemma mem_pos_monoid {R : Type*} [ordered_semiring R] [nontrivial R] (u : Rˣ) :
↑u ∈ pos_submonoid R ↔ (0 : R) < u := iff.rfl
|
9db8b8ba548b932f5e3b71a9caff27927b17def5 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/wf_auto.lean | d9490b319522392f20a67506fbc3dd5a9a5c9770 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,263 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.data.nat.basic
import Mathlib.Lean3Lib.init.data.prod
universes u l v
namespace Mathlib
inductive acc {α : Sort u} (r : α → α → Prop) : α → Prop where
| intro : ∀ (x : α), (∀ (y : α), r y x → acc r y) → acc r x
namespace acc
def inv {α : Sort u} {r : α → α → Prop} {x : α} {y : α} (h₁ : acc r x) (h₂ : r y x) : acc r y :=
acc.rec_on h₁
(fun (x₁ : α) (ac₁ : ∀ (y : α), r y x₁ → acc r y)
(ih : ∀ (y_1 : α), r y_1 x₁ → r y y_1 → acc r y) (h₂ : r y x₁) => ac₁ y h₂)
h₂
end acc
/-- A relation `r : α → α → Prop` is well-founded when `∀ x, (∀ y, r y x → P y → P x) → P x` for all predicates `P`.
Once you know that a relation is well_founded, you can use it to define fixpoint functions on `α`.-/
structure well_founded {α : Sort u} (r : α → α → Prop) where
intro :: (apply : ∀ (a : α), acc r a)
class has_well_founded (α : Sort u) where
r : α → α → Prop
wf : well_founded r
namespace well_founded
def recursion {α : Sort u} {r : α → α → Prop} (hwf : well_founded r) {C : α → Sort v} (a : α)
(h : (x : α) → ((y : α) → r y x → C y) → C x) : C a :=
acc.rec_on (apply hwf a)
fun (x₁ : α) (ac₁ : ∀ (y : α), r y x₁ → acc r y) (ih : (y : α) → r y x₁ → C y) => h x₁ ih
theorem induction {α : Sort u} {r : α → α → Prop} (hwf : well_founded r) {C : α → Prop} (a : α)
(h : ∀ (x : α), (∀ (y : α), r y x → C y) → C x) : C a :=
recursion hwf a h
def fix_F {α : Sort u} {r : α → α → Prop} {C : α → Sort v}
(F : (x : α) → ((y : α) → r y x → C y) → C x) (x : α) (a : acc r x) : C x :=
acc.rec_on a
fun (x₁ : α) (ac₁ : ∀ (y : α), r y x₁ → acc r y) (ih : (y : α) → r y x₁ → C y) => F x₁ ih
theorem fix_F_eq {α : Sort u} {r : α → α → Prop} {C : α → Sort v}
(F : (x : α) → ((y : α) → r y x → C y) → C x) (x : α) (acx : acc r x) :
fix_F F x acx = F x fun (y : α) (p : r y x) => fix_F F y (acc.inv acx p) :=
sorry
/-- Well-founded fixpoint -/
def fix {α : Sort u} {C : α → Sort v} {r : α → α → Prop} (hwf : well_founded r)
(F : (x : α) → ((y : α) → r y x → C y) → C x) (x : α) : C x :=
fix_F F x sorry
/-- Well-founded fixpoint satisfies fixpoint equation -/
theorem fix_eq {α : Sort u} {C : α → Sort v} {r : α → α → Prop} (hwf : well_founded r)
(F : (x : α) → ((y : α) → r y x → C y) → C x) (x : α) :
fix hwf F x = F x fun (y : α) (h : r y x) => fix hwf F y :=
fix_F_eq F x (apply hwf x)
end well_founded
/-- Empty relation is well-founded -/
def empty_wf {α : Sort u} : well_founded empty_relation :=
well_founded.intro fun (a : α) => acc.intro a fun (b : α) (lt : False) => False._oldrec lt
/- Subrelation of a well-founded relation is well-founded -/
namespace subrelation
def accessible {α : Sort u} {r : α → α → Prop} {Q : α → α → Prop} (h₁ : subrelation Q r) {a : α}
(ac : acc r a) : acc Q a :=
acc.rec_on ac
fun (x : α) (ax : ∀ (y : α), r y x → acc r y) (ih : ∀ (y : α), r y x → acc Q y) =>
acc.intro x fun (y : α) (lt : Q y x) => ih y (h₁ lt)
def wf {α : Sort u} {r : α → α → Prop} {Q : α → α → Prop} (h₁ : subrelation Q r)
(h₂ : well_founded r) : well_founded Q :=
well_founded.intro fun (a : α) => accessible h₁ (well_founded.apply h₂ a)
end subrelation
-- The inverse image of a well-founded relation is well-founded
namespace inv_image
def accessible {α : Sort u} {β : Sort v} {r : β → β → Prop} (f : α → β) {a : α} (ac : acc r (f a)) :
acc (inv_image r f) a :=
acc_aux f ac a rfl
def wf {α : Sort u} {β : Sort v} {r : β → β → Prop} (f : α → β) (h : well_founded r) :
well_founded (inv_image r f) :=
well_founded.intro fun (a : α) => accessible f (well_founded.apply h (f a))
end inv_image
-- The transitive closure of a well-founded relation is well-founded
namespace tc
def accessible {α : Sort u} {r : α → α → Prop} {z : α} (ac : acc r z) : acc (tc r) z :=
acc.rec_on ac
fun (x : α) (acx : ∀ (y : α), r y x → acc r y) (ih : ∀ (y : α), r y x → acc (tc r) y) =>
acc.intro x
fun (y : α) (rel : tc r y x) =>
tc.rec_on rel
(fun (a b : α) (rab : r a b) (acx : ∀ (y : α), r y b → acc r y)
(ih : ∀ (y : α), r y b → acc (tc r) y) => ih a rab)
(fun (a b c : α) (rab : tc r a b) (rbc : tc r b c)
(ih₁ :
(∀ (y : α), r y b → acc r y) → (∀ (y : α), r y b → acc (tc r) y) → acc (tc r) a)
(ih₂ :
(∀ (y : α), r y c → acc r y) → (∀ (y : α), r y c → acc (tc r) y) → acc (tc r) b)
(acx : ∀ (y : α), r y c → acc r y) (ih : ∀ (y : α), r y c → acc (tc r) y) =>
acc.inv (ih₂ acx ih) rab)
acx ih
def wf {α : Sort u} {r : α → α → Prop} (h : well_founded r) : well_founded (tc r) :=
well_founded.intro fun (a : α) => accessible (well_founded.apply h a)
end tc
/-- less-than is well-founded -/
def nat.lt_wf : well_founded nat.lt :=
well_founded.intro
(Nat.rec (acc.intro 0 fun (n : ℕ) (h : n < 0) => absurd h (nat.not_lt_zero n))
fun (n : ℕ) (ih : acc Less n) =>
acc.intro (Nat.succ n)
fun (m : ℕ) (h : m < Nat.succ n) =>
or.elim (nat.eq_or_lt_of_le (nat.le_of_succ_le_succ h))
(fun (e : m = n) => eq.substr e ih) (acc.inv ih))
def measure {α : Sort u} : (α → ℕ) → α → α → Prop := inv_image Less
def measure_wf {α : Sort u} (f : α → ℕ) : well_founded (measure f) := inv_image.wf f nat.lt_wf
def sizeof_measure (α : Sort u) [SizeOf α] : α → α → Prop := measure sizeof
def sizeof_measure_wf (α : Sort u) [SizeOf α] : well_founded (sizeof_measure α) := measure_wf sizeof
protected instance has_well_founded_of_has_sizeof (α : Sort u) [SizeOf α] : has_well_founded α :=
has_well_founded.mk (sizeof_measure α) (sizeof_measure_wf α)
namespace prod
inductive lex {α : Type u} {β : Type v} (ra : α → α → Prop) (rb : β → β → Prop) :
α × β → α × β → Prop
where
| left : ∀ {a₁ : α} (b₁ : β) {a₂ : α} (b₂ : β), ra a₁ a₂ → lex ra rb (a₁, b₁) (a₂, b₂)
| right : ∀ (a : α) {b₁ b₂ : β}, rb b₁ b₂ → lex ra rb (a, b₁) (a, b₂)
inductive rprod {α : Type u} {β : Type v} (ra : α → α → Prop) (rb : β → β → Prop) :
α × β → α × β → Prop
where
| intro : ∀ {a₁ : α} {b₁ : β} {a₂ : α} {b₂ : β}, ra a₁ a₂ → rb b₁ b₂ → rprod ra rb (a₁, b₁) (a₂, b₂)
def lex_accessible {α : Type u} {β : Type v} {ra : α → α → Prop} {rb : β → β → Prop} {a : α}
(aca : acc ra a) (acb : ∀ (b : β), acc rb b) (b : β) : acc (lex ra rb) (a, b) :=
acc.rec_on aca
fun (xa : α) (aca : ∀ (y : α), ra y xa → acc ra y)
(iha : ∀ (y : α), ra y xa → ∀ (b : β), acc (lex ra rb) (y, b)) (b : β) =>
acc.rec_on (acb b)
fun (xb : β) (acb : ∀ (y : β), rb y xb → acc rb y)
(ihb : ∀ (y : β), rb y xb → acc (lex ra rb) (xa, y)) =>
acc.intro (xa, xb)
fun (p : α × β) (lt : lex ra rb p (xa, xb)) =>
(fun (aux : xa = xa → xb = xb → acc (lex ra rb) p) => aux rfl rfl)
(lex.rec_on lt
(fun (a₁ : α) (b₁ : β) (a₂ : α) (b₂ : β) (h : ra a₁ a₂) (eq₂ : a₂ = xa)
(eq₃ : b₂ = xb) => iha a₁ (eq.rec_on eq₂ h) b₁)
fun (a : α) (b₁ b₂ : β) (h : rb b₁ b₂) (eq₂ : a = xa) (eq₃ : b₂ = xb) =>
eq.rec_on (Eq.symm eq₂) (ihb b₁ (eq.rec_on eq₃ h)))
def lex_wf {α : Type u} {β : Type v} {ra : α → α → Prop} {rb : β → β → Prop} (ha : well_founded ra)
(hb : well_founded rb) : well_founded (lex ra rb) :=
well_founded.intro
fun (p : α × β) =>
cases_on p
fun (a : α) (b : β) => lex_accessible (well_founded.apply ha a) (well_founded.apply hb) b
def rprod_sub_lex {α : Type u} {β : Type v} {ra : α → α → Prop} {rb : β → β → Prop} (a : α × β)
(b : α × β) : rprod ra rb a b → lex ra rb a b :=
fun (h : rprod ra rb a b) =>
rprod.rec_on h
fun (a₁ : α) (b₁ : β) (a₂ : α) (b₂ : β) (h₁ : ra a₁ a₂) (h₂ : rb b₁ b₂) => lex.left b₁ b₂ h₁
def rprod_wf {α : Type u} {β : Type v} {ra : α → α → Prop} {rb : β → β → Prop}
(ha : well_founded ra) (hb : well_founded rb) : well_founded (rprod ra rb) :=
subrelation.wf rprod_sub_lex (lex_wf ha hb)
protected instance has_well_founded {α : Type u} {β : Type v} [s₁ : has_well_founded α]
[s₂ : has_well_founded β] : has_well_founded (α × β) :=
has_well_founded.mk (lex has_well_founded.r has_well_founded.r) sorry
end Mathlib |
4ef395afb2ef62791b532601262a9b69d98ba97b | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/category_theory/limits/functor_category.lean | bdfa647ca3534407dd09dc575acd92dcc7b01904 | [
"Apache-2.0"
] | permissive | mcncm/mathlib | 8d25099344d9d2bee62822cb9ed43aa3e09fa05e | fde3d78cadeec5ef827b16ae55664ef115e66f57 | refs/heads/master | 1,672,743,316,277 | 1,602,618,514,000 | 1,602,618,514,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,776 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.limits.preserves.basic
open category_theory category_theory.category
namespace category_theory.limits
universes v v₂ u -- declare the `v`'s first; see `category_theory.category` for an explanation
variables {C : Type u} [category.{v} C]
variables {J K : Type v} [small_category J] [category.{v₂} K]
@[simp, reassoc]
lemma limit.lift_π_app (H : J ⥤ K ⥤ C) [has_limit H] (c : cone H) (j : J) (k : K) :
(limit.lift H c).app k ≫ (limit.π H j).app k = (c.π.app j).app k :=
congr_app (limit.lift_π c j) k
@[simp, reassoc]
lemma colimit.ι_desc_app (H : J ⥤ K ⥤ C) [has_colimit H] (c : cocone H) (j : J) (k : K) :
(colimit.ι H j).app k ≫ (colimit.desc H c).app k = (c.ι.app j).app k :=
congr_app (colimit.ι_desc c j) k
/--
The evaluation functors jointly reflect limits: that is, to show a cone is a limit of `F`
it suffices to show that each evaluation cone is a limit. In other words, to prove a cone is
limiting you can show it's pointwise limiting.
-/
def evaluation_jointly_reflects_limits {F : J ⥤ K ⥤ C} (c : cone F)
(t : Π (k : K), is_limit (((evaluation K C).obj k).map_cone c)) : is_limit c :=
{ lift := λ s,
{ app := λ k, (t k).lift ⟨s.X.obj k, whisker_right s.π ((evaluation K C).obj k)⟩,
naturality' := λ X Y f, (t Y).hom_ext $ λ j,
begin
rw [assoc, (t Y).fac _ j],
simpa using ((t X).fac_assoc ⟨s.X.obj X, whisker_right s.π ((evaluation K C).obj X)⟩ j _).symm,
end },
fac' := λ s j, nat_trans.ext _ _ $ funext $ λ k, (t k).fac _ j,
uniq' := λ s m w, nat_trans.ext _ _ $ funext $ λ x, (t x).hom_ext $ λ j,
(congr_app (w j) x).trans
((t x).fac ⟨s.X.obj _, whisker_right s.π ((evaluation K C).obj _)⟩ j).symm }
/--
Given a functor `F` and a collection of limit cones for each diagram `X ↦ F X k`, we can stitch
them together to give a cone for the diagram `F`.
`combined_is_limit` shows that the new cone is limiting, and `eval_combined` shows it is
(essentially) made up of the original cones.
-/
@[simps] def combine_cones (F : J ⥤ K ⥤ C) (c : Π (k : K), limit_cone (F.flip.obj k)) :
cone F :=
{ X :=
{ obj := λ k, (c k).cone.X,
map := λ k₁ k₂ f, (c k₂).is_limit.lift ⟨_, (c k₁).cone.π ≫ F.flip.map f⟩,
map_id' := λ k, (c k).is_limit.hom_ext (λ j, by { dsimp, simp }),
map_comp' := λ k₁ k₂ k₃ f₁ f₂, (c k₃).is_limit.hom_ext (λ j, by simp) },
π :=
{ app := λ j, { app := λ k, (c k).cone.π.app j },
naturality' := λ j₁ j₂ g, nat_trans.ext _ _ $ funext $ λ k, (c k).cone.π.naturality g } }
/-- The stitched together cones each project down to the original given cones (up to iso). -/
def evaluate_combined_cones (F : J ⥤ K ⥤ C) (c : Π (k : K), limit_cone (F.flip.obj k)) (k : K) :
((evaluation K C).obj k).map_cone (combine_cones F c) ≅ (c k).cone :=
cones.ext (iso.refl _) (by tidy)
/-- Stitching together limiting cones gives a limiting cone. -/
def combined_is_limit (F : J ⥤ K ⥤ C) (c : Π (k : K), limit_cone (F.flip.obj k)) :
is_limit (combine_cones F c) :=
evaluation_jointly_reflects_limits _
(λ k, (c k).is_limit.of_iso_limit (evaluate_combined_cones F c k).symm)
/--
The evaluation functors jointly reflect colimits: that is, to show a cocone is a colimit of `F`
it suffices to show that each evaluation cocone is a colimit. In other words, to prove a cocone is
colimiting you can show it's pointwise colimiting.
-/
def evaluation_jointly_reflects_colimits {F : J ⥤ K ⥤ C} (c : cocone F)
(t : Π (k : K), is_colimit (((evaluation K C).obj k).map_cocone c)) : is_colimit c :=
{ desc := λ s,
{ app := λ k, (t k).desc ⟨s.X.obj k, whisker_right s.ι ((evaluation K C).obj k)⟩,
naturality' := λ X Y f, (t X).hom_ext $ λ j,
begin
rw [(t X).fac_assoc _ j],
erw ← (c.ι.app j).naturality_assoc f,
erw (t Y).fac ⟨s.X.obj _, whisker_right s.ι _⟩ j,
dsimp,
simp,
end },
fac' := λ s j, nat_trans.ext _ _ $ funext $ λ k, (t k).fac _ j,
uniq' := λ s m w, nat_trans.ext _ _ $ funext $ λ x, (t x).hom_ext $ λ j,
(congr_app (w j) x).trans
((t x).fac ⟨s.X.obj _, whisker_right s.ι ((evaluation K C).obj _)⟩ j).symm }
/--
Given a functor `F` and a collection of colimit cocones for each diagram `X ↦ F X k`, we can stitch
them together to give a cocone for the diagram `F`.
`combined_is_colimit` shows that the new cocone is colimiting, and `eval_combined` shows it is
(essentially) made up of the original cocones.
-/
@[simps] def combine_cocones (F : J ⥤ K ⥤ C) (c : Π (k : K), colimit_cocone (F.flip.obj k)) :
cocone F :=
{ X :=
{ obj := λ k, (c k).cocone.X,
map := λ k₁ k₂ f, (c k₁).is_colimit.desc ⟨_, F.flip.map f ≫ (c k₂).cocone.ι⟩,
map_id' := λ k, (c k).is_colimit.hom_ext (λ j, by { dsimp, simp }),
map_comp' := λ k₁ k₂ k₃ f₁ f₂, (c k₁).is_colimit.hom_ext (λ j, by simp) },
ι :=
{ app := λ j, { app := λ k, (c k).cocone.ι.app j },
naturality' := λ j₁ j₂ g, nat_trans.ext _ _ $ funext $ λ k, (c k).cocone.ι.naturality g } }
/-- The stitched together cocones each project down to the original given cocones (up to iso). -/
def evaluate_combined_cocones (F : J ⥤ K ⥤ C) (c : Π (k : K), colimit_cocone (F.flip.obj k)) (k : K) :
((evaluation K C).obj k).map_cocone (combine_cocones F c) ≅ (c k).cocone :=
cocones.ext (iso.refl _) (by tidy)
/-- Stitching together colimiting cocones gives a colimiting cocone. -/
def combined_is_colimit (F : J ⥤ K ⥤ C) (c : Π (k : K), colimit_cocone (F.flip.obj k)) :
is_colimit (combine_cocones F c) :=
evaluation_jointly_reflects_colimits _
(λ k, (c k).is_colimit.of_iso_colimit (evaluate_combined_cocones F c k).symm)
noncomputable theory
instance functor_category_has_limits_of_shape
[has_limits_of_shape J C] : has_limits_of_shape J (K ⥤ C) :=
{ has_limit := λ F, has_limit.mk
{ cone := combine_cones F (λ k, get_limit_cone _),
is_limit := combined_is_limit _ _ } }
instance functor_category_has_colimits_of_shape
[has_colimits_of_shape J C] : has_colimits_of_shape J (K ⥤ C) :=
{ has_colimit := λ F, has_colimit.mk
{ cocone := combine_cocones _ (λ k, get_colimit_cocone _),
is_colimit := combined_is_colimit _ _ } }
instance functor_category_has_limits [has_limits C] : has_limits (K ⥤ C) :=
{ has_limits_of_shape := λ J 𝒥, by resetI; apply_instance }
instance functor_category_has_colimits [has_colimits C] : has_colimits (K ⥤ C) :=
{ has_colimits_of_shape := λ J 𝒥, by resetI; apply_instance }
instance evaluation_preserves_limits_of_shape [has_limits_of_shape J C] (k : K) :
preserves_limits_of_shape J ((evaluation K C).obj k) :=
{ preserves_limit :=
λ F, preserves_limit_of_preserves_limit_cone (combined_is_limit _ _) $
is_limit.of_iso_limit (limit.is_limit _)
(evaluate_combined_cones F _ k).symm }
/--
If `F : J ⥤ K ⥤ C` is a functor into a functor category which has a limit,
then the evaluation of that limit at `k` is the limit of the evaluations of `F.obj j` at `k`.
-/
def limit_obj_iso_limit_comp_evaluation [has_limits_of_shape J C] (F : J ⥤ K ⥤ C) (k : K) :
(limit F).obj k ≅ limit (F ⋙ ((evaluation K C).obj k)) :=
preserves_limit_iso F ((evaluation K C).obj k)
@[simp, reassoc]
lemma limit_obj_iso_limit_comp_evaluation_hom_π
[has_limits_of_shape J C] (F : J ⥤ (K ⥤ C)) (j : J) (k : K) :
(limit_obj_iso_limit_comp_evaluation F k).hom ≫ limit.π (F ⋙ ((evaluation K C).obj k)) j =
(limit.π F j).app k :=
begin
dsimp [limit_obj_iso_limit_comp_evaluation, limits.preserves_limit_iso],
simp,
end
@[simp, reassoc]
lemma limit_obj_iso_limit_comp_evaluation_inv_π_app
[has_limits_of_shape J C] (F : J ⥤ (K ⥤ C)) (j : J) (k : K):
(limit_obj_iso_limit_comp_evaluation F k).inv ≫ (limit.π F j).app k =
limit.π (F ⋙ ((evaluation K C).obj k)) j :=
begin
dsimp [limit_obj_iso_limit_comp_evaluation, limits.preserves_limit_iso],
rw iso.inv_comp_eq,
simp,
end
@[ext]
lemma limit_obj_ext {H : J ⥤ K ⥤ C} [has_limits_of_shape J C]
{k : K} {W : C} {f g : W ⟶ (limit H).obj k}
(w : ∀ j, f ≫ (limits.limit.π H j).app k = g ≫ (limits.limit.π H j).app k) : f = g :=
begin
apply (cancel_mono (limit_obj_iso_limit_comp_evaluation H k).hom).1,
ext,
simpa using w j,
end
instance evaluation_preserves_colimits_of_shape [has_colimits_of_shape J C] (k : K) :
preserves_colimits_of_shape J ((evaluation K C).obj k) :=
{ preserves_colimit :=
λ F, preserves_colimit_of_preserves_colimit_cocone (combined_is_colimit _ _) $
is_colimit.of_iso_colimit (colimit.is_colimit _)
(evaluate_combined_cocones F _ k).symm }
/--
If `F : J ⥤ K ⥤ C` is a functor into a functor category which has a colimit,
then the evaluation of that colimit at `k` is the colimit of the evaluations of `F.obj j` at `k`.
-/
def colimit_obj_iso_colimit_comp_evaluation [has_colimits_of_shape J C] (F : J ⥤ K ⥤ C) (k : K) :
(colimit F).obj k ≅ colimit (F ⋙ ((evaluation K C).obj k)) :=
preserves_colimit_iso F ((evaluation K C).obj k)
@[simp, reassoc]
lemma colimit_obj_iso_colimit_comp_evaluation_ι_inv
[has_colimits_of_shape J C] (F : J ⥤ (K ⥤ C)) (j : J) (k : K) :
colimit.ι (F ⋙ ((evaluation K C).obj k)) j ≫ (colimit_obj_iso_colimit_comp_evaluation F k).inv =
(colimit.ι F j).app k :=
begin
dsimp [colimit_obj_iso_colimit_comp_evaluation, limits.preserves_colimit_iso],
simp,
end
@[simp, reassoc]
lemma colimit_obj_iso_colimit_comp_evaluation_ι_app_hom
[has_colimits_of_shape J C] (F : J ⥤ (K ⥤ C)) (j : J) (k : K) :
(colimit.ι F j).app k ≫ (colimit_obj_iso_colimit_comp_evaluation F k).hom =
colimit.ι (F ⋙ ((evaluation K C).obj k)) j :=
begin
dsimp [colimit_obj_iso_colimit_comp_evaluation, limits.preserves_colimit_iso],
rw ←iso.eq_comp_inv,
simp,
end
@[ext]
lemma colimit_obj_ext {H : J ⥤ K ⥤ C} [has_colimits_of_shape J C]
{k : K} {W : C} {f g : (colimit H).obj k ⟶ W}
(w : ∀ j, (colimit.ι H j).app k ≫ f = (colimit.ι H j).app k ≫ g) : f = g :=
begin
apply (cancel_epi (colimit_obj_iso_colimit_comp_evaluation H k).inv).1,
ext,
simpa using w j,
end
instance evaluation_preserves_limits [has_limits C] (k : K) :
preserves_limits ((evaluation K C).obj k) :=
{ preserves_limits_of_shape := λ J 𝒥, by resetI; apply_instance }
instance evaluation_preserves_colimits [has_colimits C] (k : K) :
preserves_colimits ((evaluation K C).obj k) :=
{ preserves_colimits_of_shape := λ J 𝒥, by resetI; apply_instance }
end category_theory.limits
|
efd16ecdae8be72eba745f05e2021b94ea433df8 | 968e2f50b755d3048175f176376eff7139e9df70 | /examples/pred_logic/unnamed_131.lean | 86725f02977241d3647d645e7c48cc333e717c90 | [] | no_license | gihanmarasingha/mth1001_sphinx | 190a003269ba5e54717b448302a27ca26e31d491 | 05126586cbf5786e521be1ea2ef5b4ba3c44e74a | refs/heads/master | 1,672,913,933,677 | 1,604,516,583,000 | 1,604,516,583,000 | 309,245,750 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 91 | lean | def avgu : ℤ × ℤ → ℤ
| (x, y) := (x + y)/2
#eval avgu (10,6) -- This displays 8. |
0a3c0216f331ffb947a07ebdbdcad9379078f835 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/algebra/category/Group/colimits.lean | 037d3b1a50afb1663dbb597453fa303a3cf9696d | [
"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 | 9,697 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import algebra.category.Group.preadditive
import group_theory.quotient_group
import category_theory.limits.concrete_category
import category_theory.limits.shapes.kernels
import category_theory.limits.shapes.concrete_category
/-!
# The category of additive commutative groups has all colimits.
This file uses a "pre-automated" approach, just as for `Mon/colimits.lean`.
It is a very uniform approach, that conceivably could be synthesised directly
by a tactic that analyses the shape of `add_comm_group` and `monoid_hom`.
TODO:
In fact, in `AddCommGroup` there is a much nicer model of colimits as quotients
of finitely supported functions, and we really should implement this as well (or instead).
-/
universes u v
open category_theory
open category_theory.limits
-- [ROBOT VOICE]:
-- You should pretend for now that this file was automatically generated.
-- It follows the same template as colimits in Mon.
namespace AddCommGroup.colimits
/-!
We build the colimit of a diagram in `AddCommGroup` by constructing the
free group on the disjoint union of all the abelian groups in the diagram,
then taking the quotient by the abelian group laws within each abelian group,
and the identifications given by the morphisms in the diagram.
-/
variables {J : Type v} [small_category J] (F : J ⥤ AddCommGroup.{v})
/--
An inductive type representing all group expressions (without relations)
on a collection of types indexed by the objects of `J`.
-/
inductive prequotient
-- There's always `of`
| of : Π (j : J) (x : F.obj j), prequotient
-- Then one generator for each operation
| zero : prequotient
| neg : prequotient → prequotient
| add : prequotient → prequotient → prequotient
instance : inhabited (prequotient F) := ⟨prequotient.zero⟩
open prequotient
/--
The relation on `prequotient` saying when two expressions are equal
because of the abelian group laws, or
because one element is mapped to another by a morphism in the diagram.
-/
inductive relation : prequotient F → prequotient F → Prop
-- Make it an equivalence relation:
| refl : Π (x), relation x x
| symm : Π (x y) (h : relation x y), relation y x
| trans : Π (x y z) (h : relation x y) (k : relation y z), relation x z
-- There's always a `map` relation
| map : Π (j j' : J) (f : j ⟶ j') (x : F.obj j), relation (of j' (F.map f x)) (of j x)
-- Then one relation per operation, describing the interaction with `of`
| zero : Π (j), relation (of j 0) zero
| neg : Π (j) (x : F.obj j), relation (of j (-x)) (neg (of j x))
| add : Π (j) (x y : F.obj j), relation (of j (x + y)) (add (of j x) (of j y))
-- Then one relation per argument of each operation
| neg_1 : Π (x x') (r : relation x x'), relation (neg x) (neg x')
| add_1 : Π (x x' y) (r : relation x x'), relation (add x y) (add x' y)
| add_2 : Π (x y y') (r : relation y y'), relation (add x y) (add x y')
-- And one relation per axiom
| zero_add : Π (x), relation (add zero x) x
| add_zero : Π (x), relation (add x zero) x
| add_left_neg : Π (x), relation (add (neg x) x) zero
| add_comm : Π (x y), relation (add x y) (add y x)
| add_assoc : Π (x y z), relation (add (add x y) z) (add x (add y z))
/--
The setoid corresponding to group expressions modulo abelian group relations and identifications.
-/
def colimit_setoid : setoid (prequotient F) :=
{ r := relation F, iseqv := ⟨relation.refl, relation.symm, relation.trans⟩ }
attribute [instance] colimit_setoid
/--
The underlying type of the colimit of a diagram in `AddCommGroup`.
-/
@[derive inhabited]
def colimit_type : Type v := quotient (colimit_setoid F)
instance : add_comm_group (colimit_type F) :=
{ zero :=
begin
exact quot.mk _ zero
end,
neg :=
begin
fapply @quot.lift,
{ intro x,
exact quot.mk _ (neg x) },
{ intros x x' r,
apply quot.sound,
exact relation.neg_1 _ _ r },
end,
add :=
begin
fapply @quot.lift _ _ ((colimit_type F) → (colimit_type F)),
{ intro x,
fapply @quot.lift,
{ intro y,
exact quot.mk _ (add x y) },
{ intros y y' r,
apply quot.sound,
exact relation.add_2 _ _ _ r } },
{ intros x x' r,
funext y,
induction y,
dsimp,
apply quot.sound,
{ exact relation.add_1 _ _ _ r },
{ refl } },
end,
zero_add := λ x,
begin
induction x,
dsimp,
apply quot.sound,
apply relation.zero_add,
refl,
end,
add_zero := λ x,
begin
induction x,
dsimp,
apply quot.sound,
apply relation.add_zero,
refl,
end,
add_left_neg := λ x,
begin
induction x,
dsimp,
apply quot.sound,
apply relation.add_left_neg,
refl,
end,
add_comm := λ x y,
begin
induction x,
induction y,
dsimp,
apply quot.sound,
apply relation.add_comm,
refl,
refl,
end,
add_assoc := λ x y z,
begin
induction x,
induction y,
induction z,
dsimp,
apply quot.sound,
apply relation.add_assoc,
refl,
refl,
refl,
end, }
@[simp] lemma quot_zero : quot.mk setoid.r zero = (0 : colimit_type F) := rfl
@[simp] lemma quot_neg (x) :
quot.mk setoid.r (neg x) = (-(quot.mk setoid.r x) : colimit_type F) := rfl
@[simp] lemma quot_add (x y) :
quot.mk setoid.r (add x y) = ((quot.mk setoid.r x) + (quot.mk setoid.r y) : colimit_type F) := rfl
/-- The bundled abelian group giving the colimit of a diagram. -/
def colimit : AddCommGroup := AddCommGroup.of (colimit_type F)
/-- The function from a given abelian group in the diagram to the colimit abelian group. -/
def cocone_fun (j : J) (x : F.obj j) : colimit_type F :=
quot.mk _ (of j x)
/-- The group homomorphism from a given abelian group in the diagram to the colimit abelian
group. -/
def cocone_morphism (j : J) : F.obj j ⟶ colimit F :=
{ to_fun := cocone_fun F j,
map_zero' := by apply quot.sound; apply relation.zero,
map_add' := by intros; apply quot.sound; apply relation.add }
@[simp] lemma cocone_naturality {j j' : J} (f : j ⟶ j') :
F.map f ≫ (cocone_morphism F j') = cocone_morphism F j :=
begin
ext,
apply quot.sound,
apply relation.map,
end
@[simp] lemma cocone_naturality_components (j j' : J) (f : j ⟶ j') (x : F.obj j):
(cocone_morphism F j') (F.map f x) = (cocone_morphism F j) x :=
by { rw ←cocone_naturality F f, refl }
/-- The cocone over the proposed colimit abelian group. -/
def colimit_cocone : cocone F :=
{ X := colimit F,
ι :=
{ app := cocone_morphism F } }.
/-- The function from the free abelian group on the diagram to the cone point of any other
cocone. -/
@[simp] def desc_fun_lift (s : cocone F) : prequotient F → s.X
| (of j x) := (s.ι.app j) x
| zero := 0
| (neg x) := -(desc_fun_lift x)
| (add x y) := desc_fun_lift x + desc_fun_lift y
/-- The function from the colimit abelian group to the cone point of any other cocone. -/
def desc_fun (s : cocone F) : colimit_type F → s.X :=
begin
fapply quot.lift,
{ exact desc_fun_lift F s },
{ intros x y r,
induction r; try { dsimp },
-- refl
{ refl },
-- symm
{ exact r_ih.symm },
-- trans
{ exact eq.trans r_ih_h r_ih_k },
-- map
{ simp, },
-- zero
{ simp, },
-- neg
{ simp, },
-- add
{ simp, },
-- neg_1
{ rw r_ih, },
-- add_1
{ rw r_ih, },
-- add_2
{ rw r_ih, },
-- zero_add
{ rw zero_add, },
-- add_zero
{ rw add_zero, },
-- add_left_neg
{ rw add_left_neg, },
-- add_comm
{ rw add_comm, },
-- add_assoc
{ rw add_assoc, } }
end
/-- The group homomorphism from the colimit abelian group to the cone point of any other cocone. -/
def desc_morphism (s : cocone F) : colimit F ⟶ s.X :=
{ to_fun := desc_fun F s,
map_zero' := rfl,
map_add' := λ x y, by { induction x; induction y; refl }, }
/-- Evidence that the proposed colimit is the colimit. -/
def colimit_cocone_is_colimit : is_colimit (colimit_cocone F) :=
{ desc := λ s, desc_morphism F s,
uniq' := λ s m w,
begin
ext,
induction x,
induction x,
{ have w' := congr_fun (congr_arg (λ f : F.obj x_j ⟶ s.X, (f : F.obj x_j → s.X)) (w x_j)) x_x,
erw w',
refl, },
{ simp *, },
{ simp *, },
{ simp *, },
refl
end }.
instance has_colimits_AddCommGroup : has_colimits AddCommGroup :=
{ has_colimits_of_shape := λ J 𝒥, by exactI
{ has_colimit := λ F, has_colimit.mk
{ cocone := colimit_cocone F,
is_colimit := colimit_cocone_is_colimit F } } }
end AddCommGroup.colimits
namespace AddCommGroup
open quotient_add_group
/--
The categorical cokernel of a morphism in `AddCommGroup`
agrees with the usual group-theoretical quotient.
-/
noncomputable def cokernel_iso_quotient {G H : AddCommGroup.{u}} (f : G ⟶ H) :
cokernel f ≅ AddCommGroup.of (H ⧸ (add_monoid_hom.range f)) :=
{ hom := cokernel.desc f (mk' _)
(by { ext, apply quotient.sound, fsplit, exact -x,
simp only [add_zero, add_monoid_hom.map_neg], }),
inv := quotient_add_group.lift _ (cokernel.π f)
(by { intros x H_1, cases H_1, induction H_1_h,
simp only [cokernel.condition_apply, zero_apply]}),
-- obviously can take care of the next goals, but it is really slow
hom_inv_id' := begin
ext1, simp only [coequalizer_as_cokernel, category.comp_id, cokernel.π_desc_assoc], ext1, refl,
end,
inv_hom_id' := begin
ext x : 2,
simp only [colimit.ι_desc_apply, id_apply, lift_mk, mk'_apply,
cofork.of_π_ι_app, comp_apply, add_monoid_hom.comp_apply],
end, }
end AddCommGroup
|
192b04c4049bbaa4ca4250b20b1d47efabebd4eb | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/topology/algebra/ordered/basic.lean | 6950c7f3e87fcdf7f9e9d10d4ffc74d084456ad7 | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 174,127 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Yury Kudryashov
-/
import tactic.tfae
import algebra.group_with_zero.power
import data.set.intervals.pi
import topology.algebra.group
import order.filter.interval
/-!
# Theory of topology on ordered spaces
## Main definitions
The order topology on an ordered space is the topology generated by all open intervals (or
equivalently by those of the form `(-∞, a)` and `(b, +∞)`). We define it as `preorder.topology α`.
However, we do *not* register it as an instance (as many existing ordered types already have
topologies, which would be equal but not definitionally equal to `preorder.topology α`). Instead,
we introduce a class `order_topology α` (which is a `Prop`, also known as a mixin) saying that on
the type `α` having already a topological space structure and a preorder structure, the topological
structure is equal to the order topology.
We also introduce another (mixin) class `order_closed_topology α` saying that the set of points
`(x, y)` with `x ≤ y` is closed in the product space. This is automatically satisfied on a linear
order with the order topology.
We prove many basic properties of such topologies.
## Main statements
This file contains the proofs of the following facts. For exact requirements
(`order_closed_topology` vs `order_topology`, `preorder` vs `partial_order` vs `linear_order` etc)
see their statements.
### Open / closed sets
* `is_open_lt` : if `f` and `g` are continuous functions, then `{x | f x < g x}` is open;
* `is_open_Iio`, `is_open_Ioi`, `is_open_Ioo` : open intervals are open;
* `is_closed_le` : if `f` and `g` are continuous functions, then `{x | f x ≤ g x}` is closed;
* `is_closed_Iic`, `is_closed_Ici`, `is_closed_Icc` : closed intervals are closed;
* `frontier_le_subset_eq`, `frontier_lt_subset_eq` : frontiers of both `{x | f x ≤ g x}`
and `{x | f x < g x}` are included by `{x | f x = g x}`;
* `exists_Ioc_subset_of_mem_nhds`, `exists_Ico_subset_of_mem_nhds` : if `x < y`, then any
neighborhood of `x` includes an interval `[x, z)` for some `z ∈ (x, y]`, and any neighborhood
of `y` includes an interval `(z, y]` for some `z ∈ [x, y)`.
### Convergence and inequalities
* `le_of_tendsto_of_tendsto` : if `f` converges to `a`, `g` converges to `b`, and eventually
`f x ≤ g x`, then `a ≤ b`
* `le_of_tendsto`, `ge_of_tendsto` : if `f` converges to `a` and eventually `f x ≤ b`
(resp., `b ≤ f x`), then `a ≤ b` (resp., `b ≤ a); we also provide primed versions
that assume the inequalities to hold for all `x`.
### Min, max, `Sup` and `Inf`
* `continuous.min`, `continuous.max`: pointwise `min`/`max` of two continuous functions is
continuous.
* `tendsto.min`, `tendsto.max` : if `f` tends to `a` and `g` tends to `b`, then their pointwise
`min`/`max` tend to `min a b` and `max a b`, respectively.
* `tendsto_of_tendsto_of_tendsto_of_le_of_le` : theorem known as squeeze theorem,
sandwich theorem, theorem of Carabinieri, and two policemen (and a drunk) theorem; if `g` and `h`
both converge to `a`, and eventually `g x ≤ f x ≤ h x`, then `f` converges to `a`.
### Connected sets and Intermediate Value Theorem
* `is_preconnected_I??` : all intervals `I??` are preconnected,
* `is_preconnected.intermediate_value`, `intermediate_value_univ` : Intermediate Value Theorem for
connected sets and connected spaces, respectively;
* `intermediate_value_Icc`, `intermediate_value_Icc'`: Intermediate Value Theorem for functions
on closed intervals.
### Miscellaneous facts
* `is_compact.exists_forall_le`, `is_compact.exists_forall_ge` : extreme value theorem, a continuous
function on a compact set takes its minimum and maximum values.
* `is_closed.Icc_subset_of_forall_mem_nhds_within` : “Continuous induction” principle;
if `s ∩ [a, b]` is closed, `a ∈ s`, and for each `x ∈ [a, b) ∩ s` some of its right neighborhoods
is included `s`, then `[a, b] ⊆ s`.
* `is_closed.Icc_subset_of_forall_exists_gt`, `is_closed.mem_of_ge_of_forall_exists_gt` : two
other versions of the “continuous induction” principle.
## Implementation
We do _not_ register the order topology as an instance on a preorder (or even on a linear order).
Indeed, on many such spaces, a topology has already been constructed in a different way (think
of the discrete spaces `ℕ` or `ℤ`, or `ℝ` that could inherit a topology as the completion of `ℚ`),
and is in general not defeq to the one generated by the intervals. We make it available as a
definition `preorder.topology α` though, that can be registered as an instance when necessary, or
for specific types.
-/
open classical set filter topological_space
open function
open_locale topological_space classical filter
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
/-- A topology on a set which is both a topological space and a preorder is _order-closed_ if the
set of points `(x, y)` with `x ≤ y` is closed in the product space. We introduce this as a mixin.
This property is satisfied for the order topology on a linear order, but it can be satisfied more
generally, and suffices to derive many interesting properties relating order and topology. -/
class order_closed_topology (α : Type*) [topological_space α] [preorder α] : Prop :=
(is_closed_le' : is_closed {p:α×α | p.1 ≤ p.2})
instance : Π [topological_space α], topological_space (order_dual α) := id
@[to_additive]
instance [topological_space α] [has_mul α] [h : has_continuous_mul α] :
has_continuous_mul (order_dual α) := h
section order_closed_topology
section preorder
variables [topological_space α] [preorder α] [t : order_closed_topology α]
include t
lemma is_closed_le_prod : is_closed {p : α × α | p.1 ≤ p.2} :=
t.is_closed_le'
lemma is_closed_le [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) :
is_closed {b | f b ≤ g b} :=
continuous_iff_is_closed.mp (hf.prod_mk hg) _ is_closed_le_prod
lemma is_closed_le' (a : α) : is_closed {b | b ≤ a} :=
is_closed_le continuous_id continuous_const
lemma is_closed_Iic {a : α} : is_closed (Iic a) :=
is_closed_le' a
lemma is_closed_ge' (a : α) : is_closed {b | a ≤ b} :=
is_closed_le continuous_const continuous_id
lemma is_closed_Ici {a : α} : is_closed (Ici a) :=
is_closed_ge' a
instance : order_closed_topology (order_dual α) :=
⟨(@order_closed_topology.is_closed_le' α _ _ _).preimage continuous_swap⟩
lemma is_closed_Icc {a b : α} : is_closed (Icc a b) :=
is_closed.inter is_closed_Ici is_closed_Iic
@[simp] lemma closure_Icc (a b : α) : closure (Icc a b) = Icc a b :=
is_closed_Icc.closure_eq
@[simp] lemma closure_Iic (a : α) : closure (Iic a) = Iic a :=
is_closed_Iic.closure_eq
@[simp] lemma closure_Ici (a : α) : closure (Ici a) = Ici a :=
is_closed_Ici.closure_eq
lemma le_of_tendsto_of_tendsto {f g : β → α} {b : filter β} {a₁ a₂ : α} [ne_bot b]
(hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) (h : f ≤ᶠ[b] g) :
a₁ ≤ a₂ :=
have tendsto (λb, (f b, g b)) b (𝓝 (a₁, a₂)),
by rw [nhds_prod_eq]; exact hf.prod_mk hg,
show (a₁, a₂) ∈ {p:α×α | p.1 ≤ p.2},
from t.is_closed_le'.mem_of_tendsto this h
lemma le_of_tendsto_of_tendsto' {f g : β → α} {b : filter β} {a₁ a₂ : α} [ne_bot b]
(hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) (h : ∀ x, f x ≤ g x) :
a₁ ≤ a₂ :=
le_of_tendsto_of_tendsto hf hg (eventually_of_forall h)
lemma le_of_tendsto {f : β → α} {a b : α} {x : filter β}
[ne_bot x] (lim : tendsto f x (𝓝 a)) (h : ∀ᶠ c in x, f c ≤ b) : a ≤ b :=
le_of_tendsto_of_tendsto lim tendsto_const_nhds h
lemma le_of_tendsto' {f : β → α} {a b : α} {x : filter β}
[ne_bot x] (lim : tendsto f x (𝓝 a)) (h : ∀ c, f c ≤ b) : a ≤ b :=
le_of_tendsto lim (eventually_of_forall h)
lemma ge_of_tendsto {f : β → α} {a b : α} {x : filter β} [ne_bot x]
(lim : tendsto f x (𝓝 a)) (h : ∀ᶠ c in x, b ≤ f c) : b ≤ a :=
le_of_tendsto_of_tendsto tendsto_const_nhds lim h
lemma ge_of_tendsto' {f : β → α} {a b : α} {x : filter β} [ne_bot x]
(lim : tendsto f x (𝓝 a)) (h : ∀ c, b ≤ f c) : b ≤ a :=
ge_of_tendsto lim (eventually_of_forall h)
@[simp]
lemma closure_le_eq [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) :
closure {b | f b ≤ g b} = {b | f b ≤ g b} :=
(is_closed_le hf hg).closure_eq
lemma closure_lt_subset_le [topological_space β] {f g : β → α} (hf : continuous f)
(hg : continuous g) :
closure {b | f b < g b} ⊆ {b | f b ≤ g b} :=
by { rw [←closure_le_eq hf hg], exact closure_mono (λ b, le_of_lt) }
lemma continuous_within_at.closure_le [topological_space β]
{f g : β → α} {s : set β} {x : β} (hx : x ∈ closure s)
(hf : continuous_within_at f s x)
(hg : continuous_within_at g s x)
(h : ∀ y ∈ s, f y ≤ g y) : f x ≤ g x :=
show (f x, g x) ∈ {p : α × α | p.1 ≤ p.2},
from order_closed_topology.is_closed_le'.closure_subset ((hf.prod hg).mem_closure hx h)
/-- If `s` is a closed set and two functions `f` and `g` are continuous on `s`,
then the set `{x ∈ s | f x ≤ g x}` is a closed set. -/
lemma is_closed.is_closed_le [topological_space β] {f g : β → α} {s : set β} (hs : is_closed s)
(hf : continuous_on f s) (hg : continuous_on g s) :
is_closed {x ∈ s | f x ≤ g x} :=
(hf.prod hg).preimage_closed_of_closed hs order_closed_topology.is_closed_le'
omit t
lemma nhds_within_Ici_ne_bot {a b : α} (H₂ : a ≤ b) :
ne_bot (𝓝[Ici a] b) :=
nhds_within_ne_bot_of_mem H₂
@[instance] lemma nhds_within_Ici_self_ne_bot (a : α) :
ne_bot (𝓝[Ici a] a) :=
nhds_within_Ici_ne_bot (le_refl a)
lemma nhds_within_Iic_ne_bot {a b : α} (H : a ≤ b) :
ne_bot (𝓝[Iic b] a) :=
nhds_within_ne_bot_of_mem H
@[instance] lemma nhds_within_Iic_self_ne_bot (a : α) :
ne_bot (𝓝[Iic a] a) :=
nhds_within_Iic_ne_bot (le_refl a)
end preorder
section partial_order
variables [topological_space α] [partial_order α] [t : order_closed_topology α]
include t
private lemma is_closed_eq_aux : is_closed {p : α × α | p.1 = p.2} :=
by simp only [le_antisymm_iff];
exact is_closed.inter t.is_closed_le' (is_closed_le continuous_snd continuous_fst)
@[priority 90] -- see Note [lower instance priority]
instance order_closed_topology.to_t2_space : t2_space α :=
{ t2 :=
have is_open {p : α × α | p.1 ≠ p.2} := is_closed_eq_aux.is_open_compl,
assume a b h,
let ⟨u, v, hu, hv, ha, hb, h⟩ := is_open_prod_iff.mp this a b h in
⟨u, v, hu, hv, ha, hb,
set.eq_empty_iff_forall_not_mem.2 $ assume a ⟨h₁, h₂⟩,
have a ≠ a, from @h (a, a) ⟨h₁, h₂⟩,
this rfl⟩ }
end partial_order
section linear_order
variables [topological_space α] [linear_order α] [order_closed_topology α]
lemma is_open_lt_prod : is_open {p : α × α | p.1 < p.2} :=
by { simp_rw [← is_closed_compl_iff, compl_set_of, not_lt],
exact is_closed_le continuous_snd continuous_fst }
lemma is_open_lt [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) :
is_open {b | f b < g b} :=
by simp [lt_iff_not_ge, -not_le]; exact (is_closed_le hg hf).is_open_compl
variables {a b : α}
lemma is_open_Iio : is_open (Iio a) :=
is_open_lt continuous_id continuous_const
lemma is_open_Ioi : is_open (Ioi a) :=
is_open_lt continuous_const continuous_id
lemma is_open_Ioo : is_open (Ioo a b) :=
is_open.inter is_open_Ioi is_open_Iio
@[simp] lemma interior_Ioi : interior (Ioi a) = Ioi a :=
is_open_Ioi.interior_eq
@[simp] lemma interior_Iio : interior (Iio a) = Iio a :=
is_open_Iio.interior_eq
@[simp] lemma interior_Ioo : interior (Ioo a b) = Ioo a b :=
is_open_Ioo.interior_eq
lemma eventually_le_of_tendsto_lt {l : filter γ} {f : γ → α} {u v : α} (hv : v < u)
(h : tendsto f l (𝓝 v)) : ∀ᶠ a in l, f a ≤ u :=
eventually.mono (tendsto_nhds.1 h (< u) is_open_Iio hv) (λ v, le_of_lt)
lemma eventually_ge_of_tendsto_gt {l : filter γ} {f : γ → α} {u v : α} (hv : u < v)
(h : tendsto f l (𝓝 v)) : ∀ᶠ a in l, u ≤ f a :=
eventually.mono (tendsto_nhds.1 h (> u) is_open_Ioi hv) (λ v, le_of_lt)
variables [topological_space γ]
/-- Intermediate value theorem for two functions: if `f` and `g` are two continuous functions
on a preconnected space and `f a ≤ g a` and `g b ≤ f b`, then for some `x` we have `f x = g x`. -/
lemma intermediate_value_univ₂ [preconnected_space γ] {a b : γ} {f g : γ → α} (hf : continuous f)
(hg : continuous g) (ha : f a ≤ g a) (hb : g b ≤ f b) :
∃ x, f x = g x :=
begin
obtain ⟨x, h, hfg, hgf⟩ : (univ ∩ {x | f x ≤ g x ∧ g x ≤ f x}).nonempty,
from is_preconnected_closed_iff.1 preconnected_space.is_preconnected_univ _ _
(is_closed_le hf hg) (is_closed_le hg hf) (λ x hx, le_total _ _) ⟨a, trivial, ha⟩
⟨b, trivial, hb⟩,
exact ⟨x, le_antisymm hfg hgf⟩
end
lemma intermediate_value_univ₂_eventually₁ [preconnected_space γ] {a : γ} {l : filter γ} [ne_bot l]
{f g : γ → α} (hf : continuous f) (hg : continuous g) (ha : f a ≤ g a) (he : g ≤ᶠ[l] f) :
∃ x, f x = g x :=
let ⟨c, hc⟩ := he.frequently.exists in intermediate_value_univ₂ hf hg ha hc
lemma intermediate_value_univ₂_eventually₂ [preconnected_space γ] {l₁ l₂ : filter γ}
[ne_bot l₁] [ne_bot l₂] {f g : γ → α} (hf : continuous f) (hg : continuous g)
(he₁ : f ≤ᶠ[l₁] g ) (he₂ : g ≤ᶠ[l₂] f) :
∃ x, f x = g x :=
let ⟨c₁, hc₁⟩ := he₁.frequently.exists, ⟨c₂, hc₂⟩ := he₂.frequently.exists in
intermediate_value_univ₂ hf hg hc₁ hc₂
/-- Intermediate value theorem for two functions: if `f` and `g` are two functions continuous
on a preconnected set `s` and for some `a b ∈ s` we have `f a ≤ g a` and `g b ≤ f b`,
then for some `x ∈ s` we have `f x = g x`. -/
lemma is_preconnected.intermediate_value₂ {s : set γ} (hs : is_preconnected s)
{a b : γ} (ha : a ∈ s) (hb : b ∈ s) {f g : γ → α}
(hf : continuous_on f s) (hg : continuous_on g s) (ha' : f a ≤ g a) (hb' : g b ≤ f b) :
∃ x ∈ s, f x = g x :=
let ⟨x, hx⟩ := @intermediate_value_univ₂ α s _ _ _ _ (subtype.preconnected_space hs) ⟨a, ha⟩ ⟨b, hb⟩
_ _ (continuous_on_iff_continuous_restrict.1 hf) (continuous_on_iff_continuous_restrict.1 hg)
ha' hb'
in ⟨x, x.2, hx⟩
lemma is_preconnected.intermediate_value₂_eventually₁ {s : set γ} (hs : is_preconnected s)
{a : γ} {l : filter γ} (ha : a ∈ s) [ne_bot l] (hl : l ≤ 𝓟 s) {f g : γ → α}
(hf : continuous_on f s) (hg : continuous_on g s) (ha' : f a ≤ g a) (he : g ≤ᶠ[l] f) :
∃ x ∈ s, f x = g x :=
begin
rw continuous_on_iff_continuous_restrict at hf hg,
obtain ⟨b, h⟩ := @intermediate_value_univ₂_eventually₁ _ _ _ _ _ _ (subtype.preconnected_space hs)
⟨a, ha⟩ _ (comap_coe_ne_bot_of_le_principal hl) _ _ hf hg ha' (eventually_comap' he),
exact ⟨b, b.prop, h⟩,
end
lemma is_preconnected.intermediate_value₂_eventually₂ {s : set γ} (hs : is_preconnected s)
{l₁ l₂ : filter γ} [ne_bot l₁] [ne_bot l₂] (hl₁ : l₁ ≤ 𝓟 s) (hl₂ : l₂ ≤ 𝓟 s) {f g : γ → α}
(hf : continuous_on f s) (hg : continuous_on g s) (he₁ : f ≤ᶠ[l₁] g) (he₂ : g ≤ᶠ[l₂] f) :
∃ x ∈ s, f x = g x :=
begin
rw continuous_on_iff_continuous_restrict at hf hg,
obtain ⟨b, h⟩ := @intermediate_value_univ₂_eventually₂ _ _ _ _ _ _ (subtype.preconnected_space hs)
_ _ (comap_coe_ne_bot_of_le_principal hl₁) (comap_coe_ne_bot_of_le_principal hl₂)
_ _ hf hg (eventually_comap' he₁) (eventually_comap' he₂),
exact ⟨b, b.prop, h⟩,
end
/-- Intermediate Value Theorem for continuous functions on connected sets. -/
lemma is_preconnected.intermediate_value {s : set γ} (hs : is_preconnected s)
{a b : γ} (ha : a ∈ s) (hb : b ∈ s) {f : γ → α} (hf : continuous_on f s) :
Icc (f a) (f b) ⊆ f '' s :=
λ x hx, mem_image_iff_bex.2 $ hs.intermediate_value₂ ha hb hf continuous_on_const hx.1 hx.2
lemma is_preconnected.intermediate_value_Ico {s : set γ} (hs : is_preconnected s)
{a : γ} {l : filter γ} (ha : a ∈ s) [ne_bot l] (hl : l ≤ 𝓟 s) {f : γ → α}
(hf : continuous_on f s) {v : α} (ht : tendsto f l (𝓝 v)) :
Ico (f a) v ⊆ f '' s :=
λ y h, bex_def.1 $ hs.intermediate_value₂_eventually₁ ha hl
hf continuous_on_const h.1 (eventually_ge_of_tendsto_gt h.2 ht)
lemma is_preconnected.intermediate_value_Ioc {s : set γ} (hs : is_preconnected s)
{a : γ} {l : filter γ} (ha : a ∈ s) [ne_bot l] (hl : l ≤ 𝓟 s) {f : γ → α}
(hf : continuous_on f s) {v : α} (ht : tendsto f l (𝓝 v)) :
Ioc v (f a) ⊆ f '' s :=
λ y h, bex_def.1 $ bex.imp_right (λ x _, eq.symm) $ hs.intermediate_value₂_eventually₁ ha hl
continuous_on_const hf h.2 (eventually_le_of_tendsto_lt h.1 ht)
lemma is_preconnected.intermediate_value_Ioo {s : set γ} (hs : is_preconnected s)
{l₁ l₂ : filter γ} [ne_bot l₁] [ne_bot l₂] (hl₁ : l₁ ≤ 𝓟 s) (hl₂ : l₂ ≤ 𝓟 s) {f : γ → α}
(hf : continuous_on f s) {v₁ v₂ : α} (ht₁ : tendsto f l₁ (𝓝 v₁)) (ht₂ : tendsto f l₂ (𝓝 v₂)) :
Ioo v₁ v₂ ⊆ f '' s :=
λ y h, bex_def.1 $ hs.intermediate_value₂_eventually₂ hl₁ hl₂
hf continuous_on_const (eventually_le_of_tendsto_lt h.1 ht₁) (eventually_ge_of_tendsto_gt h.2 ht₂)
lemma is_preconnected.intermediate_value_Ici {s : set γ} (hs : is_preconnected s)
{a : γ} {l : filter γ} (ha : a ∈ s) [ne_bot l] (hl : l ≤ 𝓟 s) {f : γ → α}
(hf : continuous_on f s) (ht : tendsto f l at_top) :
Ici (f a) ⊆ f '' s :=
λ y h, bex_def.1 $ hs.intermediate_value₂_eventually₁ ha hl
hf continuous_on_const h (tendsto_at_top.1 ht y)
lemma is_preconnected.intermediate_value_Iic {s : set γ} (hs : is_preconnected s)
{a : γ} {l : filter γ} (ha : a ∈ s) [ne_bot l] (hl : l ≤ 𝓟 s) {f : γ → α}
(hf : continuous_on f s) (ht : tendsto f l at_bot) :
Iic (f a) ⊆ f '' s :=
λ y h, bex_def.1 $ bex.imp_right (λ x _, eq.symm) $ hs.intermediate_value₂_eventually₁ ha hl
continuous_on_const hf h (tendsto_at_bot.1 ht y)
lemma is_preconnected.intermediate_value_Ioi {s : set γ} (hs : is_preconnected s)
{l₁ l₂ : filter γ} [ne_bot l₁] [ne_bot l₂] (hl₁ : l₁ ≤ 𝓟 s) (hl₂ : l₂ ≤ 𝓟 s) {f : γ → α}
(hf : continuous_on f s) {v : α} (ht₁ : tendsto f l₁ (𝓝 v)) (ht₂ : tendsto f l₂ at_top) :
Ioi v ⊆ f '' s :=
λ y h, bex_def.1 $ hs.intermediate_value₂_eventually₂ hl₁ hl₂
hf continuous_on_const (eventually_le_of_tendsto_lt h ht₁) (tendsto_at_top.1 ht₂ y)
lemma is_preconnected.intermediate_value_Iio {s : set γ} (hs : is_preconnected s)
{l₁ l₂ : filter γ} [ne_bot l₁] [ne_bot l₂] (hl₁ : l₁ ≤ 𝓟 s) (hl₂ : l₂ ≤ 𝓟 s) {f : γ → α}
(hf : continuous_on f s) {v : α} (ht₁ : tendsto f l₁ at_bot) (ht₂ : tendsto f l₂ (𝓝 v)) :
Iio v ⊆ f '' s :=
λ y h, bex_def.1 $ hs.intermediate_value₂_eventually₂ hl₁ hl₂
hf continuous_on_const (tendsto_at_bot.1 ht₁ y) (eventually_ge_of_tendsto_gt h ht₂)
lemma is_preconnected.intermediate_value_Iii {s : set γ} (hs : is_preconnected s)
{l₁ l₂ : filter γ} [ne_bot l₁] [ne_bot l₂] (hl₁ : l₁ ≤ 𝓟 s) (hl₂ : l₂ ≤ 𝓟 s) {f : γ → α}
(hf : continuous_on f s) (ht₁ : tendsto f l₁ at_bot) (ht₂ : tendsto f l₂ at_top) :
univ ⊆ f '' s :=
λ y h, bex_def.1 $ hs.intermediate_value₂_eventually₂ hl₁ hl₂
hf continuous_on_const (tendsto_at_bot.1 ht₁ y) (tendsto_at_top.1 ht₂ y)
/-- Intermediate Value Theorem for continuous functions on connected spaces. -/
lemma intermediate_value_univ [preconnected_space γ] (a b : γ) {f : γ → α} (hf : continuous f) :
Icc (f a) (f b) ⊆ range f :=
λ x hx, intermediate_value_univ₂ hf continuous_const hx.1 hx.2
/-- Intermediate Value Theorem for continuous functions on connected spaces. -/
lemma mem_range_of_exists_le_of_exists_ge [preconnected_space γ] {c : α} {f : γ → α}
(hf : continuous f) (h₁ : ∃ a, f a ≤ c) (h₂ : ∃ b, c ≤ f b) :
c ∈ range f :=
let ⟨a, ha⟩ := h₁, ⟨b, hb⟩ := h₂ in intermediate_value_univ a b hf ⟨ha, hb⟩
/-- If a preconnected set contains endpoints of an interval, then it includes the whole interval. -/
lemma is_preconnected.Icc_subset {s : set α} (hs : is_preconnected s)
{a b : α} (ha : a ∈ s) (hb : b ∈ s) :
Icc a b ⊆ s :=
by simpa only [image_id] using hs.intermediate_value ha hb continuous_on_id
/-- If a preconnected set contains endpoints of an interval, then it includes the whole interval. -/
lemma is_connected.Icc_subset {s : set α} (hs : is_connected s)
{a b : α} (ha : a ∈ s) (hb : b ∈ s) :
Icc a b ⊆ s :=
hs.2.Icc_subset ha hb
/-- If preconnected set in a linear order space is unbounded below and above, then it is the whole
space. -/
lemma is_preconnected.eq_univ_of_unbounded {s : set α} (hs : is_preconnected s) (hb : ¬bdd_below s)
(ha : ¬bdd_above s) :
s = univ :=
begin
refine eq_univ_of_forall (λ x, _),
obtain ⟨y, ys, hy⟩ : ∃ y ∈ s, y < x := not_bdd_below_iff.1 hb x,
obtain ⟨z, zs, hz⟩ : ∃ z ∈ s, x < z := not_bdd_above_iff.1 ha x,
exact hs.Icc_subset ys zs ⟨le_of_lt hy, le_of_lt hz⟩
end
/-!
### Neighborhoods to the left and to the right on an `order_closed_topology`
Limits to the left and to the right of real functions are defined in terms of neighborhoods to
the left and to the right, either open or closed, i.e., members of `𝓝[Ioi a] a` and
`𝓝[Ici a] a` on the right, and similarly on the left. Here we simply prove that all
right-neighborhoods of a point are equal, and we'll prove later other useful characterizations which
require the stronger hypothesis `order_topology α` -/
/-!
#### Right neighborhoods, point excluded
-/
lemma Ioo_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) :
Ioo a c ∈ 𝓝[Ioi b] b :=
mem_nhds_within.2 ⟨Iio c, is_open_Iio, H.2,
by rw [inter_comm, Ioi_inter_Iio]; exact Ioo_subset_Ioo_left H.1⟩
lemma Ioc_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) :
Ioc a c ∈ 𝓝[Ioi b] b :=
mem_sets_of_superset (Ioo_mem_nhds_within_Ioi H) Ioo_subset_Ioc_self
lemma Ico_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) :
Ico a c ∈ 𝓝[Ioi b] b :=
mem_sets_of_superset (Ioo_mem_nhds_within_Ioi H) Ioo_subset_Ico_self
lemma Icc_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) :
Icc a c ∈ 𝓝[Ioi b] b :=
mem_sets_of_superset (Ioo_mem_nhds_within_Ioi H) Ioo_subset_Icc_self
@[simp] lemma nhds_within_Ioc_eq_nhds_within_Ioi {a b : α} (h : a < b) :
𝓝[Ioc a b] a = 𝓝[Ioi a] a :=
le_antisymm (nhds_within_mono _ Ioc_subset_Ioi_self) $
nhds_within_le_of_mem $ Ioc_mem_nhds_within_Ioi $ left_mem_Ico.2 h
@[simp] lemma nhds_within_Ioo_eq_nhds_within_Ioi {a b : α} (h : a < b) :
𝓝[Ioo a b] a = 𝓝[Ioi a] a :=
le_antisymm (nhds_within_mono _ Ioo_subset_Ioi_self) $
nhds_within_le_of_mem $ Ioo_mem_nhds_within_Ioi $ left_mem_Ico.2 h
@[simp]
lemma continuous_within_at_Ioc_iff_Ioi [topological_space β] {a b : α} {f : α → β} (h : a < b) :
continuous_within_at f (Ioc a b) a ↔ continuous_within_at f (Ioi a) a :=
by simp only [continuous_within_at, nhds_within_Ioc_eq_nhds_within_Ioi h]
@[simp]
lemma continuous_within_at_Ioo_iff_Ioi [topological_space β] {a b : α} {f : α → β} (h : a < b) :
continuous_within_at f (Ioo a b) a ↔ continuous_within_at f (Ioi a) a :=
by simp only [continuous_within_at, nhds_within_Ioo_eq_nhds_within_Ioi h]
/-!
#### Left neighborhoods, point excluded
-/
lemma Ioo_mem_nhds_within_Iio {a b c : α} (H : b ∈ Ioc a c) :
Ioo a c ∈ 𝓝[Iio b] b :=
by simpa only [dual_Ioo] using @Ioo_mem_nhds_within_Ioi (order_dual α) _ _ _ _ _ _ ⟨H.2, H.1⟩
lemma Ico_mem_nhds_within_Iio {a b c : α} (H : b ∈ Ioc a c) :
Ico a c ∈ 𝓝[Iio b] b :=
mem_sets_of_superset (Ioo_mem_nhds_within_Iio H) Ioo_subset_Ico_self
lemma Ioc_mem_nhds_within_Iio {a b c : α} (H : b ∈ Ioc a c) :
Ioc a c ∈ 𝓝[Iio b] b :=
mem_sets_of_superset (Ioo_mem_nhds_within_Iio H) Ioo_subset_Ioc_self
lemma Icc_mem_nhds_within_Iio {a b c : α} (H : b ∈ Ioc a c) :
Icc a c ∈ 𝓝[Iio b] b :=
mem_sets_of_superset (Ioo_mem_nhds_within_Iio H) Ioo_subset_Icc_self
@[simp] lemma nhds_within_Ico_eq_nhds_within_Iio {a b : α} (h : a < b) :
𝓝[Ico a b] b = 𝓝[Iio b] b :=
by simpa only [dual_Ioc] using @nhds_within_Ioc_eq_nhds_within_Ioi (order_dual α) _ _ _ _ _ h
@[simp] lemma nhds_within_Ioo_eq_nhds_within_Iio {a b : α} (h : a < b) :
𝓝[Ioo a b] b = 𝓝[Iio b] b :=
by simpa only [dual_Ioo] using @nhds_within_Ioo_eq_nhds_within_Ioi (order_dual α) _ _ _ _ _ h
@[simp] lemma continuous_within_at_Ico_iff_Iio {a b : α} {f : α → γ} (h : a < b) :
continuous_within_at f (Ico a b) b ↔ continuous_within_at f (Iio b) b :=
by simp only [continuous_within_at, nhds_within_Ico_eq_nhds_within_Iio h]
@[simp] lemma continuous_within_at_Ioo_iff_Iio {a b : α} {f : α → γ} (h : a < b) :
continuous_within_at f (Ioo a b) b ↔ continuous_within_at f (Iio b) b :=
by simp only [continuous_within_at, nhds_within_Ioo_eq_nhds_within_Iio h]
/-!
#### Right neighborhoods, point included
-/
lemma Ioo_mem_nhds_within_Ici {a b c : α} (H : b ∈ Ioo a c) :
Ioo a c ∈ 𝓝[Ici b] b :=
mem_nhds_within_of_mem_nhds $ is_open.mem_nhds is_open_Ioo H
lemma Ioc_mem_nhds_within_Ici {a b c : α} (H : b ∈ Ioo a c) :
Ioc a c ∈ 𝓝[Ici b] b :=
mem_sets_of_superset (Ioo_mem_nhds_within_Ici H) Ioo_subset_Ioc_self
lemma Ico_mem_nhds_within_Ici {a b c : α} (H : b ∈ Ico a c) :
Ico a c ∈ 𝓝[Ici b] b :=
mem_nhds_within.2 ⟨Iio c, is_open_Iio, H.2,
by simp only [inter_comm, Ici_inter_Iio, Ico_subset_Ico_left H.1]⟩
lemma Icc_mem_nhds_within_Ici {a b c : α} (H : b ∈ Ico a c) :
Icc a c ∈ 𝓝[Ici b] b :=
mem_sets_of_superset (Ico_mem_nhds_within_Ici H) Ico_subset_Icc_self
@[simp] lemma nhds_within_Icc_eq_nhds_within_Ici {a b : α} (h : a < b) :
𝓝[Icc a b] a = 𝓝[Ici a] a :=
le_antisymm (nhds_within_mono _ Icc_subset_Ici_self) $
nhds_within_le_of_mem $ Icc_mem_nhds_within_Ici $ left_mem_Ico.2 h
@[simp] lemma nhds_within_Ico_eq_nhds_within_Ici {a b : α} (h : a < b) :
𝓝[Ico a b] a = 𝓝[Ici a] a :=
le_antisymm (nhds_within_mono _ (λ x, and.left)) $
nhds_within_le_of_mem $ Ico_mem_nhds_within_Ici $ left_mem_Ico.2 h
@[simp]
lemma continuous_within_at_Icc_iff_Ici [topological_space β] {a b : α} {f : α → β} (h : a < b) :
continuous_within_at f (Icc a b) a ↔ continuous_within_at f (Ici a) a :=
by simp only [continuous_within_at, nhds_within_Icc_eq_nhds_within_Ici h]
@[simp]
lemma continuous_within_at_Ico_iff_Ici [topological_space β] {a b : α} {f : α → β} (h : a < b) :
continuous_within_at f (Ico a b) a ↔ continuous_within_at f (Ici a) a :=
by simp only [continuous_within_at, nhds_within_Ico_eq_nhds_within_Ici h]
/-!
#### Left neighborhoods, point included
-/
lemma Ioo_mem_nhds_within_Iic {a b c : α} (H : b ∈ Ioo a c) :
Ioo a c ∈ 𝓝[Iic b] b :=
mem_nhds_within_of_mem_nhds $ is_open.mem_nhds is_open_Ioo H
lemma Ico_mem_nhds_within_Iic {a b c : α} (H : b ∈ Ioo a c) :
Ico a c ∈ 𝓝[Iic b] b :=
mem_sets_of_superset (Ioo_mem_nhds_within_Iic H) Ioo_subset_Ico_self
lemma Ioc_mem_nhds_within_Iic {a b c : α} (H : b ∈ Ioc a c) :
Ioc a c ∈ 𝓝[Iic b] b :=
by simpa only [dual_Ico] using @Ico_mem_nhds_within_Ici (order_dual α) _ _ _ _ _ _ ⟨H.2, H.1⟩
lemma Icc_mem_nhds_within_Iic {a b c : α} (H : b ∈ Ioc a c) :
Icc a c ∈ 𝓝[Iic b] b :=
mem_sets_of_superset (Ioc_mem_nhds_within_Iic H) Ioc_subset_Icc_self
@[simp] lemma nhds_within_Icc_eq_nhds_within_Iic {a b : α} (h : a < b) :
𝓝[Icc a b] b = 𝓝[Iic b] b :=
by simpa only [dual_Icc] using @nhds_within_Icc_eq_nhds_within_Ici (order_dual α) _ _ _ _ _ h
@[simp] lemma nhds_within_Ioc_eq_nhds_within_Iic {a b : α} (h : a < b) :
𝓝[Ioc a b] b = 𝓝[Iic b] b :=
by simpa only [dual_Ico] using @nhds_within_Ico_eq_nhds_within_Ici (order_dual α) _ _ _ _ _ h
@[simp]
lemma continuous_within_at_Icc_iff_Iic [topological_space β] {a b : α} {f : α → β} (h : a < b) :
continuous_within_at f (Icc a b) b ↔ continuous_within_at f (Iic b) b :=
by simp only [continuous_within_at, nhds_within_Icc_eq_nhds_within_Iic h]
@[simp]
lemma continuous_within_at_Ioc_iff_Iic [topological_space β] {a b : α} {f : α → β} (h : a < b) :
continuous_within_at f (Ioc a b) b ↔ continuous_within_at f (Iic b) b :=
by simp only [continuous_within_at, nhds_within_Ioc_eq_nhds_within_Iic h]
end linear_order
section linear_order
variables [topological_space α] [linear_order α] [order_closed_topology α] {f g : β → α}
section
variables [topological_space β]
lemma frontier_le_subset_eq (hf : continuous f) (hg : continuous g) :
frontier {b | f b ≤ g b} ⊆ {b | f b = g b} :=
begin
rw [frontier_eq_closure_inter_closure, closure_le_eq hf hg],
rintros b ⟨hb₁, hb₂⟩,
refine le_antisymm hb₁ (closure_lt_subset_le hg hf _),
convert hb₂ using 2, simp only [not_le.symm], refl
end
lemma frontier_Iic_subset (a : α) : frontier (Iic a) ⊆ {a} :=
frontier_le_subset_eq (@continuous_id α _) continuous_const
lemma frontier_Ici_subset (a : α) : frontier (Ici a) ⊆ {a} :=
@frontier_Iic_subset (order_dual α) _ _ _ _
lemma frontier_lt_subset_eq (hf : continuous f) (hg : continuous g) :
frontier {b | f b < g b} ⊆ {b | f b = g b} :=
by rw ← frontier_compl;
convert frontier_le_subset_eq hg hf; simp [ext_iff, eq_comm]
lemma continuous_if_le [topological_space γ] [Π x, decidable (f x ≤ g x)]
{f' g' : β → γ} (hf : continuous f) (hg : continuous g)
(hf' : continuous_on f' {x | f x ≤ g x}) (hg' : continuous_on g' {x | g x ≤ f x})
(hfg : ∀ x, f x = g x → f' x = g' x) :
continuous (λ x, if f x ≤ g x then f' x else g' x) :=
begin
refine continuous_if (λ a ha, hfg _ (frontier_le_subset_eq hf hg ha)) _ (hg'.mono _),
{ rwa [(is_closed_le hf hg).closure_eq] },
{ simp only [not_le], exact closure_lt_subset_le hg hf }
end
lemma continuous.if_le [topological_space γ] [Π x, decidable (f x ≤ g x)] {f' g' : β → γ}
(hf' : continuous f') (hg' : continuous g') (hf : continuous f) (hg : continuous g)
(hfg : ∀ x, f x = g x → f' x = g' x) :
continuous (λ x, if f x ≤ g x then f' x else g' x) :=
continuous_if_le hf hg hf'.continuous_on hg'.continuous_on hfg
@[continuity] lemma continuous.min (hf : continuous f) (hg : continuous g) :
continuous (λb, min (f b) (g b)) :=
hf.if_le hg hf hg (λ x, id)
@[continuity] lemma continuous.max (hf : continuous f) (hg : continuous g) :
continuous (λb, max (f b) (g b)) :=
@continuous.min (order_dual α) _ _ _ _ _ _ _ hf hg
end
lemma continuous_min : continuous (λ p : α × α, min p.1 p.2) := continuous_fst.min continuous_snd
lemma continuous_max : continuous (λ p : α × α, max p.1 p.2) := continuous_fst.max continuous_snd
lemma filter.tendsto.max {b : filter β} {a₁ a₂ : α} (hf : tendsto f b (𝓝 a₁))
(hg : tendsto g b (𝓝 a₂)) :
tendsto (λb, max (f b) (g b)) b (𝓝 (max a₁ a₂)) :=
(continuous_max.tendsto (a₁, a₂)).comp (hf.prod_mk_nhds hg)
lemma filter.tendsto.min {b : filter β} {a₁ a₂ : α} (hf : tendsto f b (𝓝 a₁))
(hg : tendsto g b (𝓝 a₂)) :
tendsto (λb, min (f b) (g b)) b (𝓝 (min a₁ a₂)) :=
(continuous_min.tendsto (a₁, a₂)).comp (hf.prod_mk_nhds hg)
end linear_order
end order_closed_topology
/-- The order topology on an ordered type is the topology generated by open intervals. We register
it on a preorder, but it is mostly interesting in linear orders, where it is also order-closed.
We define it as a mixin. If you want to introduce the order topology on a preorder, use
`preorder.topology`. -/
class order_topology (α : Type*) [t : topological_space α] [preorder α] : Prop :=
(topology_eq_generate_intervals : t = generate_from {s | ∃a, s = Ioi a ∨ s = Iio a})
/-- (Order) topology on a partial order `α` generated by the subbase of open intervals
`(a, ∞) = { x ∣ a < x }, (-∞ , b) = {x ∣ x < b}` for all `a, b` in `α`. We do not register it as an
instance as many ordered sets are already endowed with the same topology, most often in a non-defeq
way though. Register as a local instance when necessary. -/
def preorder.topology (α : Type*) [preorder α] : topological_space α :=
generate_from {s : set α | ∃ (a : α), s = {b : α | a < b} ∨ s = {b : α | b < a}}
section order_topology
instance {α : Type*} [topological_space α] [partial_order α] [order_topology α] :
order_topology (order_dual α) :=
⟨by convert @order_topology.topology_eq_generate_intervals α _ _ _;
conv in (_ ∨ _) { rw or.comm }; refl⟩
section partial_order
variables [topological_space α] [partial_order α] [t : order_topology α]
include t
lemma is_open_iff_generate_intervals {s : set α} :
is_open s ↔ generate_open {s | ∃a, s = Ioi a ∨ s = Iio a} s :=
by rw [t.topology_eq_generate_intervals]; refl
lemma is_open_lt' (a : α) : is_open {b:α | a < b} :=
by rw [@is_open_iff_generate_intervals α _ _ t]; exact generate_open.basic _ ⟨a, or.inl rfl⟩
lemma is_open_gt' (a : α) : is_open {b:α | b < a} :=
by rw [@is_open_iff_generate_intervals α _ _ t]; exact generate_open.basic _ ⟨a, or.inr rfl⟩
lemma lt_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 b, a < x :=
is_open.mem_nhds (is_open_lt' _) h
lemma le_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 b, a ≤ x :=
(𝓝 b).sets_of_superset (lt_mem_nhds h) $ assume b hb, le_of_lt hb
lemma gt_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 a, x < b :=
is_open.mem_nhds (is_open_gt' _) h
lemma ge_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 a, x ≤ b :=
(𝓝 a).sets_of_superset (gt_mem_nhds h) $ assume b hb, le_of_lt hb
lemma nhds_eq_order (a : α) :
𝓝 a = (⨅b ∈ Iio a, 𝓟 (Ioi b)) ⊓ (⨅b ∈ Ioi a, 𝓟 (Iio b)) :=
by rw [t.topology_eq_generate_intervals, nhds_generate_from];
from le_antisymm
(le_inf
(le_binfi $ assume b hb, infi_le_of_le {c : α | b < c} $ infi_le _ ⟨hb, b, or.inl rfl⟩)
(le_binfi $ assume b hb, infi_le_of_le {c : α | c < b} $ infi_le _ ⟨hb, b, or.inr rfl⟩))
(le_infi $ assume s, le_infi $ assume ⟨ha, b, hs⟩,
match s, ha, hs with
| _, h, (or.inl rfl) := inf_le_of_left_le $ infi_le_of_le b $ infi_le _ h
| _, h, (or.inr rfl) := inf_le_of_right_le $ infi_le_of_le b $ infi_le _ h
end)
lemma tendsto_order {f : β → α} {a : α} {x : filter β} :
tendsto f x (𝓝 a) ↔ (∀ a' < a, ∀ᶠ b in x, a' < f b) ∧ (∀ a' > a, ∀ᶠ b in x, f b < a') :=
by simp [nhds_eq_order a, tendsto_inf, tendsto_infi, tendsto_principal]
instance tendsto_Icc_class_nhds (a : α) : tendsto_Ixx_class Icc (𝓝 a) (𝓝 a) :=
begin
simp only [nhds_eq_order, infi_subtype'],
refine ((has_basis_infi_principal_finite _).inf
(has_basis_infi_principal_finite _)).tendsto_Ixx_class (λ s hs, _),
refine ((ord_connected_bInter _).inter (ord_connected_bInter _)).out; intros _ _,
exacts [ord_connected_Ioi, ord_connected_Iio]
end
instance tendsto_Ico_class_nhds (a : α) : tendsto_Ixx_class Ico (𝓝 a) (𝓝 a) :=
tendsto_Ixx_class_of_subset (λ _ _, Ico_subset_Icc_self)
instance tendsto_Ioc_class_nhds (a : α) : tendsto_Ixx_class Ioc (𝓝 a) (𝓝 a) :=
tendsto_Ixx_class_of_subset (λ _ _, Ioc_subset_Icc_self)
instance tendsto_Ioo_class_nhds (a : α) : tendsto_Ixx_class Ioo (𝓝 a) (𝓝 a) :=
tendsto_Ixx_class_of_subset (λ _ _, Ioo_subset_Icc_self)
/-- Also known as squeeze or sandwich theorem. This version assumes that inequalities hold
eventually for the filter. -/
lemma tendsto_of_tendsto_of_tendsto_of_le_of_le' {f g h : β → α} {b : filter β} {a : α}
(hg : tendsto g b (𝓝 a)) (hh : tendsto h b (𝓝 a))
(hgf : ∀ᶠ b in b, g b ≤ f b) (hfh : ∀ᶠ b in b, f b ≤ h b) :
tendsto f b (𝓝 a) :=
tendsto_order.2
⟨assume a' h',
have ∀ᶠ b in b, a' < g b, from (tendsto_order.1 hg).left a' h',
by filter_upwards [this, hgf] assume a, lt_of_lt_of_le,
assume a' h',
have ∀ᶠ b in b, h b < a', from (tendsto_order.1 hh).right a' h',
by filter_upwards [this, hfh] assume a h₁ h₂, lt_of_le_of_lt h₂ h₁⟩
/-- Also known as squeeze or sandwich theorem. This version assumes that inequalities hold
everywhere. -/
lemma tendsto_of_tendsto_of_tendsto_of_le_of_le {f g h : β → α} {b : filter β} {a : α}
(hg : tendsto g b (𝓝 a)) (hh : tendsto h b (𝓝 a)) (hgf : g ≤ f) (hfh : f ≤ h) :
tendsto f b (𝓝 a) :=
tendsto_of_tendsto_of_tendsto_of_le_of_le' hg hh
(eventually_of_forall hgf) (eventually_of_forall hfh)
lemma nhds_order_unbounded {a : α} (hu : ∃u, a < u) (hl : ∃l, l < a) :
𝓝 a = (⨅l (h₂ : l < a) u (h₂ : a < u), 𝓟 (Ioo l u)) :=
have ∃ u, u ∈ Ioi a, from hu, have ∃ l, l ∈ Iio a, from hl,
by { simp only [nhds_eq_order, inf_binfi, binfi_inf, *, inf_principal, Ioi_inter_Iio], refl }
lemma tendsto_order_unbounded {f : β → α} {a : α} {x : filter β}
(hu : ∃u, a < u) (hl : ∃l, l < a) (h : ∀l u, l < a → a < u → ∀ᶠ b in x, l < f b ∧ f b < u) :
tendsto f x (𝓝 a) :=
by rw [nhds_order_unbounded hu hl];
from (tendsto_infi.2 $ assume l, tendsto_infi.2 $ assume hl,
tendsto_infi.2 $ assume u, tendsto_infi.2 $ assume hu, tendsto_principal.2 $ h l u hl hu)
end partial_order
instance tendsto_Ixx_nhds_within {α : Type*} [preorder α] [topological_space α]
(a : α) {s t : set α} {Ixx}
[tendsto_Ixx_class Ixx (𝓝 a) (𝓝 a)] [tendsto_Ixx_class Ixx (𝓟 s) (𝓟 t)]:
tendsto_Ixx_class Ixx (𝓝[s] a) (𝓝[t] a) :=
filter.tendsto_Ixx_class_inf
instance tendsto_Icc_class_nhds_pi {ι : Type*} {α : ι → Type*}
[Π i, partial_order (α i)] [Π i, topological_space (α i)] [∀ i, order_topology (α i)]
(f : Π i, α i) :
tendsto_Ixx_class Icc (𝓝 f) (𝓝 f) :=
begin
constructor,
conv in ((𝓝 f).lift' powerset) { rw [nhds_pi] },
simp only [lift'_infi_powerset, comap_lift'_eq2 monotone_powerset, tendsto_infi, tendsto_lift',
mem_powerset_iff, subset_def, mem_preimage],
intros i s hs,
have : tendsto (λ g : Π i, α i, g i) (𝓝 f) (𝓝 (f i)) := ((continuous_apply i).tendsto f),
refine (tendsto_lift'.1 ((this.comp tendsto_fst).Icc (this.comp tendsto_snd)) s hs).mono _,
exact λ p hp g hg, hp ⟨hg.1 _, hg.2 _⟩
end
theorem induced_order_topology' {α : Type u} {β : Type v}
[partial_order α] [ta : topological_space β] [partial_order β] [order_topology β]
(f : α → β) (hf : ∀ {x y}, f x < f y ↔ x < y)
(H₁ : ∀ {a x}, x < f a → ∃ b < a, x ≤ f b)
(H₂ : ∀ {a x}, f a < x → ∃ b > a, f b ≤ x) :
@order_topology _ (induced f ta) _ :=
begin
letI := induced f ta,
refine ⟨eq_of_nhds_eq_nhds (λ a, _)⟩,
rw [nhds_induced, nhds_generate_from, nhds_eq_order (f a)],
apply le_antisymm,
{ refine le_infi (λ s, le_infi $ λ hs, le_principal_iff.2 _),
rcases hs with ⟨ab, b, rfl|rfl⟩,
{ exact mem_comap_sets.2 ⟨{x | f b < x},
mem_inf_sets_of_left $ mem_infi_sets _ $ mem_infi_sets (hf.2 ab) $ mem_principal_self _,
λ x, hf.1⟩ },
{ exact mem_comap_sets.2 ⟨{x | x < f b},
mem_inf_sets_of_right $ mem_infi_sets _ $ mem_infi_sets (hf.2 ab) $ mem_principal_self _,
λ x, hf.1⟩ } },
{ rw [← map_le_iff_le_comap],
refine le_inf _ _; refine le_infi (λ x, le_infi $ λ h, le_principal_iff.2 _); simp,
{ rcases H₁ h with ⟨b, ab, xb⟩,
refine mem_infi_sets _ (mem_infi_sets ⟨ab, b, or.inl rfl⟩ (mem_principal_sets.2 _)),
exact λ c hc, lt_of_le_of_lt xb (hf.2 hc) },
{ rcases H₂ h with ⟨b, ab, xb⟩,
refine mem_infi_sets _ (mem_infi_sets ⟨ab, b, or.inr rfl⟩ (mem_principal_sets.2 _)),
exact λ c hc, lt_of_lt_of_le (hf.2 hc) xb } },
end
theorem induced_order_topology {α : Type u} {β : Type v}
[partial_order α] [ta : topological_space β] [partial_order β] [order_topology β]
(f : α → β) (hf : ∀ {x y}, f x < f y ↔ x < y)
(H : ∀ {x y}, x < y → ∃ a, x < f a ∧ f a < y) :
@order_topology _ (induced f ta) _ :=
induced_order_topology' f @hf
(λ a x xa, let ⟨b, xb, ba⟩ := H xa in ⟨b, hf.1 ba, le_of_lt xb⟩)
(λ a x ax, let ⟨b, ab, bx⟩ := H ax in ⟨b, hf.1 ab, le_of_lt bx⟩)
/-- On an `ord_connected` subset of a linear order, the order topology for the restriction of the
order is the same as the restriction to the subset of the order topology. -/
instance order_topology_of_ord_connected {α : Type u}
[ta : topological_space α] [linear_order α] [order_topology α]
{t : set α} [ht : ord_connected t] :
order_topology t :=
begin
letI := induced (coe : t → α) ta,
refine ⟨eq_of_nhds_eq_nhds (λ a, _)⟩,
rw [nhds_induced, nhds_generate_from, nhds_eq_order (a : α)],
apply le_antisymm,
{ refine le_infi (λ s, le_infi $ λ hs, le_principal_iff.2 _),
rcases hs with ⟨ab, b, rfl|rfl⟩,
{ refine ⟨Ioi b, _, λ _, id⟩,
refine mem_inf_sets_of_left (mem_infi_sets b _),
exact mem_infi_sets ab (mem_principal_self (Ioi ↑b)) },
{ refine ⟨Iio b, _, λ _, id⟩,
refine mem_inf_sets_of_right (mem_infi_sets b _),
exact mem_infi_sets ab (mem_principal_self (Iio b)) } },
{ rw [← map_le_iff_le_comap],
refine le_inf _ _,
{ refine le_infi (λ x, le_infi $ λ h, le_principal_iff.2 _),
by_cases hx : x ∈ t,
{ refine mem_infi_sets (Ioi ⟨x, hx⟩) (mem_infi_sets ⟨h, ⟨⟨x, hx⟩, or.inl rfl⟩⟩ _),
exact λ _, id },
simp only [set_coe.exists, mem_set_of_eq, mem_map],
convert univ_sets _,
suffices hx' : ∀ (y : t), ↑y ∈ Ioi x,
{ simp [hx'] },
intros y,
revert hx,
contrapose!,
-- here we use the `ord_connected` hypothesis
exact λ hx, ht.out y.2 a.2 ⟨le_of_not_gt hx, le_of_lt h⟩ },
{ refine le_infi (λ x, le_infi $ λ h, le_principal_iff.2 _),
by_cases hx : x ∈ t,
{ refine mem_infi_sets (Iio ⟨x, hx⟩) (mem_infi_sets ⟨h, ⟨⟨x, hx⟩, or.inr rfl⟩⟩ _),
exact λ _, id },
simp only [set_coe.exists, mem_set_of_eq, mem_map],
convert univ_sets _,
suffices hx' : ∀ (y : t), ↑y ∈ Iio x,
{ simp [hx'] },
intros y,
revert hx,
contrapose!,
-- here we use the `ord_connected` hypothesis
exact λ hx, ht.out a.2 y.2 ⟨le_of_lt h, le_of_not_gt hx⟩ } }
end
lemma nhds_top_order [topological_space α] [order_top α] [order_topology α] :
𝓝 (⊤:α) = (⨅l (h₂ : l < ⊤), 𝓟 (Ioi l)) :=
by simp [nhds_eq_order (⊤:α)]
lemma nhds_bot_order [topological_space α] [order_bot α] [order_topology α] :
𝓝 (⊥:α) = (⨅l (h₂ : ⊥ < l), 𝓟 (Iio l)) :=
by simp [nhds_eq_order (⊥:α)]
lemma tendsto_nhds_top_mono [topological_space β] [order_top β] [order_topology β] {l : filter α}
{f g : α → β} (hf : tendsto f l (𝓝 ⊤)) (hg : f ≤ᶠ[l] g) :
tendsto g l (𝓝 ⊤) :=
begin
simp only [nhds_top_order, tendsto_infi, tendsto_principal] at hf ⊢,
intros x hx,
filter_upwards [hf x hx, hg],
exact λ x, lt_of_lt_of_le
end
lemma tendsto_nhds_bot_mono [topological_space β] [order_bot β] [order_topology β] {l : filter α}
{f g : α → β} (hf : tendsto f l (𝓝 ⊥)) (hg : g ≤ᶠ[l] f) :
tendsto g l (𝓝 ⊥) :=
@tendsto_nhds_top_mono α (order_dual β) _ _ _ _ _ _ hf hg
lemma tendsto_nhds_top_mono' [topological_space β] [order_top β] [order_topology β] {l : filter α}
{f g : α → β} (hf : tendsto f l (𝓝 ⊤)) (hg : f ≤ g) :
tendsto g l (𝓝 ⊤) :=
tendsto_nhds_top_mono hf (eventually_of_forall hg)
lemma tendsto_nhds_bot_mono' [topological_space β] [order_bot β] [order_topology β] {l : filter α}
{f g : α → β} (hf : tendsto f l (𝓝 ⊥)) (hg : g ≤ f) :
tendsto g l (𝓝 ⊥) :=
tendsto_nhds_bot_mono hf (eventually_of_forall hg)
section linear_order
variables [topological_space α] [linear_order α] [order_topology α]
lemma exists_Ioc_subset_of_mem_nhds' {a : α} {s : set α} (hs : s ∈ 𝓝 a) {l : α} (hl : l < a) :
∃ l' ∈ Ico l a, Ioc l' a ⊆ s :=
begin
rw [nhds_eq_order a] at hs,
rcases hs with ⟨t₁, ht₁, t₂, ht₂, hts⟩,
-- First we show that `t₂` includes `(-∞, a]`, so it suffices to show `(l', ∞) ⊆ t₁`
suffices : ∃ l' ∈ Ico l a, Ioi l' ⊆ t₁,
{ have A : 𝓟 (Iic a) ≤ ⨅ b ∈ Ioi a, 𝓟 (Iio b),
from (le_infi $ λ b, le_infi $ λ hb, principal_mono.2 $ Iic_subset_Iio.2 hb),
have B : t₁ ∩ Iic a ⊆ s,
from subset.trans (inter_subset_inter_right _ (A ht₂)) hts,
from this.imp (λ l', Exists.imp $ λ hl' hl x hx, B ⟨hl hx.1, hx.2⟩) },
clear hts ht₂ t₂,
-- Now we find `l` such that `(l', ∞) ⊆ t₁`
rw [mem_binfi] at ht₁,
{ rcases ht₁ with ⟨b, hb, hb'⟩,
exact ⟨max b l, ⟨le_max_right _ _, max_lt hb hl⟩,
λ x hx, hb' $ Ioi_subset_Ioi (le_max_left _ _) hx⟩ },
{ intros b hb b' hb', simp only [mem_Iio] at hb hb',
use [max b b', max_lt hb hb'],
simp [le_refl] },
exact ⟨l, hl⟩
end
lemma exists_Ico_subset_of_mem_nhds' {a : α} {s : set α} (hs : s ∈ 𝓝 a) {u : α} (hu : a < u) :
∃ u' ∈ Ioc a u, Ico a u' ⊆ s :=
begin
convert @exists_Ioc_subset_of_mem_nhds' (order_dual α) _ _ _ _ _ hs _ hu,
ext, rw [dual_Ico, dual_Ioc]
end
lemma exists_Ioc_subset_of_mem_nhds {a : α} {s : set α} (hs : s ∈ 𝓝 a) (h : ∃ l, l < a) :
∃ l < a, Ioc l a ⊆ s :=
let ⟨l', hl'⟩ := h in let ⟨l, hl⟩ := exists_Ioc_subset_of_mem_nhds' hs hl' in ⟨l, hl.fst.2, hl.snd⟩
lemma exists_Ico_subset_of_mem_nhds {a : α} {s : set α} (hs : s ∈ 𝓝 a) (h : ∃ u, a < u) :
∃ u (_ : a < u), Ico a u ⊆ s :=
let ⟨l', hl'⟩ := h in let ⟨l, hl⟩ := exists_Ico_subset_of_mem_nhds' hs hl' in ⟨l, hl.fst.1, hl.snd⟩
lemma order_separated {a₁ a₂ : α} (h : a₁ < a₂) :
∃u v : set α, is_open u ∧ is_open v ∧ a₁ ∈ u ∧ a₂ ∈ v ∧ (∀b₁∈u, ∀b₂∈v, b₁ < b₂) :=
match dense_or_discrete a₁ a₂ with
| or.inl ⟨a, ha₁, ha₂⟩ := ⟨{a' | a' < a}, {a' | a < a'}, is_open_gt' a, is_open_lt' a, ha₁, ha₂,
assume b₁ h₁ b₂ h₂, lt_trans h₁ h₂⟩
| or.inr ⟨h₁, h₂⟩ := ⟨{a | a < a₂}, {a | a₁ < a}, is_open_gt' a₂, is_open_lt' a₁, h, h,
assume b₁ hb₁ b₂ hb₂,
calc b₁ ≤ a₁ : h₂ _ hb₁
... < a₂ : h
... ≤ b₂ : h₁ _ hb₂⟩
end
@[priority 100] -- see Note [lower instance priority]
instance order_topology.to_order_closed_topology : order_closed_topology α :=
{ is_closed_le' :=
is_open_compl_iff.1 $ is_open_prod_iff.mpr $ assume a₁ a₂ (h : ¬ a₁ ≤ a₂),
have h : a₂ < a₁, from lt_of_not_ge h,
let ⟨u, v, hu, hv, ha₁, ha₂, h⟩ := order_separated h in
⟨v, u, hv, hu, ha₂, ha₁, assume ⟨b₁, b₂⟩ ⟨h₁, h₂⟩, not_le_of_gt $ h b₂ h₂ b₁ h₁⟩ }
lemma order_topology.t2_space : t2_space α := by apply_instance
@[priority 100] -- see Note [lower instance priority]
instance order_topology.regular_space : regular_space α :=
{ regular := assume s a hs ha,
have hs' : sᶜ ∈ 𝓝 a, from is_open.mem_nhds hs.is_open_compl ha,
have ∃t:set α, is_open t ∧ (∀l∈ s, l < a → l ∈ t) ∧ 𝓝[t] a = ⊥,
from by_cases
(assume h : ∃l, l < a,
let ⟨l, hl, h⟩ := exists_Ioc_subset_of_mem_nhds hs' h in
match dense_or_discrete l a with
| or.inl ⟨b, hb₁, hb₂⟩ := ⟨{a | a < b}, is_open_gt' _,
assume c hcs hca, show c < b,
from lt_of_not_ge $ assume hbc, h ⟨lt_of_lt_of_le hb₁ hbc, le_of_lt hca⟩ hcs,
inf_principal_eq_bot.2 $ (𝓝 a).sets_of_superset ((is_open_lt' _).mem_nhds hb₂) $
assume x (hx : b < x), show ¬ x < b, from not_lt.2 $ le_of_lt hx⟩
| or.inr ⟨h₁, h₂⟩ := ⟨{a' | a' < a}, is_open_gt' _, assume b hbs hba, hba,
inf_principal_eq_bot.2 $ (𝓝 a).sets_of_superset ((is_open_lt' _).mem_nhds hl) $
assume x (hx : l < x), show ¬ x < a, from not_lt.2 $ h₁ _ hx⟩
end)
(assume : ¬ ∃l, l < a, ⟨∅, is_open_empty, assume l _ hl, (this ⟨l, hl⟩).elim,
nhds_within_empty _⟩),
let ⟨t₁, ht₁o, ht₁s, ht₁a⟩ := this in
have ∃t:set α, is_open t ∧ (∀u∈ s, u>a → u ∈ t) ∧ 𝓝[t] a = ⊥,
from by_cases
(assume h : ∃u, u > a,
let ⟨u, hu, h⟩ := exists_Ico_subset_of_mem_nhds hs' h in
match dense_or_discrete a u with
| or.inl ⟨b, hb₁, hb₂⟩ := ⟨{a | b < a}, is_open_lt' _,
assume c hcs hca, show c > b,
from lt_of_not_ge $ assume hbc, h ⟨le_of_lt hca, lt_of_le_of_lt hbc hb₂⟩ hcs,
inf_principal_eq_bot.2 $ (𝓝 a).sets_of_superset ((is_open_gt' _).mem_nhds hb₁) $
assume x (hx : b > x), show ¬ x > b, from not_lt.2 $ le_of_lt hx⟩
| or.inr ⟨h₁, h₂⟩ := ⟨{a' | a' > a}, is_open_lt' _, assume b hbs hba, hba,
inf_principal_eq_bot.2 $ (𝓝 a).sets_of_superset ((is_open_gt' _).mem_nhds hu) $
assume x (hx : u > x), show ¬ x > a, from not_lt.2 $ h₂ _ hx⟩
end)
(assume : ¬ ∃u, u > a, ⟨∅, is_open_empty, assume l _ hl, (this ⟨l, hl⟩).elim,
nhds_within_empty _⟩),
let ⟨t₂, ht₂o, ht₂s, ht₂a⟩ := this in
⟨t₁ ∪ t₂, is_open.union ht₁o ht₂o,
assume x hx,
have x ≠ a, from assume eq, ha $ eq ▸ hx,
(ne_iff_lt_or_gt.mp this).imp (ht₁s _ hx) (ht₂s _ hx),
by rw [nhds_within_union, ht₁a, ht₂a, bot_sup_eq]⟩,
..order_topology.t2_space }
/-- A set is a neighborhood of `a` if and only if it contains an interval `(l, u)` containing `a`,
provided `a` is neither a bottom element nor a top element. -/
lemma mem_nhds_iff_exists_Ioo_subset' {a : α} {s : set α} (hl : ∃ l, l < a) (hu : ∃ u, a < u) :
s ∈ 𝓝 a ↔ ∃l u, a ∈ Ioo l u ∧ Ioo l u ⊆ s :=
begin
split,
{ assume h,
rcases exists_Ico_subset_of_mem_nhds h hu with ⟨u, au, hu⟩,
rcases exists_Ioc_subset_of_mem_nhds h hl with ⟨l, la, hl⟩,
refine ⟨l, u, ⟨la, au⟩, λx hx, _⟩,
cases le_total a x with hax hax,
{ exact hu ⟨hax, hx.2⟩ },
{ exact hl ⟨hx.1, hax⟩ } },
{ rintros ⟨l, u, ha, h⟩,
apply mem_sets_of_superset (is_open.mem_nhds is_open_Ioo ha) h }
end
/-- A set is a neighborhood of `a` if and only if it contains an interval `(l, u)` containing `a`.
-/
lemma mem_nhds_iff_exists_Ioo_subset [no_top_order α] [no_bot_order α] {a : α} {s : set α} :
s ∈ 𝓝 a ↔ ∃l u, a ∈ Ioo l u ∧ Ioo l u ⊆ s :=
mem_nhds_iff_exists_Ioo_subset' (no_bot a) (no_top a)
lemma nhds_basis_Ioo' {a : α} (hl : ∃ l, l < a) (hu : ∃ u, a < u) :
(𝓝 a).has_basis (λ b : α × α, b.1 < a ∧ a < b.2) (λ b, Ioo b.1 b.2) :=
⟨λ s, (mem_nhds_iff_exists_Ioo_subset' hl hu).trans $ by simp⟩
lemma nhds_basis_Ioo [no_top_order α] [no_bot_order α] (a : α) :
(𝓝 a).has_basis (λ b : α × α, b.1 < a ∧ a < b.2) (λ b, Ioo b.1 b.2) :=
nhds_basis_Ioo' (no_bot a) (no_top a)
lemma filter.eventually.exists_Ioo_subset [no_top_order α] [no_bot_order α] {a : α} {p : α → Prop}
(hp : ∀ᶠ x in 𝓝 a, p x) :
∃ l u, a ∈ Ioo l u ∧ Ioo l u ⊆ {x | p x} :=
mem_nhds_iff_exists_Ioo_subset.1 hp
lemma Iio_mem_nhds {a b : α} (h : a < b) : Iio b ∈ 𝓝 a :=
is_open.mem_nhds is_open_Iio h
lemma Ioi_mem_nhds {a b : α} (h : a < b) : Ioi a ∈ 𝓝 b :=
is_open.mem_nhds is_open_Ioi h
lemma Iic_mem_nhds {a b : α} (h : a < b) : Iic b ∈ 𝓝 a :=
mem_sets_of_superset (Iio_mem_nhds h) Iio_subset_Iic_self
lemma Ici_mem_nhds {a b : α} (h : a < b) : Ici a ∈ 𝓝 b :=
mem_sets_of_superset (Ioi_mem_nhds h) Ioi_subset_Ici_self
lemma Ioo_mem_nhds {a b x : α} (ha : a < x) (hb : x < b) : Ioo a b ∈ 𝓝 x :=
is_open.mem_nhds is_open_Ioo ⟨ha, hb⟩
lemma Ioc_mem_nhds {a b x : α} (ha : a < x) (hb : x < b) : Ioc a b ∈ 𝓝 x :=
mem_sets_of_superset (Ioo_mem_nhds ha hb) Ioo_subset_Ioc_self
lemma Ico_mem_nhds {a b x : α} (ha : a < x) (hb : x < b) : Ico a b ∈ 𝓝 x :=
mem_sets_of_superset (Ioo_mem_nhds ha hb) Ioo_subset_Ico_self
lemma Icc_mem_nhds {a b x : α} (ha : a < x) (hb : x < b) : Icc a b ∈ 𝓝 x :=
mem_sets_of_superset (Ioo_mem_nhds ha hb) Ioo_subset_Icc_self
section pi
/-!
### Intervals in `Π i, π i` belong to `𝓝 x`
For each lemma `pi_Ixx_mem_nhds` we add a non-dependent version `pi_Ixx_mem_nhds'` because
sometimes Lean fails to unify different instances while trying to apply the dependent version to,
e.g., `ι → ℝ`.
-/
variables {ι : Type*} {π : ι → Type*} [fintype ι] [Π i, linear_order (π i)]
[Π i, topological_space (π i)] [∀ i, order_topology (π i)] {a b x : Π i, π i} {a' b' x' : ι → α}
lemma pi_Iic_mem_nhds (ha : ∀ i, x i < a i) : Iic a ∈ 𝓝 x :=
pi_univ_Iic a ▸ set_pi_mem_nhds (finite.of_fintype _) (λ i _, Iic_mem_nhds (ha _))
lemma pi_Iic_mem_nhds' (ha : ∀ i, x' i < a' i) : Iic a' ∈ 𝓝 x' :=
pi_Iic_mem_nhds ha
lemma pi_Ici_mem_nhds (ha : ∀ i, a i < x i) : Ici a ∈ 𝓝 x :=
pi_univ_Ici a ▸ set_pi_mem_nhds (finite.of_fintype _) (λ i _, Ici_mem_nhds (ha _))
lemma pi_Ici_mem_nhds' (ha : ∀ i, a' i < x' i) : Ici a' ∈ 𝓝 x' :=
pi_Ici_mem_nhds ha
lemma pi_Icc_mem_nhds (ha : ∀ i, a i < x i) (hb : ∀ i, x i < b i) : Icc a b ∈ 𝓝 x :=
pi_univ_Icc a b ▸ set_pi_mem_nhds (finite.of_fintype _) (λ i _, Icc_mem_nhds (ha _) (hb _))
lemma pi_Icc_mem_nhds' (ha : ∀ i, a' i < x' i) (hb : ∀ i, x' i < b' i) : Icc a' b' ∈ 𝓝 x' :=
pi_Icc_mem_nhds ha hb
variables [nonempty ι]
lemma pi_Iio_mem_nhds (ha : ∀ i, x i < a i) : Iio a ∈ 𝓝 x :=
begin
refine mem_sets_of_superset (set_pi_mem_nhds (finite.of_fintype _) (λ i _, _))
(pi_univ_Iio_subset a),
exact Iio_mem_nhds (ha i)
end
lemma pi_Iio_mem_nhds' (ha : ∀ i, x' i < a' i) : Iio a' ∈ 𝓝 x' :=
pi_Iio_mem_nhds ha
lemma pi_Ioi_mem_nhds (ha : ∀ i, a i < x i) : Ioi a ∈ 𝓝 x :=
@pi_Iio_mem_nhds ι (λ i, order_dual (π i)) _ _ _ _ _ _ _ ha
lemma pi_Ioi_mem_nhds' (ha : ∀ i, a' i < x' i) : Ioi a' ∈ 𝓝 x' :=
pi_Ioi_mem_nhds ha
lemma pi_Ioc_mem_nhds (ha : ∀ i, a i < x i) (hb : ∀ i, x i < b i) : Ioc a b ∈ 𝓝 x :=
begin
refine mem_sets_of_superset (set_pi_mem_nhds (finite.of_fintype _) (λ i _, _))
(pi_univ_Ioc_subset a b),
exact Ioc_mem_nhds (ha i) (hb i)
end
lemma pi_Ioc_mem_nhds' (ha : ∀ i, a' i < x' i) (hb : ∀ i, x' i < b' i) : Ioc a' b' ∈ 𝓝 x' :=
pi_Ioc_mem_nhds ha hb
lemma pi_Ico_mem_nhds (ha : ∀ i, a i < x i) (hb : ∀ i, x i < b i) : Ico a b ∈ 𝓝 x :=
begin
refine mem_sets_of_superset (set_pi_mem_nhds (finite.of_fintype _) (λ i _, _))
(pi_univ_Ico_subset a b),
exact Ico_mem_nhds (ha i) (hb i)
end
lemma pi_Ico_mem_nhds' (ha : ∀ i, a' i < x' i) (hb : ∀ i, x' i < b' i) : Ico a' b' ∈ 𝓝 x' :=
pi_Ico_mem_nhds ha hb
lemma pi_Ioo_mem_nhds (ha : ∀ i, a i < x i) (hb : ∀ i, x i < b i) : Ioo a b ∈ 𝓝 x :=
begin
refine mem_sets_of_superset (set_pi_mem_nhds (finite.of_fintype _) (λ i _, _))
(pi_univ_Ioo_subset a b),
exact Ioo_mem_nhds (ha i) (hb i)
end
lemma pi_Ioo_mem_nhds' (ha : ∀ i, a' i < x' i) (hb : ∀ i, x' i < b' i) : Ioo a' b' ∈ 𝓝 x' :=
pi_Ioo_mem_nhds ha hb
end pi
lemma disjoint_nhds_at_top [no_top_order α] (x : α) :
disjoint (𝓝 x) at_top :=
begin
rw filter.disjoint_iff,
cases no_top x with a ha,
use [Iio a, Iio_mem_nhds ha, Ici a, mem_at_top a],
rw [inter_comm, Ici_inter_Iio, Ico_self]
end
@[simp] lemma inf_nhds_at_top [no_top_order α] (x : α) :
𝓝 x ⊓ at_top = ⊥ :=
disjoint_iff.1 (disjoint_nhds_at_top x)
lemma disjoint_nhds_at_bot [no_bot_order α] (x : α) :
disjoint (𝓝 x) at_bot :=
@disjoint_nhds_at_top (order_dual α) _ _ _ _ x
@[simp] lemma inf_nhds_at_bot [no_bot_order α] (x : α) :
𝓝 x ⊓ at_bot = ⊥ :=
@inf_nhds_at_top (order_dual α) _ _ _ _ x
lemma not_tendsto_nhds_of_tendsto_at_top [no_top_order α]
{F : filter β} [ne_bot F] {f : β → α} (hf : tendsto f F at_top) (x : α) :
¬ tendsto f F (𝓝 x) :=
hf.not_tendsto (disjoint_nhds_at_top x).symm
lemma not_tendsto_at_top_of_tendsto_nhds [no_top_order α]
{F : filter β} [ne_bot F] {f : β → α} {x : α} (hf : tendsto f F (𝓝 x)) :
¬ tendsto f F at_top :=
hf.not_tendsto (disjoint_nhds_at_top x)
lemma not_tendsto_nhds_of_tendsto_at_bot [no_bot_order α]
{F : filter β} [ne_bot F] {f : β → α} (hf : tendsto f F at_bot) (x : α) :
¬ tendsto f F (𝓝 x) :=
hf.not_tendsto (disjoint_nhds_at_bot x).symm
lemma not_tendsto_at_bot_of_tendsto_nhds [no_bot_order α]
{F : filter β} [ne_bot F] {f : β → α} {x : α} (hf : tendsto f F (𝓝 x)) :
¬ tendsto f F at_bot :=
hf.not_tendsto (disjoint_nhds_at_bot x)
/-!
### Neighborhoods to the left and to the right on an `order_topology`
We've seen some properties of left and right neighborhood of a point in an `order_closed_topology`.
In an `order_topology`, such neighborhoods can be characterized as the sets containing suitable
intervals to the right or to the left of `a`. We give now these characterizations. -/
-- NB: If you extend the list, append to the end please to avoid breaking the API
/-- The following statements are equivalent:
0. `s` is a neighborhood of `a` within `(a, +∞)`
1. `s` is a neighborhood of `a` within `(a, b]`
2. `s` is a neighborhood of `a` within `(a, b)`
3. `s` includes `(a, u)` for some `u ∈ (a, b]`
4. `s` includes `(a, u)` for some `u > a` -/
lemma tfae_mem_nhds_within_Ioi {a b : α} (hab : a < b) (s : set α) :
tfae [s ∈ 𝓝[Ioi a] a, -- 0 : `s` is a neighborhood of `a` within `(a, +∞)`
s ∈ 𝓝[Ioc a b] a, -- 1 : `s` is a neighborhood of `a` within `(a, b]`
s ∈ 𝓝[Ioo a b] a, -- 2 : `s` is a neighborhood of `a` within `(a, b)`
∃ u ∈ Ioc a b, Ioo a u ⊆ s, -- 3 : `s` includes `(a, u)` for some `u ∈ (a, b]`
∃ u ∈ Ioi a, Ioo a u ⊆ s] := -- 4 : `s` includes `(a, u)` for some `u > a`
begin
tfae_have : 1 ↔ 2, by rw [nhds_within_Ioc_eq_nhds_within_Ioi hab],
tfae_have : 1 ↔ 3, by rw [nhds_within_Ioo_eq_nhds_within_Ioi hab],
tfae_have : 4 → 5, from λ ⟨u, umem, hu⟩, ⟨u, umem.1, hu⟩,
tfae_have : 5 → 1,
{ rintros ⟨u, hau, hu⟩,
exact mem_sets_of_superset (Ioo_mem_nhds_within_Ioi ⟨le_refl a, hau⟩) hu },
tfae_have : 1 → 4,
{ assume h,
rcases mem_nhds_within_iff_exists_mem_nhds_inter.1 h with ⟨v, va, hv⟩,
rcases exists_Ico_subset_of_mem_nhds' va hab with ⟨u, au, hu⟩,
refine ⟨u, au, λx hx, _⟩,
refine hv ⟨hu ⟨le_of_lt hx.1, hx.2⟩, _⟩,
exact hx.1 },
tfae_finish
end
lemma mem_nhds_within_Ioi_iff_exists_mem_Ioc_Ioo_subset {a u' : α} {s : set α} (hu' : a < u') :
s ∈ 𝓝[Ioi a] a ↔ ∃u ∈ Ioc a u', Ioo a u ⊆ s :=
(tfae_mem_nhds_within_Ioi hu' s).out 0 3
/-- A set is a neighborhood of `a` within `(a, +∞)` if and only if it contains an interval `(a, u)`
with `a < u < u'`, provided `a` is not a top element. -/
lemma mem_nhds_within_Ioi_iff_exists_Ioo_subset' {a u' : α} {s : set α} (hu' : a < u') :
s ∈ 𝓝[Ioi a] a ↔ ∃u ∈ Ioi a, Ioo a u ⊆ s :=
(tfae_mem_nhds_within_Ioi hu' s).out 0 4
/-- A set is a neighborhood of `a` within `(a, +∞)` if and only if it contains an interval `(a, u)`
with `a < u`. -/
lemma mem_nhds_within_Ioi_iff_exists_Ioo_subset [no_top_order α] {a : α} {s : set α} :
s ∈ 𝓝[Ioi a] a ↔ ∃u ∈ Ioi a, Ioo a u ⊆ s :=
let ⟨u', hu'⟩ := no_top a in mem_nhds_within_Ioi_iff_exists_Ioo_subset' hu'
/-- A set is a neighborhood of `a` within `(a, +∞)` if and only if it contains an interval `(a, u]`
with `a < u`. -/
lemma mem_nhds_within_Ioi_iff_exists_Ioc_subset [no_top_order α] [densely_ordered α]
{a : α} {s : set α} : s ∈ 𝓝[Ioi a] a ↔ ∃u ∈ Ioi a, Ioc a u ⊆ s :=
begin
rw mem_nhds_within_Ioi_iff_exists_Ioo_subset,
split,
{ rintros ⟨u, au, as⟩,
rcases exists_between au with ⟨v, hv⟩,
exact ⟨v, hv.1, λx hx, as ⟨hx.1, lt_of_le_of_lt hx.2 hv.2⟩⟩ },
{ rintros ⟨u, au, as⟩,
exact ⟨u, au, subset.trans Ioo_subset_Ioc_self as⟩ }
end
/-- The following statements are equivalent:
0. `s` is a neighborhood of `b` within `(-∞, b)`
1. `s` is a neighborhood of `b` within `[a, b)`
2. `s` is a neighborhood of `b` within `(a, b)`
3. `s` includes `(l, b)` for some `l ∈ [a, b)`
4. `s` includes `(l, b)` for some `l < b` -/
lemma tfae_mem_nhds_within_Iio {a b : α} (h : a < b) (s : set α) :
tfae [s ∈ 𝓝[Iio b] b, -- 0 : `s` is a neighborhood of `b` within `(-∞, b)`
s ∈ 𝓝[Ico a b] b, -- 1 : `s` is a neighborhood of `b` within `[a, b)`
s ∈ 𝓝[Ioo a b] b, -- 2 : `s` is a neighborhood of `b` within `(a, b)`
∃ l ∈ Ico a b, Ioo l b ⊆ s, -- 3 : `s` includes `(l, b)` for some `l ∈ [a, b)`
∃ l ∈ Iio b, Ioo l b ⊆ s] := -- 4 : `s` includes `(l, b)` for some `l < b`
begin
have := @tfae_mem_nhds_within_Ioi (order_dual α) _ _ _ _ _ h s,
-- If we call `convert` here, it generates wrong equations, so we need to simplify first
simp only [exists_prop] at this ⊢,
rw [dual_Ioi, dual_Ioc, dual_Ioo] at this,
convert this; ext l; rw [dual_Ioo]
end
lemma mem_nhds_within_Iio_iff_exists_mem_Ico_Ioo_subset {a l' : α} {s : set α} (hl' : l' < a) :
s ∈ 𝓝[Iio a] a ↔ ∃l ∈ Ico l' a, Ioo l a ⊆ s :=
(tfae_mem_nhds_within_Iio hl' s).out 0 3
/-- A set is a neighborhood of `a` within `(-∞, a)` if and only if it contains an interval `(l, a)`
with `l < a`, provided `a` is not a bottom element. -/
lemma mem_nhds_within_Iio_iff_exists_Ioo_subset' {a l' : α} {s : set α} (hl' : l' < a) :
s ∈ 𝓝[Iio a] a ↔ ∃l ∈ Iio a, Ioo l a ⊆ s :=
(tfae_mem_nhds_within_Iio hl' s).out 0 4
/-- A set is a neighborhood of `a` within `(-∞, a)` if and only if it contains an interval `(l, a)`
with `l < a`. -/
lemma mem_nhds_within_Iio_iff_exists_Ioo_subset [no_bot_order α] {a : α} {s : set α} :
s ∈ 𝓝[Iio a] a ↔ ∃l ∈ Iio a, Ioo l a ⊆ s :=
let ⟨l', hl'⟩ := no_bot a in mem_nhds_within_Iio_iff_exists_Ioo_subset' hl'
/-- A set is a neighborhood of `a` within `(-∞, a)` if and only if it contains an interval `[l, a)`
with `l < a`. -/
lemma mem_nhds_within_Iio_iff_exists_Ico_subset [no_bot_order α] [densely_ordered α]
{a : α} {s : set α} : s ∈ 𝓝[Iio a] a ↔ ∃l ∈ Iio a, Ico l a ⊆ s :=
begin
convert @mem_nhds_within_Ioi_iff_exists_Ioc_subset (order_dual α) _ _ _ _ _ _ _,
simp only [dual_Ioc], refl
end
/-- The following statements are equivalent:
0. `s` is a neighborhood of `a` within `[a, +∞)`
1. `s` is a neighborhood of `a` within `[a, b]`
2. `s` is a neighborhood of `a` within `[a, b)`
3. `s` includes `[a, u)` for some `u ∈ (a, b]`
4. `s` includes `[a, u)` for some `u > a` -/
lemma tfae_mem_nhds_within_Ici {a b : α} (hab : a < b) (s : set α) :
tfae [s ∈ 𝓝[Ici a] a, -- 0 : `s` is a neighborhood of `a` within `[a, +∞)`
s ∈ 𝓝[Icc a b] a, -- 1 : `s` is a neighborhood of `a` within `[a, b]`
s ∈ 𝓝[Ico a b] a, -- 2 : `s` is a neighborhood of `a` within `[a, b)`
∃ u ∈ Ioc a b, Ico a u ⊆ s, -- 3 : `s` includes `[a, u)` for some `u ∈ (a, b]`
∃ u ∈ Ioi a, Ico a u ⊆ s] := -- 4 : `s` includes `[a, u)` for some `u > a`
begin
tfae_have : 1 ↔ 2, by rw [nhds_within_Icc_eq_nhds_within_Ici hab],
tfae_have : 1 ↔ 3, by rw [nhds_within_Ico_eq_nhds_within_Ici hab],
tfae_have : 4 → 5, from λ ⟨u, umem, hu⟩, ⟨u, umem.1, hu⟩,
tfae_have : 5 → 1,
{ rintros ⟨u, hau, hu⟩,
exact mem_sets_of_superset (Ico_mem_nhds_within_Ici ⟨le_refl a, hau⟩) hu },
tfae_have : 1 → 4,
{ assume h,
rcases mem_nhds_within_iff_exists_mem_nhds_inter.1 h with ⟨v, va, hv⟩,
rcases exists_Ico_subset_of_mem_nhds' va hab with ⟨u, au, hu⟩,
refine ⟨u, au, λx hx, _⟩,
refine hv ⟨hu ⟨hx.1, hx.2⟩, _⟩,
exact hx.1 },
tfae_finish
end
lemma mem_nhds_within_Ici_iff_exists_mem_Ioc_Ico_subset {a u' : α} {s : set α} (hu' : a < u') :
s ∈ 𝓝[Ici a] a ↔ ∃u ∈ Ioc a u', Ico a u ⊆ s :=
(tfae_mem_nhds_within_Ici hu' s).out 0 3 (by norm_num) (by norm_num)
/-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u)`
with `a < u < u'`, provided `a` is not a top element. -/
lemma mem_nhds_within_Ici_iff_exists_Ico_subset' {a u' : α} {s : set α} (hu' : a < u') :
s ∈ 𝓝[Ici a] a ↔ ∃u ∈ Ioi a, Ico a u ⊆ s :=
(tfae_mem_nhds_within_Ici hu' s).out 0 4 (by norm_num) (by norm_num)
/-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u)`
with `a < u`. -/
lemma mem_nhds_within_Ici_iff_exists_Ico_subset [no_top_order α] {a : α} {s : set α} :
s ∈ 𝓝[Ici a] a ↔ ∃u ∈ Ioi a, Ico a u ⊆ s :=
let ⟨u', hu'⟩ := no_top a in mem_nhds_within_Ici_iff_exists_Ico_subset' hu'
/-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u]`
with `a < u`. -/
lemma mem_nhds_within_Ici_iff_exists_Icc_subset' [no_top_order α] [densely_ordered α]
{a : α} {s : set α} : s ∈ 𝓝[Ici a] a ↔ ∃u ∈ Ioi a, Icc a u ⊆ s :=
begin
rw mem_nhds_within_Ici_iff_exists_Ico_subset,
split,
{ rintros ⟨u, au, as⟩,
rcases exists_between au with ⟨v, hv⟩,
exact ⟨v, hv.1, λx hx, as ⟨hx.1, lt_of_le_of_lt hx.2 hv.2⟩⟩ },
{ rintros ⟨u, au, as⟩,
exact ⟨u, au, subset.trans Ico_subset_Icc_self as⟩ }
end
/-- The following statements are equivalent:
0. `s` is a neighborhood of `b` within `(-∞, b]`
1. `s` is a neighborhood of `b` within `[a, b]`
2. `s` is a neighborhood of `b` within `(a, b]`
3. `s` includes `(l, b]` for some `l ∈ [a, b)`
4. `s` includes `(l, b]` for some `l < b` -/
lemma tfae_mem_nhds_within_Iic {a b : α} (h : a < b) (s : set α) :
tfae [s ∈ 𝓝[Iic b] b, -- 0 : `s` is a neighborhood of `b` within `(-∞, b]`
s ∈ 𝓝[Icc a b] b, -- 1 : `s` is a neighborhood of `b` within `[a, b]`
s ∈ 𝓝[Ioc a b] b, -- 2 : `s` is a neighborhood of `b` within `(a, b]`
∃ l ∈ Ico a b, Ioc l b ⊆ s, -- 3 : `s` includes `(l, b]` for some `l ∈ [a, b)`
∃ l ∈ Iio b, Ioc l b ⊆ s] := -- 4 : `s` includes `(l, b]` for some `l < b`
begin
have := @tfae_mem_nhds_within_Ici (order_dual α) _ _ _ _ _ h s,
-- If we call `convert` here, it generates wrong equations, so we need to simplify first
simp only [exists_prop] at this ⊢,
rw [dual_Icc, dual_Ioc, dual_Ioi] at this,
convert this; ext l; rw [dual_Ico]
end
lemma mem_nhds_within_Iic_iff_exists_mem_Ico_Ioc_subset {a l' : α} {s : set α} (hl' : l' < a) :
s ∈ 𝓝[Iic a] a ↔ ∃l ∈ Ico l' a, Ioc l a ⊆ s :=
(tfae_mem_nhds_within_Iic hl' s).out 0 3 (by norm_num) (by norm_num)
/-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `(l, a]`
with `l < a`, provided `a` is not a bottom element. -/
lemma mem_nhds_within_Iic_iff_exists_Ioc_subset' {a l' : α} {s : set α} (hl' : l' < a) :
s ∈ 𝓝[Iic a] a ↔ ∃l ∈ Iio a, Ioc l a ⊆ s :=
(tfae_mem_nhds_within_Iic hl' s).out 0 4 (by norm_num) (by norm_num)
/-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `(l, a]`
with `l < a`. -/
lemma mem_nhds_within_Iic_iff_exists_Ioc_subset [no_bot_order α] {a : α} {s : set α} :
s ∈ 𝓝[Iic a] a ↔ ∃l ∈ Iio a, Ioc l a ⊆ s :=
let ⟨l', hl'⟩ := no_bot a in mem_nhds_within_Iic_iff_exists_Ioc_subset' hl'
/-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `[l, a]`
with `l < a`. -/
lemma mem_nhds_within_Iic_iff_exists_Icc_subset' [no_bot_order α] [densely_ordered α]
{a : α} {s : set α} : s ∈ 𝓝[Iic a] a ↔ ∃l ∈ Iio a, Icc l a ⊆ s :=
begin
convert @mem_nhds_within_Ici_iff_exists_Icc_subset' (order_dual α) _ _ _ _ _ _ _,
simp_rw (show ∀ u : order_dual α, @Icc (order_dual α) _ a u = @Icc α _ u a, from λ u, dual_Icc),
refl,
end
/-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u]`
with `a < u`. -/
lemma mem_nhds_within_Ici_iff_exists_Icc_subset [no_top_order α] [densely_ordered α]
{a : α} {s : set α} : s ∈ 𝓝[Ici a] a ↔ ∃u, a < u ∧ Icc a u ⊆ s :=
begin
rw mem_nhds_within_Ici_iff_exists_Ico_subset,
split,
{ rintros ⟨u, au, as⟩,
rcases exists_between au with ⟨v, hv⟩,
exact ⟨v, hv.1, λx hx, as ⟨hx.1, lt_of_le_of_lt hx.2 hv.2⟩⟩ },
{ rintros ⟨u, au, as⟩,
exact ⟨u, au, subset.trans Ico_subset_Icc_self as⟩ }
end
/-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `[l, a]`
with `l < a`. -/
lemma mem_nhds_within_Iic_iff_exists_Icc_subset [no_bot_order α] [densely_ordered α]
{a : α} {s : set α} : s ∈ 𝓝[Iic a] a ↔ ∃l, l < a ∧ Icc l a ⊆ s :=
begin
rw mem_nhds_within_Iic_iff_exists_Ioc_subset,
split,
{ rintros ⟨l, la, as⟩,
rcases exists_between la with ⟨v, hv⟩,
refine ⟨v, hv.2, λx hx, as ⟨lt_of_lt_of_le hv.1 hx.1, hx.2⟩⟩, },
{ rintros ⟨l, la, as⟩,
exact ⟨l, la, subset.trans Ioc_subset_Icc_self as⟩ }
end
end linear_order
section linear_ordered_add_comm_group
variables [topological_space α] [linear_ordered_add_comm_group α] [order_topology α]
variables {l : filter β} {f g : β → α}
local notation `|` x `|` := abs x
lemma nhds_eq_infi_abs_sub (a : α) : 𝓝 a = (⨅r>0, 𝓟 {b | |a - b| < r}) :=
begin
simp only [le_antisymm_iff, nhds_eq_order, le_inf_iff, le_infi_iff, le_principal_iff, mem_Ioi,
mem_Iio, abs_sub_lt_iff, @sub_lt_iff_lt_add _ _ _ _ a, @sub_lt _ _ a, set_of_and],
refine ⟨_, _, _⟩,
{ intros ε ε0,
exact inter_mem_inf_sets
(mem_infi_sets (a - ε) $ mem_infi_sets (sub_lt_self a ε0) (mem_principal_self _))
(mem_infi_sets (ε + a) $ mem_infi_sets (by simpa) (mem_principal_self _)) },
{ intros b hb,
exact mem_infi_sets (a - b) (mem_infi_sets (sub_pos.2 hb) (by simp [Ioi])) },
{ intros b hb,
exact mem_infi_sets (b - a) (mem_infi_sets (sub_pos.2 hb) (by simp [Iio])) }
end
lemma order_topology_of_nhds_abs {α : Type*} [topological_space α] [linear_ordered_add_comm_group α]
(h_nhds : ∀a:α, 𝓝 a = (⨅r>0, 𝓟 {b | |a - b| < r})) : order_topology α :=
begin
refine ⟨eq_of_nhds_eq_nhds $ λ a, _⟩,
rw [h_nhds],
letI := preorder.topology α, letI : order_topology α := ⟨rfl⟩,
exact (nhds_eq_infi_abs_sub a).symm
end
lemma linear_ordered_add_comm_group.tendsto_nhds {x : filter β} {a : α} :
tendsto f x (𝓝 a) ↔ ∀ ε > (0 : α), ∀ᶠ b in x, |f b - a| < ε :=
by simp [nhds_eq_infi_abs_sub, abs_sub_comm a]
lemma eventually_abs_sub_lt (a : α) {ε : α} (hε : 0 < ε) : ∀ᶠ x in 𝓝 a, |x - a| < ε :=
(nhds_eq_infi_abs_sub a).symm ▸ mem_infi_sets ε
(mem_infi_sets hε $ by simp only [abs_sub_comm, mem_principal_self])
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_add_comm_group.topological_add_group : topological_add_group α :=
{ continuous_add :=
begin
refine continuous_iff_continuous_at.2 _,
rintro ⟨a, b⟩,
refine linear_ordered_add_comm_group.tendsto_nhds.2 (λ ε ε0, _),
rcases dense_or_discrete 0 ε with (⟨δ, δ0, δε⟩|⟨h₁, h₂⟩),
{ -- If there exists `δ ∈ (0, ε)`, then we choose `δ`-nhd of `a` and `(ε-δ)`-nhd of `b`
filter_upwards [prod_is_open.mem_nhds (eventually_abs_sub_lt a δ0)
(eventually_abs_sub_lt b (sub_pos.2 δε))],
rintros ⟨x, y⟩ ⟨hx : |x - a| < δ, hy : |y - b| < ε - δ⟩,
rw [add_sub_comm],
calc |x - a + (y - b)| ≤ |x - a| + |y - b| : abs_add _ _
... < δ + (ε - δ) : add_lt_add hx hy
... = ε : add_sub_cancel'_right _ _ },
{ -- Otherewise `ε`-nhd of each point `a` is `{a}`
have hε : ∀ {x y}, abs (x - y) < ε → x = y,
{ intros x y h,
simpa [sub_eq_zero] using h₂ _ h },
filter_upwards [prod_is_open.mem_nhds (eventually_abs_sub_lt a ε0)
(eventually_abs_sub_lt b ε0)],
rintros ⟨x, y⟩ ⟨hx : |x - a| < ε, hy : |y - b| < ε⟩,
simpa [hε hx, hε hy] }
end,
continuous_neg := continuous_iff_continuous_at.2 $ λ a,
linear_ordered_add_comm_group.tendsto_nhds.2 $ λ ε ε0,
(eventually_abs_sub_lt a ε0).mono $ λ x hx, by rwa [neg_sub_neg, abs_sub_comm] }
@[continuity]
lemma continuous_abs : continuous (abs : α → α) := continuous_id.max continuous_neg
lemma filter.tendsto.abs {f : β → α} {a : α} {l : filter β} (h : tendsto f l (𝓝 a)) :
tendsto (λ x, |f x|) l (𝓝 (|a|)) :=
(continuous_abs.tendsto _).comp h
lemma nhds_basis_Ioo_pos [no_bot_order α] [no_top_order α] (a : α) :
(𝓝 a).has_basis (λ ε : α, (0 : α) < ε) (λ ε, Ioo (a-ε) (a+ε)) :=
⟨begin
refine λ t, (nhds_basis_Ioo a).mem_iff.trans ⟨_, _⟩,
{ rintros ⟨⟨l, u⟩, ⟨hl : l < a, hu : a < u⟩, h' : Ioo l u ⊆ t⟩,
refine ⟨min (a-l) (u-a), by apply lt_min; rwa sub_pos, _⟩,
rintros x ⟨hx, hx'⟩,
apply h',
rw [sub_lt, lt_min_iff, sub_lt_sub_iff_left] at hx,
rw [← sub_lt_iff_lt_add', lt_min_iff, sub_lt_sub_iff_right] at hx',
exact ⟨hx.1, hx'.2⟩ },
{ rintros ⟨ε, ε_pos, h⟩,
exact ⟨(a-ε, a+ε), by simp [ε_pos], h⟩ },
end⟩
lemma nhds_basis_abs_sub_lt [no_bot_order α] [no_top_order α] (a : α) :
(𝓝 a).has_basis (λ ε : α, (0 : α) < ε) (λ ε, {b | abs (b - a) < ε}) :=
begin
convert nhds_basis_Ioo_pos a,
{ ext ε,
change abs (x - a) < ε ↔ a - ε < x ∧ x < a + ε,
simp [abs_lt, sub_lt_iff_lt_add, add_comm ε a] },
end
variable (α)
lemma nhds_basis_zero_abs_sub_lt [no_bot_order α] [no_top_order α] :
(𝓝 (0 : α)).has_basis (λ ε : α, (0 : α) < ε) (λ ε, {b | abs b < ε}) :=
by simpa using nhds_basis_abs_sub_lt (0 : α)
variable {α}
/-- If `a` is positive we can form a basis from only nonnegative `Ioo` intervals -/
lemma nhds_basis_Ioo_pos_of_pos [no_bot_order α] [no_top_order α]
{a : α} (ha : 0 < a) :
(𝓝 a).has_basis (λ ε : α, (0 : α) < ε ∧ ε ≤ a) (λ ε, Ioo (a-ε) (a+ε)) :=
⟨ λ t, (nhds_basis_Ioo_pos a).mem_iff.trans
⟨λ h, let ⟨i, hi, hit⟩ := h in
⟨min i a, ⟨lt_min hi ha, min_le_right i a⟩, trans (Ioo_subset_Ioo
(sub_le_sub_left (min_le_left i a) a) (add_le_add_left (min_le_left i a) a)) hit⟩,
λ h, let ⟨i, hi, hit⟩ := h in ⟨i, hi.1, hit⟩ ⟩ ⟩
section
variables [topological_space β] {b : β} {a : α} {s : set β}
lemma continuous.abs (h : continuous f) : continuous (λ x, |f x|) := continuous_abs.comp h
lemma continuous_at.abs (h : continuous_at f b) : continuous_at (λ x, |f x|) b := h.abs
lemma continuous_within_at.abs (h : continuous_within_at f s b) :
continuous_within_at (λ x, |f x|) s b := h.abs
lemma continuous_on.abs (h : continuous_on f s) : continuous_on (λ x, |f x|) s :=
λ x hx, (h x hx).abs
lemma tendsto_abs_nhds_within_zero : tendsto (abs : α → α) (𝓝[{0}ᶜ] 0) (𝓝[Ioi 0] 0) :=
(continuous_abs.tendsto' (0 : α) 0 abs_zero).inf $ tendsto_principal_principal.2 $ λ x, abs_pos.2
end
/-- In a linearly ordered additive commutative group with the order topology, if `f` tends to `C`
and `g` tends to `at_top` then `f + g` tends to `at_top`. -/
lemma filter.tendsto.add_at_top {C : α} (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_top) :
tendsto (λ x, f x + g x) l at_top :=
begin
nontriviality α,
obtain ⟨C', hC'⟩ : ∃ C', C' < C := no_bot C,
refine tendsto_at_top_add_left_of_le' _ C' _ hg,
exact (hf.eventually (lt_mem_nhds hC')).mono (λ x, le_of_lt)
end
/-- In a linearly ordered additive commutative group with the order topology, if `f` tends to `C`
and `g` tends to `at_bot` then `f + g` tends to `at_bot`. -/
lemma filter.tendsto.add_at_bot {C : α} (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_bot) :
tendsto (λ x, f x + g x) l at_bot :=
@filter.tendsto.add_at_top (order_dual α) _ _ _ _ _ _ _ _ hf hg
/-- In a linearly ordered additive commutative group with the order topology, if `f` tends to
`at_top` and `g` tends to `C` then `f + g` tends to `at_top`. -/
lemma filter.tendsto.at_top_add {C : α} (hf : tendsto f l at_top) (hg : tendsto g l (𝓝 C)) :
tendsto (λ x, f x + g x) l at_top :=
by { conv in (_ + _) { rw add_comm }, exact hg.add_at_top hf }
/-- In a linearly ordered additive commutative group with the order topology, if `f` tends to
`at_bot` and `g` tends to `C` then `f + g` tends to `at_bot`. -/
lemma filter.tendsto.at_bot_add {C : α} (hf : tendsto f l at_bot) (hg : tendsto g l (𝓝 C)) :
tendsto (λ x, f x + g x) l at_bot :=
by { conv in (_ + _) { rw add_comm }, exact hg.add_at_bot hf }
end linear_ordered_add_comm_group
section linear_ordered_field
variables [linear_ordered_field α] [topological_space α] [order_topology α]
variables {l : filter β} {f g : β → α}
section continuous_mul
lemma mul_tendsto_nhds_zero_right (x : α) :
tendsto (uncurry ((*) : α → α → α)) (𝓝 0 ×ᶠ 𝓝 x) $ 𝓝 0 :=
begin
have hx : 0 < 2 * (1 + abs x) := (mul_pos (zero_lt_two) $
lt_of_lt_of_le zero_lt_one $ le_add_of_le_of_nonneg le_rfl (abs_nonneg x)),
rw ((nhds_basis_zero_abs_sub_lt α).prod $ nhds_basis_abs_sub_lt x).tendsto_iff
(nhds_basis_zero_abs_sub_lt α),
refine λ ε ε_pos, ⟨(ε/(2 * (1 + abs x)), 1), ⟨div_pos ε_pos hx, zero_lt_one⟩, _⟩,
suffices : ∀ (a b : α), abs a < ε / (2 * (1 + abs x)) → abs (b - x) < 1 → (abs a) * (abs b) < ε,
by simpa only [and_imp, prod.forall, mem_prod, ← abs_mul],
intros a b h h',
refine lt_of_le_of_lt (mul_le_mul_of_nonneg_left _ (abs_nonneg a)) ((lt_div_iff hx).1 h),
calc abs b = abs ((b - x) + x) : by rw sub_add_cancel b x
... ≤ abs (b - x) + abs x : abs_add (b - x) x
... ≤ 1 + abs x : add_le_add_right (le_of_lt h') (abs x)
... ≤ 2 * (1 + abs x) : by linarith,
end
lemma mul_tendsto_nhds_zero_left (x : α) :
tendsto (uncurry ((*) : α → α → α)) (𝓝 x ×ᶠ 𝓝 0) $ 𝓝 0 :=
begin
intros s hs,
have := mul_tendsto_nhds_zero_right x hs,
rw [filter.mem_map, mem_prod_iff] at this ⊢,
obtain ⟨U, hU, V, hV, h⟩ := this,
exact ⟨V, hV, U, hU, λ y hy, ((mul_comm y.2 y.1) ▸
h (⟨hy.2, hy.1⟩ : (prod.mk y.2 y.1) ∈ (U.prod V)) : y.1 * y.2 ∈ s)⟩,
end
lemma nhds_eq_map_mul_left_nhds_one {x₀ : α} (hx₀ : x₀ ≠ 0) :
𝓝 x₀ = map (λ x, x₀*x) (𝓝 1) :=
begin
have hx₀' : 0 < abs x₀ := abs_pos.2 hx₀,
refine filter.ext (λ t, _),
simp only [exists_prop, set_of_subset_set_of, (nhds_basis_abs_sub_lt x₀).mem_iff,
(nhds_basis_abs_sub_lt (1 : α)).mem_iff, filter.mem_map],
refine ⟨λ h, _, λ h, _⟩,
{ obtain ⟨i, hi, hit⟩ := h,
refine ⟨i / (abs x₀), div_pos hi (abs_pos.2 hx₀), λ x hx, hit _⟩,
calc abs (x₀ * x - x₀) = abs (x₀ * (x - 1)) : congr_arg abs (by ring_nf)
... = abs x₀ * abs (x - 1) : abs_mul x₀ (x - 1)
... < abs x₀ * (i / abs x₀) : mul_lt_mul' le_rfl hx (abs_nonneg (x - 1)) (abs_pos.2 hx₀)
... = abs x₀ * i / abs x₀ : by ring
... = i : mul_div_cancel_left i (λ h, hx₀ (abs_eq_zero.1 h)) },
{ obtain ⟨i, hi, hit⟩ := h,
refine ⟨i * (abs x₀), mul_pos hi (abs_pos.2 hx₀), λ x hx, _⟩,
have : abs (x / x₀ - 1) < i,
calc abs (x / x₀ - 1) = abs (x / x₀ - x₀ / x₀) : (by rw div_self hx₀)
... = abs ((x - x₀) / x₀) : congr_arg abs (sub_div x x₀ x₀).symm
... = abs (x - x₀) / abs x₀ : abs_div (x - x₀) x₀
... < i * abs x₀ / abs x₀ : div_lt_div hx le_rfl
(mul_nonneg (le_of_lt hi) (abs_nonneg x₀)) (abs_pos.2 hx₀)
... = i : by rw [← mul_div_assoc', div_self (ne_of_lt $ abs_pos.2 hx₀).symm, mul_one],
specialize hit (x / x₀) this,
rwa [mul_div_assoc', mul_div_cancel_left x hx₀] at hit }
end
lemma nhds_eq_map_mul_right_nhds_one {x₀ : α} (hx₀ : x₀ ≠ 0) :
𝓝 x₀ = map (λ x, x*x₀) (𝓝 1) :=
by simp_rw [mul_comm _ x₀, nhds_eq_map_mul_left_nhds_one hx₀]
lemma mul_tendsto_nhds_one_nhds_one :
tendsto (uncurry ((*) : α → α → α)) (𝓝 1 ×ᶠ 𝓝 1) $ 𝓝 1 :=
begin
rw ((nhds_basis_Ioo_pos (1 : α)).prod $ nhds_basis_Ioo_pos (1 : α)).tendsto_iff
(nhds_basis_Ioo_pos_of_pos (zero_lt_one : (0 : α) < 1)),
intros ε hε,
have hε' : 0 ≤ 1 - ε / 4 := by linarith,
have ε_pos : 0 < ε / 4 := by linarith,
have ε_pos' : 0 < ε / 2 := by linarith,
simp only [and_imp, prod.forall, mem_Ioo, function.uncurry_apply_pair, mem_prod, prod.exists],
refine ⟨ε/4, ε/4, ⟨ε_pos, ε_pos⟩, λ a b ha ha' hb hb', _⟩,
have ha0 : 0 ≤ a := le_trans hε' (le_of_lt ha),
have hb0 : 0 ≤ b := le_trans hε' (le_of_lt hb),
refine ⟨lt_of_le_of_lt _ (mul_lt_mul'' ha hb hε' hε'),
lt_of_lt_of_le (mul_lt_mul'' ha' hb' ha0 hb0) _⟩,
{ calc 1 - ε = 1 - ε / 2 - ε/2 : by ring_nf
... ≤ 1 - ε/2 - ε/2 + (ε/2)*(ε/2) : le_add_of_nonneg_right (le_of_lt (mul_pos ε_pos' ε_pos'))
... = (1 - ε/2) * (1 - ε/2) : by ring_nf
... ≤ (1 - ε/4) * (1 - ε/4) : mul_le_mul (by linarith) (by linarith) (by linarith) hε' },
{ calc (1 + ε/4) * (1 + ε/4) = 1 + ε/2 + (ε/4)*(ε/4) : by ring_nf
... = 1 + ε/2 + (ε * ε) / 16 : by ring_nf
... ≤ 1 + ε/2 + ε/2 : add_le_add_left (div_le_div (le_of_lt hε.1) (le_trans
((mul_le_mul_left hε.1).2 hε.2) (le_of_eq $ mul_one ε)) zero_lt_two (by linarith)) (1 + ε/2)
... ≤ 1 + ε : by ring_nf }
end
@[priority 100]
instance linear_ordered_field.has_continuous_mul : has_continuous_mul α :=
⟨begin
rw continuous_iff_continuous_at,
rintro ⟨x₀, y₀⟩,
by_cases hx₀ : x₀ = 0,
{ rw [hx₀, continuous_at, zero_mul, nhds_prod_eq],
exact mul_tendsto_nhds_zero_right y₀ },
by_cases hy₀ : y₀ = 0,
{ rw [hy₀, continuous_at, mul_zero, nhds_prod_eq],
exact mul_tendsto_nhds_zero_left x₀ },
have hxy : x₀ * y₀ ≠ 0 := mul_ne_zero hx₀ hy₀,
have key : (λ p : α × α, x₀ * p.1 * (p.2 * y₀)) = ((λ x, x₀*x) ∘ (λ x, x*y₀)) ∘ (uncurry (*)),
{ ext p, simp [uncurry, mul_assoc] },
have key₂ : (λ x, x₀*x) ∘ (λ x, y₀*x) = λ x, (x₀ *y₀)*x,
{ ext x, simp },
calc map (uncurry (*)) (𝓝 (x₀, y₀))
= map (uncurry (*)) (𝓝 x₀ ×ᶠ 𝓝 y₀) : by rw nhds_prod_eq
... = map (λ (p : α × α), x₀ * p.1 * (p.2 * y₀)) ((𝓝 1) ×ᶠ (𝓝 1))
: by rw [uncurry, nhds_eq_map_mul_left_nhds_one hx₀, nhds_eq_map_mul_right_nhds_one hy₀,
prod_map_map_eq, filter.map_map]
... = map ((λ x, x₀ * x) ∘ λ x, x * y₀) (map (uncurry (*)) (𝓝 1 ×ᶠ 𝓝 1))
: by rw [key, ← filter.map_map]
... ≤ map ((λ (x : α), x₀ * x) ∘ λ x, x * y₀) (𝓝 1) : map_mono (mul_tendsto_nhds_one_nhds_one)
... = 𝓝 (x₀*y₀) : by rw [← filter.map_map, ← nhds_eq_map_mul_right_nhds_one hy₀,
nhds_eq_map_mul_left_nhds_one hy₀, filter.map_map, key₂, ← nhds_eq_map_mul_left_nhds_one hxy],
end⟩
end continuous_mul
/-- In a linearly ordered field with the order topology, if `f` tends to `at_top` and `g` tends to
a positive constant `C` then `f * g` tends to `at_top`. -/
lemma filter.tendsto.at_top_mul {C : α} (hC : 0 < C) (hf : tendsto f l at_top)
(hg : tendsto g l (𝓝 C)) :
tendsto (λ x, (f x * g x)) l at_top :=
begin
refine tendsto_at_top_mono' _ _ (hf.at_top_mul_const (half_pos hC)),
filter_upwards [hg.eventually (lt_mem_nhds (half_lt_self hC)),
hf.eventually (eventually_ge_at_top 0)],
exact λ x hg hf, mul_le_mul_of_nonneg_left hg.le hf
end
/-- In a linearly ordered field with the order topology, if `f` tends to a positive constant `C` and
`g` tends to `at_top` then `f * g` tends to `at_top`. -/
lemma filter.tendsto.mul_at_top {C : α} (hC : 0 < C) (hf : tendsto f l (𝓝 C))
(hg : tendsto g l at_top) :
tendsto (λ x, (f x * g x)) l at_top :=
by simpa only [mul_comm] using hg.at_top_mul hC hf
/-- In a linearly ordered field with the order topology, if `f` tends to `at_top` and `g` tends to
a negative constant `C` then `f * g` tends to `at_bot`. -/
lemma filter.tendsto.at_top_mul_neg {C : α} (hC : C < 0) (hf : tendsto f l at_top)
(hg : tendsto g l (𝓝 C)) :
tendsto (λ x, (f x * g x)) l at_bot :=
by simpa only [(∘), neg_mul_eq_mul_neg, neg_neg]
using tendsto_neg_at_top_at_bot.comp (hf.at_top_mul (neg_pos.2 hC) hg.neg)
/-- In a linearly ordered field with the order topology, if `f` tends to a negative constant `C` and
`g` tends to `at_top` then `f * g` tends to `at_bot`. -/
lemma filter.tendsto.neg_mul_at_top {C : α} (hC : C < 0) (hf : tendsto f l (𝓝 C))
(hg : tendsto g l at_top) :
tendsto (λ x, (f x * g x)) l at_bot :=
by simpa only [mul_comm] using hg.at_top_mul_neg hC hf
/-- In a linearly ordered field with the order topology, if `f` tends to `at_bot` and `g` tends to
a positive constant `C` then `f * g` tends to `at_bot`. -/
lemma filter.tendsto.at_bot_mul {C : α} (hC : 0 < C) (hf : tendsto f l at_bot)
(hg : tendsto g l (𝓝 C)) :
tendsto (λ x, (f x * g x)) l at_bot :=
by simpa [(∘)]
using tendsto_neg_at_top_at_bot.comp ((tendsto_neg_at_bot_at_top.comp hf).at_top_mul hC hg)
/-- In a linearly ordered field with the order topology, if `f` tends to `at_bot` and `g` tends to
a negative constant `C` then `f * g` tends to `at_top`. -/
lemma filter.tendsto.at_bot_mul_neg {C : α} (hC : C < 0) (hf : tendsto f l at_bot)
(hg : tendsto g l (𝓝 C)) :
tendsto (λ x, (f x * g x)) l at_top :=
by simpa [(∘)]
using tendsto_neg_at_bot_at_top.comp ((tendsto_neg_at_bot_at_top.comp hf).at_top_mul_neg hC hg)
/-- In a linearly ordered field with the order topology, if `f` tends to a positive constant `C` and
`g` tends to `at_bot` then `f * g` tends to `at_bot`. -/
lemma filter.tendsto.mul_at_bot {C : α} (hC : 0 < C) (hf : tendsto f l (𝓝 C))
(hg : tendsto g l at_bot) :
tendsto (λ x, (f x * g x)) l at_bot :=
by simpa only [mul_comm] using hg.at_bot_mul hC hf
/-- In a linearly ordered field with the order topology, if `f` tends to a negative constant `C` and
`g` tends to `at_bot` then `f * g` tends to `at_top`. -/
lemma filter.tendsto.neg_mul_at_bot {C : α} (hC : C < 0) (hf : tendsto f l (𝓝 C))
(hg : tendsto g l at_bot) :
tendsto (λ x, (f x * g x)) l at_top :=
by simpa only [mul_comm] using hg.at_bot_mul_neg hC hf
/-- The function `x ↦ x⁻¹` tends to `+∞` on the right of `0`. -/
lemma tendsto_inv_zero_at_top : tendsto (λx:α, x⁻¹) (𝓝[set.Ioi (0:α)] 0) at_top :=
begin
refine (at_top_basis' 1).tendsto_right_iff.2 (λ b hb, _),
have hb' : 0 < b := zero_lt_one.trans_le hb,
filter_upwards [Ioc_mem_nhds_within_Ioi ⟨le_rfl, inv_pos.2 hb'⟩],
exact λ x hx, (le_inv hx.1 hb').1 hx.2
end
/-- The function `r ↦ r⁻¹` tends to `0` on the right as `r → +∞`. -/
lemma tendsto_inv_at_top_zero' : tendsto (λr:α, r⁻¹) at_top (𝓝[set.Ioi (0:α)] 0) :=
begin
refine (has_basis.tendsto_iff at_top_basis ⟨λ s, mem_nhds_within_Ioi_iff_exists_Ioc_subset⟩).2 _,
refine λ b hb, ⟨b⁻¹, trivial, λ x hx, _⟩,
have : 0 < x := lt_of_lt_of_le (inv_pos.2 hb) hx,
exact ⟨inv_pos.2 this, (inv_le this hb).2 hx⟩
end
lemma tendsto_inv_at_top_zero : tendsto (λr:α, r⁻¹) at_top (𝓝 0) :=
tendsto_inv_at_top_zero'.mono_right inf_le_left
lemma filter.tendsto.div_at_top [has_continuous_mul α] {f g : β → α} {l : filter β} {a : α}
(h : tendsto f l (𝓝 a)) (hg : tendsto g l at_top) : tendsto (λ x, f x / g x) l (𝓝 0) :=
by { simp only [div_eq_mul_inv], exact mul_zero a ▸ h.mul (tendsto_inv_at_top_zero.comp hg) }
lemma filter.tendsto.inv_tendsto_at_top (h : tendsto f l at_top) : tendsto (f⁻¹) l (𝓝 0) :=
tendsto_inv_at_top_zero.comp h
lemma filter.tendsto.inv_tendsto_zero (h : tendsto f l (𝓝[set.Ioi 0] 0)) :
tendsto (f⁻¹) l at_top :=
tendsto_inv_zero_at_top.comp h
/-- The function `x^(-n)` tends to `0` at `+∞` for any positive natural `n`.
A version for positive real powers exists as `tendsto_rpow_neg_at_top`. -/
lemma tendsto_pow_neg_at_top {n : ℕ} (hn : 1 ≤ n) : tendsto (λ x : α, x ^ (-(n:ℤ))) at_top (𝓝 0) :=
tendsto.congr (λ x, (fpow_neg x n).symm)
(filter.tendsto.inv_tendsto_at_top (by simpa [gpow_coe_nat] using tendsto_pow_at_top hn))
lemma tendsto_fpow_at_top_zero {n : ℤ} (hn : n < 0) :
tendsto (λ x : α, x^n) at_top (𝓝 0) :=
begin
have : 1 ≤ -n := le_neg.mp (int.le_of_lt_add_one (hn.trans_le (neg_add_self 1).symm.le)),
apply tendsto.congr (show ∀ x : α, x^-(-n) = x^n, by simp),
lift -n to ℕ using le_of_lt (neg_pos.mpr hn) with N,
exact tendsto_pow_neg_at_top (by exact_mod_cast this)
end
lemma tendsto_const_mul_fpow_at_top_zero {n : ℤ} {c : α} (hn : n < 0) :
tendsto (λ x, c * x ^ n) at_top (𝓝 0) :=
(mul_zero c) ▸ (filter.tendsto.const_mul c (tendsto_fpow_at_top_zero hn))
lemma tendsto_const_mul_pow_nhds_iff {n : ℕ} {c d : α} (hc : c ≠ 0) :
tendsto (λ x : α, c * x ^ n) at_top (𝓝 d) ↔ n = 0 ∧ c = d :=
begin
refine ⟨λ h, _, λ h, _⟩,
{ have hn : n = 0,
{ by_contradiction hn,
have hn : 1 ≤ n := nat.succ_le_iff.2 (lt_of_le_of_ne (zero_le _) (ne.symm hn)),
by_cases hc' : 0 < c,
{ have := (tendsto_const_mul_pow_at_top_iff c n).2 ⟨hn, hc'⟩,
exact not_tendsto_nhds_of_tendsto_at_top this d h },
{ have := (tendsto_neg_const_mul_pow_at_top_iff c n).2 ⟨hn, lt_of_le_of_ne (not_lt.1 hc') hc⟩,
exact not_tendsto_nhds_of_tendsto_at_bot this d h } },
have : (λ x : α, c * x ^ n) = (λ x : α, c), by simp [hn],
rw [this, tendsto_const_nhds_iff] at h,
exact ⟨hn, h⟩ },
{ obtain ⟨hn, hcd⟩ := h,
simpa [hn, hcd] using tendsto_const_nhds }
end
lemma tendsto_const_mul_fpow_at_top_zero_iff {n : ℤ} {c d : α} (hc : c ≠ 0) :
tendsto (λ x : α, c * x ^ n) at_top (𝓝 d) ↔
(n = 0 ∧ c = d) ∨ (n < 0 ∧ d = 0) :=
begin
refine ⟨λ h, _, λ h, _⟩,
{ by_cases hn : 0 ≤ n,
{ lift n to ℕ using hn,
simp only [gpow_coe_nat] at h,
rw [tendsto_const_mul_pow_nhds_iff hc, ← int.coe_nat_eq_zero] at h,
exact or.inl h },
{ rw not_le at hn,
refine or.inr ⟨hn, tendsto_nhds_unique h (tendsto_const_mul_fpow_at_top_zero hn)⟩ } },
{ cases h,
{ simp only [h.left, h.right, gpow_zero, mul_one],
exact tendsto_const_nhds },
{ exact h.2.symm ▸ tendsto_const_mul_fpow_at_top_zero h.1} }
end
end linear_ordered_field
lemma preimage_neg [add_group α] : preimage (has_neg.neg : α → α) = image (has_neg.neg : α → α) :=
(image_eq_preimage_of_inverse neg_neg neg_neg).symm
lemma filter.map_neg [add_group α] : map (has_neg.neg : α → α) = comap (has_neg.neg : α → α) :=
funext $ assume f, map_eq_comap_of_inverse (funext neg_neg) (funext neg_neg)
section order_topology
variables [topological_space α] [topological_space β]
[linear_order α] [linear_order β] [order_topology α] [order_topology β]
lemma is_lub.frequently_mem {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) :
∃ᶠ x in 𝓝[Iic a] a, x ∈ s :=
begin
rcases hs with ⟨a', ha'⟩,
intro h,
rcases (ha.1 ha').eq_or_lt with (rfl|ha'a),
{ exact h.self_of_nhds_within le_rfl ha' },
{ rcases (mem_nhds_within_Iic_iff_exists_Ioc_subset' ha'a).1 h
with ⟨b, hba, hb⟩,
rcases ha.exists_between hba with ⟨b', hb's, hb'⟩,
exact hb hb' hb's },
end
lemma is_lub.frequently_nhds_mem {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) :
∃ᶠ x in 𝓝 a, x ∈ s :=
(ha.frequently_mem hs).filter_mono inf_le_left
lemma is_glb.frequently_mem {a : α} {s : set α} (ha : is_glb s a) (hs : s.nonempty) :
∃ᶠ x in 𝓝[Ici a] a, x ∈ s :=
@is_lub.frequently_mem (order_dual α) _ _ _ _ _ ha hs
lemma is_glb.frequently_nhds_mem {a : α} {s : set α} (ha : is_glb s a) (hs : s.nonempty) :
∃ᶠ x in 𝓝 a, x ∈ s :=
(ha.frequently_mem hs).filter_mono inf_le_left
lemma is_lub.mem_closure {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) :
a ∈ closure s :=
(ha.frequently_nhds_mem hs).mem_closure
lemma is_glb.mem_closure {a : α} {s : set α} (ha : is_glb s a) (hs : s.nonempty) :
a ∈ closure s :=
(ha.frequently_nhds_mem hs).mem_closure
lemma is_lub.nhds_within_ne_bot {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) :
ne_bot (𝓝[s] a) :=
mem_closure_iff_nhds_within_ne_bot.1 (ha.mem_closure hs)
lemma is_glb.nhds_within_ne_bot : ∀ {a : α} {s : set α}, is_glb s a → s.nonempty →
ne_bot (𝓝[s] a) :=
@is_lub.nhds_within_ne_bot (order_dual α) _ _ _
lemma is_lub_of_mem_nhds {s : set α} {a : α} {f : filter α}
(hsa : a ∈ upper_bounds s) (hsf : s ∈ f) [ne_bot (f ⊓ 𝓝 a)] : is_lub s a :=
⟨hsa, assume b hb,
not_lt.1 $ assume hba,
have s ∩ {a | b < a} ∈ f ⊓ 𝓝 a,
from inter_mem_inf_sets hsf (is_open.mem_nhds (is_open_lt' _) hba),
let ⟨x, ⟨hxs, hxb⟩⟩ := nonempty_of_mem_sets this in
have b < b, from lt_of_lt_of_le hxb $ hb hxs,
lt_irrefl b this⟩
lemma is_glb_of_mem_nhds : ∀ {s : set α} {a : α} {f : filter α},
a ∈ lower_bounds s → s ∈ f → ne_bot (f ⊓ 𝓝 a) → is_glb s a :=
@is_lub_of_mem_nhds (order_dual α) _ _ _
lemma is_lub.mem_upper_bounds_of_tendsto [preorder γ] [topological_space γ]
[order_closed_topology γ] {f : α → γ} {s : set α} {a : α} {b : γ}
(hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) (ha : is_lub s a)
(hb : tendsto f (𝓝[s] a) (𝓝 b)) : b ∈ upper_bounds (f '' s) :=
begin
rintro _ ⟨x, hx, rfl⟩,
replace ha := ha.inter_Ici_of_mem hx,
haveI := ha.nhds_within_ne_bot ⟨x, hx, le_rfl⟩,
refine ge_of_tendsto (hb.mono_left (nhds_within_mono _ (inter_subset_left s (Ici x)))) _,
exact mem_sets_of_superset self_mem_nhds_within (λ y hy, hf _ hx _ hy.1 hy.2)
end
-- For a version of this theorem in which the convergence considered on the domain `α` is as
-- `x : α` tends to infinity, rather than tending to a point `x` in `α`, see `is_lub_of_tendsto`,
-- below
lemma is_lub.is_lub_of_tendsto [preorder γ] [topological_space γ]
[order_closed_topology γ] {f : α → γ} {s : set α} {a : α} {b : γ}
(hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) (ha : is_lub s a) (hs : s.nonempty)
(hb : tendsto f (𝓝[s] a) (𝓝 b)) : is_lub (f '' s) b :=
begin
haveI := ha.nhds_within_ne_bot hs,
exact ⟨ha.mem_upper_bounds_of_tendsto hf hb, λ b' hb', le_of_tendsto hb
(mem_sets_of_superset self_mem_nhds_within $ λ x hx, hb' $ mem_image_of_mem _ hx)⟩
end
lemma is_glb.mem_lower_bounds_of_tendsto [preorder γ] [topological_space γ]
[order_closed_topology γ] {f : α → γ} {s : set α} {a : α} {b : γ}
(hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) (ha : is_glb s a)
(hb : tendsto f (𝓝[s] a) (𝓝 b)) : b ∈ lower_bounds (f '' s) :=
@is_lub.mem_upper_bounds_of_tendsto (order_dual α) (order_dual γ) _ _ _ _ _ _ _ _ _ _
(λ x hx y hy, hf y hy x hx) ha hb
-- For a version of this theorem in which the convergence considered on the domain `α` is as
-- `x : α` tends to negative infinity, rather than tending to a point `x` in `α`, see
-- `is_glb_of_tendsto`, below
lemma is_glb.is_glb_of_tendsto [preorder γ] [topological_space γ]
[order_closed_topology γ] {f : α → γ} {s : set α} {a : α} {b : γ}
(hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) : is_glb s a → s.nonempty →
tendsto f (𝓝[s] a) (𝓝 b) → is_glb (f '' s) b :=
@is_lub.is_lub_of_tendsto (order_dual α) (order_dual γ) _ _ _ _ _ _ f s a b
(λ x hx y hy, hf y hy x hx)
lemma is_lub.mem_lower_bounds_of_tendsto [preorder γ] [topological_space γ]
[order_closed_topology γ] {f : α → γ} {s : set α} {a : α} {b : γ}
(hf : ∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) (ha : is_lub s a)
(hb : tendsto f (𝓝[s] a) (𝓝 b)) : b ∈ lower_bounds (f '' s) :=
@is_lub.mem_upper_bounds_of_tendsto α (order_dual γ) _ _ _ _ _ _ _ _ _ _ hf ha hb
lemma is_lub.is_glb_of_tendsto [preorder γ] [topological_space γ]
[order_closed_topology γ] : ∀ {f : α → γ} {s : set α} {a : α} {b : γ},
(∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) → is_lub s a → s.nonempty →
tendsto f (𝓝[s] a) (𝓝 b) → is_glb (f '' s) b :=
@is_lub.is_lub_of_tendsto α (order_dual γ) _ _ _ _ _ _
lemma is_glb.mem_upper_bounds_of_tendsto [preorder γ] [topological_space γ]
[order_closed_topology γ] {f : α → γ} {s : set α} {a : α} {b : γ}
(hf : ∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) (ha : is_glb s a)
(hb : tendsto f (𝓝[s] a) (𝓝 b)) : b ∈ upper_bounds (f '' s) :=
@is_glb.mem_lower_bounds_of_tendsto α (order_dual γ) _ _ _ _ _ _ _ _ _ _ hf ha hb
lemma is_glb.is_lub_of_tendsto [preorder γ] [topological_space γ]
[order_closed_topology γ] : ∀ {f : α → γ} {s : set α} {a : α} {b : γ},
(∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) → is_glb s a → s.nonempty →
tendsto f (𝓝[s] a) (𝓝 b) → is_lub (f '' s) b :=
@is_glb.is_glb_of_tendsto α (order_dual γ) _ _ _ _ _ _
lemma is_lub.mem_of_is_closed {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty)
(sc : is_closed s) : a ∈ s :=
sc.closure_subset $ ha.mem_closure hs
alias is_lub.mem_of_is_closed ← is_closed.is_lub_mem
lemma is_glb.mem_of_is_closed {a : α} {s : set α} (ha : is_glb s a) (hs : s.nonempty)
(sc : is_closed s) : a ∈ s :=
sc.closure_subset $ ha.mem_closure hs
alias is_glb.mem_of_is_closed ← is_closed.is_glb_mem
/-- A compact set is bounded below -/
lemma is_compact.bdd_below {α : Type u} [topological_space α] [linear_order α]
[order_closed_topology α] [nonempty α] {s : set α} (hs : is_compact s) : bdd_below s :=
begin
by_contra H,
rcases hs.elim_finite_subcover_image (λ x (_ : x ∈ s), @is_open_Ioi _ _ _ _ x) _
with ⟨t, st, ft, ht⟩,
{ refine H (ft.bdd_below.imp $ λ C hC y hy, _),
rcases mem_bUnion_iff.1 (ht hy) with ⟨x, hx, xy⟩,
exact le_trans (hC hx) (le_of_lt xy) },
{ refine λ x hx, mem_bUnion_iff.2 (not_imp_comm.1 _ H),
exact λ h, ⟨x, λ y hy, le_of_not_lt (h.imp $ λ ys, ⟨_, hy, ys⟩)⟩ }
end
/-- A compact set is bounded above -/
lemma is_compact.bdd_above {α : Type u} [topological_space α] [linear_order α]
[order_topology α] : Π [nonempty α] {s : set α}, is_compact s → bdd_above s :=
@is_compact.bdd_below (order_dual α) _ _ _
end order_topology
section linear_order
variables [topological_space α] [linear_order α] [order_topology α] [densely_ordered α]
/-- The closure of the interval `(a, +∞)` is the closed interval `[a, +∞)`, unless `a` is a top
element. -/
lemma closure_Ioi' {a b : α} (hab : a < b) :
closure (Ioi a) = Ici a :=
begin
apply subset.antisymm,
{ exact closure_minimal Ioi_subset_Ici_self is_closed_Ici },
{ rw [← diff_subset_closure_iff, Ici_diff_Ioi_same, singleton_subset_iff],
exact is_glb_Ioi.mem_closure ⟨_, hab⟩ }
end
/-- The closure of the interval `(a, +∞)` is the closed interval `[a, +∞)`. -/
@[simp] lemma closure_Ioi (a : α) [no_top_order α] :
closure (Ioi a) = Ici a :=
let ⟨b, hb⟩ := no_top a in closure_Ioi' hb
/-- The closure of the interval `(-∞, a)` is the closed interval `(-∞, a]`, unless `a` is a bottom
element. -/
lemma closure_Iio' {a b : α} (hab : b < a) :
closure (Iio a) = Iic a :=
@closure_Ioi' (order_dual α) _ _ _ _ _ _ hab
/-- The closure of the interval `(-∞, a)` is the interval `(-∞, a]`. -/
@[simp] lemma closure_Iio (a : α) [no_bot_order α] :
closure (Iio a) = Iic a :=
let ⟨b, hb⟩ := no_bot a in closure_Iio' hb
/-- The closure of the open interval `(a, b)` is the closed interval `[a, b]`. -/
@[simp] lemma closure_Ioo {a b : α} (hab : a < b) :
closure (Ioo a b) = Icc a b :=
begin
apply subset.antisymm,
{ exact closure_minimal Ioo_subset_Icc_self is_closed_Icc },
{ rw [← diff_subset_closure_iff, Icc_diff_Ioo_same hab.le],
have hab' : (Ioo a b).nonempty, from nonempty_Ioo.2 hab,
simp only [insert_subset, singleton_subset_iff],
exact ⟨(is_glb_Ioo hab).mem_closure hab', (is_lub_Ioo hab).mem_closure hab'⟩ }
end
/-- The closure of the interval `(a, b]` is the closed interval `[a, b]`. -/
@[simp] lemma closure_Ioc {a b : α} (hab : a < b) :
closure (Ioc a b) = Icc a b :=
begin
apply subset.antisymm,
{ exact closure_minimal Ioc_subset_Icc_self is_closed_Icc },
{ apply subset.trans _ (closure_mono Ioo_subset_Ioc_self),
rw closure_Ioo hab }
end
/-- The closure of the interval `[a, b)` is the closed interval `[a, b]`. -/
@[simp] lemma closure_Ico {a b : α} (hab : a < b) :
closure (Ico a b) = Icc a b :=
begin
apply subset.antisymm,
{ exact closure_minimal Ico_subset_Icc_self is_closed_Icc },
{ apply subset.trans _ (closure_mono Ioo_subset_Ico_self),
rw closure_Ioo hab }
end
@[simp] lemma interior_Ici [no_bot_order α] {a : α} : interior (Ici a) = Ioi a :=
by rw [← compl_Iio, interior_compl, closure_Iio, compl_Iic]
@[simp] lemma interior_Iic [no_top_order α] {a : α} : interior (Iic a) = Iio a :=
by rw [← compl_Ioi, interior_compl, closure_Ioi, compl_Ici]
@[simp] lemma interior_Icc [no_bot_order α] [no_top_order α] {a b : α}:
interior (Icc a b) = Ioo a b :=
by rw [← Ici_inter_Iic, interior_inter, interior_Ici, interior_Iic, Ioi_inter_Iio]
@[simp] lemma interior_Ico [no_bot_order α] {a b : α} : interior (Ico a b) = Ioo a b :=
by rw [← Ici_inter_Iio, interior_inter, interior_Ici, interior_Iio, Ioi_inter_Iio]
@[simp] lemma interior_Ioc [no_top_order α] {a b : α} : interior (Ioc a b) = Ioo a b :=
by rw [← Ioi_inter_Iic, interior_inter, interior_Ioi, interior_Iic, Ioi_inter_Iio]
@[simp] lemma frontier_Ici [no_bot_order α] {a : α} : frontier (Ici a) = {a} :=
by simp [frontier]
@[simp] lemma frontier_Iic [no_top_order α] {a : α} : frontier (Iic a) = {a} :=
by simp [frontier]
@[simp] lemma frontier_Ioi [no_top_order α] {a : α} : frontier (Ioi a) = {a} :=
by simp [frontier]
@[simp] lemma frontier_Iio [no_bot_order α] {a : α} : frontier (Iio a) = {a} :=
by simp [frontier]
@[simp] lemma frontier_Icc [no_bot_order α] [no_top_order α] {a b : α} (h : a < b) :
frontier (Icc a b) = {a, b} :=
by simp [frontier, le_of_lt h, Icc_diff_Ioo_same]
@[simp] lemma frontier_Ioo {a b : α} (h : a < b) : frontier (Ioo a b) = {a, b} :=
by simp [frontier, h, le_of_lt h, Icc_diff_Ioo_same]
@[simp] lemma frontier_Ico [no_bot_order α] {a b : α} (h : a < b) : frontier (Ico a b) = {a, b} :=
by simp [frontier, h, le_of_lt h, Icc_diff_Ioo_same]
@[simp] lemma frontier_Ioc [no_top_order α] {a b : α} (h : a < b) : frontier (Ioc a b) = {a, b} :=
by simp [frontier, h, le_of_lt h, Icc_diff_Ioo_same]
lemma nhds_within_Ioi_ne_bot' {a b c : α} (H₁ : a < c) (H₂ : a ≤ b) :
ne_bot (𝓝[Ioi a] b) :=
mem_closure_iff_nhds_within_ne_bot.1 $ by { rw [closure_Ioi' H₁], exact H₂ }
lemma nhds_within_Ioi_ne_bot [no_top_order α] {a b : α} (H : a ≤ b) :
ne_bot (𝓝[Ioi a] b) :=
let ⟨c, hc⟩ := no_top a in nhds_within_Ioi_ne_bot' hc H
lemma nhds_within_Ioi_self_ne_bot' {a b : α} (H : a < b) :
ne_bot (𝓝[Ioi a] a) :=
nhds_within_Ioi_ne_bot' H (le_refl a)
@[instance]
lemma nhds_within_Ioi_self_ne_bot [no_top_order α] (a : α) :
ne_bot (𝓝[Ioi a] a) :=
nhds_within_Ioi_ne_bot (le_refl a)
lemma nhds_within_Iio_ne_bot' {a b c : α} (H₁ : a < c) (H₂ : b ≤ c) :
ne_bot (𝓝[Iio c] b) :=
mem_closure_iff_nhds_within_ne_bot.1 $ by { rw [closure_Iio' H₁], exact H₂ }
lemma nhds_within_Iio_ne_bot [no_bot_order α] {a b : α} (H : a ≤ b) :
ne_bot (𝓝[Iio b] a) :=
let ⟨c, hc⟩ := no_bot b in nhds_within_Iio_ne_bot' hc H
lemma nhds_within_Iio_self_ne_bot' {a b : α} (H : a < b) :
ne_bot (𝓝[Iio b] b) :=
nhds_within_Iio_ne_bot' H (le_refl b)
@[instance]
lemma nhds_within_Iio_self_ne_bot [no_bot_order α] (a : α) :
ne_bot (𝓝[Iio a] a) :=
nhds_within_Iio_ne_bot (le_refl a)
lemma right_nhds_within_Ico_ne_bot {a b : α} (H : a < b) : ne_bot (𝓝[Ico a b] b) :=
(is_lub_Ico H).nhds_within_ne_bot (nonempty_Ico.2 H)
lemma left_nhds_within_Ioc_ne_bot {a b : α} (H : a < b) : ne_bot (𝓝[Ioc a b] a) :=
(is_glb_Ioc H).nhds_within_ne_bot (nonempty_Ioc.2 H)
lemma left_nhds_within_Ioo_ne_bot {a b : α} (H : a < b) : ne_bot (𝓝[Ioo a b] a) :=
(is_glb_Ioo H).nhds_within_ne_bot (nonempty_Ioo.2 H)
lemma right_nhds_within_Ioo_ne_bot {a b : α} (H : a < b) : ne_bot (𝓝[Ioo a b] b) :=
(is_lub_Ioo H).nhds_within_ne_bot (nonempty_Ioo.2 H)
end linear_order
section linear_order
variables [topological_space α] [linear_order α] [order_topology α] [densely_ordered α]
{a b : α} {s : set α}
lemma comap_coe_nhds_within_Iio_of_Ioo_subset (hb : s ⊆ Iio b)
(hs : s.nonempty → ∃ a < b, Ioo a b ⊆ s) :
comap (coe : s → α) (𝓝[Iio b] b) = at_top :=
begin
nontriviality,
haveI : nonempty s := nontrivial_iff_nonempty.1 ‹_›,
rcases hs (nonempty_subtype.1 ‹_›) with ⟨a, h, hs⟩,
ext u, split,
{ rintros ⟨t, ht, hts⟩,
obtain ⟨x, ⟨hxa : a ≤ x, hxb : x < b⟩, hxt : Ioo x b ⊆ t⟩ :=
(mem_nhds_within_Iio_iff_exists_mem_Ico_Ioo_subset h).mp ht,
obtain ⟨y, hxy, hyb⟩ := exists_between hxb,
refine mem_sets_of_superset (mem_at_top ⟨y, hs ⟨hxa.trans_lt hxy, hyb⟩⟩) _,
rintros ⟨z, hzs⟩ (hyz : y ≤ z),
refine hts (hxt ⟨hxy.trans_le _, hb _⟩); assumption },
{ intros hu,
obtain ⟨x : s, hx : ∀ z, x ≤ z → z ∈ u⟩ := mem_at_top_sets.1 hu,
exact ⟨Ioo x b, Ioo_mem_nhds_within_Iio (right_mem_Ioc.2 $ hb x.2), λ z hz, hx _ hz.1.le⟩ }
end
lemma comap_coe_nhds_within_Ioi_of_Ioo_subset (ha : s ⊆ Ioi a)
(hs : s.nonempty → ∃ b > a, Ioo a b ⊆ s) :
comap (coe : s → α) (𝓝[Ioi a] a) = at_bot :=
begin
refine @comap_coe_nhds_within_Iio_of_Ioo_subset (order_dual α) _ _ _ _ _ _ ha (λ h, _),
rcases hs h with ⟨b, hab, h⟩,
use [b, hab],
rwa dual_Ioo
end
lemma map_coe_at_top_of_Ioo_subset (hb : s ⊆ Iio b)
(hs : ∀ a' < b, ∃ a < b, Ioo a b ⊆ s) :
map (coe : s → α) at_top = 𝓝[Iio b] b :=
begin
rcases eq_empty_or_nonempty (Iio b) with (hb'|⟨a, ha⟩),
{ rw [filter_eq_bot_of_not_nonempty at_top, map_bot, hb', nhds_within_empty],
exact λ ⟨⟨x, hx⟩⟩, not_nonempty_iff_eq_empty.2 hb' ⟨x, hb hx⟩ },
{ rw [← comap_coe_nhds_within_Iio_of_Ioo_subset hb (λ _, hs a ha), map_comap_of_mem],
rw subtype.range_coe,
exact (mem_nhds_within_Iio_iff_exists_Ioo_subset' ha).2 (hs a ha) },
end
lemma map_coe_at_bot_of_Ioo_subset (ha : s ⊆ Ioi a)
(hs : ∀ b' > a, ∃ b > a, Ioo a b ⊆ s) :
map (coe : s → α) at_bot = (𝓝[Ioi a] a) :=
begin
refine @map_coe_at_top_of_Ioo_subset (order_dual α) _ _ _ _ a s ha (λ b' hb', _),
rcases hs b' hb' with ⟨b, hab, hbs⟩,
use [b, hab],
rwa dual_Ioo
end
/-- The `at_top` filter for an open interval `Ioo a b` comes from the left-neighbourhoods filter at
the right endpoint in the ambient order. -/
lemma comap_coe_Ioo_nhds_within_Iio (a b : α) :
comap (coe : Ioo a b → α) (𝓝[Iio b] b) = at_top :=
comap_coe_nhds_within_Iio_of_Ioo_subset Ioo_subset_Iio_self $
λ h, ⟨a, nonempty_Ioo.1 h, subset.refl _⟩
/-- The `at_bot` filter for an open interval `Ioo a b` comes from the right-neighbourhoods filter at
the left endpoint in the ambient order. -/
lemma comap_coe_Ioo_nhds_within_Ioi (a b : α) :
comap (coe : Ioo a b → α) (𝓝[Ioi a] a) = at_bot :=
comap_coe_nhds_within_Ioi_of_Ioo_subset Ioo_subset_Ioi_self $
λ h, ⟨b, nonempty_Ioo.1 h, subset.refl _⟩
lemma comap_coe_Ioi_nhds_within_Ioi (a : α) : comap (coe : Ioi a → α) (𝓝[Ioi a] a) = at_bot :=
comap_coe_nhds_within_Ioi_of_Ioo_subset (subset.refl _) $
λ ⟨x, hx⟩, ⟨x, hx, Ioo_subset_Ioi_self⟩
lemma comap_coe_Iio_nhds_within_Iio (a : α) :
comap (coe : Iio a → α) (𝓝[Iio a] a) = at_top :=
@comap_coe_Ioi_nhds_within_Ioi (order_dual α) _ _ _ _ a
@[simp] lemma map_coe_Ioo_at_top {a b : α} (h : a < b) :
map (coe : Ioo a b → α) at_top = 𝓝[Iio b] b :=
map_coe_at_top_of_Ioo_subset Ioo_subset_Iio_self $ λ _ _, ⟨_, h, subset.refl _⟩
@[simp] lemma map_coe_Ioo_at_bot {a b : α} (h : a < b) :
map (coe : Ioo a b → α) at_bot = 𝓝[Ioi a] a :=
map_coe_at_bot_of_Ioo_subset Ioo_subset_Ioi_self $ λ _ _, ⟨_, h, subset.refl _⟩
@[simp] lemma map_coe_Ioi_at_bot (a : α) :
map (coe : Ioi a → α) at_bot = 𝓝[Ioi a] a :=
map_coe_at_bot_of_Ioo_subset (subset.refl _) $ λ b hb, ⟨b, hb, Ioo_subset_Ioi_self⟩
@[simp] lemma map_coe_Iio_at_top (a : α) :
map (coe : Iio a → α) at_top = 𝓝[Iio a] a :=
@map_coe_Ioi_at_bot (order_dual α) _ _ _ _ _
variables {l : filter β} {f : α → β}
@[simp] lemma tendsto_comp_coe_Ioo_at_top (h : a < b) :
tendsto (λ x : Ioo a b, f x) at_top l ↔ tendsto f (𝓝[Iio b] b) l :=
by rw [← map_coe_Ioo_at_top h, tendsto_map'_iff]
@[simp] lemma tendsto_comp_coe_Ioo_at_bot (h : a < b) :
tendsto (λ x : Ioo a b, f x) at_bot l ↔ tendsto f (𝓝[Ioi a] a) l :=
by rw [← map_coe_Ioo_at_bot h, tendsto_map'_iff]
@[simp] lemma tendsto_comp_coe_Ioi_at_bot :
tendsto (λ x : Ioi a, f x) at_bot l ↔ tendsto f (𝓝[Ioi a] a) l :=
by rw [← map_coe_Ioi_at_bot, tendsto_map'_iff]
@[simp] lemma tendsto_comp_coe_Iio_at_top :
tendsto (λ x : Iio a, f x) at_top l ↔ tendsto f (𝓝[Iio a] a) l :=
by rw [← map_coe_Iio_at_top, tendsto_map'_iff]
@[simp] lemma tendsto_Ioo_at_top {f : β → Ioo a b} :
tendsto f l at_top ↔ tendsto (λ x, (f x : α)) l (𝓝[Iio b] b) :=
by rw [← comap_coe_Ioo_nhds_within_Iio, tendsto_comap_iff]
@[simp] lemma tendsto_Ioo_at_bot {f : β → Ioo a b} :
tendsto f l at_bot ↔ tendsto (λ x, (f x : α)) l (𝓝[Ioi a] a) :=
by rw [← comap_coe_Ioo_nhds_within_Ioi, tendsto_comap_iff]
@[simp] lemma tendsto_Ioi_at_bot {f : β → Ioi a} :
tendsto f l at_bot ↔ tendsto (λ x, (f x : α)) l (𝓝[Ioi a] a) :=
by rw [← comap_coe_Ioi_nhds_within_Ioi, tendsto_comap_iff]
@[simp] lemma tendsto_Iio_at_top {f : β → Iio a} :
tendsto f l at_top ↔ tendsto (λ x, (f x : α)) l (𝓝[Iio a] a) :=
by rw [← comap_coe_Iio_nhds_within_Iio, tendsto_comap_iff]
end linear_order
section complete_linear_order
variables [complete_linear_order α] [topological_space α] [order_topology α]
[complete_linear_order β] [topological_space β] [order_topology β] [nonempty γ]
lemma Sup_mem_closure {α : Type u} [topological_space α] [complete_linear_order α]
[order_topology α] {s : set α} (hs : s.nonempty) :
Sup s ∈ closure s :=
(is_lub_Sup s).mem_closure hs
lemma Inf_mem_closure {α : Type u} [topological_space α] [complete_linear_order α]
[order_topology α] {s : set α} (hs : s.nonempty) :
Inf s ∈ closure s :=
(is_glb_Inf s).mem_closure hs
lemma is_closed.Sup_mem {α : Type u} [topological_space α] [complete_linear_order α]
[order_topology α] {s : set α} (hs : s.nonempty) (hc : is_closed s) :
Sup s ∈ s :=
(is_lub_Sup s).mem_of_is_closed hs hc
lemma is_closed.Inf_mem {α : Type u} [topological_space α] [complete_linear_order α]
[order_topology α] {s : set α} (hs : s.nonempty) (hc : is_closed s) :
Inf s ∈ s :=
(is_glb_Inf s).mem_of_is_closed hs hc
/-- A monotone function continuous at the supremum of a nonempty set sends this supremum to
the supremum of the image of this set. -/
lemma map_Sup_of_continuous_at_of_monotone' {f : α → β} {s : set α} (Cf : continuous_at f (Sup s))
(Mf : monotone f) (hs : s.nonempty) :
f (Sup s) = Sup (f '' s) :=
--This is a particular case of the more general is_lub.is_lub_of_tendsto
((is_lub_Sup _).is_lub_of_tendsto (λ x hx y hy xy, Mf xy) hs $
Cf.mono_left inf_le_left).Sup_eq.symm
/-- A monotone function `s` sending `bot` to `bot` and continuous at the supremum of a set sends
this supremum to the supremum of the image of this set. -/
lemma map_Sup_of_continuous_at_of_monotone {f : α → β} {s : set α} (Cf : continuous_at f (Sup s))
(Mf : monotone f) (fbot : f ⊥ = ⊥) :
f (Sup s) = Sup (f '' s) :=
begin
cases s.eq_empty_or_nonempty with h h,
{ simp [h, fbot] },
{ exact map_Sup_of_continuous_at_of_monotone' Cf Mf h }
end
/-- A monotone function continuous at the indexed supremum over a nonempty `Sort` sends this indexed
supremum to the indexed supremum of the composition. -/
lemma map_supr_of_continuous_at_of_monotone' {ι : Sort*} [nonempty ι] {f : α → β} {g : ι → α}
(Cf : continuous_at f (supr g)) (Mf : monotone f) :
f (⨆ i, g i) = ⨆ i, f (g i) :=
by rw [supr, map_Sup_of_continuous_at_of_monotone' Cf Mf (range_nonempty g), ← range_comp, supr]
/-- If a monotone function sending `bot` to `bot` is continuous at the indexed supremum over
a `Sort`, then it sends this indexed supremum to the indexed supremum of the composition. -/
lemma map_supr_of_continuous_at_of_monotone {ι : Sort*} {f : α → β} {g : ι → α}
(Cf : continuous_at f (supr g)) (Mf : monotone f) (fbot : f ⊥ = ⊥) :
f (⨆ i, g i) = ⨆ i, f (g i) :=
by rw [supr, map_Sup_of_continuous_at_of_monotone Cf Mf fbot, ← range_comp, supr]
/-- A monotone function continuous at the infimum of a nonempty set sends this infimum to
the infimum of the image of this set. -/
lemma map_Inf_of_continuous_at_of_monotone' {f : α → β} {s : set α} (Cf : continuous_at f (Inf s))
(Mf : monotone f) (hs : s.nonempty) :
f (Inf s) = Inf (f '' s) :=
@map_Sup_of_continuous_at_of_monotone' (order_dual α) (order_dual β) _ _ _ _ _ _ f s Cf
Mf.order_dual hs
/-- A monotone function `s` sending `top` to `top` and continuous at the infimum of a set sends
this infimum to the infimum of the image of this set. -/
lemma map_Inf_of_continuous_at_of_monotone {f : α → β} {s : set α} (Cf : continuous_at f (Inf s))
(Mf : monotone f) (ftop : f ⊤ = ⊤) :
f (Inf s) = Inf (f '' s) :=
@map_Sup_of_continuous_at_of_monotone (order_dual α) (order_dual β) _ _ _ _ _ _ f s Cf
Mf.order_dual ftop
/-- A monotone function continuous at the indexed infimum over a nonempty `Sort` sends this indexed
infimum to the indexed infimum of the composition. -/
lemma map_infi_of_continuous_at_of_monotone' {ι : Sort*} [nonempty ι] {f : α → β} {g : ι → α}
(Cf : continuous_at f (infi g)) (Mf : monotone f) :
f (⨅ i, g i) = ⨅ i, f (g i) :=
@map_supr_of_continuous_at_of_monotone' (order_dual α) (order_dual β) _ _ _ _ _ _ ι _ f g Cf
Mf.order_dual
/-- If a monotone function sending `top` to `top` is continuous at the indexed infimum over
a `Sort`, then it sends this indexed infimum to the indexed infimum of the composition. -/
lemma map_infi_of_continuous_at_of_monotone {ι : Sort*} {f : α → β} {g : ι → α}
(Cf : continuous_at f (infi g)) (Mf : monotone f) (ftop : f ⊤ = ⊤) :
f (infi g) = infi (f ∘ g) :=
@map_supr_of_continuous_at_of_monotone (order_dual α) (order_dual β) _ _ _ _ _ _ ι f g Cf
Mf.order_dual ftop
end complete_linear_order
section conditionally_complete_linear_order
variables [conditionally_complete_linear_order α] [topological_space α] [order_topology α]
[conditionally_complete_linear_order β] [topological_space β] [order_topology β] [nonempty γ]
lemma cSup_mem_closure {s : set α} (hs : s.nonempty) (B : bdd_above s) : Sup s ∈ closure s :=
(is_lub_cSup hs B).mem_closure hs
lemma cInf_mem_closure {s : set α} (hs : s.nonempty) (B : bdd_below s) : Inf s ∈ closure s :=
(is_glb_cInf hs B).mem_closure hs
lemma is_closed.cSup_mem {s : set α} (hc : is_closed s) (hs : s.nonempty) (B : bdd_above s) :
Sup s ∈ s :=
(is_lub_cSup hs B).mem_of_is_closed hs hc
lemma is_closed.cInf_mem {s : set α} (hc : is_closed s) (hs : s.nonempty) (B : bdd_below s) :
Inf s ∈ s :=
(is_glb_cInf hs B).mem_of_is_closed hs hc
/-- If a monotone function is continuous at the supremum of a nonempty bounded above set `s`,
then it sends this supremum to the supremum of the image of `s`. -/
lemma map_cSup_of_continuous_at_of_monotone {f : α → β} {s : set α} (Cf : continuous_at f (Sup s))
(Mf : monotone f) (ne : s.nonempty) (H : bdd_above s) :
f (Sup s) = Sup (f '' s) :=
begin
refine ((is_lub_cSup (ne.image f) (Mf.map_bdd_above H)).unique _).symm,
refine (is_lub_cSup ne H).is_lub_of_tendsto (λx hx y hy xy, Mf xy) ne _,
exact Cf.mono_left inf_le_left
end
/-- If a monotone function is continuous at the indexed supremum of a bounded function on
a nonempty `Sort`, then it sends this supremum to the supremum of the composition. -/
lemma map_csupr_of_continuous_at_of_monotone {f : α → β} {g : γ → α}
(Cf : continuous_at f (⨆ i, g i)) (Mf : monotone f) (H : bdd_above (range g)) :
f (⨆ i, g i) = ⨆ i, f (g i) :=
by rw [supr, map_cSup_of_continuous_at_of_monotone Cf Mf (range_nonempty _) H, ← range_comp, supr]
/-- If a monotone function is continuous at the infimum of a nonempty bounded below set `s`,
then it sends this infimum to the infimum of the image of `s`. -/
lemma map_cInf_of_continuous_at_of_monotone {f : α → β} {s : set α} (Cf : continuous_at f (Inf s))
(Mf : monotone f) (ne : s.nonempty) (H : bdd_below s) :
f (Inf s) = Inf (f '' s) :=
@map_cSup_of_continuous_at_of_monotone (order_dual α) (order_dual β) _ _ _ _ _ _ f s Cf
Mf.order_dual ne H
/-- A continuous monotone function sends indexed infimum to indexed infimum in conditionally
complete linear order, under a boundedness assumption. -/
lemma map_cinfi_of_continuous_at_of_monotone {f : α → β} {g : γ → α}
(Cf : continuous_at f (⨅ i, g i)) (Mf : monotone f) (H : bdd_below (range g)) :
f (⨅ i, g i) = ⨅ i, f (g i) :=
@map_csupr_of_continuous_at_of_monotone (order_dual α) (order_dual β) _ _ _ _ _ _ _ _ _ _
Cf Mf.order_dual H
/-- A bounded connected subset of a conditionally complete linear order includes the open interval
`(Inf s, Sup s)`. -/
lemma is_connected.Ioo_cInf_cSup_subset {s : set α} (hs : is_connected s) (hb : bdd_below s)
(ha : bdd_above s) :
Ioo (Inf s) (Sup s) ⊆ s :=
λ x hx, let ⟨y, ys, hy⟩ := (is_glb_lt_iff (is_glb_cInf hs.nonempty hb)).1 hx.1 in
let ⟨z, zs, hz⟩ := (lt_is_lub_iff (is_lub_cSup hs.nonempty ha)).1 hx.2 in
hs.Icc_subset ys zs ⟨le_of_lt hy, le_of_lt hz⟩
lemma eq_Icc_cInf_cSup_of_connected_bdd_closed {s : set α} (hc : is_connected s) (hb : bdd_below s)
(ha : bdd_above s) (hcl : is_closed s) :
s = Icc (Inf s) (Sup s) :=
subset.antisymm (subset_Icc_cInf_cSup hb ha) $
hc.Icc_subset (hcl.cInf_mem hc.nonempty hb) (hcl.cSup_mem hc.nonempty ha)
lemma is_preconnected.Ioi_cInf_subset {s : set α} (hs : is_preconnected s) (hb : bdd_below s)
(ha : ¬bdd_above s) :
Ioi (Inf s) ⊆ s :=
begin
have sne : s.nonempty := @nonempty_of_not_bdd_above α _ s ⟨Inf ∅⟩ ha,
intros x hx,
obtain ⟨y, ys, hy⟩ : ∃ y ∈ s, y < x := (is_glb_lt_iff (is_glb_cInf sne hb)).1 hx,
obtain ⟨z, zs, hz⟩ : ∃ z ∈ s, x < z := not_bdd_above_iff.1 ha x,
exact hs.Icc_subset ys zs ⟨le_of_lt hy, le_of_lt hz⟩
end
lemma is_preconnected.Iio_cSup_subset {s : set α} (hs : is_preconnected s) (hb : ¬bdd_below s)
(ha : bdd_above s) :
Iio (Sup s) ⊆ s :=
@is_preconnected.Ioi_cInf_subset (order_dual α) _ _ _ s hs ha hb
/-- A preconnected set in a conditionally complete linear order is either one of the intervals
`[Inf s, Sup s]`, `[Inf s, Sup s)`, `(Inf s, Sup s]`, `(Inf s, Sup s)`, `[Inf s, +∞)`,
`(Inf s, +∞)`, `(-∞, Sup s]`, `(-∞, Sup s)`, `(-∞, +∞)`, or `∅`. The converse statement requires
`α` to be densely ordererd. -/
lemma is_preconnected.mem_intervals {s : set α} (hs : is_preconnected s) :
s ∈ ({Icc (Inf s) (Sup s), Ico (Inf s) (Sup s), Ioc (Inf s) (Sup s), Ioo (Inf s) (Sup s),
Ici (Inf s), Ioi (Inf s), Iic (Sup s), Iio (Sup s), univ, ∅} : set (set α)) :=
begin
rcases s.eq_empty_or_nonempty with rfl|hne,
{ apply_rules [or.inr, mem_singleton] },
have hs' : is_connected s := ⟨hne, hs⟩,
by_cases hb : bdd_below s; by_cases ha : bdd_above s,
{ rcases mem_Icc_Ico_Ioc_Ioo_of_subset_of_subset (hs'.Ioo_cInf_cSup_subset hb ha)
(subset_Icc_cInf_cSup hb ha) with hs|hs|hs|hs,
{ exact (or.inl hs) },
{ exact (or.inr $ or.inl hs) },
{ exact (or.inr $ or.inr $ or.inl hs) },
{ exact (or.inr $ or.inr $ or.inr $ or.inl hs) } },
{ refine (or.inr $ or.inr $ or.inr $ or.inr _),
cases mem_Ici_Ioi_of_subset_of_subset (hs.Ioi_cInf_subset hb ha) (λ x hx, cInf_le hb hx)
with hs hs,
{ exact or.inl hs },
{ exact or.inr (or.inl hs) } },
{ iterate 6 { apply or.inr },
cases mem_Iic_Iio_of_subset_of_subset (hs.Iio_cSup_subset hb ha) (λ x hx, le_cSup ha hx)
with hs hs,
{ exact or.inl hs },
{ exact or.inr (or.inl hs) } },
{ iterate 8 { apply or.inr },
exact or.inl (hs.eq_univ_of_unbounded hb ha) }
end
/-- A preconnected set is either one of the intervals `Icc`, `Ico`, `Ioc`, `Ioo`, `Ici`, `Ioi`,
`Iic`, `Iio`, or `univ`, or `∅`. The converse statement requires `α` to be densely ordererd. Though
one can represent `∅` as `(Inf s, Inf s)`, we include it into the list of possible cases to improve
readability. -/
lemma set_of_is_preconnected_subset_of_ordered :
{s : set α | is_preconnected s} ⊆
-- bounded intervals
(range (uncurry Icc) ∪ range (uncurry Ico) ∪ range (uncurry Ioc) ∪ range (uncurry Ioo)) ∪
-- unbounded intervals and `univ`
(range Ici ∪ range Ioi ∪ range Iic ∪ range Iio ∪ {univ, ∅}) :=
begin
intros s hs,
rcases hs.mem_intervals with hs|hs|hs|hs|hs|hs|hs|hs|hs|hs,
{ exact (or.inl $ or.inl $ or.inl $ or.inl ⟨(Inf s, Sup s), hs.symm⟩) },
{ exact (or.inl $ or.inl $ or.inl $ or.inr ⟨(Inf s, Sup s), hs.symm⟩) },
{ exact (or.inl $ or.inl $ or.inr ⟨(Inf s, Sup s), hs.symm⟩) },
{ exact (or.inl $ or.inr ⟨(Inf s, Sup s), hs.symm⟩) },
{ exact (or.inr $ or.inl $ or.inl $ or.inl $ or.inl ⟨Inf s, hs.symm⟩) },
{ exact (or.inr $ or.inl $ or.inl $ or.inl $ or.inr ⟨Inf s, hs.symm⟩) },
{ exact (or.inr $ or.inl $ or.inl $ or.inr ⟨Sup s, hs.symm⟩) },
{ exact (or.inr $ or.inl $ or.inr ⟨Sup s, hs.symm⟩) },
{ exact (or.inr $ or.inr $ or.inl hs) },
{ exact (or.inr $ or.inr $ or.inr hs) }
end
/-- A "continuous induction principle" for a closed interval: if a set `s` meets `[a, b]`
on a closed subset, contains `a`, and the set `s ∩ [a, b)` has no maximal point, then `b ∈ s`. -/
lemma is_closed.mem_of_ge_of_forall_exists_gt {a b : α} {s : set α} (hs : is_closed (s ∩ Icc a b))
(ha : a ∈ s) (hab : a ≤ b) (hgt : ∀ x ∈ s ∩ Ico a b, (s ∩ Ioc x b).nonempty) :
b ∈ s :=
begin
let S := s ∩ Icc a b,
replace ha : a ∈ S, from ⟨ha, left_mem_Icc.2 hab⟩,
have Sbd : bdd_above S, from ⟨b, λ z hz, hz.2.2⟩,
let c := Sup (s ∩ Icc a b),
have c_mem : c ∈ S, from hs.cSup_mem ⟨_, ha⟩ Sbd,
have c_le : c ≤ b, from cSup_le ⟨_, ha⟩ (λ x hx, hx.2.2),
cases eq_or_lt_of_le c_le with hc hc, from hc ▸ c_mem.1,
exfalso,
rcases hgt c ⟨c_mem.1, c_mem.2.1, hc⟩ with ⟨x, xs, cx, xb⟩,
exact not_lt_of_le (le_cSup Sbd ⟨xs, le_trans (le_cSup Sbd ha) (le_of_lt cx), xb⟩) cx
end
/-- A "continuous induction principle" for a closed interval: if a set `s` meets `[a, b]`
on a closed subset, contains `a`, and for any `a ≤ x < y ≤ b`, `x ∈ s`, the set `s ∩ (x, y]`
is not empty, then `[a, b] ⊆ s`. -/
lemma is_closed.Icc_subset_of_forall_exists_gt {a b : α} {s : set α} (hs : is_closed (s ∩ Icc a b))
(ha : a ∈ s) (hgt : ∀ x ∈ s ∩ Ico a b, ∀ y ∈ Ioi x, (s ∩ Ioc x y).nonempty) :
Icc a b ⊆ s :=
begin
assume y hy,
have : is_closed (s ∩ Icc a y),
{ suffices : s ∩ Icc a y = s ∩ Icc a b ∩ Icc a y,
{ rw this, exact is_closed.inter hs is_closed_Icc },
rw [inter_assoc],
congr,
exact (inter_eq_self_of_subset_right $ Icc_subset_Icc_right hy.2).symm },
exact is_closed.mem_of_ge_of_forall_exists_gt this ha hy.1
(λ x hx, hgt x ⟨hx.1, Ico_subset_Ico_right hy.2 hx.2⟩ y hx.2.2)
end
section densely_ordered
variables [densely_ordered α] {a b : α}
/-- A "continuous induction principle" for a closed interval: if a set `s` meets `[a, b]`
on a closed subset, contains `a`, and for any `x ∈ s ∩ [a, b)` the set `s` includes some open
neighborhood of `x` within `(x, +∞)`, then `[a, b] ⊆ s`. -/
lemma is_closed.Icc_subset_of_forall_mem_nhds_within {a b : α} {s : set α}
(hs : is_closed (s ∩ Icc a b)) (ha : a ∈ s)
(hgt : ∀ x ∈ s ∩ Ico a b, s ∈ 𝓝[Ioi x] x) :
Icc a b ⊆ s :=
begin
apply hs.Icc_subset_of_forall_exists_gt ha,
rintros x ⟨hxs, hxab⟩ y hyxb,
have : s ∩ Ioc x y ∈ 𝓝[Ioi x] x,
from inter_mem_sets (hgt x ⟨hxs, hxab⟩) (Ioc_mem_nhds_within_Ioi ⟨le_refl _, hyxb⟩),
exact (nhds_within_Ioi_self_ne_bot' hxab.2).nonempty_of_mem this
end
/-- A closed interval in a densely ordered conditionally complete linear order is preconnected. -/
lemma is_preconnected_Icc : is_preconnected (Icc a b) :=
is_preconnected_closed_iff.2
begin
rintros s t hs ht hab ⟨x, hx⟩ ⟨y, hy⟩,
wlog hxy : x ≤ y := le_total x y using [x y s t, y x t s],
have xyab : Icc x y ⊆ Icc a b := Icc_subset_Icc hx.1.1 hy.1.2,
by_contradiction hst,
suffices : Icc x y ⊆ s,
from hst ⟨y, xyab $ right_mem_Icc.2 hxy, this $ right_mem_Icc.2 hxy, hy.2⟩,
apply (is_closed.inter hs is_closed_Icc).Icc_subset_of_forall_mem_nhds_within hx.2,
rintros z ⟨zs, hz⟩,
have zt : z ∈ tᶜ, from λ zt, hst ⟨z, xyab $ Ico_subset_Icc_self hz, zs, zt⟩,
have : tᶜ ∩ Ioc z y ∈ 𝓝[Ioi z] z,
{ rw [← nhds_within_Ioc_eq_nhds_within_Ioi hz.2],
exact mem_nhds_within.2 ⟨tᶜ, ht.is_open_compl, zt, subset.refl _⟩},
apply mem_sets_of_superset this,
have : Ioc z y ⊆ s ∪ t, from λ w hw, hab (xyab ⟨le_trans hz.1 (le_of_lt hw.1), hw.2⟩),
exact λ w ⟨wt, wzy⟩, (this wzy).elim id (λ h, (wt h).elim)
end
lemma is_preconnected_interval : is_preconnected (interval a b) := is_preconnected_Icc
lemma is_preconnected_iff_ord_connected {s : set α} :
is_preconnected s ↔ ord_connected s :=
⟨λ h, ⟨λ x hx y hy, h.Icc_subset hx hy⟩, λ h, is_preconnected_of_forall_pair $ λ x y hx hy,
⟨interval x y, h.interval_subset hx hy, left_mem_interval, right_mem_interval,
is_preconnected_interval⟩⟩
alias is_preconnected_iff_ord_connected ↔
is_preconnected.ord_connected set.ord_connected.is_preconnected
lemma is_preconnected_Ici : is_preconnected (Ici a) := ord_connected_Ici.is_preconnected
lemma is_preconnected_Iic : is_preconnected (Iic a) := ord_connected_Iic.is_preconnected
lemma is_preconnected_Iio : is_preconnected (Iio a) := ord_connected_Iio.is_preconnected
lemma is_preconnected_Ioi : is_preconnected (Ioi a) := ord_connected_Ioi.is_preconnected
lemma is_preconnected_Ioo : is_preconnected (Ioo a b) := ord_connected_Ioo.is_preconnected
lemma is_preconnected_Ioc : is_preconnected (Ioc a b) := ord_connected_Ioc.is_preconnected
lemma is_preconnected_Ico : is_preconnected (Ico a b) := ord_connected_Ico.is_preconnected
@[priority 100]
instance ordered_connected_space : preconnected_space α :=
⟨ord_connected_univ.is_preconnected⟩
/-- In a dense conditionally complete linear order, the set of preconnected sets is exactly
the set of the intervals `Icc`, `Ico`, `Ioc`, `Ioo`, `Ici`, `Ioi`, `Iic`, `Iio`, `(-∞, +∞)`,
or `∅`. Though one can represent `∅` as `(Inf s, Inf s)`, we include it into the list of
possible cases to improve readability. -/
lemma set_of_is_preconnected_eq_of_ordered :
{s : set α | is_preconnected s} =
-- bounded intervals
(range (uncurry Icc) ∪ range (uncurry Ico) ∪ range (uncurry Ioc) ∪ range (uncurry Ioo)) ∪
-- unbounded intervals and `univ`
(range Ici ∪ range Ioi ∪ range Iic ∪ range Iio ∪ {univ, ∅}) :=
begin
refine subset.antisymm set_of_is_preconnected_subset_of_ordered _,
simp only [subset_def, -mem_range, forall_range_iff, uncurry, or_imp_distrib, forall_and_distrib,
mem_union, mem_set_of_eq, insert_eq, mem_singleton_iff, forall_eq, forall_true_iff, and_true,
is_preconnected_Icc, is_preconnected_Ico, is_preconnected_Ioc,
is_preconnected_Ioo, is_preconnected_Ioi, is_preconnected_Iio, is_preconnected_Ici,
is_preconnected_Iic, is_preconnected_univ, is_preconnected_empty],
end
variables {δ : Type*} [linear_order δ] [topological_space δ] [order_closed_topology δ]
/-- Intermediate Value Theorem for continuous functions on closed intervals, case `f a ≤ t ≤ f b`.-/
lemma intermediate_value_Icc {a b : α} (hab : a ≤ b) {f : α → δ} (hf : continuous_on f (Icc a b)) :
Icc (f a) (f b) ⊆ f '' (Icc a b) :=
is_preconnected_Icc.intermediate_value (left_mem_Icc.2 hab) (right_mem_Icc.2 hab) hf
/-- Intermediate Value Theorem for continuous functions on closed intervals, case `f a ≥ t ≥ f b`.-/
lemma intermediate_value_Icc' {a b : α} (hab : a ≤ b) {f : α → δ} (hf : continuous_on f (Icc a b)) :
Icc (f b) (f a) ⊆ f '' (Icc a b) :=
is_preconnected_Icc.intermediate_value (right_mem_Icc.2 hab) (left_mem_Icc.2 hab) hf
/-- Intermediate Value Theorem for continuous functions on closed intervals, unordered case. -/
lemma intermediate_value_interval {a b : α} {f : α → δ} (hf : continuous_on f (interval a b)) :
interval (f a) (f b) ⊆ f '' interval a b :=
by cases le_total (f a) (f b); simp [*, is_preconnected_interval.intermediate_value]
lemma intermediate_value_Ico {a b : α} (hab : a ≤ b) {f : α → δ} (hf : continuous_on f (Icc a b)) :
Ico (f a) (f b) ⊆ f '' (Ico a b) :=
or.elim (eq_or_lt_of_le hab) (λ he y h, absurd h.2 (not_lt_of_le (he ▸ h.1)))
(λ hlt, @is_preconnected.intermediate_value_Ico _ _ _ _ _ _ _ (is_preconnected_Ico)
_ _ ⟨refl a, hlt⟩ (right_nhds_within_Ico_ne_bot hlt) inf_le_right _ (hf.mono Ico_subset_Icc_self)
_ ((hf.continuous_within_at ⟨hab, refl b⟩).mono Ico_subset_Icc_self))
lemma intermediate_value_Ico' {a b : α} (hab : a ≤ b) {f : α → δ} (hf : continuous_on f (Icc a b)) :
Ioc (f b) (f a) ⊆ f '' (Ico a b) :=
or.elim (eq_or_lt_of_le hab) (λ he y h, absurd h.1 (not_lt_of_le (he ▸ h.2)))
(λ hlt, @is_preconnected.intermediate_value_Ioc _ _ _ _ _ _ _ (is_preconnected_Ico)
_ _ ⟨refl a, hlt⟩ (right_nhds_within_Ico_ne_bot hlt) inf_le_right _ (hf.mono Ico_subset_Icc_self)
_ ((hf.continuous_within_at ⟨hab, refl b⟩).mono Ico_subset_Icc_self))
lemma intermediate_value_Ioc {a b : α} (hab : a ≤ b) {f : α → δ} (hf : continuous_on f (Icc a b)) :
Ioc (f a) (f b) ⊆ f '' (Ioc a b) :=
or.elim (eq_or_lt_of_le hab) (λ he y h, absurd h.2 (not_le_of_lt (he ▸ h.1)))
(λ hlt, @is_preconnected.intermediate_value_Ioc _ _ _ _ _ _ _ (is_preconnected_Ioc)
_ _ ⟨hlt, refl b⟩ (left_nhds_within_Ioc_ne_bot hlt) inf_le_right _ (hf.mono Ioc_subset_Icc_self)
_ ((hf.continuous_within_at ⟨refl a, hab⟩).mono Ioc_subset_Icc_self))
lemma intermediate_value_Ioc' {a b : α} (hab : a ≤ b) {f : α → δ} (hf : continuous_on f (Icc a b)) :
Ico (f b) (f a) ⊆ f '' (Ioc a b) :=
or.elim (eq_or_lt_of_le hab) (λ he y h, absurd h.1 (not_le_of_lt (he ▸ h.2)))
(λ hlt, @is_preconnected.intermediate_value_Ico _ _ _ _ _ _ _ (is_preconnected_Ioc)
_ _ ⟨hlt, refl b⟩ (left_nhds_within_Ioc_ne_bot hlt) inf_le_right _ (hf.mono Ioc_subset_Icc_self)
_ ((hf.continuous_within_at ⟨refl a, hab⟩).mono Ioc_subset_Icc_self))
lemma intermediate_value_Ioo {a b : α} (hab : a ≤ b) {f : α → δ} (hf : continuous_on f (Icc a b)) :
Ioo (f a) (f b) ⊆ f '' (Ioo a b) :=
or.elim (eq_or_lt_of_le hab) (λ he y h, absurd h.2 (not_lt_of_lt (he ▸ h.1)))
(λ hlt, @is_preconnected.intermediate_value_Ioo _ _ _ _ _ _ _ (is_preconnected_Ioo)
_ _ (left_nhds_within_Ioo_ne_bot hlt) (right_nhds_within_Ioo_ne_bot hlt)
inf_le_right inf_le_right _ (hf.mono Ioo_subset_Icc_self)
_ _ ((hf.continuous_within_at ⟨refl a, hab⟩).mono Ioo_subset_Icc_self)
((hf.continuous_within_at ⟨hab, refl b⟩).mono Ioo_subset_Icc_self))
lemma intermediate_value_Ioo' {a b : α} (hab : a ≤ b) {f : α → δ} (hf : continuous_on f (Icc a b)) :
Ioo (f b) (f a) ⊆ f '' (Ioo a b) :=
or.elim (eq_or_lt_of_le hab) (λ he y h, absurd h.1 (not_lt_of_lt (he ▸ h.2)))
(λ hlt, @is_preconnected.intermediate_value_Ioo _ _ _ _ _ _ _ (is_preconnected_Ioo)
_ _ (right_nhds_within_Ioo_ne_bot hlt) (left_nhds_within_Ioo_ne_bot hlt)
inf_le_right inf_le_right _ (hf.mono Ioo_subset_Icc_self)
_ _ ((hf.continuous_within_at ⟨hab, refl b⟩).mono Ioo_subset_Icc_self)
((hf.continuous_within_at ⟨refl a, hab⟩).mono Ioo_subset_Icc_self))
/-- A continuous function which tendsto `at_top` `at_top` and to `at_bot` `at_bot` is surjective. -/
lemma continuous.surjective {f : α → δ} (hf : continuous f) (h_top : tendsto f at_top at_top)
(h_bot : tendsto f at_bot at_bot) :
function.surjective f :=
λ p, mem_range_of_exists_le_of_exists_ge hf
(h_bot.eventually (eventually_le_at_bot p)).exists
(h_top.eventually (eventually_ge_at_top p)).exists
/-- A continuous function which tendsto `at_bot` `at_top` and to `at_top` `at_bot` is surjective. -/
lemma continuous.surjective' {f : α → δ} (hf : continuous f) (h_top : tendsto f at_bot at_top)
(h_bot : tendsto f at_top at_bot) :
function.surjective f :=
@continuous.surjective (order_dual α) _ _ _ _ _ _ _ _ _ hf h_top h_bot
/-- If a function `f : α → β` is continuous on a nonempty interval `s`, its restriction to `s`
tends to `at_bot : filter β` along `at_bot : filter ↥s` and tends to `at_top : filter β` along
`at_top : filter ↥s`, then the restriction of `f` to `s` is surjective. We formulate the
conclusion as `surj_on f s univ`. -/
lemma continuous_on.surj_on_of_tendsto {f : α → β} {s : set α} [ord_connected s]
(hs : s.nonempty) (hf : continuous_on f s) (hbot : tendsto (λ x : s, f x) at_bot at_bot)
(htop : tendsto (λ x : s, f x) at_top at_top) :
surj_on f s univ :=
by haveI := inhabited_of_nonempty hs.to_subtype;
exact (surj_on_iff_surjective.2 $
(continuous_on_iff_continuous_restrict.1 hf).surjective htop hbot)
/-- If a function `f : α → β` is continuous on a nonempty interval `s`, its restriction to `s`
tends to `at_top : filter β` along `at_bot : filter ↥s` and tends to `at_bot : filter β` along
`at_top : filter ↥s`, then the restriction of `f` to `s` is surjective. We formulate the
conclusion as `surj_on f s univ`. -/
lemma continuous_on.surj_on_of_tendsto' {f : α → β} {s : set α} [ord_connected s]
(hs : s.nonempty) (hf : continuous_on f s) (hbot : tendsto (λ x : s, f x) at_bot at_top)
(htop : tendsto (λ x : s, f x) at_top at_bot) :
surj_on f s univ :=
@continuous_on.surj_on_of_tendsto α (order_dual β) _ _ _ _ _ _ _ _ _ _ hs hf hbot htop
end densely_ordered
/-- A closed interval in a conditionally complete linear order is compact. -/
lemma is_compact_Icc {a b : α} : is_compact (Icc a b) :=
begin
cases le_or_lt a b with hab hab, swap, { simp [hab] },
refine is_compact_iff_ultrafilter_le_nhds.2 (λ f hf, _),
contrapose! hf,
rw [le_principal_iff],
have hpt : ∀ x ∈ Icc a b, {x} ∉ f,
from λ x hx hxf, hf x hx ((le_pure_iff.2 hxf).trans (pure_le_nhds x)),
set s := {x ∈ Icc a b | Icc a x ∉ f},
have hsb : b ∈ upper_bounds s, from λ x hx, hx.1.2,
have sbd : bdd_above s, from ⟨b, hsb⟩,
have ha : a ∈ s, by simp [hpt, hab],
rcases hab.eq_or_lt with rfl|hlt, { exact ha.2 },
set c := Sup s,
have hsc : is_lub s c, from is_lub_cSup ⟨a, ha⟩ sbd,
have hc : c ∈ Icc a b, from ⟨hsc.1 ha, hsc.2 hsb⟩,
specialize hf c hc,
have hcs : c ∈ s,
{ cases hc.1.eq_or_lt with heq hlt, { rwa ← heq },
refine ⟨hc, λ hcf, hf (λ U hU, _)⟩,
rcases (mem_nhds_within_Iic_iff_exists_Ioc_subset' hlt).1 (mem_nhds_within_of_mem_nhds hU)
with ⟨x, hxc, hxU⟩,
rcases ((hsc.frequently_mem ⟨a, ha⟩).and_eventually
(Ioc_mem_nhds_within_Iic ⟨hxc, le_rfl⟩)).exists
with ⟨y, ⟨hyab, hyf⟩, hy⟩,
refine mem_sets_of_superset(f.diff_mem_iff.2 ⟨hcf, hyf⟩) (subset.trans _ hxU),
rw diff_subset_iff,
exact subset.trans Icc_subset_Icc_union_Ioc
(union_subset_union subset.rfl $ Ioc_subset_Ioc_left hy.1.le) },
cases hc.2.eq_or_lt with heq hlt, { rw ← heq, exact hcs.2 },
contrapose! hf,
intros U hU,
rcases (mem_nhds_within_Ici_iff_exists_mem_Ioc_Ico_subset hlt).1 (mem_nhds_within_of_mem_nhds hU)
with ⟨y, hxy, hyU⟩,
refine mem_sets_of_superset _ hyU, clear_dependent U,
have hy : y ∈ Icc a b, from ⟨hc.1.trans hxy.1.le, hxy.2⟩,
by_cases hay : Icc a y ∈ f,
{ refine mem_sets_of_superset (f.diff_mem_iff.2 ⟨f.diff_mem_iff.2 ⟨hay, hcs.2⟩, hpt y hy⟩) _,
rw [diff_subset_iff, union_comm, Ico_union_right hxy.1.le, diff_subset_iff],
exact Icc_subset_Icc_union_Icc },
{ exact ((hsc.1 ⟨hy, hay⟩).not_lt hxy.1).elim },
end
/-- An unordered closed interval in a conditionally complete linear order is compact. -/
lemma is_compact_interval {a b : α} : is_compact (interval a b) := is_compact_Icc
lemma is_compact_pi_Icc {ι : Type*} {α : ι → Type*} [Π i, conditionally_complete_linear_order (α i)]
[Π i, topological_space (α i)] [Π i, order_topology (α i)] (a b : Π i, α i) :
is_compact (Icc a b) :=
pi_univ_Icc a b ▸ is_compact_univ_pi $ λ i, is_compact_Icc
instance compact_space_Icc (a b : α) : compact_space (Icc a b) :=
is_compact_iff_compact_space.mp is_compact_Icc
instance compact_space_pi_Icc {ι : Type*} {α : ι → Type*}
[Π i, conditionally_complete_linear_order (α i)] [Π i, topological_space (α i)]
[Π i, order_topology (α i)] (a b : Π i, α i) : compact_space (Icc a b) :=
is_compact_iff_compact_space.mp (is_compact_pi_Icc a b)
@[priority 100] -- See note [lower instance priority]
instance compact_space_of_complete_linear_order {α : Type*} [complete_linear_order α]
[topological_space α] [order_topology α] :
compact_space α :=
⟨by simp only [← Icc_bot_top, is_compact_Icc]⟩
lemma is_compact.Inf_mem {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
Inf s ∈ s :=
hs.is_closed.cInf_mem ne_s hs.bdd_below
lemma is_compact.Sup_mem {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
Sup s ∈ s :=
@is_compact.Inf_mem (order_dual α) _ _ _ _ hs ne_s
lemma is_compact.is_glb_Inf {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
is_glb s (Inf s) :=
is_glb_cInf ne_s hs.bdd_below
lemma is_compact.is_lub_Sup {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
is_lub s (Sup s) :=
@is_compact.is_glb_Inf (order_dual α) _ _ _ _ hs ne_s
lemma is_compact.is_least_Inf {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
is_least s (Inf s) :=
⟨hs.Inf_mem ne_s, (hs.is_glb_Inf ne_s).1⟩
lemma is_compact.is_greatest_Sup {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
is_greatest s (Sup s) :=
@is_compact.is_least_Inf (order_dual α) _ _ _ _ hs ne_s
lemma is_compact.exists_is_least {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
∃ x, is_least s x :=
⟨_, hs.is_least_Inf ne_s⟩
lemma is_compact.exists_is_greatest {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
∃ x, is_greatest s x :=
⟨_, hs.is_greatest_Sup ne_s⟩
lemma is_compact.exists_is_glb {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
∃ x ∈ s, is_glb s x :=
⟨_, hs.Inf_mem ne_s, hs.is_glb_Inf ne_s⟩
lemma is_compact.exists_is_lub {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
∃ x ∈ s, is_lub s x :=
⟨_, hs.Sup_mem ne_s, hs.is_lub_Sup ne_s⟩
lemma is_compact.exists_Inf_image_eq {α : Type u} [topological_space α]
{s : set α} (hs : is_compact s) (ne_s : s.nonempty) {f : α → β} (hf : continuous_on f s) :
∃ x ∈ s, Inf (f '' s) = f x :=
let ⟨x, hxs, hx⟩ := (hs.image_of_continuous_on hf).Inf_mem (ne_s.image f)
in ⟨x, hxs, hx.symm⟩
lemma is_compact.exists_Sup_image_eq {α : Type u} [topological_space α]:
∀ {s : set α}, is_compact s → s.nonempty → ∀ {f : α → β}, continuous_on f s →
∃ x ∈ s, Sup (f '' s) = f x :=
@is_compact.exists_Inf_image_eq (order_dual β) _ _ _ _ _
lemma eq_Icc_of_connected_compact {s : set α} (h₁ : is_connected s) (h₂ : is_compact s) :
s = Icc (Inf s) (Sup s) :=
eq_Icc_cInf_cSup_of_connected_bdd_closed h₁ h₂.bdd_below h₂.bdd_above h₂.is_closed
/-- The extreme value theorem: a continuous function realizes its minimum on a compact set -/
lemma is_compact.exists_forall_le {α : Type u} [topological_space α]
{s : set α} (hs : is_compact s) (ne_s : s.nonempty) {f : α → β} (hf : continuous_on f s) :
∃x∈s, ∀y∈s, f x ≤ f y :=
begin
rcases hs.exists_Inf_image_eq ne_s hf with ⟨x, hxs, hx⟩,
refine ⟨x, hxs, λ y hy, _⟩,
rw ← hx,
exact ((hs.image_of_continuous_on hf).is_glb_Inf (ne_s.image f)).1 (mem_image_of_mem _ hy)
end
/-- The extreme value theorem: a continuous function realizes its maximum on a compact set -/
lemma is_compact.exists_forall_ge {α : Type u} [topological_space α]:
∀ {s : set α}, is_compact s → s.nonempty → ∀ {f : α → β}, continuous_on f s →
∃x∈s, ∀y∈s, f y ≤ f x :=
@is_compact.exists_forall_le (order_dual β) _ _ _ _ _
/-- The extreme value theorem: if a continuous function `f` tends to infinity away from compact
sets, then it has a global minimum. -/
lemma continuous.exists_forall_le {α : Type*} [topological_space α] [nonempty α] {f : α → β}
(hf : continuous f) (hlim : tendsto f (cocompact α) at_top) :
∃ x, ∀ y, f x ≤ f y :=
begin
inhabit α,
obtain ⟨s : set α, hsc : is_compact s, hsf : ∀ x ∉ s, f (default α) ≤ f x⟩ :=
(has_basis_cocompact.tendsto_iff at_top_basis).1 hlim (f $ default α) trivial,
obtain ⟨x, -, hx⟩ :=
(hsc.insert (default α)).exists_forall_le (nonempty_insert _ _) hf.continuous_on,
refine ⟨x, λ y, _⟩,
by_cases hy : y ∈ s,
exacts [hx y (or.inr hy), (hx _ (or.inl rfl)).trans (hsf y hy)]
end
/-- The extreme value theorem: if a continuous function `f` tends to negative infinity away from
compactx sets, then it has a global maximum. -/
lemma continuous.exists_forall_ge {α : Type*} [topological_space α] [nonempty α] {f : α → β}
(hf : continuous f) (hlim : tendsto f (cocompact α) at_bot) :
∃ x, ∀ y, f y ≤ f x :=
@continuous.exists_forall_le (order_dual β) _ _ _ _ _ _ _ hf hlim
end conditionally_complete_linear_order
end order_topology
/-!
### Bounded monotone sequences converge
The first result in this section is that in a linear order `α`, if the range of a monotone function
`f : α → ι` admits a least upper bound `a`, then `f` converges to `a`.
Later results specialize this to the case of (conditionally) complete linear orders, where the
existence of a least upper bound `α` is automatic. In these settings the result is that `f`
converges to its supremum, `⨆ i, f i`.
Here is a counter-example to show that the order must be a linear (i.e., total) order. Take
`α = [0, 1) → ℝ` with the natural lattice structure; this is a `conditionally_complete_lattice`.
Take `ι = ℕ` and `f n x = -x^n`. Then `⨆ n, f n = 0` while none of `f n` is strictly greater than
the constant function `-0.5`.
-/
lemma tendsto_at_top_is_lub {ι α : Type*} [preorder ι] [topological_space α] [linear_order α]
[order_topology α] {f : ι → α} (h_mono : monotone f) {a : α} (ha : is_lub (set.range f) a) :
tendsto f at_top (𝓝 a) :=
begin
by_cases hi : nonempty ι,
{ resetI,
rw tendsto_order,
split,
{ intros a' ha',
obtain ⟨_, ⟨N, rfl⟩, hN⟩ : ∃ x ∈ set.range f, a' < x := (lt_is_lub_iff ha).mp ha',
have := ha.2,
apply eventually.mono (mem_at_top N),
exact λ i hi, lt_of_lt_of_le hN (h_mono hi) },
{ intros a' ha',
exact eventually_of_forall (λ i, lt_of_le_of_lt (ha.1 (set.mem_range_self i)) ha') } },
{ exact tendsto_of_not_nonempty hi }
end
lemma tendsto_at_bot_is_glb {ι α : Type*} [preorder ι] [topological_space α] [linear_order α]
[order_topology α] {f : ι → α} (h_mono : monotone f) {a : α} (ha : is_glb (set.range f) a) :
tendsto f at_bot (𝓝 a) :=
@tendsto_at_top_is_lub (order_dual ι) (order_dual α) _ _ _ _ _ h_mono.order_dual _ ha
lemma tendsto_at_top_csupr {ι α : Type*} [preorder ι] [topological_space α]
[conditionally_complete_linear_order α] [order_topology α]
{f : ι → α} (h_mono : monotone f) (hbdd : bdd_above $ range f) :
tendsto f at_top (𝓝 (⨆i, f i)) :=
begin
by_cases hi : nonempty ι,
{ resetI,
exact tendsto_at_top_is_lub h_mono (is_lub_cSup (range_nonempty f) hbdd) },
{ exact tendsto_of_not_nonempty hi }
end
lemma tendsto_at_bot_cinfi {ι α : Type*} [preorder ι] [topological_space α]
[conditionally_complete_linear_order α] [order_topology α]
{f : ι → α} (h_mono : monotone f) (hbdd : bdd_below $ range f) :
tendsto f at_bot (𝓝 (⨅i, f i)) :=
@tendsto_at_top_csupr (order_dual ι) (order_dual α) _ _ _ _ _ h_mono.order_dual hbdd
lemma tendsto_at_top_cinfi {ι α : Type*} [preorder ι] [topological_space α]
[conditionally_complete_linear_order α] [order_topology α]
{f : ι → α} (h_mono : ∀ ⦃i j⦄, i ≤ j → f j ≤ f i) (hbdd : bdd_below $ range f) :
tendsto f at_top (𝓝 (⨅i, f i)) :=
@tendsto_at_top_csupr _ (order_dual α) _ _ _ _ _ @h_mono hbdd
lemma tendsto_at_bot_csupr {ι α : Type*} [preorder ι] [topological_space α]
[conditionally_complete_linear_order α] [order_topology α]
{f : ι → α} (h_mono : ∀ ⦃i j⦄, i ≤ j → f j ≤ f i) (hbdd : bdd_above $ range f) :
tendsto f at_bot (𝓝 (⨆i, f i)) :=
@tendsto_at_bot_cinfi ι (order_dual α) _ _ _ _ _ h_mono hbdd
lemma tendsto_at_top_supr {ι α : Type*} [preorder ι] [topological_space α]
[complete_linear_order α] [order_topology α] {f : ι → α} (h_mono : monotone f) :
tendsto f at_top (𝓝 (⨆i, f i)) :=
tendsto_at_top_csupr h_mono (order_top.bdd_above _)
lemma tendsto_at_bot_infi {ι α : Type*} [preorder ι] [topological_space α]
[complete_linear_order α] [order_topology α] {f : ι → α} (h_mono : monotone f) :
tendsto f at_bot (𝓝 (⨅i, f i)) :=
tendsto_at_bot_cinfi h_mono (order_bot.bdd_below _)
lemma tendsto_at_top_infi {ι α : Type*} [preorder ι] [topological_space α]
[complete_linear_order α] [order_topology α] {f : ι → α} (h_mono : ∀ ⦃i j⦄, i ≤ j → f j ≤ f i) :
tendsto f at_top (𝓝 (⨅i, f i)) :=
tendsto_at_top_cinfi @h_mono (order_bot.bdd_below _)
lemma tendsto_at_bot_supr {ι α : Type*} [preorder ι] [topological_space α]
[complete_linear_order α] [order_topology α] {f : ι → α} (h_mono : ∀ ⦃i j⦄, i ≤ j → f j ≤ f i) :
tendsto f at_bot (𝓝 (⨆i, f i)) :=
tendsto_at_bot_csupr h_mono (order_top.bdd_above _)
lemma tendsto_of_monotone {ι α : Type*} [preorder ι] [topological_space α]
[conditionally_complete_linear_order α] [order_topology α] {f : ι → α} (h_mono : monotone f) :
tendsto f at_top at_top ∨ (∃ l, tendsto f at_top (𝓝 l)) :=
if H : bdd_above (range f) then or.inr ⟨_, tendsto_at_top_csupr h_mono H⟩
else or.inl $ tendsto_at_top_at_top_of_monotone' h_mono H
lemma tendsto_iff_tendsto_subseq_of_monotone {ι₁ ι₂ α : Type*} [semilattice_sup ι₁] [preorder ι₂]
[nonempty ι₁] [topological_space α] [conditionally_complete_linear_order α] [order_topology α]
[no_top_order α] {f : ι₂ → α} {φ : ι₁ → ι₂} {l : α} (hf : monotone f)
(hg : tendsto φ at_top at_top) :
tendsto f at_top (𝓝 l) ↔ tendsto (f ∘ φ) at_top (𝓝 l) :=
begin
split; intro h,
{ exact h.comp hg },
{ rcases tendsto_of_monotone hf with h' | ⟨l', hl'⟩,
{ exact (not_tendsto_at_top_of_tendsto_nhds h (h'.comp hg)).elim },
{ rwa tendsto_nhds_unique h (hl'.comp hg) } }
end
/-! The next family of results, such as `is_lub_of_tendsto` and `supr_eq_of_tendsto`, are converses
to the standard fact that bounded monotone functions converge. They state, that if a monotone
function `f` tends to `a` along `at_top`, then that value `a` is a least upper bound for the range
of `f`.
Related theorems above (`is_lub.is_lub_of_tendsto`, `is_glb.is_glb_of_tendsto` etc) cover the case
when `f x` tends to `a` as `x` tends to some point `b` in the domain. -/
lemma monotone.ge_of_tendsto {α β : Type*} [topological_space α] [preorder α]
[order_closed_topology α] [semilattice_sup β] {f : β → α} {a : α} (hf : monotone f)
(ha : tendsto f at_top (𝓝 a)) (b : β) :
f b ≤ a :=
begin
haveI : nonempty β := nonempty.intro b,
exact ge_of_tendsto ha ((eventually_ge_at_top b).mono (λ _ hxy, hf hxy))
end
lemma monotone.le_of_tendsto {α β : Type*} [topological_space α] [preorder α]
[order_closed_topology α] [semilattice_inf β] {f : β → α} {a : α} (hf : monotone f)
(ha : tendsto f at_bot (𝓝 a)) (b : β) :
a ≤ f b :=
@monotone.ge_of_tendsto (order_dual α) (order_dual β) _ _ _ _ f _ hf.order_dual ha b
lemma is_lub_of_tendsto {α β : Type*} [topological_space α] [preorder α] [order_closed_topology α]
[nonempty β] [semilattice_sup β] {f : β → α} {a : α} (hf : monotone f)
(ha : tendsto f at_top (𝓝 a)) :
is_lub (set.range f) a :=
begin
split,
{ rintros _ ⟨b, rfl⟩,
exact hf.ge_of_tendsto ha b },
{ exact λ _ hb, le_of_tendsto' ha (λ x, hb (set.mem_range_self x)) }
end
lemma is_glb_of_tendsto {α β : Type*} [topological_space α] [preorder α] [order_closed_topology α]
[nonempty β] [semilattice_inf β] {f : β → α} {a : α} (hf : monotone f)
(ha : tendsto f at_bot (𝓝 a)) :
is_glb (set.range f) a :=
@is_lub_of_tendsto (order_dual α) (order_dual β) _ _ _ _ _ _ _ hf.order_dual ha
lemma supr_eq_of_tendsto {α β} [topological_space α] [complete_linear_order α] [order_topology α]
[nonempty β] [semilattice_sup β] {f : β → α} {a : α} (hf : monotone f) :
tendsto f at_top (𝓝 a) → supr f = a :=
tendsto_nhds_unique (tendsto_at_top_supr hf)
lemma infi_eq_of_tendsto {α} [topological_space α] [complete_linear_order α] [order_topology α]
[nonempty β] [semilattice_sup β] {f : β → α} {a : α} (hf : ∀n m, n ≤ m → f m ≤ f n) :
tendsto f at_top (𝓝 a) → infi f = a :=
tendsto_nhds_unique (tendsto_at_top_infi hf)
lemma supr_eq_supr_subseq_of_monotone {ι₁ ι₂ α : Type*} [preorder ι₂] [complete_lattice α]
{l : filter ι₁} [l.ne_bot] {f : ι₂ → α} {φ : ι₁ → ι₂} (hf : monotone f)
(hφ : tendsto φ l at_top) :
(⨆ i, f i) = (⨆ i, f (φ i)) :=
le_antisymm
(supr_le_supr2 $ λ i, exists_imp_exists (λ j (hj : i ≤ φ j), hf hj)
(hφ.eventually $ eventually_ge_at_top i).exists)
(supr_le_supr2 $ λ i, ⟨φ i, le_refl _⟩)
lemma infi_eq_infi_subseq_of_monotone {ι₁ ι₂ α : Type*} [preorder ι₂] [complete_lattice α]
{l : filter ι₁} [l.ne_bot] {f : ι₂ → α} {φ : ι₁ → ι₂} (hf : monotone f)
(hφ : tendsto φ l at_bot) :
(⨅ i, f i) = (⨅ i, f (φ i)) :=
le_antisymm
(infi_le_infi2 $ λ i, ⟨φ i, le_refl _⟩)
(infi_le_infi2 $ λ i, exists_imp_exists (λ j (hj : φ j ≤ i), hf hj)
(hφ.eventually $ eventually_le_at_bot i).exists)
@[to_additive] lemma tendsto_inv_nhds_within_Ioi [ordered_comm_group α]
[topological_space α] [topological_group α] {a : α} :
tendsto has_inv.inv (𝓝[Ioi a] a) (𝓝[Iio (a⁻¹)] (a⁻¹)) :=
(continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal]
@[to_additive] lemma tendsto_inv_nhds_within_Iio [ordered_comm_group α]
[topological_space α] [topological_group α] {a : α} :
tendsto has_inv.inv (𝓝[Iio a] a) (𝓝[Ioi (a⁻¹)] (a⁻¹)) :=
(continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal]
@[to_additive] lemma tendsto_inv_nhds_within_Ioi_inv [ordered_comm_group α]
[topological_space α] [topological_group α] {a : α} :
tendsto has_inv.inv (𝓝[Ioi (a⁻¹)] (a⁻¹)) (𝓝[Iio a] a) :=
by simpa only [inv_inv] using @tendsto_inv_nhds_within_Ioi _ _ _ _ (a⁻¹)
@[to_additive] lemma tendsto_inv_nhds_within_Iio_inv [ordered_comm_group α]
[topological_space α] [topological_group α] {a : α} :
tendsto has_inv.inv (𝓝[Iio (a⁻¹)] (a⁻¹)) (𝓝[Ioi a] a) :=
by simpa only [inv_inv] using @tendsto_inv_nhds_within_Iio _ _ _ _ (a⁻¹)
@[to_additive] lemma tendsto_inv_nhds_within_Ici [ordered_comm_group α]
[topological_space α] [topological_group α] {a : α} :
tendsto has_inv.inv (𝓝[Ici a] a) (𝓝[Iic (a⁻¹)] (a⁻¹)) :=
(continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal]
@[to_additive] lemma tendsto_inv_nhds_within_Iic [ordered_comm_group α]
[topological_space α] [topological_group α] {a : α} :
tendsto has_inv.inv (𝓝[Iic a] a) (𝓝[Ici (a⁻¹)] (a⁻¹)) :=
(continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal]
@[to_additive] lemma tendsto_inv_nhds_within_Ici_inv [ordered_comm_group α]
[topological_space α] [topological_group α] {a : α} :
tendsto has_inv.inv (𝓝[Ici (a⁻¹)] (a⁻¹)) (𝓝[Iic a] a) :=
by simpa only [inv_inv] using @tendsto_inv_nhds_within_Ici _ _ _ _ (a⁻¹)
@[to_additive] lemma tendsto_inv_nhds_within_Iic_inv [ordered_comm_group α]
[topological_space α] [topological_group α] {a : α} :
tendsto has_inv.inv (𝓝[Iic (a⁻¹)] (a⁻¹)) (𝓝[Ici a] a) :=
by simpa only [inv_inv] using @tendsto_inv_nhds_within_Iic _ _ _ _ (a⁻¹)
lemma nhds_left_sup_nhds_right (a : α) [topological_space α] [linear_order α] :
𝓝[Iic a] a ⊔ 𝓝[Ici a] a = 𝓝 a :=
by rw [← nhds_within_union, Iic_union_Ici, nhds_within_univ]
lemma nhds_left'_sup_nhds_right (a : α) [topological_space α] [linear_order α] :
𝓝[Iio a] a ⊔ 𝓝[Ici a] a = 𝓝 a :=
by rw [← nhds_within_union, Iio_union_Ici, nhds_within_univ]
lemma nhds_left_sup_nhds_right' (a : α) [topological_space α] [linear_order α] :
𝓝[Iic a] a ⊔ 𝓝[Ioi a] a = 𝓝 a :=
by rw [← nhds_within_union, Iic_union_Ioi, nhds_within_univ]
lemma continuous_at_iff_continuous_left_right [topological_space α] [linear_order α]
[topological_space β] {a : α} {f : α → β} :
continuous_at f a ↔ continuous_within_at f (Iic a) a ∧ continuous_within_at f (Ici a) a :=
by simp only [continuous_within_at, continuous_at, ← tendsto_sup, nhds_left_sup_nhds_right]
lemma continuous_within_at_Ioi_iff_Ici {α β : Type*} [topological_space α] [partial_order α]
[topological_space β] {a : α} {f : α → β} :
continuous_within_at f (Ioi a) a ↔ continuous_within_at f (Ici a) a :=
by simp only [← Ici_diff_left, continuous_within_at_diff_self]
lemma continuous_within_at_Iio_iff_Iic
{α β : Type*} [topological_space α] [linear_order α] [topological_space β] {a : α} {f : α → β} :
continuous_within_at f (Iio a) a ↔ continuous_within_at f (Iic a) a :=
begin
have := @continuous_within_at_Ioi_iff_Ici (order_dual α) _ _ _ _ _ f,
erw [dual_Ici, dual_Ioi] at this,
exact this,
end
lemma continuous_at_iff_continuous_left'_right' [topological_space α] [linear_order α]
[topological_space β] {a : α} {f : α → β} :
continuous_at f a ↔ continuous_within_at f (Iio a) a ∧ continuous_within_at f (Ioi a) a :=
by rw [continuous_within_at_Ioi_iff_Ici, continuous_within_at_Iio_iff_Iic,
continuous_at_iff_continuous_left_right]
/-!
### Continuity of monotone functions
In this section we prove the following fact: if `f` is a monotone function on a neighborhood of `a`
and the image of this neighborhood is a neighborhood of `f a`, then `f` is continuous at `a`, see
`continuous_at_of_mono_incr_on_of_image_mem_nhds`, as well as several similar facts.
-/
section linear_order
variables [linear_order α] [topological_space α] [order_topology α]
variables [linear_order β] [topological_space β] [order_topology β]
/-- If `f` is a function strictly monotonically increasing on a right neighborhood of `a` and the
image of this neighborhood under `f` meets every interval `(f a, b]`, `b > f a`, then `f` is
continuous at `a` from the right.
The assumption `hfs : ∀ b > f a, ∃ c ∈ s, f c ∈ Ioc (f a) b` is required because otherwise the
function `f : ℝ → ℝ` given by `f x = if x ≤ 0 then x else x + 1` would be a counter-example at
`a = 0`. -/
lemma strict_mono_incr_on.continuous_at_right_of_exists_between {f : α → β} {s : set α} {a : α}
(h_mono : strict_mono_incr_on f s) (hs : s ∈ 𝓝[Ici a] a)
(hfs : ∀ b > f a, ∃ c ∈ s, f c ∈ Ioc (f a) b) :
continuous_within_at f (Ici a) a :=
begin
have ha : a ∈ Ici a := left_mem_Ici,
have has : a ∈ s := mem_of_mem_nhds_within ha hs,
refine tendsto_order.2 ⟨λ b hb, _, λ b hb, _⟩,
{ filter_upwards [hs, self_mem_nhds_within],
intros x hxs hxa,
exact hb.trans_le ((h_mono.le_iff_le has hxs).2 hxa) },
{ rcases hfs b hb with ⟨c, hcs, hac, hcb⟩,
rw [h_mono.lt_iff_lt has hcs] at hac,
filter_upwards [hs, Ico_mem_nhds_within_Ici (left_mem_Ico.2 hac)],
rintros x hx ⟨hax, hxc⟩,
exact ((h_mono.lt_iff_lt hx hcs).2 hxc).trans_le hcb }
end
/-- If `f` is a function monotonically increasing function on a right neighborhood of `a` and the
image of this neighborhood under `f` meets every interval `(f a, b)`, `b > f a`, then `f` is
continuous at `a` from the right.
The assumption `hfs : ∀ b > f a, ∃ c ∈ s, f c ∈ Ioo (f a) b` cannot be replaced by the weaker
assumption `hfs : ∀ b > f a, ∃ c ∈ s, f c ∈ Ioc (f a) b` we use for strictly monotone functions
because otherwise the function `ceil : ℝ → ℤ` would be a counter-example at `a = 0`. -/
lemma continuous_at_right_of_mono_incr_on_of_exists_between {f : α → β} {s : set α} {a : α}
(h_mono : ∀ (x ∈ s) (y ∈ s), x ≤ y → f x ≤ f y) (hs : s ∈ 𝓝[Ici a] a)
(hfs : ∀ b > f a, ∃ c ∈ s, f c ∈ Ioo (f a) b) :
continuous_within_at f (Ici a) a :=
begin
have ha : a ∈ Ici a := left_mem_Ici,
have has : a ∈ s := mem_of_mem_nhds_within ha hs,
refine tendsto_order.2 ⟨λ b hb, _, λ b hb, _⟩,
{ filter_upwards [hs, self_mem_nhds_within],
intros x hxs hxa,
exact hb.trans_le (h_mono _ has _ hxs hxa) },
{ rcases hfs b hb with ⟨c, hcs, hac, hcb⟩,
have : a < c, from not_le.1 (λ h, hac.not_le $ h_mono _ hcs _ has h),
filter_upwards [hs, Ico_mem_nhds_within_Ici (left_mem_Ico.2 this)],
rintros x hx ⟨hax, hxc⟩,
exact (h_mono _ hx _ hcs hxc.le).trans_lt hcb }
end
/-- If a function `f` with a densely ordered codomain is monotonically increasing on a right
neighborhood of `a` and the closure of the image of this neighborhood under `f` is a right
neighborhood of `f a`, then `f` is continuous at `a` from the right. -/
lemma continuous_at_right_of_mono_incr_on_of_closure_image_mem_nhds_within [densely_ordered β]
{f : α → β} {s : set α} {a : α} (h_mono : ∀ (x ∈ s) (y ∈ s), x ≤ y → f x ≤ f y)
(hs : s ∈ 𝓝[Ici a] a) (hfs : closure (f '' s) ∈ 𝓝[Ici (f a)] (f a)) :
continuous_within_at f (Ici a) a :=
begin
refine continuous_at_right_of_mono_incr_on_of_exists_between h_mono hs (λ b hb, _),
rcases (mem_nhds_within_Ici_iff_exists_mem_Ioc_Ico_subset hb).1 hfs with ⟨b', ⟨hab', hbb'⟩, hb'⟩,
rcases exists_between hab' with ⟨c', hc'⟩,
rcases mem_closure_iff.1 (hb' ⟨hc'.1.le, hc'.2⟩) (Ioo (f a) b') is_open_Ioo hc'
with ⟨_, hc, ⟨c, hcs, rfl⟩⟩,
exact ⟨c, hcs, hc.1, hc.2.trans_le hbb'⟩
end
/-- If a function `f` with a densely ordered codomain is monotonically increasing on a right
neighborhood of `a` and the image of this neighborhood under `f` is a right neighborhood of `f a`,
then `f` is continuous at `a` from the right. -/
lemma continuous_at_right_of_mono_incr_on_of_image_mem_nhds_within [densely_ordered β] {f : α → β}
{s : set α} {a : α} (h_mono : ∀ (x ∈ s) (y ∈ s), x ≤ y → f x ≤ f y) (hs : s ∈ 𝓝[Ici a] a)
(hfs : f '' s ∈ 𝓝[Ici (f a)] (f a)) :
continuous_within_at f (Ici a) a :=
continuous_at_right_of_mono_incr_on_of_closure_image_mem_nhds_within h_mono hs $
mem_sets_of_superset hfs subset_closure
/-- If a function `f` with a densely ordered codomain is strictly monotonically increasing on a
right neighborhood of `a` and the closure of the image of this neighborhood under `f` is a right
neighborhood of `f a`, then `f` is continuous at `a` from the right. -/
lemma strict_mono_incr_on.continuous_at_right_of_closure_image_mem_nhds_within [densely_ordered β]
{f : α → β} {s : set α} {a : α} (h_mono : strict_mono_incr_on f s) (hs : s ∈ 𝓝[Ici a] a)
(hfs : closure (f '' s) ∈ 𝓝[Ici (f a)] (f a)) :
continuous_within_at f (Ici a) a :=
continuous_at_right_of_mono_incr_on_of_closure_image_mem_nhds_within
(λ x hx y hy, (h_mono.le_iff_le hx hy).2) hs hfs
/-- If a function `f` with a densely ordered codomain is strictly monotonically increasing on a
right neighborhood of `a` and the image of this neighborhood under `f` is a right neighborhood of
`f a`, then `f` is continuous at `a` from the right. -/
lemma strict_mono_incr_on.continuous_at_right_of_image_mem_nhds_within [densely_ordered β]
{f : α → β} {s : set α} {a : α} (h_mono : strict_mono_incr_on f s) (hs : s ∈ 𝓝[Ici a] a)
(hfs : f '' s ∈ 𝓝[Ici (f a)] (f a)) :
continuous_within_at f (Ici a) a :=
h_mono.continuous_at_right_of_closure_image_mem_nhds_within hs
(mem_sets_of_superset hfs subset_closure)
/-- If a function `f` is strictly monotonically increasing on a right neighborhood of `a` and the
image of this neighborhood under `f` includes `Ioi (f a)`, then `f` is continuous at `a` from the
right. -/
lemma strict_mono_incr_on.continuous_at_right_of_surj_on {f : α → β} {s : set α} {a : α}
(h_mono : strict_mono_incr_on f s) (hs : s ∈ 𝓝[Ici a] a) (hfs : surj_on f s (Ioi (f a))) :
continuous_within_at f (Ici a) a :=
h_mono.continuous_at_right_of_exists_between hs $ λ b hb, let ⟨c, hcs, hcb⟩ := hfs hb in
⟨c, hcs, hcb.symm ▸ hb, hcb.le⟩
/-- If `f` is a function strictly monotonically increasing on a left neighborhood of `a` and the
image of this neighborhood under `f` meets every interval `[b, f a)`, `b < f a`, then `f` is
continuous at `a` from the left.
The assumption `hfs : ∀ b < f a, ∃ c ∈ s, f c ∈ Ico b (f a)` is required because otherwise the
function `f : ℝ → ℝ` given by `f x = if x < 0 then x else x + 1` would be a counter-example at
`a = 0`. -/
lemma strict_mono_incr_on.continuous_at_left_of_exists_between {f : α → β} {s : set α} {a : α}
(h_mono : strict_mono_incr_on f s) (hs : s ∈ 𝓝[Iic a] a)
(hfs : ∀ b < f a, ∃ c ∈ s, f c ∈ Ico b (f a)) :
continuous_within_at f (Iic a) a :=
h_mono.dual.continuous_at_right_of_exists_between hs $
λ b hb, let ⟨c, hcs, hcb, hca⟩ := hfs b hb in ⟨c, hcs, hca, hcb⟩
/-- If `f` is a function monotonically increasing function on a left neighborhood of `a` and the
image of this neighborhood under `f` meets every interval `(b, f a)`, `b < f a`, then `f` is
continuous at `a` from the left.
The assumption `hfs : ∀ b < f a, ∃ c ∈ s, f c ∈ Ioo b (f a)` cannot be replaced by the weaker
assumption `hfs : ∀ b < f a, ∃ c ∈ s, f c ∈ Ico b (f a)` we use for strictly monotone functions
because otherwise the function `floor : ℝ → ℤ` would be a counter-example at `a = 0`. -/
lemma continuous_at_left_of_mono_incr_on_of_exists_between {f : α → β} {s : set α} {a : α}
(h_mono : ∀ (x ∈ s) (y ∈ s), x ≤ y → f x ≤ f y) (hs : s ∈ 𝓝[Iic a] a)
(hfs : ∀ b < f a, ∃ c ∈ s, f c ∈ Ioo b (f a)) :
continuous_within_at f (Iic a) a :=
@continuous_at_right_of_mono_incr_on_of_exists_between (order_dual α) (order_dual β) _ _ _ _ _ _
f s a (λ x hx y hy, h_mono y hy x hx) hs $
λ b hb, let ⟨c, hcs, hcb, hca⟩ := hfs b hb in ⟨c, hcs, hca, hcb⟩
/-- If a function `f` with a densely ordered codomain is monotonically increasing on a left
neighborhood of `a` and the closure of the image of this neighborhood under `f` is a left
neighborhood of `f a`, then `f` is continuous at `a` from the left -/
lemma continuous_at_left_of_mono_incr_on_of_closure_image_mem_nhds_within [densely_ordered β]
{f : α → β} {s : set α} {a : α} (h_mono : ∀ (x ∈ s) (y ∈ s), x ≤ y → f x ≤ f y)
(hs : s ∈ 𝓝[Iic a] a) (hfs : closure (f '' s) ∈ 𝓝[Iic (f a)] (f a)) :
continuous_within_at f (Iic a) a :=
@continuous_at_right_of_mono_incr_on_of_closure_image_mem_nhds_within (order_dual α) (order_dual β)
_ _ _ _ _ _ _ f s a (λ x hx y hy, h_mono y hy x hx) hs hfs
/-- If a function `f` with a densely ordered codomain is monotonically increasing on a left
neighborhood of `a` and the image of this neighborhood under `f` is a left neighborhood of `f a`,
then `f` is continuous at `a` from the left. -/
lemma continuous_at_left_of_mono_incr_on_of_image_mem_nhds_within [densely_ordered β]
{f : α → β} {s : set α} {a : α} (h_mono : ∀ (x ∈ s) (y ∈ s), x ≤ y → f x ≤ f y)
(hs : s ∈ 𝓝[Iic a] a) (hfs : f '' s ∈ 𝓝[Iic (f a)] (f a)) :
continuous_within_at f (Iic a) a :=
continuous_at_left_of_mono_incr_on_of_closure_image_mem_nhds_within h_mono hs
(mem_sets_of_superset hfs subset_closure)
/-- If a function `f` with a densely ordered codomain is strictly monotonically increasing on a
left neighborhood of `a` and the closure of the image of this neighborhood under `f` is a left
neighborhood of `f a`, then `f` is continuous at `a` from the left. -/
lemma strict_mono_incr_on.continuous_at_left_of_closure_image_mem_nhds_within [densely_ordered β]
{f : α → β} {s : set α} {a : α} (h_mono : strict_mono_incr_on f s) (hs : s ∈ 𝓝[Iic a] a)
(hfs : closure (f '' s) ∈ 𝓝[Iic (f a)] (f a)) :
continuous_within_at f (Iic a) a :=
h_mono.dual.continuous_at_right_of_closure_image_mem_nhds_within hs hfs
/-- If a function `f` with a densely ordered codomain is strictly monotonically increasing on a
left neighborhood of `a` and the image of this neighborhood under `f` is a left neighborhood of
`f a`, then `f` is continuous at `a` from the left. -/
lemma strict_mono_incr_on.continuous_at_left_of_image_mem_nhds_within [densely_ordered β]
{f : α → β} {s : set α} {a : α} (h_mono : strict_mono_incr_on f s) (hs : s ∈ 𝓝[Iic a] a)
(hfs : f '' s ∈ 𝓝[Iic (f a)] (f a)) :
continuous_within_at f (Iic a) a :=
h_mono.dual.continuous_at_right_of_image_mem_nhds_within hs hfs
/-- If a function `f` is strictly monotonically increasing on a left neighborhood of `a` and the
image of this neighborhood under `f` includes `Iio (f a)`, then `f` is continuous at `a` from the
left. -/
lemma strict_mono_incr_on.continuous_at_left_of_surj_on {f : α → β} {s : set α} {a : α}
(h_mono : strict_mono_incr_on f s) (hs : s ∈ 𝓝[Iic a] a) (hfs : surj_on f s (Iio (f a))) :
continuous_within_at f (Iic a) a :=
h_mono.dual.continuous_at_right_of_surj_on hs hfs
/-- If a function `f` is strictly monotonically increasing on a neighborhood of `a` and the image of
this neighborhood under `f` meets every interval `[b, f a)`, `b < f a`, and every interval
`(f a, b]`, `b > f a`, then `f` is continuous at `a`. -/
lemma strict_mono_incr_on.continuous_at_of_exists_between {f : α → β} {s : set α} {a : α}
(h_mono : strict_mono_incr_on f s) (hs : s ∈ 𝓝 a)
(hfs_l : ∀ b < f a, ∃ c ∈ s, f c ∈ Ico b (f a)) (hfs_r : ∀ b > f a, ∃ c ∈ s, f c ∈ Ioc (f a) b) :
continuous_at f a :=
continuous_at_iff_continuous_left_right.2
⟨h_mono.continuous_at_left_of_exists_between (mem_nhds_within_of_mem_nhds hs) hfs_l,
h_mono.continuous_at_right_of_exists_between (mem_nhds_within_of_mem_nhds hs) hfs_r⟩
/-- If a function `f` with a densely ordered codomain is strictly monotonically increasing on a
neighborhood of `a` and the closure of the image of this neighborhood under `f` is a neighborhood of
`f a`, then `f` is continuous at `a`. -/
lemma strict_mono_incr_on.continuous_at_of_closure_image_mem_nhds [densely_ordered β] {f : α → β}
{s : set α} {a : α} (h_mono : strict_mono_incr_on f s) (hs : s ∈ 𝓝 a)
(hfs : closure (f '' s) ∈ 𝓝 (f a)) :
continuous_at f a :=
continuous_at_iff_continuous_left_right.2
⟨h_mono.continuous_at_left_of_closure_image_mem_nhds_within (mem_nhds_within_of_mem_nhds hs)
(mem_nhds_within_of_mem_nhds hfs),
h_mono.continuous_at_right_of_closure_image_mem_nhds_within (mem_nhds_within_of_mem_nhds hs)
(mem_nhds_within_of_mem_nhds hfs)⟩
/-- If a function `f` with a densely ordered codomain is strictly monotonically increasing on a
neighborhood of `a` and the image of this set under `f` is a neighborhood of `f a`, then `f` is
continuous at `a`. -/
lemma strict_mono_incr_on.continuous_at_of_image_mem_nhds [densely_ordered β] {f : α → β}
{s : set α} {a : α} (h_mono : strict_mono_incr_on f s) (hs : s ∈ 𝓝 a) (hfs : f '' s ∈ 𝓝 (f a)) :
continuous_at f a :=
h_mono.continuous_at_of_closure_image_mem_nhds hs (mem_sets_of_superset hfs subset_closure)
/-- If `f` is a function monotonically increasing function on a neighborhood of `a` and the image of
this neighborhood under `f` meets every interval `(b, f a)`, `b < f a`, and every interval `(f a,
b)`, `b > f a`, then `f` is continuous at `a`. -/
lemma continuous_at_of_mono_incr_on_of_exists_between {f : α → β} {s : set α} {a : α}
(h_mono : ∀ (x ∈ s) (y ∈ s), x ≤ y → f x ≤ f y) (hs : s ∈ 𝓝 a)
(hfs_l : ∀ b < f a, ∃ c ∈ s, f c ∈ Ioo b (f a)) (hfs_r : ∀ b > f a, ∃ c ∈ s, f c ∈ Ioo (f a) b) :
continuous_at f a :=
continuous_at_iff_continuous_left_right.2
⟨continuous_at_left_of_mono_incr_on_of_exists_between h_mono
(mem_nhds_within_of_mem_nhds hs) hfs_l,
continuous_at_right_of_mono_incr_on_of_exists_between h_mono
(mem_nhds_within_of_mem_nhds hs) hfs_r⟩
/-- If a function `f` with a densely ordered codomain is monotonically increasing on a neighborhood
of `a` and the closure of the image of this neighborhood under `f` is a neighborhood of `f a`, then
`f` is continuous at `a`. -/
lemma continuous_at_of_mono_incr_on_of_closure_image_mem_nhds [densely_ordered β] {f : α → β}
{s : set α} {a : α} (h_mono : ∀ (x ∈ s) (y ∈ s), x ≤ y → f x ≤ f y) (hs : s ∈ 𝓝 a)
(hfs : closure (f '' s) ∈ 𝓝 (f a)) :
continuous_at f a :=
continuous_at_iff_continuous_left_right.2
⟨continuous_at_left_of_mono_incr_on_of_closure_image_mem_nhds_within h_mono
(mem_nhds_within_of_mem_nhds hs) (mem_nhds_within_of_mem_nhds hfs),
continuous_at_right_of_mono_incr_on_of_closure_image_mem_nhds_within h_mono
(mem_nhds_within_of_mem_nhds hs) (mem_nhds_within_of_mem_nhds hfs)⟩
/-- If a function `f` with a densely ordered codomain is monotonically increasing on a neighborhood
of `a` and the image of this neighborhood under `f` is a neighborhood of `f a`, then `f` is
continuous at `a`. -/
lemma continuous_at_of_mono_incr_on_of_image_mem_nhds [densely_ordered β] {f : α → β}
{s : set α} {a : α} (h_mono : ∀ (x ∈ s) (y ∈ s), x ≤ y → f x ≤ f y) (hs : s ∈ 𝓝 a)
(hfs : f '' s ∈ 𝓝 (f a)) :
continuous_at f a :=
continuous_at_of_mono_incr_on_of_closure_image_mem_nhds h_mono hs
(mem_sets_of_superset hfs subset_closure)
/-- A monotone function with densely ordered codomain and a dense range is continuous. -/
lemma monotone.continuous_of_dense_range [densely_ordered β] {f : α → β}
(h_mono : monotone f) (h_dense : dense_range f) :
continuous f :=
continuous_iff_continuous_at.mpr $ λ a,
continuous_at_of_mono_incr_on_of_closure_image_mem_nhds (λ x hx y hy hxy, h_mono hxy)
univ_mem_sets $ by simp only [image_univ, h_dense.closure_eq, univ_mem_sets]
/-- A monotone surjective function with a densely ordered codomain is surjective. -/
lemma monotone.continuous_of_surjective [densely_ordered β] {f : α → β} (h_mono : monotone f)
(h_surj : function.surjective f) :
continuous f :=
h_mono.continuous_of_dense_range h_surj.dense_range
end linear_order
/-!
### Continuity of order isomorphisms
In this section we prove that an `order_iso` is continuous, hence it is a `homeomorph`. We prove
this for an `order_iso` between to partial orders with order topology.
-/
namespace order_iso
variables [partial_order α] [partial_order β] [topological_space α] [topological_space β]
[order_topology α] [order_topology β]
protected lemma continuous (e : α ≃o β) : continuous e :=
begin
rw [‹order_topology β›.topology_eq_generate_intervals],
refine continuous_generated_from (λ s hs, _),
rcases hs with ⟨a, rfl|rfl⟩,
{ rw e.preimage_Ioi, apply is_open_lt' },
{ rw e.preimage_Iio, apply is_open_gt' }
end
/-- An order isomorphism between two linear order `order_topology` spaces is a homeomorphism. -/
def to_homeomorph (e : α ≃o β) : α ≃ₜ β :=
{ continuous_to_fun := e.continuous,
continuous_inv_fun := e.symm.continuous,
.. e }
@[simp] lemma coe_to_homeomorph (e : α ≃o β) : ⇑e.to_homeomorph = e := rfl
@[simp] lemma coe_to_homeomorph_symm (e : α ≃o β) : ⇑e.to_homeomorph.symm = e.symm := rfl
end order_iso
|
561ce5f5efadf2fb74a63192a1f789c6ecad37cb | bb31430994044506fa42fd667e2d556327e18dfe | /src/data/polynomial/degree/definitions.lean | bac87138058bb7226131e1f9e82e47a232c22c44 | [
"Apache-2.0"
] | permissive | sgouezel/mathlib | 0cb4e5335a2ba189fa7af96d83a377f83270e503 | 00638177efd1b2534fc5269363ebf42a7871df9a | refs/heads/master | 1,674,527,483,042 | 1,673,665,568,000 | 1,673,665,568,000 | 119,598,202 | 0 | 0 | null | 1,517,348,647,000 | 1,517,348,646,000 | null | UTF-8 | Lean | false | false | 50,151 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker
-/
import data.fintype.big_operators
import data.nat.with_bot
import data.polynomial.monomial
import data.polynomial.coeff
/-!
# Theory of univariate polynomials
The definitions include
`degree`, `monic`, `leading_coeff`
Results include
- `degree_mul` : The degree of the product is the sum of degrees
- `leading_coeff_add_of_degree_eq` and `leading_coeff_add_of_degree_lt` :
The leading_coefficient of a sum is determined by the leading coefficients and degrees
-/
noncomputable theory
open finsupp finset
open_locale big_operators classical polynomial
namespace polynomial
universes u v
variables {R : Type u} {S : Type v} {a b c d : R} {n m : ℕ}
section semiring
variables [semiring R] {p q r : R[X]}
/-- `degree p` is the degree of the polynomial `p`, i.e. the largest `X`-exponent in `p`.
`degree p = some n` when `p ≠ 0` and `n` is the highest power of `X` that appears in `p`, otherwise
`degree 0 = ⊥`. -/
def degree (p : R[X]) : with_bot ℕ := p.support.max
lemma degree_lt_wf : well_founded (λp q : R[X], degree p < degree q) :=
inv_image.wf degree (with_bot.well_founded_lt nat.lt_wf)
instance : has_well_founded R[X] := ⟨_, degree_lt_wf⟩
/-- `nat_degree p` forces `degree p` to ℕ, by defining nat_degree 0 = 0. -/
def nat_degree (p : R[X]) : ℕ := (degree p).unbot' 0
/-- `leading_coeff p` gives the coefficient of the highest power of `X` in `p`-/
def leading_coeff (p : R[X]) : R := coeff p (nat_degree p)
/-- a polynomial is `monic` if its leading coefficient is 1 -/
def monic (p : R[X]) := leading_coeff p = (1 : R)
@[nontriviality] lemma monic_of_subsingleton [subsingleton R] (p : R[X]) : monic p :=
subsingleton.elim _ _
lemma monic.def : monic p ↔ leading_coeff p = 1 := iff.rfl
instance monic.decidable [decidable_eq R] : decidable (monic p) :=
by unfold monic; apply_instance
@[simp] lemma monic.leading_coeff {p : R[X]} (hp : p.monic) :
leading_coeff p = 1 := hp
lemma monic.coeff_nat_degree {p : R[X]} (hp : p.monic) : p.coeff p.nat_degree = 1 := hp
@[simp] lemma degree_zero : degree (0 : R[X]) = ⊥ := rfl
@[simp] lemma nat_degree_zero : nat_degree (0 : R[X]) = 0 := rfl
@[simp] lemma coeff_nat_degree : coeff p (nat_degree p) = leading_coeff p := rfl
lemma degree_eq_bot : degree p = ⊥ ↔ p = 0 :=
⟨λ h, support_eq_empty.1 (finset.max_eq_bot.1 h),
λ h, h.symm ▸ rfl⟩
@[nontriviality] lemma degree_of_subsingleton [subsingleton R] : degree p = ⊥ :=
by rw [subsingleton.elim p 0, degree_zero]
@[nontriviality] lemma nat_degree_of_subsingleton [subsingleton R] : nat_degree p = 0 :=
by rw [subsingleton.elim p 0, nat_degree_zero]
lemma degree_eq_nat_degree (hp : p ≠ 0) : degree p = (nat_degree p : with_bot ℕ) :=
let ⟨n, hn⟩ :=
not_forall.1 (mt option.eq_none_iff_forall_not_mem.2 (mt degree_eq_bot.1 hp)) in
have hn : degree p = some n := not_not.1 hn,
by rw [nat_degree, hn]; refl
lemma degree_eq_iff_nat_degree_eq {p : R[X]} {n : ℕ} (hp : p ≠ 0) :
p.degree = n ↔ p.nat_degree = n :=
by rw [degree_eq_nat_degree hp, with_bot.coe_eq_coe]
lemma degree_eq_iff_nat_degree_eq_of_pos {p : R[X]} {n : ℕ} (hn : 0 < n) :
p.degree = n ↔ p.nat_degree = n :=
begin
split,
{ intro H, rwa ← degree_eq_iff_nat_degree_eq, rintro rfl,
rw degree_zero at H, exact option.no_confusion H },
{ intro H, rwa degree_eq_iff_nat_degree_eq, rintro rfl,
rw nat_degree_zero at H, rw H at hn, exact lt_irrefl _ hn }
end
lemma nat_degree_eq_of_degree_eq_some {p : R[X]} {n : ℕ}
(h : degree p = n) : nat_degree p = n :=
have hp0 : p ≠ 0, from λ hp0, by rw hp0 at h; exact option.no_confusion h,
option.some_inj.1 $ show (nat_degree p : with_bot ℕ) = n,
by rwa [← degree_eq_nat_degree hp0]
@[simp] lemma degree_le_nat_degree : degree p ≤ nat_degree p :=
with_bot.gi_unbot'_bot.gc.le_u_l _
lemma nat_degree_eq_of_degree_eq [semiring S] {q : S[X]} (h : degree p = degree q) :
nat_degree p = nat_degree q :=
by unfold nat_degree; rw h
lemma le_degree_of_ne_zero (h : coeff p n ≠ 0) : (n : with_bot ℕ) ≤ degree p :=
show @has_le.le (with_bot ℕ) _ (some n : with_bot ℕ) (p.support.sup some : with_bot ℕ),
from finset.le_sup (mem_support_iff.2 h)
lemma le_nat_degree_of_ne_zero (h : coeff p n ≠ 0) : n ≤ nat_degree p :=
begin
rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree],
exact le_degree_of_ne_zero h,
{ assume h, subst h, exact h rfl }
end
lemma le_nat_degree_of_mem_supp (a : ℕ) :
a ∈ p.support → a ≤ nat_degree p:=
le_nat_degree_of_ne_zero ∘ mem_support_iff.mp
lemma degree_eq_of_le_of_coeff_ne_zero (pn : p.degree ≤ n) (p1 : p.coeff n ≠ 0) :
p.degree = n :=
pn.antisymm (le_degree_of_ne_zero p1)
lemma nat_degree_eq_of_le_of_coeff_ne_zero (pn : p.nat_degree ≤ n) (p1 : p.coeff n ≠ 0) :
p.nat_degree = n :=
pn.antisymm (le_nat_degree_of_ne_zero p1)
lemma degree_mono [semiring S] {f : R[X]} {g : S[X]}
(h : f.support ⊆ g.support) : f.degree ≤ g.degree := finset.sup_mono h
lemma supp_subset_range (h : nat_degree p < m) : p.support ⊆ finset.range m :=
λ n hn, mem_range.2 $ (le_nat_degree_of_mem_supp _ hn).trans_lt h
lemma supp_subset_range_nat_degree_succ : p.support ⊆ finset.range (nat_degree p + 1) :=
supp_subset_range (nat.lt_succ_self _)
lemma degree_le_degree (h : coeff q (nat_degree p) ≠ 0) : degree p ≤ degree q :=
begin
by_cases hp : p = 0,
{ rw hp, exact bot_le },
{ rw degree_eq_nat_degree hp, exact le_degree_of_ne_zero h }
end
lemma degree_ne_of_nat_degree_ne {n : ℕ} :
p.nat_degree ≠ n → degree p ≠ n :=
mt $ λ h, by rw [nat_degree, h, with_bot.unbot'_coe]
theorem nat_degree_le_iff_degree_le {n : ℕ} : nat_degree p ≤ n ↔ degree p ≤ n :=
with_bot.unbot'_bot_le_iff
lemma nat_degree_lt_iff_degree_lt (hp : p ≠ 0) :
p.nat_degree < n ↔ p.degree < ↑n :=
with_bot.unbot'_lt_iff $ degree_eq_bot.not.mpr hp
alias nat_degree_le_iff_degree_le ↔ ..
lemma nat_degree_le_nat_degree [semiring S] {q : S[X]} (hpq : p.degree ≤ q.degree) :
p.nat_degree ≤ q.nat_degree :=
with_bot.gi_unbot'_bot.gc.monotone_l hpq
lemma nat_degree_lt_nat_degree {p q : R[X]} (hp : p ≠ 0) (hpq : p.degree < q.degree) :
p.nat_degree < q.nat_degree :=
begin
by_cases hq : q = 0, { exact (not_lt_bot $ hq.subst hpq).elim },
rwa [degree_eq_nat_degree hp, degree_eq_nat_degree hq, with_bot.coe_lt_coe] at hpq
end
@[simp] lemma degree_C (ha : a ≠ 0) : degree (C a) = (0 : with_bot ℕ) :=
by rw [degree, ← monomial_zero_left, support_monomial 0 ha, max_eq_sup_coe, sup_singleton,
with_bot.coe_zero]
lemma degree_C_le : degree (C a) ≤ 0 :=
begin
by_cases h : a = 0,
{ rw [h, C_0], exact bot_le },
{ rw [degree_C h], exact le_rfl }
end
lemma degree_C_lt : degree (C a) < 1 := degree_C_le.trans_lt $ with_bot.coe_lt_coe.mpr zero_lt_one
lemma degree_one_le : degree (1 : R[X]) ≤ (0 : with_bot ℕ) :=
by rw [← C_1]; exact degree_C_le
@[simp] lemma nat_degree_C (a : R) : nat_degree (C a) = 0 :=
begin
by_cases ha : a = 0,
{ have : C a = 0, { rw [ha, C_0] },
rw [nat_degree, degree_eq_bot.2 this],
refl },
{ rw [nat_degree, degree_C ha], refl }
end
@[simp] lemma nat_degree_one : nat_degree (1 : R[X]) = 0 := nat_degree_C 1
@[simp] lemma nat_degree_nat_cast (n : ℕ) : nat_degree (n : R[X]) = 0 :=
by simp only [←C_eq_nat_cast, nat_degree_C]
@[simp] lemma degree_monomial (n : ℕ) (ha : a ≠ 0) : degree (monomial n a) = n :=
by rw [degree, support_monomial n ha]; refl
@[simp] lemma degree_C_mul_X_pow (n : ℕ) (ha : a ≠ 0) : degree (C a * X ^ n) = n :=
by rw [C_mul_X_pow_eq_monomial, degree_monomial n ha]
lemma degree_C_mul_X (ha : a ≠ 0) : degree (C a * X) = 1 :=
by simpa only [pow_one] using degree_C_mul_X_pow 1 ha
lemma degree_monomial_le (n : ℕ) (a : R) : degree (monomial n a) ≤ n :=
if h : a = 0 then by rw [h, (monomial n).map_zero]; exact bot_le else le_of_eq (degree_monomial n h)
lemma degree_C_mul_X_pow_le (n : ℕ) (a : R) : degree (C a * X ^ n) ≤ n :=
by { rw C_mul_X_pow_eq_monomial, apply degree_monomial_le }
lemma degree_C_mul_X_le (a : R) : degree (C a * X) ≤ 1 :=
by simpa only [pow_one] using degree_C_mul_X_pow_le 1 a
@[simp] lemma nat_degree_C_mul_X_pow (n : ℕ) (a : R) (ha : a ≠ 0) : nat_degree (C a * X ^ n) = n :=
nat_degree_eq_of_degree_eq_some (degree_C_mul_X_pow n ha)
@[simp] lemma nat_degree_C_mul_X (a : R) (ha : a ≠ 0) : nat_degree (C a * X) = 1 :=
by simpa only [pow_one] using nat_degree_C_mul_X_pow 1 a ha
@[simp] lemma nat_degree_monomial [decidable_eq R] (i : ℕ) (r : R) :
nat_degree (monomial i r) = if r = 0 then 0 else i :=
begin
split_ifs with hr,
{ simp [hr] },
{ rw [← C_mul_X_pow_eq_monomial, nat_degree_C_mul_X_pow i r hr] }
end
lemma nat_degree_monomial_le (a : R) {m : ℕ} : (monomial m a).nat_degree ≤ m :=
begin
rw polynomial.nat_degree_monomial,
split_ifs,
exacts [nat.zero_le _, rfl.le],
end
lemma nat_degree_monomial_eq (i : ℕ) {r : R} (r0 : r ≠ 0) :
(monomial i r).nat_degree = i :=
eq.trans (nat_degree_monomial _ _) (if_neg r0)
lemma coeff_eq_zero_of_degree_lt (h : degree p < n) : coeff p n = 0 :=
not_not.1 (mt le_degree_of_ne_zero (not_le_of_gt h))
lemma coeff_eq_zero_of_nat_degree_lt {p : R[X]} {n : ℕ} (h : p.nat_degree < n) :
p.coeff n = 0 :=
begin
apply coeff_eq_zero_of_degree_lt,
by_cases hp : p = 0,
{ subst hp, exact with_bot.bot_lt_coe n },
{ rwa [degree_eq_nat_degree hp, with_bot.coe_lt_coe] }
end
lemma ext_iff_nat_degree_le {p q : R[X]} {n : ℕ} (hp : p.nat_degree ≤ n) (hq : q.nat_degree ≤ n) :
p = q ↔ (∀ i ≤ n, p.coeff i = q.coeff i) :=
begin
refine iff.trans polynomial.ext_iff _,
refine forall_congr (λ i, ⟨λ h _, h, λ h, _⟩),
refine (le_or_lt i n).elim h (λ k, _),
refine (coeff_eq_zero_of_nat_degree_lt (hp.trans_lt k)).trans
(coeff_eq_zero_of_nat_degree_lt (hq.trans_lt k)).symm,
end
lemma ext_iff_degree_le {p q : R[X]} {n : ℕ} (hp : p.degree ≤ n) (hq : q.degree ≤ n) :
p = q ↔ (∀ i ≤ n, p.coeff i = q.coeff i) :=
ext_iff_nat_degree_le (nat_degree_le_of_degree_le hp) (nat_degree_le_of_degree_le hq)
@[simp] lemma coeff_nat_degree_succ_eq_zero {p : R[X]} : p.coeff (p.nat_degree + 1) = 0 :=
coeff_eq_zero_of_nat_degree_lt (lt_add_one _)
-- We need the explicit `decidable` argument here because an exotic one shows up in a moment!
lemma ite_le_nat_degree_coeff (p : R[X]) (n : ℕ) (I : decidable (n < 1 + nat_degree p)) :
@ite _ (n < 1 + nat_degree p) I (coeff p n) 0 = coeff p n :=
begin
split_ifs,
{ refl },
{ exact (coeff_eq_zero_of_nat_degree_lt (not_le.1 (λ w, h (nat.lt_one_add_iff.2 w)))).symm, }
end
lemma as_sum_support (p : R[X]) :
p = ∑ i in p.support, monomial i (p.coeff i) :=
(sum_monomial_eq p).symm
lemma as_sum_support_C_mul_X_pow (p : R[X]) :
p = ∑ i in p.support, C (p.coeff i) * X^i :=
trans p.as_sum_support $ by simp only [C_mul_X_pow_eq_monomial]
/--
We can reexpress a sum over `p.support` as a sum over `range n`,
for any `n` satisfying `p.nat_degree < n`.
-/
lemma sum_over_range' [add_comm_monoid S] (p : R[X]) {f : ℕ → R → S} (h : ∀ n, f n 0 = 0)
(n : ℕ) (w : p.nat_degree < n) :
p.sum f = ∑ (a : ℕ) in range n, f a (coeff p a) :=
begin
rcases p,
have := supp_subset_range w,
simp only [polynomial.sum, support, coeff, nat_degree, degree] at ⊢ this,
exact finsupp.sum_of_support_subset _ this _ (λ n hn, h n)
end
/--
We can reexpress a sum over `p.support` as a sum over `range (p.nat_degree + 1)`.
-/
lemma sum_over_range [add_comm_monoid S] (p : R[X]) {f : ℕ → R → S} (h : ∀ n, f n 0 = 0) :
p.sum f = ∑ (a : ℕ) in range (p.nat_degree + 1), f a (coeff p a) :=
sum_over_range' p h (p.nat_degree + 1) (lt_add_one _)
-- TODO this is essentially a duplicate of `sum_over_range`, and should be removed.
lemma sum_fin [add_comm_monoid S]
(f : ℕ → R → S) (hf : ∀ i, f i 0 = 0) {n : ℕ} {p : R[X]} (hn : p.degree < n) :
∑ (i : fin n), f i (p.coeff i) = p.sum f :=
begin
by_cases hp : p = 0,
{ rw [hp, sum_zero_index, finset.sum_eq_zero], intros i _, exact hf i },
rw [sum_over_range' _ hf n ((nat_degree_lt_iff_degree_lt hp).mpr hn),
fin.sum_univ_eq_sum_range (λ i, f i (p.coeff i))],
end
lemma as_sum_range' (p : R[X]) (n : ℕ) (w : p.nat_degree < n) :
p = ∑ i in range n, monomial i (coeff p i) :=
p.sum_monomial_eq.symm.trans $ p.sum_over_range' monomial_zero_right _ w
lemma as_sum_range (p : R[X]) :
p = ∑ i in range (p.nat_degree + 1), monomial i (coeff p i) :=
p.sum_monomial_eq.symm.trans $ p.sum_over_range $ monomial_zero_right
lemma as_sum_range_C_mul_X_pow (p : R[X]) :
p = ∑ i in range (p.nat_degree + 1), C (coeff p i) * X ^ i :=
p.as_sum_range.trans $ by simp only [C_mul_X_pow_eq_monomial]
lemma coeff_ne_zero_of_eq_degree (hn : degree p = n) :
coeff p n ≠ 0 :=
λ h, mem_support_iff.mp (mem_of_max hn) h
lemma eq_X_add_C_of_degree_le_one (h : degree p ≤ 1) :
p = C (p.coeff 1) * X + C (p.coeff 0) :=
ext (λ n, nat.cases_on n (by simp)
(λ n, nat.cases_on n (by simp [coeff_C])
(λ m, have degree p < m.succ.succ, from lt_of_le_of_lt h dec_trivial,
by simp [coeff_eq_zero_of_degree_lt this, coeff_C, nat.succ_ne_zero, coeff_X,
nat.succ_inj', @eq_comm ℕ 0])))
lemma eq_X_add_C_of_degree_eq_one (h : degree p = 1) :
p = C (p.leading_coeff) * X + C (p.coeff 0) :=
(eq_X_add_C_of_degree_le_one (show degree p ≤ 1, from h ▸ le_rfl)).trans
(by simp only [leading_coeff, nat_degree_eq_of_degree_eq_some h])
lemma eq_X_add_C_of_nat_degree_le_one (h : nat_degree p ≤ 1) :
p = C (p.coeff 1) * X + C (p.coeff 0) :=
eq_X_add_C_of_degree_le_one $ degree_le_of_nat_degree_le h
lemma monic.eq_X_add_C (hm : p.monic) (hnd : p.nat_degree = 1) : p = X + C (p.coeff 0) :=
by rw [←one_mul X, ←C_1, ←hm.coeff_nat_degree, hnd, ←eq_X_add_C_of_nat_degree_le_one hnd.le]
lemma exists_eq_X_add_C_of_nat_degree_le_one (h : nat_degree p ≤ 1) :
∃ a b, p = C a * X + C b :=
⟨p.coeff 1, p.coeff 0, eq_X_add_C_of_nat_degree_le_one h⟩
theorem degree_X_pow_le (n : ℕ) : degree (X^n : R[X]) ≤ n :=
by simpa only [C_1, one_mul] using degree_C_mul_X_pow_le n (1:R)
theorem degree_X_le : degree (X : R[X]) ≤ 1 :=
degree_monomial_le _ _
lemma nat_degree_X_le : (X : R[X]).nat_degree ≤ 1 :=
nat_degree_le_of_degree_le degree_X_le
lemma mem_support_C_mul_X_pow {n a : ℕ} {c : R} (h : a ∈ (C c * X ^ n).support) : a = n :=
mem_singleton.1 $ support_C_mul_X_pow' n c h
lemma card_support_C_mul_X_pow_le_one {c : R} {n : ℕ} : (C c * X ^ n).support.card ≤ 1 :=
begin
rw ← card_singleton n,
apply card_le_of_subset (support_C_mul_X_pow' n c),
end
lemma card_supp_le_succ_nat_degree (p : R[X]) : p.support.card ≤ p.nat_degree + 1 :=
begin
rw ← finset.card_range (p.nat_degree + 1),
exact finset.card_le_of_subset supp_subset_range_nat_degree_succ,
end
lemma le_degree_of_mem_supp (a : ℕ) :
a ∈ p.support → ↑a ≤ degree p :=
le_degree_of_ne_zero ∘ mem_support_iff.mp
lemma nonempty_support_iff : p.support.nonempty ↔ p ≠ 0 :=
by rw [ne.def, nonempty_iff_ne_empty, ne.def, ← support_eq_empty]
end semiring
section nonzero_semiring
variables [semiring R] [nontrivial R] {p q : R[X]}
@[simp] lemma degree_one : degree (1 : R[X]) = (0 : with_bot ℕ) :=
degree_C (show (1 : R) ≠ 0, from zero_ne_one.symm)
@[simp] lemma degree_X : degree (X : R[X]) = 1 :=
degree_monomial _ one_ne_zero
@[simp] lemma nat_degree_X : (X : R[X]).nat_degree = 1 :=
nat_degree_eq_of_degree_eq_some degree_X
end nonzero_semiring
section ring
variables [ring R]
lemma coeff_mul_X_sub_C {p : R[X]} {r : R} {a : ℕ} :
coeff (p * (X - C r)) (a + 1) = coeff p a - coeff p (a + 1) * r :=
by simp [mul_sub]
@[simp] lemma degree_neg (p : R[X]) : degree (-p) = degree p :=
by unfold degree; rw support_neg
@[simp] lemma nat_degree_neg (p : R[X]) : nat_degree (-p) = nat_degree p :=
by simp [nat_degree]
@[simp] lemma nat_degree_int_cast (n : ℤ) : nat_degree (n : R[X]) = 0 :=
by rw [←C_eq_int_cast, nat_degree_C]
@[simp] lemma leading_coeff_neg (p : R[X]) : (-p).leading_coeff = -p.leading_coeff :=
by rw [leading_coeff, leading_coeff, nat_degree_neg, coeff_neg]
end ring
section semiring
variables [semiring R]
/-- The second-highest coefficient, or 0 for constants -/
def next_coeff (p : R[X]) : R :=
if p.nat_degree = 0 then 0 else p.coeff (p.nat_degree - 1)
@[simp]
lemma next_coeff_C_eq_zero (c : R) :
next_coeff (C c) = 0 := by { rw next_coeff, simp }
lemma next_coeff_of_pos_nat_degree (p : R[X]) (hp : 0 < p.nat_degree) :
next_coeff p = p.coeff (p.nat_degree - 1) :=
by { rw [next_coeff, if_neg], contrapose! hp, simpa }
variables {p q : R[X]} {ι : Type*}
lemma coeff_nat_degree_eq_zero_of_degree_lt (h : degree p < degree q) :
coeff p (nat_degree q) = 0 :=
coeff_eq_zero_of_degree_lt (lt_of_lt_of_le h degree_le_nat_degree)
lemma ne_zero_of_degree_gt {n : with_bot ℕ} (h : n < degree p) : p ≠ 0 :=
mt degree_eq_bot.2 (ne.symm (ne_of_lt (lt_of_le_of_lt bot_le h)))
lemma ne_zero_of_degree_ge_degree (hpq : p.degree ≤ q.degree) (hp : p ≠ 0) : q ≠ 0 :=
polynomial.ne_zero_of_degree_gt (lt_of_lt_of_le (bot_lt_iff_ne_bot.mpr
(by rwa [ne.def, polynomial.degree_eq_bot])) hpq : q.degree > ⊥)
lemma ne_zero_of_nat_degree_gt {n : ℕ} (h : n < nat_degree p) : p ≠ 0 :=
λ H, by simpa [H, nat.not_lt_zero] using h
lemma degree_lt_degree (h : nat_degree p < nat_degree q) : degree p < degree q :=
begin
by_cases hp : p = 0,
{ simp [hp],
rw bot_lt_iff_ne_bot,
intro hq,
simpa [hp, degree_eq_bot.mp hq, lt_irrefl] using h },
{ rw [degree_eq_nat_degree hp, degree_eq_nat_degree $ ne_zero_of_nat_degree_gt h],
exact_mod_cast h }
end
lemma nat_degree_lt_nat_degree_iff (hp : p ≠ 0) :
nat_degree p < nat_degree q ↔ degree p < degree q :=
⟨degree_lt_degree, begin
intro h,
have hq : q ≠ 0 := ne_zero_of_degree_gt h,
rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq] at h,
exact_mod_cast h
end⟩
lemma eq_C_of_degree_le_zero (h : degree p ≤ 0) : p = C (coeff p 0) :=
begin
ext (_|n), { simp },
rw [coeff_C, if_neg (nat.succ_ne_zero _), coeff_eq_zero_of_degree_lt],
exact h.trans_lt (with_bot.some_lt_some.2 n.succ_pos),
end
lemma eq_C_of_degree_eq_zero (h : degree p = 0) : p = C (coeff p 0) :=
eq_C_of_degree_le_zero (h ▸ le_rfl)
lemma degree_le_zero_iff : degree p ≤ 0 ↔ p = C (coeff p 0) :=
⟨eq_C_of_degree_le_zero, λ h, h.symm ▸ degree_C_le⟩
lemma degree_add_le (p q : R[X]) : degree (p + q) ≤ max (degree p) (degree q) :=
calc degree (p + q) = ((p + q).support).sup some : rfl
... ≤ (p.support ∪ q.support).sup some : sup_mono support_add
... = p.support.sup some ⊔ q.support.sup some : sup_union
lemma degree_add_le_of_degree_le {p q : R[X]} {n : ℕ} (hp : degree p ≤ n)
(hq : degree q ≤ n) : degree (p + q) ≤ n :=
(degree_add_le p q).trans $ max_le hp hq
lemma nat_degree_add_le (p q : R[X]) :
nat_degree (p + q) ≤ max (nat_degree p) (nat_degree q) :=
begin
cases le_max_iff.1 (degree_add_le p q);
simp [nat_degree_le_nat_degree h]
end
lemma nat_degree_add_le_of_degree_le {p q : R[X]} {n : ℕ} (hp : nat_degree p ≤ n)
(hq : nat_degree q ≤ n) : nat_degree (p + q) ≤ n :=
(nat_degree_add_le p q).trans $ max_le hp hq
@[simp] lemma leading_coeff_zero : leading_coeff (0 : R[X]) = 0 := rfl
@[simp] lemma leading_coeff_eq_zero : leading_coeff p = 0 ↔ p = 0 :=
⟨λ h, by_contradiction $ λ hp, mt mem_support_iff.1
(not_not.2 h) (mem_of_max (degree_eq_nat_degree hp)),
λ h, h.symm ▸ leading_coeff_zero⟩
lemma leading_coeff_ne_zero : leading_coeff p ≠ 0 ↔ p ≠ 0 :=
by rw [ne.def, leading_coeff_eq_zero]
lemma leading_coeff_eq_zero_iff_deg_eq_bot : leading_coeff p = 0 ↔ degree p = ⊥ :=
by rw [leading_coeff_eq_zero, degree_eq_bot]
lemma nat_degree_mem_support_of_nonzero (H : p ≠ 0) : p.nat_degree ∈ p.support :=
by { rw mem_support_iff, exact (not_congr leading_coeff_eq_zero).mpr H }
lemma nat_degree_eq_support_max' (h : p ≠ 0) :
p.nat_degree = p.support.max' (nonempty_support_iff.mpr h) :=
(le_max' _ _ $ nat_degree_mem_support_of_nonzero h).antisymm $
max'_le _ _ _ le_nat_degree_of_mem_supp
lemma nat_degree_C_mul_X_pow_le (a : R) (n : ℕ) : nat_degree (C a * X ^ n) ≤ n :=
nat_degree_le_iff_degree_le.2 $ degree_C_mul_X_pow_le _ _
lemma degree_add_eq_left_of_degree_lt (h : degree q < degree p) : degree (p + q) = degree p :=
le_antisymm (max_eq_left_of_lt h ▸ degree_add_le _ _) $ degree_le_degree $
begin
rw [coeff_add, coeff_nat_degree_eq_zero_of_degree_lt h, add_zero],
exact mt leading_coeff_eq_zero.1 (ne_zero_of_degree_gt h)
end
lemma degree_add_eq_right_of_degree_lt (h : degree p < degree q) : degree (p + q) = degree q :=
by rw [add_comm, degree_add_eq_left_of_degree_lt h]
lemma nat_degree_add_eq_left_of_nat_degree_lt (h : nat_degree q < nat_degree p) :
nat_degree (p + q) = nat_degree p :=
nat_degree_eq_of_degree_eq (degree_add_eq_left_of_degree_lt (degree_lt_degree h))
lemma nat_degree_add_eq_right_of_nat_degree_lt (h : nat_degree p < nat_degree q) :
nat_degree (p + q) = nat_degree q :=
nat_degree_eq_of_degree_eq (degree_add_eq_right_of_degree_lt (degree_lt_degree h))
lemma degree_add_C (hp : 0 < degree p) : degree (p + C a) = degree p :=
add_comm (C a) p ▸ degree_add_eq_right_of_degree_lt $ lt_of_le_of_lt degree_C_le hp
lemma degree_add_eq_of_leading_coeff_add_ne_zero (h : leading_coeff p + leading_coeff q ≠ 0) :
degree (p + q) = max p.degree q.degree :=
le_antisymm (degree_add_le _ _) $
match lt_trichotomy (degree p) (degree q) with
| or.inl hlt :=
by rw [degree_add_eq_right_of_degree_lt hlt, max_eq_right_of_lt hlt]; exact le_rfl
| or.inr (or.inl heq) :=
le_of_not_gt $
assume hlt : max (degree p) (degree q) > degree (p + q),
h $ show leading_coeff p + leading_coeff q = 0,
begin
rw [heq, max_self] at hlt,
rw [leading_coeff, leading_coeff, nat_degree_eq_of_degree_eq heq, ← coeff_add],
exact coeff_nat_degree_eq_zero_of_degree_lt hlt
end
| or.inr (or.inr hlt) :=
by rw [degree_add_eq_left_of_degree_lt hlt, max_eq_left_of_lt hlt]; exact le_rfl
end
lemma degree_erase_le (p : R[X]) (n : ℕ) : degree (p.erase n) ≤ degree p :=
by { rcases p, simp only [erase, degree, coeff, support], convert sup_mono (erase_subset _ _) }
lemma degree_erase_lt (hp : p ≠ 0) : degree (p.erase (nat_degree p)) < degree p :=
begin
apply lt_of_le_of_ne (degree_erase_le _ _),
rw [degree_eq_nat_degree hp, degree, support_erase],
exact λ h, not_mem_erase _ _ (mem_of_max h),
end
lemma degree_update_le (p : R[X]) (n : ℕ) (a : R) :
degree (p.update n a) ≤ max (degree p) n :=
begin
rw [degree, support_update],
split_ifs,
{ exact (finset.max_mono (erase_subset _ _)).trans (le_max_left _ _) },
{ rw [max_insert, max_comm],
exact le_rfl },
end
lemma degree_sum_le (s : finset ι) (f : ι → R[X]) :
degree (∑ i in s, f i) ≤ s.sup (λ b, degree (f b)) :=
finset.induction_on s (by simp only [sum_empty, sup_empty, degree_zero, le_refl]) $
assume a s has ih,
calc degree (∑ i in insert a s, f i) ≤ max (degree (f a)) (degree (∑ i in s, f i)) :
by rw sum_insert has; exact degree_add_le _ _
... ≤ _ : by rw [sup_insert, sup_eq_max]; exact max_le_max le_rfl ih
lemma degree_mul_le (p q : R[X]) : degree (p * q) ≤ degree p + degree q :=
calc degree (p * q) ≤ (p.support).sup (λi, degree (sum q (λj a, C (coeff p i * a) * X ^ (i + j)))) :
begin
simp only [← C_mul_X_pow_eq_monomial.symm],
convert degree_sum_le _ _,
exact mul_eq_sum_sum
end
... ≤ p.support.sup (λi, q.support.sup (λj, degree (C (coeff p i * coeff q j) * X ^ (i + j)))) :
finset.sup_mono_fun (assume i hi, degree_sum_le _ _)
... ≤ degree p + degree q :
begin
refine finset.sup_le (λ a ha, finset.sup_le (λ b hb, le_trans (degree_C_mul_X_pow_le _ _) _)),
rw [with_bot.coe_add],
rw mem_support_iff at ha hb,
exact add_le_add (le_degree_of_ne_zero ha) (le_degree_of_ne_zero hb)
end
lemma degree_pow_le (p : R[X]) : ∀ (n : ℕ), degree (p ^ n) ≤ n • (degree p)
| 0 := by rw [pow_zero, zero_nsmul]; exact degree_one_le
| (n+1) := calc degree (p ^ (n + 1)) ≤ degree p + degree (p ^ n) :
by rw pow_succ; exact degree_mul_le _ _
... ≤ _ : by rw succ_nsmul; exact add_le_add le_rfl (degree_pow_le _)
@[simp] lemma leading_coeff_monomial (a : R) (n : ℕ) : leading_coeff (monomial n a) = a :=
begin
by_cases ha : a = 0,
{ simp only [ha, (monomial n).map_zero, leading_coeff_zero] },
{ rw [leading_coeff, nat_degree_monomial, if_neg ha, coeff_monomial], simp }
end
lemma leading_coeff_C_mul_X_pow (a : R) (n : ℕ) : leading_coeff (C a * X ^ n) = a :=
by rw [C_mul_X_pow_eq_monomial, leading_coeff_monomial]
lemma leading_coeff_C_mul_X (a : R) : leading_coeff (C a * X) = a :=
by simpa only [pow_one] using leading_coeff_C_mul_X_pow a 1
@[simp] lemma leading_coeff_C (a : R) : leading_coeff (C a) = a :=
leading_coeff_monomial a 0
@[simp] lemma leading_coeff_X_pow (n : ℕ) : leading_coeff ((X : R[X]) ^ n) = 1 :=
by simpa only [C_1, one_mul] using leading_coeff_C_mul_X_pow (1 : R) n
@[simp] lemma leading_coeff_X : leading_coeff (X : R[X]) = 1 :=
by simpa only [pow_one] using @leading_coeff_X_pow R _ 1
@[simp] lemma monic_X_pow (n : ℕ) : monic (X ^ n : R[X]) := leading_coeff_X_pow n
@[simp] lemma monic_X : monic (X : R[X]) := leading_coeff_X
@[simp] lemma leading_coeff_one : leading_coeff (1 : R[X]) = 1 :=
leading_coeff_C 1
@[simp] lemma monic_one : monic (1 : R[X]) := leading_coeff_C _
lemma monic.ne_zero {R : Type*} [semiring R] [nontrivial R] {p : R[X]} (hp : p.monic) :
p ≠ 0 :=
by { rintro rfl, simpa [monic] using hp }
lemma monic.ne_zero_of_ne (h : (0:R) ≠ 1) {p : R[X]} (hp : p.monic) :
p ≠ 0 :=
by { nontriviality R, exact hp.ne_zero }
lemma monic_of_nat_degree_le_of_coeff_eq_one (n : ℕ) (pn : p.nat_degree ≤ n) (p1 : p.coeff n = 1) :
monic p :=
begin
nontriviality,
refine (congr_arg _ $ nat_degree_eq_of_le_of_coeff_ne_zero pn _).trans p1,
exact ne_of_eq_of_ne p1 one_ne_zero,
end
lemma monic_of_degree_le_of_coeff_eq_one (n : ℕ) (pn : p.degree ≤ n) (p1 : p.coeff n = 1) :
monic p :=
monic_of_nat_degree_le_of_coeff_eq_one n (nat_degree_le_of_degree_le pn) p1
lemma monic.ne_zero_of_polynomial_ne {r} (hp : monic p) (hne : q ≠ r) : p ≠ 0 :=
by { haveI := nontrivial.of_polynomial_ne hne, exact hp.ne_zero }
lemma leading_coeff_add_of_degree_lt (h : degree p < degree q) :
leading_coeff (p + q) = leading_coeff q :=
have coeff p (nat_degree q) = 0, from coeff_nat_degree_eq_zero_of_degree_lt h,
by simp only [leading_coeff, nat_degree_eq_of_degree_eq (degree_add_eq_right_of_degree_lt h),
this, coeff_add, zero_add]
lemma leading_coeff_add_of_degree_eq (h : degree p = degree q)
(hlc : leading_coeff p + leading_coeff q ≠ 0) :
leading_coeff (p + q) = leading_coeff p + leading_coeff q :=
have nat_degree (p + q) = nat_degree p,
by apply nat_degree_eq_of_degree_eq;
rw [degree_add_eq_of_leading_coeff_add_ne_zero hlc, h, max_self],
by simp only [leading_coeff, this, nat_degree_eq_of_degree_eq h, coeff_add]
@[simp] lemma coeff_mul_degree_add_degree (p q : R[X]) :
coeff (p * q) (nat_degree p + nat_degree q) = leading_coeff p * leading_coeff q :=
calc coeff (p * q) (nat_degree p + nat_degree q) =
∑ x in nat.antidiagonal (nat_degree p + nat_degree q),
coeff p x.1 * coeff q x.2 : coeff_mul _ _ _
... = coeff p (nat_degree p) * coeff q (nat_degree q) :
begin
refine finset.sum_eq_single (nat_degree p, nat_degree q) _ _,
{ rintro ⟨i,j⟩ h₁ h₂, rw nat.mem_antidiagonal at h₁,
by_cases H : nat_degree p < i,
{ rw [coeff_eq_zero_of_degree_lt
(lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 H)), zero_mul] },
{ rw not_lt_iff_eq_or_lt at H, cases H,
{ subst H, rw add_left_cancel_iff at h₁, dsimp at h₁, subst h₁, exfalso, exact h₂ rfl },
{ suffices : nat_degree q < j,
{ rw [coeff_eq_zero_of_degree_lt
(lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 this)), mul_zero] },
{ by_contra H', rw not_lt at H',
exact ne_of_lt (nat.lt_of_lt_of_le
(nat.add_lt_add_right H j) (nat.add_le_add_left H' _)) h₁ } } } },
{ intro H, exfalso, apply H, rw nat.mem_antidiagonal }
end
lemma degree_mul' (h : leading_coeff p * leading_coeff q ≠ 0) :
degree (p * q) = degree p + degree q :=
have hp : p ≠ 0 := by refine mt _ h; exact λ hp, by rw [hp, leading_coeff_zero, zero_mul],
have hq : q ≠ 0 := by refine mt _ h; exact λ hq, by rw [hq, leading_coeff_zero, mul_zero],
le_antisymm (degree_mul_le _ _)
begin
rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq],
refine le_degree_of_ne_zero _,
rwa coeff_mul_degree_add_degree
end
lemma monic.degree_mul (hq : monic q) : degree (p * q) = degree p + degree q :=
if hp : p = 0 then by simp [hp]
else degree_mul' $ by rwa [hq.leading_coeff, mul_one, ne.def, leading_coeff_eq_zero]
lemma nat_degree_mul' (h : leading_coeff p * leading_coeff q ≠ 0) :
nat_degree (p * q) = nat_degree p + nat_degree q :=
have hp : p ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, zero_mul]),
have hq : q ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, mul_zero]),
nat_degree_eq_of_degree_eq_some $
by rw [degree_mul' h, with_bot.coe_add, degree_eq_nat_degree hp, degree_eq_nat_degree hq]
lemma leading_coeff_mul' (h : leading_coeff p * leading_coeff q ≠ 0) :
leading_coeff (p * q) = leading_coeff p * leading_coeff q :=
begin
unfold leading_coeff,
rw [nat_degree_mul' h, coeff_mul_degree_add_degree],
refl
end
lemma monomial_nat_degree_leading_coeff_eq_self (h : p.support.card ≤ 1) :
monomial p.nat_degree p.leading_coeff = p :=
begin
rcases card_support_le_one_iff_monomial.1 h with ⟨n, a, rfl⟩,
by_cases ha : a = 0;
simp [ha]
end
lemma C_mul_X_pow_eq_self (h : p.support.card ≤ 1) :
C p.leading_coeff * X^p.nat_degree = p :=
by rw [C_mul_X_pow_eq_monomial, monomial_nat_degree_leading_coeff_eq_self h]
lemma leading_coeff_pow' : leading_coeff p ^ n ≠ 0 →
leading_coeff (p ^ n) = leading_coeff p ^ n :=
nat.rec_on n (by simp) $
λ n ih h,
have h₁ : leading_coeff p ^ n ≠ 0 :=
λ h₁, h $ by rw [pow_succ, h₁, mul_zero],
have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 :=
by rwa [pow_succ, ← ih h₁] at h,
by rw [pow_succ, pow_succ, leading_coeff_mul' h₂, ih h₁]
lemma degree_pow' : ∀ {n : ℕ}, leading_coeff p ^ n ≠ 0 →
degree (p ^ n) = n • (degree p)
| 0 := λ h, by rw [pow_zero, ← C_1] at *;
rw [degree_C h, zero_nsmul]
| (n+1) := λ h,
have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $
by rw [pow_succ, h₁, mul_zero],
have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 :=
by rwa [pow_succ, ← leading_coeff_pow' h₁] at h,
by rw [pow_succ, degree_mul' h₂, succ_nsmul, degree_pow' h₁]
lemma nat_degree_pow' {n : ℕ} (h : leading_coeff p ^ n ≠ 0) :
nat_degree (p ^ n) = n * nat_degree p :=
if hp0 : p = 0 then
if hn0 : n = 0 then by simp *
else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp
else
have hpn : p ^ n ≠ 0, from λ hpn0, have h1 : _ := h,
by rw [← leading_coeff_pow' h1, hpn0, leading_coeff_zero] at h;
exact h rfl,
option.some_inj.1 $ show (nat_degree (p ^ n) : with_bot ℕ) = (n * nat_degree p : ℕ),
by rw [← degree_eq_nat_degree hpn, degree_pow' h, degree_eq_nat_degree hp0,
← with_bot.coe_nsmul]; simp
theorem leading_coeff_monic_mul {p q : R[X]} (hp : monic p) :
leading_coeff (p * q) = leading_coeff q :=
begin
rcases eq_or_ne q 0 with rfl|H,
{ simp },
{ rw [leading_coeff_mul', hp.leading_coeff, one_mul],
rwa [hp.leading_coeff, one_mul, ne.def, leading_coeff_eq_zero] }
end
theorem leading_coeff_mul_monic {p q : R[X]} (hq : monic q) :
leading_coeff (p * q) = leading_coeff p :=
decidable.by_cases
(λ H : leading_coeff p = 0, by rw [H, leading_coeff_eq_zero.1 H, zero_mul, leading_coeff_zero])
(λ H : leading_coeff p ≠ 0,
by rw [leading_coeff_mul', hq.leading_coeff, mul_one];
rwa [hq.leading_coeff, mul_one])
@[simp] theorem leading_coeff_mul_X_pow {p : R[X]} {n : ℕ} :
leading_coeff (p * X ^ n) = leading_coeff p :=
leading_coeff_mul_monic (monic_X_pow n)
@[simp] theorem leading_coeff_mul_X {p : R[X]} :
leading_coeff (p * X) = leading_coeff p :=
leading_coeff_mul_monic monic_X
lemma nat_degree_mul_le {p q : R[X]} : nat_degree (p * q) ≤ nat_degree p + nat_degree q :=
begin
apply nat_degree_le_of_degree_le,
apply le_trans (degree_mul_le p q),
rw with_bot.coe_add,
refine add_le_add _ _; apply degree_le_nat_degree,
end
lemma nat_degree_pow_le {p : R[X]} {n : ℕ} : (p ^ n).nat_degree ≤ n * p.nat_degree :=
begin
induction n with i hi,
{ simp },
{ rw [pow_succ, nat.succ_mul, add_comm],
apply le_trans nat_degree_mul_le,
exact add_le_add_left hi _ }
end
@[simp] lemma coeff_pow_mul_nat_degree (p : R[X]) (n : ℕ) :
(p ^ n).coeff (n * p.nat_degree) = p.leading_coeff ^ n :=
begin
induction n with i hi,
{ simp },
{ rw [pow_succ', pow_succ', nat.succ_mul],
by_cases hp1 : p.leading_coeff ^ i = 0,
{ rw [hp1, zero_mul],
by_cases hp2 : p ^ i = 0,
{ rw [hp2, zero_mul, coeff_zero] },
{ apply coeff_eq_zero_of_nat_degree_lt,
have h1 : (p ^ i).nat_degree < i * p.nat_degree,
{ apply lt_of_le_of_ne nat_degree_pow_le (λ h, hp2 _),
rw [←h, hp1] at hi,
exact leading_coeff_eq_zero.mp hi },
calc (p ^ i * p).nat_degree ≤ (p ^ i).nat_degree + p.nat_degree : nat_degree_mul_le
... < i * p.nat_degree + p.nat_degree : add_lt_add_right h1 _ } },
{ rw [←nat_degree_pow' hp1, ←leading_coeff_pow' hp1],
exact coeff_mul_degree_add_degree _ _ } }
end
lemma zero_le_degree_iff : 0 ≤ degree p ↔ p ≠ 0 :=
by rw [← not_lt, nat.with_bot.lt_zero_iff, degree_eq_bot]
lemma nat_degree_eq_zero_iff_degree_le_zero : p.nat_degree = 0 ↔ p.degree ≤ 0 :=
by rw [← nonpos_iff_eq_zero, nat_degree_le_iff_degree_le, with_bot.coe_zero]
theorem degree_le_iff_coeff_zero (f : R[X]) (n : with_bot ℕ) :
degree f ≤ n ↔ ∀ m : ℕ, n < m → coeff f m = 0 :=
by simp only [degree, finset.max, finset.sup_le_iff, mem_support_iff, ne.def, ← not_le,
not_imp_comm]
theorem degree_lt_iff_coeff_zero (f : R[X]) (n : ℕ) :
degree f < n ↔ ∀ m : ℕ, n ≤ m → coeff f m = 0 :=
begin
refine ⟨λ hf m hm, coeff_eq_zero_of_degree_lt (lt_of_lt_of_le hf (with_bot.coe_le_coe.2 hm)), _⟩,
simp only [degree, finset.sup_lt_iff (with_bot.bot_lt_coe n), mem_support_iff,
with_bot.some_eq_coe, with_bot.coe_lt_coe, ← @not_le ℕ, max_eq_sup_coe],
exact λ h m, mt (h m),
end
lemma degree_smul_le (a : R) (p : R[X]) : degree (a • p) ≤ degree p :=
begin
apply (degree_le_iff_coeff_zero _ _).2 (λ m hm, _),
rw degree_lt_iff_coeff_zero at hm,
simp [hm m le_rfl],
end
lemma nat_degree_smul_le (a : R) (p : R[X]) : nat_degree (a • p) ≤ nat_degree p :=
nat_degree_le_nat_degree (degree_smul_le a p)
lemma degree_lt_degree_mul_X (hp : p ≠ 0) : p.degree < (p * X).degree :=
by haveI := nontrivial.of_polynomial_ne hp; exact
have leading_coeff p * leading_coeff X ≠ 0, by simpa,
by erw [degree_mul' this, degree_eq_nat_degree hp,
degree_X, ← with_bot.coe_one, ← with_bot.coe_add, with_bot.coe_lt_coe];
exact nat.lt_succ_self _
lemma nat_degree_pos_iff_degree_pos :
0 < nat_degree p ↔ 0 < degree p :=
lt_iff_lt_of_le_iff_le nat_degree_le_iff_degree_le
lemma eq_C_of_nat_degree_le_zero (h : nat_degree p ≤ 0) : p = C (coeff p 0) :=
eq_C_of_degree_le_zero $ degree_le_of_nat_degree_le h
lemma eq_C_of_nat_degree_eq_zero (h : nat_degree p = 0) : p = C (coeff p 0) :=
eq_C_of_nat_degree_le_zero h.le
lemma ne_zero_of_coe_le_degree (hdeg : ↑n ≤ p.degree) : p ≠ 0 :=
zero_le_degree_iff.mp $ (with_bot.coe_le_coe.mpr n.zero_le).trans hdeg
lemma le_nat_degree_of_coe_le_degree (hdeg : ↑n ≤ p.degree) :
n ≤ p.nat_degree :=
with_bot.coe_le_coe.mp ((degree_eq_nat_degree $ ne_zero_of_coe_le_degree hdeg) ▸ hdeg)
lemma degree_sum_fin_lt {n : ℕ} (f : fin n → R) :
degree (∑ i : fin n, C (f i) * X ^ (i : ℕ)) < n :=
(degree_sum_le _ _).trans_lt $ (finset.sup_lt_iff $ with_bot.bot_lt_coe n).2 $
λ k hk, (degree_C_mul_X_pow_le _ _).trans_lt $ with_bot.coe_lt_coe.2 k.is_lt
lemma degree_linear_le : degree (C a * X + C b) ≤ 1 :=
degree_add_le_of_degree_le (degree_C_mul_X_le _) $ le_trans degree_C_le nat.with_bot.coe_nonneg
lemma degree_linear_lt : degree (C a * X + C b) < 2 :=
degree_linear_le.trans_lt $ with_bot.coe_lt_coe.mpr one_lt_two
lemma degree_C_lt_degree_C_mul_X (ha : a ≠ 0) : degree (C b) < degree (C a * X) :=
by simpa only [degree_C_mul_X ha] using degree_C_lt
@[simp] lemma degree_linear (ha : a ≠ 0) : degree (C a * X + C b) = 1 :=
by rw [degree_add_eq_left_of_degree_lt $ degree_C_lt_degree_C_mul_X ha, degree_C_mul_X ha]
lemma nat_degree_linear_le : nat_degree (C a * X + C b) ≤ 1 :=
nat_degree_le_of_degree_le degree_linear_le
@[simp] lemma nat_degree_linear (ha : a ≠ 0) : nat_degree (C a * X + C b) = 1 :=
nat_degree_eq_of_degree_eq_some $ degree_linear ha
@[simp] lemma leading_coeff_linear (ha : a ≠ 0): leading_coeff (C a * X + C b) = a :=
by rw [add_comm, leading_coeff_add_of_degree_lt (degree_C_lt_degree_C_mul_X ha),
leading_coeff_C_mul_X]
lemma degree_quadratic_le : degree (C a * X ^ 2 + C b * X + C c) ≤ 2 :=
by simpa only [add_assoc] using degree_add_le_of_degree_le (degree_C_mul_X_pow_le 2 a)
(le_trans degree_linear_le $ with_bot.coe_le_coe.mpr one_le_two)
lemma degree_quadratic_lt : degree (C a * X ^ 2 + C b * X + C c) < 3 :=
degree_quadratic_le.trans_lt $ with_bot.coe_lt_coe.mpr $ lt_add_one 2
lemma degree_linear_lt_degree_C_mul_X_sq (ha : a ≠ 0) :
degree (C b * X + C c) < degree (C a * X ^ 2) :=
by simpa only [degree_C_mul_X_pow 2 ha] using degree_linear_lt
@[simp] lemma degree_quadratic (ha : a ≠ 0) : degree (C a * X ^ 2 + C b * X + C c) = 2 :=
begin
rw [add_assoc, degree_add_eq_left_of_degree_lt $ degree_linear_lt_degree_C_mul_X_sq ha,
degree_C_mul_X_pow 2 ha],
refl
end
lemma nat_degree_quadratic_le : nat_degree (C a * X ^ 2 + C b * X + C c) ≤ 2 :=
nat_degree_le_of_degree_le degree_quadratic_le
@[simp] lemma nat_degree_quadratic (ha : a ≠ 0) : nat_degree (C a * X ^ 2 + C b * X + C c) = 2 :=
nat_degree_eq_of_degree_eq_some $ degree_quadratic ha
@[simp] lemma leading_coeff_quadratic (ha : a ≠ 0) :
leading_coeff (C a * X ^ 2 + C b * X + C c) = a :=
by rw [add_assoc, add_comm, leading_coeff_add_of_degree_lt $
degree_linear_lt_degree_C_mul_X_sq ha, leading_coeff_C_mul_X_pow]
lemma degree_cubic_le : degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) ≤ 3 :=
by simpa only [add_assoc] using degree_add_le_of_degree_le (degree_C_mul_X_pow_le 3 a)
(le_trans degree_quadratic_le $ with_bot.coe_le_coe.mpr $ nat.le_succ 2)
lemma degree_cubic_lt : degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) < 4 :=
degree_cubic_le.trans_lt $ with_bot.coe_lt_coe.mpr $ lt_add_one 3
lemma degree_quadratic_lt_degree_C_mul_X_cb (ha : a ≠ 0) :
degree (C b * X ^ 2 + C c * X + C d) < degree (C a * X ^ 3) :=
by simpa only [degree_C_mul_X_pow 3 ha] using degree_quadratic_lt
@[simp] lemma degree_cubic (ha : a ≠ 0) : degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) = 3 :=
begin
rw [add_assoc, add_assoc, ← add_assoc (C b * X ^ 2), degree_add_eq_left_of_degree_lt $
degree_quadratic_lt_degree_C_mul_X_cb ha, degree_C_mul_X_pow 3 ha],
refl
end
lemma nat_degree_cubic_le : nat_degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) ≤ 3 :=
nat_degree_le_of_degree_le degree_cubic_le
@[simp] lemma nat_degree_cubic (ha : a ≠ 0) :
nat_degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) = 3 :=
nat_degree_eq_of_degree_eq_some $ degree_cubic ha
@[simp] lemma leading_coeff_cubic (ha : a ≠ 0):
leading_coeff (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) = a :=
by rw [add_assoc, add_assoc, ← add_assoc (C b * X ^ 2), add_comm, leading_coeff_add_of_degree_lt $
degree_quadratic_lt_degree_C_mul_X_cb ha, leading_coeff_C_mul_X_pow]
end semiring
section nontrivial_semiring
variables [semiring R] [nontrivial R] {p q : R[X]}
@[simp] lemma degree_X_pow (n : ℕ) : degree ((X : R[X]) ^ n) = n :=
by rw [X_pow_eq_monomial, degree_monomial _ (one_ne_zero' R)]
@[simp] lemma nat_degree_X_pow (n : ℕ) : nat_degree ((X : R[X]) ^ n) = n :=
nat_degree_eq_of_degree_eq_some (degree_X_pow n)
/- This lemma explicitly does not require the `nontrivial R` assumption. -/
lemma nat_degree_X_pow_le {R : Type*} [semiring R] (n : ℕ) :
(X ^ n : R[X]).nat_degree ≤ n :=
begin
nontriviality R,
rwa polynomial.nat_degree_X_pow,
end
theorem not_is_unit_X : ¬ is_unit (X : R[X]) :=
λ ⟨⟨_, g, hfg, hgf⟩, rfl⟩, zero_ne_one' R $
by { change g * monomial 1 1 = 1 at hgf, rw [← coeff_one_zero, ← hgf], simp }
@[simp] lemma degree_mul_X : degree (p * X) = degree p + 1 := by simp [monic_X.degree_mul]
@[simp] lemma degree_mul_X_pow : degree (p * X ^ n) = degree p + n :=
by simp [(monic_X_pow n).degree_mul]
end nontrivial_semiring
section ring
variables [ring R] {p q : R[X]}
lemma degree_sub_le (p q : R[X]) : degree (p - q) ≤ max (degree p) (degree q) :=
by simpa only [sub_eq_add_neg, degree_neg q] using degree_add_le p (-q)
lemma degree_sub_lt (hd : degree p = degree q)
(hp0 : p ≠ 0) (hlc : leading_coeff p = leading_coeff q) :
degree (p - q) < degree p :=
have hp : monomial (nat_degree p) (leading_coeff p) + p.erase (nat_degree p) = p :=
monomial_add_erase _ _,
have hq : monomial (nat_degree q) (leading_coeff q) + q.erase (nat_degree q) = q :=
monomial_add_erase _ _,
have hd' : nat_degree p = nat_degree q := by unfold nat_degree; rw hd,
have hq0 : q ≠ 0 := mt degree_eq_bot.2 (hd ▸ mt degree_eq_bot.1 hp0),
calc degree (p - q) = degree (erase (nat_degree q) p + -erase (nat_degree q) q) :
by conv { to_lhs, rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg] }
... ≤ max (degree (erase (nat_degree q) p)) (degree (erase (nat_degree q) q))
: degree_neg (erase (nat_degree q) q) ▸ degree_add_le _ _
... < degree p : max_lt_iff.2 ⟨hd' ▸ degree_erase_lt hp0, hd.symm ▸ degree_erase_lt hq0⟩
lemma degree_X_sub_C_le (r : R) : (X - C r).degree ≤ 1 :=
(degree_sub_le _ _).trans (max_le degree_X_le (degree_C_le.trans zero_le_one))
lemma nat_degree_X_sub_C_le (r : R) : (X - C r).nat_degree ≤ 1 :=
nat_degree_le_iff_degree_le.2 $ degree_X_sub_C_le r
lemma degree_sub_eq_left_of_degree_lt (h : degree q < degree p) : degree (p - q) = degree p :=
by { rw ← degree_neg q at h, rw [sub_eq_add_neg, degree_add_eq_left_of_degree_lt h] }
lemma degree_sub_eq_right_of_degree_lt (h : degree p < degree q) : degree (p - q) = degree q :=
by { rw ← degree_neg q at h, rw [sub_eq_add_neg, degree_add_eq_right_of_degree_lt h, degree_neg] }
lemma nat_degree_sub_eq_left_of_nat_degree_lt (h : nat_degree q < nat_degree p) :
nat_degree (p - q) = nat_degree p :=
nat_degree_eq_of_degree_eq (degree_sub_eq_left_of_degree_lt (degree_lt_degree h))
lemma nat_degree_sub_eq_right_of_nat_degree_lt (h : nat_degree p < nat_degree q) :
nat_degree (p - q) = nat_degree q :=
nat_degree_eq_of_degree_eq (degree_sub_eq_right_of_degree_lt (degree_lt_degree h))
end ring
section nonzero_ring
variables [nontrivial R]
section semiring
variable [semiring R]
@[simp] lemma degree_X_add_C (a : R) : degree (X + C a) = 1 :=
have degree (C a) < degree (X : R[X]),
from calc degree (C a) ≤ 0 : degree_C_le
... < 1 : with_bot.some_lt_some.mpr zero_lt_one
... = degree X : degree_X.symm,
by rw [degree_add_eq_left_of_degree_lt this, degree_X]
@[simp] lemma nat_degree_X_add_C (x : R) : (X + C x).nat_degree = 1 :=
nat_degree_eq_of_degree_eq_some $ degree_X_add_C x
@[simp]
lemma next_coeff_X_add_C [semiring S] (c : S) : next_coeff (X + C c) = c :=
begin
nontriviality S,
simp [next_coeff_of_pos_nat_degree]
end
lemma degree_X_pow_add_C {n : ℕ} (hn : 0 < n) (a : R) :
degree ((X : R[X]) ^ n + C a) = n :=
have degree (C a) < degree ((X : R[X]) ^ n),
from degree_C_le.trans_lt $ by rwa [degree_X_pow, with_bot.coe_pos],
by rw [degree_add_eq_left_of_degree_lt this, degree_X_pow]
lemma X_pow_add_C_ne_zero {n : ℕ} (hn : 0 < n) (a : R) :
(X : R[X]) ^ n + C a ≠ 0 :=
mt degree_eq_bot.2 (show degree ((X : R[X]) ^ n + C a) ≠ ⊥,
by rw degree_X_pow_add_C hn a; exact dec_trivial)
theorem X_add_C_ne_zero (r : R) : X + C r ≠ 0 :=
pow_one (X : R[X]) ▸ X_pow_add_C_ne_zero zero_lt_one r
theorem zero_nmem_multiset_map_X_add_C {α : Type*} (m : multiset α) (f : α → R) :
(0 : R[X]) ∉ m.map (λ a, X + C (f a)) :=
λ mem, let ⟨a, _, ha⟩ := multiset.mem_map.mp mem in X_add_C_ne_zero _ ha
lemma nat_degree_X_pow_add_C {n : ℕ} {r : R} :
(X ^ n + C r).nat_degree = n :=
begin
by_cases hn : n = 0,
{ rw [hn, pow_zero, ←C_1, ←ring_hom.map_add, nat_degree_C] },
{ exact nat_degree_eq_of_degree_eq_some (degree_X_pow_add_C (pos_iff_ne_zero.mpr hn) r) },
end
lemma X_pow_add_C_ne_one {n : ℕ} (hn : 0 < n) (a : R) : (X : R[X]) ^ n + C a ≠ 1 :=
λ h, hn.ne' $ by simpa only [nat_degree_X_pow_add_C, nat_degree_one] using congr_arg nat_degree h
theorem X_add_C_ne_one (r : R) : X + C r ≠ 1 :=
pow_one (X : R[X]) ▸ X_pow_add_C_ne_one zero_lt_one r
end semiring
end nonzero_ring
section semiring
variable [semiring R]
@[simp] lemma leading_coeff_X_pow_add_C {n : ℕ} (hn : 0 < n) {r : R} :
(X ^ n + C r).leading_coeff = 1 :=
begin
nontriviality R,
rw [leading_coeff, nat_degree_X_pow_add_C, coeff_add, coeff_X_pow_self,
coeff_C, if_neg (pos_iff_ne_zero.mp hn), add_zero]
end
@[simp] lemma leading_coeff_X_add_C [semiring S] (r : S) :
(X + C r).leading_coeff = 1 :=
by rw [←pow_one (X : S[X]), leading_coeff_X_pow_add_C zero_lt_one]
@[simp] lemma leading_coeff_X_pow_add_one {n : ℕ} (hn : 0 < n) :
(X ^ n + 1 : R[X]).leading_coeff = 1 :=
leading_coeff_X_pow_add_C hn
@[simp] lemma leading_coeff_pow_X_add_C (r : R) (i : ℕ) :
leading_coeff ((X + C r) ^ i) = 1 :=
by { nontriviality, rw leading_coeff_pow'; simp }
end semiring
section ring
variable [ring R]
@[simp] lemma leading_coeff_X_pow_sub_C {n : ℕ} (hn : 0 < n) {r : R} :
(X ^ n - C r).leading_coeff = 1 :=
by rw [sub_eq_add_neg, ←map_neg C r, leading_coeff_X_pow_add_C hn]; apply_instance
@[simp] lemma leading_coeff_X_pow_sub_one {n : ℕ} (hn : 0 < n) :
(X ^ n - 1 : R[X]).leading_coeff = 1 :=
leading_coeff_X_pow_sub_C hn
variables [nontrivial R]
@[simp] lemma degree_X_sub_C (a : R) : degree (X - C a) = 1 :=
by rw [sub_eq_add_neg, ←map_neg C a, degree_X_add_C]
@[simp] lemma nat_degree_X_sub_C (x : R) : (X - C x).nat_degree = 1 :=
nat_degree_eq_of_degree_eq_some $ degree_X_sub_C x
@[simp]
lemma next_coeff_X_sub_C [ring S] (c : S) : next_coeff (X - C c) = - c :=
by rw [sub_eq_add_neg, ←map_neg C c, next_coeff_X_add_C]
lemma degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) :
degree ((X : R[X]) ^ n - C a) = n :=
by rw [sub_eq_add_neg, ←map_neg C a, degree_X_pow_add_C hn]; apply_instance
lemma X_pow_sub_C_ne_zero {n : ℕ} (hn : 0 < n) (a : R) :
(X : R[X]) ^ n - C a ≠ 0 :=
by { rw [sub_eq_add_neg, ←map_neg C a], exact X_pow_add_C_ne_zero hn _ }
theorem X_sub_C_ne_zero (r : R) : X - C r ≠ 0 :=
pow_one (X : R[X]) ▸ X_pow_sub_C_ne_zero zero_lt_one r
theorem zero_nmem_multiset_map_X_sub_C {α : Type*} (m : multiset α) (f : α → R) :
(0 : R[X]) ∉ m.map (λ a, X - C (f a)) :=
λ mem, let ⟨a, _, ha⟩ := multiset.mem_map.mp mem in X_sub_C_ne_zero _ ha
lemma nat_degree_X_pow_sub_C {n : ℕ} {r : R} :
(X ^ n - C r).nat_degree = n :=
by rw [sub_eq_add_neg, ←map_neg C r, nat_degree_X_pow_add_C]
@[simp] lemma leading_coeff_X_sub_C [ring S] (r : S) :
(X - C r).leading_coeff = 1 :=
by rw [sub_eq_add_neg, ←map_neg C r, leading_coeff_X_add_C]
end ring
section no_zero_divisors
variables [semiring R] [no_zero_divisors R] {p q : R[X]}
@[simp] lemma degree_mul : degree (p * q) = degree p + degree q :=
if hp0 : p = 0 then by simp only [hp0, degree_zero, zero_mul, with_bot.bot_add]
else if hq0 : q = 0 then by simp only [hq0, degree_zero, mul_zero, with_bot.add_bot]
else degree_mul' $ mul_ne_zero (mt leading_coeff_eq_zero.1 hp0)
(mt leading_coeff_eq_zero.1 hq0)
/-- `degree` as a monoid homomorphism between `R[X]` and `multiplicative (with_bot ℕ)`.
This is useful to prove results about multiplication and degree. -/
def degree_monoid_hom [nontrivial R] : R[X] →* multiplicative (with_bot ℕ) :=
{ to_fun := degree,
map_one' := degree_one,
map_mul' := λ _ _, degree_mul }
@[simp] lemma degree_pow [nontrivial R] (p : R[X]) (n : ℕ) :
degree (p ^ n) = n • (degree p) :=
map_pow (@degree_monoid_hom R _ _ _) _ _
@[simp] lemma leading_coeff_mul (p q : R[X]) : leading_coeff (p * q) =
leading_coeff p * leading_coeff q :=
begin
by_cases hp : p = 0,
{ simp only [hp, zero_mul, leading_coeff_zero] },
{ by_cases hq : q = 0,
{ simp only [hq, mul_zero, leading_coeff_zero] },
{ rw [leading_coeff_mul'],
exact mul_ne_zero (mt leading_coeff_eq_zero.1 hp) (mt leading_coeff_eq_zero.1 hq) } }
end
/-- `polynomial.leading_coeff` bundled as a `monoid_hom` when `R` has `no_zero_divisors`, and thus
`leading_coeff` is multiplicative -/
def leading_coeff_hom : R[X] →* R :=
{ to_fun := leading_coeff,
map_one' := by simp,
map_mul' := leading_coeff_mul }
@[simp] lemma leading_coeff_hom_apply (p : R[X]) :
leading_coeff_hom p = leading_coeff p := rfl
@[simp] lemma leading_coeff_pow (p : R[X]) (n : ℕ) :
leading_coeff (p ^ n) = leading_coeff p ^ n :=
(leading_coeff_hom : R[X] →* R).map_pow p n
end no_zero_divisors
end polynomial
|
64b9b5f80878fd095ad7a35474ac3158c154648b | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/exitAfterParseError.lean | 4d139b075f4a902e5ef74d2a0786b7c06a9ca186 | [
"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 | 27 | lean |
def foo
#exit
def bla
|
4e78eaf24dda5f086e02fc459fed3055ab44e29e | d642a6b1261b2cbe691e53561ac777b924751b63 | /src/data/equiv/algebra.lean | 46780b68ae0adb43c1b69bd574f3aaeb33d312b3 | [
"Apache-2.0"
] | permissive | cipher1024/mathlib | fee56b9954e969721715e45fea8bcb95f9dc03fe | d077887141000fefa5a264e30fa57520e9f03522 | refs/heads/master | 1,651,806,490,504 | 1,573,508,694,000 | 1,573,508,694,000 | 107,216,176 | 0 | 0 | Apache-2.0 | 1,647,363,136,000 | 1,508,213,014,000 | Lean | UTF-8 | Lean | false | false | 19,437 | lean | /-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Callum Sutton
-/
import data.equiv.basic algebra.field
/-!
# equivs in the algebraic hierarchy
In the first part there are theorems of the following
form: if `α` has a group structure and `α ≃ β` then `β` has a group structure, and
similarly for monoids, semigroups, rings, integral domains, fields and so on.
In the second part there are extensions of `equiv` called `add_equiv`,
`mul_equiv`, and `ring_equiv`, which are datatypes representing
isomorphisms of add_monoids/add_groups, monoids/groups and rings. We
also introduce the corresponding groups of automorphisms `add_aut`,
`mul_aut`, and `ring_aut`.
## Notations
The extended equivs all have coercions to functions, and the coercions are the canonical
notation when treating the isomorphisms as maps.
## Implementation notes
The fields for `mul_equiv`, `add_equiv`, and `ring_equiv` now avoid
the unbundled `is_mul_hom` and `is_add_hom`, as these are deprecated.
Definition of multiplication in the groups of automorphisms agrees
with function composition, multiplication in `equiv.perm`, and
multiplication in `category_theory.End`, not with
`category_theory.comp`.
## Tags
equiv, mul_equiv, add_equiv, ring_equiv, mul_aut, add_aut, ring_aut
-/
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
namespace equiv
section group
variables [group α]
@[to_additive]
protected def mul_left (a : α) : α ≃ α :=
{ to_fun := λx, a * x,
inv_fun := λx, a⁻¹ * x,
left_inv := assume x, show a⁻¹ * (a * x) = x, from inv_mul_cancel_left a x,
right_inv := assume x, show a * (a⁻¹ * x) = x, from mul_inv_cancel_left a x }
@[to_additive]
protected def mul_right (a : α) : α ≃ α :=
{ to_fun := λx, x * a,
inv_fun := λx, x * a⁻¹,
left_inv := assume x, show (x * a) * a⁻¹ = x, from mul_inv_cancel_right x a,
right_inv := assume x, show (x * a⁻¹) * a = x, from inv_mul_cancel_right x a }
@[to_additive]
protected def inv (α) [group α] : α ≃ α :=
{ to_fun := λa, a⁻¹,
inv_fun := λa, a⁻¹,
left_inv := assume a, inv_inv a,
right_inv := assume a, inv_inv a }
end group
section field
variables (α) [field α]
def units_equiv_ne_zero : units α ≃ {a : α | a ≠ 0} :=
⟨λ a, ⟨a.1, units.ne_zero _⟩, λ a, units.mk0 _ a.2, λ ⟨_, _, _, _⟩, units.ext rfl, λ ⟨_, _⟩, rfl⟩
variable {α}
@[simp] lemma coe_units_equiv_ne_zero (a : units α) :
((units_equiv_ne_zero α a) : α) = a := rfl
end field
section instances
variables (e : α ≃ β)
protected def has_zero [has_zero β] : has_zero α := ⟨e.symm 0⟩
lemma zero_def [has_zero β] : @has_zero.zero _ (equiv.has_zero e) = e.symm 0 := rfl
protected def has_one [has_one β] : has_one α := ⟨e.symm 1⟩
lemma one_def [has_one β] : @has_one.one _ (equiv.has_one e) = e.symm 1 := rfl
protected def has_mul [has_mul β] : has_mul α := ⟨λ x y, e.symm (e x * e y)⟩
lemma mul_def [has_mul β] (x y : α) :
@has_mul.mul _ (equiv.has_mul e) x y = e.symm (e x * e y) := rfl
protected def has_add [has_add β] : has_add α := ⟨λ x y, e.symm (e x + e y)⟩
lemma add_def [has_add β] (x y : α) :
@has_add.add _ (equiv.has_add e) x y = e.symm (e x + e y) := rfl
protected def has_inv [has_inv β] : has_inv α := ⟨λ x, e.symm (e x)⁻¹⟩
lemma inv_def [has_inv β] (x : α) : @has_inv.inv _ (equiv.has_inv e) x = e.symm (e x)⁻¹ := rfl
protected def has_neg [has_neg β] : has_neg α := ⟨λ x, e.symm (-e x)⟩
lemma neg_def [has_neg β] (x : α) : @has_neg.neg _ (equiv.has_neg e) x = e.symm (-e x) := rfl
protected def semigroup [semigroup β] : semigroup α :=
{ mul_assoc := by simp [mul_def, mul_assoc],
..equiv.has_mul e }
protected def comm_semigroup [comm_semigroup β] : comm_semigroup α :=
{ mul_comm := by simp [mul_def, mul_comm],
..equiv.semigroup e }
protected def monoid [monoid β] : monoid α :=
{ one_mul := by simp [mul_def, one_def],
mul_one := by simp [mul_def, one_def],
..equiv.semigroup e,
..equiv.has_one e }
protected def comm_monoid [comm_monoid β] : comm_monoid α :=
{ ..equiv.comm_semigroup e,
..equiv.monoid e }
protected def group [group β] : group α :=
{ mul_left_inv := by simp [mul_def, inv_def, one_def],
..equiv.monoid e,
..equiv.has_inv e }
protected def comm_group [comm_group β] : comm_group α :=
{ ..equiv.group e,
..equiv.comm_semigroup e }
protected def add_semigroup [add_semigroup β] : add_semigroup α :=
@additive.add_semigroup _ (@equiv.semigroup _ _ e multiplicative.semigroup)
protected def add_comm_semigroup [add_comm_semigroup β] : add_comm_semigroup α :=
@additive.add_comm_semigroup _ (@equiv.comm_semigroup _ _ e multiplicative.comm_semigroup)
protected def add_monoid [add_monoid β] : add_monoid α :=
@additive.add_monoid _ (@equiv.monoid _ _ e multiplicative.monoid)
protected def add_comm_monoid [add_comm_monoid β] : add_comm_monoid α :=
@additive.add_comm_monoid _ (@equiv.comm_monoid _ _ e multiplicative.comm_monoid)
protected def add_group [add_group β] : add_group α :=
@additive.add_group _ (@equiv.group _ _ e multiplicative.group)
protected def add_comm_group [add_comm_group β] : add_comm_group α :=
@additive.add_comm_group _ (@equiv.comm_group _ _ e multiplicative.comm_group)
protected def semiring [semiring β] : semiring α :=
{ right_distrib := by simp [mul_def, add_def, add_mul],
left_distrib := by simp [mul_def, add_def, mul_add],
zero_mul := by simp [mul_def, zero_def],
mul_zero := by simp [mul_def, zero_def],
..equiv.has_zero e,
..equiv.has_mul e,
..equiv.has_add e,
..equiv.monoid e,
..equiv.add_comm_monoid e }
protected def comm_semiring [comm_semiring β] : comm_semiring α :=
{ ..equiv.semiring e,
..equiv.comm_monoid e }
protected def ring [ring β] : ring α :=
{ ..equiv.semiring e,
..equiv.add_comm_group e }
protected def comm_ring [comm_ring β] : comm_ring α :=
{ ..equiv.comm_monoid e,
..equiv.ring e }
protected def zero_ne_one_class [zero_ne_one_class β] : zero_ne_one_class α :=
{ zero_ne_one := by simp [zero_def, one_def],
..equiv.has_zero e,
..equiv.has_one e }
protected def nonzero_comm_ring [nonzero_comm_ring β] : nonzero_comm_ring α :=
{ ..equiv.zero_ne_one_class e,
..equiv.comm_ring e }
protected def domain [domain β] : domain α :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := by simp [mul_def, zero_def, equiv.eq_symm_apply],
..equiv.has_zero e,
..equiv.zero_ne_one_class e,
..equiv.has_mul e,
..equiv.ring e }
protected def integral_domain [integral_domain β] : integral_domain α :=
{ ..equiv.domain e,
..equiv.nonzero_comm_ring e }
protected def division_ring [division_ring β] : division_ring α :=
{ inv_mul_cancel := λ _,
by simp [mul_def, inv_def, zero_def, one_def, (equiv.symm_apply_eq _).symm];
exact inv_mul_cancel,
mul_inv_cancel := λ _,
by simp [mul_def, inv_def, zero_def, one_def, (equiv.symm_apply_eq _).symm];
exact mul_inv_cancel,
..equiv.has_zero e,
..equiv.has_one e,
..equiv.domain e,
..equiv.has_inv e }
protected def field [field β] : field α :=
{ ..equiv.integral_domain e,
..equiv.division_ring e }
protected def discrete_field [discrete_field β] : discrete_field α :=
{ has_decidable_eq := equiv.decidable_eq e,
inv_zero := by simp [mul_def, inv_def, zero_def],
..equiv.has_mul e,
..equiv.has_inv e,
..equiv.has_zero e,
..equiv.field e }
end instances
end equiv
set_option old_structure_cmd true
/-- add_equiv α β is the type of an equiv α ≃ β which preserves addition. -/
structure add_equiv (α β : Type*) [has_add α] [has_add β] extends α ≃ β :=
(map_add' : ∀ x y : α, to_fun (x + y) = to_fun x + to_fun y)
/-- `mul_equiv α β` is the type of an equiv `α ≃ β` which preserves multiplication. -/
@[to_additive "`add_equiv α β` is the type of an equiv `α ≃ β` which preserves addition."]
structure mul_equiv (α β : Type*) [has_mul α] [has_mul β] extends α ≃ β :=
(map_mul' : ∀ x y : α, to_fun (x * y) = to_fun x * to_fun y)
infix ` ≃* `:25 := mul_equiv
infix ` ≃+ `:25 := add_equiv
namespace mul_equiv
@[to_additive]
instance {α β} [has_mul α] [has_mul β] : has_coe_to_fun (α ≃* β) := ⟨_, mul_equiv.to_fun⟩
variables [has_mul α] [has_mul β] [has_mul γ]
/-- A multiplicative isomorphism preserves multiplication (canonical form). -/
@[to_additive]
lemma map_mul (f : α ≃* β) : ∀ x y : α, f (x * y) = f x * f y := f.map_mul'
/-- A multiplicative isomorphism preserves multiplication (deprecated). -/
@[to_additive]
instance (h : α ≃* β) : is_mul_hom h := ⟨h.map_mul⟩
/-- The identity map is a multiplicative isomorphism. -/
@[refl, to_additive]
def refl (α : Type*) [has_mul α] : α ≃* α :=
{ map_mul' := λ _ _,rfl,
..equiv.refl _}
/-- The inverse of an isomorphism is an isomorphism. -/
@[symm, to_additive]
def symm (h : α ≃* β) : β ≃* α :=
{ map_mul' := λ n₁ n₂, function.injective_of_left_inverse h.left_inv begin
show h.to_equiv (h.to_equiv.symm (n₁ * n₂)) =
h ((h.to_equiv.symm n₁) * (h.to_equiv.symm n₂)),
rw h.map_mul,
show _ = h.to_equiv (_) * h.to_equiv (_),
rw [h.to_equiv.apply_symm_apply, h.to_equiv.apply_symm_apply, h.to_equiv.apply_symm_apply], end,
..h.to_equiv.symm}
@[simp, to_additive]
theorem to_equiv_symm (f : α ≃* β) : f.symm.to_equiv = f.to_equiv.symm := rfl
/-- Transitivity of multiplication-preserving isomorphisms -/
@[trans, to_additive]
def trans (h1 : α ≃* β) (h2 : β ≃* γ) : (α ≃* γ) :=
{ map_mul' := λ x y, show h2 (h1 (x * y)) = h2 (h1 x) * h2 (h1 y),
by rw [h1.map_mul, h2.map_mul],
..h1.to_equiv.trans h2.to_equiv }
/-- e.right_inv in canonical form -/
@[simp, to_additive]
lemma apply_symm_apply (e : α ≃* β) : ∀ (y : β), e (e.symm y) = y :=
e.to_equiv.apply_symm_apply
/-- e.left_inv in canonical form -/
@[simp, to_additive]
lemma symm_apply_apply (e : α ≃* β) : ∀ (x : α), e.symm (e x) = x :=
equiv.symm_apply_apply (e.to_equiv)
/-- a multiplicative equiv of monoids sends 1 to 1 (and is hence a monoid isomorphism) -/
@[simp, to_additive]
lemma map_one {α β} [monoid α] [monoid β] (h : α ≃* β) : h 1 = 1 :=
by rw [←mul_one (h 1), ←h.apply_symm_apply 1, ←h.map_mul, one_mul]
@[to_additive]
lemma map_eq_one_iff {α β} [monoid α] [monoid β] (h : α ≃* β) (x : α) :
h x = 1 ↔ x = 1 :=
h.map_one ▸ h.to_equiv.apply_eq_iff_eq x 1
@[to_additive]
lemma map_ne_one_iff {α β} [monoid α] [monoid β] (h : α ≃* β) (x : α) :
h x ≠ 1 ↔ x ≠ 1 :=
⟨mt (h.map_eq_one_iff x).2, mt (h.map_eq_one_iff x).1⟩
/-- A multiplicative bijection between two monoids is an isomorphism. -/
@[to_additive to_add_monoid_hom]
def to_monoid_hom {α β} [monoid α] [monoid β] (h : α ≃* β) : (α →* β) :=
{ to_fun := h,
map_mul' := h.map_mul,
map_one' := h.map_one }
/-- A multiplicative equivalence of groups preserves inversion. -/
@[to_additive]
lemma map_inv {α β} [group α] [group β] (h : α ≃* β) (x : α) : h x⁻¹ = (h x)⁻¹ :=
h.to_monoid_hom.map_inv x
/-- A multiplicative bijection between two monoids is a monoid hom
(deprecated -- use to_monoid_hom). -/
@[to_additive is_add_monoid_hom]
instance is_monoid_hom {α β} [monoid α] [monoid β] (h : α ≃* β) : is_monoid_hom h :=
⟨h.map_one⟩
/-- A multiplicative bijection between two groups is a group hom
(deprecated -- use to_monoid_hom). -/
@[to_additive is_add_group_hom]
instance is_group_hom {α β} [group α] [group β] (h : α ≃* β) :
is_group_hom h := { map_mul := h.map_mul }
/-- Two multiplicative isomorphisms agree if they are defined by the
same underlying function. -/
@[ext, to_additive
"Two additive isomorphisms agree if they are defined by the same underlying function."]
lemma ext {α β : Type*} [has_mul α] [has_mul β]
{f g : mul_equiv α β} (h : ∀ x, f x = g x) : f = g :=
begin
have h₁ := equiv.ext f.to_equiv g.to_equiv h,
cases f, cases g, congr,
{ exact (funext h) },
{ exact congr_arg equiv.inv_fun h₁ }
end
attribute [ext] add_equiv.ext
end mul_equiv
/-- An additive equivalence of additive groups preserves subtraction. -/
lemma add_equiv.map_sub {α β} [add_group α] [add_group β] (h : α ≃+ β) (x y : α) :
h (x - y) = h x - h y :=
h.to_add_monoid_hom.map_sub x y
/-- The group of multiplicative automorphisms. -/
@[to_additive "The group of additive automorphisms."]
def mul_aut (α : Type u) [has_mul α] := α ≃* α
namespace mul_aut
variables (α) [has_mul α]
/--
The group operation on multiplicative automorphisms is defined by
`λ g h, mul_equiv.trans h g`.
This means that multiplication agrees with composition, `(g*h)(x) = g (h x)`.
-/
instance : group (mul_aut α) :=
by refine_struct
{ mul := λ g h, mul_equiv.trans h g,
one := mul_equiv.refl α,
inv := mul_equiv.symm };
intros; ext; try { refl }; apply equiv.left_inv
/-- Monoid hom from the group of multiplicative automorphisms to the group of permutations. -/
def to_perm : mul_aut α →* equiv.perm α :=
by refine_struct { to_fun := mul_equiv.to_equiv }; intros; refl
end mul_aut
namespace add_aut
variables (α) [has_add α]
/--
The group operation on additive automorphisms is defined by
`λ g h, mul_equiv.trans h g`.
This means that multiplication agrees with composition, `(g*h)(x) = g (h x)`.
-/
instance group : group (add_aut α) :=
by refine_struct
{ mul := λ g h, add_equiv.trans h g,
one := add_equiv.refl α,
inv := add_equiv.symm };
intros; ext; try { refl }; apply equiv.left_inv
/-- Monoid hom from the group of multiplicative automorphisms to the group of permutations. -/
def to_perm : add_aut α →* equiv.perm α :=
by refine_struct { to_fun := add_equiv.to_equiv }; intros; refl
end add_aut
/-- A group is isomorphic to its group of units. -/
def to_units (α) [group α] : α ≃* units α :=
{ to_fun := λ x, ⟨x, x⁻¹, mul_inv_self _, inv_mul_self _⟩,
inv_fun := coe,
left_inv := λ x, rfl,
right_inv := λ u, units.ext rfl,
map_mul' := λ x y, units.ext rfl }
namespace units
variables [monoid α] [monoid β] [monoid γ]
(f : α → β) (g : β → γ) [is_monoid_hom f] [is_monoid_hom g]
def map_equiv (h : α ≃* β) : units α ≃* units β :=
{ inv_fun := map h.symm.to_monoid_hom,
left_inv := λ u, ext $ h.left_inv u,
right_inv := λ u, ext $ h.right_inv u,
.. map h.to_monoid_hom }
end units
/- (semi)ring equivalence. -/
structure ring_equiv (α β : Type*) [has_mul α] [has_add α] [has_mul β] [has_add β]
extends α ≃ β, α ≃* β, α ≃+ β
infix ` ≃+* `:25 := ring_equiv
namespace ring_equiv
section basic
variables [has_mul α] [has_add α] [has_mul β] [has_add β] [has_mul γ] [has_add γ]
instance : has_coe_to_fun (α ≃+* β) := ⟨_, ring_equiv.to_fun⟩
instance has_coe_to_mul_equiv : has_coe (α ≃+* β) (α ≃* β) := ⟨ring_equiv.to_mul_equiv⟩
instance has_coe_to_add_equiv : has_coe (α ≃+* β) (α ≃+ β) := ⟨ring_equiv.to_add_equiv⟩
@[squash_cast] lemma coe_mul_equiv (f : α ≃+* β) (a : α) :
(f : α ≃* β) a = f a := rfl
@[squash_cast] lemma coe_add_equiv (f : α ≃+* β) (a : α) :
(f : α ≃+ β) a = f a := rfl
variable (α)
/-- The identity map is a ring isomorphism. -/
@[refl] protected def refl : α ≃+* α := { .. mul_equiv.refl α, .. add_equiv.refl α }
variables {α}
/-- The inverse of a ring isomorphism is a ring isomorphis. -/
@[symm] protected def symm (e : α ≃+* β) : β ≃+* α :=
{ .. e.to_mul_equiv.symm, .. e.to_add_equiv.symm }
/-- Transitivity of `ring_equiv`. -/
@[trans] protected def trans (e₁ : α ≃+* β) (e₂ : β ≃+* γ) : α ≃+* γ :=
{ .. (e₁.to_mul_equiv.trans e₂.to_mul_equiv), .. (e₁.to_add_equiv.trans e₂.to_add_equiv) }
@[simp] lemma apply_symm_apply (e : α ≃+* β) : ∀ x, e (e.symm x) = x := e.to_equiv.apply_symm_apply
@[simp] lemma symm_apply_apply (e : α ≃+* β) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply
lemma image_eq_preimage (e : α ≃+* β) (s : set α) : e '' s = e.symm ⁻¹' s :=
e.to_equiv.image_eq_preimage s
end basic
section
variables [semiring α] [semiring β] (f : α ≃+* β) (x y : α)
/-- A ring isomorphism preserves multiplication. -/
lemma map_mul : f (x * y) = f x * f y := f.map_mul' x y
/-- A ring isomorphism sends one to one. -/
lemma map_one : f 1 = 1 := (f : α ≃* β).map_one
/-- A ring isomorphism preserves addition. -/
lemma map_add : f (x + y) = f x + f y := f.map_add' x y
/-- A ring isomorphism sends zero to zero. -/
lemma map_zero : f 0 = 0 := (f : α ≃+ β).map_zero
end
section
variables [ring α] [ring β] (f : α ≃+* β) (x y : α)
lemma map_neg : f (-x) = -f x := (f : α ≃+ β).map_neg x
lemma map_sub : f (x - y) = f x - f y := (f : α ≃+ β).map_sub x y
lemma map_neg_one : f (-1) = -1 := f.map_one ▸ f.map_neg 1
end
section semiring_hom
variables [semiring α] [semiring β]
/-- Reinterpret a ring equivalence as a ring homomorphism. -/
def to_ring_hom (e : α ≃+* β) : α →+* β :=
{ .. e.to_mul_equiv.to_monoid_hom, .. e.to_add_equiv.to_add_monoid_hom }
/-- Interpret an equivalence `f : α ≃ β` as a ring equivalence `α ≃+* β`. -/
def of (e : α ≃ β) [is_semiring_hom e] : α ≃+* β :=
{ .. e, .. monoid_hom.of e, .. add_monoid_hom.of e }
instance (e : α ≃+* β) : is_semiring_hom e := e.to_ring_hom.is_semiring_hom
end semiring_hom
section ring_hom
variables [ring α] [ring β]
/-- Interpret an equivalence `f : α ≃ β` as a ring equivalence `α ≃+* β`. -/
def of' (e : α ≃ β) [is_ring_hom e] : α ≃+* β :=
{ .. e, .. monoid_hom.of e, .. add_monoid_hom.of e }
instance (e : α ≃+* β) : is_ring_hom e := e.to_ring_hom.is_ring_hom
end ring_hom
/-- Two ring isomorphisms agree if they are defined by the
same underlying function. -/
@[ext] lemma ext {R S : Type*} [has_mul R] [has_add R] [has_mul S] [has_add S]
{f g : R ≃+* S} (h : ∀ x, f x = g x) : f = g :=
begin
have h₁ := equiv.ext f.to_equiv g.to_equiv h,
cases f, cases g, congr,
{ exact (funext h) },
{ exact congr_arg equiv.inv_fun h₁ }
end
end ring_equiv
/-- The group of ring automorphisms. -/
def ring_aut (R : Type u) [has_mul R] [has_add R] := ring_equiv R R
namespace ring_aut
variables (R : Type u) [has_mul R] [has_add R]
/--
The group operation on automorphisms of a ring is defined by
λ g h, ring_equiv.trans h g.
This means that multiplication agrees with composition, (g*h)(x) = g (h x) .
-/
instance : group (ring_aut R) :=
by refine_struct
{ mul := λ g h, ring_equiv.trans h g,
one := ring_equiv.refl R,
inv := ring_equiv.symm };
intros; ext; try { refl }; apply equiv.left_inv
/-- Monoid homomorphism from ring automorphisms to additive automorphisms. -/
def to_add_aut : ring_aut R →* add_aut R :=
by refine_struct { to_fun := ring_equiv.to_add_equiv }; intros; refl
/-- Monoid homomorphism from ring automorphisms to multiplicative automorphisms. -/
def to_mul_aut : ring_aut R →* mul_aut R :=
by refine_struct { to_fun := ring_equiv.to_mul_equiv }; intros; refl
/-- Monoid homomorphism from ring automorphisms to permutations. -/
def to_perm : ring_aut R →* equiv.perm R :=
by refine_struct { to_fun := ring_equiv.to_equiv }; intros; refl
end ring_aut
|
9f2855ea2955bd7d1c88625055250bf0172a1e4a | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/tactic/lint/basic.lean | f1b03c9dccb657e4367ec49c29515fe17ca0e66e | [
"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,092 | lean | /-
Copyright (c) 2020 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Robert Y. Lewis, Gabriel Ebner
-/
import tactic.core
/-!
# Basic linter types and attributes
This file defines the basic types and attributes used by the linting
framework. A linter essentially consists of a function
`declaration → tactic (option string)`, this function together with some
metadata is stored in the `linter` structure. We define two attributes:
* `@[linter]` applies to a declaration of type `linter` and adds it to the default linter set.
* `@[nolint linter_name]` omits the tagged declaration from being checked by
the linter with name `linter_name`.
-/
open tactic
setup_tactic_parser
section
local attribute [semireducible] reflected
/--
We store the list of nolint names as `@id (list name) (Prop simp_nf doc_blame has_coe_t)`
See Note [user attribute parameters]
-/
private meta def reflect_name_list : has_reflect (list name) | ns :=
`(id %%(expr.mk_app `(Prop) $ ns.map (flip expr.const [])) : list name)
private meta def parse_name_list (e : expr) : list name :=
e.app_arg.get_app_args.map expr.const_name
local attribute [instance] reflect_name_list
/-- Defines the user attribute `nolint` for skipping `#lint` -/
@[user_attribute]
meta def nolint_attr : user_attribute (name_map (list name)) (list name) :=
{ name := "nolint",
descr := "Do not report this declaration in any of the tests of `#lint`",
after_set := some $ λ n _ _, (do
ls@(_::_) ← parse_name_list <$> nolint_attr.get_param_untyped n
| fail "you need to specify at least one linter to disable",
skip),
cache_cfg :=
{ dependencies := [],
mk_cache := list.mfoldl
(λ cache d, native.rb_map.insert cache d <$>
parse_name_list <$> nolint_attr.get_param_untyped d)
mk_name_map },
parser := ident* }
end
add_tactic_doc
{ name := "nolint",
category := doc_category.attr,
decl_names := [`nolint_attr],
tags := ["linting"] }
/-- `should_be_linted linter decl` returns true if `decl` should be checked
using `linter`, i.e., if there is no `nolint` attribute. -/
meta def should_be_linted (linter : name) (decl : name) : tactic bool := do
c ← nolint_attr.get_cache,
pure $ linter ∉ (c.find decl).get_or_else []
/--
A linting test for the `#lint` command.
`test` defines a test to perform on every declaration. It should never fail. Returning `none`
signifies a passing test. Returning `some msg` reports a failing test with error `msg`.
`no_errors_found` is the message printed when all tests are negative, and `errors_found` is printed
when at least one test is positive.
If `is_fast` is false, this test will be omitted from `#lint-`.
If `auto_decls` is true, this test will also be executed on automatically generated declarations.
-/
meta structure linter :=
(test : declaration → tactic (option string))
(no_errors_found : string)
(errors_found : string)
(is_fast : bool := tt)
(auto_decls : bool)
/-- Takes a list of names that resolve to declarations of type `linter`,
and produces a list of linters. -/
meta def get_linters (l : list name) : tactic (list (name × linter)) :=
l.mmap (λ n, prod.mk n.last <$> (mk_const n >>= eval_expr linter)
<|> fail format!"invalid linter: {n}")
/-- Defines the user attribute `linter` for adding a linter to the default set.
Linters should be defined in the `linter` namespace.
A linter `linter.my_new_linter` is referred to as `my_new_linter` (without the `linter` namespace)
when used in `#lint`.
-/
@[user_attribute]
meta def linter_attr : user_attribute unit unit :=
{ name := "linter",
descr := "Use this declaration as a linting test in #lint",
after_set := some $ λ nm _ _,
mk_const nm >>= infer_type >>= unify `(linter) }
add_tactic_doc
{ name := "linter",
category := doc_category.attr,
decl_names := [`linter_attr],
tags := ["linting"] }
|
7554b1bede0418dad79271a4cce42fb79322a3ba | b7536f9489184b9b43e71226db2c620e772337e9 | /prelude/A.lean | 8e30f98e57391f671b0401a38a71a7b889423c6e | [] | no_license | gebner/lean4-split-leanpkg | bf7cf03b9672963188cb05dcba3a5d7b546a7d78 | 2a8cc83583263ef4f93a513271876ae69748661d | refs/heads/master | 1,681,771,764,711 | 1,620,545,291,000 | 1,620,545,291,000 | 365,693,312 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 11 | lean | def A := 1
|
048761e95c9e39150b3e8c74e82aff5a5ccba962 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/ring_theory/algebraic.lean | 4c411d58b5df938ea0ca623060b7f1d36bdc26bc | [
"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 | 10,097 | lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import linear_algebra.finite_dimensional
import ring_theory.integral_closure
import data.polynomial.integral_normalization
/-!
# Algebraic elements and algebraic extensions
An element of an R-algebra is algebraic over R if it is the root of a nonzero polynomial.
An R-algebra is algebraic over R if and only if all its elements are algebraic over R.
The main result in this file proves transitivity of algebraicity:
a tower of algebraic field extensions is algebraic.
-/
universes u v
open_locale classical
open polynomial
section
variables (R : Type u) {A : Type v} [comm_ring R] [ring A] [algebra R A]
/-- An element of an R-algebra is algebraic over R if it is the root of a nonzero polynomial. -/
def is_algebraic (x : A) : Prop :=
∃ p : polynomial R, p ≠ 0 ∧ aeval x p = 0
/-- An element of an R-algebra is transcendental over R if it is not algebraic over R. -/
def transcendental (x : A) : Prop := ¬ is_algebraic R x
variables {R}
/-- A subalgebra is algebraic if all its elements are algebraic. -/
def subalgebra.is_algebraic (S : subalgebra R A) : Prop := ∀ x ∈ S, is_algebraic R x
variables (R A)
/-- An algebra is algebraic if all its elements are algebraic. -/
def algebra.is_algebraic : Prop := ∀ x : A, is_algebraic R x
variables {R A}
/-- A subalgebra is algebraic if and only if it is algebraic an algebra. -/
lemma subalgebra.is_algebraic_iff (S : subalgebra R A) :
S.is_algebraic ↔ @algebra.is_algebraic R S _ _ (S.algebra) :=
begin
delta algebra.is_algebraic subalgebra.is_algebraic,
rw [subtype.forall'],
apply forall_congr, rintro ⟨x, hx⟩,
apply exists_congr, intro p,
apply and_congr iff.rfl,
have h : function.injective (S.val) := subtype.val_injective,
conv_rhs { rw [← h.eq_iff, alg_hom.map_zero], },
rw [← aeval_alg_hom_apply, S.val_apply]
end
/-- An algebra is algebraic if and only if it is algebraic as a subalgebra. -/
lemma algebra.is_algebraic_iff : algebra.is_algebraic R A ↔ (⊤ : subalgebra R A).is_algebraic :=
begin
delta algebra.is_algebraic subalgebra.is_algebraic,
simp only [algebra.mem_top, forall_prop_of_true, iff_self],
end
lemma is_algebraic_iff_not_injective {x : A} : is_algebraic R x ↔
¬ function.injective (polynomial.aeval x : polynomial R →ₐ[R] A) :=
by simp only [is_algebraic, alg_hom.injective_iff, not_forall, and.comm, exists_prop]
end
section zero_ne_one
variables (R : Type u) {A : Type v} [comm_ring R] [nontrivial R] [ring A] [algebra R A]
/-- An integral element of an algebra is algebraic.-/
lemma is_integral.is_algebraic {x : A} (h : is_integral R x) : is_algebraic R x :=
by { rcases h with ⟨p, hp, hpx⟩, exact ⟨p, hp.ne_zero, hpx⟩ }
variables {R}
/-- An element of `R` is algebraic, when viewed as an element of the `R`-algebra `A`. -/
lemma is_algebraic_algebra_map (a : R) : is_algebraic R (algebra_map R A a) :=
⟨X - C a, X_sub_C_ne_zero a, by simp only [aeval_C, aeval_X, alg_hom.map_sub, sub_self]⟩
end zero_ne_one
section field
variables (K : Type u) {A : Type v} [field K] [ring A] [algebra K A]
/-- An element of an algebra over a field is algebraic if and only if it is integral.-/
lemma is_algebraic_iff_is_integral {x : A} :
is_algebraic K x ↔ is_integral K x :=
begin
refine ⟨_, is_integral.is_algebraic K⟩,
rintro ⟨p, hp, hpx⟩,
refine ⟨_, monic_mul_leading_coeff_inv hp, _⟩,
rw [← aeval_def, alg_hom.map_mul, hpx, zero_mul],
end
lemma is_algebraic_iff_is_integral' :
algebra.is_algebraic K A ↔ algebra.is_integral K A :=
⟨λ h x, (is_algebraic_iff_is_integral K).mp (h x),
λ h x, (is_algebraic_iff_is_integral K).mpr (h x)⟩
end field
namespace algebra
variables {K : Type*} {L : Type*} {R : Type*} {S : Type*} {A : Type*}
variables [field K] [field L] [comm_ring R] [comm_ring S] [comm_ring A]
variables [algebra K L] [algebra L A] [algebra K A] [is_scalar_tower K L A]
variables [algebra R S] [algebra S A] [algebra R A] [is_scalar_tower R S A]
/-- If L is an algebraic field extension of K and A is an algebraic algebra over L,
then A is algebraic over K. -/
lemma is_algebraic_trans (L_alg : is_algebraic K L) (A_alg : is_algebraic L A) :
is_algebraic K A :=
begin
simp only [is_algebraic, is_algebraic_iff_is_integral] at L_alg A_alg ⊢,
exact is_integral_trans L_alg A_alg,
end
variables (K L)
/-- If A is an algebraic algebra over R, then A is algebraic over A when S is an extension of R,
and the map from `R` to `S` is injective. -/
lemma is_algebraic_of_larger_base_of_injective (hinj : function.injective (algebra_map R S))
(A_alg : is_algebraic R A) : is_algebraic S A :=
λ x, let ⟨p, hp₁, hp₂⟩ := A_alg x in
⟨p.map (algebra_map _ _),
by rwa [ne.def, ← degree_eq_bot, degree_map' hinj, degree_eq_bot],
by simpa⟩
/-- If A is an algebraic algebra over K, then A is algebraic over L when L is an extension of K -/
lemma is_algebraic_of_larger_base (A_alg : is_algebraic K A) : is_algebraic L A :=
is_algebraic_of_larger_base_of_injective (algebra_map K L).injective A_alg
variables {R S K L}
/-- A field extension is algebraic if it is finite. -/
lemma is_algebraic_of_finite [finite : finite_dimensional K L] : is_algebraic K L :=
λ x, (is_algebraic_iff_is_integral _).mpr (is_integral_of_submodule_noetherian ⊤
(is_noetherian.iff_fg.2 infer_instance) x algebra.mem_top)
end algebra
variables {R S : Type*} [comm_ring R] [is_domain R] [comm_ring S]
lemma exists_integral_multiple [algebra R S] {z : S} (hz : is_algebraic R z)
(inj : ∀ x, algebra_map R S x = 0 → x = 0) :
∃ (x : integral_closure R S) (y ≠ (0 : R)),
z * algebra_map R S y = x :=
begin
rcases hz with ⟨p, p_ne_zero, px⟩,
set a := p.leading_coeff with a_def,
have a_ne_zero : a ≠ 0 := mt polynomial.leading_coeff_eq_zero.mp p_ne_zero,
have y_integral : is_integral R (algebra_map R S a) := is_integral_algebra_map,
have x_integral : is_integral R (z * algebra_map R S a) :=
⟨p.integral_normalization,
monic_integral_normalization p_ne_zero,
integral_normalization_aeval_eq_zero px inj⟩,
exact ⟨⟨_, x_integral⟩, a, a_ne_zero, rfl⟩
end
/-- A fraction `(a : S) / (b : S)` can be reduced to `(c : S) / (d : R)`,
if `S` is the integral closure of `R` in an algebraic extension `L` of `R`. -/
lemma is_integral_closure.exists_smul_eq_mul {L : Type*} [field L]
[algebra R S] [algebra S L] [algebra R L] [is_scalar_tower R S L] [is_integral_closure S R L]
(h : algebra.is_algebraic R L) (inj : function.injective (algebra_map R L))
(a : S) {b : S} (hb : b ≠ 0) : ∃ (c : S) (d ≠ (0 : R)), d • a = b * c :=
begin
obtain ⟨c, d, d_ne, hx⟩ := exists_integral_multiple
(h (algebra_map _ L a / algebra_map _ L b))
((ring_hom.injective_iff _).mp inj),
refine ⟨is_integral_closure.mk' S (c : L) c.2, d, d_ne,
is_integral_closure.algebra_map_injective S R L _⟩,
simp only [algebra.smul_def, ring_hom.map_mul, is_integral_closure.algebra_map_mk', ← hx,
← is_scalar_tower.algebra_map_apply],
rw [← mul_assoc _ (_ / _), mul_div_cancel' (algebra_map S L a), mul_comm],
exact mt ((ring_hom.injective_iff _).mp (is_integral_closure.algebra_map_injective S R L) _) hb
end
section field
variables {K L : Type*} [field K] [field L] [algebra K L] (A : subalgebra K L)
lemma inv_eq_of_aeval_div_X_ne_zero {x : L} {p : polynomial K}
(aeval_ne : aeval x (div_X p) ≠ 0) :
x⁻¹ = aeval x (div_X p) / (aeval x p - algebra_map _ _ (p.coeff 0)) :=
begin
rw [inv_eq_iff, inv_div, div_eq_iff, sub_eq_iff_eq_add, mul_comm],
conv_lhs { rw ← div_X_mul_X_add p },
rw [alg_hom.map_add, alg_hom.map_mul, aeval_X, aeval_C],
exact aeval_ne
end
lemma inv_eq_of_root_of_coeff_zero_ne_zero {x : L} {p : polynomial K}
(aeval_eq : aeval x p = 0) (coeff_zero_ne : p.coeff 0 ≠ 0) :
x⁻¹ = - (aeval x (div_X p) / algebra_map _ _ (p.coeff 0)) :=
begin
convert inv_eq_of_aeval_div_X_ne_zero (mt (λ h, (algebra_map K L).injective _) coeff_zero_ne),
{ rw [aeval_eq, zero_sub, div_neg] },
rw ring_hom.map_zero,
convert aeval_eq,
conv_rhs { rw ← div_X_mul_X_add p },
rw [alg_hom.map_add, alg_hom.map_mul, h, zero_mul, zero_add, aeval_C]
end
lemma subalgebra.inv_mem_of_root_of_coeff_zero_ne_zero {x : A} {p : polynomial K}
(aeval_eq : aeval x p = 0) (coeff_zero_ne : p.coeff 0 ≠ 0) : (x⁻¹ : L) ∈ A :=
begin
have : (x⁻¹ : L) = aeval x (div_X p) / (aeval x p - algebra_map _ _ (p.coeff 0)),
{ rw [aeval_eq, subalgebra.coe_zero, zero_sub, div_neg],
convert inv_eq_of_root_of_coeff_zero_ne_zero _ coeff_zero_ne,
{ rw subalgebra.aeval_coe },
{ simpa using aeval_eq } },
rw [this, div_eq_mul_inv, aeval_eq, subalgebra.coe_zero, zero_sub, ← ring_hom.map_neg,
← ring_hom.map_inv],
exact A.mul_mem (aeval x p.div_X).2 (A.algebra_map_mem _),
end
lemma subalgebra.inv_mem_of_algebraic {x : A} (hx : is_algebraic K (x : L)) : (x⁻¹ : L) ∈ A :=
begin
obtain ⟨p, ne_zero, aeval_eq⟩ := hx,
rw [subalgebra.aeval_coe, subalgebra.coe_eq_zero] at aeval_eq,
revert ne_zero aeval_eq,
refine p.rec_on_horner _ _ _,
{ intro h,
contradiction },
{ intros p a hp ha ih ne_zero aeval_eq,
refine A.inv_mem_of_root_of_coeff_zero_ne_zero aeval_eq _,
rwa [coeff_add, hp, zero_add, coeff_C, if_pos rfl] },
{ intros p hp ih ne_zero aeval_eq,
rw [alg_hom.map_mul, aeval_X, mul_eq_zero] at aeval_eq,
cases aeval_eq with aeval_eq x_eq,
{ exact ih hp aeval_eq },
{ rw [x_eq, subalgebra.coe_zero, inv_zero],
exact A.zero_mem } }
end
/-- In an algebraic extension L/K, an intermediate subalgebra is a field. -/
lemma subalgebra.is_field_of_algebraic (hKL : algebra.is_algebraic K L) : is_field A :=
{ mul_inv_cancel := λ a ha, ⟨
⟨a⁻¹, A.inv_mem_of_algebraic (hKL a)⟩,
subtype.ext (mul_inv_cancel (mt (subalgebra.coe_eq_zero _).mp ha))⟩,
.. show nontrivial A, by apply_instance,
.. subalgebra.to_comm_ring A }
end field
|
2ac0ae6c5d613bbe70edfd2ae826a68902d744cd | c777c32c8e484e195053731103c5e52af26a25d1 | /src/group_theory/subsemigroup/centralizer.lean | 8eadf8a074db31984b64f2cf0e83e85313fb81a2 | [
"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 | 5,039 | lean | /-
Copyright (c) 2021 Thomas Browning. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Thomas Browning, Jireh Loreaux
-/
import group_theory.subsemigroup.center
import algebra.group_with_zero.units.lemmas
/-!
# Centralizers of magmas and semigroups
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
## Main definitions
* `set.centralizer`: the centralizer of a subset of a magma
* `subsemigroup.centralizer`: the centralizer of a subset of a semigroup
* `set.add_centralizer`: the centralizer of a subset of an additive magma
* `add_subsemigroup.centralizer`: the centralizer of a subset of an additive semigroup
We provide `monoid.centralizer`, `add_monoid.centralizer`, `subgroup.centralizer`, and
`add_subgroup.centralizer` in other files.
-/
variables {M : Type*} {S T : set M}
namespace set
variables (S)
/-- The centralizer of a subset of a magma. -/
@[to_additive add_centralizer /-" The centralizer of a subset of an additive magma. "-/]
def centralizer [has_mul M] : set M := {c | ∀ m ∈ S, m * c = c * m}
variables {S}
@[to_additive mem_add_centralizer]
lemma mem_centralizer_iff [has_mul M] {c : M} : c ∈ centralizer S ↔ ∀ m ∈ S, m * c = c * m :=
iff.rfl
@[to_additive decidable_mem_add_centralizer]
instance decidable_mem_centralizer [has_mul M] [∀ a : M, decidable $ ∀ b ∈ S, b * a = a * b] :
decidable_pred (∈ centralizer S) :=
λ _, decidable_of_iff' _ (mem_centralizer_iff)
variables (S)
@[simp, to_additive zero_mem_add_centralizer]
lemma one_mem_centralizer [mul_one_class M] : (1 : M) ∈ centralizer S :=
by simp [mem_centralizer_iff]
@[simp]
lemma zero_mem_centralizer [mul_zero_class M] : (0 : M) ∈ centralizer S :=
by simp [mem_centralizer_iff]
variables {S} {a b : M}
@[simp, to_additive add_mem_add_centralizer]
lemma mul_mem_centralizer [semigroup M] (ha : a ∈ centralizer S) (hb : b ∈ centralizer S) :
a * b ∈ centralizer S :=
λ g hg, by rw [mul_assoc, ←hb g hg, ← mul_assoc, ha g hg, mul_assoc]
@[simp, to_additive neg_mem_add_centralizer]
lemma inv_mem_centralizer [group M] (ha : a ∈ centralizer S) : a⁻¹ ∈ centralizer S :=
λ g hg, by rw [mul_inv_eq_iff_eq_mul, mul_assoc, eq_inv_mul_iff_mul_eq, ha g hg]
@[simp]
lemma add_mem_centralizer [distrib M] (ha : a ∈ centralizer S) (hb : b ∈ centralizer S) :
a + b ∈ centralizer S :=
λ c hc, by rw [add_mul, mul_add, ha c hc, hb c hc]
@[simp]
lemma neg_mem_centralizer [has_mul M] [has_distrib_neg M] (ha : a ∈ centralizer S) :
-a ∈ centralizer S :=
λ c hc, by rw [mul_neg, ha c hc, neg_mul]
@[simp]
lemma inv_mem_centralizer₀ [group_with_zero M] (ha : a ∈ centralizer S) : a⁻¹ ∈ centralizer S :=
(eq_or_ne a 0).elim (λ h, by { rw [h, inv_zero], exact zero_mem_centralizer S })
(λ ha0 c hc, by rw [mul_inv_eq_iff_eq_mul₀ ha0, mul_assoc, eq_inv_mul_iff_mul_eq₀ ha0, ha c hc])
@[simp, to_additive sub_mem_add_centralizer]
lemma div_mem_centralizer [group M] (ha : a ∈ centralizer S) (hb : b ∈ centralizer S) :
a / b ∈ centralizer S :=
begin
rw [div_eq_mul_inv],
exact mul_mem_centralizer ha (inv_mem_centralizer hb),
end
@[simp]
lemma div_mem_centralizer₀ [group_with_zero M] (ha : a ∈ centralizer S) (hb : b ∈ centralizer S) :
a / b ∈ centralizer S :=
begin
rw div_eq_mul_inv,
exact mul_mem_centralizer ha (inv_mem_centralizer₀ hb),
end
@[to_additive add_centralizer_subset]
lemma centralizer_subset [has_mul M] (h : S ⊆ T) : centralizer T ⊆ centralizer S :=
λ t ht s hs, ht s (h hs)
variables (M)
@[simp, to_additive add_centralizer_univ]
lemma centralizer_univ [has_mul M] : centralizer univ = center M :=
subset.antisymm (λ a ha b, ha b (set.mem_univ b)) (λ a ha b hb, ha b)
variables {M} (S)
@[simp, to_additive add_centralizer_eq_univ]
lemma centralizer_eq_univ [comm_semigroup M] : centralizer S = univ :=
subset.antisymm (subset_univ _) $ λ x hx y hy, mul_comm y x
end set
namespace subsemigroup
section
variables {M} [semigroup M] (S)
/-- The centralizer of a subset of a semigroup `M`. -/
@[to_additive "The centralizer of a subset of an additive semigroup."]
def centralizer : subsemigroup M :=
{ carrier := S.centralizer,
mul_mem' := λ a b, set.mul_mem_centralizer }
@[simp, norm_cast, to_additive] lemma coe_centralizer : ↑(centralizer S) = S.centralizer := rfl
variables {S}
@[to_additive] lemma mem_centralizer_iff {z : M} : z ∈ centralizer S ↔ ∀ g ∈ S, g * z = z * g :=
iff.rfl
@[to_additive] instance decidable_mem_centralizer (a) [decidable $ ∀ b ∈ S, b * a = a * b] :
decidable (a ∈ centralizer S) :=
decidable_of_iff' _ mem_centralizer_iff
@[to_additive]
lemma centralizer_le (h : S ⊆ T) : centralizer T ≤ centralizer S :=
set.centralizer_subset h
variables (M)
@[simp, to_additive]
lemma centralizer_univ : centralizer set.univ = center M :=
set_like.ext' (set.centralizer_univ M)
end
end subsemigroup
-- Guard against import creep
assert_not_exists finset
|
f274c7a8ad4dd5da6110d90c34c472610ddf1fa9 | 29cc89d6158dd3b90acbdbcab4d2c7eb9a7dbf0f | /x31_library.lean | b537191e60c1477f02617d4625a42f9844422f15 | [] | no_license | KjellZijlemaker/Logical_Verification_VU | ced0ba95316a30e3c94ba8eebd58ea004fa6f53b | 4578b93bf1615466996157bb333c84122b201d99 | refs/heads/master | 1,585,966,086,108 | 1,549,187,704,000 | 1,549,187,704,000 | 155,690,284 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,679 | lean | /- Library 3.1: Program Semantics — Operational Semantics -/
/- Some auxiliary lemmas concerning logical connectives and relations -/
@[simp] lemma or_imp_distrib {p q r : Prop} : p ∨ q → r ↔ (p → r) ∧ (q → r) :=
iff.intro
(assume h, ⟨assume hp, h (or.intro_left _ hp), assume hq, h (or.intro_right _ hq)⟩)
(assume ⟨hp, hq⟩ h, match h with or.inl h := hp h | or.inr h := hq h end)
@[simp] lemma and_imp_distrib {p q r : Prop} : p ∧ q → r ↔ (p → q → r) :=
iff.intro
(assume h hp hq, h ⟨hp, hq⟩)
(assume h ⟨hp, hq⟩, h hp hq)
@[simp] lemma exists_imp_distrib {α : Sort*} {p : α → Prop} {q : Prop} :
((∃a, p a) → q) ↔ (∀a, p a → q) :=
iff.intro
(assume h hp hq, h ⟨hp, hq⟩)
(assume h ⟨hp, hq⟩, h hp hq)
lemma and_exists {α : Sort*} {p : α → Prop} {q : Prop} :
(q ∧ (∃a, p a)) ↔ (∃a, q ∧ p a) :=
iff.intro
(assume ⟨h₁, a, h₂⟩, ⟨a, h₁, h₂⟩)
(assume ⟨a, h₁, h₂⟩, ⟨h₁, a, h₂⟩)
@[simp] lemma exists_false {α : Sort*} : (∃a:α, false) ↔ false :=
iff.intro (assume ⟨a, f⟩, f) (assume h, h.elim)
/-- `refl_trans r`: relexive and transitive closure of `r` -/
inductive refl_trans {α : Sort*} (r : α → α → Prop) (a : α) : α → Prop
| refl {} : refl_trans a
| tail {b c} : refl_trans b → r b c → refl_trans c
attribute [refl] refl_trans.refl
namespace refl_trans
variables {α : Sort*} {r : α → α → Prop} {a b c d : α}
@[trans] lemma trans (hab : refl_trans r a b) (hbc : refl_trans r b c) : refl_trans r a c :=
begin
induction hbc,
case refl_trans.refl { assumption },
case refl_trans.tail : c d hbc hcd hac { exact hac.tail hcd }
end
lemma single (hab : r a b) : refl_trans r a b :=
refl.tail hab
lemma head (hab : r a b) (hbc : refl_trans r b c) : refl_trans r a c :=
begin
induction hbc,
case refl_trans.refl { exact refl.tail hab },
case refl_trans.tail : c d hbc hcd hac { exact hac.tail hcd }
end
lemma head_induction_on {α : Sort*} {r : α → α → Prop} {b : α}
{P : ∀(a:α), refl_trans r a b → Prop}
{a : α} (h : refl_trans r a b)
(refl : P b refl)
(head : ∀{a c} (h' : r a c) (h : refl_trans r c b), P c h → P a (h.head h')) :
P a h :=
begin
induction h generalizing P,
case refl_trans.refl { exact refl },
case refl_trans.tail : b c hab hbc ih {
apply ih,
show P b _, from head hbc _ refl,
show ∀a a', r a a' → refl_trans r a' b → P a' _ → P a _, from assume a a' hab hbc, head hab _
}
end
lemma trans_induction_on {α : Sort*} {r : α → α → Prop}
{P : ∀{a b : α}, refl_trans r a b → Prop}
{a b : α} (h : refl_trans r a b)
(ih₁ : ∀a, @P a a refl)
(ih₂ : ∀{a b} (h : r a b), P (single h))
(ih₃ : ∀{a b c} (h₁ : refl_trans r a b) (h₂ : refl_trans r b c), P h₁ → P h₂ → P (h₁.trans h₂)) :
P h :=
begin
induction h,
case refl_trans.refl { exact ih₁ a },
case refl_trans.tail : b c hab hbc ih { exact ih₃ hab (single hbc) ih (ih₂ hbc) }
end
lemma lift {β : Sort*} {p : β → β → Prop} (f : α → β) (h : ∀a b, r a b → p (f a) (f b))
(hab : refl_trans r a b) : refl_trans p (f a) (f b) :=
hab.trans_induction_on (assume a, refl) (assume a b, single ∘ h _ _) (assume a b c _ _, trans)
lemma mono {p : α → α → Prop} :
(∀a b, r a b → p a b) → refl_trans r a b → refl_trans p a b :=
lift id
lemma refl_trans_refl_trans_eq : refl_trans (refl_trans r) = refl_trans r :=
funext $ assume a, funext $ assume b, propext $
iff.intro
(assume h, begin induction h, { refl }, { transitivity; assumption } end)
(refl_trans.mono (assume a b, single))
end refl_trans
|
9464b28a6c87c2993824cc7378d40092d046ab7d | a721fe7446524f18ba361625fc01033d9c8b7a78 | /src/principia/myrat/basic.lean | 07fcc874fc8255e4065dd7af58542d8009ff045a | [] | no_license | Sterrs/leaning | 8fd80d1f0a6117a220bb2e57ece639b9a63deadc | 3901cc953694b33adda86cb88ca30ba99594db31 | refs/heads/master | 1,627,023,822,744 | 1,616,515,221,000 | 1,616,515,221,000 | 245,512,190 | 2 | 0 | null | 1,616,429,050,000 | 1,583,527,118,000 | Lean | UTF-8 | Lean | false | false | 6,766 | lean | import .frac
import ..myfield.basic
namespace hidden
open myint
open myring
open ordered_myring
open ordered_integral_domain
def myrat := quotient frac.frac.setoid
namespace myrat
instance deceq: decidable_eq myrat := quotient.decidable_eq
private lemma class_setoid (x y : frac) :
⟦x⟧ = ⟦y⟧ ↔ x ≈ y := iff.intro quotient.exact quotient.sound
theorem class_equiv {x y : frac} :
⟦x⟧ = ⟦y⟧ ↔ x.num * y.denom = y.num * x.denom :=
begin
split; assume h,
rwa [←frac.setoid_equiv, ←class_setoid],
rwa [class_setoid, frac.setoid_equiv],
end
def neg : myrat → myrat :=
quotient.lift (λ x, ⟦-x⟧) frac.neg_well_defined
instance: has_neg myrat := ⟨neg⟩
instance has_neg2: has_neg (quotient frac.frac.setoid) := ⟨neg⟩
private theorem neg_eq_cls {x: frac}:
-⟦x⟧ = ⟦-x⟧ := rfl
private lemma one_pos: (0: myint) < 1 := nontrivial_zero_lt_one myint.nontrivial
instance: has_zero myrat := ⟨⟦⟨0, 1, one_pos⟩⟧⟩
theorem rat_zero: (0: myrat) = ⟦⟨0, 1, one_pos⟩⟧ := rfl
instance: has_one myrat := ⟨⟦⟨1, 1, one_pos⟩⟧⟩
theorem rat_one: (1: myrat) = ⟦⟨1, 1, one_pos⟩⟧ := rfl
instance: has_coe myint myrat := ⟨λ m, ⟦⟨m, 1, one_pos⟩⟧⟩
theorem nontrivial: (0: myrat) ≠ 1 :=
begin
assume hydroxide,
have := quotient.exact hydroxide,
rw frac.setoid_equiv at this,
cases quotient.exact this,
end
theorem coe_int {m : myint} : (↑m : myrat) = ⟦⟨m, 1, one_pos⟩⟧ :=
rfl
theorem coe_cancel {m n : myint}:
(↑m : myrat) = ↑n ↔ m = n :=
begin
split; assume h, {
rw [coe_int, coe_int, class_equiv] at h,
dsimp only [] at h,
rwa [mul_one, mul_one] at h,
}, {
congr, assumption,
},
end
def add : myrat → myrat → myrat :=
quotient.lift₂ (λ x y, ⟦x + y⟧) frac.add_well_defined
instance: has_add myrat := ⟨add⟩
instance has_add2: has_add (quotient frac.frac.setoid) := ⟨add⟩
private theorem add_eq_cls {x y: frac}:
⟦x⟧ + ⟦y⟧ = ⟦x + y⟧ := rfl
theorem two_nzero: (2: myrat) ≠ 0 :=
begin
assume water,
have := quotient.exact water,
rw frac.setoid_equiv at this,
cases (quotient.exact this),
end
def sub (x y : myrat) : myrat :=
x + -y
instance: has_sub myrat := ⟨sub⟩
instance has_sub2: has_sub (quotient frac.frac.setoid) := ⟨sub⟩
private theorem sub_eq_cls {x y: frac}:
⟦x⟧ - ⟦y⟧ = ⟦x + -y⟧ := rfl
variables {x y z : myrat}
variables {m n k : myint}
theorem add_coe: (↑m : myrat) + ↑n = ↑(m + n) :=
begin
repeat { rw coe_int, },
apply congr_arg quotient.mk,
rw ←frac.frac_add_add,
dsimp [frac.add],
repeat {rw mul_one},
refl,
end
theorem neg_coe: -(↑m : myrat) = ↑(-m) :=
begin
repeat { rw coe_int, },
rw [neg_eq_cls, frac.frac_neg_neg],
dsimp [frac.neg],
refl,
end
def mul : myrat → myrat → myrat :=
quotient.lift₂ (λ x y, ⟦x * y⟧) frac.mul_well_defined
instance: has_mul myrat := ⟨mul⟩
instance has_mul2: has_mul (quotient frac.frac.setoid) := ⟨mul⟩
def inv : myrat → myrat :=
quotient.lift (λ x, ⟦x⁻¹⟧) frac.inv_well_defined
instance: has_inv myrat := ⟨inv⟩
instance has_inv2: has_inv (quotient frac.frac.setoid) := ⟨inv⟩
-- Multiplication
private theorem mul_eq_cls {x y : frac}:
⟦x⟧ * ⟦y⟧ = ⟦x * y⟧ := rfl
-- Reciprocal "inv"
private theorem inv_eq_cls {x : frac}:
⟦x⟧⁻¹ = ⟦x⁻¹⟧ := rfl
@[simp]
theorem zero_inv : 0⁻¹ = (0 : myrat) :=
rfl
private theorem inv_self_mul : x ≠ 0 → x * x⁻¹ = 1 :=
begin
cases quotient.exists_rep x with a ha, subst ha,
assume hx,
rw [inv_eq_cls, mul_eq_cls, rat_one],
rw class_equiv,
dsimp only [],
rw [frac.mul_num, frac.mul_denom],
have : a.num ≠ 0,
rw rat_zero at hx,
have h : ¬⟦a⟧ = ⟦{num := 0, denom := 1, denom_pos := one_pos}⟧,
from hx,
clear hx,
rw [class_equiv, mul_one, zero_mul] at h,
assumption,
rw [frac.inv_num_nonzero this, frac.inv_denom_nonzero this],
ac_refl,
end
instance: myring myrat := ⟨
by apply_instance,
λ x y z: myrat,
begin
cases quotient.exists_rep x with a ha, subst ha,
cases quotient.exists_rep y with b hb, subst hb,
cases quotient.exists_rep z with c hc, subst hc,
apply congr_arg quotient.mk,
rw frac.num_and_denom_eq,
repeat { rw frac.add_num <|> rw frac.add_denom <|> rw myring.add_mul },
split; ac_refl,
end,
λ x: myrat,
begin
cases quotient.exists_rep x with a ha, subst ha,
rw [rat_zero, add_eq_cls],
rw frac.sound_exact_iff,
rw frac.setoid_equiv,
rw frac.add_denom,
rw frac.add_num,
dsimp only [],
rw myring.zero_mul,
rw myring.add_zero,
repeat {rw myring.mul_one},
end,
λ x: myrat,
begin
cases quotient.exists_rep x with a ha, subst ha,
rw neg_eq_cls,
rw add_eq_cls,
apply quotient.sound,
rw frac.setoid_equiv,
dsimp only [],
repeat {rw myring.zero_mul},
rw frac.add_num,
rw mul_one,
rw frac.neg_denom,
rw frac.neg_num,
rw neg_mul,
from add_neg _,
end,
λ x y z: myrat,
begin
cases quotient.exists_rep x with a ha,
cases quotient.exists_rep y with b hb,
cases quotient.exists_rep z with c hc,
rw [←ha, ←hb, ←hc],
repeat {rw mul_eq_cls,},
rw class_equiv,
repeat { rw frac.mul_num <|> rw frac.mul_denom, },
ac_refl,
end,
λ x y: myrat,
begin
cases quotient.exists_rep x with a ha,
cases quotient.exists_rep y with b hb,
rw [←ha, ←hb],
repeat {rw mul_eq_cls,},
rw class_equiv,
repeat { rw frac.mul_num <|> rw frac.mul_denom, },
ac_refl,
end,
λ x: myrat,
begin
cases quotient.exists_rep x with a ha,
rw [←ha, rat_one],
rw mul_eq_cls,
rw class_equiv,
rw [frac.mul_num, frac.mul_denom],
dsimp only [],
repeat {rw myring.mul_one},
end,
λ x y z: myrat,
begin
cases quotient.exists_rep x with a ha, subst ha,
cases quotient.exists_rep y with b hb, subst hb,
cases quotient.exists_rep z with c hc, subst hc,
repeat { rw mul_eq_cls <|> rw add_eq_cls, },
rw class_equiv,
repeat { rw frac.mul_num <|> rw frac.mul_denom <|> rw frac.add_num <|> rw frac.add_denom, },
-- ac_refl can't expand brackets
repeat { rw myring.add_mul <|> rw myring.mul_add, },
ac_refl,
end⟩
instance: myfield myrat := {
mul_inv := λ x hx, inv_self_mul hx,
nontrivial := nontrivial
}
-- Moved here as they might be useful
-- theorem one_plus_one : 1 + 1 = (2 : myrat):= rfl
-- theorem double_eq_add_self : 2 * x = x + x :=
-- by rw [←one_plus_one, add_mul, one_mul]
-- theorem half_plus_half {ε : myrat} : ε / 2 + ε / 2 = ε :=
-- begin
-- rw [←double_eq_add_self, mul_comm, div_mul_cancel two_nzero],
-- end
end myrat
end hidden
|
a3b25d4b1b2203c35a11f2735e53a4fdf555eca1 | 75bd9c50a345718d735a7533c007cf45f9da9a83 | /src/algebra/associated.lean | 5f02075f274de1d0cca1f402ec38621890f9c9f0 | [
"Apache-2.0"
] | permissive | jtbarker/mathlib | a1a3b1ddc16179826260578410746756ef18032c | 392d3e376b44265ef2dedbd92231d3177acc1fd0 | refs/heads/master | 1,671,246,411,096 | 1,600,801,712,000 | 1,600,801,712,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 27,424 | lean | /-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Jens Wagemaker
-/
import data.multiset.basic
import algebra.divisibility
/-!
# Associated, prime, and irreducible elements.
-/
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
lemma is_unit_pow [monoid α] {a : α} (n : ℕ) : is_unit a → is_unit (a ^ n) :=
λ ⟨u, hu⟩, ⟨u ^ n, by simp *⟩
theorem is_unit_iff_dvd_one [comm_monoid α] {x : α} : is_unit x ↔ x ∣ 1 :=
⟨by rintro ⟨u, rfl⟩; exact ⟨_, u.mul_inv.symm⟩,
λ ⟨y, h⟩, ⟨⟨x, y, h.symm, by rw [h, mul_comm]⟩, rfl⟩⟩
theorem is_unit_iff_forall_dvd [comm_monoid α] {x : α} :
is_unit x ↔ ∀ y, x ∣ y :=
is_unit_iff_dvd_one.trans ⟨λ h y, dvd.trans h (one_dvd _), λ h, h _⟩
theorem is_unit_of_dvd_unit {α} [comm_monoid α] {x y : α}
(xy : x ∣ y) (hu : is_unit y) : is_unit x :=
is_unit_iff_dvd_one.2 $ dvd_trans xy $ is_unit_iff_dvd_one.1 hu
theorem is_unit_int {n : ℤ} : is_unit n ↔ n.nat_abs = 1 :=
⟨begin rintro ⟨u, rfl⟩, exact (int.units_eq_one_or u).elim (by simp) (by simp) end,
λ h, is_unit_iff_dvd_one.2 ⟨n, by rw [← int.nat_abs_mul_self, h]; refl⟩⟩
lemma is_unit_of_dvd_one [comm_monoid α] : ∀a ∣ 1, is_unit (a:α)
| a ⟨b, eq⟩ := ⟨units.mk_of_mul_eq_one a b eq.symm, rfl⟩
lemma dvd_and_not_dvd_iff [comm_cancel_monoid_with_zero α] {x y : α} :
x ∣ y ∧ ¬y ∣ x ↔ dvd_not_unit x y :=
⟨λ ⟨⟨d, hd⟩, hyx⟩, ⟨λ hx0, by simpa [hx0] using hyx, ⟨d,
mt is_unit_iff_dvd_one.1 (λ ⟨e, he⟩, hyx ⟨e, by rw [hd, mul_assoc, ← he, mul_one]⟩), hd⟩⟩,
λ ⟨hx0, d, hdu, hdx⟩, ⟨⟨d, hdx⟩, λ ⟨e, he⟩, hdu (is_unit_of_dvd_one _
⟨e, mul_left_cancel' hx0 $ by conv {to_lhs, rw [he, hdx]};simp [mul_assoc]⟩)⟩⟩
lemma pow_dvd_pow_iff [comm_cancel_monoid_with_zero α]
{x : α} {n m : ℕ} (h0 : x ≠ 0) (h1 : ¬ is_unit x) :
x ^ n ∣ x ^ m ↔ n ≤ m :=
begin
split,
{ intro h, rw [← not_lt], intro hmn, apply h1,
have : x ^ m * x ∣ x ^ m * 1,
{ rw [← pow_succ', mul_one], exact dvd_trans (pow_dvd_pow _ (nat.succ_le_of_lt hmn)) h },
rwa [mul_dvd_mul_iff_left, ← is_unit_iff_dvd_one] at this, apply pow_ne_zero m h0 },
{ apply pow_dvd_pow }
end
section prime
variables [comm_monoid_with_zero α]
/-- prime element of a `comm_monoid_with_zero` -/
def prime (p : α) : Prop :=
p ≠ 0 ∧ ¬ is_unit p ∧ (∀a b, p ∣ a * b → p ∣ a ∨ p ∣ b)
namespace prime
variables {p : α} (hp : prime p)
lemma ne_zero (hp : prime p) : p ≠ 0 :=
hp.1
lemma not_unit (hp : prime p) : ¬ is_unit p :=
hp.2.1
lemma ne_one (hp : prime p) : p ≠ 1 :=
λ h, hp.2.1 (h.symm ▸ is_unit_one)
lemma div_or_div (hp : prime p) {a b : α} (h : p ∣ a * b) :
p ∣ a ∨ p ∣ b :=
hp.2.2 a b h
lemma dvd_of_dvd_pow (hp : prime p) {a : α} {n : ℕ} (h : p ∣ a^n) :
p ∣ a :=
begin
induction n with n ih,
{ rw pow_zero at h,
have := is_unit_of_dvd_one _ h,
have := not_unit hp,
contradiction },
rw pow_succ at h,
cases div_or_div hp h with dvd_a dvd_pow,
{ assumption },
exact ih dvd_pow
end
end prime
@[simp] lemma not_prime_zero : ¬ prime (0 : α) :=
λ h, h.ne_zero rfl
@[simp] lemma not_prime_one : ¬ prime (1 : α) :=
λ h, h.not_unit is_unit_one
lemma exists_mem_multiset_dvd_of_prime {s : multiset α} {p : α} (hp : prime p) :
p ∣ s.prod → ∃a∈s, p ∣ a :=
multiset.induction_on s (assume h, (hp.not_unit $ is_unit_of_dvd_one _ h).elim) $
assume a s ih h,
have p ∣ a * s.prod, by simpa using h,
match hp.div_or_div this with
| or.inl h := ⟨a, multiset.mem_cons_self a s, h⟩
| or.inr h := let ⟨a, has, h⟩ := ih h in ⟨a, multiset.mem_cons_of_mem has, h⟩
end
end prime
lemma left_dvd_or_dvd_right_of_dvd_prime_mul [comm_cancel_monoid_with_zero α] {a : α} :
∀ {b p : α}, prime p → a ∣ p * b → p ∣ a ∨ a ∣ b :=
begin
rintros b p hp ⟨c, hc⟩,
rcases hp.2.2 a c (hc ▸ dvd_mul_right _ _) with h | ⟨x, rfl⟩,
{ exact or.inl h },
{ rw [mul_left_comm, mul_right_inj' hp.ne_zero] at hc,
exact or.inr (hc.symm ▸ dvd_mul_right _ _) }
end
/-- `irreducible p` states that `p` is non-unit and only factors into units.
We explicitly avoid stating that `p` is non-zero, this would require a semiring. Assuming only a
monoid allows us to reuse irreducible for associated elements.
-/
@[class] def irreducible [monoid α] (p : α) : Prop :=
¬ is_unit p ∧ ∀a b, p = a * b → is_unit a ∨ is_unit b
namespace irreducible
lemma not_unit [monoid α] {p : α} (hp : irreducible p) : ¬ is_unit p :=
hp.1
lemma is_unit_or_is_unit [monoid α] {p : α} (hp : irreducible p) {a b : α} (h : p = a * b) :
is_unit a ∨ is_unit b :=
hp.2 a b h
end irreducible
@[simp] theorem not_irreducible_one [monoid α] : ¬ irreducible (1 : α) :=
by simp [irreducible]
@[simp] theorem not_irreducible_zero [monoid_with_zero α] : ¬ irreducible (0 : α)
| ⟨hn0, h⟩ := have is_unit (0:α) ∨ is_unit (0:α), from h 0 0 ((mul_zero 0).symm),
this.elim hn0 hn0
theorem irreducible.ne_zero [monoid_with_zero α] : ∀ {p:α}, irreducible p → p ≠ 0
| _ hp rfl := not_irreducible_zero hp
theorem of_irreducible_mul {α} [monoid α] {x y : α} :
irreducible (x * y) → is_unit x ∨ is_unit y
| ⟨_, h⟩ := h _ _ rfl
theorem irreducible_or_factor {α} [monoid α] (x : α) (h : ¬ is_unit x) :
irreducible x ∨ ∃ a b, ¬ is_unit a ∧ ¬ is_unit b ∧ a * b = x :=
begin
haveI := classical.dec,
refine or_iff_not_imp_right.2 (λ H, _),
simp [h, irreducible] at H ⊢,
refine λ a b h, classical.by_contradiction $ λ o, _,
simp [not_or_distrib] at o,
exact H _ o.1 _ o.2 h.symm
end
lemma irreducible_of_prime [comm_cancel_monoid_with_zero α] {p : α} (hp : prime p) : irreducible p :=
⟨hp.not_unit, λ a b hab,
(show a * b ∣ a ∨ a * b ∣ b, from hab ▸ hp.div_or_div (hab ▸ (dvd_refl _))).elim
(λ ⟨x, hx⟩, or.inr (is_unit_iff_dvd_one.2
⟨x, mul_right_cancel' (show a ≠ 0, from λ h, by simp [*, prime] at *)
$ by conv {to_lhs, rw hx}; simp [mul_comm, mul_assoc, mul_left_comm]⟩))
(λ ⟨x, hx⟩, or.inl (is_unit_iff_dvd_one.2
⟨x, mul_right_cancel' (show b ≠ 0, from λ h, by simp [*, prime] at *)
$ by conv {to_lhs, rw hx}; simp [mul_comm, mul_assoc, mul_left_comm]⟩))⟩
lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul [comm_cancel_monoid_with_zero α]
{p : α} (hp : prime p) {a b : α} {k l : ℕ} :
p ^ k ∣ a → p ^ l ∣ b → p ^ ((k + l) + 1) ∣ a * b → p ^ (k + 1) ∣ a ∨ p ^ (l + 1) ∣ b :=
λ ⟨x, hx⟩ ⟨y, hy⟩ ⟨z, hz⟩,
have h : p ^ (k + l) * (x * y) = p ^ (k + l) * (p * z),
by simpa [mul_comm, _root_.pow_add, hx, hy, mul_assoc, mul_left_comm] using hz,
have hp0: p ^ (k + l) ≠ 0, from pow_ne_zero _ hp.ne_zero,
have hpd : p ∣ x * y, from ⟨z, by rwa [mul_right_inj' hp0] at h⟩,
(hp.div_or_div hpd).elim
(λ ⟨d, hd⟩, or.inl ⟨d, by simp [*, pow_succ, mul_comm, mul_left_comm, mul_assoc]⟩)
(λ ⟨d, hd⟩, or.inr ⟨d, by simp [*, pow_succ, mul_comm, mul_left_comm, mul_assoc]⟩)
/-- If `p` and `q` are irreducible, then `p ∣ q` implies `q ∣ p`. -/
lemma dvd_symm_of_irreducible [monoid α] {p q : α}
(hp : irreducible p) (hq : irreducible q) : p ∣ q → q ∣ p :=
begin
tactic.unfreeze_local_instances,
rintros ⟨q', rfl⟩,
rw is_unit.mul_right_dvd (or.resolve_left (of_irreducible_mul hq) hp.not_unit),
end
lemma dvd_symm_iff_of_irreducible [monoid α] {p q : α}
(hp : irreducible p) (hq : irreducible q) : p ∣ q ↔ q ∣ p :=
⟨dvd_symm_of_irreducible hp hq, dvd_symm_of_irreducible hq hp⟩
/-- Two elements of a `monoid` are `associated` if one of them is another one
multiplied by a unit on the right. -/
def associated [monoid α] (x y : α) : Prop := ∃u:units α, x * u = y
local infix ` ~ᵤ ` : 50 := associated
namespace associated
@[refl] protected theorem refl [monoid α] (x : α) : x ~ᵤ x := ⟨1, by simp⟩
@[symm] protected theorem symm [monoid α] : ∀{x y : α}, x ~ᵤ y → y ~ᵤ x
| x _ ⟨u, rfl⟩ := ⟨u⁻¹, by rw [mul_assoc, units.mul_inv, mul_one]⟩
@[trans] protected theorem trans [monoid α] : ∀{x y z : α}, x ~ᵤ y → y ~ᵤ z → x ~ᵤ z
| x _ _ ⟨u, rfl⟩ ⟨v, rfl⟩ := ⟨u * v, by rw [units.coe_mul, mul_assoc]⟩
/-- The setoid of the relation `x ~ᵤ y` iff there is a unit `u` such that `x * u = y` -/
protected def setoid (α : Type*) [monoid α] : setoid α :=
{ r := associated, iseqv := ⟨associated.refl, λa b, associated.symm, λa b c, associated.trans⟩ }
end associated
local attribute [instance] associated.setoid
theorem unit_associated_one [monoid α] {u : units α} : (u : α) ~ᵤ 1 := ⟨u⁻¹, units.mul_inv u⟩
theorem associated_one_iff_is_unit [monoid α] {a : α} : (a : α) ~ᵤ 1 ↔ is_unit a :=
iff.intro
(assume h, let ⟨c, h⟩ := h.symm in h ▸ ⟨c, (one_mul _).symm⟩)
(assume ⟨c, h⟩, associated.symm ⟨c, by simp [h]⟩)
theorem associated_zero_iff_eq_zero [monoid_with_zero α] (a : α) : a ~ᵤ 0 ↔ a = 0 :=
iff.intro
(assume h, let ⟨u, h⟩ := h.symm in by simpa using h.symm)
(assume h, h ▸ associated.refl a)
theorem associated_one_of_mul_eq_one [comm_monoid α] {a : α} (b : α) (hab : a * b = 1) : a ~ᵤ 1 :=
show (units.mk_of_mul_eq_one a b hab : α) ~ᵤ 1, from unit_associated_one
theorem associated_one_of_associated_mul_one [comm_monoid α] {a b : α} :
a * b ~ᵤ 1 → a ~ᵤ 1
| ⟨u, h⟩ := associated_one_of_mul_eq_one (b * u) $ by simpa [mul_assoc] using h
lemma associated_mul_mul [comm_monoid α] {a₁ a₂ b₁ b₂ : α} :
a₁ ~ᵤ b₁ → a₂ ~ᵤ b₂ → (a₁ * a₂) ~ᵤ (b₁ * b₂)
| ⟨c₁, h₁⟩ ⟨c₂, h₂⟩ := ⟨c₁ * c₂, by simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm]⟩
lemma dvd_of_associated [monoid α] {a b : α} : a ~ᵤ b → a ∣ b := λ ⟨u, hu⟩, ⟨u, hu.symm⟩
lemma dvd_dvd_of_associated [monoid α] {a b : α} (h : a ~ᵤ b) : a ∣ b ∧ b ∣ a :=
⟨dvd_of_associated h, dvd_of_associated h.symm⟩
theorem associated_of_dvd_dvd [cancel_monoid_with_zero α]
{a b : α} (hab : a ∣ b) (hba : b ∣ a) : a ~ᵤ b :=
begin
rcases hab with ⟨c, rfl⟩,
rcases hba with ⟨d, a_eq⟩,
by_cases ha0 : a = 0,
{ simp [*] at * },
have hac0 : a * c ≠ 0,
{ intro con, rw [con, zero_mul] at a_eq, apply ha0 a_eq, },
have : a * (c * d) = a * 1 := by rw [← mul_assoc, ← a_eq, mul_one],
have hcd : (c * d) = 1, from mul_left_cancel' ha0 this,
have : a * c * (d * c) = a * c * 1 := by rw [← mul_assoc, ← a_eq, mul_one],
have hdc : d * c = 1, from mul_left_cancel' hac0 this,
exact ⟨⟨c, d, hcd, hdc⟩, rfl⟩
end
theorem dvd_dvd_iff_associated [cancel_monoid_with_zero α] {a b : α} : a ∣ b ∧ b ∣ a ↔ a ~ᵤ b :=
⟨λ ⟨h1, h2⟩, associated_of_dvd_dvd h1 h2, dvd_dvd_of_associated⟩
lemma exists_associated_mem_of_dvd_prod [comm_cancel_monoid_with_zero α] {p : α}
(hp : prime p) {s : multiset α} : (∀ r ∈ s, prime r) → p ∣ s.prod → ∃ q ∈ s, p ~ᵤ q :=
multiset.induction_on s (by simp [mt is_unit_iff_dvd_one.2 hp.not_unit])
(λ a s ih hs hps, begin
rw [multiset.prod_cons] at hps,
cases hp.div_or_div hps with h h,
{ use [a, by simp],
cases h with u hu,
cases ((irreducible_of_prime (hs a (multiset.mem_cons.2
(or.inl rfl)))).2 p u hu).resolve_left hp.not_unit with v hv,
exact ⟨v, by simp [hu, hv]⟩ },
{ rcases ih (λ r hr, hs _ (multiset.mem_cons.2 (or.inr hr))) h with ⟨q, hq₁, hq₂⟩,
exact ⟨q, multiset.mem_cons.2 (or.inr hq₁), hq₂⟩ }
end)
lemma dvd_iff_dvd_of_rel_left [comm_monoid_with_zero α] {a b c : α} (h : a ~ᵤ b) : a ∣ c ↔ b ∣ c :=
let ⟨u, hu⟩ := h in hu ▸ units.mul_right_dvd.symm
lemma dvd_iff_dvd_of_rel_right [comm_monoid_with_zero α] {a b c : α} (h : b ~ᵤ c) : a ∣ b ↔ a ∣ c :=
let ⟨u, hu⟩ := h in hu ▸ units.dvd_mul_right.symm
lemma eq_zero_iff_of_associated [comm_monoid_with_zero α] {a b : α} (h : a ~ᵤ b) : a = 0 ↔ b = 0 :=
⟨λ ha, let ⟨u, hu⟩ := h in by simp [hu.symm, ha],
λ hb, let ⟨u, hu⟩ := h.symm in by simp [hu.symm, hb]⟩
lemma ne_zero_iff_of_associated [comm_monoid_with_zero α] {a b : α} (h : a ~ᵤ b) : a ≠ 0 ↔ b ≠ 0 :=
by haveI := classical.dec; exact not_iff_not.2 (eq_zero_iff_of_associated h)
lemma prime_of_associated [comm_monoid_with_zero α] {p q : α} (h : p ~ᵤ q) (hp : prime p) : prime q :=
⟨(ne_zero_iff_of_associated h).1 hp.ne_zero,
let ⟨u, hu⟩ := h in
⟨λ ⟨v, hv⟩, hp.not_unit ⟨v * u⁻¹, by simp [hv, hu.symm]⟩,
hu ▸ by { simp [units.mul_right_dvd], intros a b, exact hp.div_or_div }⟩⟩
lemma prime_iff_of_associated [comm_monoid_with_zero α] {p q : α}
(h : p ~ᵤ q) : prime p ↔ prime q :=
⟨prime_of_associated h, prime_of_associated h.symm⟩
lemma is_unit_iff_of_associated [monoid α] {a b : α} (h : a ~ᵤ b) : is_unit a ↔ is_unit b :=
⟨let ⟨u, hu⟩ := h in λ ⟨v, hv⟩, ⟨v * u, by simp [hv, hu.symm]⟩,
let ⟨u, hu⟩ := h.symm in λ ⟨v, hv⟩, ⟨v * u, by simp [hv, hu.symm]⟩⟩
lemma irreducible_of_associated [comm_monoid_with_zero α] {p q : α} (h : p ~ᵤ q)
(hp : irreducible p) : irreducible q :=
⟨mt (is_unit_iff_of_associated h).2 hp.1,
let ⟨u, hu⟩ := h in λ a b hab,
have hpab : p = a * (b * (u⁻¹ : units α)),
from calc p = (p * u) * (u ⁻¹ : units α) : by simp
... = _ : by rw hu; simp [hab, mul_assoc],
(hp.2 _ _ hpab).elim or.inl (λ ⟨v, hv⟩, or.inr ⟨v * u, by simp [hv]⟩)⟩
lemma irreducible_iff_of_associated [comm_monoid_with_zero α] {p q : α} (h : p ~ᵤ q) :
irreducible p ↔ irreducible q :=
⟨irreducible_of_associated h, irreducible_of_associated h.symm⟩
lemma associated_mul_left_cancel [comm_cancel_monoid_with_zero α] {a b c d : α}
(h : a * b ~ᵤ c * d) (h₁ : a ~ᵤ c) (ha : a ≠ 0) : b ~ᵤ d :=
let ⟨u, hu⟩ := h in let ⟨v, hv⟩ := associated.symm h₁ in
⟨u * (v : units α), mul_left_cancel' ha
begin
rw [← hv, mul_assoc c (v : α) d, mul_left_comm c, ← hu],
simp [hv.symm, mul_assoc, mul_comm, mul_left_comm]
end⟩
lemma associated_mul_right_cancel [comm_cancel_monoid_with_zero α] {a b c d : α} :
a * b ~ᵤ c * d → b ~ᵤ d → b ≠ 0 → a ~ᵤ c :=
by rw [mul_comm a, mul_comm c]; exact associated_mul_left_cancel
/-- The quotient of a monoid by the `associated` relation. Two elements `x` and `y`
are associated iff there is a unit `u` such that `x * u = y`. There is a natural
monoid structure on `associates α`. -/
def associates (α : Type*) [monoid α] : Type* :=
quotient (associated.setoid α)
namespace associates
open associated
/-- The canonical quotient map from a monoid `α` into the `associates` of `α` -/
protected def mk {α : Type*} [monoid α] (a : α) : associates α :=
⟦ a ⟧
instance [monoid α] : inhabited (associates α) := ⟨⟦1⟧⟩
theorem mk_eq_mk_iff_associated [monoid α] {a b : α} :
associates.mk a = associates.mk b ↔ a ~ᵤ b :=
iff.intro quotient.exact quot.sound
theorem quotient_mk_eq_mk [monoid α] (a : α) : ⟦ a ⟧ = associates.mk a := rfl
theorem quot_mk_eq_mk [monoid α] (a : α) : quot.mk setoid.r a = associates.mk a := rfl
theorem forall_associated [monoid α] {p : associates α → Prop} :
(∀a, p a) ↔ (∀a, p (associates.mk a)) :=
iff.intro
(assume h a, h _)
(assume h a, quotient.induction_on a h)
theorem mk_surjective [monoid α] : function.surjective (@associates.mk α _) :=
forall_associated.2 (λ a, ⟨a, rfl⟩)
instance [monoid α] : has_one (associates α) := ⟨⟦ 1 ⟧⟩
theorem one_eq_mk_one [monoid α] : (1 : associates α) = associates.mk 1 := rfl
instance [monoid α] : has_bot (associates α) := ⟨1⟩
lemma exists_rep [monoid α] (a : associates α) : ∃ a0 : α, associates.mk a0 = a :=
quot.exists_rep a
section comm_monoid
variable [comm_monoid α]
instance : has_mul (associates α) :=
⟨λa' b', quotient.lift_on₂ a' b' (λa b, ⟦ a * b ⟧) $
assume a₁ a₂ b₁ b₂ ⟨c₁, h₁⟩ ⟨c₂, h₂⟩,
quotient.sound $ ⟨c₁ * c₂, by simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm]⟩⟩
theorem mk_mul_mk {x y : α} : associates.mk x * associates.mk y = associates.mk (x * y) :=
rfl
instance : comm_monoid (associates α) :=
{ one := 1,
mul := (*),
mul_one := assume a', quotient.induction_on a' $
assume a, show ⟦a * 1⟧ = ⟦ a ⟧, by simp,
one_mul := assume a', quotient.induction_on a' $
assume a, show ⟦1 * a⟧ = ⟦ a ⟧, by simp,
mul_assoc := assume a' b' c', quotient.induction_on₃ a' b' c' $
assume a b c, show ⟦a * b * c⟧ = ⟦a * (b * c)⟧, by rw [mul_assoc],
mul_comm := assume a' b', quotient.induction_on₂ a' b' $
assume a b, show ⟦a * b⟧ = ⟦b * a⟧, by rw [mul_comm] }
instance : preorder (associates α) :=
{ le := has_dvd.dvd,
le_refl := dvd_refl,
le_trans := λ a b c, dvd_trans}
@[simp] lemma mk_one : associates.mk (1 : α) = 1 := rfl
lemma mk_pow (a : α) (n : ℕ) : associates.mk (a ^ n) = (associates.mk a) ^ n :=
by induction n; simp [*, pow_succ, associates.mk_mul_mk.symm]
lemma dvd_eq_le : ((∣) : associates α → associates α → Prop) = (≤) := rfl
theorem prod_mk {p : multiset α} : (p.map associates.mk).prod = associates.mk p.prod :=
multiset.induction_on p (by simp; refl) $ assume a s ih, by simp [ih]; refl
theorem rel_associated_iff_map_eq_map {p q : multiset α} :
multiset.rel associated p q ↔ p.map associates.mk = q.map associates.mk :=
by rw [← multiset.rel_eq];
simp [multiset.rel_map_left, multiset.rel_map_right, mk_eq_mk_iff_associated]
theorem mul_eq_one_iff {x y : associates α} : x * y = 1 ↔ (x = 1 ∧ y = 1) :=
iff.intro
(quotient.induction_on₂ x y $ assume a b h,
have a * b ~ᵤ 1, from quotient.exact h,
⟨quotient.sound $ associated_one_of_associated_mul_one this,
quotient.sound $ associated_one_of_associated_mul_one $ by rwa [mul_comm] at this⟩)
(by simp {contextual := tt})
theorem prod_eq_one_iff {p : multiset (associates α)} :
p.prod = 1 ↔ (∀a ∈ p, (a:associates α) = 1) :=
multiset.induction_on p
(by simp)
(by simp [mul_eq_one_iff, or_imp_distrib, forall_and_distrib] {contextual := tt})
theorem units_eq_one (u : units (associates α)) : u = 1 :=
units.ext (mul_eq_one_iff.1 u.val_inv).1
instance unique_units : unique (units (associates α)) :=
{ default := 1, uniq := associates.units_eq_one }
theorem coe_unit_eq_one (u : units (associates α)): (u : associates α) = 1 :=
by simp
theorem is_unit_iff_eq_one (a : associates α) : is_unit a ↔ a = 1 :=
iff.intro
(assume ⟨u, h⟩, h ▸ coe_unit_eq_one _)
(assume h, h.symm ▸ is_unit_one)
theorem is_unit_mk {a : α} : is_unit (associates.mk a) ↔ is_unit a :=
calc is_unit (associates.mk a) ↔ a ~ᵤ 1 :
by rw [is_unit_iff_eq_one, one_eq_mk_one, mk_eq_mk_iff_associated]
... ↔ is_unit a : associated_one_iff_is_unit
section order
theorem mul_mono {a b c d : associates α} (h₁ : a ≤ b) (h₂ : c ≤ d) :
a * c ≤ b * d :=
let ⟨x, hx⟩ := h₁, ⟨y, hy⟩ := h₂ in
⟨x * y, by simp [hx, hy, mul_comm, mul_assoc, mul_left_comm]⟩
theorem one_le {a : associates α} : 1 ≤ a :=
dvd.intro _ (one_mul a)
theorem prod_le_prod {p q : multiset (associates α)} (h : p ≤ q) : p.prod ≤ q.prod :=
begin
haveI := classical.dec_eq (associates α),
haveI := classical.dec_eq α,
suffices : p.prod ≤ (p + (q - p)).prod, { rwa [multiset.add_sub_of_le h] at this },
suffices : p.prod * 1 ≤ p.prod * (q - p).prod, { simpa },
exact mul_mono (le_refl p.prod) one_le
end
theorem le_mul_right {a b : associates α} : a ≤ a * b := ⟨b, rfl⟩
theorem le_mul_left {a b : associates α} : a ≤ b * a :=
by rw [mul_comm]; exact le_mul_right
end order
end comm_monoid
instance [has_zero α] [monoid α] : has_zero (associates α) := ⟨⟦ 0 ⟧⟩
instance [has_zero α] [monoid α] : has_top (associates α) := ⟨0⟩
section comm_monoid_with_zero
variables [comm_monoid_with_zero α]
@[simp] theorem mk_eq_zero {a : α} : associates.mk a = 0 ↔ a = 0 :=
⟨assume h, (associated_zero_iff_eq_zero a).1 $ quotient.exact h, assume h, h.symm ▸ rfl⟩
instance : comm_monoid_with_zero (associates α) :=
{ zero_mul := by { rintro ⟨a⟩, show associates.mk (0 * a) = associates.mk 0, rw [zero_mul] },
mul_zero := by { rintro ⟨a⟩, show associates.mk (a * 0) = associates.mk 0, rw [mul_zero] },
.. associates.comm_monoid, .. associates.has_zero }
instance [nontrivial α] : nontrivial (associates α) :=
⟨⟨0, 1,
assume h,
have (0 : α) ~ᵤ 1, from quotient.exact h,
have (0 : α) = 1, from ((associated_zero_iff_eq_zero 1).1 this.symm).symm,
zero_ne_one this⟩⟩
lemma exists_non_zero_rep {a : associates α} : a ≠ 0 → ∃ a0 : α, a0 ≠ 0 ∧ associates.mk a0 = a :=
quotient.induction_on a (λ b nz, ⟨b, mt (congr_arg quotient.mk) nz, rfl⟩)
theorem dvd_of_mk_le_mk {a b : α} : associates.mk a ≤ associates.mk b → a ∣ b
| ⟨c', hc'⟩ := (quotient.induction_on c' $ assume c hc,
let ⟨d, hd⟩ := (quotient.exact hc).symm in
⟨(↑d) * c,
calc b = (a * c) * ↑d : hd.symm
... = a * (↑d * c) : by ac_refl⟩) hc'
theorem mk_le_mk_of_dvd {a b : α} : a ∣ b → associates.mk a ≤ associates.mk b :=
assume ⟨c, hc⟩, ⟨associates.mk c, by simp [hc]; refl⟩
theorem mk_le_mk_iff_dvd_iff {a b : α} : associates.mk a ≤ associates.mk b ↔ a ∣ b :=
iff.intro dvd_of_mk_le_mk mk_le_mk_of_dvd
theorem mk_dvd_mk {a b : α} : associates.mk a ∣ associates.mk b ↔ a ∣ b :=
iff.intro dvd_of_mk_le_mk mk_le_mk_of_dvd
lemma prime.le_or_le {p : associates α} (hp : prime p) {a b : associates α} (h : p ≤ a * b) :
p ≤ a ∨ p ≤ b :=
hp.2.2 a b h
lemma exists_mem_multiset_le_of_prime {s : multiset (associates α)} {p : associates α}
(hp : prime p) :
p ≤ s.prod → ∃a∈s, p ≤ a :=
multiset.induction_on s (assume ⟨d, eq⟩, (hp.ne_one (mul_eq_one_iff.1 eq.symm).1).elim) $
assume a s ih h,
have p ≤ a * s.prod, by simpa using h,
match prime.le_or_le hp this with
| or.inl h := ⟨a, multiset.mem_cons_self a s, h⟩
| or.inr h := let ⟨a, has, h⟩ := ih h in ⟨a, multiset.mem_cons_of_mem has, h⟩
end
lemma prime_mk (p : α) : prime (associates.mk p) ↔ _root_.prime p :=
begin
rw [prime, _root_.prime, forall_associated],
transitivity,
{ apply and_congr, refl,
apply and_congr, refl,
apply forall_congr, assume a,
exact forall_associated },
apply and_congr,
{ rw [(≠), mk_eq_zero] },
apply and_congr,
{ rw [is_unit_mk], },
apply forall_congr, assume a,
apply forall_congr, assume b,
rw [mk_mul_mk, mk_dvd_mk, mk_dvd_mk, mk_dvd_mk],
end
theorem irreducible_mk (a : α) : irreducible (associates.mk a) ↔ irreducible a :=
begin
simp only [irreducible, is_unit_mk],
apply and_congr iff.rfl,
split,
{ rintro h x y rfl,
simpa [is_unit_mk] using h (associates.mk x) (associates.mk y) rfl },
{ intros h x y,
refine quotient.induction_on₂ x y (assume x y a_eq, _),
rcases quotient.exact a_eq.symm with ⟨u, a_eq⟩,
rw mul_assoc at a_eq,
show is_unit (associates.mk x) ∨ is_unit (associates.mk y),
simpa [is_unit_mk] using h _ _ a_eq.symm }
end
theorem mk_dvd_not_unit_mk_iff {a b : α} :
dvd_not_unit (associates.mk a) (associates.mk b) ↔
dvd_not_unit a b :=
begin
rw [dvd_not_unit, dvd_not_unit, ne, ne, mk_eq_zero],
apply and_congr_right, intro ane0,
split,
{ contrapose!, rw forall_associated,
intros h x hx hbax,
rw [mk_mul_mk, mk_eq_mk_iff_associated] at hbax,
cases hbax with u hu,
apply h (x * ↑u⁻¹),
{ rw is_unit_mk at hx,
rw is_unit_iff_of_associated,
apply hx,
use u,
simp, },
simp [← mul_assoc, ← hu] },
{ rintro ⟨x, ⟨hx, rfl⟩⟩,
use associates.mk x,
simp [is_unit_mk, mk_mul_mk, hx], }
end
theorem dvd_not_unit_of_lt {a b : associates α} (hlt : a < b) :
dvd_not_unit a b :=
begin
split, { rintro rfl, apply not_lt_of_le _ hlt, apply dvd_zero },
rcases hlt with ⟨⟨x, rfl⟩, ndvd⟩,
refine ⟨x, _, rfl⟩,
contrapose! ndvd,
rcases ndvd with ⟨u, rfl⟩,
simp,
end
end comm_monoid_with_zero
section comm_cancel_monoid_with_zero
variable [comm_cancel_monoid_with_zero α]
instance : partial_order (associates α) :=
{ le_antisymm := λ a' b', quotient.induction_on₂ a' b' (λ a b hab hba,
quot.sound $ associated_of_dvd_dvd (dvd_of_mk_le_mk hab) (dvd_of_mk_le_mk hba))
.. associates.preorder }
instance : order_bot (associates α) :=
{ bot := 1,
bot_le := assume a, one_le,
.. associates.partial_order }
instance : order_top (associates α) :=
{ top := 0,
le_top := assume a, ⟨0, (mul_zero a).symm⟩,
.. associates.partial_order }
instance : no_zero_divisors (associates α) :=
⟨λ x y,
(quotient.induction_on₂ x y $ assume a b h,
have a * b = 0, from (associated_zero_iff_eq_zero _).1 (quotient.exact h),
have a = 0 ∨ b = 0, from mul_eq_zero.1 this,
this.imp (assume h, h.symm ▸ rfl) (assume h, h.symm ▸ rfl))⟩
theorem irreducible_iff_prime_iff :
(∀ a : α, irreducible a ↔ prime a) ↔ (∀ a : (associates α), irreducible a ↔ prime a) :=
begin
rw forall_associated, split;
intros h a; have ha := h a; rw irreducible_mk at *; rw prime_mk at *; exact ha,
end
lemma eq_of_mul_eq_mul_left :
∀(a b c : associates α), a ≠ 0 → a * b = a * c → b = c :=
begin
rintros ⟨a⟩ ⟨b⟩ ⟨c⟩ ha h,
rcases quotient.exact' h with ⟨u, hu⟩,
have hu : a * (b * ↑u) = a * c, { rwa [← mul_assoc] },
exact quotient.sound' ⟨u, mul_left_cancel' (mt mk_eq_zero.2 ha) hu⟩
end
lemma eq_of_mul_eq_mul_right :
∀(a b c : associates α), b ≠ 0 → a * b = c * b → a = c :=
λ a b c bne0, (mul_comm b a) ▸ (mul_comm b c) ▸ (eq_of_mul_eq_mul_left b a c bne0)
lemma le_of_mul_le_mul_left (a b c : associates α) (ha : a ≠ 0) :
a * b ≤ a * c → b ≤ c
| ⟨d, hd⟩ := ⟨d, eq_of_mul_eq_mul_left a _ _ ha $ by rwa ← mul_assoc⟩
lemma one_or_eq_of_le_of_prime :
∀(p m : associates α), prime p → m ≤ p → (m = 1 ∨ m = p)
| _ m ⟨hp0, hp1, h⟩ ⟨d, rfl⟩ :=
match h m d (dvd_refl _) with
| or.inl h := classical.by_cases (assume : m = 0, by simp [this]) $
assume : m ≠ 0,
have m * d ≤ m * 1, by simpa using h,
have d ≤ 1, from associates.le_of_mul_le_mul_left m d 1 ‹m ≠ 0› this,
have d = 1, from bot_unique this,
by simp [this]
| or.inr h := classical.by_cases (assume : d = 0, by simp [this] at hp0; contradiction) $
assume : d ≠ 0,
have d * m ≤ d * 1, by simpa [mul_comm] using h,
or.inl $ bot_unique $ associates.le_of_mul_le_mul_left d m 1 ‹d ≠ 0› this
end
instance : comm_cancel_monoid_with_zero (associates α) :=
{ mul_left_cancel_of_ne_zero := eq_of_mul_eq_mul_left,
mul_right_cancel_of_ne_zero := eq_of_mul_eq_mul_right,
.. (infer_instance : comm_monoid_with_zero (associates α)) }
theorem dvd_not_unit_iff_lt {a b : associates α} :
dvd_not_unit a b ↔ a < b :=
dvd_and_not_dvd_iff.symm
end comm_cancel_monoid_with_zero
end associates
|
3a95901af2d6ac414318a9b26615b4826c5dd112 | 08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4 | /src/Lean/Compiler/LCNF/Main.lean | 8776e19cb8eb81cf458b520eafff54cdaf51c6e0 | [
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"Apache-2.0",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | gebner/lean4 | d51c4922640a52a6f7426536ea669ef18a1d9af5 | 8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f | refs/heads/master | 1,685,732,780,391 | 1,672,962,627,000 | 1,673,459,398,000 | 373,307,283 | 0 | 0 | Apache-2.0 | 1,691,316,730,000 | 1,622,669,271,000 | Lean | UTF-8 | Lean | false | false | 4,065 | lean | /-
Copyright (c) 2022 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Compiler.Options
import Lean.Compiler.LCNF.PassManager
import Lean.Compiler.LCNF.Passes
import Lean.Compiler.LCNF.PrettyPrinter
import Lean.Compiler.LCNF.ToDecl
import Lean.Compiler.LCNF.Check
import Lean.Compiler.LCNF.PullLetDecls
import Lean.Compiler.LCNF.PhaseExt
import Lean.Compiler.LCNF.CSE
namespace Lean.Compiler.LCNF
/--
We do not generate code for `declName` if
- Its type is a proposition.
- Its type is a type former.
- It is tagged as `[macro_inline]`.
- It is a type class instance.
Remark: we still generate code for declarations tagged as `[inline]`
and `[specialize]` since they can be partially applied.
-/
def shouldGenerateCode (declName : Name) : CoreM Bool := do
if (← isCompIrrelevant |>.run') then return false
let some info ← getDeclInfo? declName | return false
unless info.hasValue do return false
let env ← getEnv
if isExtern env declName then return false
if hasMacroInlineAttribute env declName then return false
if (← Meta.isMatcher declName) then return false
if isCasesOnRecursor env declName then return false
-- TODO: check if type class instance
return true
where
isCompIrrelevant : MetaM Bool := do
let info ← getConstInfo declName
Meta.isProp info.type <||> Meta.isTypeFormerType info.type
/--
A checkpoint in code generation to print all declarations in between
compiler passes in order to ease debugging.
The trace can be viewed with `set_option trace.Compiler.step true`.
-/
def checkpoint (stepName : Name) (decls : Array Decl) : CompilerM Unit := do
for decl in decls do
trace[Compiler.stat] "{decl.name} : {decl.size}"
withOptions (fun opts => opts.setBool `pp.motives.pi false) do
let clsName := `Compiler ++ stepName
if (← Lean.isTracingEnabledFor clsName) then
Lean.addTrace clsName m!"size: {decl.size}\n{← ppDecl' decl}"
if compiler.check.get (← getOptions) then
decl.check
if compiler.check.get (← getOptions) then
checkDeadLocalDecls decls
namespace PassManager
def run (declNames : Array Name) : CompilerM (Array Decl) := withAtLeastMaxRecDepth 8192 do
/-
Note: we need to increase the recursion depth because we currently do to save phase1
declarations in .olean files. Then, we have to recursively compile all dependencies,
and it often creates a very deep recursion.
Moreover, some declarations get very big during simplification.
-/
let declNames ← declNames.filterM (shouldGenerateCode ·)
if declNames.isEmpty then return #[]
let mut decls ← declNames.mapM toDecl
decls := markRecDecls decls
let manager ← getPassManager
for pass in manager.passes do
trace[Compiler] "Running pass: {pass.name}"
decls ← withPhase pass.phase <| pass.run decls
withPhase pass.phaseOut <| checkpoint pass.name decls
if (← Lean.isTracingEnabledFor `Compiler.result) then
for decl in decls do
-- We display the declaration saved in the environment because the names have been normalized
let some decl' ← getDeclAt? decl.name .mono | unreachable!
Lean.addTrace `Compiler.result m!"size: {decl.size}\n{← ppDecl' decl'}"
return decls
end PassManager
def compile (declNames : Array Name) : CoreM (Array Decl) :=
CompilerM.run <| PassManager.run declNames
def showDecl (phase : Phase) (declName : Name) : CoreM Format := do
let some decl ← getDeclAt? declName phase | return "<not-available>"
ppDecl' decl
@[export lean_lcnf_compile_decls]
def main (declNames : List Name) : CoreM Unit := do
profileitM Exception "compilation new" (← getOptions) do
CompilerM.run <| discard <| PassManager.run declNames.toArray
builtin_initialize
registerTraceClass `Compiler.init (inherited := true)
registerTraceClass `Compiler.test (inherited := true)
registerTraceClass `Compiler.result (inherited := true)
registerTraceClass `Compiler.jp
end Lean.Compiler.LCNF
|
ae2dee7c559a6273df538c1d9bd5cb97a6e6a95d | 947b78d97130d56365ae2ec264df196ce769371a | /src/Lean/CoreM.lean | bf9a64f6f58b017bd00b6982b4d7972c18ce734c | [
"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 | 4,068 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Util.RecDepth
import Lean.Util.Trace
import Lean.Environment
import Lean.Exception
import Lean.InternalExceptionId
import Lean.Eval
import Lean.MonadEnv
namespace Lean
namespace Core
structure State :=
(env : Environment)
(nextMacroScope : MacroScope := firstFrontendMacroScope + 1)
(ngen : NameGenerator := {})
(traceState : TraceState := {})
instance State.inhabited : Inhabited State := ⟨{ env := arbitrary _ }⟩
structure Context :=
(options : Options := {})
(currRecDepth : Nat := 0)
(maxRecDepth : Nat := 1000)
(ref : Syntax := Syntax.missing)
abbrev CoreM := ReaderT Context $ StateRefT State $ EIO Exception
instance CoreM.inhabited {α} : Inhabited (CoreM α) :=
⟨fun _ _ => throw $ arbitrary _⟩
instance : Ref CoreM :=
{ getRef := do ctx ← read; pure ctx.ref,
withRef := fun α ref x => adaptReader (fun (ctx : Context) => { ctx with ref := ref }) x }
instance : MonadEnv CoreM :=
{ getEnv := do s ← get; pure s.env,
modifyEnv := fun f => modify fun s => { s with env := f s.env } }
instance : MonadOptions CoreM :=
{ getOptions := do ctx ← read; pure ctx.options }
instance : AddMessageContext CoreM :=
{ addMessageContext := addMessageContextPartial }
instance : MonadNameGenerator CoreM :=
{ getNGen := do s ← get; pure s.ngen,
setNGen := fun ngen => modify fun s => { s with ngen := ngen } }
instance : MonadRecDepth CoreM :=
{ withRecDepth := fun α d x => adaptReader (fun (ctx : Context) => { ctx with currRecDepth := d }) x,
getRecDepth := do ctx ← read; pure ctx.currRecDepth,
getMaxRecDepth := do ctx ← read; pure ctx.maxRecDepth }
@[inline] def liftIOCore {α} (x : IO α) : CoreM α := do
ref ← getRef;
liftM $ (adaptExcept (fun (err : IO.Error) => Exception.error ref (toString err)) x : EIO Exception α)
instance : MonadIO CoreM :=
{ liftIO := @liftIOCore }
instance : MonadTrace CoreM :=
{ getTraceState := do s ← get; pure s.traceState,
modifyTraceState := fun f => modify $ fun s => { s with traceState := f s.traceState } }
private def mkFreshNameImp (n : Name) : CoreM Name := do
fresh ← modifyGet fun s => (s.nextMacroScope, { s with nextMacroScope := s.nextMacroScope + 1 });
env ← getEnv;
pure $ addMacroScope env.mainModule n fresh
def mkFreshUserName {m} [MonadLiftT CoreM m] (n : Name) : m Name :=
liftM $ mkFreshNameImp n
@[inline] def CoreM.run {α} (x : CoreM α) (ctx : Context) (s : State) : EIO Exception (α × State) :=
(x.run ctx).run s
@[inline] def CoreM.run' {α} (x : CoreM α) (ctx : Context) (s : State) : EIO Exception α :=
Prod.fst <$> x.run ctx s
@[inline] def CoreM.toIO {α} (x : CoreM α) (ctx : Context) (s : State) : IO (α × State) := do
e ← (x.run ctx s).toIO';
match e with
| Except.error (Exception.error _ msg) => do e ← msg.toString; throw $ IO.userError e
| Except.error (Exception.internal id) => throw $ IO.userError $ "internal exception #" ++ toString id.idx
| Except.ok a => pure a
instance hasEval {α} [MetaHasEval α] : MetaHasEval (CoreM α) :=
⟨fun env opts x _ => do
(a, s) ← (finally x printTraces).toIO { maxRecDepth := getMaxRecDepth opts, options := opts } { env := env};
MetaHasEval.eval s.env opts a⟩
end Core
export Core (CoreM mkFreshUserName)
@[inline] def catchInternalId {α} {m : Type → Type} [MonadExcept Exception m] (id : InternalExceptionId) (x : m α) (h : Exception → m α) : m α :=
catch x fun ex => match ex with
| Exception.error _ _ => throw ex
| Exception.internal id' => if id == id' then h ex else throw ex
@[inline] def catchInternalIds {α} {m : Type → Type} [MonadExcept Exception m] (ids : List InternalExceptionId) (x : m α) (h : Exception → m α) : m α :=
catch x fun ex => match ex with
| Exception.error _ _ => throw ex
| Exception.internal id => if ids.contains id then h ex else throw ex
end Lean
|
c73c13ab218e3a255d14aff12d6952e2563402a0 | 3dd1b66af77106badae6edb1c4dea91a146ead30 | /tests/lean/run/nat_bug3.lean | 261c8b69e09d9504f05edbfa559b0f31b2a67c84 | [
"Apache-2.0"
] | permissive | silky/lean | 79c20c15c93feef47bb659a2cc139b26f3614642 | df8b88dca2f8da1a422cb618cd476ef5be730546 | refs/heads/master | 1,610,737,587,697 | 1,406,574,534,000 | 1,406,574,534,000 | 22,362,176 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 699 | lean | import logic num
using num eq_proofs
inductive nat : Type :=
| zero : nat
| succ : nat → nat
abbreviation plus (x y : nat) : nat
:= nat_rec x (λn r, succ r) y
definition to_nat [coercion] [inline] (n : num) : nat
:= num_rec zero (λn, pos_num_rec (succ zero) (λn r, plus r (plus r (succ zero))) (λn r, plus r r) n) n
definition add (x y : nat) : nat
:= plus x y
variable le : nat → nat → Prop
infixl `+`:65 := add
infix `≤`:50 := le
axiom add_one (n:nat) : n + (succ zero) = succ n
axiom add_le_right_inv {n m k : nat} (H : n + k ≤ m + k) : n ≤ m
theorem succ_le_cancel {n m : nat} (H : succ n ≤ succ m) : n ≤ m
:= add_le_right_inv (add_one m⁻¹ ▸ add_one n⁻¹ ▸ H)
|
86d95ece70e1bc9f918e8764c4c2de3475a3bb63 | ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5 | /tests/bench/rbmap.lean | d0fdb26f3401d176ec418d15342958270339082d | [
"Apache-2.0"
] | permissive | dupuisf/lean4 | d082d13b01243e1de29ae680eefb476961221eef | 6a39c65bd28eb0e28c3870188f348c8914502718 | refs/heads/master | 1,676,948,755,391 | 1,610,665,114,000 | 1,610,665,114,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,916 | lean | #lang lean4
/-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Data.Option.Basic
import Init.Data.List.BasicAux
import Init.Data.String
import Init.System.IO
universes u v w w'
inductive color
| Red | Black
inductive Tree
| Leaf {} : Tree
| Node (color : color) (lchild : Tree) (key : Nat) (val : Bool) (rchild : Tree) : Tree
variables {σ : Type w}
open color Nat Tree
def fold (f : Nat → Bool → σ → σ) : Tree → σ → σ
| Leaf, b => b
| Node _ l k v r, b => fold f r (f k v (fold f l b))
@[inline]
def balance1 : Nat → Bool → Tree → Tree → Tree
| kv, vv, t, Node _ (Node Red l kx vx r₁) ky vy r₂ => Node Red (Node Black l kx vx r₁) ky vy (Node Black r₂ kv vv t)
| kv, vv, t, Node _ l₁ ky vy (Node Red l₂ kx vx r) => Node Red (Node Black l₁ ky vy l₂) kx vx (Node Black r kv vv t)
| kv, vv, t, Node _ l ky vy r => Node Black (Node Red l ky vy r) kv vv t
| _, _, _, _ => Leaf
@[inline]
def balance2 : Tree → Nat → Bool → Tree → Tree
| t, kv, vv, Node _ (Node Red l kx₁ vx₁ r₁) ky vy r₂ => Node Red (Node Black t kv vv l) kx₁ vx₁ (Node Black r₁ ky vy r₂)
| t, kv, vv, Node _ l₁ ky vy (Node Red l₂ kx₂ vx₂ r₂) => Node Red (Node Black t kv vv l₁) ky vy (Node Black l₂ kx₂ vx₂ r₂)
| t, kv, vv, Node _ l ky vy r => Node Black t kv vv (Node Red l ky vy r)
| _, _, _, _ => Leaf
def isRed : Tree → Bool
| Node Red _ _ _ _ => true
| _ => false
def ins : Tree → Nat → Bool → Tree
| Leaf, kx, vx => Node Red Leaf kx vx Leaf
| Node Red a ky vy b, kx, vx =>
(if kx < ky then Node Red (ins a kx vx) ky vy b
else if kx = ky then Node Red a kx vx b
else Node Red a ky vy (ins b kx vx))
| Node Black a ky vy b, kx, vx =>
if kx < ky then
(if isRed a then balance1 ky vy b (ins a kx vx)
else Node Black (ins a kx vx) ky vy b)
else if kx = ky then Node Black a kx vx b
else if isRed b then balance2 a ky vy (ins b kx vx)
else Node Black a ky vy (ins b kx vx)
def setBlack : Tree → Tree
| Node _ l k v r => Node Black l k v r
| e => e
def insert (t : Tree) (k : Nat) (v : Bool) : Tree :=
if isRed t then setBlack (ins t k v)
else ins t k v
def mkMapAux : Nat → Tree → Tree
| 0, m => m
| n+1, m => mkMapAux n (insert m n (n % 10 = 0))
def mkMap (n : Nat) :=
mkMapAux n Leaf
def main (xs : List String) : IO UInt32 :=
let m := mkMap xs.head!.toNat!;
let v := fold (fun (k : Nat) (v : Bool) (r : Nat) => if v then r + 1 else r) m 0;
IO.println (toString v) *>
pure 0
|
33bd2dabd697d70d24f9ae79749a9a516ca00ff9 | b9d8165d695e844c92d9d4cdcac7b5ab9efe09f7 | /src/topology/basic.lean | 28085f2d268d32fa37f7950f0a06c5a205432b0e | [
"Apache-2.0"
] | permissive | spapinistarkware/mathlib | e917d9c44bf85ef51db18e7a11615959f714efc5 | 0a9a1ff463a1f26e27d7c391eb7f6334f0d90383 | refs/heads/master | 1,606,808,129,547 | 1,577,478,369,000 | 1,577,478,369,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 34,492 | 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, Jeremy Avigad
-/
import order.filter
/-!
# Basic theory of topological spaces.
The main definition is the type class `topological space α` which endows a type `α` with a topology.
Then `set α` gets predicates `is_open`, `is_closed` and functions `interior`, `closure` and
`frontier`. Each point `x` of `α` gets a neighborhood filter `𝓝 x`.
This file also defines locally finite families of subsets of `α`.
For topological spaces `α` and `β`, a function `f : α → β` and a point `a : α`,
`continuous_at f a` means `f` is continuous at `a`, and global continuity is
`continuous f`. There is also a version of continuity `pcontinuous` for
partially defined functions.
## Implementation notes
Topology in mathlib heavily uses filters (even more than in Bourbaki). See explanations in
`docs/theories/topology.md`.
## References
* [N. Bourbaki, *General Topology*][bourbaki1966]
* [I. M. James, *Topologies and Uniformities*][james1999]
## Tags
topological space, interior, closure, frontier, neighborhood, continuity, continuous function
-/
open set filter lattice classical
open_locale classical
universes u v w
/-- A topology on `α`. -/
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 : α} {s s₁ s₂ : set α} {p p₁ p₂ : α → Prop}
@[ext]
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_Inter [fintype β] {s : β → set α}
(h : ∀ i, is_open (s i)) : is_open (⋂ i, s i) :=
suffices is_open (⋂ (i : β) (hi : i ∈ @univ β), s i), by simpa,
is_open_bInter finite_univ (λ i _, h i)
lemma is_open_Inter_prop {p : Prop} {s : p → set α}
(h : ∀ h : p, is_open (s h)) : is_open (Inter s) :=
by by_cases p; simp *
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 : f i = t)⟩, heq ▸ 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_bUnion {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_Union [fintype β] {s : β → set α}
(h : ∀ i, is_closed (s i)) : is_closed (Union s) :=
suffices is_closed (⋃ (i : β) (hi : i ∈ @univ β), s i),
by convert this; simp [set.ext_iff],
is_closed_bUnion finite_univ (λ i _, h i)
lemma is_closed_Union_prop {p : Prop} {s : p → set α}
(h : ∀ h : p, is_closed (s h)) : is_closed (Union s) :=
by by_cases p; simp *
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
lemma monotone_closure (α : Type*) [topological_space α] : monotone (@closure α _) :=
λ _ _, closure_mono
lemma closure_inter_subset_inter_closure (s t : set α) :
closure (s ∩ t) ⊆ closure s ∩ closure t :=
(monotone_closure α).map_inf_le s t
lemma is_closed_of_closure_subset {s : set α} (h : closure s ⊆ s) : is_closed s :=
by rw subset.antisymm subset_closure h; exact 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)
((monotone_closure α).le_map_sup s t)
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
lemma dense_of_subset_dense {s₁ s₂ : set α} (h : s₁ ⊆ s₂) (hd : closure s₁ = univ) :
closure s₂ = univ :=
by { rw [← univ_subset_iff, ← hd], exact closure_mono h }
/-- 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]
/-- The complement of a set has the same frontier as the original set. -/
@[simp] lemma frontier_compl (s : set α) : frontier (-s) = frontier s :=
by simp only [frontier_eq_closure_inter_closure, lattice.neg_neg, inter_comm]
lemma frontier_inter_subset (s t : set α) :
frontier (s ∩ t) ⊆ (frontier s ∩ closure t) ∪ (closure s ∩ frontier t) :=
begin
simp only [frontier_eq_closure_inter_closure, compl_inter, closure_union],
convert inter_subset_inter_left _ (closure_inter_subset_inter_closure s t),
simp only [inter_distrib_left, inter_distrib_right, inter_assoc],
congr' 2,
apply inter_comm
end
lemma frontier_union_subset (s t : set α) :
frontier (s ∪ t) ⊆ (frontier s ∩ closure (-t)) ∪ (closure (-s) ∩ frontier t) :=
by simpa only [frontier_compl, (compl_union _ _).symm]
using frontier_inter_subset (-s) (-t)
lemma is_closed.frontier_eq {s : set α} (hs : is_closed s) : frontier s = s \ interior s :=
by rw [frontier, closure_eq_of_is_closed hs]
lemma is_open.frontier_eq {s : set α} (hs : is_open s) : frontier s = closure s \ s :=
by rw [frontier, interior_eq_of_open hs]
/-- The frontier of a set is closed. -/
lemma is_closed_frontier {s : set α} : is_closed (frontier s) :=
by rw frontier_eq_closure_inter_closure; exact is_closed_inter is_closed_closure is_closed_closure
/-- The frontier of a set has no interior point. -/
lemma interior_frontier {s : set α} (h : is_closed s) : interior (frontier s) = ∅ :=
begin
have A : frontier s = s \ interior s, from h.frontier_eq,
have B : interior (frontier s) ⊆ interior s, by rw A; exact interior_mono (diff_subset _ _),
have C : interior (frontier s) ⊆ frontier s := interior_subset,
have : interior (frontier s) ⊆ (interior s) ∩ (s \ interior s) :=
subset_inter B (by simpa [A] using C),
rwa [inter_diff_self, subset_empty_iff] at this,
end
/-- neighbourhood filter -/
def nhds (a : α) : filter α := (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, principal s)
localized "notation `𝓝` := nhds" in topological_space
lemma nhds_def (a : α) : 𝓝 a = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, principal s) := rfl
lemma le_nhds_iff {f a} : f ≤ 𝓝 a ↔ ∀ s : set α, a ∈ s → is_open s → s ∈ f :=
by simp [nhds_def]
lemma nhds_le_of_le {f a} {s : set α} (h : a ∈ s) (o : is_open s) (sf : principal s ≤ f) : 𝓝 a ≤ f :=
by rw nhds_def; exact infi_le_of_le s (infi_le_of_le ⟨h, o⟩ sf)
lemma nhds_sets {a : α} : (𝓝 a).sets = {s | ∃t⊆s, is_open t ∧ a ∈ t} :=
calc (𝓝 a).sets = (⋃s∈{s : set α| a ∈ s ∧ is_open s}, (principal s).sets) : binfi_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 (𝓝 a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, principal (image f s)) :=
calc map f (𝓝 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]
attribute [irreducible] nhds
lemma mem_nhds_sets_iff {a : α} {s : set α} :
s ∈ 𝓝 a ↔ ∃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 ∈ 𝓝 a → 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 ∈ 𝓝 a :=
mem_nhds_sets_iff.2 ⟨s, subset.refl _, hs, ha⟩
theorem all_mem_nhds (x : α) (P : set α → Prop) (hP : ∀ s t, s ⊆ t → P s → P t) :
(∀ s ∈ 𝓝 x, P s) ↔ (∀ s, is_open s → x ∈ s → P s) :=
iff.intro
(λ h s os xs, h s (mem_nhds_sets os xs))
(λ h t,
begin
change t ∈ (𝓝 x).sets → P t,
rw nhds_sets,
rintros ⟨s, hs, opens, xs⟩,
exact hP _ _ hs (h s opens xs),
end)
theorem all_mem_nhds_filter (x : α) (f : set α → set β) (hf : ∀ s t, s ⊆ t → f s ⊆ f t)
(l : filter β) :
(∀ s ∈ 𝓝 x, f s ∈ l) ↔ (∀ s, is_open s → x ∈ s → f s ∈ l) :=
all_mem_nhds _ _ (λ s t ssubt h, mem_sets_of_superset h (hf s t ssubt))
theorem rtendsto_nhds {r : rel β α} {l : filter β} {a : α} :
rtendsto r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.core s ∈ l) :=
all_mem_nhds_filter _ _ (λ s t, id) _
theorem rtendsto'_nhds {r : rel β α} {l : filter β} {a : α} :
rtendsto' r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.preimage s ∈ l) :=
by { rw [rtendsto'_def], apply all_mem_nhds_filter, apply rel.preimage_mono }
theorem ptendsto_nhds {f : β →. α} {l : filter β} {a : α} :
ptendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.core s ∈ l) :=
rtendsto_nhds
theorem ptendsto'_nhds {f : β →. α} {l : filter β} {a : α} :
ptendsto' f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.preimage s ∈ l) :=
rtendsto'_nhds
theorem tendsto_nhds {f : β → α} {l : filter β} {a : α} :
tendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f ⁻¹' s ∈ l) :=
all_mem_nhds_filter _ _ (λ s t h, preimage_mono h) _
lemma tendsto_const_nhds {a : α} {f : filter β} : tendsto (λb:β, a) f (𝓝 a) :=
tendsto_nhds.mpr $ assume s hs ha, univ_mem_sets' $ assume _, ha
lemma pure_le_nhds : pure ≤ (𝓝 : α → filter α) :=
assume a, by rw nhds_def; exact le_infi
(assume s, le_infi $ assume ⟨h₁, _⟩, principal_mono.mpr $
singleton_subset_iff.2 h₁)
lemma tendsto_pure_nhds {α : Type*} [topological_space β] (f : α → β) (a : α) :
tendsto f (pure a) (𝓝 (f a)) :=
begin
rw [tendsto, filter.map_pure],
exact pure_le_nhds (f a)
end
@[simp] lemma nhds_neq_bot {a : α} : 𝓝 a ≠ ⊥ :=
assume : 𝓝 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 | 𝓝 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 ∈ 𝓝 a :=
by simp only [interior_eq_nhds, le_principal_iff]; refl
lemma is_open_iff_nhds {s : set α} : is_open s ↔ ∀a∈s, 𝓝 a ≤ principal s :=
calc is_open s ↔ s ⊆ interior s : subset_interior_iff_open.symm
... ↔ (∀a∈s, 𝓝 a ≤ principal s) : by rw [interior_eq_nhds]; refl
lemma is_open_iff_mem_nhds {s : set α} : is_open s ↔ ∀a∈s, s ∈ 𝓝 a :=
is_open_iff_nhds.trans $ forall_congr $ λ _, imp_congr_right $ λ _, le_principal_iff
lemma closure_eq_nhds {s : set α} : closure s = {a | 𝓝 a ⊓ principal s ≠ ⊥} :=
calc closure s = - interior (- s) : closure_eq_compl_interior_compl
... = {a | ¬ 𝓝 a ≤ principal (-s)} : by rw [interior_eq_nhds]; refl
... = {a | 𝓝 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 ∈ 𝓝 a, 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 ∧ u.val ≤ 𝓝 x :=
begin
rw closure_eq_nhds, change 𝓝 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, 𝓝 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, 𝓝 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 ∈ 𝓝 a, from mem_nhds_sets h hs,
have 𝓝 a ⊓ principal s = 𝓝 a, from inf_of_le_left $ by rwa le_principal_iff,
have 𝓝 a ⊓ principal (s ∩ t) ≠ ⊥,
from calc 𝓝 a ⊓ principal (s ∩ t) = 𝓝 a ⊓ (principal s ⊓ principal t) : by rw inf_principal
... = 𝓝 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 (𝓝 a)) (hs : is_closed s) (h : f ⁻¹' s ∈ b) : a ∈ s :=
have b.map f ≤ 𝓝 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_of_closed_of_tendsto' {f : β → α} {x : filter β} {a : α} {s : set α}
(hf : tendsto f x (𝓝 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)
lemma mem_closure_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α}
(hb : b ≠ ⊥) (hf : tendsto f b (𝓝 a)) (h : f ⁻¹' s ∈ b) : a ∈ closure s :=
mem_of_closed_of_tendsto hb hf (is_closed_closure) $
filter.mem_sets_of_superset h (preimage_mono subset_closure)
section lim
variables [inhabited α]
/-- 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 ≤ 𝓝 a
lemma lim_spec {f : filter α} (h : ∃a, f ≤ 𝓝 a) : f ≤ 𝓝 (lim f) := epsilon_spec h
end lim
/- 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 ∈ 𝓝 x, 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 ∈ (𝓝 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 𝓝 a ≤ principal (t ∩ (⋂ i∈{i | f i ∩ t ≠ ∅ }, - f i)) :
begin
rw [le_principal_iff],
apply @filter.inter_mem_sets _ (𝓝 a) _ _ h_sets,
apply @filter.Inter_mem_sets _ (𝓝 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
end topological_space
section continuous
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
variables [topological_space α] [topological_space β] [topological_space γ]
open_locale topological_space
/-- A function between topological spaces is continuous if the preimage
of every open set is open. -/
def continuous (f : α → β) := ∀s, is_open s → is_open (f ⁻¹' s)
/-- A function between topological spaces is continuous at a point `x₀`
if `f x` tends to `f x₀` when `x` tends to `x₀`. -/
def continuous_at (f : α → β) (x : α) := tendsto f (𝓝 x) (𝓝 (f x))
lemma continuous_at.preimage_mem_nhds {f : α → β} {x : α} {t : set β} (h : continuous_at f x)
(ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ 𝓝 x :=
h ht
lemma continuous_id : continuous (id : α → α) :=
assume s h, h
lemma continuous.comp {g : β → γ} {f : α → β} (hg : continuous g) (hf : continuous f) :
continuous (g ∘ f) :=
assume s h, hf _ (hg s h)
lemma continuous_at.comp {g : β → γ} {f : α → β} {x : α}
(hg : continuous_at g (f x)) (hf : continuous_at f x) :
continuous_at (g ∘ f) x :=
hg.comp hf
lemma continuous.tendsto {f : α → β} (hf : continuous f) (x) :
tendsto f (𝓝 x) (𝓝 (f x)) | s :=
show s ∈ 𝓝 (f x) → s ∈ map f (𝓝 x),
by simp [nhds_sets]; exact
assume t t_subset t_open fx_in_t,
⟨f ⁻¹' t, preimage_mono t_subset, hf t t_open, fx_in_t⟩
lemma continuous.continuous_at {f : α → β} {x : α} (h : continuous f) :
continuous_at f x :=
h.tendsto x
lemma continuous_iff_continuous_at {f : α → β} : continuous f ↔ ∀ x, continuous_at f x :=
⟨continuous.tendsto,
assume hf : ∀x, tendsto f (𝓝 x) (𝓝 (f x)),
assume s, assume hs : is_open s,
have ∀a, f a ∈ s → s ∈ 𝓝 (f a),
by simp [nhds_sets]; exact assume a ha, ⟨s, subset.refl s, hs, ha⟩,
show is_open (f ⁻¹' s),
by simp [is_open_iff_nhds]; exact assume a ha, hf a (this a ha)⟩
lemma continuous_const {b : β} : continuous (λa:α, b) :=
continuous_iff_continuous_at.mpr $ assume a, tendsto_const_nhds
lemma continuous_iff_is_closed {f : α → β} :
continuous f ↔ (∀s, is_closed s → is_closed (f ⁻¹' s)) :=
⟨assume hf s hs, hf (-s) hs,
assume hf s, by rw [←is_closed_compl_iff, ←is_closed_compl_iff]; exact hf _⟩
lemma continuous_at_iff_ultrafilter {f : α → β} (x) : continuous_at f x ↔
∀ g, is_ultrafilter g → g ≤ 𝓝 x → g.map f ≤ 𝓝 (f x) :=
tendsto_iff_ultrafilter f (𝓝 x) (𝓝 (f x))
lemma continuous_iff_ultrafilter {f : α → β} :
continuous f ↔ ∀ x g, is_ultrafilter g → g ≤ 𝓝 x → g.map f ≤ 𝓝 (f x) :=
by simp only [continuous_iff_continuous_at, continuous_at_iff_ultrafilter]
/-- A piecewise defined function `if p then f else g` is continuous, if both `f` and `g`
are continuous, and they coincide on the frontier (boundary) of the set `{a | p a}`. -/
lemma continuous_if {p : α → Prop} {f g : α → β} {h : ∀a, decidable (p a)}
(hp : ∀a∈frontier {a | p a}, f a = g a) (hf : continuous f) (hg : continuous g) :
continuous (λa, @ite (p a) (h a) β (f a) (g a)) :=
continuous_iff_is_closed.mpr $
assume s hs,
have (λa, ite (p a) (f a) (g a)) ⁻¹' s =
(closure {a | p a} ∩ f ⁻¹' s) ∪ (closure {a | ¬ p a} ∩ g ⁻¹' s),
from set.ext $ assume a,
classical.by_cases
(assume : a ∈ frontier {a | p a},
have hac : a ∈ closure {a | p a}, from this.left,
have hai : a ∈ closure {a | ¬ p a},
from have a ∈ - interior {a | p a}, from this.right, by rwa [←closure_compl] at this,
by by_cases p a; simp [h, hp a this, hac, hai, iff_def] {contextual := tt})
(assume hf : a ∈ - frontier {a | p a},
classical.by_cases
(assume : p a,
have hc : a ∈ closure {a | p a}, from subset_closure this,
have hnc : a ∉ closure {a | ¬ p a},
by show a ∉ closure (- {a | p a}); rw [closure_compl]; simpa [frontier, hc] using hf,
by simp [this, hc, hnc])
(assume : ¬ p a,
have hc : a ∈ closure {a | ¬ p a}, from subset_closure this,
have hnc : a ∉ closure {a | p a},
begin
have hc : a ∈ closure (- {a | p a}), from hc,
simp [closure_compl] at hc,
simpa [frontier, hc] using hf
end,
by simp [this, hc, hnc])),
by rw [this]; exact is_closed_union
(is_closed_inter is_closed_closure $ continuous_iff_is_closed.mp hf s hs)
(is_closed_inter is_closed_closure $ continuous_iff_is_closed.mp hg s hs)
/- Continuity and partial functions -/
/-- Continuity of a partial function -/
def pcontinuous (f : α →. β) := ∀ s, is_open s → is_open (f.preimage s)
lemma open_dom_of_pcontinuous {f : α →. β} (h : pcontinuous f) : is_open f.dom :=
by rw [←pfun.preimage_univ]; exact h _ is_open_univ
lemma pcontinuous_iff' {f : α →. β} :
pcontinuous f ↔ ∀ {x y} (h : y ∈ f x), ptendsto' f (𝓝 x) (𝓝 y) :=
begin
split,
{ intros h x y h',
rw [ptendsto'_def],
change ∀ (s : set β), s ∈ (𝓝 y).sets → pfun.preimage f s ∈ (𝓝 x).sets,
rw [nhds_sets, nhds_sets],
rintros s ⟨t, tsubs, opent, yt⟩,
exact ⟨f.preimage t, pfun.preimage_mono _ tsubs, h _ opent, ⟨y, yt, h'⟩⟩
},
intros hf s os,
rw is_open_iff_nhds,
rintros x ⟨y, ys, fxy⟩ t,
rw [mem_principal_sets],
assume h : f.preimage s ⊆ t,
change t ∈ 𝓝 x,
apply mem_sets_of_superset _ h,
have h' : ∀ s ∈ 𝓝 y, f.preimage s ∈ 𝓝 x,
{ intros s hs,
have : ptendsto' f (𝓝 x) (𝓝 y) := hf fxy,
rw ptendsto'_def at this,
exact this s hs },
show f.preimage s ∈ 𝓝 x,
apply h', rw mem_nhds_sets_iff, exact ⟨s, set.subset.refl _, os, ys⟩
end
lemma image_closure_subset_closure_image {f : α → β} {s : set α} (h : continuous f) :
f '' closure s ⊆ closure (f '' s) :=
have ∀ (a : α), 𝓝 a ⊓ principal s ≠ ⊥ → 𝓝 (f a) ⊓ principal (f '' s) ≠ ⊥,
from assume a ha,
have h₁ : ¬ map f (𝓝 a ⊓ principal s) = ⊥,
by rwa[map_eq_bot_iff],
have h₂ : map f (𝓝 a ⊓ principal s) ≤ 𝓝 (f a) ⊓ principal (f '' s),
from le_inf
(le_trans (map_mono inf_le_left) $ by rw [continuous_iff_continuous_at] at h; exact h a)
(le_trans (map_mono inf_le_right) $ by simp; exact subset.refl _),
neq_bot_of_le_neq_bot h₁ h₂,
by simp [image_subset_iff, closure_eq_nhds]; assumption
lemma mem_closure {s : set α} {t : set β} {f : α → β} {a : α}
(hf : continuous f) (ha : a ∈ closure s) (ht : ∀a∈s, f a ∈ t) : f a ∈ closure t :=
subset.trans (image_closure_subset_closure_image hf) (closure_mono $ image_subset_iff.2 ht) $
(mem_image_of_mem f ha)
end continuous
|
8d0afc22002489b06c13fbadc9b9ea02d12dfdb9 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /tmp/new-frontend/parser/token.lean | c1dc4042600736a5c9bb48bb9e0ef86fa427913d | [
"Apache-2.0"
] | permissive | mhuisi/lean4 | 28d35a4febc2e251c7f05492e13f3b05d6f9b7af | dda44bc47f3e5d024508060dac2bcb59fd12e4c0 | refs/heads/master | 1,621,225,489,283 | 1,585,142,689,000 | 1,585,142,689,000 | 250,590,438 | 0 | 2 | Apache-2.0 | 1,602,443,220,000 | 1,585,327,814,000 | C | UTF-8 | Lean | false | false | 13,744 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Sebastian Ullrich
Tokenizer for the Lean language
Even though our Parser architecture does not statically depend on a tokenizer but works directly on
the input String, we still use a "tokenizer" Parser in the Lean Parser in some circumstances:
* to distinguish between identifiers and keywords
* for error recovery: advance until next command token
* ...?
-/
prelude
import init.lean.parser.combinators init.lean.parser.stringliteral
namespace Lean
namespace Parser
open MonadParsec Combinators String HasView
def matchToken : BasicParserM (Option TokenConfig) :=
do cfg ← read,
it ← leftOver,
pure $ Prod.snd <$> cfg.tokens.oldMatchPrefix it
private def finishCommentBlockAux : Nat → Nat → BasicParserM Unit
| nesting (n+1) :=
str "/-" *> finishCommentBlockAux (nesting + 1) n
<|>
str "-/" *> (if nesting = 1 then pure () else finishCommentBlockAux (nesting - 1) n)
<|>
any *> finishCommentBlockAux nesting n
| _ _ := error "unreachable"
def finishCommentBlock (nesting := 1) : BasicParserM Unit :=
do r ← remaining,
finishCommentBlockAux nesting (r+1) <?> "end of comment block"
private def whitespaceAux : Nat → BasicParserM Unit
| (n+1) :=
do whitespace,
str "--" *> takeWhile' (≠ '\n') *> whitespaceAux n
<|>
-- a "/--" doc comment is an actual token, not whitespace
try (str "/-" *> notFollowedBy (str "-")) *> finishCommentBlock *> whitespaceAux n
<|>
pure ()
| 0 := error "unreachable"
variables {m : Type → Type}
local notation `Parser` := m Syntax
local notation `lift` := @monadLift BasicParserM _ _ _
/-- Skip whitespace and comments. -/
def whitespace : BasicParserM Unit :=
hidden $ do
start ← leftOver,
-- every `whitespaceAux` loop reads at least one Char
whitespaceAux (start.remaining+1)
section
variables [Monad m] [MonadParsec Syntax m]
@[inline] def asSubstring {α : Type} (p : m α) : m Substring :=
do start ← leftOver,
p,
stop ← leftOver,
pure ⟨start, stop⟩
variables [monadBasicParser m]
@[specialize] def updateLast (f : Syntax → Syntax) (trailing : Substring) : List Syntax → List Syntax
| [] := []
| [stx] := [f stx]
| (stx::stxs) := stx :: updateLast stxs
private partial def updateTrailing : Substring → Syntax → Syntax
| trailing (Syntax.atom a@⟨some info, _⟩) := Syntax.atom {a with info := some {info with trailing := trailing}}
| trailing (Syntax.ident id@{info := some info, ..}) := Syntax.ident {id with info := some {info with trailing := trailing}}
| trailing (Syntax.rawNode n) := Syntax.rawNode {n with args := updateLast (updateTrailing trailing) trailing n.args}
| trailing stx := stx
def withTrailing (stx : Syntax) : m Syntax :=
do -- TODO(Sebastian): less greedy, more natural whitespace assignment
-- E.g. only read up to the next line break
trailing ← lift $ asSubstring $ whitespace,
pure $ updateTrailing trailing stx
def mkRawRes (start stop : String.OldIterator) : Syntax :=
let ss : Substring := ⟨start, stop⟩ in
Syntax.atom ⟨some {leading := ⟨start, start⟩, pos := start.offset, trailing := ⟨stop, stop⟩}, ss.toString⟩
/-- Match an arbitrary Parser and return the consumed String in a `Syntax.atom`. -/
@[inline] def raw {α : Type} (p : m α) (trailingWs := false) : Parser := do
start ← leftOver,
p,
stop ← leftOver,
let stx := mkRawRes start stop,
if trailingWs then withTrailing stx else pure stx
instance raw.tokens {α} (p : m α) (t) : Parser.HasTokens (raw p t : Parser) := default _
instance raw.view {α} (p : m α) (t) : Parser.HasView (Option SyntaxAtom) (raw p t : Parser) :=
{ view := λ stx, match stx with
| Syntax.atom atom := some atom
| _ := none,
review := λ a, (Syntax.atom <$> a).getOrElse Syntax.missing }
/-- Like `raw (str s)`, but default to `s` in views. -/
@[inline, derive HasTokens HasView]
def rawStr (s : String) (trailingWs := false) : Parser :=
raw (str s) trailingWs
instance rawStr.viewDefault (s) (t) : Parser.HasViewDefault (rawStr s t : Parser) (Option SyntaxAtom) (some {val := s}) :=
⟨⟩
end
set_option class.instance_max_depth 200
@[derive HasTokens HasView]
def detailIdentPart.Parser : BasicParserM Syntax :=
nodeChoice! detailIdentPart {
escaped: node! detailIdentPartEscaped [
escBegin: rawStr idBeginEscape.toString,
escaped: raw $ takeUntil1 isIdEndEscape,
escEnd: rawStr idEndEscape.toString,
],
default: raw $ satisfy isIdFirst *> takeWhile isIdRest
}
@[derive HasTokens HasView]
def detailIdentSuffix.Parser : RecT Unit Syntax BasicParserM Syntax :=
-- consume '.' only when followed by a character starting an detailIdentPart
try (lookahead (ch '.' *> (ch idBeginEscape <|> satisfy isIdFirst)))
*> node! detailIdentSuffix [«.»: rawStr ".", ident: recurse ()]
def detailIdent' : RecT Unit Syntax BasicParserM Syntax :=
node! detailIdent [part: monadLift detailIdentPart.Parser, suffix: optional detailIdentSuffix.Parser]
/-- A Parser that gives a more detailed View of `SyntaxIdent.rawVal`. Not used by default for
performance reasons. -/
def detailIdent.Parser : BasicParserM Syntax :=
RecT.runParsec detailIdent' $ λ _, detailIdent'
private def ident' : basicParser :=
do
start ← leftOver,
s ← idPart,
n ← foldl Name.mkString (mkSimpleName s) $ do {
-- consume '.' only when followed by a character starting an detailIdentPart
try (lookahead (ch '.' *> (ch idBeginEscape <|> satisfy isIdFirst))),
ch '.',
idPart
},
stop ← leftOver,
pure $ Syntax.ident {
info := some {leading := ⟨start, start⟩, pos := start.offset, trailing := ⟨stop, stop⟩},
rawVal := ⟨start, stop⟩,
val := n
}
-- the Node macro doesn't seem to like these...
--TODO(Sebastian): these should probably generate better error messages
def parseBinLit : BasicParserM Unit :=
ch '0' *> (ch 'b' <|> ch 'B') *> many1' (ch '0' <|> ch '1')
def parseOctLit : BasicParserM String :=
ch '0' *> (ch 'o' <|> ch 'O') *> takeWhile1 (λ c, c ≥ '0' && c < '8')
def parseHexLit : BasicParserM String :=
ch '0' *> (ch 'x' <|> ch 'X') *> takeWhile1 (λ c, c.isDigit || c.isAlpha)
--TODO(Sebastian): other bases
def number' : basicParser :=
nodeLongestChoice! number {
base10: raw $ takeWhile1 Char.isDigit,
base2: raw parseBinLit,
base8: raw parseOctLit,
base16: raw parseHexLit,
}
def stringLit' : basicParser :=
node! stringLit [val: raw parseStringLiteral]
private def mkConsumeToken (tk : TokenConfig) (it : String.OldIterator) : basicParser :=
let it' := it.nextn tk.prefix.length in
MonadParsec.lift $ λ _, Parsec.Result.ok (mkRawRes it it') it' none
def numberOrStringLit : basicParser :=
number' <|> stringLit'
def tokenCont (it : String.OldIterator) (tk : TokenConfig) : basicParser :=
do id ← ident',
it' ← leftOver,
-- if a token is both a symbol and a valid identifier (i.e. a keyword),
-- we want it to be recognized as a symbol
if it.offset + tk.prefix.length ≥ it'.offset then
mkConsumeToken tk it
else pure id
def token : basicParser :=
do it ← leftOver,
cache ← getCache,
-- NOTE: using `catch` instead of `<|>` so that error messages from the second block are preferred
catch (do
-- check token cache
some tkc ← pure cache.tokenCache | failure,
guard (it.offset = tkc.startIt.offset),
-- hackishly update Parsec Position
MonadParsec.lift (λ it, Parsec.Result.ok () tkc.stopIt none),
putCache {cache with hit := cache.hit + 1},
pure tkc.tk
) (λ _, do
-- cache failed, update cache
identStart ← observing $ lookahead (satisfy isIdFirst <|> ch idBeginEscape),
tk ← matchToken,
tk ← match tk, identStart with
| some tk@{suffixParser := some _, ..}, _ :=
error "token: not implemented" --str tk *> MonadParsec.lift r
| some tk, Except.ok _ := tokenCont it tk
| some tk, Except.error _ := mkConsumeToken tk it
| none, Except.ok _ := ident'
| none, Except.error _ := numberOrStringLit,
tk ← withTrailing tk,
newIt ← leftOver,
putCache {cache with tokenCache := some ⟨it, newIt, tk⟩, miss := cache.miss + 1},
pure tk
)
def peekToken : BasicParserM (Except (Parsec.Message Syntax) Syntax) :=
observing (try (lookahead token))
variable [monadBasicParser m]
def symbolCore (sym : String) (lbp : Nat) (ex : DList String) : Parser :=
lift $ try $ do {
it ← leftOver,
stx@(Syntax.atom ⟨_, sym'⟩) ← token | error "" ex it,
when (sym ≠ sym') $
error sym' ex it,
pure stx
} <?> sym
@[inline] def symbol (sym : String) (lbp := 0) : Parser :=
let sym := sym.trim in
symbolCore sym lbp (DList.singleton sym)
instance symbol.tokens (sym lbp) : Parser.HasTokens (symbol sym lbp : Parser) :=
⟨[⟨sym.trim, lbp, none⟩]⟩
instance symbol.View (sym lbp) : Parser.HasView (Option SyntaxAtom) (symbol sym lbp : Parser) :=
{ view := λ stx, match stx with
| Syntax.atom atom := some atom
| _ := none,
review := λ a, (Syntax.atom <$> a).getOrElse Syntax.missing }
instance symbol.viewDefault (sym lbp) : Parser.HasViewDefault (symbol sym lbp : Parser) _
(some {info := none, val := sym.trim}) := ⟨⟩
def number.Parser : Parser :=
lift $ try $ do {
it ← leftOver,
stx ← token,
if stx.isOfKind number then pure stx
else error "" (DList.singleton "number") it
}
instance number.Parser.tokens : Parser.HasTokens (number.Parser : Parser) := default _
instance number.Parser.view : Parser.HasView number.View (number.Parser : Parser) :=
{..number.HasView}
private def toNatCore (base : Nat) : String.OldIterator → Nat → Nat → Nat
| it 0 r := r
| it (i+1) r :=
let c := it.curr in
let val := if c.isDigit then
c.toNat - '0'.toNat
else if c ≥ 'a' ∧ c ≤ 'f' then
c.toNat - 'a'.toNat
else
c.toNat - 'A'.toNat in
let r := r*base + val in
toNatCore it.next i r
private def toNatBase (s : String) (base : Nat) : Nat :=
toNatCore base s.mkOldIterator s.length 0
def number.View.toNat : number.View → Nat
| (number.View.base10 (some atom)) := atom.val.toNat
| (number.View.base2 (some atom)) := toNatBase atom.val 2
| (number.View.base8 (some atom)) := toNatBase atom.val 8
| (number.View.base16 (some atom)) := toNatBase atom.val 16
| _ := 1138 -- should never happen, but let's still choose a grep-able number
def number.View.ofNat (n : Nat) : number.View :=
number.View.base10 (some {val := toString n})
def stringLit.Parser : Parser :=
lift $ try $ do {
it ← leftOver,
stx ← token,
some _ ← pure $ tryView stringLit stx | error "" (DList.singleton "String") it,
pure stx
} <?> "String"
instance stringLit.Parser.tokens : Parser.HasTokens (stringLit.Parser : Parser) := default _
instance stringLit.Parser.View : Parser.HasView stringLit.View (stringLit.Parser : Parser) :=
{..stringLit.HasView}
def stringLit.View.value (lit : stringLit.View) : Option String := do
atom ← lit.val,
Except.ok s ← pure $ Parsec.parse (parseStringLiteral : Parsec' _) atom.val
| failure,
pure s
def ident.Parser : Parser :=
lift $ try $ do {
it ← leftOver,
stx@(Syntax.ident _) ← token | error "" (DList.singleton "identifier") it,
pure stx
} <?> "identifier"
instance ident.Parser.tokens : Parser.HasTokens (ident.Parser : Parser) := default _
instance ident.Parser.View : Parser.HasView SyntaxIdent (ident.Parser : Parser) :=
{ view := λ stx, match stx with
| Syntax.ident id := id
| _ := {rawVal := Substring.ofString "NOTAnIdent", val := `NOTAnIdent},
review := Syntax.ident }
/-- Read identifier without consulting the token table. -/
def rawIdent.Parser : Parser :=
lift $ ident' >>= withTrailing
instance rawIdent.Parser.tokens : Parser.HasTokens (rawIdent.Parser : Parser) := default _
instance rawIdent.Parser.View : Parser.HasView SyntaxIdent (rawIdent.Parser : Parser) :=
{..(ident.Parser.View : HasView _ (_ : Parser))}
/-- Check if the following token is the symbol _or_ identifier `sym`. Useful for
parsing local tokens that have not been added to the token table (but may have
been so by some unrelated code).
For example, the universe `max` Function is parsed using this Combinator so that
it can still be used as an identifier outside of universes (but registering it
as a token in a Term Syntax would not break the universe Parser). -/
def symbolOrIdent (sym : String) : Parser :=
lift $ try $ do
it ← leftOver,
stx ← token,
let sym' := match stx with
| Syntax.atom ⟨_, sym'⟩ := some sym'
| Syntax.ident id := some id.rawVal.toString
| _ := none,
when (sym' ≠ some sym) $
error "" (DList.singleton (repr sym)) it,
pure stx
instance symbolOrIdent.tokens (sym) : Parser.HasTokens (symbolOrIdent sym : Parser) :=
default _
instance symbolOrIdent.View (sym) : Parser.HasView Syntax (symbolOrIdent sym : Parser) := default _
/-- A unicode symbol with an ASCII fallback -/
@[derive HasTokens HasView]
def unicodeSymbol (unicode ascii : String) (lbp := 0) : Parser :=
lift $ anyOf [symbol unicode lbp, symbol ascii lbp]
-- use unicode variant by default
instance unicodeSymbol.viewDefault (u a lbp) : Parser.HasViewDefault (unicodeSymbol u a lbp : Parser) _ (Syntax.atom ⟨none, u⟩) := ⟨⟩
def indexed {α : Type} (map : TokenMap α) : m (List α) :=
lift $ do
Except.ok tk ← peekToken | error "",
n ← match tk with
| Syntax.atom ⟨_, s⟩ := pure $ mkSimpleName s
| Syntax.ident _ := pure `ident
| Syntax.rawNode n := pure n.kind.name
| _ := error "",
Option.toMonad $ map.find n
end «Parser»
end Lean
|
64cc6adaf8d4154d89f3d8dc02c680f7b165afa5 | 4fa161becb8ce7378a709f5992a594764699e268 | /src/ring_theory/polynomial.lean | 352c0ce1cd794d13f4e6abc92d459054a90c3a15 | [
"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 | 18,602 | lean | /-
Copyright (c) 2019 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
Ring-theoretic supplement of data.polynomial.
Main result: Hilbert basis theorem, that if a ring is noetherian then so is its polynomial ring.
-/
import data.mv_polynomial
import ring_theory.noetherian
noncomputable theory
local attribute [instance, priority 100] classical.prop_decidable
universes u v w
namespace polynomial
variables (R : Type u) [comm_ring R]
/-- The `R`-submodule of `R[X]` consisting of polynomials of degree ≤ `n`. -/
def degree_le (n : with_bot ℕ) : submodule R (polynomial R) :=
⨅ k : ℕ, ⨅ h : ↑k > n, (lcoeff R k).ker
/-- The `R`-submodule of `R[X]` consisting of polynomials of degree < `n`. -/
def degree_lt (n : ℕ) : submodule R (polynomial R) :=
⨅ k : ℕ, ⨅ h : k ≥ n, (lcoeff R k).ker
variable {R}
theorem mem_degree_le {n : with_bot ℕ} {f : polynomial R} :
f ∈ degree_le R n ↔ degree f ≤ n :=
by simp only [degree_le, submodule.mem_infi, degree_le_iff_coeff_zero, linear_map.mem_ker]; refl
@[mono] theorem degree_le_mono {m n : with_bot ℕ} (H : m ≤ n) :
degree_le R m ≤ degree_le R n :=
λ f hf, mem_degree_le.2 (le_trans (mem_degree_le.1 hf) H)
theorem degree_le_eq_span_X_pow {n : ℕ} :
degree_le R n = submodule.span R ↑((finset.range (n+1)).image (λ n, X^n) : finset (polynomial R)) :=
begin
apply le_antisymm,
{ intros p hp, replace hp := mem_degree_le.1 hp,
rw [← finsupp.sum_single p, finsupp.sum],
refine submodule.sum_mem _ (λ k hk, _),
show monomial _ _ ∈ _,
have := with_bot.coe_le_coe.1 (finset.sup_le_iff.1 hp k hk),
rw [single_eq_C_mul_X, C_mul'],
refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $
finset.mem_image.2 ⟨_, finset.mem_range.2 (nat.lt_succ_of_le this), rfl⟩) },
rw [submodule.span_le, finset.coe_image, set.image_subset_iff],
intros k hk, apply mem_degree_le.2,
apply le_trans (degree_X_pow_le _) (with_bot.coe_le_coe.2 $ nat.le_of_lt_succ $ finset.mem_range.1 hk)
end
theorem mem_degree_lt {n : ℕ} {f : polynomial R} :
f ∈ degree_lt R n ↔ degree f < n :=
by { simp_rw [degree_lt, submodule.mem_infi, linear_map.mem_ker, degree,
finset.sup_lt_iff (with_bot.bot_lt_coe n), finsupp.mem_support_iff, with_bot.some_eq_coe,
with_bot.coe_lt_coe, lt_iff_not_ge', ne, not_imp_not], refl }
@[mono] theorem degree_lt_mono {m n : ℕ} (H : m ≤ n) :
degree_lt R m ≤ degree_lt R n :=
λ f hf, mem_degree_lt.2 (lt_of_lt_of_le (mem_degree_lt.1 hf) $ with_bot.coe_le_coe.2 H)
theorem degree_lt_eq_span_X_pow {n : ℕ} :
degree_lt R n = submodule.span R ↑((finset.range n).image (λ n, X^n) : finset (polynomial R)) :=
begin
apply le_antisymm,
{ intros p hp, replace hp := mem_degree_lt.1 hp,
rw [← finsupp.sum_single p, finsupp.sum],
refine submodule.sum_mem _ (λ k hk, _),
show monomial _ _ ∈ _,
have := with_bot.coe_lt_coe.1 ((finset.sup_lt_iff $ with_bot.bot_lt_coe n).1 hp k hk),
rw [single_eq_C_mul_X, C_mul'],
refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $
finset.mem_image.2 ⟨_, finset.mem_range.2 this, rfl⟩) },
rw [submodule.span_le, finset.coe_image, set.image_subset_iff],
intros k hk, apply mem_degree_lt.2,
exact lt_of_le_of_lt (degree_X_pow_le _) (with_bot.coe_lt_coe.2 $ finset.mem_range.1 hk)
end
/-- Given a polynomial, return the polynomial whose coefficients are in
the ring closure of the original coefficients. -/
def restriction (p : polynomial R) : polynomial (ring.closure (↑p.frange : set R)) :=
⟨p.support, λ i, ⟨p.to_fun i,
if H : p.to_fun i = 0 then H.symm ▸ is_add_submonoid.zero_mem
else ring.subset_closure $ finsupp.mem_frange.2 ⟨H, i, rfl⟩⟩,
λ i, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ H, subtype.eq H, subtype.mk.inj⟩)⟩
@[simp] theorem coeff_restriction {p : polynomial R} {n : ℕ} : ↑(coeff (restriction p) n) = coeff p n := rfl
@[simp] theorem coeff_restriction' {p : polynomial R} {n : ℕ} : (coeff (restriction p) n).1 = coeff p n := rfl
@[simp] theorem degree_restriction {p : polynomial R} : (restriction p).degree = p.degree := rfl
@[simp] theorem nat_degree_restriction {p : polynomial R} : (restriction p).nat_degree = p.nat_degree := rfl
@[simp] theorem monic_restriction {p : polynomial R} : monic (restriction p) ↔ monic p :=
⟨λ H, congr_arg subtype.val H, λ H, subtype.eq H⟩
@[simp] theorem restriction_zero : restriction (0 : polynomial R) = 0 := rfl
@[simp] theorem restriction_one : restriction (1 : polynomial R) = 1 :=
ext $ λ i, subtype.eq $ by rw [coeff_restriction', coeff_one, coeff_one]; split_ifs; refl
variables {S : Type v} [comm_ring S] {f : R → S} {x : S}
theorem eval₂_restriction {p : polynomial R} :
eval₂ f x p = eval₂ (f ∘ subtype.val) x p.restriction :=
rfl
section to_subring
variables (p : polynomial R) (T : set R) [is_subring T]
/-- Given a polynomial `p` and a subring `T` that contains the coefficients of `p`,
return the corresponding polynomial whose coefficients are in `T. -/
def to_subring (hp : ↑p.frange ⊆ T) : polynomial T :=
⟨p.support, λ i, ⟨p.to_fun i,
if H : p.to_fun i = 0 then H.symm ▸ is_add_submonoid.zero_mem
else hp $ finsupp.mem_frange.2 ⟨H, i, rfl⟩⟩,
λ i, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ H, subtype.eq H, subtype.mk.inj⟩)⟩
variables (hp : ↑p.frange ⊆ T)
include hp
@[simp] theorem coeff_to_subring {n : ℕ} : ↑(coeff (to_subring p T hp) n) = coeff p n := rfl
@[simp] theorem coeff_to_subring' {n : ℕ} : (coeff (to_subring p T hp) n).1 = coeff p n := rfl
@[simp] theorem degree_to_subring : (to_subring p T hp).degree = p.degree := rfl
@[simp] theorem nat_degree_to_subring : (to_subring p T hp).nat_degree = p.nat_degree := rfl
@[simp] theorem monic_to_subring : monic (to_subring p T hp) ↔ monic p :=
⟨λ H, congr_arg subtype.val H, λ H, subtype.eq H⟩
omit hp
@[simp] theorem to_subring_zero : to_subring (0 : polynomial R) T (set.empty_subset _) = 0 := rfl
@[simp] theorem to_subring_one : to_subring (1 : polynomial R) T
(set.subset.trans (finset.coe_subset.2 finsupp.frange_single)
(finset.singleton_subset_set_iff.2 is_submonoid.one_mem)) = 1 :=
ext $ λ i, subtype.eq $ by rw [coeff_to_subring', coeff_one, coeff_one]; split_ifs; refl
end to_subring
variables (T : set R) [is_subring T]
/-- Given a polynomial whose coefficients are in some subring, return
the corresponding polynomial whose coefificents are in the ambient ring. -/
def of_subring (p : polynomial T) : polynomial R :=
⟨p.support, subtype.val ∘ p.to_fun,
λ n, finsupp.mem_support_iff.trans (not_iff_not_of_iff
⟨λ h, congr_arg subtype.val h, λ h, subtype.eq h⟩)⟩
@[simp] theorem frange_of_subring {p : polynomial T} :
↑(p.of_subring T).frange ⊆ T :=
λ y H, let ⟨hy, x, hx⟩ := finsupp.mem_frange.1 H in hx ▸ (p.to_fun x).2
end polynomial
variables {R : Type u} {σ : Type v} [comm_ring R]
namespace ideal
open polynomial
/-- Transport an ideal of `R[X]` to an `R`-submodule of `R[X]`. -/
def of_polynomial (I : ideal (polynomial R)) : submodule R (polynomial R) :=
{ carrier := I.carrier,
zero_mem' := I.zero_mem,
add_mem' := λ _ _, I.add_mem,
smul_mem' := λ c x H, by rw [← C_mul']; exact submodule.smul_mem _ _ H }
variables {I : ideal (polynomial R)}
theorem mem_of_polynomial (x) : x ∈ I.of_polynomial ↔ x ∈ I := iff.rfl
variables (I)
/-- Given an ideal `I` of `R[X]`, make the `R`-submodule of `I`
consisting of polynomials of degree ≤ `n`. -/
def degree_le (n : with_bot ℕ) : submodule R (polynomial R) :=
degree_le R n ⊓ I.of_polynomial
/-- Given an ideal `I` of `R[X]`, make the ideal in `R` of
leading coefficients of polynomials in `I` with degree ≤ `n`. -/
def leading_coeff_nth (n : ℕ) : ideal R :=
(I.degree_le n).map $ lcoeff R n
theorem mem_leading_coeff_nth (n : ℕ) (x) :
x ∈ I.leading_coeff_nth n ↔ ∃ p ∈ I, degree p ≤ n ∧ leading_coeff p = x :=
begin
simp only [leading_coeff_nth, degree_le, submodule.mem_map, lcoeff_apply, submodule.mem_inf, mem_degree_le],
split,
{ rintro ⟨p, ⟨hpdeg, hpI⟩, rfl⟩,
cases lt_or_eq_of_le hpdeg with hpdeg hpdeg,
{ refine ⟨0, I.zero_mem, bot_le, _⟩,
rw [leading_coeff_zero, eq_comm],
exact coeff_eq_zero_of_degree_lt hpdeg },
{ refine ⟨p, hpI, le_of_eq hpdeg, _⟩,
rw [leading_coeff, nat_degree, hpdeg], refl } },
{ rintro ⟨p, hpI, hpdeg, rfl⟩,
have : nat_degree p + (n - nat_degree p) = n,
{ exact nat.add_sub_cancel' (nat_degree_le_of_degree_le hpdeg) },
refine ⟨p * X ^ (n - nat_degree p), ⟨_, I.mul_mem_right hpI⟩, _⟩,
{ apply le_trans (degree_mul_le _ _) _,
apply le_trans (add_le_add' (degree_le_nat_degree) (degree_X_pow_le _)) _,
rw [← with_bot.coe_add, this],
exact le_refl _ },
{ rw [leading_coeff, ← coeff_mul_X_pow p (n - nat_degree p), this] } }
end
theorem mem_leading_coeff_nth_zero (x) :
x ∈ I.leading_coeff_nth 0 ↔ C x ∈ I :=
(mem_leading_coeff_nth _ _ _).trans
⟨λ ⟨p, hpI, hpdeg, hpx⟩, by rwa [← hpx, leading_coeff,
nat.eq_zero_of_le_zero (nat_degree_le_of_degree_le hpdeg),
← eq_C_of_degree_le_zero hpdeg],
λ hx, ⟨C x, hx, degree_C_le, leading_coeff_C x⟩⟩
theorem leading_coeff_nth_mono {m n : ℕ} (H : m ≤ n) :
I.leading_coeff_nth m ≤ I.leading_coeff_nth n :=
begin
intros r hr,
simp only [submodule.mem_coe, mem_leading_coeff_nth] at hr ⊢,
rcases hr with ⟨p, hpI, hpdeg, rfl⟩,
refine ⟨p * X ^ (n - m), I.mul_mem_right hpI, _, leading_coeff_mul_X_pow⟩,
refine le_trans (degree_mul_le _ _) _,
refine le_trans (add_le_add' hpdeg (degree_X_pow_le _)) _,
rw [← with_bot.coe_add, nat.add_sub_cancel' H],
exact le_refl _
end
/-- Given an ideal `I` in `R[X]`, make the ideal in `R` of the
leading coefficients in `I`. -/
def leading_coeff : ideal R :=
⨆ n : ℕ, I.leading_coeff_nth n
theorem mem_leading_coeff (x) :
x ∈ I.leading_coeff ↔ ∃ p ∈ I, polynomial.leading_coeff p = x :=
begin
rw [leading_coeff, submodule.mem_supr_of_directed],
simp only [mem_leading_coeff_nth],
{ split, { rintro ⟨i, p, hpI, hpdeg, rfl⟩, exact ⟨p, hpI, rfl⟩ },
rintro ⟨p, hpI, rfl⟩, exact ⟨nat_degree p, p, hpI, degree_le_nat_degree, rfl⟩ },
intros i j, exact ⟨i + j, I.leading_coeff_nth_mono (nat.le_add_right _ _),
I.leading_coeff_nth_mono (nat.le_add_left _ _)⟩
end
theorem is_fg_degree_le [is_noetherian_ring R] (n : ℕ) :
submodule.fg (I.degree_le n) :=
is_noetherian_submodule_left.1 (is_noetherian_of_fg_of_noetherian _
⟨_, degree_le_eq_span_X_pow.symm⟩) _
end ideal
/-- Hilbert basis theorem: a polynomial ring over a noetherian ring is a noetherian ring. -/
protected theorem polynomial.is_noetherian_ring [is_noetherian_ring R] : is_noetherian_ring (polynomial R) :=
⟨assume I : ideal (polynomial R),
let L := I.leading_coeff in
let M := well_founded.min (is_noetherian_iff_well_founded.1 (by apply_instance))
(set.range I.leading_coeff_nth) ⟨_, ⟨0, rfl⟩⟩ in
have hm : M ∈ set.range I.leading_coeff_nth := well_founded.min_mem _ _ _,
let ⟨N, HN⟩ := hm, ⟨s, hs⟩ := I.is_fg_degree_le N in
have hm2 : ∀ k, I.leading_coeff_nth k ≤ M := λ k, or.cases_on (le_or_lt k N)
(λ h, HN ▸ I.leading_coeff_nth_mono h)
(λ h x hx, classical.by_contradiction $ λ hxm,
have ¬M < I.leading_coeff_nth k, by refine well_founded.not_lt_min
(well_founded_submodule_gt _ _) _ _ _; exact ⟨k, rfl⟩,
this ⟨HN ▸ I.leading_coeff_nth_mono (le_of_lt h), λ H, hxm (H hx)⟩),
have hs2 : ∀ {x}, x ∈ I.degree_le N → x ∈ ideal.span (↑s : set (polynomial R)),
from hs ▸ λ x hx, submodule.span_induction hx (λ _ hx, ideal.subset_span hx) (ideal.zero_mem _)
(λ _ _, ideal.add_mem _) (λ c f hf, f.C_mul' c ▸ ideal.mul_mem_left _ hf),
⟨s, le_antisymm (ideal.span_le.2 $ λ x hx, have x ∈ I.degree_le N, from hs ▸ submodule.subset_span hx, this.2) $ begin
change I ≤ ideal.span ↑s,
intros p hp, generalize hn : p.nat_degree = k,
induction k using nat.strong_induction_on with k ih generalizing p,
cases le_or_lt k N,
{ subst k, refine hs2 ⟨polynomial.mem_degree_le.2
(le_trans polynomial.degree_le_nat_degree $ with_bot.coe_le_coe.2 h), hp⟩ },
{ have hp0 : p ≠ 0,
{ rintro rfl, cases hn, exact nat.not_lt_zero _ h },
have : (0 : R) ≠ 1,
{ intro h, apply hp0, ext i, refine (mul_one _).symm.trans _,
rw [← h, mul_zero], refl },
haveI : nonzero R := ⟨this⟩,
have : p.leading_coeff ∈ I.leading_coeff_nth N,
{ rw HN, exact hm2 k ((I.mem_leading_coeff_nth _ _).2
⟨_, hp, hn ▸ polynomial.degree_le_nat_degree, rfl⟩) },
rw I.mem_leading_coeff_nth at this,
rcases this with ⟨q, hq, hdq, hlqp⟩,
have hq0 : q ≠ 0,
{ intro H, rw [← polynomial.leading_coeff_eq_zero] at H,
rw [hlqp, polynomial.leading_coeff_eq_zero] at H, exact hp0 H },
have h1 : p.degree = (q * polynomial.X ^ (k - q.nat_degree)).degree,
{ rw [polynomial.degree_mul_eq', polynomial.degree_X_pow],
rw [polynomial.degree_eq_nat_degree hp0, polynomial.degree_eq_nat_degree hq0],
rw [← with_bot.coe_add, nat.add_sub_cancel', hn],
{ refine le_trans (polynomial.nat_degree_le_of_degree_le hdq) (le_of_lt h) },
rw [polynomial.leading_coeff_X_pow, mul_one],
exact mt polynomial.leading_coeff_eq_zero.1 hq0 },
have h2 : p.leading_coeff = (q * polynomial.X ^ (k - q.nat_degree)).leading_coeff,
{ rw [← hlqp, polynomial.leading_coeff_mul_X_pow] },
have := polynomial.degree_sub_lt h1 hp0 h2,
rw [polynomial.degree_eq_nat_degree hp0] at this,
rw ← sub_add_cancel p (q * polynomial.X ^ (k - q.nat_degree)),
refine (ideal.span ↑s).add_mem _ ((ideal.span ↑s).mul_mem_right _),
{ by_cases hpq : p - q * polynomial.X ^ (k - q.nat_degree) = 0,
{ rw hpq, exact ideal.zero_mem _ },
refine ih _ _ (I.sub_mem hp (I.mul_mem_right hq)) rfl,
rwa [polynomial.degree_eq_nat_degree hpq, with_bot.coe_lt_coe, hn] at this },
exact hs2 ⟨polynomial.mem_degree_le.2 hdq, hq⟩ }
end⟩⟩
attribute [instance] polynomial.is_noetherian_ring
namespace mv_polynomial
lemma is_noetherian_ring_fin_0 [is_noetherian_ring R] :
is_noetherian_ring (mv_polynomial (fin 0) R) :=
is_noetherian_ring_of_ring_equiv R
((mv_polynomial.pempty_ring_equiv R).symm.trans
(mv_polynomial.ring_equiv_of_equiv _ fin_zero_equiv'.symm))
theorem is_noetherian_ring_fin [is_noetherian_ring R] :
∀ {n : ℕ}, is_noetherian_ring (mv_polynomial (fin n) R)
| 0 := is_noetherian_ring_fin_0
| (n+1) :=
@is_noetherian_ring_of_ring_equiv (polynomial (mv_polynomial (fin n) R)) _ _ _
(mv_polynomial.fin_succ_equiv _ n).symm
(@polynomial.is_noetherian_ring (mv_polynomial (fin n) R) _ (is_noetherian_ring_fin))
/-- The multivariate polynomial ring in finitely many variables over a noetherian ring
is itself a noetherian ring. -/
instance is_noetherian_ring [fintype σ] [is_noetherian_ring R] :
is_noetherian_ring (mv_polynomial σ R) :=
trunc.induction_on (fintype.equiv_fin σ) $ λ e,
@is_noetherian_ring_of_ring_equiv (mv_polynomial (fin (fintype.card σ)) R) _ _ _
(mv_polynomial.ring_equiv_of_equiv _ e.symm) is_noetherian_ring_fin
lemma is_integral_domain_fin_zero (R : Type u) [comm_ring R] (hR : is_integral_domain R) :
is_integral_domain (mv_polynomial (fin 0) R) :=
ring_equiv.is_integral_domain R hR
((ring_equiv_of_equiv R fin_zero_equiv').trans (mv_polynomial.pempty_ring_equiv R))
/-- Auxilliary lemma:
Multivariate polynomials over an integral domain
with variables indexed by `fin n` form an integral domain.
This fact is proven inductively,
and then used to prove the general case without any finiteness hypotheses.
See `mv_polynomial.integral_domain` for the general case. -/
lemma is_integral_domain_fin (R : Type u) [comm_ring R] (hR : is_integral_domain R) :
∀ (n : ℕ), is_integral_domain (mv_polynomial (fin n) R)
| 0 := is_integral_domain_fin_zero R hR
| (n+1) :=
ring_equiv.is_integral_domain
(polynomial (mv_polynomial (fin n) R))
(is_integral_domain_fin n).polynomial
(mv_polynomial.fin_succ_equiv _ n)
lemma is_integral_domain_fintype (R : Type u) (σ : Type v) [comm_ring R] [fintype σ]
(hR : is_integral_domain R) : is_integral_domain (mv_polynomial σ R) :=
trunc.induction_on (fintype.equiv_fin σ) $ λ e,
@ring_equiv.is_integral_domain _ (mv_polynomial (fin $ fintype.card σ) R) _ _
(mv_polynomial.is_integral_domain_fin _ hR _)
(ring_equiv_of_equiv R e)
/-- Auxilliary definition:
Multivariate polynomials in finitely many variables over an integral domain form an integral domain.
This fact is proven by transport of structure from the `mv_polynomial.integral_domain_fin`,
and then used to prove the general case without finiteness hypotheses.
See `mv_polynomial.integral_domain` for the general case. -/
def integral_domain_fintype (R : Type u) (σ : Type v) [integral_domain R] [fintype σ] :
integral_domain (mv_polynomial σ R) :=
@is_integral_domain.to_integral_domain _ _ $ mv_polynomial.is_integral_domain_fintype R σ $
integral_domain.to_is_integral_domain R
protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {R : Type u} [integral_domain R] {σ : Type v}
(p q : mv_polynomial σ R) (h : p * q = 0) : p = 0 ∨ q = 0 :=
begin
obtain ⟨s, p, rfl⟩ := exists_finset_rename p,
obtain ⟨t, q, rfl⟩ := exists_finset_rename q,
have : p.rename (subtype.map id (finset.subset_union_left s t) : {x // x ∈ s} → {x // x ∈ s ∪ t}) *
q.rename (subtype.map id (finset.subset_union_right s t)) = 0,
{ apply rename_injective _ subtype.val_injective, simpa using h },
letI := mv_polynomial.integral_domain_fintype R {x // x ∈ (s ∪ t)},
rw mul_eq_zero at this,
cases this; [left, right],
all_goals { simpa using congr_arg (rename subtype.val) this }
end
/-- The multivariate polynomial ring over an integral domain is an integral domain. -/
instance {R : Type u} {σ : Type v} [integral_domain R] :
integral_domain (mv_polynomial σ R) :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := mv_polynomial.eq_zero_or_eq_zero_of_mul_eq_zero,
zero_ne_one :=
begin
intro H,
have : eval₂ id (λ s, (0:R)) (0 : mv_polynomial σ R) =
eval₂ id (λ s, (0:R)) (1 : mv_polynomial σ R),
{ congr, exact H },
simpa,
end,
.. (by apply_instance : comm_ring (mv_polynomial σ R)) }
end mv_polynomial
|
86fe49d68abff2b3f2281fabfca2838eb1cebc1d | 3446e92e64a5de7ed1f2109cfb024f83cd904c34 | /src/game/world1/level5.lean | 1b969435de86a869b4011b420210f018dac547ff | [] | no_license | kckennylau/natural_number_game | 019f4a5f419c9681e65234ecd124c564f9a0a246 | ad8c0adaa725975be8a9f978c8494a39311029be | refs/heads/master | 1,598,784,137,722 | 1,571,905,156,000 | 1,571,905,156,000 | 218,354,686 | 0 | 0 | null | 1,572,373,319,000 | 1,572,373,318,000 | null | UTF-8 | Lean | false | false | 2,850 | lean | import mynat.definition -- hide
import mynat.add -- definition of addition
namespace mynat -- hide
/-
# World 1 : Tutorial world
## Level 5: addition
We have a new import -- the definition of addition.
Peano defined addition `a + b` by induction on `b`, or,
more precisely, by *recursion* on `b`. He first explained how to add 0 to a number:
this is the base case.
* `add_zero : ∀ a : mynat, a + 0 = a`
We will call this theorem `add_zero`. **Note the name of this theorem**.
Mathematicians sometimes call it "Lemma 2.1" or "Hypothesis P6" or something. But
computer scientists call it `add_zero` because it tells you
what the answer to "a add zero" is. It's a *much* better name than "Lemma 2.1".
Even better, we can use the rewrite tactic with `add_zero`.
If you ever see `x + 0` in your goal, `rw add_zero,` should simplify it to `x`.
Now here's the inductive step. If you know how to add `d` to `a`, then
Peano tells you how to add `succ(d)` to `a`. It looks like this:
* `add_succ : ∀ a d : mynat, a + succ(d) = succ (a + d)`
What's going on here is that we assume `a + d` is already
defined, and we define `a + succ(d)` to be the number after it.
**Note the name of this theorem too** -- `add_succ` tells you
how to add a successor to something. If you ever see `... + succ ...`
in your goal, you should be able to use `rw add_succ,` to make
progress. Here is a simple example where we shall see both.
Delete `sorry`. Observe that the goal mentions `... + succ ...`. So type
`rw add_succ,`
and hit enter; see the goal change. **Don't forget the commma**.
Do you see that the goal now mentions ` ... + 0 ...`? So type
`rw add_zero,`
and then observe that you can close the goal with
`refl,`
and you're done. You might want to review this proof now; at
three lines long it is our current record. Click on a line in the proof
and then use the arrow keys to move your cursor
around (try going up and down first), and you can see what
Lean is thinking on each line of the proof. The goal changes
just before each comma. That's why commas are important.
FAQ. Question: why has the top left hand box gone blank?
Answer: Maybe you tried a tactic which didn't work. Or maybe you're
in the middle of typing a tactic. Try deleting up to the last
comma, or adding a new comma. Look at the
error message. What line is the first error on? Perhaps
Lean thinks you're in the middle of writing a tactic that you
think you finished. Did you perhaps forget a comma somewhere?
When you're happy, let's move onto world 2, addition world, and
learn about proof by induction. Click on "next world" in the top right.
-/
/- Lemma : no-side-bar
For all natural numbers `a`, we have `a + succ(0) = succ(a)`.
-/
lemma add_succ_zero (a : mynat) : a + succ(0) = succ(a) :=
begin [less_leaky]
rw add_succ,
rw add_zero,
refl,
end
end mynat |
eb15bcab70316ecc4a0b4f247f423abb025fe94c | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/lie/universal_enveloping.lean | 218f402cb80cdbcb1a9765318150afb967129e71 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 5,592 | lean | /-
Copyright (c) 2020 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import algebra.lie.of_associative
import algebra.ring_quot
import linear_algebra.tensor_algebra.basic
/-!
# Universal enveloping algebra
Given a commutative ring `R` and a Lie algebra `L` over `R`, we construct the universal
enveloping algebra of `L`, together with its universal property.
## Main definitions
* `universal_enveloping_algebra`: the universal enveloping algebra, endowed with an
`R`-algebra structure.
* `universal_enveloping_algebra.ι`: the Lie algebra morphism from `L` to its universal
enveloping algebra.
* `universal_enveloping_algebra.lift`: given an associative algebra `A`, together with a Lie
algebra morphism `f : L →ₗ⁅R⁆ A`, `lift R L f : universal_enveloping_algebra R L →ₐ[R] A` is the
unique morphism of algebras through which `f` factors.
* `universal_enveloping_algebra.ι_comp_lift`: states that the lift of a morphism is indeed part
of a factorisation.
* `universal_enveloping_algebra.lift_unique`: states that lifts of morphisms are indeed unique.
* `universal_enveloping_algebra.hom_ext`: a restatement of `lift_unique` as an extensionality
lemma.
## Tags
lie algebra, universal enveloping algebra, tensor algebra
-/
universes u₁ u₂ u₃
variables (R : Type u₁) (L : Type u₂)
variables [comm_ring R] [lie_ring L] [lie_algebra R L]
local notation `ιₜ` := tensor_algebra.ι R
namespace universal_enveloping_algebra
/-- The quotient by the ideal generated by this relation is the universal enveloping algebra.
Note that we have avoided using the more natural expression:
| lie_compat (x y : L) : rel (ιₜ ⁅x, y⁆) ⁅ιₜ x, ιₜ y⁆
so that our construction needs only the semiring structure of the tensor algebra. -/
inductive rel : tensor_algebra R L → tensor_algebra R L → Prop
| lie_compat (x y : L) : rel (ιₜ ⁅x, y⁆ + (ιₜ y) * (ιₜ x)) ((ιₜ x) * (ιₜ y))
end universal_enveloping_algebra
/-- The universal enveloping algebra of a Lie algebra. -/
@[derive [inhabited, ring, algebra R]]
def universal_enveloping_algebra := ring_quot (universal_enveloping_algebra.rel R L)
namespace universal_enveloping_algebra
/-- The quotient map from the tensor algebra to the universal enveloping algebra as a morphism of
associative algebras. -/
def mk_alg_hom : tensor_algebra R L →ₐ[R] universal_enveloping_algebra R L :=
ring_quot.mk_alg_hom R (rel R L)
variables {L}
/-- The natural Lie algebra morphism from a Lie algebra to its universal enveloping algebra. -/
def ι : L →ₗ⁅R⁆ universal_enveloping_algebra R L :=
{ map_lie' := λ x y, by
{ suffices : mk_alg_hom R L (ιₜ ⁅x, y⁆ + (ιₜ y) * (ιₜ x)) = mk_alg_hom R L ((ιₜ x) * (ιₜ y)),
{ rw alg_hom.map_mul at this, simp [lie_ring.of_associative_ring_bracket, ← this], },
exact ring_quot.mk_alg_hom_rel _ (rel.lie_compat x y), },
..(mk_alg_hom R L).to_linear_map.comp ιₜ }
variables {A : Type u₃} [ring A] [algebra R A] (f : L →ₗ⁅R⁆ A)
/-- The universal property of the universal enveloping algebra: Lie algebra morphisms into
associative algebras lift to associative algebra morphisms from the universal enveloping algebra. -/
def lift : (L →ₗ⁅R⁆ A) ≃ (universal_enveloping_algebra R L →ₐ[R] A) :=
{ to_fun := λ f,
ring_quot.lift_alg_hom R ⟨tensor_algebra.lift R (f : L →ₗ[R] A),
begin
intros a b h, induction h with x y,
simp only [lie_ring.of_associative_ring_bracket,
map_add, tensor_algebra.lift_ι_apply, lie_hom.coe_to_linear_map, lie_hom.map_lie,
map_mul, sub_add_cancel],
end⟩,
inv_fun := λ F, (F : universal_enveloping_algebra R L →ₗ⁅R⁆ A).comp (ι R),
left_inv := λ f, by { ext, simp only [ι, mk_alg_hom,
tensor_algebra.lift_ι_apply, lie_hom.coe_to_linear_map, linear_map.to_fun_eq_coe,
linear_map.coe_comp, lie_hom.coe_comp, alg_hom.coe_to_lie_hom, lie_hom.coe_mk,
function.comp_app, alg_hom.to_linear_map_apply, ring_quot.lift_alg_hom_mk_alg_hom_apply], },
right_inv := λ F, by { ext, simp only [ι, mk_alg_hom,
tensor_algebra.lift_ι_apply, lie_hom.coe_to_linear_map, linear_map.to_fun_eq_coe,
linear_map.coe_comp, lie_hom.coe_linear_map_comp, alg_hom.comp_to_linear_map,
function.comp_app, alg_hom.to_linear_map_apply, ring_quot.lift_alg_hom_mk_alg_hom_apply,
alg_hom.coe_to_lie_hom, lie_hom.coe_mk], } }
@[simp] lemma lift_symm_apply (F : universal_enveloping_algebra R L →ₐ[R] A) :
(lift R).symm F = (F : universal_enveloping_algebra R L →ₗ⁅R⁆ A).comp (ι R) :=
rfl
@[simp] lemma ι_comp_lift : (lift R f) ∘ (ι R) = f :=
funext $ lie_hom.ext_iff.mp $ (lift R).symm_apply_apply f
@[simp] lemma lift_ι_apply (x : L) : lift R f (ι R x) = f x :=
by rw [←function.comp_apply (lift R f) (ι R) x, ι_comp_lift]
lemma lift_unique (g : universal_enveloping_algebra R L →ₐ[R] A) :
g ∘ (ι R) = f ↔ g = lift R f :=
begin
refine iff.trans _ (lift R).symm_apply_eq,
split; {intro h, ext, simp [←h] },
end
/-- See note [partially-applied ext lemmas]. -/
@[ext] lemma hom_ext {g₁ g₂ : universal_enveloping_algebra R L →ₐ[R] A}
(h : (g₁ : universal_enveloping_algebra R L →ₗ⁅R⁆ A).comp (ι R) =
(g₂ : universal_enveloping_algebra R L →ₗ⁅R⁆ A).comp (ι R)) :
g₁ = g₂ :=
have h' : (lift R).symm g₁ = (lift R).symm g₂, { ext, simp [h], },
(lift R).symm.injective h'
end universal_enveloping_algebra
|
1c408a58157fdf152ef9021a5648c96f31deb340 | ea4aee6b11f86433e69bb5e50d0259e056d0ae61 | /src/tidy/repeat_at_least_once.lean | 3cd85cdf7a773942d1ff0cab9de619746978f3e4 | [] | no_license | timjb/lean-tidy | e18feff0b7f0aad08c614fb4d34aaf527bf21e20 | e767e259bf76c69edfd4ab8af1b76e6f1ed67f48 | refs/heads/master | 1,624,861,693,182 | 1,504,411,006,000 | 1,504,411,006,000 | 103,740,824 | 0 | 0 | null | 1,505,553,968,000 | 1,505,553,968,000 | null | UTF-8 | Lean | false | false | 394 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
namespace tactic
meta def repeat_at_least_once ( t : tactic unit ) : tactic unit := t >> repeat t
namespace interactive
meta def repeat_at_least_once : itactic → tactic unit :=
tactic.repeat_at_least_once
end interactive
end tactic |
dbab7160aee8d5a091a0a73934ba54eae625035d | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/linear_algebra/exterior_algebra/basic.lean | d5c712c549edb010f6719513dd9b5bf2ae62d1e7 | [
"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,993 | lean | /-
Copyright (c) 2020 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhangir Azerbayev, Adam Topaz, Eric Wieser
-/
import algebra.ring_quot
import linear_algebra.clifford_algebra.basic
import linear_algebra.alternating
import group_theory.perm.sign
/-!
# Exterior Algebras
We construct the exterior algebra of a module `M` over a commutative semiring `R`.
## Notation
The exterior algebra of the `R`-module `M` is denoted as `exterior_algebra R M`.
It is endowed with the structure of an `R`-algebra.
Given a linear morphism `f : M → A` from a module `M` to another `R`-algebra `A`, such that
`cond : ∀ m : M, f m * f m = 0`, there is a (unique) lift of `f` to an `R`-algebra morphism,
which is denoted `exterior_algebra.lift R f cond`.
The canonical linear map `M → exterior_algebra R M` is denoted `exterior_algebra.ι R`.
## Theorems
The main theorems proved ensure that `exterior_algebra R M` satisfies the universal property
of the exterior algebra.
1. `ι_comp_lift` is fact that the composition of `ι R` with `lift R f cond` agrees with `f`.
2. `lift_unique` ensures the uniqueness of `lift R f cond` with respect to 1.
## Definitions
* `ι_multi` is the `alternating_map` corresponding to the wedge product of `ι R m` terms.
## Implementation details
The exterior algebra of `M` is constructed as simply `clifford_algebra (0 : quadratic_form R M)`,
as this avoids us having to duplicate API.
-/
universes u1 u2 u3
variables (R : Type u1) [comm_ring R]
variables (M : Type u2) [add_comm_group M] [module R M]
/--
The exterior algebra of an `R`-module `M`.
-/
@[reducible]
def exterior_algebra := clifford_algebra (0 : quadratic_form R M)
namespace exterior_algebra
variables {M}
/--
The canonical linear map `M →ₗ[R] exterior_algebra R M`.
-/
@[reducible] def ι : M →ₗ[R] exterior_algebra R M := by exact clifford_algebra.ι _
variables {R}
/-- As well as being linear, `ι m` squares to zero -/
@[simp]
theorem ι_sq_zero (m : M) : (ι R m) * (ι R m) = 0 :=
(clifford_algebra.ι_sq_scalar _ m).trans $ map_zero _
variables {A : Type*} [semiring A] [algebra R A]
@[simp]
theorem comp_ι_sq_zero (g : exterior_algebra R M →ₐ[R] A)
(m : M) : g (ι R m) * g (ι R m) = 0 :=
by rw [←alg_hom.map_mul, ι_sq_zero, alg_hom.map_zero]
variables (R)
/--
Given a linear map `f : M →ₗ[R] A` into an `R`-algebra `A`, which satisfies the condition:
`cond : ∀ m : M, f m * f m = 0`, this is the canonical lift of `f` to a morphism of `R`-algebras
from `exterior_algebra R M` to `A`.
-/
@[simps symm_apply]
def lift : {f : M →ₗ[R] A // ∀ m, f m * f m = 0} ≃ (exterior_algebra R M →ₐ[R] A) :=
equiv.trans (equiv.subtype_equiv (equiv.refl _) $ by simp) $ clifford_algebra.lift _
@[simp]
theorem ι_comp_lift (f : M →ₗ[R] A) (cond : ∀ m, f m * f m = 0) :
(lift R ⟨f, cond⟩).to_linear_map.comp (ι R) = f :=
clifford_algebra.ι_comp_lift f _
@[simp]
theorem lift_ι_apply (f : M →ₗ[R] A) (cond : ∀ m, f m * f m = 0) (x) :
lift R ⟨f, cond⟩ (ι R x) = f x :=
clifford_algebra.lift_ι_apply f _ x
@[simp]
theorem lift_unique (f : M →ₗ[R] A) (cond : ∀ m, f m * f m = 0)
(g : exterior_algebra R M →ₐ[R] A) : g.to_linear_map.comp (ι R) = f ↔ g = lift R ⟨f, cond⟩ :=
clifford_algebra.lift_unique f _ _
variables {R M}
@[simp]
theorem lift_comp_ι (g : exterior_algebra R M →ₐ[R] A) :
lift R ⟨g.to_linear_map.comp (ι R), comp_ι_sq_zero _⟩ = g :=
clifford_algebra.lift_comp_ι g
/-- See note [partially-applied ext lemmas]. -/
@[ext]
theorem hom_ext {f g : exterior_algebra R M →ₐ[R] A}
(h : f.to_linear_map.comp (ι R) = g.to_linear_map.comp (ι R)) : f = g :=
clifford_algebra.hom_ext h
/-- If `C` holds for the `algebra_map` of `r : R` into `exterior_algebra R M`, the `ι` of `x : M`,
and is preserved under addition and muliplication, then it holds for all of `exterior_algebra R M`.
-/
@[elab_as_eliminator]
lemma induction {C : exterior_algebra R M → Prop}
(h_grade0 : ∀ r, C (algebra_map R (exterior_algebra R M) r))
(h_grade1 : ∀ x, C (ι R x))
(h_mul : ∀ a b, C a → C b → C (a * b))
(h_add : ∀ a b, C a → C b → C (a + b))
(a : exterior_algebra R M) :
C a :=
clifford_algebra.induction h_grade0 h_grade1 h_mul h_add a
/-- The left-inverse of `algebra_map`. -/
def algebra_map_inv : exterior_algebra R M →ₐ[R] R :=
exterior_algebra.lift R ⟨(0 : M →ₗ[R] R), λ m, by simp⟩
variables (M)
lemma algebra_map_left_inverse :
function.left_inverse algebra_map_inv (algebra_map R $ exterior_algebra R M) :=
λ x, by simp [algebra_map_inv]
@[simp] lemma algebra_map_inj (x y : R) :
algebra_map R (exterior_algebra R M) x = algebra_map R (exterior_algebra R M) y ↔ x = y :=
(algebra_map_left_inverse M).injective.eq_iff
@[simp] lemma algebra_map_eq_zero_iff (x : R) :
algebra_map R (exterior_algebra R M) x = 0 ↔ x = 0 :=
map_eq_zero_iff (algebra_map _ _) (algebra_map_left_inverse _).injective
@[simp] lemma algebra_map_eq_one_iff (x : R) : algebra_map R (exterior_algebra R M) x = 1 ↔ x = 1 :=
map_eq_one_iff (algebra_map _ _) (algebra_map_left_inverse _).injective
lemma is_unit_algebra_map (r : R) : is_unit (algebra_map R (exterior_algebra R M) r) ↔ is_unit r :=
is_unit_map_of_left_inverse _ (algebra_map_left_inverse M)
/-- Invertibility in the exterior algebra is the same as invertibility of the base ring. -/
@[simps]
def invertible_algebra_map_equiv (r : R) :
invertible (algebra_map R (exterior_algebra R M) r) ≃ invertible r :=
invertible_equiv_of_left_inverse _ _ _ (algebra_map_left_inverse M)
variables {M}
/-- The canonical map from `exterior_algebra R M` into `triv_sq_zero_ext R M` that sends
`exterior_algebra.ι` to `triv_sq_zero_ext.inr`. -/
def to_triv_sq_zero_ext : exterior_algebra R M →ₐ[R] triv_sq_zero_ext R M :=
lift R ⟨triv_sq_zero_ext.inr_hom R M, λ m, triv_sq_zero_ext.inr_mul_inr R m m⟩
@[simp] lemma to_triv_sq_zero_ext_ι (x : M) :
to_triv_sq_zero_ext (ι R x) = triv_sq_zero_ext.inr x :=
lift_ι_apply _ _ _ _
/-- The left-inverse of `ι`.
As an implementation detail, we implement this using `triv_sq_zero_ext` which has a suitable
algebra structure. -/
def ι_inv : exterior_algebra R M →ₗ[R] M :=
(triv_sq_zero_ext.snd_hom R M).comp to_triv_sq_zero_ext.to_linear_map
lemma ι_left_inverse : function.left_inverse ι_inv (ι R : M → exterior_algebra R M) :=
λ x, by simp [ι_inv]
variables (R)
@[simp] lemma ι_inj (x y : M) : ι R x = ι R y ↔ x = y :=
ι_left_inverse.injective.eq_iff
variables {R}
@[simp] lemma ι_eq_zero_iff (x : M) : ι R x = 0 ↔ x = 0 :=
by rw [←ι_inj R x 0, linear_map.map_zero]
@[simp] lemma ι_eq_algebra_map_iff (x : M) (r : R) : ι R x = algebra_map R _ r ↔ x = 0 ∧ r = 0 :=
begin
refine ⟨λ h, _, _⟩,
{ have hf0 : to_triv_sq_zero_ext (ι R x) = (0, x), from to_triv_sq_zero_ext_ι _,
rw [h, alg_hom.commutes] at hf0,
have : r = 0 ∧ 0 = x := prod.ext_iff.1 hf0,
exact this.symm.imp_left eq.symm, },
{ rintro ⟨rfl, rfl⟩,
rw [linear_map.map_zero, ring_hom.map_zero] }
end
@[simp] lemma ι_ne_one [nontrivial R] (x : M) : ι R x ≠ 1 :=
begin
rw [←(algebra_map R (exterior_algebra R M)).map_one, ne.def, ι_eq_algebra_map_iff],
exact one_ne_zero ∘ and.right,
end
/-- The generators of the exterior algebra are disjoint from its scalars. -/
lemma ι_range_disjoint_one :
disjoint (linear_map.range (ι R : M →ₗ[R] exterior_algebra R M))
(1 : submodule R (exterior_algebra R M)) :=
begin
rw submodule.disjoint_def,
rintros _ ⟨x, hx⟩ ⟨r, (rfl : algebra_map _ _ _ = _)⟩,
rw ι_eq_algebra_map_iff x at hx,
rw [hx.2, ring_hom.map_zero]
end
@[simp]
lemma ι_add_mul_swap (x y : M) : ι R x * ι R y + ι R y * ι R x = 0 :=
calc _ = ι R (x + y) * ι R (x + y) : by simp [mul_add, add_mul]
... = _ : ι_sq_zero _
lemma ι_mul_prod_list {n : ℕ} (f : fin n → M) (i : fin n) :
(ι R $ f i) * (list.of_fn $ λ i, ι R $ f i).prod = 0 :=
begin
induction n with n hn,
{ exact i.elim0, },
{ rw [list.of_fn_succ, list.prod_cons, ←mul_assoc],
by_cases h : i = 0,
{ rw [h, ι_sq_zero, zero_mul], },
{ replace hn := congr_arg ((*) $ ι R $ f 0) (hn (λ i, f $ fin.succ i) (i.pred h)),
simp only at hn,
rw [fin.succ_pred, ←mul_assoc, mul_zero] at hn,
refine (eq_zero_iff_eq_zero_of_add_eq_zero _).mp hn,
rw [← add_mul, ι_add_mul_swap, zero_mul], } }
end
variables (R)
/-- The product of `n` terms of the form `ι R m` is an alternating map.
This is a special case of `multilinear_map.mk_pi_algebra_fin`, and the exterior algebra version of
`tensor_algebra.tprod`. -/
def ι_multi (n : ℕ) : alternating_map R M (exterior_algebra R M) (fin n) :=
let F := (multilinear_map.mk_pi_algebra_fin R n (exterior_algebra R M)).comp_linear_map (λ i, ι R)
in
{ map_eq_zero_of_eq' := λ f x y hfxy hxy, begin
rw [multilinear_map.comp_linear_map_apply, multilinear_map.mk_pi_algebra_fin_apply],
wlog h : x < y := lt_or_gt_of_ne hxy using x y,
clear hxy,
induction n with n hn generalizing x y,
{ exact x.elim0, },
{ rw [list.of_fn_succ, list.prod_cons],
by_cases hx : x = 0,
-- one of the repeated terms is on the left
{ rw hx at hfxy h,
rw [hfxy, ←fin.succ_pred y (ne_of_lt h).symm],
exact ι_mul_prod_list (f ∘ fin.succ) _, },
-- ignore the left-most term and induct on the remaining ones, decrementing indices
{ convert mul_zero _,
refine hn (λ i, f $ fin.succ i)
(x.pred hx) (y.pred (ne_of_lt $ lt_of_le_of_lt x.zero_le h).symm)
(fin.pred_lt_pred_iff.mpr h) _,
simp only [fin.succ_pred],
exact hfxy, } }
end,
to_fun := F, ..F}
variables {R}
lemma ι_multi_apply {n : ℕ} (v : fin n → M) :
ι_multi R n v = (list.of_fn $ λ i, ι R (v i)).prod := rfl
@[simp] lemma ι_multi_zero_apply (v : fin 0 → M) : ι_multi R 0 v = 1 := rfl
@[simp] lemma ι_multi_succ_apply {n : ℕ} (v : fin n.succ → M) :
ι_multi R _ v = ι R (v 0) * ι_multi R _ (matrix.vec_tail v):=
(congr_arg list.prod (list.of_fn_succ _)).trans list.prod_cons
lemma ι_multi_succ_curry_left {n : ℕ} (m : M) :
(ι_multi R n.succ).curry_left m =
(linear_map.mul_left R (ι R m)).comp_alternating_map (ι_multi R n) :=
alternating_map.ext $ λ v, (ι_multi_succ_apply _).trans $ begin
simp_rw matrix.tail_cons,
refl,
end
end exterior_algebra
namespace tensor_algebra
variables {R M}
/-- The canonical image of the `tensor_algebra` in the `exterior_algebra`, which maps
`tensor_algebra.ι R x` to `exterior_algebra.ι R x`. -/
def to_exterior : tensor_algebra R M →ₐ[R] exterior_algebra R M :=
tensor_algebra.lift R (exterior_algebra.ι R : M →ₗ[R] exterior_algebra R M)
@[simp] lemma to_exterior_ι (m : M) : (tensor_algebra.ι R m).to_exterior = exterior_algebra.ι R m :=
by simp [to_exterior]
end tensor_algebra
|
085ee8c556b7e25b6f6fc0c21908d00607c129ea | b3fced0f3ff82d577384fe81653e47df68bb2fa1 | /src/analysis/calculus/mean_value.lean | d9aa219e771e799048dd599f0deb0d4dadf6708d | [
"Apache-2.0"
] | permissive | ratmice/mathlib | 93b251ef5df08b6fd55074650ff47fdcc41a4c75 | 3a948a6a4cd5968d60e15ed914b1ad2f4423af8d | refs/heads/master | 1,599,240,104,318 | 1,572,981,183,000 | 1,572,981,183,000 | 219,830,178 | 0 | 0 | Apache-2.0 | 1,572,980,897,000 | 1,572,980,896,000 | null | UTF-8 | Lean | false | false | 7,663 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
The mean value inequality: a bound on the derivative of a function implies that this function
is Lipschitz continuous for the same bound.
-/
import analysis.calculus.deriv
set_option class.instance_max_depth 100
variables {E : Type*} [normed_group E] [normed_space ℝ E]
{F : Type*} [normed_group F] [normed_space ℝ F]
open metric set lattice asymptotics continuous_linear_map
/-- The mean value theorem along a segment: a bound on the derivative of a function along a segment
implies a bound on the distance of the endpoints images -/
theorem norm_image_sub_le_of_norm_deriv_le_segment {f : ℝ → F} {C : ℝ}
(hf : differentiable_on ℝ f (Icc 0 1))
(bound : ∀t ∈ Icc (0:ℝ) 1, ∥fderiv_within ℝ f (Icc 0 1) t∥ ≤ C) :
∥f 1 - f 0∥ ≤ C :=
begin
/- Let D > C. We will show that, for all t ∈ [0,1], one has ∥f t - f 0∥ ≤ D * t. This is true
for t=0. Let k be maximal in [0,1] for which this holds. By continuity of all functions, the
maximum is realized. If k were <1, then a point x slightly to its right would satisfy
∥f x - f k∥ ≤ D * (k-x), since the differential of f at k has norm at most C < D. Therefore,
the point x also satisfies ∥f x - f 0∥ ≤ D * x, contradicting the maximality of k. Hence, k = 1. -/
refine le_of_forall_le_of_dense (λD hD, _),
let K := {t ∈ Icc (0 : ℝ) 1 | ∥f t - f 0∥ ≤ D * t},
let k := Sup K,
have k_mem_K : k ∈ K,
{ refine cSup_mem_of_is_closed _ _ _,
show K ≠ ∅,
{ have : (0 : ℝ) ∈ K, by simp [K, le_refl, zero_le_one],
apply ne_empty_of_mem this },
show bdd_above K, from ⟨1, λy hy, hy.1.2⟩,
have A : continuous_on (λt:ℝ, (∥f t - f 0∥, D * t)) (Icc 0 1),
{ apply continuous_on.prod,
{ refine continuous_norm.comp_continuous_on _,
apply continuous_on.sub hf.continuous_on continuous_on_const },
{ exact (continuous_mul continuous_const continuous_id).continuous_on } },
show is_closed K, from
A.preimage_closed_of_closed is_closed_Icc (ordered_topology.is_closed_le' _) },
have : k = 1,
{ by_contradiction k_ne_1,
have k_lt_1 : k < 1 := lt_of_le_of_ne k_mem_K.1.2 k_ne_1,
have : 0 ≤ k := k_mem_K.1.1,
let g := fderiv_within ℝ f (Icc 0 1) k,
let h := λx, f x - f k - g (x-k),
have : is_o (λ x, h x) (λ x, x - k) (nhds_within k (Icc 0 1)) :=
(hf k k_mem_K.1).has_fderiv_within_at,
have : {x | ∥h x∥ ≤ (D-C) * ∥x-k∥} ∈ nhds_within k (Icc 0 1) :=
this (D-C) (sub_pos_of_lt hD),
rcases (mem_nhds_within _ _ _).1 this with ⟨s, s_open, ks, hs⟩,
rcases is_open_iff.1 s_open k ks with ⟨ε, εpos, hε⟩,
change 0 < ε at εpos,
let δ := min ε (1-k),
have δpos : 0 < δ, by simp [δ, εpos, k_lt_1],
let x := k + δ/2,
have k_lt_x : k < x, by { simp only [x], linarith },
have x_lt_1 : x < 1 := calc
x < k + δ : add_lt_add_left (half_lt_self δpos) _
... ≤ k + (1-k) : add_le_add_left (min_le_right _ _) _
... = 1 : by ring,
have xε : x ∈ ball k ε,
{ simp [dist, x, abs_of_nonneg (le_of_lt (half_pos δpos))],
exact lt_of_lt_of_le (half_lt_self δpos) (min_le_left _ _) },
have xI : x ∈ Icc (0:ℝ) 1 :=
⟨le_of_lt (lt_of_le_of_lt (k_mem_K.1.1) k_lt_x), le_of_lt x_lt_1⟩,
have Ih : ∥h x∥ ≤ (D - C) * ∥x - k∥ :=
hs ⟨hε xε, xI⟩,
have I : ∥f x - f k∥ ≤ D * (x-k) := calc
∥f x - f k∥ = ∥g (x-k) + h x∥ : by { congr' 1, simp only [h], abel }
... ≤ ∥g (x-k)∥ + ∥h x∥ : norm_triangle _ _
... ≤ ∥g∥ * ∥x-k∥ + (D-C) * ∥x-k∥ : add_le_add (g.le_op_norm _) Ih
... ≤ C * ∥x-k∥ + (D-C) * ∥x-k∥ :
add_le_add_right (mul_le_mul_of_nonneg_right (bound k k_mem_K.1) (norm_nonneg _)) _
... = D * ∥x-k∥ : by ring
... = D * (x-k) : by simp [norm, abs_of_nonneg (le_of_lt (half_pos δpos))],
have : ∥f x - f 0∥ ≤ D * x := calc
∥f x - f 0∥ = ∥(f x - f k) + (f k - f 0)∥ : by { congr' 1, abel }
... ≤ ∥f x - f k∥ + ∥f k - f 0∥ : norm_triangle _ _
... ≤ D * (x - k) + D * k : add_le_add I (k_mem_K.2)
... = D * x : by ring,
have xK : x ∈ K := ⟨xI, this⟩,
have : x ≤ k := le_cSup ⟨1, λy hy, hy.1.2⟩ xK,
exact (not_le_of_lt k_lt_x) this },
rw this at k_mem_K,
simpa [this] using k_mem_K.2
end
/-- The mean value theorem on a convex set: if the derivative of a function is bounded by C, then
the function is C-Lipschitz -/
theorem norm_image_sub_le_of_norm_deriv_le_convex {f : E → F} {C : ℝ} {s : set E} {x y : E}
(hf : differentiable_on ℝ f s) (bound : ∀x∈s, ∥fderiv_within ℝ f s x∥ ≤ C)
(hs : convex s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ :=
begin
/- By composition with t ↦ x + t • (y-x), we reduce to a statement for functions defined
on [0,1], for which it is proved in norm_image_sub_le_of_norm_deriv_le_segment.
We just have to check the differentiability of the composition and bounds on its derivative,
which is straightforward but tedious for lack of automation. -/
have C0 : 0 ≤ C := le_trans (norm_nonneg _) (bound x xs),
let g := λ(t:ℝ), f (x + t • (y-x)),
have D1 : differentiable ℝ (λt:ℝ, x + t • (y-x)) :=
differentiable.add (differentiable_const _)
(differentiable.smul' differentiable_id (differentiable_const _)),
have segm : (λ (t : ℝ), x + t • (y - x)) '' Icc 0 1 ⊆ s,
by { rw image_Icc_zero_one_eq_segment, apply (convex_segment_iff _).1 hs x y xs ys },
have : f x = g 0, by { simp only [g], rw [zero_smul, add_zero] },
rw this,
have : f y = g 1, by { simp only [g], rw one_smul, congr' 1, abel },
rw this,
apply norm_image_sub_le_of_norm_deriv_le_segment
(hf.comp D1.differentiable_on (image_subset_iff.1 segm)) (λt ht, _),
/- It remains to check that the derivative of g is bounded by C ∥y-x∥ at any t ∈ [0,1] -/
have t_s : x + t • (y-x) ∈ s := segm (mem_image_of_mem _ ht),
simp only [g],
/- Expand the derivative of the composition, and bound its norm by the product of the norms -/
rw fderiv_within.comp t (hf _ t_s) ((D1 t).differentiable_within_at) (image_subset_iff.1 segm)
(unique_diff_on_Icc_zero_one t ht),
refine le_trans (op_norm_comp_le _ _) (mul_le_mul (bound _ t_s) _ (norm_nonneg _) C0),
have : fderiv_within ℝ (λ (t : ℝ), x + t • (y - x)) (Icc 0 1) t =
(id : ℝ →L[ℝ] ℝ).smul_right (y - x) := calc
fderiv_within ℝ (λ (t : ℝ), x + t • (y - x)) (Icc 0 1) t
= fderiv ℝ (λ (t : ℝ), x + t • (y - x)) t :
differentiable.fderiv_within (D1 t) (unique_diff_on_Icc_zero_one t ht)
... = fderiv ℝ (λ (t : ℝ), x) t + fderiv ℝ (λ (t : ℝ), t • (y-x)) t :
fderiv_add (differentiable_at_const _) ((differentiable.smul' differentiable_id (differentiable_const _)) t)
... = fderiv ℝ (λ (t : ℝ), t • (y-x)) t :
by rw [fderiv_const, zero_add]
... = t • fderiv ℝ (λ (t : ℝ), (y-x)) t + (fderiv ℝ id t).smul_right (y - x) :
fderiv_smul' differentiable_at_id (differentiable_at_const _)
... = (id : ℝ →L[ℝ] ℝ).smul_right (y - x) :
by rw [fderiv_const, smul_zero, zero_add, fderiv_id],
rw [this, smul_right_norm],
calc ∥(id : ℝ →L[ℝ] ℝ)∥ * ∥y - x∥ ≤ 1 * ∥y-x∥ :
mul_le_mul_of_nonneg_right norm_id (norm_nonneg _)
... = ∥y - x∥ : one_mul _
end
|
fc107273b1d483be6208ed31d0be2c696b7b60b9 | a523fc1740c8cb84cd0fa0f4b52a760da4e32a5c | /src/missing_mathlib/algebra/ring.lean | 1e4caadedc8a6d70e39469b30c78a1bf3d120fb8 | [] | no_license | abentkamp/spectral | a1aff51e85d30b296a81d256ced1d382345d3396 | 751645679ef1cb6266316349de9e492eff85484c | refs/heads/master | 1,669,994,798,064 | 1,597,591,646,000 | 1,597,591,646,000 | 287,544,072 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 108 | lean | import algebra.ring
universes u v
variable {α : Type u}
section domain
variable [domain α]
end domain |
7263fb112483eadac7ea6bd6b7a480e45b908fda | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/pp_links.lean | f9d1d579f6da1b377709285b0570263e070be649 | [
"Apache-2.0"
] | permissive | leanprover-community/lean | 12b87f69d92e614daea8bcc9d4de9a9ace089d0e | cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0 | refs/heads/master | 1,687,508,156,644 | 1,684,951,104,000 | 1,684,951,104,000 | 169,960,991 | 457 | 107 | Apache-2.0 | 1,686,744,372,000 | 1,549,790,268,000 | C++ | UTF-8 | Lean | false | false | 292 | lean | open tactic
structure point (α : Type*) :=
(x : α) (y : α)
example : ∀ i : ℤ, (i, i).snd = i + 0 + (point.mk 0 i).x := by do
os ← get_options,
set_options (os.set_bool `pp.links tt)
example : ∃ i j : ℤ, true := by do
os ← get_options,
set_options (os.set_bool `pp.links tt)
|
3565b73ef41304f339b1c45ea4c939bdfe430c03 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/meta/expr_lens_auto.lean | ce91b336a0326a12386f209d39d39d9e4b681444 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,765 | lean | /-
Copyright (c) 2020 Keeley Hoek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Keeley Hoek, Scott Morrison
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.meta.expr
import Mathlib.PostPort
universes l
namespace Mathlib
/-!
# A lens for zooming into nested `expr` applications
A "lens" for looking into the subterms of an expression, tracking where we've been, so that
when we "zoom out" after making a change we know exactly which order of `congr_fun`s and
`congr_arg`s we need to make things work.
This file defines the `expr_lens` inductive type, defines basic operations this type, and defines a
useful map-like function `expr.app_map` on `expr`s which maps over applications.
This file is for non-tactics.
## Tags
expr, expr_lens, congr, environment, meta, metaprogramming, tactic
-/
/-! ### Declarations about `expr_lens` -/
/-- You're supposed to think of an `expr_lens` as a big set of nested applications with a single
hole which needs to be filled, either in a function spot or argument spot. `expr_lens.fill` can
fill this hole and turn your lens back into a real `expr`. -/
namespace expr_lens
/-- Inductive type with two constructors `F` and `A`,
that represent the function-part `f` and arg-part `a` of an application `f a`. They specify the
directions in which an `expr_lens` should zoom into an `expr`.
This type is used in the development of rewriting tactics such as `nth_rewrite` and
`rewrite_search`. -/
inductive dir where
| F : dir
| A : dir
/-- String representation of `dir`. -/
def dir.to_string : dir → string := sorry
protected instance dir.has_to_string : has_to_string dir := has_to_string.mk dir.to_string
end Mathlib |
e2748636ba4cb0f5ef66bc8c41c346405aac8132 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /test/norm_cast_coe_fn.lean | 3942e367604f87ccecd90f441c21ef2b67146efa | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 767 | lean | import tactic.norm_cast
structure hom (α β : Type) :=
(to_fun : α → β)
instance {α β} : has_coe_to_fun (hom α β) :=
⟨_, hom.to_fun⟩
structure hom_plus (α β) extends hom α β
instance {α β} : has_coe (hom_plus α β) (hom α β) :=
⟨hom_plus.to_hom⟩
instance {α β} : has_coe_to_fun (hom_plus α β) :=
⟨λ _, α → β, λ f, f⟩
@[norm_cast] lemma hom_plus.coe_fn (α β : Type) (a : α) (h : hom_plus α β) :
(h : hom α β) a = h a :=
rfl
example (α β : Type) (a : α) (h : hom_plus α β) :
(h : hom α β) a = h a :=
by norm_cast
def f1 (n : ℕ) : hom_plus ℕ ℕ := ⟨⟨λ m, m + n⟩⟩
def f2 : hom ℕ (hom ℕ ℕ) := ⟨λ n, f1 n⟩
@[norm_cast] lemma coe_f1 (n : ℕ) :
(f1 n : hom ℕ ℕ) = f2 n :=
rfl
|
6860d2568511bc1fc794bbd0acc3212b392301f9 | 4bddde0d06fbd53be6f23d7f5899998e8f63410b | /test/test.lean | bafdf7950720aebcf1fae00576ecdcc3af03cbd5 | [] | no_license | khoek/libiconfig | 4816290a5862af14b07683b3d2663e8e62832ef4 | 6f55c50bc5d852d26ee5ee4c5b52b2cda2a852e5 | refs/heads/master | 1,586,109,683,212 | 1,559,567,916,000 | 1,559,567,916,000 | 157,085,466 | 0 | 1 | null | 1,559,567,917,000 | 1,541,945,134,000 | Lean | UTF-8 | Lean | false | false | 605 | lean | import tactic.iconfig
section
iconfig_mk my_tac
set_option formatter.hide_full_terms false
iconfig_add my_tac [
abool : bool, -- (TODO:) := tt ! iconfig.overload_policy.ignore⟩,
anum : nat,
aenum : enat,
astr : string,
aident : name,
]
end
namespace tactic
namespace interactive
meta def cfgdump (c : iconfig my_tac) : tactic unit := do
l ← iconfig.read c,
l.bool "abool" >>= tactic.trace,
return ()
end interactive
end tactic
example : tt := begin
cfgdump {
abool := ff,
anum := 113,
aenum := inf,
astr := "ello",
aident s.sss4,
},
simp
end
|
536390f64ad32808400627be8084415d85fa5cdf | 491068d2ad28831e7dade8d6dff871c3e49d9431 | /library/theories/group_theory/finsubg.lean | 7074531ff4f2c264df8a19ca8d36560c7878aef9 | [
"Apache-2.0"
] | permissive | davidmueller13/lean | 65a3ed141b4088cd0a268e4de80eb6778b21a0e9 | c626e2e3c6f3771e07c32e82ee5b9e030de5b050 | refs/heads/master | 1,611,278,313,401 | 1,444,021,177,000 | 1,444,021,177,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 20,702 | lean | /-
Copyright (c) 2015 Haitao Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author : Haitao Zhang
-/
-- develop the concept of finite subgroups based on finsets so that the properties
-- can be used directly without translating from the set based theory first
import data algebra.group .subgroup
open function algebra finset
-- ⁻¹ in eq.ops conflicts with group ⁻¹
open eq.ops
namespace group
open ops
section subg
-- we should be able to prove properties using finsets directly
variable {G : Type}
variable [ambientG : group G]
include ambientG
definition finset_mul_closed_on [reducible] (H : finset G) : Prop :=
∀ x y : G, x ∈ H → y ∈ H → x * y ∈ H
definition finset_has_inv (H : finset G) : Prop :=
∀ a : G, a ∈ H → a⁻¹ ∈ H
structure is_finsubg [class] (H : finset G) : Type :=
(has_one : 1 ∈ H)
(mul_closed : finset_mul_closed_on H)
(has_inv : finset_has_inv H)
definition univ_is_finsubg [instance] [finG : fintype G] : is_finsubg (@finset.univ G _) :=
is_finsubg.mk !mem_univ (λ x y Px Py, !mem_univ) (λ a Pa, !mem_univ)
definition one_is_finsubg [instance] : is_finsubg (singleton (1:G)) :=
is_finsubg.mk !mem_singleton
(λ x y Px Py, by rewrite [eq_of_mem_singleton Px, eq_of_mem_singleton Py, one_mul]; apply mem_singleton)
(λ x Px, by rewrite [eq_of_mem_singleton Px, one_inv]; apply mem_singleton)
lemma finsubg_has_one (H : finset G) [h : is_finsubg H] : 1 ∈ H :=
@is_finsubg.has_one G _ H h
lemma finsubg_mul_closed (H : finset G) [h : is_finsubg H] {x y : G} : x ∈ H → y ∈ H → x * y ∈ H :=
@is_finsubg.mul_closed G _ H h x y
lemma finsubg_has_inv (H : finset G) [h : is_finsubg H] {a : G} : a ∈ H → a⁻¹ ∈ H :=
@is_finsubg.has_inv G _ H h a
variable [deceqG : decidable_eq G]
include deceqG
definition finsubg_to_subg [instance] {H : finset G} [h : is_finsubg H]
: is_subgroup (ts H) :=
is_subgroup.mk
(mem_eq_mem_to_set H 1 ▸ finsubg_has_one H)
(take x y, begin repeat rewrite -mem_eq_mem_to_set,
apply finsubg_mul_closed H end)
(take a, begin repeat rewrite -mem_eq_mem_to_set,
apply finsubg_has_inv H end)
open nat
lemma finsubg_eq_singleton_one_of_card_one {H : finset G} [h : is_finsubg H] :
card H = 1 → H = singleton 1 :=
assume Pcard, eq.symm (eq_of_card_eq_of_subset (by rewrite [Pcard])
(subset_of_forall take g,
by rewrite [mem_singleton_eq]; intro Pg; rewrite Pg; exact finsubg_has_one H))
end subg
section fin_lcoset
open set
variable {A : Type}
variable [deceq : decidable_eq A]
include deceq
variable [s : group A]
include s
definition fin_lcoset (H : finset A) (a : A) := finset.image (lmul_by a) H
definition fin_rcoset (H : finset A) (a : A) : finset A := image (rmul_by a) H
definition fin_lcosets (H G : finset A) := image (fin_lcoset H) G
definition fin_inv : finset A → finset A := image has_inv.inv
variable {H : finset A}
lemma lmul_rmul {a b : A} : (lmul_by a) ∘ (rmul_by b) = (rmul_by b) ∘ (lmul_by a) :=
funext take c, calc a*(c*b) = (a*c)*b : mul.assoc
lemma fin_lrcoset_comm {a b : A} :
fin_lcoset (fin_rcoset H b) a = fin_rcoset (fin_lcoset H a) b :=
by esimp [fin_lcoset, fin_rcoset]; rewrite [-*image_compose, lmul_rmul]
lemma inv_mem_fin_inv {a : A} : a ∈ H → a⁻¹ ∈ fin_inv H :=
assume Pin, mem_image Pin rfl
lemma fin_lcoset_eq (a : A) : ts (fin_lcoset H a) = a ∘> (ts H) := calc
ts (fin_lcoset H a) = coset.l a (ts H) : to_set_image
... = a ∘> (ts H) : glcoset_eq_lcoset
lemma fin_lcoset_id : fin_lcoset H 1 = H :=
by rewrite [eq_eq_to_set_eq, fin_lcoset_eq, glcoset_id]
lemma fin_lcoset_compose (a b : A) : fin_lcoset (fin_lcoset H b) a = fin_lcoset H (a*b) :=
to_set.inj (by rewrite [*fin_lcoset_eq, glcoset_compose])
lemma fin_lcoset_inv (a : A) : fin_lcoset (fin_lcoset H a) a⁻¹ = H :=
to_set.inj (by rewrite [*fin_lcoset_eq, glcoset_inv])
lemma fin_lcoset_card (a : A) : card (fin_lcoset H a) = card H :=
card_image_eq_of_inj_on (lmul_inj_on a (ts H))
lemma fin_lcosets_card_eq {G : finset A} : ∀ gH, gH ∈ fin_lcosets H G → card gH = card H :=
take gH, assume Pcosets, obtain g Pg, from exists_of_mem_image Pcosets,
and.right Pg ▸ fin_lcoset_card g
variable [is_finsubgH : is_finsubg H]
include is_finsubgH
lemma fin_lcoset_same (x a : A) : x ∈ (fin_lcoset H a) = (fin_lcoset H x = fin_lcoset H a) :=
begin
rewrite mem_eq_mem_to_set,
rewrite [eq_eq_to_set_eq, *(fin_lcoset_eq x), fin_lcoset_eq a],
exact (subg_lcoset_same x a)
end
lemma fin_mem_lcoset (g : A) : g ∈ fin_lcoset H g :=
have P : g ∈ g ∘> ts H, from and.left (subg_in_coset_refl g),
assert P1 : g ∈ ts (fin_lcoset H g), from eq.symm (fin_lcoset_eq g) ▸ P,
eq.symm (mem_eq_mem_to_set _ g) ▸ P1
lemma fin_lcoset_subset {S : finset A} (Psub : S ⊆ H) : ∀ x, x ∈ H → fin_lcoset S x ⊆ H :=
assert Psubs : set.subset (ts S) (ts H), from subset_eq_to_set_subset S H ▸ Psub,
take x, assume Pxs : x ∈ ts H,
assert Pcoset : set.subset (x ∘> ts S) (ts H), from subg_lcoset_subset_subg Psubs x Pxs,
by rewrite [subset_eq_to_set_subset, fin_lcoset_eq x]; exact Pcoset
lemma finsubg_lcoset_id {a : A} : a ∈ H → fin_lcoset H a = H :=
by rewrite [eq_eq_to_set_eq, fin_lcoset_eq, mem_eq_mem_to_set]; apply subgroup_lcoset_id
lemma finsubg_inv_lcoset_eq_rcoset {a : A} :
fin_inv (fin_lcoset H a) = fin_rcoset H a⁻¹ :=
begin
esimp [fin_inv, fin_lcoset, fin_rcoset],
rewrite [-image_compose],
apply ext, intro b,
rewrite [*mem_image_iff, ↑compose, ↑lmul_by, ↑rmul_by],
apply iff.intro,
intro Pl, cases Pl with h Ph, cases Ph with Pin Peq,
existsi h⁻¹, apply and.intro,
exact finsubg_has_inv H Pin,
rewrite [-mul_inv, Peq],
intro Pr, cases Pr with h Ph, cases Ph with Pin Peq,
existsi h⁻¹, apply and.intro,
exact finsubg_has_inv H Pin,
rewrite [mul_inv, inv_inv, Peq],
end
lemma finsubg_conj_closed {g h : A} : g ∈ H → h ∈ H → g ∘c h ∈ H :=
assume Pgin Phin, finsubg_mul_closed H (finsubg_mul_closed H Pgin Phin) (finsubg_has_inv H Pgin)
variable {G : finset A}
variable [is_finsubgG : is_finsubg G]
include is_finsubgG
open finset.partition
definition fin_lcoset_partition_subg (Psub : H ⊆ G) :=
partition.mk G (fin_lcoset H) fin_lcoset_same
(restriction_imp_union (fin_lcoset H) fin_lcoset_same (fin_lcoset_subset Psub))
open nat
theorem lagrange_theorem (Psub : H ⊆ G) : card G = card (fin_lcosets H G) * card H := calc
card G = nat.finset.Sum (fin_lcosets H G) card : class_equation (fin_lcoset_partition_subg Psub)
... = nat.finset.Sum (fin_lcosets H G) (λ x, card H) : nat.finset.Sum_ext (take g P, fin_lcosets_card_eq g P)
... = card (fin_lcosets H G) * card H : Sum_const_eq_card_mul
end fin_lcoset
section
open fintype list subtype
lemma dinj_tag {A : Type} (P : A → Prop) : dinj P tag :=
take a₁ a₂ Pa₁ Pa₂ Pteq, subtype.no_confusion Pteq (λ Pe Pqe, Pe)
open nat
lemma card_pos {A : Type} [ambientA : group A] [finA : fintype A] : 0 < card A :=
length_pos_of_mem (mem_univ 1)
end
section lcoset_fintype
open fintype list subtype
variables {A : Type} [ambientA : group A] [finA : fintype A] [deceqA : decidable_eq A]
include ambientA deceqA finA
variables G H : finset A
definition is_fin_lcoset [reducible] (S : finset A) : Prop :=
∃ g, g ∈ G ∧ fin_lcoset H g = S
definition to_list : list A := list.filter (λ g, g ∈ G) (elems A)
definition list_lcosets : list (finset A) := erase_dup (map (fin_lcoset H) (to_list G))
definition lcoset_type [reducible] : Type := {S : finset A | is_fin_lcoset G H S}
definition all_lcosets : list (lcoset_type G H) :=
dmap (is_fin_lcoset G H) tag (list_lcosets G H)
variables {G H} [finsubgG : is_finsubg G]
include finsubgG
lemma self_is_lcoset : is_fin_lcoset G H H :=
exists.intro 1 (and.intro !finsubg_has_one fin_lcoset_id)
lemma lcoset_subset_of_subset (J : lcoset_type G H) : H ⊆ G → elt_of J ⊆ G :=
assume Psub, obtain j Pjin Pj, from has_property J,
by rewrite [-Pj]; apply fin_lcoset_subset Psub; exact Pjin
variables (G H)
definition lcoset_one : lcoset_type G H := tag H self_is_lcoset
variables {G H}
definition lcoset_lmul {g : A} (Pgin : g ∈ G) (S : lcoset_type G H)
: lcoset_type G H :=
tag (fin_lcoset (elt_of S) g)
(obtain f Pfin Pf, from has_property S,
exists.intro (g*f)
(by apply and.intro;
exact finsubg_mul_closed G Pgin Pfin;
rewrite [-Pf, -fin_lcoset_compose]))
definition lcoset_mul (S₁ S₂ : lcoset_type G H): finset A :=
Union (elt_of S₁) (fin_lcoset (elt_of S₂))
lemma mul_mem_lcoset_mul (J K : lcoset_type G H) {g h} :
g ∈ elt_of J → h ∈ elt_of K → g*h ∈ lcoset_mul J K :=
assume Pg, begin
rewrite [↑lcoset_mul, mem_Union_iff, ↑fin_lcoset],
intro Ph, existsi g, apply and.intro, exact Pg,
rewrite [mem_image_iff, ↑lmul_by],
existsi h, exact and.intro Ph rfl
end
lemma is_lcoset_of_mem_list_lcosets {S : finset A}
: S ∈ list_lcosets G H → is_fin_lcoset G H S :=
assume Pin, obtain g Pgin Pg, from exists_of_mem_map (mem_of_mem_erase_dup Pin),
exists.intro g (and.intro (of_mem_filter Pgin) Pg)
lemma mem_list_lcosets_of_is_lcoset {S : finset A}
: is_fin_lcoset G H S → S ∈ list_lcosets G H :=
assume Plcoset, obtain g Pgin Pg, from Plcoset,
Pg ▸ mem_erase_dup (mem_map _ (mem_filter_of_mem (complete g) Pgin))
lemma fin_lcosets_eq :
fin_lcosets H G = to_finset_of_nodup (list_lcosets G H) !nodup_erase_dup :=
ext (take S, iff.intro
(λ Pimg, mem_list_lcosets_of_is_lcoset (exists_of_mem_image Pimg))
(λ Pl, obtain g Pg, from is_lcoset_of_mem_list_lcosets Pl,
iff.elim_right !mem_image_iff (is_lcoset_of_mem_list_lcosets Pl)))
lemma length_all_lcosets : length (all_lcosets G H) = card (fin_lcosets H G) :=
eq.trans
(show length (all_lcosets G H) = length (list_lcosets G H), from
assert Pmap : map elt_of (all_lcosets G H) = list_lcosets G H, from
map_dmap_of_inv_of_pos (λ S P, rfl) (λ S, is_lcoset_of_mem_list_lcosets),
by rewrite[-Pmap, length_map])
(by rewrite fin_lcosets_eq)
lemma lcoset_lmul_compose {f g : A} (Pf : f ∈ G) (Pg : g ∈ G) (S : lcoset_type G H) :
lcoset_lmul Pf (lcoset_lmul Pg S) = lcoset_lmul (finsubg_mul_closed G Pf Pg) S :=
subtype.eq !fin_lcoset_compose
lemma lcoset_lmul_one (S : lcoset_type G H) : lcoset_lmul !finsubg_has_one S = S :=
subtype.eq fin_lcoset_id
lemma lcoset_lmul_inv {g : A} {Pg : g ∈ G} (S : lcoset_type G H) :
lcoset_lmul (finsubg_has_inv G Pg) (lcoset_lmul Pg S) = S :=
subtype.eq (to_set.inj begin
esimp [lcoset_lmul],
rewrite [fin_lcoset_compose, mul.left_inv, fin_lcoset_eq, glcoset_id]
end)
lemma lcoset_lmul_inj {g : A} {Pg : g ∈ G}:
@injective (lcoset_type G H) _ (lcoset_lmul Pg) :=
injective_of_has_left_inverse (exists.intro (lcoset_lmul (finsubg_has_inv G Pg)) lcoset_lmul_inv)
lemma card_elt_of_lcoset_type (S : lcoset_type G H) : card (elt_of S) = card H :=
obtain f Pfin Pf, from has_property S, Pf ▸ fin_lcoset_card f
definition lcoset_fintype [instance] : fintype (lcoset_type G H) :=
fintype.mk (all_lcosets G H)
(dmap_nodup_of_dinj (dinj_tag (is_fin_lcoset G H)) !nodup_erase_dup)
(take s, subtype.destruct s (take S, assume PS, mem_dmap PS (mem_list_lcosets_of_is_lcoset PS)))
lemma card_lcoset_type : card (lcoset_type G H) = card (fin_lcosets H G) :=
length_all_lcosets
open nat nat.finset
variable [finsubgH : is_finsubg H]
include finsubgH
theorem lagrange_theorem' (Psub : H ⊆ G) : card G = card (lcoset_type G H) * card H :=
calc card G = card (fin_lcosets H G) * card H : lagrange_theorem Psub
... = card (lcoset_type G H) * card H : card_lcoset_type
lemma lcoset_disjoint {S₁ S₂ : lcoset_type G H} : S₁ ≠ S₂ → elt_of S₁ ∩ elt_of S₂ = ∅ :=
obtain f₁ Pfin₁ Pf₁, from has_property S₁,
obtain f₂ Pfin₂ Pf₂, from has_property S₂,
assume Pne, inter_eq_empty_of_disjoint (disjoint.intro
take g, begin
rewrite [-Pf₁, -Pf₂, *fin_lcoset_same],
intro Pgf₁, rewrite [Pgf₁, Pf₁, Pf₂],
intro Peq, exact absurd (subtype.eq Peq) Pne
end )
lemma card_Union_lcosets (lcs : finset (lcoset_type G H)) :
card (Union lcs elt_of) = card lcs * card H :=
calc card (Union lcs elt_of) = ∑ lc ∈ lcs, card (elt_of lc) : card_Union_of_disjoint lcs elt_of (λ (S₁ S₂ : lcoset_type G H) P₁ P₂ Pne, lcoset_disjoint Pne)
... = ∑ lc ∈ lcs, card H : Sum_ext (take lc P, card_elt_of_lcoset_type _)
... = card lcs * card H : Sum_const_eq_card_mul
lemma exists_of_lcoset_type (J : lcoset_type G H) :
∃ j, j ∈ elt_of J ∧ fin_lcoset H j = elt_of J :=
obtain j Pjin Pj, from has_property J,
exists.intro j (and.intro (Pj ▸ !fin_mem_lcoset) Pj)
lemma lcoset_not_empty (J : lcoset_type G H) : elt_of J ≠ ∅ :=
obtain j Pjin Pj, from has_property J,
assume Pempty, absurd (by rewrite [-Pempty, -Pj]; apply fin_mem_lcoset) (not_mem_empty j)
end lcoset_fintype
section normalizer
open subtype
variables {G : Type} [ambientG : group G] [finG : fintype G] [deceqG : decidable_eq G]
include ambientG deceqG finG
variable H : finset G
definition normalizer : finset G := {g ∈ univ | ∀ h, h ∈ H → g ∘c h ∈ H}
variable {H}
variable [finsubgH : is_finsubg H]
include finsubgH
lemma subset_normalizer : H ⊆ normalizer H :=
subset_of_forall take g, assume PginH, mem_sep_of_mem !mem_univ
(take h, assume PhinH, finsubg_conj_closed PginH PhinH)
lemma normalizer_has_one : 1 ∈ normalizer H :=
mem_of_subset_of_mem subset_normalizer (finsubg_has_one H)
lemma normalizer_mul_closed : finset_mul_closed_on (normalizer H) :=
take f g, assume Pfin Pgin,
mem_sep_of_mem !mem_univ take h, assume Phin, begin
rewrite [-conj_compose],
apply of_mem_sep Pfin,
apply of_mem_sep Pgin,
exact Phin
end
lemma conj_eq_of_mem_normalizer {g : G} : g ∈ normalizer H → image (conj_by g) H = H :=
assume Pgin,
eq_of_card_eq_of_subset (card_image_eq_of_inj_on (take h j, assume P1 P2, !conj_inj))
(subset_of_forall take h, assume Phin,
obtain j Pjin Pj, from exists_of_mem_image Phin,
begin substvars, apply of_mem_sep Pgin, exact Pjin end)
lemma normalizer_has_inv : finset_has_inv (normalizer H) :=
take g, assume Pgin,
mem_sep_of_mem !mem_univ take h, begin
rewrite [-(conj_eq_of_mem_normalizer Pgin) at {1}, mem_image_iff],
intro Pex, cases Pex with k Pk,
rewrite [-(and.right Pk), conj_compose, mul.left_inv, conj_id],
exact and.left Pk
end
definition normalizer_is_finsubg [instance] : is_finsubg (normalizer H) :=
is_finsubg.mk normalizer_has_one normalizer_mul_closed normalizer_has_inv
lemma lcoset_subset_normalizer (J : lcoset_type (normalizer H) H) :
elt_of J ⊆ normalizer H :=
lcoset_subset_of_subset J subset_normalizer
lemma lcoset_subset_normalizer_of_mem {g : G} :
g ∈ normalizer H → fin_lcoset H g ⊆ normalizer H :=
assume Pgin, fin_lcoset_subset subset_normalizer g Pgin
lemma lrcoset_same_of_mem_normalizer {g : G} :
g ∈ normalizer H → fin_lcoset H g = fin_rcoset H g :=
assume Pg, ext take h, iff.intro
(assume Pl, obtain j Pjin Pj, from exists_of_mem_image Pl,
mem_image (of_mem_sep Pg j Pjin)
(calc g*j*g⁻¹*g = g*j : inv_mul_cancel_right
... = h : Pj))
(assume Pr, obtain j Pjin Pj, from exists_of_mem_image Pr,
mem_image (of_mem_sep (finsubg_has_inv (normalizer H) Pg) j Pjin)
(calc g*(g⁻¹*j*g⁻¹⁻¹) = g*(g⁻¹*j*g) : inv_inv
... = g*(g⁻¹*(j*g)) : mul.assoc
... = j*g : mul_inv_cancel_left
... = h : Pj))
lemma lcoset_mul_eq_lcoset (J K : lcoset_type (normalizer H) H) {g : G} :
g ∈ elt_of J → (lcoset_mul J K) = fin_lcoset (elt_of K) g :=
assume Pgin,
obtain j Pjin Pj, from has_property J,
obtain k Pkin Pk, from has_property K,
Union_const (lcoset_not_empty J) begin
rewrite [-Pk], intro h Phin,
assert Phinn : h ∈ normalizer H,
apply mem_of_subset_of_mem (lcoset_subset_normalizer_of_mem Pjin),
rewrite Pj, assumption,
revert Phin Pgin,
rewrite [-Pj, *fin_lcoset_same],
intro Pheq Pgeq,
rewrite [*(lrcoset_same_of_mem_normalizer Pkin), *fin_lrcoset_comm, Pheq, Pgeq]
end
lemma lcoset_mul_is_lcoset (J K : lcoset_type (normalizer H) H) :
is_fin_lcoset (normalizer H) H (lcoset_mul J K) :=
obtain j Pjin Pj, from has_property J,
obtain k Pkin Pk, from has_property K,
exists.intro (j*k) (and.intro (finsubg_mul_closed _ Pjin Pkin)
begin rewrite [lcoset_mul_eq_lcoset J K (Pj ▸ fin_mem_lcoset j), -fin_lcoset_compose, Pk] end)
lemma lcoset_inv_is_lcoset (J : lcoset_type (normalizer H) H) :
is_fin_lcoset (normalizer H) H (fin_inv (elt_of J)) :=
obtain j Pjin Pj, from has_property J, exists.intro j⁻¹
begin
rewrite [-Pj, finsubg_inv_lcoset_eq_rcoset],
apply and.intro,
apply normalizer_has_inv, assumption,
apply lrcoset_same_of_mem_normalizer, apply normalizer_has_inv, assumption
end
definition fin_coset_mul (J K : lcoset_type (normalizer H) H) : lcoset_type (normalizer H) H :=
tag (lcoset_mul J K) (lcoset_mul_is_lcoset J K)
definition fin_coset_inv (J : lcoset_type (normalizer H) H) : lcoset_type (normalizer H) H :=
tag (fin_inv (elt_of J)) (lcoset_inv_is_lcoset J)
definition fin_coset_one : lcoset_type (normalizer H) H :=
tag H self_is_lcoset
local infix `^` := fin_coset_mul
lemma fin_coset_mul_eq_lcoset (J K : lcoset_type (normalizer H) H) {g : G} :
g ∈ (elt_of J) → elt_of (J ^ K) = fin_lcoset (elt_of K) g :=
assume Pgin, lcoset_mul_eq_lcoset J K Pgin
lemma fin_coset_mul_assoc (J K L : lcoset_type (normalizer H) H) :
J ^ K ^ L = J ^ (K ^ L) :=
obtain j Pjin Pj, from exists_of_lcoset_type J,
obtain k Pkin Pk, from exists_of_lcoset_type K,
assert Pjk : j*k ∈ elt_of (J ^ K), from mul_mem_lcoset_mul J K Pjin Pkin,
obtain l Plin Pl, from has_property L,
subtype.eq (begin
rewrite [fin_coset_mul_eq_lcoset (J ^ K) _ Pjk,
fin_coset_mul_eq_lcoset J _ Pjin,
fin_coset_mul_eq_lcoset K _ Pkin,
-Pl, *fin_lcoset_compose]
end)
lemma fin_coset_mul_one (J : lcoset_type (normalizer H) H) :
J ^ fin_coset_one = J :=
obtain j Pjin Pj, from exists_of_lcoset_type J,
subtype.eq begin
rewrite [↑fin_coset_one, fin_coset_mul_eq_lcoset _ _ Pjin, -Pj]
end
lemma fin_coset_one_mul (J : lcoset_type (normalizer H) H) :
fin_coset_one ^ J = J :=
subtype.eq begin
rewrite [↑fin_coset_one, fin_coset_mul_eq_lcoset _ _ (finsubg_has_one H), fin_lcoset_id]
end
lemma fin_coset_left_inv (J : lcoset_type (normalizer H) H) :
(fin_coset_inv J) ^ J = fin_coset_one :=
obtain j Pjin Pj, from exists_of_lcoset_type J,
assert Pjinv : j⁻¹ ∈ elt_of (fin_coset_inv J), from inv_mem_fin_inv Pjin,
subtype.eq begin
rewrite [↑fin_coset_one, fin_coset_mul_eq_lcoset _ _ Pjinv, -Pj, fin_lcoset_inv]
end
variable (H)
definition fin_coset_group [instance] : group (lcoset_type (normalizer H) H) :=
group.mk fin_coset_mul fin_coset_mul_assoc fin_coset_one fin_coset_one_mul fin_coset_mul_one fin_coset_inv fin_coset_left_inv
variables {H} (Hc : finset (lcoset_type (normalizer H) H))
definition fin_coset_Union : finset G := Union Hc elt_of
variables {Hc} [finsubgHc : is_finsubg Hc]
include finsubgHc
lemma mem_normalizer_of_mem_fcU {j : G} : j ∈ fin_coset_Union Hc → j ∈ normalizer H :=
assume Pjin, obtain J PJ PjJ, from iff.elim_left !mem_Union_iff Pjin,
mem_of_subset_of_mem !lcoset_subset_normalizer PjJ
lemma fcU_has_one : (1:G) ∈ fin_coset_Union Hc :=
iff.elim_right (mem_Union_iff Hc elt_of (1:G))
(exists.intro 1 (and.intro (finsubg_has_one Hc) (finsubg_has_one H)))
lemma fcU_has_inv : finset_has_inv (fin_coset_Union Hc) :=
take j, assume Pjin, obtain J PJ PjJ, from iff.elim_left !mem_Union_iff Pjin,
have PJinv : J⁻¹ ∈ Hc, from finsubg_has_inv Hc PJ,
have Pjinv : j⁻¹ ∈ elt_of J⁻¹, from inv_mem_fin_inv PjJ,
iff.elim_right !mem_Union_iff (exists.intro J⁻¹ (and.intro PJinv Pjinv))
lemma fcU_mul_closed : finset_mul_closed_on (fin_coset_Union Hc) :=
take j k, assume Pjin Pkin,
obtain J PJ PjJ, from iff.elim_left !mem_Union_iff Pjin,
obtain K PK PkK, from iff.elim_left !mem_Union_iff Pkin,
assert Pjk : j*k ∈ elt_of (J*K), from mul_mem_lcoset_mul J K PjJ PkK,
iff.elim_right !mem_Union_iff
(exists.intro (J*K) (and.intro (finsubg_mul_closed Hc PJ PK) Pjk))
definition fcU_is_finsubg [instance] : is_finsubg (fin_coset_Union Hc) :=
is_finsubg.mk fcU_has_one fcU_mul_closed fcU_has_inv
end normalizer
end group
|
c5002d66cf2e7967d024bdf3b3cdadbe7a23ce9f | 4fa161becb8ce7378a709f5992a594764699e268 | /src/tactic/default.lean | 2d0b3fbc5baf095b956bf2c9dfd712ec71ee1b96 | [
"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 | 970 | lean | /-
This file imports many useful tactics ("the kitchen sink").
You can use `import tactic` at the beginning of your file to get everything.
(Although you may want to strip things down when you're polishing.)
Because this file imports some complicated tactics, it has many transitive dependencies
(which of course may not use `import tactic`, and must import selectively).
As (non-exhaustive) examples, these includes things like:
* algebra.group_power
* algebra.ordered_ring
* data.rat
* data.nat.prime
* data.list.perm
* data.set.lattice
* data.equiv.encodable
* order.complete_lattice
-/
import tactic.abel
import tactic.ring_exp
import tactic.noncomm_ring
import tactic.linarith
import tactic.omega
import tactic.tfae
import tactic.apply_fun
import tactic.interval_cases
import tactic.reassoc_axiom -- most likely useful only for category_theory
import tactic.slice
import tactic.subtype_instance
import tactic.group
import tactic.cancel_denoms
import tactic.zify
|
5795816db333bdb644ea5e63aab45adc12f363a5 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/data/finset/basic.lean | 8a5963971e58e93f8645be12ee763f36597dd332 | [
"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 | 114,807 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro
-/
import data.multiset.finset_ops
import tactic.monotonicity
import tactic.apply
import tactic.nth_rewrite
/-!
# Finite sets
Terms of type `finset α` are one way of talking about finite subsets of `α` in mathlib.
Below, `finset α` is defined as a structure with 2 fields:
1. `val` is a `multiset α` of elements;
2. `nodup` is a proof that `val` has no duplicates.
Finsets in Lean are constructive in that they have an underlying `list` that enumerates their
elements. In particular, any function that uses the data of the underlying list cannot depend on its
ordering. This is handled on the `multiset` level by multiset API, so in most cases one needn't
worry about it explicitly.
Finsets give a basic foundation for defining finite sums and products over types:
1. `∑ i in (s : finset α), f i`;
2. `∏ i in (s : finset α), f i`.
Lean refers to these operations as `big_operator`s.
More information can be found in `algebra.big_operators.basic`.
Finsets are directly used to define fintypes in Lean.
A `fintype α` instance for a type `α` consists of
a universal `finset α` containing every term of `α`, called `univ`. See `data.fintype.basic`.
There is also `univ'`, the noncomputable partner to `univ`,
which is defined to be `α` as a finset if `α` is finite,
and the empty finset otherwise. See `data.fintype.basic`.
## Main declarations
### Main definitions
* `finset`: Defines a type for the finite subsets of `α`.
Constructing a `finset` requires two pieces of data: `val`, a `multiset α` of elements,
and `nodup`, a proof that `val` has no duplicates.
* `finset.has_mem`: Defines membership `a ∈ (s : finset α)`.
* `finset.has_coe`: Provides a coercion `s : finset α` to `s : set α`.
* `finset.induction_on`: Induction on finsets. To prove a proposition about an arbitrary `finset α`,
it suffices to prove it for the empty finset, and to show that if it holds for some `finset α`,
then it holds for the finset obtained by inserting a new element.
* `finset.choose`: Given a proof `h` of existence and uniqueness of a certain element
satisfying a predicate, `choose s h` returns the element of `s` satisfying that predicate.
* `finset.card`: `card s : ℕ` returns the cardinalilty of `s : finset α`.
The API for `card`'s interaction with operations on finsets is extensive.
TODO: The noncomputable sister `fincard` is about to be added into mathlib.
### Finset constructions
* `singleton`: Denoted by `{a}`; the finset consisting of one element.
* `finset.empty`: Denoted by `∅`. The finset associated to any type consisting of no elements.
* `finset.range`: For any `n : ℕ`, `range n` is equal to `{0, 1, ... , n - 1} ⊆ ℕ`.
This convention is consistent with other languages and normalizes `card (range n) = n`.
Beware, `n` is not in `range n`.
* `finset.diag`: Given `s`, `diag s` is the set of pairs `(a, a)` with `a ∈ s`. See also
`finset.off_diag`: Given a finite set `s`, the off-diagonal,
`s.off_diag` is the set of pairs `(a, b)` with `a ≠ b` for `a, b ∈ s`.
* `finset.attach`: Given `s : finset α`, `attach s` forms a finset of elements of the subtype
`{a // a ∈ s}`; in other words, it attaches elements to a proof of membership in the set.
### Finsets from functions
* `finset.image`: Given a function `f : α → β`, `s.image f` is the image finset in `β`.
* `finset.map`: Given an embedding `f : α ↪ β`, `s.map f` is the image finset in `β`.
* `finset.filter`: Given a predicate `p : α → Prop`, `s.filter p` is
the finset consisting of those elements in `s` satisfying the predicate `p`.
### The lattice structure on subsets of finsets
There is a natural lattice structure on the subsets of a set.
In Lean, we use lattice notation to talk about things involving unions and intersections. See
`order.lattice`. For the lattice structure on finsets, `⊥` is called `bot` with `⊥ = ∅` and `⊤` is
called `top` with `⊤ = univ`.
* `finset.subset`: Lots of API about lattices, otherwise behaves exactly as one would expect.
* `finset.union`: Defines `s ∪ t` (or `s ⊔ t`) as the union of `s` and `t`.
See `finset.bUnion` for finite unions.
* `finset.inter`: Defines `s ∩ t` (or `s ⊓ t`) as the intersection of `s` and `t`.
TODO: `finset.bInter` for finite intersections.
* `finset.disj_union`: Given a hypothesis `h` which states that finsets `s` and `t` are disjoint,
`s.disj_union t h` is the set such that `a ∈ disj_union s t h` iff `a ∈ s` or `a ∈ t`; this does
not require decidable equality on the type `α`.
### Operations on two or more finsets
* `finset.insert` and `finset.cons`: For any `a : α`, `insert s a` returns `s ∪ {a}`. `cons s a h`
returns the same except that it requires a hypothesis stating that `a` is not already in `s`.
This does not require decidable equality on the type `α`.
* `finset.union`: see "The lattice structure on subsets of finsets"
* `finset.inter`: see "The lattice structure on subsets of finsets"
* `finset.erase`: For any `a : α`, `erase s a` returns `s` with the element `a` removed.
* `finset.sdiff`: Defines the set difference `s \ t` for finsets `s` and `t`.
* `finset.prod`: Given finsets of `α` and `β`, defines finsets of `α × β`.
For arbitrary dependent products, see `data.finset.pi`.
* `finset.sigma`: Given finsets of `α` and `β`, defines finsets of the dependent sum type `Σ α, β`
* `finset.bUnion`: Finite unions of finsets; given an indexing function `f : α → finset β` and a
`s : finset α`, `s.bUnion f` is the union of all finsets of the form `f a` for `a ∈ s`.
* `finset.bInter`: TODO: Implemement finite intersections.
### Maps constructed using finsets
* `finset.piecewise`: Given two functions `f`, `g`, `s.piecewise f g` is a function which is equal
to `f` on `s` and `g` on the complement.
### Predicates on finsets
* `disjoint`: defined via the lattice structure on finsets; two sets are disjoint if their
intersection is empty.
* `finset.nonempty`: A finset is nonempty if it has elements.
This is equivalent to saying `s ≠ ∅`. TODO: Decide on the simp normal form.
### Equivalences between finsets
* The `data.equiv` files describe a general type of equivalence, so look in there for any lemmas.
There is some API for rewriting sums and products from `s` to `t` given that `s ≃ t`.
TODO: examples
## Tags
finite sets, finset
-/
open multiset subtype nat function
variables {α : Type*} {β : Type*} {γ : Type*}
/-- `finset α` is the type of finite sets of elements of `α`. It is implemented
as a multiset (a list up to permutation) which has no duplicate elements. -/
structure finset (α : Type*) :=
(val : multiset α)
(nodup : nodup val)
namespace finset
theorem eq_of_veq : ∀ {s t : finset α}, s.1 = t.1 → s = t
| ⟨s, _⟩ ⟨t, _⟩ rfl := rfl
@[simp] theorem val_inj {s t : finset α} : s.1 = t.1 ↔ s = t :=
⟨eq_of_veq, congr_arg _⟩
@[simp] theorem erase_dup_eq_self [decidable_eq α] (s : finset α) : erase_dup s.1 = s.1 :=
erase_dup_eq_self.2 s.2
instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α)
| s₁ s₂ := decidable_of_iff _ val_inj
/-! ### membership -/
instance : has_mem α (finset α) := ⟨λ a s, a ∈ s.1⟩
theorem mem_def {a : α} {s : finset α} : a ∈ s ↔ a ∈ s.1 := iff.rfl
@[simp] theorem mem_mk {a : α} {s nd} : a ∈ @finset.mk α s nd ↔ a ∈ s := iff.rfl
instance decidable_mem [h : decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ s) :=
multiset.decidable_mem _ _
/-! ### set coercion -/
/-- Convert a finset to a set in the natural way. -/
instance : has_coe_t (finset α) (set α) := ⟨λ s, {x | x ∈ s}⟩
@[simp, norm_cast] lemma mem_coe {a : α} {s : finset α} : a ∈ (s : set α) ↔ a ∈ s := iff.rfl
@[simp] lemma set_of_mem {α} {s : finset α} : {a | a ∈ s} = s := rfl
@[simp] lemma coe_mem {s : finset α} (x : (s : set α)) : ↑x ∈ s := x.2
@[simp] lemma mk_coe {s : finset α} (x : (s : set α)) {h} :
(⟨x, h⟩ : (s : set α)) = x :=
subtype.coe_eta _ _
instance decidable_mem' [decidable_eq α] (a : α) (s : finset α) :
decidable (a ∈ (s : set α)) := s.decidable_mem _
/-! ### extensionality -/
theorem ext_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ :=
val_inj.symm.trans $ nodup_ext s₁.2 s₂.2
@[ext]
theorem ext {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ :=
ext_iff.2
@[simp, norm_cast] theorem coe_inj {s₁ s₂ : finset α} : (s₁ : set α) = s₂ ↔ s₁ = s₂ :=
set.ext_iff.trans ext_iff.symm
lemma coe_injective {α} : injective (coe : finset α → set α) :=
λ s t, coe_inj.1
/-! ### subset -/
instance : has_subset (finset α) := ⟨λ s₁ s₂, ∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂⟩
theorem subset_def {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ s₁.1 ⊆ s₂.1 := iff.rfl
@[simp] theorem subset.refl (s : finset α) : s ⊆ s := subset.refl _
theorem subset_of_eq {s t : finset α} (h : s = t) : s ⊆ t := h ▸ subset.refl _
theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := subset.trans
theorem superset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊇ s₂ → s₂ ⊇ s₃ → s₁ ⊇ s₃ :=
λ h' h, subset.trans h h'
-- TODO: these should be global attributes, but this will require fixing other files
local attribute [trans] subset.trans superset.trans
theorem mem_of_subset {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := mem_of_subset
theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ :=
ext $ λ a, ⟨@H₁ a, @H₂ a⟩
theorem subset_iff {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ := iff.rfl
@[simp, norm_cast] theorem coe_subset {s₁ s₂ : finset α} :
(s₁ : set α) ⊆ s₂ ↔ s₁ ⊆ s₂ := iff.rfl
@[simp] theorem val_le_iff {s₁ s₂ : finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ := le_iff_subset s₁.2
instance : has_ssubset (finset α) := ⟨λa b, a ⊆ b ∧ ¬ b ⊆ a⟩
instance : partial_order (finset α) :=
{ le := (⊆),
lt := (⊂),
le_refl := subset.refl,
le_trans := @subset.trans _,
le_antisymm := @subset.antisymm _ }
theorem subset.antisymm_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ :=
le_antisymm_iff
@[simp] theorem le_eq_subset : ((≤) : finset α → finset α → Prop) = (⊆) := rfl
@[simp] theorem lt_eq_subset : ((<) : finset α → finset α → Prop) = (⊂) := rfl
theorem le_iff_subset {s₁ s₂ : finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ := iff.rfl
theorem lt_iff_ssubset {s₁ s₂ : finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ := iff.rfl
@[simp, norm_cast] lemma coe_ssubset {s₁ s₂ : finset α} : (s₁ : set α) ⊂ s₂ ↔ s₁ ⊂ s₂ :=
show (s₁ : set α) ⊂ s₂ ↔ s₁ ⊆ s₂ ∧ ¬s₂ ⊆ s₁,
by simp only [set.ssubset_def, finset.coe_subset]
@[simp] theorem val_lt_iff {s₁ s₂ : finset α} : s₁.1 < s₂.1 ↔ s₁ ⊂ s₂ :=
and_congr val_le_iff $ not_congr val_le_iff
theorem ssubset_iff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ⊂ s₂ ↔ ∃ x ∈ s₂, x ∉ s₁ :=
set.ssubset_iff_of_subset h
/-! ### Nonempty -/
/-- The property `s.nonempty` expresses the fact that the finset `s` is not empty. It should be used
in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks
to the dot notation. -/
protected def nonempty (s : finset α) : Prop := ∃ x:α, x ∈ s
@[simp, norm_cast] lemma coe_nonempty {s : finset α} : (s:set α).nonempty ↔ s.nonempty := iff.rfl
lemma nonempty.bex {s : finset α} (h : s.nonempty) : ∃ x:α, x ∈ s := h
lemma nonempty.mono {s t : finset α} (hst : s ⊆ t) (hs : s.nonempty) : t.nonempty :=
set.nonempty.mono hst hs
lemma nonempty.forall_const {s : finset α} (h : s.nonempty) {p : Prop} : (∀ x ∈ s, p) ↔ p :=
let ⟨x, hx⟩ := h in ⟨λ h, h x hx, λ h x hx, h⟩
/-! ### empty -/
/-- The empty finset -/
protected def empty : finset α := ⟨0, nodup_zero⟩
instance : has_emptyc (finset α) := ⟨finset.empty⟩
instance inhabited_finset : inhabited (finset α) := ⟨∅⟩
@[simp] theorem empty_val : (∅ : finset α).1 = 0 := rfl
@[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : finset α) := id
@[simp] theorem not_nonempty_empty : ¬(∅ : finset α).nonempty :=
λ ⟨x, hx⟩, not_mem_empty x hx
@[simp] theorem mk_zero : (⟨0, nodup_zero⟩ : finset α) = ∅ := rfl
theorem ne_empty_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ≠ ∅ :=
λ e, not_mem_empty a $ e ▸ h
theorem nonempty.ne_empty {s : finset α} (h : s.nonempty) : s ≠ ∅ :=
exists.elim h $ λ a, ne_empty_of_mem
@[simp] theorem empty_subset (s : finset α) : ∅ ⊆ s := zero_subset _
theorem eq_empty_of_forall_not_mem {s : finset α} (H : ∀x, x ∉ s) : s = ∅ :=
eq_of_veq (eq_zero_of_forall_not_mem H)
lemma eq_empty_iff_forall_not_mem {s : finset α} : s = ∅ ↔ ∀ x, x ∉ s :=
⟨by rintro rfl x; exact id, λ h, eq_empty_of_forall_not_mem h⟩
@[simp] theorem val_eq_zero {s : finset α} : s.1 = 0 ↔ s = ∅ := @val_inj _ s ∅
theorem subset_empty {s : finset α} : s ⊆ ∅ ↔ s = ∅ := subset_zero.trans val_eq_zero
theorem nonempty_of_ne_empty {s : finset α} (h : s ≠ ∅) : s.nonempty :=
exists_mem_of_ne_zero (mt val_eq_zero.1 h)
theorem nonempty_iff_ne_empty {s : finset α} : s.nonempty ↔ s ≠ ∅ :=
⟨nonempty.ne_empty, nonempty_of_ne_empty⟩
@[simp] theorem not_nonempty_iff_eq_empty {s : finset α} : ¬s.nonempty ↔ s = ∅ :=
by { rw nonempty_iff_ne_empty, exact not_not, }
theorem eq_empty_or_nonempty (s : finset α) : s = ∅ ∨ s.nonempty :=
classical.by_cases or.inl (λ h, or.inr (nonempty_of_ne_empty h))
@[simp, norm_cast] lemma coe_empty : ((∅ : finset α) : set α) = ∅ := rfl
@[simp, norm_cast] lemma coe_eq_empty {s : finset α} :
(s : set α) = ∅ ↔ s = ∅ :=
by rw [← coe_empty, coe_inj]
/-- A `finset` for an empty type is empty. -/
lemma eq_empty_of_not_nonempty (h : ¬ nonempty α) (s : finset α) : s = ∅ :=
finset.eq_empty_of_forall_not_mem $ λ x, false.elim $ not_nonempty_iff_imp_false.1 h x
/-! ### singleton -/
/--
`{a} : finset a` is the set `{a}` containing `a` and nothing else.
This differs from `insert a ∅` in that it does not require a `decidable_eq` instance for `α`.
-/
instance : has_singleton α (finset α) := ⟨λ a, ⟨{a}, nodup_singleton a⟩⟩
@[simp] theorem singleton_val (a : α) : ({a} : finset α).1 = a ::ₘ 0 := rfl
@[simp] theorem mem_singleton {a b : α} : b ∈ ({a} : finset α) ↔ b = a := mem_singleton
theorem not_mem_singleton {a b : α} : a ∉ ({b} : finset α) ↔ a ≠ b := not_congr mem_singleton
theorem mem_singleton_self (a : α) : a ∈ ({a} : finset α) := or.inl rfl
theorem singleton_inj {a b : α} : ({a} : finset α) = {b} ↔ a = b :=
⟨λ h, mem_singleton.1 (h ▸ mem_singleton_self _), congr_arg _⟩
@[simp] theorem singleton_nonempty (a : α) : ({a} : finset α).nonempty := ⟨a, mem_singleton_self a⟩
@[simp] theorem singleton_ne_empty (a : α) : ({a} : finset α) ≠ ∅ := (singleton_nonempty a).ne_empty
@[simp, norm_cast] lemma coe_singleton (a : α) : (({a} : finset α) : set α) = {a} :=
by { ext, simp }
lemma eq_singleton_iff_unique_mem {s : finset α} {a : α} :
s = {a} ↔ a ∈ s ∧ ∀ x ∈ s, x = a :=
begin
split; intro t,
rw t,
refine ⟨finset.mem_singleton_self _, λ _, finset.mem_singleton.1⟩,
ext, rw finset.mem_singleton,
refine ⟨t.right _, λ r, r.symm ▸ t.left⟩
end
lemma eq_singleton_iff_nonempty_unique_mem {s : finset α} {a : α} :
s = {a} ↔ s.nonempty ∧ ∀ x ∈ s, x = a :=
begin
split,
{ intros h, subst h, simp, },
{ rintros ⟨hne, h_uniq⟩, rw eq_singleton_iff_unique_mem, refine ⟨_, h_uniq⟩,
rw ← h_uniq hne.some hne.some_spec, apply hne.some_spec, },
end
lemma singleton_iff_unique_mem (s : finset α) : (∃ a, s = {a}) ↔ ∃! a, a ∈ s :=
by simp only [eq_singleton_iff_unique_mem, exists_unique]
lemma singleton_subset_set_iff {s : set α} {a : α} :
↑({a} : finset α) ⊆ s ↔ a ∈ s :=
by rw [coe_singleton, set.singleton_subset_iff]
@[simp] lemma singleton_subset_iff {s : finset α} {a : α} :
{a} ⊆ s ↔ a ∈ s :=
singleton_subset_set_iff
/-! ### cons -/
/-- `cons a s h` is the set `{a} ∪ s` containing `a` and the elements of `s`. It is the same as
`insert a s` when it is defined, but unlike `insert a s` it does not require `decidable_eq α`,
and the union is guaranteed to be disjoint. -/
def cons {α} (a : α) (s : finset α) (h : a ∉ s) : finset α :=
⟨a ::ₘ s.1, multiset.nodup_cons.2 ⟨h, s.2⟩⟩
@[simp] theorem mem_cons {α a s h b} : b ∈ @cons α a s h ↔ b = a ∨ b ∈ s :=
by rcases s with ⟨⟨s⟩⟩; apply list.mem_cons_iff
@[simp] theorem cons_val {a : α} {s : finset α} (h : a ∉ s) : (cons a s h).1 = a ::ₘ s.1 := rfl
@[simp] theorem mk_cons {a : α} {s : multiset α} (h : (a ::ₘ s).nodup) :
(⟨a ::ₘ s, h⟩ : finset α) = cons a ⟨s, (multiset.nodup_cons.1 h).2⟩ (multiset.nodup_cons.1 h).1 :=
rfl
@[simp] theorem nonempty_cons {a : α} {s : finset α} (h : a ∉ s) : (cons a s h).nonempty :=
⟨a, mem_cons.2 (or.inl rfl)⟩
@[simp] lemma nonempty_mk_coe : ∀ {l : list α} {hl}, (⟨↑l, hl⟩ : finset α).nonempty ↔ l ≠ []
| [] hl := by simp
| (a::l) hl := by simp [← multiset.cons_coe]
/-! ### disjoint union -/
/-- `disj_union s t h` is the set such that `a ∈ disj_union s t h` iff `a ∈ s` or `a ∈ t`.
It is the same as `s ∪ t`, but it does not require decidable equality on the type. The hypothesis
ensures that the sets are disjoint. -/
def disj_union {α} (s t : finset α) (h : ∀ a ∈ s, a ∉ t) : finset α :=
⟨s.1 + t.1, multiset.nodup_add.2 ⟨s.2, t.2, h⟩⟩
@[simp] theorem mem_disj_union {α s t h a} :
a ∈ @disj_union α s t h ↔ a ∈ s ∨ a ∈ t :=
by rcases s with ⟨⟨s⟩⟩; rcases t with ⟨⟨t⟩⟩; apply list.mem_append
/-! ### insert -/
section decidable_eq
variables [decidable_eq α]
/-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/
instance : has_insert α (finset α) := ⟨λ a s, ⟨_, nodup_ndinsert a s.2⟩⟩
theorem insert_def (a : α) (s : finset α) : insert a s = ⟨_, nodup_ndinsert a s.2⟩ := rfl
@[simp] theorem insert_val (a : α) (s : finset α) : (insert a s).1 = ndinsert a s.1 := rfl
theorem insert_val' (a : α) (s : finset α) : (insert a s).1 = erase_dup (a ::ₘ s.1) :=
by rw [erase_dup_cons, erase_dup_eq_self]; refl
theorem insert_val_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : (insert a s).1 = a ::ₘ s.1 :=
by rw [insert_val, ndinsert_of_not_mem h]
@[simp] theorem mem_insert {a b : α} {s : finset α} : a ∈ insert b s ↔ a = b ∨ a ∈ s := mem_ndinsert
theorem mem_insert_self (a : α) (s : finset α) : a ∈ insert a s := mem_ndinsert_self a s.1
theorem mem_insert_of_mem {a b : α} {s : finset α} (h : a ∈ s) : a ∈ insert b s :=
mem_ndinsert_of_mem h
theorem mem_of_mem_insert_of_ne {a b : α} {s : finset α} (h : b ∈ insert a s) : b ≠ a → b ∈ s :=
(mem_insert.1 h).resolve_left
@[simp] theorem cons_eq_insert {α} [decidable_eq α] (a s h) : @cons α a s h = insert a s :=
ext $ λ a, by simp
@[simp, norm_cast] lemma coe_insert (a : α) (s : finset α) :
↑(insert a s) = (insert a s : set α) :=
set.ext $ λ x, by simp only [mem_coe, mem_insert, set.mem_insert_iff]
lemma mem_insert_coe {s : finset α} {x y : α} : x ∈ insert y s ↔ x ∈ insert y (s : set α) :=
by simp
instance : is_lawful_singleton α (finset α) := ⟨λ a, by { ext, simp }⟩
@[simp] theorem insert_eq_of_mem {a : α} {s : finset α} (h : a ∈ s) : insert a s = s :=
eq_of_veq $ ndinsert_of_mem h
@[simp] theorem insert_singleton_self_eq (a : α) : ({a, a} : finset α) = {a} :=
insert_eq_of_mem $ mem_singleton_self _
theorem insert.comm (a b : α) (s : finset α) : insert a (insert b s) = insert b (insert a s) :=
ext $ λ x, by simp only [mem_insert, or.left_comm]
theorem insert_singleton_comm (a b : α) : ({a, b} : finset α) = {b, a} :=
begin
ext,
simp [or.comm]
end
@[simp] theorem insert_idem (a : α) (s : finset α) : insert a (insert a s) = insert a s :=
ext $ λ x, by simp only [mem_insert, or.assoc.symm, or_self]
@[simp] theorem insert_nonempty (a : α) (s : finset α) : (insert a s).nonempty :=
⟨a, mem_insert_self a s⟩
@[simp] theorem insert_ne_empty (a : α) (s : finset α) : insert a s ≠ ∅ :=
(insert_nonempty a s).ne_empty
section
universe u
/-!
The universe annotation is required for the following instance, possibly this is a bug in Lean. See
leanprover.zulipchat.com/#narrow/stream/113488-general/topic/strange.20error.20(universe.20issue.3F)
-/
instance {α : Type u} [decidable_eq α] (i : α) (s : finset α) :
nonempty.{u + 1} ((insert i s : finset α) : set α) :=
(finset.coe_nonempty.mpr (s.insert_nonempty i)).to_subtype
end
lemma ne_insert_of_not_mem (s t : finset α) {a : α} (h : a ∉ s) :
s ≠ insert a t :=
by { contrapose! h, simp [h] }
theorem insert_subset {a : α} {s t : finset α} : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t :=
by simp only [subset_iff, mem_insert, forall_eq, or_imp_distrib, forall_and_distrib]
theorem subset_insert (a : α) (s : finset α) : s ⊆ insert a s :=
λ b, mem_insert_of_mem
theorem insert_subset_insert (a : α) {s t : finset α} (h : s ⊆ t) : insert a s ⊆ insert a t :=
insert_subset.2 ⟨mem_insert_self _ _, subset.trans h (subset_insert _ _)⟩
lemma ssubset_iff {s t : finset α} : s ⊂ t ↔ (∃a ∉ s, insert a s ⊆ t) :=
by exact_mod_cast @set.ssubset_iff_insert α s t
lemma ssubset_insert {s : finset α} {a : α} (h : a ∉ s) : s ⊂ insert a s :=
ssubset_iff.mpr ⟨a, h, subset.refl _⟩
@[elab_as_eliminator]
protected theorem induction {α : Type*} {p : finset α → Prop} [decidable_eq α]
(h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : ∀ s, p s
| ⟨s, nd⟩ := multiset.induction_on s (λ _, h₁) (λ a s IH nd, begin
cases nodup_cons.1 nd with m nd',
rw [← (eq_of_veq _ : insert a (finset.mk s _) = ⟨a ::ₘ s, nd⟩)],
{ exact h₂ (by exact m) (IH nd') },
{ rw [insert_val, ndinsert_of_not_mem m] }
end) nd
/--
To prove a proposition about an arbitrary `finset α`,
it suffices to prove it for the empty `finset`,
and to show that if it holds for some `finset α`,
then it holds for the `finset` obtained by inserting a new element.
-/
@[elab_as_eliminator]
protected theorem induction_on {α : Type*} {p : finset α → Prop} [decidable_eq α]
(s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : p s :=
finset.induction h₁ h₂ s
/--
To prove a proposition about `S : finset α`,
it suffices to prove it for the empty `finset`,
and to show that if it holds for some `finset α ⊆ S`,
then it holds for the `finset` obtained by inserting a new element of `S`.
-/
@[elab_as_eliminator]
theorem induction_on' {α : Type*} {p : finset α → Prop} [decidable_eq α]
(S : finset α) (h₁ : p ∅) (h₂ : ∀ {a s}, a ∈ S → s ⊆ S → a ∉ s → p s → p (insert a s)) : p S :=
@finset.induction_on α (λ T, T ⊆ S → p T) _ S (λ _, h₁) (λ a s has hqs hs,
let ⟨hS, sS⟩ := finset.insert_subset.1 hs in h₂ hS sS has (hqs sS)) (finset.subset.refl S)
/-- Inserting an element to a finite set is equivalent to the option type. -/
def subtype_insert_equiv_option {t : finset α} {x : α} (h : x ∉ t) :
{i // i ∈ insert x t} ≃ option {i // i ∈ t} :=
begin
refine
{ to_fun := λ y, if h : ↑y = x then none else some ⟨y, (mem_insert.mp y.2).resolve_left h⟩,
inv_fun := λ y, y.elim ⟨x, mem_insert_self _ _⟩ $ λ z, ⟨z, mem_insert_of_mem z.2⟩,
.. },
{ intro y, by_cases h : ↑y = x,
simp only [subtype.ext_iff, h, option.elim, dif_pos, subtype.coe_mk],
simp only [h, option.elim, dif_neg, not_false_iff, subtype.coe_eta, subtype.coe_mk] },
{ rintro (_|y), simp only [option.elim, dif_pos, subtype.coe_mk],
have : ↑y ≠ x, { rintro ⟨⟩, exact h y.2 },
simp only [this, option.elim, subtype.eta, dif_neg, not_false_iff, subtype.coe_eta,
subtype.coe_mk] },
end
/-! ### union -/
/-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/
instance : has_union (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndunion s₁.1 s₂.2⟩⟩
theorem union_val_nd (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = ndunion s₁.1 s₂.1 := rfl
@[simp] theorem union_val (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = s₁.1 ∪ s₂.1 :=
ndunion_eq_union s₁.2
@[simp] theorem mem_union {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := mem_ndunion
@[simp] theorem disj_union_eq_union {α} [decidable_eq α] (s t h) : @disj_union α s t h = s ∪ t :=
ext $ λ a, by simp
theorem mem_union_left {a : α} {s₁ : finset α} (s₂ : finset α) (h : a ∈ s₁) : a ∈ s₁ ∪ s₂ :=
mem_union.2 $ or.inl h
theorem mem_union_right {a : α} {s₂ : finset α} (s₁ : finset α) (h : a ∈ s₂) : a ∈ s₁ ∪ s₂ :=
mem_union.2 $ or.inr h
theorem forall_mem_union {s₁ s₂ : finset α} {p : α → Prop} :
(∀ ab ∈ (s₁ ∪ s₂), p ab) ↔ (∀ a ∈ s₁, p a) ∧ (∀ b ∈ s₂, p b) :=
⟨λ h, ⟨λ a, h a ∘ mem_union_left _, λ b, h b ∘ mem_union_right _⟩,
λ h ab hab, (mem_union.mp hab).elim (h.1 _) (h.2 _)⟩
theorem not_mem_union {a : α} {s₁ s₂ : finset α} : a ∉ s₁ ∪ s₂ ↔ a ∉ s₁ ∧ a ∉ s₂ :=
by rw [mem_union, not_or_distrib]
@[simp, norm_cast]
lemma coe_union (s₁ s₂ : finset α) : ↑(s₁ ∪ s₂) = (s₁ ∪ s₂ : set α) := set.ext $ λ x, mem_union
theorem union_subset {s₁ s₂ s₃ : finset α} (h₁ : s₁ ⊆ s₃) (h₂ : s₂ ⊆ s₃) : s₁ ∪ s₂ ⊆ s₃ :=
val_le_iff.1 (ndunion_le.2 ⟨h₁, val_le_iff.2 h₂⟩)
theorem subset_union_left (s₁ s₂ : finset α) : s₁ ⊆ s₁ ∪ s₂ := λ x, mem_union_left _
theorem subset_union_right (s₁ s₂ : finset α) : s₂ ⊆ s₁ ∪ s₂ := λ x, mem_union_right _
lemma union_subset_union {s1 t1 s2 t2 : finset α} (h1 : s1 ⊆ t1) (h2 : s2 ⊆ t2) :
s1 ∪ s2 ⊆ t1 ∪ t2 :=
by { intros x hx, rw finset.mem_union at hx ⊢, tauto }
theorem union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ :=
ext $ λ x, by simp only [mem_union, or_comm]
instance : is_commutative (finset α) (∪) := ⟨union_comm⟩
@[simp] theorem union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) :=
ext $ λ x, by simp only [mem_union, or_assoc]
instance : is_associative (finset α) (∪) := ⟨union_assoc⟩
@[simp] theorem union_idempotent (s : finset α) : s ∪ s = s :=
ext $ λ _, mem_union.trans $ or_self _
instance : is_idempotent (finset α) (∪) := ⟨union_idempotent⟩
theorem union_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) :=
ext $ λ _, by simp only [mem_union, or.left_comm]
theorem union_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ :=
ext $ λ x, by simp only [mem_union, or_assoc, or_comm (x ∈ s₂)]
theorem union_self (s : finset α) : s ∪ s = s := union_idempotent s
@[simp] theorem union_empty (s : finset α) : s ∪ ∅ = s :=
ext $ λ x, mem_union.trans $ or_false _
@[simp] theorem empty_union (s : finset α) : ∅ ∪ s = s :=
ext $ λ x, mem_union.trans $ false_or _
theorem insert_eq (a : α) (s : finset α) : insert a s = {a} ∪ s := rfl
@[simp] theorem insert_union (a : α) (s t : finset α) : insert a s ∪ t = insert a (s ∪ t) :=
by simp only [insert_eq, union_assoc]
@[simp] theorem union_insert (a : α) (s t : finset α) : s ∪ insert a t = insert a (s ∪ t) :=
by simp only [insert_eq, union_left_comm]
theorem insert_union_distrib (a : α) (s t : finset α) :
insert a (s ∪ t) = insert a s ∪ insert a t :=
by simp only [insert_union, union_insert, insert_idem]
@[simp] lemma union_eq_left_iff_subset {s t : finset α} :
s ∪ t = s ↔ t ⊆ s :=
begin
split,
{ assume h,
have : t ⊆ s ∪ t := subset_union_right _ _,
rwa h at this },
{ assume h,
exact subset.antisymm (union_subset (subset.refl _) h) (subset_union_left _ _) }
end
@[simp] lemma left_eq_union_iff_subset {s t : finset α} :
s = s ∪ t ↔ t ⊆ s :=
by rw [← union_eq_left_iff_subset, eq_comm]
@[simp] lemma union_eq_right_iff_subset {s t : finset α} :
t ∪ s = s ↔ t ⊆ s :=
by rw [union_comm, union_eq_left_iff_subset]
@[simp] lemma right_eq_union_iff_subset {s t : finset α} :
s = t ∪ s ↔ t ⊆ s :=
by rw [← union_eq_right_iff_subset, eq_comm]
/--
To prove a relation on pairs of `finset X`, it suffices to show that it is
* symmetric,
* it holds when one of the `finset`s is empty,
* it holds for pairs of singletons,
* if it holds for `[a, c]` and for `[b, c]`, then it holds for `[a ∪ b, c]`.
-/
lemma induction_on_union (P : finset α → finset α → Prop)
(symm : ∀ {a b}, P a b → P b a)
(empty_right : ∀ {a}, P a ∅)
(singletons : ∀ {a b}, P {a} {b})
(union_of : ∀ {a b c}, P a c → P b c → P (a ∪ b) c) :
∀ a b, P a b :=
begin
intros a b,
refine finset.induction_on b empty_right (λ x s xs hi, symm _),
rw finset.insert_eq,
apply union_of _ (symm hi),
refine finset.induction_on a empty_right (λ a t ta hi, symm _),
rw finset.insert_eq,
exact union_of singletons (symm hi),
end
/-! ### inter -/
/-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/
instance : has_inter (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndinter s₂.1 s₁.2⟩⟩
theorem inter_val_nd (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = ndinter s₁.1 s₂.1 := rfl
@[simp] theorem inter_val (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = s₁.1 ∩ s₂.1 :=
ndinter_eq_inter s₁.2
@[simp] theorem mem_inter {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := mem_ndinter
theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) :
a ∈ s₁ := (mem_inter.1 h).1
theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) :
a ∈ s₂ := (mem_inter.1 h).2
theorem mem_inter_of_mem {a : α} {s₁ s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ :=
and_imp.1 mem_inter.2
theorem inter_subset_left (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₁ := λ a, mem_of_mem_inter_left
theorem inter_subset_right (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₂ := λ a, mem_of_mem_inter_right
theorem subset_inter {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₁ ⊆ s₃ → s₁ ⊆ s₂ ∩ s₃ :=
by simp only [subset_iff, mem_inter] {contextual:=tt}; intros; split; trivial
@[simp, norm_cast]
lemma coe_inter (s₁ s₂ : finset α) : ↑(s₁ ∩ s₂) = (s₁ ∩ s₂ : set α) := set.ext $ λ _, mem_inter
@[simp] theorem union_inter_cancel_left {s t : finset α} : (s ∪ t) ∩ s = s :=
by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_left]
@[simp] theorem union_inter_cancel_right {s t : finset α} : (s ∪ t) ∩ t = t :=
by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_right]
theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ :=
ext $ λ _, by simp only [mem_inter, and_comm]
@[simp] theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) :=
ext $ λ _, by simp only [mem_inter, and_assoc]
theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) :=
ext $ λ _, by simp only [mem_inter, and.left_comm]
theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ :=
ext $ λ _, by simp only [mem_inter, and.right_comm]
@[simp] theorem inter_self (s : finset α) : s ∩ s = s :=
ext $ λ _, mem_inter.trans $ and_self _
@[simp] theorem inter_empty (s : finset α) : s ∩ ∅ = ∅ :=
ext $ λ _, mem_inter.trans $ and_false _
@[simp] theorem empty_inter (s : finset α) : ∅ ∩ s = ∅ :=
ext $ λ _, mem_inter.trans $ false_and _
@[simp] lemma inter_union_self (s t : finset α) : s ∩ (t ∪ s) = s :=
by rw [inter_comm, union_inter_cancel_right]
@[simp] theorem insert_inter_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₂) :
insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) :=
ext $ λ x, have x = a ∨ x ∈ s₂ ↔ x ∈ s₂, from or_iff_right_of_imp $ by rintro rfl; exact h,
by simp only [mem_inter, mem_insert, or_and_distrib_left, this]
@[simp] theorem inter_insert_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₁) :
s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) :=
by rw [inter_comm, insert_inter_of_mem h, inter_comm]
@[simp] theorem insert_inter_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₂) :
insert a s₁ ∩ s₂ = s₁ ∩ s₂ :=
ext $ λ x, have ¬ (x = a ∧ x ∈ s₂), by rintro ⟨rfl, H⟩; exact h H,
by simp only [mem_inter, mem_insert, or_and_distrib_right, this, false_or]
@[simp] theorem inter_insert_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₁) :
s₁ ∩ insert a s₂ = s₁ ∩ s₂ :=
by rw [inter_comm, insert_inter_of_not_mem h, inter_comm]
@[simp] theorem singleton_inter_of_mem {a : α} {s : finset α} (H : a ∈ s) : {a} ∩ s = {a} :=
show insert a ∅ ∩ s = insert a ∅, by rw [insert_inter_of_mem H, empty_inter]
@[simp] theorem singleton_inter_of_not_mem {a : α} {s : finset α} (H : a ∉ s) : {a} ∩ s = ∅ :=
eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_singleton]; rintro x ⟨rfl, h⟩; exact H h
@[simp] theorem inter_singleton_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ∩ {a} = {a} :=
by rw [inter_comm, singleton_inter_of_mem h]
@[simp] theorem inter_singleton_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : s ∩ {a} = ∅ :=
by rw [inter_comm, singleton_inter_of_not_mem h]
@[mono]
lemma inter_subset_inter {x y s t : finset α} (h : x ⊆ y) (h' : s ⊆ t) : x ∩ s ⊆ y ∩ t :=
begin
intros a a_in,
rw finset.mem_inter at a_in ⊢,
exact ⟨h a_in.1, h' a_in.2⟩
end
lemma inter_subset_inter_right {x y s : finset α} (h : x ⊆ y) : x ∩ s ⊆ y ∩ s :=
finset.inter_subset_inter h (finset.subset.refl _)
lemma inter_subset_inter_left {x y s : finset α} (h : x ⊆ y) : s ∩ x ⊆ s ∩ y :=
finset.inter_subset_inter (finset.subset.refl _) h
/-! ### lattice laws -/
instance : lattice (finset α) :=
{ sup := (∪),
sup_le := assume a b c, union_subset,
le_sup_left := subset_union_left,
le_sup_right := subset_union_right,
inf := (∩),
le_inf := assume a b c, subset_inter,
inf_le_left := inter_subset_left,
inf_le_right := inter_subset_right,
..finset.partial_order }
@[simp] theorem sup_eq_union : ((⊔) : finset α → finset α → finset α) = (∪) := rfl
@[simp] theorem inf_eq_inter : ((⊓) : finset α → finset α → finset α) = (∩) := rfl
instance : semilattice_inf_bot (finset α) :=
{ bot := ∅, bot_le := empty_subset, ..finset.lattice }
@[simp] lemma bot_eq_empty : (⊥ : finset α) = ∅ := rfl
instance {α : Type*} [decidable_eq α] : semilattice_sup_bot (finset α) :=
{ ..finset.semilattice_inf_bot, ..finset.lattice }
instance : distrib_lattice (finset α) :=
{ le_sup_inf := assume a b c, show (a ∪ b) ∩ (a ∪ c) ⊆ a ∪ b ∩ c,
by simp only [subset_iff, mem_inter, mem_union, and_imp, or_imp_distrib] {contextual:=tt};
simp only [true_or, imp_true_iff, true_and, or_true],
..finset.lattice }
theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left
theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right
theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left
theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right
lemma union_eq_empty_iff (A B : finset α) : A ∪ B = ∅ ↔ A = ∅ ∧ B = ∅ := sup_eq_bot_iff
/-! ### erase -/
/-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are
not equal to `a`. -/
def erase (s : finset α) (a : α) : finset α := ⟨_, nodup_erase_of_nodup a s.2⟩
@[simp] theorem erase_val (s : finset α) (a : α) : (erase s a).1 = s.1.erase a := rfl
@[simp] theorem mem_erase {a b : α} {s : finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s :=
mem_erase_iff_of_nodup s.2
theorem not_mem_erase (a : α) (s : finset α) : a ∉ erase s a := mem_erase_of_nodup s.2
@[simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl
theorem ne_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ≠ a :=
by simp only [mem_erase]; exact and.left
theorem mem_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ∈ s := mem_of_mem_erase
theorem mem_erase_of_ne_of_mem {a b : α} {s : finset α} : a ≠ b → a ∈ s → a ∈ erase s b :=
by simp only [mem_erase]; exact and.intro
/-- An element of `s` that is not an element of `erase s a` must be
`a`. -/
lemma eq_of_mem_of_not_mem_erase {a b : α} {s : finset α} (hs : b ∈ s)
(hsa : b ∉ s.erase a) : b = a :=
begin
rw [mem_erase, not_and] at hsa,
exact not_imp_not.mp hsa hs
end
theorem erase_insert {a : α} {s : finset α} (h : a ∉ s) : erase (insert a s) a = s :=
ext $ assume x, by simp only [mem_erase, mem_insert, and_or_distrib_left, not_and_self, false_or];
apply and_iff_right_of_imp; rintro H rfl; exact h H
theorem insert_erase {a : α} {s : finset α} (h : a ∈ s) : insert a (erase s a) = s :=
ext $ assume x, by simp only [mem_insert, mem_erase, or_and_distrib_left, dec_em, true_and];
apply or_iff_right_of_imp; rintro rfl; exact h
theorem erase_subset_erase (a : α) {s t : finset α} (h : s ⊆ t) : erase s a ⊆ erase t a :=
val_le_iff.1 $ erase_le_erase _ $ val_le_iff.2 h
theorem erase_subset (a : α) (s : finset α) : erase s a ⊆ s := erase_subset _ _
@[simp, norm_cast] lemma coe_erase (a : α) (s : finset α) : ↑(erase s a) = (s \ {a} : set α) :=
set.ext $ λ _, mem_erase.trans $ by rw [and_comm, set.mem_diff, set.mem_singleton_iff]; refl
lemma erase_ssubset {a : α} {s : finset α} (h : a ∈ s) : s.erase a ⊂ s :=
calc s.erase a ⊂ insert a (s.erase a) : ssubset_insert $ not_mem_erase _ _
... = _ : insert_erase h
theorem erase_eq_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : erase s a = s :=
eq_of_veq $ erase_of_not_mem h
theorem subset_insert_iff {a : α} {s t : finset α} : s ⊆ insert a t ↔ erase s a ⊆ t :=
by simp only [subset_iff, or_iff_not_imp_left, mem_erase, mem_insert, and_imp];
exact forall_congr (λ x, forall_swap)
theorem erase_insert_subset (a : α) (s : finset α) : erase (insert a s) a ⊆ s :=
subset_insert_iff.1 $ subset.refl _
theorem insert_erase_subset (a : α) (s : finset α) : s ⊆ insert a (erase s a) :=
subset_insert_iff.2 $ subset.refl _
lemma erase_inj {x y : α} (s : finset α) (hx : x ∈ s) :
s.erase x = s.erase y ↔ x = y :=
begin
refine ⟨λ h, _, congr_arg _⟩,
rw eq_of_mem_of_not_mem_erase hx,
rw ←h,
simp,
end
lemma erase_inj_on (s : finset α) : set.inj_on s.erase s :=
λ _ _ _ _, (erase_inj s ‹_›).mp
/-! ### sdiff -/
/-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/
instance : has_sdiff (finset α) := ⟨λs₁ s₂, ⟨s₁.1 - s₂.1, nodup_of_le (sub_le_self _ _) s₁.2⟩⟩
@[simp] theorem mem_sdiff {a : α} {s₁ s₂ : finset α} :
a ∈ s₁ \ s₂ ↔ a ∈ s₁ ∧ a ∉ s₂ := mem_sub_of_nodup s₁.2
@[simp] theorem inter_sdiff_self (s₁ s₂ : finset α) : s₁ ∩ (s₂ \ s₁) = ∅ :=
eq_empty_of_forall_not_mem $
by simp only [mem_inter, mem_sdiff]; rintro x ⟨h, _, hn⟩; exact hn h
instance : generalized_boolean_algebra (finset α) :=
{ sup_inf_sdiff := λ x y, by { simp only [ext_iff, mem_union, mem_sdiff, inf_eq_inter, sup_eq_union,
mem_inter], tauto },
inf_inf_sdiff := λ x y, by { simp only [ext_iff, inter_sdiff_self, inter_empty, inter_assoc,
false_iff, inf_eq_inter, not_mem_empty], tauto },
..finset.has_sdiff,
..finset.distrib_lattice,
..finset.semilattice_inf_bot }
lemma not_mem_sdiff_of_mem_right {a : α} {s t : finset α} (h : a ∈ t) : a ∉ s \ t :=
by simp only [mem_sdiff, h, not_true, not_false_iff, and_false]
theorem union_sdiff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ∪ (s₂ \ s₁) = s₂ :=
sup_sdiff_of_le h
theorem sdiff_union_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : (s₂ \ s₁) ∪ s₁ = s₂ :=
(union_comm _ _).trans (union_sdiff_of_subset h)
theorem inter_sdiff (s t u : finset α) : s ∩ (t \ u) = s ∩ t \ u :=
by { ext x, simp [and_assoc] }
@[simp] theorem sdiff_inter_self (s₁ s₂ : finset α) : (s₂ \ s₁) ∩ s₁ = ∅ :=
inf_sdiff_self_left
@[simp] theorem sdiff_self (s₁ : finset α) : s₁ \ s₁ = ∅ :=
sdiff_self
theorem sdiff_inter_distrib_right (s₁ s₂ s₃ : finset α) : s₁ \ (s₂ ∩ s₃) = (s₁ \ s₂) ∪ (s₁ \ s₃) :=
sdiff_inf
@[simp] theorem sdiff_inter_self_left (s₁ s₂ : finset α) : s₁ \ (s₁ ∩ s₂) = s₁ \ s₂ :=
sdiff_inf_self_left
@[simp] theorem sdiff_inter_self_right (s₁ s₂ : finset α) : s₁ \ (s₂ ∩ s₁) = s₁ \ s₂ :=
sdiff_inf_self_right
@[simp] theorem sdiff_empty {s₁ : finset α} : s₁ \ ∅ = s₁ :=
sdiff_bot
@[mono]
theorem sdiff_subset_sdiff {s₁ s₂ t₁ t₂ : finset α} (h₁ : t₁ ⊆ t₂) (h₂ : s₂ ⊆ s₁) :
t₁ \ s₁ ⊆ t₂ \ s₂ :=
sdiff_le_sdiff ‹t₁ ≤ t₂› ‹s₂ ≤ s₁›
@[simp, norm_cast] lemma coe_sdiff (s₁ s₂ : finset α) : ↑(s₁ \ s₂) = (s₁ \ s₂ : set α) :=
set.ext $ λ _, mem_sdiff
@[simp] theorem union_sdiff_self_eq_union {s t : finset α} : s ∪ (t \ s) = s ∪ t :=
sup_sdiff_self_right
@[simp] theorem sdiff_union_self_eq_union {s t : finset α} : (s \ t) ∪ t = s ∪ t :=
sup_sdiff_self_left
lemma union_sdiff_symm {s t : finset α} : s ∪ (t \ s) = t ∪ (s \ t) :=
sup_sdiff_symm
lemma sdiff_union_inter (s t : finset α) : (s \ t) ∪ (s ∩ t) = s :=
by { rw union_comm, exact sup_inf_sdiff _ _ }
@[simp] lemma sdiff_idem (s t : finset α) : s \ t \ t = s \ t :=
sdiff_idem
lemma sdiff_eq_empty_iff_subset {s t : finset α} : s \ t = ∅ ↔ s ⊆ t :=
sdiff_eq_bot_iff
@[simp] lemma empty_sdiff (s : finset α) : ∅ \ s = ∅ :=
bot_sdiff
lemma insert_sdiff_of_not_mem (s : finset α) {t : finset α} {x : α} (h : x ∉ t) :
(insert x s) \ t = insert x (s \ t) :=
begin
rw [← coe_inj, coe_insert, coe_sdiff, coe_sdiff, coe_insert],
exact set.insert_diff_of_not_mem s h
end
lemma insert_sdiff_of_mem (s : finset α) {t : finset α} {x : α} (h : x ∈ t) :
(insert x s) \ t = s \ t :=
begin
rw [← coe_inj, coe_sdiff, coe_sdiff, coe_insert],
exact set.insert_diff_of_mem s h
end
@[simp] lemma insert_sdiff_insert (s t : finset α) (x : α) :
(insert x s) \ (insert x t) = s \ insert x t :=
insert_sdiff_of_mem _ (mem_insert_self _ _)
lemma sdiff_insert_of_not_mem {s : finset α} {x : α} (h : x ∉ s) (t : finset α) :
s \ (insert x t) = s \ t :=
begin
refine subset.antisymm (sdiff_subset_sdiff (subset.refl _) (subset_insert _ _)) (λ y hy, _),
simp only [mem_sdiff, mem_insert, not_or_distrib] at hy ⊢,
exact ⟨hy.1, λ hxy, h $ hxy ▸ hy.1, hy.2⟩
end
@[simp] lemma sdiff_subset (s t : finset α) : s \ t ⊆ s :=
show s \ t ≤ s, from sdiff_le
lemma union_sdiff_distrib (s₁ s₂ t : finset α) : (s₁ ∪ s₂) \ t = s₁ \ t ∪ s₂ \ t :=
sup_sdiff
lemma sdiff_union_distrib (s t₁ t₂ : finset α) : s \ (t₁ ∪ t₂) = (s \ t₁) ∩ (s \ t₂) :=
sdiff_sup
lemma union_sdiff_self (s t : finset α) : (s ∪ t) \ t = s \ t :=
sup_sdiff_right_self
lemma sdiff_singleton_eq_erase (a : α) (s : finset α) : s \ singleton a = erase s a :=
by { ext, rw [mem_erase, mem_sdiff, mem_singleton], tauto }
lemma sdiff_sdiff_self_left (s t : finset α) : s \ (s \ t) = s ∩ t :=
sdiff_sdiff_right_self
lemma sdiff_eq_sdiff_iff_inter_eq_inter {s t₁ t₂ : finset α} : s \ t₁ = s \ t₂ ↔ s ∩ t₁ = s ∩ t₂ :=
sdiff_eq_sdiff_iff_inf_eq_inf
lemma union_eq_sdiff_union_sdiff_union_inter (s t : finset α) :
s ∪ t = (s \ t) ∪ (t \ s) ∪ (s ∩ t) :=
sup_eq_sdiff_sup_sdiff_sup_inf
end decidable_eq
/-! ### attach -/
/-- `attach s` takes the elements of `s` and forms a new set of elements of the
subtype `{x // x ∈ s}`. -/
def attach (s : finset α) : finset {x // x ∈ s} := ⟨attach s.1, nodup_attach.2 s.2⟩
theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {s : finset α} (hx : x ∈ s) :
sizeof x < sizeof s := by
{ cases s, dsimp [sizeof, has_sizeof.sizeof, finset.sizeof],
apply lt_add_left, exact multiset.sizeof_lt_sizeof_of_mem hx }
@[simp] theorem attach_val (s : finset α) : s.attach.1 = s.1.attach := rfl
@[simp] theorem mem_attach (s : finset α) : ∀ x, x ∈ s.attach := mem_attach _
@[simp] theorem attach_empty : attach (∅ : finset α) = ∅ := rfl
/-! ### piecewise -/
section piecewise
/-- `s.piecewise f g` is the function equal to `f` on the finset `s`, and to `g` on its
complement. -/
def piecewise {α : Type*} {δ : α → Sort*} (s : finset α) (f g : Πi, δ i) [∀j, decidable (j ∈ s)] :
Πi, δ i :=
λi, if i ∈ s then f i else g i
variables {δ : α → Sort*} (s : finset α) (f g : Πi, δ i)
@[simp] lemma piecewise_insert_self [decidable_eq α] {j : α} [∀i, decidable (i ∈ insert j s)] :
(insert j s).piecewise f g j = f j :=
by simp [piecewise]
@[simp] lemma piecewise_empty [∀i : α, decidable (i ∈ (∅ : finset α))] : piecewise ∅ f g = g :=
by { ext i, simp [piecewise] }
variable [∀j, decidable (j ∈ s)]
@[norm_cast] lemma piecewise_coe [∀j, decidable (j ∈ (s : set α))] :
(s : set α).piecewise f g = s.piecewise f g :=
by { ext, congr }
@[simp, priority 980]
lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i :=
by simp [piecewise, hi]
@[simp, priority 980]
lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i :=
by simp [piecewise, hi]
lemma piecewise_congr {f f' g g' : Π i, δ i} (hf : ∀ i ∈ s, f i = f' i) (hg : ∀ i ∉ s, g i = g' i) :
s.piecewise f g = s.piecewise f' g' :=
funext $ λ i, if_ctx_congr iff.rfl (hf i) (hg i)
@[simp, priority 990]
lemma piecewise_insert_of_ne [decidable_eq α] {i j : α} [∀i, decidable (i ∈ insert j s)]
(h : i ≠ j) : (insert j s).piecewise f g i = s.piecewise f g i :=
by simp [piecewise, h]
lemma piecewise_insert [decidable_eq α] (j : α) [∀i, decidable (i ∈ insert j s)] :
(insert j s).piecewise f g = update (s.piecewise f g) j (f j) :=
begin
classical,
rw [← piecewise_coe, ← piecewise_coe, ← set.piecewise_insert, ← coe_insert j s],
congr
end
lemma piecewise_cases {i} (p : δ i → Prop) (hf : p (f i)) (hg : p (g i)) : p (s.piecewise f g i) :=
by by_cases hi : i ∈ s; simpa [hi]
lemma piecewise_mem_set_pi {δ : α → Type*} {t : set α} {t' : Π i, set (δ i)}
{f g} (hf : f ∈ set.pi t t') (hg : g ∈ set.pi t t') : s.piecewise f g ∈ set.pi t t' :=
by { classical, rw ← piecewise_coe, exact set.piecewise_mem_pi ↑s hf hg }
lemma piecewise_singleton [decidable_eq α] (i : α) :
piecewise {i} f g = update g i (f i) :=
by rw [← insert_emptyc_eq, piecewise_insert, piecewise_empty]
lemma piecewise_piecewise_of_subset_left {s t : finset α} [Π i, decidable (i ∈ s)]
[Π i, decidable (i ∈ t)] (h : s ⊆ t) (f₁ f₂ g : Π a, δ a) :
s.piecewise (t.piecewise f₁ f₂) g = s.piecewise f₁ g :=
s.piecewise_congr (λ i hi, piecewise_eq_of_mem _ _ _ (h hi)) (λ _ _, rfl)
@[simp] lemma piecewise_idem_left (f₁ f₂ g : Π a, δ a) :
s.piecewise (s.piecewise f₁ f₂) g = s.piecewise f₁ g :=
piecewise_piecewise_of_subset_left (subset.refl _) _ _ _
lemma piecewise_piecewise_of_subset_right {s t : finset α} [Π i, decidable (i ∈ s)]
[Π i, decidable (i ∈ t)] (h : t ⊆ s) (f g₁ g₂ : Π a, δ a) :
s.piecewise f (t.piecewise g₁ g₂) = s.piecewise f g₂ :=
s.piecewise_congr (λ _ _, rfl) (λ i hi, t.piecewise_eq_of_not_mem _ _ (mt (@h _) hi))
@[simp] lemma piecewise_idem_right (f g₁ g₂ : Π a, δ a) :
s.piecewise f (s.piecewise g₁ g₂) = s.piecewise f g₂ :=
piecewise_piecewise_of_subset_right (subset.refl _) f g₁ g₂
lemma update_eq_piecewise {β : Type*} [decidable_eq α] (f : α → β) (i : α) (v : β) :
update f i v = piecewise (singleton i) (λj, v) f :=
(piecewise_singleton _ _ _).symm
lemma update_piecewise [decidable_eq α] (i : α) (v : δ i) :
update (s.piecewise f g) i v = s.piecewise (update f i v) (update g i v) :=
begin
ext j,
rcases em (j = i) with (rfl|hj); by_cases hs : j ∈ s; simp *
end
lemma update_piecewise_of_mem [decidable_eq α] {i : α} (hi : i ∈ s) (v : δ i) :
update (s.piecewise f g) i v = s.piecewise (update f i v) g :=
begin
rw update_piecewise,
refine s.piecewise_congr (λ _ _, rfl) (λ j hj, update_noteq _ _ _),
exact λ h, hj (h.symm ▸ hi)
end
lemma update_piecewise_of_not_mem [decidable_eq α] {i : α} (hi : i ∉ s) (v : δ i) :
update (s.piecewise f g) i v = s.piecewise f (update g i v) :=
begin
rw update_piecewise,
refine s.piecewise_congr (λ j hj, update_noteq _ _ _) (λ _ _, rfl),
exact λ h, hi (h ▸ hj)
end
lemma piecewise_le_of_le_of_le {δ : α → Type*} [Π i, preorder (δ i)] {f g h : Π i, δ i}
(Hf : f ≤ h) (Hg : g ≤ h) : s.piecewise f g ≤ h :=
λ x, piecewise_cases s f g (≤ h x) (Hf x) (Hg x)
lemma le_piecewise_of_le_of_le {δ : α → Type*} [Π i, preorder (δ i)] {f g h : Π i, δ i}
(Hf : h ≤ f) (Hg : h ≤ g) : h ≤ s.piecewise f g :=
λ x, piecewise_cases s f g (λ y, h x ≤ y) (Hf x) (Hg x)
lemma piecewise_le_piecewise' {δ : α → Type*} [Π i, preorder (δ i)] {f g f' g' : Π i, δ i}
(Hf : ∀ x ∈ s, f x ≤ f' x) (Hg : ∀ x ∉ s, g x ≤ g' x) : s.piecewise f g ≤ s.piecewise f' g' :=
λ x, by { by_cases hx : x ∈ s; simp [hx, *] }
lemma piecewise_le_piecewise {δ : α → Type*} [Π i, preorder (δ i)] {f g f' g' : Π i, δ i}
(Hf : f ≤ f') (Hg : g ≤ g') : s.piecewise f g ≤ s.piecewise f' g' :=
s.piecewise_le_piecewise' (λ x _, Hf x) (λ x _, Hg x)
lemma piecewise_mem_Icc_of_mem_of_mem {δ : α → Type*} [Π i, preorder (δ i)] {f f₁ g g₁ : Π i, δ i}
(hf : f ∈ set.Icc f₁ g₁) (hg : g ∈ set.Icc f₁ g₁) :
s.piecewise f g ∈ set.Icc f₁ g₁ :=
⟨le_piecewise_of_le_of_le _ hf.1 hg.1, piecewise_le_of_le_of_le _ hf.2 hg.2⟩
lemma piecewise_mem_Icc {δ : α → Type*} [Π i, preorder (δ i)] {f g : Π i, δ i} (h : f ≤ g) :
s.piecewise f g ∈ set.Icc f g :=
piecewise_mem_Icc_of_mem_of_mem _ (set.left_mem_Icc.2 h) (set.right_mem_Icc.2 h)
lemma piecewise_mem_Icc' {δ : α → Type*} [Π i, preorder (δ i)] {f g : Π i, δ i} (h : g ≤ f) :
s.piecewise f g ∈ set.Icc g f :=
piecewise_mem_Icc_of_mem_of_mem _ (set.right_mem_Icc.2 h) (set.left_mem_Icc.2 h)
end piecewise
section decidable_pi_exists
variables {s : finset α}
instance decidable_dforall_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] :
decidable (∀a (h : a ∈ s), p a h) :=
multiset.decidable_dforall_multiset
/-- decidable equality for functions whose domain is bounded by finsets -/
instance decidable_eq_pi_finset {β : α → Type*} [h : ∀a, decidable_eq (β a)] :
decidable_eq (Πa∈s, β a) :=
multiset.decidable_eq_pi_multiset
instance decidable_dexists_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] :
decidable (∃a (h : a ∈ s), p a h) :=
multiset.decidable_dexists_multiset
end decidable_pi_exists
/-! ### filter -/
section filter
variables (p q : α → Prop) [decidable_pred p] [decidable_pred q]
/-- `filter p s` is the set of elements of `s` that satisfy `p`. -/
def filter (s : finset α) : finset α :=
⟨_, nodup_filter p s.2⟩
@[simp] theorem filter_val (s : finset α) : (filter p s).1 = s.1.filter p := rfl
@[simp] theorem filter_subset (s : finset α) : s.filter p ⊆ s := filter_subset _ _
variable {p}
@[simp] theorem mem_filter {s : finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := mem_filter
theorem filter_ssubset {s : finset α} : s.filter p ⊂ s ↔ ∃ x ∈ s, ¬ p x :=
⟨λ h, let ⟨x, hs, hp⟩ := set.exists_of_ssubset h in ⟨x, hs, mt (λ hp, mem_filter.2 ⟨hs, hp⟩) hp⟩,
λ ⟨x, hs, hp⟩, ⟨s.filter_subset _, λ h, hp (mem_filter.1 (h hs)).2⟩⟩
variable (p)
theorem filter_filter (s : finset α) : (s.filter p).filter q = s.filter (λa, p a ∧ q a) :=
ext $ assume a, by simp only [mem_filter, and_comm, and.left_comm]
lemma filter_true {s : finset α} [h : decidable_pred (λ _, true)] :
@finset.filter α (λ _, true) h s = s :=
by ext; simp
@[simp] theorem filter_false {h} (s : finset α) : @filter α (λa, false) h s = ∅ :=
ext $ assume a, by simp only [mem_filter, and_false]; refl
variables {p q}
/-- If all elements of a `finset` satisfy the predicate `p`, `s.filter p` is `s`. -/
@[simp] lemma filter_true_of_mem {s : finset α} (h : ∀ x ∈ s, p x) : s.filter p = s :=
ext $ λ x, ⟨λ h, (mem_filter.1 h).1, λ hx, mem_filter.2 ⟨hx, h x hx⟩⟩
/-- If all elements of a `finset` fail to satisfy the predicate `p`, `s.filter p` is `∅`. -/
lemma filter_false_of_mem {s : finset α} (h : ∀ x ∈ s, ¬ p x) : s.filter p = ∅ :=
eq_empty_of_forall_not_mem (by simpa)
lemma filter_congr {s : finset α} (H : ∀ x ∈ s, p x ↔ q x) : filter p s = filter q s :=
eq_of_veq $ filter_congr H
variables (p q)
lemma filter_empty : filter p ∅ = ∅ := subset_empty.1 $ filter_subset _ _
lemma filter_subset_filter {s t : finset α} (h : s ⊆ t) : s.filter p ⊆ t.filter p :=
assume a ha, mem_filter.2 ⟨h (mem_filter.1 ha).1, (mem_filter.1 ha).2⟩
@[simp, norm_cast] lemma coe_filter (s : finset α) : ↑(s.filter p) = ({x ∈ ↑s | p x} : set α) :=
set.ext $ λ _, mem_filter
theorem filter_singleton (a : α) : filter p (singleton a) = if p a then singleton a else ∅ :=
by { classical, ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] }
variable [decidable_eq α]
theorem filter_union (s₁ s₂ : finset α) : (s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p :=
ext $ λ _, by simp only [mem_filter, mem_union, or_and_distrib_right]
theorem filter_union_right (s : finset α) : s.filter p ∪ s.filter q = s.filter (λx, p x ∨ q x) :=
ext $ λ x, by simp only [mem_filter, mem_union, and_or_distrib_left.symm]
lemma filter_mem_eq_inter {s t : finset α} [Π i, decidable (i ∈ t)] :
s.filter (λ i, i ∈ t) = s ∩ t :=
ext $ λ i, by rw [mem_filter, mem_inter]
theorem filter_inter (s t : finset α) : filter p s ∩ t = filter p (s ∩ t) :=
by { ext, simp only [mem_inter, mem_filter, and.right_comm] }
theorem inter_filter (s t : finset α) : s ∩ filter p t = filter p (s ∩ t) :=
by rw [inter_comm, filter_inter, inter_comm]
theorem filter_insert (a : α) (s : finset α) :
filter p (insert a s) = if p a then insert a (filter p s) else filter p s :=
by { ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] }
theorem filter_or [decidable_pred (λ a, p a ∨ q a)] (s : finset α) :
s.filter (λ a, p a ∨ q a) = s.filter p ∪ s.filter q :=
ext $ λ _, by simp only [mem_filter, mem_union, and_or_distrib_left]
theorem filter_and [decidable_pred (λ a, p a ∧ q a)] (s : finset α) :
s.filter (λ a, p a ∧ q a) = s.filter p ∩ s.filter q :=
ext $ λ _, by simp only [mem_filter, mem_inter, and_comm, and.left_comm, and_self]
theorem filter_not [decidable_pred (λ a, ¬ p a)] (s : finset α) :
s.filter (λ a, ¬ p a) = s \ s.filter p :=
ext $ by simpa only [mem_filter, mem_sdiff, and_comm, not_and] using λ a, and_congr_right $
λ h : a ∈ s, (imp_iff_right h).symm.trans imp_not_comm
theorem sdiff_eq_filter (s₁ s₂ : finset α) :
s₁ \ s₂ = filter (∉ s₂) s₁ := ext $ λ _, by simp only [mem_sdiff, mem_filter]
theorem sdiff_eq_self (s₁ s₂ : finset α) :
s₁ \ s₂ = s₁ ↔ s₁ ∩ s₂ ⊆ ∅ :=
by { simp [subset.antisymm_iff],
split; intro h,
{ transitivity' ((s₁ \ s₂) ∩ s₂), mono, simp },
{ calc s₁ \ s₂
⊇ s₁ \ (s₁ ∩ s₂) : by simp [(⊇)]
... ⊇ s₁ \ ∅ : by mono using [(⊇)]
... ⊇ s₁ : by simp [(⊇)] } }
theorem filter_union_filter_neg_eq [decidable_pred (λ a, ¬ p a)]
(s : finset α) : s.filter p ∪ s.filter (λa, ¬ p a) = s :=
by simp only [filter_not, union_sdiff_of_subset (filter_subset p s)]
theorem filter_inter_filter_neg_eq (s : finset α) : s.filter p ∩ s.filter (λa, ¬ p a) = ∅ :=
by simp only [filter_not, inter_sdiff_self]
lemma subset_union_elim {s : finset α} {t₁ t₂ : set α} (h : ↑s ⊆ t₁ ∪ t₂) :
∃s₁ s₂ : finset α, s₁ ∪ s₂ = s ∧ ↑s₁ ⊆ t₁ ∧ ↑s₂ ⊆ t₂ \ t₁ :=
begin
classical,
refine ⟨s.filter (∈ t₁), s.filter (∉ t₁), _, _ , _⟩,
{ simp [filter_union_right, em] },
{ intro x, simp },
{ intro x, simp, intros hx hx₂, refine ⟨or.resolve_left (h hx) hx₂, hx₂⟩ }
end
/- We can simplify an application of filter where the decidability is inferred in "the wrong way" -/
@[simp] lemma filter_congr_decidable {α} (s : finset α) (p : α → Prop) (h : decidable_pred p)
[decidable_pred p] : @filter α p h s = s.filter p :=
by congr
section classical
open_locale classical
/-- The following instance allows us to write `{ x ∈ s | p x }` for `finset.filter s p`.
Since the former notation requires us to define this for all propositions `p`, and `finset.filter`
only works for decidable propositions, the notation `{ x ∈ s | p x }` is only compatible with
classical logic because it uses `classical.prop_decidable`.
We don't want to redo all lemmas of `finset.filter` for `has_sep.sep`, so we make sure that `simp`
unfolds the notation `{ x ∈ s | p x }` to `finset.filter s p`. If `p` happens to be decidable, the
simp-lemma `filter_congr_decidable` will make sure that `finset.filter` uses the right instance
for decidability.
-/
noncomputable instance {α : Type*} : has_sep α (finset α) := ⟨λ p x, x.filter p⟩
@[simp] lemma sep_def {α : Type*} (s : finset α) (p : α → Prop) : {x ∈ s | p x} = s.filter p := rfl
end classical
/--
After filtering out everything that does not equal a given value, at most that value remains.
This is equivalent to `filter_eq'` with the equality the other way.
-/
-- This is not a good simp lemma, as it would prevent `finset.mem_filter` from firing
-- on, e.g. `x ∈ s.filter(eq b)`.
lemma filter_eq [decidable_eq β] (s : finset β) (b : β) :
s.filter (eq b) = ite (b ∈ s) {b} ∅ :=
begin
split_ifs,
{ ext,
simp only [mem_filter, mem_singleton],
exact ⟨λ h, h.2.symm, by { rintro ⟨h⟩, exact ⟨h, rfl⟩, }⟩ },
{ ext,
simp only [mem_filter, not_and, iff_false, not_mem_empty],
rintros m ⟨e⟩, exact h m, }
end
/--
After filtering out everything that does not equal a given value, at most that value remains.
This is equivalent to `filter_eq` with the equality the other way.
-/
lemma filter_eq' [decidable_eq β] (s : finset β) (b : β) :
s.filter (λ a, a = b) = ite (b ∈ s) {b} ∅ :=
trans (filter_congr (λ _ _, ⟨eq.symm, eq.symm⟩)) (filter_eq s b)
lemma filter_ne [decidable_eq β] (s : finset β) (b : β) :
s.filter (λ a, b ≠ a) = s.erase b :=
by { ext, simp only [mem_filter, mem_erase, ne.def], tauto, }
lemma filter_ne' [decidable_eq β] (s : finset β) (b : β) :
s.filter (λ a, a ≠ b) = s.erase b :=
trans (filter_congr (λ _ _, ⟨ne.symm, ne.symm⟩)) (filter_ne s b)
end filter
/-! ### range -/
section range
variables {n m l : ℕ}
/-- `range n` is the set of natural numbers less than `n`. -/
def range (n : ℕ) : finset ℕ := ⟨_, nodup_range n⟩
@[simp] theorem range_coe (n : ℕ) : (range n).1 = multiset.range n := rfl
@[simp] theorem mem_range : m ∈ range n ↔ m < n := mem_range
@[simp] theorem range_zero : range 0 = ∅ := rfl
@[simp] theorem range_one : range 1 = {0} := rfl
theorem range_succ : range (succ n) = insert n (range n) :=
eq_of_veq $ (range_succ n).trans $ (ndinsert_of_not_mem not_mem_range_self).symm
theorem range_add_one : range (n + 1) = insert n (range n) :=
range_succ
@[simp] theorem not_mem_range_self : n ∉ range n := not_mem_range_self
@[simp] theorem self_mem_range_succ (n : ℕ) : n ∈ range (n + 1) := multiset.self_mem_range_succ n
@[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := range_subset
theorem range_mono : monotone range := λ _ _, range_subset.2
lemma mem_range_succ_iff {a b : ℕ} : a ∈ finset.range b.succ ↔ a ≤ b :=
finset.mem_range.trans nat.lt_succ_iff
lemma mem_range_le {n x : ℕ} (hx : x ∈ range n) : x ≤ n :=
(mem_range.1 hx).le
lemma mem_range_sub_ne_zero {n x : ℕ} (hx : x ∈ range n) : n - x ≠ 0 :=
ne_of_gt $ nat.sub_pos_of_lt $ mem_range.1 hx
end range
/- useful rules for calculations with quantifiers -/
theorem exists_mem_empty_iff (p : α → Prop) : (∃ x, x ∈ (∅ : finset α) ∧ p x) ↔ false :=
by simp only [not_mem_empty, false_and, exists_false]
theorem exists_mem_insert [d : decidable_eq α]
(a : α) (s : finset α) (p : α → Prop) :
(∃ x, x ∈ insert a s ∧ p x) ↔ p a ∨ (∃ x, x ∈ s ∧ p x) :=
by simp only [mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left]
theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : finset α) → p x) ↔ true :=
iff_true_intro $ λ _, false.elim
theorem forall_mem_insert [d : decidable_eq α]
(a : α) (s : finset α) (p : α → Prop) :
(∀ x, x ∈ insert a s → p x) ↔ p a ∧ (∀ x, x ∈ s → p x) :=
by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq]
end finset
/-- Equivalence between the set of natural numbers which are `≥ k` and `ℕ`, given by `n → n - k`. -/
def not_mem_range_equiv (k : ℕ) : {n // n ∉ range k} ≃ ℕ :=
{ to_fun := λ i, i.1 - k,
inv_fun := λ j, ⟨j + k, by simp⟩,
left_inv :=
begin
assume j,
rw subtype.ext_iff_val,
apply nat.sub_add_cancel,
simpa using j.2
end,
right_inv := λ j, nat.add_sub_cancel _ _ }
@[simp] lemma coe_not_mem_range_equiv (k : ℕ) :
(not_mem_range_equiv k : {n // n ∉ range k} → ℕ) = (λ i, i - k) := rfl
@[simp] lemma coe_not_mem_range_equiv_symm (k : ℕ) :
((not_mem_range_equiv k).symm : ℕ → {n // n ∉ range k}) = λ j, ⟨j + k, by simp⟩ := rfl
namespace option
/-- Construct an empty or singleton finset from an `option` -/
def to_finset (o : option α) : finset α :=
match o with
| none := ∅
| some a := {a}
end
@[simp] theorem to_finset_none : none.to_finset = (∅ : finset α) := rfl
@[simp] theorem to_finset_some {a : α} : (some a).to_finset = {a} := rfl
@[simp] theorem mem_to_finset {a : α} {o : option α} : a ∈ o.to_finset ↔ a ∈ o :=
by cases o; simp only [to_finset, finset.mem_singleton, option.mem_def, eq_comm]; refl
end option
/-! ### erase_dup on list and multiset -/
namespace multiset
variable [decidable_eq α]
/-- `to_finset s` removes duplicates from the multiset `s` to produce a finset. -/
def to_finset (s : multiset α) : finset α := ⟨_, nodup_erase_dup s⟩
@[simp] theorem to_finset_val (s : multiset α) : s.to_finset.1 = s.erase_dup := rfl
theorem to_finset_eq {s : multiset α} (n : nodup s) : finset.mk s n = s.to_finset :=
finset.val_inj.1 (erase_dup_eq_self.2 n).symm
@[simp] theorem mem_to_finset {a : α} {s : multiset α} : a ∈ s.to_finset ↔ a ∈ s :=
mem_erase_dup
@[simp] lemma to_finset_zero :
to_finset (0 : multiset α) = ∅ :=
rfl
@[simp] lemma to_finset_cons (a : α) (s : multiset α) :
to_finset (a ::ₘ s) = insert a (to_finset s) :=
finset.eq_of_veq erase_dup_cons
@[simp] lemma to_finset_add (s t : multiset α) :
to_finset (s + t) = to_finset s ∪ to_finset t :=
finset.ext $ by simp
@[simp] lemma to_finset_nsmul (s : multiset α) :
∀(n : ℕ) (hn : n ≠ 0), (n •ℕ s).to_finset = s.to_finset
| 0 h := by contradiction
| (n+1) h :=
begin
by_cases n = 0,
{ rw [h, zero_add, one_nsmul] },
{ rw [add_nsmul, to_finset_add, one_nsmul, to_finset_nsmul n h, finset.union_idempotent] }
end
@[simp] lemma to_finset_inter (s t : multiset α) :
to_finset (s ∩ t) = to_finset s ∩ to_finset t :=
finset.ext $ by simp
@[simp] lemma to_finset_union (s t : multiset α) :
(s ∪ t).to_finset = s.to_finset ∪ t.to_finset :=
by ext; simp
theorem to_finset_eq_empty {m : multiset α} : m.to_finset = ∅ ↔ m = 0 :=
finset.val_inj.symm.trans multiset.erase_dup_eq_zero
@[simp] lemma to_finset_subset (m1 m2 : multiset α) :
m1.to_finset ⊆ m2.to_finset ↔ m1 ⊆ m2 :=
by simp only [finset.subset_iff, multiset.subset_iff, multiset.mem_to_finset]
end multiset
namespace finset
@[simp] lemma val_to_finset [decidable_eq α] (s : finset α) : s.val.to_finset = s :=
by { ext, rw [multiset.mem_to_finset, ←mem_def] }
end finset
namespace list
variable [decidable_eq α]
/-- `to_finset l` removes duplicates from the list `l` to produce a finset. -/
def to_finset (l : list α) : finset α := multiset.to_finset l
@[simp] theorem to_finset_val (l : list α) : l.to_finset.1 = (l.erase_dup : multiset α) := rfl
theorem to_finset_eq {l : list α} (n : nodup l) : @finset.mk α l n = l.to_finset :=
multiset.to_finset_eq n
@[simp] theorem mem_to_finset {a : α} {l : list α} : a ∈ l.to_finset ↔ a ∈ l :=
mem_erase_dup
@[simp] theorem to_finset_nil : to_finset (@nil α) = ∅ :=
rfl
@[simp] theorem to_finset_cons {a : α} {l : list α} : to_finset (a :: l) = insert a (to_finset l) :=
finset.eq_of_veq $ by by_cases h : a ∈ l; simp [finset.insert_val', multiset.erase_dup_cons, h]
lemma to_finset_surj_on : set.surj_on to_finset {l : list α | l.nodup} set.univ :=
begin
rintro s -,
cases s with t hl, induction t using quot.ind with l,
refine ⟨l, hl, (to_finset_eq hl).symm⟩
end
theorem to_finset_surjective : surjective (to_finset : list α → finset α) :=
by { intro s, rcases to_finset_surj_on (set.mem_univ s) with ⟨l, -, hls⟩, exact ⟨l, hls⟩ }
end list
namespace finset
/-! ### map -/
section map
open function
/-- When `f` is an embedding of `α` in `β` and `s` is a finset in `α`, then `s.map f` is the image
finset in `β`. The embedding condition guarantees that there are no duplicates in the image. -/
def map (f : α ↪ β) (s : finset α) : finset β :=
⟨s.1.map f, nodup_map f.2 s.2⟩
@[simp] theorem map_val (f : α ↪ β) (s : finset α) : (map f s).1 = s.1.map f := rfl
@[simp] theorem map_empty (f : α ↪ β) : (∅ : finset α).map f = ∅ := rfl
variables {f : α ↪ β} {s : finset α}
@[simp] theorem mem_map {b : β} : b ∈ s.map f ↔ ∃ a ∈ s, f a = b :=
mem_map.trans $ by simp only [exists_prop]; refl
@[simp] theorem mem_map_equiv {f : α ≃ β} {b : β} :
b ∈ s.map f.to_embedding ↔ f.symm b ∈ s :=
by { rw mem_map, exact ⟨by { rintro ⟨a, H, rfl⟩, simpa }, λ h, ⟨_, h, by simp⟩⟩ }
theorem mem_map' (f : α ↪ β) {a} {s : finset α} : f a ∈ s.map f ↔ a ∈ s :=
mem_map_of_injective f.2
theorem mem_map_of_mem (f : α ↪ β) {a} {s : finset α} : a ∈ s → f a ∈ s.map f :=
(mem_map' _).2
@[simp, norm_cast] theorem coe_map (f : α ↪ β) (s : finset α) : (↑(s.map f) : set β) = f '' ↑s :=
set.ext $ λ x, mem_map.trans set.mem_image_iff_bex.symm
theorem coe_map_subset_range (f : α ↪ β) (s : finset α) : (↑(s.map f) : set β) ⊆ set.range f :=
calc ↑(s.map f) = f '' ↑s : coe_map f s
... ⊆ set.range f : set.image_subset_range f ↑s
theorem map_to_finset [decidable_eq α] [decidable_eq β] {s : multiset α} :
s.to_finset.map f = (s.map f).to_finset :=
ext $ λ _, by simp only [mem_map, multiset.mem_map, exists_prop, multiset.mem_to_finset]
@[simp] theorem map_refl : s.map (embedding.refl _) = s :=
ext $ λ _, by simpa only [mem_map, exists_prop] using exists_eq_right
theorem map_map {g : β ↪ γ} : (s.map f).map g = s.map (f.trans g) :=
eq_of_veq $ by simp only [map_val, multiset.map_map]; refl
theorem map_subset_map {s₁ s₂ : finset α} : s₁.map f ⊆ s₂.map f ↔ s₁ ⊆ s₂ :=
⟨λ h x xs, (mem_map' _).1 $ h $ (mem_map' f).2 xs,
λ h, by simp [subset_def, map_subset_map h]⟩
theorem map_inj {s₁ s₂ : finset α} : s₁.map f = s₂.map f ↔ s₁ = s₂ :=
by simp only [subset.antisymm_iff, map_subset_map]
/-- Associate to an embedding `f` from `α` to `β` the embedding that maps a finset to its image
under `f`. -/
def map_embedding (f : α ↪ β) : finset α ↪ finset β := ⟨map f, λ s₁ s₂, map_inj.1⟩
@[simp] theorem map_embedding_apply : map_embedding f s = map f s := rfl
theorem map_filter {p : β → Prop} [decidable_pred p] :
(s.map f).filter p = (s.filter (p ∘ f)).map f :=
eq_of_veq (map_filter _ _ _)
theorem map_union [decidable_eq α] [decidable_eq β]
{f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).map f = s₁.map f ∪ s₂.map f :=
ext $ λ _, by simp only [mem_map, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib]
theorem map_inter [decidable_eq α] [decidable_eq β]
{f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∩ s₂).map f = s₁.map f ∩ s₂.map f :=
ext $ λ b, by simp only [mem_map, mem_inter, exists_prop]; exact
⟨by rintro ⟨a, ⟨m₁, m₂⟩, rfl⟩; exact ⟨⟨a, m₁, rfl⟩, ⟨a, m₂, rfl⟩⟩,
by rintro ⟨⟨a, m₁, e⟩, ⟨a', m₂, rfl⟩⟩; cases f.2 e; exact ⟨_, ⟨m₁, m₂⟩, rfl⟩⟩
@[simp] theorem map_singleton (f : α ↪ β) (a : α) : map f {a} = {f a} :=
ext $ λ _, by simp only [mem_map, mem_singleton, exists_prop, exists_eq_left]; exact eq_comm
@[simp] theorem map_insert [decidable_eq α] [decidable_eq β]
(f : α ↪ β) (a : α) (s : finset α) :
(insert a s).map f = insert (f a) (s.map f) :=
by simp only [insert_eq, map_union, map_singleton]
@[simp] theorem map_eq_empty : s.map f = ∅ ↔ s = ∅ :=
⟨λ h, eq_empty_of_forall_not_mem $
λ a m, ne_empty_of_mem (mem_map_of_mem _ m) h, λ e, e.symm ▸ rfl⟩
lemma attach_map_val {s : finset α} : s.attach.map (embedding.subtype _) = s :=
eq_of_veq $ by rw [map_val, attach_val]; exact attach_map_val _
lemma nonempty.map (h : s.nonempty) (f : α ↪ β) : (s.map f).nonempty :=
let ⟨a, ha⟩ := h in ⟨f a, (mem_map' f).mpr ha⟩
end map
lemma range_add_one' (n : ℕ) :
range (n + 1) = insert 0 ((range n).map ⟨λi, i + 1, assume i j, nat.succ.inj⟩) :=
by ext (⟨⟩ | ⟨n⟩); simp [nat.succ_eq_add_one, nat.zero_lt_succ n]
/-! ### image -/
section image
variables [decidable_eq β]
/-- `image f s` is the forward image of `s` under `f`. -/
def image (f : α → β) (s : finset α) : finset β := (s.1.map f).to_finset
@[simp] theorem image_val (f : α → β) (s : finset α) : (image f s).1 = (s.1.map f).erase_dup := rfl
@[simp] theorem image_empty (f : α → β) : (∅ : finset α).image f = ∅ := rfl
variables {f : α → β} {s : finset α}
@[simp] theorem mem_image {b : β} : b ∈ s.image f ↔ ∃ a ∈ s, f a = b :=
by simp only [mem_def, image_val, mem_erase_dup, multiset.mem_map, exists_prop]
theorem mem_image_of_mem (f : α → β) {a} {s : finset α} (h : a ∈ s) : f a ∈ s.image f :=
mem_image.2 ⟨_, h, rfl⟩
lemma filter_mem_image_eq_image (f : α → β) (s : finset α) (t : finset β) (h : ∀ x ∈ s, f x ∈ t) :
t.filter (λ y, y ∈ s.image f) = s.image f :=
by { ext, rw [mem_filter, mem_image],
simp only [and_imp, exists_prop, and_iff_right_iff_imp, exists_imp_distrib],
rintros x xel rfl, exact h _ xel }
lemma fiber_nonempty_iff_mem_image (f : α → β) (s : finset α) (y : β) :
(s.filter (λ x, f x = y)).nonempty ↔ y ∈ s.image f :=
by simp [finset.nonempty]
@[simp, norm_cast] lemma coe_image {f : α → β} : ↑(s.image f) = f '' ↑s :=
set.ext $ λ _, mem_image.trans set.mem_image_iff_bex.symm
lemma nonempty.image (h : s.nonempty) (f : α → β) : (s.image f).nonempty :=
let ⟨a, ha⟩ := h in ⟨f a, mem_image_of_mem f ha⟩
@[simp]
lemma nonempty.image_iff (f : α → β) : (s.image f).nonempty ↔ s.nonempty :=
⟨λ ⟨y, hy⟩, let ⟨x, hx, _⟩ := mem_image.mp hy in ⟨x, hx⟩, λ h, h.image f⟩
theorem image_to_finset [decidable_eq α] {s : multiset α} :
s.to_finset.image f = (s.map f).to_finset :=
ext $ λ _, by simp only [mem_image, multiset.mem_to_finset, exists_prop, multiset.mem_map]
theorem image_val_of_inj_on (H : set.inj_on f s) : (image f s).1 = s.1.map f :=
multiset.erase_dup_eq_self.2 (nodup_map_on H s.2)
@[simp]
theorem image_id [decidable_eq α] : s.image id = s :=
ext $ λ _, by simp only [mem_image, exists_prop, id, exists_eq_right]
theorem image_image [decidable_eq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) :=
eq_of_veq $ by simp only [image_val, erase_dup_map_erase_dup_eq, multiset.map_map]
theorem image_subset_image {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁.image f ⊆ s₂.image f :=
by simp only [subset_def, image_val, subset_erase_dup', erase_dup_subset',
multiset.map_subset_map h]
theorem image_subset_iff {s : finset α} {t : finset β} {f : α → β} :
s.image f ⊆ t ↔ ∀ x ∈ s, f x ∈ t :=
calc s.image f ⊆ t ↔ f '' ↑s ⊆ ↑t : by norm_cast
... ↔ _ : set.image_subset_iff
theorem image_mono (f : α → β) : monotone (finset.image f) := λ _ _, image_subset_image
theorem coe_image_subset_range : ↑(s.image f) ⊆ set.range f :=
calc ↑(s.image f) = f '' ↑s : coe_image
... ⊆ set.range f : set.image_subset_range f ↑s
theorem image_filter {p : β → Prop} [decidable_pred p] :
(s.image f).filter p = (s.filter (p ∘ f)).image f :=
ext $ λ b, by simp only [mem_filter, mem_image, exists_prop]; exact
⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, ⟨h1, h2⟩, rfl⟩,
by rintro ⟨x, ⟨h1, h2⟩, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩
theorem image_union [decidable_eq α] {f : α → β} (s₁ s₂ : finset α) :
(s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f :=
ext $ λ _, by simp only [mem_image, mem_union, exists_prop, or_and_distrib_right,
exists_or_distrib]
theorem image_inter [decidable_eq α] (s₁ s₂ : finset α) (hf : ∀x y, f x = f y → x = y) :
(s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f :=
ext $ by simp only [mem_image, exists_prop, mem_inter]; exact λ b,
⟨λ ⟨a, ⟨m₁, m₂⟩, e⟩, ⟨⟨a, m₁, e⟩, ⟨a, m₂, e⟩⟩,
λ ⟨⟨a, m₁, e₁⟩, ⟨a', m₂, e₂⟩⟩, ⟨a, ⟨m₁, hf _ _ (e₂.trans e₁.symm) ▸ m₂⟩, e₁⟩⟩.
@[simp] theorem image_singleton (f : α → β) (a : α) : image f {a} = {f a} :=
ext $ λ x, by simpa only [mem_image, exists_prop, mem_singleton, exists_eq_left] using eq_comm
@[simp] theorem image_insert [decidable_eq α] (f : α → β) (a : α) (s : finset α) :
(insert a s).image f = insert (f a) (s.image f) :=
by simp only [insert_eq, image_singleton, image_union]
@[simp] theorem image_eq_empty : s.image f = ∅ ↔ s = ∅ :=
⟨λ h, eq_empty_of_forall_not_mem $
λ a m, ne_empty_of_mem (mem_image_of_mem _ m) h, λ e, e.symm ▸ rfl⟩
lemma mem_range_iff_mem_finset_range_of_mod_eq' [decidable_eq α] {f : ℕ → α} {a : α} {n : ℕ}
(hn : 0 < n) (h : ∀i, f (i % n) = f i) :
a ∈ set.range f ↔ a ∈ (finset.range n).image (λi, f i) :=
begin
split,
{ rintros ⟨i, hi⟩,
simp only [mem_image, exists_prop, mem_range],
exact ⟨i % n, nat.mod_lt i hn, (rfl.congr hi).mp (h i)⟩ },
{ rintro h,
simp only [mem_image, exists_prop, set.mem_range, mem_range] at *,
rcases h with ⟨i, hi, ha⟩,
use ⟨i, ha⟩ },
end
lemma mem_range_iff_mem_finset_range_of_mod_eq [decidable_eq α] {f : ℤ → α} {a : α} {n : ℕ}
(hn : 0 < n) (h : ∀i, f (i % n) = f i) :
a ∈ set.range f ↔ a ∈ (finset.range n).image (λi, f i) :=
suffices (∃i, f (i % n) = a) ↔ ∃i, i < n ∧ f ↑i = a, by simpa [h],
have hn' : 0 < (n : ℤ), from int.coe_nat_lt.mpr hn,
iff.intro
(assume ⟨i, hi⟩,
have 0 ≤ i % ↑n, from int.mod_nonneg _ (ne_of_gt hn'),
⟨int.to_nat (i % n),
by rw [←int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos i hn', hi⟩⟩)
(assume ⟨i, hi, ha⟩,
⟨i, by rw [int.mod_eq_of_lt (int.coe_zero_le _) (int.coe_nat_lt_coe_nat_of_lt hi), ha]⟩)
lemma attach_image_val [decidable_eq α] {s : finset α} : s.attach.image subtype.val = s :=
eq_of_veq $ by rw [image_val, attach_val, multiset.attach_map_val, erase_dup_eq_self]
@[simp] lemma attach_insert [decidable_eq α] {a : α} {s : finset α} :
attach (insert a s) = insert (⟨a, mem_insert_self a s⟩ : {x // x ∈ insert a s})
((attach s).image (λx, ⟨x.1, mem_insert_of_mem x.2⟩)) :=
ext $ λ ⟨x, hx⟩, ⟨or.cases_on (mem_insert.1 hx)
(λ h : x = a, λ _, mem_insert.2 $ or.inl $ subtype.eq h)
(λ h : x ∈ s, λ _, mem_insert_of_mem $ mem_image.2 $ ⟨⟨x, h⟩, mem_attach _ _, subtype.eq rfl⟩),
λ _, finset.mem_attach _ _⟩
theorem map_eq_image (f : α ↪ β) (s : finset α) : s.map f = s.image f :=
eq_of_veq $ (multiset.erase_dup_eq_self.2 (s.map f).2).symm
lemma image_const {s : finset α} (h : s.nonempty) (b : β) : s.image (λa, b) = singleton b :=
ext $ assume b', by simp only [mem_image, exists_prop, exists_and_distrib_right,
h.bex, true_and, mem_singleton, eq_comm]
/--
Because `finset.image` requires a `decidable_eq` instances for the target type,
we can only construct a `functor finset` when working classically.
-/
instance [Π P, decidable P] : functor finset :=
{ map := λ α β f s, s.image f, }
instance [Π P, decidable P] : is_lawful_functor finset :=
{ id_map := λ α x, image_id,
comp_map := λ α β γ f g s, image_image.symm, }
/-- Given a finset `s` and a predicate `p`, `s.subtype p` is the finset of `subtype p` whose
elements belong to `s`. -/
protected def subtype {α} (p : α → Prop) [decidable_pred p] (s : finset α) : finset (subtype p) :=
(s.filter p).attach.map ⟨λ x, ⟨x.1, (finset.mem_filter.1 x.2).2⟩,
λ x y H, subtype.eq $ subtype.mk.inj H⟩
@[simp] lemma mem_subtype {p : α → Prop} [decidable_pred p] {s : finset α} :
∀{a : subtype p}, a ∈ s.subtype p ↔ (a : α) ∈ s
| ⟨a, ha⟩ := by simp [finset.subtype, ha]
lemma subtype_eq_empty {p : α → Prop} [decidable_pred p] {s : finset α} :
s.subtype p = ∅ ↔ ∀ x, p x → x ∉ s :=
by simp [ext_iff, subtype.forall, subtype.coe_mk]; refl
/-- `s.subtype p` converts back to `s.filter p` with
`embedding.subtype`. -/
@[simp] lemma subtype_map (p : α → Prop) [decidable_pred p] :
(s.subtype p).map (embedding.subtype _) = s.filter p :=
begin
ext x,
rw mem_map,
change (∃ a : {x // p x}, ∃ H, (a : α) = x) ↔ _,
split,
{ rintros ⟨y, hy, hyval⟩,
rw [mem_subtype, hyval] at hy,
rw mem_filter,
use hy,
rw ← hyval,
use y.property },
{ intro hx,
rw mem_filter at hx,
use ⟨⟨x, hx.2⟩, mem_subtype.2 hx.1, rfl⟩ }
end
/-- If all elements of a `finset` satisfy the predicate `p`,
`s.subtype p` converts back to `s` with `embedding.subtype`. -/
lemma subtype_map_of_mem {p : α → Prop} [decidable_pred p] (h : ∀ x ∈ s, p x) :
(s.subtype p).map (embedding.subtype _) = s :=
by rw [subtype_map, filter_true_of_mem h]
/-- If a `finset` of a subtype is converted to the main type with
`embedding.subtype`, all elements of the result have the property of
the subtype. -/
lemma property_of_mem_map_subtype {p : α → Prop} (s : finset {x // p x}) {a : α}
(h : a ∈ s.map (embedding.subtype _)) : p a :=
begin
rcases mem_map.1 h with ⟨x, hx, rfl⟩,
exact x.2
end
/-- If a `finset` of a subtype is converted to the main type with
`embedding.subtype`, the result does not contain any value that does
not satisfy the property of the subtype. -/
lemma not_mem_map_subtype_of_not_property {p : α → Prop} (s : finset {x // p x})
{a : α} (h : ¬ p a) : a ∉ (s.map (embedding.subtype _)) :=
mt s.property_of_mem_map_subtype h
/-- If a `finset` of a subtype is converted to the main type with
`embedding.subtype`, the result is a subset of the set giving the
subtype. -/
lemma map_subtype_subset {t : set α} (s : finset t) :
↑(s.map (embedding.subtype _)) ⊆ t :=
begin
intros a ha,
rw mem_coe at ha,
convert property_of_mem_map_subtype s ha
end
lemma subset_image_iff {f : α → β}
{s : finset β} {t : set α} : ↑s ⊆ f '' t ↔ ∃s' : finset α, ↑s' ⊆ t ∧ s'.image f = s :=
begin
classical,
split, swap,
{ rintro ⟨s, hs, rfl⟩, rw [coe_image], exact set.image_subset f hs },
intro h, induction s using finset.induction with a s has ih h,
{ refine ⟨∅, set.empty_subset _, _⟩,
convert finset.image_empty _ },
rw [finset.coe_insert, set.insert_subset] at h,
rcases ih h.2 with ⟨s', hst, hsi⟩,
rcases h.1 with ⟨x, hxt, rfl⟩,
refine ⟨insert x s', _, _⟩,
{ rw [finset.coe_insert, set.insert_subset], exact ⟨hxt, hst⟩ },
rw [finset.image_insert, hsi],
congr
end
end image
end finset
theorem multiset.to_finset_map [decidable_eq α] [decidable_eq β] (f : α → β) (m : multiset α) :
(m.map f).to_finset = m.to_finset.image f :=
finset.val_inj.1 (multiset.erase_dup_map_erase_dup_eq _ _).symm
namespace finset
/-! ### card -/
section card
/-- `card s` is the cardinality (number of elements) of `s`. -/
def card (s : finset α) : nat := s.1.card
theorem card_def (s : finset α) : s.card = s.1.card := rfl
@[simp] lemma card_mk {m nodup} : (⟨m, nodup⟩ : finset α).card = m.card := rfl
@[simp] theorem card_empty : card (∅ : finset α) = 0 := rfl
@[simp] theorem card_eq_zero {s : finset α} : card s = 0 ↔ s = ∅ :=
card_eq_zero.trans val_eq_zero
theorem card_pos {s : finset α} : 0 < card s ↔ s.nonempty :=
pos_iff_ne_zero.trans $ (not_congr card_eq_zero).trans nonempty_iff_ne_empty.symm
theorem card_ne_zero_of_mem {s : finset α} {a : α} (h : a ∈ s) : card s ≠ 0 :=
(not_congr card_eq_zero).2 (ne_empty_of_mem h)
theorem card_eq_one {s : finset α} : s.card = 1 ↔ ∃ a, s = {a} :=
by cases s; simp only [multiset.card_eq_one, finset.card, ← val_inj, singleton_val]
theorem card_le_one {s : finset α} : s.card ≤ 1 ↔ ∀ (a ∈ s) (b ∈ s), a = b :=
begin
rcases s.eq_empty_or_nonempty with rfl|⟨x, hx⟩, { simp },
refine (nat.succ_le_of_lt (card_pos.2 ⟨x, hx⟩)).le_iff_eq.trans (card_eq_one.trans ⟨_, _⟩),
{ rintro ⟨y, rfl⟩, simp },
{ exact λ h, ⟨x, eq_singleton_iff_unique_mem.2 ⟨hx, λ y hy, h _ hy _ hx⟩⟩ }
end
theorem one_lt_card {s : finset α} : 1 < s.card ↔ ∃ (a ∈ s) (b ∈ s), a ≠ b :=
by { rw ← not_iff_not, push_neg, exact card_le_one }
@[simp] theorem card_insert_of_not_mem [decidable_eq α]
{a : α} {s : finset α} (h : a ∉ s) : card (insert a s) = card s + 1 :=
by simpa only [card_cons, card, insert_val] using
congr_arg multiset.card (ndinsert_of_not_mem h)
theorem card_insert_of_mem [decidable_eq α] {a : α} {s : finset α}
(h : a ∈ s) : card (insert a s) = card s := by rw insert_eq_of_mem h
theorem card_insert_le [decidable_eq α] (a : α) (s : finset α) : card (insert a s) ≤ card s + 1 :=
by by_cases a ∈ s; [{rw [insert_eq_of_mem h], apply nat.le_add_right},
rw [card_insert_of_not_mem h]]
@[simp] theorem card_singleton (a : α) : card ({a} : finset α) = 1 := card_singleton _
lemma card_singleton_inter [decidable_eq α] {x : α} {s : finset α} : ({x} ∩ s).card ≤ 1 :=
begin
cases (finset.decidable_mem x s),
{ simp [finset.singleton_inter_of_not_mem h] },
{ simp [finset.singleton_inter_of_mem h] },
end
theorem card_erase_of_mem [decidable_eq α] {a : α} {s : finset α} :
a ∈ s → card (erase s a) = pred (card s) := card_erase_of_mem
theorem card_erase_lt_of_mem [decidable_eq α] {a : α} {s : finset α} :
a ∈ s → card (erase s a) < card s := card_erase_lt_of_mem
theorem card_erase_le [decidable_eq α] {a : α} {s : finset α} :
card (erase s a) ≤ card s := card_erase_le
theorem pred_card_le_card_erase [decidable_eq α] {a : α} {s : finset α} :
card s - 1 ≤ card (erase s a) :=
begin
by_cases h : a ∈ s,
{ rw [card_erase_of_mem h], refl },
{ rw [erase_eq_of_not_mem h], apply nat.sub_le }
end
@[simp] theorem card_range (n : ℕ) : card (range n) = n := card_range n
@[simp] theorem card_attach {s : finset α} : card (attach s) = card s := multiset.card_attach
end card
end finset
theorem multiset.to_finset_card_le [decidable_eq α] (m : multiset α) : m.to_finset.card ≤ m.card :=
card_le_of_le (erase_dup_le _)
theorem list.to_finset_card_le [decidable_eq α] (l : list α) : l.to_finset.card ≤ l.length :=
multiset.to_finset_card_le ⟦l⟧
namespace finset
section card
theorem card_image_le [decidable_eq β] {f : α → β} {s : finset α} : card (image f s) ≤ card s :=
by simpa only [card_map] using (s.1.map f).to_finset_card_le
theorem card_image_of_inj_on [decidable_eq β] {f : α → β} {s : finset α}
(H : set.inj_on f s) : card (image f s) = card s :=
by simp only [card, image_val_of_inj_on H, card_map]
theorem inj_on_of_card_image_eq [decidable_eq β] {f : α → β} {s : finset α}
(H : card (image f s) = card s) :
set.inj_on f s :=
begin
change (s.1.map f).erase_dup.card = s.1.card at H,
have : (s.1.map f).erase_dup = s.1.map f,
{ apply multiset.eq_of_le_of_card_le,
{ apply multiset.erase_dup_le },
rw H,
simp only [multiset.card_map] },
rw multiset.erase_dup_eq_self at this,
apply inj_on_of_nodup_map this,
end
theorem card_image_eq_iff_inj_on [decidable_eq β] {f : α → β} {s : finset α} :
(s.image f).card = s.card ↔ set.inj_on f s :=
⟨inj_on_of_card_image_eq, card_image_of_inj_on⟩
theorem card_image_of_injective [decidable_eq β] {f : α → β} (s : finset α)
(H : injective f) : card (image f s) = card s :=
card_image_of_inj_on $ λ x _ y _ h, H h
lemma fiber_card_ne_zero_iff_mem_image (s : finset α) (f : α → β) [decidable_eq β] (y : β) :
(s.filter (λ x, f x = y)).card ≠ 0 ↔ y ∈ s.image f :=
by { rw [←pos_iff_ne_zero, card_pos, fiber_nonempty_iff_mem_image] }
@[simp] lemma card_map {α β} (f : α ↪ β) {s : finset α} : (s.map f).card = s.card :=
multiset.card_map _ _
@[simp] lemma card_subtype (p : α → Prop) [decidable_pred p] (s : finset α) :
(s.subtype p).card = (s.filter p).card :=
by simp [finset.subtype]
lemma card_eq_of_bijective {s : finset α} {n : ℕ}
(f : ∀i, i < n → α)
(hf : ∀a∈s, ∃i, ∃h:i<n, f i h = a) (hf' : ∀i (h : i < n), f i h ∈ s)
(f_inj : ∀i j (hi : i < n) (hj : j < n), f i hi = f j hj → i = j) :
card s = n :=
begin
classical,
have : ∀ (a : α), a ∈ s ↔ ∃i (hi : i ∈ range n), f i (mem_range.1 hi) = a,
from assume a, ⟨assume ha, let ⟨i, hi, eq⟩ := hf a ha in ⟨i, mem_range.2 hi, eq⟩,
assume ⟨i, hi, eq⟩, eq ▸ hf' i (mem_range.1 hi)⟩,
have : s = ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)),
by simpa only [ext_iff, mem_image, exists_prop, subtype.exists, mem_attach, true_and],
calc card s = card ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)) :
by rw [this]
... = card ((range n).attach) :
card_image_of_injective _ $ assume ⟨i, hi⟩ ⟨j, hj⟩ eq,
subtype.eq $ f_inj i j (mem_range.1 hi) (mem_range.1 hj) eq
... = card (range n) : card_attach
... = n : card_range n
end
lemma card_eq_succ [decidable_eq α] {s : finset α} {n : ℕ} :
s.card = n + 1 ↔ (∃a t, a ∉ t ∧ insert a t = s ∧ card t = n) :=
iff.intro
(assume eq,
have 0 < card s, from eq.symm ▸ nat.zero_lt_succ _,
let ⟨a, has⟩ := card_pos.mp this in
⟨a, s.erase a, s.not_mem_erase a, insert_erase has,
by simp only [eq, card_erase_of_mem has, pred_succ]⟩)
(assume ⟨a, t, hat, s_eq, n_eq⟩, s_eq ▸ n_eq ▸ card_insert_of_not_mem hat)
theorem card_le_of_subset {s t : finset α} : s ⊆ t → card s ≤ card t :=
multiset.card_le_of_le ∘ val_le_iff.mpr
theorem card_filter_le (s : finset α) (p : α → Prop) [decidable_pred p] :
card (s.filter p) ≤ card s :=
card_le_of_subset $ filter_subset _ _
theorem eq_of_subset_of_card_le {s t : finset α} (h : s ⊆ t) (h₂ : card t ≤ card s) : s = t :=
eq_of_veq $ multiset.eq_of_le_of_card_le (val_le_iff.mpr h) h₂
lemma card_lt_card {s t : finset α} (h : s ⊂ t) : s.card < t.card :=
card_lt_of_lt (val_lt_iff.2 h)
lemma card_le_card_of_inj_on {s : finset α} {t : finset β}
(f : α → β) (hf : ∀a∈s, f a ∈ t) (f_inj : ∀a₁∈s, ∀a₂∈s, f a₁ = f a₂ → a₁ = a₂) :
card s ≤ card t :=
begin
classical,
calc card s = card (s.image f) : by rw [card_image_of_inj_on f_inj]
... ≤ card t : card_le_of_subset $ image_subset_iff.2 hf
end
/--
If there are more pigeons than pigeonholes, then there are two pigeons
in the same pigeonhole.
-/
lemma exists_ne_map_eq_of_card_lt_of_maps_to {s : finset α} {t : finset β} (hc : t.card < s.card)
{f : α → β} (hf : ∀ a ∈ s, f a ∈ t) :
∃ (x ∈ s) (y ∈ s), x ≠ y ∧ f x = f y :=
begin
classical, by_contra hz, push_neg at hz,
refine hc.not_le (card_le_card_of_inj_on f hf _),
intros x hx y hy, contrapose, exact hz x hx y hy,
end
lemma le_card_of_inj_on_range {n} {s : finset α}
(f : ℕ → α) (hf : ∀i<n, f i ∈ s) (f_inj : ∀ (i<n) (j<n), f i = f j → i = j) : n ≤ card s :=
calc n = card (range n) : (card_range n).symm
... ≤ card s : card_le_card_of_inj_on f (by simpa only [mem_range]) (by simpa only [mem_range])
/-- Suppose that, given objects defined on all strict subsets of any finset `s`, one knows how to
define an object on `s`. Then one can inductively define an object on all finsets, starting from
the empty set and iterating. This can be used either to define data, or to prove properties. -/
def strong_induction {p : finset α → Sort*} (H : ∀ s, (∀ t ⊂ s, p t) → p s) :
∀ (s : finset α), p s
| s := H s (λ t h, have card t < card s, from card_lt_card h, strong_induction t)
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]}
lemma strong_induction_eq {p : finset α → Sort*} (H : ∀ s, (∀ t ⊂ s, p t) → p s) (s : finset α) :
strong_induction H s = H s (λ t h, strong_induction H t) :=
by rw strong_induction
/-- Analogue of `strong_induction` with order of arguments swapped. -/
@[elab_as_eliminator] def strong_induction_on {p : finset α → Sort*} :
∀ (s : finset α), (∀s, (∀ t ⊂ s, p t) → p s) → p s :=
λ s H, strong_induction H s
lemma strong_induction_on_eq {p : finset α → Sort*} (s : finset α) (H : ∀ s, (∀ t ⊂ s, p t) → p s) :
s.strong_induction_on H = H s (λ t h, t.strong_induction_on H) :=
by { dunfold strong_induction_on, rw strong_induction }
@[elab_as_eliminator] lemma case_strong_induction_on [decidable_eq α] {p : finset α → Prop}
(s : finset α) (h₀ : p ∅) (h₁ : ∀ a s, a ∉ s → (∀t ⊆ s, p t) → p (insert a s)) : p s :=
finset.strong_induction_on s $ λ s,
finset.induction_on s (λ _, h₀) $ λ a s n _ ih, h₁ a s n $
λ t ss, ih _ (lt_of_le_of_lt ss (ssubset_insert n) : t < _)
lemma card_congr {s : finset α} {t : finset β} (f : Π a ∈ s, β)
(h₁ : ∀ a ha, f a ha ∈ t) (h₂ : ∀ a b ha hb, f a ha = f b hb → a = b)
(h₃ : ∀ b ∈ t, ∃ a ha, f a ha = b) : s.card = t.card :=
by haveI := classical.prop_decidable; exact
calc s.card = s.attach.card : card_attach.symm
... = (s.attach.image (λ (a : {a // a ∈ s}), f a.1 a.2)).card :
eq.symm (card_image_of_injective _ (λ a b h, subtype.eq (h₂ _ _ _ _ h)))
... = t.card : congr_arg card (finset.ext $ λ b,
⟨λ h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ h₁ _ _,
λ h, let ⟨a, ha₁, ha₂⟩ := h₃ b h in mem_image.2 ⟨⟨a, ha₁⟩, by simp [ha₂]⟩⟩)
lemma card_union_add_card_inter [decidable_eq α] (s t : finset α) :
(s ∪ t).card + (s ∩ t).card = s.card + t.card :=
finset.induction_on t (by simp) $ λ a r har, by by_cases a ∈ s; simp *; cc
lemma card_union_le [decidable_eq α] (s t : finset α) :
(s ∪ t).card ≤ s.card + t.card :=
card_union_add_card_inter s t ▸ le_add_right _ _
lemma card_union_eq [decidable_eq α] {s t : finset α} (h : disjoint s t) :
(s ∪ t).card = s.card + t.card :=
begin
rw [← card_union_add_card_inter],
convert (add_zero _).symm, rw [card_eq_zero], rwa [disjoint_iff] at h
end
lemma surj_on_of_inj_on_of_card_le {s : finset α} {t : finset β}
(f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t)
(hinj : ∀ a₁ a₂ ha₁ ha₂, f a₁ ha₁ = f a₂ ha₂ → a₁ = a₂)
(hst : card t ≤ card s) :
(∀ b ∈ t, ∃ a ha, b = f a ha) :=
by haveI := classical.dec_eq β; exact
λ b hb,
have h : card (image (λ (a : {a // a ∈ s}), f a a.prop) (attach s)) = card s,
from @card_attach _ s ▸ card_image_of_injective _
(λ ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ h, subtype.eq $ hinj _ _ _ _ h),
have h₁ : image (λ a : {a // a ∈ s}, f a a.prop) s.attach = t :=
eq_of_subset_of_card_le (λ b h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in
ha₂ ▸ hf _ _) (by simp [hst, h]),
begin
rw ← h₁ at hb,
rcases mem_image.1 hb with ⟨a, ha₁, ha₂⟩,
exact ⟨a, a.2, ha₂.symm⟩,
end
open function
lemma inj_on_of_surj_on_of_card_le {s : finset α} {t : finset β}
(f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t)
(hsurj : ∀ b ∈ t, ∃ a ha, b = f a ha)
(hst : card s ≤ card t)
⦃a₁ a₂⦄ (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s)
(ha₁a₂: f a₁ ha₁ = f a₂ ha₂) : a₁ = a₂ :=
by haveI : inhabited {x // x ∈ s} := ⟨⟨a₁, ha₁⟩⟩; exact
let f' : {x // x ∈ s} → {x // x ∈ t} := λ x, ⟨f x.1 x.2, hf x.1 x.2⟩ in
let g : {x // x ∈ t} → {x // x ∈ s} :=
@surj_inv _ _ f'
(λ x, let ⟨y, hy₁, hy₂⟩ := hsurj x.1 x.2 in ⟨⟨y, hy₁⟩, subtype.eq hy₂.symm⟩) in
have hg : injective g, from injective_surj_inv _,
have hsg : surjective g, from λ x,
let ⟨y, hy⟩ := surj_on_of_inj_on_of_card_le (λ (x : {x // x ∈ t}) (hx : x ∈ t.attach), g x)
(λ x _, show (g x) ∈ s.attach, from mem_attach _ _)
(λ x y _ _ hxy, hg hxy) (by simpa) x (mem_attach _ _) in
⟨y, hy.snd.symm⟩,
have hif : injective f',
from (left_inverse_of_surjective_of_right_inverse hsg
(right_inverse_surj_inv _)).injective,
subtype.ext_iff_val.1 (@hif ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ (subtype.eq ha₁a₂))
end card
section bUnion
/-!
### bUnion
This section is about the bounded union of an indexed family `t : α → finset β` of finite sets
over a finite set `s : finset α`.
-/
variables [decidable_eq β] {s : finset α} {t : α → finset β}
/-- `bUnion s t` is the union of `t x` over `x ∈ s`.
(This was formerly `bind` due to the monad structure on types with `decidable_eq`.) -/
protected def bUnion (s : finset α) (t : α → finset β) : finset β :=
(s.1.bind (λ a, (t a).1)).to_finset
@[simp] theorem bUnion_val (s : finset α) (t : α → finset β) :
(s.bUnion t).1 = (s.1.bind (λ a, (t a).1)).erase_dup := rfl
@[simp] theorem bUnion_empty : finset.bUnion ∅ t = ∅ := rfl
@[simp] theorem mem_bUnion {b : β} : b ∈ s.bUnion t ↔ ∃a∈s, b ∈ t a :=
by simp only [mem_def, bUnion_val, mem_erase_dup, mem_bind, exists_prop]
@[simp] theorem bUnion_insert [decidable_eq α] {a : α} : (insert a s).bUnion t = t a ∪ s.bUnion t :=
ext $ λ x, by simp only [mem_bUnion, exists_prop, mem_union, mem_insert,
or_and_distrib_right, exists_or_distrib, exists_eq_left]
-- ext $ λ x, by simp [or_and_distrib_right, exists_or_distrib]
@[simp] lemma singleton_bUnion {a : α} : finset.bUnion {a} t = t a :=
begin
classical,
rw [← insert_emptyc_eq, bUnion_insert, bUnion_empty, union_empty]
end
theorem bUnion_inter (s : finset α) (f : α → finset β) (t : finset β) :
s.bUnion f ∩ t = s.bUnion (λ x, f x ∩ t) :=
begin
ext x,
simp only [mem_bUnion, mem_inter],
tauto
end
theorem inter_bUnion (t : finset β) (s : finset α) (f : α → finset β) :
t ∩ s.bUnion f = s.bUnion (λ x, t ∩ f x) :=
by rw [inter_comm, bUnion_inter]; simp [inter_comm]
theorem image_bUnion [decidable_eq γ] {f : α → β} {s : finset α} {t : β → finset γ} :
(s.image f).bUnion t = s.bUnion (λa, t (f a)) :=
by haveI := classical.dec_eq α; exact
finset.induction_on s rfl (λ a s has ih,
by simp only [image_insert, bUnion_insert, ih])
theorem bUnion_image [decidable_eq γ] {s : finset α} {t : α → finset β} {f : β → γ} :
(s.bUnion t).image f = s.bUnion (λa, (t a).image f) :=
by haveI := classical.dec_eq α; exact
finset.induction_on s rfl (λ a s has ih,
by simp only [bUnion_insert, image_union, ih])
theorem bind_to_finset [decidable_eq α] (s : multiset α) (t : α → multiset β) :
(s.bind t).to_finset = s.to_finset.bUnion (λa, (t a).to_finset) :=
ext $ λ x, by simp only [multiset.mem_to_finset, mem_bUnion, multiset.mem_bind, exists_prop]
lemma bUnion_mono {t₁ t₂ : α → finset β} (h : ∀a∈s, t₁ a ⊆ t₂ a) : s.bUnion t₁ ⊆ s.bUnion t₂ :=
have ∀b a, a ∈ s → b ∈ t₁ a → (∃ (a : α), a ∈ s ∧ b ∈ t₂ a),
from assume b a ha hb, ⟨a, ha, finset.mem_of_subset (h a ha) hb⟩,
by simpa only [subset_iff, mem_bUnion, exists_imp_distrib, and_imp, exists_prop]
lemma bUnion_subset_bUnion_of_subset_left {α : Type*} {s₁ s₂ : finset α}
(t : α → finset β) (h : s₁ ⊆ s₂) : s₁.bUnion t ⊆ s₂.bUnion t :=
begin
intro x,
simp only [and_imp, mem_bUnion, exists_prop],
exact Exists.imp (λ a ha, ⟨h ha.1, ha.2⟩)
end
lemma subset_bUnion_of_mem {s : finset α}
(u : α → finset β) {x : α} (xs : x ∈ s) :
u x ⊆ s.bUnion u :=
begin
apply subset.trans _ (bUnion_subset_bUnion_of_subset_left u (singleton_subset_iff.2 xs)),
exact subset_of_eq singleton_bUnion.symm,
end
lemma bUnion_singleton {f : α → β} : s.bUnion (λa, {f a}) = s.image f :=
ext $ λ x, by simp only [mem_bUnion, mem_image, mem_singleton, eq_comm]
@[simp] lemma bUnion_singleton_eq_self [decidable_eq α] :
s.bUnion (singleton : α → finset α) = s :=
by { rw bUnion_singleton, exact image_id }
lemma bUnion_filter_eq_of_maps_to [decidable_eq α] {s : finset α} {t : finset β} {f : α → β}
(h : ∀ x ∈ s, f x ∈ t) :
t.bUnion (λa, s.filter $ (λc, f c = a)) = s :=
ext $ λ b, by simpa using h b
lemma image_bUnion_filter_eq [decidable_eq α] (s : finset β) (g : β → α) :
(s.image g).bUnion (λa, s.filter $ (λc, g c = a)) = s :=
bUnion_filter_eq_of_maps_to (λ x, mem_image_of_mem g)
lemma erase_bUnion (f : α → finset β) (s : finset α) (b : β) :
(s.bUnion f).erase b = s.bUnion (λ x, (f x).erase b) :=
by { ext, simp only [finset.mem_bUnion, iff_self, exists_and_distrib_left, finset.mem_erase] }
end bUnion
/-! ### prod -/
section prod
variables {s : finset α} {t : finset β}
/-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/
protected def product (s : finset α) (t : finset β) : finset (α × β) := ⟨_, nodup_product s.2 t.2⟩
@[simp] theorem product_val : (s.product t).1 = s.1.product t.1 := rfl
@[simp] theorem mem_product {p : α × β} : p ∈ s.product t ↔ p.1 ∈ s ∧ p.2 ∈ t := mem_product
theorem subset_product [decidable_eq α] [decidable_eq β] {s : finset (α × β)} :
s ⊆ (s.image prod.fst).product (s.image prod.snd) :=
λ p hp, mem_product.2 ⟨mem_image_of_mem _ hp, mem_image_of_mem _ hp⟩
theorem product_eq_bUnion [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) :
s.product t = s.bUnion (λa, t.image $ λb, (a, b)) :=
ext $ λ ⟨x, y⟩, by simp only [mem_product, mem_bUnion, mem_image, exists_prop, prod.mk.inj_iff,
and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left]
@[simp] theorem card_product (s : finset α) (t : finset β) : card (s.product t) = card s * card t :=
multiset.card_product _ _
theorem filter_product (p : α → Prop) (q : β → Prop) [decidable_pred p] [decidable_pred q] :
(s.product t).filter (λ (x : α × β), p x.1 ∧ q x.2) = (s.filter p).product (t.filter q) :=
by { ext ⟨a, b⟩, simp only [mem_filter, mem_product], finish, }
lemma filter_product_card (s : finset α) (t : finset β)
(p : α → Prop) (q : β → Prop) [decidable_pred p] [decidable_pred q] :
((s.product t).filter (λ (x : α × β), p x.1 ↔ q x.2)).card =
(s.filter p).card * (t.filter q).card + (s.filter (not ∘ p)).card * (t.filter (not ∘ q)).card :=
begin
classical,
rw [← card_product, ← card_product, ← filter_product, ← filter_product, ← card_union_eq],
{ apply congr_arg, ext ⟨a, b⟩, simp only [filter_union_right, mem_filter, mem_product],
split; intros; finish, },
{ rw disjoint_iff, change _ ∩ _ = ∅, ext ⟨a, b⟩, rw mem_inter, finish, },
end
end prod
/-! ### sigma -/
section sigma
variables {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)}
/-- `sigma s t` is the set of dependent pairs `⟨a, b⟩` such that `a ∈ s` and `b ∈ t a`. -/
protected def sigma (s : finset α) (t : Πa, finset (σ a)) : finset (Σa, σ a) :=
⟨_, nodup_sigma s.2 (λ a, (t a).2)⟩
@[simp] theorem mem_sigma {p : sigma σ} : p ∈ s.sigma t ↔ p.1 ∈ s ∧ p.2 ∈ t (p.1) := mem_sigma
theorem sigma_mono {s₁ s₂ : finset α} {t₁ t₂ : Πa, finset (σ a)}
(H1 : s₁ ⊆ s₂) (H2 : ∀a, t₁ a ⊆ t₂ a) : s₁.sigma t₁ ⊆ s₂.sigma t₂ :=
λ ⟨x, sx⟩ H, let ⟨H3, H4⟩ := mem_sigma.1 H in mem_sigma.2 ⟨H1 H3, H2 x H4⟩
theorem sigma_eq_bUnion [decidable_eq (Σ a, σ a)] (s : finset α)
(t : Πa, finset (σ a)) :
s.sigma t = s.bUnion (λa, (t a).map $ embedding.sigma_mk a) :=
by { ext ⟨x, y⟩, simp [and.left_comm] }
end sigma
/-! ### disjoint -/
section disjoint
variable [decidable_eq α]
theorem disjoint_left {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t :=
by simp only [_root_.disjoint, inf_eq_inter, le_iff_subset, subset_iff, mem_inter, not_and,
and_imp]; refl
theorem disjoint_val {s t : finset α} : disjoint s t ↔ s.1.disjoint t.1 :=
disjoint_left
theorem disjoint_iff_inter_eq_empty {s t : finset α} : disjoint s t ↔ s ∩ t = ∅ :=
disjoint_iff
instance decidable_disjoint (U V : finset α) : decidable (disjoint U V) :=
decidable_of_decidable_of_iff (by apply_instance) eq_bot_iff
theorem disjoint_right {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s :=
by rw [disjoint.comm, disjoint_left]
theorem disjoint_iff_ne {s t : finset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b :=
by simp only [disjoint_left, imp_not_comm, forall_eq']
theorem disjoint_of_subset_left {s t u : finset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t :=
disjoint_left.2 (λ x m₁, (disjoint_left.1 d) (h m₁))
theorem disjoint_of_subset_right {s t u : finset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t :=
disjoint_right.2 (λ x m₁, (disjoint_right.1 d) (h m₁))
@[simp] theorem disjoint_empty_left (s : finset α) : disjoint ∅ s := disjoint_bot_left
@[simp] theorem disjoint_empty_right (s : finset α) : disjoint s ∅ := disjoint_bot_right
@[simp] theorem singleton_disjoint {s : finset α} {a : α} : disjoint (singleton a) s ↔ a ∉ s :=
by simp only [disjoint_left, mem_singleton, forall_eq]
@[simp] theorem disjoint_singleton {s : finset α} {a : α} : disjoint s (singleton a) ↔ a ∉ s :=
disjoint.comm.trans singleton_disjoint
@[simp] theorem disjoint_insert_left {a : α} {s t : finset α} :
disjoint (insert a s) t ↔ a ∉ t ∧ disjoint s t :=
by simp only [disjoint_left, mem_insert, or_imp_distrib, forall_and_distrib, forall_eq]
@[simp] theorem disjoint_insert_right {a : α} {s t : finset α} :
disjoint s (insert a t) ↔ a ∉ s ∧ disjoint s t :=
disjoint.comm.trans $ by rw [disjoint_insert_left, disjoint.comm]
@[simp] theorem disjoint_union_left {s t u : finset α} :
disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u :=
by simp only [disjoint_left, mem_union, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_union_right {s t u : finset α} :
disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u :=
by simp only [disjoint_right, mem_union, or_imp_distrib, forall_and_distrib]
lemma sdiff_disjoint {s t : finset α} : disjoint (t \ s) s :=
disjoint_left.2 $ assume a ha, (mem_sdiff.1 ha).2
lemma disjoint_sdiff {s t : finset α} : disjoint s (t \ s) :=
sdiff_disjoint.symm
lemma disjoint_sdiff_inter (s t : finset α) : disjoint (s \ t) (s ∩ t) :=
disjoint_of_subset_right (inter_subset_right _ _) sdiff_disjoint
lemma sdiff_eq_self_iff_disjoint {s t : finset α} : s \ t = s ↔ disjoint s t :=
by rw [sdiff_eq_self, subset_empty, disjoint_iff_inter_eq_empty]
lemma sdiff_eq_self_of_disjoint {s t : finset α} (h : disjoint s t) : s \ t = s :=
sdiff_eq_self_iff_disjoint.2 h
lemma disjoint_self_iff_empty (s : finset α) : disjoint s s ↔ s = ∅ :=
disjoint_self
lemma disjoint_bUnion_left {ι : Type*}
(s : finset ι) (f : ι → finset α) (t : finset α) :
disjoint (s.bUnion f) t ↔ (∀i∈s, disjoint (f i) t) :=
begin
classical,
refine s.induction _ _,
{ simp only [forall_mem_empty_iff, bUnion_empty, disjoint_empty_left] },
{ assume i s his ih,
simp only [disjoint_union_left, bUnion_insert, his, forall_mem_insert, ih] }
end
lemma disjoint_bUnion_right {ι : Type*}
(s : finset α) (t : finset ι) (f : ι → finset α) :
disjoint s (t.bUnion f) ↔ (∀i∈t, disjoint s (f i)) :=
by simpa only [disjoint.comm] using disjoint_bUnion_left t f s
@[simp] theorem card_disjoint_union {s t : finset α} (h : disjoint s t) :
card (s ∪ t) = card s + card t :=
by rw [← card_union_add_card_inter, disjoint_iff_inter_eq_empty.1 h, card_empty, add_zero]
theorem card_sdiff {s t : finset α} (h : s ⊆ t) : card (t \ s) = card t - card s :=
suffices card (t \ s) = card ((t \ s) ∪ s) - card s, by rwa sdiff_union_of_subset h at this,
by rw [card_disjoint_union sdiff_disjoint, nat.add_sub_cancel]
lemma disjoint_filter {s : finset α} {p q : α → Prop} [decidable_pred p] [decidable_pred q] :
disjoint (s.filter p) (s.filter q) ↔ (∀ x ∈ s, p x → ¬ q x) :=
by split; simp [disjoint_left] {contextual := tt}
lemma disjoint_filter_filter {s t : finset α} {p q : α → Prop} [decidable_pred p]
[decidable_pred q] :
(disjoint s t) → disjoint (s.filter p) (t.filter q) :=
disjoint.mono (filter_subset _ _) (filter_subset _ _)
lemma disjoint_iff_disjoint_coe {α : Type*} {a b : finset α} [decidable_eq α] :
disjoint a b ↔ disjoint (↑a : set α) (↑b : set α) :=
by { rw [finset.disjoint_left, set.disjoint_left], refl }
lemma filter_card_add_filter_neg_card_eq_card {α : Type*} {s : finset α} (p : α → Prop)
[decidable_pred p] :
(s.filter p).card + (s.filter (not ∘ p)).card = s.card :=
by { classical, simp [← card_union_eq, filter_union_filter_neg_eq, disjoint_filter], }
end disjoint
section self_prod
variables (s : finset α) [decidable_eq α]
/-- Given a finite set `s`, the diagonal, `s.diag` is the set of pairs of the form `(a, a)` for
`a ∈ s`. -/
def diag := (s.product s).filter (λ (a : α × α), a.fst = a.snd)
/-- Given a finite set `s`, the off-diagonal, `s.off_diag` is the set of pairs `(a, b)` with `a ≠ b`
for `a, b ∈ s`. -/
def off_diag := (s.product s).filter (λ (a : α × α), a.fst ≠ a.snd)
@[simp] lemma mem_diag (x : α × α) : x ∈ s.diag ↔ x.1 ∈ s ∧ x.1 = x.2 :=
by { simp only [diag, mem_filter, mem_product], split; intros; finish, }
@[simp] lemma mem_off_diag (x : α × α) : x ∈ s.off_diag ↔ x.1 ∈ s ∧ x.2 ∈ s ∧ x.1 ≠ x.2 :=
by { simp only [off_diag, mem_filter, mem_product], split; intros; finish, }
@[simp] lemma diag_card : (diag s).card = s.card :=
begin
suffices : diag s = s.image (λ a, (a, a)), { rw this, apply card_image_of_inj_on, finish, },
ext ⟨a₁, a₂⟩, rw mem_diag, split; intros; finish,
end
@[simp] lemma off_diag_card : (off_diag s).card = s.card * s.card - s.card :=
begin
suffices : (diag s).card + (off_diag s).card = s.card * s.card,
{ nth_rewrite 2 ← s.diag_card, finish, },
rw ← card_product,
apply filter_card_add_filter_neg_card_eq_card,
end
end self_prod
/--
Given a set A and a set B inside it, we can shrink A to any appropriate size, and keep B
inside it.
-/
lemma exists_intermediate_set {A B : finset α} (i : ℕ)
(h₁ : i + card B ≤ card A) (h₂ : B ⊆ A) :
∃ (C : finset α), B ⊆ C ∧ C ⊆ A ∧ card C = i + card B :=
begin
classical,
rcases nat.le.dest h₁ with ⟨k, _⟩,
clear h₁,
induction k with k ih generalizing A,
{ exact ⟨A, h₂, subset.refl _, h.symm⟩ },
{ have : (A \ B).nonempty,
{ rw [← card_pos, card_sdiff h₂, ← h, nat.add_right_comm,
nat.add_sub_cancel, nat.add_succ],
apply nat.succ_pos },
rcases this with ⟨a, ha⟩,
have z : i + card B + k = card (erase A a),
{ rw [card_erase_of_mem, ← h, nat.add_succ, nat.pred_succ],
rw mem_sdiff at ha,
exact ha.1 },
rcases ih _ z with ⟨B', hB', B'subA', cards⟩,
{ exact ⟨B', hB', trans B'subA' (erase_subset _ _), cards⟩ },
{ rintros t th,
apply mem_erase_of_ne_of_mem _ (h₂ th),
rintro rfl,
exact not_mem_sdiff_of_mem_right th ha } }
end
/-- We can shrink A to any smaller size. -/
lemma exists_smaller_set (A : finset α) (i : ℕ) (h₁ : i ≤ card A) :
∃ (B : finset α), B ⊆ A ∧ card B = i :=
let ⟨B, _, x₁, x₂⟩ := exists_intermediate_set i (by simpa) (empty_subset A) in ⟨B, x₁, x₂⟩
/-- `finset.fin_range k` is the finset `{0, 1, ..., k-1}`, as a `finset (fin k)`. -/
def fin_range (k : ℕ) : finset (fin k) :=
⟨list.fin_range k, list.nodup_fin_range k⟩
@[simp]
lemma fin_range_card {k : ℕ} : (fin_range k).card = k :=
by simp [fin_range]
@[simp]
lemma mem_fin_range {k : ℕ} (m : fin k) : m ∈ fin_range k :=
list.mem_fin_range m
@[simp] lemma coe_fin_range (k : ℕ) : (fin_range k : set (fin k)) = set.univ :=
set.eq_univ_of_forall mem_fin_range
/-- Given a finset `s` of `ℕ` contained in `{0,..., n-1}`, the corresponding finset in `fin n`
is `s.attach_fin h` where `h` is a proof that all elements of `s` are less than `n`. -/
def attach_fin (s : finset ℕ) {n : ℕ} (h : ∀ m ∈ s, m < n) : finset (fin n) :=
⟨s.1.pmap (λ a ha, ⟨a, ha⟩) h, multiset.nodup_pmap (λ _ _ _ _, fin.veq_of_eq) s.2⟩
@[simp] lemma mem_attach_fin {n : ℕ} {s : finset ℕ} (h : ∀ m ∈ s, m < n) {a : fin n} :
a ∈ s.attach_fin h ↔ (a : ℕ) ∈ s :=
⟨λ h, let ⟨b, hb₁, hb₂⟩ := multiset.mem_pmap.1 h in hb₂ ▸ hb₁,
λ h, multiset.mem_pmap.2 ⟨a, h, fin.eta _ _⟩⟩
@[simp] lemma card_attach_fin {n : ℕ} (s : finset ℕ) (h : ∀ m ∈ s, m < n) :
(s.attach_fin h).card = s.card := multiset.card_pmap _ _ _
/-! ### choose -/
section choose
variables (p : α → Prop) [decidable_pred p] (l : finset α)
/-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of
`l` satisfying `p` this unique element, as an element of the corresponding subtype. -/
def choose_x (hp : (∃! a, a ∈ l ∧ p a)) : { a // a ∈ l ∧ p a } :=
multiset.choose_x p l.val hp
/-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of
`l` satisfying `p` this unique element, as an element of the ambient type. -/
def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp
lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) :=
(choose_x p l hp).property
lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1
lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2
end choose
theorem lt_wf {α} : well_founded (@has_lt.lt (finset α) _) :=
have H : subrelation (@has_lt.lt (finset α) _)
(inv_image (<) card),
from λ x y hxy, card_lt_card hxy,
subrelation.wf H $ inv_image.wf _ $ nat.lt_wf
end finset
namespace equiv
/-- Given an equivalence `α` to `β`, produce an equivalence between `finset α` and `finset β`. -/
protected def finset_congr (e : α ≃ β) : finset α ≃ finset β :=
{ to_fun := λ s, s.map e.to_embedding,
inv_fun := λ s, s.map e.symm.to_embedding,
left_inv := λ s, by simp [finset.map_map],
right_inv := λ s, by simp [finset.map_map] }
@[simp] lemma finset_congr_apply (e : α ≃ β) (s : finset α) :
e.finset_congr s = s.map e.to_embedding :=
rfl
@[simp] lemma finset_congr_refl :
(equiv.refl α).finset_congr = equiv.refl _ :=
by { ext, simp }
@[simp] lemma finset_congr_symm (e : α ≃ β) :
e.finset_congr.symm = e.symm.finset_congr :=
rfl
@[simp] lemma finset_congr_trans (e : α ≃ β) (e' : β ≃ γ) :
e.finset_congr.trans (e'.finset_congr) = (e.trans e').finset_congr :=
by { ext, simp [-finset.mem_map, -equiv.trans_to_embedding] }
end equiv
namespace list
variable [decidable_eq α]
theorem to_finset_card_of_nodup {l : list α} (h : l.nodup) : l.to_finset.card = l.length :=
congr_arg card $ (@multiset.erase_dup_eq_self α _ l).2 h
end list
namespace multiset
variable [decidable_eq α]
theorem to_finset_card_of_nodup {l : multiset α} (h : l.nodup) : l.to_finset.card = l.card :=
congr_arg card $ (@multiset.erase_dup_eq_self α _ l).2 h
lemma disjoint_to_finset (m1 m2 : multiset α) :
_root_.disjoint m1.to_finset m2.to_finset ↔ m1.disjoint m2 :=
begin
rw finset.disjoint_iff_ne,
split,
{ intro h,
intros a ha1 ha2,
rw ← multiset.mem_to_finset at ha1 ha2,
exact h _ ha1 _ ha2 rfl },
{ rintros h a ha b hb rfl,
rw multiset.mem_to_finset at ha hb,
exact h ha hb }
end
end multiset
|
2de9355f727222d06edd35522323cd942a9012f5 | 57fdc8de88f5ea3bfde4325e6ecd13f93a274ab5 | /algebra/ordered_ring.lean | 0087c8b0014ac6ab9bc611cc160017231d7372f9 | [
"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 | 8,216 | 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 order.basic algebra.order algebra.ordered_group algebra.ring
universe u
variable {α : Type u}
-- TODO: this is necessary additionally to mul_nonneg otherwise the simplifier can not match
lemma zero_le_mul [ordered_semiring α] {a b : α} : 0 ≤ a → 0 ≤ b → 0 ≤ a * b :=
mul_nonneg
section linear_ordered_semiring
variable [linear_ordered_semiring α]
@[simp] lemma mul_le_mul_left {a b c : α} (h : 0 < c) : c * a ≤ c * b ↔ a ≤ b :=
⟨λ h', le_of_mul_le_mul_left h' h, λ h', mul_le_mul_of_nonneg_left h' (le_of_lt h)⟩
@[simp] lemma mul_le_mul_right {a b c : α} (h : 0 < c) : a * c ≤ b * c ↔ a ≤ b :=
⟨λ h', le_of_mul_le_mul_right h' h, λ h', mul_le_mul_of_nonneg_right h' (le_of_lt h)⟩
@[simp] lemma mul_lt_mul_left {a b c : α} (h : 0 < c) : c * a < c * b ↔ a < b :=
⟨λ h', lt_of_mul_lt_mul_left h' (le_of_lt h), λ h', mul_lt_mul_of_pos_left h' h⟩
@[simp] lemma mul_lt_mul_right {a b c : α} (h : 0 < c) : a * c < b * c ↔ a < b :=
⟨λ h', lt_of_mul_lt_mul_right h' (le_of_lt h), λ h', mul_lt_mul_of_pos_right h' h⟩
lemma le_mul_iff_one_le_left {a b : α} (hb : b > 0) : b ≤ a * b ↔ 1 ≤ a :=
suffices 1 * b ≤ a * b ↔ 1 ≤ a, by rwa one_mul at this,
mul_le_mul_right hb
lemma lt_mul_iff_one_lt_left {a b : α} (hb : b > 0) : b < a * b ↔ 1 < a :=
suffices 1 * b < a * b ↔ 1 < a, by rwa one_mul at this,
mul_lt_mul_right hb
lemma le_mul_iff_one_le_right {a b : α} (hb : b > 0) : b ≤ b * a ↔ 1 ≤ a :=
suffices b * 1 ≤ b * a ↔ 1 ≤ a, by rwa mul_one at this,
mul_le_mul_left hb
lemma lt_mul_iff_one_lt_right {a b : α} (hb : b > 0) : b < b * a ↔ 1 < a :=
suffices b * 1 < b * a ↔ 1 < a, by rwa mul_one at this,
mul_lt_mul_left hb
lemma lt_mul_of_gt_one_right' {a b : α} (hb : b > 0) : a > 1 → b < b * a :=
(lt_mul_iff_one_lt_right hb).2
lemma le_mul_of_ge_one_right' {a b : α} (hb : b ≥ 0) (h : a ≥ 1) : b ≤ b * a :=
suffices b * 1 ≤ b * a, by rwa mul_one at this,
mul_le_mul_of_nonneg_left h hb
lemma le_mul_of_ge_one_left' {a b : α} (hb : b ≥ 0) (h : a ≥ 1) : b ≤ a * b :=
suffices 1 * b ≤ a * b, by rwa one_mul at this,
mul_le_mul_of_nonneg_right h hb
theorem mul_nonneg_iff_right_nonneg_of_pos {a b : α} (h : 0 < a) : 0 ≤ b * a ↔ 0 ≤ b :=
⟨assume : 0 ≤ b * a, nonneg_of_mul_nonneg_right this h, assume : 0 ≤ b, mul_nonneg this $ le_of_lt h⟩
lemma bit1_pos {a : α} (h : 0 ≤ a) : 0 < bit1 a :=
lt_add_of_le_of_pos (add_nonneg h h) zero_lt_one
lemma bit1_pos' {a : α} (h : 0 < a) : 0 < bit1 a :=
bit1_pos (le_of_lt h)
lemma lt_add_one (a : α) : a < a + 1 :=
lt_add_of_le_of_pos (le_refl _) zero_lt_one
lemma one_lt_two : 1 < (2 : α) := lt_add_one _
end linear_ordered_semiring
instance linear_ordered_semiring.to_no_top_order {α : Type*} [linear_ordered_semiring α] :
no_top_order α :=
⟨assume a, ⟨a + 1, lt_add_of_pos_right _ zero_lt_one⟩⟩
instance linear_ordered_semiring.to_no_bot_order {α : Type*} [linear_ordered_ring α] :
no_bot_order α :=
⟨assume a, ⟨a - 1, sub_lt_iff.mpr $ lt_add_of_pos_right _ zero_lt_one⟩⟩
instance to_domain [s : linear_ordered_ring α] : domain α :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := @linear_ordered_ring.eq_zero_or_eq_zero_of_mul_eq_zero α s,
..s }
section linear_ordered_ring
variable [linear_ordered_ring α]
@[simp] lemma mul_le_mul_left_of_neg {a b c : α} (h : c < 0) : c * a ≤ c * b ↔ b ≤ a :=
⟨le_imp_le_iff_lt_imp_lt.2 $ λ h', mul_lt_mul_of_neg_left h' h,
λ h', mul_le_mul_of_nonpos_left h' (le_of_lt h)⟩
@[simp] lemma mul_le_mul_right_of_neg {a b c : α} (h : c < 0) : a * c ≤ b * c ↔ b ≤ a :=
⟨le_imp_le_iff_lt_imp_lt.2 $ λ h', mul_lt_mul_of_neg_right h' h,
λ h', mul_le_mul_of_nonpos_right h' (le_of_lt h)⟩
@[simp] lemma mul_lt_mul_left_of_neg {a b c : α} (h : c < 0) : c * a < c * b ↔ b < a :=
le_iff_le_iff_lt_iff_lt.1 (mul_le_mul_left_of_neg h)
@[simp] lemma mul_lt_mul_right_of_neg {a b c : α} (h : c < 0) : a * c < b * c ↔ b < a :=
le_iff_le_iff_lt_iff_lt.1 (mul_le_mul_right_of_neg h)
lemma sub_one_lt (a : α) : a - 1 < a :=
sub_lt_iff.2 (lt_add_one a)
end linear_ordered_ring
set_option old_structure_cmd true
/-- Extend `nonneg_comm_group` to support ordered rings
specified by their nonnegative elements -/
class nonneg_ring (α : Type*)
extends ring α, zero_ne_one_class α, nonneg_comm_group α :=
(mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b))
(mul_pos : ∀ {a b}, pos a → pos b → pos (a * b))
/-- Extend `nonneg_comm_group` to support linearly ordered rings
specified by their nonnegative elements -/
class linear_nonneg_ring (α : Type*) extends domain α, nonneg_comm_group α :=
(mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b))
(nonneg_total : ∀ a, nonneg a ∨ nonneg (-a))
namespace nonneg_ring
open nonneg_comm_group
variable [s : nonneg_ring α]
instance to_ordered_ring : ordered_ring α :=
{ le := (≤),
lt := (<),
lt_iff_le_not_le := @lt_iff_le_not_le _ _,
le_refl := @le_refl _ _,
le_trans := @le_trans _ _,
le_antisymm := @le_antisymm _ _,
add_lt_add_left := @add_lt_add_left _ _,
add_le_add_left := @add_le_add_left _ _,
mul_nonneg := λ a b, by simp [nonneg_def.symm]; exact mul_nonneg,
mul_pos := λ a b, by simp [pos_def.symm]; exact mul_pos,
..s }
def nonneg_ring.to_linear_nonneg_ring
(nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a))
: linear_nonneg_ring α :=
{ nonneg_total := nonneg_total,
eq_zero_or_eq_zero_of_mul_eq_zero :=
suffices ∀ {a} b : α, nonneg a → a * b = 0 → a = 0 ∨ b = 0,
from λ a b, (nonneg_total a).elim (this b)
(λ na, by simpa using this b na),
suffices ∀ {a b : α}, nonneg a → nonneg b → a * b = 0 → a = 0 ∨ b = 0,
from λ a b na, (nonneg_total b).elim (this na)
(λ nb, by simpa using this na nb),
λ a b na nb z, classical.by_cases
(λ nna : nonneg (-a), or.inl (nonneg_antisymm na nna))
(λ pa, classical.by_cases
(λ nnb : nonneg (-b), or.inr (nonneg_antisymm nb nnb))
(λ pb, absurd z $ ne_of_gt $ pos_def.1 $ mul_pos
((pos_iff _ _).2 ⟨na, pa⟩)
((pos_iff _ _).2 ⟨nb, pb⟩))),
..s }
end nonneg_ring
namespace linear_nonneg_ring
open nonneg_comm_group
variable [s : linear_nonneg_ring α]
instance to_nonneg_ring : nonneg_ring α :=
{ mul_pos := λ a b pa pb,
let ⟨a1, a2⟩ := (pos_iff α a).1 pa,
⟨b1, b2⟩ := (pos_iff α b).1 pb in
have ab : nonneg (a * b), from mul_nonneg a1 b1,
(pos_iff α _).2 ⟨ab, λ hn,
have a * b = 0, from nonneg_antisymm ab hn,
(eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).elim
(ne_of_gt (pos_def.1 pa))
(ne_of_gt (pos_def.1 pb))⟩,
..s }
instance to_linear_order : linear_order α :=
{ le := (≤),
lt := (<),
lt_iff_le_not_le := @lt_iff_le_not_le _ _,
le_refl := @le_refl _ _,
le_trans := @le_trans _ _,
le_antisymm := @le_antisymm _ _,
le_total := nonneg_total_iff.1 nonneg_total,
..s }
instance to_linear_ordered_ring : linear_ordered_ring α :=
{ le := (≤),
lt := (<),
lt_iff_le_not_le := @lt_iff_le_not_le _ _,
le_refl := @le_refl _ _,
le_trans := @le_trans _ _,
le_antisymm := @le_antisymm _ _,
le_total := @le_total _ _,
add_lt_add_left := @add_lt_add_left _ _,
add_le_add_left := @add_le_add_left _ _,
mul_nonneg := by simp [nonneg_def.symm]; exact @mul_nonneg _ _,
mul_pos := by simp [pos_def.symm]; exact @nonneg_ring.mul_pos _ _,
zero_lt_one := lt_of_not_ge $ λ (h : nonneg (0 - 1)), begin
rw [zero_sub] at h,
have := mul_nonneg h h, simp at this,
exact zero_ne_one _ (nonneg_antisymm this h).symm
end, ..s }
instance to_decidable_linear_ordered_comm_ring
[decidable_pred (@nonneg α _)]
[comm : @is_commutative α (*)]
: decidable_linear_ordered_comm_ring α :=
{ decidable_le := by apply_instance,
decidable_eq := by apply_instance,
decidable_lt := by apply_instance,
mul_comm := is_commutative.comm (*),
..@linear_nonneg_ring.to_linear_ordered_ring _ s }
end linear_nonneg_ring
|
929f95fed1e7d64eec326118af7e657fef2e2caf | f3a5af2927397cf346ec0e24312bfff077f00425 | /src/tactic/nat_num_game.lean | 7c49d6d2c8d1a00077d8a3f6a9e3bf56c39f1bf6 | [
"Apache-2.0"
] | permissive | ImperialCollegeLondon/natural_number_game | 05c39e1586408cfb563d1a12e1085a90726ab655 | f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd | refs/heads/master | 1,688,570,964,990 | 1,636,908,242,000 | 1,636,908,242,000 | 195,403,790 | 277 | 84 | Apache-2.0 | 1,694,547,955,000 | 1,562,328,792,000 | Lean | UTF-8 | Lean | false | false | 1,873 | lean | -- Many many thanks to Rob Lewis for supplying 99.9% of this file.
import tactic.modded tactic.apply
open tactic
meta def copy_decl (d : declaration) : tactic unit :=
add_decl $ d.update_name $ d.to_name.update_prefix `nat_num_game.interactive
@[reducible] meta def filter (d : declaration) : bool :=
d.to_name ∉ [`tactic.interactive.induction,
`tactic.interactive.cases,
`tactic.interactive.rw,
`tactic.interactive.symmetry,
`tactic.interactive.use]
meta def copy_decls : tactic unit :=
do env ← get_env,
let ls := env.fold [] list.cons,
ls.mmap' $ λ dec, when (dec.to_name.get_prefix = `tactic.interactive ∧ filter dec) (copy_decl dec)
@[reducible] meta def nat_num_game := tactic
namespace nat_num_game
--meta instance : monad nat_num_game := by delta nat_num_game; apply_instance
--meta instance : alternative nat_num_game := by delta nat_num_game; apply_instance
meta def step {α} (c : nat_num_game α) : nat_num_game unit :=
c >> return ()
meta def istep := @tactic.istep
meta def save_info := tactic.save_info
meta def execute (c : nat_num_game unit) : nat_num_game unit :=
c
meta def execute_with := @smt_tactic.execute_with
--meta def trace_state {α : Type}
meta def solve1 := @tactic.solve1
end nat_num_game
--#check tactic.interactive.induction
namespace nat_num_game.interactive
meta def induction
:= tactic.interactive.induction'
meta def cases
:= tactic.interactive.cases'
meta def rw
:= tactic.interactive.rw'
meta def symmetry
:= tactic.interactive.symmetry'
meta def use
:= tactic.interactive.use'
end nat_num_game.interactive
run_cmd copy_decls
--TODO : why is this broken?
--#print tactic.interactive.rintro
--#exit
-- example just to check it's running
-- example (n : ℕ) : true :=
-- begin [nat_num_game]
-- induction n,
-- sorry, sorry
-- end
|
59bc3824de00a3244ef53793becf053358781b23 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/elab4.lean | 29300b21f86c37fe4c7f90417ff760dbc69c84ab | [
"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 | 337 | lean | definition foo.f {A : Type*} {B : Type*} (a : A) (b : B) : A := a
definition boo.f (a : nat) (b : nat) (c : nat) := a + b + c
definition bla.f (a b c d : bool) := a
open boo foo bla
set_option pp.full_names true
#check f 0 1 2
#check f 0 1 2 3
#check f 0 1
#check f tt 2
#check f tt ff tt
#check f tt ff
#check @foo.f _ _ 0 1
|
16ff2b14d59e10d019e1215911688ddfdaab6c92 | 8b9f17008684d796c8022dab552e42f0cb6fb347 | /tests/lean/run/match1.lean | 296dc13c4a6614c345104a607f7de37f81b0a090 | [
"Apache-2.0"
] | permissive | chubbymaggie/lean | 0d06ae25f9dd396306fb02190e89422ea94afd7b | d2c7b5c31928c98f545b16420d37842c43b4ae9a | refs/heads/master | 1,611,313,622,901 | 1,430,266,839,000 | 1,430,267,083,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 741 | lean | import data.nat.basic
open nat
definition two1 : nat := 2
definition two2 : nat := succ (succ (zero))
constant f : nat → nat → nat
(*
local tc = type_checker_with_hints(get_env(), true)
local plugin = whnf_match_plugin(tc)
function tst_match(p, t)
local r1, r2 = match(p, t, plugin)
assert(r1)
print("--------------")
for i = 1, #r1 do
print(" expr:#" .. i .. " := " .. tostring(r1[i]))
end
for i = 1, #r2 do
print(" lvl:#" .. i .. " := " .. tostring(r2[i]))
end
end
local nat = Const("nat")
local f = Const("f")
local two1 = Const("two1")
local two2 = Const("two2")
local succ = Const({"nat", "succ"})
local V0 = mk_idx_meta(0, nat)
tst_match(f(succ(V0), two1), f(two2, two2))
*)
|
5798d8a0c4aff1839fb2f67c4c580982917de66a | 75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2 | /hott/types/nat/basic.hlean | baac4f2100231388cef37a226a85d5a63d8e2ac2 | [
"Apache-2.0"
] | permissive | jroesch/lean | 30ef0860fa905d35b9ad6f76de1a4f65c9af6871 | 3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2 | refs/heads/master | 1,586,090,835,348 | 1,455,142,203,000 | 1,455,142,277,000 | 51,536,958 | 1 | 0 | null | 1,455,215,811,000 | 1,455,215,811,000 | null | UTF-8 | Lean | false | false | 10,023 | hlean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
(Ported from standard library)
Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad
Basic operations on the natural numbers.
-/
import ..num algebra.ring
open prod binary eq algebra lift is_trunc
namespace nat
/- a variant of add, defined by recursion on the first argument -/
definition addl (x y : ℕ) : ℕ :=
nat.rec y (λ n r, succ r) x
infix ` ⊕ `:65 := addl
theorem addl_succ_right (n m : ℕ) : n ⊕ succ m = succ (n ⊕ m) :=
nat.rec_on n
rfl
(λ n₁ ih, calc
succ n₁ ⊕ succ m = succ (n₁ ⊕ succ m) : rfl
... = succ (succ (n₁ ⊕ m)) : ih
... = succ (succ n₁ ⊕ m) : rfl)
theorem add_eq_addl (x : ℕ) : Πy, x + y = x ⊕ y :=
nat.rec_on x
(λ y, nat.rec_on y
rfl
(λ y₁ ih, calc
0 + succ y₁ = succ (0 + y₁) : rfl
... = succ (0 ⊕ y₁) : {ih}
... = 0 ⊕ (succ y₁) : rfl))
(λ x₁ ih₁ y, nat.rec_on y
(calc
succ x₁ + 0 = succ (x₁ + 0) : rfl
... = succ (x₁ ⊕ 0) : {ih₁ 0}
... = succ x₁ ⊕ 0 : rfl)
(λ y₁ ih₂, calc
succ x₁ + succ y₁ = succ (succ x₁ + y₁) : rfl
... = succ (succ x₁ ⊕ y₁) : {ih₂}
... = succ x₁ ⊕ succ y₁ : addl_succ_right))
/- successor and predecessor -/
theorem succ_ne_zero (n : ℕ) : succ n ≠ 0 :=
by contradiction
-- add_rewrite succ_ne_zero
theorem pred_zero [simp] : pred 0 = 0 :=
rfl
theorem pred_succ [simp] (n : ℕ) : pred (succ n) = n :=
rfl
theorem eq_zero_sum_eq_succ_pred (n : ℕ) : n = 0 ⊎ n = succ (pred n) :=
nat.rec_on n
(sum.inl rfl)
(take m IH, sum.inr
(show succ m = succ (pred (succ m)), from ap succ !pred_succ⁻¹))
theorem exists_eq_succ_of_ne_zero {n : ℕ} (H : n ≠ 0) : Σk : ℕ, n = succ k :=
sigma.mk _ (sum_resolve_right !eq_zero_sum_eq_succ_pred H)
theorem succ.inj {n m : ℕ} (H : succ n = succ m) : n = m :=
down (nat.no_confusion H imp.id)
abbreviation eq_of_succ_eq_succ := @succ.inj
theorem succ_ne_self {n : ℕ} : succ n ≠ n :=
nat.rec_on n
(take H : 1 = 0,
have ne : 1 ≠ 0, from !succ_ne_zero,
absurd H ne)
(take k IH H, IH (succ.inj H))
theorem discriminate {B : Type} {n : ℕ} (H1: n = 0 → B) (H2 : Πm, n = succ m → B) : B :=
have H : n = n → B, from nat.cases_on n H1 H2,
H rfl
theorem two_step_rec_on {P : ℕ → Type} (a : ℕ) (H1 : P 0) (H2 : P 1)
(H3 : Π (n : ℕ) (IH1 : P n) (IH2 : P (succ n)), P (succ (succ n))) : P a :=
have stronger : P a × P (succ a), from
nat.rec_on a
(pair H1 H2)
(take k IH,
have IH1 : P k, from prod.pr1 IH,
have IH2 : P (succ k), from prod.pr2 IH,
pair IH2 (H3 k IH1 IH2)),
prod.pr1 stronger
theorem sub_induction {P : ℕ → ℕ → Type} (n m : ℕ) (H1 : Πm, P 0 m)
(H2 : Πn, P (succ n) 0) (H3 : Πn m, P n m → P (succ n) (succ m)) : P n m :=
have general : Πm, P n m, from nat.rec_on n H1
(take k : ℕ,
assume IH : Πm, P k m,
take m : ℕ,
nat.cases_on m (H2 k) (take l, (H3 k l (IH l)))),
general m
/- addition -/
protected definition add_zero [simp] (n : ℕ) : n + 0 = n :=
rfl
definition add_succ [simp] (n m : ℕ) : n + succ m = succ (n + m) :=
rfl
protected definition zero_add [simp] (n : ℕ) : 0 + n = n :=
begin
induction n with n IH,
reflexivity,
exact ap succ IH
end
definition succ_add [simp] (n m : ℕ) : (succ n) + m = succ (n + m) :=
begin
induction m with m IH,
reflexivity,
exact ap succ IH
end
protected definition add_comm [simp] (n m : ℕ) : n + m = m + n :=
begin
induction n with n IH,
{ apply nat.zero_add},
{ exact !succ_add ⬝ ap succ IH}
end
protected definition add_add (n l k : ℕ) : n + l + k = n + (k + l) :=
begin
induction l with l IH,
reflexivity,
exact succ_add (n + l) k ⬝ ap succ IH
end
definition succ_add_eq_succ_add (n m : ℕ) : succ n + m = n + succ m :=
!succ_add
protected definition add_assoc [simp] (n m k : ℕ) : (n + m) + k = n + (m + k) :=
begin
induction k with k IH,
reflexivity,
exact ap succ IH
end
protected theorem add_left_comm : Π (n m k : ℕ), n + (m + k) = m + (n + k) :=
left_comm nat.add_comm nat.add_assoc
protected theorem add_right_comm : Π (n m k : ℕ), n + m + k = n + k + m :=
right_comm nat.add_comm nat.add_assoc
protected theorem add_left_cancel {n m k : ℕ} : n + m = n + k → m = k :=
nat.rec_on n
(take H : 0 + m = 0 + k,
!nat.zero_add⁻¹ ⬝ H ⬝ !nat.zero_add)
(take (n : ℕ) (IH : n + m = n + k → m = k) (H : succ n + m = succ n + k),
have succ (n + m) = succ (n + k),
from calc
succ (n + m) = succ n + m : succ_add
... = succ n + k : H
... = succ (n + k) : succ_add,
have n + m = n + k, from succ.inj this,
IH this)
protected theorem add_right_cancel {n m k : ℕ} (H : n + m = k + m) : n = k :=
have H2 : m + n = m + k, from !nat.add_comm ⬝ H ⬝ !nat.add_comm,
nat.add_left_cancel H2
theorem eq_zero_of_add_eq_zero_right {n m : ℕ} : n + m = 0 → n = 0 :=
nat.rec_on n
(take (H : 0 + m = 0), rfl)
(take k IH,
assume H : succ k + m = 0,
absurd
(show succ (k + m) = 0, from calc
succ (k + m) = succ k + m : succ_add
... = 0 : H)
!succ_ne_zero)
theorem eq_zero_of_add_eq_zero_left {n m : ℕ} (H : n + m = 0) : m = 0 :=
eq_zero_of_add_eq_zero_right (!nat.add_comm ⬝ H)
theorem eq_zero_prod_eq_zero_of_add_eq_zero {n m : ℕ} (H : n + m = 0) : n = 0 × m = 0 :=
pair (eq_zero_of_add_eq_zero_right H) (eq_zero_of_add_eq_zero_left H)
theorem add_one [simp] (n : ℕ) : n + 1 = succ n := rfl
theorem one_add (n : ℕ) : 1 + n = succ n :=
!nat.zero_add ▸ !succ_add
/- multiplication -/
protected theorem mul_zero [simp] (n : ℕ) : n * 0 = 0 :=
rfl
theorem mul_succ [simp] (n m : ℕ) : n * succ m = n * m + n :=
rfl
-- commutativity, distributivity, associativity, identity
protected theorem zero_mul [simp] (n : ℕ) : 0 * n = 0 :=
nat.rec_on n
!nat.mul_zero
(take m IH, !mul_succ ⬝ !nat.add_zero ⬝ IH)
theorem succ_mul [simp] (n m : ℕ) : (succ n) * m = (n * m) + m :=
nat.rec_on m
(by rewrite nat.mul_zero)
(take k IH, calc
succ n * succ k = succ n * k + succ n : mul_succ
... = n * k + k + succ n : IH
... = n * k + (k + succ n) : nat.add_assoc
... = n * k + (succ n + k) : nat.add_comm
... = n * k + (n + succ k) : succ_add_eq_succ_add
... = n * k + n + succ k : nat.add_assoc
... = n * succ k + succ k : mul_succ)
protected theorem mul_comm [simp] (n m : ℕ) : n * m = m * n :=
nat.rec_on m
(!nat.mul_zero ⬝ !nat.zero_mul⁻¹)
(take k IH, calc
n * succ k = n * k + n : mul_succ
... = k * n + n : IH
... = (succ k) * n : succ_mul)
protected theorem right_distrib (n m k : ℕ) : (n + m) * k = n * k + m * k :=
nat.rec_on k
(calc
(n + m) * 0 = 0 : nat.mul_zero
... = 0 + 0 : nat.add_zero
... = n * 0 + 0 : nat.mul_zero
... = n * 0 + m * 0 : nat.mul_zero)
(take l IH, calc
(n + m) * succ l = (n + m) * l + (n + m) : mul_succ
... = n * l + m * l + (n + m) : IH
... = n * l + m * l + n + m : nat.add_assoc
... = n * l + n + m * l + m : nat.add_right_comm
... = n * l + n + (m * l + m) : nat.add_assoc
... = n * succ l + (m * l + m) : mul_succ
... = n * succ l + m * succ l : mul_succ)
protected theorem left_distrib (n m k : ℕ) : n * (m + k) = n * m + n * k :=
calc
n * (m + k) = (m + k) * n : nat.mul_comm
... = m * n + k * n : nat.right_distrib
... = n * m + k * n : nat.mul_comm
... = n * m + n * k : nat.mul_comm
protected theorem mul_assoc [simp] (n m k : ℕ) : (n * m) * k = n * (m * k) :=
nat.rec_on k
(calc
(n * m) * 0 = n * (m * 0) : nat.mul_zero)
(take l IH,
calc
(n * m) * succ l = (n * m) * l + n * m : mul_succ
... = n * (m * l) + n * m : IH
... = n * (m * l + m) : nat.left_distrib
... = n * (m * succ l) : mul_succ)
protected theorem mul_one [simp] (n : ℕ) : n * 1 = n :=
calc
n * 1 = n * 0 + n : mul_succ
... = 0 + n : nat.mul_zero
... = n : nat.zero_add
protected theorem one_mul [simp] (n : ℕ) : 1 * n = n :=
calc
1 * n = n * 1 : nat.mul_comm
... = n : nat.mul_one
theorem eq_zero_sum_eq_zero_of_mul_eq_zero {n m : ℕ} : n * m = 0 → n = 0 ⊎ m = 0 :=
nat.cases_on n
(assume H, sum.inl rfl)
(take n',
nat.cases_on m
(assume H, sum.inr rfl)
(take m',
assume H : succ n' * succ m' = 0,
absurd
(calc
0 = succ n' * succ m' : H
... = succ n' * m' + succ n' : mul_succ
... = succ (succ n' * m' + n') : add_succ)⁻¹
!succ_ne_zero))
protected definition comm_semiring [reducible] [trans_instance] : comm_semiring nat :=
⦃comm_semiring,
add := nat.add,
add_assoc := nat.add_assoc,
zero := nat.zero,
zero_add := nat.zero_add,
add_zero := nat.add_zero,
add_comm := nat.add_comm,
mul := nat.mul,
mul_assoc := nat.mul_assoc,
one := nat.succ nat.zero,
one_mul := nat.one_mul,
mul_one := nat.mul_one,
left_distrib := nat.left_distrib,
right_distrib := nat.right_distrib,
zero_mul := nat.zero_mul,
mul_zero := nat.mul_zero,
mul_comm := nat.mul_comm,
is_hset_carrier:= _⦄
end nat
section
open nat
definition iterate {A : Type} (op : A → A) : ℕ → A → A
| 0 := λ a, a
| (succ k) := λ a, op (iterate k a)
notation f`^[`n`]` := iterate f n
end
|
090f6cf36202bf3e63f3b965a4649e3740086058 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/limits/shapes/terminal.lean | 7f70267457a1b63b3f8194d50d0fe234fc484f34 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,750 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Bhavik Mehta
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.pempty
import Mathlib.category_theory.limits.limits
import Mathlib.PostPort
universes u v u₂
namespace Mathlib
/-!
# Initial and terminal objects in a category.
## References
* [Stacks: Initial and final objects](https://stacks.math.columbia.edu/tag/002B)
-/
namespace category_theory.limits
/-- Construct a cone for the empty diagram given an object. -/
/-- Construct a cocone for the empty diagram given an object. -/
@[simp] theorem as_empty_cone_π_app {C : Type u} [category C] (X : C) : ∀ (X_1 : discrete pempty), nat_trans.app (cone.π (as_empty_cone X)) X_1 = as_empty_cone._aux_1 X X_1 :=
fun (X_1 : discrete pempty) => Eq.refl (nat_trans.app (cone.π (as_empty_cone X)) X_1)
@[simp] theorem as_empty_cocone_ι_app {C : Type u} [category C] (X : C) : ∀ (X_1 : discrete pempty), nat_trans.app (cocone.ι (as_empty_cocone X)) X_1 = as_empty_cocone._aux_1 X X_1 :=
fun (X_1 : discrete pempty) => Eq.refl (nat_trans.app (cocone.ι (as_empty_cocone X)) X_1)
/-- `X` is terminal if the cone it induces on the empty diagram is limiting. -/
/-- `X` is initial if the cocone it induces on the empty diagram is colimiting. -/
def is_terminal {C : Type u} [category C] (X : C) :=
is_limit (as_empty_cone X)
def is_initial {C : Type u} [category C] (X : C) :=
is_colimit (as_empty_cocone X)
/-- Give the morphism to a terminal object from any other. -/
def is_terminal.from {C : Type u} [category C] {X : C} (t : is_terminal X) (Y : C) : Y ⟶ X :=
is_limit.lift t (as_empty_cone Y)
/-- Any two morphisms to a terminal object are equal. -/
theorem is_terminal.hom_ext {C : Type u} [category C] {X : C} {Y : C} (t : is_terminal X) (f : Y ⟶ X) (g : Y ⟶ X) : f = g := sorry
/-- Give the morphism from an initial object to any other. -/
def is_initial.to {C : Type u} [category C] {X : C} (t : is_initial X) (Y : C) : X ⟶ Y :=
is_colimit.desc t (as_empty_cocone Y)
/-- Any two morphisms from an initial object are equal. -/
theorem is_initial.hom_ext {C : Type u} [category C] {X : C} {Y : C} (t : is_initial X) (f : X ⟶ Y) (g : X ⟶ Y) : f = g := sorry
/-- Any morphism from a terminal object is mono. -/
theorem is_terminal.mono_from {C : Type u} [category C] {X : C} {Y : C} (t : is_terminal X) (f : X ⟶ Y) : mono f :=
mono.mk fun (Z : C) (g h : Z ⟶ X) (eq : g ≫ f = h ≫ f) => is_terminal.hom_ext t g h
/-- Any morphism to an initial object is epi. -/
theorem is_initial.epi_to {C : Type u} [category C] {X : C} {Y : C} (t : is_initial X) (f : Y ⟶ X) : epi f :=
epi.mk fun (Z : C) (g h : X ⟶ Z) (eq : f ≫ g = f ≫ h) => is_initial.hom_ext t g h
/--
A category has a terminal object if it has a limit over the empty diagram.
Use `has_terminal_of_unique` to construct instances.
-/
/--
def has_terminal (C : Type u) [category C] :=
has_limits_of_shape (discrete pempty) C
A category has an initial object if it has a colimit over the empty diagram.
Use `has_initial_of_unique` to construct instances.
-/
def has_initial (C : Type u) [category C] :=
has_colimits_of_shape (discrete pempty) C
/--
An arbitrary choice of terminal object, if one exists.
You can use the notation `⊤_ C`.
This object is characterized by having a unique morphism from any object.
-/
/--
def terminal (C : Type u) [category C] [has_terminal C] : C :=
limit (functor.empty C)
An arbitrary choice of initial object, if one exists.
You can use the notation `⊥_ C`.
This object is characterized by having a unique morphism to any object.
-/
def initial (C : Type u) [category C] [has_initial C] : C :=
colimit (functor.empty C)
prefix:20 "⊤_" => Mathlib.category_theory.limits.terminal
prefix:20 "⊥_" => Mathlib.category_theory.limits.initial
/-- We can more explicitly show that a category has a terminal object by specifying the object,
and showing there is a unique morphism to it from any other object. -/
theorem has_terminal_of_unique {C : Type u} [category C] (X : C) [h : (Y : C) → unique (Y ⟶ X)] : has_terminal C := sorry
/-- We can more explicitly show that a category has an initial object by specifying the object,
and showing there is a unique morphism from it to any other object. -/
theorem has_initial_of_unique {C : Type u} [category C] (X : C) [h : (Y : C) → unique (X ⟶ Y)] : has_initial C := sorry
/-- The map from an object to the terminal object. -/
def terminal.from {C : Type u} [category C] [has_terminal C] (P : C) : P ⟶ ⊤_C :=
limit.lift (functor.empty C) (as_empty_cone P)
/-- The map to an object from the initial object. -/
def initial.to {C : Type u} [category C] [has_initial C] (P : C) : ⊥_C ⟶ P :=
colimit.desc (functor.empty C) (as_empty_cocone P)
protected instance unique_to_terminal {C : Type u} [category C] [has_terminal C] (P : C) : unique (P ⟶ ⊤_C) :=
unique.mk { default := terminal.from P } sorry
protected instance unique_from_initial {C : Type u} [category C] [has_initial C] (P : C) : unique (⊥_C ⟶ P) :=
unique.mk { default := initial.to P } sorry
/-- A terminal object is terminal. -/
def terminal_is_terminal {C : Type u} [category C] [has_terminal C] : is_terminal (⊤_C) :=
is_limit.mk fun (s : cone (functor.empty C)) => terminal.from (cone.X s)
/-- An initial object is initial. -/
def initial_is_initial {C : Type u} [category C] [has_initial C] : is_initial (⊥_C) :=
is_colimit.mk fun (s : cocone (functor.empty C)) => initial.to (cocone.X s)
/-- Any morphism from a terminal object is mono. -/
protected instance terminal.mono_from {C : Type u} [category C] {Y : C} [has_terminal C] (f : ⊤_C ⟶ Y) : mono f :=
is_terminal.mono_from terminal_is_terminal f
/-- Any morphism to an initial object is epi. -/
protected instance initial.epi_to {C : Type u} [category C] {Y : C} [has_initial C] (f : Y ⟶ ⊥_C) : epi f :=
is_initial.epi_to initial_is_initial f
/-- An initial object is terminal in the opposite category. -/
def terminal_op_of_initial {C : Type u} [category C] {X : C} (t : is_initial X) : is_terminal (opposite.op X) :=
is_limit.mk fun (s : cone (functor.empty (Cᵒᵖ))) => has_hom.hom.op (is_initial.to t (opposite.unop (cone.X s)))
/-- An initial object in the opposite category is terminal in the original category. -/
def terminal_unop_of_initial {C : Type u} [category C] {X : Cᵒᵖ} (t : is_initial X) : is_terminal (opposite.unop X) :=
is_limit.mk fun (s : cone (functor.empty C)) => has_hom.hom.unop (is_initial.to t (opposite.op (cone.X s)))
/-- A terminal object is initial in the opposite category. -/
def initial_op_of_terminal {C : Type u} [category C] {X : C} (t : is_terminal X) : is_initial (opposite.op X) :=
is_colimit.mk fun (s : cocone (functor.empty (Cᵒᵖ))) => has_hom.hom.op (is_terminal.from t (opposite.unop (cocone.X s)))
/-- A terminal object in the opposite category is initial in the original category. -/
def initial_unop_of_terminal {C : Type u} [category C] {X : Cᵒᵖ} (t : is_terminal X) : is_initial (opposite.unop X) :=
is_colimit.mk fun (s : cocone (functor.empty C)) => has_hom.hom.unop (is_terminal.from t (opposite.op (cocone.X s)))
/-- From a functor `F : J ⥤ C`, given an initial object of `J`, construct a cone for `J`.
In `limit_of_diagram_initial` we show it is a limit cone. -/
@[simp] theorem cone_of_diagram_initial_π_app {C : Type u} [category C] {J : Type v} [small_category J] {X : J} (tX : is_initial X) (F : J ⥤ C) (j : J) : nat_trans.app (cone.π (cone_of_diagram_initial tX F)) j = functor.map F (is_initial.to tX j) :=
Eq.refl (nat_trans.app (cone.π (cone_of_diagram_initial tX F)) j)
/-- From a functor `F : J ⥤ C`, given an initial object of `J`, show the cone
`cone_of_diagram_initial` is a limit. -/
def limit_of_diagram_initial {C : Type u} [category C] {J : Type v} [small_category J] {X : J} (tX : is_initial X) (F : J ⥤ C) : is_limit (cone_of_diagram_initial tX F) :=
is_limit.mk fun (s : cone F) => nat_trans.app (cone.π s) X
-- This is reducible to allow usage of lemmas about `cone_point_unique_up_to_iso`.
/-- For a functor `F : J ⥤ C`, if `J` has an initial object then the image of it is isomorphic
to the limit of `F`. -/
def limit_of_initial {C : Type u} [category C] {J : Type v} [small_category J] (F : J ⥤ C) [has_initial J] [has_limit F] : limit F ≅ functor.obj F (⊥_J) :=
is_limit.cone_point_unique_up_to_iso (limit.is_limit F) (limit_of_diagram_initial initial_is_initial F)
/-- From a functor `F : J ⥤ C`, given a terminal object of `J`, construct a cocone for `J`.
In `colimit_of_diagram_terminal` we show it is a colimit cocone. -/
@[simp] theorem cocone_of_diagram_terminal_X {C : Type u} [category C] {J : Type v} [small_category J] {X : J} (tX : is_terminal X) (F : J ⥤ C) : cocone.X (cocone_of_diagram_terminal tX F) = functor.obj F X :=
Eq.refl (cocone.X (cocone_of_diagram_terminal tX F))
/-- From a functor `F : J ⥤ C`, given a terminal object of `J`, show the cocone
`cocone_of_diagram_terminal` is a colimit. -/
def colimit_of_diagram_terminal {C : Type u} [category C] {J : Type v} [small_category J] {X : J} (tX : is_terminal X) (F : J ⥤ C) : is_colimit (cocone_of_diagram_terminal tX F) :=
is_colimit.mk fun (s : cocone F) => nat_trans.app (cocone.ι s) X
-- This is reducible to allow usage of lemmas about `cocone_point_unique_up_to_iso`.
/-- For a functor `F : J ⥤ C`, if `J` has a terminal object then the image of it is isomorphic
to the colimit of `F`. -/
def colimit_of_terminal {C : Type u} [category C] {J : Type v} [small_category J] (F : J ⥤ C) [has_terminal J] [has_colimit F] : colimit F ≅ functor.obj F (⊤_J) :=
is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit F) (colimit_of_diagram_terminal terminal_is_terminal F)
/--
The comparison morphism from the image of a terminal object to the terminal object in the target
category.
-/
-- TODO: Show this is an isomorphism if and only if `G` preserves terminal objects.
def terminal_comparison {C : Type u} [category C] {D : Type u₂} [category D] (G : C ⥤ D) [has_terminal C] [has_terminal D] : functor.obj G (⊤_C) ⟶ ⊤_D :=
terminal.from (functor.obj G (⊤_C))
/--
The comparison morphism from the initial object in the target category to the image of the initial
object.
-/
-- TODO: Show this is an isomorphism if and only if `G` preserves initial objects.
def initial_comparison {C : Type u} [category C] {D : Type u₂} [category D] (G : C ⥤ D) [has_initial C] [has_initial D] : ⊥_D ⟶ functor.obj G (⊥_C) :=
initial.to (functor.obj G (⊥_C))
|
256ba6bc7b7a00de9fae64fe0b4c6b81bd3ed17d | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /test/lint_simp_comm.lean | dc675d22ee2d5ebaa66d7a87015551821c0f0fc6 | [
"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 | 1,081 | lean | import tactic.lint
import algebra.group.basic
/-! ## Commutativity lemmas should be rejected -/
attribute [simp] add_comm add_left_comm
open tactic
run_cmd do
decl ← get_decl ``add_comm,
res ← linter.simp_comm.test decl,
-- linter complains
guard res.is_some
open tactic
run_cmd do
decl ← get_decl ``add_left_comm,
res ← linter.simp_comm.test decl,
-- linter complains
guard res.is_some
/-! ## Floris' trick should be accepted -/
@[simp] lemma list.filter_congr_decidable {α} (s : list α) (p : α → Prop) (h : decidable_pred p)
[decidable_pred p] : @list.filter α p h s = s.filter p :=
by congr
-- lemma is unproblematic
example : @list.filter _ (λ x, x > 0) (λ _, classical.prop_decidable _) [1,2,3] = [1,2,3] :=
begin
-- can rewrite once
simp only [list.filter_congr_decidable],
-- but not twice
success_if_fail { simp only [list.filter_congr_decidable] },
refl
end
open tactic
set_option pp.all true
run_cmd do
decl ← get_decl ``list.filter_congr_decidable,
res ← linter.simp_comm.test decl,
-- linter does not complain
guard res.is_none
|
36a6ab96012aec771b878a620b4628a691437dd3 | 618003631150032a5676f229d13a079ac875ff77 | /src/tactic/push_neg.lean | d49a1d050cc90cee6b598379af312317e9dc7fc8 | [
"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 | 7,955 | lean | /-
Copyright (c) 2019 Patrick Massot All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Patrick Massot, Simon Hudon
A tactic pushing negations into an expression
-/
import tactic.interactive
import algebra.order
open tactic expr
namespace push_neg
section
universe u
variable {α : Sort u}
variables (p q : Prop)
variable (s : α → Prop)
local attribute [instance, priority 10] classical.prop_decidable
theorem not_not_eq : (¬ ¬ p) = p := propext not_not
theorem not_and_eq : (¬ (p ∧ q)) = (¬ p ∨ ¬ q) := propext not_and_distrib
theorem not_or_eq : (¬ (p ∨ q)) = (¬ p ∧ ¬ q) := propext not_or_distrib
theorem not_forall_eq : (¬ ∀ x, s x) = (∃ x, ¬ s x) := propext not_forall
theorem not_exists_eq : (¬ ∃ x, s x) = (∀ x, ¬ s x) := propext not_exists
theorem not_implies_eq : (¬ (p → q)) = (p ∧ ¬ q) := propext not_imp
theorem classical.implies_iff_not_or : (p → q) ↔ (¬ p ∨ q) := imp_iff_not_or
theorem not_eq (a b : α) : (¬ a = b) ↔ (a ≠ b) := iff.rfl
variable {β : Type u}
variable [linear_order β]
theorem not_le_eq (a b : β) : (¬ (a ≤ b)) = (b < a) := propext not_le
theorem not_lt_eq (a b : β) : (¬ (a < b)) = (b ≤ a) := propext not_lt
end
meta def whnf_reducible (e : expr) : tactic expr := whnf e reducible
private meta def transform_negation_step (e : expr) :
tactic (option (expr × expr)) :=
do e ← whnf_reducible e,
match e with
| `(¬ %%ne) :=
(do ne ← whnf_reducible ne,
match ne with
| `(¬ %%a) := do pr ← mk_app ``not_not_eq [a],
return (some (a, pr))
| `(%%a ∧ %%b) := do pr ← mk_app ``not_and_eq [a, b],
return (some (`(¬ %%a ∨ ¬ %%b), pr))
| `(%%a ∨ %%b) := do pr ← mk_app ``not_or_eq [a, b],
return (some (`(¬ %%a ∧ ¬ %%b), pr))
| `(%%a ≤ %%b) := do e ← to_expr ``(%%b < %%a),
pr ← mk_app ``not_le_eq [a, b],
return (some (e, pr))
| `(%%a < %%b) := do e ← to_expr ``(%%b ≤ %%a),
pr ← mk_app ``not_lt_eq [a, b],
return (some (e, pr))
| `(Exists %%p) := do pr ← mk_app ``not_exists_eq [p],
e ← match p with
| (lam n bi typ bo) := do
body ← mk_app ``not [bo],
return (pi n bi typ body)
| _ := tactic.fail "Unexpected failure negating ∃"
end,
return (some (e, pr))
| (pi n bi d p) := if p.has_var then do
pr ← mk_app ``not_forall_eq [lam n bi d p],
body ← mk_app ``not [p],
e ← mk_app ``Exists [lam n bi d body],
return (some (e, pr))
else do
pr ← mk_app ``not_implies_eq [d, p],
`(%%_ = %%e') ← infer_type pr,
return (some (e', pr))
| _ := return none
end)
| _ := return none
end
private meta def transform_negation : expr → tactic (option (expr × expr))
| e :=
do (some (e', pr)) ← transform_negation_step e | return none,
(some (e'', pr')) ← transform_negation e' | return (some (e', pr)),
pr'' ← mk_eq_trans pr pr',
return (some (e'', pr''))
meta def normalize_negations (t : expr) : tactic (expr × expr) :=
do (_, e, pr) ← simplify_top_down ()
(λ _, λ e, do
oepr ← transform_negation e,
match oepr with
| (some (e', pr)) := return ((), e', pr)
| none := do pr ← mk_eq_refl e, return ((), e, pr)
end)
t { eta := ff },
return (e, pr)
meta def push_neg_at_hyp (h : name) : tactic unit :=
do H ← get_local h,
t ← infer_type H,
(e, pr) ← normalize_negations t,
replace_hyp H e pr,
skip
meta def push_neg_at_goal : tactic unit :=
do H ← target,
(e, pr) ← normalize_negations H,
replace_target e pr
end push_neg
open interactive (parse loc.ns loc.wildcard)
open interactive.types (location texpr)
open lean.parser (tk ident many) interactive.loc
local postfix `?`:9001 := optional
local postfix *:9001 := many
open push_neg
/--
Push negations in the goal of some assumption.
For instance, a hypothesis `h : ¬ ∀ x, ∃ y, x ≤ y` will be transformed by `push_neg at h` into
`h : ∃ x, ∀ y, y < x`. Variables names are conserved.
This tactic pushes negations inside expressions. For instance, given an assumption
```lean
h : ¬ ∀ ε > 0, ∃ δ > 0, ∀ x, |x - x₀| ≤ δ → |f x - y₀| ≤ ε)
```
writing `push_neg at h` will turn `h` into
```lean
h : ∃ ε, ε > 0 ∧ ∀ δ, δ > 0 → (∃ x, |x - x₀| ≤ δ ∧ ε < |f x - y₀|),
```
(the pretty printer does *not* use the abreviations `∀ δ > 0` and `∃ ε > 0` but this issue
has nothing to do with `push_neg`).
Note that names are conserved by this tactic, contrary to what would happen with `simp`
using the relevant lemmas. One can also use this tactic at the goal using `push_neg`,
at every assumption and the goal using `push_neg at *` or at selected assumptions and the goal
using say `push_neg at h h' ⊢` as usual.
-/
meta def tactic.interactive.push_neg : parse location → tactic unit
| (loc.ns loc_l) := loc_l.mmap'
(λ l, match l with
| some h := do push_neg_at_hyp h,
try `[simp only [push_neg.not_eq] at h { eta := ff }]
| none := do push_neg_at_goal,
try `[simp only [push_neg.not_eq] { eta := ff }]
end)
| loc.wildcard := do
push_neg_at_goal,
local_context >>= mmap' (λ h, push_neg_at_hyp (local_pp_name h)) ,
try `[simp only [push_neg.not_eq] at * { eta := ff }]
add_tactic_doc
{ name := "push_neg",
category := doc_category.tactic,
decl_names := [`tactic.interactive.push_neg],
tags := ["logic"] }
lemma imp_of_not_imp_not (P Q : Prop) : (¬ Q → ¬ P) → (P → Q) :=
λ h hP, classical.by_contradiction (λ h', h h' hP)
/-- Matches either an identifier "h" or a pair of identifiers "h with k" -/
meta def name_with_opt : lean.parser (name × option name) :=
prod.mk <$> ident <*> (some <$> (tk "with" >> ident) <|> return none)
/--
Transforms the goal into its contrapositive.
* `contrapose` turns a goal `P → Q` into `¬ Q → ¬ P`
* `contrapose!` turns a goal `P → Q` into `¬ Q → ¬ P` and pushes negations inside `P` and `Q`
using `push_neg`
* `contrapose h` first reverts the local assumption `h`, and then uses `contrapose` and `intro h`
* `contrapose! h` first reverts the local assumption `h`, and then uses `contrapose!` and `intro h`
* `contrapose h with new_h` uses the name `new_h` for the introduced hypothesis
-/
meta def tactic.interactive.contrapose (push : parse (tk "!" )?) : parse name_with_opt? → tactic unit
| (some (h, h')) := get_local h >>= revert >> tactic.interactive.contrapose none >> intro (h'.get_or_else h) >> skip
| none :=
do `(%%P → %%Q) ← target | fail "The goal is not an implication, and you didn't specify an assumption",
cp ← mk_mapp ``imp_of_not_imp_not [P, Q] <|> fail "contrapose only applies to nondependent arrows between props",
apply cp,
when push.is_some $ try (tactic.interactive.push_neg (loc.ns [none]))
add_tactic_doc
{ name := "contrapose",
category := doc_category.tactic,
decl_names := [`tactic.interactive.contrapose],
tags := ["logic"] }
|
575a7c74aeae1ce46878c9e3c080a81136f6a5e0 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/univPolyEnum.lean | 96f4af0867f257b2d2966b77c997368e2042180a | [
"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 | 35 | lean | inductive T : Type u
| intro : T
|
f0ff35f688fc9f59b0898dbb551bd357d6edb4b7 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/list_elab1.lean | f383919055dfeb7a0f367308d1aa685c1d347e88 | [
"Apache-2.0"
] | permissive | soonhokong/lean | cb8aa01055ffe2af0fb99a16b4cda8463b882cd1 | 38607e3eb57f57f77c0ac114ad169e9e4262e24f | refs/heads/master | 1,611,187,284,081 | 1,450,766,737,000 | 1,476,122,547,000 | 11,513,992 | 2 | 0 | null | 1,401,763,102,000 | 1,374,182,235,000 | C++ | UTF-8 | Lean | false | false | 1,146 | lean | ----------------------------------------------------------------------------------------------------
--- Copyright (c) 2014 Parikshit Khanna. All rights reserved.
--- Released under Apache 2.0 license as described in the file LICENSE.
--- Authors: Parikshit Khanna, Jeremy Avigad
----------------------------------------------------------------------------------------------------
-- Theory list
-- ===========
--
-- Basic properties of lists.
import data.nat
open nat eq.ops
inductive list (T : Type) : Type :=
| nil {} : list T
| cons : T → list T → list T
namespace list
theorem list_induction_on {T : Type} {P : list T → Prop} (l : list T) (Hnil : P nil)
(Hind : forall x : T, forall l : list T, forall H : P l, P (cons x l)) : P l :=
list.rec Hnil Hind l
definition concat {T : Type} (s t : list T) : list T :=
list.rec t (fun x : T, fun l : list T, fun u : list T, cons x u) s
attribute concat [reducible]
theorem concat_nil {T : Type} (t : list T) : concat t nil = t :=
list_induction_on t (eq.refl (concat nil nil))
(take (x : T) (l : list T) (H : concat l nil = l),
H ▸ (eq.refl (concat (cons x l) nil)))
end list
|
2558a0973409cee630d17e0dce30f4403e3f64f9 | 842b7df4a999c5c50bbd215b8617dd705e43c2e1 | /nat_num_game/src/Advanced_Addition_World/adv_add_wrld2.lean | cd258e1cd2898d56509c875802d07dd6fa72abe1 | [] | no_license | Samyak-Surti/LeanCode | 1c245631f74b00057d20483c8ac75916e8643b14 | 944eac3e5f43e2614ed246083b97fbdf24181d83 | refs/heads/master | 1,669,023,730,828 | 1,595,534,784,000 | 1,595,534,784,000 | 282,037,186 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 199 | lean | theorem succ_succ_inj {a b : ℕ} (h : nat.succ(nat.succ(a)) = nat.succ(nat.succ(b))) : a = b :=
begin
have hs : nat.succ a = nat.succ b,
apply nat.succ.inj h,
apply nat.succ.inj hs,
end |
4173baf3d1e9d7559f30fae142d0fd3a2d1e84a2 | ff5230333a701471f46c57e8c115a073ebaaa448 | /library/init/meta/environment.lean | 92b9b936ef0881747e0be28f539028a7fdb42b3a | [
"Apache-2.0"
] | permissive | stanford-cs242/lean | f81721d2b5d00bc175f2e58c57b710d465e6c858 | 7bd861261f4a37326dcf8d7a17f1f1f330e4548c | refs/heads/master | 1,600,957,431,849 | 1,576,465,093,000 | 1,576,465,093,000 | 225,779,423 | 0 | 3 | Apache-2.0 | 1,575,433,936,000 | 1,575,433,935,000 | null | UTF-8 | Lean | false | false | 9,756 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta.declaration init.meta.exceptional init.data.option.basic
import init.meta.rb_map
/-- An __environment__ contains all of the declarations and notation that have been defined so far. -/
meta constant environment : Type
namespace environment
/--
Consider a type ψ which is an inductive datatype using a single constructor `mk (a : α) (b : β) : → ψ`.
Lean will automatically make two projection functions `a : ψ → α`, `b : ψ → β`.
Lean tags these declarations as __projections__.
This helps the simplifier / rewriter not have to expand projectors.
Eg `a (mk x y)` will automatically reduce to `x`.
If you `extend` a structure, all of the projections on the parent will also be created for the child.
[TODO] any other reasons Lean treats projections differently to regular declarations?
I know that you get projection macros.
[TODO] Are there projections that aren't arguments to constructors?
[NOTE] projectors have nothing to do with the dot `mylist.map` syntax.
You can find out if a declaration is a projection using `environment.is_projection` which returns `projection_info`.
Data for a projection declaration:
- `cname` is the name of the constructor associated with the projection.
- `nparams` is the number of constructor parameters. Eg `and.intro` has two type parameters.
- `idx` is the parameter being projected by this projection.
- `is_class` is tt iff this is a typeclass projection.
### Examples:
- `and.right` is a projection with ``{cname := `and.intro, nparams := 2, idx := 1, is_class := ff}``
- `ordered_ring.neg` is a projection with ``{cname := `ordered_ring.mk, nparams := 1, idx := 5, is_class := tt}``.
-/
structure projection_info :=
(cname : name)
(nparams : nat)
(idx : nat)
(is_class : bool)
/-- A marking on the binders of structures and inductives indicating
how this constructor should mark its parameters.
inductive foo
| one {} : foo -> foo -- relaxed_implicit
| two ( ) : foo -> foo -- none
| three : foo -> foo -- implicit (default)
-/
inductive implicit_infer_kind | implicit | relaxed_implicit | none
instance implicit_infer_kind.inhabited : inhabited implicit_infer_kind := ⟨implicit_infer_kind.implicit⟩
/-- One introduction rule in an inductive declaration -/
meta structure intro_rule :=
(constr : name)
(type : expr)
(infer : implicit_infer_kind := implicit_infer_kind.implicit)
/-- Create a standard environment using the given trust level -/
meta constant mk_std : nat → environment
/-- Return the trust level of the given environment -/
meta constant trust_lvl : environment → nat
/-- Add a new declaration to the environment -/
meta constant add : environment → declaration → exceptional environment
/-- Retrieve a declaration from the environment -/
meta constant get : environment → name → exceptional declaration
meta def contains (env : environment) (d : name) : bool :=
match env.get d with
| exceptional.success _ := tt
| exceptional.exception ._ _ := ff
end
meta constant add_defn_eqns (env : environment) (opt : options)
(lp_params : list name) (params : list expr) (sig : expr)
(eqns : list (list (expr ff) × expr)) (is_meta : bool) : exceptional environment
/-- Register the given name as a namespace, making it available to the `open` command -/
meta constant add_namespace : environment → name → environment
/-- Return tt iff the given name is a namespace -/
meta constant is_namespace : environment → name → bool
/-- Add a new inductive datatype to the environment
name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/
meta constant add_inductive (env : environment)
(n : name) (levels : list name) (num_params : nat) (type : expr)
(intros : list (name × expr)) (is_meta : bool) : exceptional environment
/-- Add a new general inductive declaration to the environment.
This has the same effect as a `inductive` in the file, including generating
all the auxiliary definitions, as well as triggering mutual/nested inductive
compilation, by contrast to `environment.add_inductive` which only adds the
core axioms supported by the kernel.
The `inds` argument should be a list of inductives in the mutual family.
The first argument is a pair of the name of the type being constructed
and the type of this inductive family (not including the params).
The second argument is a list of intro rules, specified by a name, an
`implicit_infer_kind` giving the implicitness of the params for this constructor,
and an expression with the type of the constructor (not including the params).
-/
meta constant add_ginductive (env : environment) (opt : options)
(levels : list name) (params : list expr)
(inds : list ((name × expr) × list intro_rule))
(is_meta : bool) : exceptional environment
/-- Return tt iff the given name is an inductive datatype -/
meta constant is_inductive : environment → name → bool
/-- Return tt iff the given name is a constructor -/
meta constant is_constructor : environment → name → bool
/-- Return tt iff the given name is a recursor -/
meta constant is_recursor : environment → name → bool
/-- Return tt iff the given name is a recursive inductive datatype -/
meta constant is_recursive : environment → name → bool
/-- Return the name of the inductive datatype of the given constructor. -/
meta constant inductive_type_of : environment → name → option name
/-- Return the constructors of the inductive datatype with the given name -/
meta constant constructors_of : environment → name → list name
/-- Return the recursor of the given inductive datatype -/
meta constant recursor_of : environment → name → option name
/-- Return the number of parameters of the inductive datatype -/
meta constant inductive_num_params : environment → name → nat
/-- Return the number of indices of the inductive datatype -/
meta constant inductive_num_indices : environment → name → nat
/-- Return tt iff the inductive datatype recursor supports dependent elimination -/
meta constant inductive_dep_elim : environment → name → bool
/-- Functionally equivalent to `is_inductive`.
Technically, this works by checking if the name is in the ginductive environment
extension which is outside the kernel, whereas `is_inductive` works by looking at the kernel extension.
But there are no `is_inductive`s which are not `is_ginductive`.
-/
meta constant is_ginductive : environment → name → bool
/-- See the docstring for `projection_info`. -/
meta constant is_projection : environment → name → option projection_info
/-- Fold over declarations in the environment. -/
meta constant fold {α :Type} : environment → α → (declaration → α → α) → α
/-- `relation_info env n` returns some value if n is marked as a relation in the given environment.
the tuple contains: total number of arguments of the relation, lhs position and rhs position. -/
meta constant relation_info : environment → name → option (nat × nat × nat)
/-- `refl_for env R` returns the name of the reflexivity theorem for the relation R -/
meta constant refl_for : environment → name → option name
/-- `symm_for env R` returns the name of the symmetry theorem for the relation R -/
meta constant symm_for : environment → name → option name
/-- `trans_for env R` returns the name of the transitivity theorem for the relation R -/
meta constant trans_for : environment → name → option name
/-- `decl_olean env d` returns the name of the .olean file where d was defined.
The result is none if d was not defined in an imported file. -/
meta constant decl_olean : environment → name → option string
/-- `decl_pos env d` returns the source location of d if available. -/
meta constant decl_pos : environment → name → option pos
/-- Return the fields of the structure with the given name, or `none` if it is not a structure -/
meta constant structure_fields : environment → name → option (list name)
/-- `get_class_attribute_symbols env attr_name` return symbols
occurring in instances of type classes tagged with the attribute `attr_name`.
Example: [algebra] -/
meta constant get_class_attribute_symbols : environment → name → name_set
/-- The fingerprint of the environment is a hash formed from all of the declarations in the environment. -/
meta constant fingerprint : environment → nat
open expr
meta constant unfold_untrusted_macros : environment → expr → expr
meta constant unfold_all_macros : environment → expr → expr
meta def is_constructor_app (env : environment) (e : expr) : bool :=
is_constant (get_app_fn e) && is_constructor env (const_name (get_app_fn e))
meta def is_refl_app (env : environment) (e : expr) : option (name × expr × expr) :=
match (refl_for env (const_name (get_app_fn e))) with
| (some n) :=
if get_app_num_args e ≥ 2
then some (n, app_arg (app_fn e), app_arg e)
else none
| none := none
end
/-- Return true if 'n' has been declared in the current file -/
meta def in_current_file (env : environment) (n : name) : bool :=
(env.decl_olean n).is_none && env.contains n
meta def is_definition (env : environment) (n : name) : bool :=
match env.get n with
| exceptional.success (declaration.defn _ _ _ _ _ _) := tt
| _ := ff
end
end environment
meta instance : has_repr environment :=
⟨λ e, "[environment]"⟩
meta instance : inhabited environment :=
⟨environment.mk_std 0⟩
|
cea6e88d3b8334259daa0412b76747aa50f44c44 | 8b9f17008684d796c8022dab552e42f0cb6fb347 | /library/data/examples/notencodable.lean | 55ba37087ffe2a86c3028286deb68abba09783c9 | [
"Apache-2.0"
] | permissive | chubbymaggie/lean | 0d06ae25f9dd396306fb02190e89422ea94afd7b | d2c7b5c31928c98f545b16420d37842c43b4ae9a | refs/heads/master | 1,611,313,622,901 | 1,430,266,839,000 | 1,430,267,083,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,170 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: data.examples.unencodable
Author: Leonardo de Moura
Small example showing that (nat → nat) is not encodable.
-/
import data.encodable
open nat encodable option
section
hypothesis nat_nat_encodable : encodable (nat → nat)
private definition decode_fun (n : nat) : option (nat → nat) :=
@decode (nat → nat) nat_nat_encodable n
private definition encode_fun (f : nat → nat) : nat :=
@encode (nat → nat) nat_nat_encodable f
private lemma encodek_fun : ∀ f : nat → nat, decode_fun (encode_fun f) = some f :=
λ f, !encodek
private definition f (n : nat) : nat :=
match decode_fun n with
| some g := succ (g n)
| none := 0
end
private definition v : nat := encode_fun f
private lemma f_eq : succ (f v) = f v :=
begin
change (succ (f v) =
match decode_fun (encode_fun f) with
| some g := succ (g v)
| none := 0
end),
rewrite encodek_fun
end
end
theorem not_encodable_nat_arrow_nat : (encodable (nat → nat)) → false :=
assume h, absurd (f_eq h) succ_ne_self
|
d338b385bb92ec8552efa274aa1df06b99bb65c2 | b2fe74b11b57d362c13326bc5651244f111fa6f4 | /src/category_theory/sites/canonical.lean | eeb4ee71eade62b61ea8d39d5465b6d9f57a9e9a | [
"Apache-2.0"
] | permissive | midfield/mathlib | c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7 | 775edc615ecec631d65b6180dbcc7bc26c3abc26 | refs/heads/master | 1,675,330,551,921 | 1,608,304,514,000 | 1,608,304,514,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,645 | 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.sites.sheaf
/-!
# The canonical topology on a category
We define the finest (largest) Grothendieck topology for which a given presheaf `P` is a sheaf.
This is well defined since if `P` is a sheaf for a topology `J`, then it is a sheaf for any
coarser (smaller) topology. Nonetheless we define the topology explicitly by specifying its sieves:
A sieve `S` on `X` is covering for `finest_topology_single P` iff
for any `f : Y ⟶ X`, `P` satisfies the sheaf axiom for `S.pullback f`.
Showing that this is a genuine Grothendieck topology (namely that it satisfies the transitivity
axiom) forms the bulk of this file.
This generalises to a set of presheaves, giving the topology `finest_topology Ps` which is the
finest topology for which every presheaf in `Ps` is a sheaf.
Using `Ps` as the set of representable presheaves defines the `canonical_topology`: the finest
topology for which every representable is a sheaf.
A Grothendieck topology is called `subcanonical` if it is smaller than the canonical topology,
equivalently it is subcanonical iff every representable presheaf is a sheaf.
## References
* https://ncatlab.org/nlab/show/canonical+topology
* https://ncatlab.org/nlab/show/subcanonical+coverage
* https://stacks.math.columbia.edu/tag/00Z9
* https://math.stackexchange.com/a/358709/
-/
universes v u
namespace category_theory
open category_theory category limits sieve classical
variables {C : Type u} [category.{v} C]
namespace sheaf
variables {P : Cᵒᵖ ⥤ Type v}
variables {X Y : C} {S : sieve X} {R : presieve X}
variables (J J₂ : grothendieck_topology C)
/--
To show `P` is a sheaf for the binding of `U` with `B`, it suffices to show that `P` is a sheaf for
`U`, that `P` is a sheaf for each sieve in `B`, and that it is separated for any pullback of any
sieve in `B`.
This is mostly an auxiliary lemma to show `is_sheaf_for_trans`.
Adapted from [Elephant], Lemma C2.1.7(i) with suggestions as mentioned in
https://math.stackexchange.com/a/358709/
-/
lemma is_sheaf_for_bind (P : Cᵒᵖ ⥤ Type v) (U : sieve X)
(B : Π ⦃Y⦄ ⦃f : Y ⟶ X⦄, U f → sieve Y)
(hU : presieve.is_sheaf_for P U)
(hB : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄ (hf : U f), presieve.is_sheaf_for P (B hf))
(hB' : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄ (h : U f) ⦃Z⦄ (g : Z ⟶ Y),
presieve.is_separated_for P ((B h).pullback g)) :
presieve.is_sheaf_for P (sieve.bind U B) :=
begin
intros s hs,
let y : Π ⦃Y⦄ ⦃f : Y ⟶ X⦄ (hf : U f), presieve.family_of_elements P (B hf) :=
λ Y f hf Z g hg, s _ (presieve.bind_comp _ _ hg),
have hy : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄ (hf : U f), (y hf).compatible,
{ intros Y f H Y₁ Y₂ Z g₁ g₂ f₁ f₂ hf₁ hf₂ comm,
apply hs,
apply reassoc_of comm },
let t : presieve.family_of_elements P U := λ Y f hf, (hB hf).amalgamate (y hf) (hy hf),
have ht : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄ (hf : U f), (y hf).is_amalgamation (t f hf) :=
λ Y f hf, (hB hf).is_amalgamation _,
have hT : t.compatible,
{ rw presieve.compatible_iff_sieve_compatible,
intros Z W f h hf,
apply (hB (U.downward_closed hf h)).is_separated_for.ext,
intros Y l hl,
apply (hB' hf (l ≫ h)).ext,
intros M m hm,
have : bind U B (m ≫ l ≫ h ≫ f),
{ have : bind U B _ := presieve.bind_comp f hf hm,
simpa using this },
transitivity s (m ≫ l ≫ h ≫ f) this,
{ have := ht (U.downward_closed hf h) _ ((B _).downward_closed hl m),
rw [op_comp, functor_to_types.map_comp_apply] at this,
rw this,
change s _ _ = s _ _,
simp },
{ have : s _ _ = _ := (ht hf _ hm).symm,
simp only [assoc] at this,
rw this,
simp } },
refine ⟨hU.amalgamate t hT, _, _⟩,
{ rintro Z _ ⟨Y, f, g, hg, hf, rfl⟩,
rw [op_comp, functor_to_types.map_comp_apply, presieve.is_sheaf_for.valid_glue _ _ _ hg],
apply ht hg _ hf },
{ intros y hy,
apply hU.is_separated_for.ext,
intros Y f hf,
apply (hB hf).is_separated_for.ext,
intros Z g hg,
rw [←functor_to_types.map_comp_apply, ←op_comp, hy _ (presieve.bind_comp _ _ hg),
hU.valid_glue _ _ hf, ht hf _ hg] }
end
/--
Given two sieves `R` and `S`, to show that `P` is a sheaf for `S`, we can show:
* `P` is a sheaf for `R`
* `P` is a sheaf for the pullback of `S` along any arrow in `R`
* `P` is separated for the pullback of `R` along any arrow in `S`.
This is mostly an auxiliary lemma to construct `finest_topology`.
Adapted from [Elephant], Lemma C2.1.7(ii) with suggestions as mentioned in
https://math.stackexchange.com/a/358709
-/
lemma is_sheaf_for_trans (P : Cᵒᵖ ⥤ Type v) (R S : sieve X)
(hR : presieve.is_sheaf_for P R)
(hR' : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄ (hf : S f), presieve.is_separated_for P (R.pullback f))
(hS : Π ⦃Y⦄ ⦃f : Y ⟶ X⦄ (hf : R f), presieve.is_sheaf_for P (S.pullback f)) :
presieve.is_sheaf_for P S :=
begin
have : (bind R (λ Y f hf, S.pullback f) : presieve X) ≤ S,
{ rintros Z f ⟨W, f, g, hg, (hf : S _), rfl⟩,
apply hf },
apply presieve.is_sheaf_for_subsieve_aux P this,
apply is_sheaf_for_bind _ _ _ hR hS,
{ intros Y f hf Z g,
dsimp,
rw ← pullback_comp,
apply (hS (R.downward_closed hf _)).is_separated_for },
{ intros Y f hf,
have : (sieve.pullback f (bind R (λ T (k : T ⟶ X) (hf : R k), pullback k S))) = R.pullback f,
{ ext Z g,
split,
{ rintro ⟨W, k, l, hl, _, comm⟩,
rw [pullback_apply, ← comm],
simp [hl] },
{ intro a,
refine ⟨Z, 𝟙 Z, _, a, _⟩,
simp [hf] } },
rw this,
apply hR' hf },
end
/--
Construct the finest (largest) Grothendieck topology for which the given presheaf is a sheaf.
This is a special case of https://stacks.math.columbia.edu/tag/00Z9, but following a different
proof (see the comments there).
-/
def finest_topology_single (P : Cᵒᵖ ⥤ Type v) : grothendieck_topology C :=
{ sieves := λ X S, ∀ Y (f : Y ⟶ X), presieve.is_sheaf_for P (S.pullback f),
top_mem' := λ X Y f,
begin
rw sieve.pullback_top,
exact presieve.is_sheaf_for_top_sieve P,
end,
pullback_stable' := λ X Y S f hS Z g,
begin
rw ← pullback_comp,
apply hS,
end,
transitive' := λ X S hS R hR Z g,
begin
-- This is the hard part of the construction, showing that the given set of sieves satisfies
-- the transitivity axiom.
refine is_sheaf_for_trans P (pullback g S) _ (hS Z g) _ _,
{ intros Y f hf,
rw ← pullback_comp,
apply (hS _ _).is_separated_for },
{ intros Y f hf,
have := hR hf _ (𝟙 _),
rw [pullback_id, pullback_comp] at this,
apply this },
end }
/--
Construct the finest (largest) Grothendieck topology for which all the given presheaves are sheaves.
This is equal to the construction of https://stacks.math.columbia.edu/tag/00Z9.
-/
def finest_topology (Ps : set (Cᵒᵖ ⥤ Type v)) : grothendieck_topology C :=
Inf (finest_topology_single '' Ps)
/-- Check that if `P ∈ Ps`, then `P` is indeed a sheaf for the finest topology on `Ps`. -/
lemma sheaf_for_finest_topology (Ps : set (Cᵒᵖ ⥤ Type v)) (h : P ∈ Ps) :
presieve.is_sheaf (finest_topology Ps) P :=
λ X S hS, by simpa using hS _ ⟨⟨_, _, ⟨_, h, rfl⟩, rfl⟩, rfl⟩ _ (𝟙 _)
/--
Check that if each `P ∈ Ps` is a sheaf for `J`, then `J` is a subtopology of `finest_topology Ps`.
-/
lemma le_finest_topology (Ps : set (Cᵒᵖ ⥤ Type v)) (J : grothendieck_topology C)
(hJ : ∀ P ∈ Ps, presieve.is_sheaf J P) : J ≤ finest_topology Ps :=
begin
rintro X S hS _ ⟨⟨_, _, ⟨P, hP, rfl⟩, rfl⟩, rfl⟩,
intros Y f, -- this can't be combined with the previous because the `subst` is applied at the end
exact hJ P hP (S.pullback f) (J.pullback_stable f hS),
end
/--
The `canonical_topology` on a category is the finest (largest) topology for which every
representable presheaf is a sheaf.
See https://stacks.math.columbia.edu/tag/00ZA
-/
def canonical_topology (C : Type u) [category.{v} C] : grothendieck_topology C :=
finest_topology (set.range yoneda.obj)
/-- `yoneda.obj X` is a sheaf for the canonical topology. -/
lemma is_sheaf_yoneda_obj (X : C) : presieve.is_sheaf (canonical_topology C) (yoneda.obj X) :=
λ Y S hS, sheaf_for_finest_topology _ (set.mem_range_self _) _ hS
/-- A representable functor is a sheaf for the canonical topology. -/
lemma is_sheaf_of_representable (P : Cᵒᵖ ⥤ Type v) [representable P] :
presieve.is_sheaf (canonical_topology C) P :=
presieve.is_sheaf_iso (canonical_topology C) representable.w (is_sheaf_yoneda_obj _)
/--
A subcanonical topology is a topology which is smaller than the canonical topology.
Equivalently, a topology is subcanonical iff every representable is a sheaf.
-/
def subcanonical (J : grothendieck_topology C) : Prop :=
J ≤ canonical_topology C
namespace subcanonical
/-- If every functor `yoneda.obj X` is a `J`-sheaf, then `J` is subcanonical. -/
lemma of_yoneda_is_sheaf (J : grothendieck_topology C)
(h : ∀ X, presieve.is_sheaf J (yoneda.obj X)) :
subcanonical J :=
le_finest_topology _ _ (by { rintro P ⟨X, rfl⟩, apply h })
/-- If `J` is subcanonical, then any representable is a `J`-sheaf. -/
lemma is_sheaf_of_representable {J : grothendieck_topology C} (hJ : subcanonical J)
(P : Cᵒᵖ ⥤ Type v) [representable P] :
presieve.is_sheaf J P :=
presieve.is_sheaf_of_le _ hJ (is_sheaf_of_representable P)
end subcanonical
end sheaf
end category_theory
|
486d6f0598ec8f61381c538d7bc67a7fd879e3bc | ad0c7d243dc1bd563419e2767ed42fb323d7beea | /analysis/topology/topological_space.lean | df4ff60c2f89c59143245745075a53ddcbf9de4b | [
"Apache-2.0"
] | permissive | sebzim4500/mathlib | e0b5a63b1655f910dee30badf09bd7e191d3cf30 | 6997cafbd3a7325af5cb318561768c316ceb7757 | refs/heads/master | 1,585,549,958,618 | 1,538,221,723,000 | 1,538,221,723,000 | 150,869,076 | 0 | 0 | Apache-2.0 | 1,538,229,323,000 | 1,538,229,323,000 | null | UTF-8 | Lean | false | false | 61,395 | 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}
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 (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∪ s₂) :=
have (⋃₀ {s₁, s₂}) = (s₁ ∪ s₂), by simp [union_comm],
this ▸ is_open_sUnion $ show ∀(t : set α), t ∈ ({s₁, s₂} : set (set α)) → is_open t,
by finish
lemma is_open_Union {f : ι → set α} (h : ∀i, is_open (f i)) : is_open (⋃i, f i) :=
is_open_sUnion $ assume t ⟨i, (heq : t = f i)⟩, heq.symm ▸ 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
@[simp] lemma is_open_empty : is_open (∅ : set α) :=
have is_open (⋃₀ ∅ : set α), from is_open_sUnion (assume a, false.elim),
by simp at this; assumption
lemma is_open_sInter {s : set (set α)} (hs : finite s) : (∀t ∈ s, is_open t) → is_open (⋂₀ s) :=
finite.induction_on hs (by simp) $ λ a s has hs ih h, begin
suffices : is_open (a ∩ ⋂₀ s), { simpa },
exact is_open_inter (h _ $ mem_insert _ _) (ih $ assume t ht, h _ $ mem_insert_of_mem _ ht)
end
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 simp)
(by simp [or_imp_distrib, _root_.is_open_inter, forall_and_distrib] {contextual := tt})
lemma is_open_const {p : Prop} : is_open {a : α | p} :=
by_cases
(assume : p, begin simp [*]; exact is_open_univ end)
(assume : ¬ p, begin simp [*]; 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 simp [is_closed]
@[simp] lemma is_closed_univ : is_closed (univ : set α) := by simp [is_closed]
lemma is_closed_union : is_closed s₁ → is_closed s₂ → is_closed (s₁ ∪ s₂) :=
by simp [is_closed]; exact is_open_inter
lemma is_closed_sInter {s : set (set α)} : (∀t ∈ s, is_closed t) → is_closed (⋂₀ s) :=
by simp [is_closed, compl_sInter]; 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 simp)
(by simp [or_imp_distrib, is_closed_union, forall_and_distrib] {contextual := tt})
lemma is_closed_imp [topological_space α] {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 $ by finish,
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 [interior, and_comm, 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 [interior_eq_iff_open.symm, subset.antisymm_iff, interior_subset]
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) $ by simp [is_open_inter])
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 simp [subset_interior_iff_subset_of_open, this, is_open_diff hu₁ h₁],
have u \ s ⊆ ∅,
by rw [h₂] at this; assumption,
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 [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 [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) $ by simp [is_closed_union])
(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
simp [interior, closure],
rw [compl_sUnion, compl_image_set_of],
simp [compl_subset_compl]
end
@[simp] lemma interior_compl_eq {s : set α} : interior (- s) = - closure s :=
by simp [closure_eq_compl_interior_compl]
@[simp] lemma closure_compl_eq {s : set α} : closure (- s) = - interior s :=
by simp [closure_eq_compl_interior_compl]
lemma closure_compl {s : set α} : closure (-s) = - interior s :=
subset.antisymm
(by simp [closure_subset_iff_subset_of_is_closed, compl_subset_compl, subset.refl])
begin
rw [compl_subset_comm, subset_interior_iff_subset_of_open, compl_subset_comm],
exact subset_closure,
exact is_open_compl_iff.mpr is_closed_closure
end
lemma interior_compl {s : set α} : interior (-s) = - closure s :=
calc interior (- s) = - - interior (- s) : by simp
... = - closure (- (- s)) : by rw [closure_compl]
... = - closure s : by simp
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[h]) U U_op x_in },
{ ext x,
suffices : x ∈ closure s, by simp [this],
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 [frontier_eq_closure_inter_closure, 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₂⟩, by simp [ge]⟩)
⟨univ, by simp⟩
... = {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₃⟩, by simp; exact ⟨i, ⟨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₂⟩, by simp [ge]⟩)
⟨univ, by simp⟩
... = _ : by simp
lemma mem_nhds_sets_iff {a : α} {s : set α} :
s ∈ (nhds a).sets ↔ ∃t⊆s, is_open t ∧ a ∈ t :=
by simp [nhds_sets]
lemma mem_of_nhds {a : α} {s : set α} : s ∈ (nhds a).sets → a ∈ s :=
by simp [mem_nhds_sets_iff]; exact assume t ht _ hs, ht hs
lemma mem_nhds_sets {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) :
s ∈ (nhds a).sets :=
by simp [nhds_sets]; exact ⟨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 $ by simp [h₁]
@[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 $ by simp [mem_interior, nhds_sets]
lemma mem_interior_iff_mem_nhds {s : set α} {a : α} :
a ∈ interior s ↔ s ∈ (nhds a).sets :=
by simp [interior_eq_nhds]
lemma is_open_iff_nhds {s : set α} : is_open s ↔ ∀a∈s, nhds a ≤ principal s :=
calc is_open s ↔ interior s = s : by rw [interior_eq_iff_open]
... ↔ s ⊆ interior s : ⟨assume h, by simp [*, subset.refl], subset.antisymm interior_subset⟩
... ↔ (∀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 :=
by simpa using @is_open_iff_nhds α _ _
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 [principal_univ])
(by simp)).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)⟩
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 simp [*, subset.refl], 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 simp [this],
have nhds a ⊓ principal (s ∩ t) ≠ ⊥,
from calc nhds a ⊓ principal (s ∩ t) = nhds a ⊓ (principal s ⊓ principal t) : by simp
... = 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 [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 [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; 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 $ by simp⟩
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, by simp at h; exact h 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 (by simp)) 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 (by simp)) (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 _⟩ (by simp),
by contradiction
lemma compact_iff_ultrafilter_le_nhds {s : set α} :
compact s ↔ (∀f, 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, 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 [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 [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, by simp; exact subset.refl s,
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 simp [ht₁], finite_insert _ finite_empty⟩ $
principal_mono.mpr $
show s - ⋃₀{t} ⊆ - t, begin simp; exact assume x ⟨_, hnt⟩, hnt end,
have is_closed (- t), from is_open_compl_iff.mp $ by simp; 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 ⟨∅, by simp, by simp, 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 simpa,
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 [f, hid, (hf ⟨_, hid⟩).2] using hxi⟩,
⟨f '' d,
assume i ⟨j, hj, h⟩,
h ▸ by simpa [f, hj] using (hf ⟨_, hj⟩).1,
finite_image f hd₂,
subset.trans hd₃ $ by simpa [subset_def]⟩
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 [not_and, 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 [closure_eq_nhds] at hx; exact hx t₂ ht₂ this,
have ∀x∈s, ∃t∈f.sets, x ∉ closure t, by simpa [_root_.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 [subset_def]) 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 (by simp at hfs; assumption) this,
have ∅ ∈ f.sets,
from mem_sets_of_superset this $ assume x ⟨hxs, hxi⟩,
let ⟨t, htc', hxt⟩ := (show ∃t ∈ c', x ∈ t, by simpa using hsc' hxs) in
have -closure (b ⟨t, htc'⟩) = t, from (hb _).right,
have x ∈ - t,
from this ▸ (calc x ∈ b ⟨t, htc'⟩ : by simp at hxi; have h := hxi t htc'; rwa [dif_pos htc'] at h
... ⊆ closure (b ⟨t, htc'⟩) : subset_closure
... ⊆ - - closure (b ⟨t, htc'⟩) : by simp; 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 $
by simpa [empty_in_sets_eq_bot] using 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, by simpa using hc₂) in
⟨{i}, by simp [hic], finite_singleton _, by simp [hai]⟩
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,
have compact s', from compact_bUnion_of_compact hs (λ_ _, compact_singleton),
e ▸ this
end compact
/- separation axioms -/
section separation
/-- A T₁ space, also known as a Fréchet space, is a topological space
where for every pair `x ≠ y`, there is an open set containing `x` and not `y`.
Equivalently, every singleton set is closed. -/
class t1_space (α : Type u) [topological_space α] :=
(t1 : ∀x, is_closed ({x} : set α))
lemma is_closed_singleton [t1_space α] {x : α} : is_closed ({x} : set α) :=
t1_space.t1 x
lemma compl_singleton_mem_nhds [t1_space α] {x y : α} (h : y ≠ x) : - {x} ∈ (nhds y).sets :=
mem_nhds_sets is_closed_singleton $ by simp; exact h
@[simp] lemma closure_singleton [topological_space α] [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 α] :=
(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 [topological_space α] [t2_space α] : t1_space α :=
⟨assume x,
have ∀y, y ≠ x ↔ ∃ (i : set α), (x ∉ i ∧ is_open i) ∧ y ∈ i,
from assume y, ⟨assume h',
let ⟨u, v, hu, hv, hy, hx, h⟩ := t2_separation h' in
have x ∉ u,
from assume : x ∈ u,
have x ∈ u ∩ v, from ⟨this, hx⟩,
by rwa [h] at this,
⟨u, ⟨this, hu⟩, hy⟩,
assume ⟨s, ⟨hx, hs⟩, hy⟩ h, hx $ h ▸ hy⟩,
have (-{x} : set α) = (⋃s∈{s : set α | x ∉ s ∧ is_open s}, s),
by apply set.ext; simpa,
show is_open (- {x}),
by rw [this]; exact (is_open_Union $ assume s, is_open_Union $ assume ⟨_, hs⟩, hs)⟩
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
@[simp] lemma nhds_eq_nhds_iff {a b : α} [t2_space α] : nhds a = nhds b ↔ a = b :=
⟨assume h, eq_of_nhds_neq_bot $ by simp [h], 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 simp [inf_of_le_left h], 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 t2_space α :=
(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 simp; exact ht₃,
subset.trans (compl_subset_comm.1 ht₂) h₁,
is_closed_compl_iff.mpr ht₁⟩
end regularity
/- 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)
... = _ : by simp },
case generate_open.sUnion : k hk' hk
{ exact λ ⟨t, htk, hat⟩, calc _ ≤ principal t : hk t htk hat
... ≤ _ : begin simp; exact subset_sUnion_of_mem htk end }
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, t ∈ (n a').sets) :
@nhds α (topological_space.mk_of_nhds n) a = n a :=
by letI := topological_space.mk_of_nhds n; from
(le_antisymm
(assume s hs, let ⟨t, ht, hst, h⟩ := h₁ hs in
have t ∈ (nhds a).sets, from mem_nhds_sets h (mem_pure_sets.1 $ h₀ a ht),
(nhds a).sets_of_superset this hst)
(assume s hs,
let ⟨t, hts, ht, hat⟩ := (@mem_nhds_sets_iff α (topological_space.mk_of_nhds n) _ _).1 hs in
(n a).sets_of_superset (ht _ hat) hts))
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
@[simp] lemma is_open_top {s : set α} : @is_open α ⊤ s := trivial
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 [is_open_iff_nhds]; 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, by simp; exact t.is_open_univ⟩,
is_open_inter := assume s₁ s₂ ⟨s'₁, hs₁, eq₁⟩ ⟨s'₂, hs₂, eq₂⟩,
⟨s'₁ ∩ s'₂, by simp [eq₁, eq₂]; exact t.is_open_inter _ _ hs₁ hs₂⟩,
is_open_sUnion := assume s h,
begin
simp [classical.skolem] at h,
cases h with f hf,
apply exists.intro (⋃(x : set α) (h : x ∈ s), f x h),
simp [sUnion_eq_bUnion, (λx h, (hf x h).right.symm)],
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_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, by simp; assumption, by simp [preimage_compl, heq.symm]⟩,
assume ⟨t, ht, heq⟩, ⟨-t, ht, by simp [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 simp; exact t.is_open_univ,
is_open_inter := assume s₁ s₂ h₁ h₂, by simp; 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) }
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 α) :=
⟨⊤⟩
lemma t2_space_top : @t2_space α ⊤ :=
{ t2 := assume x y hxy, ⟨{x}, {y}, trivial, trivial, mem_insert _ _, mem_insert _ _,
eq_empty_iff_forall_not_mem.2 $ by intros z hz; simp at hz; cc⟩ }
instance : topological_space empty := ⊤
instance : topological_space unit := ⊤
instance : topological_space bool := ⊤
instance : topological_space ℕ := ⊤
instance : topological_space ℤ := ⊤
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 [-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 },
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 [list.forall₂_and_left, flip] at ⊢ hv,
exact ⟨hv.1, hu.flip⟩ },
exact mem_traverse_sets _ _ (this.imp $ assume a s ⟨hs, ha⟩, mem_nhds_sets hs ha) } }
end
lemma quotient_dense_of_dense [setoid α] [topological_space α] {s : set α} (H : ∀ x, x ∈ closure s) :
closure (quotient.mk '' s) = univ :=
begin
ext x,
suffices : x ∈ closure (quotient.mk '' s), by simp [this],
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 [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 ⟨by tauto, 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⟩
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 [ie] using ne_empty_of_mem h⟩, ie⟩, h, subset.refl _⟩,
eq_univ_iff_forall.2 $ assume a, ⟨univ, ⟨∅, by simp; exact (@empty_ne_univ _ ⟨a⟩).symm⟩, 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}, by simp [this, hs]⟩))
(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⟩ $ by simp [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 [and_comm, and.left_comm] },
{ 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₁⟩, by simpa [(≥)] using hu₃⟩ },
{ suffices : a ∈ (⋃₀ b), { simpa [and_comm] },
{ rw [hb.2.1], trivial } }
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 {contextual:=tt}) (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]; simp [infi_subtype],
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₁ (by simp [countable_Union_Prop]),
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 [closure_eq_nhds, nhds_eq, infi_inf w],
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 at hs, split; apply inter_subset_inter_left; simp [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, by simp⟩⟩,
by simp [this]) ⟩⟩
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 ⟨B, cB, _, bB⟩ := is_open_generated_countable_inter α in
begin
let B' := {b ∈ B | ∃ s ∈ S, b ⊆ s},
rcases axiom_of_choice (λ b:B', b.2.2) with ⟨f, hf⟩,
change B' → set α at f,
haveI : encodable B' := (countable_subset (sep_subset _ _) cB).to_encodable,
have : range f ⊆ S := range_subset_iff.2 (λ x, (hf x).fst),
exact ⟨_, countable_range f, this,
subset.antisymm (sUnion_subset_sUnion this) $
sUnion_subset $ λ s hs x xs,
let ⟨b, hb, xb, bs⟩ := mem_basis_subset_of_mem_open bB xs (H _ hs) in
⟨_, ⟨⟨_, hb, _, hs, bs⟩, rfl⟩, (hf _).snd xb⟩⟩
end
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
|
da1ec4143d4d0d07c7f45729786fb6eb4263d5c3 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/computability/turing_machine.lean | ffc12b44718a7fef3c393e46adf9ae875cdd5f7b | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 109,861 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import algebra.order
import data.fintype.basic
import data.pfun
import tactic.apply_fun
import logic.function.iterate
/-!
# Turing machines
This file defines a sequence of simple machine languages, starting with Turing machines and working
up to more complex languages based on Wang B-machines.
## Naming conventions
Each model of computation in this file shares a naming convention for the elements of a model of
computation. These are the parameters for the language:
* `Γ` is the alphabet on the tape.
* `Λ` is the set of labels, or internal machine states.
* `σ` is the type of internal memory, not on the tape. This does not exist in the TM0 model, and
later models achieve this by mixing it into `Λ`.
* `K` is used in the TM2 model, which has multiple stacks, and denotes the number of such stacks.
All of these variables denote "essentially finite" types, but for technical reasons it is
convenient to allow them to be infinite anyway. When using an infinite type, we will be interested
to prove that only finitely many values of the type are ever interacted with.
Given these parameters, there are a few common structures for the model that arise:
* `stmt` is the set of all actions that can be performed in one step. For the TM0 model this set is
finite, and for later models it is an infinite inductive type representing "possible program
texts".
* `cfg` is the set of instantaneous configurations, that is, the state of the machine together with
its environment.
* `machine` is the set of all machines in the model. Usually this is approximately a function
`Λ → stmt`, although different models have different ways of halting and other actions.
* `step : cfg → option cfg` is the function that describes how the state evolves over one step.
If `step c = none`, then `c` is a terminal state, and the result of the computation is read off
from `c`. Because of the type of `step`, these models are all deterministic by construction.
* `init : input → cfg` sets up the initial state. The type `input` depends on the model;
in most cases it is `list Γ`.
* `eval : machine → input → roption output`, given a machine `M` and input `i`, starts from
`init i`, runs `step` until it reaches an output, and then applies a function `cfg → output` to
the final state to obtain the result. The type `output` depends on the model.
* `supports : machine → finset Λ → Prop` asserts that a machine `M` starts in `S : finset Λ`, and
can only ever jump to other states inside `S`. This implies that the behavior of `M` on any input
cannot depend on its values outside `S`. We use this to allow `Λ` to be an infinite set when
convenient, and prove that only finitely many of these states are actually accessible. This
formalizes "essentially finite" mentioned above.
-/
open relation
open nat (iterate)
open function (update iterate_succ iterate_succ_apply iterate_succ'
iterate_succ_apply' iterate_zero_apply)
namespace turing
/-- The `blank_extends` partial order holds of `l₁` and `l₂` if `l₂` is obtained by adding
blanks (`default Γ`) to the end of `l₁`. -/
def blank_extends {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : Prop :=
∃ n, l₂ = l₁ ++ list.repeat (default Γ) n
@[refl] theorem blank_extends.refl {Γ} [inhabited Γ] (l : list Γ) : blank_extends l l := ⟨0, by simp⟩
@[trans] theorem blank_extends.trans {Γ} [inhabited Γ] {l₁ l₂ l₃ : list Γ} :
blank_extends l₁ l₂ → blank_extends l₂ l₃ → blank_extends l₁ l₃ :=
by rintro ⟨i, rfl⟩ ⟨j, rfl⟩; exact ⟨i+j, by simp [list.repeat_add]⟩
theorem blank_extends.below_of_le {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} :
blank_extends l l₁ → blank_extends l l₂ →
l₁.length ≤ l₂.length → blank_extends l₁ l₂ :=
begin
rintro ⟨i, rfl⟩ ⟨j, rfl⟩ h, use j - i,
simp only [list.length_append, add_le_add_iff_left, list.length_repeat] at h,
simp only [← list.repeat_add, nat.add_sub_cancel' h, list.append_assoc],
end
/-- Any two extensions by blank `l₁,l₂` of `l` have a common join (which can be taken to be the
longer of `l₁` and `l₂`). -/
def blank_extends.above {Γ} [inhabited Γ] {l l₁ l₂ : list Γ}
(h₁ : blank_extends l l₁) (h₂ : blank_extends l l₂) :
{l' // blank_extends l₁ l' ∧ blank_extends l₂ l'} :=
if h : l₁.length ≤ l₂.length then
⟨l₂, h₁.below_of_le h₂ h, blank_extends.refl _⟩
else
⟨l₁, blank_extends.refl _, h₂.below_of_le h₁ (le_of_not_ge h)⟩
theorem blank_extends.above_of_le {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} :
blank_extends l₁ l → blank_extends l₂ l →
l₁.length ≤ l₂.length → blank_extends l₁ l₂ :=
begin
rintro ⟨i, rfl⟩ ⟨j, e⟩ h, use i - j,
refine list.append_right_cancel (e.symm.trans _),
rw [list.append_assoc, ← list.repeat_add, nat.sub_add_cancel],
apply_fun list.length at e,
simp only [list.length_append, list.length_repeat] at e,
rwa [ge, ← add_le_add_iff_left, e, add_le_add_iff_right]
end
/-- `blank_rel` is the symmetric closure of `blank_extends`, turning it into an equivalence
relation. Two lists are related by `blank_rel` if one extends the other by blanks. -/
def blank_rel {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : Prop :=
blank_extends l₁ l₂ ∨ blank_extends l₂ l₁
@[refl] theorem blank_rel.refl {Γ} [inhabited Γ] (l : list Γ) : blank_rel l l :=
or.inl (blank_extends.refl _)
@[symm] theorem blank_rel.symm {Γ} [inhabited Γ] {l₁ l₂ : list Γ} :
blank_rel l₁ l₂ → blank_rel l₂ l₁ := or.symm
@[trans] theorem blank_rel.trans {Γ} [inhabited Γ] {l₁ l₂ l₃ : list Γ} :
blank_rel l₁ l₂ → blank_rel l₂ l₃ → blank_rel l₁ l₃ :=
begin
rintro (h₁|h₁) (h₂|h₂),
{ exact or.inl (h₁.trans h₂) },
{ cases le_total l₁.length l₃.length with h h,
{ exact or.inl (h₁.above_of_le h₂ h) },
{ exact or.inr (h₂.above_of_le h₁ h) } },
{ cases le_total l₁.length l₃.length with h h,
{ exact or.inl (h₁.below_of_le h₂ h) },
{ exact or.inr (h₂.below_of_le h₁ h) } },
{ exact or.inr (h₂.trans h₁) },
end
/-- Given two `blank_rel` lists, there exists (constructively) a common join. -/
def blank_rel.above {Γ} [inhabited Γ] {l₁ l₂ : list Γ} (h : blank_rel l₁ l₂) :
{l // blank_extends l₁ l ∧ blank_extends l₂ l} :=
begin
refine if hl : l₁.length ≤ l₂.length
then ⟨l₂, or.elim h id (λ h', _), blank_extends.refl _⟩
else ⟨l₁, blank_extends.refl _, or.elim h (λ h', _) id⟩,
exact (blank_extends.refl _).above_of_le h' hl,
exact (blank_extends.refl _).above_of_le h' (le_of_not_ge hl)
end
/-- Given two `blank_rel` lists, there exists (constructively) a common meet. -/
def blank_rel.below {Γ} [inhabited Γ] {l₁ l₂ : list Γ} (h : blank_rel l₁ l₂) :
{l // blank_extends l l₁ ∧ blank_extends l l₂} :=
begin
refine if hl : l₁.length ≤ l₂.length
then ⟨l₁, blank_extends.refl _, or.elim h id (λ h', _)⟩
else ⟨l₂, or.elim h (λ h', _) id, blank_extends.refl _⟩,
exact (blank_extends.refl _).above_of_le h' hl,
exact (blank_extends.refl _).above_of_le h' (le_of_not_ge hl)
end
theorem blank_rel.equivalence (Γ) [inhabited Γ] : equivalence (@blank_rel Γ _) :=
⟨blank_rel.refl, @blank_rel.symm _ _, @blank_rel.trans _ _⟩
/-- Construct a setoid instance for `blank_rel`. -/
def blank_rel.setoid (Γ) [inhabited Γ] : setoid (list Γ) := ⟨_, blank_rel.equivalence _⟩
/-- A `list_blank Γ` is a quotient of `list Γ` by extension by blanks at the end. This is used to
represent half-tapes of a Turing machine, so that we can pretend that the list continues
infinitely with blanks. -/
def list_blank (Γ) [inhabited Γ] := quotient (blank_rel.setoid Γ)
instance list_blank.inhabited {Γ} [inhabited Γ] : inhabited (list_blank Γ) := ⟨quotient.mk' []⟩
instance list_blank.has_emptyc {Γ} [inhabited Γ] : has_emptyc (list_blank Γ) := ⟨quotient.mk' []⟩
/-- A modified version of `quotient.lift_on'` specialized for `list_blank`, with the stronger
precondition `blank_extends` instead of `blank_rel`. -/
@[elab_as_eliminator, reducible]
protected def list_blank.lift_on {Γ} [inhabited Γ] {α} (l : list_blank Γ) (f : list Γ → α)
(H : ∀ a b, blank_extends a b → f a = f b) : α :=
l.lift_on' f $ by rintro a b (h|h); [exact H _ _ h, exact (H _ _ h).symm]
/-- The quotient map turning a `list` into a `list_blank`. -/
def list_blank.mk {Γ} [inhabited Γ] : list Γ → list_blank Γ := quotient.mk'
@[elab_as_eliminator]
protected lemma list_blank.induction_on {Γ} [inhabited Γ]
{p : list_blank Γ → Prop} (q : list_blank Γ)
(h : ∀ a, p (list_blank.mk a)) : p q := quotient.induction_on' q h
/-- The head of a `list_blank` is well defined. -/
def list_blank.head {Γ} [inhabited Γ] (l : list_blank Γ) : Γ :=
l.lift_on list.head begin
rintro _ _ ⟨i, rfl⟩,
cases a, {cases i; refl}, refl
end
@[simp] theorem list_blank.head_mk {Γ} [inhabited Γ] (l : list Γ) :
list_blank.head (list_blank.mk l) = l.head := rfl
/-- The tail of a `list_blank` is well defined (up to the tail of blanks). -/
def list_blank.tail {Γ} [inhabited Γ] (l : list_blank Γ) : list_blank Γ :=
l.lift_on (λ l, list_blank.mk l.tail) begin
rintro _ _ ⟨i, rfl⟩,
refine quotient.sound' (or.inl _),
cases a; [{cases i; [exact ⟨0, rfl⟩, exact ⟨i, rfl⟩]}, exact ⟨i, rfl⟩]
end
@[simp] theorem list_blank.tail_mk {Γ} [inhabited Γ] (l : list Γ) :
list_blank.tail (list_blank.mk l) = list_blank.mk l.tail := rfl
/-- We can cons an element onto a `list_blank`. -/
def list_blank.cons {Γ} [inhabited Γ] (a : Γ) (l : list_blank Γ) : list_blank Γ :=
l.lift_on (λ l, list_blank.mk (list.cons a l)) begin
rintro _ _ ⟨i, rfl⟩,
exact quotient.sound' (or.inl ⟨i, rfl⟩),
end
@[simp] theorem list_blank.cons_mk {Γ} [inhabited Γ] (a : Γ) (l : list Γ) :
list_blank.cons a (list_blank.mk l) = list_blank.mk (a :: l) := rfl
@[simp] theorem list_blank.head_cons {Γ} [inhabited Γ] (a : Γ) :
∀ (l : list_blank Γ), (l.cons a).head = a :=
quotient.ind' $ by exact λ l, rfl
@[simp] theorem list_blank.tail_cons {Γ} [inhabited Γ] (a : Γ) :
∀ (l : list_blank Γ), (l.cons a).tail = l :=
quotient.ind' $ by exact λ l, rfl
/-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `list` where
this only holds for nonempty lists. -/
@[simp] theorem list_blank.cons_head_tail {Γ} [inhabited Γ] :
∀ (l : list_blank Γ), l.tail.cons l.head = l :=
quotient.ind' begin
refine (λ l, quotient.sound' (or.inr _)),
cases l, {exact ⟨1, rfl⟩}, {refl},
end
/-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `list` where
this only holds for nonempty lists. -/
theorem list_blank.exists_cons {Γ} [inhabited Γ] (l : list_blank Γ) :
∃ a l', l = list_blank.cons a l' :=
⟨_, _, (list_blank.cons_head_tail _).symm⟩
/-- The n-th element of a `list_blank` is well defined for all `n : ℕ`, unlike in a `list`. -/
def list_blank.nth {Γ} [inhabited Γ] (l : list_blank Γ) (n : ℕ) : Γ :=
l.lift_on (λ l, list.inth l n) begin
rintro l _ ⟨i, rfl⟩,
simp only [list.inth],
cases lt_or_le _ _ with h h, {rw list.nth_append h},
rw list.nth_len_le h,
cases le_or_lt _ _ with h₂ h₂, {rw list.nth_len_le h₂},
rw [list.nth_le_nth h₂, list.nth_le_append_right h, list.nth_le_repeat]
end
@[simp] theorem list_blank.nth_mk {Γ} [inhabited Γ] (l : list Γ) (n : ℕ) :
(list_blank.mk l).nth n = l.inth n := rfl
@[simp] theorem list_blank.nth_zero {Γ} [inhabited Γ] (l : list_blank Γ) : l.nth 0 = l.head :=
begin
conv {to_lhs, rw [← list_blank.cons_head_tail l]},
exact quotient.induction_on' l.tail (λ l, rfl)
end
@[simp] theorem list_blank.nth_succ {Γ} [inhabited Γ] (l : list_blank Γ) (n : ℕ) :
l.nth (n + 1) = l.tail.nth n :=
begin
conv {to_lhs, rw [← list_blank.cons_head_tail l]},
exact quotient.induction_on' l.tail (λ l, rfl)
end
@[ext] theorem list_blank.ext {Γ} [inhabited Γ] {L₁ L₂ : list_blank Γ} :
(∀ i, L₁.nth i = L₂.nth i) → L₁ = L₂ :=
list_blank.induction_on L₁ $ λ l₁, list_blank.induction_on L₂ $ λ l₂ H,
begin
wlog h : l₁.length ≤ l₂.length using l₁ l₂,
swap, { exact (this $ λ i, (H i).symm).symm },
refine quotient.sound' (or.inl ⟨l₂.length - l₁.length, _⟩),
refine list.ext_le _ (λ i h h₂, eq.symm _),
{ simp only [nat.add_sub_of_le h, list.length_append, list.length_repeat] },
simp at H,
cases lt_or_le i l₁.length with h' h',
{ simpa only [list.nth_le_append _ h',
list.nth_le_nth h, list.nth_le_nth h', option.iget] using H i },
{ simpa only [list.nth_le_append_right h', list.nth_le_repeat,
list.nth_le_nth h, list.nth_len_le h', option.iget] using H i },
end
/-- Apply a function to a value stored at the nth position of the list. -/
@[simp] def list_blank.modify_nth {Γ} [inhabited Γ] (f : Γ → Γ) : ℕ → list_blank Γ → list_blank Γ
| 0 L := L.tail.cons (f L.head)
| (n+1) L := (L.tail.modify_nth n).cons L.head
theorem list_blank.nth_modify_nth {Γ} [inhabited Γ] (f : Γ → Γ) (n i) (L : list_blank Γ) :
(L.modify_nth f n).nth i = if i = n then f (L.nth i) else L.nth i :=
begin
induction n with n IH generalizing i L,
{ cases i; simp only [list_blank.nth_zero, if_true,
list_blank.head_cons, list_blank.modify_nth, eq_self_iff_true,
list_blank.nth_succ, if_false, list_blank.tail_cons] },
{ cases i,
{ rw if_neg (nat.succ_ne_zero _).symm,
simp only [list_blank.nth_zero, list_blank.head_cons, list_blank.modify_nth] },
{ simp only [IH, list_blank.modify_nth, list_blank.nth_succ, list_blank.tail_cons],
congr } }
end
/-- A pointed map of `inhabited` types is a map that sends one default value to the other. -/
structure {u v} pointed_map (Γ : Type u) (Γ' : Type v)
[inhabited Γ] [inhabited Γ'] : Type (max u v) :=
(f : Γ → Γ') (map_pt' : f (default _) = default _)
instance {Γ Γ'} [inhabited Γ] [inhabited Γ'] : inhabited (pointed_map Γ Γ') :=
⟨⟨λ _, default _, rfl⟩⟩
instance {Γ Γ'} [inhabited Γ] [inhabited Γ'] : has_coe_to_fun (pointed_map Γ Γ') :=
⟨_, pointed_map.f⟩
@[simp] theorem pointed_map.mk_val {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : Γ → Γ') (pt) : (pointed_map.mk f pt : Γ → Γ') = f := rfl
@[simp] theorem pointed_map.map_pt {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') : f (default _) = default _ := pointed_map.map_pt' _
@[simp] theorem pointed_map.head_map {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') (l : list Γ) : (l.map f).head = f l.head :=
by cases l; [exact (pointed_map.map_pt f).symm, refl]
/-- The `map` function on lists is well defined on `list_blank`s provided that the map is
pointed. -/
def list_blank.map {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') (l : list_blank Γ) : list_blank Γ' :=
l.lift_on (λ l, list_blank.mk (list.map f l)) begin
rintro l _ ⟨i, rfl⟩, refine quotient.sound' (or.inl ⟨i, _⟩),
simp only [pointed_map.map_pt, list.map_append, list.map_repeat],
end
@[simp] theorem list_blank.map_mk {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') (l : list Γ) : (list_blank.mk l).map f = list_blank.mk (l.map f) := rfl
@[simp] theorem list_blank.head_map {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') (l : list_blank Γ) : (l.map f).head = f l.head :=
begin
conv {to_lhs, rw [← list_blank.cons_head_tail l]},
exact quotient.induction_on' l (λ a, rfl)
end
@[simp] theorem list_blank.tail_map {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') (l : list_blank Γ) : (l.map f).tail = l.tail.map f :=
begin
conv {to_lhs, rw [← list_blank.cons_head_tail l]},
exact quotient.induction_on' l (λ a, rfl)
end
@[simp] theorem list_blank.map_cons {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') (l : list_blank Γ) (a : Γ) : (l.cons a).map f = (l.map f).cons (f a) :=
begin
refine (list_blank.cons_head_tail _).symm.trans _,
simp only [list_blank.head_map, list_blank.head_cons, list_blank.tail_map, list_blank.tail_cons]
end
@[simp] theorem list_blank.nth_map {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') (l : list_blank Γ) (n : ℕ) : (l.map f).nth n = f (l.nth n) :=
l.induction_on begin
intro l, simp only [list.nth_map, list_blank.map_mk, list_blank.nth_mk, list.inth],
cases l.nth n, {exact f.2.symm}, {refl}
end
/-- The `i`-th projection as a pointed map. -/
def proj {ι : Type*} {Γ : ι → Type*} [∀ i, inhabited (Γ i)] (i : ι) :
pointed_map (∀ i, Γ i) (Γ i) := ⟨λ a, a i, rfl⟩
theorem proj_map_nth {ι : Type*} {Γ : ι → Type*} [∀ i, inhabited (Γ i)] (i : ι)
(L n) : (list_blank.map (@proj ι Γ _ i) L).nth n = L.nth n i :=
by rw list_blank.nth_map; refl
theorem list_blank.map_modify_nth {Γ Γ'} [inhabited Γ] [inhabited Γ']
(F : pointed_map Γ Γ') (f : Γ → Γ) (f' : Γ' → Γ')
(H : ∀ x, F (f x) = f' (F x)) (n) (L : list_blank Γ) :
(L.modify_nth f n).map F = (L.map F).modify_nth f' n :=
by induction n with n IH generalizing L; simp only [*,
list_blank.head_map, list_blank.modify_nth, list_blank.map_cons, list_blank.tail_map]
/-- Append a list on the left side of a list_blank. -/
@[simp] def list_blank.append {Γ} [inhabited Γ] : list Γ → list_blank Γ → list_blank Γ
| [] L := L
| (a :: l) L := list_blank.cons a (list_blank.append l L)
@[simp] theorem list_blank.append_mk {Γ} [inhabited Γ] (l₁ l₂ : list Γ) :
list_blank.append l₁ (list_blank.mk l₂) = list_blank.mk (l₁ ++ l₂) :=
by induction l₁; simp only [*,
list_blank.append, list.nil_append, list.cons_append, list_blank.cons_mk]
theorem list_blank.append_assoc {Γ} [inhabited Γ] (l₁ l₂ : list Γ) (l₃ : list_blank Γ) :
list_blank.append (l₁ ++ l₂) l₃ = list_blank.append l₁ (list_blank.append l₂ l₃) :=
l₃.induction_on $ by intro; simp only [list_blank.append_mk, list.append_assoc]
/-- The `bind` function on lists is well defined on `list_blank`s provided that the default element
is sent to a sequence of default elements. -/
def list_blank.bind {Γ Γ'} [inhabited Γ] [inhabited Γ']
(l : list_blank Γ) (f : Γ → list Γ')
(hf : ∃ n, f (default _) = list.repeat (default _) n) : list_blank Γ' :=
l.lift_on (λ l, list_blank.mk (list.bind l f)) begin
rintro l _ ⟨i, rfl⟩, cases hf with n e, refine quotient.sound' (or.inl ⟨i * n, _⟩),
rw [list.bind_append, mul_comm], congr,
induction i with i IH, refl,
simp only [IH, e, list.repeat_add, nat.mul_succ, add_comm, list.repeat_succ, list.cons_bind],
end
@[simp] lemma list_blank.bind_mk {Γ Γ'} [inhabited Γ] [inhabited Γ']
(l : list Γ) (f : Γ → list Γ') (hf) :
(list_blank.mk l).bind f hf = list_blank.mk (l.bind f) := rfl
@[simp] lemma list_blank.cons_bind {Γ Γ'} [inhabited Γ] [inhabited Γ']
(a : Γ) (l : list_blank Γ) (f : Γ → list Γ') (hf) :
(l.cons a).bind f hf = (l.bind f hf).append (f a) :=
l.induction_on $ by intro; simp only [list_blank.append_mk,
list_blank.bind_mk, list_blank.cons_mk, list.cons_bind]
/-- The tape of a Turing machine is composed of a head element (which we imagine to be the
current position of the head), together with two `list_blank`s denoting the portions of the tape
going off to the left and right. When the Turing machine moves right, an element is pulled from the
right side and becomes the new head, while the head element is consed onto the left side. -/
structure tape (Γ : Type*) [inhabited Γ] :=
(head : Γ)
(left : list_blank Γ)
(right : list_blank Γ)
instance tape.inhabited {Γ} [inhabited Γ] : inhabited (tape Γ) :=
⟨by constructor; apply default⟩
/-- A direction for the turing machine `move` command, either
left or right. -/
@[derive decidable_eq, derive inhabited]
inductive dir | left | right
/-- The "inclusive" left side of the tape, including both `left` and `head`. -/
def tape.left₀ {Γ} [inhabited Γ] (T : tape Γ) : list_blank Γ := T.left.cons T.head
/-- The "inclusive" right side of the tape, including both `right` and `head`. -/
def tape.right₀ {Γ} [inhabited Γ] (T : tape Γ) : list_blank Γ := T.right.cons T.head
/-- Move the tape in response to a motion of the Turing machine. Note that `T.move dir.left` makes
`T.left` smaller; the Turing machine is moving left and the tape is moving right. -/
def tape.move {Γ} [inhabited Γ] : dir → tape Γ → tape Γ
| dir.left ⟨a, L, R⟩ := ⟨L.head, L.tail, R.cons a⟩
| dir.right ⟨a, L, R⟩ := ⟨R.head, L.cons a, R.tail⟩
@[simp] theorem tape.move_left_right {Γ} [inhabited Γ] (T : tape Γ) :
(T.move dir.left).move dir.right = T :=
by cases T; simp [tape.move]
@[simp] theorem tape.move_right_left {Γ} [inhabited Γ] (T : tape Γ) :
(T.move dir.right).move dir.left = T :=
by cases T; simp [tape.move]
/-- Construct a tape from a left side and an inclusive right side. -/
def tape.mk' {Γ} [inhabited Γ] (L R : list_blank Γ) : tape Γ := ⟨R.head, L, R.tail⟩
@[simp] theorem tape.mk'_left {Γ} [inhabited Γ] (L R : list_blank Γ) :
(tape.mk' L R).left = L := rfl
@[simp] theorem tape.mk'_head {Γ} [inhabited Γ] (L R : list_blank Γ) :
(tape.mk' L R).head = R.head := rfl
@[simp] theorem tape.mk'_right {Γ} [inhabited Γ] (L R : list_blank Γ) :
(tape.mk' L R).right = R.tail := rfl
@[simp] theorem tape.mk'_right₀ {Γ} [inhabited Γ] (L R : list_blank Γ) :
(tape.mk' L R).right₀ = R := list_blank.cons_head_tail _
@[simp] theorem tape.mk'_left_right₀ {Γ} [inhabited Γ] (T : tape Γ) :
tape.mk' T.left T.right₀ = T :=
by cases T; simp only [tape.right₀, tape.mk',
list_blank.head_cons, list_blank.tail_cons, eq_self_iff_true, and_self]
theorem tape.exists_mk' {Γ} [inhabited Γ] (T : tape Γ) :
∃ L R, T = tape.mk' L R := ⟨_, _, (tape.mk'_left_right₀ _).symm⟩
@[simp] theorem tape.move_left_mk' {Γ} [inhabited Γ] (L R : list_blank Γ) :
(tape.mk' L R).move dir.left = tape.mk' L.tail (R.cons L.head) :=
by simp only [tape.move, tape.mk', list_blank.head_cons, eq_self_iff_true,
list_blank.cons_head_tail, and_self, list_blank.tail_cons]
@[simp] theorem tape.move_right_mk' {Γ} [inhabited Γ] (L R : list_blank Γ) :
(tape.mk' L R).move dir.right = tape.mk' (L.cons R.head) R.tail :=
by simp only [tape.move, tape.mk', list_blank.head_cons, eq_self_iff_true,
list_blank.cons_head_tail, and_self, list_blank.tail_cons]
/-- Construct a tape from a left side and an inclusive right side. -/
def tape.mk₂ {Γ} [inhabited Γ] (L R : list Γ) : tape Γ :=
tape.mk' (list_blank.mk L) (list_blank.mk R)
/-- Construct a tape from a list, with the head of the list at the TM head and the rest going
to the right. -/
def tape.mk₁ {Γ} [inhabited Γ] (l : list Γ) : tape Γ :=
tape.mk₂ [] l
/-- The `nth` function of a tape is integer-valued, with index `0` being the head, negative indexes
on the left and positive indexes on the right. (Picture a number line.) -/
def tape.nth {Γ} [inhabited Γ] (T : tape Γ) : ℤ → Γ
| 0 := T.head
| (n+1:ℕ) := T.right.nth n
| -[1+ n] := T.left.nth n
@[simp] theorem tape.nth_zero {Γ} [inhabited Γ] (T : tape Γ) : T.nth 0 = T.1 := rfl
theorem tape.right₀_nth {Γ} [inhabited Γ] (T : tape Γ) (n : ℕ) : T.right₀.nth n = T.nth n :=
by cases n; simp only [tape.nth, tape.right₀, int.coe_nat_zero,
list_blank.nth_zero, list_blank.nth_succ, list_blank.head_cons, list_blank.tail_cons]
@[simp] theorem tape.mk'_nth_nat {Γ} [inhabited Γ] (L R : list_blank Γ) (n : ℕ) :
(tape.mk' L R).nth n = R.nth n :=
by rw [← tape.right₀_nth, tape.mk'_right₀]
@[simp] theorem tape.move_left_nth {Γ} [inhabited Γ] :
∀ (T : tape Γ) (i : ℤ), (T.move dir.left).nth i = T.nth (i-1)
| ⟨a, L, R⟩ -[1+ n] := (list_blank.nth_succ _ _).symm
| ⟨a, L, R⟩ 0 := (list_blank.nth_zero _).symm
| ⟨a, L, R⟩ 1 := (list_blank.nth_zero _).trans (list_blank.head_cons _ _)
| ⟨a, L, R⟩ ((n+1:ℕ)+1) := begin
rw add_sub_cancel,
change (R.cons a).nth (n+1) = R.nth n,
rw [list_blank.nth_succ, list_blank.tail_cons]
end
@[simp] theorem tape.move_right_nth {Γ} [inhabited Γ] (T : tape Γ) (i : ℤ) :
(T.move dir.right).nth i = T.nth (i+1) :=
by conv {to_rhs, rw ← T.move_right_left}; rw [tape.move_left_nth, add_sub_cancel]
@[simp] theorem tape.move_right_n_head {Γ} [inhabited Γ] (T : tape Γ) (i : ℕ) :
((tape.move dir.right)^[i] T).head = T.nth i :=
by induction i generalizing T; [refl, simp only [*,
tape.move_right_nth, int.coe_nat_succ, iterate_succ]]
/-- Replace the current value of the head on the tape. -/
def tape.write {Γ} [inhabited Γ] (b : Γ) (T : tape Γ) : tape Γ := {head := b, ..T}
@[simp] theorem tape.write_self {Γ} [inhabited Γ] : ∀ (T : tape Γ), T.write T.1 = T :=
by rintro ⟨⟩; refl
@[simp] theorem tape.write_nth {Γ} [inhabited Γ] (b : Γ) :
∀ (T : tape Γ) {i : ℤ}, (T.write b).nth i = if i = 0 then b else T.nth i
| ⟨a, L, R⟩ 0 := rfl
| ⟨a, L, R⟩ (n+1:ℕ) := rfl
| ⟨a, L, R⟩ -[1+ n] := rfl
@[simp] theorem tape.write_mk' {Γ} [inhabited Γ] (a b : Γ) (L R : list_blank Γ) :
(tape.mk' L (R.cons a)).write b = tape.mk' L (R.cons b) :=
by simp only [tape.write, tape.mk', list_blank.head_cons, list_blank.tail_cons,
eq_self_iff_true, and_self]
/-- Apply a pointed map to a tape to change the alphabet. -/
def tape.map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (T : tape Γ) : tape Γ' :=
⟨f T.1, T.2.map f, T.3.map f⟩
@[simp] theorem tape.map_fst {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') : ∀ (T : tape Γ), (T.map f).1 = f T.1 :=
by rintro ⟨⟩; refl
@[simp] theorem tape.map_write {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (b : Γ) :
∀ (T : tape Γ), (T.write b).map f = (T.map f).write (f b) :=
by rintro ⟨⟩; refl
@[simp] theorem tape.write_move_right_n {Γ} [inhabited Γ] (f : Γ → Γ) (L R : list_blank Γ) (n : ℕ) :
((tape.move dir.right)^[n] (tape.mk' L R)).write (f (R.nth n)) =
((tape.move dir.right)^[n] (tape.mk' L (R.modify_nth f n))) :=
begin
induction n with n IH generalizing L R,
{ simp only [list_blank.nth_zero, list_blank.modify_nth, iterate_zero_apply],
rw [← tape.write_mk', list_blank.cons_head_tail] },
simp only [list_blank.head_cons, list_blank.nth_succ, list_blank.modify_nth,
tape.move_right_mk', list_blank.tail_cons, iterate_succ_apply, IH]
end
theorem tape.map_move {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') (T : tape Γ) (d) : (T.move d).map f = (T.map f).move d :=
by cases T; cases d; simp only [tape.move, tape.map,
list_blank.head_map, eq_self_iff_true, list_blank.map_cons, and_self, list_blank.tail_map]
theorem tape.map_mk' {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ')
(L R : list_blank Γ) : (tape.mk' L R).map f = tape.mk' (L.map f) (R.map f) :=
by simp only [tape.mk', tape.map, list_blank.head_map,
eq_self_iff_true, and_self, list_blank.tail_map]
theorem tape.map_mk₂ {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ')
(L R : list Γ) : (tape.mk₂ L R).map f = tape.mk₂ (L.map f) (R.map f) :=
by simp only [tape.mk₂, tape.map_mk', list_blank.map_mk]
theorem tape.map_mk₁ {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ')
(l : list Γ) : (tape.mk₁ l).map f = tape.mk₁ (l.map f) := tape.map_mk₂ _ _ _
/-- Run a state transition function `σ → option σ` "to completion". The return value is the last
state returned before a `none` result. If the state transition function always returns `some`,
then the computation diverges, returning `roption.none`. -/
def eval {σ} (f : σ → option σ) : σ → roption σ :=
pfun.fix (λ s, roption.some $ (f s).elim (sum.inl s) sum.inr)
/-- The reflexive transitive closure of a state transition function. `reaches f a b` means
there is a finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`.
This relation permits zero steps of the state transition function. -/
def reaches {σ} (f : σ → option σ) : σ → σ → Prop :=
refl_trans_gen (λ a b, b ∈ f a)
/-- The transitive closure of a state transition function. `reaches₁ f a b` means there is a
nonempty finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`.
This relation does not permit zero steps of the state transition function. -/
def reaches₁ {σ} (f : σ → option σ) : σ → σ → Prop :=
trans_gen (λ a b, b ∈ f a)
theorem reaches₁_eq {σ} {f : σ → option σ} {a b c}
(h : f a = f b) : reaches₁ f a c ↔ reaches₁ f b c :=
trans_gen.head'_iff.trans (trans_gen.head'_iff.trans $ by rw h).symm
theorem reaches_total {σ} {f : σ → option σ}
{a b c} : reaches f a b → reaches f a c →
reaches f b c ∨ reaches f c b :=
refl_trans_gen.total_of_right_unique $ λ _ _ _, option.mem_unique
theorem reaches₁_fwd {σ} {f : σ → option σ}
{a b c} (h₁ : reaches₁ f a c) (h₂ : b ∈ f a) : reaches f b c :=
begin
rcases trans_gen.head'_iff.1 h₁ with ⟨b', hab, hbc⟩,
cases option.mem_unique hab h₂, exact hbc
end
/-- A variation on `reaches`. `reaches₀ f a b` holds if whenever `reaches₁ f b c` then
`reaches₁ f a c`. This is a weaker property than `reaches` and is useful for replacing states with
equivalent states without taking a step. -/
def reaches₀ {σ} (f : σ → option σ) (a b : σ) : Prop :=
∀ c, reaches₁ f b c → reaches₁ f a c
theorem reaches₀.trans {σ} {f : σ → option σ} {a b c : σ}
(h₁ : reaches₀ f a b) (h₂ : reaches₀ f b c) : reaches₀ f a c
| d h₃ := h₁ _ (h₂ _ h₃)
@[refl] theorem reaches₀.refl {σ} {f : σ → option σ} (a : σ) : reaches₀ f a a
| b h := h
theorem reaches₀.single {σ} {f : σ → option σ} {a b : σ}
(h : b ∈ f a) : reaches₀ f a b
| c h₂ := h₂.head h
theorem reaches₀.head {σ} {f : σ → option σ} {a b c : σ}
(h : b ∈ f a) (h₂ : reaches₀ f b c) : reaches₀ f a c :=
(reaches₀.single h).trans h₂
theorem reaches₀.tail {σ} {f : σ → option σ} {a b c : σ}
(h₁ : reaches₀ f a b) (h : c ∈ f b) : reaches₀ f a c :=
h₁.trans (reaches₀.single h)
theorem reaches₀_eq {σ} {f : σ → option σ} {a b}
(e : f a = f b) : reaches₀ f a b
| d h := (reaches₁_eq e).2 h
theorem reaches₁.to₀ {σ} {f : σ → option σ} {a b : σ}
(h : reaches₁ f a b) : reaches₀ f a b
| c h₂ := h.trans h₂
theorem reaches.to₀ {σ} {f : σ → option σ} {a b : σ}
(h : reaches f a b) : reaches₀ f a b
| c h₂ := h₂.trans_right h
theorem reaches₀.tail' {σ} {f : σ → option σ} {a b c : σ}
(h : reaches₀ f a b) (h₂ : c ∈ f b) : reaches₁ f a c :=
h _ (trans_gen.single h₂)
/-- (co-)Induction principle for `eval`. If a property `C` holds of any point `a` evaluating to `b`
which is either terminal (meaning `a = b`) or where the next point also satisfies `C`, then it
holds of any point where `eval f a` evaluates to `b`. This formalizes the notion that if
`eval f a` evaluates to `b` then it reaches terminal state `b` in finitely many steps. -/
@[elab_as_eliminator] def eval_induction {σ}
{f : σ → option σ} {b : σ} {C : σ → Sort*} {a : σ} (h : b ∈ eval f a)
(H : ∀ a, b ∈ eval f a →
(∀ a', b ∈ eval f a' → f a = some a' → C a') → C a) : C a :=
pfun.fix_induction h (λ a' ha' h', H _ ha' $ λ b' hb' e, h' _ hb' $
roption.mem_some_iff.2 $ by rw e; refl)
theorem mem_eval {σ} {f : σ → option σ} {a b} :
b ∈ eval f a ↔ reaches f a b ∧ f b = none :=
⟨λ h, begin
refine eval_induction h (λ a h IH, _),
cases e : f a with a',
{ rw roption.mem_unique h (pfun.mem_fix_iff.2 $ or.inl $
roption.mem_some_iff.2 $ by rw e; refl),
exact ⟨refl_trans_gen.refl, e⟩ },
{ rcases pfun.mem_fix_iff.1 h with h | ⟨_, h, h'⟩;
rw e at h; cases roption.mem_some_iff.1 h,
cases IH a' h' (by rwa e) with h₁ h₂,
exact ⟨refl_trans_gen.head e h₁, h₂⟩ }
end, λ ⟨h₁, h₂⟩, begin
refine refl_trans_gen.head_induction_on h₁ _ (λ a a' h _ IH, _),
{ refine pfun.mem_fix_iff.2 (or.inl _),
rw h₂, apply roption.mem_some },
{ refine pfun.mem_fix_iff.2 (or.inr ⟨_, _, IH⟩),
rw show f a = _, from h,
apply roption.mem_some }
end⟩
theorem eval_maximal₁ {σ} {f : σ → option σ} {a b}
(h : b ∈ eval f a) (c) : ¬ reaches₁ f b c | bc :=
let ⟨ab, b0⟩ := mem_eval.1 h, ⟨b', h', _⟩ := trans_gen.head'_iff.1 bc in
by cases b0.symm.trans h'
theorem eval_maximal {σ} {f : σ → option σ} {a b}
(h : b ∈ eval f a) {c} : reaches f b c ↔ c = b :=
let ⟨ab, b0⟩ := mem_eval.1 h in
refl_trans_gen_iff_eq $ λ b' h', by cases b0.symm.trans h'
theorem reaches_eval {σ} {f : σ → option σ} {a b}
(ab : reaches f a b) : eval f a = eval f b :=
roption.ext $ λ c,
⟨λ h, let ⟨ac, c0⟩ := mem_eval.1 h in
mem_eval.2 ⟨(or_iff_left_of_imp $ by exact
λ cb, (eval_maximal h).1 cb ▸ refl_trans_gen.refl).1
(reaches_total ab ac), c0⟩,
λ h, let ⟨bc, c0⟩ := mem_eval.1 h in mem_eval.2 ⟨ab.trans bc, c0⟩,⟩
/-- Given a relation `tr : σ₁ → σ₂ → Prop` between state spaces, and state transition functions
`f₁ : σ₁ → option σ₁` and `f₂ : σ₂ → option σ₂`, `respects f₁ f₂ tr` means that if `tr a₁ a₂` holds
initially and `f₁` takes a step to `a₂` then `f₂` will take one or more steps before reaching a
state `b₂` satisfying `tr a₂ b₂`, and if `f₁ a₁` terminates then `f₂ a₂` also terminates.
Such a relation `tr` is also known as a refinement. -/
def respects {σ₁ σ₂}
(f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂ → Prop) :=
∀ ⦃a₁ a₂⦄, tr a₁ a₂ → (match f₁ a₁ with
| some b₁ := ∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂
| none := f₂ a₂ = none
end : Prop)
theorem tr_reaches₁ {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}
(H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches₁ f₁ a₁ b₁) :
∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ :=
begin
induction ab with c₁ ac c₁ d₁ ac cd IH,
{ have := H aa,
rwa (show f₁ a₁ = _, from ac) at this },
{ rcases IH with ⟨c₂, cc, ac₂⟩,
have := H cc,
rw (show f₁ c₁ = _, from cd) at this,
rcases this with ⟨d₂, dd, cd₂⟩,
exact ⟨_, dd, ac₂.trans cd₂⟩ }
end
theorem tr_reaches {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}
(H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches f₁ a₁ b₁) :
∃ b₂, tr b₁ b₂ ∧ reaches f₂ a₂ b₂ :=
begin
rcases refl_trans_gen_iff_eq_or_trans_gen.1 ab with rfl | ab,
{ exact ⟨_, aa, refl_trans_gen.refl⟩ },
{ exact let ⟨b₂, bb, h⟩ := tr_reaches₁ H aa ab in
⟨b₂, bb, h.to_refl⟩ }
end
theorem tr_reaches_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}
(H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₂} (ab : reaches f₂ a₂ b₂) :
∃ c₁ c₂, reaches f₂ b₂ c₂ ∧ tr c₁ c₂ ∧ reaches f₁ a₁ c₁ :=
begin
induction ab with c₂ d₂ ac cd IH,
{ exact ⟨_, _, refl_trans_gen.refl, aa, refl_trans_gen.refl⟩ },
{ rcases IH with ⟨e₁, e₂, ce, ee, ae⟩,
rcases refl_trans_gen.cases_head ce with rfl | ⟨d', cd', de⟩,
{ have := H ee, revert this,
cases eg : f₁ e₁ with g₁; simp only [respects, and_imp, exists_imp_distrib],
{ intro c0, cases cd.symm.trans c0 },
{ intros g₂ gg cg,
rcases trans_gen.head'_iff.1 cg with ⟨d', cd', dg⟩,
cases option.mem_unique cd cd',
exact ⟨_, _, dg, gg, ae.tail eg⟩ } },
{ cases option.mem_unique cd cd',
exact ⟨_, _, de, ee, ae⟩ } }
end
theorem tr_eval {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}
(H : respects f₁ f₂ tr) {a₁ b₁ a₂} (aa : tr a₁ a₂)
(ab : b₁ ∈ eval f₁ a₁) : ∃ b₂, tr b₁ b₂ ∧ b₂ ∈ eval f₂ a₂ :=
begin
cases mem_eval.1 ab with ab b0,
rcases tr_reaches H aa ab with ⟨b₂, bb, ab⟩,
refine ⟨_, bb, mem_eval.2 ⟨ab, _⟩⟩,
have := H bb, rwa b0 at this
end
theorem tr_eval_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}
(H : respects f₁ f₂ tr) {a₁ b₂ a₂} (aa : tr a₁ a₂)
(ab : b₂ ∈ eval f₂ a₂) : ∃ b₁, tr b₁ b₂ ∧ b₁ ∈ eval f₁ a₁ :=
begin
cases mem_eval.1 ab with ab b0,
rcases tr_reaches_rev H aa ab with ⟨c₁, c₂, bc, cc, ac⟩,
cases (refl_trans_gen_iff_eq
(by exact option.eq_none_iff_forall_not_mem.1 b0)).1 bc,
refine ⟨_, cc, mem_eval.2 ⟨ac, _⟩⟩,
have := H cc, cases f₁ c₁ with d₁, {refl},
rcases this with ⟨d₂, dd, bd⟩,
rcases trans_gen.head'_iff.1 bd with ⟨e, h, _⟩,
cases b0.symm.trans h
end
theorem tr_eval_dom {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}
(H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) :
(eval f₂ a₂).dom ↔ (eval f₁ a₁).dom :=
⟨λ h, let ⟨b₂, tr, h, _⟩ := tr_eval_rev H aa ⟨h, rfl⟩ in h,
λ h, let ⟨b₂, tr, h, _⟩ := tr_eval H aa ⟨h, rfl⟩ in h⟩
/-- A simpler version of `respects` when the state transition relation `tr` is a function. -/
def frespects {σ₁ σ₂} (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂) (a₂ : σ₂) : option σ₁ → Prop
| (some b₁) := reaches₁ f₂ a₂ (tr b₁)
| none := f₂ a₂ = none
theorem frespects_eq {σ₁ σ₂} {f₂ : σ₂ → option σ₂} {tr : σ₁ → σ₂} {a₂ b₂}
(h : f₂ a₂ = f₂ b₂) : ∀ {b₁}, frespects f₂ tr a₂ b₁ ↔ frespects f₂ tr b₂ b₁
| (some b₁) := reaches₁_eq h
| none := by unfold frespects; rw h
theorem fun_respects {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂} :
respects f₁ f₂ (λ a b, tr a = b) ↔ ∀ ⦃a₁⦄, frespects f₂ tr (tr a₁) (f₁ a₁) :=
forall_congr $ λ a₁, by cases f₁ a₁; simp only [frespects, respects, exists_eq_left', forall_eq']
theorem tr_eval' {σ₁ σ₂}
(f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂)
(H : respects f₁ f₂ (λ a b, tr a = b))
(a₁) : eval f₂ (tr a₁) = tr <$> eval f₁ a₁ :=
roption.ext $ λ b₂,
⟨λ h, let ⟨b₁, bb, hb⟩ := tr_eval_rev H rfl h in
(roption.mem_map_iff _).2 ⟨b₁, hb, bb⟩,
λ h, begin
rcases (roption.mem_map_iff _).1 h with ⟨b₁, ab, bb⟩,
rcases tr_eval H rfl ab with ⟨_, rfl, h⟩,
rwa bb at h
end⟩
/-!
## The TM0 model
A TM0 turing machine is essentially a Post-Turing machine, adapted for type theory.
A Post-Turing machine with symbol type `Γ` and label type `Λ` is a function
`Λ → Γ → option (Λ × stmt)`, where a `stmt` can be either `move left`, `move right` or `write a`
for `a : Γ`. The machine works over a "tape", a doubly-infinite sequence of elements of `Γ`, and
an instantaneous configuration, `cfg`, is a label `q : Λ` indicating the current internal state of
the machine, and a `tape Γ` (which is essentially `ℤ →₀ Γ`). The evolution is described by the
`step` function:
* If `M q T.head = none`, then the machine halts.
* If `M q T.head = some (q', s)`, then the machine performs action `s : stmt` and then transitions
to state `q'`.
The initial state takes a `list Γ` and produces a `tape Γ` where the head of the list is the head
of the tape and the rest of the list extends to the right, with the left side all blank. The final
state takes the entire right side of the tape right or equal to the current position of the
machine. (This is actually a `list_blank Γ`, not a `list Γ`, because we don't know, at this level
of generality, where the output ends. If equality to `default Γ` is decidable we can trim the list
to remove the infinite tail of blanks.)
-/
namespace TM0
section
parameters (Γ : Type*) [inhabited Γ] -- type of tape symbols
parameters (Λ : Type*) [inhabited Λ] -- type of "labels" or TM states
/-- A Turing machine "statement" is just a command to either move
left or right, or write a symbol on the tape. -/
inductive stmt
| move : dir → stmt
| write : Γ → stmt
instance stmt.inhabited : inhabited stmt := ⟨stmt.write (default _)⟩
/-- A Post-Turing machine with symbol type `Γ` and label type `Λ`
is a function which, given the current state `q : Λ` and
the tape head `a : Γ`, either halts (returns `none`) or returns
a new state `q' : Λ` and a `stmt` describing what to do,
either a move left or right, or a write command.
Both `Λ` and `Γ` are required to be inhabited; the default value
for `Γ` is the "blank" tape value, and the default value of `Λ` is
the initial state. -/
@[nolint unused_arguments] -- [inhabited Λ]: this is a deliberate addition, see comment
def machine := Λ → Γ → option (Λ × stmt)
instance machine.inhabited : inhabited machine := by unfold machine; apply_instance
/-- The configuration state of a Turing machine during operation
consists of a label (machine state), and a tape, represented in
the form `(a, L, R)` meaning the tape looks like `L.rev ++ [a] ++ R`
with the machine currently reading the `a`. The lists are
automatically extended with blanks as the machine moves around. -/
structure cfg :=
(q : Λ)
(tape : tape Γ)
instance cfg.inhabited : inhabited cfg := ⟨⟨default _, default _⟩⟩
parameters {Γ Λ}
/-- Execution semantics of the Turing machine. -/
def step (M : machine) : cfg → option cfg
| ⟨q, T⟩ := (M q T.1).map (λ ⟨q', a⟩, ⟨q',
match a with
| stmt.move d := T.move d
| stmt.write a := T.write a
end⟩)
/-- The statement `reaches M s₁ s₂` means that `s₂` is obtained
starting from `s₁` after a finite number of steps from `s₂`. -/
def reaches (M : machine) : cfg → cfg → Prop :=
refl_trans_gen (λ a b, b ∈ step M a)
/-- The initial configuration. -/
def init (l : list Γ) : cfg :=
⟨default Λ, tape.mk₁ l⟩
/-- Evaluate a Turing machine on initial input to a final state,
if it terminates. -/
def eval (M : machine) (l : list Γ) : roption (list_blank Γ) :=
(eval (step M) (init l)).map (λ c, c.tape.right₀)
/-- The raw definition of a Turing machine does not require that
`Γ` and `Λ` are finite, and in practice we will be interested
in the infinite `Λ` case. We recover instead a notion of
"effectively finite" Turing machines, which only make use of a
finite subset of their states. We say that a set `S ⊆ Λ`
supports a Turing machine `M` if `S` is closed under the
transition function and contains the initial state. -/
def supports (M : machine) (S : set Λ) :=
default Λ ∈ S ∧ ∀ {q a q' s}, (q', s) ∈ M q a → q ∈ S → q' ∈ S
theorem step_supports (M : machine) {S}
(ss : supports M S) : ∀ {c c' : cfg},
c' ∈ step M c → c.q ∈ S → c'.q ∈ S
| ⟨q, T⟩ c' h₁ h₂ := begin
rcases option.map_eq_some'.1 h₁ with ⟨⟨q', a⟩, h, rfl⟩,
exact ss.2 h h₂,
end
theorem univ_supports (M : machine) : supports M set.univ :=
⟨trivial, λ q a q' s h₁ h₂, trivial⟩
end
section
variables {Γ : Type*} [inhabited Γ]
variables {Γ' : Type*} [inhabited Γ']
variables {Λ : Type*} [inhabited Λ]
variables {Λ' : Type*} [inhabited Λ']
/-- Map a TM statement across a function. This does nothing to move statements and maps the write
values. -/
def stmt.map (f : pointed_map Γ Γ') : stmt Γ → stmt Γ'
| (stmt.move d) := stmt.move d
| (stmt.write a) := stmt.write (f a)
/-- Map a configuration across a function, given `f : Γ → Γ'` a map of the alphabets and
`g : Λ → Λ'` a map of the machine states. -/
def cfg.map (f : pointed_map Γ Γ') (g : Λ → Λ') : cfg Γ Λ → cfg Γ' Λ'
| ⟨q, T⟩ := ⟨g q, T.map f⟩
variables (M : machine Γ Λ)
(f₁ : pointed_map Γ Γ') (f₂ : pointed_map Γ' Γ) (g₁ : Λ → Λ') (g₂ : Λ' → Λ)
/-- Because the state transition function uses the alphabet and machine states in both the input
and output, to map a machine from one alphabet and machine state space to another we need functions
in both directions, essentially an `equiv` without the laws. -/
def machine.map : machine Γ' Λ'
| q l := (M (g₂ q) (f₂ l)).map (prod.map g₁ (stmt.map f₁))
theorem machine.map_step {S : set Λ}
(f₂₁ : function.right_inverse f₁ f₂)
(g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) :
∀ c : cfg Γ Λ, c.q ∈ S →
(step M c).map (cfg.map f₁ g₁) =
step (M.map f₁ f₂ g₁ g₂) (cfg.map f₁ g₁ c)
| ⟨q, T⟩ h := begin
unfold step machine.map cfg.map,
simp only [turing.tape.map_fst, g₂₁ q h, f₂₁ _],
rcases M q T.1 with _|⟨q', d|a⟩, {refl},
{ simp only [step, cfg.map, option.map_some', tape.map_move f₁], refl },
{ simp only [step, cfg.map, option.map_some', tape.map_write], refl }
end
theorem map_init (g₁ : pointed_map Λ Λ') (l : list Γ) :
(init l).map f₁ g₁ = init (l.map f₁) :=
congr (congr_arg cfg.mk g₁.map_pt) (tape.map_mk₁ _ _)
theorem machine.map_respects
(g₁ : pointed_map Λ Λ') (g₂ : Λ' → Λ)
{S} (ss : supports M S)
(f₂₁ : function.right_inverse f₁ f₂)
(g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) :
respects (step M) (step (M.map f₁ f₂ g₁ g₂))
(λ a b, a.q ∈ S ∧ cfg.map f₁ g₁ a = b)
| c _ ⟨cs, rfl⟩ := begin
cases e : step M c with c'; unfold respects,
{ rw [← M.map_step f₁ f₂ g₁ g₂ f₂₁ g₂₁ _ cs, e], refl },
{ refine ⟨_, ⟨step_supports M ss e cs, rfl⟩, trans_gen.single _⟩,
rw [← M.map_step f₁ f₂ g₁ g₂ f₂₁ g₂₁ _ cs, e], exact rfl }
end
end
end TM0
/-!
## The TM1 model
The TM1 model is a simplification and extension of TM0 (Post-Turing model) in the direction of
Wang B-machines. The machine's internal state is extended with a (finite) store `σ` of variables
that may be accessed and updated at any time.
A machine is given by a `Λ` indexed set of procedures or functions. Each function has a body which
is a `stmt`. Most of the regular commands are allowed to use the current value `a` of the local
variables and the value `T.head` on the tape to calculate what to write or how to change local
state, but the statements themselves have a fixed structure. The `stmt`s can be as follows:
* `move d q`: move left or right, and then do `q`
* `write (f : Γ → σ → Γ) q`: write `f a T.head` to the tape, then do `q`
* `load (f : Γ → σ → σ) q`: change the internal state to `f a T.head`
* `branch (f : Γ → σ → bool) qtrue qfalse`: If `f a T.head` is true, do `qtrue`, else `qfalse`
* `goto (f : Γ → σ → Λ)`: Go to label `f a T.head`
* `halt`: Transition to the halting state, which halts on the following step
Note that here most statements do not have labels; `goto` commands can only go to a new function.
Only the `goto` and `halt` statements actually take a step; the rest is done by recursion on
statements and so take 0 steps. (There is a uniform bound on many statements can be executed before
the next `goto`, so this is an `O(1)` speedup with the constant depending on the machine.)
The `halt` command has a one step stutter before actually halting so that any changes made before
the halt have a chance to be "committed", since the `eval` relation uses the final configuration
before the halt as the output, and `move` and `write` etc. take 0 steps in this model.
-/
namespace TM1
section
parameters (Γ : Type*) [inhabited Γ] -- Type of tape symbols
parameters (Λ : Type*) -- Type of function labels
parameters (σ : Type*) -- Type of variable settings
/-- The TM1 model is a simplification and extension of TM0
(Post-Turing model) in the direction of Wang B-machines. The machine's
internal state is extended with a (finite) store `σ` of variables
that may be accessed and updated at any time.
A machine is given by a `Λ` indexed set of procedures or functions.
Each function has a body which is a `stmt`, which can either be a
`move` or `write` command, a `branch` (if statement based on the
current tape value), a `load` (set the variable value),
a `goto` (call another function), or `halt`. Note that here
most statements do not have labels; `goto` commands can only
go to a new function. All commands have access to the variable value
and current tape value. -/
inductive stmt
| move : dir → stmt → stmt
| write : (Γ → σ → Γ) → stmt → stmt
| load : (Γ → σ → σ) → stmt → stmt
| branch : (Γ → σ → bool) → stmt → stmt → stmt
| goto : (Γ → σ → Λ) → stmt
| halt : stmt
open stmt
instance stmt.inhabited : inhabited stmt := ⟨halt⟩
/-- The configuration of a TM1 machine is given by the currently
evaluating statement, the variable store value, and the tape. -/
structure cfg :=
(l : option Λ)
(var : σ)
(tape : tape Γ)
instance cfg.inhabited [inhabited σ] : inhabited cfg := ⟨⟨default _, default _, default _⟩⟩
parameters {Γ Λ σ}
/-- The semantics of TM1 evaluation. -/
def step_aux : stmt → σ → tape Γ → cfg
| (move d q) v T := step_aux q v (T.move d)
| (write a q) v T := step_aux q v (T.write (a T.1 v))
| (load s q) v T := step_aux q (s T.1 v) T
| (branch p q₁ q₂) v T := cond (p T.1 v) (step_aux q₁ v T) (step_aux q₂ v T)
| (goto l) v T := ⟨some (l T.1 v), v, T⟩
| halt v T := ⟨none, v, T⟩
/-- The state transition function. -/
def step (M : Λ → stmt) : cfg → option cfg
| ⟨none, v, T⟩ := none
| ⟨some l, v, T⟩ := some (step_aux (M l) v T)
/-- A set `S` of labels supports the statement `q` if all the `goto`
statements in `q` refer only to other functions in `S`. -/
def supports_stmt (S : finset Λ) : stmt → Prop
| (move d q) := supports_stmt q
| (write a q) := supports_stmt q
| (load s q) := supports_stmt q
| (branch p q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂
| (goto l) := ∀ a v, l a v ∈ S
| halt := true
open_locale classical
/-- The subterm closure of a statement. -/
noncomputable def stmts₁ : stmt → finset stmt
| Q@(move d q) := insert Q (stmts₁ q)
| Q@(write a q) := insert Q (stmts₁ q)
| Q@(load s q) := insert Q (stmts₁ q)
| Q@(branch p q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂)
| Q := {Q}
theorem stmts₁_self {q} : q ∈ stmts₁ q :=
by cases q; apply_rules [finset.mem_insert_self, finset.mem_singleton_self]
theorem stmts₁_trans {q₁ q₂} :
q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ :=
begin
intros h₁₂ q₀ h₀₁,
induction q₂ with _ q IH _ q IH _ q IH;
simp only [stmts₁] at h₁₂ ⊢;
simp only [finset.mem_insert, finset.mem_union, finset.mem_singleton] at h₁₂,
iterate 3 {
rcases h₁₂ with rfl | h₁₂,
{ unfold stmts₁ at h₀₁, exact h₀₁ },
{ exact finset.mem_insert_of_mem (IH h₁₂) } },
case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {
rcases h₁₂ with rfl | h₁₂ | h₁₂,
{ unfold stmts₁ at h₀₁, exact h₀₁ },
{ exact finset.mem_insert_of_mem (finset.mem_union_left _ $ IH₁ h₁₂) },
{ exact finset.mem_insert_of_mem (finset.mem_union_right _ $ IH₂ h₁₂) } },
case TM1.stmt.goto : l {
subst h₁₂, exact h₀₁ },
case TM1.stmt.halt {
subst h₁₂, exact h₀₁ }
end
theorem stmts₁_supports_stmt_mono {S q₁ q₂}
(h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ :=
begin
induction q₂ with _ q IH _ q IH _ q IH;
simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union,
finset.mem_singleton] at h hs,
iterate 3 { rcases h with rfl | h; [exact hs, exact IH h hs] },
case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {
rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] },
case TM1.stmt.goto : l { subst h, exact hs },
case TM1.stmt.halt { subst h, trivial }
end
/-- The set of all statements in a turing machine, plus one extra value `none` representing the
halt state. This is used in the TM1 to TM0 reduction. -/
noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) :=
(S.bind (λ q, stmts₁ (M q))).insert_none
theorem stmts_trans {M : Λ → stmt} {S q₁ q₂}
(h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S :=
by simp only [stmts, finset.mem_insert_none, finset.mem_bind,
option.mem_def, forall_eq', exists_imp_distrib];
exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩
variable [inhabited Λ]
/-- A set `S` of labels supports machine `M` if all the `goto`
statements in the functions in `S` refer only to other functions
in `S`. -/
def supports (M : Λ → stmt) (S : finset Λ) :=
default Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q)
theorem stmts_supports_stmt {M : Λ → stmt} {S q}
(ss : supports M S) : some q ∈ stmts M S → supports_stmt S q :=
by simp only [stmts, finset.mem_insert_none, finset.mem_bind,
option.mem_def, forall_eq', exists_imp_distrib];
exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls)
theorem step_supports (M : Λ → stmt) {S}
(ss : supports M S) : ∀ {c c' : cfg},
c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none
| ⟨some l₁, v, T⟩ c' h₁ h₂ := begin
replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂),
simp only [step, option.mem_def] at h₁, subst c',
revert h₂, induction M l₁ with _ q IH _ q IH _ q IH generalizing v T;
intro hs,
iterate 3 { exact IH _ _ hs },
case TM1.stmt.branch : p q₁' q₂' IH₁ IH₂ {
unfold step_aux, cases p T.1 v,
{ exact IH₂ _ _ hs.2 },
{ exact IH₁ _ _ hs.1 } },
case TM1.stmt.goto { exact finset.some_mem_insert_none.2 (hs _ _) },
case TM1.stmt.halt { apply multiset.mem_cons_self }
end
variable [inhabited σ]
/-- The initial state, given a finite input that is placed on the tape starting at the TM head and
going to the right. -/
def init (l : list Γ) : cfg :=
⟨some (default _), default _, tape.mk₁ l⟩
/-- Evaluate a TM to completion, resulting in an output list on the tape (with an indeterminate
number of blanks on the end). -/
def eval (M : Λ → stmt) (l : list Γ) : roption (list_blank Γ) :=
(eval (step M) (init l)).map (λ c, c.tape.right₀)
end
end TM1
/-!
## TM1 emulator in TM0
To prove that TM1 computable functions are TM0 computable, we need to reduce each TM1 program to a
TM0 program. So suppose a TM1 program is given. We take the following:
* The alphabet `Γ` is the same for both TM1 and TM0
* The set of states `Λ'` is defined to be `option stmt₁ × σ`, that is, a TM1 statement or `none`
representing halt, and the possible settings of the internal variables.
Note that this is an infinite set, because `stmt₁` is infinite. This is okay because we assume
that from the initial TM1 state, only finitely many other labels are reachable, and there are
only finitely many statements that appear in all of these functions.
Even though `stmt₁` contains a statement called `halt`, we must separate it from `none`
(`some halt` steps to `none` and `none` actually halts) because there is a one step stutter in the
TM1 semantics.
-/
namespace TM1to0
section
parameters {Γ : Type*} [inhabited Γ]
parameters {Λ : Type*} [inhabited Λ]
parameters {σ : Type*} [inhabited σ]
local notation `stmt₁` := TM1.stmt Γ Λ σ
local notation `cfg₁` := TM1.cfg Γ Λ σ
local notation `stmt₀` := TM0.stmt Γ
parameters (M : Λ → stmt₁)
include M
/-- The base machine state space is a pair of an `option stmt₁` representing the current program
to be executed, or `none` for the halt state, and a `σ` which is the local state (stored in the TM,
not the tape). Because there are an infinite number of programs, this state space is infinite, but
for a finitely supported TM1 machine and a finite type `σ`, only finitely many of these states are
reachable. -/
@[nolint unused_arguments] -- [inhabited Λ] [inhabited σ] (M : Λ → stmt₁): We need the M assumption
-- because of the inhabited instance, but we could avoid the inhabited instances on Λ and σ here.
-- But they are parameters so we cannot easily skip them for just this definition.
def Λ' := option stmt₁ × σ
instance : inhabited Λ' := ⟨(some (M (default _)), default _)⟩
open TM0.stmt
/-- The core TM1 → TM0 translation function. Here `s` is the current value on the tape, and the
`stmt₁` is the TM1 statement to translate, with local state `v : σ`. We evaluate all regular
instructions recursively until we reach either a `move` or `write` command, or a `goto`; in the
latter case we emit a dummy `write s` step and transition to the new target location. -/
def tr_aux (s : Γ) : stmt₁ → σ → Λ' × stmt₀
| (TM1.stmt.move d q) v := ((some q, v), move d)
| (TM1.stmt.write a q) v := ((some q, v), write (a s v))
| (TM1.stmt.load a q) v := tr_aux q (a s v)
| (TM1.stmt.branch p q₁ q₂) v := cond (p s v) (tr_aux q₁ v) (tr_aux q₂ v)
| (TM1.stmt.goto l) v := ((some (M (l s v)), v), write s)
| TM1.stmt.halt v := ((none, v), write s)
local notation `cfg₀` := TM0.cfg Γ Λ'
/-- The translated TM0 machine (given the TM1 machine input). -/
def tr : TM0.machine Γ Λ'
| (none, v) s := none
| (some q, v) s := some (tr_aux s q v)
/-- Translate configurations from TM1 to TM0. -/
def tr_cfg : cfg₁ → cfg₀
| ⟨l, v, T⟩ := ⟨(l.map M, v), T⟩
theorem tr_respects : respects (TM1.step M) (TM0.step tr)
(λ c₁ c₂, tr_cfg c₁ = c₂) :=
fun_respects.2 $ λ ⟨l₁, v, T⟩, begin
cases l₁ with l₁, {exact rfl},
unfold tr_cfg TM1.step frespects option.map function.comp option.bind,
induction M l₁ with _ q IH _ q IH _ q IH generalizing v T,
case TM1.stmt.move : d q IH { exact trans_gen.head rfl (IH _ _) },
case TM1.stmt.write : a q IH { exact trans_gen.head rfl (IH _ _) },
case TM1.stmt.load : a q IH { exact (reaches₁_eq (by refl)).2 (IH _ _) },
case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {
unfold TM1.step_aux, cases e : p T.1 v,
{ exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₂ _ _) },
{ exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₁ _ _) } },
iterate 2 {
exact trans_gen.single (congr_arg some
(congr (congr_arg TM0.cfg.mk rfl) (tape.write_self T))) }
end
theorem tr_eval (l : list Γ) : TM0.eval tr l = TM1.eval M l :=
(congr_arg _ (tr_eval' _ _ _ tr_respects ⟨some _, _, _⟩)).trans begin
rw [roption.map_eq_map, roption.map_map, TM1.eval],
congr' with ⟨⟩, refl
end
variables [fintype σ]
/-- Given a finite set of accessible `Λ` machine states, there is a finite set of accessible
machine states in the target (even though the type `Λ'` is infinite). -/
noncomputable def tr_stmts (S : finset Λ) : finset Λ' :=
(TM1.stmts M S).product finset.univ
open_locale classical
local attribute [simp] TM1.stmts₁_self
theorem tr_supports {S : finset Λ} (ss : TM1.supports M S) :
TM0.supports tr (↑(tr_stmts S)) :=
⟨finset.mem_product.2 ⟨finset.some_mem_insert_none.2
(finset.mem_bind.2 ⟨_, ss.1, TM1.stmts₁_self⟩),
finset.mem_univ _⟩,
λ q a q' s h₁ h₂, begin
rcases q with ⟨_|q, v⟩, {cases h₁},
cases q' with q' v', simp only [tr_stmts, finset.mem_coe,
finset.mem_product, finset.mem_univ, and_true] at h₂ ⊢,
cases q', {exact multiset.mem_cons_self _ _},
simp only [tr, option.mem_def] at h₁,
have := TM1.stmts_supports_stmt ss h₂,
revert this, induction q generalizing v; intro hs,
case TM1.stmt.move : d q {
cases h₁, refine TM1.stmts_trans _ h₂,
unfold TM1.stmts₁,
exact finset.mem_insert_of_mem TM1.stmts₁_self },
case TM1.stmt.write : b q {
cases h₁, refine TM1.stmts_trans _ h₂,
unfold TM1.stmts₁,
exact finset.mem_insert_of_mem TM1.stmts₁_self },
case TM1.stmt.load : b q IH {
refine IH (TM1.stmts_trans _ h₂) _ h₁ hs,
unfold TM1.stmts₁,
exact finset.mem_insert_of_mem TM1.stmts₁_self },
case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {
change cond (p a v) _ _ = ((some q', v'), s) at h₁,
cases p a v,
{ refine IH₂ (TM1.stmts_trans _ h₂) _ h₁ hs.2,
unfold TM1.stmts₁,
exact finset.mem_insert_of_mem (finset.mem_union_right _ TM1.stmts₁_self) },
{ refine IH₁ (TM1.stmts_trans _ h₂) _ h₁ hs.1,
unfold TM1.stmts₁,
exact finset.mem_insert_of_mem (finset.mem_union_left _ TM1.stmts₁_self) } },
case TM1.stmt.goto : l {
cases h₁, exact finset.some_mem_insert_none.2
(finset.mem_bind.2 ⟨_, hs _ _, TM1.stmts₁_self⟩) },
case TM1.stmt.halt { cases h₁ }
end⟩
end
end TM1to0
/-!
## TM1(Γ) emulator in TM1(bool)
The most parsimonious Turing machine model that is still Turing complete is `TM0` with `Γ = bool`.
Because our construction in the previous section reducing `TM1` to `TM0` doesn't change the
alphabet, we can do the alphabet reduction on `TM1` instead of `TM0` directly.
The basic idea is to use a bijection between `Γ` and a subset of `vector bool n`, where `n` is a
fixed constant. Each tape element is represented as a block of `n` bools. Whenever the machine
wants to read a symbol from the tape, it traverses over the block, performing `n` `branch`
instructions to each any of the `2^n` results.
For the `write` instruction, we have to use a `goto` because we need to follow a different code
path depending on the local state, which is not available in the TM1 model, so instead we jump to
a label computed using the read value and the local state, which performs the writing and returns
to normal execution.
Emulation overhead is `O(1)`. If not for the above `write` behavior it would be 1-1 because we are
exploiting the 0-step behavior of regular commands to avoid taking steps, but there are
nevertheless a bounded number of `write` calls between `goto` statements because TM1 statements are
finitely long.
-/
namespace TM1to1
open TM1
section
parameters {Γ : Type*} [inhabited Γ]
theorem exists_enc_dec [fintype Γ] :
∃ n (enc : Γ → vector bool n) (dec : vector bool n → Γ),
enc (default _) = vector.repeat ff n ∧ ∀ a, dec (enc a) = a :=
begin
rcases fintype.exists_equiv_fin Γ with ⟨n, ⟨F⟩⟩,
let G : fin n ↪ fin n → bool := ⟨λ a b, a = b,
λ a b h, of_to_bool_true $ (congr_fun h b).trans $ to_bool_tt rfl⟩,
let H := (F.to_embedding.trans G).trans
(equiv.vector_equiv_fin _ _).symm.to_embedding,
classical,
let enc := H.set_value (default _) (vector.repeat ff n),
exact ⟨_, enc, function.inv_fun enc,
H.set_value_eq _ _, function.left_inverse_inv_fun enc.2⟩
end
parameters {Λ : Type*} [inhabited Λ]
parameters {σ : Type*} [inhabited σ]
local notation `stmt₁` := stmt Γ Λ σ
local notation `cfg₁` := cfg Γ Λ σ
/-- The configuration state of the TM. -/
inductive Λ' : Type (max u_1 u_2 u_3)
| normal : Λ → Λ'
| write : Γ → stmt₁ → Λ'
instance : inhabited Λ' := ⟨Λ'.normal (default _)⟩
local notation `stmt'` := stmt bool Λ' σ
local notation `cfg'` := cfg bool Λ' σ
/-- Read a vector of length `n` from the tape. -/
def read_aux : ∀ n, (vector bool n → stmt') → stmt'
| 0 f := f vector.nil
| (i+1) f := stmt.branch (λ a s, a)
(stmt.move dir.right $ read_aux i (λ v, f (tt :: v)))
(stmt.move dir.right $ read_aux i (λ v, f (ff :: v)))
parameters {n : ℕ} (enc : Γ → vector bool n) (dec : vector bool n → Γ)
/-- A move left or right corresponds to `n` moves across the super-cell. -/
def move (d : dir) (q : stmt') : stmt' := (stmt.move d)^[n] q
/-- To read a symbol from the tape, we use `read_aux` to traverse the symbol,
then return to the original position with `n` moves to the left. -/
def read (f : Γ → stmt') : stmt' :=
read_aux n (λ v, move dir.left $ f (dec v))
/-- Write a list of bools on the tape. -/
def write : list bool → stmt' → stmt'
| [] q := q
| (a :: l) q := stmt.write (λ _ _, a) $ stmt.move dir.right $ write l q
/-- Translate a normal instruction. For the `write` command, we use a `goto` indirection so that
we can access the current value of the tape. -/
def tr_normal : stmt₁ → stmt'
| (stmt.move d q) := move d $ tr_normal q
| (stmt.write f q) := read $ λ a, stmt.goto $ λ _ s, Λ'.write (f a s) q
| (stmt.load f q) := read $ λ a, stmt.load (λ _ s, f a s) $ tr_normal q
| (stmt.branch p q₁ q₂) := read $ λ a, stmt.branch (λ _ s, p a s) (tr_normal q₁) (tr_normal q₂)
| (stmt.goto l) := read $ λ a, stmt.goto $ λ _ s, Λ'.normal (l a s)
| stmt.halt := stmt.halt
theorem step_aux_move (d q v T) :
step_aux (move d q) v T =
step_aux q v ((tape.move d)^[n] T) :=
begin
suffices : ∀ i,
step_aux (stmt.move d^[i] q) v T =
step_aux q v (tape.move d^[i] T), from this n,
intro, induction i with i IH generalizing T, {refl},
rw [iterate_succ', step_aux, IH, iterate_succ]
end
theorem supports_stmt_move {S d q} :
supports_stmt S (move d q) = supports_stmt S q :=
suffices ∀ {i}, supports_stmt S (stmt.move d^[i] q) = _, from this,
by intro; induction i generalizing q; simp only [*, iterate]; refl
theorem supports_stmt_write {S l q} :
supports_stmt S (write l q) = supports_stmt S q :=
by induction l with a l IH; simp only [write, supports_stmt, *]
theorem supports_stmt_read {S} : ∀ {f : Γ → stmt'},
(∀ a, supports_stmt S (f a)) → supports_stmt S (read f) :=
suffices ∀ i (f : vector bool i → stmt'),
(∀ v, supports_stmt S (f v)) → supports_stmt S (read_aux i f),
from λ f hf, this n _ (by intro; simp only [supports_stmt_move, hf]),
λ i f hf, begin
induction i with i IH, {exact hf _},
split; apply IH; intro; apply hf,
end
parameter (enc0 : enc (default _) = vector.repeat ff n)
section
parameter {enc}
include enc0
/-- The low level tape corresponding to the given tape over alphabet `Γ`. -/
def tr_tape' (L R : list_blank Γ) : tape bool :=
begin
refine tape.mk'
(L.bind (λ x, (enc x).to_list.reverse) ⟨n, _⟩)
(R.bind (λ x, (enc x).to_list) ⟨n, _⟩);
simp only [enc0, vector.repeat,
list.reverse_repeat, bool.default_bool, vector.to_list_mk]
end
/-- The low level tape corresponding to the given tape over alphabet `Γ`. -/
def tr_tape (T : tape Γ) : tape bool := tr_tape' T.left T.right₀
theorem tr_tape_mk' (L R : list_blank Γ) : tr_tape (tape.mk' L R) = tr_tape' L R :=
by simp only [tr_tape, tape.mk'_left, tape.mk'_right₀]
end
parameters (M : Λ → stmt₁)
/-- The top level program. -/
def tr : Λ' → stmt'
| (Λ'.normal l) := tr_normal (M l)
| (Λ'.write a q) := write (enc a).to_list $ move dir.left $ tr_normal q
/-- The machine configuration translation. -/
def tr_cfg : cfg₁ → cfg'
| ⟨l, v, T⟩ := ⟨l.map Λ'.normal, v, tr_tape T⟩
parameter {enc}
include enc0
theorem tr_tape'_move_left (L R) :
(tape.move dir.left)^[n] (tr_tape' L R) =
(tr_tape' L.tail (R.cons L.head)) :=
begin
obtain ⟨a, L, rfl⟩ := L.exists_cons,
simp only [tr_tape', list_blank.cons_bind, list_blank.head_cons, list_blank.tail_cons],
suffices : ∀ {L' R' l₁ l₂}
(e : vector.to_list (enc a) = list.reverse_core l₁ l₂),
tape.move dir.left^[l₁.length]
(tape.mk' (list_blank.append l₁ L') (list_blank.append l₂ R')) =
tape.mk' L' (list_blank.append (vector.to_list (enc a)) R'),
{ simpa only [list.length_reverse, vector.to_list_length]
using this (list.reverse_reverse _).symm },
intros, induction l₁ with b l₁ IH generalizing l₂,
{ cases e, refl },
simp only [list.length, list.cons_append, iterate_succ_apply],
convert IH e,
simp only [list_blank.tail_cons, list_blank.append, tape.move_left_mk', list_blank.head_cons]
end
theorem tr_tape'_move_right (L R) :
(tape.move dir.right)^[n] (tr_tape' L R) =
(tr_tape' (L.cons R.head) R.tail) :=
begin
suffices : ∀ i L, (tape.move dir.right)^[i] ((tape.move dir.left)^[i] L) = L,
{ refine (eq.symm _).trans (this n _),
simp only [tr_tape'_move_left, list_blank.cons_head_tail,
list_blank.head_cons, list_blank.tail_cons] },
intros, induction i with i IH, {refl},
rw [iterate_succ_apply, iterate_succ_apply', tape.move_left_right, IH]
end
theorem step_aux_write (q v a b L R) :
step_aux (write (enc a).to_list q) v (tr_tape' L (list_blank.cons b R)) =
step_aux q v (tr_tape' (list_blank.cons a L) R) :=
begin
simp only [tr_tape', list.cons_bind, list.append_assoc],
suffices : ∀ {L' R'} (l₁ l₂ l₂' : list bool)
(e : l₂'.length = l₂.length),
step_aux (write l₂ q) v (tape.mk' (list_blank.append l₁ L') (list_blank.append l₂' R')) =
step_aux q v (tape.mk' (L'.append (list.reverse_core l₂ l₁)) R'),
{ convert this [] _ _ ((enc b).2.trans (enc a).2.symm);
rw list_blank.cons_bind; refl },
clear a b L R, intros,
induction l₂ with a l₂ IH generalizing l₁ l₂',
{ cases list.length_eq_zero.1 e, refl },
cases l₂' with b l₂'; injection e with e,
dunfold write step_aux,
convert IH _ _ e, simp only [list_blank.head_cons, list_blank.tail_cons,
list_blank.append, tape.move_right_mk', tape.write_mk']
end
parameters (encdec : ∀ a, dec (enc a) = a)
include encdec
theorem step_aux_read (f v L R) :
step_aux (read f) v (tr_tape' L R) =
step_aux (f R.head) v (tr_tape' L R) :=
begin
suffices : ∀ f,
step_aux (read_aux n f) v (tr_tape' enc0 L R) =
step_aux (f (enc R.head)) v
(tr_tape' enc0 (L.cons R.head) R.tail),
{ rw [read, this, step_aux_move, encdec, tr_tape'_move_left enc0],
simp only [list_blank.head_cons, list_blank.cons_head_tail, list_blank.tail_cons] },
obtain ⟨a, R, rfl⟩ := R.exists_cons,
simp only [list_blank.head_cons, list_blank.tail_cons,
tr_tape', list_blank.cons_bind, list_blank.append_assoc],
suffices : ∀ i f L' R' l₁ l₂ h,
step_aux (read_aux i f) v
(tape.mk' (list_blank.append l₁ L') (list_blank.append l₂ R')) =
step_aux (f ⟨l₂, h⟩) v
(tape.mk' (list_blank.append (l₂.reverse_core l₁) L') R'),
{ intro f, convert this n f _ _ _ _ (enc a).2; simp },
clear f L a R, intros, subst i,
induction l₂ with a l₂ IH generalizing l₁, {refl},
transitivity step_aux
(read_aux l₂.length (λ v, f (a :: v))) v
(tape.mk' ((L'.append l₁).cons a) (R'.append l₂)),
{ dsimp [read_aux, step_aux], simp, cases a; refl },
rw [← list_blank.append, IH], refl
end
theorem tr_respects : respects (step M) (step tr)
(λ c₁ c₂, tr_cfg c₁ = c₂) :=
fun_respects.2 $ λ ⟨l₁, v, T⟩, begin
obtain ⟨L, R, rfl⟩ := T.exists_mk',
cases l₁ with l₁, {exact rfl},
suffices : ∀ q R, reaches (step (tr enc dec M))
(step_aux (tr_normal dec q) v (tr_tape' enc0 L R))
(tr_cfg enc0 (step_aux q v (tape.mk' L R))),
{ refine trans_gen.head' rfl _, rw tr_tape_mk', exact this _ R },
clear R l₁, intros,
induction q with _ q IH _ q IH _ q IH generalizing v L R,
case TM1.stmt.move : d q IH {
cases d; simp only [tr_normal, iterate, step_aux_move, step_aux,
list_blank.head_cons, tape.move_left_mk',
list_blank.cons_head_tail, list_blank.tail_cons,
tr_tape'_move_left enc0, tr_tape'_move_right enc0];
apply IH },
case TM1.stmt.write : f q IH {
simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux],
refine refl_trans_gen.head rfl _,
obtain ⟨a, R, rfl⟩ := R.exists_cons,
rw [tr, tape.mk'_head, step_aux_write, list_blank.head_cons,
step_aux_move, tr_tape'_move_left enc0, list_blank.head_cons,
list_blank.tail_cons, tape.write_mk'],
apply IH },
case TM1.stmt.load : a q IH {
simp only [tr_normal, step_aux_read dec enc0 encdec],
apply IH },
case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {
simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux],
cases p R.head v; [apply IH₂, apply IH₁] },
case TM1.stmt.goto : l {
simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux, tr_cfg, tr_tape_mk'],
apply refl_trans_gen.refl },
case TM1.stmt.halt {
simp only [tr_normal, step_aux, tr_cfg, step_aux_move,
tr_tape'_move_left enc0, tr_tape'_move_right enc0, tr_tape_mk'],
apply refl_trans_gen.refl }
end
omit enc0 encdec
open_locale classical
parameters [fintype Γ]
/-- The set of accessible `Λ'.write` machine states. -/
noncomputable def writes : stmt₁ → finset Λ'
| (stmt.move d q) := writes q
| (stmt.write f q) := finset.univ.image (λ a, Λ'.write a q) ∪ writes q
| (stmt.load f q) := writes q
| (stmt.branch p q₁ q₂) := writes q₁ ∪ writes q₂
| (stmt.goto l) := ∅
| stmt.halt := ∅
/-- The set of accessible machine states, assuming that the input machine is supported on `S`,
are the normal states embedded from `S`, plus all write states accessible from these states. -/
noncomputable def tr_supp (S : finset Λ) : finset Λ' :=
S.bind (λ l, insert (Λ'.normal l) (writes (M l)))
theorem tr_supports {S} (ss : supports M S) :
supports tr (tr_supp S) :=
⟨finset.mem_bind.2 ⟨_, ss.1, finset.mem_insert_self _ _⟩,
λ q h, begin
suffices : ∀ q, supports_stmt S q →
(∀ q' ∈ writes q, q' ∈ tr_supp M S) →
supports_stmt (tr_supp M S) (tr_normal dec q) ∧
∀ q' ∈ writes q, supports_stmt (tr_supp M S) (tr enc dec M q'),
{ rcases finset.mem_bind.1 h with ⟨l, hl, h⟩,
have := this _ (ss.2 _ hl) (λ q' hq,
finset.mem_bind.2 ⟨_, hl, finset.mem_insert_of_mem hq⟩),
rcases finset.mem_insert.1 h with rfl | h,
exacts [this.1, this.2 _ h] },
intros q hs hw, induction q,
case TM1.stmt.move : d q IH {
unfold writes at hw ⊢,
replace IH := IH hs hw, refine ⟨_, IH.2⟩,
cases d; simp only [tr_normal, iterate, supports_stmt_move, IH] },
case TM1.stmt.write : f q IH {
unfold writes at hw ⊢,
simp only [finset.mem_image, finset.mem_union, finset.mem_univ,
exists_prop, true_and] at hw ⊢,
replace IH := IH hs (λ q hq, hw q (or.inr hq)),
refine ⟨supports_stmt_read _ $ λ a _ s,
hw _ (or.inl ⟨_, rfl⟩), λ q' hq, _⟩,
rcases hq with ⟨a, q₂, rfl⟩ | hq,
{ simp only [tr, supports_stmt_write, supports_stmt_move, IH.1] },
{ exact IH.2 _ hq } },
case TM1.stmt.load : a q IH {
unfold writes at hw ⊢,
replace IH := IH hs hw,
refine ⟨supports_stmt_read _ (λ a, IH.1), IH.2⟩ },
case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {
unfold writes at hw ⊢,
simp only [finset.mem_union] at hw ⊢,
replace IH₁ := IH₁ hs.1 (λ q hq, hw q (or.inl hq)),
replace IH₂ := IH₂ hs.2 (λ q hq, hw q (or.inr hq)),
exact ⟨supports_stmt_read _ (λ a, ⟨IH₁.1, IH₂.1⟩),
λ q, or.rec (IH₁.2 _) (IH₂.2 _)⟩ },
case TM1.stmt.goto : l {
refine ⟨_, λ _, false.elim⟩,
refine supports_stmt_read _ (λ a _ s, _),
exact finset.mem_bind.2 ⟨_, hs _ _, finset.mem_insert_self _ _⟩ },
case TM1.stmt.halt {
refine ⟨_, λ _, false.elim⟩,
simp only [supports_stmt, supports_stmt_move, tr_normal] }
end⟩
end
end TM1to1
/-!
## TM0 emulator in TM1
To establish that TM0 and TM1 are equivalent computational models, we must also have a TM0 emulator
in TM1. The main complication here is that TM0 allows an action to depend on the value at the head
and local state, while TM1 doesn't (in order to have more programming language-like semantics).
So we use a computed `goto` to go to a state that performes the desired action and then returns to
normal execution.
One issue with this is that the `halt` instruction is supposed to halt immediately, not take a step
to a halting state. To resolve this we do a check for `halt` first, then `goto` (with an
unreachable branch).
-/
namespace TM0to1
section
parameters {Γ : Type*} [inhabited Γ]
parameters {Λ : Type*} [inhabited Λ]
/-- The machine states for a TM1 emulating a TM0 machine. States of the TM0 machine are embedded
as `normal q` states, but the actual operation is split into two parts, a jump to `act s q`
followed by the action and a jump to the next `normal` state. -/
inductive Λ'
| normal : Λ → Λ'
| act : TM0.stmt Γ → Λ → Λ'
instance : inhabited Λ' := ⟨Λ'.normal (default _)⟩
local notation `cfg₀` := TM0.cfg Γ Λ
local notation `stmt₁` := TM1.stmt Γ Λ' unit
local notation `cfg₁` := TM1.cfg Γ Λ' unit
parameters (M : TM0.machine Γ Λ)
open TM1.stmt
/-- The program. -/
def tr : Λ' → stmt₁
| (Λ'.normal q) :=
branch (λ a _, (M q a).is_none) halt $
goto (λ a _, match M q a with
| none := default _ -- unreachable
| some (q', s) := Λ'.act s q'
end)
| (Λ'.act (TM0.stmt.move d) q) := move d $ goto (λ _ _, Λ'.normal q)
| (Λ'.act (TM0.stmt.write a) q) := write (λ _ _, a) $ goto (λ _ _, Λ'.normal q)
/-- The configuration translation. -/
def tr_cfg : cfg₀ → cfg₁
| ⟨q, T⟩ := ⟨cond (M q T.1).is_some (some (Λ'.normal q)) none, (), T⟩
theorem tr_respects : respects (TM0.step M) (TM1.step tr)
(λ a b, tr_cfg a = b) :=
fun_respects.2 $ λ ⟨q, T⟩, begin
cases e : M q T.1,
{ simp only [TM0.step, tr_cfg, e]; exact eq.refl none },
cases val with q' s,
simp only [frespects, TM0.step, tr_cfg, e, option.is_some, cond, option.map_some'],
have : TM1.step (tr M) ⟨some (Λ'.act s q'), (), T⟩ =
some ⟨some (Λ'.normal q'), (), TM0.step._match_1 T s⟩,
{ cases s with d a; refl },
refine trans_gen.head _ (trans_gen.head' this _),
{ unfold TM1.step TM1.step_aux tr has_mem.mem,
rw e, refl },
cases e' : M q' _,
{ apply refl_trans_gen.single,
unfold TM1.step TM1.step_aux tr has_mem.mem,
rw e', refl },
{ refl }
end
end
end TM0to1
/-!
## The TM2 model
The TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite)
collection of stacks, each with elements of different types (the alphabet of stack `k : K` is
`Γ k`). The statements are:
* `push k (f : σ → Γ k) q` puts `f a` on the `k`-th stack, then does `q`.
* `pop k (f : σ → option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the
value of the `k`-th stack, and removes this element from the stack, then does `q`.
* `peek k (f : σ → option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the
value of the `k`-th stack, then does `q`.
* `load (f : σ → σ) q` reads nothing but applies `f` to the internal state, then does `q`.
* `branch (f : σ → bool) qtrue qfalse` does `qtrue` or `qfalse` according to `f a`.
* `goto (f : σ → Λ)` jumps to label `f a`.
* `halt` halts on the next step.
The configuration is a tuple `(l, var, stk)` where `l : option Λ` is the current label to run or
`none` for the halting state, `var : σ` is the (finite) internal state, and `stk : ∀ k, list (Γ k)`
is the collection of stacks. (Note that unlike the `TM0` and `TM1` models, these are not
`list_blank`s, they have definite ends that can be detected by the `pop` command.)
Given a designated stack `k` and a value `L : list (Γ k)`, the initial configuration has all the
stacks empty except the designated "input" stack; in `eval` this designated stack also functions
as the output stack.
-/
namespace TM2
section
parameters {K : Type*} [decidable_eq K] -- Index type of stacks
parameters (Γ : K → Type*) -- Type of stack elements
parameters (Λ : Type*) -- Type of function labels
parameters (σ : Type*) -- Type of variable settings
/-- The TM2 model removes the tape entirely from the TM1 model,
replacing it with an arbitrary (finite) collection of stacks.
The operation `push` puts an element on one of the stacks,
and `pop` removes an element from a stack (and modifying the
internal state based on the result). `peek` modifies the
internal state but does not remove an element. -/
inductive stmt
| push : ∀ k, (σ → Γ k) → stmt → stmt
| peek : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt
| pop : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt
| load : (σ → σ) → stmt → stmt
| branch : (σ → bool) → stmt → stmt → stmt
| goto : (σ → Λ) → stmt
| halt : stmt
open stmt
instance stmt.inhabited : inhabited stmt := ⟨halt⟩
/-- A configuration in the TM2 model is a label (or `none` for the halt state), the state of
local variables, and the stacks. (Note that the stacks are not `list_blank`s, they have a definite
size.) -/
structure cfg :=
(l : option Λ)
(var : σ)
(stk : ∀ k, list (Γ k))
instance cfg.inhabited [inhabited σ] : inhabited cfg := ⟨⟨default _, default _, default _⟩⟩
parameters {Γ Λ σ K}
/-- The step function for the TM2 model. -/
@[simp] def step_aux : stmt → σ → (∀ k, list (Γ k)) → cfg
| (push k f q) v S := step_aux q v (update S k (f v :: S k))
| (peek k f q) v S := step_aux q (f v (S k).head') S
| (pop k f q) v S := step_aux q (f v (S k).head') (update S k (S k).tail)
| (load a q) v S := step_aux q (a v) S
| (branch f q₁ q₂) v S :=
cond (f v) (step_aux q₁ v S) (step_aux q₂ v S)
| (goto f) v S := ⟨some (f v), v, S⟩
| halt v S := ⟨none, v, S⟩
/-- The step function for the TM2 model. -/
@[simp] def step (M : Λ → stmt) : cfg → option cfg
| ⟨none, v, S⟩ := none
| ⟨some l, v, S⟩ := some (step_aux (M l) v S)
/-- The (reflexive) reachability relation for the TM2 model. -/
def reaches (M : Λ → stmt) : cfg → cfg → Prop :=
refl_trans_gen (λ a b, b ∈ step M a)
/-- Given a set `S` of states, `support_stmt S q` means that `q` only jumps to states in `S`. -/
def supports_stmt (S : finset Λ) : stmt → Prop
| (push k f q) := supports_stmt q
| (peek k f q) := supports_stmt q
| (pop k f q) := supports_stmt q
| (load a q) := supports_stmt q
| (branch f q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂
| (goto l) := ∀ v, l v ∈ S
| halt := true
open_locale classical
/-- The set of subtree statements in a statement. -/
noncomputable def stmts₁ : stmt → finset stmt
| Q@(push k f q) := insert Q (stmts₁ q)
| Q@(peek k f q) := insert Q (stmts₁ q)
| Q@(pop k f q) := insert Q (stmts₁ q)
| Q@(load a q) := insert Q (stmts₁ q)
| Q@(branch f q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂)
| Q@(goto l) := {Q}
| Q@halt := {Q}
theorem stmts₁_self {q} : q ∈ stmts₁ q :=
by cases q; apply_rules [finset.mem_insert_self, finset.mem_singleton_self]
theorem stmts₁_trans {q₁ q₂} :
q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ :=
begin
intros h₁₂ q₀ h₀₁,
induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH;
simp only [stmts₁] at h₁₂ ⊢;
simp only [finset.mem_insert, finset.mem_singleton, finset.mem_union] at h₁₂,
iterate 4 {
rcases h₁₂ with rfl | h₁₂,
{ unfold stmts₁ at h₀₁, exact h₀₁ },
{ exact finset.mem_insert_of_mem (IH h₁₂) } },
case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ {
rcases h₁₂ with rfl | h₁₂ | h₁₂,
{ unfold stmts₁ at h₀₁, exact h₀₁ },
{ exact finset.mem_insert_of_mem (finset.mem_union_left _ (IH₁ h₁₂)) },
{ exact finset.mem_insert_of_mem (finset.mem_union_right _ (IH₂ h₁₂)) } },
case TM2.stmt.goto : l {
subst h₁₂, exact h₀₁ },
case TM2.stmt.halt {
subst h₁₂, exact h₀₁ }
end
theorem stmts₁_supports_stmt_mono {S q₁ q₂}
(h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ :=
begin
induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH;
simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union,
finset.mem_singleton] at h hs,
iterate 4 { rcases h with rfl | h; [exact hs, exact IH h hs] },
case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ {
rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] },
case TM2.stmt.goto : l { subst h, exact hs },
case TM2.stmt.halt { subst h, trivial }
end
/-- The set of statements accessible from initial set `S` of labels. -/
noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) :=
(S.bind (λ q, stmts₁ (M q))).insert_none
theorem stmts_trans {M : Λ → stmt} {S q₁ q₂}
(h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S :=
by simp only [stmts, finset.mem_insert_none, finset.mem_bind,
option.mem_def, forall_eq', exists_imp_distrib];
exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩
variable [inhabited Λ]
/-- Given a TM2 machine `M` and a set `S` of states, `supports M S` means that all states in
`S` jump only to other states in `S`. -/
def supports (M : Λ → stmt) (S : finset Λ) :=
default Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q)
theorem stmts_supports_stmt {M : Λ → stmt} {S q}
(ss : supports M S) : some q ∈ stmts M S → supports_stmt S q :=
by simp only [stmts, finset.mem_insert_none, finset.mem_bind,
option.mem_def, forall_eq', exists_imp_distrib];
exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls)
theorem step_supports (M : Λ → stmt) {S}
(ss : supports M S) : ∀ {c c' : cfg},
c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none
| ⟨some l₁, v, T⟩ c' h₁ h₂ := begin
replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂),
simp only [step, option.mem_def] at h₁, subst c',
revert h₂, induction M l₁ with _ _ q IH _ _ q IH _ _ q IH _ q IH generalizing v T;
intro hs,
iterate 4 { exact IH _ _ hs },
case TM2.stmt.branch : p q₁' q₂' IH₁ IH₂ {
unfold step_aux, cases p v,
{ exact IH₂ _ _ hs.2 },
{ exact IH₁ _ _ hs.1 } },
case TM2.stmt.goto { exact finset.some_mem_insert_none.2 (hs _) },
case TM2.stmt.halt { apply multiset.mem_cons_self }
end
variable [inhabited σ]
/-- The initial state of the TM2 model. The input is provided on a designated stack. -/
def init (k) (L : list (Γ k)) : cfg :=
⟨some (default _), default _, update (λ _, []) k L⟩
/-- Evaluates a TM2 program to completion, with the output on the same stack as the input. -/
def eval (M : Λ → stmt) (k) (L : list (Γ k)) : roption (list (Γ k)) :=
(eval (step M) (init k L)).map $ λ c, c.stk k
end
end TM2
/-!
## TM2 emulator in TM1
To prove that TM2 computable functions are TM1 computable, we need to reduce each TM2 program to a
TM1 program. So suppose a TM2 program is given. This program has to maintain a whole collection of
stacks, but we have only one tape, so we must "multiplex" them all together. Pictorially, if stack
1 contains `[a, b]` and stack 2 contains `[c, d, e, f]` then the tape looks like this:
```
bottom: ... | _ | T | _ | _ | _ | _ | ...
stack 1: ... | _ | b | a | _ | _ | _ | ...
stack 2: ... | _ | f | e | d | c | _ | ...
```
where a tape element is a vertical slice through the diagram. Here the alphabet is
`Γ' := bool × ∀ k, option (Γ k)`, where:
* `bottom : bool` is marked only in one place, the initial position of the TM, and represents the
tail of all stacks. It is never modified.
* `stk k : option (Γ k)` is the value of the `k`-th stack, if in range, otherwise `none` (which is
the blank value). Note that the head of the stack is at the far end; this is so that push and pop
don't have to do any shifting.
In "resting" position, the TM is sitting at the position marked `bottom`. For non-stack actions,
it operates in place, but for the stack actions `push`, `peek`, and `pop`, it must shuttle to the
end of the appropriate stack, make its changes, and then return to the bottom. So the states are:
* `normal (l : Λ)`: waiting at `bottom` to execute function `l`
* `go k (s : st_act k) (q : stmt₂)`: travelling to the right to get to the end of stack `k` in
order to perform stack action `s`, and later continue with executing `q`
* `ret (q : stmt₂)`: travelling to the left after having performed a stack action, and executing
`q` once we arrive
Because of the shuttling, emulation overhead is `O(n)`, where `n` is the current maximum of the
length of all stacks. Therefore a program that takes `k` steps to run in TM2 takes `O((m+k)k)`
steps to run when emulated in TM1, where `m` is the length of the input.
-/
namespace TM2to1
-- A displaced lemma proved in unnecessary generality
theorem stk_nth_val {K : Type*} {Γ : K → Type*} {L : list_blank (∀ k, option (Γ k))} {k S} (n)
(hL : list_blank.map (proj k) L = list_blank.mk (list.map some S).reverse) :
L.nth n k = S.reverse.nth n :=
begin
rw [← proj_map_nth, hL, ← list.map_reverse, list_blank.nth_mk, list.inth, list.nth_map],
cases S.reverse.nth n; refl
end
section
parameters {K : Type*} [decidable_eq K]
parameters {Γ : K → Type*}
parameters {Λ : Type*} [inhabited Λ]
parameters {σ : Type*} [inhabited σ]
local notation `stmt₂` := TM2.stmt Γ Λ σ
local notation `cfg₂` := TM2.cfg Γ Λ σ
/-- The alphabet of the TM2 simulator on TM1 is a marker for the stack bottom,
plus a vector of stack elements for each stack, or none if the stack does not extend this far. -/
@[nolint unused_arguments] -- [decidable_eq K]: Because K is a parameter, we cannot easily skip
-- the decidable_eq assumption, and this is a local definition anyway so it's not important.
def Γ' := bool × ∀ k, option (Γ k)
instance Γ'.inhabited : inhabited Γ' := ⟨⟨ff, λ _, none⟩⟩
instance Γ'.fintype [fintype K] [∀ k, fintype (Γ k)] : fintype Γ' :=
prod.fintype _ _
/-- The bottom marker is fixed throughout the calculation, so we use the `add_bottom` function
to express the program state in terms of a tape with only the stacks themselves. -/
def add_bottom (L : list_blank (∀ k, option (Γ k))) : list_blank Γ' :=
list_blank.cons (tt, L.head) (L.tail.map ⟨prod.mk ff, rfl⟩)
theorem add_bottom_map (L) : (add_bottom L).map ⟨prod.snd, rfl⟩ = L :=
begin
simp only [add_bottom, list_blank.map_cons]; convert list_blank.cons_head_tail _,
generalize : list_blank.tail L = L',
refine L'.induction_on _, intro l, simp,
rw (_ : _ ∘ _ = id), {simp},
funext a, refl
end
theorem add_bottom_modify_nth (f : (∀ k, option (Γ k)) → (∀ k, option (Γ k))) (L n) :
(add_bottom L).modify_nth (λ a, (a.1, f a.2)) n = add_bottom (L.modify_nth f n) :=
begin
cases n; simp only [add_bottom,
list_blank.head_cons, list_blank.modify_nth, list_blank.tail_cons],
congr, symmetry, apply list_blank.map_modify_nth, intro, refl
end
theorem add_bottom_nth_snd (L n) : ((add_bottom L).nth n).2 = L.nth n :=
by conv {to_rhs, rw [← add_bottom_map L, list_blank.nth_map]}; refl
theorem add_bottom_nth_succ_fst (L n) : ((add_bottom L).nth (n+1)).1 = ff :=
by rw [list_blank.nth_succ, add_bottom, list_blank.tail_cons, list_blank.nth_map]; refl
theorem add_bottom_head_fst (L) : (add_bottom L).head.1 = tt :=
by rw [add_bottom, list_blank.head_cons]; refl
/-- A stack action is a command that interacts with the top of a stack. Our default position
is at the bottom of all the stacks, so we have to hold on to this action while going to the end
to modify the stack. -/
inductive st_act (k : K)
| push : (σ → Γ k) → st_act
| peek : (σ → option (Γ k) → σ) → st_act
| pop : (σ → option (Γ k) → σ) → st_act
instance st_act.inhabited {k} : inhabited (st_act k) := ⟨st_act.peek (λ s _, s)⟩
section
open st_act
/-- The TM2 statement corresponding to a stack action. -/
@[nolint unused_arguments] -- [inhabited Λ]: as this is a local definition it is more trouble than
-- it is worth to omit the typeclass assumption without breaking the parameters
def st_run {k : K} : st_act k → stmt₂ → stmt₂
| (push f) := TM2.stmt.push k f
| (peek f) := TM2.stmt.peek k f
| (pop f) := TM2.stmt.pop k f
/-- The effect of a stack action on the local variables, given the value of the stack. -/
def st_var {k : K} (v : σ) (l : list (Γ k)) : st_act k → σ
| (push f) := v
| (peek f) := f v l.head'
| (pop f) := f v l.head'
/-- The effect of a stack action on the stack. -/
def st_write {k : K} (v : σ) (l : list (Γ k)) : st_act k → list (Γ k)
| (push f) := f v :: l
| (peek f) := l
| (pop f) := l.tail
/-- We have partitioned the TM2 statements into "stack actions", which require going to the end
of the stack, and all other actions, which do not. This is a modified recursor which lumps the
stack actions into one. -/
@[elab_as_eliminator] def {l} stmt_st_rec
{C : stmt₂ → Sort l}
(H₁ : Π k (s : st_act k) q (IH : C q), C (st_run s q))
(H₂ : Π a q (IH : C q), C (TM2.stmt.load a q))
(H₃ : Π p q₁ q₂ (IH₁ : C q₁) (IH₂ : C q₂), C (TM2.stmt.branch p q₁ q₂))
(H₄ : Π l, C (TM2.stmt.goto l))
(H₅ : C TM2.stmt.halt) : ∀ n, C n
| (TM2.stmt.push k f q) := H₁ _ (push f) _ (stmt_st_rec q)
| (TM2.stmt.peek k f q) := H₁ _ (peek f) _ (stmt_st_rec q)
| (TM2.stmt.pop k f q) := H₁ _ (pop f) _ (stmt_st_rec q)
| (TM2.stmt.load a q) := H₂ _ _ (stmt_st_rec q)
| (TM2.stmt.branch a q₁ q₂) := H₃ _ _ _ (stmt_st_rec q₁) (stmt_st_rec q₂)
| (TM2.stmt.goto l) := H₄ _
| TM2.stmt.halt := H₅
theorem supports_run (S : finset Λ) {k} (s : st_act k) (q) :
TM2.supports_stmt S (st_run s q) ↔ TM2.supports_stmt S q :=
by rcases s with _|_|_; refl
end
/-- The machine states of the TM2 emulator. We can either be in a normal state when waiting for the
next TM2 action, or we can be in the "go" and "return" states to go to the top of the stack and
return to the bottom, respectively. -/
inductive Λ' : Type (max u_1 u_2 u_3 u_4)
| normal : Λ → Λ'
| go (k) : st_act k → stmt₂ → Λ'
| ret : stmt₂ → Λ'
open Λ'
instance Λ'.inhabited : inhabited Λ' := ⟨normal (default _)⟩
local notation `stmt₁` := TM1.stmt Γ' Λ' σ
local notation `cfg₁` := TM1.cfg Γ' Λ' σ
open TM1.stmt
/-- The program corresponding to state transitions at the end of a stack. Here we start out just
after the top of the stack, and should end just after the new top of the stack. -/
def tr_st_act {k} (q : stmt₁) : st_act k → stmt₁
| (st_act.push f) := write (λ a s, (a.1, update a.2 k $ some $ f s)) $ move dir.right q
| (st_act.peek f) := move dir.left $ load (λ a s, f s (a.2 k)) $ move dir.right q
| (st_act.pop f) :=
branch (λ a _, a.1)
( load (λ a s, f s none) q )
( move dir.left $
load (λ a s, f s (a.2 k)) $
write (λ a s, (a.1, update a.2 k none)) q )
/-- The initial state for the TM2 emulator, given an initial TM2 state. All stacks start out empty
except for the input stack, and the stack bottom mark is set at the head. -/
def tr_init (k) (L : list (Γ k)) : list Γ' :=
let L' : list Γ' := L.reverse.map (λ a, (ff, update (λ _, none) k a)) in
(tt, L'.head.2) :: L'.tail
theorem step_run {k : K} (q v S) : ∀ s : st_act k,
TM2.step_aux (st_run s q) v S =
TM2.step_aux q (st_var v (S k) s) (update S k (st_write v (S k) s))
| (st_act.push f) := rfl
| (st_act.peek f) := by unfold st_write; rw function.update_eq_self; refl
| (st_act.pop f) := rfl
/-- The translation of TM2 statements to TM1 statements. regular actions have direct equivalents,
but stack actions are deferred by going to the corresponding `go` state, so that we can find the
appropriate stack top. -/
def tr_normal : stmt₂ → stmt₁
| (TM2.stmt.push k f q) := goto (λ _ _, go k (st_act.push f) q)
| (TM2.stmt.peek k f q) := goto (λ _ _, go k (st_act.peek f) q)
| (TM2.stmt.pop k f q) := goto (λ _ _, go k (st_act.pop f) q)
| (TM2.stmt.load a q) := load (λ _, a) (tr_normal q)
| (TM2.stmt.branch f q₁ q₂) := branch (λ a, f) (tr_normal q₁) (tr_normal q₂)
| (TM2.stmt.goto l) := goto (λ a s, normal (l s))
| TM2.stmt.halt := halt
theorem tr_normal_run {k} (s q) : tr_normal (st_run s q) = goto (λ _ _, go k s q) :=
by rcases s with _|_|_; refl
open_locale classical
/-- The set of machine states accessible from an initial TM2 statement. -/
noncomputable def tr_stmts₁ : stmt₂ → finset Λ'
| Q@(TM2.stmt.push k f q) := {go k (st_act.push f) q, ret q} ∪ tr_stmts₁ q
| Q@(TM2.stmt.peek k f q) := {go k (st_act.peek f) q, ret q} ∪ tr_stmts₁ q
| Q@(TM2.stmt.pop k f q) := {go k (st_act.pop f) q, ret q} ∪ tr_stmts₁ q
| Q@(TM2.stmt.load a q) := tr_stmts₁ q
| Q@(TM2.stmt.branch f q₁ q₂) := tr_stmts₁ q₁ ∪ tr_stmts₁ q₂
| _ := ∅
theorem tr_stmts₁_run {k s q} : tr_stmts₁ (st_run s q) = {go k s q, ret q} ∪ tr_stmts₁ q :=
by rcases s with _|_|_; unfold tr_stmts₁ st_run
theorem tr_respects_aux₂
{k q v} {S : Π k, list (Γ k)} {L : list_blank (∀ k, option (Γ k))}
(hL : ∀ k, L.map (proj k) = list_blank.mk ((S k).map some).reverse) (o) :
let v' := st_var v (S k) o,
Sk' := st_write v (S k) o,
S' := update S k Sk' in
∃ (L' : list_blank (∀ k, option (Γ k))),
(∀ k, L'.map (proj k) = list_blank.mk ((S' k).map some).reverse) ∧
TM1.step_aux (tr_st_act q o) v
((tape.move dir.right)^[(S k).length] (tape.mk' ∅ (add_bottom L))) =
TM1.step_aux q v'
((tape.move dir.right)^[(S' k).length] (tape.mk' ∅ (add_bottom L'))) :=
begin
dsimp only, simp, cases o;
simp only [st_write, st_var, tr_st_act, TM1.step_aux],
case TM2to1.st_act.push : f {
have := tape.write_move_right_n (λ a : Γ', (a.1, update a.2 k (some (f v)))),
dsimp only at this,
refine ⟨_, λ k', _, by rw [
tape.move_right_n_head, list.length, tape.mk'_nth_nat, this,
add_bottom_modify_nth (λ a, update a k (some (f v))),
nat.add_one, iterate_succ']⟩,
refine list_blank.ext (λ i, _),
rw [list_blank.nth_map, list_blank.nth_modify_nth, proj, pointed_map.mk_val],
by_cases h' : k' = k,
{ subst k', split_ifs; simp only [list.reverse_cons,
function.update_same, list_blank.nth_mk, list.inth, list.map],
{ rw [list.nth_le_nth, list.nth_le_append_right];
simp only [h, list.nth_le_singleton, list.length_map, list.length_reverse, nat.succ_pos',
list.length_append, lt_add_iff_pos_right, list.length] },
rw [← proj_map_nth, hL, list_blank.nth_mk, list.inth],
cases decidable.lt_or_gt_of_ne h with h h,
{ rw list.nth_append, simpa only [list.length_map, list.length_reverse] using h },
{ rw [list.nth_len_le, list.nth_len_le];
simp only [nat.add_one_le_iff, h, list.length, le_of_lt,
list.length_reverse, list.length_append, list.length_map] } },
{ split_ifs; rw [function.update_noteq h', ← proj_map_nth, hL],
rw function.update_noteq h' } },
case TM2to1.st_act.peek : f {
rw function.update_eq_self,
use [L, hL], rw [tape.move_left_right], congr,
cases e : S k, {refl},
rw [list.length_cons, iterate_succ', tape.move_right_left, tape.move_right_n_head,
tape.mk'_nth_nat, add_bottom_nth_snd, stk_nth_val _ (hL k), e,
list.reverse_cons, ← list.length_reverse, list.nth_concat_length], refl },
case TM2to1.st_act.pop : f {
cases e : S k,
{ simp only [tape.mk'_head, list_blank.head_cons, tape.move_left_mk',
list.length, tape.write_mk', list.head', iterate_zero_apply, list.tail_nil],
rw [← e, function.update_eq_self], exact ⟨L, hL, by rw [add_bottom_head_fst, cond]⟩ },
{ refine ⟨_, λ k', _, by rw [
list.length_cons, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_succ_fst,
cond, iterate_succ', tape.move_right_left, tape.move_right_n_head, tape.mk'_nth_nat,
tape.write_move_right_n (λ a:Γ', (a.1, update a.2 k none)),
add_bottom_modify_nth (λ a, update a k none),
add_bottom_nth_snd, stk_nth_val _ (hL k), e,
show (list.cons hd tl).reverse.nth tl.length = some hd,
by rw [list.reverse_cons, ← list.length_reverse, list.nth_concat_length]; refl,
list.head', list.tail]⟩,
refine list_blank.ext (λ i, _),
rw [list_blank.nth_map, list_blank.nth_modify_nth, proj, pointed_map.mk_val],
by_cases h' : k' = k,
{ subst k', split_ifs; simp only [
function.update_same, list_blank.nth_mk, list.tail, list.inth],
{ rw [list.nth_len_le], {refl}, rw [h, list.length_reverse, list.length_map] },
rw [← proj_map_nth, hL, list_blank.nth_mk, list.inth, e, list.map, list.reverse_cons],
cases decidable.lt_or_gt_of_ne h with h h,
{ rw list.nth_append, simpa only [list.length_map, list.length_reverse] using h },
{ rw [list.nth_len_le, list.nth_len_le];
simp only [nat.add_one_le_iff, h, list.length, le_of_lt,
list.length_reverse, list.length_append, list.length_map] } },
{ split_ifs; rw [function.update_noteq h', ← proj_map_nth, hL],
rw function.update_noteq h' } } },
end
parameters (M : Λ → stmt₂)
include M
/-- The TM2 emulator machine states written as a TM1 program.
This handles the `go` and `ret` states, which shuttle to and from a stack top. -/
def tr : Λ' → stmt₁
| (normal q) := tr_normal (M q)
| (go k s q) :=
branch (λ a s, (a.2 k).is_none) (tr_st_act (goto (λ _ _, ret q)) s)
(move dir.right $ goto (λ _ _, go k s q))
| (ret q) :=
branch (λ a s, a.1) (tr_normal q)
(move dir.left $ goto (λ _ _, ret q))
local attribute [pp_using_anonymous_constructor] turing.TM1.cfg
/-- The relation between TM2 configurations and TM1 configurations of the TM2 emulator. -/
inductive tr_cfg : cfg₂ → cfg₁ → Prop
| mk {q v} {S : ∀ k, list (Γ k)} (L : list_blank (∀ k, option (Γ k))) :
(∀ k, L.map (proj k) = list_blank.mk ((S k).map some).reverse) →
tr_cfg ⟨q, v, S⟩ ⟨q.map normal, v, tape.mk' ∅ (add_bottom L)⟩
theorem tr_respects_aux₁ {k} (o q v) {S : list (Γ k)} {L : list_blank (∀ k, option (Γ k))}
(hL : L.map (proj k) = list_blank.mk (S.map some).reverse) (n ≤ S.length) :
reaches₀ (TM1.step tr)
⟨some (go k o q), v, (tape.mk' ∅ (add_bottom L))⟩
⟨some (go k o q), v, (tape.move dir.right)^[n] (tape.mk' ∅ (add_bottom L))⟩ :=
begin
induction n with n IH, {refl},
apply (IH (le_of_lt H)).tail,
rw iterate_succ_apply', simp only [TM1.step, TM1.step_aux, tr,
tape.mk'_nth_nat, tape.move_right_n_head, add_bottom_nth_snd,
option.mem_def],
rw [stk_nth_val _ hL, list.nth_le_nth], refl, rwa list.length_reverse
end
theorem tr_respects_aux₃ {q v} {L : list_blank (∀ k, option (Γ k))} (n) :
reaches₀ (TM1.step tr)
⟨some (ret q), v, (tape.move dir.right)^[n] (tape.mk' ∅ (add_bottom L))⟩
⟨some (ret q), v, (tape.mk' ∅ (add_bottom L))⟩ :=
begin
induction n with n IH, {refl},
refine reaches₀.head _ IH,
rw [option.mem_def, TM1.step, tr, TM1.step_aux, tape.move_right_n_head, tape.mk'_nth_nat,
add_bottom_nth_succ_fst, TM1.step_aux, iterate_succ', tape.move_right_left], refl,
end
theorem tr_respects_aux {q v T k} {S : Π k, list (Γ k)}
(hT : ∀ k, list_blank.map (proj k) T = list_blank.mk ((S k).map some).reverse)
(o : st_act k)
(IH : ∀ {v : σ} {S : Π (k : K), list (Γ k)} {T : list_blank (∀ k, option (Γ k))},
(∀ k, list_blank.map (proj k) T = list_blank.mk ((S k).map some).reverse) →
(∃ b, tr_cfg (TM2.step_aux q v S) b ∧
reaches (TM1.step tr) (TM1.step_aux (tr_normal q) v (tape.mk' ∅ (add_bottom T))) b)) :
∃ b, tr_cfg (TM2.step_aux (st_run o q) v S) b ∧
reaches (TM1.step tr) (TM1.step_aux (tr_normal (st_run o q))
v (tape.mk' ∅ (add_bottom T))) b :=
begin
simp only [tr_normal_run, step_run],
have hgo := tr_respects_aux₁ M o q v (hT k) _ (le_refl _),
obtain ⟨T', hT', hrun⟩ := tr_respects_aux₂ hT o,
have hret := tr_respects_aux₃ M _,
have := hgo.tail' rfl,
rw [tr, TM1.step_aux, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_snd,
stk_nth_val _ (hT k), list.nth_len_le (le_of_eq (list.length_reverse _)),
option.is_none, cond, hrun, TM1.step_aux] at this,
obtain ⟨c, gc, rc⟩ := IH hT',
refine ⟨c, gc, (this.to₀.trans hret c (trans_gen.head' rfl _)).to_refl⟩,
rw [tr, TM1.step_aux, tape.mk'_head, add_bottom_head_fst],
exact rc,
end
local attribute [simp] respects TM2.step TM2.step_aux tr_normal
theorem tr_respects : respects (TM2.step M) (TM1.step tr) tr_cfg :=
λ c₁ c₂ h, begin
cases h with l v S L hT, clear h,
cases l, {constructor},
simp only [TM2.step, respects, option.map_some'],
suffices : ∃ b, _ ∧ reaches (TM1.step (tr M)) _ _,
from let ⟨b, c, r⟩ := this in ⟨b, c, trans_gen.head' rfl r⟩,
rw [tr],
revert v S L hT, refine stmt_st_rec _ _ _ _ _ (M l); intros,
{ exact tr_respects_aux M hT s @IH },
{ exact IH _ hT },
{ unfold TM2.step_aux tr_normal TM1.step_aux,
cases p v; [exact IH₂ _ hT, exact IH₁ _ hT] },
{ exact ⟨_, ⟨_, hT⟩, refl_trans_gen.refl⟩ },
{ exact ⟨_, ⟨_, hT⟩, refl_trans_gen.refl⟩ }
end
theorem tr_cfg_init (k) (L : list (Γ k)) :
tr_cfg (TM2.init k L) (TM1.init (tr_init k L)) :=
begin
rw (_ : TM1.init _ = _),
{ refine ⟨list_blank.mk (L.reverse.map $ λ a, update (default _) k (some a)), λ k', _⟩,
refine list_blank.ext (λ i, _),
rw [list_blank.map_mk, list_blank.nth_mk, list.inth, list.map_map, (∘),
list.nth_map, proj, pointed_map.mk_val],
by_cases k' = k,
{ subst k', simp only [function.update_same],
rw [list_blank.nth_mk, list.inth, ← list.map_reverse, list.nth_map] },
{ simp only [function.update_noteq h],
rw [list_blank.nth_mk, list.inth, list.map, list.reverse_nil, list.nth],
cases L.reverse.nth i; refl } },
{ rw [tr_init, TM1.init], dsimp only, congr; cases L.reverse; try {refl},
simp only [list.map_map, list.tail_cons, list.map], refl }
end
theorem tr_eval_dom (k) (L : list (Γ k)) :
(TM1.eval tr (tr_init k L)).dom ↔ (TM2.eval M k L).dom :=
tr_eval_dom tr_respects (tr_cfg_init _ _)
theorem tr_eval (k) (L : list (Γ k)) {L₁ L₂}
(H₁ : L₁ ∈ TM1.eval tr (tr_init k L))
(H₂ : L₂ ∈ TM2.eval M k L) :
∃ (S : ∀ k, list (Γ k)) (L' : list_blank (∀ k, option (Γ k))),
add_bottom L' = L₁ ∧
(∀ k, L'.map (proj k) = list_blank.mk ((S k).map some).reverse) ∧
S k = L₂ :=
begin
obtain ⟨c₁, h₁, rfl⟩ := (roption.mem_map_iff _).1 H₁,
obtain ⟨c₂, h₂, rfl⟩ := (roption.mem_map_iff _).1 H₂,
obtain ⟨_, ⟨q, v, S, L', hT⟩, h₃⟩ := tr_eval (tr_respects M) (tr_cfg_init M k L) h₂,
cases roption.mem_unique h₁ h₃,
exact ⟨S, L', by simp only [tape.mk'_right₀], hT, rfl⟩
end
/-- The support of a set of TM2 states in the TM2 emulator. -/
noncomputable def tr_supp (S : finset Λ) : finset Λ' :=
S.bind (λ l, insert (normal l) (tr_stmts₁ (M l)))
theorem tr_supports {S} (ss : TM2.supports M S) :
TM1.supports tr (tr_supp S) :=
⟨finset.mem_bind.2 ⟨_, ss.1, finset.mem_insert.2 $ or.inl rfl⟩,
λ l' h, begin
suffices : ∀ q (ss' : TM2.supports_stmt S q)
(sub : ∀ x ∈ tr_stmts₁ q, x ∈ tr_supp M S),
TM1.supports_stmt (tr_supp M S) (tr_normal q) ∧
(∀ l' ∈ tr_stmts₁ q, TM1.supports_stmt (tr_supp M S) (tr M l')),
{ rcases finset.mem_bind.1 h with ⟨l, lS, h⟩,
have := this _ (ss.2 l lS) (λ x hx,
finset.mem_bind.2 ⟨_, lS, finset.mem_insert_of_mem hx⟩),
rcases finset.mem_insert.1 h with rfl | h;
[exact this.1, exact this.2 _ h] },
clear h l', refine stmt_st_rec _ _ _ _ _; intros,
{ -- stack op
rw TM2to1.supports_run at ss',
simp only [TM2to1.tr_stmts₁_run, finset.mem_union,
finset.mem_insert, finset.mem_singleton] at sub,
have hgo := sub _ (or.inl $ or.inl rfl),
have hret := sub _ (or.inl $ or.inr rfl),
cases IH ss' (λ x hx, sub x $ or.inr hx) with IH₁ IH₂,
refine ⟨by simp only [tr_normal_run, TM1.supports_stmt]; intros; exact hgo, λ l h, _⟩,
rw [tr_stmts₁_run] at h,
simp only [TM2to1.tr_stmts₁_run, finset.mem_union,
finset.mem_insert, finset.mem_singleton] at h,
rcases h with ⟨rfl | rfl⟩ | h,
{ unfold TM1.supports_stmt TM2to1.tr,
rcases s with _|_|_,
{ exact ⟨λ _ _, hret, λ _ _, hgo⟩ },
{ exact ⟨λ _ _, hret, λ _ _, hgo⟩ },
{ exact ⟨⟨λ _ _, hret, λ _ _, hret⟩, λ _ _, hgo⟩ } },
{ unfold TM1.supports_stmt TM2to1.tr,
exact ⟨IH₁, λ _ _, hret⟩ },
{ exact IH₂ _ h } },
{ -- load
unfold TM2to1.tr_stmts₁ at ss' sub ⊢,
exact IH ss' sub },
{ -- branch
unfold TM2to1.tr_stmts₁ at sub,
cases IH₁ ss'.1 (λ x hx, sub x $ finset.mem_union_left _ hx) with IH₁₁ IH₁₂,
cases IH₂ ss'.2 (λ x hx, sub x $ finset.mem_union_right _ hx) with IH₂₁ IH₂₂,
refine ⟨⟨IH₁₁, IH₂₁⟩, λ l h, _⟩,
rw [tr_stmts₁] at h,
rcases finset.mem_union.1 h with h | h;
[exact IH₁₂ _ h, exact IH₂₂ _ h] },
{ -- goto
rw tr_stmts₁, unfold TM2to1.tr_normal TM1.supports_stmt,
unfold TM2.supports_stmt at ss',
exact ⟨λ _ v, finset.mem_bind.2 ⟨_, ss' v, finset.mem_insert_self _ _⟩, λ _, false.elim⟩ },
{ exact ⟨trivial, λ _, false.elim⟩ } -- halt
end⟩
end
end TM2to1
end turing
|
0e95b0311692261776570f059afed50dbd9a2305 | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/tactic/ring.lean | 6c74d0d351712d2c8d0f8585fc33aa6a4181accb | [
"Apache-2.0"
] | permissive | agjftucker/mathlib | d634cd0d5256b6325e3c55bb7fb2403548371707 | 87fe50de17b00af533f72a102d0adefe4a2285e8 | refs/heads/master | 1,625,378,131,941 | 1,599,166,526,000 | 1,599,166,526,000 | 160,748,509 | 0 | 0 | Apache-2.0 | 1,544,141,789,000 | 1,544,141,789,000 | null | UTF-8 | Lean | false | false | 28,926 | 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 tactic.norm_num
import data.int.range
/-!
# `ring`
Evaluate expressions in the language of commutative (semi)rings.
Based on <http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf> .
-/
namespace tactic
namespace ring
/-- The normal form that `ring` uses is mediated by the function `horner a x n b := a * x ^ n + b`.
The reason we use a definition rather than the (more readable) expression on the right is because
this expression contains a number of typeclass arguments in different positions, while `horner`
contains only one `comm_semiring` instance at the top level. See also `horner_expr` for a
description of normal form. -/
def horner {α} [comm_semiring α] (a x : α) (n : ℕ) (b : α) := a * x ^ n + b
/-- This cache contains data required by the `ring` tactic during execution. -/
meta structure cache :=
(α : expr)
(univ : level)
(comm_semiring_inst : expr)
(red : transparency)
(ic : ref instance_cache)
(nc : ref instance_cache)
(atoms : ref (buffer expr))
/-- The monad that `ring` works in. This is a reader monad containing a mutable cache (using `ref`
for mutability), as well as the list of atoms-up-to-defeq encountered thus far, used for atom
sorting. -/
@[derive [monad, alternative]]
meta def ring_m (α : Type) : Type :=
reader_t cache tactic α
/-- Get the `ring` data from the monad. -/
meta def get_cache : ring_m cache := reader_t.read
/-- Get an already encountered atom by its index. -/
meta def get_atom (n : ℕ) : ring_m expr :=
⟨λ c, do es ← read_ref c.atoms, pure (es.read' n)⟩
/-- Get the index corresponding to an atomic expression, if it has already been encountered, or
put it in the list of atoms and return the new index, otherwise. -/
meta def add_atom (e : expr) : ring_m ℕ :=
⟨λ c, do
let red := c.red,
es ← read_ref c.atoms,
es.iterate failed (λ n e' t, t <|> (is_def_eq e e' red $> n)) <|>
(es.size <$ write_ref c.atoms (es.push_back e))⟩
/-- Lift a tactic into the `ring_m` monad. -/
@[inline] meta def lift {α} (m : tactic α) : ring_m α := reader_t.lift m
/-- Run a `ring_m` tactic in the tactic monad. -/
meta def ring_m.run (red : transparency) (e : expr) {α} (m : ring_m α) : tactic α :=
do α ← infer_type e,
u ← mk_meta_univ,
infer_type α >>= unify (expr.sort (level.succ u)),
u ← get_univ_assignment u,
ic ← mk_instance_cache α,
(ic, c) ← ic.get ``comm_semiring,
nc ← mk_instance_cache `(ℕ),
using_new_ref ic $ λ r,
using_new_ref nc $ λ nr,
using_new_ref mk_buffer $ λ atoms,
reader_t.run m ⟨α, u, c, red, r, nr, atoms⟩
/-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This version
is abstract over the instance cache in question (either the ring `α`, or `ℕ` for exponents). -/
@[inline] meta def ic_lift' (icf : cache → ref instance_cache) {α}
(f : instance_cache → tactic (instance_cache × α)) : ring_m α :=
⟨λ c, do
let r := icf c,
ic ← read_ref r,
(ic', a) ← f ic,
a <$ write_ref r ic'⟩
/-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This uses
the instance cache corresponding to the ring `α`. -/
@[inline] meta def ic_lift {α} : (instance_cache → tactic (instance_cache × α)) → ring_m α :=
ic_lift' cache.ic
/-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This uses
the instance cache corresponding to `ℕ`, which is used for computations in the exponent. -/
@[inline] meta def nc_lift {α} : (instance_cache → tactic (instance_cache × α)) → ring_m α :=
ic_lift' cache.nc
/-- Apply a theorem that expects a `comm_semiring` instance. This is a special case of
`ic_lift mk_app`, but it comes up often because `horner` and all its theorems have this assumption;
it also does not require the tactic monad which improves access speed a bit. -/
meta def cache.cs_app (c : cache) (n : name) : list expr → expr :=
(@expr.const tt n [c.univ] c.α c.comm_semiring_inst).mk_app
/-- Every expression in the language of commutative semirings can be viewed as a sum of monomials,
where each monomial is a product of powers of atoms. We fix a global order on atoms (up to
definitional equality), and then separate the terms according to their smallest atom. So the top
level expression is `a * x^n + b` where `x` is the smallest atom and `n > 0` is a numeral, and
`n` is maximal (so `a` contains at least one monomial not containing an `x`), and `b` contains no
monomials with an `x` (hence all atoms in `b` are larger than `x`).
If there is no `x` satisfying these constraints, then the expression must be a numeral. Even though
we are working over rings, we allow rational constants when these can be interpreted in the ring,
so we can solve problems like `x / 3 = 1 / 3 * x` even though these are not technically in the
language of rings.
These constraints ensure that there is a unique normal form for each ring expression, and so the
algorithm is simply to calculate the normal form of each side and compare for equality.
To allow us to efficiently pattern match on normal forms, we maintain this inductive type that
holds a normalized expression together with its structure. All the `expr`s in this type could be
removed without loss of information, and conversely the `horner_expr` structure and the `ℕ` and
`ℚ` values can be recovered from the top level `expr`, but we keep both in order to keep proof
producing normalization functions efficient. -/
meta inductive horner_expr : Type
| const (e : expr) (coeff : ℚ) : horner_expr
| xadd (e : expr) (a : horner_expr) (x : expr × ℕ) (n : expr × ℕ) (b : horner_expr) : horner_expr
/-- Get the expression corresponding to a `horner_expr`. This can be calculated recursively from
the structure, but we cache the exprs in all subterms so that this function can be computed in
constant time. -/
meta def horner_expr.e : horner_expr → expr
| (horner_expr.const e _) := e
| (horner_expr.xadd e _ _ _ _) := e
/-- Is this expr the constant `0`? -/
meta def horner_expr.is_zero : horner_expr → bool
| (horner_expr.const _ c) := c = 0
| _ := ff
meta instance : has_coe horner_expr expr := ⟨horner_expr.e⟩
meta instance : has_coe_to_fun horner_expr := ⟨_, λ e, ((e : expr) : expr → expr)⟩
/-- Construct a `xadd` node, generating the cached expr using the input cache. -/
meta def horner_expr.xadd' (c : cache) (a : horner_expr)
(x : expr × ℕ) (n : expr × ℕ) (b : horner_expr) : horner_expr :=
horner_expr.xadd (c.cs_app ``horner [a, x.1, n.1, b]) a x n b
open horner_expr
/-- Pretty printer for `horner_expr`. -/
meta def horner_expr.to_string : horner_expr → string
| (const e c) := to_string (e, c)
| (xadd e a x (_, n) b) :=
"(" ++ a.to_string ++ ") * (" ++ to_string x.1 ++ ")^"
++ to_string n ++ " + " ++ b.to_string
/-- Pretty printer for `horner_expr`. -/
meta def horner_expr.pp : horner_expr → tactic format
| (const e c) := pp (e, c)
| (xadd e a x (_, n) b) := do
pa ← a.pp, pb ← b.pp, px ← pp x.1,
return $ "(" ++ pa ++ ") * (" ++ px ++ ")^" ++ to_string n ++ " + " ++ pb
meta instance : has_to_tactic_format horner_expr := ⟨horner_expr.pp⟩
/-- Reflexivity conversion for a `horner_expr`. -/
meta def horner_expr.refl_conv (e : horner_expr) : ring_m (horner_expr × expr) :=
do p ← lift $ mk_eq_refl e, return (e, p)
theorem zero_horner {α} [comm_semiring α] (x n b) :
@horner α _ 0 x n b = b :=
by simp [horner]
theorem horner_horner {α} [comm_semiring α] (a₁ x n₁ n₂ b n')
(h : n₁ + n₂ = n') :
@horner α _ (horner a₁ x n₁ 0) x n₂ b = horner a₁ x n' b :=
by simp [h.symm, horner, pow_add, mul_assoc]
/-- Evaluate `horner a n x b` where `a` and `b` are already in normal form. -/
meta def eval_horner : horner_expr → expr × ℕ → expr × ℕ → horner_expr → ring_m (horner_expr × expr)
| ha@(const a coeff) x n b := do
c ← get_cache,
if coeff = 0 then
return (b, c.cs_app ``zero_horner [x.1, n.1, b])
else (xadd' c ha x n b).refl_conv
| ha@(xadd a a₁ x₁ n₁ b₁) x n b := do
c ← get_cache,
if x₁.2 = x.2 ∧ b₁.e.to_nat = some 0 then do
(n', h) ← nc_lift $ λ nc, norm_num.prove_add_nat' nc n₁.1 n.1,
return (xadd' c a₁ x (n', n₁.2 + n.2) b,
c.cs_app ``horner_horner [a₁, x.1, n₁.1, n.1, b, n', h])
else (xadd' c ha x n b).refl_conv
theorem const_add_horner {α} [comm_semiring α] (k a x n b b') (h : k + b = b') :
k + @horner α _ a x n b = horner a x n b' :=
by simp [h.symm, horner]; cc
theorem horner_add_const {α} [comm_semiring α] (a x n b k b') (h : b + k = b') :
@horner α _ a x n b + k = horner a x n b' :=
by simp [h.symm, horner, add_assoc]
theorem horner_add_horner_lt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b')
(h₁ : n₁ + k = n₂) (h₂ : (a₁ + horner a₂ x k 0 : α) = a') (h₃ : b₁ + b₂ = b') :
@horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₁ b' :=
by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc
theorem horner_add_horner_gt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b')
(h₁ : n₂ + k = n₁) (h₂ : (horner a₁ x k 0 + a₂ : α) = a') (h₃ : b₁ + b₂ = b') :
@horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₂ b' :=
by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc
theorem horner_add_horner_eq {α} [comm_semiring α] (a₁ x n b₁ a₂ b₂ a' b' t)
(h₁ : a₁ + a₂ = a') (h₂ : b₁ + b₂ = b') (h₃ : horner a' x n b' = t) :
@horner α _ a₁ x n b₁ + horner a₂ x n b₂ = t :=
by simp [h₃.symm, h₂.symm, h₁.symm, horner, add_mul, mul_comm]; cc
/-- Evaluate `a + b` where `a` and `b` are already in normal form. -/
meta def eval_add : horner_expr → horner_expr → ring_m (horner_expr × expr)
| (const e₁ c₁) (const e₂ c₂) := ic_lift $ λ ic, do
let n := c₁ + c₂,
(ic, e) ← ic.of_rat n,
(ic, p) ← norm_num.prove_add_rat ic e₁ e₂ e c₁ c₂ n,
return (ic, const e n, p)
| he₁@(const e₁ c₁) he₂@(xadd e₂ a x n b) := do
c ← get_cache,
if c₁ = 0 then ic_lift $ λ ic, do
(ic, p) ← ic.mk_app ``zero_add [e₂],
return (ic, he₂, p)
else do
(b', h) ← eval_add he₁ b,
return (xadd' c a x n b',
c.cs_app ``const_add_horner [e₁, a, x.1, n.1, b, b', h])
| he₁@(xadd e₁ a x n b) he₂@(const e₂ c₂) := do
c ← get_cache,
if c₂ = 0 then ic_lift $ λ ic, do
(ic, p) ← ic.mk_app ``add_zero [e₁],
return (ic, he₁, p)
else do
(b', h) ← eval_add b he₂,
return (xadd' c a x n b',
c.cs_app ``horner_add_const [a, x.1, n.1, b, e₂, b', h])
| he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) := do
c ← get_cache,
if x₁.2 < x₂.2 then do
(b', h) ← eval_add b₁ he₂,
return (xadd' c a₁ x₁ n₁ b',
c.cs_app ``horner_add_const [a₁, x₁.1, n₁.1, b₁, e₂, b', h])
else if x₁.2 ≠ x₂.2 then do
(b', h) ← eval_add he₁ b₂,
return (xadd' c a₂ x₂ n₂ b',
c.cs_app ``const_add_horner [e₁, a₂, x₂.1, n₂.1, b₂, b', h])
else if n₁.2 < n₂.2 then do
let k := n₂.2 - n₁.2,
(ek, h₁) ← nc_lift (λ nc, do
(nc, ek) ← nc.of_nat k,
(nc, h₁) ← norm_num.prove_add_nat nc n₁.1 ek n₂.1,
return (nc, ek, h₁)),
α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [],
(a', h₂) ← eval_add a₁ (xadd' c a₂ x₁ (ek, k) (const α0 0)),
(b', h₃) ← eval_add b₁ b₂,
return (xadd' c a' x₁ n₁ b',
c.cs_app ``horner_add_horner_lt [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃])
else if n₁.2 ≠ n₂.2 then do
let k := n₁.2 - n₂.2,
(ek, h₁) ← nc_lift (λ nc, do
(nc, ek) ← nc.of_nat k,
(nc, h₁) ← norm_num.prove_add_nat nc n₂.1 ek n₁.1,
return (nc, ek, h₁)),
α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [],
(a', h₂) ← eval_add (xadd' c a₁ x₁ (ek, k) (const α0 0)) a₂,
(b', h₃) ← eval_add b₁ b₂,
return (xadd' c a' x₁ n₂ b',
c.cs_app ``horner_add_horner_gt [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃])
else do
(a', h₁) ← eval_add a₁ a₂,
(b', h₂) ← eval_add b₁ b₂,
(t, h₃) ← eval_horner a' x₁ n₁ b',
return (t, c.cs_app ``horner_add_horner_eq
[a₁, x₁.1, n₁.1, b₁, a₂, b₂, a', b', t, h₁, h₂, h₃])
theorem horner_neg {α} [comm_ring α] (a x n b a' b')
(h₁ : -a = a') (h₂ : -b = b') :
-@horner α _ a x n b = horner a' x n b' :=
by simp [h₂.symm, h₁.symm, horner]; cc
/-- Evaluate `-a` where `a` is already in normal form. -/
meta def eval_neg : horner_expr → ring_m (horner_expr × expr)
| (const e coeff) := do
(e', p) ← ic_lift $ λ ic, norm_num.prove_neg ic e,
return (const e' (-coeff), p)
| (xadd e a x n b) := do
c ← get_cache,
(a', h₁) ← eval_neg a,
(b', h₂) ← eval_neg b,
p ← ic_lift $ λ ic, ic.mk_app ``horner_neg [a, x.1, n.1, b, a', b', h₁, h₂],
return (xadd' c a' x n b', p)
theorem horner_const_mul {α} [comm_semiring α] (c a x n b a' b')
(h₁ : c * a = a') (h₂ : c * b = b') :
c * @horner α _ a x n b = horner a' x n b' :=
by simp [h₂.symm, h₁.symm, horner, mul_add, mul_assoc]
theorem horner_mul_const {α} [comm_semiring α] (a x n b c a' b')
(h₁ : a * c = a') (h₂ : b * c = b') :
@horner α _ a x n b * c = horner a' x n b' :=
by simp [h₂.symm, h₁.symm, horner, add_mul, mul_right_comm]
/-- Evaluate `k * a` where `k` is a rational numeral and `a` is in normal form. -/
meta def eval_const_mul (k : expr × ℚ) :
horner_expr → ring_m (horner_expr × expr)
| (const e coeff) := do
(e', p) ← ic_lift $ λ ic, norm_num.prove_mul_rat ic k.1 e k.2 coeff,
return (const e' (k.2 * coeff), p)
| (xadd e a x n b) := do
c ← get_cache,
(a', h₁) ← eval_const_mul a,
(b', h₂) ← eval_const_mul b,
return (xadd' c a' x n b',
c.cs_app ``horner_const_mul [k.1, a, x.1, n.1, b, a', b', h₁, h₂])
theorem horner_mul_horner_zero {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ aa t)
(h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa)
(h₂ : horner aa x n₂ 0 = t) :
horner a₁ x n₁ b₁ * horner a₂ x n₂ 0 = t :=
by rw [← h₂, ← h₁];
simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc]
theorem horner_mul_horner {α} [comm_semiring α]
(a₁ x n₁ b₁ a₂ n₂ b₂ aa haa ab bb t)
(h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa)
(h₂ : horner aa x n₂ 0 = haa)
(h₃ : a₁ * b₂ = ab) (h₄ : b₁ * b₂ = bb)
(H : haa + horner ab x n₁ bb = t) :
horner a₁ x n₁ b₁ * horner a₂ x n₂ b₂ = t :=
by rw [← H, ← h₂, ← h₁, ← h₃, ← h₄];
simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc]
/-- Evaluate `a * b` where `a` and `b` are in normal form. -/
meta def eval_mul : horner_expr → horner_expr → ring_m (horner_expr × expr)
| (const e₁ c₁) (const e₂ c₂) := do
(e', p) ← ic_lift $ λ ic, norm_num.prove_mul_rat ic e₁ e₂ c₁ c₂,
return (const e' (c₁ * c₂), p)
| (const e₁ c₁) e₂ :=
if c₁ = 0 then do
c ← get_cache,
α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [],
p ← ic_lift $ λ ic, ic.mk_app ``zero_mul [e₂],
return (const α0 0, p)
else if c₁ = 1 then do
p ← ic_lift $ λ ic, ic.mk_app ``one_mul [e₂],
return (e₂, p)
else eval_const_mul (e₁, c₁) e₂
| e₁ he₂@(const e₂ c₂) := do
p₁ ← ic_lift $ λ ic, ic.mk_app ``mul_comm [e₁, e₂],
(e', p₂) ← eval_mul he₂ e₁,
p ← lift $ mk_eq_trans p₁ p₂, return (e', p)
| he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) := do
c ← get_cache,
if x₁.2 < x₂.2 then do
(a', h₁) ← eval_mul a₁ he₂,
(b', h₂) ← eval_mul b₁ he₂,
return (xadd' c a' x₁ n₁ b',
c.cs_app ``horner_mul_const [a₁, x₁.1, n₁.1, b₁, e₂, a', b', h₁, h₂])
else if x₁.2 ≠ x₂.2 then do
(a', h₁) ← eval_mul he₁ a₂,
(b', h₂) ← eval_mul he₁ b₂,
return (xadd' c a' x₂ n₂ b',
c.cs_app ``horner_const_mul [e₁, a₂, x₂.1, n₂.1, b₂, a', b', h₁, h₂])
else do
(aa, h₁) ← eval_mul he₁ a₂,
α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [],
(haa, h₂) ← eval_horner aa x₁ n₂ (const α0 0),
if b₂.is_zero then
return (haa, c.cs_app ``horner_mul_horner_zero
[a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, aa, haa, h₁, h₂])
else do
(ab, h₃) ← eval_mul a₁ b₂,
(bb, h₄) ← eval_mul b₁ b₂,
(t, H) ← eval_add haa (xadd' c ab x₁ n₁ bb),
return (t, c.cs_app ``horner_mul_horner
[a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, aa, haa, ab, bb, t, h₁, h₂, h₃, h₄, H])
theorem horner_pow {α} [comm_semiring α] (a x n m n' a') (h₁ : n * m = n') (h₂ : a ^ m = a') :
@horner α _ a x n 0 ^ m = horner a' x n' 0 :=
by simp [h₁.symm, h₂.symm, horner, mul_pow, pow_mul]
theorem pow_succ {α} [comm_semiring α] (a n b c)
(h₁ : (a:α) ^ n = b) (h₂ : b * a = c) : a ^ (n + 1) = c :=
by rw [← h₂, ← h₁, pow_succ']
/-- Evaluate `a ^ n` where `a` is in normal form and `n` is a natural numeral. -/
meta def eval_pow : horner_expr → expr × ℕ → ring_m (horner_expr × expr)
| e (_, 0) := do
c ← get_cache,
α1 ← ic_lift $ λ ic, ic.mk_app ``has_one.one [],
p ← ic_lift $ λ ic, ic.mk_app ``pow_zero [e],
return (const α1 1, p)
| e (_, 1) := do
p ← ic_lift $ λ ic, ic.mk_app ``pow_one [e],
return (e, p)
| (const e coeff) (e₂, m) := ic_lift $ λ ic, do
(ic, e', p) ← norm_num.prove_pow e coeff ic e₂,
return (ic, const e' (coeff ^ m), p)
| he@(xadd e a x n b) m := do
c ← get_cache,
match b.e.to_nat with
| some 0 := do
(n', h₁) ← nc_lift $ λ nc, norm_num.prove_mul_rat nc n.1 m.1 n.2 m.2,
(a', h₂) ← eval_pow a m,
α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [],
return (xadd' c a' x (n', n.2 * m.2) (const α0 0),
c.cs_app ``horner_pow [a, x.1, n.1, m.1, n', a', h₁, h₂])
| _ := do
e₂ ← nc_lift $ λ nc, nc.of_nat (m.2-1),
(tl, hl) ← eval_pow he (e₂, m.2-1),
(t, p₂) ← eval_mul tl he,
return (t, c.cs_app ``pow_succ [e, e₂, tl, t, hl, p₂])
end
theorem horner_atom {α} [comm_semiring α] (x : α) : x = horner 1 x 1 0 :=
by simp [horner]
/-- Evaluate `a` where `a` is an atom. -/
meta def eval_atom (e : expr) : ring_m (horner_expr × expr) :=
do c ← get_cache,
i ← add_atom e,
α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [],
α1 ← ic_lift $ λ ic, ic.mk_app ``has_one.one [],
return (xadd' c (const α1 1) (e, i) (`(1), 1) (const α0 0),
c.cs_app ``horner_atom [e])
lemma subst_into_pow {α} [monoid α] (l r tl tr t)
(prl : (l : α) = tl) (prr : (r : ℕ) = tr) (prt : tl ^ tr = t) : l ^ r = t :=
by rw [prl, prr, prt]
lemma unfold_sub {α} [add_group α] (a b c : α)
(h : a + -b = c) : a - b = c := h
lemma unfold_div {α} [division_ring α] (a b c : α)
(h : a * b⁻¹ = c) : a / b = c := h
/-- Evaluate a ring expression `e` recursively to normal form, together with a proof of
equality. -/
meta def eval : expr → ring_m (horner_expr × expr)
| `(%%e₁ + %%e₂) := do
(e₁', p₁) ← eval e₁,
(e₂', p₂) ← eval e₂,
(e', p') ← eval_add e₁' e₂',
p ← ic_lift $ λ ic, ic.mk_app ``norm_num.subst_into_add [e₁, e₂, e₁', e₂', e', p₁, p₂, p'],
return (e', p)
| e@`(@has_sub.sub %%α %%P %%e₁ %%e₂) :=
mcond (succeeds (lift $ mk_app ``comm_ring [α] >>= mk_instance))
(do
e₂' ← ic_lift $ λ ic, ic.mk_app ``has_neg.neg [e₂],
e ← ic_lift $ λ ic, ic.mk_app ``has_add.add [e₁, e₂'],
(e', p) ← eval e,
p' ← ic_lift $ λ ic, ic.mk_app ``unfold_sub [e₁, e₂, e', p],
return (e', p'))
(eval_atom e)
| `(- %%e) := do
(e₁, p₁) ← eval e,
(e₂, p₂) ← eval_neg e₁,
p ← ic_lift $ λ ic, ic.mk_app ``norm_num.subst_into_neg [e, e₁, e₂, p₁, p₂],
return (e₂, p)
| `(%%e₁ * %%e₂) := do
(e₁', p₁) ← eval e₁,
(e₂', p₂) ← eval e₂,
(e', p') ← eval_mul e₁' e₂',
p ← ic_lift $ λ ic, ic.mk_app ``norm_num.subst_into_mul [e₁, e₂, e₁', e₂', e', p₁, p₂, p'],
return (e', p)
| e@`(has_inv.inv %%_) := (do
(e', p) ← lift $ norm_num.derive e <|> refl_conv e,
n ← lift $ e'.to_rat,
return (const e' n, p)) <|> eval_atom e
| e@`(@has_div.div _ %%inst %%e₁ %%e₂) := mcond
(succeeds (do
inst' ← ic_lift $ λ ic, ic.mk_app ``division_ring_has_div [],
lift $ is_def_eq inst inst'))
(do
e₂' ← ic_lift $ λ ic, ic.mk_app ``has_inv.inv [e₂],
e ← ic_lift $ λ ic, ic.mk_app ``has_mul.mul [e₁, e₂'],
(e', p) ← eval e,
p' ← ic_lift $ λ ic, ic.mk_app ``unfold_div [e₁, e₂, e', p],
return (e', p'))
(eval_atom e)
| e@`(@has_pow.pow _ _ %%P %%e₁ %%e₂) := do
(e₂', p₂) ← lift $ norm_num.derive e₂ <|> refl_conv e₂,
match e₂'.to_nat, P with
| some k, `(monoid.has_pow) := do
(e₁', p₁) ← eval e₁,
(e', p') ← eval_pow e₁' (e₂, k),
p ← ic_lift $ λ ic, ic.mk_app ``subst_into_pow [e₁, e₂, e₁', e₂', e', p₁, p₂, p'],
return (e', p)
| some k, `(nat.has_pow) := do
(e₁', p₁) ← eval e₁,
(e', p') ← eval_pow e₁' (e₂, k),
p₃ ← ic_lift $ λ ic, ic.mk_app ``subst_into_pow [e₁, e₂, e₁', e₂', e', p₁, p₂, p'],
p₄ ← lift $ mk_eq_symm $ `(nat.pow_eq_pow).mk_app [e₁, e₂],
p ← lift $ mk_eq_trans p₄ p₃,
return (e', p)
| _, _ := eval_atom e
end
| e := match e.to_nat with
| some n := (const e (rat.of_int n)).refl_conv
| none := eval_atom e
end
/-- Evaluate a ring expression `e` recursively to normal form, together with a proof of
equality. -/
meta def eval' (red : transparency) (e : expr) : tactic (expr × expr) :=
ring_m.run red e $ do (e', p) ← eval e, return (e', p)
theorem horner_def' {α} [comm_semiring α] (a x n b) : @horner α _ a x n b = x ^ n * a + b :=
by simp [horner, mul_comm]
theorem mul_assoc_rev {α} [semigroup α] (a b c : α) : a * (b * c) = a * b * c :=
by simp [mul_assoc]
theorem pow_add_rev {α} [monoid α] (a : α) (m n : ℕ) : a ^ m * a ^ n = a ^ (m + n) :=
by simp [pow_add]
theorem pow_add_rev_right {α} [monoid α] (a b : α) (m n : ℕ) : b * a ^ m * a ^ n = b * a ^ (m + n) :=
by simp [pow_add, mul_assoc]
theorem add_neg_eq_sub {α} [add_group α] (a b : α) : a + -b = a - b := rfl
/-- If `ring` fails to close the goal, it falls back on normalizing the expression to a "pretty"
form so that you can see why it failed. This setting adjusts the resulting form:
* `raw` is the form that `ring` actually uses internally, with iterated applications of `horner`.
Not very readable but useful if you don't want any postprocessing.
This results in terms like `horner (horner (horner 3 y 1 0) x 2 1) x 1 (horner 1 y 1 0)`.
* `horner` maintains the Horner form structure, but it unfolds the `horner` definition itself,
and tries to otherwise minimize parentheses.
This results in terms like `(3 * x ^ 2 * y + 1) * x + y`.
* `SOP` means sum of products form, expanding everything to monomials.
This results in terms like `3 * x ^ 3 * y + x + y`. -/
@[derive has_reflect]
inductive normalize_mode | raw | SOP | horner
instance : inhabited normalize_mode := ⟨normalize_mode.horner⟩
/-- A `ring`-based normalization simplifier that rewrites ring expressions into the specified mode.
* `raw` is the form that `ring` actually uses internally, with iterated applications of `horner`.
Not very readable but useful if you don't want any postprocessing.
This results in terms like `horner (horner (horner 3 y 1 0) x 2 1) x 1 (horner 1 y 1 0)`.
* `horner` maintains the Horner form structure, but it unfolds the `horner` definition itself,
and tries to otherwise minimize parentheses.
This results in terms like `(3 * x ^ 2 * y + 1) * x + y`.
* `SOP` means sum of products form, expanding everything to monomials.
This results in terms like `3 * x ^ 3 * y + x + y`. -/
meta def normalize (red : transparency) (mode := normalize_mode.horner) (e : expr) : tactic (expr × expr) := do
pow_lemma ← simp_lemmas.mk.add_simp ``pow_one,
let lemmas := match mode with
| normalize_mode.SOP :=
[``horner_def', ``add_zero, ``mul_one, ``mul_add, ``mul_sub,
``mul_assoc_rev, ``pow_add_rev, ``pow_add_rev_right,
``mul_neg_eq_neg_mul_symm, ``add_neg_eq_sub]
| normalize_mode.horner :=
[``horner.equations._eqn_1, ``add_zero, ``one_mul, ``pow_one,
``neg_mul_eq_neg_mul_symm, ``add_neg_eq_sub]
| _ := []
end,
lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk,
(_, e', pr) ← ext_simplify_core () {}
simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do
(new_e, pr) ← match mode with
| normalize_mode.raw := eval' red
| normalize_mode.horner := trans_conv (eval' red) (simplify lemmas [])
| normalize_mode.SOP :=
trans_conv (eval' red) $
trans_conv (simplify lemmas []) $
simp_bottom_up' (λ e, norm_num.derive e <|> pow_lemma.rewrite e)
end e,
guard (¬ new_e =ₐ e),
return ((), new_e, some pr, ff))
(λ _ _ _ _ _, failed) `eq e,
return (e', pr)
end ring
namespace interactive
open interactive interactive.types lean.parser
open tactic.ring
local postfix `?`:9001 := optional
/-- Tactic for solving equations in the language of *commutative* (semi)rings.
This version of `ring` fails if the target is not an equality
that is provable by the axioms of commutative (semi)rings. -/
meta def ring1 (red : parse (tk "!")?) : tactic unit :=
let transp := if red.is_some then semireducible else reducible in
do `(%%e₁ = %%e₂) ← target,
((e₁', p₁), (e₂', p₂)) ← ring_m.run transp e₁ $
prod.mk <$> eval e₁ <*> eval e₂,
is_def_eq e₁' e₂',
p ← mk_eq_symm p₂ >>= mk_eq_trans p₁,
tactic.exact p
/-- Parser for `ring`'s `mode` argument, which can only be the "keywords" `raw`, `horner` or `SOP`.
(Because these are not actually keywords we use a name parser and postprocess the result.) -/
meta def ring.mode : lean.parser ring.normalize_mode :=
with_desc "(SOP|raw|horner)?" $
do mode ← ident?, match mode with
| none := return ring.normalize_mode.horner
| some `horner := return ring.normalize_mode.horner
| some `SOP := return ring.normalize_mode.SOP
| some `raw := return ring.normalize_mode.raw
| _ := failed
end
/-- Tactic for solving equations in the language of *commutative* (semi)rings.
Attempts to prove the goal outright if there is no `at`
specifier and the target is an equality, but if this
fails it falls back to rewriting all ring expressions
into a normal form. When writing a normal form,
`ring SOP` will use sum-of-products form instead of horner form.
`ring!` will use a more aggressive reducibility setting to identify atoms.
Based on [Proving Equalities in a Commutative Ring Done Right
in Coq](http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf) by Benjamin Grégoire
and Assia Mahboubi.
-/
meta def ring (red : parse (tk "!")?) (SOP : parse ring.mode) (loc : parse location) : tactic unit :=
match loc with
| interactive.loc.ns [none] := instantiate_mvars_in_target >> ring1 red
| _ := failed
end <|>
do ns ← loc.get_locals,
let transp := if red.is_some then semireducible else reducible,
tt ← tactic.replace_at (normalize transp SOP) ns loc.include_goal
| fail "ring failed to simplify",
when loc.include_goal $ try tactic.reflexivity
add_hint_tactic "ring"
add_tactic_doc
{ name := "ring",
category := doc_category.tactic,
decl_names := [`tactic.interactive.ring],
tags := ["arithmetic", "simplification", "decision procedure"] }
end interactive
end tactic
namespace conv.interactive
open conv interactive
open tactic tactic.interactive (ring.mode ring1)
open tactic.ring (normalize)
local postfix `?`:9001 := optional
/--
Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic `ring`.
-/
meta def ring (red : parse (lean.parser.tk "!")?) (SOP : parse ring.mode) : conv unit :=
let transp := if red.is_some then semireducible else reducible in
discharge_eq_lhs (ring1 red)
<|> replace_lhs (normalize transp SOP)
<|> fail "ring failed to simplify"
end conv.interactive
|
99c0fd8d5ce8f2b849867c99ad82262fa66e7cd5 | af6139dd14451ab8f69cf181cf3a20f22bd699be | /library/init/meta/attribute.lean | b8479bc2c768c662a7f1d2e8c1dfce1dc5f903ee | [
"Apache-2.0"
] | permissive | gitter-badger/lean-1 | 1cca01252d3113faa45681b6a00e1b5e3a0f6203 | 5c7ade4ee4f1cdf5028eabc5db949479d6737c85 | refs/heads/master | 1,611,425,383,521 | 1,487,871,140,000 | 1,487,871,140,000 | 82,995,612 | 0 | 0 | null | 1,487,905,618,000 | 1,487,905,618,000 | null | UTF-8 | Lean | false | false | 1,587 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
-/
prelude
import init.meta.tactic init.meta.rb_map init.meta.quote
meta constant attribute.get_instances : name → tactic (list name)
meta constant attribute.fingerprint : name → tactic nat
structure user_attribute :=
(name : name)
(descr : string)
/- Registers a new user-defined attribute. The argument must be the name of a definition of type
`user_attribute` or a sub-structure. -/
meta constant attribute.register : name → command
meta structure caching_user_attribute (α : Type) extends user_attribute :=
(mk_cache : list _root_.name → tactic α)
(dependencies : list _root_.name)
meta constant caching_user_attribute.get_cache : Π {α : Type}, caching_user_attribute α → tactic α
open tactic
meta def mk_name_set_attr (attr_name : name) : command :=
do t ← to_expr ``(caching_user_attribute name_set),
v ← to_expr ``({name := %%(quote attr_name),
descr := "name_set attribute",
mk_cache := λ ns, return $ name_set.of_list ns,
dependencies := [] } : caching_user_attribute name_set),
add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff),
attribute.register attr_name
meta def get_name_set_for_attr (attr_name : name) : tactic name_set :=
do
cnst ← return (expr.const attr_name []),
attr ← eval_expr (caching_user_attribute name_set) cnst,
caching_user_attribute.get_cache attr
|
f0552eb64dc87ca8f71c3509acdc641d4c76d872 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/data/finsupp/pointwise.lean | e859af998c5f8f60b0ce963386783c5707b9e135 | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 2,433 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import data.finsupp.basic
/-!
# The pointwise product on `finsupp`.
For the convolution product on `finsupp` when the domain has a binary operation,
see the type synonyms `add_monoid_algebra`
(which is in turn used to define `polynomial` and `mv_polynomial`)
and `monoid_algebra`.
-/
noncomputable theory
open_locale classical
open finset
universes u₁ u₂ u₃ u₄ u₅
variables {α : Type u₁} {β : Type u₂} {γ : Type u₃} {δ : Type u₄} {ι : Type u₅}
namespace finsupp
/-! ### Declarations about the pointwise product on `finsupp`s -/
section
variables [mul_zero_class β]
/-- The product of `f g : α →₀ β` is the finitely supported function
whose value at `a` is `f a * g a`. -/
instance : has_mul (α →₀ β) := ⟨zip_with (*) (mul_zero 0)⟩
@[simp] lemma mul_apply {g₁ g₂ : α →₀ β} {a : α} : (g₁ * g₂) a = g₁ a * g₂ a :=
rfl
lemma support_mul {g₁ g₂ : α →₀ β} : (g₁ * g₂).support ⊆ g₁.support ∩ g₂.support :=
begin
intros a h,
simp only [mul_apply, mem_support_iff] at h,
simp only [mem_support_iff, mem_inter, ne.def],
rw ←not_or_distrib,
intro w,
apply h,
cases w; { rw w, simp },
end
instance : mul_zero_class (α →₀ β) :=
{ zero := 0,
mul := (*),
mul_zero := λ f, by { ext, simp only [mul_apply, zero_apply, mul_zero], },
zero_mul := λ f, by { ext, simp only [mul_apply, zero_apply, zero_mul], }, }
end
instance [semigroup_with_zero β] : semigroup_with_zero (α →₀ β) :=
{ mul := (*),
mul_assoc := λ f g h, by { ext, simp only [mul_apply, mul_assoc], },
..(infer_instance : mul_zero_class (α →₀ β)) }
instance [non_unital_non_assoc_semiring β] : non_unital_non_assoc_semiring (α →₀ β) :=
{ left_distrib := λ f g h, by { ext, simp only [mul_apply, add_apply, left_distrib] {proj := ff} },
right_distrib := λ f g h,
by { ext, simp only [mul_apply, add_apply, right_distrib] {proj := ff} },
..(infer_instance : mul_zero_class (α →₀ β)),
..(infer_instance : add_comm_monoid (α →₀ β)) }
instance [non_unital_semiring β] : non_unital_semiring (α →₀ β) :=
{ ..(infer_instance : semigroup (α →₀ β)),
..(infer_instance : non_unital_non_assoc_semiring (α →₀ β)) }
end finsupp
|
984bb972035361b7356308ac91779b4ef4ca48fd | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/topology/metric_space/closeds.lean | dcbfb77ea0c57a7737265fcec2b8673533337eaf | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 21,273 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import topology.metric_space.hausdorff_distance
import topology.compacts
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 topological_space ennreal
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 : ℕ → ℝ≥0∞ := λ n, (2⁻¹)^n,
have B_pos : ∀ n, (0:ℝ≥0∞) < B n,
by simp [B, ennreal.pow_pos],
have B_ne_top : ∀ n, B n ≠ ⊤,
by simp [B, 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.inv_pow, div_eq_mul_inv],
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 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 exists_between ε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.to_uniform_inducing).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 nonempty_compacts.to_closeds.uniform_embedding.embedding.is_compact_iff_is_compact_image,
rw [image_univ],
exact nonempty_compacts.is_closed_in_closeds.is_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`. -/
rcases exists_countable_dense α 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 λt, mem_closure_iff.2 (λε εpos, _),
-- t is a compact nonempty set, that we have to approximate uniformly by a a set in `v`.
rcases exists_between ε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,
rcases mem_closure_iff.1 (s_dense x) (δ/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
x.2.2.bounded y.2.2.bounded
/-- 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
|
1a66203790ef3f4be65a7ef02b30d1084ca693e8 | 08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4 | /src/Init/Data/String/Extra.lean | 02bfdee8948181ca1f7f8d335307a7cb2176ab09 | [
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"Apache-2.0",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | gebner/lean4 | d51c4922640a52a6f7426536ea669ef18a1d9af5 | 8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f | refs/heads/master | 1,685,732,780,391 | 1,672,962,627,000 | 1,673,459,398,000 | 373,307,283 | 0 | 0 | Apache-2.0 | 1,691,316,730,000 | 1,622,669,271,000 | Lean | UTF-8 | Lean | false | false | 3,326 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import Init.Control.Except
import Init.Data.ByteArray
import Init.SimpLemmas
import Init.Data.Nat.Linear
import Init.Util
import Init.WFTactics
namespace String
/-- Interpret the string as the decimal representation of a natural number.
Panics if the string is not a string of digits. -/
def toNat! (s : String) : Nat :=
if s.isNat then
s.foldl (fun n c => n*10 + (c.toNat - '0'.toNat)) 0
else
panic! "Nat expected"
/--
Convert a [UTF-8](https://en.wikipedia.org/wiki/UTF-8) encoded `ByteArray` string to `String`.
The result is unspecified if `a` is not properly UTF-8 encoded.
-/
@[extern "lean_string_from_utf8_unchecked"]
opaque fromUTF8Unchecked (a : @& ByteArray) : String
/-- Convert the given `String` to a [UTF-8](https://en.wikipedia.org/wiki/UTF-8) encoded byte array. -/
@[extern "lean_string_to_utf8"]
opaque toUTF8 (a : @& String) : ByteArray
theorem one_le_csize (c : Char) : 1 ≤ csize c := by
simp [csize, Char.utf8Size]
repeat (first | split | decide)
@[simp] theorem pos_lt_eq (p₁ p₂ : Pos) : (p₁ < p₂) = (p₁.1 < p₂.1) := rfl
@[simp] theorem pos_add_char (p : Pos) (c : Char) : (p + c).byteIdx = p.byteIdx + csize c := rfl
theorem eq_empty_of_bsize_eq_zero (h : s.endPos = {}) : s = "" := by
match s with
| ⟨[]⟩ => rfl
| ⟨c::cs⟩ =>
injection h with h
simp [endPos, utf8ByteSize, utf8ByteSize.go] at h
have : utf8ByteSize.go cs + 1 ≤ utf8ByteSize.go cs + csize c := Nat.add_le_add_left (one_le_csize c) _
simp_arith [h] at this
theorem lt_next (s : String) (i : String.Pos) : i.1 < (s.next i).1 := by
simp_arith [next]; apply one_le_csize
theorem Iterator.sizeOf_next_lt_of_hasNext (i : String.Iterator) (h : i.hasNext) : sizeOf i.next < sizeOf i := by
cases i; rename_i s pos; simp [Iterator.next, Iterator.sizeOf_eq]; simp [Iterator.hasNext] at h
have := String.lt_next s pos
apply Nat.sub.elim (motive := fun k => k < _) (utf8ByteSize s) (String.next s pos).1
. intro _ k he
simp [he]; rw [Nat.add_comm, Nat.add_sub_assoc (Nat.le_of_lt this)]
have := Nat.zero_lt_sub_of_lt this
simp_all_arith
. intro; apply Nat.zero_lt_sub_of_lt h
macro_rules | `(tactic| decreasing_trivial) => `(tactic| apply String.Iterator.sizeOf_next_lt_of_hasNext; assumption)
theorem Iterator.sizeOf_next_lt_of_atEnd (i : String.Iterator) (h : ¬ i.atEnd = true) : sizeOf i.next < sizeOf i :=
have h : i.hasNext = true := by simp_arith [atEnd] at h; simp_arith [hasNext, h]
sizeOf_next_lt_of_hasNext i h
macro_rules | `(tactic| decreasing_trivial) => `(tactic| apply String.Iterator.sizeOf_next_lt_of_atEnd; assumption)
namespace Iterator
/-- Advance the given iterator until the predicate returns true or the end of the string is reached. -/
@[specialize] def find (it : Iterator) (p : Char → Bool) : Iterator :=
if it.atEnd then it
else if p it.curr then it
else find it.next p
@[specialize] def foldUntil (it : Iterator) (init : α) (f : α → Char → Option α) : α × Iterator :=
if it.atEnd then
(init, it)
else if let some a := f init it.curr then
foldUntil it.next a f
else
(init, it)
end Iterator
end String
|
d713be0dbfeee94069a988f105a0b0a1534d2257 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/algebra/ring/boolean_ring.lean | 48516c021d21265c89c2b04548f314c73d749c9b | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 15,961 | lean | /-
Copyright (c) 2021 Bryan Gin-ge Chen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bryan Gin-ge Chen, Yaël Dillies
-/
import algebra.punit_instances
import order.hom.lattice
import tactic.abel
import tactic.ring
/-!
# Boolean rings
A Boolean ring is a ring where multiplication is idempotent. They are equivalent to Boolean
algebras.
## Main declarations
* `boolean_ring`: a typeclass for rings where multiplication is idempotent.
* `boolean_ring.to_boolean_algebra`: Turn a Boolean ring into a Boolean algebra.
* `boolean_algebra.to_boolean_ring`: Turn a Boolean algebra into a Boolean ring.
* `as_boolalg`: Type-synonym for the Boolean algebra associated to a Boolean ring.
* `as_boolring`: Type-synonym for the Boolean ring associated to a Boolean algebra.
## Implementation notes
We provide two ways of turning a Boolean algebra/ring into a Boolean ring/algebra:
* Instances on the same type accessible in locales `boolean_algebra_of_boolean_ring` and
`boolean_ring_of_boolean_algebra`.
* Type-synonyms `as_boolalg` and `as_boolring`.
At this point in time, it is not clear the first way is useful, but we keep it for educational
purposes and because it is easier than dealing with
`of_boolalg`/`to_boolalg`/`of_boolring`/`to_boolring` explicitly.
## Tags
boolean ring, boolean algebra
-/
variables {α β γ : Type*}
/-- A Boolean ring is a ring where multiplication is idempotent. -/
class boolean_ring α extends ring α :=
(mul_self : ∀ a : α, a * a = a)
section boolean_ring
variables [boolean_ring α] (a b : α)
instance : is_idempotent α (*) := ⟨boolean_ring.mul_self⟩
@[simp] lemma mul_self : a * a = a := boolean_ring.mul_self _
@[simp] lemma add_self : a + a = 0 :=
have a + a = a + a + (a + a) :=
calc a + a = (a+a) * (a+a) : by rw mul_self
... = a*a + a*a + (a*a + a*a) : by rw [add_mul, mul_add]
... = a + a + (a + a) : by rw mul_self,
by rwa self_eq_add_left at this
@[simp] lemma neg_eq : -a = a :=
calc -a = -a + 0 : by rw add_zero
... = -a + -a + a : by rw [←neg_add_self, add_assoc]
... = a : by rw [add_self, zero_add]
lemma add_eq_zero : a + b = 0 ↔ a = b :=
calc a + b = 0 ↔ a = -b : add_eq_zero_iff_eq_neg
... ↔ a = b : by rw neg_eq
@[simp] lemma mul_add_mul : a*b + b*a = 0 :=
have a + b = a + b + (a*b + b*a) :=
calc a + b = (a + b) * (a + b) : by rw mul_self
... = a*a + a*b + (b*a + b*b) : by rw [add_mul, mul_add, mul_add]
... = a + a*b + (b*a + b) : by simp only [mul_self]
... = a + b + (a*b + b*a) : by abel,
by rwa self_eq_add_right at this
@[simp] lemma sub_eq_add : a - b = a + b :=
by rw [sub_eq_add_neg, add_right_inj, neg_eq]
@[simp] lemma mul_one_add_self : a * (1 + a) = 0 := by rw [mul_add, mul_one, mul_self, add_self]
@[priority 100] -- Note [lower instance priority]
instance boolean_ring.to_comm_ring : comm_ring α :=
{ mul_comm := λ a b, by rw [←add_eq_zero, mul_add_mul],
.. (infer_instance : boolean_ring α) }
end boolean_ring
instance : boolean_ring punit := ⟨λ _, subsingleton.elim _ _⟩
/-! ### Turning a Boolean ring into a Boolean algebra -/
section ring_to_algebra
/-- Type synonym to view a Boolean ring as a Boolean algebra. -/
def as_boolalg (α : Type*) := α
/-- The "identity" equivalence between `as_boolalg α` and `α`. -/
def to_boolalg : α ≃ as_boolalg α := equiv.refl _
/-- The "identity" equivalence between `α` and `as_boolalg α`. -/
def of_boolalg : as_boolalg α ≃ α := equiv.refl _
@[simp] lemma to_boolalg_symm_eq : (@to_boolalg α).symm = of_boolalg := rfl
@[simp] lemma of_boolalg_symm_eq : (@of_boolalg α).symm = to_boolalg := rfl
@[simp] lemma to_boolalg_of_boolalg (a : as_boolalg α) : to_boolalg (of_boolalg a) = a := rfl
@[simp] lemma of_boolalg_to_boolalg (a : α) : of_boolalg (to_boolalg a) = a := rfl
@[simp] lemma to_boolalg_inj {a b : α} : to_boolalg a = to_boolalg b ↔ a = b := iff.rfl
@[simp] lemma of_boolalg_inj {a b : as_boolalg α} : of_boolalg a = of_boolalg b ↔ a = b := iff.rfl
instance [inhabited α] : inhabited (as_boolalg α) := ‹inhabited α›
variables [boolean_ring α] [boolean_ring β] [boolean_ring γ]
namespace boolean_ring
/-- The join operation in a Boolean ring is `x + y + x * y`. -/
def has_sup : has_sup α := ⟨λ x y, x + y + x * y⟩
/-- The meet operation in a Boolean ring is `x * y`. -/
def has_inf : has_inf α := ⟨(*)⟩
-- Note [lower instance priority]
localized "attribute [instance, priority 100] boolean_ring.has_sup" in
boolean_algebra_of_boolean_ring
localized "attribute [instance, priority 100] boolean_ring.has_inf" in
boolean_algebra_of_boolean_ring
lemma sup_comm (a b : α) : a ⊔ b = b ⊔ a := by { dsimp only [(⊔)], ring }
lemma inf_comm (a b : α) : a ⊓ b = b ⊓ a := by { dsimp only [(⊓)], ring }
lemma sup_assoc (a b c : α) : a ⊔ b ⊔ c = a ⊔ (b ⊔ c) := by { dsimp only [(⊔)], ring }
lemma inf_assoc (a b c : α) : a ⊓ b ⊓ c = a ⊓ (b ⊓ c) := by { dsimp only [(⊓)], ring }
lemma sup_inf_self (a b : α) : a ⊔ a ⊓ b = a :=
by { dsimp only [(⊔), (⊓)], assoc_rw [mul_self, add_self, add_zero] }
lemma inf_sup_self (a b : α) : a ⊓ (a ⊔ b) = a :=
begin
dsimp only [(⊔), (⊓)],
rw [mul_add, mul_add, mul_self, ←mul_assoc, mul_self, add_assoc, add_self, add_zero]
end
lemma le_sup_inf_aux (a b c : α) : (a + b + a * b) * (a + c + a * c) = a + b * c + a * (b * c) :=
calc (a + b + a * b) * (a + c + a * c) =
a * a + b * c + a * (b * c) +
(a * b + (a * a) * b) +
(a * c + (a * a) * c) +
(a * b * c + (a * a) * b * c) : by ring
... = a + b * c + a * (b * c) : by simp only [mul_self, add_self, add_zero]
lemma le_sup_inf (a b c : α) : (a ⊔ b) ⊓ (a ⊔ c) ⊔ (a ⊔ b ⊓ c) = a ⊔ b ⊓ c :=
by { dsimp only [(⊔), (⊓)], rw [le_sup_inf_aux, add_self, mul_self, zero_add] }
/--
The Boolean algebra structure on a Boolean ring.
The data is defined so that:
* `a ⊔ b` unfolds to `a + b + a * b`
* `a ⊓ b` unfolds to `a * b`
* `a ≤ b` unfolds to `a + b + a * b = b`
* `⊥` unfolds to `0`
* `⊤` unfolds to `1`
* `aᶜ` unfolds to `1 + a`
* `a \ b` unfolds to `a * (1 + b)`
-/
def to_boolean_algebra : boolean_algebra α :=
{ le_sup_inf := le_sup_inf,
top := 1,
le_top := λ a, show a + 1 + a * 1 = 1, by assoc_rw [mul_one, add_comm, add_self, add_zero],
bot := 0,
bot_le := λ a, show 0 + a + 0 * a = a, by rw [zero_mul, zero_add, add_zero],
compl := λ a, 1 + a,
inf_compl_le_bot := λ a,
show a*(1+a) + 0 + a*(1+a)*0 = 0,
by norm_num [mul_add, mul_self, add_self],
top_le_sup_compl := λ a,
begin
change 1 + (a + (1+a) + a*(1+a)) + 1*(a + (1+a) + a*(1+a)) = a + (1+a) + a*(1+a),
norm_num [mul_add, mul_self],
rw [←add_assoc, add_self],
end,
.. lattice.mk' sup_comm sup_assoc inf_comm inf_assoc sup_inf_self inf_sup_self }
localized "attribute [instance, priority 100] boolean_ring.to_boolean_algebra" in
boolean_algebra_of_boolean_ring
end boolean_ring
instance : boolean_algebra (as_boolalg α) := @boolean_ring.to_boolean_algebra α _
@[simp] lemma of_boolalg_top : of_boolalg (⊤ : as_boolalg α) = 1 := rfl
@[simp] lemma of_boolalg_bot : of_boolalg (⊥ : as_boolalg α) = 0 := rfl
@[simp] lemma of_boolalg_sup (a b : as_boolalg α) :
of_boolalg (a ⊔ b) = of_boolalg a + of_boolalg b + of_boolalg a * of_boolalg b := rfl
@[simp] lemma of_boolalg_inf (a b : as_boolalg α) :
of_boolalg (a ⊓ b) = of_boolalg a * of_boolalg b := rfl
@[simp] lemma of_boolalg_compl (a : as_boolalg α) : of_boolalg aᶜ = 1 + of_boolalg a := rfl
@[simp] lemma of_boolalg_sdiff (a b : as_boolalg α) :
of_boolalg (a \ b) = of_boolalg a * (1 + of_boolalg b) := rfl
private lemma of_boolalg_symm_diff_aux (a b : α) : (a + b + a * b) * (1 + a * b) = a + b :=
calc (a + b + a * b) * (1 + a * b)
= a + b + (a * b + (a * b) * (a * b)) + (a * (b * b) + (a * a) * b) : by ring
... = a + b : by simp only [mul_self, add_self, add_zero]
@[simp] lemma of_boolalg_symm_diff (a b : as_boolalg α) :
of_boolalg (a ∆ b) = of_boolalg a + of_boolalg b :=
by { rw symm_diff_eq_sup_sdiff_inf, exact of_boolalg_symm_diff_aux _ _ }
@[simp] lemma of_boolalg_mul_of_boolalg_eq_left_iff {a b : as_boolalg α} :
of_boolalg a * of_boolalg b = of_boolalg a ↔ a ≤ b :=
@inf_eq_left (as_boolalg α) _ _ _
@[simp] lemma to_boolalg_zero : to_boolalg (0 : α) = ⊥ := rfl
@[simp] lemma to_boolalg_one : to_boolalg (1 : α) = ⊤ := rfl
@[simp] lemma to_boolalg_mul (a b : α) :
to_boolalg (a * b) = to_boolalg a ⊓ to_boolalg b := rfl
-- `to_boolalg_add` simplifies the LHS but this lemma is eligible to `dsimp`
@[simp, nolint simp_nf] lemma to_boolalg_add_add_mul (a b : α) :
to_boolalg (a + b + a * b) = to_boolalg a ⊔ to_boolalg b := rfl
@[simp] lemma to_boolalg_add (a b : α) : to_boolalg (a + b) = to_boolalg a ∆ to_boolalg b :=
(of_boolalg_symm_diff _ _).symm
/-- Turn a ring homomorphism from Boolean rings `α` to `β` into a bounded lattice homomorphism
from `α` to `β` considered as Boolean algebras. -/
@[simps] protected def ring_hom.as_boolalg (f : α →+* β) :
bounded_lattice_hom (as_boolalg α) (as_boolalg β) :=
{ to_fun := to_boolalg ∘ f ∘ of_boolalg,
map_sup' := λ a b, begin
dsimp,
simp_rw [map_add f, map_mul f],
refl,
end,
map_inf' := f.map_mul',
map_top' := f.map_one',
map_bot' := f.map_zero' }
@[simp] lemma ring_hom.as_boolalg_id : (ring_hom.id α).as_boolalg = bounded_lattice_hom.id _ := rfl
@[simp] lemma ring_hom.as_boolalg_comp (g : β →+* γ) (f : α →+* β) :
(g.comp f).as_boolalg = g.as_boolalg.comp f.as_boolalg := rfl
end ring_to_algebra
/-! ### Turning a Boolean algebra into a Boolean ring -/
section algebra_to_ring
/-- Type synonym to view a Boolean ring as a Boolean algebra. -/
def as_boolring (α : Type*) := α
/-- The "identity" equivalence between `as_boolring α` and `α`. -/
def to_boolring : α ≃ as_boolring α := equiv.refl _
/-- The "identity" equivalence between `α` and `as_boolring α`. -/
def of_boolring : as_boolring α ≃ α := equiv.refl _
@[simp] lemma to_boolring_symm_eq : (@to_boolring α).symm = of_boolring := rfl
@[simp] lemma of_boolring_symm_eq : (@of_boolring α).symm = to_boolring := rfl
@[simp] lemma to_boolring_of_boolring (a : as_boolring α) : to_boolring (of_boolring a) = a := rfl
@[simp] lemma of_boolring_to_boolring (a : α) : of_boolring (to_boolring a) = a := rfl
@[simp] lemma to_boolring_inj {a b : α} : to_boolring a = to_boolring b ↔ a = b := iff.rfl
@[simp] lemma of_boolring_inj {a b : as_boolring α} : of_boolring a = of_boolring b ↔ a = b :=
iff.rfl
instance [inhabited α] : inhabited (as_boolring α) := ‹inhabited α›
/-- Every generalized Boolean algebra has the structure of a non unital commutative ring with the
following data:
* `a + b` unfolds to `a ∆ b` (symmetric difference)
* `a * b` unfolds to `a ⊓ b`
* `-a` unfolds to `a`
* `0` unfolds to `⊥`
-/
@[reducible] -- See note [reducible non-instances]
def generalized_boolean_algebra.to_non_unital_comm_ring [generalized_boolean_algebra α] :
non_unital_comm_ring α :=
{ add := (∆),
add_assoc := symm_diff_assoc,
zero := ⊥,
zero_add := bot_symm_diff,
add_zero := symm_diff_bot,
zero_mul := λ _, bot_inf_eq,
mul_zero := λ _, inf_bot_eq,
neg := id,
add_left_neg := symm_diff_self,
add_comm := symm_diff_comm,
mul := (⊓),
mul_assoc := λ _ _ _, inf_assoc,
mul_comm := λ _ _, inf_comm,
left_distrib := inf_symm_diff_distrib_left,
right_distrib := inf_symm_diff_distrib_right }
instance [generalized_boolean_algebra α] : non_unital_comm_ring (as_boolring α) :=
@generalized_boolean_algebra.to_non_unital_comm_ring α _
variables [boolean_algebra α] [boolean_algebra β] [boolean_algebra γ]
/-- Every Boolean algebra has the structure of a Boolean ring with the following data:
* `a + b` unfolds to `a ∆ b` (symmetric difference)
* `a * b` unfolds to `a ⊓ b`
* `-a` unfolds to `a`
* `0` unfolds to `⊥`
* `1` unfolds to `⊤`
-/
@[reducible] -- See note [reducible non-instances]
def boolean_algebra.to_boolean_ring : boolean_ring α :=
{ one := ⊤,
one_mul := λ _, top_inf_eq,
mul_one := λ _, inf_top_eq,
mul_self := λ b, inf_idem,
..generalized_boolean_algebra.to_non_unital_comm_ring }
localized "attribute [instance, priority 100] generalized_boolean_algebra.to_non_unital_comm_ring
boolean_algebra.to_boolean_ring" in boolean_ring_of_boolean_algebra
instance : boolean_ring (as_boolring α) := @boolean_algebra.to_boolean_ring α _
@[simp] lemma of_boolring_zero : of_boolring (0 : as_boolring α) = ⊥ := rfl
@[simp] lemma of_boolring_one : of_boolring (1 : as_boolring α) = ⊤ := rfl
-- `sub_eq_add` proves this lemma but it is eligible for `dsimp`
@[simp, nolint simp_nf] lemma of_boolring_neg (a : as_boolring α) :
of_boolring (-a) = of_boolring a := rfl
@[simp] lemma of_boolring_add (a b : as_boolring α) :
of_boolring (a + b) = of_boolring a ∆ of_boolring b := rfl
-- `sub_eq_add` simplifies the LHS but this lemma is eligible for `dsimp`
@[simp, nolint simp_nf] lemma of_boolring_sub (a b : as_boolring α) :
of_boolring (a - b) = of_boolring a ∆ of_boolring b := rfl
@[simp] lemma of_boolring_mul (a b : as_boolring α) :
of_boolring (a * b) = of_boolring a ⊓ of_boolring b := rfl
@[simp] lemma of_boolring_le_of_boolring_iff {a b : as_boolring α} :
of_boolring a ≤ of_boolring b ↔ a * b = a := inf_eq_left.symm
@[simp] lemma to_boolring_bot : to_boolring (⊥ : α) = 0 := rfl
@[simp] lemma to_boolring_top : to_boolring (⊤ : α) = 1 := rfl
@[simp] lemma to_boolring_inf (a b : α) : to_boolring (a ⊓ b) = to_boolring a * to_boolring b := rfl
@[simp] lemma to_boolring_symm_diff (a b : α) :
to_boolring (a ∆ b) = to_boolring a + to_boolring b := rfl
/-- Turn a bounded lattice homomorphism from Boolean algebras `α` to `β` into a ring homomorphism
from `α` to `β` considered as Boolean rings. -/
@[simps] protected def bounded_lattice_hom.as_boolring (f : bounded_lattice_hom α β) :
as_boolring α →+* as_boolring β :=
{ to_fun := to_boolring ∘ f ∘ of_boolring,
map_zero' := f.map_bot',
map_one' := f.map_top',
map_add' := map_symm_diff f,
map_mul' := f.map_inf' }
@[simp] lemma bounded_lattice_hom.as_boolring_id :
(bounded_lattice_hom.id α).as_boolring = ring_hom.id _ := rfl
@[simp] lemma bounded_lattice_hom.as_boolring_comp (g : bounded_lattice_hom β γ)
(f : bounded_lattice_hom α β) :
(g.comp f).as_boolring = g.as_boolring.comp f.as_boolring := rfl
end algebra_to_ring
/-! ### Equivalence between Boolean rings and Boolean algebras -/
/-- Order isomorphism between `α` considered as a Boolean ring considered as a Boolean algebra and
`α`. -/
@[simps] def order_iso.as_boolalg_as_boolring (α : Type*) [boolean_algebra α] :
as_boolalg (as_boolring α) ≃o α :=
⟨of_boolalg.trans of_boolring, λ a b,
of_boolring_le_of_boolring_iff.trans of_boolalg_mul_of_boolalg_eq_left_iff⟩
/-- Ring isomorphism between `α` considered as a Boolean algebra considered as a Boolean ring and
`α`. -/
@[simps] def ring_equiv.as_boolring_as_boolalg (α : Type*) [boolean_ring α] :
as_boolring (as_boolalg α) ≃+* α :=
{ map_mul' := λ a b, rfl,
map_add' := of_boolalg_symm_diff,
..of_boolring.trans of_boolalg }
open bool
instance : boolean_ring bool :=
{ add := bxor,
add_assoc := bxor_assoc,
zero := ff,
zero_add := ff_bxor,
add_zero := bxor_ff,
neg := id,
sub := bxor,
sub_eq_add_neg := λ _ _, rfl,
add_left_neg := bxor_self,
add_comm := bxor_comm,
one := tt,
mul := band,
mul_assoc := band_assoc,
one_mul := tt_band,
mul_one := band_tt,
left_distrib := band_bxor_distrib_left,
right_distrib := band_bxor_distrib_right,
mul_self := band_self }
|
97d8dca3b9efe57ed04bd2bb566186602f9a4378 | f57749ca63d6416f807b770f67559503fdb21001 | /hott/algebra/category/functor.hlean | bd7e7dcbe25c0476e1e1ee5499bafe06d1ce543d | [
"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 | 10,273 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Jakob von Raumer
-/
import .iso types.pi
open function category eq prod prod.ops equiv is_equiv sigma sigma.ops is_trunc funext iso
open pi
structure functor (C D : Precategory) : Type :=
(to_fun_ob : C → D)
(to_fun_hom : Π ⦃a b : C⦄, hom a b → hom (to_fun_ob a) (to_fun_ob b))
(respect_id : Π (a : C), to_fun_hom (ID a) = ID (to_fun_ob a))
(respect_comp : Π {a b c : C} (g : hom b c) (f : hom a b),
to_fun_hom (g ∘ f) = to_fun_hom g ∘ to_fun_hom f)
namespace functor
infixl `⇒`:25 := functor
variables {A B C D E : Precategory}
attribute to_fun_ob [coercion]
attribute to_fun_hom [coercion]
-- The following lemmas will later be used to prove that the type of
-- precategories forms a precategory itself
protected definition compose [reducible] (G : functor D E) (F : functor C D) : functor C E :=
functor.mk
(λ x, G (F x))
(λ a b f, G (F f))
(λ a, abstract calc
G (F (ID a)) = G (ID (F a)) : by rewrite respect_id
... = ID (G (F a)) : by rewrite respect_id end)
(λ a b c g f, abstract calc
G (F (g ∘ f)) = G (F g ∘ F f) : by rewrite respect_comp
... = G (F g) ∘ G (F f) : by rewrite respect_comp end)
infixr `∘f`:60 := functor.compose
protected definition id [reducible] {C : Precategory} : functor C C :=
mk (λa, a) (λ a b f, f) (λ a, idp) (λ a b c f g, idp)
protected definition ID [reducible] (C : Precategory) : functor C C := @functor.id C
definition functor_mk_eq' {F₁ F₂ : C → D} {H₁ : Π(a b : C), hom a b → hom (F₁ a) (F₁ b)}
{H₂ : Π(a b : C), hom a b → hom (F₂ a) (F₂ b)} (id₁ id₂ comp₁ comp₂)
(pF : F₁ = F₂) (pH : pF ▸ H₁ = H₂)
: functor.mk F₁ H₁ id₁ comp₁ = functor.mk F₂ H₂ id₂ comp₂ :=
apd01111 functor.mk pF pH !is_hprop.elim !is_hprop.elim
definition functor_eq' {F₁ F₂ : C ⇒ D}
: Π(p : to_fun_ob F₁ = to_fun_ob F₂),
(transport (λx, Πa b f, hom (x a) (x b)) p (to_fun_hom F₁) = to_fun_hom F₂) → F₁ = F₂ :=
functor.rec_on F₁ (λO₁ H₁ id₁ comp₁, functor.rec_on F₂ (λO₂ H₂ id₂ comp₂ p, !functor_mk_eq'))
definition functor_mk_eq {F₁ F₂ : C → D} {H₁ : Π(a b : C), hom a b → hom (F₁ a) (F₁ b)}
{H₂ : Π(a b : C), hom a b → hom (F₂ a) (F₂ b)} (id₁ id₂ comp₁ comp₂) (pF : F₁ ~ F₂)
(pH : Π(a b : C) (f : hom a b), hom_of_eq (pF b) ∘ H₁ a b f ∘ inv_of_eq (pF a) = H₂ a b f)
: functor.mk F₁ H₁ id₁ comp₁ = functor.mk F₂ H₂ id₂ comp₂ :=
begin
fapply functor_mk_eq',
{ exact eq_of_homotopy pF},
{ refine eq_of_homotopy (λc, eq_of_homotopy (λc', eq_of_homotopy (λf, _))), intros,
rewrite [+pi_transport_constant,-pH,-transport_hom]}
end
definition functor_eq {F₁ F₂ : C ⇒ D} : Π(p : to_fun_ob F₁ ~ to_fun_ob F₂),
(Π(a b : C) (f : hom a b), hom_of_eq (p b) ∘ F₁ f ∘ inv_of_eq (p a) = F₂ f) → F₁ = F₂ :=
functor.rec_on F₁ (λO₁ H₁ id₁ comp₁, functor.rec_on F₂ (λO₂ H₂ id₂ comp₂ p, !functor_mk_eq))
definition functor_mk_eq_constant {F : C → D} {H₁ : Π(a b : C), hom a b → hom (F a) (F b)}
{H₂ : Π(a b : C), hom a b → hom (F a) (F b)} (id₁ id₂ comp₁ comp₂)
(pH : Π(a b : C) (f : hom a b), H₁ a b f = H₂ a b f)
: functor.mk F H₁ id₁ comp₁ = functor.mk F H₂ id₂ comp₂ :=
functor_eq (λc, idp) (λa b f, !id_leftright ⬝ !pH)
protected definition preserve_iso (F : C ⇒ D) {a b : C} (f : hom a b) [H : is_iso f] :
is_iso (F f) :=
begin
fapply @is_iso.mk, apply (F (f⁻¹)),
repeat (apply concat ; symmetry ; apply (respect_comp F) ;
apply concat ; apply (ap (λ x, to_fun_hom F x)) ;
(apply left_inverse | apply right_inverse);
apply (respect_id F) ),
end
definition respect_inv (F : C ⇒ D) {a b : C} (f : hom a b)
[H : is_iso f] [H' : is_iso (F f)] :
F (f⁻¹) = (F f)⁻¹ :=
begin
fapply @left_inverse_eq_right_inverse, apply (F f),
transitivity to_fun_hom F (f⁻¹ ∘ f),
{symmetry, apply (respect_comp F)},
{transitivity to_fun_hom F category.id,
{congruence, apply left_inverse},
{apply respect_id}},
apply right_inverse
end
attribute functor.preserve_iso [instance]
definition respect_inv' (F : C ⇒ D) {a b : C} (f : hom a b) {H : is_iso f} : F (f⁻¹) = (F f)⁻¹ :=
respect_inv F f
protected definition assoc (H : C ⇒ D) (G : B ⇒ C) (F : A ⇒ B) :
H ∘f (G ∘f F) = (H ∘f G) ∘f F :=
!functor_mk_eq_constant (λa b f, idp)
protected definition id_left (F : C ⇒ D) : functor.id ∘f F = F :=
functor.rec_on F (λF1 F2 F3 F4, !functor_mk_eq_constant (λa b f, idp))
protected definition id_right (F : C ⇒ D) : F ∘f functor.id = F :=
functor.rec_on F (λF1 F2 F3 F4, !functor_mk_eq_constant (λa b f, idp))
protected definition comp_id_eq_id_comp (F : C ⇒ D) : F ∘f functor.id = functor.id ∘f F :=
!functor.id_right ⬝ !functor.id_left⁻¹
-- "functor C D" is equivalent to a certain sigma type
protected definition sigma_char :
(Σ (to_fun_ob : C → D)
(to_fun_hom : Π ⦃a b : C⦄, hom a b → hom (to_fun_ob a) (to_fun_ob b)),
(Π (a : C), to_fun_hom (ID a) = ID (to_fun_ob a)) ×
(Π {a b c : C} (g : hom b c) (f : hom a b),
to_fun_hom (g ∘ f) = to_fun_hom g ∘ to_fun_hom f)) ≃ (functor C D) :=
begin
fapply equiv.MK,
{intro S, fapply functor.mk,
exact (S.1), exact (S.2.1),
-- TODO(Leo): investigate why we need to use relaxed-exact (rexact) tactic here
exact (pr₁ S.2.2), rexact (pr₂ S.2.2)},
{intro F, cases F with d1 d2 d3 d4, exact ⟨d1, d2, (d3, @d4)⟩},
{intro F, cases F, reflexivity},
{intro S, cases S with d1 S2, cases S2 with d2 P1, cases P1, reflexivity},
end
section
local attribute precategory.is_hset_hom [priority 1001]
protected theorem is_hset_functor [instance]
[HD : is_hset D] : is_hset (functor C D) :=
by apply is_trunc_equiv_closed; apply functor.sigma_char
end
definition functor_mk_eq'_idp (F : C → D) (H : Π(a b : C), hom a b → hom (F a) (F b))
(id comp) : functor_mk_eq' id id comp comp (idpath F) (idpath H) = idp :=
begin
fapply (apd011 (apd01111 functor.mk idp idp)),
apply is_hset.elim,
apply is_hset.elim
end
definition functor_eq'_idp (F : C ⇒ D) : functor_eq' idp idp = (idpath F) :=
by (cases F; apply functor_mk_eq'_idp)
definition functor_eq_eta' {F₁ F₂ : C ⇒ D} (p : F₁ = F₂)
: functor_eq' (ap to_fun_ob p) (!transport_compose⁻¹ ⬝ apd to_fun_hom p) = p :=
begin
cases p, cases F₁,
apply concat, rotate_left 1, apply functor_eq'_idp,
esimp
end
definition functor_eq2' {F₁ F₂ : C ⇒ D} {p₁ p₂ : to_fun_ob F₁ = to_fun_ob F₂} (q₁ q₂)
(r : p₁ = p₂) : functor_eq' p₁ q₁ = functor_eq' p₂ q₂ :=
by cases r; apply (ap (functor_eq' p₂)); apply is_hprop.elim
definition functor_eq2 {F₁ F₂ : C ⇒ D} (p q : F₁ = F₂) (r : ap010 to_fun_ob p ~ ap010 to_fun_ob q)
: p = q :=
begin
cases F₁ with ob₁ hom₁ id₁ comp₁,
cases F₂ with ob₂ hom₂ id₂ comp₂,
rewrite [-functor_eq_eta' p, -functor_eq_eta' q],
apply functor_eq2',
apply ap_eq_ap_of_homotopy,
exact r,
end
definition ap010_apd01111_functor {F₁ F₂ : C → D} {H₁ : Π(a b : C), hom a b → hom (F₁ a) (F₁ b)}
{H₂ : Π(a b : C), hom a b → hom (F₂ a) (F₂ b)} {id₁ id₂ comp₁ comp₂}
(pF : F₁ = F₂) (pH : pF ▸ H₁ = H₂) (pid : cast (apd011 _ pF pH) id₁ = id₂)
(pcomp : cast (apd0111 _ pF pH pid) comp₁ = comp₂) (c : C)
: ap010 to_fun_ob (apd01111 functor.mk pF pH pid pcomp) c = ap10 pF c :=
by cases pF; cases pH; cases pid; cases pcomp; apply idp
definition ap010_functor_eq {F₁ F₂ : C ⇒ D} (p : to_fun_ob F₁ ~ to_fun_ob F₂)
(q : (λ(a b : C) (f : hom a b), hom_of_eq (p b) ∘ F₁ f ∘ inv_of_eq (p a)) ~3 to_fun_hom F₂) (c : C) :
ap010 to_fun_ob (functor_eq p q) c = p c :=
begin
cases F₁ with F₁o F₁h F₁id F₁comp, cases F₂ with F₂o F₂h F₂id F₂comp,
esimp [functor_eq,functor_mk_eq,functor_mk_eq'],
rewrite [ap010_apd01111_functor,↑ap10,{apd10 (eq_of_homotopy p)}right_inv apd10]
end
definition ap010_functor_mk_eq_constant {F : C → D} {H₁ : Π(a b : C), hom a b → hom (F a) (F b)}
{H₂ : Π(a b : C), hom a b → hom (F a) (F b)} {id₁ id₂ comp₁ comp₂}
(pH : Π(a b : C) (f : hom a b), H₁ a b f = H₂ a b f) (c : C) :
ap010 to_fun_ob (functor_mk_eq_constant id₁ id₂ comp₁ comp₂ pH) c = idp :=
!ap010_functor_eq
definition ap010_assoc (H : C ⇒ D) (G : B ⇒ C) (F : A ⇒ B) (a : A) :
ap010 to_fun_ob (functor.assoc H G F) a = idp :=
by apply ap010_functor_mk_eq_constant
definition compose_pentagon (K : D ⇒ E) (H : C ⇒ D) (G : B ⇒ C) (F : A ⇒ B) :
(calc K ∘f H ∘f G ∘f F = (K ∘f H) ∘f G ∘f F : functor.assoc
... = ((K ∘f H) ∘f G) ∘f F : functor.assoc)
=
(calc K ∘f H ∘f G ∘f F = K ∘f (H ∘f G) ∘f F : ap (λx, K ∘f x) !functor.assoc
... = (K ∘f H ∘f G) ∘f F : functor.assoc
... = ((K ∘f H) ∘f G) ∘f F : ap (λx, x ∘f F) !functor.assoc) :=
begin
have lem1 : Π{F₁ F₂ : A ⇒ D} (p : F₁ = F₂) (a : A),
ap010 to_fun_ob (ap (λx, K ∘f x) p) a = ap (to_fun_ob K) (ap010 to_fun_ob p a),
by intros; cases p; esimp,
have lem2 : Π{F₁ F₂ : B ⇒ E} (p : F₁ = F₂) (a : A),
ap010 to_fun_ob (ap (λx, x ∘f F) p) a = ap010 to_fun_ob p (F a),
by intros; cases p; esimp,
apply functor_eq2,
intro a, esimp,
rewrite [+ap010_con,lem1,lem2,
ap010_assoc K H (G ∘f F) a,
ap010_assoc (K ∘f H) G F a,
ap010_assoc H G F a,
ap010_assoc K H G (F a),
ap010_assoc K (H ∘f G) F a],
end
end functor
|
22ebd04f89a17fef19776fdb87cf60c6cd447771 | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /tests/bench/rbmap_checkpoint.lean | 4c4ecf178b793b789f940943d7bb4ad5cb9799af | [
"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 | 3,429 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Data.Option.Basic
import Init.Data.List.BasicAux
import Init.Data.String
import Init.System.IO
universes u v w w'
inductive color
| Red | Black
inductive Tree
| Leaf {} : Tree
| Node (color : color) (lchild : Tree) (key : Nat) (val : Bool) (rchild : Tree) : Tree
instance : Inhabited Tree := ⟨Tree.Leaf⟩
variable {σ : Type w}
open color Nat Tree
def fold (f : Nat → Bool → σ → σ) : Tree → σ → σ
| Leaf, b => b
| Node _ l k v r, b => fold f r (f k v (fold f l b))
@[inline]
def balance1 : Nat → Bool → Tree → Tree → Tree
| kv, vv, t, Node _ (Node Red l kx vx r₁) ky vy r₂ => Node Red (Node Black l kx vx r₁) ky vy (Node Black r₂ kv vv t)
| kv, vv, t, Node _ l₁ ky vy (Node Red l₂ kx vx r) => Node Red (Node Black l₁ ky vy l₂) kx vx (Node Black r kv vv t)
| kv, vv, t, Node _ l ky vy r => Node Black (Node Red l ky vy r) kv vv t
| _, _, _, _ => Leaf
@[inline]
def balance2 : Tree → Nat → Bool → Tree → Tree
| t, kv, vv, Node _ (Node Red l kx₁ vx₁ r₁) ky vy r₂ => Node Red (Node Black t kv vv l) kx₁ vx₁ (Node Black r₁ ky vy r₂)
| t, kv, vv, Node _ l₁ ky vy (Node Red l₂ kx₂ vx₂ r₂) => Node Red (Node Black t kv vv l₁) ky vy (Node Black l₂ kx₂ vx₂ r₂)
| t, kv, vv, Node _ l ky vy r => Node Black t kv vv (Node Red l ky vy r)
| _, _, _, _ => Leaf
def isRed : Tree → Bool
| Node Red _ _ _ _ => true
| _ => false
def ins : Tree → Nat → Bool → Tree
| Leaf, kx, vx => Node Red Leaf kx vx Leaf
| Node Red a ky vy b, kx, vx =>
(if kx < ky then Node Red (ins a kx vx) ky vy b
else if kx = ky then Node Red a kx vx b
else Node Red a ky vy (ins b kx vx))
| Node Black a ky vy b, kx, vx =>
if kx < ky then
(if isRed a then balance1 ky vy b (ins a kx vx)
else Node Black (ins a kx vx) ky vy b)
else if kx = ky then Node Black a kx vx b
else if isRed b then balance2 a ky vy (ins b kx vx)
else Node Black a ky vy (ins b kx vx)
def setBlack : Tree → Tree
| Node _ l k v r => Node Black l k v r
| e => e
def insert (t : Tree) (k : Nat) (v : Bool) : Tree :=
if isRed t then setBlack (ins t k v)
else ins t k v
def mkMapAux (freq : Nat) : Nat → Tree → List Tree → List Tree
| 0, m, r => m::r
| n+1, m, r =>
let m := insert m n (n % 10 = 0);
let r := if n % freq == 0 then m::r else r;
mkMapAux freq n m r
def mkMap (n : Nat) (freq : Nat) : List Tree :=
mkMapAux freq n Leaf []
def myLen : List Tree → Nat → Nat
| Node _ _ _ _ _ :: xs, r => myLen xs (r + 1)
| _ :: xs, r => myLen xs r
| [], r => r
def main (xs : List String) : IO UInt32 := do
let [n, freq] ← pure xs | throw $ IO.userError "invalid input";
let n := n.toNat!;
let freq := freq.toNat!;
let freq := if freq == 0 then 1 else freq;
let mList := mkMap n freq;
let v := fold (fun (k : Nat) (v : Bool) (r : Nat) => if v then r + 1 else r) mList.head! 0;
IO.println (toString (myLen mList 0) ++ " " ++ toString v) *>
pure 0
|
6b7670417a714d5b34d5b2848974952d3a4e2c82 | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/data/set/disjointed.lean | c2026f83a90691cdb12750167b22e538e097cbce | [
"Apache-2.0"
] | permissive | agjftucker/mathlib | d634cd0d5256b6325e3c55bb7fb2403548371707 | 87fe50de17b00af533f72a102d0adefe4a2285e8 | refs/heads/master | 1,625,378,131,941 | 1,599,166,526,000 | 1,599,166,526,000 | 160,748,509 | 0 | 0 | Apache-2.0 | 1,544,141,789,000 | 1,544,141,789,000 | null | UTF-8 | Lean | false | false | 4,336 | 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
Disjointed sets
-/
import data.set.lattice
import tactic.wlog
open set classical
open_locale classical
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x}
{s t u : set α}
/-- A relation `p` holds pairwise if `p i j` for all `i ≠ j`. -/
def pairwise {α : Type*} (p : α → α → Prop) := ∀i j, i ≠ j → p i j
theorem set.pairwise_on_univ {r : α → α → Prop} :
(univ : set α).pairwise_on r ↔ pairwise r :=
by simp only [pairwise_on, pairwise, mem_univ, forall_const]
theorem set.pairwise_on.on_injective {s : set α} {r : α → α → Prop} (hs : pairwise_on s r)
{f : β → α} (hf : function.injective f) (hfs : ∀ x, f x ∈ s) :
pairwise (r on f) :=
λ i j hij, hs _ (hfs i) _ (hfs j) (hf.ne hij)
theorem pairwise_on_bool {r} (hr : symmetric r) {a b : α} :
pairwise (r on (λ c, cond c a b)) ↔ r a b :=
by simpa [pairwise, function.on_fun] using @hr a b
theorem pairwise_disjoint_on_bool [semilattice_inf_bot α] {a b : α} :
pairwise (disjoint on (λ c, cond c a b)) ↔ disjoint a b :=
pairwise_on_bool disjoint.symm
theorem pairwise.pairwise_on {p : α → α → Prop} (h : pairwise p) (s : set α) : s.pairwise_on p :=
λ x hx y hy, h x y
theorem pairwise_disjoint_fiber (f : α → β) : pairwise (disjoint on (λ y : β, f ⁻¹' {y})) :=
set.pairwise_on_univ.1 $ pairwise_on_disjoint_fiber f univ
namespace set
/-- If `f : ℕ → set α` is a sequence of sets, then `disjointed f` is
the sequence formed with each set subtracted from the later ones
in the sequence, to form a disjoint sequence. -/
def disjointed (f : ℕ → set α) (n : ℕ) : set α := f n ∩ (⋂i<n, (f i)ᶜ)
lemma disjoint_disjointed {f : ℕ → set α} : pairwise (disjoint on disjointed f) :=
λ i j h, begin
wlog h' : i ≤ j; [skip, {revert a, exact (this h.symm).symm}],
rintro a ⟨⟨h₁, _⟩, h₂, h₃⟩, simp at h₃,
exact h₃ _ (lt_of_le_of_ne h' h) h₁
end
lemma disjoint_disjointed' {f : ℕ → set α} :
∀ i j, i ≠ j → (disjointed f i) ∩ (disjointed f j) = ∅ :=
λ i j hij, disjoint_iff.1 $ disjoint_disjointed i j hij
lemma disjointed_subset {f : ℕ → set α} {n : ℕ} : disjointed f n ⊆ f n := inter_subset_left _ _
lemma Union_lt_succ {f : ℕ → set α} {n} : (⋃i < nat.succ n, f i) = f n ∪ (⋃i < n, f i) :=
ext $ λ a, by simp [nat.lt_succ_iff_lt_or_eq, or_and_distrib_right, exists_or_distrib, or_comm]
lemma Inter_lt_succ {f : ℕ → set α} {n} : (⋂i < nat.succ n, f i) = f n ∩ (⋂i < n, f i) :=
ext $ λ a, by simp [nat.lt_succ_iff_lt_or_eq, or_imp_distrib, forall_and_distrib, and_comm]
lemma Union_disjointed {f : ℕ → set α} : (⋃n, disjointed f n) = (⋃n, f n) :=
subset.antisymm (Union_subset_Union $ assume i, inter_subset_left _ _) $
assume x h,
have ∃n, x ∈ f n, from mem_Union.mp h,
have hn : ∀ (i : ℕ), i < nat.find this → x ∉ f i,
from assume i, nat.find_min this,
mem_Union.mpr ⟨nat.find this, nat.find_spec this, by simp; assumption⟩
lemma disjointed_induct {f : ℕ → set α} {n : ℕ} {p : set α → Prop}
(h₁ : p (f n)) (h₂ : ∀t i, p t → p (t \ f i)) :
p (disjointed f n) :=
begin
rw disjointed,
generalize_hyp : f n = t at h₁ ⊢,
induction n,
case nat.zero { simp [nat.not_lt_zero, h₁] },
case nat.succ : n ih {
rw [Inter_lt_succ, inter_comm ((f n)ᶜ), ← inter_assoc],
exact h₂ _ n ih }
end
lemma disjointed_of_mono {f : ℕ → set α} {n : ℕ} (hf : monotone f) :
disjointed f (n + 1) = f (n + 1) \ f n :=
have (⋂i (h : i < n + 1), (f i)ᶜ) = (f n)ᶜ,
from le_antisymm
(infi_le_of_le n $ infi_le_of_le (nat.lt_succ_self _) $ subset.refl _)
(le_infi $ assume i, le_infi $ assume hi, compl_le_compl $ hf $ nat.le_of_succ_le_succ hi),
by simp [disjointed, this, diff_eq]
lemma Union_disjointed_of_mono {f : ℕ → set α} (hf : monotone f) :
∀ n : ℕ, (⋃i<n.succ, disjointed f i) = f n
| 0 := by rw [Union_lt_succ]; simp [disjointed, nat.not_lt_zero]
| (n+1) := by rw [Union_lt_succ,
disjointed_of_mono hf, Union_disjointed_of_mono n,
diff_union_self, union_eq_self_of_subset_right (hf (nat.le_succ _))]
end set
|
00609d45c8f65ec1e7d1fc6356dc839ea6e542b4 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/casesUsing.lean | b5f070709d547ecf8b03925878e10dabc8a8f69d | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 4,713 | lean | import Lean
open Lean
open Lean.Meta
open Lean.Elab.Tactic
universe u
axiom elimEx (motive : Nat → Nat → Sort u) (x y : Nat)
(diag : (a : Nat) → motive a a)
(upper : (delta a : Nat) → motive a (a + delta.succ))
(lower : (delta a : Nat) → motive (a + delta.succ) a)
: motive y x
theorem ex1 (p q : Nat) : p ≤ q ∨ p > q := by
cases p, q using elimEx with
| diag => apply Or.inl; apply Nat.le_refl
| lower d => apply Or.inl; show p ≤ p + d.succ; admit
| upper d => apply Or.inr; show q + d.succ > q; admit
theorem ex2 (p q : Nat) : p ≤ q ∨ p > q := by
cases p, q using elimEx
case lower => admit
case upper => admit
case diag => apply Or.inl; apply Nat.le_refl
axiom Nat.parityElim (motive : Nat → Sort u)
(even : (n : Nat) → motive (2*n))
(odd : (n : Nat) → motive (2*n+1))
(n : Nat)
: motive n
theorem time2Eq (n : Nat) : 2*n = n + n := by
rw [Nat.mul_comm]
show (0 + n) + n = n+n
simp
theorem ex3 (n : Nat) : Exists (fun m => n = m + m ∨ n = m + m + 1) := by
cases n using Nat.parityElim with
| even i =>
apply Exists.intro i
apply Or.inl
rw [time2Eq]
| odd i =>
apply Exists.intro i
apply Or.inr
rw [time2Eq]
open Nat in
theorem ex3b (n : Nat) : Exists (fun m => n = m + m ∨ n = m + m + 1) := by
cases n using parityElim with
| even i =>
apply Exists.intro i
apply Or.inl
rw [time2Eq]
| odd i =>
apply Exists.intro i
apply Or.inr
rw [time2Eq]
def ex4 {α} (xs : List α) (h : xs = [] → False) : α := by
cases he:xs with
| nil => contradiction
| cons x _ => exact x
def ex5 {α} (xs : List α) (h : xs = [] → False) : α := by
cases he:xs using List.casesOn with
| nil => contradiction
| cons x _ => exact x
theorem ex6 {α} (f : List α → Bool) (h₁ : {xs : List α} → f xs = true → xs = []) (xs : List α) (h₂ : xs ≠ []) : f xs = false :=
match he:f xs with
| true => False.elim (h₂ (h₁ he))
| false => rfl
theorem ex7 {α} (f : List α → Bool) (h₁ : {xs : List α} → f xs = true → xs = []) (xs : List α) (h₂ : xs ≠ []) : f xs = false := by
cases he:f xs with
| true => exact False.elim (h₂ (h₁ he))
| false => rfl
theorem ex8 {α} (f : List α → Bool) (h₁ : {xs : List α} → f xs = true → xs = []) (xs : List α) (h₂ : xs ≠ []) : f xs = false := by
cases he:f xs using Bool.casesOn with
| true => exact False.elim (h₂ (h₁ he))
| false => rfl
theorem ex9 (xs : List α) (h : xs = [] → False) : Nonempty α := by
cases xs using List.rec with
| nil => contradiction
| cons x _ => apply Nonempty.intro; assumption
theorem modLt (x : Nat) {y : Nat} (h : y > 0) : x % y < y := by
induction x, y using Nat.mod.inductionOn with
| ind x y h₁ ih =>
rw [Nat.mod_eq_sub_mod h₁.2]
exact ih h
| base x y h₁ =>
match Iff.mp (Decidable.not_and_iff_or_not ..) h₁ with
| Or.inl h₁ => contradiction
| Or.inr h₁ =>
have hgt := Nat.gt_of_not_le h₁
have heq := Nat.mod_eq_of_lt hgt
rw [← heq] at hgt
assumption
theorem ex11 {p q : Prop } (h : p ∨ q) : q ∨ p := by
induction h using Or.casesOn with
| inr h => ?myright
| inl h => ?myleft
case myleft => exact Or.inr h
case myright => exact Or.inl h
theorem ex12 {p q : Prop } (h : p ∨ q) : q ∨ p := by
cases h using Or.casesOn with
| inr h => ?myright
| inl h => ?myleft
case myleft => exact Or.inr h
case myright => exact Or.inl h
theorem ex13 (p q : Nat) : p ≤ q ∨ p > q := by
cases p, q using elimEx with
| diag => ?hdiag
| lower d => ?hlower
| upper d => ?hupper
case hdiag => apply Or.inl; apply Nat.le_refl
case hlower => apply Or.inl; show p ≤ p + d.succ; admit
case hupper => apply Or.inr; show q + d.succ > q; admit
theorem ex14 (p q : Nat) : p ≤ q ∨ p > q := by
cases p, q using elimEx with
| diag => ?hdiag
| lower d => _
| upper d => ?hupper
case hdiag => apply Or.inl; apply Nat.le_refl
case lower => apply Or.inl; show p ≤ p + d.succ; admit
case hupper => apply Or.inr; show q + d.succ > q; admit
theorem ex15 (p q : Nat) : p ≤ q ∨ p > q := by
cases p, q using elimEx with
| diag => ?hdiag
| lower d => _
| upper d => ?hupper
{ apply Or.inl; apply Nat.le_refl }
{ apply Or.inl; show p ≤ p + d.succ; admit }
{ apply Or.inr; show q + d.succ > q; admit }
theorem ex16 {p q : Prop} (h : p ∨ q) : q ∨ p := by
induction h
case inl h' => exact Or.inr h'
case inr h' => exact Or.inl h'
theorem ex17 (n : Nat) : 0 + n = n := by
induction n
case zero => rfl
case succ m ih =>
show Nat.succ (0 + m) = Nat.succ m
rw [ih]
|
850214eb214c4f644ed937cee21abd38bf642257 | 618003631150032a5676f229d13a079ac875ff77 | /src/tactic/omega/nat/dnf.lean | ba1b26ca7f32aa5e623b2420393f60d9af843715 | [
"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 | 4,950 | lean | /- Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Seul Baek
DNF transformation. -/
import tactic.omega.clause
import tactic.omega.nat.form
namespace omega
namespace nat
open_locale omega.nat
@[simp] def dnf_core : preform → list clause
| (p ∨* q) := (dnf_core p) ++ (dnf_core q)
| (p ∧* q) :=
(list.product (dnf_core p) (dnf_core q)).map
(λ pq, clause.append pq.fst pq.snd)
| (t =* s) :=
[([term.sub (canonize s) (canonize t)],[])]
| (t ≤* s) := [([],[term.sub (canonize s) (canonize t)])]
| (¬* _) := []
lemma exists_clause_holds_core {v : nat → nat} :
∀ {p : preform}, p.neg_free → p.sub_free → p.holds v →
∃ c ∈ (dnf_core p), clause.holds (λ x, ↑(v x)) c :=
begin
preform.induce `[intros h1 h0 h2],
{ apply list.exists_mem_cons_of,
constructor, rw list.forall_mem_singleton,
cases h0 with ht hs,
simp only [val_canonize ht, val_canonize hs,
term.val_sub, preform.holds, sub_eq_add_neg] at *,
rw [h2, add_neg_self], apply list.forall_mem_nil },
{ apply list.exists_mem_cons_of,
constructor,
apply list.forall_mem_nil,
rw list.forall_mem_singleton,
simp only [val_canonize (h0.left), val_canonize (h0.right),
term.val_sub, preform.holds, sub_eq_add_neg] at *,
rw [←sub_eq_add_neg, le_sub, sub_zero, int.coe_nat_le],
assumption },
{ cases h1 },
{ cases h2 with h2 h2;
[ {cases (ihp h1.left h0.left h2) with c h3},
{cases (ihq h1.right h0.right h2) with c h3}];
cases h3 with h3 h4;
refine ⟨c, list.mem_append.elim_right _, h4⟩;
[left,right]; assumption },
{ rcases (ihp h1.left h0.left h2.left) with ⟨cp, hp1, hp2⟩,
rcases (ihq h1.right h0.right h2.right) with ⟨cq, hq1, hq2⟩,
refine ⟨clause.append cp cq, ⟨_, clause.holds_append hp2 hq2⟩⟩,
simp only [dnf_core, list.mem_map],
refine ⟨(cp,cq),⟨_,rfl⟩⟩,
rw list.mem_product,
constructor; assumption }
end
def term.vars_core (is : list int) : list bool :=
is.map (λ i, if i = 0 then ff else tt)
/-- Return a list of bools that encodes which variables have nonzero coefficients -/
def term.vars (t : term) : list bool :=
term.vars_core t.snd
def bools.or : list bool → list bool → list bool
| [] bs2 := bs2
| bs1 [] := bs1
| (b1::bs1) (b2::bs2) := (b1 || b2)::(bools.or bs1 bs2)
/-- Return a list of bools that encodes which variables have nonzero coefficients in any one of the input terms -/
def terms.vars : list term → list bool
| [] := []
| (t::ts) := bools.or (term.vars t) (terms.vars ts)
open_locale list.func -- get notation for list.func.set
def nonneg_consts_core : nat → list bool → list term
| _ [] := []
| k (ff::bs) := nonneg_consts_core (k+1) bs
| k (tt::bs) := ⟨0, [] {k ↦ 1}⟩::nonneg_consts_core (k+1) bs
def nonneg_consts (bs : list bool) : list term :=
nonneg_consts_core 0 bs
def nonnegate : clause → clause | (eqs,les) :=
let xs := terms.vars eqs in
let ys := terms.vars les in
let bs := bools.or xs ys in
(eqs, nonneg_consts bs ++ les)
/-- DNF transformation -/
def dnf (p : preform) : list clause :=
(dnf_core p).map nonnegate
lemma holds_nonneg_consts_core {v : nat → int} (h1 : ∀ x, 0 ≤ v x) :
∀ m bs, (∀ t ∈ (nonneg_consts_core m bs), 0 ≤ term.val v t)
| _ [] := λ _ h2, by cases h2
| k (ff::bs) := holds_nonneg_consts_core (k+1) bs
| k (tt::bs) :=
begin
simp only [nonneg_consts_core],
rw list.forall_mem_cons,
constructor,
{ simp only [term.val, one_mul, zero_add, coeffs.val_set],
apply h1 },
{ apply holds_nonneg_consts_core (k+1) bs }
end
lemma holds_nonneg_consts {v : nat → int} {bs : list bool} :
(∀ x, 0 ≤ v x) → (∀ t ∈ (nonneg_consts bs), 0 ≤ term.val v t)
| h1 :=
by apply holds_nonneg_consts_core h1
lemma exists_clause_holds {v : nat → nat} {p : preform} :
p.neg_free → p.sub_free → p.holds v →
∃ c ∈ (dnf p), clause.holds (λ x, ↑(v x)) c :=
begin
intros h1 h2 h3,
rcases (exists_clause_holds_core h1 h2 h3) with ⟨c,h4,h5⟩,
existsi (nonnegate c),
have h6 : nonnegate c ∈ dnf p,
{ simp only [dnf], rw list.mem_map,
refine ⟨c,h4,rfl⟩ },
refine ⟨h6,_⟩, cases c with eqs les,
simp only [nonnegate, clause.holds],
constructor, apply h5.left,
rw list.forall_mem_append,
apply and.intro (holds_nonneg_consts _) h5.right,
apply int.coe_nat_nonneg
end
lemma exists_clause_sat {p : preform} :
p.neg_free → p.sub_free →
p.sat → ∃ c ∈ (dnf p), clause.sat c :=
begin
intros h1 h2 h3, cases h3 with v h3,
rcases (exists_clause_holds h1 h2 h3) with ⟨c,h4,h5⟩,
refine ⟨c,h4,_,h5⟩
end
lemma unsat_of_unsat_dnf (p : preform) :
p.neg_free → p.sub_free → clauses.unsat (dnf p) → p.unsat :=
begin
intros hnf hsf h1 h2, apply h1,
apply exists_clause_sat hnf hsf h2
end
end nat
end omega
|
dec7116f704df2a7ec13f0504697416327c3b576 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebra/group/ulift.lean | 49fff01eb444d87b8608d9410a486e2ac861295b | [] | 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,009 | 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.data.equiv.mul_add
import Mathlib.PostPort
universes u u_1 v
namespace Mathlib
/-!
# `ulift` instances for groups and monoids
This file defines instances for group, monoid, semigroup and related structures on `ulift` types.
(Recall `ulift α` is just a "copy" of a type `α` in a higher universe.)
We use `tactic.pi_instance_derive_field`, even though it wasn't intended for this purpose,
which seems to work fine.
We also provide `ulift.mul_equiv : ulift R ≃* R` (and its additive analogue).
-/
namespace ulift
protected instance has_one {α : Type u} [HasOne α] : HasOne (ulift α) :=
{ one := up 1 }
@[simp] theorem one_down {α : Type u} [HasOne α] : down 1 = 1 :=
rfl
protected instance has_mul {α : Type u} [Mul α] : Mul (ulift α) :=
{ mul := fun (f g : ulift α) => up (down f * down g) }
@[simp] theorem add_down {α : Type u} {x : ulift α} {y : ulift α} [Add α] : down (x + y) = down x + down y :=
rfl
protected instance has_sub {α : Type u} [Sub α] : Sub (ulift α) :=
{ sub := fun (f g : ulift α) => up (down f - down g) }
@[simp] theorem sub_down {α : Type u} {x : ulift α} {y : ulift α} [Sub α] : down (x - y) = down x - down y :=
rfl
protected instance has_inv {α : Type u} [has_inv α] : has_inv (ulift α) :=
has_inv.mk fun (f : ulift α) => up (down f⁻¹)
@[simp] theorem neg_down {α : Type u} {x : ulift α} [Neg α] : down (-x) = -down x :=
rfl
protected instance add_semigroup {α : Type u} [add_semigroup α] : add_semigroup (ulift α) :=
add_semigroup.mk Add.add sorry
/--
The multiplicative equivalence between `ulift α` and `α`.
-/
def mul_equiv {α : Type u} [semigroup α] : ulift α ≃* α :=
mul_equiv.mk down up sorry sorry sorry
protected instance add_comm_semigroup {α : Type u} [add_comm_semigroup α] : add_comm_semigroup (ulift α) :=
add_comm_semigroup.mk Add.add sorry sorry
protected instance monoid {α : Type u} [monoid α] : monoid (ulift α) :=
monoid.mk Mul.mul sorry 1 sorry sorry
protected instance comm_monoid {α : Type u} [comm_monoid α] : comm_monoid (ulift α) :=
comm_monoid.mk Mul.mul sorry 1 sorry sorry sorry
protected instance group {α : Type u} [group α] : group (ulift α) :=
group.mk Mul.mul sorry 1 sorry sorry has_inv.inv Div.div sorry
protected instance comm_group {α : Type u} [comm_group α] : comm_group (ulift α) :=
comm_group.mk Mul.mul sorry 1 sorry sorry has_inv.inv Div.div sorry sorry
protected instance left_cancel_semigroup {α : Type u} [left_cancel_semigroup α] : left_cancel_semigroup (ulift α) :=
left_cancel_semigroup.mk Mul.mul sorry sorry
protected instance right_cancel_semigroup {α : Type u} [right_cancel_semigroup α] : right_cancel_semigroup (ulift α) :=
right_cancel_semigroup.mk Mul.mul sorry sorry
|
3dfa08eae8a164af292cc22d8373e1196d10a552 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/analysis/calculus/extend_deriv.lean | 62f9065ef2309219a3c27d256bbfbb986ff3892f | [
"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 | 11,570 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import analysis.calculus.mean_value
/-!
# Extending differentiability to the boundary
We investigate how differentiable functions inside a set extend to differentiable functions
on the boundary. For this, it suffices that the function and its derivative admit limits there.
A general version of this statement is given in `has_fderiv_at_boundary_of_tendsto_fderiv`.
One-dimensional versions, in which one wants to obtain differentiability at the left endpoint or
the right endpoint of an interval, are given in
`has_deriv_at_interval_left_endpoint_of_tendsto_deriv` and
`has_deriv_at_interval_right_endpoint_of_tendsto_deriv`. These versions are formulated in terms
of the one-dimensional derivative `deriv ℝ f`.
-/
variables {E : Type*} [normed_group E] [normed_space ℝ E]
{F : Type*} [normed_group F] [normed_space ℝ F]
open filter set metric continuous_linear_map
open_locale topological_space
local attribute [mono] prod_mono
/-- If a function `f` is differentiable in a convex open set and continuous on its closure, and its
derivative converges to a limit `f'` at a point on the boundary, then `f` is differentiable there
with derivative `f'`. -/
theorem has_fderiv_at_boundary_of_tendsto_fderiv {f : E → F} {s : set E} {x : E} {f' : E →L[ℝ] F}
(f_diff : differentiable_on ℝ f s) (s_conv : convex ℝ s) (s_open : is_open s)
(f_cont : ∀y ∈ closure s, continuous_within_at f s y)
(h : tendsto (λy, fderiv ℝ f y) (𝓝[s] x) (𝓝 f')) :
has_fderiv_within_at f f' (closure s) x :=
begin
classical,
-- one can assume without loss of generality that `x` belongs to the closure of `s`, as the
-- statement is empty otherwise
by_cases hx : x ∉ closure s,
{ rw ← closure_closure at hx, exact has_fderiv_within_at_of_not_mem_closure hx },
push_neg at hx,
rw [has_fderiv_within_at, has_fderiv_at_filter, asymptotics.is_o_iff],
/- One needs to show that `∥f y - f x - f' (y - x)∥ ≤ ε ∥y - x∥` for `y` close to `x` in `closure
s`, where `ε` is an arbitrary positive constant. By continuity of the functions, it suffices to
prove this for nearby points inside `s`. In a neighborhood of `x`, the derivative of `f` is
arbitrarily close to `f'` by assumption. The mean value inequality completes the proof. -/
assume ε ε_pos,
obtain ⟨δ, δ_pos, hδ⟩ : ∃ δ > 0, ∀ y ∈ s, dist y x < δ → ∥fderiv ℝ f y - f'∥ < ε,
by simpa [dist_zero_right] using tendsto_nhds_within_nhds.1 h ε ε_pos,
set B := ball x δ,
suffices : ∀ y ∈ B ∩ (closure s), ∥f y - f x - (f' y - f' x)∥ ≤ ε * ∥y - x∥,
from mem_nhds_within_iff.2 ⟨δ, δ_pos, λy hy, by simpa using this y hy⟩,
suffices : ∀ p : E × E, p ∈ closure ((B ∩ s).prod (B ∩ s)) → ∥f p.2 - f p.1 - (f' p.2 - f' p.1)∥
≤ ε * ∥p.2 - p.1∥,
{ rw closure_prod_eq at this,
intros y y_in,
apply this ⟨x, y⟩,
have : B ∩ closure s ⊆ closure (B ∩ s), from closure_inter_open is_open_ball,
exact ⟨this ⟨mem_ball_self δ_pos, hx⟩, this y_in⟩ },
have key : ∀ p : E × E, p ∈ (B ∩ s).prod (B ∩ s) → ∥f p.2 - f p.1 - (f' p.2 - f' p.1)∥
≤ ε * ∥p.2 - p.1∥,
{ rintros ⟨u, v⟩ ⟨u_in, v_in⟩,
have conv : convex ℝ (B ∩ s) := (convex_ball _ _).inter s_conv,
have diff : differentiable_on ℝ f (B ∩ s) := f_diff.mono (inter_subset_right _ _),
have bound : ∀ z ∈ (B ∩ s), ∥fderiv_within ℝ f (B ∩ s) z - f'∥ ≤ ε,
{ intros z z_in,
convert le_of_lt (hδ _ z_in.2 z_in.1),
have op : is_open (B ∩ s) := is_open_ball.inter s_open,
rw differentiable_at.fderiv_within _ (op.unique_diff_on z z_in),
exact (diff z z_in).differentiable_at (is_open.mem_nhds op z_in) },
simpa using conv.norm_image_sub_le_of_norm_fderiv_within_le' diff bound u_in v_in },
rintros ⟨u, v⟩ uv_in,
refine continuous_within_at.closure_le uv_in _ _ key,
have f_cont' : ∀y ∈ closure s, continuous_within_at (f - f') s y,
{ intros y y_in,
exact tendsto.sub (f_cont y y_in) (f'.cont.continuous_within_at) },
all_goals { -- common start for both continuity proofs
have : (B ∩ s).prod (B ∩ s) ⊆ s.prod s, by mono ; exact inter_subset_right _ _,
obtain ⟨u_in, v_in⟩ : u ∈ closure s ∧ v ∈ closure s,
by simpa [closure_prod_eq] using closure_mono this uv_in,
apply continuous_within_at.mono _ this,
simp only [continuous_within_at] },
rw nhds_within_prod_eq,
{ have : ∀ u v, f v - f u - (f' v - f' u) = f v - f' v - (f u - f' u) := by { intros, abel },
simp only [this],
exact tendsto.comp continuous_norm.continuous_at
((tendsto.comp (f_cont' v v_in) tendsto_snd).sub $
tendsto.comp (f_cont' u u_in) tendsto_fst) },
{ apply tendsto_nhds_within_of_tendsto_nhds,
rw nhds_prod_eq,
exact tendsto_const_nhds.mul
(tendsto.comp continuous_norm.continuous_at $ tendsto_snd.sub tendsto_fst) },
end
/-- If a function is differentiable on the right of a point `a : ℝ`, continuous at `a`, and
its derivative also converges at `a`, then `f` is differentiable on the right at `a`. -/
lemma has_deriv_at_interval_left_endpoint_of_tendsto_deriv {s : set ℝ} {e : E} {a : ℝ} {f : ℝ → E}
(f_diff : differentiable_on ℝ f s) (f_lim : continuous_within_at f s a)
(hs : s ∈ 𝓝[Ioi a] a)
(f_lim' : tendsto (λx, deriv f x) (𝓝[Ioi a] a) (𝓝 e)) :
has_deriv_within_at f e (Ici a) a :=
begin
/- This is a specialization of `has_fderiv_at_boundary_of_tendsto_fderiv`. To be in the setting of
this theorem, we need to work on an open interval with closure contained in `s ∪ {a}`, that we
call `t = (a, b)`. Then, we check all the assumptions of this theorem and we apply it. -/
obtain ⟨b, ab, sab⟩ : ∃ b ∈ Ioi a, Ioc a b ⊆ s :=
mem_nhds_within_Ioi_iff_exists_Ioc_subset.1 hs,
let t := Ioo a b,
have ts : t ⊆ s := subset.trans Ioo_subset_Ioc_self sab,
have t_diff : differentiable_on ℝ f t := f_diff.mono ts,
have t_conv : convex ℝ t := convex_Ioo a b,
have t_open : is_open t := is_open_Ioo,
have t_closure : closure t = Icc a b := closure_Ioo ab,
have t_cont : ∀y ∈ closure t, continuous_within_at f t y,
{ rw t_closure,
assume y hy,
by_cases h : y = a,
{ rw h, exact f_lim.mono ts },
{ have : y ∈ s := sab ⟨lt_of_le_of_ne hy.1 (ne.symm h), hy.2⟩,
exact (f_diff.continuous_on y this).mono ts } },
have t_diff' : tendsto (λx, fderiv ℝ f x) (𝓝[t] a) (𝓝 (smul_right 1 e)),
{ simp [deriv_fderiv.symm],
refine tendsto.comp is_bounded_bilinear_map_smul_right.continuous_right.continuous_at _,
exact tendsto_nhds_within_mono_left Ioo_subset_Ioi_self f_lim' },
-- now we can apply `has_fderiv_at_boundary_of_differentiable`
have : has_deriv_within_at f e (Icc a b) a,
{ rw [has_deriv_within_at_iff_has_fderiv_within_at, ← t_closure],
exact has_fderiv_at_boundary_of_tendsto_fderiv t_diff t_conv t_open t_cont t_diff' },
exact this.nhds_within (mem_nhds_within_Ici_iff_exists_Icc_subset.2 ⟨b, ab, subset.refl _⟩)
end
/-- If a function is differentiable on the left of a point `a : ℝ`, continuous at `a`, and
its derivative also converges at `a`, then `f` is differentiable on the left at `a`. -/
lemma has_deriv_at_interval_right_endpoint_of_tendsto_deriv {s : set ℝ} {e : E} {a : ℝ} {f : ℝ → E}
(f_diff : differentiable_on ℝ f s) (f_lim : continuous_within_at f s a)
(hs : s ∈ 𝓝[Iio a] a)
(f_lim' : tendsto (λx, deriv f x) (𝓝[Iio a] a) (𝓝 e)) :
has_deriv_within_at f e (Iic a) a :=
begin
/- This is a specialization of `has_fderiv_at_boundary_of_differentiable`. To be in the setting of
this theorem, we need to work on an open interval with closure contained in `s ∪ {a}`, that we
call `t = (b, a)`. Then, we check all the assumptions of this theorem and we apply it. -/
obtain ⟨b, ba, sab⟩ : ∃ b ∈ Iio a, Ico b a ⊆ s :=
mem_nhds_within_Iio_iff_exists_Ico_subset.1 hs,
let t := Ioo b a,
have ts : t ⊆ s := subset.trans Ioo_subset_Ico_self sab,
have t_diff : differentiable_on ℝ f t := f_diff.mono ts,
have t_conv : convex ℝ t := convex_Ioo b a,
have t_open : is_open t := is_open_Ioo,
have t_closure : closure t = Icc b a := closure_Ioo ba,
have t_cont : ∀y ∈ closure t, continuous_within_at f t y,
{ rw t_closure,
assume y hy,
by_cases h : y = a,
{ rw h, exact f_lim.mono ts },
{ have : y ∈ s := sab ⟨hy.1, lt_of_le_of_ne hy.2 h⟩,
exact (f_diff.continuous_on y this).mono ts } },
have t_diff' : tendsto (λx, fderiv ℝ f x) (𝓝[t] a) (𝓝 (smul_right 1 e)),
{ simp [deriv_fderiv.symm],
refine tendsto.comp is_bounded_bilinear_map_smul_right.continuous_right.continuous_at _,
exact tendsto_nhds_within_mono_left Ioo_subset_Iio_self f_lim' },
-- now we can apply `has_fderiv_at_boundary_of_differentiable`
have : has_deriv_within_at f e (Icc b a) a,
{ rw [has_deriv_within_at_iff_has_fderiv_within_at, ← t_closure],
exact has_fderiv_at_boundary_of_tendsto_fderiv t_diff t_conv t_open t_cont t_diff' },
exact this.nhds_within (mem_nhds_within_Iic_iff_exists_Icc_subset.2 ⟨b, ba, subset.refl _⟩)
end
/-- If a real function `f` has a derivative `g` everywhere but at a point, and `f` and `g` are
continuous at this point, then `g` is also the derivative of `f` at this point. -/
lemma has_deriv_at_of_has_deriv_at_of_ne {f g : ℝ → E} {x : ℝ}
(f_diff : ∀ y ≠ x, has_deriv_at f (g y) y)
(hf : continuous_at f x) (hg : continuous_at g x) :
has_deriv_at f (g x) x :=
begin
have A : has_deriv_within_at f (g x) (Ici x) x,
{ have diff : differentiable_on ℝ f (Ioi x) :=
λy hy, (f_diff y (ne_of_gt hy)).differentiable_at.differentiable_within_at,
-- next line is the nontrivial bit of this proof, appealing to differentiability
-- extension results.
apply has_deriv_at_interval_left_endpoint_of_tendsto_deriv diff hf.continuous_within_at
self_mem_nhds_within,
have : tendsto g (𝓝[Ioi x] x) (𝓝 (g x)) := tendsto_inf_left hg,
apply this.congr' _,
apply mem_of_superset self_mem_nhds_within (λy hy, _),
exact (f_diff y (ne_of_gt hy)).deriv.symm },
have B : has_deriv_within_at f (g x) (Iic x) x,
{ have diff : differentiable_on ℝ f (Iio x) :=
λy hy, (f_diff y (ne_of_lt hy)).differentiable_at.differentiable_within_at,
-- next line is the nontrivial bit of this proof, appealing to differentiability
-- extension results.
apply has_deriv_at_interval_right_endpoint_of_tendsto_deriv diff hf.continuous_within_at
self_mem_nhds_within,
have : tendsto g (𝓝[Iio x] x) (𝓝 (g x)) := tendsto_inf_left hg,
apply this.congr' _,
apply mem_of_superset self_mem_nhds_within (λy hy, _),
exact (f_diff y (ne_of_lt hy)).deriv.symm },
simpa using B.union A
end
/-- If a real function `f` has a derivative `g` everywhere but at a point, and `f` and `g` are
continuous at this point, then `g` is the derivative of `f` everywhere. -/
lemma has_deriv_at_of_has_deriv_at_of_ne' {f g : ℝ → E} {x : ℝ}
(f_diff : ∀ y ≠ x, has_deriv_at f (g y) y)
(hf : continuous_at f x) (hg : continuous_at g x) (y : ℝ) :
has_deriv_at f (g y) y :=
begin
rcases eq_or_ne y x with rfl|hne,
{ exact has_deriv_at_of_has_deriv_at_of_ne f_diff hf hg },
{ exact f_diff y hne }
end
|
e1b7a32d72df9fca1381b281f9cf60295a908995 | 36c7a18fd72e5b57229bd8ba36493daf536a19ce | /tests/lean/run/blast_cc11.lean | d71a01c77c03dc739f23b3a06e9fd703e4d4d0fe | [
"Apache-2.0"
] | permissive | YHVHvx/lean | 732bf0fb7a298cd7fe0f15d82f8e248c11db49e9 | 038369533e0136dd395dc252084d3c1853accbf2 | refs/heads/master | 1,610,701,080,210 | 1,449,128,595,000 | 1,449,128,595,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 876 | lean | import data.list
set_option blast.subst false
set_option blast.simp false
definition t1 (a b : nat) : (a = b) ↔ (b = a) :=
by blast
print t1
definition t2 (a b : nat) : (a = b) = (b = a) :=
by blast
print t2
definition t3 (a b : nat) : (a = b) == (b = a) :=
by blast
print t3
open perm
definition t4 (a b : list nat) : (a ~ b) ↔ (b ~ a) :=
by blast
definition t5 (a b : list nat) : (a ~ b) = (b ~ a) :=
by blast
definition t6 (a b : list nat) : (a ~ b) == (b ~ a) :=
by blast
definition t7 (p : Prop) (a b : nat) : a = b → b ≠ a → p :=
by blast
definition t8 (a b : Prop) : (a ↔ b) → ((b ↔ a) ↔ (a ↔ b)) :=
by blast
definition t9 (a b c : nat) : b = c → (a = b ↔ c = a) :=
by blast
definition t10 (a b c : list nat) : b ~ c → (a ~ b ↔ c ~ a) :=
by blast
definition t11 (a b c : list nat) : b ~ c → ((a ~ b) = (c ~ a)) :=
by blast
|
1f218dda705ddd1f84a50aaef75e9ba22729d93a | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /tests/lean/interactive/plainTermGoal.lean | c8e92d29240dd43eef726aa68dd174c266466234 | [
"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 | 873 | lean |
example : 0 < 2 :=
Nat.ltTrans Nat.zeroLtOne (Nat.ltSuccSelf _)
--^ $/lean/plainTermGoal
--^ $/lean/plainTermGoal
--^ $/lean/plainTermGoal
--^ $/lean/plainTermGoal
--^ $/lean/plainTermGoal
example : OptionM Unit := do
let y : Int ← none
let x ← Nat.zero
--^ $/lean/plainTermGoal
return ()
example (m n : Nat) : m < n :=
Nat.ltTrans _ _
--^ $/lean/plainTermGoal
example : True := sorry
--^ $/lean/plainTermGoal
example : ∀ n, n < n + 42 :=
fun n => Nat.ltOfLeOfLt (Nat.leAddRight n 41) (Nat.ltSuccSelf _)
--^ $/lean/plainTermGoal
--^ $/lean/plainTermGoal
example : ∀ n, n < 1 + n := by
intro n
rw [Nat.add_comm]
--^ $/lean/plainTermGoal
exact Nat.ltSuccSelf _
--^ $/lean/plainTermGoal
|
4ec9fa5126d71f7295fc9b6d7bdc93dfb6082b37 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/algebraic_geometry/gluing.lean | 9fc37f88a00ca312ca7bf5a4fded05743a34c127 | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 17,336 | lean | /-
Copyright (c) 2022 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import algebraic_geometry.presheafed_space.gluing
/-!
# Gluing Schemes
Given a family of gluing data of schemes, we may glue them together.
## Main definitions
* `algebraic_geometry.Scheme.glue_data`: A structure containing the family of gluing data.
* `algebraic_geometry.Scheme.glue_data.glued`: The glued scheme.
This is defined as the multicoequalizer of `∐ V i j ⇉ ∐ U i`, so that the general colimit API
can be used.
* `algebraic_geometry.Scheme.glue_data.ι`: The immersion `ι i : U i ⟶ glued` for each `i : J`.
* `algebraic_geometry.Scheme.glue_data.iso_carrier`: The isomorphism between the underlying space
of the glued scheme and the gluing of the underlying topological spaces.
* `algebraic_geometry.Scheme.open_cover.glue_data`: The glue data associated with an open cover.
* `algebraic_geometry.Scheme.open_cover.from_glue_data`: The canonical morphism
`𝒰.glue_data.glued ⟶ X`. This has an `is_iso` instance.
* `algebraic_geometry.Scheme.open_cover.glue_morphisms`: We may glue a family of compatible
morphisms defined on an open cover of a scheme.
## Main results
* `algebraic_geometry.Scheme.glue_data.ι_is_open_immersion`: The map `ι i : U i ⟶ glued`
is an open immersion for each `i : J`.
* `algebraic_geometry.Scheme.glue_data.ι_jointly_surjective` : The underlying maps of
`ι i : U i ⟶ glued` are jointly surjective.
* `algebraic_geometry.Scheme.glue_data.V_pullback_cone_is_limit` : `V i j` is the pullback
(intersection) of `U i` and `U j` over the glued space.
* `algebraic_geometry.Scheme.glue_data.ι_eq_iff_rel` : `ι i x = ι j y` if and only if they coincide
when restricted to `V i i`.
* `algebraic_geometry.Scheme.glue_data.is_open_iff` : An subset of the glued scheme is open iff
all its preimages in `U i` are open.
## Implementation details
All the hard work is done in `algebraic_geometry/presheafed_space/gluing.lean` where we glue
presheafed spaces, sheafed spaces, and locally ringed spaces.
-/
noncomputable theory
universe u
open topological_space category_theory opposite
open category_theory.limits algebraic_geometry.PresheafedSpace
open category_theory.glue_data
namespace algebraic_geometry
namespace Scheme
/--
A family of gluing data consists of
1. An index type `J`
2. An scheme `U i` for each `i : J`.
3. An scheme `V i j` for each `i j : J`.
(Note that this is `J × J → Scheme` rather than `J → J → Scheme` to connect to the
limits library easier.)
4. An open immersion `f i j : V i j ⟶ U i` for each `i j : ι`.
5. A transition map `t i j : V i j ⟶ V j i` for each `i j : ι`.
such that
6. `f i i` is an isomorphism.
7. `t i i` is the identity.
8. `V i j ×[U i] V i k ⟶ V i j ⟶ V j i` factors through `V j k ×[U j] V j i ⟶ V j i` via some
`t' : V i j ×[U i] V i k ⟶ V j k ×[U j] V j i`.
9. `t' i j k ≫ t' j k i ≫ t' k i j = 𝟙 _`.
We can then glue the schemes `U i` together by identifying `V i j` with `V j i`, such
that the `U i`'s are open subschemes of the glued space.
-/
@[nolint has_nonempty_instance]
structure glue_data extends category_theory.glue_data Scheme :=
(f_open : ∀ i j, is_open_immersion (f i j))
attribute [instance] glue_data.f_open
namespace glue_data
variables (D : glue_data)
include D
local notation `𝖣` := D.to_glue_data
/-- The glue data of locally ringed spaces spaces associated to a family of glue data of schemes. -/
abbreviation to_LocallyRingedSpace_glue_data : LocallyRingedSpace.glue_data :=
{ f_open := D.f_open,
to_glue_data := 𝖣 .map_glue_data forget_to_LocallyRingedSpace }
/-- (Implementation). The glued scheme of a glue data.
This should not be used outside this file. Use `Scheme.glue_data.glued` instead. -/
def glued_Scheme : Scheme :=
begin
apply LocallyRingedSpace.is_open_immersion.Scheme
D.to_LocallyRingedSpace_glue_data.to_glue_data.glued,
intro x,
obtain ⟨i, y, rfl⟩ := D.to_LocallyRingedSpace_glue_data.ι_jointly_surjective x,
refine ⟨_, _ ≫ D.to_LocallyRingedSpace_glue_data.to_glue_data.ι i, _⟩,
swap, exact (D.U i).affine_cover.map y,
split,
{ dsimp [-set.mem_range],
rw [coe_comp, set.range_comp],
refine set.mem_image_of_mem _ _,
exact (D.U i).affine_cover.covers y },
{ apply_instance },
end
instance : creates_colimit 𝖣 .diagram.multispan forget_to_LocallyRingedSpace :=
creates_colimit_of_fully_faithful_of_iso D.glued_Scheme
(has_colimit.iso_of_nat_iso (𝖣 .diagram_iso forget_to_LocallyRingedSpace).symm)
instance : preserves_colimit 𝖣 .diagram.multispan forget_to_Top :=
begin
delta forget_to_Top LocallyRingedSpace.forget_to_Top,
apply_instance,
end
instance : has_multicoequalizer 𝖣 .diagram :=
has_colimit_of_created _ forget_to_LocallyRingedSpace
/-- The glued scheme of a glued space. -/
abbreviation glued : Scheme := 𝖣 .glued
/-- The immersion from `D.U i` into the glued space. -/
abbreviation ι (i : D.J) : D.U i ⟶ D.glued := 𝖣 .ι i
/-- The gluing as sheafed spaces is isomorphic to the gluing as presheafed spaces. -/
abbreviation iso_LocallyRingedSpace :
D.glued.to_LocallyRingedSpace ≅ D.to_LocallyRingedSpace_glue_data.to_glue_data.glued :=
𝖣 .glued_iso forget_to_LocallyRingedSpace
lemma ι_iso_LocallyRingedSpace_inv (i : D.J) :
D.to_LocallyRingedSpace_glue_data.to_glue_data.ι i ≫ D.iso_LocallyRingedSpace.inv = 𝖣 .ι i :=
𝖣 .ι_glued_iso_inv forget_to_LocallyRingedSpace i
instance ι_is_open_immersion (i : D.J) :
is_open_immersion (𝖣 .ι i) :=
by { rw ← D.ι_iso_LocallyRingedSpace_inv, apply_instance }
lemma ι_jointly_surjective (x : 𝖣 .glued.carrier) :
∃ (i : D.J) (y : (D.U i).carrier), (D.ι i).1.base y = x :=
𝖣 .ι_jointly_surjective (forget_to_Top ⋙ forget Top) x
@[simp, reassoc]
lemma glue_condition (i j : D.J) :
D.t i j ≫ D.f j i ≫ D.ι j = D.f i j ≫ D.ι i :=
𝖣 .glue_condition i j
/-- The pullback cone spanned by `V i j ⟶ U i` and `V i j ⟶ U j`.
This is a pullback diagram (`V_pullback_cone_is_limit`). -/
def V_pullback_cone (i j : D.J) : pullback_cone (D.ι i) (D.ι j) :=
pullback_cone.mk (D.f i j) (D.t i j ≫ D.f j i) (by simp)
/-- The following diagram is a pullback, i.e. `Vᵢⱼ` is the intersection of `Uᵢ` and `Uⱼ` in `X`.
Vᵢⱼ ⟶ Uᵢ
| |
↓ ↓
Uⱼ ⟶ X
-/
def V_pullback_cone_is_limit (i j : D.J) :
is_limit (D.V_pullback_cone i j) :=
𝖣 .V_pullback_cone_is_limit_of_map forget_to_LocallyRingedSpace i j
(D.to_LocallyRingedSpace_glue_data.V_pullback_cone_is_limit _ _)
/-- The underlying topological space of the glued scheme is isomorphic to the gluing of the
underlying spacess -/
def iso_carrier :
D.glued.carrier ≅ D.to_LocallyRingedSpace_glue_data.to_SheafedSpace_glue_data
.to_PresheafedSpace_glue_data.to_Top_glue_data.to_glue_data.glued :=
begin
refine (PresheafedSpace.forget _).map_iso _ ≪≫
glue_data.glued_iso _ (PresheafedSpace.forget _),
refine SheafedSpace.forget_to_PresheafedSpace.map_iso _ ≪≫
SheafedSpace.glue_data.iso_PresheafedSpace _,
refine LocallyRingedSpace.forget_to_SheafedSpace.map_iso _ ≪≫
LocallyRingedSpace.glue_data.iso_SheafedSpace _,
exact Scheme.glue_data.iso_LocallyRingedSpace _
end
@[simp]
lemma ι_iso_carrier_inv (i : D.J) :
D.to_LocallyRingedSpace_glue_data.to_SheafedSpace_glue_data
.to_PresheafedSpace_glue_data.to_Top_glue_data.to_glue_data.ι i ≫ D.iso_carrier.inv =
(D.ι i).1.base :=
begin
delta iso_carrier,
simp only [functor.map_iso_inv, iso.trans_inv, iso.trans_assoc,
glue_data.ι_glued_iso_inv_assoc, functor.map_iso_trans, category.assoc],
iterate 3 { erw ← comp_base },
simp_rw ← category.assoc,
rw D.to_LocallyRingedSpace_glue_data.to_SheafedSpace_glue_data.ι_iso_PresheafedSpace_inv i,
erw D.to_LocallyRingedSpace_glue_data.ι_iso_SheafedSpace_inv i,
change (_ ≫ D.iso_LocallyRingedSpace.inv).1.base = _,
rw D.ι_iso_LocallyRingedSpace_inv i
end
/-- An equivalence relation on `Σ i, D.U i` that holds iff `𝖣 .ι i x = 𝖣 .ι j y`.
See `Scheme.gluing_data.ι_eq_iff`. -/
def rel (a b : Σ i, ((D.U i).carrier : Type*)) : Prop :=
a = b ∨ ∃ (x : (D.V (a.1, b.1)).carrier),
(D.f _ _).1.base x = a.2 ∧ (D.t _ _ ≫ D.f _ _).1.base x = b.2
lemma ι_eq_iff (i j : D.J) (x : (D.U i).carrier) (y : (D.U j).carrier) :
(𝖣 .ι i).1.base x = (𝖣 .ι j).1.base y ↔ D.rel ⟨i, x⟩ ⟨j, y⟩ :=
begin
refine iff.trans _ (D.to_LocallyRingedSpace_glue_data.to_SheafedSpace_glue_data
.to_PresheafedSpace_glue_data.to_Top_glue_data.ι_eq_iff_rel i j x y),
rw ← ((Top.mono_iff_injective D.iso_carrier.inv).mp infer_instance).eq_iff,
simp_rw [← comp_apply, D.ι_iso_carrier_inv]
end
lemma is_open_iff (U : set D.glued.carrier) : is_open U ↔ ∀ i, is_open ((D.ι i).1.base ⁻¹' U) :=
begin
rw ← (Top.homeo_of_iso D.iso_carrier.symm).is_open_preimage,
rw Top.glue_data.is_open_iff,
apply forall_congr,
intro i,
erw [← set.preimage_comp, ← coe_comp, ι_iso_carrier_inv]
end
/-- The open cover of the glued space given by the glue data. -/
def open_cover (D : Scheme.glue_data) : open_cover D.glued :=
{ J := D.J,
obj := D.U,
map := D.ι,
f := λ x, (D.ι_jointly_surjective x).some,
covers := λ x, ⟨_, (D.ι_jointly_surjective x).some_spec.some_spec⟩ }
end glue_data
namespace open_cover
variables {X : Scheme.{u}} (𝒰 : open_cover.{u} X)
/-- (Implementation) the transition maps in the glue data associated with an open cover. -/
def glued_cover_t' (x y z : 𝒰.J) :
pullback (pullback.fst : pullback (𝒰.map x) (𝒰.map y) ⟶ _)
(pullback.fst : pullback (𝒰.map x) (𝒰.map z) ⟶ _) ⟶
pullback (pullback.fst : pullback (𝒰.map y) (𝒰.map z) ⟶ _)
(pullback.fst : pullback (𝒰.map y) (𝒰.map x) ⟶ _) :=
begin
refine (pullback_right_pullback_fst_iso _ _ _).hom ≫ _,
refine _ ≫ (pullback_symmetry _ _).hom,
refine _ ≫ (pullback_right_pullback_fst_iso _ _ _).inv,
refine pullback.map _ _ _ _ (pullback_symmetry _ _).hom (𝟙 _) (𝟙 _) _ _,
{ simp [pullback.condition] },
{ simp }
end
@[simp, reassoc]
lemma glued_cover_t'_fst_fst (x y z : 𝒰.J) :
𝒰.glued_cover_t' x y z ≫ pullback.fst ≫ pullback.fst = pullback.fst ≫ pullback.snd :=
by { delta glued_cover_t', simp }
@[simp, reassoc]
lemma glued_cover_t'_fst_snd (x y z : 𝒰.J) :
glued_cover_t' 𝒰 x y z ≫ pullback.fst ≫ pullback.snd = pullback.snd ≫ pullback.snd :=
by { delta glued_cover_t', simp }
@[simp, reassoc]
lemma glued_cover_t'_snd_fst (x y z : 𝒰.J) :
glued_cover_t' 𝒰 x y z ≫ pullback.snd ≫ pullback.fst = pullback.fst ≫ pullback.snd :=
by { delta glued_cover_t', simp }
@[simp, reassoc]
lemma glued_cover_t'_snd_snd (x y z : 𝒰.J) :
glued_cover_t' 𝒰 x y z ≫ pullback.snd ≫ pullback.snd = pullback.fst ≫ pullback.fst :=
by { delta glued_cover_t', simp }
lemma glued_cover_cocycle_fst (x y z : 𝒰.J) :
glued_cover_t' 𝒰 x y z ≫ glued_cover_t' 𝒰 y z x ≫ glued_cover_t' 𝒰 z x y ≫ pullback.fst =
pullback.fst :=
by apply pullback.hom_ext; simp
lemma glued_cover_cocycle_snd (x y z : 𝒰.J) :
glued_cover_t' 𝒰 x y z ≫ glued_cover_t' 𝒰 y z x ≫ glued_cover_t' 𝒰 z x y ≫ pullback.snd =
pullback.snd :=
by apply pullback.hom_ext; simp [pullback.condition]
lemma glued_cover_cocycle (x y z : 𝒰.J) :
glued_cover_t' 𝒰 x y z ≫ glued_cover_t' 𝒰 y z x ≫ glued_cover_t' 𝒰 z x y = 𝟙 _ :=
begin
apply pullback.hom_ext; simp_rw [category.id_comp, category.assoc],
apply glued_cover_cocycle_fst,
apply glued_cover_cocycle_snd,
end
/-- The glue data associated with an open cover.
The canonical isomorphism `𝒰.glued_cover.glued ⟶ X` is provided by `𝒰.from_glued`. -/
@[simps]
def glued_cover : Scheme.glue_data.{u} :=
{ J := 𝒰.J,
U := 𝒰.obj,
V := λ ⟨x, y⟩, pullback (𝒰.map x) (𝒰.map y),
f := λ x y, pullback.fst,
f_id := λ x, infer_instance,
t := λ x y, (pullback_symmetry _ _).hom,
t_id := λ x, by simpa,
t' := λ x y z, glued_cover_t' 𝒰 x y z,
t_fac := λ x y z, by apply pullback.hom_ext; simp,
-- The `cocycle` field could have been `by tidy` but lean timeouts.
cocycle := λ x y z, glued_cover_cocycle 𝒰 x y z,
f_open := λ x, infer_instance }
/-- The canonical morphism from the gluing of an open cover of `X` into `X`.
This is an isomorphism, as witnessed by an `is_iso` instance. -/
def from_glued : 𝒰.glued_cover.glued ⟶ X :=
begin
fapply multicoequalizer.desc,
exact λ x, (𝒰.map x),
rintro ⟨x, y⟩,
change pullback.fst ≫ _ = ((pullback_symmetry _ _).hom ≫ pullback.fst) ≫ _,
simpa using pullback.condition
end
@[simp, reassoc]
lemma ι_from_glued (x : 𝒰.J) :
𝒰.glued_cover.ι x ≫ 𝒰.from_glued = 𝒰.map x :=
multicoequalizer.π_desc _ _ _ _ _
lemma from_glued_injective : function.injective 𝒰.from_glued.1.base :=
begin
intros x y h,
obtain ⟨i, x, rfl⟩ := 𝒰.glued_cover.ι_jointly_surjective x,
obtain ⟨j, y, rfl⟩ := 𝒰.glued_cover.ι_jointly_surjective y,
simp_rw [← comp_apply, ← SheafedSpace.comp_base, ← LocallyRingedSpace.comp_val] at h,
erw [ι_from_glued, ι_from_glued] at h,
let e := (Top.pullback_cone_is_limit _ _).cone_point_unique_up_to_iso
(is_limit_of_has_pullback_of_preserves_limit Scheme.forget_to_Top
(𝒰.map i) (𝒰.map j)),
rw 𝒰.glued_cover.ι_eq_iff,
right,
use e.hom ⟨⟨x, y⟩, h⟩,
simp_rw ← comp_apply,
split,
{ erw is_limit.cone_point_unique_up_to_iso_hom_comp _ _ walking_cospan.left, refl },
{ erw [pullback_symmetry_hom_comp_fst,
is_limit.cone_point_unique_up_to_iso_hom_comp _ _ walking_cospan.right], refl }
end
instance from_glued_stalk_iso (x : 𝒰.glued_cover.glued.carrier) :
is_iso (PresheafedSpace.stalk_map 𝒰.from_glued.val x) :=
begin
obtain ⟨i, x, rfl⟩ := 𝒰.glued_cover.ι_jointly_surjective x,
have := PresheafedSpace.stalk_map.congr_hom _ _ (congr_arg subtype.val $ 𝒰.ι_from_glued i) x,
erw PresheafedSpace.stalk_map.comp at this,
rw ← is_iso.eq_comp_inv at this,
rw this,
apply_instance,
end
lemma from_glued_open_map : is_open_map 𝒰.from_glued.1.base :=
begin
intros U hU,
rw is_open_iff_forall_mem_open,
intros x hx,
rw 𝒰.glued_cover.is_open_iff at hU,
use 𝒰.from_glued.val.base '' U ∩ set.range (𝒰.map (𝒰.f x)).1.base,
use set.inter_subset_left _ _,
split,
{ rw ← set.image_preimage_eq_inter_range,
apply (show is_open_immersion (𝒰.map (𝒰.f x)), by apply_instance).base_open.is_open_map,
convert hU (𝒰.f x) using 1,
rw ← ι_from_glued, erw coe_comp, rw set.preimage_comp,
congr' 1,
refine set.preimage_image_eq _ 𝒰.from_glued_injective },
{ exact ⟨hx, 𝒰.covers x⟩ }
end
lemma from_glued_open_embedding : open_embedding 𝒰.from_glued.1.base :=
open_embedding_of_continuous_injective_open (by continuity) 𝒰.from_glued_injective
𝒰.from_glued_open_map
instance : epi 𝒰.from_glued.val.base :=
begin
rw Top.epi_iff_surjective,
intro x,
obtain ⟨y, h⟩ := 𝒰.covers x,
use (𝒰.glued_cover.ι (𝒰.f x)).1.base y,
rw ← comp_apply,
rw ← 𝒰.ι_from_glued (𝒰.f x) at h,
exact h
end
instance from_glued_open_immersion : is_open_immersion 𝒰.from_glued :=
SheafedSpace.is_open_immersion.of_stalk_iso _ 𝒰.from_glued_open_embedding
instance : is_iso 𝒰.from_glued :=
begin
apply is_iso_of_reflects_iso _ (Scheme.forget_to_LocallyRingedSpace ⋙
LocallyRingedSpace.forget_to_SheafedSpace ⋙ SheafedSpace.forget_to_PresheafedSpace),
change @is_iso (PresheafedSpace _) _ _ _ 𝒰.from_glued.val,
apply PresheafedSpace.is_open_immersion.to_iso,
end
/-- Given an open cover of `X`, and a morphism `𝒰.obj x ⟶ Y` for each open subscheme in the cover,
such that these morphisms are compatible in the intersection (pullback), we may glue the morphisms
together into a morphism `X ⟶ Y`.
Note:
If `X` is exactly (defeq to) the gluing of `U i`, then using `multicoequalizer.desc` suffices.
-/
def glue_morphisms {Y : Scheme} (f : ∀ x, 𝒰.obj x ⟶ Y)
(hf : ∀ x y, (pullback.fst : pullback (𝒰.map x) (𝒰.map y) ⟶ _) ≫ f x = pullback.snd ≫ f y) :
X ⟶ Y :=
begin
refine inv 𝒰.from_glued ≫ _,
fapply multicoequalizer.desc,
exact f,
rintro ⟨i, j⟩,
change pullback.fst ≫ f i = (_ ≫ _) ≫ f j,
erw pullback_symmetry_hom_comp_fst,
exact hf i j
end
@[simp, reassoc]
lemma ι_glue_morphisms {Y : Scheme} (f : ∀ x, 𝒰.obj x ⟶ Y)
(hf : ∀ x y, (pullback.fst : pullback (𝒰.map x) (𝒰.map y) ⟶ _) ≫ f x = pullback.snd ≫ f y)
(x : 𝒰.J) : (𝒰.map x) ≫ 𝒰.glue_morphisms f hf = f x :=
begin
rw [← ι_from_glued, category.assoc],
erw [is_iso.hom_inv_id_assoc, multicoequalizer.π_desc],
end
lemma hom_ext {Y : Scheme} (f₁ f₂ : X ⟶ Y) (h : ∀ x, 𝒰.map x ≫ f₁ = 𝒰.map x ≫ f₂) : f₁ = f₂ :=
begin
rw ← cancel_epi 𝒰.from_glued,
apply multicoequalizer.hom_ext,
intro x,
erw multicoequalizer.π_desc_assoc,
erw multicoequalizer.π_desc_assoc,
exact h x,
end
end open_cover
end Scheme
end algebraic_geometry
|
019a8adfd1fdad89a0bb7e00dbd4f801babc978a | 94e33a31faa76775069b071adea97e86e218a8ee | /src/field_theory/abel_ruffini.lean | aa9ee0ae382e9b75e4197b442f41b21c8c061e50 | [
"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 | 17,339 | lean | /-
Copyright (c) 2020 Thomas Browning and Patrick Lutz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Thomas Browning, Patrick Lutz
-/
import group_theory.solvable
import field_theory.polynomial_galois_group
import ring_theory.roots_of_unity
/-!
# The Abel-Ruffini Theorem
This file proves one direction of the Abel-Ruffini theorem, namely that if an element is solvable
by radicals, then its minimal polynomial has solvable Galois group.
## Main definitions
* `solvable_by_rad F E` : the intermediate field of solvable-by-radicals elements
## Main results
* the Abel-Ruffini Theorem `solvable_by_rad.is_solvable'` : An irreducible polynomial with a root
that is solvable by radicals has a solvable Galois group.
-/
noncomputable theory
open_locale classical polynomial
open polynomial intermediate_field
section abel_ruffini
variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E]
lemma gal_zero_is_solvable : is_solvable (0 : F[X]).gal :=
by apply_instance
lemma gal_one_is_solvable : is_solvable (1 : F[X]).gal :=
by apply_instance
lemma gal_C_is_solvable (x : F) : is_solvable (C x).gal :=
by apply_instance
lemma gal_X_is_solvable : is_solvable (X : F[X]).gal :=
by apply_instance
lemma gal_X_sub_C_is_solvable (x : F) : is_solvable (X - C x).gal :=
by apply_instance
lemma gal_X_pow_is_solvable (n : ℕ) : is_solvable (X ^ n : F[X]).gal :=
by apply_instance
lemma gal_mul_is_solvable {p q : F[X]}
(hp : is_solvable p.gal) (hq : is_solvable q.gal) : is_solvable (p * q).gal :=
solvable_of_solvable_injective (gal.restrict_prod_injective p q)
lemma gal_prod_is_solvable {s : multiset F[X]}
(hs : ∀ p ∈ s, is_solvable (gal p)) : is_solvable s.prod.gal :=
begin
apply multiset.induction_on' s,
{ exact gal_one_is_solvable },
{ intros p t hps hts ht,
rw [multiset.insert_eq_cons, multiset.prod_cons],
exact gal_mul_is_solvable (hs p hps) ht },
end
lemma gal_is_solvable_of_splits {p q : F[X]}
(hpq : fact (p.splits (algebra_map F q.splitting_field))) (hq : is_solvable q.gal) :
is_solvable p.gal :=
begin
haveI : is_solvable (q.splitting_field ≃ₐ[F] q.splitting_field) := hq,
exact solvable_of_surjective (alg_equiv.restrict_normal_hom_surjective q.splitting_field),
end
lemma gal_is_solvable_tower (p q : F[X])
(hpq : p.splits (algebra_map F q.splitting_field))
(hp : is_solvable p.gal)
(hq : is_solvable (q.map (algebra_map F p.splitting_field)).gal) :
is_solvable q.gal :=
begin
let K := p.splitting_field,
let L := q.splitting_field,
haveI : fact (p.splits (algebra_map F L)) := ⟨hpq⟩,
let ϕ : (L ≃ₐ[K] L) ≃* (q.map (algebra_map F K)).gal :=
(is_splitting_field.alg_equiv L (q.map (algebra_map F K))).aut_congr,
have ϕ_inj : function.injective ϕ.to_monoid_hom := ϕ.injective,
haveI : is_solvable (K ≃ₐ[F] K) := hp,
haveI : is_solvable (L ≃ₐ[K] L) := solvable_of_solvable_injective ϕ_inj,
exact is_solvable_of_is_scalar_tower F p.splitting_field q.splitting_field,
end
section gal_X_pow_sub_C
lemma gal_X_pow_sub_one_is_solvable (n : ℕ) : is_solvable (X ^ n - 1 : F[X]).gal :=
begin
by_cases hn : n = 0,
{ rw [hn, pow_zero, sub_self],
exact gal_zero_is_solvable },
have hn' : 0 < n := pos_iff_ne_zero.mpr hn,
have hn'' : (X ^ n - 1 : F[X]) ≠ 0 :=
λ h, one_ne_zero ((leading_coeff_X_pow_sub_one hn').symm.trans (congr_arg leading_coeff h)),
apply is_solvable_of_comm,
intros σ τ,
ext a ha,
rw [mem_root_set hn'', alg_hom.map_sub, aeval_X_pow, aeval_one, sub_eq_zero] at ha,
have key : ∀ σ : (X ^ n - 1 : F[X]).gal, ∃ m : ℕ, σ a = a ^ m,
{ intro σ,
obtain ⟨m, hm⟩ := map_root_of_unity_eq_pow_self σ.to_alg_hom
⟨is_unit.unit (is_unit_of_pow_eq_one a n ha hn'),
by { ext, rwa [units.coe_pow, is_unit.unit_spec, subtype.coe_mk n hn'] }⟩,
use m,
convert hm },
obtain ⟨c, hc⟩ := key σ,
obtain ⟨d, hd⟩ := key τ,
rw [σ.mul_apply, τ.mul_apply, hc, τ.map_pow, hd, σ.map_pow, hc, ←pow_mul, pow_mul'],
end
lemma gal_X_pow_sub_C_is_solvable_aux (n : ℕ) (a : F)
(h : (X ^ n - 1 : F[X]).splits (ring_hom.id F)) : is_solvable (X ^ n - C a).gal :=
begin
by_cases ha : a = 0,
{ rw [ha, C_0, sub_zero],
exact gal_X_pow_is_solvable n },
have ha' : algebra_map F (X ^ n - C a).splitting_field a ≠ 0 :=
mt ((injective_iff_map_eq_zero _).mp (ring_hom.injective _) a) ha,
by_cases hn : n = 0,
{ rw [hn, pow_zero, ←C_1, ←C_sub],
exact gal_C_is_solvable (1 - a) },
have hn' : 0 < n := pos_iff_ne_zero.mpr hn,
have hn'' : X ^ n - C a ≠ 0 :=
λ h, one_ne_zero ((leading_coeff_X_pow_sub_C hn').symm.trans (congr_arg leading_coeff h)),
have hn''' : (X ^ n - 1 : F[X]) ≠ 0 :=
λ h, one_ne_zero ((leading_coeff_X_pow_sub_one hn').symm.trans (congr_arg leading_coeff h)),
have mem_range : ∀ {c}, c ^ n = 1 → ∃ d, algebra_map F (X ^ n - C a).splitting_field d = c :=
λ c hc, ring_hom.mem_range.mp (minpoly.mem_range_of_degree_eq_one F c (or.resolve_left h hn'''
(minpoly.irreducible ((splitting_field.normal (X ^ n - C a)).is_integral c)) (minpoly.dvd F c
(by rwa [map_id, alg_hom.map_sub, sub_eq_zero, aeval_X_pow, aeval_one])))),
apply is_solvable_of_comm,
intros σ τ,
ext b hb,
rw [mem_root_set hn'', alg_hom.map_sub, aeval_X_pow, aeval_C, sub_eq_zero] at hb,
have hb' : b ≠ 0,
{ intro hb',
rw [hb', zero_pow hn'] at hb,
exact ha' hb.symm },
have key : ∀ σ : (X ^ n - C a).gal, ∃ c, σ b = b * algebra_map F _ c,
{ intro σ,
have key : (σ b / b) ^ n = 1 := by rw [div_pow, ←σ.map_pow, hb, σ.commutes, div_self ha'],
obtain ⟨c, hc⟩ := mem_range key,
use c,
rw [hc, mul_div_cancel' (σ b) hb'] },
obtain ⟨c, hc⟩ := key σ,
obtain ⟨d, hd⟩ := key τ,
rw [σ.mul_apply, τ.mul_apply, hc, τ.map_mul, τ.commutes, hd, σ.map_mul, σ.commutes, hc],
rw [mul_assoc, mul_assoc, mul_right_inj' hb', mul_comm],
end
lemma splits_X_pow_sub_one_of_X_pow_sub_C {F : Type*} [field F] {E : Type*} [field E]
(i : F →+* E) (n : ℕ) {a : F} (ha : a ≠ 0) (h : (X ^ n - C a).splits i) : (X ^ n - 1).splits i :=
begin
have ha' : i a ≠ 0 := mt ((injective_iff_map_eq_zero i).mp (i.injective) a) ha,
by_cases hn : n = 0,
{ rw [hn, pow_zero, sub_self],
exact splits_zero i },
have hn' : 0 < n := pos_iff_ne_zero.mpr hn,
have hn'' : (X ^ n - C a).degree ≠ 0 :=
ne_of_eq_of_ne (degree_X_pow_sub_C hn' a) (mt with_bot.coe_eq_coe.mp hn),
obtain ⟨b, hb⟩ := exists_root_of_splits i h hn'',
rw [eval₂_sub, eval₂_X_pow, eval₂_C, sub_eq_zero] at hb,
have hb' : b ≠ 0,
{ intro hb',
rw [hb', zero_pow hn'] at hb,
exact ha' hb.symm },
let s := ((X ^ n - C a).map i).roots,
have hs : _ = _ * (s.map _).prod := eq_prod_roots_of_splits h,
rw [leading_coeff_X_pow_sub_C hn', ring_hom.map_one, C_1, one_mul] at hs,
have hs' : s.card = n := (nat_degree_eq_card_roots h).symm.trans nat_degree_X_pow_sub_C,
apply @splits_of_exists_multiset F E _ _ i (X ^ n - 1) (s.map (λ c : E, c / b)),
rw [leading_coeff_X_pow_sub_one hn', ring_hom.map_one, C_1, one_mul, multiset.map_map],
have C_mul_C : (C (i a⁻¹)) * (C (i a)) = 1,
{ rw [←C_mul, ←i.map_mul, inv_mul_cancel ha, i.map_one, C_1] },
have key1 : (X ^ n - 1).map i = C (i a⁻¹) * ((X ^ n - C a).map i).comp (C b * X),
{ rw [polynomial.map_sub, polynomial.map_sub, polynomial.map_pow, map_X, map_C,
polynomial.map_one, sub_comp, pow_comp, X_comp, C_comp, mul_pow, ←C_pow, hb, mul_sub,
←mul_assoc, C_mul_C, one_mul] },
have key2 : (λ q : E[X], q.comp (C b * X)) ∘ (λ c : E, X - C c) =
(λ c : E, C b * (X - C (c / b))),
{ ext1 c,
change (X - C c).comp (C b * X) = C b * (X - C (c / b)),
rw [sub_comp, X_comp, C_comp, mul_sub, ←C_mul, mul_div_cancel' c hb'] },
rw [key1, hs, multiset_prod_comp, multiset.map_map, key2, multiset.prod_map_mul,
multiset.map_const, multiset.prod_repeat, hs', ←C_pow, hb, ←mul_assoc, C_mul_C, one_mul],
all_goals { exact field.to_nontrivial F },
end
lemma gal_X_pow_sub_C_is_solvable (n : ℕ) (x : F) : is_solvable (X ^ n - C x).gal :=
begin
by_cases hx : x = 0,
{ rw [hx, C_0, sub_zero],
exact gal_X_pow_is_solvable n },
apply gal_is_solvable_tower (X ^ n - 1) (X ^ n - C x),
{ exact splits_X_pow_sub_one_of_X_pow_sub_C _ n hx (splitting_field.splits _) },
{ exact gal_X_pow_sub_one_is_solvable n },
{ rw [polynomial.map_sub, polynomial.map_pow, map_X, map_C],
apply gal_X_pow_sub_C_is_solvable_aux,
have key := splitting_field.splits (X ^ n - 1 : F[X]),
rwa [←splits_id_iff_splits, polynomial.map_sub, polynomial.map_pow, map_X, polynomial.map_one]
at key }
end
end gal_X_pow_sub_C
variables (F)
/-- Inductive definition of solvable by radicals -/
inductive is_solvable_by_rad : E → Prop
| base (a : F) : is_solvable_by_rad (algebra_map F E a)
| add (a b : E) : is_solvable_by_rad a → is_solvable_by_rad b → is_solvable_by_rad (a + b)
| neg (α : E) : is_solvable_by_rad α → is_solvable_by_rad (-α)
| mul (α β : E) : is_solvable_by_rad α → is_solvable_by_rad β → is_solvable_by_rad (α * β)
| inv (α : E) : is_solvable_by_rad α → is_solvable_by_rad α⁻¹
| rad (α : E) (n : ℕ) (hn : n ≠ 0) : is_solvable_by_rad (α^n) → is_solvable_by_rad α
variables (E)
/-- The intermediate field of solvable-by-radicals elements -/
def solvable_by_rad : intermediate_field F E :=
{ carrier := is_solvable_by_rad F,
zero_mem' := by { convert is_solvable_by_rad.base (0 : F), rw ring_hom.map_zero },
add_mem' := is_solvable_by_rad.add,
neg_mem' := is_solvable_by_rad.neg,
one_mem' := by { convert is_solvable_by_rad.base (1 : F), rw ring_hom.map_one },
mul_mem' := is_solvable_by_rad.mul,
inv_mem' := is_solvable_by_rad.inv,
algebra_map_mem' := is_solvable_by_rad.base }
namespace solvable_by_rad
variables {F} {E} {α : E}
lemma induction (P : solvable_by_rad F E → Prop)
(base : ∀ α : F, P (algebra_map F (solvable_by_rad F E) α))
(add : ∀ α β : solvable_by_rad F E, P α → P β → P (α + β))
(neg : ∀ α : solvable_by_rad F E, P α → P (-α))
(mul : ∀ α β : solvable_by_rad F E, P α → P β → P (α * β))
(inv : ∀ α : solvable_by_rad F E, P α → P α⁻¹)
(rad : ∀ α : solvable_by_rad F E, ∀ n : ℕ, n ≠ 0 → P (α^n) → P α)
(α : solvable_by_rad F E) : P α :=
begin
revert α,
suffices : ∀ (α : E), is_solvable_by_rad F α → (∃ β : solvable_by_rad F E, ↑β = α ∧ P β),
{ intro α,
obtain ⟨α₀, hα₀, Pα⟩ := this α (subtype.mem α),
convert Pα,
exact subtype.ext hα₀.symm },
apply is_solvable_by_rad.rec,
{ exact λ α, ⟨algebra_map F (solvable_by_rad F E) α, rfl, base α⟩ },
{ intros α β hα hβ Pα Pβ,
obtain ⟨⟨α₀, hα₀, Pα⟩, β₀, hβ₀, Pβ⟩ := ⟨Pα, Pβ⟩,
exact ⟨α₀ + β₀, by {rw [←hα₀, ←hβ₀], refl }, add α₀ β₀ Pα Pβ⟩ },
{ intros α hα Pα,
obtain ⟨α₀, hα₀, Pα⟩ := Pα,
exact ⟨-α₀, by {rw ←hα₀, refl }, neg α₀ Pα⟩ },
{ intros α β hα hβ Pα Pβ,
obtain ⟨⟨α₀, hα₀, Pα⟩, β₀, hβ₀, Pβ⟩ := ⟨Pα, Pβ⟩,
exact ⟨α₀ * β₀, by {rw [←hα₀, ←hβ₀], refl }, mul α₀ β₀ Pα Pβ⟩ },
{ intros α hα Pα,
obtain ⟨α₀, hα₀, Pα⟩ := Pα,
exact ⟨α₀⁻¹, by {rw ←hα₀, refl }, inv α₀ Pα⟩ },
{ intros α n hn hα Pα,
obtain ⟨α₀, hα₀, Pα⟩ := Pα,
refine ⟨⟨α, is_solvable_by_rad.rad α n hn hα⟩, rfl, rad _ n hn _⟩,
convert Pα,
exact subtype.ext (eq.trans ((solvable_by_rad F E).coe_pow _ n) hα₀.symm) }
end
theorem is_integral (α : solvable_by_rad F E) : is_integral F α :=
begin
revert α,
apply solvable_by_rad.induction,
{ exact λ _, is_integral_algebra_map },
{ exact λ _ _, is_integral_add },
{ exact λ _, is_integral_neg },
{ exact λ _ _, is_integral_mul },
{ exact λ α hα, subalgebra.inv_mem_of_algebraic (integral_closure F (solvable_by_rad F E))
(show is_algebraic F ↑(⟨α, hα⟩ : integral_closure F (solvable_by_rad F E)),
by exact is_algebraic_iff_is_integral.mpr hα) },
{ intros α n hn hα,
obtain ⟨p, h1, h2⟩ := is_algebraic_iff_is_integral.mpr hα,
refine is_algebraic_iff_is_integral.mp ⟨p.comp (X ^ n),
⟨λ h, h1 (leading_coeff_eq_zero.mp _), by rw [aeval_comp, aeval_X_pow, h2]⟩⟩,
rwa [←leading_coeff_eq_zero, leading_coeff_comp, leading_coeff_X_pow, one_pow, mul_one] at h,
rwa nat_degree_X_pow }
end
/-- The statement to be proved inductively -/
def P (α : solvable_by_rad F E) : Prop := is_solvable (minpoly F α).gal
/-- An auxiliary induction lemma, which is generalized by `solvable_by_rad.is_solvable`. -/
lemma induction3 {α : solvable_by_rad F E} {n : ℕ} (hn : n ≠ 0) (hα : P (α ^ n)) : P α :=
begin
let p := minpoly F (α ^ n),
have hp : p.comp (X ^ n) ≠ 0,
{ intro h,
cases (comp_eq_zero_iff.mp h) with h' h',
{ exact minpoly.ne_zero (is_integral (α ^ n)) h' },
{ exact hn (by rw [←nat_degree_C _, ←h'.2, nat_degree_X_pow]) } },
apply gal_is_solvable_of_splits,
{ exact ⟨splits_of_splits_of_dvd _ hp (splitting_field.splits (p.comp (X ^ n)))
(minpoly.dvd F α (by rw [aeval_comp, aeval_X_pow, minpoly.aeval]))⟩ },
{ refine gal_is_solvable_tower p (p.comp (X ^ n)) _ hα _,
{ exact gal.splits_in_splitting_field_of_comp _ _ (by rwa [nat_degree_X_pow]) },
{ obtain ⟨s, hs⟩ := (splits_iff_exists_multiset _).1 (splitting_field.splits p),
rw [map_comp, polynomial.map_pow, map_X, hs, mul_comp, C_comp],
apply gal_mul_is_solvable (gal_C_is_solvable _),
rw multiset_prod_comp,
apply gal_prod_is_solvable,
intros q hq,
rw multiset.mem_map at hq,
obtain ⟨q, hq, rfl⟩ := hq,
rw multiset.mem_map at hq,
obtain ⟨q, hq, rfl⟩ := hq,
rw [sub_comp, X_comp, C_comp],
exact gal_X_pow_sub_C_is_solvable n q } },
end
/-- An auxiliary induction lemma, which is generalized by `solvable_by_rad.is_solvable`. -/
lemma induction2 {α β γ : solvable_by_rad F E} (hγ : γ ∈ F⟮α, β⟯) (hα : P α) (hβ : P β) : P γ :=
begin
let p := (minpoly F α),
let q := (minpoly F β),
have hpq := polynomial.splits_of_splits_mul _ (mul_ne_zero (minpoly.ne_zero (is_integral α))
(minpoly.ne_zero (is_integral β))) (splitting_field.splits (p * q)),
let f : F⟮α, β⟯ →ₐ[F] (p * q).splitting_field := classical.choice (alg_hom_mk_adjoin_splits
begin
intros x hx,
cases hx,
rw hx,
exact ⟨is_integral α, hpq.1⟩,
cases hx,
exact ⟨is_integral β, hpq.2⟩,
end),
have key : minpoly F γ = minpoly F (f ⟨γ, hγ⟩) := minpoly.eq_of_irreducible_of_monic
(minpoly.irreducible (is_integral γ)) begin
suffices : aeval (⟨γ, hγ⟩ : F ⟮α, β⟯) (minpoly F γ) = 0,
{ rw [aeval_alg_hom_apply, this, alg_hom.map_zero] },
apply (algebra_map F⟮α, β⟯ (solvable_by_rad F E)).injective,
rw [ring_hom.map_zero, is_scalar_tower.algebra_map_aeval],
exact minpoly.aeval F γ,
end (minpoly.monic (is_integral γ)),
rw [P, key],
exact gal_is_solvable_of_splits ⟨normal.splits (splitting_field.normal _) _⟩
(gal_mul_is_solvable hα hβ),
end
/-- An auxiliary induction lemma, which is generalized by `solvable_by_rad.is_solvable`. -/
lemma induction1 {α β : solvable_by_rad F E} (hβ : β ∈ F⟮α⟯) (hα : P α) : P β :=
induction2 (adjoin.mono F _ _ (ge_of_eq (set.pair_eq_singleton α)) hβ) hα hα
theorem is_solvable (α : solvable_by_rad F E) :
is_solvable (minpoly F α).gal :=
begin
revert α,
apply solvable_by_rad.induction,
{ exact λ α, by { rw minpoly.eq_X_sub_C, exact gal_X_sub_C_is_solvable α } },
{ exact λ α β, induction2 (add_mem (subset_adjoin F _ (set.mem_insert α _))
(subset_adjoin F _ (set.mem_insert_of_mem α (set.mem_singleton β)))) },
{ exact λ α, induction1 (neg_mem (mem_adjoin_simple_self F α)) },
{ exact λ α β, induction2 (mul_mem (subset_adjoin F _ (set.mem_insert α _))
(subset_adjoin F _ (set.mem_insert_of_mem α (set.mem_singleton β)))) },
{ exact λ α, induction1 (inv_mem (mem_adjoin_simple_self F α)) },
{ exact λ α n, induction3 },
end
/-- **Abel-Ruffini Theorem** (one direction): An irreducible polynomial with an
`is_solvable_by_rad` root has solvable Galois group -/
lemma is_solvable' {α : E} {q : F[X]} (q_irred : irreducible q)
(q_aeval : aeval α q = 0) (hα : is_solvable_by_rad F α) :
_root_.is_solvable q.gal :=
begin
haveI : _root_.is_solvable (q * C q.leading_coeff⁻¹).gal,
{ rw [minpoly.eq_of_irreducible q_irred q_aeval,
←show minpoly F (⟨α, hα⟩ : solvable_by_rad F E) = minpoly F α,
from minpoly.eq_of_algebra_map_eq (ring_hom.injective _) (is_integral ⟨α, hα⟩) rfl],
exact is_solvable ⟨α, hα⟩ },
refine solvable_of_surjective (gal.restrict_dvd_surjective ⟨C q.leading_coeff⁻¹, rfl⟩ _),
rw [mul_ne_zero_iff, ne, ne, C_eq_zero, inv_eq_zero],
exact ⟨q_irred.ne_zero, leading_coeff_ne_zero.mpr q_irred.ne_zero⟩,
end
end solvable_by_rad
end abel_ruffini
|
17b93b58342db68e0f6a765df37fdae6fc25be26 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/1058.lean | 6bc0b6b1ae48f4f74d9476a86d4032db60781c51 | [
"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 | 128 | lean | example : List (Unit -> Nat) :=
let g := [by exact fun _ => 0]; g
example : List (Unit -> Nat) :=
let g := [fun _ => 0]; g
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.