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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aa099359bae5f16864fe9cb5fb70e48cab5aa280 | 38bf3fd2bb651ab70511408fcf70e2029e2ba310 | /src/data/set/finite.lean | b9f835f4cbe6c54a129d751d1774b405b62eb941 | [
"Apache-2.0"
] | permissive | JaredCorduan/mathlib | 130392594844f15dad65a9308c242551bae6cd2e | d5de80376088954d592a59326c14404f538050a1 | refs/heads/master | 1,595,862,206,333 | 1,570,816,457,000 | 1,570,816,457,000 | 209,134,499 | 0 | 0 | Apache-2.0 | 1,568,746,811,000 | 1,568,746,811,000 | null | UTF-8 | Lean | false | false | 21,259 | 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
Finite sets.
-/
import logic.function
import data.nat.basic data.fintype data.set.lattice data.set.function
open set lattice function
universes u v w x
variables {α : Type u} {β : Type v} {ι : Sort w} {γ : Type x}
namespace set
/-- A set is finite if the subtype is a fintype, i.e. there is a
list that enumerates its members. -/
def finite (s : set α) : Prop := nonempty (fintype s)
/-- A set is infinite if it is not finite. -/
def infinite (s : set α) : Prop := ¬ finite s
/-- Construct a fintype from a finset with the same elements. -/
def fintype_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : fintype p :=
fintype.subtype s H
@[simp] theorem card_fintype_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) :
@fintype.card p (fintype_of_finset s H) = s.card :=
fintype.subtype_card s H
theorem card_fintype_of_finset' {p : set α} (s : finset α)
(H : ∀ x, x ∈ s ↔ x ∈ p) [fintype p] : fintype.card p = s.card :=
by rw ← card_fintype_of_finset s H; congr
/-- Construct a finset enumerating a set `s`, given a `fintype` instance. -/
def to_finset (s : set α) [fintype s] : finset α :=
⟨(@finset.univ s _).1.map subtype.val,
multiset.nodup_map (λ a b, subtype.eq) finset.univ.2⟩
@[simp] theorem mem_to_finset {s : set α} [fintype s] {a : α} : a ∈ s.to_finset ↔ a ∈ s :=
by simp [to_finset]
@[simp] theorem mem_to_finset_val {s : set α} [fintype s] {a : α} : a ∈ s.to_finset.1 ↔ a ∈ s :=
mem_to_finset
noncomputable instance finite.fintype {s : set α} (h : finite s) : fintype s :=
classical.choice h
/-- Get a finset from a finite set -/
noncomputable def finite.to_finset {s : set α} (h : finite s) : finset α :=
@set.to_finset _ _ (finite.fintype h)
@[simp] theorem finite.mem_to_finset {s : set α} {h : finite s} {a : α} : a ∈ h.to_finset ↔ a ∈ s :=
@mem_to_finset _ _ (finite.fintype h) _
lemma finite.coe_to_finset {α} {s : set α} (h : finite s) : ↑h.to_finset = s :=
by { ext, apply mem_to_finset }
lemma exists_finset_of_finite {s : set α} (h : finite s) : ∃(s' : finset α), ↑s' = s :=
⟨h.to_finset, h.coe_to_finset⟩
theorem finite.exists_finset {s : set α} : finite s →
∃ s' : finset α, ∀ a : α, a ∈ s' ↔ a ∈ s
| ⟨h⟩ := by exactI ⟨to_finset s, λ _, mem_to_finset⟩
theorem finite.exists_finset_coe {s : set α} (hs : finite s) :
∃ s' : finset α, ↑s' = s :=
let ⟨s', h⟩ := hs.exists_finset in ⟨s', set.ext h⟩
theorem finite_mem_finset (s : finset α) : finite {a | a ∈ s} :=
⟨fintype_of_finset s (λ _, iff.rfl)⟩
theorem finite.of_fintype [fintype α] (s : set α) : finite s :=
by classical; exact ⟨set_fintype s⟩
instance decidable_mem_of_fintype [decidable_eq α] (s : set α) [fintype s] (a) : decidable (a ∈ s) :=
decidable_of_iff _ mem_to_finset
instance fintype_empty : fintype (∅ : set α) :=
fintype_of_finset ∅ $ by simp
theorem empty_card : fintype.card (∅ : set α) = 0 := rfl
@[simp] theorem empty_card' {h : fintype.{u} (∅ : set α)} :
@fintype.card (∅ : set α) h = 0 :=
eq.trans (by congr) empty_card
@[simp] theorem finite_empty : @finite α ∅ := ⟨set.fintype_empty⟩
def fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) : fintype (insert a s : set α) :=
fintype_of_finset ⟨a :: s.to_finset.1,
multiset.nodup_cons_of_nodup (by simp [h]) s.to_finset.2⟩ $ by simp
theorem card_fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) :
@fintype.card _ (fintype_insert' s h) = fintype.card s + 1 :=
by rw [fintype_insert', card_fintype_of_finset];
simp [finset.card, to_finset]; refl
@[simp] theorem card_insert {a : α} (s : set α)
[fintype s] (h : a ∉ s) {d : fintype.{u} (insert a s : set α)} :
@fintype.card _ d = fintype.card s + 1 :=
by rw ← card_fintype_insert' s h; congr
lemma card_image_of_inj_on {s : set α} [fintype s]
{f : α → β} [fintype (f '' s)] (H : ∀x∈s, ∀y∈s, f x = f y → x = y) :
fintype.card (f '' s) = fintype.card s :=
by haveI := classical.prop_decidable; exact
calc fintype.card (f '' s) = (s.to_finset.image f).card : card_fintype_of_finset' _ (by simp)
... = s.to_finset.card : finset.card_image_of_inj_on
(λ x hx y hy hxy, H x (mem_to_finset.1 hx) y (mem_to_finset.1 hy) hxy)
... = fintype.card s : (card_fintype_of_finset' _ (λ a, mem_to_finset)).symm
lemma card_image_of_injective (s : set α) [fintype s]
{f : α → β} [fintype (f '' s)] (H : function.injective f) :
fintype.card (f '' s) = fintype.card s :=
card_image_of_inj_on $ λ _ _ _ _ h, H h
instance fintype_insert [decidable_eq α] (a : α) (s : set α) [fintype s] : fintype (insert a s : set α) :=
if h : a ∈ s then by rwa [insert_eq, union_eq_self_of_subset_left (singleton_subset_iff.2 h)]
else fintype_insert' _ h
@[simp] theorem finite_insert (a : α) {s : set α} : finite s → finite (insert a s)
| ⟨h⟩ := ⟨@set.fintype_insert _ (classical.dec_eq α) _ _ h⟩
lemma to_finset_insert [decidable_eq α] {a : α} {s : set α} (hs : finite s) :
(finite_insert a hs).to_finset = insert a hs.to_finset :=
finset.ext.mpr $ by simp
@[elab_as_eliminator]
theorem finite.induction_on {C : set α → Prop} {s : set α} (h : finite s)
(H0 : C ∅) (H1 : ∀ {a s}, a ∉ s → finite s → C s → C (insert a s)) : C s :=
let ⟨t⟩ := h in by exactI
match s.to_finset, @mem_to_finset _ s _ with
| ⟨l, nd⟩, al := begin
change ∀ a, a ∈ l ↔ a ∈ s at al,
clear _let_match _match t h, revert s nd al,
refine multiset.induction_on l _ (λ a l IH, _); intros s nd al,
{ rw show s = ∅, from eq_empty_iff_forall_not_mem.2 (by simpa using al),
exact H0 },
{ rw ← show insert a {x | x ∈ l} = s, from set.ext (by simpa using al),
cases multiset.nodup_cons.1 nd with m nd',
refine H1 _ ⟨finset.subtype.fintype ⟨l, nd'⟩⟩ (IH nd' (λ _, iff.rfl)),
exact m }
end
end
@[elab_as_eliminator]
theorem finite.dinduction_on {C : ∀s:set α, finite s → Prop} {s : set α} (h : finite s)
(H0 : C ∅ finite_empty)
(H1 : ∀ {a s}, a ∉ s → ∀h:finite s, C s h → C (insert a s) (finite_insert a h)) :
C s h :=
have ∀h:finite s, C s h,
from finite.induction_on h (assume h, H0) (assume a s has hs ih h, H1 has hs (ih _)),
this h
instance fintype_singleton (a : α) : fintype ({a} : set α) :=
fintype_insert' _ (not_mem_empty _)
@[simp] theorem card_singleton (a : α) :
fintype.card ({a} : set α) = 1 :=
by rw [show fintype.card ({a} : set α) = _, from
card_fintype_insert' ∅ (not_mem_empty a)]; refl
@[simp] theorem finite_singleton (a : α) : finite ({a} : set α) :=
⟨set.fintype_singleton _⟩
instance fintype_pure : ∀ a : α, fintype (pure a : set α) :=
set.fintype_singleton
theorem finite_pure (a : α) : finite (pure a : set α) :=
⟨set.fintype_pure a⟩
instance fintype_univ [fintype α] : fintype (@univ α) :=
fintype_of_finset finset.univ $ λ _, iff_true_intro (finset.mem_univ _)
theorem finite_univ [fintype α] : finite (@univ α) := ⟨set.fintype_univ⟩
instance fintype_union [decidable_eq α] (s t : set α) [fintype s] [fintype t] : fintype (s ∪ t : set α) :=
fintype_of_finset (s.to_finset ∪ t.to_finset) $ by simp
theorem finite_union {s t : set α} : finite s → finite t → finite (s ∪ t)
| ⟨hs⟩ ⟨ht⟩ := ⟨@set.fintype_union _ (classical.dec_eq α) _ _ hs ht⟩
instance fintype_sep (s : set α) (p : α → Prop) [fintype s] [decidable_pred p] : fintype ({a ∈ s | p a} : set α) :=
fintype_of_finset (s.to_finset.filter p) $ by simp
instance fintype_inter (s t : set α) [fintype s] [decidable_pred t] : fintype (s ∩ t : set α) :=
set.fintype_sep s t
def fintype_subset (s : set α) {t : set α} [fintype s] [decidable_pred t] (h : t ⊆ s) : fintype t :=
by rw ← inter_eq_self_of_subset_right h; apply_instance
theorem finite_subset {s : set α} : finite s → ∀ {t : set α}, t ⊆ s → finite t
| ⟨hs⟩ t h := ⟨@set.fintype_subset _ _ _ hs (classical.dec_pred t) h⟩
instance fintype_image [decidable_eq β] (s : set α) (f : α → β) [fintype s] : fintype (f '' s) :=
fintype_of_finset (s.to_finset.image f) $ by simp
instance fintype_range [decidable_eq β] (f : α → β) [fintype α] : fintype (range f) :=
fintype_of_finset (finset.univ.image f) $ by simp [range]
theorem finite_range (f : α → β) [fintype α] : finite (range f) :=
by haveI := classical.dec_eq β; exact ⟨by apply_instance⟩
theorem finite_image {s : set α} (f : α → β) : finite s → finite (f '' s)
| ⟨h⟩ := ⟨@set.fintype_image _ _ (classical.dec_eq β) _ _ h⟩
instance fintype_map {α β} [decidable_eq β] :
∀ (s : set α) (f : α → β) [fintype s], fintype (f <$> s) := set.fintype_image
theorem finite_map {α β} {s : set α} :
∀ (f : α → β), finite s → finite (f <$> s) := finite_image
def fintype_of_fintype_image (s : set α)
{f : α → β} {g} (I : is_partial_inv f g) [fintype (f '' s)] : fintype s :=
fintype_of_finset ⟨_, @multiset.nodup_filter_map β α g _
(@injective_of_partial_inv_right _ _ f g I) (f '' s).to_finset.2⟩ $ λ a,
begin
suffices : (∃ b x, f x = b ∧ g b = some a ∧ x ∈ s) ↔ a ∈ s,
by simpa [exists_and_distrib_left.symm, and.comm, and.left_comm, and.assoc],
rw exists_swap,
suffices : (∃ x, x ∈ s ∧ g (f x) = some a) ↔ a ∈ s, {simpa [and.comm, and.left_comm, and.assoc]},
simp [I _, (injective_of_partial_inv I).eq_iff]
end
theorem finite_of_finite_image_on {s : set α} {f : α → β} (hi : set.inj_on f s) :
finite (f '' s) → finite s | ⟨h⟩ :=
⟨@fintype.of_injective _ _ h (λa:s, ⟨f a.1, mem_image_of_mem f a.2⟩) $
assume a b eq, subtype.eq $ hi a.2 b.2 $ subtype.ext.1 eq⟩
theorem finite_image_iff_on {s : set α} {f : α → β} (hi : inj_on f s) :
finite (f '' s) ↔ finite s :=
⟨finite_of_finite_image_on hi, finite_image _⟩
theorem finite_of_finite_image {s : set α} {f : α → β} (I : set.inj_on f s) :
finite (f '' s) → finite s :=
finite_of_finite_image_on I
theorem finite_preimage {s : set β} {f : α → β}
(I : set.inj_on f (f⁻¹' s)) (h : finite s) : finite (f ⁻¹' s) :=
finite_of_finite_image I (finite_subset h (image_preimage_subset f s))
instance fintype_Union [decidable_eq α] {ι : Type*} [fintype ι]
(f : ι → set α) [∀ i, fintype (f i)] : fintype (⋃ i, f i) :=
fintype_of_finset (finset.univ.bind (λ i, (f i).to_finset)) $ by simp
theorem finite_Union {ι : Type*} [fintype ι] {f : ι → set α} (H : ∀i, finite (f i)) : finite (⋃ i, f i) :=
⟨@set.fintype_Union _ (classical.dec_eq α) _ _ _ (λ i, finite.fintype (H i))⟩
def fintype_bUnion [decidable_eq α] {ι : Type*} {s : set ι} [fintype s]
(f : ι → set α) (H : ∀ i ∈ s, fintype (f i)) : fintype (⋃ i ∈ s, f i) :=
by rw bUnion_eq_Union; exact
@set.fintype_Union _ _ _ _ _ (by rintro ⟨i, hi⟩; exact H i hi)
instance fintype_bUnion' [decidable_eq α] {ι : Type*} {s : set ι} [fintype s]
(f : ι → set α) [H : ∀ i, fintype (f i)] : fintype (⋃ i ∈ s, f i) :=
fintype_bUnion _ (λ i _, H i)
theorem finite_sUnion {s : set (set α)} (h : finite s) (H : ∀t∈s, finite t) : finite (⋃₀ s) :=
by rw sUnion_eq_Union; haveI := finite.fintype h;
apply finite_Union; simpa using H
theorem finite_bUnion {α} {ι : Type*} {s : set ι} {f : ι → set α} :
finite s → (∀i, finite (f i)) → finite (⋃ i∈s, f i)
| ⟨hs⟩ h := by rw [bUnion_eq_Union]; exactI finite_Union (λ i, h _)
theorem finite_bUnion' {α} {ι : Type*} {s : set ι} (f : ι → set α) :
finite s → (∀i ∈ s, finite (f i)) → finite (⋃ i∈s, f i)
| ⟨hs⟩ h := by { rw [bUnion_eq_Union], exactI finite_Union (λ i, h i.1 i.2) }
instance fintype_lt_nat (n : ℕ) : fintype {i | i < n} :=
fintype_of_finset (finset.range n) $ by simp
instance fintype_le_nat (n : ℕ) : fintype {i | i ≤ n} :=
by simpa [nat.lt_succ_iff] using set.fintype_lt_nat (n+1)
lemma finite_le_nat (n : ℕ) : finite {i | i ≤ n} := ⟨set.fintype_le_nat _⟩
lemma finite_lt_nat (n : ℕ) : finite {i | i < n} := ⟨set.fintype_lt_nat _⟩
instance fintype_prod (s : set α) (t : set β) [fintype s] [fintype t] : fintype (set.prod s t) :=
fintype_of_finset (s.to_finset.product t.to_finset) $ by simp
lemma finite_prod {s : set α} {t : set β} : finite s → finite t → finite (set.prod s t)
| ⟨hs⟩ ⟨ht⟩ := by exactI ⟨set.fintype_prod s t⟩
def fintype_bind {α β} [decidable_eq β] (s : set α) [fintype s]
(f : α → set β) (H : ∀ a ∈ s, fintype (f a)) : fintype (s >>= f) :=
set.fintype_bUnion _ H
instance fintype_bind' {α β} [decidable_eq β] (s : set α) [fintype s]
(f : α → set β) [H : ∀ a, fintype (f a)] : fintype (s >>= f) :=
fintype_bind _ _ (λ i _, H i)
theorem finite_bind {α β} {s : set α} {f : α → set β} :
finite s → (∀ a ∈ s, finite (f a)) → finite (s >>= f)
| ⟨hs⟩ H := ⟨@fintype_bind _ _ (classical.dec_eq β) _ hs _ (λ a ha, (H a ha).fintype)⟩
instance fintype_seq {α β : Type u} [decidable_eq β]
(f : set (α → β)) (s : set α) [fintype f] [fintype s] :
fintype (f <*> s) :=
by rw seq_eq_bind_map; apply set.fintype_bind'
theorem finite_seq {α β : Type u} {f : set (α → β)} {s : set α} :
finite f → finite s → finite (f <*> s)
| ⟨hf⟩ ⟨hs⟩ := by { haveI := classical.dec_eq β, exactI ⟨set.fintype_seq _ _⟩ }
/-- There are finitely many subsets of a given finite set -/
lemma finite_subsets_of_finite {α : Type u} {a : set α} (h : finite a) : finite {b | b ⊆ a} :=
begin
-- we just need to translate the result, already known for finsets,
-- to the language of finite sets
let s := coe '' ((finset.powerset (finite.to_finset h)).to_set),
have : finite s := finite_image _ (finite_mem_finset _),
have : {b | b ⊆ a} ⊆ s :=
begin
assume b hb,
rw [set.mem_image],
rw [set.mem_set_of_eq] at hb,
let b' : finset α := finite.to_finset (finite_subset h hb),
have : b' ∈ (finset.powerset (finite.to_finset h)).to_set :=
show b' ∈ (finset.powerset (finite.to_finset h)),
by simp [b', finset.subset_iff]; exact hb,
have : coe b' = b := by ext; simp,
exact ⟨b', by assumption, by assumption⟩
end,
exact finite_subset ‹finite s› this
end
lemma exists_min [decidable_linear_order β] (s : set α) (f : α → β) (h1 : finite s)
(h : nonempty s) : ∃ a, a ∈ s ∧ ∀ b ∈ s, f a ≤ f b :=
begin
have := (finite.to_finset h1).exists_min f,
simp at this ⊢, unfreezeI, rcases h with ⟨⟨x, hx⟩⟩,
exact this x hx
end
end set
namespace finset
variables [decidable_eq β]
variables {s t u : finset α} {f : α → β} {a : α}
lemma finite_to_set (s : finset α) : set.finite (↑s : set α) :=
set.finite_mem_finset s
@[simp] lemma coe_bind {f : α → finset β} : ↑(s.bind f) = (⋃x ∈ (↑s : set α), ↑(f x) : set β) :=
by simp [set.ext_iff]
@[simp] lemma coe_to_finset {s : set α} {hs : set.finite s} : ↑(hs.to_finset) = s :=
by simp [set.ext_iff]
@[simp] lemma coe_to_finset' (s : set α) [fintype s] : (↑s.to_finset : set α) = s :=
by ext; simp
end finset
namespace set
lemma finite_subset_Union {s : set α} (hs : finite s)
{ι} {t : ι → set α} (h : s ⊆ ⋃ i, t i) : ∃ I : set ι, finite I ∧ s ⊆ ⋃ i ∈ I, t i :=
begin
unfreezeI, cases hs,
choose f hf using show ∀ x : s, ∃ i, x.1 ∈ t i, {simpa [subset_def] using h},
refine ⟨range f, finite_range f, _⟩,
rintro x hx,
simp,
exact ⟨_, ⟨_, hx, rfl⟩, hf ⟨x, hx⟩⟩
end
lemma finite_range_ite {p : α → Prop} [decidable_pred p] {f g : α → β} (hf : finite (range f))
(hg : finite (range g)) : finite (range (λ x, if p x then f x else g x)) :=
finite_subset (finite_union hf hg) range_ite_subset
lemma finite_range_const {c : β} : finite (range (λ x : α, c)) :=
finite_subset (finite_singleton c) range_const_subset
lemma range_find_greatest_subset {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ}:
range (λ x, nat.find_greatest (P x) b) ⊆ ↑(finset.range (b + 1)) :=
by { rw range_subset_iff, assume x, simp [nat.lt_succ_iff, nat.find_greatest_le] }
lemma finite_range_find_greatest {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ} :
finite (range (λ x, nat.find_greatest (P x) b)) :=
finite_subset (finset.finite_to_set $ finset.range (b + 1)) range_find_greatest_subset
lemma infinite_univ_nat : infinite (univ : set ℕ) :=
assume (h : finite (univ : set ℕ)),
let ⟨n, hn⟩ := finset.exists_nat_subset_range h.to_finset in
have n ∈ finset.range n, from finset.subset_iff.mpr hn $ by simp,
by simp * at *
lemma not_injective_nat_fintype [fintype α] {f : ℕ → α} : ¬ injective f :=
assume (h : injective f),
have finite (f '' univ),
from finite_subset (finset.finite_to_set $ fintype.elems α) (assume a h, fintype.complete a),
have finite (univ : set ℕ), from finite_of_finite_image (set.inj_on_of_injective _ h) this,
infinite_univ_nat this
lemma not_injective_int_fintype [fintype α] {f : ℤ → α} : ¬ injective f :=
assume hf,
have injective (f ∘ (coe : ℕ → ℤ)), from injective_comp hf $ assume i j, int.of_nat_inj,
not_injective_nat_fintype this
lemma card_lt_card {s t : set α} [fintype s] [fintype t] (h : s ⊂ t) :
fintype.card s < fintype.card t :=
begin
haveI := classical.prop_decidable,
rw [← finset.coe_to_finset' s, ← finset.coe_to_finset' t, finset.coe_ssubset] at h,
rw [card_fintype_of_finset' _ (λ x, mem_to_finset),
card_fintype_of_finset' _ (λ x, mem_to_finset)],
exact finset.card_lt_card h,
end
lemma card_le_of_subset {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) :
fintype.card s ≤ fintype.card t :=
calc fintype.card s = s.to_finset.card : set.card_fintype_of_finset' _ (by simp)
... ≤ t.to_finset.card : finset.card_le_of_subset (λ x hx, by simp [set.subset_def, *] at *)
... = fintype.card t : eq.symm (set.card_fintype_of_finset' _ (by simp))
lemma eq_of_subset_of_card_le {s t : set α} [fintype s] [fintype t]
(hsub : s ⊆ t) (hcard : fintype.card t ≤ fintype.card s) : s = t :=
classical.by_contradiction (λ h, lt_irrefl (fintype.card t)
(have fintype.card s < fintype.card t := set.card_lt_card ⟨hsub, h⟩,
by rwa [le_antisymm (card_le_of_subset hsub) hcard] at this))
lemma card_range_of_injective [fintype α] {f : α → β} (hf : injective f)
[fintype (range f)] : fintype.card (range f) = fintype.card α :=
eq.symm $ fintype.card_congr (@equiv.of_bijective _ _ (λ a : α, show range f, from ⟨f a, a, rfl⟩)
⟨λ x y h, hf $ subtype.mk.inj h, λ b, let ⟨a, ha⟩ := b.2 in ⟨a, by simp *⟩⟩)
lemma finite.exists_maximal_wrt [partial_order β]
(f : α → β) (s : set α) (h : set.finite s) : s ≠ ∅ → ∃a∈s, ∀a'∈s, f a ≤ f a' → f a = f a' :=
begin
classical,
refine h.induction_on _ _,
{ assume h, contradiction },
assume a s his _ ih _,
by_cases s = ∅,
{ use a, simp [h] },
rcases ih h with ⟨b, hb, ih⟩,
by_cases f b ≤ f a,
{ refine ⟨a, set.mem_insert _ _, assume c hc hac, le_antisymm hac _⟩,
rcases set.mem_insert_iff.1 hc with rfl | hcs,
{ refl },
{ rwa [← ih c hcs (le_trans h hac)] } },
{ refine ⟨b, set.mem_insert_of_mem _ hb, assume c hc hbc, _⟩,
rcases set.mem_insert_iff.1 hc with rfl | hcs,
{ exact (h hbc).elim },
{ exact ih c hcs hbc } }
end
end set
namespace finset
section preimage
noncomputable def preimage {f : α → β} (s : finset β)
(hf : set.inj_on f (f ⁻¹' ↑s)) : finset α :=
set.finite.to_finset (set.finite_preimage hf (set.finite_mem_finset s))
@[simp] lemma mem_preimage {f : α → β} {s : finset β} {hf : set.inj_on f (f ⁻¹' ↑s)} {x : α} :
x ∈ preimage s hf ↔ f x ∈ s :=
by simp [preimage]
@[simp] lemma coe_preimage {f : α → β} (s : finset β)
(hf : set.inj_on f (f ⁻¹' ↑s)) : (↑(preimage s hf) : set α) = f ⁻¹' ↑s :=
by simp [set.ext_iff]
lemma image_preimage [decidable_eq β] (f : α → β) (s : finset β)
(hf : set.bij_on f (f ⁻¹' s.to_set) s.to_set) :
image f (preimage s (set.inj_on_of_bij_on hf)) = s :=
finset.coe_inj.1 $
suffices f '' (f ⁻¹' ↑s) = ↑s, by simpa,
(set.subset.antisymm (image_preimage_subset _ _) hf.2.2)
end preimage
@[to_additive]
lemma prod_preimage [comm_monoid β] (f : α → γ) (s : finset γ)
(hf : set.bij_on f (f ⁻¹' ↑s) ↑s) (g : γ → β) :
(preimage s (set.inj_on_of_bij_on hf)).prod (g ∘ f) = s.prod g :=
by classical;
calc
(preimage s (set.inj_on_of_bij_on hf)).prod (g ∘ f)
= (image f (preimage s (set.inj_on_of_bij_on hf))).prod g :
begin
rw prod_image,
intros x hx y hy hxy,
apply set.inj_on_of_bij_on hf,
repeat { try { rw mem_preimage at hx hy,
rw [set.mem_preimage, mem_coe] },
assumption },
end
... = s.prod g : by rw image_preimage
end finset
|
e323307c89d7c574aa0689eb80d0443fde4858ff | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/normed_space/star/spectrum.lean | 2680b98fdefa0d9d5029b5d356975fdb148b6b6d | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 8,039 | lean | /-
Copyright (c) 2022 Jireh Loreaux. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jireh Loreaux
-/
import analysis.normed_space.star.basic
import analysis.normed_space.spectrum
import analysis.special_functions.exponential
import algebra.star.star_alg_hom
/-! # Spectral properties in C⋆-algebras
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file, we establish various properties related to the spectrum of elements in C⋆-algebras.
-/
local postfix `⋆`:std.prec.max_plus := star
section
open_locale topology ennreal
open filter ennreal spectrum cstar_ring
section unitary_spectrum
variables
{𝕜 : Type*} [normed_field 𝕜]
{E : Type*} [normed_ring E] [star_ring E] [cstar_ring E]
[normed_algebra 𝕜 E] [complete_space E]
lemma unitary.spectrum_subset_circle (u : unitary E) :
spectrum 𝕜 (u : E) ⊆ metric.sphere 0 1 :=
begin
nontriviality E,
refine λ k hk, mem_sphere_zero_iff_norm.mpr (le_antisymm _ _),
{ simpa only [cstar_ring.norm_coe_unitary u] using norm_le_norm_of_mem hk },
{ rw ←unitary.coe_to_units_apply u at hk,
have hnk := ne_zero_of_mem_of_unit hk,
rw [←inv_inv (unitary.to_units u), ←spectrum.map_inv, set.mem_inv] at hk,
have : ‖k‖⁻¹ ≤ ‖↑((unitary.to_units u)⁻¹)‖, simpa only [norm_inv] using norm_le_norm_of_mem hk,
simpa using inv_le_of_inv_le (norm_pos_iff.mpr hnk) this }
end
lemma spectrum.subset_circle_of_unitary {u : E} (h : u ∈ unitary E) :
spectrum 𝕜 u ⊆ metric.sphere 0 1 :=
unitary.spectrum_subset_circle ⟨u, h⟩
end unitary_spectrum
section complex_scalars
open complex
variables {A : Type*}
[normed_ring A] [normed_algebra ℂ A] [complete_space A] [star_ring A] [cstar_ring A]
local notation `↑ₐ` := algebra_map ℂ A
lemma is_self_adjoint.spectral_radius_eq_nnnorm {a : A}
(ha : is_self_adjoint a) :
spectral_radius ℂ a = ‖a‖₊ :=
begin
have hconst : tendsto (λ n : ℕ, (‖a‖₊ : ℝ≥0∞)) at_top _ := tendsto_const_nhds,
refine tendsto_nhds_unique _ hconst,
convert (spectrum.pow_nnnorm_pow_one_div_tendsto_nhds_spectral_radius (a : A)).comp
(nat.tendsto_pow_at_top_at_top_of_one_lt one_lt_two),
refine funext (λ n, _),
rw [function.comp_app, ha.nnnorm_pow_two_pow, ennreal.coe_pow, ←rpow_nat_cast,
←rpow_mul],
simp,
end
lemma is_star_normal.spectral_radius_eq_nnnorm (a : A) [is_star_normal a] :
spectral_radius ℂ a = ‖a‖₊ :=
begin
refine (ennreal.pow_strict_mono two_ne_zero).injective _,
have heq : (λ n : ℕ, ((‖(a⋆ * a) ^ n‖₊ ^ (1 / n : ℝ)) : ℝ≥0∞))
= (λ x, x ^ 2) ∘ (λ n : ℕ, ((‖a ^ n‖₊ ^ (1 / n : ℝ)) : ℝ≥0∞)),
{ funext,
rw [function.comp_apply, ←rpow_nat_cast, ←rpow_mul, mul_comm, rpow_mul, rpow_nat_cast,
←coe_pow, sq, ←nnnorm_star_mul_self, commute.mul_pow (star_comm_self' a), star_pow], },
have h₂ := ((ennreal.continuous_pow 2).tendsto (spectral_radius ℂ a)).comp
(spectrum.pow_nnnorm_pow_one_div_tendsto_nhds_spectral_radius a),
rw ←heq at h₂,
convert tendsto_nhds_unique h₂ (pow_nnnorm_pow_one_div_tendsto_nhds_spectral_radius (a⋆ * a)),
rw [(is_self_adjoint.star_mul_self a).spectral_radius_eq_nnnorm, sq, nnnorm_star_mul_self,
coe_mul],
end
/-- Any element of the spectrum of a selfadjoint is real. -/
theorem is_self_adjoint.mem_spectrum_eq_re [star_module ℂ A] {a : A}
(ha : is_self_adjoint a) {z : ℂ} (hz : z ∈ spectrum ℂ a) : z = z.re :=
begin
have hu := exp_mem_unitary_of_mem_skew_adjoint ℂ (ha.smul_mem_skew_adjoint conj_I),
let Iu := units.mk0 I I_ne_zero,
have : exp ℂ (I • z) ∈ spectrum ℂ (exp ℂ (I • a)),
by simpa only [units.smul_def, units.coe_mk0]
using spectrum.exp_mem_exp (Iu • a) (smul_mem_smul_iff.mpr hz),
exact complex.ext (of_real_re _)
(by simpa only [←complex.exp_eq_exp_ℂ, mem_sphere_zero_iff_norm, norm_eq_abs, abs_exp,
real.exp_eq_one_iff, smul_eq_mul, I_mul, neg_eq_zero]
using spectrum.subset_circle_of_unitary hu this),
end
/-- Any element of the spectrum of a selfadjoint is real. -/
theorem self_adjoint.mem_spectrum_eq_re [star_module ℂ A]
(a : self_adjoint A) {z : ℂ} (hz : z ∈ spectrum ℂ (a : A)) : z = z.re :=
a.prop.mem_spectrum_eq_re hz
/-- The spectrum of a selfadjoint is real -/
theorem is_self_adjoint.coe_re_map_spectrum [star_module ℂ A] {a : A}
(ha : is_self_adjoint a) : spectrum ℂ a = (coe ∘ re '' (spectrum ℂ a) : set ℂ) :=
le_antisymm (λ z hz, ⟨z, hz, (ha.mem_spectrum_eq_re hz).symm⟩) (λ z, by
{ rintros ⟨z, hz, rfl⟩,
simpa only [(ha.mem_spectrum_eq_re hz).symm, function.comp_app] using hz })
/-- The spectrum of a selfadjoint is real -/
theorem self_adjoint.coe_re_map_spectrum [star_module ℂ A] (a : self_adjoint A) :
spectrum ℂ (a : A) = (coe ∘ re '' (spectrum ℂ (a : A)) : set ℂ) :=
a.property.coe_re_map_spectrum
end complex_scalars
namespace star_alg_hom
variables {F A B : Type*}
[normed_ring A] [normed_algebra ℂ A] [complete_space A] [star_ring A] [cstar_ring A]
[normed_ring B] [normed_algebra ℂ B] [complete_space B] [star_ring B] [cstar_ring B]
[hF : star_alg_hom_class F ℂ A B] (φ : F)
include hF
/-- A star algebra homomorphism of complex C⋆-algebras is norm contractive. -/
lemma nnnorm_apply_le (a : A) : ‖(φ a : B)‖₊ ≤ ‖a‖₊ :=
begin
suffices : ∀ s : A, is_self_adjoint s → ‖φ s‖₊ ≤ ‖s‖₊,
{ exact nonneg_le_nonneg_of_sq_le_sq zero_le'
(by simpa only [nnnorm_star_mul_self, map_star, map_mul]
using this _ (is_self_adjoint.star_mul_self a)) },
{ intros s hs,
simpa only [hs.spectral_radius_eq_nnnorm, (hs.star_hom_apply φ).spectral_radius_eq_nnnorm,
coe_le_coe] using (show spectral_radius ℂ (φ s) ≤ spectral_radius ℂ s,
from supr_le_supr_of_subset (alg_hom.spectrum_apply_subset φ s)) }
end
/-- A star algebra homomorphism of complex C⋆-algebras is norm contractive. -/
lemma norm_apply_le (a : A) : ‖(φ a : B)‖ ≤ ‖a‖ := nnnorm_apply_le φ a
/-- Star algebra homomorphisms between C⋆-algebras are continuous linear maps.
See note [lower instance priority] -/
@[priority 100]
noncomputable instance : continuous_linear_map_class F ℂ A B :=
{ map_continuous := λ φ, add_monoid_hom_class.continuous_of_bound φ 1
(by simpa only [one_mul] using nnnorm_apply_le φ),
.. alg_hom_class.linear_map_class }
end star_alg_hom
end
namespace weak_dual
open continuous_map complex
open_locale complex_star_module
variables {F A : Type*} [normed_ring A] [normed_algebra ℂ A] [complete_space A]
[star_ring A] [cstar_ring A] [star_module ℂ A] [hF : alg_hom_class F ℂ A ℂ]
include hF
/-- This instance is provided instead of `star_alg_hom_class` to avoid type class inference loops.
See note [lower instance priority] -/
@[priority 100]
noncomputable instance : star_hom_class F A ℂ :=
{ coe := λ φ, φ,
coe_injective' := fun_like.coe_injective',
map_star := λ φ a,
begin
suffices hsa : ∀ s : self_adjoint A, (φ s)⋆ = φ s,
{ rw ←real_part_add_I_smul_imaginary_part a,
simp only [map_add, map_smul, star_add, star_smul, hsa, self_adjoint.star_coe_eq] },
{ intros s,
have := alg_hom.apply_mem_spectrum φ (s : A),
rw self_adjoint.coe_re_map_spectrum s at this,
rcases this with ⟨⟨_, _⟩, _, heq⟩,
rw [←heq, is_R_or_C.star_def, is_R_or_C.conj_of_real] }
end }
/-- This is not an instance to avoid type class inference loops. See
`weak_dual.complex.star_hom_class`. -/
noncomputable def _root_.alg_hom_class.star_alg_hom_class : star_alg_hom_class F ℂ A ℂ :=
{ coe := λ f, f,
.. weak_dual.complex.star_hom_class,
.. hF }
omit hF
namespace character_space
noncomputable instance : star_alg_hom_class (character_space ℂ A) ℂ A ℂ :=
{ coe := λ f, f,
.. alg_hom_class.star_alg_hom_class }
end character_space
end weak_dual
|
88881eb55168b44879e2847454f23cb84389338a | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/term_pred.lean | ab839fdc7241166f087ae1a3308f3e27b30a20dd | [
"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 | 599 | lean | inductive term
| app : string → list term → term
| var : string → term
inductive bin_only : term → Prop
| leaf : ∀ x, bin_only (term.var x)
| bin_app : ∀ op a b, bin_only a → bin_only b → bin_only (term.app op [a, b])
example (op : string) (a : term) : ¬ bin_only (term.app op [a]) :=
begin
intro h,
cases h
end
example (op : string) (a b : term) (H : bin_only (term.app op [a, b])) : bin_only a :=
begin
cases H,
assumption
end
example (op : string) (a b : term) (H : bin_only (term.app op [a, b])) : bin_only b :=
begin
cases H with _ _ _ _ H1 H2,
exact H2
end
|
9e7ea061e39c8d14d5557cdca77a772dd4cc76ea | 4727251e0cd73359b15b664c3170e5d754078599 | /src/topology/algebra/const_mul_action.lean | 04fb4e45d85d8b0d6a2eb0ef8c65d09a990e8745 | [
"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 | 18,422 | lean | /-
Copyright (c) 2021 Alex Kontorovich, Heather Macbeth. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alex Kontorovich, Heather Macbeth
-/
import topology.algebra.constructions
import topology.homeomorph
import group_theory.group_action.basic
/-!
# Monoid actions continuous in the second variable
In this file we define class `has_continuous_const_smul`. We say `has_continuous_const_smul Γ T` if
`Γ` acts on `T` and for each `γ`, the map `x ↦ γ • x` is continuous. (This differs from
`has_continuous_smul`, which requires simultaneous continuity in both variables.)
## Main definitions
* `has_continuous_const_smul Γ T` : typeclass saying that the map `x ↦ γ • x` is continuous on `T`;
* `properly_discontinuous_smul`: says that the scalar multiplication `(•) : Γ → T → T`
is properly discontinuous, that is, for any pair of compact sets `K, L` in `T`, only finitely
many `γ:Γ` move `K` to have nontrivial intersection with `L`.
* `homeomorph.smul`: scalar multiplication by an element of a group `Γ` acting on `T`
is a homeomorphism of `T`.
## Main results
* `is_open_map_quotient_mk_mul` : The quotient map by a group action is open.
* `t2_space_of_properly_discontinuous_smul_of_t2_space` : The quotient by a discontinuous group
action of a locally compact t2 space is t2.
## Tags
Hausdorff, discrete group, properly discontinuous, quotient space
-/
open_locale topological_space pointwise
open filter set
local attribute [instance] mul_action.orbit_rel
/-- Class `has_continuous_const_smul Γ T` says that the scalar multiplication `(•) : Γ → T → T`
is continuous in the second argument. We use the same class for all kinds of multiplicative
actions, including (semi)modules and algebras.
-/
class has_continuous_const_smul (Γ : Type*) (T : Type*) [topological_space T] [has_scalar Γ T]
: Prop :=
(continuous_const_smul : ∀ γ : Γ, continuous (λ x : T, γ • x))
/-- Class `has_continuous_const_vadd Γ T` says that the additive action `(+ᵥ) : Γ → T → T`
is continuous in the second argument. We use the same class for all kinds of additive actions,
including (semi)modules and algebras.
-/
class has_continuous_const_vadd (Γ : Type*) (T : Type*) [topological_space T]
[has_vadd Γ T] : Prop :=
(continuous_const_vadd : ∀ γ : Γ, continuous (λ x : T, γ +ᵥ x))
attribute [to_additive] has_continuous_const_smul
export has_continuous_const_smul (continuous_const_smul)
export has_continuous_const_vadd (continuous_const_vadd)
variables {M α β : Type*}
section has_scalar
variables [topological_space α] [has_scalar M α] [has_continuous_const_smul M α]
@[to_additive]
lemma filter.tendsto.const_smul {f : β → α} {l : filter β} {a : α} (hf : tendsto f l (𝓝 a))
(c : M) :
tendsto (λ x, c • f x) l (𝓝 (c • a)) :=
((continuous_const_smul _).tendsto _).comp hf
variables [topological_space β] {f : β → M} {g : β → α} {b : β} {s : set β}
@[to_additive]
lemma continuous_within_at.const_smul (hg : continuous_within_at g s b) (c : M) :
continuous_within_at (λ x, c • g x) s b :=
hg.const_smul c
@[to_additive]
lemma continuous_at.const_smul (hg : continuous_at g b) (c : M) :
continuous_at (λ x, c • g x) b :=
hg.const_smul c
@[to_additive]
lemma continuous_on.const_smul (hg : continuous_on g s) (c : M) :
continuous_on (λ x, c • g x) s :=
λ x hx, (hg x hx).const_smul c
@[continuity, to_additive]
lemma continuous.const_smul (hg : continuous g) (c : M) :
continuous (λ x, c • g x) :=
(continuous_const_smul _).comp hg
/-- If a scalar is central, then its right action is continuous when its left action is. -/
instance has_continuous_const_smul.op [has_scalar Mᵐᵒᵖ α] [is_central_scalar M α] :
has_continuous_const_smul Mᵐᵒᵖ α :=
⟨ mul_opposite.rec $ λ c, by simpa only [op_smul_eq_smul] using continuous_const_smul c ⟩
@[to_additive] instance mul_opposite.has_continuous_const_smul :
has_continuous_const_smul M αᵐᵒᵖ :=
⟨λ c, mul_opposite.continuous_op.comp $ mul_opposite.continuous_unop.const_smul c⟩
@[to_additive]
instance [has_scalar M β] [has_continuous_const_smul M β] :
has_continuous_const_smul M (α × β) :=
⟨λ _, (continuous_fst.const_smul _).prod_mk (continuous_snd.const_smul _)⟩
@[to_additive]
instance {ι : Type*} {γ : ι → Type*} [∀ i, topological_space (γ i)] [Π i, has_scalar M (γ i)]
[∀ i, has_continuous_const_smul M (γ i)] : has_continuous_const_smul M (Π i, γ i) :=
⟨λ _, continuous_pi $ λ i, (continuous_apply i).const_smul _⟩
end has_scalar
section monoid
variables [topological_space α]
variables [monoid M] [mul_action M α] [has_continuous_const_smul M α]
@[to_additive] instance units.has_continuous_const_smul : has_continuous_const_smul Mˣ α :=
{ continuous_const_smul := λ m, (continuous_const_smul (m : M) : _) }
@[to_additive]
lemma smul_closure_subset (c : M) (s : set α) : c • closure s ⊆ closure (c • s) :=
((set.maps_to_image _ _).closure $ continuous_id.const_smul c).image_subset
@[to_additive]
lemma smul_closure_orbit_subset (c : M) (x : α) :
c • closure (mul_action.orbit M x) ⊆ closure (mul_action.orbit M x) :=
(smul_closure_subset c _).trans $ closure_mono $ mul_action.smul_orbit_subset _ _
end monoid
section group
variables {G : Type*} [topological_space α] [group G] [mul_action G α]
[has_continuous_const_smul G α]
@[to_additive]
lemma tendsto_const_smul_iff {f : β → α} {l : filter β} {a : α} (c : G) :
tendsto (λ x, c • f x) l (𝓝 $ c • a) ↔ tendsto f l (𝓝 a) :=
⟨λ h, by simpa only [inv_smul_smul] using h.const_smul c⁻¹,
λ h, h.const_smul _⟩
variables [topological_space β] {f : β → α} {b : β} {s : set β}
@[to_additive]
lemma continuous_within_at_const_smul_iff (c : G) :
continuous_within_at (λ x, c • f x) s b ↔ continuous_within_at f s b :=
tendsto_const_smul_iff c
@[to_additive]
lemma continuous_on_const_smul_iff (c : G) : continuous_on (λ x, c • f x) s ↔ continuous_on f s :=
forall₂_congr $ λ b hb, continuous_within_at_const_smul_iff c
@[to_additive]
lemma continuous_at_const_smul_iff (c : G) :
continuous_at (λ x, c • f x) b ↔ continuous_at f b :=
tendsto_const_smul_iff c
@[to_additive]
lemma continuous_const_smul_iff (c : G) :
continuous (λ x, c • f x) ↔ continuous f :=
by simp only [continuous_iff_continuous_at, continuous_at_const_smul_iff]
/-- The homeomorphism given by scalar multiplication by a given element of a group `Γ` acting on
`T` is a homeomorphism from `T` to itself. -/
@[to_additive] def homeomorph.smul (γ : G) : α ≃ₜ α :=
{ to_equiv := mul_action.to_perm γ,
continuous_to_fun := continuous_const_smul γ,
continuous_inv_fun := continuous_const_smul γ⁻¹ }
/-- The homeomorphism given by affine-addition by an element of an additive group `Γ` acting on
`T` is a homeomorphism from `T` to itself. -/
add_decl_doc homeomorph.vadd
@[to_additive]
lemma is_open_map_smul (c : G) : is_open_map (λ x : α, c • x) :=
(homeomorph.smul c).is_open_map
@[to_additive] lemma is_open.smul {s : set α} (hs : is_open s) (c : G) : is_open (c • s) :=
is_open_map_smul c s hs
@[to_additive]
lemma is_closed_map_smul (c : G) : is_closed_map (λ x : α, c • x) :=
(homeomorph.smul c).is_closed_map
@[to_additive] lemma is_closed.smul {s : set α} (hs : is_closed s) (c : G) : is_closed (c • s) :=
is_closed_map_smul c s hs
@[to_additive] lemma closure_smul (c : G) (s : set α) : closure (c • s) = c • closure s :=
((homeomorph.smul c).image_closure s).symm
@[to_additive] lemma interior_smul (c : G) (s : set α) : interior (c • s) = c • interior s :=
((homeomorph.smul c).image_interior s).symm
end group
section group_with_zero
variables {G₀ : Type*} [topological_space α] [group_with_zero G₀] [mul_action G₀ α]
[has_continuous_const_smul G₀ α]
lemma tendsto_const_smul_iff₀ {f : β → α} {l : filter β} {a : α} {c : G₀} (hc : c ≠ 0) :
tendsto (λ x, c • f x) l (𝓝 $ c • a) ↔ tendsto f l (𝓝 a) :=
tendsto_const_smul_iff (units.mk0 c hc)
variables [topological_space β] {f : β → α} {b : β} {c : G₀} {s : set β}
lemma continuous_within_at_const_smul_iff₀ (hc : c ≠ 0) :
continuous_within_at (λ x, c • f x) s b ↔ continuous_within_at f s b :=
tendsto_const_smul_iff (units.mk0 c hc)
lemma continuous_on_const_smul_iff₀ (hc : c ≠ 0) :
continuous_on (λ x, c • f x) s ↔ continuous_on f s :=
continuous_on_const_smul_iff (units.mk0 c hc)
lemma continuous_at_const_smul_iff₀ (hc : c ≠ 0) :
continuous_at (λ x, c • f x) b ↔ continuous_at f b :=
continuous_at_const_smul_iff (units.mk0 c hc)
lemma continuous_const_smul_iff₀ (hc : c ≠ 0) :
continuous (λ x, c • f x) ↔ continuous f :=
continuous_const_smul_iff (units.mk0 c hc)
/-- Scalar multiplication by a non-zero element of a group with zero acting on `α` is a
homeomorphism from `α` onto itself. -/
protected def homeomorph.smul_of_ne_zero (c : G₀) (hc : c ≠ 0) : α ≃ₜ α :=
homeomorph.smul (units.mk0 c hc)
lemma is_open_map_smul₀ {c : G₀} (hc : c ≠ 0) : is_open_map (λ x : α, c • x) :=
(homeomorph.smul_of_ne_zero c hc).is_open_map
lemma is_open.smul₀ {c : G₀} {s : set α} (hs : is_open s) (hc : c ≠ 0) : is_open (c • s) :=
is_open_map_smul₀ hc s hs
lemma interior_smul₀ {c : G₀} (hc : c ≠ 0) (s : set α) : interior (c • s) = c • interior s :=
((homeomorph.smul_of_ne_zero c hc).image_interior s).symm
lemma closure_smul₀ {E} [has_zero E] [mul_action_with_zero G₀ E] [topological_space E]
[t1_space E] [has_continuous_const_smul G₀ E] (c : G₀) (s : set E) :
closure (c • s) = c • closure s :=
begin
rcases eq_or_ne c 0 with rfl|hc,
{ rcases eq_empty_or_nonempty s with rfl|hs,
{ simp },
{ rw [zero_smul_set hs, zero_smul_set hs.closure], exact closure_singleton } },
{ exact ((homeomorph.smul_of_ne_zero c hc).image_closure s).symm }
end
/-- `smul` is a closed map in the second argument.
The lemma that `smul` is a closed map in the first argument (for a normed space over a complete
normed field) is `is_closed_map_smul_left` in `analysis.normed_space.finite_dimension`. -/
lemma is_closed_map_smul_of_ne_zero {c : G₀} (hc : c ≠ 0) : is_closed_map (λ x : α, c • x) :=
(homeomorph.smul_of_ne_zero c hc).is_closed_map
lemma is_closed.smul_of_ne_zero {c : G₀} {s : set α} (hs : is_closed s) (hc : c ≠ 0) :
is_closed (c • s) :=
is_closed_map_smul_of_ne_zero hc s hs
/-- `smul` is a closed map in the second argument.
The lemma that `smul` is a closed map in the first argument (for a normed space over a complete
normed field) is `is_closed_map_smul_left` in `analysis.normed_space.finite_dimension`. -/
lemma is_closed_map_smul₀ {𝕜 M : Type*} [division_ring 𝕜] [add_comm_monoid M] [topological_space M]
[t1_space M] [module 𝕜 M] [has_continuous_const_smul 𝕜 M] (c : 𝕜) :
is_closed_map (λ x : M, c • x) :=
begin
rcases eq_or_ne c 0 with (rfl|hne),
{ simp only [zero_smul], exact is_closed_map_const },
{ exact (homeomorph.smul_of_ne_zero c hne).is_closed_map },
end
lemma is_closed.smul₀ {𝕜 M : Type*} [division_ring 𝕜] [add_comm_monoid M] [topological_space M]
[t1_space M] [module 𝕜 M] [has_continuous_const_smul 𝕜 M] (c : 𝕜) {s : set M} (hs : is_closed s) :
is_closed (c • s) :=
is_closed_map_smul₀ c s hs
end group_with_zero
namespace is_unit
variables [monoid M] [topological_space α] [mul_action M α] [has_continuous_const_smul M α]
lemma tendsto_const_smul_iff {f : β → α} {l : filter β} {a : α} {c : M} (hc : is_unit c) :
tendsto (λ x, c • f x) l (𝓝 $ c • a) ↔ tendsto f l (𝓝 a) :=
let ⟨u, hu⟩ := hc in hu ▸ tendsto_const_smul_iff u
variables [topological_space β] {f : β → α} {b : β} {c : M} {s : set β}
lemma continuous_within_at_const_smul_iff (hc : is_unit c) :
continuous_within_at (λ x, c • f x) s b ↔ continuous_within_at f s b :=
let ⟨u, hu⟩ := hc in hu ▸ continuous_within_at_const_smul_iff u
lemma continuous_on_const_smul_iff (hc : is_unit c) :
continuous_on (λ x, c • f x) s ↔ continuous_on f s :=
let ⟨u, hu⟩ := hc in hu ▸ continuous_on_const_smul_iff u
lemma continuous_at_const_smul_iff (hc : is_unit c) :
continuous_at (λ x, c • f x) b ↔ continuous_at f b :=
let ⟨u, hu⟩ := hc in hu ▸ continuous_at_const_smul_iff u
lemma continuous_const_smul_iff (hc : is_unit c) :
continuous (λ x, c • f x) ↔ continuous f :=
let ⟨u, hu⟩ := hc in hu ▸ continuous_const_smul_iff u
lemma is_open_map_smul (hc : is_unit c) : is_open_map (λ x : α, c • x) :=
let ⟨u, hu⟩ := hc in hu ▸ is_open_map_smul u
lemma is_closed_map_smul (hc : is_unit c) : is_closed_map (λ x : α, c • x) :=
let ⟨u, hu⟩ := hc in hu ▸ is_closed_map_smul u
end is_unit
/-- Class `properly_discontinuous_smul Γ T` says that the scalar multiplication `(•) : Γ → T → T`
is properly discontinuous, that is, for any pair of compact sets `K, L` in `T`, only finitely many
`γ:Γ` move `K` to have nontrivial intersection with `L`.
-/
class properly_discontinuous_smul (Γ : Type*) (T : Type*) [topological_space T]
[has_scalar Γ T] : Prop :=
(finite_disjoint_inter_image : ∀ {K L : set T}, is_compact K → is_compact L →
set.finite {γ : Γ | (((•) γ) '' K) ∩ L ≠ ∅ })
/-- Class `properly_discontinuous_vadd Γ T` says that the additive action `(+ᵥ) : Γ → T → T`
is properly discontinuous, that is, for any pair of compact sets `K, L` in `T`, only finitely many
`γ:Γ` move `K` to have nontrivial intersection with `L`.
-/
class properly_discontinuous_vadd (Γ : Type*) (T : Type*) [topological_space T]
[has_vadd Γ T] : Prop :=
(finite_disjoint_inter_image : ∀ {K L : set T}, is_compact K → is_compact L →
set.finite {γ : Γ | (((+ᵥ) γ) '' K) ∩ L ≠ ∅ })
attribute [to_additive] properly_discontinuous_smul
variables {Γ : Type*} [group Γ] {T : Type*} [topological_space T] [mul_action Γ T]
/-- A finite group action is always properly discontinuous
-/
@[priority 100, to_additive] instance fintype.properly_discontinuous_smul [fintype Γ] :
properly_discontinuous_smul Γ T :=
{ finite_disjoint_inter_image := λ _ _ _ _, set.finite.of_fintype _}
export properly_discontinuous_smul (finite_disjoint_inter_image)
export properly_discontinuous_vadd (finite_disjoint_inter_image)
/-- The quotient map by a group action is open. -/
@[to_additive]
lemma is_open_map_quotient_mk_mul [has_continuous_const_smul Γ T] :
is_open_map (quotient.mk : T → quotient (mul_action.orbit_rel Γ T)) :=
begin
intros U hU,
rw [is_open_coinduced, mul_action.quotient_preimage_image_eq_union_mul U],
exact is_open_Union (λ γ, (homeomorph.smul γ).is_open_map U hU)
end
/-- The quotient by a discontinuous group action of a locally compact t2 space is t2. -/
@[priority 100, to_additive] instance t2_space_of_properly_discontinuous_smul_of_t2_space
[t2_space T] [locally_compact_space T] [has_continuous_const_smul Γ T]
[properly_discontinuous_smul Γ T] : t2_space (quotient (mul_action.orbit_rel Γ T)) :=
begin
set Q := quotient (mul_action.orbit_rel Γ T),
rw t2_space_iff_nhds,
let f : T → Q := quotient.mk,
have f_op : is_open_map f := is_open_map_quotient_mk_mul,
rintros ⟨x₀⟩ ⟨y₀⟩ (hxy : f x₀ ≠ f y₀),
show ∃ (U ∈ 𝓝 (f x₀)) (V ∈ 𝓝 (f y₀)), U ∩ V = ∅,
have hx₀y₀ : x₀ ≠ y₀ := ne_of_apply_ne _ hxy,
have hγx₀y₀ : ∀ γ : Γ, γ • x₀ ≠ y₀ := not_exists.mp (mt quotient.sound hxy.symm : _),
obtain ⟨K₀, L₀, K₀_in, L₀_in, hK₀, hL₀, hK₀L₀⟩ := t2_separation_compact_nhds hx₀y₀,
let bad_Γ_set := {γ : Γ | (((•) γ) '' K₀) ∩ L₀ ≠ ∅ },
have bad_Γ_finite : bad_Γ_set.finite := finite_disjoint_inter_image hK₀ hL₀,
choose u v hu hv u_v_disjoint using λ γ, t2_separation_nhds (hγx₀y₀ γ),
let U₀₀ := ⋂ γ ∈ bad_Γ_set, ((•) γ) ⁻¹' (u γ),
let U₀ := U₀₀ ∩ K₀,
let V₀₀ := ⋂ γ ∈ bad_Γ_set, v γ,
let V₀ := V₀₀ ∩ L₀,
have U_nhds : f '' U₀ ∈ 𝓝 (f x₀),
{ apply f_op.image_mem_nhds (inter_mem ((bInter_mem bad_Γ_finite).mpr $ λ γ hγ, _) K₀_in),
exact (continuous_const_smul _).continuous_at (hu γ) },
have V_nhds : f '' V₀ ∈ 𝓝 (f y₀),
from f_op.image_mem_nhds (inter_mem ((bInter_mem bad_Γ_finite).mpr $ λ γ hγ, hv γ) L₀_in),
refine ⟨f '' U₀, U_nhds, f '' V₀, V_nhds, _⟩,
rw mul_action.image_inter_image_iff,
rintros x ⟨x_in_U₀₀, x_in_K₀⟩ γ,
by_cases H : γ ∈ bad_Γ_set,
{ rintros ⟨h, -⟩,
exact eq_empty_iff_forall_not_mem.mp (u_v_disjoint γ) (γ • x)
⟨(mem_Inter₂.mp x_in_U₀₀ γ H : _), mem_Inter₂.mp h γ H⟩ },
{ rintros ⟨-, h'⟩,
simp only [image_smul, not_not, mem_set_of_eq, ne.def] at H,
exact eq_empty_iff_forall_not_mem.mp H (γ • x) ⟨mem_image_of_mem _ x_in_K₀, h'⟩ },
end
section nhds
section mul_action
variables {G₀ : Type*} [group_with_zero G₀] [mul_action G₀ α]
[topological_space α] [has_continuous_const_smul G₀ α]
/-- Scalar multiplication preserves neighborhoods. -/
lemma set_smul_mem_nhds_smul {c : G₀} {s : set α} {x : α} (hs : s ∈ 𝓝 x) (hc : c ≠ 0) :
c • s ∈ 𝓝 (c • x : α) :=
begin
rw mem_nhds_iff at hs ⊢,
obtain ⟨U, hs', hU, hU'⟩ := hs,
exact ⟨c • U, set.smul_set_mono hs', hU.smul₀ hc, set.smul_mem_smul_set hU'⟩,
end
lemma set_smul_mem_nhds_smul_iff {c : G₀} {s : set α} {x : α} (hc : c ≠ 0) :
c • s ∈ 𝓝 (c • x : α) ↔ s ∈ 𝓝 x :=
begin
refine ⟨λ h, _, λ h, set_smul_mem_nhds_smul h hc⟩,
rw [←inv_smul_smul₀ hc x, ←inv_smul_smul₀ hc s],
exact set_smul_mem_nhds_smul h (inv_ne_zero hc),
end
end mul_action
section distrib_mul_action
variables {G₀ : Type*} [group_with_zero G₀] [add_monoid α] [distrib_mul_action G₀ α]
[topological_space α] [has_continuous_const_smul G₀ α]
lemma set_smul_mem_nhds_zero_iff {s : set α} {c : G₀} (hc : c ≠ 0) :
c • s ∈ 𝓝 (0 : α) ↔ s ∈ 𝓝 (0 : α) :=
begin
refine iff.trans _ (set_smul_mem_nhds_smul_iff hc),
rw smul_zero,
end
end distrib_mul_action
end nhds
|
07260bb93086b57cbc022ce090b44434a561bd50 | 5ee26964f602030578ef0159d46145dd2e357ba5 | /src/for_mathlib/division_ring.lean | 51fc428ea55a69048fb3721d3c54c252d5e015a2 | [
"Apache-2.0"
] | permissive | fpvandoorn/lean-perfectoid-spaces | 569b4006fdfe491ca8b58dd817bb56138ada761f | 06cec51438b168837fc6e9268945735037fd1db6 | refs/heads/master | 1,590,154,571,918 | 1,557,685,392,000 | 1,557,685,392,000 | 186,363,547 | 0 | 0 | Apache-2.0 | 1,557,730,933,000 | 1,557,730,933,000 | null | UTF-8 | Lean | false | false | 574 | lean | import algebra.field
@[simp]
lemma division_ring.val_inv {R : Type*} [division_ring R] (x : units R) : (x.val)⁻¹ = x.inv :=
begin
rw [←units.mul_left_inj x],
show x.val * _ = x.val * _,
rw [x.val_inv, mul_inv_cancel],
have h : x.val * x.inv ≠ 0,
rw x.val_inv,
simp,
exact ne_zero_of_mul_ne_zero_right h
end
@[simp]
lemma division_ring.inv_val {R : Type*} [division_ring R] (x : units R) : x⁻¹.val = x.inv := rfl
def units.mk' {R : Type*} [division_ring R] {y : R} (h : y ≠ 0) : units R :=
⟨y, y⁻¹, mul_inv_cancel h, inv_mul_cancel h⟩
|
c265ee0e8e604380b1da94405cb7883a1f732821 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/analysis/box_integral/partition/subbox_induction.lean | 3c24e8a148c1d9156ec66f67c6c340a221011225 | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 10,560 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import analysis.box_integral.box.subbox_induction
import analysis.box_integral.partition.tagged
/-!
# Induction on subboxes
In this file we prove (see
`box_integral.tagged_partition.exists_is_Henstock_is_subordinate_homothetic`) that for every box `I`
in `ℝⁿ` and a function `r : ℝⁿ → ℝ` positive on `I` there exists a tagged partition `π` of `I` such
that
* `π` is a Henstock partition;
* `π` is subordinate to `r`;
* each box in `π` is homothetic to `I` with coefficient of the form `1 / 2 ^ n`.
Later we will use this lemma to prove that the Henstock filter is nontrivial, hence the Henstock
integral is well-defined.
## Tags
partition, tagged partition, Henstock integral
-/
namespace box_integral
open set metric
open_locale classical topological_space
noncomputable theory
variables {ι : Type*} [fintype ι] {I J : box ι}
namespace prepartition
/-- Split a box in `ℝⁿ` into `2 ^ n` boxes by hyperplanes passing through its center. -/
def split_center (I : box ι) : prepartition I :=
{ boxes := finset.univ.map (box.split_center_box_emb I),
le_of_mem' := by simp [I.split_center_box_le],
pairwise_disjoint :=
begin
rw [finset.coe_map, finset.coe_univ, image_univ],
rintro _ ⟨s, rfl⟩ _ ⟨t, rfl⟩ Hne,
exact I.disjoint_split_center_box (mt (congr_arg _) Hne)
end }
@[simp] lemma mem_split_center : J ∈ split_center I ↔ ∃ s, I.split_center_box s = J :=
by simp [split_center]
lemma is_partition_split_center (I : box ι) : is_partition (split_center I) :=
λ x hx, by simp [hx]
lemma upper_sub_lower_of_mem_split_center (h : J ∈ split_center I) (i : ι) :
J.upper i - J.lower i = (I.upper i - I.lower i) / 2 :=
let ⟨s, hs⟩ := mem_split_center.1 h in hs ▸ I.upper_sub_lower_split_center_box s i
end prepartition
namespace box
open prepartition tagged_prepartition
/-- Let `p` be a predicate on `box ι`, let `I` be a box. Suppose that the following two properties
hold true.
* Consider a smaller box `J ≤ I`. The hyperplanes passing through the center of `J` split it into
`2 ^ n` boxes. If `p` holds true on each of these boxes, then it true on `J`.
* For each `z` in the closed box `I.Icc` there exists a neighborhood `U` of `z` within `I.Icc` such
that for every box `J ≤ I` such that `z ∈ J.Icc ⊆ U`, if `J` is homothetic to `I` with a
coefficient of the form `1 / 2 ^ m`, then `p` is true on `J`.
Then `p I` is true. See also `box_integral.box.subbox_induction_on'` for a version using
`box_integral.box.split_center_box` instead of `box_integral.prepartition.split_center`. -/
@[elab_as_eliminator]
lemma subbox_induction_on {p : box ι → Prop} (I : box ι)
(H_ind : ∀ J ≤ I, (∀ J' ∈ split_center J, p J') → p J)
(H_nhds : ∀ z ∈ I.Icc, ∃ (U ∈ 𝓝[I.Icc] z), ∀ (J ≤ I) (m : ℕ), z ∈ J.Icc → J.Icc ⊆ U →
(∀ i, J.upper i - J.lower i = (I.upper i - I.lower i) / 2 ^ m) → p J) :
p I :=
begin
refine subbox_induction_on' I (λ J hle hs, H_ind J hle $ λ J' h', _) H_nhds,
rcases mem_split_center.1 h' with ⟨s, rfl⟩,
exact hs s
end
/-- Given a box `I` in `ℝⁿ` and a function `r : ℝⁿ → (0, ∞)`, there exists a tagged partition `π` of
`I` such that
* `π` is a Henstock partition;
* `π` is subordinate to `r`;
* each box in `π` is homothetic to `I` with coefficient of the form `1 / 2 ^ m`.
This lemma implies that the Henstock filter is nontrivial, hence the Henstock integral is
well-defined. -/
lemma exists_tagged_partition_is_Henstock_is_subordinate_homothetic (I : box ι)
(r : (ι → ℝ) → Ioi (0 : ℝ)) :
∃ π : tagged_prepartition I, π.is_partition ∧ π.is_Henstock ∧ π.is_subordinate r ∧
(∀ J ∈ π, ∃ m : ℕ, ∀ i, (J : _).upper i - J.lower i = (I.upper i - I.lower i) / 2 ^ m) ∧
π.distortion = I.distortion :=
begin
refine subbox_induction_on I (λ J hle hJ, _) (λ z hz, _),
{ choose! πi hP hHen hr Hn Hd using hJ, choose! n hn using Hn,
have hP : ((split_center J).bUnion_tagged πi).is_partition,
from (is_partition_split_center _).bUnion_tagged hP,
have hsub : ∀ (J' ∈ (split_center J).bUnion_tagged πi), ∃ n : ℕ, ∀ i,
(J' : _).upper i - J'.lower i = (J.upper i - J.lower i) / 2 ^ n,
{ intros J' hJ',
rcases (split_center J).mem_bUnion_tagged.1 hJ' with ⟨J₁, h₁, h₂⟩,
refine ⟨n J₁ J' + 1, λ i, _⟩,
simp only [hn J₁ h₁ J' h₂, upper_sub_lower_of_mem_split_center h₁, pow_succ,
div_div_eq_div_mul] },
refine ⟨_, hP, is_Henstock_bUnion_tagged.2 hHen, is_subordinate_bUnion_tagged.2 hr, hsub, _⟩,
refine tagged_prepartition.distortion_of_const _ hP.nonempty_boxes (λ J' h', _),
rcases hsub J' h' with ⟨n, hn⟩,
exact box.distortion_eq_of_sub_eq_div hn },
{ refine ⟨I.Icc ∩ closed_ball z (r z),
inter_mem_nhds_within _ (closed_ball_mem_nhds _ (r z).coe_prop), _⟩,
intros J Hle n Hmem HIcc Hsub,
rw set.subset_inter_iff at HIcc,
refine ⟨single _ _ le_rfl _ Hmem, is_partition_single _, is_Henstock_single _,
(is_subordinate_single _ _).2 HIcc.2, _, distortion_single _ _⟩,
simp only [tagged_prepartition.mem_single, forall_eq],
refine ⟨0, λ i, _⟩, simp }
end
end box
namespace prepartition
open tagged_prepartition finset function
/-- Given a box `I` in `ℝⁿ`, a function `r : ℝⁿ → (0, ∞)`, and a prepartition `π` of `I`, there
exists a tagged prepartition `π'` of `I` such that
* each box of `π'` is included in some box of `π`;
* `π'` is a Henstock partition;
* `π'` is subordinate to `r`;
* `π'` covers exactly the same part of `I` as `π`;
* the distortion of `π'` is equal to the distortion of `π`.
-/
lemma exists_tagged_le_is_Henstock_is_subordinate_Union_eq {I : box ι} (r : (ι → ℝ) → Ioi (0 : ℝ))
(π : prepartition I) :
∃ π' : tagged_prepartition I, π'.to_prepartition ≤ π ∧
π'.is_Henstock ∧ π'.is_subordinate r ∧ π'.distortion = π.distortion ∧
π'.Union = π.Union :=
begin
have := λ J, box.exists_tagged_partition_is_Henstock_is_subordinate_homothetic J r,
choose! πi πip πiH πir hsub πid, clear hsub,
refine ⟨π.bUnion_tagged πi, bUnion_le _ _, is_Henstock_bUnion_tagged.2 (λ J _, πiH J),
is_subordinate_bUnion_tagged.2 (λ J _, πir J), _, π.Union_bUnion_partition (λ J _, πip J)⟩,
rw [distortion_bUnion_tagged],
exact sup_congr rfl (λ J _, πid J)
end
/-- Given a prepartition `π` of a box `I` and a function `r : ℝⁿ → (0, ∞)`, `π.to_subordinate r`
is a tagged partition `π'` such that
* each box of `π'` is included in some box of `π`;
* `π'` is a Henstock partition;
* `π'` is subordinate to `r`;
* `π'` covers exactly the same part of `I` as `π`;
* the distortion of `π'` is equal to the distortion of `π`.
-/
def to_subordinate (π : prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) : tagged_prepartition I :=
(π.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r).some
lemma to_subordinate_to_prepartition_le (π : prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) :
(π.to_subordinate r).to_prepartition ≤ π :=
(π.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r).some_spec.1
lemma is_Henstock_to_subordinate (π : prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) :
(π.to_subordinate r).is_Henstock :=
(π.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r).some_spec.2.1
lemma is_subordinate_to_subordinate (π : prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) :
(π.to_subordinate r).is_subordinate r :=
(π.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r).some_spec.2.2.1
@[simp] lemma distortion_to_subordinate (π : prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) :
(π.to_subordinate r).distortion = π.distortion :=
(π.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r).some_spec.2.2.2.1
@[simp] lemma Union_to_subordinate (π : prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) :
(π.to_subordinate r).Union = π.Union :=
(π.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r).some_spec.2.2.2.2
end prepartition
namespace tagged_prepartition
/-- Given a tagged prepartition `π₁`, a prepartition `π₂` that covers exactly `I \ π₁.Union`, and
a function `r : ℝⁿ → (0, ∞)`, returns the union of `π₁` and `π₂.to_subordinate r`. This partition
`π` has the following properties:
* `π` is a partition, i.e. it covers the whole `I`;
* `π₁.boxes ⊆ π.boxes`;
* `π.tag J = π₁.tag J` whenever `J ∈ π₁`;
* `π` is Henstock outside of `π₁`: `π.tag J ∈ J.Icc` whenever `J ∈ π`, `J ∉ π₁`;
* `π` is subordinate to `r` outside of `π₁`;
* the distortion of `π` is equal to the maximum of the distortions of `π₁` and `π₂`.
-/
def union_compl_to_subordinate (π₁ : tagged_prepartition I) (π₂ : prepartition I)
(hU : π₂.Union = I \ π₁.Union) (r : (ι → ℝ) → Ioi (0 : ℝ)) :
tagged_prepartition I :=
π₁.disj_union (π₂.to_subordinate r)
(((π₂.Union_to_subordinate r).trans hU).symm ▸ disjoint_diff)
lemma is_partition_union_compl_to_subordinate (π₁ : tagged_prepartition I) (π₂ : prepartition I)
(hU : π₂.Union = I \ π₁.Union) (r : (ι → ℝ) → Ioi (0 : ℝ)) :
is_partition (π₁.union_compl_to_subordinate π₂ hU r) :=
prepartition.is_partition_disj_union_of_eq_diff ((π₂.Union_to_subordinate r).trans hU)
@[simp] lemma union_compl_to_subordinate_boxes (π₁ : tagged_prepartition I) (π₂ : prepartition I)
(hU : π₂.Union = I \ π₁.Union) (r : (ι → ℝ) → Ioi (0 : ℝ)) :
(π₁.union_compl_to_subordinate π₂ hU r).boxes = π₁.boxes ∪ (π₂.to_subordinate r).boxes :=
rfl
@[simp] lemma Union_union_compl_to_subordinate_boxes (π₁ : tagged_prepartition I)
(π₂ : prepartition I) (hU : π₂.Union = I \ π₁.Union) (r : (ι → ℝ) → Ioi (0 : ℝ)) :
(π₁.union_compl_to_subordinate π₂ hU r).Union = I :=
(is_partition_union_compl_to_subordinate _ _ _ _).Union_eq
@[simp] lemma distortion_union_compl_to_subordinate (π₁ : tagged_prepartition I)
(π₂ : prepartition I) (hU : π₂.Union = I \ π₁.Union) (r : (ι → ℝ) → Ioi (0 : ℝ)) :
(π₁.union_compl_to_subordinate π₂ hU r).distortion = max π₁.distortion π₂.distortion :=
by simp [union_compl_to_subordinate]
end tagged_prepartition
end box_integral
|
21c4ef9da4f931b18697e438c3543863b93a229e | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/meta/uchange.lean | 7409087fdaff137467f9f9be1dc94dc8a8d02e9d | [
"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,946 | lean | /-
Copyright (c) 2020 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
/-!
# Changing universes of types in meta-code
This file defines the meta type `uchange (α : Type v) : Type u`, which
permits us to change the universe of a type analogously to `ulift`.
However since `uchange` is meta, it can both lift and lower the universe.
The implementation of `uchange` is efficient. Both `uchange.up` and
`uchange.down` compile to no-ops.
-/
universes u v
/--
`unchecked_cast' a : β` performs an unchecked cast of `(a : α)` to `β`.
Unlike `unchecked_cast`, it can cast across universes. The VM implementation
is guaranteed to be the identity.
-/
@[inline, irreducible]
meta def unchecked_cast' {α : Sort u} {β : Sort v} (a : α) : β :=
plift.down $ @cast (α → β → plift β) (β → α → plift β) undefined (λ _ a, plift.up a)
(cast undefined punit.star) a
/--
`uchange (α : Sort v) : Sort u` is an equivalent type in a different universe.
In the VM, both `α` and `uchange α` have the same representation.
This definition is `meta` because it collapses the universe hierarchy; if pure code could do
this then one could derive Girard's paradox.
-/
meta def uchange (α : Type v) : Type u :=
unchecked_cast' α
namespace uchange
variables {α : Type v} (a : α)
meta instance [decidable_eq α] : decidable_eq (uchange α) :=
unchecked_cast' (by apply_instance : _root_.decidable_eq α)
/--
`uchange.down` embeds `α` to `uchange α`.
The VM implementation is guaranteed to be the identity.
-/
@[inline]
meta def down {α} (a : α) : uchange α :=
unchecked_cast' a
/--
`uchange.up` extracts from `uchange α` an `α`.
The VM implementation is guaranteed to be the identity.
-/
@[inline]
meta def up {α} (a : uchange α) : α :=
unchecked_cast' a
end uchange
-- Sanity check
#eval do
guard $ (uchange.down.{0} 42).up = 42,
tactic.skip
|
1cd463e9d2030975ef505e7aece745f9ff4251ee | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/topology/homeomorph.lean | ede44d16f8a45c814174311f2cc7466525629e24 | [
"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 | 14,606 | lean | /-
Copyright (c) 2019 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Patrick Massot, Sébastien Gouëzel, Zhouhang Zhou, Reid Barton
-/
import topology.dense_embedding
/-!
# Homeomorphisms
This file defines homeomorphisms between two topological spaces. They are bijections with both
directions continuous. We denote homeomorphisms with the notation `≃ₜ`.
# Main definitions
* `homeomorph α β`: The type of homeomorphisms from `α` to `β`.
This type can be denoted using the following notation: `α ≃ₜ β`.
# Main results
* Pretty much every topological property is preserved under homeomorphisms.
* `homeomorph.homeomorph_of_continuous_open`: A continuous bijection that is
an open map is a homeomorphism.
-/
open set filter
open_locale topological_space
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
/-- Homeomorphism between `α` and `β`, also called topological isomorphism -/
@[nolint has_inhabited_instance] -- not all spaces are homeomorphic to each other
structure homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β]
extends α ≃ β :=
(continuous_to_fun : continuous to_fun . tactic.interactive.continuity')
(continuous_inv_fun : continuous inv_fun . tactic.interactive.continuity')
infix ` ≃ₜ `:25 := homeomorph
namespace homeomorph
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
instance : has_coe_to_fun (α ≃ₜ β) := ⟨λ_, α → β, λe, e.to_equiv⟩
@[simp] lemma homeomorph_mk_coe (a : equiv α β) (b c) :
((homeomorph.mk a b c) : α → β) = a :=
rfl
@[simp] lemma coe_to_equiv (h : α ≃ₜ β) : ⇑h.to_equiv = h := rfl
/-- Inverse of a homeomorphism. -/
protected def symm (h : α ≃ₜ β) : β ≃ₜ α :=
{ continuous_to_fun := h.continuous_inv_fun,
continuous_inv_fun := h.continuous_to_fun,
to_equiv := h.to_equiv.symm }
/-- See Note [custom simps projection]. We need to specify this projection explicitly in this case,
because it is a composition of multiple projections. -/
def simps.apply (h : α ≃ₜ β) : α → β := h
/-- See Note [custom simps projection] -/
def simps.symm_apply (h : α ≃ₜ β) : β → α := h.symm
initialize_simps_projections homeomorph
(to_equiv_to_fun → apply, to_equiv_inv_fun → symm_apply, -to_equiv)
lemma to_equiv_injective : function.injective (to_equiv : α ≃ₜ β → α ≃ β)
| ⟨e, h₁, h₂⟩ ⟨e', h₁', h₂'⟩ rfl := rfl
@[ext] lemma ext {h h' : α ≃ₜ β} (H : ∀ x, h x = h' x) : h = h' :=
to_equiv_injective $ equiv.ext H
/-- Identity map as a homeomorphism. -/
@[simps apply {fully_applied := ff}]
protected def refl (α : Type*) [topological_space α] : α ≃ₜ α :=
{ continuous_to_fun := continuous_id,
continuous_inv_fun := continuous_id,
to_equiv := equiv.refl α }
/-- Composition of two homeomorphisms. -/
protected def trans (h₁ : α ≃ₜ β) (h₂ : β ≃ₜ γ) : α ≃ₜ γ :=
{ continuous_to_fun := h₂.continuous_to_fun.comp h₁.continuous_to_fun,
continuous_inv_fun := h₁.continuous_inv_fun.comp h₂.continuous_inv_fun,
to_equiv := equiv.trans h₁.to_equiv h₂.to_equiv }
@[simp] lemma homeomorph_mk_coe_symm (a : equiv α β) (b c) :
((homeomorph.mk a b c).symm : β → α) = a.symm :=
rfl
@[simp] lemma refl_symm : (homeomorph.refl α).symm = homeomorph.refl α := rfl
@[continuity]
protected lemma continuous (h : α ≃ₜ β) : continuous h := h.continuous_to_fun
@[continuity] -- otherwise `by continuity` can't prove continuity of `h.to_equiv.symm`
protected lemma continuous_symm (h : α ≃ₜ β) : continuous (h.symm) := h.continuous_inv_fun
@[simp] lemma apply_symm_apply (h : α ≃ₜ β) (x : β) : h (h.symm x) = x :=
h.to_equiv.apply_symm_apply x
@[simp] lemma symm_apply_apply (h : α ≃ₜ β) (x : α) : h.symm (h x) = x :=
h.to_equiv.symm_apply_apply x
protected lemma bijective (h : α ≃ₜ β) : function.bijective h := h.to_equiv.bijective
protected lemma injective (h : α ≃ₜ β) : function.injective h := h.to_equiv.injective
protected lemma surjective (h : α ≃ₜ β) : function.surjective h := h.to_equiv.surjective
/-- Change the homeomorphism `f` to make the inverse function definitionally equal to `g`. -/
def change_inv (f : α ≃ₜ β) (g : β → α) (hg : function.right_inverse g f) : α ≃ₜ β :=
have g = f.symm, from funext (λ x, calc g x = f.symm (f (g x)) : (f.left_inv (g x)).symm
... = f.symm x : by rw hg x),
{ to_fun := f,
inv_fun := g,
left_inv := by convert f.left_inv,
right_inv := by convert f.right_inv,
continuous_to_fun := f.continuous,
continuous_inv_fun := by convert f.symm.continuous }
@[simp] lemma symm_comp_self (h : α ≃ₜ β) : ⇑h.symm ∘ ⇑h = id :=
funext h.symm_apply_apply
@[simp] lemma self_comp_symm (h : α ≃ₜ β) : ⇑h ∘ ⇑h.symm = id :=
funext h.apply_symm_apply
@[simp] lemma range_coe (h : α ≃ₜ β) : range h = univ :=
h.surjective.range_eq
lemma image_symm (h : α ≃ₜ β) : image h.symm = preimage h :=
funext h.symm.to_equiv.image_eq_preimage
lemma preimage_symm (h : α ≃ₜ β) : preimage h.symm = image h :=
(funext h.to_equiv.image_eq_preimage).symm
@[simp] lemma image_preimage (h : α ≃ₜ β) (s : set β) : h '' (h ⁻¹' s) = s :=
h.to_equiv.image_preimage s
@[simp] lemma preimage_image (h : α ≃ₜ β) (s : set α) : h ⁻¹' (h '' s) = s :=
h.to_equiv.preimage_image s
protected lemma inducing (h : α ≃ₜ β) : inducing h :=
inducing_of_inducing_compose h.continuous h.symm.continuous $
by simp only [symm_comp_self, inducing_id]
lemma induced_eq (h : α ≃ₜ β) : topological_space.induced h ‹_› = ‹_› := h.inducing.1.symm
protected lemma quotient_map (h : α ≃ₜ β) : quotient_map h :=
quotient_map.of_quotient_map_compose h.symm.continuous h.continuous $
by simp only [self_comp_symm, quotient_map.id]
lemma coinduced_eq (h : α ≃ₜ β) : topological_space.coinduced h ‹_› = ‹_› :=
h.quotient_map.2.symm
protected lemma embedding (h : α ≃ₜ β) : embedding h :=
⟨h.inducing, h.injective⟩
/-- Homeomorphism given an embedding. -/
noncomputable def of_embedding (f : α → β) (hf : embedding f) : α ≃ₜ (set.range f) :=
{ continuous_to_fun := continuous_subtype_mk _ hf.continuous,
continuous_inv_fun := by simp [hf.continuous_iff, continuous_subtype_coe],
.. equiv.of_injective f hf.inj }
protected lemma second_countable_topology [topological_space.second_countable_topology β]
(h : α ≃ₜ β) :
topological_space.second_countable_topology α :=
h.inducing.second_countable_topology
lemma compact_image {s : set α} (h : α ≃ₜ β) : is_compact (h '' s) ↔ is_compact s :=
h.embedding.is_compact_iff_is_compact_image.symm
lemma compact_preimage {s : set β} (h : α ≃ₜ β) : is_compact (h ⁻¹' s) ↔ is_compact s :=
by rw ← image_symm; exact h.symm.compact_image
protected lemma dense_embedding (h : α ≃ₜ β) : dense_embedding h :=
{ dense := h.surjective.dense_range,
.. h.embedding }
@[simp] lemma is_open_preimage (h : α ≃ₜ β) {s : set β} : is_open (h ⁻¹' s) ↔ is_open s :=
h.quotient_map.is_open_preimage
@[simp] lemma is_open_image (h : α ≃ₜ β) {s : set α} : is_open (h '' s) ↔ is_open s :=
by rw [← preimage_symm, is_open_preimage]
@[simp] lemma is_closed_preimage (h : α ≃ₜ β) {s : set β} : is_closed (h ⁻¹' s) ↔ is_closed s :=
by simp only [← is_open_compl_iff, ← preimage_compl, is_open_preimage]
@[simp] lemma is_closed_image (h : α ≃ₜ β) {s : set α} : is_closed (h '' s) ↔ is_closed s :=
by rw [← preimage_symm, is_closed_preimage]
lemma preimage_closure (h : α ≃ₜ β) (s : set β) : h ⁻¹' (closure s) = closure (h ⁻¹' s) :=
by rw [h.embedding.closure_eq_preimage_closure_image, h.image_preimage]
lemma image_closure (h : α ≃ₜ β) (s : set α) : h '' (closure s) = closure (h '' s) :=
by rw [← preimage_symm, preimage_closure]
protected lemma is_open_map (h : α ≃ₜ β) : is_open_map h := λ s, h.is_open_image.2
protected lemma is_closed_map (h : α ≃ₜ β) : is_closed_map h := λ s, h.is_closed_image.2
protected lemma closed_embedding (h : α ≃ₜ β) : closed_embedding h :=
closed_embedding_of_embedding_closed h.embedding h.is_closed_map
@[simp] lemma map_nhds_eq (h : α ≃ₜ β) (x : α) : map h (𝓝 x) = 𝓝 (h x) :=
h.embedding.map_nhds_of_mem _ (by simp)
lemma symm_map_nhds_eq (h : α ≃ₜ β) (x : α) : map h.symm (𝓝 (h x)) = 𝓝 x :=
by rw [h.symm.map_nhds_eq, h.symm_apply_apply]
lemma nhds_eq_comap (h : α ≃ₜ β) (x : α) : 𝓝 x = comap h (𝓝 (h x)) :=
h.embedding.to_inducing.nhds_eq_comap x
@[simp] lemma comap_nhds_eq (h : α ≃ₜ β) (y : β) : comap h (𝓝 y) = 𝓝 (h.symm y) :=
by rw [h.nhds_eq_comap, h.apply_symm_apply]
/-- If an bijective map `e : α ≃ β` is continuous and open, then it is a homeomorphism. -/
def homeomorph_of_continuous_open (e : α ≃ β) (h₁ : continuous e) (h₂ : is_open_map e) :
α ≃ₜ β :=
{ continuous_to_fun := h₁,
continuous_inv_fun := begin
rw continuous_def,
intros s hs,
convert ← h₂ s hs using 1,
apply e.image_eq_preimage
end,
to_equiv := e }
@[simp] lemma comp_continuous_on_iff (h : α ≃ₜ β) (f : γ → α) (s : set γ) :
continuous_on (h ∘ f) s ↔ continuous_on f s :=
h.inducing.continuous_on_iff.symm
@[simp] lemma comp_continuous_iff (h : α ≃ₜ β) {f : γ → α} :
continuous (h ∘ f) ↔ continuous f :=
h.inducing.continuous_iff.symm
@[simp] lemma comp_continuous_iff' (h : α ≃ₜ β) {f : β → γ} :
continuous (f ∘ h) ↔ continuous f :=
h.quotient_map.continuous_iff.symm
/-- If two sets are equal, then they are homeomorphic. -/
def set_congr {s t : set α} (h : s = t) : s ≃ₜ t :=
{ continuous_to_fun := continuous_subtype_mk _ continuous_subtype_val,
continuous_inv_fun := continuous_subtype_mk _ continuous_subtype_val,
to_equiv := equiv.set_congr h }
/-- Sum of two homeomorphisms. -/
def sum_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α ⊕ γ ≃ₜ β ⊕ δ :=
{ continuous_to_fun :=
begin
convert continuous_sum_rec (continuous_inl.comp h₁.continuous)
(continuous_inr.comp h₂.continuous),
ext x, cases x; refl,
end,
continuous_inv_fun :=
begin
convert continuous_sum_rec (continuous_inl.comp h₁.symm.continuous)
(continuous_inr.comp h₂.symm.continuous),
ext x, cases x; refl
end,
to_equiv := h₁.to_equiv.sum_congr h₂.to_equiv }
/-- Product of two homeomorphisms. -/
def prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α × γ ≃ₜ β × δ :=
{ continuous_to_fun := (h₁.continuous.comp continuous_fst).prod_mk
(h₂.continuous.comp continuous_snd),
continuous_inv_fun := (h₁.symm.continuous.comp continuous_fst).prod_mk
(h₂.symm.continuous.comp continuous_snd),
to_equiv := h₁.to_equiv.prod_congr h₂.to_equiv }
@[simp] lemma prod_congr_symm (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) :
(h₁.prod_congr h₂).symm = h₁.symm.prod_congr h₂.symm := rfl
@[simp] lemma coe_prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) :
⇑(h₁.prod_congr h₂) = prod.map h₁ h₂ := rfl
section
variables (α β γ)
/-- `α × β` is homeomorphic to `β × α`. -/
def prod_comm : α × β ≃ₜ β × α :=
{ continuous_to_fun := continuous_snd.prod_mk continuous_fst,
continuous_inv_fun := continuous_snd.prod_mk continuous_fst,
to_equiv := equiv.prod_comm α β }
@[simp] lemma prod_comm_symm : (prod_comm α β).symm = prod_comm β α := rfl
@[simp] lemma coe_prod_comm : ⇑(prod_comm α β) = prod.swap := rfl
/-- `(α × β) × γ` is homeomorphic to `α × (β × γ)`. -/
def prod_assoc : (α × β) × γ ≃ₜ α × (β × γ) :=
{ continuous_to_fun := (continuous_fst.comp continuous_fst).prod_mk
((continuous_snd.comp continuous_fst).prod_mk continuous_snd),
continuous_inv_fun := (continuous_fst.prod_mk (continuous_fst.comp continuous_snd)).prod_mk
(continuous_snd.comp continuous_snd),
to_equiv := equiv.prod_assoc α β γ }
/-- `α × {*}` is homeomorphic to `α`. -/
@[simps apply {fully_applied := ff}]
def prod_punit : α × punit ≃ₜ α :=
{ to_equiv := equiv.prod_punit α,
continuous_to_fun := continuous_fst,
continuous_inv_fun := continuous_id.prod_mk continuous_const }
/-- `{*} × α` is homeomorphic to `α`. -/
def punit_prod : punit × α ≃ₜ α :=
(prod_comm _ _).trans (prod_punit _)
@[simp] lemma coe_punit_prod : ⇑(punit_prod α) = prod.snd := rfl
end
/-- `ulift α` is homeomorphic to `α`. -/
def {u v} ulift {α : Type u} [topological_space α] : ulift.{v u} α ≃ₜ α :=
{ continuous_to_fun := continuous_ulift_down,
continuous_inv_fun := continuous_ulift_up,
to_equiv := equiv.ulift }
section distrib
/-- `(α ⊕ β) × γ` is homeomorphic to `α × γ ⊕ β × γ`. -/
def sum_prod_distrib : (α ⊕ β) × γ ≃ₜ α × γ ⊕ β × γ :=
begin
refine (homeomorph.homeomorph_of_continuous_open (equiv.sum_prod_distrib α β γ).symm _ _).symm,
{ convert continuous_sum_rec
((continuous_inl.comp continuous_fst).prod_mk continuous_snd)
((continuous_inr.comp continuous_fst).prod_mk continuous_snd),
ext1 x, cases x; refl, },
{ exact (is_open_map_sum
(open_embedding_inl.prod open_embedding_id).is_open_map
(open_embedding_inr.prod open_embedding_id).is_open_map) }
end
/-- `α × (β ⊕ γ)` is homeomorphic to `α × β ⊕ α × γ`. -/
def prod_sum_distrib : α × (β ⊕ γ) ≃ₜ α × β ⊕ α × γ :=
(prod_comm _ _).trans $
sum_prod_distrib.trans $
sum_congr (prod_comm _ _) (prod_comm _ _)
variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)]
/-- `(Σ i, σ i) × β` is homeomorphic to `Σ i, (σ i × β)`. -/
def sigma_prod_distrib : ((Σ i, σ i) × β) ≃ₜ (Σ i, (σ i × β)) :=
homeomorph.symm $
homeomorph_of_continuous_open (equiv.sigma_prod_distrib σ β).symm
(continuous_sigma $ λ i,
(continuous_sigma_mk.comp continuous_fst).prod_mk continuous_snd)
(is_open_map_sigma $ λ i,
(open_embedding_sigma_mk.prod open_embedding_id).is_open_map)
end distrib
/--
A subset of a topological space is homeomorphic to its image under a homeomorphism.
-/
def image (e : α ≃ₜ β) (s : set α) : s ≃ₜ e '' s :=
{ continuous_to_fun := by continuity!,
continuous_inv_fun := by continuity!,
..e.to_equiv.image s, }
end homeomorph
|
90ca1f9bace1efa5870af70adab0a756c2ba6ae4 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/ring_theory/ideal/over_auto.lean | 447f93a4e8e3ce3f623db4340a5a532e8778925e | [] | 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,283 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Anne Baanen
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.ring_theory.algebraic
import Mathlib.ring_theory.localization
import Mathlib.PostPort
universes u_1 u_2
namespace Mathlib
/-!
# Ideals over/under ideals
This file concerns ideals lying over other ideals.
Let `f : R →+* S` be a ring homomorphism (typically a ring extension), `I` an ideal of `R` and
`J` an ideal of `S`. We say `J` lies over `I` (and `I` under `J`) if `I` is the `f`-preimage of `J`.
This is expressed here by writing `I = J.comap f`.
## Implementation notes
The proofs of the `comap_ne_bot` and `comap_lt_comap` families use an approach
specific for their situation: we construct an element in `I.comap f` from the
coefficients of a minimal polynomial.
Once mathlib has more material on the localization at a prime ideal, the results
can be proven using more general going-up/going-down theory.
-/
namespace ideal
theorem coeff_zero_mem_comap_of_root_mem_of_eval_mem {R : Type u_1} [comm_ring R] {S : Type u_2}
[comm_ring S] {f : R →+* S} {I : ideal S} {r : S} (hr : r ∈ I) {p : polynomial R}
(hp : polynomial.eval₂ f r p ∈ I) : polynomial.coeff p 0 ∈ comap f I :=
sorry
theorem coeff_zero_mem_comap_of_root_mem {R : Type u_1} [comm_ring R] {S : Type u_2} [comm_ring S]
{f : R →+* S} {I : ideal S} {r : S} (hr : r ∈ I) {p : polynomial R}
(hp : polynomial.eval₂ f r p = 0) : polynomial.coeff p 0 ∈ comap f I :=
coeff_zero_mem_comap_of_root_mem_of_eval_mem hr (Eq.symm hp ▸ ideal.zero_mem I)
theorem exists_coeff_ne_zero_mem_comap_of_non_zero_divisor_root_mem {R : Type u_1} [comm_ring R]
{S : Type u_2} [comm_ring S] {f : R →+* S} {I : ideal S} {r : S}
(r_non_zero_divisor : ∀ {x : S}, x * r = 0 → x = 0) (hr : r ∈ I) {p : polynomial R}
(p_ne_zero : p ≠ 0) (hp : polynomial.eval₂ f r p = 0) :
∃ (i : ℕ), polynomial.coeff p i ≠ 0 ∧ polynomial.coeff p i ∈ comap f I :=
sorry
theorem exists_coeff_ne_zero_mem_comap_of_root_mem {R : Type u_1} [comm_ring R] {S : Type u_2}
[integral_domain S] {f : R →+* S} {I : ideal S} {r : S} (r_ne_zero : r ≠ 0) (hr : r ∈ I)
{p : polynomial R} (p_ne_zero : p ≠ 0) (hp : polynomial.eval₂ f r p = 0) :
∃ (i : ℕ), polynomial.coeff p i ≠ 0 ∧ polynomial.coeff p i ∈ comap f I :=
exists_coeff_ne_zero_mem_comap_of_non_zero_divisor_root_mem
(fun (_x : S) (h : _x * r = 0) => or.resolve_right (iff.mp mul_eq_zero h) r_ne_zero) hr
theorem exists_coeff_mem_comap_sdiff_comap_of_root_mem_sdiff {R : Type u_1} [comm_ring R]
{S : Type u_2} [integral_domain S] {f : R →+* S} {I : ideal S} {J : ideal S} [is_prime I]
(hIJ : I ≤ J) {r : S} (hr : r ∈ ↑J \ ↑I) {p : polynomial R}
(p_ne_zero : polynomial.map (quotient.mk (comap f I)) p ≠ 0)
(hpI : polynomial.eval₂ f r p ∈ I) :
∃ (i : ℕ), polynomial.coeff p i ∈ ↑(comap f J) \ ↑(comap f I) :=
sorry
theorem comap_ne_bot_of_root_mem {R : Type u_1} [comm_ring R] {S : Type u_2} [integral_domain S]
{f : R →+* S} {I : ideal S} {r : S} (r_ne_zero : r ≠ 0) (hr : r ∈ I) {p : polynomial R}
(p_ne_zero : p ≠ 0) (hp : polynomial.eval₂ f r p = 0) : comap f I ≠ ⊥ :=
sorry
theorem comap_lt_comap_of_root_mem_sdiff {R : Type u_1} [comm_ring R] {S : Type u_2}
[integral_domain S] {f : R →+* S} {I : ideal S} {J : ideal S} [is_prime I] (hIJ : I ≤ J) {r : S}
(hr : r ∈ ↑J \ ↑I) {p : polynomial R}
(p_ne_zero : polynomial.map (quotient.mk (comap f I)) p ≠ 0) (hp : polynomial.eval₂ f r p ∈ I) :
comap f I < comap f J :=
sorry
theorem comap_ne_bot_of_algebraic_mem {R : Type u_1} [comm_ring R] {S : Type u_2}
[integral_domain S] {I : ideal S} [algebra R S] {x : S} (x_ne_zero : x ≠ 0) (x_mem : x ∈ I)
(hx : is_algebraic R x) : comap (algebra_map R S) I ≠ ⊥ :=
sorry
theorem comap_ne_bot_of_integral_mem {R : Type u_1} [comm_ring R] {S : Type u_2} [integral_domain S]
{I : ideal S} [algebra R S] [nontrivial R] {x : S} (x_ne_zero : x ≠ 0) (x_mem : x ∈ I)
(hx : is_integral R x) : comap (algebra_map R S) I ≠ ⊥ :=
comap_ne_bot_of_algebraic_mem x_ne_zero x_mem (is_integral.is_algebraic R hx)
theorem eq_bot_of_comap_eq_bot {R : Type u_1} [comm_ring R] {S : Type u_2} [integral_domain S]
{I : ideal S} [algebra R S] [nontrivial R] (hRS : algebra.is_integral R S)
(hI : comap (algebra_map R S) I = ⊥) : I = ⊥ :=
sorry
theorem mem_of_one_mem {S : Type u_2} [integral_domain S] {I : ideal S} (h : 1 ∈ I) (x : S) :
x ∈ I :=
Eq.symm (iff.mpr (eq_top_iff_one I) h) ▸ submodule.mem_top
theorem comap_lt_comap_of_integral_mem_sdiff {R : Type u_1} [comm_ring R] {S : Type u_2}
[integral_domain S] {I : ideal S} {J : ideal S} [algebra R S] [hI : is_prime I] (hIJ : I ≤ J)
{x : S} (mem : x ∈ ↑J \ ↑I) (integral : is_integral R x) :
comap (algebra_map R S) I < comap (algebra_map R S) J :=
sorry
theorem is_maximal_of_is_integral_of_is_maximal_comap {R : Type u_1} [comm_ring R] {S : Type u_2}
[integral_domain S] [algebra R S] (hRS : algebra.is_integral R S) (I : ideal S) [is_prime I]
(hI : is_maximal (comap (algebra_map R S) I)) : is_maximal I :=
sorry
theorem is_maximal_of_is_integral_of_is_maximal_comap' {R : Type u_1} {S : Type u_2} [comm_ring R]
[integral_domain S] (f : R →+* S) (hf : ring_hom.is_integral f) (I : ideal S) [hI' : is_prime I]
(hI : is_maximal (comap f I)) : is_maximal I :=
is_maximal_of_is_integral_of_is_maximal_comap hf I hI
theorem is_maximal_comap_of_is_integral_of_is_maximal {R : Type u_1} [comm_ring R] {S : Type u_2}
[integral_domain S] [algebra R S] (hRS : algebra.is_integral R S) (I : ideal S)
[hI : is_maximal I] : is_maximal (comap (algebra_map R S) I) :=
sorry
theorem is_maximal_comap_of_is_integral_of_is_maximal' {R : Type u_1} {S : Type u_2} [comm_ring R]
[integral_domain S] (f : R →+* S) (hf : ring_hom.is_integral f) (I : ideal S)
(hI : is_maximal I) : is_maximal (comap f I) :=
is_maximal_comap_of_is_integral_of_is_maximal hf I
theorem integral_closure.comap_ne_bot {R : Type u_1} [comm_ring R] {S : Type u_2}
[integral_domain S] [algebra R S] [nontrivial R] {I : ideal ↥(integral_closure R S)}
(I_ne_bot : I ≠ ⊥) : comap (algebra_map R ↥(integral_closure R S)) I ≠ ⊥ :=
sorry
theorem integral_closure.eq_bot_of_comap_eq_bot {R : Type u_1} [comm_ring R] {S : Type u_2}
[integral_domain S] [algebra R S] [nontrivial R] {I : ideal ↥(integral_closure R S)} :
comap (algebra_map R ↥(integral_closure R S)) I = ⊥ → I = ⊥ :=
imp_of_not_imp_not (comap (algebra_map R ↥(integral_closure R S)) I = ⊥) (I = ⊥)
integral_closure.comap_ne_bot
theorem integral_closure.comap_lt_comap {R : Type u_1} [comm_ring R] {S : Type u_2}
[integral_domain S] [algebra R S] {I : ideal ↥(integral_closure R S)}
{J : ideal ↥(integral_closure R S)} [is_prime I] (I_lt_J : I < J) :
comap (algebra_map R ↥(integral_closure R S)) I <
comap (algebra_map R ↥(integral_closure R S)) J :=
sorry
theorem integral_closure.is_maximal_of_is_maximal_comap {R : Type u_1} [comm_ring R] {S : Type u_2}
[integral_domain S] [algebra R S] (I : ideal ↥(integral_closure R S)) [is_prime I]
(hI : is_maximal (comap (algebra_map R ↥(integral_closure R S)) I)) : is_maximal I :=
is_maximal_of_is_integral_of_is_maximal_comap
(fun (x : ↥(integral_closure R S)) => integral_closure.is_integral x) I hI
/-- `comap (algebra_map R S)` is a surjection from the prime spec of `R` to prime spec of `S`.
`hP : (algebra_map R S).ker ≤ P` is a slight generalization of the extension being injective -/
theorem exists_ideal_over_prime_of_is_integral' {R : Type u_1} [comm_ring R] {S : Type u_2}
[integral_domain S] [algebra R S] (H : algebra.is_integral R S) (P : ideal R) [is_prime P]
(hP : ring_hom.ker (algebra_map R S) ≤ P) :
∃ (Q : ideal S), is_prime Q ∧ comap (algebra_map R S) Q = P :=
sorry
/-- More general going-up theorem than `exists_ideal_over_prime_of_is_integral'`.
TODO: Version of going-up theorem with arbitrary length chains (by induction on this)?
Not sure how best to write an ascending chain in Lean -/
theorem exists_ideal_over_prime_of_is_integral {R : Type u_1} [comm_ring R] {S : Type u_2}
[integral_domain S] [algebra R S] (H : algebra.is_integral R S) (P : ideal R) [is_prime P]
(I : ideal S) [is_prime I] (hIP : comap (algebra_map R S) I ≤ P) :
∃ (Q : ideal S), ∃ (H : Q ≥ I), is_prime Q ∧ comap (algebra_map R S) Q = P :=
sorry
/-- `comap (algebra_map R S)` is a surjection from the max spec of `S` to max spec of `R`.
`hP : (algebra_map R S).ker ≤ P` is a slight generalization of the extension being injective -/
theorem exists_ideal_over_maximal_of_is_integral {R : Type u_1} [comm_ring R] {S : Type u_2}
[integral_domain S] [algebra R S] (H : algebra.is_integral R S) (P : ideal R)
[P_max : is_maximal P] (hP : ring_hom.ker (algebra_map R S) ≤ P) :
∃ (Q : ideal S), is_maximal Q ∧ comap (algebra_map R S) Q = P :=
sorry
end Mathlib |
17f5f2c214f6a579305a4532d2b49a62b79aafc3 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/bitvec/core.lean | 7f0c665168f762962c0676e26d066c2cc1f3bb2f | [
"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 | 8,751 | lean | /-
Copyright (c) 2015 Joe Hendrix. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joe Hendrix, Sebastian Ullrich
-/
import data.vector.basic
import data.nat.pow
/-!
# Basic operations on bitvectors
This is a work-in-progress, and contains additions to other theories.
This file was moved to mathlib from core Lean in the switch to Lean 3.20.0c.
It is not fully in compliance with mathlib style standards.
-/
/-- `bitvec n` is a `vector` of `bool` with length `n`. -/
@[reducible] def bitvec (n : ℕ) := vector bool n
namespace bitvec
open nat
open vector
local infix `++ₜ`:65 := vector.append
/-- Create a zero bitvector -/
@[reducible] protected def zero (n : ℕ) : bitvec n := repeat ff n
/-- Create a bitvector of length `n` whose `n-1`st entry is 1 and other entries are 0. -/
@[reducible] protected def one : Π (n : ℕ), bitvec n
| 0 := nil
| (succ n) := repeat ff n ++ₜ tt::ᵥnil
/-- Create a bitvector from another with a provably equal length. -/
protected def cong {a b : ℕ} (h : a = b) : bitvec a → bitvec b
| ⟨x, p⟩ := ⟨x, h ▸ p⟩
/-- `bitvec` specific version of `vector.append` -/
def append {m n} : bitvec m → bitvec n → bitvec (m + n) := vector.append
/-! ### Shift operations -/
section shift
variable {n : ℕ}
/-- `shl x i` is the bitvector obtained by left-shifting `x` `i` times and padding with `ff`.
If `x.length < i` then this will return the all-`ff`s bitvector. -/
def shl (x : bitvec n) (i : ℕ) : bitvec n :=
bitvec.cong (by simp) $
drop i x ++ₜ repeat ff (min n i)
/-- `fill_shr x i fill` is the bitvector obtained by right-shifting `x` `i` times and then
padding with `fill : bool`. If `x.length < i` then this will return the constant `fill`
bitvector. -/
def fill_shr (x : bitvec n) (i : ℕ) (fill : bool) : bitvec n :=
bitvec.cong
begin
by_cases (i ≤ n),
{ have h₁ := nat.sub_le n i,
rw [min_eq_right h],
rw [min_eq_left h₁, ← add_tsub_assoc_of_le h, nat.add_comm, add_tsub_cancel_right] },
{ have h₁ := le_of_not_ge h,
rw [min_eq_left h₁, tsub_eq_zero_iff_le.mpr h₁, zero_min, nat.add_zero] }
end $
repeat fill (min n i) ++ₜ take (n-i) x
/-- unsigned shift right -/
def ushr (x : bitvec n) (i : ℕ) : bitvec n :=
fill_shr x i ff
/-- signed shift right -/
def sshr : Π {m : ℕ}, bitvec m → ℕ → bitvec m
| 0 _ _ := nil
| (succ m) x i := head x ::ᵥ fill_shr (tail x) i (head x)
end shift
/-! ### Bitwise operations -/
section bitwise
variable {n : ℕ}
/-- bitwise not -/
def not : bitvec n → bitvec n := map bnot
/-- bitwise and -/
def and : bitvec n → bitvec n → bitvec n := map₂ band
/-- bitwise or -/
def or : bitvec n → bitvec n → bitvec n := map₂ bor
/-- bitwise xor -/
def xor : bitvec n → bitvec n → bitvec n := map₂ bxor
end bitwise
/-! ### Arithmetic operators -/
section arith
variable {n : ℕ}
/-- `xor3 x y c` is `((x XOR y) XOR c)`. -/
protected def xor3 (x y c : bool) := bxor (bxor x y) c
/-- `carry x y c` is `x && y || x && c || y && c`. -/
protected def carry (x y c : bool) :=
x && y || x && c || y && c
/-- `neg x` is the two's complement of `x`. -/
protected def neg (x : bitvec n) : bitvec n :=
let f := λ y c, (y || c, bxor y c) in
prod.snd (map_accumr f x ff)
/-- Add with carry (no overflow) -/
def adc (x y : bitvec n) (c : bool) : bitvec (n+1) :=
let f := λ x y c, (bitvec.carry x y c, bitvec.xor3 x y c) in
let ⟨c, z⟩ := vector.map_accumr₂ f x y c in
c ::ᵥ z
/-- The sum of two bitvectors -/
protected def add (x y : bitvec n) : bitvec n := tail (adc x y ff)
/-- Subtract with borrow -/
def sbb (x y : bitvec n) (b : bool) : bool × bitvec n :=
let f := λ x y c, (bitvec.carry (bnot x) y c, bitvec.xor3 x y c) in
vector.map_accumr₂ f x y b
/-- The difference of two bitvectors -/
protected def sub (x y : bitvec n) : bitvec n := prod.snd (sbb x y ff)
instance : has_zero (bitvec n) := ⟨bitvec.zero n⟩
instance : has_one (bitvec n) := ⟨bitvec.one n⟩
instance : has_add (bitvec n) := ⟨bitvec.add⟩
instance : has_sub (bitvec n) := ⟨bitvec.sub⟩
instance : has_neg (bitvec n) := ⟨bitvec.neg⟩
/-- The product of two bitvectors -/
protected def mul (x y : bitvec n) : bitvec n :=
let f := λ r b, cond b (r + r + y) (r + r) in
(to_list x).foldl f 0
instance : has_mul (bitvec n) := ⟨bitvec.mul⟩
end arith
/-! ### Comparison operators -/
section comparison
variable {n : ℕ}
/-- `uborrow x y` returns `tt` iff the "subtract with borrow" operation on `x`, `y` and `ff`
required a borrow. -/
def uborrow (x y : bitvec n) : bool := prod.fst (sbb x y ff)
/-- unsigned less-than proposition -/
def ult (x y : bitvec n) : Prop := uborrow x y
/-- unsigned greater-than proposition -/
def ugt (x y : bitvec n) : Prop := ult y x
/-- unsigned less-than-or-equal-to proposition -/
def ule (x y : bitvec n) : Prop := ¬ (ult y x)
/-- unsigned greater-than-or-equal-to proposition -/
def uge (x y : bitvec n) : Prop := ule y x
/-- `sborrow x y` returns `tt` iff `x < y` as two's complement integers -/
def sborrow : Π {n : ℕ}, bitvec n → bitvec n → bool
| 0 _ _ := ff
| (succ n) x y :=
match (head x, head y) with
| (tt, ff) := tt
| (ff, tt) := ff
| _ := uborrow (tail x) (tail y)
end
/-- signed less-than proposition -/
def slt (x y : bitvec n) : Prop := sborrow x y
/-- signed greater-than proposition -/
def sgt (x y : bitvec n) : Prop := slt y x
/-- signed less-than-or-equal-to proposition -/
def sle (x y : bitvec n) : Prop := ¬ (slt y x)
/-- signed greater-than-or-equal-to proposition -/
def sge (x y : bitvec n) : Prop := sle y x
end comparison
/-! ### Conversion to `nat` and `int` -/
section conversion
variable {α : Type}
/-- Create a bitvector from a `nat` -/
protected def of_nat : Π (n : ℕ), nat → bitvec n
| 0 x := nil
| (succ n) x := of_nat n (x / 2) ++ₜ to_bool (x % 2 = 1) ::ᵥ nil
/-- Create a bitvector in the two's complement representation from an `int` -/
protected def of_int : Π (n : ℕ), int → bitvec (succ n)
| n (int.of_nat m) := ff ::ᵥ bitvec.of_nat n m
| n (int.neg_succ_of_nat m) := tt ::ᵥ not (bitvec.of_nat n m)
/-- `add_lsb r b` is `r + r + 1` if `b` is `tt` and `r + r` otherwise. -/
def add_lsb (r : ℕ) (b : bool) := r + r + cond b 1 0
/-- Given a `list` of `bool`s, return the `nat` they represent as a list of binary digits. -/
def bits_to_nat (v : list bool) : nat :=
v.foldl add_lsb 0
/-- Return the natural number encoded by the input bitvector -/
protected def to_nat {n : nat} (v : bitvec n) : nat :=
bits_to_nat (to_list v)
theorem bits_to_nat_to_list {n : ℕ} (x : bitvec n) :
bitvec.to_nat x = bits_to_nat (vector.to_list x) := rfl
local attribute [simp] nat.add_comm nat.add_assoc nat.add_left_comm nat.mul_comm nat.mul_assoc
local attribute [simp] nat.zero_add nat.add_zero nat.one_mul nat.mul_one nat.zero_mul nat.mul_zero
-- mul_left_comm
theorem to_nat_append {m : ℕ} (xs : bitvec m) (b : bool) :
bitvec.to_nat (xs ++ₜ b::ᵥnil) = bitvec.to_nat xs * 2 + bitvec.to_nat (b::ᵥnil) :=
begin
cases xs with xs P,
simp [bits_to_nat_to_list], clear P,
unfold bits_to_nat list.foldl,
-- generalize the accumulator of foldl
generalize h : 0 = x, conv in (add_lsb x b) { rw ←h }, clear h,
simp,
induction xs with x xs generalizing x,
{ simp, unfold list.foldl add_lsb, simp [nat.mul_succ] },
{ simp, apply xs_ih }
end
theorem bits_to_nat_to_bool (n : ℕ)
: bitvec.to_nat (to_bool (n % 2 = 1) ::ᵥ nil) = n % 2 :=
begin
simp [bits_to_nat_to_list],
unfold bits_to_nat add_lsb list.foldl cond,
simp [cond_to_bool_mod_two],
end
theorem of_nat_succ {k n : ℕ}
: bitvec.of_nat (succ k) n = bitvec.of_nat k (n / 2) ++ₜ to_bool (n % 2 = 1) ::ᵥ nil :=
rfl
theorem to_nat_of_nat {k n : ℕ}
: bitvec.to_nat (bitvec.of_nat k n) = n % 2 ^ k :=
begin
induction k with k ih generalizing n,
{ simp [nat.mod_one], refl },
{ rw [of_nat_succ, to_nat_append, ih, bits_to_nat_to_bool, mod_pow_succ, nat.mul_comm] }
end
/-- Return the integer encoded by the input bitvector -/
protected def to_int : Π {n : nat}, bitvec n → int
| 0 _ := 0
| (succ n) v :=
cond (head v)
(int.neg_succ_of_nat $ bitvec.to_nat $ not $ tail v)
(int.of_nat $ bitvec.to_nat $ tail v)
end conversion
/-! ### Miscellaneous instances -/
private def repr {n : nat} : bitvec n → string
| ⟨bs, p⟩ :=
"0b" ++ (bs.map (λ b : bool, if b then '1' else '0')).as_string
instance (n : nat) : has_repr (bitvec n) :=
⟨repr⟩
end bitvec
instance {n} {x y : bitvec n} : decidable (bitvec.ult x y) := bool.decidable_eq _ _
instance {n} {x y : bitvec n} : decidable (bitvec.ugt x y) := bool.decidable_eq _ _
|
6889263b46bab1c1ed118319dec8c22da3c0308b | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/ring_theory/subsemiring.lean | 21aa757a4b501098edb71b14c1267c7be20311d2 | [
"Apache-2.0"
] | permissive | hikari0108/mathlib | b7ea2b7350497ab1a0b87a09d093ecc025a50dfa | a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901 | refs/heads/master | 1,690,483,608,260 | 1,631,541,580,000 | 1,631,541,580,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 33,558 | 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.ring.prod
import group_theory.submonoid
import group_theory.submonoid.center
import data.equiv.ring
/-!
# 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
variables {R : Type u} {S : Type v} {T : Type w}
[non_assoc_semiring R] [non_assoc_semiring S] [non_assoc_semiring T]
(M : submonoid R)
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 :=
⟨subsemiring.carrier, λ p q h, by cases p; cases q; congr'⟩
@[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 }
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. -/
theorem one_mem : (1 : R) ∈ s := s.one_mem'
/-- A subsemiring contains the semiring's 0. -/
theorem zero_mem : (0 : R) ∈ s := s.zero_mem'
/-- A subsemiring is closed under multiplication. -/
theorem mul_mem : ∀ {x y : R}, x ∈ s → y ∈ s → x * y ∈ s := s.mul_mem'
/-- A subsemiring is closed under addition. -/
theorem add_mem : ∀ {x y : R}, x ∈ s → y ∈ s → x + y ∈ s := 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 :=
s.to_submonoid.list_prod_mem
/-- Sum of a list of elements in a `subsemiring` is in the `subsemiring`. -/
lemma list_sum_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.sum ∈ s :=
s.to_add_submonoid.list_sum_mem
/-- Product of a multiset of elements in a `subsemiring` of a `comm_semiring`
is in the `subsemiring`. -/
lemma multiset_prod_mem {R} [comm_semiring R] (s : subsemiring R) (m : multiset R) :
(∀a ∈ m, a ∈ s) → m.prod ∈ s :=
s.to_submonoid.multiset_prod_mem m
/-- Sum of a multiset of elements in a `subsemiring` of a `semiring` is
in the `add_subsemiring`. -/
lemma multiset_sum_mem (m : multiset R) :
(∀a ∈ m, a ∈ s) → m.sum ∈ s :=
s.to_add_submonoid.multiset_sum_mem m
/-- Product of elements of a subsemiring of a `comm_semiring` indexed by a `finset` is in the
subsemiring. -/
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 :=
s.to_submonoid.prod_mem h
/-- Sum of elements in an `subsemiring` of an `semiring` indexed by a `finset`
is in the `add_subsemiring`. -/
lemma sum_mem (s : subsemiring R)
{ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) :
∑ i in t, f i ∈ s :=
s.to_add_submonoid.sum_mem h
lemma pow_mem {R : Type*} [semiring R] (s : subsemiring R) {x : R} (hx : x ∈ s) (n : ℕ) :
x^n ∈ s := s.to_submonoid.pow_mem hx n
lemma nsmul_mem {x : R} (hx : x ∈ s) (n : ℕ) :
n • x ∈ s := s.to_add_submonoid.nsmul_mem hx n
lemma coe_nat_mem (n : ℕ) : (n : R) ∈ s :=
by simp only [← nsmul_one, nsmul_mem, one_mem]
/-- 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,
.. 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)
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)
/-- 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)
/-- 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)
/-! Note: currently, there is no `linear_ordered_comm_semiring`. -/
@[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_bInter_iff
@[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 ▸ s.coe_nat_mem 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
/-- 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
@[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
/-- 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
/-- 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, M.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, H1, Hmul, H0, Hadd⟩).2 Hs h
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 : set R).prod 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 : set R).prod (t : set S) :=
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}
open subsemiring
/-- Restriction of a ring homomorphism to a subsemiring of the domain. -/
def srestrict (f : R →+* S) (s : subsemiring R) : s →+* S := f.comp s.subtype
@[simp] lemma srestrict_apply (f : R →+* S) (x : s) : f.srestrict s x = f x := rfl
/-- Restriction of a ring homomorphism to a subsemiring of the codomain. -/
def cod_srestrict (f : R →+* S) (s : subsemiring S) (h : ∀ x, f x ∈ s) : R →+* s :=
{ to_fun := λ n, ⟨f n, h n⟩,
.. (f : R →* S).cod_mrestrict s.to_submonoid h,
.. (f : R →+ S).cod_mrestrict s.to_add_submonoid 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_srestrict 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_srestrict _ (λ 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
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*} [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
lemma smul_def [mul_action R' α] {S : subsemiring R'} (g : S) (m : α) : g • m = (g : R') • m := rfl
instance smul_comm_class_left
[mul_action R' β] [has_scalar α β] [smul_comm_class R' α β] (S : subsemiring R') :
smul_comm_class S α β :=
S.to_submonoid.smul_comm_class_left
instance smul_comm_class_right
[has_scalar α β] [mul_action 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_scalar α β] [mul_action R' α] [mul_action R' β] [is_scalar_tower R' α β]
(S : subsemiring R') :
is_scalar_tower S α β :=
S.to_submonoid.is_scalar_tower
instance [mul_action R' α] [has_faithful_scalar R' α] (S : subsemiring R') :
has_faithful_scalar S α :=
S.to_submonoid.has_faithful_scalar
/-- 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 [add_comm_monoid α] [module R' α] (S : subsemiring R') : module S α :=
{ smul := (•), .. module.comp_hom _ S.subtype }
end subsemiring
end actions
|
731b1bccef2d90e7257119669a31d8acd248a924 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/topology/metric_space/completion.lean | 29c31422613e8487ddc061e2fa024f66cb7b1497 | [
"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 | 8,116 | 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.uniform_space.completion
import topology.metric_space.isometry
import topology.instances.real
/-!
# The completion of a metric space
Completion of uniform spaces are already defined in `topology.uniform_space.completion`. We show
here that the uniform space completion of a metric space inherits a metric space structure,
by extending the distance to the completion and checking that it is indeed a distance, and that
it defines the same uniformity as the already defined uniform structure on the completion
-/
open set filter uniform_space metric
open_locale filter topological_space uniformity
noncomputable theory
universes u v
variables {α : Type u} {β : Type v} [pseudo_metric_space α]
namespace uniform_space.completion
/-- The distance on the completion is obtained by extending the distance on the original space,
by uniform continuity. -/
instance : has_dist (completion α) :=
⟨completion.extension₂ dist⟩
/-- The new distance is uniformly continuous. -/
protected lemma uniform_continuous_dist :
uniform_continuous (λp:completion α × completion α, dist p.1 p.2) :=
uniform_continuous_extension₂ dist
/-- The new distance is continuous. -/
protected lemma continuous_dist [topological_space β] {f g : β → completion α} (hf : continuous f)
(hg : continuous g) :
continuous (λ x, dist (f x) (g x)) :=
completion.uniform_continuous_dist.continuous.comp (hf.prod_mk hg : _)
/-- The new distance is an extension of the original distance. -/
@[simp] protected lemma dist_eq (x y : α) : dist (x : completion α) y = dist x y :=
completion.extension₂_coe_coe uniform_continuous_dist _ _
/- Let us check that the new distance satisfies the axioms of a distance, by starting from the
properties on α and extending them to `completion α` by continuity. -/
protected lemma dist_self (x : completion α) : dist x x = 0 :=
begin
apply induction_on x,
{ refine is_closed_eq _ continuous_const,
exact completion.continuous_dist continuous_id continuous_id },
{ assume a,
rw [completion.dist_eq, dist_self] }
end
protected lemma dist_comm (x y : completion α) : dist x y = dist y x :=
begin
apply induction_on₂ x y,
{ exact is_closed_eq (completion.continuous_dist continuous_fst continuous_snd)
(completion.continuous_dist continuous_snd continuous_fst) },
{ assume a b,
rw [completion.dist_eq, completion.dist_eq, dist_comm] }
end
protected lemma dist_triangle (x y z : completion α) : dist x z ≤ dist x y + dist y z :=
begin
apply induction_on₃ x y z,
{ refine is_closed_le _ (continuous.add _ _);
apply_rules [completion.continuous_dist, continuous.fst, continuous.snd, continuous_id] },
{ assume a b c,
rw [completion.dist_eq, completion.dist_eq, completion.dist_eq],
exact dist_triangle a b c }
end
/-- Elements of the uniformity (defined generally for completions) can be characterized in terms
of the distance. -/
protected lemma mem_uniformity_dist (s : set (completion α × completion α)) :
s ∈ 𝓤 (completion α) ↔ (∃ε>0, ∀{a b}, dist a b < ε → (a, b) ∈ s) :=
begin
split,
{ /- Start from an entourage `s`. It contains a closed entourage `t`. Its pullback in `α` is an
entourage, so it contains an `ε`-neighborhood of the diagonal by definition of the entourages
in metric spaces. Then `t` contains an `ε`-neighborhood of the diagonal in `completion α`, as
closed properties pass to the completion. -/
assume hs,
rcases mem_uniformity_is_closed hs with ⟨t, ht, ⟨tclosed, ts⟩⟩,
have A : {x : α × α | (coe (x.1), coe (x.2)) ∈ t} ∈ uniformity α :=
uniform_continuous_def.1 (uniform_continuous_coe α) t ht,
rcases mem_uniformity_dist.1 A with ⟨ε, εpos, hε⟩,
refine ⟨ε, εpos, λx y hxy, _⟩,
have : ε ≤ dist x y ∨ (x, y) ∈ t,
{ apply induction_on₂ x y,
{ have : {x : completion α × completion α | ε ≤ dist (x.fst) (x.snd) ∨ (x.fst, x.snd) ∈ t}
= {p : completion α × completion α | ε ≤ dist p.1 p.2} ∪ t, by ext; simp,
rw this,
apply is_closed.union _ tclosed,
exact is_closed_le continuous_const completion.uniform_continuous_dist.continuous },
{ assume x y,
rw completion.dist_eq,
by_cases h : ε ≤ dist x y,
{ exact or.inl h },
{ have Z := hε (not_le.1 h),
simp only [set.mem_set_of_eq] at Z,
exact or.inr Z }}},
simp only [not_le.mpr hxy, false_or, not_le] at this,
exact ts this },
{ /- Start from a set `s` containing an ε-neighborhood of the diagonal in `completion α`. To show
that it is an entourage, we use the fact that `dist` is uniformly continuous on
`completion α × completion α` (this is a general property of the extension of uniformly
continuous functions). Therefore, the preimage of the ε-neighborhood of the diagonal in ℝ
is an entourage in `completion α × completion α`. Massaging this property, it follows that
the ε-neighborhood of the diagonal is an entourage in `completion α`, and therefore this is
also the case of `s`. -/
rintros ⟨ε, εpos, hε⟩,
let r : set (ℝ × ℝ) := {p | dist p.1 p.2 < ε},
have : r ∈ uniformity ℝ := metric.dist_mem_uniformity εpos,
have T := uniform_continuous_def.1 (@completion.uniform_continuous_dist α _) r this,
simp only [uniformity_prod_eq_prod, mem_prod_iff, exists_prop,
filter.mem_map, set.mem_set_of_eq] at T,
rcases T with ⟨t1, ht1, t2, ht2, ht⟩,
refine mem_of_superset ht1 _,
have A : ∀a b : completion α, (a, b) ∈ t1 → dist a b < ε,
{ assume a b hab,
have : ((a, b), (a, a)) ∈ t1 ×ˢ t2 := ⟨hab, refl_mem_uniformity ht2⟩,
have I := ht this,
simp [completion.dist_self, real.dist_eq, completion.dist_comm] at I,
exact lt_of_le_of_lt (le_abs_self _) I },
show t1 ⊆ s,
{ rintros ⟨a, b⟩ hp,
have : dist a b < ε := A a b hp,
exact hε this }}
end
/-- If two points are at distance 0, then they coincide. -/
protected lemma eq_of_dist_eq_zero (x y : completion α) (h : dist x y = 0) : x = y :=
begin
/- This follows from the separation of `completion α` and from the description of
entourages in terms of the distance. -/
have : separated_space (completion α) := by apply_instance,
refine separated_def.1 this x y (λs hs, _),
rcases (completion.mem_uniformity_dist s).1 hs with ⟨ε, εpos, hε⟩,
rw ← h at εpos,
exact hε εpos
end
/-- Reformulate `completion.mem_uniformity_dist` in terms that are suitable for the definition
of the metric space structure. -/
protected lemma uniformity_dist' :
𝓤 (completion α) = (⨅ε:{ε : ℝ // 0 < ε}, 𝓟 {p | dist p.1 p.2 < ε.val}) :=
begin
ext s, rw mem_infi_of_directed,
{ simp [completion.mem_uniformity_dist, subset_def] },
{ rintro ⟨r, hr⟩ ⟨p, hp⟩, use ⟨min r p, lt_min hr hp⟩,
simp [lt_min_iff, (≥)] {contextual := tt} }
end
protected lemma uniformity_dist :
𝓤 (completion α) = (⨅ ε>0, 𝓟 {p | dist p.1 p.2 < ε}) :=
by simpa [infi_subtype] using @completion.uniformity_dist' α _
/-- Metric space structure on the completion of a pseudo_metric space. -/
instance : metric_space (completion α) :=
{ dist_self := completion.dist_self,
eq_of_dist_eq_zero := completion.eq_of_dist_eq_zero,
dist_comm := completion.dist_comm,
dist_triangle := completion.dist_triangle,
dist := dist,
to_uniform_space := by apply_instance,
uniformity_dist := completion.uniformity_dist }
/-- The embedding of a metric space in its completion is an isometry. -/
lemma coe_isometry : isometry (coe : α → completion α) :=
isometry.of_dist_eq completion.dist_eq
@[simp] protected lemma edist_eq (x y : α) : edist (x : completion α) y = edist x y :=
coe_isometry x y
end uniform_space.completion
|
d9c7f3b105b2f17d44e03410c9fcb4a5331bc319 | a4673261e60b025e2c8c825dfa4ab9108246c32e | /tests/lean/run/newfrontend1.lean | 03cbf8701be0d22e724a05d6a175dc35bab1a09a | [
"Apache-2.0"
] | permissive | jcommelin/lean4 | c02dec0cc32c4bccab009285475f265f17d73228 | 2909313475588cc20ac0436e55548a4502050d0a | refs/heads/master | 1,674,129,550,893 | 1,606,415,348,000 | 1,606,415,348,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,077 | lean | def x := 1
#check x
variables {α : Type}
def f (a : α) : α :=
a
def tst (xs : List Nat) : Nat :=
xs.foldl (init := 10) (· + ·)
#check tst [1, 2, 3]
#check fun x y : Nat => x + y
#check tst
#check (fun stx => if True then let e := stx; Pure.pure e else Pure.pure stx : Nat → Id Nat)
#check let x : Nat := 1; x
def foo (a : Nat) (b : Nat := 10) (c : Bool := Bool.true) : Nat :=
a + b
set_option pp.all true
#check foo 1
#check foo 3 (c := false)
def Nat.boo (a : Nat) :=
succ a -- succ here is resolved as `Nat.succ`.
#check Nat.boo
#check true
-- apply is still a valid identifier name
def apply := "hello"
#check apply
theorem simple1 (x y : Nat) (h : x = y) : x = y :=
by {
assumption
}
theorem simple2 (x y : Nat) : x = y → x = y :=
by {
intro h;
assumption
}
syntax "intro2" : tactic
macro_rules
| `(tactic| intro2) => `(tactic| intro; intro )
theorem simple3 (x y : Nat) : x = x → x = y → x = y :=
by {
intro2;
assumption
}
macro intro3 : tactic => `(intro; intro; intro)
macro check2 x:term : command => `(#check $x #check $x)
macro foo x:term "," y:term : term => `($x + $y + $x)
set_option pp.all false
check2 0+1
check2 foo 0,1
theorem simple4 (x y : Nat) : y = y → x = x → x = y → x = y :=
by {
intro3;
assumption
}
theorem simple5 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by {
intro h1; intro _; intro h3;
exact Eq.trans h3 h1
}
theorem simple6 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by {
intro h1; intro _; intro h3;
refine Eq.trans ?_ h1;
assumption
}
theorem simple7 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by {
intro h1; intro _; intro h3;
refine! Eq.trans ?pre ?post;
exact y;
{ exact h3 }
{ exact h1 }
}
theorem simple8 (x y z : Nat) : y = z → x = x → x = y → x = z := by
intro h1; intro _; intro h3
refine! Eq.trans ?pre ?post
case post => exact h1
case pre => exact h3
theorem simple9 (x y z : Nat) : y = z → x = x → x = y → x = z := by
intros h1 _ h3
traceState
focus
refine! Eq.trans ?pre ?post
(exact h1) <|> (exact y; exact h3; assumption)
namespace Foo
def Prod.mk := 1
#check (⟨2, 3⟩ : Prod _ _)
end Foo
theorem simple10 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by {
intro h1; intro h2; intro h3;
skip;
apply Eq.trans;
exact h3;
assumption
}
theorem simple11 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by {
intro h1; intro h2; intro h3;
apply @Eq.trans;
traceState;
exact h3;
assumption
}
theorem simple12 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by {
intro h1; intro h2; intro h3;
apply @Eq.trans;
try exact h1; -- `exact h1` fails
traceState;
try exact h3;
traceState;
try exact h1;
}
theorem simple13 (x y z : Nat) : y = z → x = x → x = y → x = z := by
intros h1 h2 h3
traceState
apply @Eq.trans
case b => exact y
traceState
repeat assumption
theorem simple13b (x y z : Nat) : y = z → x = x → x = y → x = z := by {
intros h1 h2 h3;
traceState;
apply @Eq.trans;
case b => exact y;
traceState;
repeat assumption
}
theorem simple14 (x y z : Nat) : y = z → x = x → x = y → x = z := by
intros
apply @Eq.trans
case b => exact y
repeat assumption
theorem simple15 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by {
intros h1 h2 h3;
revert y;
intros y h1 h3;
apply Eq.trans;
exact h3;
exact h1
}
theorem simple16 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by {
intros h1 h2 h3;
try clear x; -- should fail
clear h2;
traceState;
apply Eq.trans;
exact h3;
exact h1
}
macro "blabla" : tactic => `(assumption)
-- Tactic head symbols do not become reserved words
def blabla := 100
#check blabla
theorem simple17 (x : Nat) (h : x = 0) : x = 0 :=
by blabla
theorem simple18 (x : Nat) (h : x = 0) : x = 0 :=
by blabla
theorem simple19 (x y : Nat) (h₁ : x = 0) (h₂ : x = y) : y = 0 :=
by subst x; subst y; exact rfl
theorem tstprec1 (x y z : Nat) : x + y * z = x + (y * z) :=
rfl
theorem tstprec2 (x y z : Nat) : y * z + x = (y * z) + x :=
rfl
set_option pp.all true
#check fun {α} (a : α) => a
#check @(fun α (a : α) => a)
#check
let myid := fun {α} (a : α) => a;
myid [myid 1]
-- In the following example, we need `@` otherwise we will try to insert mvars for α and [Add α],
-- and will fail to generate instance for [Add α]
#check @(fun α (s : Add α) (a : α) => a + a)
def g1 {α} (a₁ a₂ : α) {β} (b : β) : α × α × β :=
(a₁, a₂, b)
def id1 : {α : Type} → α → α :=
fun x => x
def listId : List ({α : Type} → α → α) :=
(fun x => x) :: []
def id2 : {α : Type} → α → α :=
@(fun α (x : α) => id1 x)
def id3 : {α : Type} → α → α :=
@(fun α x => id1 x)
def id4 : {α : Type} → α → α :=
fun x => id1 x
def id5 : {α : Type} → α → α :=
fun {α} x => id1 x
def id6 : {α : Type} → α → α :=
@(fun {α} x => id1 x)
def id7 : {α : Type} → α → α :=
fun {α} x => @id α x
def id8 : {α : Type} → α → α :=
fun {α} x => id (@id α x)
def altTst1 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) :=
⟨StateT.failure, StateT.orElse⟩
def altTst2 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) :=
⟨@(fun α => StateT.failure), @(fun α => StateT.orElse)⟩
def altTst3 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) :=
⟨fun {α} => StateT.failure, fun {α} => StateT.orElse⟩
#check_failure 1 + true
/-
universes u v
/-
MonadFunctorT.{u ?M_1 v} (λ (β : Type u), m α) (λ (β : Type u), m' α) n n'
-/
set_option syntaxMaxDepth 100
set_option trace.Elab true
def adapt {m m' σ σ'} {n n' : Type → Type} [MonadFunctor m m' n n'] [MonadStateAdapter σ σ' m m'] : MonadStateAdapter σ σ' n n' :=
⟨fun split join => monadMap (adaptState split join : m α → m' α)⟩
-/
syntax "fn" (term:max)+ "=>" term : term
macro_rules
| `(fn $xs* => $b) => `(fun $xs* => $b)
set_option pp.all false
#check fn x => x+1
#check fn α (a : α) => a
def tst1 : {α : Type} → α → α :=
@(fn α a => a)
#check @tst1
syntax ident "==>" term : term
syntax "{" ident "}" "==>" term : term
macro_rules
| `($x:ident ==> $b) => `(fn $x => $b)
| `({$x:ident} ==> $b) => `(fun {$x:ident} => $b)
#check x ==> x+1
def tst2a : {α : Type} → α → α :=
@(α ==> a ==> a)
def tst2b : {α : Type} → α → α :=
{α} ==> a ==> a
#check @tst2a
#check @tst2b
def tst3a : {α : Type} → {β : Type} → α → β → α × β :=
@(α ==> @(β ==> a ==> b ==> (a, b)))
def tst3b : {α : Type} → {β : Type} → α → β → α × β :=
{α} ==> {β} ==> a ==> b ==> (a, b)
syntax "function" (term:max)+ "=>" term : term
macro_rules
| `(function $xs* => $b) => `(@(fun $xs* => $b))
def tst4 : {α : Type} → {β : Type} → α → β → α × β :=
function α β a b => (a, b)
theorem simple20 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by intros h1 h2 h3;
try clear x; -- should fail
clear h2;
traceState;
apply Eq.trans;
exact h3;
exact h1
theorem simple21 (x y z : Nat) : y = z → x = x → y = x → x = z :=
fun h1 _ h3 =>
have x = y from by { apply Eq.symm; assumption };
Eq.trans this (by assumption)
theorem simple22 (x y z : Nat) : y = z → y = x → id (x = z + 0) :=
fun h1 h2 => show x = z + 0 by
apply Eq.trans
exact h2.symm
assumption
skip
theorem simple23 (x y z : Nat) : y = z → x = x → y = x → x = z :=
fun h1 _ h3 =>
have x = y by apply Eq.symm; assumption
Eq.trans this (by assumption)
theorem simple24 (x y z : Nat) : y = z → x = x → y = x → x = z :=
fun h1 _ h3 =>
have h : x = y by apply Eq.symm; assumption
Eq.trans h (by assumption)
def f1 (x : Nat) : Nat :=
let double x := x + x
let rec loop x :=
match x with
| 0 => 0
| x+1 => loop x + double x
loop x
#eval f1 5
def f2 (x : Nat) : String :=
let bad x : String := toString x
bad x
def f3 x y :=
x + y + 1
theorem f3eq x y : f3 x y = x + y + 1 :=
rfl
def f4 x y : String :=
if x > y + 1 then "hello" else "world"
|
b2dd74a8a90feb7985ee52b8869470af8989ad9f | 54deab7025df5d2df4573383df7e1e5497b7a2c2 | /order/galois_connection.lean | 64114988e032f6eaa8faa1558a27efaabd97c616 | [
"Apache-2.0"
] | permissive | HGldJ1966/mathlib | f8daac93a5b4ae805cfb0ecebac21a9ce9469009 | c5c5b504b918a6c5e91e372ee29ed754b0513e85 | refs/heads/master | 1,611,340,395,683 | 1,503,040,489,000 | 1,503,040,489,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,709 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl
Galois connections - order theoretic adjoints.
-/
import order data.set
open function set lattice
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a a₁ a₂ : α} {b b₁ b₂ : β}
def galois_connection [preorder α] [preorder β] (l : α → β) (u : β → α) := ∀a b, l a ≤ b ↔ a ≤ u b
namespace galois_connection
section
variables [preorder α] [preorder β] {l : α → β} {u : β → α} (gc : galois_connection l u)
lemma monotone_intro (hu : monotone u) (hl : monotone l)
(hul : increasing (u ∘ l)) (hlu : decreasing (l ∘ u)) : galois_connection l u :=
assume a b, ⟨assume h, le_trans (hul _) (hu h), assume h, le_trans (hl h) (hlu _)⟩
include gc
lemma l_le {a : α} {b : β} : a ≤ u b → l a ≤ b :=
(gc _ _).mpr
lemma le_u {a : α} {b : β} : l a ≤ b → a ≤ u b :=
(gc _ _).mp
lemma increasing_u_l : increasing (u ∘ l) :=
assume a, gc.le_u $ le_refl _
lemma decreasing_l_u : decreasing (l ∘ u) :=
assume a, gc.l_le $ le_refl _
lemma monotone_u : monotone u :=
assume a b H, gc.le_u (le_trans (gc.decreasing_l_u a) H)
lemma monotone_l : monotone l :=
assume a b H, gc.l_le (le_trans H (gc.increasing_u_l b))
lemma upper_bounds_l_image_subset {s : set α} : upper_bounds (l '' s) ⊆ u ⁻¹' upper_bounds s :=
assume b hb c, assume : c ∈ s, gc.le_u (hb _ (mem_image_of_mem _ ‹c ∈ s›))
lemma lower_bounds_u_image_subset {s : set β} : lower_bounds (u '' s) ⊆ l ⁻¹' lower_bounds s :=
assume a ha c, assume : c ∈ s, gc.l_le (ha _ (mem_image_of_mem _ ‹c ∈ s›))
lemma is_lub_l_image {s : set α} {a : α} (h : is_lub s a) : is_lub (l '' s) (l a) :=
⟨mem_upper_bounds_image gc.monotone_l $ and.elim_left ‹is_lub s a›,
assume b hb, gc.l_le $ and.elim_right ‹is_lub s a› _ $ gc.upper_bounds_l_image_subset hb⟩
lemma is_glb_u_image {s : set β} {b : β} (h : is_glb s b) : is_glb (u '' s) (u b) :=
⟨mem_lower_bounds_image gc.monotone_u $ and.elim_left ‹is_glb s b›,
assume a ha, gc.le_u $ and.elim_right ‹is_glb s b› _ $ gc.lower_bounds_u_image_subset ha⟩
lemma is_glb_l {a : α} : is_glb { b | a ≤ u b } (l a) :=
⟨assume b, gc.l_le, assume b h, h _ $ gc.increasing_u_l _⟩
lemma is_lub_u {b : β} : is_lub { a | l a ≤ b } (u b) :=
⟨assume b, gc.le_u, assume b h, h _ $ gc.decreasing_l_u _⟩
end
section partial_order
variables [partial_order α] [partial_order β] {l : α → β} {u : β → α} (gc : galois_connection l u)
include gc
lemma u_l_u_eq_u : u ∘ l ∘ u = u :=
funext (assume x, le_antisymm (gc.monotone_u (gc.decreasing_l_u _)) (gc.increasing_u_l _))
lemma l_u_l_eq_l : l ∘ u ∘ l = l :=
funext (assume x, le_antisymm (gc.decreasing_l_u _) (gc.monotone_l (gc.increasing_u_l _)))
end partial_order
section order_top
variables [order_top α] [order_top β] {l : α → β} {u : β → α} (gc : galois_connection l u)
include gc
lemma u_top : u ⊤ = ⊤ :=
eq_of_is_glb_of_is_glb (gc.is_glb_u_image is_glb_empty) $ by simp [is_glb_empty, image_empty]
end order_top
section order_bot
variables [order_bot α] [order_bot β] {l : α → β} {u : β → α} (gc : galois_connection l u)
include gc
lemma l_bot : l ⊥ = ⊥ :=
eq_of_is_lub_of_is_lub (gc.is_lub_l_image is_lub_empty) $ by simp [is_lub_empty, image_empty]
end order_bot
section semilattice_sup
variables [semilattice_sup α] [semilattice_sup β] {l : α → β} {u : β → α} (gc : galois_connection l u)
include gc
lemma l_sup : l (a₁ ⊔ a₂) = l a₁ ⊔ l a₂ :=
have {l a₂, l a₁} = l '' {a₂, a₁}, by simp [image_insert_eq, image_singleton],
eq.symm $ is_lub_iff_sup_eq.mp $
by rw [this]; exact gc.is_lub_l_image (is_lub_insert_sup is_lub_singleton)
end semilattice_sup
section semilattice_inf
variables [semilattice_inf α] [semilattice_inf β] {l : α → β} {u : β → α} (gc : galois_connection l u)
include gc
lemma u_inf : u (b₁ ⊓ b₂) = u b₁ ⊓ u b₂ :=
have {u b₂, u b₁} = u '' {b₂, b₁}, by simp [image_insert_eq, image_singleton],
eq.symm $ is_glb_iff_inf_eq.mp $
by rw [this]; exact gc.is_glb_u_image (is_glb_insert_inf is_glb_singleton)
end semilattice_inf
section complete_lattice
variables [complete_lattice α] [complete_lattice β] {l : α → β} {u : β → α} (gc : galois_connection l u)
include gc
lemma l_supr {f : ι → α} : l (supr f) = (⨆i, l (f i)) :=
eq.symm $ is_lub_iff_supr_eq.mp $ show is_lub (range (l ∘ f)) (l (supr f)),
by rw [range_compose, ←Sup_range]; exact gc.is_lub_l_image is_lub_Sup
lemma u_infi {f : ι → β} : u (infi f) = (⨅i, u (f i)) :=
eq.symm $ is_glb_iff_infi_eq.mp $ show is_glb (range (u ∘ f)) (u (infi f)),
by rw [range_compose, ←Inf_range]; exact gc.is_glb_u_image is_glb_Inf
end complete_lattice
/- Constructing Galois connections -/
section constructions
protected lemma id [pα : preorder α] : @galois_connection α α pα pα id id :=
assume a b, iff.intro (λx, x) (λx, x)
protected lemma compose [preorder α] [preorder β] [preorder γ]
(l1 : α → β) (u1 : β → α) (l2 : β → γ) (u2 : γ → β)
(gc1 : galois_connection l1 u1) (gc2 : galois_connection l2 u2) :
galois_connection (l2 ∘ l1) (u1 ∘ u2) :=
by intros a b; rewrite gc2; rewrite gc1
protected lemma dual [pα : preorder α] [pβ : preorder β]
(l : α → β) (u : β → α) (gc : galois_connection l u) :
@galois_connection β α (preorder_dual pβ) (preorder_dual pα) u l :=
assume a b, (gc _ _).symm
protected lemma dfun {ι : Type u} {α : ι → Type v} {β : ι → Type w}
[∀i, preorder (α i)] [∀i, preorder (β i)]
(l : Πi, α i → β i) (u : Πi, β i → α i) (gc : ∀i, galois_connection (l i) (u i)) :
@galois_connection (Π i, α i) (Π i, β i) _ _ (λa i, l i (a i)) (λb i, u i (b i)) :=
assume a b, forall_congr $ assume i, gc i (a i) (b i)
end constructions
end galois_connection
namespace set
variables {f : α → β}
protected lemma image_preimage : galois_connection (image f) (preimage f) :=
assume a b, image_subset_iff_subset_preimage
/- Move to set? -/
definition kern_image (f : α → β) (s : set α) : set β := {y | ∀x, f x = y → x ∈ s }
protected lemma preimage_kern_image : galois_connection (preimage f) (kern_image f) :=
assume a b,
⟨ assume h x hx y hy, have f y ∈ a, from hy.symm ▸ hx, h this,
assume h x (hx : f x ∈ a), h hx x rfl⟩
end set
namespace nat
lemma galois_connection_mul_div {k : ℕ} (h : k > 0) : galois_connection (λn, n * k) (λn, n / k) :=
assume x y, (le_div_iff_mul_le x y h).symm
end nat
|
2d1a1656ba69214d444493e8ecc2aad5f256f1c2 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/e16.lean | b9979b5bca124cd238ad5b288293760c1a045d1b | [
"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 | 678 | lean | prelude
inductive nat : Type :=
| zero : nat
| succ : nat → nat
namespace nat end nat open nat
inductive list (A : Type) : Type :=
| nil {} : list A
| cons : A → list A → list A
namespace list end list open list
check nil
check nil.{1}
check @nil.{1} nat
check @nil nat
check cons zero nil
inductive vector (A : Type) : nat → Type :=
| vnil {} : vector A zero
| vcons : forall {n : nat}, A → vector A n → vector A (succ n)
namespace vector end vector open vector
check vcons zero vnil
constant n : nat
check vcons n vnil
check vector.rec
definition vector_to_list {A : Type} {n : nat} (v : vector A n) : list A
:= vector.rec nil (fun n a v l, cons a l) v
|
8563edcc12a69c05263c96a90b04f3f9d87a15ab | 957a80ea22c5abb4f4670b250d55534d9db99108 | /tests/lean/run/pathsimp.lean | ff0d60df4223c608efb114777076dd0eabf56379 | [
"Apache-2.0"
] | permissive | GaloisInc/lean | aa1e64d604051e602fcf4610061314b9a37ab8cd | f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0 | refs/heads/master | 1,592,202,909,807 | 1,504,624,387,000 | 1,504,624,387,000 | 75,319,626 | 2 | 1 | Apache-2.0 | 1,539,290,164,000 | 1,480,616,104,000 | C++ | UTF-8 | Lean | false | false | 1,268 | lean | universes u v
inductive path {α : Type u} (a : α) : α → Type u
| refl : path a
namespace path
attribute [refl] path.refl
@[symm] def symm {α : Type u} {a b : α} (h : path a b) : path b a :=
by induction h; refl
@[trans] def trans {α : Type u} {a b c : α} (h : path a b) (h' : path b c) : path a c :=
by induction h; induction h'; refl
@[congr] def congr {α : Type u} {β : Type v} (f f' : α → β) (a a' : α)
(hf : path f f') (ha : path a a') : path (f a) (f' a') :=
by induction hf; induction ha; refl
def mp {α β : Type u} (h : path α β) : α → β :=
by intro; induction h; assumption
open tactic expr
meta def path_simp_target (sls : simp_lemmas) := do
tgt ← target,
(tgt', prf) ← simplify sls [] tgt {lift_eq:=ff} `path,
prf ← mk_mapp `path.symm [none, tgt, tgt', prf],
mk_mapp `path.mp [tgt', tgt, prf] >>= apply
def nat_zero_add (n : ℕ) : path (0 + n) n := sorry
def foo (n : ℕ) : path (0 + (0 + n)) n := by do
let sls := simp_lemmas.mk,
-- path.congr can be used as a congruence lemma
sls ← sls.add_congr ``path.congr,
-- nat_zero_add can be used as a simplification lemma even though it has
-- associated equational lemmas
sls ← sls.add_simp ``nat_zero_add,
trace sls,
path_simp_target sls, reflexivity
end path |
123bca5527dbbc4b20e529b60a5b3338ec224969 | 30b012bb72d640ec30c8fdd4c45fdfa67beb012c | /data/list/basic.lean | e32d5434582d739e081000775c7e23c4657e1453 | [
"Apache-2.0"
] | permissive | kckennylau/mathlib | 21fb810b701b10d6606d9002a4004f7672262e83 | 47b3477e20ffb5a06588dd3abb01fe0fe3205646 | refs/heads/master | 1,634,976,409,281 | 1,542,042,832,000 | 1,542,319,733,000 | 109,560,458 | 0 | 0 | Apache-2.0 | 1,542,369,208,000 | 1,509,867,494,000 | Lean | UTF-8 | Lean | false | false | 184,358 | lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro
Basic properties of lists.
-/
import
tactic.interactive tactic.mk_iff_of_inductive_prop tactic.split_ifs
logic.basic logic.function logic.relation
algebra.group order.basic
data.nat.basic data.option data.bool data.prod data.sigma data.fin
open function nat
namespace list
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
@[simp] theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ [].
theorem head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} :
(h₁::t₁) = (h₂::t₂) → h₁ = h₂ :=
assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq)
theorem tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} :
(h₁::t₁) = (h₂::t₂) → t₁ = t₂ :=
assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq)
theorem cons_inj {a : α} : injective (cons a) :=
assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe
@[simp] theorem cons_inj' (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' :=
⟨λ e, cons_inj e, congr_arg _⟩
/- mem -/
theorem eq_nil_of_forall_not_mem : ∀ {l : list α}, (∀ a, a ∉ l) → l = nil
| [] := assume h, rfl
| (b :: l') := assume h, absurd (mem_cons_self b l') (h b)
theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _
theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b :=
assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this)
(assume : a = b, this)
(assume : a ∈ [], absurd this (not_mem_nil a))
@[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b :=
⟨eq_of_mem_singleton, or.inl⟩
theorem mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l :=
assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl)
(assume : a = b, begin subst a, exact binl end)
(assume : a ∈ l, this)
theorem eq_or_ne_mem_of_mem {a b : α} {l : list α} (h : a ∈ b :: l) : a = b ∨ (a ≠ b ∧ a ∈ l) :=
classical.by_cases or.inl $ assume : a ≠ b, h.elim or.inl $ assume h, or.inr ⟨this, h⟩
theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t :=
mt mem_append.1 $ not_or_distrib.2 ⟨h₁, h₂⟩
theorem ne_nil_of_mem {a : α} {l : list α} (h : a ∈ l) : l ≠ [] :=
by intro e; rw e at h; cases h
theorem length_eq_zero {l : list α} : length l = 0 ↔ l = [] :=
⟨eq_nil_of_length_eq_zero, λ h, h.symm ▸ rfl⟩
theorem length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l
| (b::l) _ := zero_lt_succ _
theorem exists_mem_of_length_pos : ∀ {l : list α}, 0 < length l → ∃ a, a ∈ l
| (b::l) _ := ⟨b, mem_cons_self _ _⟩
theorem length_pos_iff_exists_mem {l : list α} : 0 < length l ↔ ∃ a, a ∈ l :=
⟨exists_mem_of_length_pos, λ ⟨a, h⟩, length_pos_of_mem h⟩
theorem length_eq_one {l : list α} : length l = 1 ↔ ∃ a, l = [a] :=
⟨match l with [a], _ := ⟨a, rfl⟩ end, λ ⟨a, e⟩, e.symm ▸ rfl⟩
theorem mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t :=
begin
induction l with b l ih, {cases h}, rcases h with rfl | h,
{ exact ⟨[], l, rfl⟩ },
{ rcases ih h with ⟨s, t, rfl⟩,
exact ⟨b::s, t, rfl⟩ }
end
theorem mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l :=
or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r)
theorem ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b :=
assume nin aeqb, absurd (or.inl aeqb) nin
theorem not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l :=
assume nin nainl, absurd (or.inr nainl) nin
theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l :=
assume p1 p2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2))
theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l :=
assume p, and.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p)
theorem mem_map_of_mem (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l :=
begin
induction l with b l' ih,
{cases h},
{rcases h with rfl | h,
{exact or.inl rfl},
{exact or.inr (ih h)}}
end
theorem exists_of_mem_map {f : α → β} {b : β} {l : list α} (h : b ∈ map f l) : ∃ a, a ∈ l ∧ f a = b :=
begin
induction l with c l' ih,
{cases h},
{cases (eq_or_mem_of_mem_cons h) with h h,
{exact ⟨c, mem_cons_self _ _, h.symm⟩},
{rcases ih h with ⟨a, ha₁, ha₂⟩,
exact ⟨a, mem_cons_of_mem _ ha₁, ha₂⟩ }}
end
@[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b :=
⟨exists_of_mem_map, λ ⟨a, la, h⟩, by rw [← h]; exact mem_map_of_mem f la⟩
@[simp] theorem mem_map_of_inj {f : α → β} (H : injective f) {a : α} {l : list α} :
f a ∈ map f l ↔ a ∈ l :=
⟨λ m, let ⟨a', m', e⟩ := exists_of_mem_map m in H e ▸ m', mem_map_of_mem _⟩
@[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l
| [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩
| (c :: L) := by simp only [join, mem_append, @mem_join L, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left]
theorem exists_of_mem_join {a : α} {L : list (list α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l :=
mem_join.1
theorem mem_join_of_mem {a : α} {L : list (list α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L :=
mem_join.2 ⟨l, lL, al⟩
@[simp] theorem mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f ↔ ∃ a ∈ l, b ∈ f a :=
iff.trans mem_join
⟨λ ⟨l', h1, h2⟩, let ⟨a, al, fa⟩ := exists_of_mem_map h1 in ⟨a, al, fa.symm ▸ h2⟩,
λ ⟨a, al, bfa⟩, ⟨f a, mem_map_of_mem _ al, bfa⟩⟩
theorem exists_of_mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f → ∃ a ∈ l, b ∈ f a :=
mem_bind.1
theorem mem_bind_of_mem {b : β} {l : list α} {f : α → list β} {a} (al : a ∈ l) (h : b ∈ f a) : b ∈ list.bind l f :=
mem_bind.2 ⟨a, al, h⟩
lemma bind_map {g : α → list β} {f : β → γ} :
∀(l : list α), list.map f (l.bind g) = l.bind (λa, (g a).map f)
| [] := rfl
| (a::l) := by simp only [cons_bind, map_append, bind_map l]
/- bounded quantifiers over lists -/
theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x.
@[simp] theorem forall_mem_cons' {p : α → Prop} {a : α} {l : list α} :
(∀ (x : α), x = a ∨ x ∈ l → p x) ↔ p a ∧ ∀ x ∈ l, p x :=
by simp only [or_imp_distrib, forall_and_distrib, forall_eq]
theorem forall_mem_cons {p : α → Prop} {a : α} {l : list α} :
(∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x :=
by simp only [mem_cons_iff, forall_mem_cons']
theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α}
(h : ∀ x ∈ a :: l, p x) :
∀ x ∈ l, p x :=
(forall_mem_cons.1 h).2
theorem forall_mem_singleton {p : α → Prop} {a : α} : (∀ x ∈ [a], p x) ↔ p a :=
by simp only [mem_singleton, forall_eq]
theorem forall_mem_append {p : α → Prop} {l₁ l₂ : list α} :
(∀ x ∈ l₁ ++ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) :=
by simp only [mem_append, or_imp_distrib, forall_and_distrib]
theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x.
theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) :
∃ x ∈ a :: l, p x :=
bex.intro a (mem_cons_self _ _) h
theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) :
∃ x ∈ a :: l, p x :=
bex.elim h (λ x xl px, bex.intro x (mem_cons_of_mem _ xl) px)
theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) :
p a ∨ ∃ x ∈ l, p x :=
bex.elim h (λ x xal px,
or.elim (eq_or_mem_of_mem_cons xal)
(assume : x = a, begin rw ←this, left, exact px end)
(assume : x ∈ l, or.inr (bex.intro x this px)))
@[simp] theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) :
(∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x :=
iff.intro or_exists_of_exists_mem_cons
(assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists)
/- list subset -/
theorem subset_def {l₁ l₂ : list α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := iff.rfl
theorem subset_app_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ :=
λ s, subset.trans s $ subset_append_left _ _
theorem subset_app_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ :=
λ s, subset.trans s $ subset_append_right _ _
@[simp] theorem cons_subset {a : α} {l m : list α} :
a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m :=
by simp only [subset_def, mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq]
theorem cons_subset_of_subset_of_mem {a : α} {l m : list α}
(ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m :=
cons_subset.2 ⟨ainm, lsubm⟩
theorem app_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) :
l₁ ++ l₂ ⊆ l :=
λ a h, (mem_append.1 h).elim (@l₁subl _) (@l₂subl _)
theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = []
| [] s := rfl
| (a::l) s := false.elim $ s $ mem_cons_self a l
theorem eq_nil_iff_forall_not_mem {l : list α} : l = [] ↔ ∀ a, a ∉ l :=
show l = [] ↔ l ⊆ [], from ⟨λ e, e ▸ subset.refl _, eq_nil_of_subset_nil⟩
theorem map_subset {l₁ l₂ : list α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ :=
λ x, by simp only [mem_map, not_and, exists_imp_distrib, and_imp]; exact λ a h e, ⟨a, H h, e⟩
/- append -/
lemma append_eq_has_append {L₁ L₂ : list α} : list.append L₁ L₂ = L₁ ++ L₂ := rfl
theorem append_ne_nil_of_ne_nil_left (s t : list α) : s ≠ [] → s ++ t ≠ [] :=
by induction s; intros; contradiction
theorem append_ne_nil_of_ne_nil_right (s t : list α) : t ≠ [] → s ++ t ≠ [] :=
by induction s; intros; contradiction
theorem append_foldl (f : α → β → α) (a : α) (s t : list β) : foldl f a (s ++ t) = foldl f (foldl f a s) t :=
by {induction s with b s H generalizing a, refl, simp only [foldl, cons_append], rw H _}
theorem append_foldr (f : α → β → β) (a : β) (s t : list α) : foldr f a (s ++ t) = foldr f (foldr f a t) s :=
by {induction s with b s H generalizing a, refl, simp only [foldr, cons_append], rw H _}
@[simp] lemma append_eq_nil {p q : list α} : (p ++ q) = [] ↔ p = [] ∧ q = [] :=
by cases p; simp only [nil_append, cons_append, eq_self_iff_true, true_and, false_and]
@[simp] lemma nil_eq_append_iff {a b : list α} : [] = a ++ b ↔ a = [] ∧ b = [] :=
by rw [eq_comm, append_eq_nil]
lemma append_eq_cons_iff {a b c : list α} {x : α} :
a ++ b = x :: c ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) :=
by cases a; simp only [and_assoc, @eq_comm _ c, nil_append, cons_append, eq_self_iff_true,
true_and, false_and, exists_false, false_or, or_false, exists_and_distrib_left, exists_eq_left']
lemma cons_eq_append_iff {a b c : list α} {x : α} :
(x :: c : list α) = a ++ b ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) :=
by rw [eq_comm, append_eq_cons_iff]
lemma append_eq_append_iff {a b c d : list α} :
a ++ b = c ++ d ↔ (∃a', c = a ++ a' ∧ b = a' ++ d) ∨ (∃c', a = c ++ c' ∧ d = c' ++ b) :=
begin
induction a generalizing c,
case nil { rw nil_append, split,
{ rintro rfl, left, exact ⟨_, rfl, rfl⟩ },
{ rintro (⟨a', rfl, rfl⟩ | ⟨a', H, rfl⟩), {refl}, {rw [← append_assoc, ← H], refl} } },
case cons : a as ih {
cases c,
{ simp only [cons_append, nil_append, false_and, exists_false, false_or, exists_eq_left'], exact eq_comm },
{ simp only [cons_append, @eq_comm _ a, ih, and_assoc, and_or_distrib_left, exists_and_distrib_left] } }
end
/-- Split a list at an index. `split 2 [a, b, c] = ([a, b], [c])` -/
def split_at : ℕ → list α → list α × list α
| 0 a := ([], a)
| (succ n) [] := ([], [])
| (succ n) (x :: xs) := let (l, r) := split_at n xs in (x :: l, r)
@[simp] theorem split_at_eq_take_drop : ∀ (n : ℕ) (l : list α), split_at n l = (take n l, drop n l)
| 0 a := rfl
| (succ n) [] := rfl
| (succ n) (x :: xs) := by simp only [split_at, split_at_eq_take_drop n xs, take, drop]
@[simp] theorem take_append_drop : ∀ (n : ℕ) (l : list α), take n l ++ drop n l = l
| 0 a := rfl
| (succ n) [] := rfl
| (succ n) (x :: xs) := congr_arg (cons x) $ take_append_drop n xs
-- TODO(Leo): cleanup proof after arith dec proc
theorem append_inj : ∀ {s₁ s₂ t₁ t₂ : list α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂
| [] [] t₁ t₂ h hl := ⟨rfl, h⟩
| (a::s₁) [] t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl
| [] (b::s₂) t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl.symm
| (a::s₁) (b::s₂) t₁ t₂ h hl := list.no_confusion h $ λab hap,
let ⟨e1, e2⟩ := @append_inj s₁ s₂ t₁ t₂ hap (succ.inj hl) in
by rw [ab, e1, e2]; exact ⟨rfl, rfl⟩
theorem append_inj_left {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : t₁ = t₂ :=
(append_inj h hl).right
theorem append_inj_right {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : s₁ = s₂ :=
(append_inj h hl).left
theorem append_inj' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ ∧ t₁ = t₂ :=
append_inj h $ @nat.add_right_cancel _ (length t₁) _ $
let hap := congr_arg length h in by simp only [length_append] at hap; rwa [← hl] at hap
theorem append_inj_left' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : t₁ = t₂ :=
(append_inj' h hl).right
theorem append_inj_right' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ :=
(append_inj' h hl).left
theorem append_left_cancel {s t₁ t₂ : list α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ :=
append_inj_left h rfl
theorem append_right_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ :=
append_inj_right' h rfl
theorem append_left_inj {t₁ t₂ : list α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ :=
⟨append_left_cancel, congr_arg _⟩
theorem append_right_inj {s₁ s₂ : list α} (t) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ :=
⟨append_right_cancel, congr_arg _⟩
theorem map_eq_append_split {f : α → β} {l : list α} {s₁ s₂ : list β}
(h : map f l = s₁ ++ s₂) : ∃ l₁ l₂, l = l₁ ++ l₂ ∧ map f l₁ = s₁ ∧ map f l₂ = s₂ :=
begin
have := h, rw [← take_append_drop (length s₁) l] at this ⊢,
rw map_append at this,
refine ⟨_, _, rfl, append_inj this _⟩,
rw [length_map, length_take, min_eq_left],
rw [← length_map f l, h, length_append],
apply nat.le_add_right
end
/- join -/
attribute [simp] join
theorem join_eq_nil : ∀ {L : list (list α)}, join L = [] ↔ ∀ l ∈ L, l = []
| [] := iff_of_true rfl (forall_mem_nil _)
| (l::L) := by simp only [join, append_eq_nil, join_eq_nil, forall_mem_cons]
@[simp] theorem join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ :=
by induction L₁; [refl, simp only [*, join, cons_append, append_assoc]]
/- repeat -/
@[simp] theorem repeat_succ (a : α) (n) : repeat a (n + 1) = a :: repeat a n := rfl
theorem eq_of_mem_repeat {a b : α} : ∀ {n}, b ∈ repeat a n → b = a
| (n+1) h := or.elim h id $ @eq_of_mem_repeat _
theorem eq_repeat_of_mem {a : α} : ∀ {l : list α}, (∀ b ∈ l, b = a) → l = repeat a l.length
| [] H := rfl
| (b::l) H := by cases forall_mem_cons.1 H with H₁ H₂;
unfold length repeat; congr; [exact H₁, exact eq_repeat_of_mem H₂]
theorem eq_repeat' {a : α} {l : list α} : l = repeat a l.length ↔ ∀ b ∈ l, b = a :=
⟨λ h, h.symm ▸ λ b, eq_of_mem_repeat, eq_repeat_of_mem⟩
theorem eq_repeat {a : α} {n} {l : list α} : l = repeat a n ↔ length l = n ∧ ∀ b ∈ l, b = a :=
⟨λ h, h.symm ▸ ⟨length_repeat _ _, λ b, eq_of_mem_repeat⟩,
λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩
theorem repeat_add (a : α) (m n) : repeat a (m + n) = repeat a m ++ repeat a n :=
by induction m; simp only [*, zero_add, succ_add, repeat]; split; refl
theorem repeat_subset_singleton (a : α) (n) : repeat a n ⊆ [a] :=
λ b h, mem_singleton.2 (eq_of_mem_repeat h)
@[simp] theorem map_const (l : list α) (b : β) : map (function.const α b) l = repeat b l.length :=
by induction l; [refl, simp only [*, map]]; split; refl
theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ :=
by rw map_const at h; exact eq_of_mem_repeat h
@[simp] theorem map_repeat (f : α → β) (a : α) (n) : map f (repeat a n) = repeat (f a) n :=
by induction n; [refl, simp only [*, repeat, map]]; split; refl
@[simp] theorem tail_repeat (a : α) (n) : tail (repeat a n) = repeat a n.pred :=
by cases n; refl
@[simp] theorem join_repeat_nil (n : ℕ) : join (repeat [] n) = @nil α :=
by induction n; [refl, simp only [*, repeat, join, append_nil]]
/- bind -/
@[simp] theorem bind_eq_bind {α β} (f : α → list β) (l : list α) :
l >>= f = l.bind f := rfl
@[simp] theorem bind_append {α β} (f : α → list β) (l₁ l₂ : list α) :
(l₁ ++ l₂).bind f = l₁.bind f ++ l₂.bind f :=
append_bind _ _ _
/- concat -/
/-- Concatenate an element at the end of a list. `concat [a, b] c = [a, b, c]` -/
@[simp] def concat : list α → α → list α
| [] a := [a]
| (b::l) a := b :: concat l a
@[simp] theorem concat_nil (a : α) : concat [] a = [a] := rfl
@[simp] theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl
@[simp] theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] :=
by induction l; intro h; contradiction
@[simp] theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ :=
by induction l₁; simp only [*, cons_append, concat]; split; refl
@[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] :=
by induction l; simp only [*, concat]; split; refl
@[simp] theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) :=
by simp only [concat_eq_append, length_append, length]
theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a :=
by induction l₂ with b l₂ ih; simp only [concat_eq_append, nil_append, cons_append, append_assoc]
/- reverse -/
@[simp] theorem reverse_nil : reverse (@nil α) = [] := rfl
local attribute [simp] reverse_core
@[simp] theorem reverse_cons (a : α) (l : list α) : reverse (a::l) = reverse l ++ [a] :=
have aux : ∀ l₁ l₂, reverse_core l₁ l₂ ++ [a] = reverse_core l₁ (l₂ ++ [a]),
by intro l₁; induction l₁; intros; [refl, simp only [*, reverse_core, cons_append]],
(aux l nil).symm
theorem reverse_core_eq (l₁ l₂ : list α) : reverse_core l₁ l₂ = reverse l₁ ++ l₂ :=
by induction l₁ generalizing l₂; [refl, simp only [*, reverse_core, reverse_cons, append_assoc]]; refl
theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a :=
by simp only [reverse_cons, concat_eq_append]
@[simp] theorem reverse_singleton (a : α) : reverse [a] = [a] := rfl
@[simp] theorem reverse_append (s t : list α) : reverse (s ++ t) = (reverse t) ++ (reverse s) :=
by induction s; [rw [nil_append, reverse_nil, append_nil],
simp only [*, cons_append, reverse_cons, append_assoc]]
@[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l :=
by induction l; [refl, simp only [*, reverse_cons, reverse_append]]; refl
theorem reverse_injective : injective (@reverse α) :=
injective_of_left_inverse reverse_reverse
@[simp] theorem reverse_inj {l₁ l₂ : list α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ :=
reverse_injective.eq_iff
@[simp] theorem reverse_eq_nil {l : list α} : reverse l = [] ↔ l = [] :=
@reverse_inj _ l []
theorem concat_eq_reverse_cons (a : α) (l : list α) : concat l a = reverse (a :: reverse l) :=
by simp only [concat_eq_append, reverse_cons, reverse_reverse]
@[simp] theorem length_reverse (l : list α) : length (reverse l) = length l :=
by induction l; [refl, simp only [*, reverse_cons, length_append, length]]
@[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) :=
by induction l; [refl, simp only [*, map, reverse_cons, map_append]]
theorem map_reverse_core (f : α → β) (l₁ l₂ : list α) :
map f (reverse_core l₁ l₂) = reverse_core (map f l₁) (map f l₂) :=
by simp only [reverse_core_eq, map_append, map_reverse]
@[simp] theorem mem_reverse {a : α} {l : list α} : a ∈ reverse l ↔ a ∈ l :=
by induction l; [refl, simp only [*, reverse_cons, mem_append, mem_singleton, mem_cons_iff, not_mem_nil, false_or, or_false, or_comm]]
@[simp] theorem reverse_repeat (a : α) (n) : reverse (repeat a n) = repeat a n :=
eq_repeat.2 ⟨by simp only [length_reverse, length_repeat], λ b h, eq_of_mem_repeat (mem_reverse.1 h)⟩
@[elab_as_eliminator] def reverse_rec_on {C : list α → Sort*}
(l : list α) (H0 : C [])
(H1 : ∀ (l : list α) (a : α), C l → C (l ++ [a])) : C l :=
begin
rw ← reverse_reverse l,
induction reverse l,
{ exact H0 },
{ rw reverse_cons, exact H1 _ _ ih }
end
/- last -/
@[simp] theorem last_cons {a : α} {l : list α} : ∀ (h₁ : a :: l ≠ nil) (h₂ : l ≠ nil), last (a :: l) h₁ = last l h₂ :=
by {induction l; intros, contradiction, reflexivity}
@[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a :=
by induction l; [refl, simp only [cons_append, last_cons _ (λ H, cons_ne_nil _ _ (append_eq_nil.1 H).2), *]]
theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a :=
by simp only [concat_eq_append, last_append]
@[simp] theorem last_singleton (a : α) (h : [a] ≠ []) : last [a] h = a := rfl
@[simp] theorem last_cons_cons (a₁ a₂ : α) (l : list α) (h : a₁::a₂::l ≠ []) :
last (a₁::a₂::l) h = last (a₂::l) (cons_ne_nil a₂ l) := rfl
theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) :
last l₁ h₁ = last l₂ h₂ :=
by subst l₁
/- head and tail -/
@[simp] def head' : list α → option α
| [] := none
| (a :: l) := some a
theorem head_eq_head' [inhabited α] (l : list α) : head l = (head' l).iget :=
by cases l; refl
@[simp] theorem head_cons [inhabited α] (a : α) (l : list α) : head (a::l) = a := rfl
@[simp] theorem tail_nil : tail (@nil α) = [] := rfl
@[simp] theorem tail_cons (a : α) (l : list α) : tail (a::l) = l := rfl
@[simp] theorem head_append [inhabited α] (t : list α) {s : list α} (h : s ≠ []) : head (s ++ t) = head s :=
by {induction s, contradiction, refl}
theorem cons_head_tail [inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l :=
by {induction l, contradiction, refl}
/- map -/
lemma map_congr {f g : α → β} : ∀ {l : list α}, (∀ x ∈ l, f x = g x) → map f l = map g l
| [] _ := rfl
| (a::l) h := let ⟨h₁, h₂⟩ := forall_mem_cons.1 h in
by rw [map, map, h₁, map_congr h₂]
theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) :=
by induction l; [refl, simp only [*, concat_eq_append, cons_append, map, map_append]]; split; refl
theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l :=
by induction l; [refl, simp only [*, map]]; split; refl
@[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : list β) : foldl f a (map g l) = foldl (λx y, f x (g y)) a l :=
by revert a; induction l; intros; [refl, simp only [*, map, foldl]]
@[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : list β) : foldr f a (map g l) = foldr (f ∘ g) a l :=
by revert a; induction l; intros; [refl, simp only [*, map, foldr]]
theorem foldl_hom (f : α → β) (g : α → γ → α) (g' : β → γ → β) (a : α)
(h : ∀a x, f (g a x) = g' (f a) x) (l : list γ) : f (foldl g a l) = foldl g' (f a) l :=
by revert a; induction l; intros; [refl, simp only [*, foldl]]
theorem foldr_hom (f : α → β) (g : γ → α → α) (g' : γ → β → β) (a : α)
(h : ∀x a, f (g x a) = g' x (f a)) (l : list γ) : f (foldr g a l) = foldr g' (f a) l :=
by revert a; induction l; intros; [refl, simp only [*, foldr]]
theorem eq_nil_of_map_eq_nil {f : α → β} {l : list α} (h : map f l = nil) : l = nil :=
eq_nil_of_length_eq_zero $ by rw [← length_map f l, h]; refl
@[simp] theorem map_join (f : α → β) (L : list (list α)) :
map f (join L) = join (map (map f) L) :=
by induction L; [refl, simp only [*, join, map, map_append]]
theorem bind_ret_eq_map {α β} (f : α → β) (l : list α) :
l.bind (list.ret ∘ f) = map f l :=
by unfold list.bind; induction l; simp only [map, join, list.ret, cons_append, nil_append, *]; split; refl
@[simp] theorem map_eq_map {α β} (f : α → β) (l : list α) :
f <$> l = map f l := rfl
@[simp] theorem map_tail (f : α → β) (l) : map f (tail l) = tail (map f l) :=
by cases l; refl
/- map₂ -/
theorem nil_map₂ (f : α → β → γ) (l : list β) : map₂ f [] l = [] :=
by cases l; refl
theorem map₂_nil (f : α → β → γ) (l : list α) : map₂ f l [] = [] :=
by cases l; refl
/- sublists -/
@[simp] theorem nil_sublist : Π (l : list α), [] <+ l
| [] := sublist.slnil
| (a :: l) := sublist.cons _ _ a (nil_sublist l)
@[refl, simp] theorem sublist.refl : Π (l : list α), l <+ l
| [] := sublist.slnil
| (a :: l) := sublist.cons2 _ _ a (sublist.refl l)
@[trans] theorem sublist.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ :=
sublist.rec_on h₂ (λ_ s, s)
(λl₂ l₃ a h₂ IH l₁ h₁, sublist.cons _ _ _ (IH l₁ h₁))
(λl₂ l₃ a h₂ IH l₁ h₁, @sublist.cases_on _ (λl₁ l₂', l₂' = a :: l₂ → l₁ <+ a :: l₃) _ _ h₁
(λ_, nil_sublist _)
(λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons _ _ _ (IH _ h₁) end)
(λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons2 _ _ _ (IH _ h₁) end) rfl)
l₁ h₁
@[simp] theorem sublist_cons (a : α) (l : list α) : l <+ a::l :=
sublist.cons _ _ _ (sublist.refl l)
theorem sublist_of_cons_sublist {a : α} {l₁ l₂ : list α} : a::l₁ <+ l₂ → l₁ <+ l₂ :=
sublist.trans (sublist_cons a l₁)
theorem cons_sublist_cons {l₁ l₂ : list α} (a : α) (s : l₁ <+ l₂) : a::l₁ <+ a::l₂ :=
sublist.cons2 _ _ _ s
@[simp] theorem sublist_append_left : Π (l₁ l₂ : list α), l₁ <+ l₁++l₂
| [] l₂ := nil_sublist _
| (a::l₁) l₂ := cons_sublist_cons _ (sublist_append_left l₁ l₂)
@[simp] theorem sublist_append_right : Π (l₁ l₂ : list α), l₂ <+ l₁++l₂
| [] l₂ := sublist.refl _
| (a::l₁) l₂ := sublist.cons _ _ _ (sublist_append_right l₁ l₂)
theorem sublist_cons_of_sublist (a : α) {l₁ l₂ : list α} : l₁ <+ l₂ → l₁ <+ a::l₂ :=
sublist.cons _ _ _
theorem sublist_app_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ :=
s.trans $ sublist_append_left _ _
theorem sublist_app_of_sublist_right {l l₁ l₂ : list α} (s : l <+ l₂) : l <+ l₁++l₂ :=
s.trans $ sublist_append_right _ _
theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂
| ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s
| ._ (sublist.cons2 ._ ._ a s) := s
theorem cons_sublist_cons_iff {l₁ l₂ : list α} {a : α} : a::l₁ <+ a::l₂ ↔ l₁ <+ l₂ :=
⟨sublist_of_cons_sublist_cons, cons_sublist_cons _⟩
@[simp] theorem append_sublist_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+ l++l₂ ↔ l₁ <+ l₂
| [] := iff.rfl
| (a::l) := cons_sublist_cons_iff.trans (append_sublist_append_left l)
theorem append_sublist_append_of_sublist_right {l₁ l₂ : list α} (h : l₁ <+ l₂) (l) : l₁++l <+ l₂++l :=
begin
induction h with _ _ a _ ih _ _ a _ ih,
{ refl },
{ apply sublist_cons_of_sublist a ih },
{ apply cons_sublist_cons a ih }
end
theorem sublist_or_mem_of_sublist {l l₁ l₂ : list α} {a : α} (h : l <+ l₁ ++ a::l₂) : l <+ l₁ ++ l₂ ∨ a ∈ l :=
begin
induction l₁ with b l₁ IH generalizing l,
{ cases h, { left, exact ‹l <+ l₂› }, { right, apply mem_cons_self } },
{ cases h with _ _ _ h _ _ _ h,
{ exact or.imp_left (sublist_cons_of_sublist _) (IH h) },
{ exact (IH h).imp (cons_sublist_cons _) (mem_cons_of_mem _) } }
end
theorem reverse_sublist {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse :=
begin
induction h with _ _ _ _ ih _ _ a _ ih, {refl},
{ rw reverse_cons, exact sublist_app_of_sublist_left ih },
{ rw [reverse_cons, reverse_cons], exact append_sublist_append_of_sublist_right ih [a] }
end
@[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ :=
⟨λ h, by have := reverse_sublist h; simp only [reverse_reverse] at this; assumption, reverse_sublist⟩
@[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ :=
⟨λ h, by have := reverse_sublist h; simp only [reverse_append, append_sublist_append_left, reverse_sublist_iff] at this; assumption,
λ h, append_sublist_append_of_sublist_right h l⟩
theorem subset_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂
| ._ ._ sublist.slnil b h := h
| ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (subset_of_sublist s h)
| ._ ._ (sublist.cons2 l₁ l₂ a s) b h :=
match eq_or_mem_of_mem_cons h with
| or.inl h := h ▸ mem_cons_self _ _
| or.inr h := mem_cons_of_mem _ (subset_of_sublist s h)
end
theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l :=
⟨λ h, subset_of_sublist h (mem_singleton_self _), λ h,
let ⟨s, t, e⟩ := mem_split h in e.symm ▸
(cons_sublist_cons _ (nil_sublist _)).trans (sublist_append_right _ _)⟩
theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] :=
eq_nil_of_subset_nil $ subset_of_sublist s
theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n :=
⟨λ h, by simpa only [length_repeat] using length_le_of_sublist h,
λ h, by induction h; [refl, simp only [*, repeat_succ, sublist.cons]] ⟩
theorem eq_of_sublist_of_length_eq : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂
| ._ ._ sublist.slnil h := rfl
| ._ ._ (sublist.cons l₁ l₂ a s) h :=
absurd (length_le_of_sublist s) $ not_le_of_gt $ by rw h; apply lt_succ_self
| ._ ._ (sublist.cons2 l₁ l₂ a s) h :=
by rw [length, length] at h; injection h with h; rw eq_of_sublist_of_length_eq s h
theorem eq_of_sublist_of_length_le {l₁ l₂ : list α} (s : l₁ <+ l₂) (h : length l₂ ≤ length l₁) : l₁ = l₂ :=
eq_of_sublist_of_length_eq s (le_antisymm (length_le_of_sublist s) h)
theorem sublist_antisymm {l₁ l₂ : list α} (s₁ : l₁ <+ l₂) (s₂ : l₂ <+ l₁) : l₁ = l₂ :=
eq_of_sublist_of_length_le s₁ (length_le_of_sublist s₂)
instance decidable_sublist [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+ l₂)
| [] l₂ := is_true $ nil_sublist _
| (a::l₁) [] := is_false $ λh, list.no_confusion $ eq_nil_of_sublist_nil h
| (a::l₁) (b::l₂) :=
if h : a = b then
decidable_of_decidable_of_iff (decidable_sublist l₁ l₂) $
by rw [← h]; exact ⟨cons_sublist_cons _, sublist_of_cons_sublist_cons⟩
else decidable_of_decidable_of_iff (decidable_sublist (a::l₁) l₂)
⟨sublist_cons_of_sublist _, λs, match a, l₁, s, h with
| a, l₁, sublist.cons ._ ._ ._ s', h := s'
| ._, ._, sublist.cons2 t ._ ._ s', h := absurd rfl h
end⟩
/- index_of -/
section index_of
variable [decidable_eq α]
@[simp] theorem index_of_nil (a : α) : index_of a [] = 0 := rfl
theorem index_of_cons (a b : α) (l : list α) : index_of a (b::l) = if a = b then 0 else succ (index_of a l) := rfl
theorem index_of_cons_eq {a b : α} (l : list α) : a = b → index_of a (b::l) = 0 :=
assume e, if_pos e
@[simp] theorem index_of_cons_self (a : α) (l : list α) : index_of a (a::l) = 0 :=
index_of_cons_eq _ rfl
@[simp] theorem index_of_cons_ne {a b : α} (l : list α) : a ≠ b → index_of a (b::l) = succ (index_of a l) :=
assume n, if_neg n
theorem index_of_eq_length {a : α} {l : list α} : index_of a l = length l ↔ a ∉ l :=
begin
induction l with b l ih,
{ exact iff_of_true rfl (not_mem_nil _) },
simp only [length, mem_cons_iff, index_of_cons], split_ifs,
{ exact iff_of_false (by rintro ⟨⟩) (λ H, H $ or.inl h) },
{ simp only [h, false_or], rw ← ih, exact succ_inj' }
end
@[simp] theorem index_of_of_not_mem {l : list α} {a : α} : a ∉ l → index_of a l = length l :=
index_of_eq_length.2
theorem index_of_le_length {a : α} {l : list α} : index_of a l ≤ length l :=
begin
induction l with b l ih, {refl},
simp only [length, index_of_cons],
by_cases h : a = b, {rw if_pos h, exact nat.zero_le _},
rw if_neg h, exact succ_le_succ ih
end
theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l :=
⟨λh, by_contradiction $ λ al, ne_of_lt h $ index_of_eq_length.2 al,
λal, lt_of_le_of_ne index_of_le_length $ λ h, index_of_eq_length.1 h al⟩
end index_of
/- nth element -/
theorem nth_le_of_mem : ∀ {a} {l : list α}, a ∈ l → ∃ n h, nth_le l n h = a
| a (_ :: l) (or.inl rfl) := ⟨0, succ_pos _, rfl⟩
| a (b :: l) (or.inr m) :=
let ⟨n, h, e⟩ := nth_le_of_mem m in ⟨n+1, succ_lt_succ h, e⟩
theorem nth_le_nth : ∀ {l : list α} {n} h, nth l n = some (nth_le l n h)
| (a :: l) 0 h := rfl
| (a :: l) (n+1) h := @nth_le_nth l n _
theorem nth_ge_len : ∀ {l : list α} {n}, n ≥ length l → nth l n = none
| [] n h := rfl
| (a :: l) (n+1) h := nth_ge_len (le_of_succ_le_succ h)
theorem nth_eq_some {l : list α} {n a} : nth l n = some a ↔ ∃ h, nth_le l n h = a :=
⟨λ e,
have h : n < length l, from lt_of_not_ge $ λ hn,
by rw nth_ge_len hn at e; contradiction,
⟨h, by rw nth_le_nth h at e;
injection e with e; apply nth_le_mem⟩,
λ ⟨h, e⟩, e ▸ nth_le_nth _⟩
theorem nth_of_mem {a} {l : list α} (h : a ∈ l) : ∃ n, nth l n = some a :=
let ⟨n, h, e⟩ := nth_le_of_mem h in ⟨n, by rw [nth_le_nth, e]⟩
theorem nth_le_mem : ∀ (l : list α) n h, nth_le l n h ∈ l
| (a :: l) 0 h := mem_cons_self _ _
| (a :: l) (n+1) h := mem_cons_of_mem _ (nth_le_mem l _ _)
theorem nth_mem {l : list α} {n a} (e : nth l n = some a) : a ∈ l :=
let ⟨h, e⟩ := nth_eq_some.1 e in e ▸ nth_le_mem _ _ _
theorem mem_iff_nth_le {a} {l : list α} : a ∈ l ↔ ∃ n h, nth_le l n h = a :=
⟨nth_le_of_mem, λ ⟨n, h, e⟩, e ▸ nth_le_mem _ _ _⟩
theorem mem_iff_nth {a} {l : list α} : a ∈ l ↔ ∃ n, nth l n = some a :=
mem_iff_nth_le.trans $ exists_congr $ λ n, nth_eq_some.symm
@[simp] theorem nth_map (f : α → β) : ∀ l n, nth (map f l) n = (nth l n).map f
| [] n := rfl
| (a :: l) 0 := rfl
| (a :: l) (n+1) := nth_map l n
theorem nth_le_map (f : α → β) {l n} (H1 H2) : nth_le (map f l) n H1 = f (nth_le l n H2) :=
option.some.inj $ by rw [← nth_le_nth, nth_map, nth_le_nth]; refl
@[simp] theorem nth_le_map' (f : α → β) {l n} (H) :
nth_le (map f l) n H = f (nth_le l n (length_map f l ▸ H)) :=
nth_le_map f _ _
@[extensionality]
theorem ext : ∀ {l₁ l₂ : list α}, (∀n, nth l₁ n = nth l₂ n) → l₁ = l₂
| [] [] h := rfl
| (a::l₁) [] h := by have h0 := h 0; contradiction
| [] (a'::l₂) h := by have h0 := h 0; contradiction
| (a::l₁) (a'::l₂) h := by have h0 : some a = some a' := h 0; injection h0 with aa;
simp only [aa, ext (λn, h (n+1))]; split; refl
theorem ext_le {l₁ l₂ : list α} (hl : length l₁ = length l₂) (h : ∀n h₁ h₂, nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ :=
ext $ λn, if h₁ : n < length l₁
then by rw [nth_le_nth, nth_le_nth, h n h₁ (by rwa [← hl])]
else let h₁ := le_of_not_gt h₁ in by rw [nth_ge_len h₁, nth_ge_len (by rwa [← hl])]
@[simp] theorem index_of_nth_le [decidable_eq α] {a : α} : ∀ {l : list α} h, nth_le l (index_of a l) h = a
| (b::l) h := by by_cases h' : a = b; simp only [h', if_pos, if_false, index_of_cons, nth_le, @index_of_nth_le l]
@[simp] theorem index_of_nth [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : nth l (index_of a l) = some a :=
by rw [nth_le_nth, index_of_nth_le (index_of_lt_length.2 h)]
theorem nth_le_reverse_aux1 : ∀ (l r : list α) (i h1 h2), nth_le (reverse_core l r) (i + length l) h1 = nth_le r i h2
| [] r i := λh1 h2, rfl
| (a :: l) r i := by rw (show i + length (a :: l) = i + 1 + length l, from add_right_comm i (length l) 1); exact
λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2)
theorem nth_le_reverse_aux2 : ∀ (l r : list α) (i : nat) (h1) (h2),
nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2
| [] r i h1 h2 := absurd h2 (not_lt_zero _)
| (a :: l) r 0 h1 h2 := begin
have aux := nth_le_reverse_aux1 l (a :: r) 0,
rw zero_add at aux,
exact aux _ (zero_lt_succ _)
end
| (a :: l) r (i+1) h1 h2 := begin
have aux := nth_le_reverse_aux2 l (a :: r) i,
have heq := calc length (a :: l) - 1 - (i + 1)
= length l - (1 + i) : by rw add_comm; refl
... = length l - 1 - i : by rw nat.sub_sub,
rw [← heq] at aux,
apply aux
end
@[simp] theorem nth_le_reverse (l : list α) (i : nat) (h1 h2) :
nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 :=
nth_le_reverse_aux2 _ _ _ _ _
/-- Convert a list into an array (whose length is the length of `l`) -/
def to_array (l : list α) : array l.length α :=
{data := λ v, l.nth_le v.1 v.2}
/-- "inhabited" `nth` function: returns `default` instead of `none` in the case
that the index is out of bounds. -/
@[simp] def inth [h : inhabited α] (l : list α) (n : nat) : α := (nth l n).iget
/- nth tail operation -/
/-- Apply a function to the nth tail of `l`.
`modify_nth_tail f 2 [a, b, c] = [a, b] ++ f [c]`. Returns the input without
using `f` if the index is larger than the length of the list. -/
@[simp] def modify_nth_tail (f : list α → list α) : ℕ → list α → list α
| 0 l := f l
| (n+1) [] := []
| (n+1) (a::l) := a :: modify_nth_tail n l
/-- Apply `f` to the head of the list, if it exists. -/
@[simp] def modify_head (f : α → α) : list α → list α
| [] := []
| (a::l) := f a :: l
/-- Apply `f` to the nth element of the list, if it exists. -/
def modify_nth (f : α → α) : ℕ → list α → list α :=
modify_nth_tail (modify_head f)
lemma modify_nth_tail_modify_nth_tail {f g : list α → list α} (m : ℕ) :
∀n (l:list α), (l.modify_nth_tail f n).modify_nth_tail g (m + n) =
l.modify_nth_tail (λl, (f l).modify_nth_tail g m) n
| 0 l := rfl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_modify_nth_tail n l)
lemma modify_nth_tail_modify_nth_tail_le
{f g : list α → list α} (m n : ℕ) (l : list α) (h : n ≤ m) :
(l.modify_nth_tail f n).modify_nth_tail g m =
l.modify_nth_tail (λl, (f l).modify_nth_tail g (m - n)) n :=
begin
rcases le_iff_exists_add.1 h with ⟨m, rfl⟩,
rw [nat.add_sub_cancel_left, add_comm, modify_nth_tail_modify_nth_tail]
end
lemma modify_nth_tail_modify_nth_tail_same {f g : list α → list α} (n : ℕ) (l:list α) :
(l.modify_nth_tail f n).modify_nth_tail g n = l.modify_nth_tail (g ∘ f) n :=
by rw [modify_nth_tail_modify_nth_tail_le n n l (le_refl n), nat.sub_self]; refl
lemma modify_nth_tail_id :
∀n (l:list α), l.modify_nth_tail id n = l
| 0 l := rfl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_id n l)
theorem remove_nth_eq_nth_tail : ∀ n (l : list α), remove_nth l n = modify_nth_tail tail n l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (cons _) (remove_nth_eq_nth_tail _ _)
theorem update_nth_eq_modify_nth (a : α) : ∀ n (l : list α),
update_nth l n a = modify_nth (λ _, a) n l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (b::l) := congr_arg (cons _) (update_nth_eq_modify_nth _ _)
theorem modify_nth_eq_update_nth (f : α → α) : ∀ n (l : list α),
modify_nth f n l = ((λ a, update_nth l n (f a)) <$> nth l n).get_or_else l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (b::l) := (congr_arg (cons b)
(modify_nth_eq_update_nth n l)).trans $ by cases nth l n; refl
theorem nth_modify_nth (f : α → α) : ∀ n (l : list α) m,
nth (modify_nth f n l) m = (λ a, if n = m then f a else a) <$> nth l m
| n l 0 := by cases l; cases n; refl
| n [] (m+1) := by cases n; refl
| 0 (a::l) (m+1) := by cases nth l m; refl
| (n+1) (a::l) (m+1) := (nth_modify_nth n l m).trans $
by cases nth l m with b; by_cases n = m;
simp only [h, if_pos, if_true, if_false, option.map_none, option.map_some, mt succ_inj, not_false_iff]
theorem modify_nth_tail_length (f : list α → list α) (H : ∀ l, length (f l) = length l) :
∀ n l, length (modify_nth_tail f n l) = length l
| 0 l := H _
| (n+1) [] := rfl
| (n+1) (a::l) := @congr_arg _ _ _ _ (+1) (modify_nth_tail_length _ _)
@[simp] theorem modify_nth_length (f : α → α) :
∀ n l, length (modify_nth f n l) = length l :=
modify_nth_tail_length _ (λ l, by cases l; refl)
@[simp] theorem update_nth_length (l : list α) (n) (a : α) :
length (update_nth l n a) = length l :=
by simp only [update_nth_eq_modify_nth, modify_nth_length]
@[simp] theorem nth_modify_nth_eq (f : α → α) (n) (l : list α) :
nth (modify_nth f n l) n = f <$> nth l n :=
by simp only [nth_modify_nth, if_pos]
@[simp] theorem nth_modify_nth_ne (f : α → α) {m n} (l : list α) (h : m ≠ n) :
nth (modify_nth f m l) n = nth l n :=
by simp only [nth_modify_nth, if_neg h, id_map']
theorem nth_update_nth_eq (a : α) (n) (l : list α) :
nth (update_nth l n a) n = (λ _, a) <$> nth l n :=
by simp only [update_nth_eq_modify_nth, nth_modify_nth_eq]
theorem nth_update_nth_of_lt (a : α) {n} {l : list α} (h : n < length l) :
nth (update_nth l n a) n = some a :=
by rw [nth_update_nth_eq, nth_le_nth h]; refl
theorem nth_update_nth_ne (a : α) {m n} (l : list α) (h : m ≠ n) :
nth (update_nth l m a) n = nth l n :=
by simp only [update_nth_eq_modify_nth, nth_modify_nth_ne _ _ h]
section insert_nth
variable {a : α}
def insert_nth (n : ℕ) (a : α) : list α → list α := modify_nth_tail (list.cons a) n
@[simp] lemma insert_nth_nil (a : α) : insert_nth 0 a [] = [a] := rfl
lemma length_insert_nth : ∀n as, n ≤ length as → length (insert_nth n a as) = length as + 1
| 0 as h := rfl
| (n+1) [] h := (nat.not_succ_le_zero _ h).elim
| (n+1) (a'::as) h := congr_arg nat.succ $ length_insert_nth n as (nat.le_of_succ_le_succ h)
lemma remove_nth_insert_nth (n:ℕ) (l : list α) : (l.insert_nth n a).remove_nth n = l :=
by rw [remove_nth_eq_nth_tail, insert_nth, modify_nth_tail_modify_nth_tail_same];
from modify_nth_tail_id _ _
lemma insert_nth_remove_nth_of_ge : ∀n m as, n < length as → m ≥ n →
insert_nth m a (as.remove_nth n) = (as.insert_nth (m + 1) a).remove_nth n
| 0 0 [] has _ := (lt_irrefl _ has).elim
| 0 0 (a::as) has hmn := by simp [remove_nth, insert_nth]
| 0 (m+1) (a::as) has hmn := rfl
| (n+1) (m+1) (a::as) has hmn :=
congr_arg (cons a) $
insert_nth_remove_nth_of_ge n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn)
lemma insert_nth_remove_nth_of_le : ∀n m as, n < length as → m ≤ n →
insert_nth m a (as.remove_nth n) = (as.insert_nth m a).remove_nth (n + 1)
| n 0 (a :: as) has hmn := rfl
| (n + 1) (m + 1) (a :: as) has hmn :=
congr_arg (cons a) $
insert_nth_remove_nth_of_le n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn)
lemma insert_nth_comm (a b : α) :
∀(i j : ℕ) (l : list α) (h : i ≤ j) (hj : j ≤ length l),
(l.insert_nth i a).insert_nth (j + 1) b = (l.insert_nth j b).insert_nth i a
| 0 j l := by simp [insert_nth]
| (i + 1) 0 l := assume h, (nat.not_lt_zero _ h).elim
| (i + 1) (j+1) [] := by simp
| (i + 1) (j+1) (c::l) :=
assume h₀ h₁,
by simp [insert_nth]; exact insert_nth_comm i j l (nat.le_of_succ_le_succ h₀) (nat.le_of_succ_le_succ h₁)
end insert_nth
/- take, drop -/
@[simp] theorem take_zero (l : list α) : take 0 l = [] := rfl
@[simp] theorem take_nil : ∀ n, take n [] = ([] : list α)
| 0 := rfl
| (n+1) := rfl
theorem take_cons (n) (a : α) (l : list α) : take (succ n) (a::l) = a :: take n l := rfl
theorem take_all : ∀ (l : list α), take (length l) l = l
| [] := rfl
| (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_all end
theorem take_all_of_ge : ∀ {n} {l : list α}, n ≥ length l → take n l = l
| 0 [] h := rfl
| 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _))
| (n+1) [] h := rfl
| (n+1) (a::l) h :=
begin
change a :: take n l = a :: l,
rw [take_all_of_ge (le_of_succ_le_succ h)]
end
@[simp] theorem take_left : ∀ l₁ l₂ : list α, take (length l₁) (l₁ ++ l₂) = l₁
| [] l₂ := rfl
| (a::l₁) l₂ := congr_arg (cons a) (take_left l₁ l₂)
theorem take_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) :
take n (l₁ ++ l₂) = l₁ :=
by rw ← h; apply take_left
theorem take_take : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l
| n 0 l := by rw [min_zero, take_zero, take_nil]
| 0 m l := by rw [zero_min, take_zero, take_zero]
| (succ n) (succ m) nil := by simp only [take_nil]
| (succ n) (succ m) (a::l) := by simp only [take, min_succ_succ, take_take n m l]; split; refl
@[simp] theorem drop_nil : ∀ n, drop n [] = ([] : list α)
| 0 := rfl
| (n+1) := rfl
@[simp] theorem drop_one : ∀ l : list α, drop 1 l = tail l
| [] := rfl
| (a :: l) := rfl
theorem drop_add : ∀ m n (l : list α), drop (m + n) l = drop m (drop n l)
| m 0 l := rfl
| m (n+1) [] := (drop_nil _).symm
| m (n+1) (a::l) := drop_add m n _
@[simp] theorem drop_left : ∀ l₁ l₂ : list α, drop (length l₁) (l₁ ++ l₂) = l₂
| [] l₂ := rfl
| (a::l₁) l₂ := drop_left l₁ l₂
theorem drop_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) :
drop n (l₁ ++ l₂) = l₂ :=
by rw ← h; apply drop_left
theorem drop_eq_nth_le_cons : ∀ {n} {l : list α} h,
drop n l = nth_le l n h :: drop (n+1) l
| 0 (a::l) h := rfl
| (n+1) (a::l) h := @drop_eq_nth_le_cons n _ _
@[simp] theorem drop_drop (n : ℕ) : ∀ (m) (l : list α), drop n (drop m l) = drop (n + m) l
| m [] := by simp
| 0 l := by simp
| (m+1) (a::l) :=
calc drop n (drop (m + 1) (a :: l)) = drop n (drop m l) : rfl
... = drop (n + m) l : drop_drop m l
... = drop (n + (m + 1)) (a :: l) : rfl
theorem drop_take : ∀ (m : ℕ) (n : ℕ) (l : list α),
drop m (take (m + n) l) = take n (drop m l)
| 0 n _ := by simp
| (m+1) n nil := by simp
| (m+1) n (_::l) :=
have h: m + 1 + n = (m+n) + 1, by simp,
by simpa [take_cons, h] using drop_take m n l
theorem modify_nth_tail_eq_take_drop (f : list α → list α) (H : f [] = []) :
∀ n l, modify_nth_tail f n l = take n l ++ f (drop n l)
| 0 l := rfl
| (n+1) [] := H.symm
| (n+1) (b::l) := congr_arg (cons b) (modify_nth_tail_eq_take_drop n l)
theorem modify_nth_eq_take_drop (f : α → α) :
∀ n l, modify_nth f n l = take n l ++ modify_head f (drop n l) :=
modify_nth_tail_eq_take_drop _ rfl
theorem modify_nth_eq_take_cons_drop (f : α → α) {n l} (h) :
modify_nth f n l = take n l ++ f (nth_le l n h) :: drop (n+1) l :=
by rw [modify_nth_eq_take_drop, drop_eq_nth_le_cons h]; refl
theorem update_nth_eq_take_cons_drop (a : α) {n l} (h : n < length l) :
update_nth l n a = take n l ++ a :: drop (n+1) l :=
by rw [update_nth_eq_modify_nth, modify_nth_eq_take_cons_drop _ h]
@[simp] lemma update_nth_eq_nil (l : list α) (n : ℕ) (a : α) : l.update_nth n a = [] ↔ l = [] :=
by cases l; cases n; simp only [update_nth]
section take'
variable [inhabited α]
def take' : ∀ n, list α → list α
| 0 l := []
| (n+1) l := l.head :: take' n l.tail
@[simp] theorem take'_length : ∀ n l, length (@take' α _ n l) = n
| 0 l := rfl
| (n+1) l := congr_arg succ (take'_length _ _)
@[simp] theorem take'_nil : ∀ n, take' n (@nil α) = repeat (default _) n
| 0 := rfl
| (n+1) := congr_arg (cons _) (take'_nil _)
theorem take'_eq_take : ∀ {n} {l : list α},
n ≤ length l → take' n l = take n l
| 0 l h := rfl
| (n+1) (a::l) h := congr_arg (cons _) $
take'_eq_take $ le_of_succ_le_succ h
@[simp] theorem take'_left (l₁ l₂ : list α) : take' (length l₁) (l₁ ++ l₂) = l₁ :=
(take'_eq_take (by simp only [length_append, nat.le_add_right])).trans (take_left _ _)
theorem take'_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) :
take' n (l₁ ++ l₂) = l₁ :=
by rw ← h; apply take'_left
end take'
/- take_while -/
/-- Get the longest initial segment of the list whose members all satisfy `p`.
`take_while (λ x, x < 3) [0, 2, 5, 1] = [0, 2]` -/
def take_while (p : α → Prop) [decidable_pred p] : list α → list α
| [] := []
| (a::l) := if p a then a :: take_while l else []
/- foldl, foldr, scanl, scanr -/
lemma foldl_ext (f g : α → β → α) (a : α)
{l : list β} (H : ∀ a : α, ∀ b ∈ l, f a b = g a b) :
foldl f a l = foldl g a l :=
begin
induction l with hd tl ih generalizing a, {refl},
unfold foldl,
rw [ih (λ a b bin, H a b $ mem_cons_of_mem _ bin), H a hd (mem_cons_self _ _)]
end
lemma foldr_ext (f g : α → β → β) (b : β)
{l : list α} (H : ∀ a ∈ l, ∀ b : β, f a b = g a b) :
foldr f b l = foldr g b l :=
begin
induction l with hd tl ih, {refl},
simp only [mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] at H,
simp only [foldr, ih H.2, H.1]
end
@[simp] theorem foldl_nil (f : α → β → α) (a : α) : foldl f a [] = a := rfl
@[simp] theorem foldl_cons (f : α → β → α) (a : α) (b : β) (l : list β) :
foldl f a (b::l) = foldl f (f a b) l := rfl
@[simp] theorem foldr_nil (f : α → β → β) (b : β) : foldr f b [] = b := rfl
@[simp] theorem foldr_cons (f : α → β → β) (b : β) (a : α) (l : list α) :
foldr f b (a::l) = f a (foldr f b l) := rfl
@[simp] theorem foldl_append (f : α → β → α) :
∀ (a : α) (l₁ l₂ : list β), foldl f a (l₁++l₂) = foldl f (foldl f a l₁) l₂
| a [] l₂ := rfl
| a (b::l₁) l₂ := by simp only [cons_append, foldl_cons, foldl_append (f a b) l₁ l₂]
@[simp] theorem foldr_append (f : α → β → β) :
∀ (b : β) (l₁ l₂ : list α), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁
| b [] l₂ := rfl
| b (a::l₁) l₂ := by simp only [cons_append, foldr_cons, foldr_append b l₁ l₂]
@[simp] theorem foldl_join (f : α → β → α) :
∀ (a : α) (L : list (list β)), foldl f a (join L) = foldl (foldl f) a L
| a [] := rfl
| a (l::L) := by simp only [join, foldl_append, foldl_cons, foldl_join (foldl f a l) L]
@[simp] theorem foldr_join (f : α → β → β) :
∀ (b : β) (L : list (list α)), foldr f b (join L) = foldr (λ l b, foldr f b l) b L
| a [] := rfl
| a (l::L) := by simp only [join, foldr_append, foldr_join a L, foldr_cons]
theorem foldl_reverse (f : α → β → α) (a : α) (l : list β) : foldl f a (reverse l) = foldr (λx y, f y x) a l :=
by induction l; [refl, simp only [*, reverse_cons, foldl_append, foldl_cons, foldl_nil, foldr]]
theorem foldr_reverse (f : α → β → β) (a : β) (l : list α) : foldr f a (reverse l) = foldl (λx y, f y x) a l :=
let t := foldl_reverse (λx y, f y x) a (reverse l) in
by rw reverse_reverse l at t; rwa t
@[simp] theorem foldr_eta : ∀ (l : list α), foldr cons [] l = l
| [] := rfl
| (x::l) := by simp only [foldr_cons, foldr_eta l]; split; refl
@[simp] theorem reverse_foldl {l : list α} : reverse (foldl (λ t h, h :: t) [] l) = l :=
by rw ←foldr_reverse; simp
/-- Fold a function `f` over the list from the left, returning the list
of partial results. `scanl (+) 0 [1, 2, 3] = [0, 1, 3, 6]` -/
def scanl (f : α → β → α) : α → list β → list α
| a [] := [a]
| a (b::l) := a :: scanl (f a b) l
def scanr_aux (f : α → β → β) (b : β) : list α → β × list β
| [] := (b, [])
| (a::l) := let (b', l') := scanr_aux l in (f a b', b' :: l')
/-- Fold a function `f` over the list from the right, returning the list
of partial results. `scanr (+) 0 [1, 2, 3] = [6, 5, 3, 0]` -/
def scanr (f : α → β → β) (b : β) (l : list α) : list β :=
let (b', l') := scanr_aux f b l in b' :: l'
@[simp] theorem scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] := rfl
@[simp] theorem scanr_aux_cons (f : α → β → β) (b : β) : ∀ (a : α) (l : list α),
scanr_aux f b (a::l) = (foldr f b (a::l), scanr f b l)
| a [] := rfl
| a (x::l) := let t := scanr_aux_cons x l in
by simp only [scanr, scanr_aux, t, foldr_cons]
@[simp] theorem scanr_cons (f : α → β → β) (b : β) (a : α) (l : list α) :
scanr f b (a::l) = foldr f b (a::l) :: scanr f b l :=
by simp only [scanr, scanr_aux_cons, foldr_cons]; split; refl
section foldl_eq_foldr
-- foldl and foldr coincide when f is commutative and associative
variables {f : α → α → α} (hcomm : commutative f) (hassoc : associative f)
include hassoc
theorem foldl1_eq_foldr1 : ∀ a b l, foldl f a (l++[b]) = foldr f b (a::l)
| a b nil := rfl
| a b (c :: l) := by simp only [cons_append, foldl_cons, foldr_cons, foldl1_eq_foldr1 _ _ l]; rw hassoc
include hcomm
theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l)
| a b nil := hcomm a b
| a b (c::l) := by simp only [foldl_cons];
rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; refl
theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l
| a nil := rfl
| a (b :: l) :=
by simp only [foldr_cons, foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l)
end foldl_eq_foldr
section
variables {op : α → α → α} [ha : is_associative α op] [hc : is_commutative α op]
local notation a * b := op a b
local notation l <*> a := foldl op a l
include ha
lemma foldl_assoc : ∀ {l : list α} {a₁ a₂}, l <*> (a₁ * a₂) = a₁ * (l <*> a₂)
| [] a₁ a₂ := rfl
| (a :: l) a₁ a₂ :=
calc a::l <*> (a₁ * a₂) = l <*> (a₁ * (a₂ * a)) : by simp only [foldl_cons, ha.assoc]
... = a₁ * (a::l <*> a₂) : by rw [foldl_assoc, foldl_cons]
lemma foldl_op_eq_op_foldr_assoc : ∀{l : list α} {a₁ a₂}, (l <*> a₁) * a₂ = a₁ * l.foldr (*) a₂
| [] a₁ a₂ := rfl
| (a :: l) a₁ a₂ := by simp only [foldl_cons, foldr_cons, foldl_assoc, ha.assoc]; rw [foldl_op_eq_op_foldr_assoc]
include hc
lemma foldl_assoc_comm_cons {l : list α} {a₁ a₂} : (a₁ :: l) <*> a₂ = a₁ * (l <*> a₂) :=
by rw [foldl_cons, hc.comm, foldl_assoc]
end
/- mfoldl, mfoldr -/
section mfoldl_mfoldr
variables {m : Type v → Type w} [monad m]
@[simp] theorem mfoldl_nil (f : β → α → m β) {b} : mfoldl f b [] = pure b := rfl
@[simp] theorem mfoldr_nil (f : α → β → m β) {b} : mfoldr f b [] = pure b := rfl
@[simp] theorem mfoldl_cons {f : β → α → m β} {b a l} :
mfoldl f b (a :: l) = f b a >>= λ b', mfoldl f b' l := rfl
@[simp] theorem mfoldr_cons {f : α → β → m β} {b a l} :
mfoldr f b (a :: l) = mfoldr f b l >>= f a := rfl
variables [is_lawful_monad m]
@[simp] theorem mfoldl_append {f : β → α → m β} : ∀ {b l₁ l₂},
mfoldl f b (l₁ ++ l₂) = mfoldl f b l₁ >>= λ x, mfoldl f x l₂
| _ [] _ := by simp only [nil_append, mfoldl_nil, pure_bind]
| _ (_::_) _ := by simp only [cons_append, mfoldl_cons, mfoldl_append, bind_assoc]
@[simp] theorem mfoldr_append {f : α → β → m β} : ∀ {b l₁ l₂},
mfoldr f b (l₁ ++ l₂) = mfoldr f b l₂ >>= λ x, mfoldr f x l₁
| _ [] _ := by simp only [nil_append, mfoldr_nil, bind_pure]
| _ (_::_) _ := by simp only [mfoldr_cons, cons_append, mfoldr_append, bind_assoc]
end mfoldl_mfoldr
/- sum -/
/-- Product of a list. `prod [a, b, c] = ((1 * a) * b) * c` -/
@[to_additive list.sum]
def prod [has_mul α] [has_one α] : list α → α := foldl (*) 1
attribute [to_additive list.sum.equations._eqn_1] list.prod.equations._eqn_1
section monoid
variables [monoid α] {l l₁ l₂ : list α} {a : α}
@[simp, to_additive list.sum_nil]
theorem prod_nil : ([] : list α).prod = 1 := rfl
@[simp, to_additive list.sum_cons]
theorem prod_cons : (a::l).prod = a * l.prod :=
calc (a::l).prod = foldl (*) (a * 1) l : by simp only [list.prod, foldl_cons, one_mul, mul_one]
... = _ : foldl_assoc
@[simp, to_additive list.sum_append]
theorem prod_append : (l₁ ++ l₂).prod = l₁.prod * l₂.prod :=
calc (l₁ ++ l₂).prod = foldl (*) (foldl (*) 1 l₁ * 1) l₂ : by simp [list.prod]
... = l₁.prod * l₂.prod : foldl_assoc
@[simp, to_additive list.sum_join]
theorem prod_join {l : list (list α)} : l.join.prod = (l.map list.prod).prod :=
by induction l; [refl, simp only [*, list.join, map, prod_append, prod_cons]]
end monoid
@[simp, to_additive list.sum_erase]
theorem prod_erase [decidable_eq α] [comm_monoid α] {a} :
Π {l : list α}, a ∈ l → a * (l.erase a).prod = l.prod
| (b::l) h :=
begin
rcases eq_or_ne_mem_of_mem h with rfl | ⟨ne, h⟩,
{ simp only [list.erase, if_pos, prod_cons] },
{ simp only [list.erase, if_neg (mt eq.symm ne), prod_cons, prod_erase h, mul_left_comm a b] }
end
lemma dvd_prod [comm_semiring α] {a} {l : list α} (ha : a ∈ l) : a ∣ l.prod :=
let ⟨s, t, h⟩ := mem_split ha in
by rw [h, prod_append, prod_cons, mul_left_comm]; exact dvd_mul_right _ _
@[simp] theorem sum_const_nat (m n : ℕ) : sum (list.repeat m n) = m * n :=
by induction n; [refl, simp only [*, repeat_succ, sum_cons, nat.mul_succ, add_comm]]
@[simp] theorem length_join (L : list (list α)) : length (join L) = sum (map length L) :=
by induction L; [refl, simp only [*, join, map, sum_cons, length_append]]
@[simp] theorem length_bind (l : list α) (f : α → list β) : length (list.bind l f) = sum (map (length ∘ f) l) :=
by rw [list.bind, length_join, map_map]
/- lexicographic ordering -/
inductive lex (r : α → α → Prop) : list α → list α → Prop
| nil {} {a l} : lex [] (a :: l)
| cons {a l₁ l₂} (h : lex l₁ l₂) : lex (a :: l₁) (a :: l₂)
| rel {a₁ l₁ a₂ l₂} (h : r a₁ a₂) : lex (a₁ :: l₁) (a₂ :: l₂)
namespace lex
theorem cons_iff {r : α → α → Prop} [is_irrefl α r] {a l₁ l₂} :
lex r (a :: l₁) (a :: l₂) ↔ lex r l₁ l₂ :=
⟨λ h, by cases h with _ _ _ _ _ h _ _ _ _ h;
[exact h, exact (irrefl_of r a h).elim], lex.cons⟩
instance is_order_connected (r : α → α → Prop)
[is_order_connected α r] [is_trichotomous α r] :
is_order_connected (list α) (lex r) :=
⟨λ l₁, match l₁ with
| _, [], c::l₃, nil := or.inr nil
| _, [], c::l₃, rel _ := or.inr nil
| _, [], c::l₃, cons _ := or.inr nil
| _, b::l₂, c::l₃, nil := or.inl nil
| a::l₁, b::l₂, c::l₃, rel h :=
(is_order_connected.conn _ b _ h).imp rel rel
| a::l₁, b::l₂, _::l₃, cons h := begin
rcases trichotomous_of r a b with ab | rfl | ab,
{ exact or.inl (rel ab) },
{ exact (_match _ l₂ _ h).imp cons cons },
{ exact or.inr (rel ab) }
end
end⟩
instance is_trichotomous (r : α → α → Prop) [is_trichotomous α r] :
is_trichotomous (list α) (lex r) :=
⟨λ l₁, match l₁ with
| [], [] := or.inr (or.inl rfl)
| [], b::l₂ := or.inl nil
| a::l₁, [] := or.inr (or.inr nil)
| a::l₁, b::l₂ := begin
rcases trichotomous_of r a b with ab | rfl | ab,
{ exact or.inl (rel ab) },
{ exact (_match l₁ l₂).imp cons
(or.imp (congr_arg _) cons) },
{ exact or.inr (or.inr (rel ab)) }
end
end⟩
instance is_asymm (r : α → α → Prop)
[is_asymm α r] : is_asymm (list α) (lex r) :=
⟨λ l₁, match l₁ with
| a::l₁, b::l₂, lex.rel h₁, lex.rel h₂ := asymm h₁ h₂
| a::l₁, b::l₂, lex.rel h₁, lex.cons h₂ := asymm h₁ h₁
| a::l₁, b::l₂, lex.cons h₁, lex.rel h₂ := asymm h₂ h₂
| a::l₁, b::l₂, lex.cons h₁, lex.cons h₂ :=
by exact _match _ _ h₁ h₂
end⟩
instance is_strict_total_order (r : α → α → Prop)
[is_strict_total_order' α r] : is_strict_total_order' (list α) (lex r) :=
{..is_strict_weak_order_of_is_order_connected}
instance decidable_rel [decidable_eq α] (r : α → α → Prop)
[decidable_rel r] : decidable_rel (lex r)
| l₁ [] := is_false $ λ h, by cases h
| [] (b::l₂) := is_true lex.nil
| (a::l₁) (b::l₂) := begin
haveI := decidable_rel l₁ l₂,
refine decidable_of_iff (r a b ∨ a = b ∧ lex r l₁ l₂) ⟨λ h, _, λ h, _⟩,
{ rcases h with h | ⟨rfl, h⟩,
{ exact lex.rel h },
{ exact lex.cons h } },
{ rcases h with _|⟨_,_,_,h⟩|⟨_,_,_,_,h⟩,
{ exact or.inr ⟨rfl, h⟩ },
{ exact or.inl h } }
end
theorem append_right (r : α → α → Prop) :
∀ {s₁ s₂} t, lex r s₁ s₂ → lex r s₁ (s₂ ++ t)
| _ _ t nil := nil
| _ _ t (cons h) := cons (append_right _ h)
| _ _ t (rel r) := rel r
theorem append_left (R : α → α → Prop) {t₁ t₂} (h : lex R t₁ t₂) :
∀ s, lex R (s ++ t₁) (s ++ t₂)
| [] := h
| (a::l) := cons (append_left l)
theorem imp {r s : α → α → Prop} (H : ∀ a b, r a b → s a b) :
∀ l₁ l₂, lex r l₁ l₂ → lex s l₁ l₂
| _ _ nil := nil
| _ _ (cons h) := cons (imp _ _ h)
| _ _ (rel r) := rel (H _ _ r)
theorem to_ne : ∀ {l₁ l₂ : list α}, lex (≠) l₁ l₂ → l₁ ≠ l₂
| _ _ (cons h) e := to_ne h (list.cons.inj e).2
| _ _ (rel r) e := r (list.cons.inj e).1
theorem ne_iff {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) :
lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ :=
⟨to_ne, λ h, begin
induction l₁ with a l₁ IH generalizing l₂; cases l₂ with b l₂,
{ contradiction },
{ apply nil },
{ exact (not_lt_of_ge H).elim (succ_pos _) },
{ cases classical.em (a = b) with ab ab,
{ subst b, apply cons,
exact IH (le_of_succ_le_succ H) (mt (congr_arg _) h) },
{ exact rel ab } }
end⟩
end lex
--Note: this overrides an instance in core lean
instance has_lt' [has_lt α] : has_lt (list α) := ⟨lex (<)⟩
theorem nil_lt_cons [has_lt α] (a : α) (l : list α) : [] < a :: l :=
lex.nil
instance [linear_order α] : linear_order (list α) :=
linear_order_of_STO' (lex (<))
--Note: this overrides an instance in core lean
instance has_le' [linear_order α] : has_le (list α) :=
preorder.to_has_le _
instance [decidable_linear_order α] : decidable_linear_order (list α) :=
decidable_linear_order_of_STO' (lex (<))
/- all & any -/
@[simp] theorem all_nil (p : α → bool) : all [] p = tt := rfl
@[simp] theorem all_cons (p : α → bool) (a : α) (l : list α) : all (a::l) p = (p a && all l p) := rfl
theorem all_iff_forall {p : α → bool} {l : list α} : all l p ↔ ∀ a ∈ l, p a :=
begin
induction l with a l ih,
{ exact iff_of_true rfl (forall_mem_nil _) },
simp only [all_cons, band_coe_iff, ih, forall_mem_cons]
end
theorem all_iff_forall_prop {p : α → Prop} [decidable_pred p]
{l : list α} : all l (λ a, p a) ↔ ∀ a ∈ l, p a :=
by simp only [all_iff_forall, bool.of_to_bool_iff]
@[simp] theorem any_nil (p : α → bool) : any [] p = ff := rfl
@[simp] theorem any_cons (p : α → bool) (a : α) (l : list α) : any (a::l) p = (p a || any l p) := rfl
theorem any_iff_exists {p : α → bool} {l : list α} : any l p ↔ ∃ a ∈ l, p a :=
begin
induction l with a l ih,
{ exact iff_of_false bool.not_ff (not_exists_mem_nil _) },
simp only [any_cons, bor_coe_iff, ih, exists_mem_cons_iff]
end
theorem any_iff_exists_prop {p : α → Prop} [decidable_pred p]
{l : list α} : any l (λ a, p a) ↔ ∃ a ∈ l, p a :=
by simp [any_iff_exists]
theorem any_of_mem {p : α → bool} {a : α} {l : list α} (h₁ : a ∈ l) (h₂ : p a) : any l p :=
any_iff_exists.2 ⟨_, h₁, h₂⟩
instance decidable_forall_mem {p : α → Prop} [decidable_pred p] (l : list α) :
decidable (∀ x ∈ l, p x) :=
decidable_of_iff _ all_iff_forall_prop
instance decidable_exists_mem {p : α → Prop} [decidable_pred p] (l : list α) :
decidable (∃ x ∈ l, p x) :=
decidable_of_iff _ any_iff_exists_prop
/- map for partial functions -/
/-- Partial map. If `f : Π a, p a → β` is a partial function defined on
`a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l`
but is defined only when all members of `l` satisfy `p`, using the proof
to apply `f`. -/
@[simp] def pmap {p : α → Prop} (f : Π a, p a → β) : Π l : list α, (∀ a ∈ l, p a) → list β
| [] H := []
| (a::l) H := f a (forall_mem_cons.1 H).1 :: pmap l (forall_mem_cons.1 H).2
/-- "Attach" the proof that the elements of `l` are in `l` to produce a new list
with the same elements but in the type `{x // x ∈ l}`. -/
def attach (l : list α) : list {x // x ∈ l} := pmap subtype.mk l (λ a, id)
theorem pmap_eq_map (p : α → Prop) (f : α → β) (l : list α) (H) :
@pmap _ _ p (λ a _, f a) l H = map f l :=
by induction l; [refl, simp only [*, pmap, map]]; split; refl
theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β}
(l : list α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) :
pmap f l H₁ = pmap g l H₂ :=
by induction l with _ _ ih; [refl, rw [pmap, pmap, h, ih]]
theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β)
(l H) : map g (pmap f l H) = pmap (λ a h, g (f a h)) l H :=
by induction l; [refl, simp only [*, pmap, map]]; split; refl
theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β)
(l H) : pmap f l H = l.attach.map (λ x, f x.1 (H _ x.2)) :=
by rw [attach, map_pmap]; exact pmap_congr l (λ a h₁ h₂, rfl)
theorem attach_map_val (l : list α) : l.attach.map subtype.val = l :=
by rw [attach, map_pmap]; exact (pmap_eq_map _ _ _ _).trans (map_id l)
@[simp] theorem mem_attach (l : list α) : ∀ x, x ∈ l.attach | ⟨a, h⟩ :=
by have := mem_map.1 (by rw [attach_map_val]; exact h);
{ rcases this with ⟨⟨_, _⟩, m, rfl⟩, exact m }
@[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β}
{l H b} : b ∈ pmap f l H ↔ ∃ a (h : a ∈ l), f a (H a h) = b :=
by simp only [pmap_eq_map_attach, mem_map, mem_attach, true_and, subtype.exists]
@[simp] theorem length_pmap {p : α → Prop} {f : Π a, p a → β}
{l H} : length (pmap f l H) = length l :=
by induction l; [refl, simp only [*, pmap, length]]
@[simp] lemma length_attach {α} (L : list α) : L.attach.length = L.length := length_pmap
/- find -/
section find
variables {p : α → Prop} [decidable_pred p] {l : list α} {a : α}
/-- `find p l` is the first element of `l` satisfying `p`, or `none` if no such
element exists. -/
def find (p : α → Prop) [decidable_pred p] : list α → option α
| [] := none
| (a::l) := if p a then some a else find l
def find_indexes_aux (p : α → Prop) [decidable_pred p] : list α → nat → list nat
| [] n := []
| (a::l) n := let t := find_indexes_aux l (succ n) in if p a then n :: t else t
/-- `find_indexes p l` is the list of indexes of elements of `l` that satisfy `p`. -/
def find_indexes (p : α → Prop) [decidable_pred p] (l : list α) : list nat :=
find_indexes_aux p l 0
@[simp] theorem find_nil (p : α → Prop) [decidable_pred p] : find p [] = none :=
rfl
@[simp] theorem find_cons_of_pos (l) (h : p a) : find p (a::l) = some a :=
if_pos h
@[simp] theorem find_cons_of_neg (l) (h : ¬ p a) : find p (a::l) = find p l :=
if_neg h
@[simp] theorem find_eq_none : find p l = none ↔ ∀ x ∈ l, ¬ p x :=
begin
induction l with a l IH,
{ exact iff_of_true rfl (forall_mem_nil _) },
rw forall_mem_cons, by_cases h : p a,
{ simp only [find_cons_of_pos _ h, h, not_true, false_and] },
{ rwa [find_cons_of_neg _ h, iff_true_intro h, true_and] }
end
@[simp] theorem find_some (H : find p l = some a) : p a :=
begin
induction l with b l IH, {contradiction},
by_cases h : p b,
{ rw find_cons_of_pos _ h at H, cases H, exact h },
{ rw find_cons_of_neg _ h at H, exact IH H }
end
@[simp] theorem find_mem (H : find p l = some a) : a ∈ l :=
begin
induction l with b l IH, {contradiction},
by_cases h : p b,
{ rw find_cons_of_pos _ h at H, cases H, apply mem_cons_self },
{ rw find_cons_of_neg _ h at H, exact mem_cons_of_mem _ (IH H) }
end
end find
/-- `indexes_of a l` is the list of all indexes of `a` in `l`.
`indexes_of a [a, b, a, a] = [0, 2, 3]` -/
def indexes_of [decidable_eq α] (a : α) : list α → list nat := find_indexes (eq a)
/- filter_map -/
@[simp] theorem filter_map_nil (f : α → option β) : filter_map f [] = [] := rfl
@[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (l : list α) (h : f a = none) :
filter_map f (a :: l) = filter_map f l :=
by simp only [filter_map, h]
@[simp] theorem filter_map_cons_some (f : α → option β)
(a : α) (l : list α) {b : β} (h : f a = some b) :
filter_map f (a :: l) = b :: filter_map f l :=
by simp only [filter_map, h]; split; refl
theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f :=
begin
funext l,
induction l with a l IH, {refl},
simp only [filter_map_cons_some (some ∘ f) _ _ rfl, IH, map_cons], split; refl
end
theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] :
filter_map (option.guard p) = filter p :=
begin
funext l,
induction l with a l IH, {refl},
by_cases pa : p a,
{ simp only [filter_map, option.guard, IH, if_pos pa, filter_cons_of_pos _ pa], split; refl },
{ simp only [filter_map, option.guard, IH, if_neg pa, filter_cons_of_neg _ pa] }
end
theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (l : list α) :
filter_map g (filter_map f l) = filter_map (λ x, (f x).bind g) l :=
begin
induction l with a l IH, {refl},
cases h : f a with b,
{ rw [filter_map_cons_none _ _ h, filter_map_cons_none, IH],
simp only [h, option.none_bind'] },
rw filter_map_cons_some _ _ _ h,
cases h' : g b with c;
[ rw [filter_map_cons_none _ _ h', filter_map_cons_none, IH],
rw [filter_map_cons_some _ _ _ h', filter_map_cons_some, IH] ];
simp only [h, h', option.some_bind']
end
theorem map_filter_map (f : α → option β) (g : β → γ) (l : list α) :
map g (filter_map f l) = filter_map (λ x, (f x).map g) l :=
by rw [← filter_map_eq_map, filter_map_filter_map]; refl
theorem filter_map_map (f : α → β) (g : β → option γ) (l : list α) :
filter_map g (map f l) = filter_map (g ∘ f) l :=
by rw [← filter_map_eq_map, filter_map_filter_map]; refl
theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (l : list α) :
filter p (filter_map f l) = filter_map (λ x, (f x).filter p) l :=
by rw [← filter_map_eq_filter, filter_map_filter_map]; refl
theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (l : list α) :
filter_map f (filter p l) = filter_map (λ x, if p x then f x else none) l :=
begin
rw [← filter_map_eq_filter, filter_map_filter_map], congr,
funext x,
show (option.guard p x).bind f = ite (p x) (f x) none,
by_cases h : p x,
{ simp only [option.guard, if_pos h, option.some_bind'] },
{ simp only [option.guard, if_neg h, option.none_bind'] }
end
@[simp] theorem filter_map_some (l : list α) : filter_map some l = l :=
by rw filter_map_eq_map; apply map_id
@[simp] theorem mem_filter_map (f : α → option β) (l : list α) {b : β} :
b ∈ filter_map f l ↔ ∃ a, a ∈ l ∧ f a = some b :=
begin
induction l with a l IH,
{ split, { intro H, cases H }, { rintro ⟨_, H, _⟩, cases H } },
cases h : f a with b',
{ have : f a ≠ some b, {rw h, intro, contradiction},
simp only [filter_map_cons_none _ _ h, IH, mem_cons_iff,
or_and_distrib_right, exists_or_distrib, exists_eq_left, this, false_or] },
{ have : f a = some b ↔ b = b',
{ split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} },
simp only [filter_map_cons_some _ _ _ h, IH, mem_cons_iff,
or_and_distrib_right, exists_or_distrib, this, exists_eq_left] }
end
theorem map_filter_map_of_inv (f : α → option β) (g : β → α)
(H : ∀ x : α, (f x).map g = some x) (l : list α) :
map g (filter_map f l) = l :=
by simp only [map_filter_map, H, filter_map_some]
theorem filter_map_sublist_filter_map (f : α → option β) {l₁ l₂ : list α}
(s : l₁ <+ l₂) : filter_map f l₁ <+ filter_map f l₂ :=
by induction s with l₁ l₂ a s IH l₁ l₂ a s IH;
simp only [filter_map]; cases f a with b;
simp only [filter_map, IH, sublist.cons, sublist.cons2]
theorem map_sublist_map (f : α → β) {l₁ l₂ : list α}
(s : l₁ <+ l₂) : map f l₁ <+ map f l₂ :=
by rw ← filter_map_eq_map; exact filter_map_sublist_filter_map _ s
/- filter -/
section filter
variables {p : α → Prop} [decidable_pred p]
lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q]
: ∀ {l : list α}, (∀ x ∈ l, p x ↔ q x) → filter p l = filter q l
| [] _ := rfl
| (a::l) h := by rw forall_mem_cons at h; by_cases pa : p a;
[simp only [filter_cons_of_pos _ pa, filter_cons_of_pos _ (h.1.1 pa), filter_congr h.2],
simp only [filter_cons_of_neg _ pa, filter_cons_of_neg _ (mt h.1.2 pa), filter_congr h.2]]; split; refl
@[simp] theorem filter_subset (l : list α) : filter p l ⊆ l :=
subset_of_sublist $ filter_sublist l
theorem of_mem_filter {a : α} : ∀ {l}, a ∈ filter p l → p a
| (b::l) ain :=
if pb : p b then
have a ∈ b :: filter p l, by simpa only [filter_cons_of_pos _ pb] using ain,
or.elim (eq_or_mem_of_mem_cons this)
(assume : a = b, begin rw [← this] at pb, exact pb end)
(assume : a ∈ filter p l, of_mem_filter this)
else
begin simp only [filter_cons_of_neg _ pb] at ain, exact (of_mem_filter ain) end
theorem mem_of_mem_filter {a : α} {l} (h : a ∈ filter p l) : a ∈ l :=
filter_subset l h
theorem mem_filter_of_mem {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l
| (_::l) (or.inl rfl) pa := by rw filter_cons_of_pos _ pa; apply mem_cons_self
| (b::l) (or.inr ain) pa := if pb : p b
then by rw [filter_cons_of_pos _ pb]; apply mem_cons_of_mem; apply mem_filter_of_mem ain pa
else by rw [filter_cons_of_neg _ pb]; apply mem_filter_of_mem ain pa
@[simp] theorem mem_filter {a : α} {l} : a ∈ filter p l ↔ a ∈ l ∧ p a :=
⟨λ h, ⟨mem_of_mem_filter h, of_mem_filter h⟩, λ ⟨h₁, h₂⟩, mem_filter_of_mem h₁ h₂⟩
theorem filter_eq_self {l} : filter p l = l ↔ ∀ a ∈ l, p a :=
begin
induction l with a l ih,
{ exact iff_of_true rfl (forall_mem_nil _) },
rw forall_mem_cons, by_cases p a,
{ rw [filter_cons_of_pos _ h, cons_inj', ih, and_iff_right h] },
{ rw [filter_cons_of_neg _ h],
refine iff_of_false _ (mt and.left h), intro e,
have := filter_sublist l, rw e at this,
exact not_lt_of_ge (length_le_of_sublist this) (lt_succ_self _) }
end
theorem filter_eq_nil {l} : filter p l = [] ↔ ∀ a ∈ l, ¬p a :=
by simp only [eq_nil_iff_forall_not_mem, mem_filter, not_and]
theorem filter_sublist_filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ :=
by rw ← filter_map_eq_filter; exact filter_map_sublist_filter_map _ s
theorem filter_of_map (f : β → α) (l) : filter p (map f l) = map f (filter (p ∘ f) l) :=
by rw [← filter_map_eq_map, filter_filter_map, filter_map_filter]; refl
@[simp] theorem filter_filter {q} [decidable_pred q] : ∀ l,
filter p (filter q l) = filter (λ a, p a ∧ q a) l
| [] := rfl
| (a :: l) := by by_cases hp : p a; by_cases hq : q a; simp only [hp, hq, filter, if_true, if_false,
true_and, false_and, filter_filter l, eq_self_iff_true]
@[simp] theorem span_eq_take_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), span p l = (take_while p l, drop_while p l)
| [] := rfl
| (a::l) := if pa : p a then by simp only [span, if_pos pa, span_eq_take_drop l, take_while, drop_while]
else by simp only [span, take_while, drop_while, if_neg pa]
@[simp] theorem take_while_append_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), take_while p l ++ drop_while p l = l
| [] := rfl
| (a::l) := if pa : p a then by rw [take_while, drop_while, if_pos pa, if_pos pa, cons_append, take_while_append_drop l]
else by rw [take_while, drop_while, if_neg pa, if_neg pa, nil_append]
/-- `countp p l` is the number of elements of `l` that satisfy `p`. -/
def countp (p : α → Prop) [decidable_pred p] : list α → nat
| [] := 0
| (x::xs) := if p x then succ (countp xs) else countp xs
@[simp] theorem countp_nil (p : α → Prop) [decidable_pred p] : countp p [] = 0 := rfl
@[simp] theorem countp_cons_of_pos {a : α} (l) (pa : p a) : countp p (a::l) = countp p l + 1 :=
if_pos pa
@[simp] theorem countp_cons_of_neg {a : α} (l) (pa : ¬ p a) : countp p (a::l) = countp p l :=
if_neg pa
theorem countp_eq_length_filter (l) : countp p l = length (filter p l) :=
by induction l with x l ih; [refl, by_cases (p x)]; [simp only [filter_cons_of_pos _ h, countp, ih, if_pos h],
simp only [countp_cons_of_neg _ h, ih, filter_cons_of_neg _ h]]; refl
local attribute [simp] countp_eq_length_filter
@[simp] theorem countp_append (l₁ l₂) : countp p (l₁ ++ l₂) = countp p l₁ + countp p l₂ :=
by simp only [countp_eq_length_filter, filter_append, length_append]
theorem countp_pos {l} : 0 < countp p l ↔ ∃ a ∈ l, p a :=
by simp only [countp_eq_length_filter, length_pos_iff_exists_mem, mem_filter, exists_prop]
theorem countp_le_of_sublist {l₁ l₂} (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ :=
by simpa only [countp_eq_length_filter] using length_le_of_sublist (filter_sublist_filter s)
@[simp] theorem countp_filter {q} [decidable_pred q] (l : list α) :
countp p (filter q l) = countp (λ a, p a ∧ q a) l :=
by simp only [countp_eq_length_filter, filter_filter]
end filter
/- count -/
section count
variable [decidable_eq α]
/-- `count a l` is the number of occurrences of `a` in `l`. -/
def count (a : α) : list α → nat := countp (eq a)
@[simp] theorem count_nil (a : α) : count a [] = 0 := rfl
theorem count_cons (a b : α) (l : list α) :
count a (b :: l) = if a = b then succ (count a l) else count a l := rfl
theorem count_cons' (a b : α) (l : list α) :
count a (b :: l) = count a l + (if a = b then 1 else 0) :=
begin rw count_cons, split_ifs; refl end
@[simp] theorem count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) :=
if_pos rfl
@[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l :=
if_neg h
theorem count_le_of_sublist (a : α) {l₁ l₂} : l₁ <+ l₂ → count a l₁ ≤ count a l₂ :=
countp_le_of_sublist
theorem count_le_count_cons (a b : α) (l : list α) : count a l ≤ count a (b :: l) :=
count_le_of_sublist _ (sublist_cons _ _)
theorem count_singleton (a : α) : count a [a] = 1 := if_pos rfl
@[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ :=
countp_append
@[simp] theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) :=
by rw [concat_eq_append, count_append, count_singleton]
theorem count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l :=
by simp only [count, countp_pos, exists_prop, exists_eq_right']
@[simp] theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 :=
by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h')
theorem not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l :=
λ h', ne_of_gt (count_pos.2 h') h
@[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n :=
by rw [count, countp_eq_length_filter, filter_eq_self.2, length_repeat];
exact λ b m, (eq_of_mem_repeat m).symm
theorem le_count_iff_repeat_sublist {a : α} {l : list α} {n : ℕ} : n ≤ count a l ↔ repeat a n <+ l :=
⟨λ h, ((repeat_sublist_repeat a).2 h).trans $
have filter (eq a) l = repeat a (count a l), from eq_repeat.2
⟨by simp only [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩,
by rw ← this; apply filter_sublist,
λ h, by simpa only [count_repeat] using count_le_of_sublist a h⟩
@[simp] theorem count_filter {p} [decidable_pred p]
{a} {l : list α} (h : p a) : count a (filter p l) = count a l :=
by simp only [count, countp_filter]; congr; exact
set.ext (λ b, and_iff_left_of_imp (λ e, e ▸ h))
end count
/- prefix, suffix, infix -/
/-- `is_prefix l₁ l₂`, or `l₁ <+: l₂`, means that `l₁` is a prefix of `l₂`,
that is, `l₂` has the form `l₁ ++ t` for some `t`. -/
def is_prefix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, l₁ ++ t = l₂
/-- `is_suffix l₁ l₂`, or `l₁ <:+ l₂`, means that `l₁` is a suffix of `l₂`,
that is, `l₂` has the form `t ++ l₁` for some `t`. -/
def is_suffix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, t ++ l₁ = l₂
/-- `is_infix l₁ l₂`, or `l₁ <:+: l₂`, means that `l₁` is a contiguous
substring of `l₂`, that is, `l₂` has the form `s ++ l₁ ++ t` for some `s, t`. -/
def is_infix (l₁ : list α) (l₂ : list α) : Prop := ∃ s t, s ++ l₁ ++ t = l₂
infix ` <+: `:50 := is_prefix
infix ` <:+ `:50 := is_suffix
infix ` <:+: `:50 := is_infix
@[simp] theorem prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩
@[simp] theorem suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩
@[simp] theorem infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩
theorem nil_prefix (l : list α) : [] <+: l := ⟨l, rfl⟩
theorem nil_suffix (l : list α) : [] <:+ l := ⟨l, append_nil _⟩
@[refl] theorem prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩
@[refl] theorem suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩
@[simp] theorem suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a]
@[simp] theorem prefix_concat (a : α) (l) : l <+: concat l a :=
by simp only [concat_eq_append, prefix_append]
theorem infix_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <:+: l₂ :=
λ⟨t, h⟩, ⟨[], t, h⟩
theorem infix_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <:+: l₂ :=
λ⟨t, h⟩, ⟨t, [], by simp only [h, append_nil]⟩
@[refl] theorem infix_refl (l : list α) : l <:+: l := infix_of_prefix $ prefix_refl l
theorem nil_infix (l : list α) : [] <:+: l := infix_of_prefix $ nil_prefix l
theorem infix_cons {L₁ L₂ : list α} {x : α} : L₁ <:+: L₂ → L₁ <:+: x :: L₂ :=
λ⟨LP, LS, H⟩, ⟨x :: LP, LS, H ▸ rfl⟩
@[trans] theorem is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃
| l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, (append_assoc _ _ _).symm⟩
@[trans] theorem is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃
| l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, append_assoc _ _ _⟩
@[trans] theorem is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃
| l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp only [append_assoc]⟩
theorem sublist_of_infix {l₁ l₂ : list α} : l₁ <:+: l₂ → l₁ <+ l₂ :=
λ⟨s, t, h⟩, by rw [← h]; exact (sublist_append_right _ _).trans (sublist_append_left _ _)
theorem sublist_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <+ l₂ :=
sublist_of_infix ∘ infix_of_prefix
theorem sublist_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <+ l₂ :=
sublist_of_infix ∘ infix_of_suffix
theorem reverse_suffix {l₁ l₂ : list α} : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ :=
⟨λ ⟨r, e⟩, ⟨reverse r,
by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩,
λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_append, e]⟩⟩
theorem reverse_prefix {l₁ l₂ : list α} : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ :=
by rw ← reverse_suffix; simp only [reverse_reverse]
theorem length_le_of_infix {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ ≤ length l₂ :=
length_le_of_sublist $ sublist_of_infix s
theorem eq_nil_of_infix_nil {l : list α} (s : l <:+: []) : l = [] :=
eq_nil_of_sublist_nil $ sublist_of_infix s
theorem eq_nil_of_prefix_nil {l : list α} (s : l <+: []) : l = [] :=
eq_nil_of_infix_nil $ infix_of_prefix s
theorem eq_nil_of_suffix_nil {l : list α} (s : l <:+ []) : l = [] :=
eq_nil_of_infix_nil $ infix_of_suffix s
theorem infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ :=
⟨λ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩,
λ⟨._, ⟨t, rfl⟩, ⟨s, e⟩⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩
theorem eq_of_infix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_infix s
theorem eq_of_prefix_of_length_eq {l₁ l₂ : list α} (s : l₁ <+: l₂) : length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_prefix s
theorem eq_of_suffix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+ l₂) : length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_suffix s
theorem prefix_of_prefix_length_le : ∀ {l₁ l₂ l₃ : list α},
l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂
| [] l₂ l₃ h₁ h₂ _ := nil_prefix _
| (a::l₁) (b::l₂) _ ⟨r₁, rfl⟩ ⟨r₂, e⟩ ll := begin
injection e with _ e', subst b,
rcases prefix_of_prefix_length_le ⟨_, rfl⟩ ⟨_, e'⟩
(le_of_succ_le_succ ll) with ⟨r₃, rfl⟩,
exact ⟨r₃, rfl⟩
end
theorem prefix_or_prefix_of_prefix {l₁ l₂ l₃ : list α}
(h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ :=
(le_total (length l₁) (length l₂)).imp
(prefix_of_prefix_length_le h₁ h₂)
(prefix_of_prefix_length_le h₂ h₁)
theorem suffix_of_suffix_length_le {l₁ l₂ l₃ : list α}
(h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) : l₁ <:+ l₂ :=
reverse_prefix.1 $ prefix_of_prefix_length_le
(reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll])
theorem suffix_or_suffix_of_suffix {l₁ l₂ l₃ : list α}
(h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ :=
(prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp
reverse_prefix.1 reverse_prefix.1
theorem infix_of_mem_join : ∀ {L : list (list α)} {l}, l ∈ L → l <:+: join L
| (_ :: L) l (or.inl rfl) := infix_append [] _ _
| (l' :: L) l (or.inr h) :=
is_infix.trans (infix_of_mem_join h) $ infix_of_suffix $ suffix_append _ _
theorem prefix_append_left_inj {l₁ l₂ : list α} (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ :=
exists_congr $ λ r, by rw [append_assoc, append_left_inj]
theorem prefix_cons_inj {l₁ l₂ : list α} (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ :=
prefix_append_left_inj [a]
theorem take_prefix (n) (l : list α) : take n l <+: l := ⟨_, take_append_drop _ _⟩
theorem drop_suffix (n) (l : list α) : drop n l <:+ l := ⟨_, take_append_drop _ _⟩
theorem prefix_iff_eq_append {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ :=
⟨by rintros ⟨r, rfl⟩; rw drop_left, λ e, ⟨_, e⟩⟩
theorem suffix_iff_eq_append {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ :=
⟨by rintros ⟨r, rfl⟩; simp only [length_append, nat.add_sub_cancel, take_left], λ e, ⟨_, e⟩⟩
theorem prefix_iff_eq_take {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ :=
⟨λ h, append_right_cancel $
(prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,
λ e, e.symm ▸ take_prefix _ _⟩
theorem suffix_iff_eq_drop {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ :=
⟨λ h, append_left_cancel $
(suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,
λ e, e.symm ▸ drop_suffix _ _⟩
instance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂)
| [] l₂ := is_true ⟨l₂, rfl⟩
| (a::l₁) [] := is_false $ λ ⟨t, te⟩, list.no_confusion te
| (a::l₁) (b::l₂) :=
if h : a = b then
@decidable_of_iff _ _ (by rw [← h, prefix_cons_inj])
(decidable_prefix l₁ l₂)
else
is_false $ λ ⟨t, te⟩, h $ by injection te
-- Alternatively, use mem_tails
instance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂)
| [] l₂ := is_true ⟨l₂, append_nil _⟩
| (a::l₁) [] := is_false $ mt (length_le_of_sublist ∘ sublist_of_suffix) dec_trivial
| l₁ l₂ := let len1 := length l₁, len2 := length l₂ in
if hl : len1 ≤ len2 then
decidable_of_iff' (l₁ = drop (len2-len1) l₂) suffix_iff_eq_drop
else is_false $ λ h, hl $ length_le_of_sublist $ sublist_of_suffix h
/-- `inits l` is the list of initial segments of `l`.
`inits [1, 2, 3] = [[], [1], [1, 2], [1, 2, 3]]` -/
@[simp] def inits : list α → list (list α)
| [] := [[]]
| (a::l) := [] :: map (λt, a::t) (inits l)
@[simp] theorem mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t
| s [] := suffices s = nil ↔ s <+: nil, by simpa only [inits, mem_singleton],
⟨λh, h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩
| s (a::t) :=
suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t, by simpa,
⟨λo, match s, o with
| ._, or.inl rfl := ⟨_, rfl⟩
| s, or.inr ⟨r, hr, hs⟩ := let ⟨s, ht⟩ := (mem_inits _ _).1 hr in
by rw [← hs, ← ht]; exact ⟨s, rfl⟩
end, λmi, match s, mi with
| [], ⟨._, rfl⟩ := or.inl rfl
| (b::s), ⟨r, hr⟩ := list.no_confusion hr $ λba (st : s++r = t), or.inr $
by rw ba; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩
end⟩
/-- `tails l` is the list of terminal segments of `l`.
`tails [1, 2, 3] = [[1, 2, 3], [2, 3], [3], []]` -/
@[simp] def tails : list α → list (list α)
| [] := [[]]
| (a::l) := (a::l) :: tails l
@[simp] theorem mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t
| s [] := by simp only [tails, mem_singleton]; exact ⟨λh, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩
| s (a::t) := by simp only [tails, mem_cons_iff, mem_tails s t]; exact show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t, from
⟨λo, match s, t, o with
| ._, t, or.inl rfl := suffix_refl _
| s, ._, or.inr ⟨l, rfl⟩ := ⟨a::l, rfl⟩
end, λe, match s, t, e with
| ._, t, ⟨[], rfl⟩ := or.inl rfl
| s, t, ⟨b::l, he⟩ := list.no_confusion he (λab lt, or.inr ⟨l, lt⟩)
end⟩
instance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂)
| [] l₂ := is_true ⟨[], l₂, rfl⟩
| (a::l₁) [] := is_false $ λ⟨s, t, te⟩, absurd te $ append_ne_nil_of_ne_nil_left _ _ $
append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h
| l₁ l₂ := decidable_of_decidable_of_iff (list.decidable_bex (λt, l₁ <+: t) (tails l₂)) $
by refine (exists_congr (λt, _)).trans (infix_iff_prefix_suffix _ _).symm;
exact ⟨λ⟨h1, h2⟩, ⟨h2, (mem_tails _ _).1 h1⟩, λ⟨h2, h1⟩, ⟨(mem_tails _ _).2 h1, h2⟩⟩
/- sublists -/
def sublists'_aux : list α → (list α → list β) → list (list β) → list (list β)
| [] f r := f [] :: r
| (a::l) f r := sublists'_aux l f (sublists'_aux l (f ∘ cons a) r)
/-- `sublists' l` is the list of all (non-contiguous) sublists of `l`.
It differs from `sublists` only in the order of appearance of the sublists;
`sublists'` uses the first element of the list as the MSB,
`sublists` uses the first element of the list as the LSB.
`sublists' [1, 2, 3] = [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]` -/
def sublists' (l : list α) : list (list α) :=
sublists'_aux l id []
@[simp] theorem sublists'_nil : sublists' (@nil α) = [[]] := rfl
@[simp] theorem sublists'_singleton (a : α) : sublists' [a] = [[], [a]] := rfl
theorem map_sublists'_aux (g : list β → list γ) (l : list α) (f r) :
map g (sublists'_aux l f r) = sublists'_aux l (g ∘ f) (map g r) :=
by induction l generalizing f r; [refl, simp only [*, sublists'_aux]]
theorem sublists'_aux_append (r' : list (list β)) (l : list α) (f r) :
sublists'_aux l f (r ++ r') = sublists'_aux l f r ++ r' :=
by induction l generalizing f r; [refl, simp only [*, sublists'_aux]]
theorem sublists'_aux_eq_sublists' (l f r) :
@sublists'_aux α β l f r = map f (sublists' l) ++ r :=
by rw [sublists', map_sublists'_aux, ← sublists'_aux_append]; refl
@[simp] theorem sublists'_cons (a : α) (l : list α) :
sublists' (a :: l) = sublists' l ++ map (cons a) (sublists' l) :=
by rw [sublists', sublists'_aux]; simp only [sublists'_aux_eq_sublists', map_id, append_nil]; refl
@[simp] theorem mem_sublists' {s t : list α} : s ∈ sublists' t ↔ s <+ t :=
begin
induction t with a t IH generalizing s,
{ simp only [sublists'_nil, mem_singleton],
exact ⟨λ h, by rw h, eq_nil_of_sublist_nil⟩ },
simp only [sublists'_cons, mem_append, IH, mem_map],
split; intro h, rcases h with h | ⟨s, h, rfl⟩,
{ exact sublist_cons_of_sublist _ h },
{ exact cons_sublist_cons _ h },
{ cases h with _ _ _ h s _ _ h,
{ exact or.inl h },
{ exact or.inr ⟨s, h, rfl⟩ } }
end
@[simp] theorem length_sublists' : ∀ l : list α, length (sublists' l) = 2 ^ length l
| [] := rfl
| (a::l) := by simp only [sublists'_cons, length_append, length_sublists' l, length_map,
length, pow_succ, mul_succ, mul_zero, zero_add]
def sublists_aux : list α → (list α → list β → list β) → list β
| [] f := []
| (a::l) f := f [a] (sublists_aux l (λys r, f ys (f (a :: ys) r)))
/-- `sublists l` is the list of all (non-contiguous) sublists of `l`.
`sublists [1, 2, 3] = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]` -/
def sublists (l : list α) : list (list α) :=
[] :: sublists_aux l cons
@[simp] theorem sublists_nil : sublists (@nil α) = [[]] := rfl
@[simp] theorem sublists_singleton (a : α) : sublists [a] = [[], [a]] := rfl
def sublists_aux₁ : list α → (list α → list β) → list β
| [] f := []
| (a::l) f := f [a] ++ sublists_aux₁ l (λys, f ys ++ f (a :: ys))
theorem sublists_aux₁_eq_sublists_aux : ∀ l (f : list α → list β),
sublists_aux₁ l f = sublists_aux l (λ ys r, f ys ++ r)
| [] f := rfl
| (a::l) f := by rw [sublists_aux₁, sublists_aux]; simp only [*, append_assoc]
theorem sublists_aux_cons_eq_sublists_aux₁ (l : list α) :
sublists_aux l cons = sublists_aux₁ l (λ x, [x]) :=
by rw [sublists_aux₁_eq_sublists_aux]; refl
theorem sublists_aux_eq_foldr.aux {a : α} {l : list α}
(IH₁ : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons))
(IH₂ : ∀ (f : list α → list (list α) → list (list α)),
sublists_aux l f = foldr f [] (sublists_aux l cons))
(f : list α → list β → list β) : sublists_aux (a::l) f = foldr f [] (sublists_aux (a::l) cons) :=
begin
simp only [sublists_aux, foldr_cons], rw [IH₂, IH₁], congr' 1,
induction sublists_aux l cons with _ _ ih, {refl},
simp only [ih, foldr_cons]
end
theorem sublists_aux_eq_foldr (l : list α) : ∀ (f : list α → list β → list β),
sublists_aux l f = foldr f [] (sublists_aux l cons) :=
suffices _ ∧ ∀ f : list α → list (list α) → list (list α),
sublists_aux l f = foldr f [] (sublists_aux l cons),
from this.1,
begin
induction l with a l IH, {split; intro; refl},
exact ⟨sublists_aux_eq_foldr.aux IH.1 IH.2,
sublists_aux_eq_foldr.aux IH.2 IH.2⟩
end
theorem sublists_aux_cons_cons (l : list α) (a : α) :
sublists_aux (a::l) cons = [a] :: foldr (λys r, ys :: (a :: ys) :: r) [] (sublists_aux l cons) :=
by rw [← sublists_aux_eq_foldr]; refl
theorem sublists_aux₁_append : ∀ (l₁ l₂ : list α) (f : list α → list β),
sublists_aux₁ (l₁ ++ l₂) f = sublists_aux₁ l₁ f ++
sublists_aux₁ l₂ (λ x, f x ++ sublists_aux₁ l₁ (f ∘ (++ x)))
| [] l₂ f := by simp only [sublists_aux₁, nil_append, append_nil]
| (a::l₁) l₂ f := by simp only [sublists_aux₁, cons_append, sublists_aux₁_append l₁, append_assoc]; refl
theorem sublists_aux₁_concat (l : list α) (a : α) (f : list α → list β) :
sublists_aux₁ (l ++ [a]) f = sublists_aux₁ l f ++
f [a] ++ sublists_aux₁ l (λ x, f (x ++ [a])) :=
by simp only [sublists_aux₁_append, sublists_aux₁, append_assoc, append_nil]
theorem sublists_aux₁_bind : ∀ (l : list α)
(f : list α → list β) (g : β → list γ),
(sublists_aux₁ l f).bind g = sublists_aux₁ l (λ x, (f x).bind g)
| [] f g := rfl
| (a::l) f g := by simp only [sublists_aux₁, bind_append, sublists_aux₁_bind l]
theorem sublists_aux_cons_append (l₁ l₂ : list α) :
sublists_aux (l₁ ++ l₂) cons = sublists_aux l₁ cons ++
(do x ← sublists_aux l₂ cons, (++ x) <$> sublists l₁) :=
begin
simp only [sublists, sublists_aux_cons_eq_sublists_aux₁, sublists_aux₁_append, bind_eq_bind, sublists_aux₁_bind],
congr, funext x, apply congr_arg _,
rw [← bind_ret_eq_map, sublists_aux₁_bind], exact (append_nil _).symm
end
theorem sublists_append (l₁ l₂ : list α) :
sublists (l₁ ++ l₂) = (do x ← sublists l₂, (++ x) <$> sublists l₁) :=
by simp only [map, sublists, sublists_aux_cons_append, map_eq_map, bind_eq_bind,
cons_bind, map_id', append_nil, cons_append, map_id' (λ _, rfl)]; split; refl
@[simp] theorem sublists_concat (l : list α) (a : α) :
sublists (l ++ [a]) = sublists l ++ map (λ x, x ++ [a]) (sublists l) :=
by rw [sublists_append, sublists_singleton, bind_eq_bind, cons_bind, cons_bind, nil_bind,
map_eq_map, map_eq_map, map_id' (append_nil), append_nil]
theorem sublists_reverse (l : list α) : sublists (reverse l) = map reverse (sublists' l) :=
by induction l with hd tl ih; [refl,
simp only [reverse_cons, sublists_append, sublists'_cons, map_append, ih, sublists_singleton,
map_eq_map, bind_eq_bind, map_map, cons_bind, append_nil, nil_bind, (∘)]]
theorem sublists_eq_sublists' (l : list α) : sublists l = map reverse (sublists' (reverse l)) :=
by rw [← sublists_reverse, reverse_reverse]
theorem sublists'_reverse (l : list α) : sublists' (reverse l) = map reverse (sublists l) :=
by simp only [sublists_eq_sublists', map_map, map_id' (reverse_reverse)]
theorem sublists'_eq_sublists (l : list α) : sublists' l = map reverse (sublists (reverse l)) :=
by rw [← sublists'_reverse, reverse_reverse]
theorem sublists_aux_ne_nil : ∀ (l : list α), [] ∉ sublists_aux l cons
| [] := id
| (a::l) := begin
rw [sublists_aux_cons_cons],
refine not_mem_cons_of_ne_of_not_mem (cons_ne_nil _ _).symm _,
have := sublists_aux_ne_nil l, revert this,
induction sublists_aux l cons; intro, {rwa foldr},
simp only [foldr, mem_cons_iff, false_or, not_or_distrib],
exact ⟨ne_of_not_mem_cons this, ih (not_mem_of_not_mem_cons this)⟩
end
@[simp] theorem mem_sublists {s t : list α} : s ∈ sublists t ↔ s <+ t :=
by rw [← reverse_sublist_iff, ← mem_sublists',
sublists'_reverse, mem_map_of_inj reverse_injective]
@[simp] theorem length_sublists (l : list α) : length (sublists l) = 2 ^ length l :=
by simp only [sublists_eq_sublists', length_map, length_sublists', length_reverse]
theorem map_ret_sublist_sublists (l : list α) : map list.ret l <+ sublists l :=
reverse_rec_on l (nil_sublist _) $
λ l a IH, by simp only [map, map_append, sublists_concat]; exact
((append_sublist_append_left _).2 $ singleton_sublist.2 $
mem_map.2 ⟨[], mem_sublists.2 (nil_sublist _), by refl⟩).trans
((append_sublist_append_right _).2 IH)
/- transpose -/
def transpose_aux : list α → list (list α) → list (list α)
| [] ls := ls
| (a::i) [] := [a] :: transpose_aux i []
| (a::i) (l::ls) := (a::l) :: transpose_aux i ls
/-- transpose of a list of lists, treated as a matrix.
`transpose [[1, 2], [3, 4], [5, 6]] = [[1, 3, 5], [2, 4, 6]]` -/
def transpose : list (list α) → list (list α)
| [] := []
| (l::ls) := transpose_aux l (transpose ls)
/- forall₂ -/
section forall₂
variables {r : α → β → Prop} {p : γ → δ → Prop}
open relator relation
inductive forall₂ (R : α → β → Prop) : list α → list β → Prop
| nil {} : forall₂ [] []
| cons {a b l₁ l₂} : R a b → forall₂ l₁ l₂ → forall₂ (a::l₁) (b::l₂)
run_cmd tactic.mk_iff_of_inductive_prop `list.forall₂ `list.forall₂_iff
attribute [simp] forall₂.nil
@[simp] theorem forall₂_cons {R : α → β → Prop} {a b l₁ l₂} :
forall₂ R (a::l₁) (b::l₂) ↔ R a b ∧ forall₂ R l₁ l₂ :=
⟨λ h, by cases h with h₁ h₂; split; assumption, λ ⟨h₁, h₂⟩, forall₂.cons h₁ h₂⟩
theorem forall₂.imp {R S : α → β → Prop}
(H : ∀ a b, R a b → S a b) {l₁ l₂}
(h : forall₂ R l₁ l₂) : forall₂ S l₁ l₂ :=
by induction h; constructor; solve_by_elim
lemma forall₂.mp {r q s : α → β → Prop} (h : ∀a b, r a b → q a b → s a b) :
∀{l₁ l₂}, forall₂ r l₁ l₂ → forall₂ q l₁ l₂ → forall₂ s l₁ l₂
| [] [] forall₂.nil forall₂.nil := forall₂.nil
| (a::l₁) (b::l₂) (forall₂.cons hr hrs) (forall₂.cons hq hqs) :=
forall₂.cons (h a b hr hq) (forall₂.mp hrs hqs)
lemma forall₂.flip : ∀{a b}, forall₂ (flip r) b a → forall₂ r a b
| _ _ forall₂.nil := forall₂.nil
| (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := forall₂.cons h₁ h₂.flip
lemma forall₂_same {r : α → α → Prop} : ∀{l}, (∀x∈l, r x x) → forall₂ r l l
| [] _ := forall₂.nil
| (a::as) h := forall₂.cons
(h _ (mem_cons_self _ _))
(forall₂_same $ assume a ha, h a $ mem_cons_of_mem _ ha)
lemma forall₂_refl {r} [is_refl α r] (l : list α) : forall₂ r l l :=
forall₂_same $ assume a h, is_refl.refl _ _
lemma forall₂_eq_eq_eq : forall₂ ((=) : α → α → Prop) = (=) :=
begin
funext a b, apply propext,
split,
{ assume h, induction h, {refl}, simp only [*]; split; refl },
{ assume h, subst h, exact forall₂_refl _ }
end
@[simp] lemma forall₂_nil_left_iff {l} : forall₂ r nil l ↔ l = nil :=
⟨λ H, by cases H; refl, by rintro rfl; exact forall₂.nil⟩
@[simp] lemma forall₂_nil_right_iff {l} : forall₂ r l nil ↔ l = nil :=
⟨λ H, by cases H; refl, by rintro rfl; exact forall₂.nil⟩
lemma forall₂_cons_left_iff {a l u} : forall₂ r (a::l) u ↔ (∃b u', r a b ∧ forall₂ r l u' ∧ u = b :: u') :=
iff.intro
(assume h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end)
(assume h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end)
lemma forall₂_cons_right_iff {b l u} :
forall₂ r u (b::l) ↔ (∃a u', r a b ∧ forall₂ r u' l ∧ u = a :: u') :=
iff.intro
(assume h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end)
(assume h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end)
lemma forall₂_and_left {r : α → β → Prop} {p : α → Prop} :
∀l u, forall₂ (λa b, p a ∧ r a b) l u ↔ (∀a∈l, p a) ∧ forall₂ r l u
| [] u := by simp only [forall₂_nil_left_iff, forall_prop_of_false (not_mem_nil _), imp_true_iff, true_and]
| (a::l) u := by simp only [forall₂_and_left l, forall₂_cons_left_iff, forall_mem_cons,
and_assoc, and_comm, and.left_comm, exists_and_distrib_left.symm]
@[simp] lemma forall₂_map_left_iff {f : γ → α} :
∀{l u}, forall₂ r (map f l) u ↔ forall₂ (λc b, r (f c) b) l u
| [] _ := by simp only [map, forall₂_nil_left_iff]
| (a::l) _ := by simp only [map, forall₂_cons_left_iff, forall₂_map_left_iff]
@[simp] lemma forall₂_map_right_iff {f : γ → β} :
∀{l u}, forall₂ r l (map f u) ↔ forall₂ (λa c, r a (f c)) l u
| _ [] := by simp only [map, forall₂_nil_right_iff]
| _ (b::u) := by simp only [map, forall₂_cons_right_iff, forall₂_map_right_iff]
lemma left_unique_forall₂ (hr : left_unique r) : left_unique (forall₂ r)
| a₀ nil a₁ forall₂.nil forall₂.nil := rfl
| (a₀::l₀) (b::l) (a₁::l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) :=
hr ha₀ ha₁ ▸ left_unique_forall₂ h₀ h₁ ▸ rfl
lemma right_unique_forall₂ (hr : right_unique r) : right_unique (forall₂ r)
| nil a₀ a₁ forall₂.nil forall₂.nil := rfl
| (b::l) (a₀::l₀) (a₁::l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) :=
hr ha₀ ha₁ ▸ right_unique_forall₂ h₀ h₁ ▸ rfl
lemma bi_unique_forall₂ (hr : bi_unique r) : bi_unique (forall₂ r) :=
⟨assume a b c, left_unique_forall₂ hr.1, assume a b c, right_unique_forall₂ hr.2⟩
theorem forall₂_length_eq {R : α → β → Prop} :
∀ {l₁ l₂}, forall₂ R l₁ l₂ → length l₁ = length l₂
| _ _ forall₂.nil := rfl
| _ _ (forall₂.cons h₁ h₂) := congr_arg succ (forall₂_length_eq h₂)
theorem forall₂_zip {R : α → β → Prop} :
∀ {l₁ l₂}, forall₂ R l₁ l₂ → ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b
| _ _ (forall₂.cons h₁ h₂) x y (or.inl rfl) := h₁
| _ _ (forall₂.cons h₁ h₂) x y (or.inr h₃) := forall₂_zip h₂ h₃
theorem forall₂_iff_zip {R : α → β → Prop} {l₁ l₂} : forall₂ R l₁ l₂ ↔
length l₁ = length l₂ ∧ ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b :=
⟨λ h, ⟨forall₂_length_eq h, @forall₂_zip _ _ _ _ _ h⟩,
λ h, begin
cases h with h₁ h₂,
induction l₁ with a l₁ IH generalizing l₂,
{ cases length_eq_zero.1 h₁.symm, constructor },
{ cases l₂ with b l₂; injection h₁ with h₁,
exact forall₂.cons (h₂ $ or.inl rfl) (IH h₁ $ λ a b h, h₂ $ or.inr h) }
end⟩
theorem forall₂_take {R : α → β → Prop} :
∀ n {l₁ l₂}, forall₂ R l₁ l₂ → forall₂ R (take n l₁) (take n l₂)
| 0 _ _ _ := by simp only [forall₂.nil, take]
| (n+1) _ _ (forall₂.nil) := by simp only [forall₂.nil, take]
| (n+1) _ _ (forall₂.cons h₁ h₂) := by simp [and.intro h₁ h₂, forall₂_take n]
theorem forall₂_drop {R : α → β → Prop} :
∀ n {l₁ l₂}, forall₂ R l₁ l₂ → forall₂ R (drop n l₁) (drop n l₂)
| 0 _ _ h := by simp only [drop, h]
| (n+1) _ _ (forall₂.nil) := by simp only [forall₂.nil, drop]
| (n+1) _ _ (forall₂.cons h₁ h₂) := by simp [and.intro h₁ h₂, forall₂_drop n]
theorem forall₂_take_append {R : α → β → Prop} (l : list α) (l₁ : list β) (l₂ : list β)
(h : forall₂ R l (l₁ ++ l₂)) : forall₂ R (list.take (length l₁) l) l₁ :=
have h': forall₂ R (take (length l₁) l) (take (length l₁) (l₁ ++ l₂)), from forall₂_take (length l₁) h,
by rwa [take_left] at h'
theorem forall₂_drop_append {R : α → β → Prop} (l : list α) (l₁ : list β) (l₂ : list β)
(h : forall₂ R l (l₁ ++ l₂)) : forall₂ R (list.drop (length l₁) l) l₂ :=
have h': forall₂ R (drop (length l₁) l) (drop (length l₁) (l₁ ++ l₂)), from forall₂_drop (length l₁) h,
by rwa [drop_left] at h'
lemma rel_mem (hr : bi_unique r) : (r ⇒ forall₂ r ⇒ iff) (∈) (∈)
| a b h [] [] forall₂.nil := by simp only [not_mem_nil]
| a b h (a'::as) (b'::bs) (forall₂.cons h₁ h₂) := rel_or (rel_eq hr h h₁) (rel_mem h h₂)
lemma rel_map : ((r ⇒ p) ⇒ forall₂ r ⇒ forall₂ p) map map
| f g h [] [] forall₂.nil := forall₂.nil
| f g h (a::as) (b::bs) (forall₂.cons h₁ h₂) := forall₂.cons (h h₁) (rel_map @h h₂)
lemma rel_append : (forall₂ r ⇒ forall₂ r ⇒ forall₂ r) append append
| [] [] h l₁ l₂ hl := hl
| (a::as) (b::bs) (forall₂.cons h₁ h₂) l₁ l₂ hl := forall₂.cons h₁ (rel_append h₂ hl)
lemma rel_join : (forall₂ (forall₂ r) ⇒ forall₂ r) join join
| [] [] forall₂.nil := forall₂.nil
| (a::as) (b::bs) (forall₂.cons h₁ h₂) := rel_append h₁ (rel_join h₂)
lemma rel_bind : (forall₂ r ⇒ (r ⇒ forall₂ p) ⇒ forall₂ p) list.bind list.bind :=
assume a b h₁ f g h₂, rel_join (rel_map @h₂ h₁)
lemma rel_foldl : ((p ⇒ r ⇒ p) ⇒ p ⇒ forall₂ r ⇒ p) foldl foldl
| f g hfg _ _ h _ _ forall₂.nil := h
| f g hfg x y hxy _ _ (forall₂.cons hab hs) := rel_foldl @hfg (hfg hxy hab) hs
lemma rel_foldr : ((r ⇒ p ⇒ p) ⇒ p ⇒ forall₂ r ⇒ p) foldr foldr
| f g hfg _ _ h _ _ forall₂.nil := h
| f g hfg x y hxy _ _ (forall₂.cons hab hs) := hfg hab (rel_foldr @hfg hxy hs)
lemma rel_filter {p : α → Prop} {q : β → Prop} [decidable_pred p] [decidable_pred q]
(hpq : (r ⇒ (↔)) p q) :
(forall₂ r ⇒ forall₂ r) (filter p) (filter q)
| _ _ forall₂.nil := forall₂.nil
| (a::as) (b::bs) (forall₂.cons h₁ h₂) :=
begin
by_cases p a,
{ have : q b, { rwa [← hpq h₁] },
simp only [filter_cons_of_pos _ h, filter_cons_of_pos _ this, forall₂_cons, h₁, rel_filter h₂, and_true], },
{ have : ¬ q b, { rwa [← hpq h₁] },
simp only [filter_cons_of_neg _ h, filter_cons_of_neg _ this, rel_filter h₂], },
end
theorem filter_map_cons (f : α → option β) (a : α) (l : list α) :
filter_map f (a :: l) = option.cases_on (f a) (filter_map f l) (λb, b :: filter_map f l) :=
begin
generalize eq : f a = b,
cases b,
{ rw filter_map_cons_none _ _ eq },
{ rw filter_map_cons_some _ _ _ eq },
end
lemma rel_filter_map {f : α → option γ} {q : β → option δ} :
((r ⇒ option.rel p) ⇒ forall₂ r ⇒ forall₂ p) filter_map filter_map
| f g hfg _ _ forall₂.nil := forall₂.nil
| f g hfg (a::as) (b::bs) (forall₂.cons h₁ h₂) :=
by rw [filter_map_cons, filter_map_cons];
from match f a, g b, hfg h₁ with
| _, _, option.rel.none := rel_filter_map @hfg h₂
| _, _, option.rel.some h := forall₂.cons h (rel_filter_map @hfg h₂)
end
@[to_additive list.rel_sum]
lemma rel_prod [monoid α] [monoid β]
(h : r 1 1) (hf : (r ⇒ r ⇒ r) (*) (*)) : (forall₂ r ⇒ r) prod prod :=
assume a b, rel_foldl (assume a b, hf) h
end forall₂
/- sections -/
/-- List of all sections through a list of lists. A section
of `[L₁, L₂, ..., Lₙ]` is a list whose first element comes from
`L₁`, whose second element comes from `L₂`, and so on. -/
def sections : list (list α) → list (list α)
| [] := [[]]
| (l::L) := bind (sections L) $ λ s, map (λ a, a::s) l
theorem mem_sections {L : list (list α)} {f} : f ∈ sections L ↔ forall₂ (∈) f L :=
begin
refine ⟨λ h, _, λ h, _⟩,
{ induction L generalizing f, {cases mem_singleton.1 h, exact forall₂.nil},
simp only [sections, bind_eq_bind, mem_bind, mem_map] at h,
rcases h with ⟨_, _, _, _, rfl⟩,
simp only [*, forall₂_cons, true_and] },
{ induction h with a l f L al fL fs, {exact or.inl rfl},
simp only [sections, bind_eq_bind, mem_bind, mem_map],
exact ⟨_, fs, _, al, rfl, rfl⟩ }
end
theorem mem_sections_length {L : list (list α)} {f} (h : f ∈ sections L) : length f = length L :=
forall₂_length_eq (mem_sections.1 h)
lemma rel_sections {r : α → β → Prop} : (forall₂ (forall₂ r) ⇒ forall₂ (forall₂ r)) sections sections
| _ _ forall₂.nil := forall₂.cons forall₂.nil forall₂.nil
| _ _ (forall₂.cons h₀ h₁) :=
rel_bind (rel_sections h₁) (assume _ _ hl, rel_map (assume _ _ ha, forall₂.cons ha hl) h₀)
/- permutations -/
section permutations
def permutations_aux2 (t : α) (ts : list α) (r : list β) : list α → (list α → β) → list α × list β
| [] f := (ts, r)
| (y::ys) f := let (us, zs) := permutations_aux2 ys (λx : list α, f (y::x)) in
(y :: us, f (t :: y :: us) :: zs)
private def meas : (Σ'_:list α, list α) → ℕ × ℕ | ⟨l, i⟩ := (length l + length i, length l)
local infix ` ≺ `:50 := inv_image (prod.lex (<) (<)) meas
@[elab_as_eliminator] def permutations_aux.rec {C : list α → list α → Sort v}
(H0 : ∀ is, C [] is)
(H1 : ∀ t ts is, C ts (t::is) → C is [] → C (t::ts) is) : ∀ l₁ l₂, C l₁ l₂
| [] is := H0 is
| (t::ts) is :=
have h1 : ⟨ts, t :: is⟩ ≺ ⟨t :: ts, is⟩, from
show prod.lex _ _ (succ (length ts + length is), length ts) (succ (length ts) + length is, length (t :: ts)),
by rw nat.succ_add; exact prod.lex.right _ _ (lt_succ_self _),
have h2 : ⟨is, []⟩ ≺ ⟨t :: ts, is⟩, from prod.lex.left _ _ _ (lt_add_of_pos_left _ (succ_pos _)),
H1 t ts is (permutations_aux.rec ts (t::is)) (permutations_aux.rec is [])
using_well_founded {
dec_tac := tactic.assumption,
rel_tac := λ _ _, `[exact ⟨(≺), @inv_image.wf _ _ _ meas (prod.lex_wf lt_wf lt_wf)⟩] }
def permutations_aux : list α → list α → list (list α) :=
@@permutations_aux.rec (λ _ _, list (list α)) (λ is, [])
(λ t ts is IH1 IH2, foldr (λy r, (permutations_aux2 t ts r y id).2) IH1 (is :: IH2))
/-- List of all permutations of `l`.
permutations [1, 2, 3] =
[[1, 2, 3], [2, 1, 3], [3, 2, 1],
[2, 3, 1], [3, 1, 2], [1, 3, 2]] -/
def permutations (l : list α) : list (list α) :=
l :: permutations_aux l []
@[simp] theorem permutations_aux_nil (is : list α) : permutations_aux [] is = [] :=
by rw [permutations_aux, permutations_aux.rec]
@[simp] theorem permutations_aux_cons (t : α) (ts is : list α) :
permutations_aux (t :: ts) is = foldr (λy r, (permutations_aux2 t ts r y id).2)
(permutations_aux ts (t::is)) (permutations is) :=
by rw [permutations_aux, permutations_aux.rec]; refl
end permutations
/- insert -/
section insert
variable [decidable_eq α]
@[simp] theorem insert_nil (a : α) : insert a nil = [a] := rfl
theorem insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else a :: l := rfl
@[simp] theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l :=
by simp only [insert.def, if_pos h]
@[simp] theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = a :: l :=
by simp only [insert.def, if_neg h]; split; refl
@[simp] theorem mem_insert_iff {a b : α} {l : list α} : a ∈ insert b l ↔ a = b ∨ a ∈ l :=
begin
by_cases h' : b ∈ l,
{ simp only [insert_of_mem h'],
apply (or_iff_right_of_imp _).symm,
exact λ e, e.symm ▸ h' },
simp only [insert_of_not_mem h', mem_cons_iff]
end
@[simp] theorem suffix_insert (a : α) (l : list α) : l <:+ insert a l :=
by by_cases a ∈ l; [simp only [insert_of_mem h], simp only [insert_of_not_mem h, suffix_cons]]
@[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l :=
mem_insert_iff.2 (or.inl rfl)
@[simp] theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l :=
mem_insert_iff.2 (or.inr h)
theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l :=
mem_insert_iff.1 h
@[simp] theorem length_insert_of_mem {a : α} [decidable_eq α] {l : list α} (h : a ∈ l) :
length (insert a l) = length l :=
by rw insert_of_mem h
@[simp] theorem length_insert_of_not_mem {a : α} [decidable_eq α] {l : list α} (h : a ∉ l) :
length (insert a l) = length l + 1 :=
by rw insert_of_not_mem h; refl
end insert
/- erase -/
section erase
variable [decidable_eq α]
@[simp] theorem erase_nil (a : α) : [].erase a = [] := rfl
theorem erase_cons (a b : α) (l : list α) : (b :: l).erase a = if b = a then l else b :: l.erase a := rfl
@[simp] theorem erase_cons_head (a : α) (l : list α) : (a :: l).erase a = l :=
by simp only [erase_cons, if_pos rfl]
@[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) : (b::l).erase a = b :: l.erase a :=
by simp only [erase_cons, if_neg h]; split; refl
@[simp] theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l :=
by induction l with _ _ ih; [refl,
simp only [list.erase, if_neg (ne_of_not_mem_cons h).symm, ih (not_mem_of_not_mem_cons h)]]; split; refl
theorem exists_erase_eq {a : α} {l : list α} (h : a ∈ l) :
∃ l₁ l₂, a ∉ l₁ ∧ l = l₁ ++ a :: l₂ ∧ l.erase a = l₁ ++ l₂ :=
by induction l with b l ih; [cases h, {
by_cases e : b = a,
{ subst b, exact ⟨[], l, not_mem_nil _, rfl, by simp only [erase_cons_head, nil_append]⟩ },
{ exact let ⟨l₁, l₂, h₁, h₂, h₃⟩ := ih (h.resolve_left (ne.symm e)) in
⟨b::l₁, l₂, not_mem_cons_of_ne_of_not_mem (ne.symm e) h₁,
by rw h₂; refl,
by simp only [erase_cons_tail _ e, h₃, cons_append]; split; refl⟩ } }]
@[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) : length (l.erase a) = pred (length l) :=
match l, l.erase a, exists_erase_eq h with
| ._, ._, ⟨l₁, l₂, _, rfl, rfl⟩ := by simp only [length_append]; refl
end
theorem erase_append_left {a : α} : ∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erase a = l₁.erase a ++ l₂
| (x::xs) l₂ h := begin
by_cases h' : x = a, { simp only [h', erase_cons_head, cons_append] },
simp only [cons_append, erase_cons_tail _ h', erase_append_left l₂ (mem_of_ne_of_mem (ne.symm h') h)], split; refl
end
theorem erase_append_right {a : α} : ∀ {l₁ : list α} (l₂), a ∉ l₁ → (l₁++l₂).erase a = l₁ ++ l₂.erase a
| [] l₂ h := rfl
| (x::xs) l₂ h := by simp only [*, cons_append, erase_cons_tail _(ne_of_not_mem_cons h).symm, erase_append_right _ (not_mem_of_not_mem_cons h)]; split; refl
theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l :=
if h : a ∈ l then match l, l.erase a, exists_erase_eq h with
| ._, ._, ⟨l₁, l₂, _, rfl, rfl⟩ := by simp only [append_sublist_append_left, sublist_cons]
end else by rw erase_of_not_mem h
theorem erase_subset (a : α) (l : list α) : l.erase a ⊆ l :=
subset_of_sublist (erase_sublist a l)
theorem erase_sublist_erase (a : α) : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → l₁.erase a <+ l₂.erase a
| ._ ._ sublist.slnil := sublist.slnil
| ._ ._ (sublist.cons l₁ l₂ b s) := if h : b = a
then by rw [h, erase_cons_head]; exact (erase_sublist _ _).trans s
else by rw erase_cons_tail _ h; exact (erase_sublist_erase s).cons _ _ _
| ._ ._ (sublist.cons2 l₁ l₂ b s) := if h : b = a
then by rw [h, erase_cons_head, erase_cons_head]; exact s
else by rw [erase_cons_tail _ h, erase_cons_tail _ h]; exact (erase_sublist_erase s).cons2 _ _ _
theorem mem_of_mem_erase {a b : α} {l : list α} : a ∈ l.erase b → a ∈ l :=
@erase_subset _ _ _ _ _
@[simp] theorem mem_erase_of_ne {a b : α} {l : list α} (ab : a ≠ b) : a ∈ l.erase b ↔ a ∈ l :=
⟨mem_of_mem_erase, λ al,
if h : b ∈ l then match l, l.erase b, exists_erase_eq h, al with
| ._, ._, ⟨l₁, l₂, _, rfl, rfl⟩, al := by simpa only [mem_append, mem_cons_iff, ab, false_or] using al
end else by simp only [erase_of_not_mem h, al]⟩
theorem erase_comm (a b : α) (l : list α) : (l.erase a).erase b = (l.erase b).erase a :=
if ab : a = b then by rw ab else
if ha : a ∈ l then
if hb : b ∈ l then match l, l.erase a, exists_erase_eq ha, hb with
| ._, ._, ⟨l₁, l₂, ha', rfl, rfl⟩, hb :=
if h₁ : b ∈ l₁ then
by rw [erase_append_left _ h₁, erase_append_left _ h₁,
erase_append_right _ (mt mem_of_mem_erase ha'), erase_cons_head]
else
by rw [erase_append_right _ h₁, erase_append_right _ h₁, erase_append_right _ ha',
erase_cons_tail _ ab, erase_cons_head]
end
else by simp only [erase_of_not_mem hb, erase_of_not_mem (mt mem_of_mem_erase hb)]
else by simp only [erase_of_not_mem ha, erase_of_not_mem (mt mem_of_mem_erase ha)]
theorem map_erase [decidable_eq β] {f : α → β} (finj : injective f) {a : α} :
∀ (l : list α), map f (l.erase a) = (map f l).erase (f a)
| [] := rfl
| (b::l) := if h : f b = f a then by simp only [h, finj h, erase_cons_head, map_cons]
else by simp only [map, erase_cons_tail _ h, erase_cons_tail _ (mt (congr_arg f) h), map_erase l]; split; refl
theorem map_foldl_erase [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} :
map f (foldl list.erase l₁ l₂) = foldl (λ l a, l.erase (f a)) (map f l₁) l₂ :=
by induction l₂ generalizing l₁; [refl,
simp only [foldl_cons, map_erase finj, *]]
end erase
/- diff -/
section diff
variable [decidable_eq α]
@[simp] theorem diff_nil (l : list α) : l.diff [] = l := rfl
@[simp] theorem diff_cons (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.erase a).diff l₂ :=
if h : a ∈ l₁ then by simp only [list.diff, if_pos h]
else by simp only [list.diff, if_neg h, erase_of_not_mem h]
@[simp] theorem nil_diff (l : list α) : [].diff l = [] :=
by induction l; [refl, simp only [*, diff_cons, erase_of_not_mem (not_mem_nil _)]]
theorem diff_eq_foldl : ∀ (l₁ l₂ : list α), l₁.diff l₂ = foldl list.erase l₁ l₂
| l₁ [] := rfl
| l₁ (a::l₂) := (diff_cons l₁ l₂ a).trans (diff_eq_foldl _ _)
@[simp] theorem diff_append (l₁ l₂ l₃ : list α) : l₁.diff (l₂ ++ l₃) = (l₁.diff l₂).diff l₃ :=
by simp only [diff_eq_foldl, foldl_append]
@[simp] theorem map_diff [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} :
map f (l₁.diff l₂) = (map f l₁).diff (map f l₂) :=
by simp only [diff_eq_foldl, foldl_map, map_foldl_erase finj]
theorem diff_sublist : ∀ l₁ l₂ : list α, l₁.diff l₂ <+ l₁
| l₁ [] := sublist.refl _
| l₁ (a::l₂) := calc l₁.diff (a :: l₂) = (l₁.erase a).diff l₂ : diff_cons _ _ _
... <+ l₁.erase a : diff_sublist _ _
... <+ l₁ : list.erase_sublist _ _
theorem diff_subset (l₁ l₂ : list α) : l₁.diff l₂ ⊆ l₁ :=
subset_of_sublist $ diff_sublist _ _
theorem mem_diff_of_mem {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁ → a ∉ l₂ → a ∈ l₁.diff l₂
| l₁ [] h₁ h₂ := h₁
| l₁ (b::l₂) h₁ h₂ := by rw diff_cons; exact
mem_diff_of_mem ((mem_erase_of_ne (ne_of_not_mem_cons h₂)).2 h₁) (not_mem_of_not_mem_cons h₂)
theorem diff_sublist_of_sublist : ∀ {l₁ l₂ l₃: list α}, l₁ <+ l₂ → l₁.diff l₃ <+ l₂.diff l₃
| l₁ l₂ [] h := h
| l₁ l₂ (a::l₃) h := by simp only
[diff_cons, diff_sublist_of_sublist (erase_sublist_erase _ h)]
theorem erase_diff_erase_sublist_of_sublist {a : α} : ∀ {l₁ l₂ : list α},
l₁ <+ l₂ → (l₂.erase a).diff (l₁.erase a) <+ l₂.diff l₁
| [] l₂ h := erase_sublist _ _
| (b::l₁) l₂ h := if heq : b = a then by simp only [heq, erase_cons_head, diff_cons]
else by simpa only [erase_cons_head, erase_cons_tail _ heq, diff_cons, erase_comm a b l₂]
using erase_diff_erase_sublist_of_sublist (erase_sublist_erase b h)
end diff
/- zip & unzip -/
@[simp] theorem zip_cons_cons (a : α) (b : β) (l₁ : list α) (l₂ : list β) :
zip (a :: l₁) (b :: l₂) = (a, b) :: zip l₁ l₂ := rfl
@[simp] theorem zip_nil_left (l : list α) : zip ([] : list β) l = [] := rfl
@[simp] theorem zip_nil_right (l : list α) : zip l ([] : list β) = [] :=
by cases l; refl
@[simp] theorem zip_swap : ∀ (l₁ : list α) (l₂ : list β),
(zip l₁ l₂).map prod.swap = zip l₂ l₁
| [] l₂ := (zip_nil_right _).symm
| l₁ [] := by rw zip_nil_right; refl
| (a::l₁) (b::l₂) := by simp only [zip_cons_cons, map_cons, zip_swap l₁ l₂, prod.swap_prod_mk]; split; refl
@[simp] theorem length_zip : ∀ (l₁ : list α) (l₂ : list β),
length (zip l₁ l₂) = min (length l₁) (length l₂)
| [] l₂ := rfl
| l₁ [] := by simp only [length, zip_nil_right, min_zero]
| (a::l₁) (b::l₂) := by by simp only [length, zip_cons_cons, length_zip l₁ l₂, min_add_add_right]
theorem zip_append : ∀ {l₁ l₂ r₁ r₂ : list α} (h : length l₁ = length l₂),
zip (l₁ ++ r₁) (l₂ ++ r₂) = zip l₁ l₂ ++ zip r₁ r₂
| [] l₂ r₁ r₂ h := by simp only [eq_nil_of_length_eq_zero h.symm]; refl
| l₁ [] r₁ r₂ h := by simp only [eq_nil_of_length_eq_zero h]; refl
| (a::l₁) (b::l₂) r₁ r₂ h := by simp only [cons_append, zip_cons_cons, zip_append (succ_inj h)]; split; refl
theorem zip_map (f : α → γ) (g : β → δ) : ∀ (l₁ : list α) (l₂ : list β),
zip (l₁.map f) (l₂.map g) = (zip l₁ l₂).map (prod.map f g)
| [] l₂ := rfl
| l₁ [] := by simp only [map, zip_nil_right]
| (a::l₁) (b::l₂) := by simp only [map, zip_cons_cons, zip_map l₁ l₂, prod.map]; split; refl
theorem zip_map_left (f : α → γ) (l₁ : list α) (l₂ : list β) :
zip (l₁.map f) l₂ = (zip l₁ l₂).map (prod.map f id) :=
by rw [← zip_map, map_id]
theorem zip_map_right (f : β → γ) (l₁ : list α) (l₂ : list β) :
zip l₁ (l₂.map f) = (zip l₁ l₂).map (prod.map id f) :=
by rw [← zip_map, map_id]
theorem zip_map' (f : α → β) (g : α → γ) : ∀ (l : list α),
zip (l.map f) (l.map g) = l.map (λ a, (f a, g a))
| [] := rfl
| (a::l) := by simp only [map, zip_cons_cons, zip_map' l]; split; refl
theorem mem_zip {a b} : ∀ {l₁ : list α} {l₂ : list β},
(a, b) ∈ zip l₁ l₂ → a ∈ l₁ ∧ b ∈ l₂
| (_::l₁) (_::l₂) (or.inl rfl) := ⟨or.inl rfl, or.inl rfl⟩
| (a'::l₁) (b'::l₂) (or.inr h) := by split; simp only [mem_cons_iff, or_true, mem_zip h]
@[simp] theorem unzip_nil : unzip (@nil (α × β)) = ([], []) := rfl
@[simp] theorem unzip_cons (a : α) (b : β) (l : list (α × β)) :
unzip ((a, b) :: l) = (a :: (unzip l).1, b :: (unzip l).2) :=
by rw unzip; cases unzip l; refl
theorem unzip_eq_map : ∀ (l : list (α × β)), unzip l = (l.map prod.fst, l.map prod.snd)
| [] := rfl
| ((a, b) :: l) := by simp only [unzip_cons, map_cons, unzip_eq_map l]
theorem unzip_left (l : list (α × β)) : (unzip l).1 = l.map prod.fst :=
by simp only [unzip_eq_map]
theorem unzip_right (l : list (α × β)) : (unzip l).2 = l.map prod.snd :=
by simp only [unzip_eq_map]
theorem unzip_swap (l : list (α × β)) : unzip (l.map prod.swap) = (unzip l).swap :=
by simp only [unzip_eq_map, map_map]; split; refl
theorem zip_unzip : ∀ (l : list (α × β)), zip (unzip l).1 (unzip l).2 = l
| [] := rfl
| ((a, b) :: l) := by simp only [unzip_cons, zip_cons_cons, zip_unzip l]; split; refl
theorem unzip_zip_left : ∀ {l₁ : list α} {l₂ : list β}, length l₁ ≤ length l₂ →
(unzip (zip l₁ l₂)).1 = l₁
| [] l₂ h := rfl
| l₁ [] h := by rw eq_nil_of_length_eq_zero (eq_zero_of_le_zero h); refl
| (a::l₁) (b::l₂) h := by simp only [zip_cons_cons, unzip_cons, unzip_zip_left (le_of_succ_le_succ h)]; split; refl
theorem unzip_zip_right {l₁ : list α} {l₂ : list β} (h : length l₂ ≤ length l₁) :
(unzip (zip l₁ l₂)).2 = l₂ :=
by rw [← zip_swap, unzip_swap]; exact unzip_zip_left h
theorem unzip_zip {l₁ : list α} {l₂ : list β} (h : length l₁ = length l₂) :
unzip (zip l₁ l₂) = (l₁, l₂) :=
by rw [← @prod.mk.eta _ _ (unzip (zip l₁ l₂)),
unzip_zip_left (le_of_eq h), unzip_zip_right (ge_of_eq h)]
def revzip (l : list α) : list (α × α) := zip l l.reverse
@[simp] theorem length_revzip (l : list α) : length (revzip l) = length l :=
by simp only [revzip, length_zip, length_reverse, min_self]
@[simp] theorem unzip_revzip (l : list α) : (revzip l).unzip = (l, l.reverse) :=
unzip_zip (length_reverse l).symm
@[simp] theorem revzip_map_fst (l : list α) : (revzip l).map prod.fst = l :=
by rw [← unzip_left, unzip_revzip]
@[simp] theorem revzip_map_snd (l : list α) : (revzip l).map prod.snd = l.reverse :=
by rw [← unzip_right, unzip_revzip]
theorem reverse_revzip (l : list α) : reverse l.revzip = revzip l.reverse :=
by rw [← zip_unzip.{u u} (revzip l).reverse, unzip_eq_map]; simp; simp [revzip]
theorem revzip_swap (l : list α) : (revzip l).map prod.swap = revzip l.reverse :=
by simp [revzip]
/- enum -/
theorem length_enum_from : ∀ n (l : list α), length (enum_from n l) = length l
| n [] := rfl
| n (a::l) := congr_arg nat.succ (length_enum_from _ _)
theorem length_enum : ∀ (l : list α), length (enum l) = length l := length_enum_from _
@[simp] theorem enum_from_nth : ∀ n (l : list α) m,
nth (enum_from n l) m = (λ a, (n + m, a)) <$> nth l m
| n [] m := rfl
| n (a :: l) 0 := rfl
| n (a :: l) (m+1) := (enum_from_nth (n+1) l m).trans $
by rw [add_right_comm]; refl
@[simp] theorem enum_nth : ∀ (l : list α) n,
nth (enum l) n = (λ a, (n, a)) <$> nth l n :=
by simp only [enum, enum_from_nth, zero_add]; intros; refl
@[simp] theorem enum_from_map_snd : ∀ n (l : list α),
map prod.snd (enum_from n l) = l
| n [] := rfl
| n (a :: l) := congr_arg (cons _) (enum_from_map_snd _ _)
@[simp] theorem enum_map_snd : ∀ (l : list α),
map prod.snd (enum l) = l := enum_from_map_snd _
/- product -/
/-- `product l₁ l₂` is the list of pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂`.
product [1, 2] [5, 6] = [(1, 5), (1, 6), (2, 5), (2, 6)] -/
def product (l₁ : list α) (l₂ : list β) : list (α × β) :=
l₁.bind $ λ a, l₂.map $ prod.mk a
@[simp] theorem nil_product (l : list β) : product (@nil α) l = [] := rfl
@[simp] theorem product_cons (a : α) (l₁ : list α) (l₂ : list β)
: product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ := rfl
@[simp] theorem product_nil : ∀ (l : list α), product l (@nil β) = []
| [] := rfl
| (a::l) := by rw [product_cons, product_nil]; refl
@[simp] theorem mem_product {l₁ : list α} {l₂ : list β} {a : α} {b : β} :
(a, b) ∈ product l₁ l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ :=
by simp only [product, mem_bind, mem_map, prod.ext_iff, exists_prop,
and.left_comm, exists_and_distrib_left, exists_eq_left, exists_eq_right]
theorem length_product (l₁ : list α) (l₂ : list β) :
length (product l₁ l₂) = length l₁ * length l₂ :=
by induction l₁ with x l₁ IH; [exact (zero_mul _).symm,
simp only [length, product_cons, length_append, IH,
right_distrib, one_mul, length_map, add_comm]]
/- sigma -/
section
variable {σ : α → Type*}
/-- `sigma l₁ l₂` is the list of dependent pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂ a`.
sigma [1, 2] (λ_, [5, 6]) = [(1, 5), (1, 6), (2, 5), (2, 6)] -/
protected def sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : list (Σ a, σ a) :=
l₁.bind $ λ a, (l₂ a).map $ sigma.mk a
@[simp] theorem nil_sigma (l : Π a, list (σ a)) : (@nil α).sigma l = [] := rfl
@[simp] theorem sigma_cons (a : α) (l₁ : list α) (l₂ : Π a, list (σ a))
: (a::l₁).sigma l₂ = map (sigma.mk a) (l₂ a) ++ l₁.sigma l₂ := rfl
@[simp] theorem sigma_nil : ∀ (l : list α), l.sigma (λ a, @nil (σ a)) = []
| [] := rfl
| (a::l) := by rw [sigma_cons, sigma_nil]; refl
@[simp] theorem mem_sigma {l₁ : list α} {l₂ : Π a, list (σ a)} {a : α} {b : σ a} :
sigma.mk a b ∈ l₁.sigma l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ a :=
by simp only [list.sigma, mem_bind, mem_map, exists_prop, exists_and_distrib_left,
and.left_comm, exists_eq_left, heq_iff_eq, exists_eq_right]
theorem length_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) :
length (l₁.sigma l₂) = (l₁.map (λ a, length (l₂ a))).sum :=
by induction l₁ with x l₁ IH; [refl,
simp only [map, sigma_cons, length_append, length_map, IH, sum_cons]]
end
/- of_fn -/
def of_fn_aux {n} (f : fin n → α) : ∀ m, m ≤ n → list α → list α
| 0 h l := l
| (succ m) h l := of_fn_aux m (le_of_lt h) (f ⟨m, h⟩ :: l)
def of_fn {n} (f : fin n → α) : list α :=
of_fn_aux f n (le_refl _) []
theorem length_of_fn_aux {n} (f : fin n → α) :
∀ m h l, length (of_fn_aux f m h l) = length l + m
| 0 h l := rfl
| (succ m) h l := (length_of_fn_aux m _ _).trans (succ_add _ _)
@[simp] theorem length_of_fn {n} (f : fin n → α) : length (of_fn f) = n :=
(length_of_fn_aux f _ _ _).trans (zero_add _)
def of_fn_nth_val {n} (f : fin n → α) (i : ℕ) : option α :=
if h : _ then some (f ⟨i, h⟩) else none
theorem nth_of_fn_aux {n} (f : fin n → α) (i) :
∀ m h l,
(∀ i, nth l i = of_fn_nth_val f (i + m)) →
nth (of_fn_aux f m h l) i = of_fn_nth_val f i
| 0 h l H := H i
| (succ m) h l H := nth_of_fn_aux m _ _ begin
intro j, cases j with j,
{ simp only [nth, of_fn_nth_val, zero_add, dif_pos (show m < n, from h)] },
{ simp only [nth, H, succ_add] }
end
@[simp] theorem nth_of_fn {n} (f : fin n → α) (i) :
nth (of_fn f) i = of_fn_nth_val f i :=
nth_of_fn_aux f _ _ _ _ $ λ i,
by simp only [of_fn_nth_val, dif_neg (not_lt.2 (le_add_left n i))]; refl
@[simp] theorem nth_le_of_fn {n} (f : fin n → α) (i : fin n) :
nth_le (of_fn f) i.1 ((length_of_fn f).symm ▸ i.2) = f i :=
option.some.inj $ by rw [← nth_le_nth];
simp only [list.nth_of_fn, of_fn_nth_val, fin.eta, dif_pos i.2]
theorem array_eq_of_fn {n} (a : array n α) : a.to_list = of_fn a.read :=
suffices ∀ {m h l}, d_array.rev_iterate_aux a
(λ i, cons) m h l = of_fn_aux (d_array.read a) m h l, from this,
begin
intros, induction m with m IH generalizing l, {refl},
simp only [d_array.rev_iterate_aux, of_fn_aux, IH]
end
theorem of_fn_zero (f : fin 0 → α) : of_fn f = [] := rfl
theorem of_fn_succ {n} (f : fin (succ n) → α) :
of_fn f = f 0 :: of_fn (λ i, f i.succ) :=
suffices ∀ {m h l}, of_fn_aux f (succ m) (succ_le_succ h) l =
f 0 :: of_fn_aux (λ i, f i.succ) m h l, from this,
begin
intros, induction m with m IH generalizing l, {refl},
rw [of_fn_aux, IH], refl
end
theorem of_fn_nth_le : ∀ l : list α, of_fn (λ i, nth_le l i.1 i.2) = l
| [] := rfl
| (a::l) := by rw of_fn_succ; congr; simp only [fin.succ_val]; exact of_fn_nth_le l
/- disjoint -/
section disjoint
/-- `disjoint l₁ l₂` means that `l₁` and `l₂` have no elements in common. -/
def disjoint (l₁ l₂ : list α) : Prop := ∀ ⦃a⦄, a ∈ l₁ → a ∈ l₂ → false
theorem disjoint.symm {l₁ l₂ : list α} (d : disjoint l₁ l₂) : disjoint l₂ l₁
| a i₂ i₁ := d i₁ i₂
@[simp] theorem disjoint_comm {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ disjoint l₂ l₁ :=
⟨disjoint.symm, disjoint.symm⟩
theorem disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₁ → a ∉ l₂ := iff.rfl
theorem disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₂ → a ∉ l₁ :=
disjoint_comm
theorem disjoint_iff_ne {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ a ∈ l₁, ∀ b ∈ l₂, a ≠ b :=
by simp only [disjoint_left, imp_not_comm, forall_eq']
theorem disjoint_of_subset_left {l₁ l₂ l : list α} (ss : l₁ ⊆ l) (d : disjoint l l₂) : disjoint l₁ l₂
| x m₁ := d (ss m₁)
theorem disjoint_of_subset_right {l₁ l₂ l : list α} (ss : l₂ ⊆ l) (d : disjoint l₁ l) : disjoint l₁ l₂
| x m m₁ := d m (ss m₁)
theorem disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ :=
disjoint_of_subset_left (list.subset_cons _ _)
theorem disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ :=
disjoint_of_subset_right (list.subset_cons _ _)
@[simp] theorem disjoint_nil_left (l : list α) : disjoint [] l
| a := (not_mem_nil a).elim
@[simp] theorem singleton_disjoint {l : list α} {a : α} : disjoint [a] l ↔ a ∉ l :=
by simp only [disjoint, mem_singleton, forall_eq]; refl
@[simp] theorem disjoint_singleton {l : list α} {a : α} : disjoint l [a] ↔ a ∉ l :=
by rw disjoint_comm; simp only [singleton_disjoint]
@[simp] theorem disjoint_append_left {l₁ l₂ l : list α} :
disjoint (l₁++l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l :=
by simp only [disjoint, mem_append, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_append_right {l₁ l₂ l : list α} :
disjoint l (l₁++l₂) ↔ disjoint l l₁ ∧ disjoint l l₂ :=
disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_append_left]
@[simp] theorem disjoint_cons_left {a : α} {l₁ l₂ : list α} :
disjoint (a::l₁) l₂ ↔ a ∉ l₂ ∧ disjoint l₁ l₂ :=
(@disjoint_append_left _ [a] l₁ l₂).trans $ by simp only [singleton_disjoint]
@[simp] theorem disjoint_cons_right {a : α} {l₁ l₂ : list α} :
disjoint l₁ (a::l₂) ↔ a ∉ l₁ ∧ disjoint l₁ l₂ :=
disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_cons_left]
theorem disjoint_of_disjoint_append_left_left {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₁ l :=
(disjoint_append_left.1 d).1
theorem disjoint_of_disjoint_append_left_right {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₂ l :=
(disjoint_append_left.1 d).2
theorem disjoint_of_disjoint_append_right_left {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₁ :=
(disjoint_append_right.1 d).1
theorem disjoint_of_disjoint_append_right_right {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₂ :=
(disjoint_append_right.1 d).2
end disjoint
/- union -/
section union
variable [decidable_eq α]
@[simp] theorem nil_union (l : list α) : [] ∪ l = l := rfl
@[simp] theorem cons_union (l₁ l₂ : list α) (a : α) : a :: l₁ ∪ l₂ = insert a (l₁ ∪ l₂) := rfl
@[simp] theorem mem_union {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∪ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ :=
by induction l₁; simp only [nil_union, not_mem_nil, false_or, cons_union, mem_insert_iff, mem_cons_iff, or_assoc, *]
theorem mem_union_left {a : α} {l₁ : list α} (h : a ∈ l₁) (l₂ : list α) : a ∈ l₁ ∪ l₂ :=
mem_union.2 (or.inl h)
theorem mem_union_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ∪ l₂ :=
mem_union.2 (or.inr h)
theorem sublist_suffix_of_union : ∀ l₁ l₂ : list α, ∃ t, t <+ l₁ ∧ t ++ l₂ = l₁ ∪ l₂
| [] l₂ := ⟨[], by refl, rfl⟩
| (a::l₁) l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in
if h : a ∈ l₁ ∪ l₂
then ⟨t, sublist_cons_of_sublist _ s, by simp only [e, cons_union, insert_of_mem h]⟩
else ⟨a::t, cons_sublist_cons _ s, by simp only [cons_append, cons_union, e, insert_of_not_mem h]; split; refl⟩
theorem suffix_union_right (l₁ l₂ : list α) : l₂ <:+ l₁ ∪ l₂ :=
(sublist_suffix_of_union l₁ l₂).imp (λ a, and.right)
theorem union_sublist_append (l₁ l₂ : list α) : l₁ ∪ l₂ <+ l₁ ++ l₂ :=
let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in
e ▸ (append_sublist_append_right _).2 s
theorem forall_mem_union {p : α → Prop} {l₁ l₂ : list α} :
(∀ x ∈ l₁ ∪ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) :=
by simp only [mem_union, or_imp_distrib, forall_and_distrib]
theorem forall_mem_of_forall_mem_union_left {p : α → Prop} {l₁ l₂ : list α}
(h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₁, p x :=
(forall_mem_union.1 h).1
theorem forall_mem_of_forall_mem_union_right {p : α → Prop} {l₁ l₂ : list α}
(h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₂, p x :=
(forall_mem_union.1 h).2
end union
/- inter -/
section inter
variable [decidable_eq α]
@[simp] theorem inter_nil (l : list α) : [] ∩ l = [] := rfl
@[simp] theorem inter_cons_of_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) :
(a::l₁) ∩ l₂ = a :: (l₁ ∩ l₂) :=
if_pos h
@[simp] theorem inter_cons_of_not_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∉ l₂) :
(a::l₁) ∩ l₂ = l₁ ∩ l₂ :=
if_neg h
theorem mem_of_mem_inter_left {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₁ :=
mem_of_mem_filter
theorem mem_of_mem_inter_right {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₂ :=
of_mem_filter
theorem mem_inter_of_mem_of_mem {l₁ l₂ : list α} {a : α} : a ∈ l₁ → a ∈ l₂ → a ∈ l₁ ∩ l₂ :=
mem_filter_of_mem
@[simp] theorem mem_inter {a : α} {l₁ l₂ : list α} : a ∈ l₁ ∩ l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ :=
mem_filter
theorem inter_subset_left (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₁ :=
filter_subset _
theorem inter_subset_right (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₂ :=
λ a, mem_of_mem_inter_right
theorem subset_inter {l l₁ l₂ : list α} (h₁ : l ⊆ l₁) (h₂ : l ⊆ l₂) : l ⊆ l₁ ∩ l₂ :=
λ a h, mem_inter.2 ⟨h₁ h, h₂ h⟩
theorem inter_eq_nil_iff_disjoint {l₁ l₂ : list α} : l₁ ∩ l₂ = [] ↔ disjoint l₁ l₂ :=
by simp only [eq_nil_iff_forall_not_mem, mem_inter, not_and]; refl
theorem forall_mem_inter_of_forall_left {p : α → Prop} {l₁ : list α} (h : ∀ x ∈ l₁, p x)
(l₂ : list α) :
∀ x, x ∈ l₁ ∩ l₂ → p x :=
ball.imp_left (λ x, mem_of_mem_inter_left) h
theorem forall_mem_inter_of_forall_right {p : α → Prop} (l₁ : list α) {l₂ : list α}
(h : ∀ x ∈ l₂, p x) :
∀ x, x ∈ l₁ ∩ l₂ → p x :=
ball.imp_left (λ x, mem_of_mem_inter_right) h
end inter
/- bag_inter -/
section bag_inter
variable [decidable_eq α]
@[simp] theorem nil_bag_inter (l : list α) : [].bag_inter l = [] :=
by cases l; refl
@[simp] theorem bag_inter_nil (l : list α) : l.bag_inter [] = [] :=
by cases l; refl
@[simp] theorem cons_bag_inter_of_pos {a} (l₁ : list α) {l₂} (h : a ∈ l₂) :
(a :: l₁).bag_inter l₂ = a :: l₁.bag_inter (l₂.erase a) :=
by cases l₂; exact if_pos h
@[simp] theorem cons_bag_inter_of_neg {a} (l₁ : list α) {l₂} (h : a ∉ l₂) :
(a :: l₁).bag_inter l₂ = l₁.bag_inter l₂ :=
begin
cases l₂, {simp only [bag_inter_nil]},
simp only [erase_of_not_mem h, list.bag_inter, if_neg h]
end
theorem mem_bag_inter {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁.bag_inter l₂ ↔ a ∈ l₁ ∧ a ∈ l₂
| [] l₂ := by simp only [nil_bag_inter, not_mem_nil, false_and]
| (b::l₁) l₂ := begin
by_cases b ∈ l₂,
{ rw [cons_bag_inter_of_pos _ h, mem_cons_iff, mem_cons_iff, mem_bag_inter],
by_cases ba : a = b,
{ simp only [ba, h, eq_self_iff_true, true_or, true_and] },
{ simp only [mem_erase_of_ne ba, ba, false_or] } },
{ rw [cons_bag_inter_of_neg _ h, mem_bag_inter, mem_cons_iff, or_and_distrib_right],
symmetry, apply or_iff_right_of_imp,
rintro ⟨rfl, h'⟩, exact h.elim h' }
end
theorem bag_inter_sublist_left : ∀ l₁ l₂ : list α, l₁.bag_inter l₂ <+ l₁
| [] l₂ := by simp [nil_sublist]
| (b::l₁) l₂ := begin
by_cases b ∈ l₂; simp [h],
{ apply cons_sublist_cons, apply bag_inter_sublist_left },
{ apply sublist_cons_of_sublist, apply bag_inter_sublist_left }
end
end bag_inter
/- pairwise relation (generalized no duplicate) -/
section pairwise
variable (R : α → α → Prop)
/-- `pairwise R l` means that all the elements with earlier indexes are
`R`-related to all the elements with later indexes.
pairwise R [1, 2, 3] ↔ R 1 2 ∧ R 1 3 ∧ R 2 3
For example if `R = (≠)` then it asserts `l` has no duplicates,
and if `R = (<)` then it asserts that `l` is (strictly) sorted. -/
inductive pairwise : list α → Prop
| nil : pairwise []
| cons : ∀ {a : α} {l : list α}, (∀ a' ∈ l, R a a') → pairwise l → pairwise (a::l)
attribute [simp] pairwise.nil
run_cmd tactic.mk_iff_of_inductive_prop `list.pairwise `list.pairwise_iff
variable {R}
@[simp] theorem pairwise_cons {a : α} {l : list α} :
pairwise R (a::l) ↔ (∀ a' ∈ l, R a a') ∧ pairwise R l :=
⟨λ p, by cases p with a l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩
theorem rel_of_pairwise_cons {a : α} {l : list α}
(p : pairwise R (a::l)) : ∀ {a'}, a' ∈ l → R a a' :=
(pairwise_cons.1 p).1
theorem pairwise_of_pairwise_cons {a : α} {l : list α}
(p : pairwise R (a::l)) : pairwise R l :=
(pairwise_cons.1 p).2
theorem pairwise.imp_of_mem {S : α → α → Prop} {l : list α}
(H : ∀ {a b}, a ∈ l → b ∈ l → R a b → S a b) (p : pairwise R l) : pairwise S l :=
begin
induction p with a l r p IH generalizing H; constructor,
{ exact ball.imp_right
(λ x h, H (mem_cons_self _ _) (mem_cons_of_mem _ h)) r },
{ exact IH (λ a b m m', H
(mem_cons_of_mem _ m) (mem_cons_of_mem _ m')) }
end
theorem pairwise.imp {S : α → α → Prop}
(H : ∀ a b, R a b → S a b) {l : list α} : pairwise R l → pairwise S l :=
pairwise.imp_of_mem (λ a b _ _, H a b)
theorem pairwise.and {S : α → α → Prop} {l : list α} :
pairwise (λ a b, R a b ∧ S a b) l ↔ pairwise R l ∧ pairwise S l :=
⟨λ h, ⟨h.imp (λ a b h, h.1), h.imp (λ a b h, h.2)⟩,
λ ⟨hR, hS⟩, begin
clear_, induction hR with a l R1 R2 IH;
simp only [pairwise.nil, pairwise_cons] at *,
exact ⟨λ b bl, ⟨R1 b bl, hS.1 b bl⟩, IH hS.2⟩
end⟩
theorem pairwise.imp₂ {S : α → α → Prop} {T : α → α → Prop}
(H : ∀ a b, R a b → S a b → T a b) {l : list α}
(hR : pairwise R l) (hS : pairwise S l) : pairwise T l :=
(pairwise.and.2 ⟨hR, hS⟩).imp $ λ a b, and.rec (H a b)
theorem pairwise.iff_of_mem {S : α → α → Prop} {l : list α}
(H : ∀ {a b}, a ∈ l → b ∈ l → (R a b ↔ S a b)) : pairwise R l ↔ pairwise S l :=
⟨pairwise.imp_of_mem (λ a b m m', (H m m').1),
pairwise.imp_of_mem (λ a b m m', (H m m').2)⟩
theorem pairwise.iff {S : α → α → Prop}
(H : ∀ a b, R a b ↔ S a b) {l : list α} : pairwise R l ↔ pairwise S l :=
pairwise.iff_of_mem (λ a b _ _, H a b)
theorem pairwise_of_forall {l : list α} (H : ∀ x y, R x y) : pairwise R l :=
by induction l; [exact pairwise.nil _,
simp only [*, pairwise_cons, forall_2_true_iff, and_true]]
theorem pairwise.and_mem {l : list α} :
pairwise R l ↔ pairwise (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l :=
pairwise.iff_of_mem (by simp only [true_and, iff_self, forall_2_true_iff] {contextual := tt})
theorem pairwise.imp_mem {l : list α} :
pairwise R l ↔ pairwise (λ x y, x ∈ l → y ∈ l → R x y) l :=
pairwise.iff_of_mem (by simp only [forall_prop_of_true, iff_self, forall_2_true_iff] {contextual := tt})
theorem pairwise_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → pairwise R l₂ → pairwise R l₁
| ._ ._ sublist.slnil h := h
| ._ ._ (sublist.cons l₁ l₂ a s) (pairwise.cons i n) := pairwise_of_sublist s n
| ._ ._ (sublist.cons2 l₁ l₂ a s) (pairwise.cons i n) :=
(pairwise_of_sublist s n).cons (ball.imp_left (subset_of_sublist s) i)
theorem pairwise_singleton (R) (a : α) : pairwise R [a] :=
by simp only [pairwise_cons, mem_singleton, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, and_true]
theorem pairwise_pair {a b : α} : pairwise R [a, b] ↔ R a b :=
by simp only [pairwise_cons, mem_singleton, forall_eq, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, and_true]
theorem pairwise_append {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔
pairwise R l₁ ∧ pairwise R l₂ ∧ ∀ x ∈ l₁, ∀ y ∈ l₂, R x y :=
by induction l₁ with x l₁ IH; [simp only [list.pairwise.nil, forall_prop_of_false (not_mem_nil _), forall_true_iff, and_true, true_and, nil_append],
simp only [cons_append, pairwise_cons, forall_mem_append, IH, forall_mem_cons, forall_and_distrib, and_assoc, and.left_comm]]
theorem pairwise_app_comm (s : symmetric R) {l₁ l₂ : list α} :
pairwise R (l₁++l₂) ↔ pairwise R (l₂++l₁) :=
have ∀ l₁ l₂ : list α,
(∀ (x : α), x ∈ l₁ → ∀ (y : α), y ∈ l₂ → R x y) →
(∀ (x : α), x ∈ l₂ → ∀ (y : α), y ∈ l₁ → R x y),
from λ l₁ l₂ a x xm y ym, s (a y ym x xm),
by simp only [pairwise_append, and.left_comm]; rw iff.intro (this l₁ l₂) (this l₂ l₁)
theorem pairwise_middle (s : symmetric R) {a : α} {l₁ l₂ : list α} :
pairwise R (l₁ ++ a::l₂) ↔ pairwise R (a::(l₁++l₂)) :=
show pairwise R (l₁ ++ ([a] ++ l₂)) ↔ pairwise R ([a] ++ l₁ ++ l₂),
by rw [← append_assoc, pairwise_append, @pairwise_append _ _ ([a] ++ l₁), pairwise_app_comm s];
simp only [mem_append, or_comm]
theorem pairwise_map (f : β → α) :
∀ {l : list β}, pairwise R (map f l) ↔ pairwise (λ a b : β, R (f a) (f b)) l
| [] := by simp only [map, pairwise.nil]
| (b::l) :=
have (∀ a b', b' ∈ l → f b' = a → R (f b) a) ↔ ∀ (b' : β), b' ∈ l → R (f b) (f b'), from
forall_swap.trans $ forall_congr $ λ a, forall_swap.trans $ by simp only [forall_eq'],
by simp only [map, pairwise_cons, mem_map, exists_imp_distrib, and_imp, this, pairwise_map]
theorem pairwise_of_pairwise_map {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α}
(p : pairwise S (map f l)) : pairwise R l :=
((pairwise_map f).1 p).imp H
theorem pairwise_map_of_pairwise {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α}
(p : pairwise R l) : pairwise S (map f l) :=
(pairwise_map f).2 $ p.imp H
theorem pairwise_filter_map (f : β → option α) {l : list β} :
pairwise R (filter_map f l) ↔ pairwise (λ a a' : β, ∀ (b ∈ f a) (b' ∈ f a'), R b b') l :=
let S (a a' : β) := ∀ (b ∈ f a) (b' ∈ f a'), R b b' in
begin
simp only [option.mem_def], induction l with a l IH,
{ simp only [filter_map, pairwise.nil] },
cases e : f a with b,
{ rw [filter_map_cons_none _ _ e, IH, pairwise_cons],
simp only [e, forall_prop_of_false not_false, forall_3_true_iff, true_and] },
rw [filter_map_cons_some _ _ _ e],
simp only [pairwise_cons, mem_filter_map, exists_imp_distrib, and_imp, IH, e, forall_eq'],
show (∀ (a' : α) (x : β), x ∈ l → f x = some a' → R b a') ∧ pairwise S l ↔
(∀ (a' : β), a' ∈ l → ∀ (b' : α), f a' = some b' → R b b') ∧ pairwise S l,
from and_congr ⟨λ h b mb a ma, h a b mb ma, λ h a b mb ma, h b mb a ma⟩ iff.rfl
end
theorem pairwise_filter_map_of_pairwise {S : β → β → Prop} (f : α → option β)
(H : ∀ (a a' : α), R a a' → ∀ (b ∈ f a) (b' ∈ f a'), S b b') {l : list α}
(p : pairwise R l) : pairwise S (filter_map f l) :=
(pairwise_filter_map _).2 $ p.imp H
theorem pairwise_filter (p : α → Prop) [decidable_pred p] {l : list α} :
pairwise R (filter p l) ↔ pairwise (λ x y, p x → p y → R x y) l :=
begin
rw [← filter_map_eq_filter, pairwise_filter_map],
apply pairwise.iff, intros, simp only [option.mem_def, option.guard_eq_some, and_imp, forall_eq'],
end
theorem pairwise_filter_of_pairwise (p : α → Prop) [decidable_pred p] {l : list α}
: pairwise R l → pairwise R (filter p l) :=
pairwise_of_sublist (filter_sublist _)
theorem pairwise_join {L : list (list α)} : pairwise R (join L) ↔
(∀ l ∈ L, pairwise R l) ∧ pairwise (λ l₁ l₂, ∀ (x ∈ l₁) (y ∈ l₂), R x y) L :=
begin
induction L with l L IH, {simp only [join, pairwise.nil, forall_prop_of_false (not_mem_nil _), forall_const, and_self]},
have : (∀ (x : α), x ∈ l → ∀ (y : α) (x_1 : list α), x_1 ∈ L → y ∈ x_1 → R x y) ↔
∀ (a' : list α), a' ∈ L → ∀ (x : α), x ∈ l → ∀ (y : α), y ∈ a' → R x y :=
⟨λ h a b c d e, h c d e a b, λ h c d e a b, h a b c d e⟩,
simp only [join, pairwise_append, IH, mem_join, exists_imp_distrib, and_imp, this, forall_mem_cons, pairwise_cons],
simp only [and_assoc, and_comm, and.left_comm],
end
@[simp] theorem pairwise_reverse : ∀ {R} {l : list α},
pairwise R (reverse l) ↔ pairwise (λ x y, R y x) l :=
suffices ∀ {R l}, @pairwise α R l → pairwise (λ x y, R y x) (reverse l),
from λ R l, ⟨λ p, reverse_reverse l ▸ this p, this⟩,
λ R l p, by induction p with a l h p IH;
[apply pairwise.nil, simpa only [reverse_cons, pairwise_append, IH,
pairwise_cons, forall_prop_of_false (not_mem_nil _), forall_true_iff,
pairwise.nil, mem_reverse, mem_singleton, forall_eq, true_and] using h]
theorem pairwise_iff_nth_le {R} : ∀ {l : list α},
pairwise R l ↔ ∀ i j (h₁ : j < length l) (h₂ : i < j), R (nth_le l i (lt_trans h₂ h₁)) (nth_le l j h₁)
| [] := by simp only [pairwise.nil, true_iff]; exact λ i j h, (not_lt_zero j).elim h
| (a::l) := begin
rw [pairwise_cons, pairwise_iff_nth_le],
refine ⟨λ H i j h₁ h₂, _, λ H, ⟨λ a' m, _,
λ i j h₁ h₂, H _ _ (succ_lt_succ h₁) (succ_lt_succ h₂)⟩⟩,
{ cases j with j, {exact (not_lt_zero _).elim h₂},
cases i with i,
{ exact H.1 _ (nth_le_mem l _ _) },
{ exact H.2 _ _ (lt_of_succ_lt_succ h₁) (lt_of_succ_lt_succ h₂) } },
{ rcases nth_le_of_mem m with ⟨n, h, rfl⟩,
exact H _ _ (succ_lt_succ h) (succ_pos _) }
end
theorem pairwise_sublists' {R} : ∀ {l : list α}, pairwise R l →
pairwise (lex (swap R)) (sublists' l)
| _ (pairwise.nil _) := pairwise_singleton _ _
| _ (@pairwise.cons _ _ a l H₁ H₂) :=
begin
simp only [sublists'_cons, pairwise_append, pairwise_map, mem_sublists', mem_map, exists_imp_distrib, and_imp],
have IH := pairwise_sublists' H₂,
refine ⟨IH, IH.imp (λ l₁ l₂, lex.cons), _⟩,
intros l₁ sl₁ x l₂ sl₂ e, subst e,
cases l₁ with b l₁, {constructor},
exact lex.rel (H₁ _ $ subset_of_sublist sl₁ $ mem_cons_self _ _)
end
theorem pairwise_sublists {R} {l : list α} (H : pairwise R l) :
pairwise (λ l₁ l₂, lex R (reverse l₁) (reverse l₂)) (sublists l) :=
by have := pairwise_sublists' (pairwise_reverse.2 H);
rwa [sublists'_reverse, pairwise_map] at this
variable [decidable_rel R]
instance decidable_pairwise (l : list α) : decidable (pairwise R l) :=
by induction l with hd tl ih; [exact is_true (pairwise.nil _),
exactI decidable_of_iff' _ pairwise_cons]
/- pairwise reduct -/
/-- `pw_filter R l` is a maximal sublist of `l` which is `pairwise R`.
`pw_filter (≠)` is the erase duplicates function, and `pw_filter (<)` finds
a maximal increasing subsequence in `l`. For example,
pw_filter (<) [0, 1, 5, 2, 6, 3, 4] = [0, 1, 5, 6] -/
def pw_filter (R : α → α → Prop) [decidable_rel R] : list α → list α
| [] := []
| (x :: xs) := let IH := pw_filter xs in if ∀ y ∈ IH, R x y then x :: IH else IH
@[simp] theorem pw_filter_nil : pw_filter R [] = [] := rfl
@[simp] theorem pw_filter_cons_of_pos {a : α} {l : list α} (h : ∀ b ∈ pw_filter R l, R a b) :
pw_filter R (a::l) = a :: pw_filter R l := if_pos h
@[simp] theorem pw_filter_cons_of_neg {a : α} {l : list α} (h : ¬ ∀ b ∈ pw_filter R l, R a b) :
pw_filter R (a::l) = pw_filter R l := if_neg h
theorem pw_filter_sublist : ∀ (l : list α), pw_filter R l <+ l
| [] := nil_sublist _
| (x::l) := begin
by_cases (∀ y ∈ pw_filter R l, R x y),
{ rw [pw_filter_cons_of_pos h],
exact cons_sublist_cons _ (pw_filter_sublist l) },
{ rw [pw_filter_cons_of_neg h],
exact sublist_cons_of_sublist _ (pw_filter_sublist l) },
end
theorem pw_filter_subset (l : list α) : pw_filter R l ⊆ l :=
subset_of_sublist (pw_filter_sublist _)
theorem pairwise_pw_filter : ∀ (l : list α), pairwise R (pw_filter R l)
| [] := pairwise.nil _
| (x::l) := begin
by_cases (∀ y ∈ pw_filter R l, R x y),
{ rw [pw_filter_cons_of_pos h],
exact pairwise_cons.2 ⟨h, pairwise_pw_filter l⟩ },
{ rw [pw_filter_cons_of_neg h],
exact pairwise_pw_filter l },
end
theorem pw_filter_eq_self {l : list α} : pw_filter R l = l ↔ pairwise R l :=
⟨λ e, e ▸ pairwise_pw_filter l, λ p, begin
induction l with x l IH, {refl},
cases pairwise_cons.1 p with al p,
rw [pw_filter_cons_of_pos (ball.imp_left (pw_filter_subset l) al), IH p],
end⟩
@[simp] theorem pw_filter_idempotent {l : list α} :
pw_filter R (pw_filter R l) = pw_filter R l :=
pw_filter_eq_self.mpr (pairwise_pw_filter l)
theorem forall_mem_pw_filter (neg_trans : ∀ {x y z}, R x z → R x y ∨ R y z)
(a : α) (l : list α) : (∀ b ∈ pw_filter R l, R a b) ↔ (∀ b ∈ l, R a b) :=
⟨begin
induction l with x l IH, { exact λ _ _, false.elim },
simp only [forall_mem_cons],
by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h,
{ simp only [pw_filter_cons_of_pos h, forall_mem_cons, and_imp],
exact λ r H, ⟨r, IH H⟩ },
{ rw [pw_filter_cons_of_neg h],
refine λ H, ⟨_, IH H⟩,
cases e : find (λ y, ¬ R x y) (pw_filter R l) with k,
{ refine h.elim (ball.imp_right _ (find_eq_none.1 e)),
exact λ y _, not_not.1 },
{ have := find_some e,
exact (neg_trans (H k (find_mem e))).resolve_right this } }
end, ball.imp_left (pw_filter_subset l)⟩
end pairwise
/- chain relation (conjunction of R a b ∧ R b c ∧ R c d ...) -/
section chain
variable (R : α → α → Prop)
/-- `chain R a l` means that `R` holds between adjacent elements of `a::l`.
`chain R a [b, c, d] ↔ R a b ∧ R b c ∧ R c d` -/
inductive chain : α → list α → Prop
| nil (a : α) : chain a []
| cons : ∀ {a b : α} {l : list α}, R a b → chain b l → chain a (b::l)
attribute [simp] chain.nil
run_cmd tactic.mk_iff_of_inductive_prop `list.chain `list.chain_iff
variable {R}
@[simp] theorem chain_cons {a b : α} {l : list α} :
chain R a (b::l) ↔ R a b ∧ chain R b l :=
⟨λ p, by cases p with _ a b l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩
theorem rel_of_chain_cons {a b : α} {l : list α}
(p : chain R a (b::l)) : R a b :=
(chain_cons.1 p).1
theorem chain_of_chain_cons {a b : α} {l : list α}
(p : chain R a (b::l)) : chain R b l :=
(chain_cons.1 p).2
theorem chain.imp {S : α → α → Prop}
(H : ∀ a b, R a b → S a b) {a : α} {l : list α} (p : chain R a l) : chain S a l :=
by induction p with _ a b l r p IH; constructor;
[exact H _ _ r, exact IH]
theorem chain.iff {S : α → α → Prop}
(H : ∀ a b, R a b ↔ S a b) {a : α} {l : list α} : chain R a l ↔ chain S a l :=
⟨chain.imp (λ a b, (H a b).1), chain.imp (λ a b, (H a b).2)⟩
theorem chain.iff_mem {S : α → α → Prop} {a : α} {l : list α} :
chain R a l ↔ chain (λ x y, x ∈ a :: l ∧ y ∈ l ∧ R x y) a l :=
⟨λ p, by induction p with _ a b l r p IH; constructor;
[exact ⟨mem_cons_self _ _, mem_cons_self _ _, r⟩,
exact IH.imp (λ a b ⟨am, bm, h⟩,
⟨mem_cons_of_mem _ am, mem_cons_of_mem _ bm, h⟩)],
chain.imp (λ a b h, h.2.2)⟩
theorem chain_singleton {a b : α} : chain R a [b] ↔ R a b :=
by simp only [chain_cons, chain.nil, and_true]
theorem chain_split {a b : α} {l₁ l₂ : list α} : chain R a (l₁++b::l₂) ↔
chain R a (l₁++[b]) ∧ chain R b l₂ :=
by induction l₁ with x l₁ IH generalizing a;
simp only [*, nil_append, cons_append, chain.nil, chain_cons, and_true, and_assoc]
theorem chain_map (f : β → α) {b : β} {l : list β} :
chain R (f b) (map f l) ↔ chain (λ a b : β, R (f a) (f b)) b l :=
by induction l generalizing b; simp only [map, chain.nil, chain_cons, *]
theorem chain_of_chain_map {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, S (f a) (f b) → R a b) {a : α} {l : list α}
(p : chain S (f a) (map f l)) : chain R a l :=
((chain_map f).1 p).imp H
theorem chain_map_of_chain {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, R a b → S (f a) (f b)) {a : α} {l : list α}
(p : chain R a l) : chain S (f a) (map f l) :=
(chain_map f).2 $ p.imp H
theorem chain_of_pairwise {a : α} {l : list α} (p : pairwise R (a::l)) : chain R a l :=
begin
cases pairwise_cons.1 p with r p', clear p,
induction p' with b l r' p IH generalizing a, {exact chain.nil _ _},
simp only [chain_cons, forall_mem_cons] at r,
exact chain_cons.2 ⟨r.1, IH r'⟩
end
theorem chain_iff_pairwise (tr : transitive R) {a : α} {l : list α} :
chain R a l ↔ pairwise R (a::l) :=
⟨λ c, begin
induction c with b b c l r p IH, {exact pairwise_singleton _ _},
apply IH.cons _, simp only [mem_cons_iff, forall_mem_cons', r, true_and],
show ∀ x ∈ l, R b x, from λ x m, (tr r (rel_of_pairwise_cons IH m)),
end, chain_of_pairwise⟩
instance decidable_chain [decidable_rel R] (a : α) (l : list α) : decidable (chain R a l) :=
by induction l generalizing a; simp only [chain.nil, chain_cons]; resetI; apply_instance
end chain
/- no duplicates predicate -/
/-- `nodup l` means that `l` has no duplicates, that is, any element appears at most
once in the list. It is defined as `pairwise (≠)`. -/
def nodup : list α → Prop := pairwise (≠)
section nodup
@[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l :=
⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩
@[simp] theorem nodup_nil : @nodup α [] := pairwise.nil _
@[simp] theorem nodup_cons {a : α} {l : list α} : nodup (a::l) ↔ a ∉ l ∧ nodup l :=
by simp only [nodup, pairwise_cons, forall_mem_ne]
lemma rel_nodup {r : α → β → Prop} (hr : relator.bi_unique r) : (forall₂ r ⇒ (↔)) nodup nodup
| _ _ forall₂.nil := by simp only [nodup_nil]
| _ _ (forall₂.cons hab h) :=
by simpa only [nodup_cons] using relator.rel_and (relator.rel_not (rel_mem hr hab h)) (rel_nodup h)
theorem nodup_cons_of_nodup {a : α} {l : list α} (m : a ∉ l) (n : nodup l) : nodup (a::l) :=
nodup_cons.2 ⟨m, n⟩
theorem nodup_singleton (a : α) : nodup [a] :=
nodup_cons_of_nodup (not_mem_nil a) nodup_nil
theorem nodup_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : nodup l :=
(nodup_cons.1 h).2
theorem not_mem_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : a ∉ l :=
(nodup_cons.1 h).1
theorem not_nodup_cons_of_mem {a : α} {l : list α} : a ∈ l → ¬ nodup (a :: l) :=
imp_not_comm.1 not_mem_of_nodup_cons
theorem nodup_of_sublist {l₁ l₂ : list α} : l₁ <+ l₂ → nodup l₂ → nodup l₁ :=
pairwise_of_sublist
theorem not_nodup_pair (a : α) : ¬ nodup [a, a] :=
not_nodup_cons_of_mem $ mem_singleton_self _
theorem nodup_iff_sublist {l : list α} : nodup l ↔ ∀ a, ¬ [a, a] <+ l :=
⟨λ d a h, not_nodup_pair a (nodup_of_sublist h d), begin
induction l with a l IH; intro h, {exact nodup_nil},
exact nodup_cons_of_nodup
(λ al, h a $ cons_sublist_cons _ $ singleton_sublist.2 al)
(IH $ λ a s, h a $ sublist_cons_of_sublist _ s)
end⟩
theorem nodup_iff_nth_le_inj {l : list α} :
nodup l ↔ ∀ i j h₁ h₂, nth_le l i h₁ = nth_le l j h₂ → i = j :=
pairwise_iff_nth_le.trans
⟨λ H i j h₁ h₂ h, ((lt_trichotomy _ _)
.resolve_left (λ h', H _ _ h₂ h' h))
.resolve_right (λ h', H _ _ h₁ h' h.symm),
λ H i j h₁ h₂ h, ne_of_lt h₂ (H _ _ _ _ h)⟩
@[simp] theorem nth_le_index_of [decidable_eq α] {l : list α} (H : nodup l) (n h) : index_of (nth_le l n h) l = n :=
nodup_iff_nth_le_inj.1 H _ _ _ h $
index_of_nth_le $ index_of_lt_length.2 $ nth_le_mem _ _ _
theorem nodup_iff_count_le_one [decidable_eq α] {l : list α} : nodup l ↔ ∀ a, count a l ≤ 1 :=
nodup_iff_sublist.trans $ forall_congr $ λ a,
have [a, a] <+ l ↔ 1 < count a l, from (@le_count_iff_repeat_sublist _ _ a l 2).symm,
(not_congr this).trans not_lt
@[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {l : list α}
(d : nodup l) (h : a ∈ l) : count a l = 1 :=
le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h)
theorem nodup_of_nodup_append_left {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₁ :=
nodup_of_sublist (sublist_append_left l₁ l₂)
theorem nodup_of_nodup_append_right {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₂ :=
nodup_of_sublist (sublist_append_right l₁ l₂)
theorem nodup_append {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup l₁ ∧ nodup l₂ ∧ disjoint l₁ l₂ :=
by simp only [nodup, pairwise_append, disjoint_iff_ne]
theorem disjoint_of_nodup_append {l₁ l₂ : list α} (d : nodup (l₁++l₂)) : disjoint l₁ l₂ :=
(nodup_append.1 d).2.2
theorem nodup_append_of_nodup {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) (dj : disjoint l₁ l₂) : nodup (l₁++l₂) :=
nodup_append.2 ⟨d₁, d₂, dj⟩
theorem nodup_app_comm {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup (l₂++l₁) :=
by simp only [nodup_append, and.left_comm, disjoint_comm]
theorem nodup_middle {a : α} {l₁ l₂ : list α} : nodup (l₁ ++ a::l₂) ↔ nodup (a::(l₁++l₂)) :=
by simp only [nodup_append, not_or_distrib, and.left_comm, and_assoc, nodup_cons, mem_append, disjoint_cons_right]
theorem nodup_of_nodup_map (f : α → β) {l : list α} : nodup (map f l) → nodup l :=
pairwise_of_pairwise_map f $ λ a b, mt $ congr_arg f
theorem nodup_map_on {f : α → β} {l : list α} (H : ∀x∈l, ∀y∈l, f x = f y → x = y)
(d : nodup l) : nodup (map f l) :=
pairwise_map_of_pairwise _ (by exact λ a b ⟨ma, mb, n⟩ e, n (H a ma b mb e)) (pairwise.and_mem.1 d)
theorem nodup_map {f : α → β} {l : list α} (hf : injective f) : nodup l → nodup (map f l) :=
nodup_map_on (assume x _ y _ h, hf h)
theorem nodup_map_iff {f : α → β} {l : list α} (hf : injective f) : nodup (map f l) ↔ nodup l :=
⟨nodup_of_nodup_map _, nodup_map hf⟩
@[simp] theorem nodup_attach {l : list α} : nodup (attach l) ↔ nodup l :=
⟨λ h, attach_map_val l ▸ nodup_map (λ a b, subtype.eq) h,
λ h, nodup_of_nodup_map subtype.val ((attach_map_val l).symm ▸ h)⟩
theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {l : list α} {H}
(hf : ∀ a ha b hb, f a ha = f b hb → a = b) (h : nodup l) : nodup (pmap f l H) :=
by rw [pmap_eq_map_attach]; exact nodup_map
(λ ⟨a, ha⟩ ⟨b, hb⟩ h, by congr; exact hf a (H _ ha) b (H _ hb) h)
(nodup_attach.2 h)
theorem nodup_filter (p : α → Prop) [decidable_pred p] {l} : nodup l → nodup (filter p l) :=
pairwise_filter_of_pairwise p
@[simp] theorem nodup_reverse {l : list α} : nodup (reverse l) ↔ nodup l :=
pairwise_reverse.trans $ by simp only [nodup, ne.def, eq_comm]
instance nodup_decidable [decidable_eq α] : ∀ l : list α, decidable (nodup l) :=
list.decidable_pairwise
theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {l} (d : nodup l) : l.erase a = filter (≠ a) l :=
begin
induction d with b l m d IH, {refl},
by_cases b = a,
{ subst h, rw [erase_cons_head, filter_cons_of_neg],
symmetry, rw filter_eq_self, simpa only [ne.def, eq_comm] using m, exact not_not_intro rfl },
{ rw [erase_cons_tail _ h, filter_cons_of_pos, IH], exact h }
end
theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) :=
nodup_of_sublist (erase_sublist _ _)
theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) :
a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l :=
by rw nodup_erase_eq_filter b d; simp only [mem_filter, and_comm]
theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a :=
λ H, ((mem_erase_iff_of_nodup h).1 H).1 rfl
theorem nodup_join {L : list (list α)} : nodup (join L) ↔ (∀ l ∈ L, nodup l) ∧ pairwise disjoint L :=
by simp only [nodup, pairwise_join, disjoint_left.symm, forall_mem_ne]
theorem nodup_bind {l₁ : list α} {f : α → list β} : nodup (l₁.bind f) ↔
(∀ x ∈ l₁, nodup (f x)) ∧ pairwise (λ (a b : α), disjoint (f a) (f b)) l₁ :=
by simp only [list.bind, nodup_join, pairwise_map, and_comm, and.left_comm, mem_map, exists_imp_distrib, and_imp];
rw [show (∀ (l : list β) (x : α), f x = l → x ∈ l₁ → nodup l) ↔
(∀ (x : α), x ∈ l₁ → nodup (f x)),
from forall_swap.trans $ forall_congr $ λ_, forall_eq']
theorem nodup_product {l₁ : list α} {l₂ : list β} (d₁ : nodup l₁) (d₂ : nodup l₂) :
nodup (product l₁ l₂) :=
nodup_bind.2
⟨λ a ma, nodup_map (injective_of_left_inverse (λ b, (rfl : (a,b).2 = b))) d₂,
d₁.imp $ λ a₁ a₂ n x h₁ h₂, begin
rcases mem_map.1 h₁ with ⟨b₁, mb₁, rfl⟩,
rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩,
exact n rfl
end⟩
theorem nodup_sigma {σ : α → Type*} {l₁ : list α} {l₂ : Π a, list (σ a)}
(d₁ : nodup l₁) (d₂ : ∀ a, nodup (l₂ a)) : nodup (l₁.sigma l₂) :=
nodup_bind.2
⟨λ a ma, nodup_map (λ b b' h, by injection h with _ h; exact eq_of_heq h) (d₂ a),
d₁.imp $ λ a₁ a₂ n x h₁ h₂, begin
rcases mem_map.1 h₁ with ⟨b₁, mb₁, rfl⟩,
rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩,
exact n rfl
end⟩
theorem nodup_filter_map {f : α → option β} {l : list α}
(H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') :
nodup l → nodup (filter_map f l) :=
pairwise_filter_map_of_pairwise f $ λ a a' n b bm b' bm' e, n $ H a a' b' (e ▸ bm) bm'
theorem nodup_concat {a : α} {l : list α} (h : a ∉ l) (h' : nodup l) : nodup (concat l a) :=
by rw concat_eq_append; exact nodup_append_of_nodup h' (nodup_singleton _) (disjoint_singleton.2 h)
theorem nodup_insert [decidable_eq α] {a : α} {l : list α} (h : nodup l) : nodup (insert a l) :=
if h' : a ∈ l then by rw [insert_of_mem h']; exact h
else by rw [insert_of_not_mem h', nodup_cons]; split; assumption
theorem nodup_union [decidable_eq α] (l₁ : list α) {l₂ : list α} (h : nodup l₂) :
nodup (l₁ ∪ l₂) :=
begin
induction l₁ with a l₁ ih generalizing l₂,
{ exact h },
apply nodup_insert,
exact ih h
end
theorem nodup_inter_of_nodup [decidable_eq α] {l₁ : list α} (l₂) : nodup l₁ → nodup (l₁ ∩ l₂) :=
nodup_filter _
@[simp] theorem nodup_sublists {l : list α} : nodup (sublists l) ↔ nodup l :=
⟨λ h, nodup_of_nodup_map _ (nodup_of_sublist (map_ret_sublist_sublists _) h),
λ h, (pairwise_sublists h).imp (λ _ _ h, mt reverse_inj.2 h.to_ne)⟩
@[simp] theorem nodup_sublists' {l : list α} : nodup (sublists' l) ↔ nodup l :=
by rw [sublists'_eq_sublists, nodup_map_iff reverse_injective,
nodup_sublists, nodup_reverse]
end nodup
/- erase duplicates function -/
section erase_dup
variable [decidable_eq α]
/-- `erase_dup l` removes duplicates from `l` (taking only the first occurrence).
erase_dup [1, 2, 2, 0, 1] = [1, 2, 0] -/
def erase_dup : list α → list α := pw_filter (≠)
@[simp] theorem erase_dup_nil : erase_dup [] = ([] : list α) := rfl
theorem erase_dup_cons_of_mem' {a : α} {l : list α} (h : a ∈ erase_dup l) :
erase_dup (a::l) = erase_dup l :=
pw_filter_cons_of_neg $ by simpa only [forall_mem_ne] using h
theorem erase_dup_cons_of_not_mem' {a : α} {l : list α} (h : a ∉ erase_dup l) :
erase_dup (a::l) = a :: erase_dup l :=
pw_filter_cons_of_pos $ by simpa only [forall_mem_ne] using h
@[simp] theorem mem_erase_dup {a : α} {l : list α} : a ∈ erase_dup l ↔ a ∈ l :=
by simpa only [erase_dup, forall_mem_ne, not_not] using not_congr (@forall_mem_pw_filter α (≠) _
(λ x y z xz, not_and_distrib.1 $ mt (and.rec eq.trans) xz) a l)
@[simp] theorem erase_dup_cons_of_mem {a : α} {l : list α} (h : a ∈ l) :
erase_dup (a::l) = erase_dup l :=
erase_dup_cons_of_mem' $ mem_erase_dup.2 h
@[simp] theorem erase_dup_cons_of_not_mem {a : α} {l : list α} (h : a ∉ l) :
erase_dup (a::l) = a :: erase_dup l :=
erase_dup_cons_of_not_mem' $ mt mem_erase_dup.1 h
theorem erase_dup_sublist : ∀ (l : list α), erase_dup l <+ l := pw_filter_sublist
theorem erase_dup_subset : ∀ (l : list α), erase_dup l ⊆ l := pw_filter_subset
theorem subset_erase_dup (l : list α) : l ⊆ erase_dup l :=
λ a, mem_erase_dup.2
theorem nodup_erase_dup : ∀ l : list α, nodup (erase_dup l) := pairwise_pw_filter
theorem erase_dup_eq_self {l : list α} : erase_dup l = l ↔ nodup l := pw_filter_eq_self
@[simp] theorem erase_dup_idempotent {l : list α} : erase_dup (erase_dup l) = erase_dup l :=
pw_filter_idempotent
theorem erase_dup_append (l₁ l₂ : list α) : erase_dup (l₁ ++ l₂) = l₁ ∪ erase_dup l₂ :=
begin
induction l₁ with a l₁ IH, {refl}, rw [cons_union, ← IH],
show erase_dup (a :: (l₁ ++ l₂)) = insert a (erase_dup (l₁ ++ l₂)),
by_cases a ∈ erase_dup (l₁ ++ l₂);
[ rw [erase_dup_cons_of_mem' h, insert_of_mem h],
rw [erase_dup_cons_of_not_mem' h, insert_of_not_mem h]]
end
end erase_dup
/- iota and range -/
/-- `range' s n` is the list of numbers `[s, s+1, ..., s+n-1]`.
It is intended mainly for proving properties of `range` and `iota`. -/
@[simp] def range' : ℕ → ℕ → list ℕ
| s 0 := []
| s (n+1) := s :: range' (s+1) n
@[simp] theorem length_range' : ∀ (s n : ℕ), length (range' s n) = n
| s 0 := rfl
| s (n+1) := congr_arg succ (length_range' _ _)
@[simp] theorem mem_range' {m : ℕ} : ∀ {s n : ℕ}, m ∈ range' s n ↔ s ≤ m ∧ m < s + n
| s 0 := (false_iff _).2 $ λ ⟨H1, H2⟩, not_le_of_lt H2 H1
| s (succ n) :=
have m = s → m < s + n + 1,
from λ e, e ▸ lt_succ_of_le (le_add_right _ _),
have l : m = s ∨ s + 1 ≤ m ↔ s ≤ m,
by simpa only [eq_comm] using (@le_iff_eq_or_lt _ _ s m).symm,
(mem_cons_iff _ _ _).trans $ by simp only [mem_range',
or_and_distrib_left, or_iff_right_of_imp this, l, add_right_comm]; refl
theorem map_add_range' (a) : ∀ s n : ℕ, map ((+) a) (range' s n) = range' (a + s) n
| s 0 := rfl
| s (n+1) := congr_arg (cons _) (map_add_range' (s+1) n)
theorem chain_succ_range' : ∀ s n : ℕ, chain (λ a b, b = succ a) s (range' (s+1) n)
| s 0 := chain.nil _ _
| s (n+1) := (chain_succ_range' (s+1) n).cons rfl
theorem chain_lt_range' (s n : ℕ) : chain (<) s (range' (s+1) n) :=
(chain_succ_range' s n).imp (λ a b e, e.symm ▸ lt_succ_self _)
theorem pairwise_lt_range' : ∀ s n : ℕ, pairwise (<) (range' s n)
| s 0 := pairwise.nil _
| s (n+1) := (chain_iff_pairwise (by exact λ a b c, lt_trans)).1 (chain_lt_range' s n)
theorem nodup_range' (s n : ℕ) : nodup (range' s n) :=
(pairwise_lt_range' s n).imp (λ a b, ne_of_lt)
theorem range'_append : ∀ s m n : ℕ, range' s m ++ range' (s+m) n = range' s (n+m)
| s 0 n := rfl
| s (m+1) n := show s :: (range' (s+1) m ++ range' (s+m+1) n) = s :: range' (s+1) (n+m),
by rw [add_right_comm, range'_append]
theorem range'_sublist_right {s m n : ℕ} : range' s m <+ range' s n ↔ m ≤ n :=
⟨λ h, by simpa only [length_range'] using length_le_of_sublist h,
λ h, by rw [← nat.sub_add_cancel h, ← range'_append]; apply sublist_append_left⟩
theorem range'_subset_right {s m n : ℕ} : range' s m ⊆ range' s n ↔ m ≤ n :=
⟨λ h, le_of_not_lt $ λ hn, lt_irrefl (s+n) $
(mem_range'.1 $ h $ mem_range'.2 ⟨le_add_right _ _, nat.add_lt_add_left hn s⟩).2,
λ h, subset_of_sublist (range'_sublist_right.2 h)⟩
theorem nth_range' : ∀ s {m n : ℕ}, m < n → nth (range' s n) m = some (s + m)
| s 0 (n+1) _ := rfl
| s (m+1) (n+1) h := (nth_range' (s+1) (lt_of_add_lt_add_right h)).trans $ by rw add_right_comm; refl
theorem range'_concat (s n : ℕ) : range' s (n + 1) = range' s n ++ [s+n] :=
by rw add_comm n 1; exact (range'_append s n 1).symm
theorem range_core_range' : ∀ s n : ℕ, range_core s (range' s n) = range' 0 (n + s)
| 0 n := rfl
| (s+1) n := by rw [show n+(s+1) = n+1+s, from add_right_comm n s 1]; exact range_core_range' s (n+1)
theorem range_eq_range' (n : ℕ) : range n = range' 0 n :=
(range_core_range' n 0).trans $ by rw zero_add
theorem range_succ_eq_map (n : ℕ) : range (n + 1) = 0 :: map succ (range n) :=
by rw [range_eq_range', range_eq_range', range',
add_comm, ← map_add_range'];
congr; exact funext one_add
theorem range'_eq_map_range (s n : ℕ) : range' s n = map ((+) s) (range n) :=
by rw [range_eq_range', map_add_range']; refl
@[simp] theorem length_range (n : ℕ) : length (range n) = n :=
by simp only [range_eq_range', length_range']
theorem pairwise_lt_range (n : ℕ) : pairwise (<) (range n) :=
by simp only [range_eq_range', pairwise_lt_range']
theorem nodup_range (n : ℕ) : nodup (range n) :=
by simp only [range_eq_range', nodup_range']
theorem range_sublist {m n : ℕ} : range m <+ range n ↔ m ≤ n :=
by simp only [range_eq_range', range'_sublist_right]
theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n :=
by simp only [range_eq_range', range'_subset_right]
@[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n :=
by simp only [range_eq_range', mem_range', nat.zero_le, true_and, zero_add]
@[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n :=
mt mem_range.1 $ lt_irrefl _
theorem nth_range {m n : ℕ} (h : m < n) : nth (range n) m = some m :=
by simp only [range_eq_range', nth_range' _ h, zero_add]
theorem range_concat (n : ℕ) : range (n + 1) = range n ++ [n] :=
by simp only [range_eq_range', range'_concat, zero_add]
theorem iota_eq_reverse_range' : ∀ n : ℕ, iota n = reverse (range' 1 n)
| 0 := rfl
| (n+1) := by simp only [iota, range'_concat, iota_eq_reverse_range' n, reverse_append, add_comm]; refl
@[simp] theorem length_iota (n : ℕ) : length (iota n) = n :=
by simp only [iota_eq_reverse_range', length_reverse, length_range']
theorem pairwise_gt_iota (n : ℕ) : pairwise (>) (iota n) :=
by simp only [iota_eq_reverse_range', pairwise_reverse, pairwise_lt_range']
theorem nodup_iota (n : ℕ) : nodup (iota n) :=
by simp only [iota_eq_reverse_range', nodup_reverse, nodup_range']
theorem mem_iota {m n : ℕ} : m ∈ iota n ↔ 1 ≤ m ∧ m ≤ n :=
by simp only [iota_eq_reverse_range', mem_reverse, mem_range', add_comm, lt_succ_iff]
theorem reverse_range' : ∀ s n : ℕ,
reverse (range' s n) = map (λ i, s + n - 1 - i) (range n)
| s 0 := rfl
| s (n+1) := by rw [range'_concat, reverse_append, range_succ_eq_map];
simpa only [show s + (n + 1) - 1 = s + n, from rfl, (∘),
λ a i, show a - 1 - i = a - succ i, from pred_sub _ _,
reverse_singleton, map_cons, nat.sub_zero, cons_append,
nil_append, eq_self_iff_true, true_and, map_map]
using reverse_range' s n
@[simp] theorem enum_from_map_fst : ∀ n (l : list α),
map prod.fst (enum_from n l) = range' n l.length
| n [] := rfl
| n (a :: l) := congr_arg (cons _) (enum_from_map_fst _ _)
@[simp] theorem enum_map_fst (l : list α) :
map prod.fst (enum l) = range l.length :=
by simp only [enum, enum_from_map_fst, range_eq_range']
def reduce_option {α} : list (option α) → list α :=
list.filter_map id
def map_head {α} (f : α → α) : list α → list α
| [] := []
| (x :: xs) := f x :: xs
def map_last {α} (f : α → α) : list α → list α
| [] := []
| [x] := [f x]
| (x :: xs) := x :: map_last xs
@[simp] def last' {α} : α → list α → α
| a [] := a
| a (b::l) := last' b l
theorem last'_mem {α} : ∀ a l, @last' α a l ∈ a :: l
| a [] := or.inl rfl
| a (b::l) := or.inr (last'_mem b l)
@[simp] lemma nth_le_attach {α} (L : list α) (i) (H : i < L.attach.length) :
(L.attach.nth_le i H).1 = L.nth_le i (length_attach L ▸ H) :=
calc (L.attach.nth_le i H).1
= (L.attach.map subtype.val).nth_le i (by simpa using H) : by rw nth_le_map'
... = L.nth_le i _ : by congr; apply attach_map_val
@[simp] lemma nth_le_range {n} (i) (H : i < (range n).length) :
nth_le (range n) i H = i :=
option.some.inj $ by rw [← nth_le_nth _, nth_range (by simpa using H)]
theorem of_fn_eq_pmap {α n} {f : fin n → α} :
of_fn f = pmap (λ i hi, f ⟨i, hi⟩) (range n) (λ _, mem_range.1) :=
by rw [pmap_eq_map_attach]; from ext_le (by simp)
(λ i hi1 hi2, by simp at hi1; simp [nth_le_of_fn f ⟨i, hi1⟩])
theorem nodup_of_fn {α n} {f : fin n → α} (hf : function.injective f) :
nodup (of_fn f) :=
by rw of_fn_eq_pmap; from nodup_pmap
(λ _ _ _ _ H, fin.veq_of_eq $ hf H) (nodup_range n)
section tfae
/-- tfae: The Following (propositions) Are Equivalent -/
def tfae (l : list Prop) : Prop := ∀ x ∈ l, ∀ y ∈ l, x ↔ y
theorem tfae_nil : tfae [] := forall_mem_nil _
theorem tfae_singleton (p) : tfae [p] := by simp [tfae]
theorem tfae_cons_of_mem {a b} {l : list Prop} (h : b ∈ l) :
tfae (a::l) ↔ (a ↔ b) ∧ tfae l :=
⟨λ H, ⟨H a (by simp) b (or.inr h), λ p hp q hq, H _ (or.inr hp) _ (or.inr hq)⟩,
begin
rintro ⟨ab, H⟩ p (rfl | hp) q (rfl | hq),
{ refl },
{ exact ab.trans (H _ h _ hq) },
{ exact (ab.trans (H _ h _ hp)).symm },
{ exact H _ hp _ hq }
end⟩
theorem tfae_cons_cons {a b} {l : list Prop} : tfae (a::b::l) ↔ (a ↔ b) ∧ tfae (b::l) :=
tfae_cons_of_mem (or.inl rfl)
theorem tfae_of_forall (b : Prop) (l : list Prop) (h : ∀ a ∈ l, a ↔ b) : tfae l :=
λ a₁ h₁ a₂ h₂, (h _ h₁).trans (h _ h₂).symm
theorem tfae_of_cycle {a b} {l : list Prop} :
list.chain (→) a (b::l) → (last' b l → a) → tfae (a::b::l) :=
begin
induction l with c l IH generalizing a b; simp [tfae_cons_cons, tfae_singleton] at *,
{ exact iff.intro },
intros ab bc ch la,
have := IH bc ch (ab ∘ la),
exact ⟨⟨ab, la ∘ (this.2 c (or.inl rfl) _ (last'_mem _ _)).1 ∘ bc⟩, this⟩
end
theorem tfae.out {l} (h : tfae l) (n₁ n₂)
(h₁ : n₁ < list.length l . tactic.exact_dec_trivial)
(h₂ : n₂ < list.length l . tactic.exact_dec_trivial) :
list.nth_le l n₁ h₁ ↔ list.nth_le l n₂ h₂ :=
h _ (list.nth_le_mem _ _ _) _ (list.nth_le_mem _ _ _)
end tfae
section choose
variables (p : α → Prop) [decidable_pred p] (l : list α)
def choose_x : Π l : list α, Π hp : (∃ a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a }
| [] hp := false.elim (exists.elim hp (assume a h, not_mem_nil a h.left))
| (l :: ls) hp := if pl : p l then ⟨l, ⟨or.inl rfl, pl⟩⟩ else
subtype.rec_on (choose_x ls
begin
rcases hp with ⟨a, rfl | a_mem_ls, pa⟩,
{ exfalso; apply pl pa },
{ exact ⟨a, a_mem_ls, pa⟩ }
end) (λ a ⟨a_mem_ls, pa⟩, ⟨a, ⟨or.inr a_mem_ls, pa⟩⟩)
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
end list
theorem option.to_list_nodup {α} : ∀ o : option α, o.to_list.nodup
| none := list.nodup_nil
| (some x) := list.nodup_singleton x
|
2d1e8c5c2f7c3b143170e9c436a4530a3ae28ed6 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/order/monotone/odd.lean | 54fa7633b1132256eddaa47d288ce7d9c9eacb43 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 2,439 | lean | /-
Copyright (c) 2022 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import order.monotone.union
import algebra.order.group.instances
/-!
# Monotonicity of odd functions
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
An odd function on a linear ordered additive commutative group `G` is monotone on the whole group
provided that is is monotone on `set.Ici 0`, see `monotone_of_odd_of_monotone_on_nonneg`. We also
prove versions of this lemma for `antitone`, `strict_mono`, and `strict_anti`.
-/
open set
variables {G H : Type*} [linear_ordered_add_comm_group G] [ordered_add_comm_group H]
/-- An odd function on a linear ordered additive commutative group is strictly monotone on the whole
group provided that it is strictly monotone on `set.Ici 0`. -/
lemma strict_mono_of_odd_strict_mono_on_nonneg {f : G → H} (h₁ : ∀ x, f (-x) = -f x)
(h₂ : strict_mono_on f (Ici 0)) :
strict_mono f :=
begin
refine strict_mono_on.Iic_union_Ici (λ x hx y hy hxy, neg_lt_neg_iff.1 _) h₂,
rw [← h₁, ← h₁],
exact h₂ (neg_nonneg.2 hy) (neg_nonneg.2 hx) (neg_lt_neg hxy)
end
/-- An odd function on a linear ordered additive commutative group is strictly antitone on the whole
group provided that it is strictly antitone on `set.Ici 0`. -/
lemma strict_anti_of_odd_strict_anti_on_nonneg {f : G → H} (h₁ : ∀ x, f (-x) = -f x)
(h₂ : strict_anti_on f (Ici 0)) :
strict_anti f :=
@strict_mono_of_odd_strict_mono_on_nonneg G Hᵒᵈ _ _ _ h₁ h₂
/-- An odd function on a linear ordered additive commutative group is monotone on the whole group
provided that it is monotone on `set.Ici 0`. -/
lemma monotone_of_odd_of_monotone_on_nonneg {f : G → H} (h₁ : ∀ x, f (-x) = -f x)
(h₂ : monotone_on f (Ici 0)) : monotone f :=
begin
refine monotone_on.Iic_union_Ici (λ x hx y hy hxy, neg_le_neg_iff.1 _) h₂,
rw [← h₁, ← h₁],
exact h₂ (neg_nonneg.2 hy) (neg_nonneg.2 hx) (neg_le_neg hxy)
end
/-- An odd function on a linear ordered additive commutative group is antitone on the whole group
provided that it is monotone on `set.Ici 0`. -/
lemma antitone_of_odd_of_monotone_on_nonneg {f : G → H} (h₁ : ∀ x, f (-x) = -f x)
(h₂ : antitone_on f (Ici 0)) : antitone f :=
@monotone_of_odd_of_monotone_on_nonneg G Hᵒᵈ _ _ _ h₁ h₂
|
418551ae928ab743828750559d6620d260fe0b62 | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/data/list/sigma.lean | 4e5d1ef4eff21f608b4286b92e41f4033d5f3c8d | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 21,011 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Sean Leather
Functions on lists of sigma types.
-/
import data.list.perm data.sigma
universes u v
namespace list
variables {α : Type u} {β : α → Type v}
/- keys -/
/-- List of keys from a list of key-value pairs -/
def keys : list (sigma β) → list α :=
map sigma.fst
@[simp] theorem keys_nil : @keys α β [] = [] :=
rfl
@[simp] theorem keys_cons {s} {l : list (sigma β)} : (s :: l).keys = s.1 :: l.keys :=
rfl
theorem mem_keys_of_mem {s : sigma β} {l : list (sigma β)} : s ∈ l → s.1 ∈ l.keys :=
mem_map_of_mem sigma.fst
theorem exists_of_mem_keys {a} {l : list (sigma β)} (h : a ∈ l.keys) :
∃ (b : β a), sigma.mk a b ∈ l :=
let ⟨⟨a', b'⟩, m, e⟩ := exists_of_mem_map h in
eq.rec_on e (exists.intro b' m)
theorem mem_keys {a} {l : list (sigma β)} : a ∈ l.keys ↔ ∃ (b : β a), sigma.mk a b ∈ l :=
⟨exists_of_mem_keys, λ ⟨b, h⟩, mem_keys_of_mem h⟩
theorem not_mem_keys {a} {l : list (sigma β)} : a ∉ l.keys ↔ ∀ b : β a, sigma.mk a b ∉ l :=
(not_iff_not_of_iff mem_keys).trans not_exists
theorem not_eq_key {a} {l : list (sigma β)} : a ∉ l.keys ↔ ∀ s : sigma β, s ∈ l → a ≠ s.1 :=
iff.intro
(λ h₁ s h₂ e, absurd (mem_keys_of_mem h₂) (by rwa e at h₁))
(λ f h₁, let ⟨b, h₂⟩ := exists_of_mem_keys h₁ in f _ h₂ rfl)
/- nodupkeys -/
def nodupkeys (l : list (sigma β)) : Prop :=
l.keys.nodup
theorem nodupkeys_iff_pairwise {l} : nodupkeys l ↔
pairwise (λ s s' : sigma β, s.1 ≠ s'.1) l := pairwise_map _
@[simp] theorem nodupkeys_nil : @nodupkeys α β [] := pairwise.nil
@[simp] theorem nodupkeys_cons {s : sigma β} {l : list (sigma β)} :
nodupkeys (s::l) ↔ s.1 ∉ l.keys ∧ nodupkeys l :=
by simp [keys, nodupkeys]
theorem nodupkeys.eq_of_fst_eq {l : list (sigma β)}
(nd : nodupkeys l) {s s' : sigma β} (h : s ∈ l) (h' : s' ∈ l) :
s.1 = s'.1 → s = s' :=
@forall_of_forall_of_pairwise _
(λ s s' : sigma β, s.1 = s'.1 → s = s')
(λ s s' H h, (H h.symm).symm) _ (λ x h _, rfl)
((nodupkeys_iff_pairwise.1 nd).imp (λ s s' h h', (h h').elim)) _ h _ h'
theorem nodupkeys.eq_of_mk_mem {a : α} {b b' : β a} {l : list (sigma β)}
(nd : nodupkeys l) (h : sigma.mk a b ∈ l) (h' : sigma.mk a b' ∈ l) : b = b' :=
by cases nd.eq_of_fst_eq h h' rfl; refl
theorem nodupkeys_singleton (s : sigma β) : nodupkeys [s] := nodup_singleton _
theorem nodupkeys_of_sublist {l₁ l₂ : list (sigma β)} (h : l₁ <+ l₂) : nodupkeys l₂ → nodupkeys l₁ :=
nodup_of_sublist (map_sublist_map _ h)
theorem nodup_of_nodupkeys {l : list (sigma β)} : nodupkeys l → nodup l :=
nodup_of_nodup_map _
theorem perm_nodupkeys {l₁ l₂ : list (sigma β)} (h : l₁ ~ l₂) : nodupkeys l₁ ↔ nodupkeys l₂ :=
perm_nodup $ perm_map _ h
theorem nodupkeys_join {L : list (list (sigma β))} :
nodupkeys (join L) ↔ (∀ l ∈ L, nodupkeys l) ∧ pairwise disjoint (L.map keys) :=
begin
rw [nodupkeys_iff_pairwise, pairwise_join, pairwise_map],
refine and_congr (ball_congr $ λ l h, by simp [nodupkeys_iff_pairwise]) _,
apply iff_of_eq, congr', ext l₁ l₂,
simp [keys, disjoint_iff_ne]
end
theorem nodup_enum_map_fst (l : list α) : (l.enum.map prod.fst).nodup :=
by simp [list.nodup_range]
variables [decidable_eq α]
/- lookup -/
/-- `lookup a l` is the first value in `l` corresponding to the key `a`,
or `none` if no such element exists. -/
def lookup (a : α) : list (sigma β) → option (β a)
| [] := none
| (⟨a', b⟩ :: l) := if h : a' = a then some (eq.rec_on h b) else lookup l
@[simp] theorem lookup_nil (a : α) : lookup a [] = @none (β a) := rfl
@[simp] theorem lookup_cons_eq (l) (a : α) (b : β a) : lookup a (⟨a, b⟩::l) = some b :=
dif_pos rfl
@[simp] theorem lookup_cons_ne (l) {a} :
∀ s : sigma β, a ≠ s.1 → lookup a (s::l) = lookup a l
| ⟨a', b⟩ h := dif_neg h.symm
theorem lookup_is_some {a : α} : ∀ {l : list (sigma β)},
(lookup a l).is_some ↔ a ∈ l.keys
| [] := by simp
| (⟨a', b⟩ :: l) := begin
by_cases h : a = a',
{ subst a', simp },
{ simp [h, lookup_is_some] },
end
theorem lookup_eq_none {a : α} {l : list (sigma β)} :
lookup a l = none ↔ a ∉ l.keys :=
begin
have := not_congr (@lookup_is_some _ _ _ a l),
simp at this, refine iff.trans _ this,
cases lookup a l; exact dec_trivial
end
theorem of_mem_lookup
{a : α} {b : β a} : ∀ {l : list (sigma β)}, b ∈ lookup a l → sigma.mk a b ∈ l
| (⟨a', b'⟩ :: l) H := begin
by_cases h : a = a',
{ subst a', simp at H, simp [H] },
{ simp [h] at H, exact or.inr (of_mem_lookup H) }
end
theorem mem_lookup {a} {b : β a} {l : list (sigma β)} (nd : l.nodupkeys)
(h : sigma.mk a b ∈ l) : b ∈ lookup a l :=
begin
cases option.is_some_iff_exists.mp (lookup_is_some.mpr (mem_keys_of_mem h)) with b' h',
cases nd.eq_of_mk_mem h (of_mem_lookup h'),
exact h'
end
theorem map_lookup_eq_find (a : α) : ∀ l : list (sigma β),
(lookup a l).map (sigma.mk a) = find (λ s, a = s.1) l
| [] := rfl
| (⟨a', b'⟩ :: l) := begin
by_cases h : a = a',
{ subst a', simp },
{ simp [h, map_lookup_eq_find] }
end
theorem mem_lookup_iff {a : α} {b : β a} {l : list (sigma β)} (nd : l.nodupkeys) :
b ∈ lookup a l ↔ sigma.mk a b ∈ l :=
⟨of_mem_lookup, mem_lookup nd⟩
theorem perm_lookup (a : α) {l₁ l₂ : list (sigma β)}
(nd₁ : l₁.nodupkeys) (nd₂ : l₂.nodupkeys) (p : l₁ ~ l₂) : lookup a l₁ = lookup a l₂ :=
by ext b; simp [mem_lookup_iff, nd₁, nd₂]; exact mem_of_perm p
/- lookup_all -/
/-- `lookup_all a l` is the list of all values in `l` corresponding to the key `a`. -/
def lookup_all (a : α) : list (sigma β) → list (β a)
| [] := []
| (⟨a', b⟩ :: l) := if h : a' = a then eq.rec_on h b :: lookup_all l else lookup_all l
@[simp] theorem lookup_all_nil (a : α) : lookup_all a [] = @nil (β a) := rfl
@[simp] theorem lookup_all_cons_eq (l) (a : α) (b : β a) :
lookup_all a (⟨a, b⟩::l) = b :: lookup_all a l :=
dif_pos rfl
@[simp] theorem lookup_all_cons_ne (l) {a} :
∀ s : sigma β, a ≠ s.1 → lookup_all a (s::l) = lookup_all a l
| ⟨a', b⟩ h := dif_neg h.symm
theorem lookup_all_eq_nil {a : α} : ∀ {l : list (sigma β)},
lookup_all a l = [] ↔ ∀ b : β a, sigma.mk a b ∉ l
| [] := by simp
| (⟨a', b⟩ :: l) := begin
by_cases h : a = a',
{ subst a', simp, exact λ H, H b (or.inl rfl) },
{ simp [h, lookup_all_eq_nil] },
end
theorem head_lookup_all (a : α) : ∀ l : list (sigma β),
head' (lookup_all a l) = lookup a l
| [] := by simp
| (⟨a', b⟩ :: l) := by by_cases h : a = a'; [{subst h, simp}, simp *]
theorem mem_lookup_all {a : α} {b : β a} :
∀ {l : list (sigma β)}, b ∈ lookup_all a l ↔ sigma.mk a b ∈ l
| [] := by simp
| (⟨a', b'⟩ :: l) := by by_cases h : a = a'; [{subst h, simp *}, simp *]
theorem lookup_all_sublist (a : α) :
∀ l : list (sigma β), (lookup_all a l).map (sigma.mk a) <+ l
| [] := by simp
| (⟨a', b'⟩ :: l) := begin
by_cases h : a = a',
{ subst h, simp, exact (lookup_all_sublist l).cons2 _ _ _ },
{ simp [h], exact (lookup_all_sublist l).cons _ _ _ }
end
theorem lookup_all_length_le_one (a : α) {l : list (sigma β)} (h : l.nodupkeys) :
length (lookup_all a l) ≤ 1 :=
by have := nodup_of_sublist (map_sublist_map _ $ lookup_all_sublist a l) h;
rw map_map at this; rwa [← nodup_repeat, ← map_const _ a]
theorem lookup_all_eq_lookup (a : α) {l : list (sigma β)} (h : l.nodupkeys) :
lookup_all a l = (lookup a l).to_list :=
begin
rw ← head_lookup_all,
have := lookup_all_length_le_one a h, revert this,
rcases lookup_all a l with _|⟨b, _|⟨c, l⟩⟩; intro; try {refl},
exact absurd this dec_trivial
end
theorem lookup_all_nodup (a : α) {l : list (sigma β)} (h : l.nodupkeys) :
(lookup_all a l).nodup :=
by rw lookup_all_eq_lookup a h; apply option.to_list_nodup
theorem perm_lookup_all (a : α) {l₁ l₂ : list (sigma β)}
(nd₁ : l₁.nodupkeys) (nd₂ : l₂.nodupkeys) (p : l₁ ~ l₂) : lookup_all a l₁ = lookup_all a l₂ :=
by simp [lookup_all_eq_lookup, nd₁, nd₂, perm_lookup a nd₁ nd₂ p]
/- kreplace -/
def kreplace (a : α) (b : β a) : list (sigma β) → list (sigma β) :=
lookmap $ λ s, if h : a = s.1 then some ⟨a, b⟩ else none
theorem kreplace_of_forall_not (a : α) (b : β a) {l : list (sigma β)}
(H : ∀ b : β a, sigma.mk a b ∉ l) : kreplace a b l = l :=
lookmap_of_forall_not _ $ begin
rintro ⟨a', b'⟩ h, dsimp, split_ifs,
{ subst a', exact H _ h }, {refl}
end
theorem kreplace_self {a : α} {b : β a} {l : list (sigma β)}
(nd : nodupkeys l) (h : sigma.mk a b ∈ l) : kreplace a b l = l :=
begin
refine (lookmap_congr _).trans
(lookmap_id' (option.guard (λ s, a = s.1)) _ _),
{ rintro ⟨a', b'⟩ h', dsimp [option.guard], split_ifs,
{ subst a', exact ⟨rfl, heq_of_eq $ nd.eq_of_mk_mem h h'⟩ },
{ refl } },
{ rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, dsimp [option.guard], split_ifs,
{ subst a₁, rintro ⟨⟩, simp }, { rintro ⟨⟩ } },
end
theorem keys_kreplace (a : α) (b : β a) : ∀ l : list (sigma β),
(kreplace a b l).keys = l.keys :=
lookmap_map_eq _ _ $ by rintro ⟨a₁, b₂⟩ ⟨a₂, b₂⟩;
dsimp; split_ifs; simp [h] {contextual := tt}
theorem kreplace_nodupkeys (a : α) (b : β a) {l : list (sigma β)} :
(kreplace a b l).nodupkeys ↔ l.nodupkeys :=
by simp [nodupkeys, keys_kreplace]
theorem perm_kreplace {a : α} {b : β a} {l₁ l₂ : list (sigma β)}
(nd : l₁.nodupkeys) : l₁ ~ l₂ →
kreplace a b l₁ ~ kreplace a b l₂ :=
perm_lookmap _ $ begin
refine (nodupkeys_iff_pairwise.1 nd).imp _,
intros x y h z h₁ w h₂,
split_ifs at h₁ h₂; cases h₁; cases h₂,
exact (h (h_2.symm.trans h_1)).elim
end
/- kerase -/
/-- Remove the first pair with the key `a`. -/
def kerase (a : α) : list (sigma β) → list (sigma β) :=
erasep $ λ s, a = s.1
@[simp] theorem kerase_nil {a} : @kerase _ β _ a [] = [] :=
rfl
@[simp] theorem kerase_cons_eq {a} {s : sigma β} {l : list (sigma β)} (h : a = s.1) :
kerase a (s :: l) = l :=
by simp [kerase, h]
@[simp] theorem kerase_cons_ne {a} {s : sigma β} {l : list (sigma β)} (h : a ≠ s.1) :
kerase a (s :: l) = s :: kerase a l :=
by simp [kerase, h]
@[simp] theorem kerase_of_not_mem_keys {a} {l : list (sigma β)} (h : a ∉ l.keys) :
kerase a l = l :=
by induction l with _ _ ih;
[refl, { simp [not_or_distrib] at h, simp [h.1, ih h.2] }]
theorem kerase_sublist (a : α) (l : list (sigma β)) : kerase a l <+ l :=
erasep_sublist _
theorem kerase_keys_subset (a) (l : list (sigma β)) :
(kerase a l).keys ⊆ l.keys :=
subset_of_sublist (map_sublist_map _ (kerase_sublist a l))
theorem mem_keys_of_mem_keys_kerase {a₁ a₂} {l : list (sigma β)} :
a₁ ∈ (kerase a₂ l).keys → a₁ ∈ l.keys :=
@kerase_keys_subset _ _ _ _ _ _
theorem exists_of_kerase {a : α} {l : list (sigma β)} (h : a ∈ l.keys) :
∃ (b : β a) (l₁ l₂ : list (sigma β)),
a ∉ l₁.keys ∧
l = l₁ ++ ⟨a, b⟩ :: l₂ ∧
kerase a l = l₁ ++ l₂ :=
begin
induction l,
case list.nil { cases h },
case list.cons : hd tl ih {
by_cases e : a = hd.1,
{ subst e,
exact ⟨hd.2, [], tl, by simp, by cases hd; refl, by simp⟩ },
{ simp at h,
cases h,
case or.inl : h { exact absurd h e },
case or.inr : h {
rcases ih h with ⟨b, tl₁, tl₂, h₁, h₂, h₃⟩,
exact ⟨b, hd :: tl₁, tl₂, not_mem_cons_of_ne_of_not_mem e h₁,
by rw h₂; refl, by simp [e, h₃]⟩ } } }
end
@[simp] theorem mem_keys_kerase_of_ne {a₁ a₂} {l : list (sigma β)} (h : a₁ ≠ a₂) :
a₁ ∈ (kerase a₂ l).keys ↔ a₁ ∈ l.keys :=
iff.intro mem_keys_of_mem_keys_kerase $ λ p,
if q : a₂ ∈ l.keys then
match l, kerase a₂ l, exists_of_kerase q, p with
| _, _, ⟨_, _, _, _, rfl, rfl⟩, p := by simpa [keys, h] using p
end
else
by simp [q, p]
theorem keys_kerase {a} {l : list (sigma β)} : (kerase a l).keys = l.keys.erase a :=
by rw [keys, kerase, ←erasep_map sigma.fst l, erase_eq_erasep]
theorem kerase_nodupkeys (a : α) {l : list (sigma β)} : nodupkeys l → (kerase a l).nodupkeys :=
nodupkeys_of_sublist $ kerase_sublist _ _
theorem perm_kerase {a : α} {l₁ l₂ : list (sigma β)}
(nd : l₁.nodupkeys) : l₁ ~ l₂ → kerase a l₁ ~ kerase a l₂ :=
perm_erasep _ $ (nodupkeys_iff_pairwise.1 nd).imp $
by rintro x y h rfl; exact h
@[simp] theorem not_mem_keys_kerase (a) {l : list (sigma β)} (nd : l.nodupkeys) :
a ∉ (kerase a l).keys :=
begin
induction l,
case list.nil { simp },
case list.cons : hd tl ih {
simp at nd,
by_cases h : a = hd.1,
{ subst h, simp [nd.1] },
{ simp [h, ih nd.2] } }
end
@[simp] theorem lookup_kerase (a) {l : list (sigma β)} (nd : l.nodupkeys) :
lookup a (kerase a l) = none :=
lookup_eq_none.mpr (not_mem_keys_kerase a nd)
@[simp] theorem lookup_kerase_ne {a a'} {l : list (sigma β)} (h : a ≠ a') :
lookup a (kerase a' l) = lookup a l :=
begin
induction l,
case list.nil { refl },
case list.cons : hd tl ih {
cases hd with ah bh,
by_cases h₁ : a = ah; by_cases h₂ : a' = ah,
{ substs h₁ h₂, cases ne.irrefl h },
{ subst h₁, simp [h₂] },
{ subst h₂, simp [h] },
{ simp [h₁, h₂, ih] }
}
end
theorem kerase_append_left {a} : ∀ {l₁ l₂ : list (sigma β)},
a ∈ l₁.keys → kerase a (l₁ ++ l₂) = kerase a l₁ ++ l₂
| [] _ h := by cases h
| (s :: l₁) l₂ h₁ :=
if h₂ : a = s.1 then
by simp [h₂]
else
by simp at h₁;
cases h₁;
[exact absurd h₁ h₂, simp [h₂, kerase_append_left h₁]]
theorem kerase_append_right {a} : ∀ {l₁ l₂ : list (sigma β)},
a ∉ l₁.keys → kerase a (l₁ ++ l₂) = l₁ ++ kerase a l₂
| [] _ h := rfl
| (_ :: l₁) l₂ h := by simp [not_or_distrib] at h;
simp [h.1, kerase_append_right h.2]
theorem kerase_comm (a₁ a₂) (l : list (sigma β)) :
kerase a₂ (kerase a₁ l) = kerase a₁ (kerase a₂ l) :=
if h : a₁ = a₂ then
by simp [h]
else if ha₁ : a₁ ∈ l.keys then
if ha₂ : a₂ ∈ l.keys then
match l, kerase a₁ l, exists_of_kerase ha₁, ha₂ with
| _, _, ⟨b₁, l₁, l₂, a₁_nin_l₁, rfl, rfl⟩, a₂_in_l₁_app_l₂ :=
if h' : a₂ ∈ l₁.keys then
by simp [kerase_append_left h',
kerase_append_right (mt (mem_keys_kerase_of_ne h).mp a₁_nin_l₁)]
else
by simp [kerase_append_right h', kerase_append_right a₁_nin_l₁,
@kerase_cons_ne _ _ _ a₂ ⟨a₁, b₁⟩ _ (ne.symm h)]
end
else
by simp [ha₂, mt mem_keys_of_mem_keys_kerase ha₂]
else
by simp [ha₁, mt mem_keys_of_mem_keys_kerase ha₁]
/- kinsert -/
/-- Insert the pair `⟨a, b⟩` and erase the first pair with the key `a`. -/
def kinsert (a : α) (b : β a) (l : list (sigma β)) : list (sigma β) :=
⟨a, b⟩ :: kerase a l
@[simp] theorem kinsert_def {a} {b : β a} {l : list (sigma β)} :
kinsert a b l = ⟨a, b⟩ :: kerase a l := rfl
@[simp] theorem mem_keys_kinsert {a a'} {b' : β a'} {l : list (sigma β)} :
a ∈ (kinsert a' b' l).keys ↔ a = a' ∨ a ∈ l.keys :=
by by_cases h : a = a'; simp [h]
theorem kinsert_nodupkeys (a) (b : β a) {l : list (sigma β)} (nd : l.nodupkeys) :
(kinsert a b l).nodupkeys :=
nodupkeys_cons.mpr ⟨not_mem_keys_kerase a nd, kerase_nodupkeys a nd⟩
theorem perm_kinsert {a} {b : β a} {l₁ l₂ : list (sigma β)} (nd₁ : l₁.nodupkeys)
(p : l₁ ~ l₂) : kinsert a b l₁ ~ kinsert a b l₂ :=
perm.skip ⟨a, b⟩ $ perm_kerase nd₁ p
@[simp] theorem lookup_kinsert {a} {b : β a} (l : list (sigma β)) :
lookup a (kinsert a b l) = some b :=
by simp only [kinsert, lookup_cons_eq]
@[simp] theorem lookup_kinsert_ne {a a'} {b' : β a'} {l : list (sigma β)} (h : a ≠ a') :
lookup a (kinsert a' b' l) = lookup a l :=
by simp [h, lookup_cons_ne _ ⟨a', b'⟩ h]
/- kextract -/
def kextract (a : α) : list (sigma β) → option (β a) × list (sigma β)
| [] := (none, [])
| (s::l) := if h : s.1 = a then (some (eq.rec_on h s.2), l) else
let (b', l') := kextract l in (b', s :: l')
@[simp] theorem kextract_eq_lookup_kerase (a : α) :
∀ l : list (sigma β), kextract a l = (lookup a l, kerase a l)
| [] := rfl
| (⟨a', b⟩::l) := begin
simp [kextract], dsimp, split_ifs,
{ subst a', simp [kerase] },
{ simp [kextract, ne.symm h, kextract_eq_lookup_kerase l, kerase] }
end
/- kunion -/
/-- `kunion l₁ l₂` is the append to l₁ of l₂ after, for each key in l₁, the
first matching pair in l₂ is erased. -/
def kunion : list (sigma β) → list (sigma β) → list (sigma β)
| [] l₂ := l₂
| (s :: l₁) l₂ := s :: kunion l₁ (kerase s.1 l₂)
@[simp] theorem nil_kunion {l : list (sigma β)} : kunion [] l = l :=
rfl
@[simp] theorem kunion_nil : ∀ {l : list (sigma β)}, kunion l [] = l
| [] := rfl
| (_ :: l) := by rw [kunion, kerase_nil, kunion_nil]
@[simp] theorem kunion_cons {s} {l₁ l₂ : list (sigma β)} :
kunion (s :: l₁) l₂ = s :: kunion l₁ (kerase s.1 l₂) :=
rfl
@[simp] theorem mem_keys_kunion {a} {l₁ l₂ : list (sigma β)} :
a ∈ (kunion l₁ l₂).keys ↔ a ∈ l₁.keys ∨ a ∈ l₂.keys :=
begin
induction l₁ generalizing l₂,
case list.nil { simp },
case list.cons : s l₁ ih { by_cases h : a = s.1; [simp [h], simp [h, ih]] }
end
@[simp] theorem kunion_kerase {a} : ∀ {l₁ l₂ : list (sigma β)},
kunion (kerase a l₁) (kerase a l₂) = kerase a (kunion l₁ l₂)
| [] _ := rfl
| (s :: _) l := by by_cases h : a = s.1;
simp [h, kerase_comm a s.1 l, kunion_kerase]
theorem kunion_nodupkeys {l₁ l₂ : list (sigma β)}
(nd₁ : l₁.nodupkeys) (nd₂ : l₂.nodupkeys) : (kunion l₁ l₂).nodupkeys :=
begin
induction l₁ generalizing l₂,
case list.nil { simp only [nil_kunion, nd₂] },
case list.cons : s l₁ ih {
simp at nd₁,
simp [not_or_distrib, nd₁.1, nd₂, ih nd₁.2 (kerase_nodupkeys s.1 nd₂)] }
end
theorem perm_kunion_left {l₁ l₂ : list (sigma β)} (p : l₁ ~ l₂) (l) :
kunion l₁ l ~ kunion l₂ l :=
begin
induction p generalizing l,
case list.perm.nil { refl },
case list.perm.skip : hd tl₁ tl₂ p ih {
simp [ih (kerase hd.1 l), perm.skip] },
case list.perm.swap : s₁ s₂ l {
simp [kerase_comm, perm.swap] },
case list.perm.trans : l₁ l₂ l₃ p₁₂ p₂₃ ih₁₂ ih₂₃ {
exact perm.trans (ih₁₂ l) (ih₂₃ l) }
end
theorem perm_kunion_right : ∀ l {l₁ l₂ : list (sigma β)},
l₁.nodupkeys → l₁ ~ l₂ → kunion l l₁ ~ kunion l l₂
| [] _ _ _ p := p
| (s :: l) l₁ l₂ nd₁ p :=
by simp [perm.skip s
(perm_kunion_right l (kerase_nodupkeys s.1 nd₁) (perm_kerase nd₁ p))]
theorem perm_kunion {l₁ l₂ l₃ l₄ : list (sigma β)} (nd₃ : l₃.nodupkeys)
(p₁₂ : l₁ ~ l₂) (p₃₄ : l₃ ~ l₄) : kunion l₁ l₃ ~ kunion l₂ l₄ :=
perm.trans (perm_kunion_left p₁₂ l₃) (perm_kunion_right l₂ nd₃ p₃₄)
@[simp] theorem lookup_kunion_left {a} {l₁ l₂ : list (sigma β)} (h : a ∈ l₁.keys) :
lookup a (kunion l₁ l₂) = lookup a l₁ :=
begin
induction l₁ with s _ ih generalizing l₂; simp at h; cases h; cases s with a',
{ subst h, simp },
{ rw kunion_cons,
by_cases h' : a = a',
{ subst h', simp },
{ simp [h', ih h] } }
end
@[simp] theorem lookup_kunion_right {a} {l₁ l₂ : list (sigma β)} (h : a ∉ l₁.keys) :
lookup a (kunion l₁ l₂) = lookup a l₂ :=
begin
induction l₁ generalizing l₂,
case list.nil { simp },
case list.cons : _ _ ih { simp [not_or_distrib] at h, simp [h.1, ih h.2] }
end
@[simp] theorem mem_lookup_kunion {a} {b : β a} {l₁ l₂ : list (sigma β)} :
b ∈ lookup a (kunion l₁ l₂) ↔ b ∈ lookup a l₁ ∨ a ∉ l₁.keys ∧ b ∈ lookup a l₂ :=
begin
induction l₁ generalizing l₂,
case list.nil { simp },
case list.cons : s _ ih {
cases s with a',
by_cases h₁ : a = a',
{ subst h₁, simp },
{ let h₂ := @ih (kerase a' l₂), simp [h₁] at h₂, simp [h₁, h₂] } }
end
theorem mem_lookup_kunion_middle {a} {b : β a} {l₁ l₂ l₃ : list (sigma β)}
(h₁ : b ∈ lookup a (kunion l₁ l₃)) (h₂ : a ∉ keys l₂) :
b ∈ lookup a (kunion (kunion l₁ l₂) l₃) :=
match mem_lookup_kunion.mp h₁ with
| or.inl h := mem_lookup_kunion.mpr (or.inl (mem_lookup_kunion.mpr (or.inl h)))
| or.inr h := mem_lookup_kunion.mpr $
or.inr ⟨mt mem_keys_kunion.mp (not_or_distrib.mpr ⟨h.1, h₂⟩), h.2⟩
end
end list
|
4c31f904e09033124c134b54c254eaf342e39982 | 54d7e71c3616d331b2ec3845d31deb08f3ff1dea | /tests/lean/run/cc_value.lean | a26ec438fec5fa6dcde9b81bbdbc1b88d6dc5bb4 | [
"Apache-2.0"
] | permissive | pachugupta/lean | 6f3305c4292288311cc4ab4550060b17d49ffb1d | 0d02136a09ac4cf27b5c88361750e38e1f485a1a | refs/heads/master | 1,611,110,653,606 | 1,493,130,117,000 | 1,493,167,649,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 414 | lean | open tactic
example (a b : nat) : a = 1 → b = 2 → a = b → false :=
by cc
example (a b c : int) : a = 1 → c = -2 → a = b → c = b → false :=
by cc
example (a b : char) : a = #"h" → b = #"w" → a = b → false :=
by cc
example (a b : string) : a = "hello" → b = "world" → a = b → false :=
by cc
example (a b c : string) : a = c → a = "hello" → c = "world" → c = b → false :=
by cc
|
31abafd87a1f1fa5805a9325fa06e37118983785 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/order/conditionally_complete_lattice.lean | d0cd695289dae692b6060f83329abb9118389b5e | [
"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 | 53,629 | lean | /-
Copyright (c) 2018 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import order.bounds
import data.set.intervals.basic
import data.set.finite
import data.set.lattice
/-!
# Theory of conditionally complete lattices.
A conditionally complete lattice is a lattice in which every non-empty bounded subset s
has a least upper bound and a greatest lower bound, denoted below by Sup s and Inf s.
Typical examples are real, nat, int with their usual orders.
The theory is very comparable to the theory of complete lattices, except that suitable
boundedness and nonemptiness assumptions have to be added to most statements.
We introduce two predicates bdd_above and bdd_below to express this boundedness, prove
their basic properties, and then go on to prove most useful properties of Sup and Inf
in conditionally complete lattices.
To differentiate the statements between complete lattices and conditionally complete
lattices, we prefix Inf and Sup in the statements by c, giving cInf and cSup. For instance,
Inf_le is a statement in complete lattices ensuring Inf s ≤ x, while cInf_le is the same
statement in conditionally complete lattices with an additional assumption that s is
bounded below.
-/
set_option old_structure_cmd true
open function order_dual set
variables {α β γ : Type*} {ι : Sort*}
section
/-!
Extension of Sup and Inf from a preorder `α` to `with_top α` and `with_bot α`
-/
open_locale classical
noncomputable instance {α : Type*} [preorder α] [has_Sup α] : has_Sup (with_top α) :=
⟨λ S, if ⊤ ∈ S then ⊤ else
if bdd_above (coe ⁻¹' S : set α) then ↑(Sup (coe ⁻¹' S : set α)) else ⊤⟩
noncomputable instance {α : Type*} [has_Inf α] : has_Inf (with_top α) :=
⟨λ S, if S ⊆ {⊤} then ⊤ else ↑(Inf (coe ⁻¹' S : set α))⟩
noncomputable instance {α : Type*} [has_Sup α] : has_Sup (with_bot α) :=
⟨(@with_top.has_Inf αᵒᵈ _).Inf⟩
noncomputable instance {α : Type*} [preorder α] [has_Inf α] : has_Inf (with_bot α) :=
⟨(@with_top.has_Sup αᵒᵈ _ _).Sup⟩
@[simp]
theorem with_top.cInf_empty {α : Type*} [has_Inf α] : Inf (∅ : set (with_top α)) = ⊤ :=
if_pos $ set.empty_subset _
@[simp]
theorem with_top.cinfi_empty {α : Type*} [is_empty ι] [has_Inf α] (f : ι → with_top α) :
(⨅ i, f i) = ⊤ :=
by rw [infi, range_eq_empty, with_top.cInf_empty]
lemma with_top.coe_Inf' [has_Inf α] {s : set α} (hs : s.nonempty) :
↑(Inf s) = (Inf (coe '' s) : with_top α) :=
begin
obtain ⟨x, hx⟩ := hs,
change _ = ite _ _ _,
split_ifs,
{ cases h (mem_image_of_mem _ hx) },
{ rw preimage_image_eq,
exact option.some_injective _ },
end
@[norm_cast] lemma with_top.coe_infi [nonempty ι] [has_Inf α] (f : ι → α) :
↑(⨅ i, f i) = (⨅ i, f i : with_top α) :=
by rw [infi, infi, with_top.coe_Inf' (range_nonempty f), range_comp]
theorem with_top.coe_Sup' [preorder α] [has_Sup α] {s : set α} (hs : bdd_above s) :
↑(Sup s) = (Sup (coe '' s) : with_top α) :=
begin
change _ = ite _ _ _,
rw [if_neg, preimage_image_eq, if_pos hs],
{ exact option.some_injective _ },
{ rintro ⟨x, h, ⟨⟩⟩ },
end
@[norm_cast] lemma with_top.coe_supr [preorder α] [has_Sup α] (f : ι → α)
(h : bdd_above (set.range f)) :
↑(⨆ i, f i) = (⨆ i, f i : with_top α) :=
by rw [supr, supr, with_top.coe_Sup' h, range_comp]
@[simp]
theorem with_bot.cSup_empty {α : Type*} [has_Sup α] : Sup (∅ : set (with_bot α)) = ⊥ :=
if_pos $ set.empty_subset _
@[simp]
theorem with_bot.csupr_empty {α : Type*} [is_empty ι] [has_Sup α] (f : ι → with_bot α) :
(⨆ i, f i) = ⊥ :=
@with_top.cinfi_empty _ αᵒᵈ _ _ _
@[norm_cast] lemma with_bot.coe_Sup' [has_Sup α] {s : set α} (hs : s.nonempty) :
↑(Sup s) = (Sup (coe '' s) : with_bot α) :=
@with_top.coe_Inf' αᵒᵈ _ _ hs
@[norm_cast] lemma with_bot.coe_supr [nonempty ι] [has_Sup α] (f : ι → α) :
↑(⨆ i, f i) = (⨆ i, f i : with_bot α) :=
@with_top.coe_infi αᵒᵈ _ _ _ _
@[norm_cast] theorem with_bot.coe_Inf' [preorder α] [has_Inf α] {s : set α} (hs : bdd_below s) :
↑(Inf s) = (Inf (coe '' s) : with_bot α) :=
@with_top.coe_Sup' αᵒᵈ _ _ _ hs
@[norm_cast] lemma with_bot.coe_infi [preorder α] [has_Inf α] (f : ι → α)
(h : bdd_below (set.range f)) :
↑(⨅ i, f i) = (⨅ i, f i : with_bot α) :=
@with_top.coe_supr αᵒᵈ _ _ _ _ h
end -- section
/-- A conditionally complete lattice is a lattice in which
every nonempty subset which is bounded above has a supremum, and
every nonempty subset which is bounded below has an infimum.
Typical examples are real numbers or natural numbers.
To differentiate the statements from the corresponding statements in (unconditional)
complete lattices, we prefix Inf and Sup by a c everywhere. The same statements should
hold in both worlds, sometimes with additional assumptions of nonemptiness or
boundedness.-/
class conditionally_complete_lattice (α : Type*) extends lattice α, has_Sup α, has_Inf α :=
(le_cSup : ∀ s a, bdd_above s → a ∈ s → a ≤ Sup s)
(cSup_le : ∀ s a, set.nonempty s → a ∈ upper_bounds s → Sup s ≤ a)
(cInf_le : ∀ s a, bdd_below s → a ∈ s → Inf s ≤ a)
(le_cInf : ∀ s a, set.nonempty s → a ∈ lower_bounds s → a ≤ Inf s)
/-- A conditionally complete linear order is a linear order in which
every nonempty subset which is bounded above has a supremum, and
every nonempty subset which is bounded below has an infimum.
Typical examples are real numbers or natural numbers.
To differentiate the statements from the corresponding statements in (unconditional)
complete linear orders, we prefix Inf and Sup by a c everywhere. The same statements should
hold in both worlds, sometimes with additional assumptions of nonemptiness or
boundedness.-/
class conditionally_complete_linear_order (α : Type*)
extends conditionally_complete_lattice α, linear_order α renaming max → sup min → inf
/-- A conditionally complete linear order with `bot` is a linear order with least element, in which
every nonempty subset which is bounded above has a supremum, and every nonempty subset (necessarily
bounded below) has an infimum. A typical example is the natural numbers.
To differentiate the statements from the corresponding statements in (unconditional)
complete linear orders, we prefix Inf and Sup by a c everywhere. The same statements should
hold in both worlds, sometimes with additional assumptions of nonemptiness or
boundedness.-/
@[ancestor conditionally_complete_linear_order has_bot]
class conditionally_complete_linear_order_bot (α : Type*)
extends conditionally_complete_linear_order α, has_bot α :=
(bot_le : ∀ x : α, ⊥ ≤ x)
(cSup_empty : Sup ∅ = ⊥)
@[priority 100] -- see Note [lower instance priority]
instance conditionally_complete_linear_order_bot.to_order_bot
[h : conditionally_complete_linear_order_bot α] : order_bot α :=
{ ..h }
/-- A complete lattice is a conditionally complete lattice, as there are no restrictions
on the properties of Inf and Sup in a complete lattice.-/
@[priority 100] -- see Note [lower instance priority]
instance complete_lattice.to_conditionally_complete_lattice [complete_lattice α] :
conditionally_complete_lattice α :=
{ le_cSup := by intros; apply le_Sup; assumption,
cSup_le := by intros; apply Sup_le; assumption,
cInf_le := by intros; apply Inf_le; assumption,
le_cInf := by intros; apply le_Inf; assumption,
..‹complete_lattice α› }
@[priority 100] -- see Note [lower instance priority]
instance complete_linear_order.to_conditionally_complete_linear_order_bot {α : Type*}
[complete_linear_order α] :
conditionally_complete_linear_order_bot α :=
{ cSup_empty := Sup_empty,
..complete_lattice.to_conditionally_complete_lattice, .. ‹complete_linear_order α› }
section
open_locale classical
/-- A well founded linear order is conditionally complete, with a bottom element. -/
@[reducible] noncomputable def is_well_order.conditionally_complete_linear_order_bot
(α : Type*) [i₁ : linear_order α] [i₂ : order_bot α] [h : is_well_order α (<)] :
conditionally_complete_linear_order_bot α :=
{ Inf := λ s, if hs : s.nonempty then h.wf.min s hs else ⊥,
cInf_le := λ s a hs has, begin
have s_ne : s.nonempty := ⟨a, has⟩,
simpa [s_ne] using not_lt.1 (h.wf.not_lt_min s s_ne has),
end,
le_cInf := λ s a hs has, begin
simp only [hs, dif_pos],
exact has (h.wf.min_mem s hs),
end,
Sup := λ s, if hs : (upper_bounds s).nonempty then h.wf.min _ hs else ⊥,
le_cSup := λ s a hs has, begin
have h's : (upper_bounds s).nonempty := hs,
simp only [h's, dif_pos],
exact h.wf.min_mem _ h's has,
end,
cSup_le := λ s a hs has, begin
have h's : (upper_bounds s).nonempty := ⟨a, has⟩,
simp only [h's, dif_pos],
simpa using h.wf.not_lt_min _ h's has,
end,
cSup_empty := by simpa using eq_bot_iff.2 (not_lt.1 $ h.wf.not_lt_min _ _ $ mem_univ ⊥),
..i₁, ..i₂, ..linear_order.to_lattice }
end
section order_dual
instance (α : Type*) [conditionally_complete_lattice α] : conditionally_complete_lattice αᵒᵈ :=
{ le_cSup := @conditionally_complete_lattice.cInf_le α _,
cSup_le := @conditionally_complete_lattice.le_cInf α _,
le_cInf := @conditionally_complete_lattice.cSup_le α _,
cInf_le := @conditionally_complete_lattice.le_cSup α _,
..order_dual.has_Inf α,
..order_dual.has_Sup α,
..order_dual.lattice α }
instance (α : Type*) [conditionally_complete_linear_order α] :
conditionally_complete_linear_order αᵒᵈ :=
{ ..order_dual.conditionally_complete_lattice α,
..order_dual.linear_order α }
end order_dual
section conditionally_complete_lattice
variables [conditionally_complete_lattice α] {s t : set α} {a b : α}
theorem le_cSup (h₁ : bdd_above s) (h₂ : a ∈ s) : a ≤ Sup s :=
conditionally_complete_lattice.le_cSup s a h₁ h₂
theorem cSup_le (h₁ : s.nonempty) (h₂ : ∀ b ∈ s, b ≤ a) : Sup s ≤ a :=
conditionally_complete_lattice.cSup_le s a h₁ h₂
theorem cInf_le (h₁ : bdd_below s) (h₂ : a ∈ s) : Inf s ≤ a :=
conditionally_complete_lattice.cInf_le s a h₁ h₂
theorem le_cInf (h₁ : s.nonempty) (h₂ : ∀ b ∈ s, a ≤ b) : a ≤ Inf s :=
conditionally_complete_lattice.le_cInf s a h₁ h₂
theorem le_cSup_of_le (hs : bdd_above s) (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s :=
le_trans h (le_cSup hs hb)
theorem cInf_le_of_le (hs : bdd_below s) (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a :=
le_trans (cInf_le hs hb) h
theorem cSup_le_cSup (ht : bdd_above t) (hs : s.nonempty) (h : s ⊆ t) : Sup s ≤ Sup t :=
cSup_le hs (λ a ha, le_cSup ht (h ha))
theorem cInf_le_cInf (ht : bdd_below t) (hs : s.nonempty) (h : s ⊆ t) : Inf t ≤ Inf s :=
le_cInf hs (λ a ha, cInf_le ht (h ha))
theorem le_cSup_iff (h : bdd_above s) (hs : s.nonempty) :
a ≤ Sup s ↔ ∀ b, b ∈ upper_bounds s → a ≤ b :=
⟨λ h b hb, le_trans h (cSup_le hs hb), λ hb, hb _ (λ x, le_cSup h)⟩
theorem cInf_le_iff (h : bdd_below s) (hs : s.nonempty) :
Inf s ≤ a ↔ ∀ b ∈ lower_bounds s, b ≤ a :=
⟨λ h b hb, le_trans (le_cInf hs hb) h, λ hb, hb _ (λ x, cInf_le h)⟩
lemma is_lub_cSup (ne : s.nonempty) (H : bdd_above s) : is_lub s (Sup s) :=
⟨λ x, le_cSup H, λ x, cSup_le ne⟩
lemma is_lub_csupr [nonempty ι] {f : ι → α} (H : bdd_above (range f)) :
is_lub (range f) (⨆ i, f i) :=
is_lub_cSup (range_nonempty f) H
lemma is_lub_csupr_set {f : β → α} {s : set β} (H : bdd_above (f '' s)) (Hne : s.nonempty) :
is_lub (f '' s) (⨆ i : s, f i) :=
by { rw ← Sup_image', exact is_lub_cSup (Hne.image _) H }
lemma is_glb_cInf (ne : s.nonempty) (H : bdd_below s) : is_glb s (Inf s) :=
⟨λ x, cInf_le H, λ x, le_cInf ne⟩
lemma is_glb_cinfi [nonempty ι] {f : ι → α} (H : bdd_below (range f)) :
is_glb (range f) (⨅ i, f i) :=
is_glb_cInf (range_nonempty f) H
lemma is_glb_cinfi_set {f : β → α} {s : set β} (H : bdd_below (f '' s)) (Hne : s.nonempty) :
is_glb (f '' s) (⨅ i : s, f i) :=
@is_lub_csupr_set αᵒᵈ _ _ _ _ H Hne
lemma csupr_le_iff [nonempty ι] {f : ι → α} {a : α} (hf : bdd_above (range f)) :
supr f ≤ a ↔ ∀ i, f i ≤ a :=
(is_lub_le_iff $ is_lub_csupr hf).trans forall_range_iff
lemma le_cinfi_iff [nonempty ι] {f : ι → α} {a : α} (hf : bdd_below (range f)) :
a ≤ infi f ↔ ∀ i, a ≤ f i :=
(le_is_glb_iff $ is_glb_cinfi hf).trans forall_range_iff
lemma csupr_set_le_iff {ι : Type*} {s : set ι} {f : ι → α} {a : α} (hs : s.nonempty)
(hf : bdd_above (f '' s)) :
(⨆ i : s, f i) ≤ a ↔ ∀ i ∈ s, f i ≤ a :=
(is_lub_le_iff $ is_lub_csupr_set hf hs).trans ball_image_iff
lemma le_cinfi_set_iff {ι : Type*} {s : set ι} {f : ι → α} {a : α} (hs : s.nonempty)
(hf : bdd_below (f '' s)) :
a ≤ (⨅ i : s, f i) ↔ ∀ i ∈ s, a ≤ f i :=
(le_is_glb_iff $ is_glb_cinfi_set hf hs).trans ball_image_iff
lemma is_lub.cSup_eq (H : is_lub s a) (ne : s.nonempty) : Sup s = a :=
(is_lub_cSup ne ⟨a, H.1⟩).unique H
lemma is_lub.csupr_eq [nonempty ι] {f : ι → α} (H : is_lub (range f) a) : (⨆ i, f i) = a :=
H.cSup_eq (range_nonempty f)
lemma is_lub.csupr_set_eq {s : set β} {f : β → α} (H : is_lub (f '' s) a) (Hne : s.nonempty) :
(⨆ i : s, f i) = a :=
is_lub.cSup_eq (image_eq_range f s ▸ H) (image_eq_range f s ▸ Hne.image f)
/-- A greatest element of a set is the supremum of this set. -/
lemma is_greatest.cSup_eq (H : is_greatest s a) : Sup s = a :=
H.is_lub.cSup_eq H.nonempty
lemma is_greatest.Sup_mem (H : is_greatest s a) : Sup s ∈ s :=
H.cSup_eq.symm ▸ H.1
lemma is_glb.cInf_eq (H : is_glb s a) (ne : s.nonempty) : Inf s = a :=
(is_glb_cInf ne ⟨a, H.1⟩).unique H
lemma is_glb.cinfi_eq [nonempty ι] {f : ι → α} (H : is_glb (range f) a) : (⨅ i, f i) = a :=
H.cInf_eq (range_nonempty f)
lemma is_glb.cinfi_set_eq {s : set β} {f : β → α} (H : is_glb (f '' s) a) (Hne : s.nonempty) :
(⨅ i : s, f i) = a :=
is_glb.cInf_eq (image_eq_range f s ▸ H) (image_eq_range f s ▸ Hne.image f)
/-- A least element of a set is the infimum of this set. -/
lemma is_least.cInf_eq (H : is_least s a) : Inf s = a :=
H.is_glb.cInf_eq H.nonempty
lemma is_least.Inf_mem (H : is_least s a) : Inf s ∈ s :=
H.cInf_eq.symm ▸ H.1
lemma subset_Icc_cInf_cSup (hb : bdd_below s) (ha : bdd_above s) :
s ⊆ Icc (Inf s) (Sup s) :=
λ x hx, ⟨cInf_le hb hx, le_cSup ha hx⟩
theorem cSup_le_iff (hb : bdd_above s) (hs : s.nonempty) : Sup s ≤ a ↔ ∀ b ∈ s, b ≤ a :=
is_lub_le_iff (is_lub_cSup hs hb)
theorem le_cInf_iff (hb : bdd_below s) (hs : s.nonempty) : a ≤ Inf s ↔ ∀ b ∈ s, a ≤ b :=
le_is_glb_iff (is_glb_cInf hs hb)
lemma cSup_lower_bounds_eq_cInf {s : set α} (h : bdd_below s) (hs : s.nonempty) :
Sup (lower_bounds s) = Inf s :=
(is_lub_cSup h $ hs.mono $ λ x hx y hy, hy hx).unique (is_glb_cInf hs h).is_lub
lemma cInf_upper_bounds_eq_cSup {s : set α} (h : bdd_above s) (hs : s.nonempty) :
Inf (upper_bounds s) = Sup s :=
(is_glb_cInf h $ hs.mono $ λ x hx y hy, hy hx).unique (is_lub_cSup hs h).is_glb
lemma not_mem_of_lt_cInf {x : α} {s : set α} (h : x < Inf s) (hs : bdd_below s) : x ∉ s :=
λ hx, lt_irrefl _ (h.trans_le (cInf_le hs hx))
lemma not_mem_of_cSup_lt {x : α} {s : set α} (h : Sup s < x) (hs : bdd_above s) : x ∉ s :=
@not_mem_of_lt_cInf αᵒᵈ _ x s h hs
/--Introduction rule to prove that `b` is the supremum of `s`: it suffices to check that `b`
is larger than all elements of `s`, and that this is not the case of any `w<b`.
See `Sup_eq_of_forall_le_of_forall_lt_exists_gt` for a version in complete lattices. -/
theorem cSup_eq_of_forall_le_of_forall_lt_exists_gt (hs : s.nonempty)
(H : ∀ a ∈ s, a ≤ b) (H' : ∀ w, w < b → ∃ a ∈ s, w < a) : Sup s = b :=
eq_of_le_of_not_lt (cSup_le hs H) $ λ hb, let ⟨a, ha, ha'⟩ := H' _ hb in
lt_irrefl _ $ ha'.trans_le $ le_cSup ⟨b, H⟩ ha
/--Introduction rule to prove that `b` is the infimum of `s`: it suffices to check that `b`
is smaller than all elements of `s`, and that this is not the case of any `w>b`.
See `Inf_eq_of_forall_ge_of_forall_gt_exists_lt` for a version in complete lattices. -/
theorem cInf_eq_of_forall_ge_of_forall_gt_exists_lt : s.nonempty → (∀ a ∈ s, b ≤ a) →
(∀ w, b < w → ∃ a ∈ s, a < w) → Inf s = b :=
@cSup_eq_of_forall_le_of_forall_lt_exists_gt αᵒᵈ _ _ _
/--b < Sup s when there is an element a in s with b < a, when s is bounded above.
This is essentially an iff, except that the assumptions for the two implications are
slightly different (one needs boundedness above for one direction, nonemptiness and linear
order for the other one), so we formulate separately the two implications, contrary to
the complete_lattice case.-/
lemma lt_cSup_of_lt (hs : bdd_above s) (ha : a ∈ s) (h : b < a) : b < Sup s :=
lt_of_lt_of_le h (le_cSup hs ha)
/--Inf s < b when there is an element a in s with a < b, when s is bounded below.
This is essentially an iff, except that the assumptions for the two implications are
slightly different (one needs boundedness below for one direction, nonemptiness and linear
order for the other one), so we formulate separately the two implications, contrary to
the complete_lattice case.-/
lemma cInf_lt_of_lt : bdd_below s → a ∈ s → a < b → Inf s < b :=
@lt_cSup_of_lt αᵒᵈ _ _ _ _
/-- If all elements of a nonempty set `s` are less than or equal to all elements
of a nonempty set `t`, then there exists an element between these sets. -/
lemma exists_between_of_forall_le (sne : s.nonempty) (tne : t.nonempty)
(hst : ∀ (x ∈ s) (y ∈ t), x ≤ y) : (upper_bounds s ∩ lower_bounds t).nonempty :=
⟨Inf t, λ x hx, le_cInf tne $ hst x hx, λ y hy, cInf_le (sne.mono hst) hy⟩
/--The supremum of a singleton is the element of the singleton-/
@[simp] theorem cSup_singleton (a : α) : Sup {a} = a :=
is_greatest_singleton.cSup_eq
/--The infimum of a singleton is the element of the singleton-/
@[simp] theorem cInf_singleton (a : α) : Inf {a} = a :=
is_least_singleton.cInf_eq
@[simp] theorem cSup_pair (a b : α) : Sup {a, b} = a ⊔ b :=
(@is_lub_pair _ _ a b).cSup_eq (insert_nonempty _ _)
@[simp] theorem cInf_pair (a b : α) : Inf {a, b} = a ⊓ b :=
(@is_glb_pair _ _ a b).cInf_eq (insert_nonempty _ _)
/--If a set is bounded below and above, and nonempty, its infimum is less than or equal to
its supremum.-/
theorem cInf_le_cSup (hb : bdd_below s) (ha : bdd_above s) (ne : s.nonempty) : Inf s ≤ Sup s :=
is_glb_le_is_lub (is_glb_cInf ne hb) (is_lub_cSup ne ha) ne
/--The sup of a union of two sets is the max of the suprema of each subset, under the assumptions
that all sets are bounded above and nonempty.-/
theorem cSup_union (hs : bdd_above s) (sne : s.nonempty) (ht : bdd_above t) (tne : t.nonempty) :
Sup (s ∪ t) = Sup s ⊔ Sup t :=
((is_lub_cSup sne hs).union (is_lub_cSup tne ht)).cSup_eq sne.inl
/--The inf of a union of two sets is the min of the infima of each subset, under the assumptions
that all sets are bounded below and nonempty.-/
theorem cInf_union (hs : bdd_below s) (sne : s.nonempty) (ht : bdd_below t) (tne : t.nonempty) :
Inf (s ∪ t) = Inf s ⊓ Inf t :=
@cSup_union αᵒᵈ _ _ _ hs sne ht tne
/--The supremum of an intersection of two sets is bounded by the minimum of the suprema of each
set, if all sets are bounded above and nonempty.-/
theorem cSup_inter_le (hs : bdd_above s) (ht : bdd_above t) (hst : (s ∩ t).nonempty) :
Sup (s ∩ t) ≤ Sup s ⊓ Sup t :=
cSup_le hst $ λ x hx, le_inf (le_cSup hs hx.1) (le_cSup ht hx.2)
/--The infimum of an intersection of two sets is bounded below by the maximum of the
infima of each set, if all sets are bounded below and nonempty.-/
theorem le_cInf_inter : bdd_below s → bdd_below t → (s ∩ t).nonempty →
Inf s ⊔ Inf t ≤ Inf (s ∩ t) :=
@cSup_inter_le αᵒᵈ _ _ _
/-- The supremum of insert a s is the maximum of a and the supremum of s, if s is
nonempty and bounded above.-/
theorem cSup_insert (hs : bdd_above s) (sne : s.nonempty) : Sup (insert a s) = a ⊔ Sup s :=
((is_lub_cSup sne hs).insert a).cSup_eq (insert_nonempty a s)
/-- The infimum of insert a s is the minimum of a and the infimum of s, if s is
nonempty and bounded below.-/
theorem cInf_insert (hs : bdd_below s) (sne : s.nonempty) : Inf (insert a s) = a ⊓ Inf s :=
@cSup_insert αᵒᵈ _ _ _ hs sne
@[simp] lemma cInf_Icc (h : a ≤ b) : Inf (Icc a b) = a :=
(is_glb_Icc h).cInf_eq (nonempty_Icc.2 h)
@[simp] lemma cInf_Ici : Inf (Ici a) = a := is_least_Ici.cInf_eq
@[simp] lemma cInf_Ico (h : a < b) : Inf (Ico a b) = a :=
(is_glb_Ico h).cInf_eq (nonempty_Ico.2 h)
@[simp] lemma cInf_Ioc [densely_ordered α] (h : a < b) : Inf (Ioc a b) = a :=
(is_glb_Ioc h).cInf_eq (nonempty_Ioc.2 h)
@[simp] lemma cInf_Ioi [no_max_order α] [densely_ordered α] : Inf (Ioi a) = a :=
cInf_eq_of_forall_ge_of_forall_gt_exists_lt nonempty_Ioi (λ _, le_of_lt)
(λ w hw, by simpa using exists_between hw)
@[simp] lemma cInf_Ioo [densely_ordered α] (h : a < b) : Inf (Ioo a b) = a :=
(is_glb_Ioo h).cInf_eq (nonempty_Ioo.2 h)
@[simp] lemma cSup_Icc (h : a ≤ b) : Sup (Icc a b) = b :=
(is_lub_Icc h).cSup_eq (nonempty_Icc.2 h)
@[simp] lemma cSup_Ico [densely_ordered α] (h : a < b) : Sup (Ico a b) = b :=
(is_lub_Ico h).cSup_eq (nonempty_Ico.2 h)
@[simp] lemma cSup_Iic : Sup (Iic a) = a := is_greatest_Iic.cSup_eq
@[simp] lemma cSup_Iio [no_min_order α] [densely_ordered α] : Sup (Iio a) = a :=
cSup_eq_of_forall_le_of_forall_lt_exists_gt nonempty_Iio (λ _, le_of_lt)
(λ w hw, by simpa [and_comm] using exists_between hw)
@[simp] lemma cSup_Ioc (h : a < b) : Sup (Ioc a b) = b :=
(is_lub_Ioc h).cSup_eq (nonempty_Ioc.2 h)
@[simp] lemma cSup_Ioo [densely_ordered α] (h : a < b) : Sup (Ioo a b) = b :=
(is_lub_Ioo h).cSup_eq (nonempty_Ioo.2 h)
/--The indexed supremum of a function is bounded above by a uniform bound-/
lemma csupr_le [nonempty ι] {f : ι → α} {c : α} (H : ∀ x, f x ≤ c) : supr f ≤ c :=
cSup_le (range_nonempty f) (by rwa forall_range_iff)
/--The indexed supremum of a function is bounded below by the value taken at one point-/
lemma le_csupr {f : ι → α} (H : bdd_above (range f)) (c : ι) : f c ≤ supr f :=
le_cSup H (mem_range_self _)
lemma le_csupr_of_le {f : ι → α} (H : bdd_above (range f)) (c : ι) (h : a ≤ f c) : a ≤ supr f :=
le_trans h (le_csupr H c)
/--The indexed supremum of two functions are comparable if the functions are pointwise comparable-/
lemma csupr_mono {f g : ι → α} (B : bdd_above (range g)) (H : ∀ x, f x ≤ g x) :
supr f ≤ supr g :=
begin
casesI is_empty_or_nonempty ι,
{ rw [supr_of_empty', supr_of_empty'] },
{ exact csupr_le (λ x, le_csupr_of_le B x (H x)) },
end
lemma le_csupr_set {f : β → α} {s : set β}
(H : bdd_above (f '' s)) {c : β} (hc : c ∈ s) : f c ≤ ⨆ i : s, f i :=
(le_cSup H $ mem_image_of_mem f hc).trans_eq Sup_image'
/--The indexed infimum of two functions are comparable if the functions are pointwise comparable-/
lemma cinfi_mono {f g : ι → α} (B : bdd_below (range f)) (H : ∀ x, f x ≤ g x) :
infi f ≤ infi g :=
@csupr_mono αᵒᵈ _ _ _ _ B H
/--The indexed minimum of a function is bounded below by a uniform lower bound-/
lemma le_cinfi [nonempty ι] {f : ι → α} {c : α} (H : ∀ x, c ≤ f x) : c ≤ infi f :=
@csupr_le αᵒᵈ _ _ _ _ _ H
/--The indexed infimum of a function is bounded above by the value taken at one point-/
lemma cinfi_le {f : ι → α} (H : bdd_below (range f)) (c : ι) : infi f ≤ f c :=
@le_csupr αᵒᵈ _ _ _ H c
lemma cinfi_le_of_le {f : ι → α} (H : bdd_below (range f)) (c : ι) (h : f c ≤ a) : infi f ≤ a :=
@le_csupr_of_le αᵒᵈ _ _ _ _ H c h
lemma cinfi_set_le {f : β → α} {s : set β}
(H : bdd_below (f '' s)) {c : β} (hc : c ∈ s) : (⨅ i : s, f i) ≤ f c :=
@le_csupr_set αᵒᵈ _ _ _ _ H _ hc
@[simp] theorem csupr_const [hι : nonempty ι] {a : α} : (⨆ b : ι, a) = a :=
by rw [supr, range_const, cSup_singleton]
@[simp] theorem cinfi_const [hι : nonempty ι] {a : α} : (⨅ b:ι, a) = a := @csupr_const αᵒᵈ _ _ _ _
@[simp] theorem supr_unique [unique ι] {s : ι → α} : (⨆ i, s i) = s default :=
have ∀ i, s i = s default := λ i, congr_arg s (unique.eq_default i),
by simp only [this, csupr_const]
@[simp] theorem infi_unique [unique ι] {s : ι → α} : (⨅ i, s i) = s default :=
@supr_unique αᵒᵈ _ _ _ _
@[simp] lemma csupr_pos {p : Prop} {f : p → α} (hp : p) : (⨆ h : p, f h) = f hp :=
by haveI := unique_prop hp; exact supr_unique
@[simp] lemma cinfi_pos {p : Prop} {f : p → α} (hp : p) : (⨅ h : p, f h) = f hp :=
@csupr_pos αᵒᵈ _ _ _ hp
lemma csupr_set {s : set β} {f : β → α} : (⨆ x : s, f x) = Sup (f '' s) :=
begin
rw supr,
congr,
ext,
rw [mem_image, mem_range, set_coe.exists],
simp_rw [subtype.coe_mk, exists_prop],
end
lemma cinfi_set {s : set β} {f : β → α} : (⨅ x : s, f x) = Inf (f '' s) := @csupr_set αᵒᵈ _ _ _ _
/--Introduction rule to prove that `b` is the supremum of `f`: it suffices to check that `b`
is larger than `f i` for all `i`, and that this is not the case of any `w<b`.
See `supr_eq_of_forall_le_of_forall_lt_exists_gt` for a version in complete lattices. -/
theorem csupr_eq_of_forall_le_of_forall_lt_exists_gt [nonempty ι] {f : ι → α} (h₁ : ∀ i, f i ≤ b)
(h₂ : ∀ w, w < b → (∃ i, w < f i)) : (⨆ (i : ι), f i) = b :=
cSup_eq_of_forall_le_of_forall_lt_exists_gt (range_nonempty f) (forall_range_iff.mpr h₁)
(λ w hw, exists_range_iff.mpr $ h₂ w hw)
/--Introduction rule to prove that `b` is the infimum of `f`: it suffices to check that `b`
is smaller than `f i` for all `i`, and that this is not the case of any `w>b`.
See `infi_eq_of_forall_ge_of_forall_gt_exists_lt` for a version in complete lattices. -/
theorem cinfi_eq_of_forall_ge_of_forall_gt_exists_lt [nonempty ι] {f : ι → α} (h₁ : ∀ i, b ≤ f i)
(h₂ : ∀ w, b < w → (∃ i, f i < w)) : (⨅ (i : ι), f i) = b :=
@csupr_eq_of_forall_le_of_forall_lt_exists_gt αᵒᵈ _ _ _ _ ‹_› ‹_› ‹_›
/-- Nested intervals lemma: if `f` is a monotone sequence, `g` is an antitone sequence, and
`f n ≤ g n` for all `n`, then `⨆ n, f n` belongs to all the intervals `[f n, g n]`. -/
lemma monotone.csupr_mem_Inter_Icc_of_antitone [semilattice_sup β]
{f g : β → α} (hf : monotone f) (hg : antitone g) (h : f ≤ g) :
(⨆ n, f n) ∈ ⋂ n, Icc (f n) (g n) :=
begin
refine mem_Inter.2 (λ n, _),
haveI : nonempty β := ⟨n⟩,
have : ∀ m, f m ≤ g n := λ m, hf.forall_le_of_antitone hg h m n,
exact ⟨le_csupr ⟨g $ n, forall_range_iff.2 this⟩ _, csupr_le this⟩
end
/-- Nested intervals lemma: if `[f n, g n]` is an antitone sequence of nonempty
closed intervals, then `⨆ n, f n` belongs to all the intervals `[f n, g n]`. -/
lemma csupr_mem_Inter_Icc_of_antitone_Icc [semilattice_sup β]
{f g : β → α} (h : antitone (λ n, Icc (f n) (g n))) (h' : ∀ n, f n ≤ g n) :
(⨆ n, f n) ∈ ⋂ n, Icc (f n) (g n) :=
monotone.csupr_mem_Inter_Icc_of_antitone (λ m n hmn, ((Icc_subset_Icc_iff (h' n)).1 (h hmn)).1)
(λ m n hmn, ((Icc_subset_Icc_iff (h' n)).1 (h hmn)).2) h'
lemma finset.nonempty.sup'_eq_cSup_image {s : finset β} (hs : s.nonempty) (f : β → α) :
s.sup' hs f = Sup (f '' s) :=
eq_of_forall_ge_iff $ λ a,
by simp [cSup_le_iff (s.finite_to_set.image f).bdd_above (hs.to_set.image f)]
lemma finset.nonempty.sup'_id_eq_cSup {s : finset α} (hs : s.nonempty) :
s.sup' hs id = Sup s :=
by rw [hs.sup'_eq_cSup_image, image_id]
/--Introduction rule to prove that b is the supremum of s: it suffices to check that
1) b is an upper bound
2) every other upper bound b' satisfies b ≤ b'.-/
theorem cSup_eq_of_is_forall_le_of_forall_le_imp_ge (hs : s.nonempty)
(h_is_ub : ∀ a ∈ s, a ≤ b) (h_b_le_ub : ∀ub, (∀ a ∈ s, a ≤ ub) → (b ≤ ub)) : Sup s = b :=
(cSup_le hs h_is_ub).antisymm (h_b_le_ub _ $ λ a, le_cSup ⟨b, h_is_ub⟩)
end conditionally_complete_lattice
instance pi.conditionally_complete_lattice {ι : Type*} {α : Π i : ι, Type*}
[Π i, conditionally_complete_lattice (α i)] :
conditionally_complete_lattice (Π i, α i) :=
{ le_cSup := λ s f ⟨g, hg⟩ hf i, le_cSup ⟨g i, set.forall_range_iff.2 $ λ ⟨f', hf'⟩, hg hf' i⟩
⟨⟨f, hf⟩, rfl⟩,
cSup_le := λ s f hs hf i, cSup_le (by haveI := hs.to_subtype; apply range_nonempty) $
λ b ⟨⟨g, hg⟩, hb⟩, hb ▸ hf hg i,
cInf_le := λ s f ⟨g, hg⟩ hf i, cInf_le ⟨g i, set.forall_range_iff.2 $ λ ⟨f', hf'⟩, hg hf' i⟩
⟨⟨f, hf⟩, rfl⟩,
le_cInf := λ s f hs hf i, le_cInf (by haveI := hs.to_subtype; apply range_nonempty) $
λ b ⟨⟨g, hg⟩, hb⟩, hb ▸ hf hg i,
.. pi.lattice, .. pi.has_Sup, .. pi.has_Inf }
section conditionally_complete_linear_order
variables [conditionally_complete_linear_order α] {s t : set α} {a b : α}
lemma finset.nonempty.cSup_eq_max' {s : finset α} (h : s.nonempty) : Sup ↑s = s.max' h :=
eq_of_forall_ge_iff $ λ a, (cSup_le_iff s.bdd_above h.to_set).trans (s.max'_le_iff h).symm
lemma finset.nonempty.cInf_eq_min' {s : finset α} (h : s.nonempty) : Inf ↑s = s.min' h :=
@finset.nonempty.cSup_eq_max' αᵒᵈ _ s h
lemma finset.nonempty.cSup_mem {s : finset α} (h : s.nonempty) : Sup (s : set α) ∈ s :=
by { rw h.cSup_eq_max', exact s.max'_mem _ }
lemma finset.nonempty.cInf_mem {s : finset α} (h : s.nonempty) : Inf (s : set α) ∈ s :=
@finset.nonempty.cSup_mem αᵒᵈ _ _ h
lemma set.nonempty.cSup_mem (h : s.nonempty) (hs : s.finite) : Sup s ∈ s :=
by { lift s to finset α using hs, exact finset.nonempty.cSup_mem h }
lemma set.nonempty.cInf_mem (h : s.nonempty) (hs : s.finite) : Inf s ∈ s :=
@set.nonempty.cSup_mem αᵒᵈ _ _ h hs
lemma set.finite.cSup_lt_iff (hs : s.finite) (h : s.nonempty) : Sup s < a ↔ ∀ x ∈ s, x < a :=
⟨λ h x hx, (le_cSup hs.bdd_above hx).trans_lt h, λ H, H _ $ h.cSup_mem hs⟩
lemma set.finite.lt_cInf_iff (hs : s.finite) (h : s.nonempty) : a < Inf s ↔ ∀ x ∈ s, a < x :=
@set.finite.cSup_lt_iff αᵒᵈ _ _ _ hs h
/-- When b < Sup s, there is an element a in s with b < a, if s is nonempty and the order is
a linear order. -/
lemma exists_lt_of_lt_cSup (hs : s.nonempty) (hb : b < Sup s) : ∃ a ∈ s, b < a :=
by { contrapose! hb, exact cSup_le hs hb }
/--
Indexed version of the above lemma `exists_lt_of_lt_cSup`.
When `b < supr f`, there is an element `i` such that `b < f i`.
-/
lemma exists_lt_of_lt_csupr [nonempty ι] {f : ι → α} (h : b < supr f) : ∃ i, b < f i :=
let ⟨_, ⟨i, rfl⟩, h⟩ := exists_lt_of_lt_cSup (range_nonempty f) h in ⟨i, h⟩
/--When Inf s < b, there is an element a in s with a < b, if s is nonempty and the order is
a linear order.-/
lemma exists_lt_of_cInf_lt (hs : s.nonempty) (hb : Inf s < b) : ∃ a ∈ s, a < b :=
@exists_lt_of_lt_cSup αᵒᵈ _ _ _ hs hb
/--
Indexed version of the above lemma `exists_lt_of_cInf_lt`
When `infi f < a`, there is an element `i` such that `f i < a`.
-/
lemma exists_lt_of_cinfi_lt [nonempty ι] {f : ι → α} (h : infi f < a) : ∃ i, f i < a :=
@exists_lt_of_lt_csupr αᵒᵈ _ _ _ _ _ h
open function
variables [is_well_order α (<)]
lemma Inf_eq_argmin_on (hs : s.nonempty) :
Inf s = argmin_on id (@is_well_founded.wf α (<) _) s hs :=
is_least.cInf_eq ⟨argmin_on_mem _ _ _ _, λ a ha, argmin_on_le id _ _ ha⟩
lemma is_least_Inf (hs : s.nonempty) : is_least s (Inf s) :=
by { rw Inf_eq_argmin_on hs, exact ⟨argmin_on_mem _ _ _ _, λ a ha, argmin_on_le id _ _ ha⟩ }
lemma le_cInf_iff' (hs : s.nonempty) : b ≤ Inf s ↔ b ∈ lower_bounds s :=
le_is_glb_iff (is_least_Inf hs).is_glb
lemma Inf_mem (hs : s.nonempty) : Inf s ∈ s := (is_least_Inf hs).1
lemma infi_mem [nonempty ι] (f : ι → α) : infi f ∈ range f := Inf_mem (range_nonempty f)
lemma monotone_on.map_Inf {β : Type*} [conditionally_complete_lattice β] {f : α → β}
(hf : monotone_on f s) (hs : s.nonempty) : f (Inf s) = Inf (f '' s) :=
(hf.map_is_least (is_least_Inf hs)).cInf_eq.symm
lemma monotone.map_Inf {β : Type*} [conditionally_complete_lattice β] {f : α → β} (hf : monotone f)
(hs : s.nonempty) : f (Inf s) = Inf (f '' s) :=
(hf.map_is_least (is_least_Inf hs)).cInf_eq.symm
end conditionally_complete_linear_order
/-!
### Lemmas about a conditionally complete linear order with bottom element
In this case we have `Sup ∅ = ⊥`, so we can drop some `nonempty`/`set.nonempty` assumptions.
-/
section conditionally_complete_linear_order_bot
variables [conditionally_complete_linear_order_bot α]
@[simp] lemma cSup_empty : (Sup ∅ : α) = ⊥ :=
conditionally_complete_linear_order_bot.cSup_empty
@[simp] lemma csupr_of_empty [is_empty ι] (f : ι → α) : (⨆ i, f i) = ⊥ :=
by rw [supr_of_empty', cSup_empty]
@[simp] lemma csupr_false (f : false → α) : (⨆ i, f i) = ⊥ := csupr_of_empty f
@[simp] lemma cInf_univ : Inf (univ : set α) = ⊥ := is_least_univ.cInf_eq
lemma is_lub_cSup' {s : set α} (hs : bdd_above s) : is_lub s (Sup s) :=
begin
rcases eq_empty_or_nonempty s with (rfl|hne),
{ simp only [cSup_empty, is_lub_empty] },
{ exact is_lub_cSup hne hs }
end
lemma cSup_le_iff' {s : set α} (hs : bdd_above s) {a : α} : Sup s ≤ a ↔ ∀ x ∈ s, x ≤ a :=
is_lub_le_iff (is_lub_cSup' hs)
lemma cSup_le' {s : set α} {a : α} (h : a ∈ upper_bounds s) : Sup s ≤ a :=
(cSup_le_iff' ⟨a, h⟩).2 h
theorem le_cSup_iff' {s : set α} {a : α} (h : bdd_above s) :
a ≤ Sup s ↔ ∀ b, b ∈ upper_bounds s → a ≤ b :=
⟨λ h b hb, le_trans h (cSup_le' hb), λ hb, hb _ (λ x, le_cSup h)⟩
lemma le_csupr_iff' {s : ι → α} {a : α} (h : bdd_above (range s)) :
a ≤ supr s ↔ ∀ b, (∀ i, s i ≤ b) → a ≤ b :=
by simp [supr, h, le_cSup_iff', upper_bounds]
theorem le_cInf_iff'' {s : set α} {a : α} (ne : s.nonempty) :
a ≤ Inf s ↔ ∀ (b : α), b ∈ s → a ≤ b :=
le_cInf_iff ⟨⊥, λ a _, bot_le⟩ ne
theorem le_cinfi_iff' [nonempty ι] {f : ι → α} {a : α} :
a ≤ infi f ↔ ∀ i, a ≤ f i :=
le_cinfi_iff ⟨⊥, λ a _, bot_le⟩
theorem cInf_le' {s : set α} {a : α} (h : a ∈ s) : Inf s ≤ a :=
cInf_le ⟨⊥, λ a _, bot_le⟩ h
theorem cinfi_le' (f : ι → α) (i : ι) : infi f ≤ f i :=
cinfi_le ⟨⊥, λ a _, bot_le⟩ _
lemma exists_lt_of_lt_cSup' {s : set α} {a : α} (h : a < Sup s) : ∃ b ∈ s, a < b :=
by { contrapose! h, exact cSup_le' h }
lemma csupr_le_iff' {f : ι → α} (h : bdd_above (range f)) {a : α} :
(⨆ i, f i) ≤ a ↔ ∀ i, f i ≤ a :=
(cSup_le_iff' h).trans forall_range_iff
lemma csupr_le' {f : ι → α} {a : α} (h : ∀ i, f i ≤ a) : (⨆ i, f i) ≤ a :=
cSup_le' $ forall_range_iff.2 h
lemma exists_lt_of_lt_csupr' {f : ι → α} {a : α} (h : a < ⨆ i, f i) : ∃ i, a < f i :=
by { contrapose! h, exact csupr_le' h }
lemma csupr_mono' {ι'} {f : ι → α} {g : ι' → α} (hg : bdd_above (range g))
(h : ∀ i, ∃ i', f i ≤ g i') : supr f ≤ supr g :=
csupr_le' $ λ i, exists.elim (h i) (le_csupr_of_le hg)
lemma cInf_le_cInf' {s t : set α} (h₁ : t.nonempty) (h₂ : t ⊆ s) : Inf s ≤ Inf t :=
cInf_le_cInf (order_bot.bdd_below s) h₁ h₂
end conditionally_complete_linear_order_bot
namespace with_top
open_locale classical
variables [conditionally_complete_linear_order_bot α]
/-- The Sup of a non-empty set is its least upper bound for a conditionally
complete lattice with a top. -/
lemma is_lub_Sup' {β : Type*} [conditionally_complete_lattice β]
{s : set (with_top β)} (hs : s.nonempty) : is_lub s (Sup s) :=
begin
split,
{ show ite _ _ _ ∈ _,
split_ifs,
{ intros _ _, exact le_top },
{ rintro (⟨⟩|a) ha,
{ contradiction },
apply some_le_some.2,
exact le_cSup h_1 ha },
{ intros _ _, exact le_top } },
{ show ite _ _ _ ∈ _,
split_ifs,
{ rintro (⟨⟩|a) ha,
{ exact le_rfl },
{ exact false.elim (not_top_le_coe a (ha h)) } },
{ rintro (⟨⟩|b) hb,
{ exact le_top },
refine some_le_some.2 (cSup_le _ _),
{ rcases hs with ⟨⟨⟩|b, hb⟩,
{ exact absurd hb h },
{ exact ⟨b, hb⟩ } },
{ intros a ha, exact some_le_some.1 (hb ha) } },
{ rintro (⟨⟩|b) hb,
{ exact le_rfl },
{ exfalso, apply h_1, use b, intros a ha, exact some_le_some.1 (hb ha) } } }
end
lemma is_lub_Sup (s : set (with_top α)) : is_lub s (Sup s) :=
begin
cases s.eq_empty_or_nonempty with hs hs,
{ rw hs,
show is_lub ∅ (ite _ _ _),
split_ifs,
{ cases h },
{ rw [preimage_empty, cSup_empty], exact is_lub_empty },
{ exfalso, apply h_1, use ⊥, rintro a ⟨⟩ } },
exact is_lub_Sup' hs,
end
/-- The Inf of a bounded-below set is its greatest lower bound for a conditionally
complete lattice with a top. -/
lemma is_glb_Inf' {β : Type*} [conditionally_complete_lattice β]
{s : set (with_top β)} (hs : bdd_below s) : is_glb s (Inf s) :=
begin
split,
{ show ite _ _ _ ∈ _,
split_ifs,
{ intros a ha, exact top_le_iff.2 (set.mem_singleton_iff.1 (h ha)) },
{ rintro (⟨⟩|a) ha,
{ exact le_top },
refine some_le_some.2 (cInf_le _ ha),
rcases hs with ⟨⟨⟩|b, hb⟩,
{ exfalso,
apply h,
intros c hc,
rw [mem_singleton_iff, ←top_le_iff],
exact hb hc },
use b,
intros c hc,
exact some_le_some.1 (hb hc) } },
{ show ite _ _ _ ∈ _,
split_ifs,
{ intros _ _, exact le_top },
{ rintro (⟨⟩|a) ha,
{ exfalso, apply h, intros b hb, exact set.mem_singleton_iff.2 (top_le_iff.1 (ha hb)) },
{ refine some_le_some.2 (le_cInf _ _),
{ classical, contrapose! h,
rintros (⟨⟩|a) ha,
{ exact mem_singleton ⊤ },
{ exact (h ⟨a, ha⟩).elim }},
{ intros b hb,
rw ←some_le_some,
exact ha hb } } } }
end
lemma is_glb_Inf (s : set (with_top α)) : is_glb s (Inf s) :=
begin
by_cases hs : bdd_below s,
{ exact is_glb_Inf' hs },
{ exfalso, apply hs, use ⊥, intros _ _, exact bot_le },
end
noncomputable instance : complete_linear_order (with_top α) :=
{ Sup := Sup, le_Sup := λ s, (is_lub_Sup s).1, Sup_le := λ s, (is_lub_Sup s).2,
Inf := Inf, le_Inf := λ s, (is_glb_Inf s).2, Inf_le := λ s, (is_glb_Inf s).1,
.. with_top.linear_order, ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot }
/-- A version of `with_top.coe_Sup'` with a more convenient but less general statement. -/
@[norm_cast] lemma coe_Sup {s : set α} (hb : bdd_above s) :
↑(Sup s) = (⨆ a ∈ s, ↑a : with_top α) :=
by rw [coe_Sup' hb, Sup_image]
/-- A version of `with_top.coe_Inf'` with a more convenient but less general statement. -/
@[norm_cast] lemma coe_Inf {s : set α} (hs : s.nonempty) :
↑(Inf s) = (⨅ a ∈ s, ↑a : with_top α) :=
by rw [coe_Inf' hs, Inf_image]
end with_top
namespace monotone
variables [preorder α] [conditionally_complete_lattice β] {f : α → β} (h_mono : monotone f)
/-! A monotone function into a conditionally complete lattice preserves the ordering properties of
`Sup` and `Inf`. -/
lemma le_cSup_image {s : set α} {c : α} (hcs : c ∈ s) (h_bdd : bdd_above s) :
f c ≤ Sup (f '' s) :=
le_cSup (map_bdd_above h_mono h_bdd) (mem_image_of_mem f hcs)
lemma cSup_image_le {s : set α} (hs : s.nonempty) {B : α} (hB: B ∈ upper_bounds s) :
Sup (f '' s) ≤ f B :=
cSup_le (nonempty.image f hs) (h_mono.mem_upper_bounds_image hB)
lemma cInf_image_le {s : set α} {c : α} (hcs : c ∈ s) (h_bdd : bdd_below s) :
Inf (f '' s) ≤ f c :=
@le_cSup_image αᵒᵈ βᵒᵈ _ _ _ (λ x y hxy, h_mono hxy) _ _ hcs h_bdd
lemma le_cInf_image {s : set α} (hs : s.nonempty) {B : α} (hB: B ∈ lower_bounds s) :
f B ≤ Inf (f '' s) :=
@cSup_image_le αᵒᵈ βᵒᵈ _ _ _ (λ x y hxy, h_mono hxy) _ hs _ hB
end monotone
namespace galois_connection
variables [conditionally_complete_lattice α] [conditionally_complete_lattice β] [nonempty ι]
{l : α → β} {u : β → α}
lemma l_cSup (gc : galois_connection l u) {s : set α} (hne : s.nonempty)
(hbdd : bdd_above s) :
l (Sup s) = ⨆ x : s, l x :=
eq.symm $ is_lub.csupr_set_eq (gc.is_lub_l_image $ is_lub_cSup hne hbdd) hne
lemma l_cSup' (gc : galois_connection l u) {s : set α} (hne : s.nonempty) (hbdd : bdd_above s) :
l (Sup s) = Sup (l '' s) :=
by rw [gc.l_cSup hne hbdd, csupr_set]
lemma l_csupr (gc : galois_connection l u) {f : ι → α}
(hf : bdd_above (range f)) :
l (⨆ i, f i) = ⨆ i, l (f i) :=
by rw [supr, gc.l_cSup (range_nonempty _) hf, supr_range']
lemma l_csupr_set (gc : galois_connection l u) {s : set γ} {f : γ → α}
(hf : bdd_above (f '' s)) (hne : s.nonempty) :
l (⨆ i : s, f i) = ⨆ i : s, l (f i) :=
by { haveI := hne.to_subtype, rw image_eq_range at hf, exact gc.l_csupr hf }
lemma u_cInf (gc : galois_connection l u) {s : set β} (hne : s.nonempty)
(hbdd : bdd_below s) :
u (Inf s) = ⨅ x : s, u x :=
gc.dual.l_cSup hne hbdd
lemma u_cInf' (gc : galois_connection l u) {s : set β} (hne : s.nonempty) (hbdd : bdd_below s) :
u (Inf s) = Inf (u '' s) :=
gc.dual.l_cSup' hne hbdd
lemma u_cinfi (gc : galois_connection l u) {f : ι → β}
(hf : bdd_below (range f)) :
u (⨅ i, f i) = ⨅ i, u (f i) :=
gc.dual.l_csupr hf
lemma u_cinfi_set (gc : galois_connection l u) {s : set γ} {f : γ → β}
(hf : bdd_below (f '' s)) (hne : s.nonempty) :
u (⨅ i : s, f i) = ⨅ i : s, u (f i) :=
gc.dual.l_csupr_set hf hne
end galois_connection
namespace order_iso
variables [conditionally_complete_lattice α] [conditionally_complete_lattice β] [nonempty ι]
lemma map_cSup (e : α ≃o β) {s : set α} (hne : s.nonempty) (hbdd : bdd_above s) :
e (Sup s) = ⨆ x : s, e x :=
e.to_galois_connection.l_cSup hne hbdd
lemma map_cSup' (e : α ≃o β) {s : set α} (hne : s.nonempty) (hbdd : bdd_above s) :
e (Sup s) = Sup (e '' s) :=
e.to_galois_connection.l_cSup' hne hbdd
lemma map_csupr (e : α ≃o β) {f : ι → α} (hf : bdd_above (range f)) :
e (⨆ i, f i) = ⨆ i, e (f i) :=
e.to_galois_connection.l_csupr hf
lemma map_csupr_set (e : α ≃o β) {s : set γ} {f : γ → α}
(hf : bdd_above (f '' s)) (hne : s.nonempty) :
e (⨆ i : s, f i) = ⨆ i : s, e (f i) :=
e.to_galois_connection.l_csupr_set hf hne
lemma map_cInf (e : α ≃o β) {s : set α} (hne : s.nonempty) (hbdd : bdd_below s) :
e (Inf s) = ⨅ x : s, e x :=
e.dual.map_cSup hne hbdd
lemma map_cInf' (e : α ≃o β) {s : set α} (hne : s.nonempty) (hbdd : bdd_below s) :
e (Inf s) = Inf (e '' s) :=
e.dual.map_cSup' hne hbdd
lemma map_cinfi (e : α ≃o β) {f : ι → α} (hf : bdd_below (range f)) :
e (⨅ i, f i) = ⨅ i, e (f i) :=
e.dual.map_csupr hf
lemma map_cinfi_set (e : α ≃o β) {s : set γ} {f : γ → α}
(hf : bdd_below (f '' s)) (hne : s.nonempty) :
e (⨅ i : s, f i) = ⨅ i : s, e (f i) :=
e.dual.map_csupr_set hf hne
end order_iso
/-!
### Supremum/infimum of `set.image2`
A collection of lemmas showing what happens to the suprema/infima of `s` and `t` when mapped under
a binary function whose partial evaluations are lower/upper adjoints of Galois connections.
-/
section
variables [conditionally_complete_lattice α] [conditionally_complete_lattice β]
[conditionally_complete_lattice γ] {f : α → β → γ} {s : set α} {t : set β}
variables {l u : α → β → γ} {l₁ u₁ : β → γ → α} {l₂ u₂ : α → γ → β}
lemma cSup_image2_eq_cSup_cSup (h₁ : ∀ b, galois_connection (swap l b) (u₁ b))
(h₂ : ∀ a, galois_connection (l a) (u₂ a))
(hs₀ : s.nonempty) (hs₁ : bdd_above s) (ht₀ : t.nonempty) (ht₁ : bdd_above t) :
Sup (image2 l s t) = l (Sup s) (Sup t) :=
begin
refine eq_of_forall_ge_iff (λ c, _),
rw [cSup_le_iff (hs₁.image2 (λ _, (h₁ _).monotone_l) (λ _, (h₂ _).monotone_l) ht₁)
(hs₀.image2 ht₀), forall_image2_iff, forall₂_swap, (h₂ _).le_iff_le, cSup_le_iff ht₁ ht₀],
simp_rw [←(h₂ _).le_iff_le, (h₁ _).le_iff_le, cSup_le_iff hs₁ hs₀],
end
lemma cSup_image2_eq_cSup_cInf (h₁ : ∀ b, galois_connection (swap l b) (u₁ b))
(h₂ : ∀ a, galois_connection (l a ∘ of_dual) (to_dual ∘ u₂ a)) :
s.nonempty → bdd_above s → t.nonempty → bdd_below t → Sup (image2 l s t) = l (Sup s) (Inf t) :=
@cSup_image2_eq_cSup_cSup _ βᵒᵈ _ _ _ _ _ _ _ _ _ h₁ h₂
lemma cSup_image2_eq_cInf_cSup (h₁ : ∀ b, galois_connection (swap l b ∘ of_dual) (to_dual ∘ u₁ b))
(h₂ : ∀ a, galois_connection (l a) (u₂ a)) :
s.nonempty → bdd_below s → t.nonempty → bdd_above t → Sup (image2 l s t) = l (Inf s) (Sup t) :=
@cSup_image2_eq_cSup_cSup αᵒᵈ _ _ _ _ _ _ _ _ _ _ h₁ h₂
lemma cSup_image2_eq_cInf_cInf (h₁ : ∀ b, galois_connection (swap l b ∘ of_dual) (to_dual ∘ u₁ b))
(h₂ : ∀ a, galois_connection (l a ∘ of_dual) (to_dual ∘ u₂ a)) :
s.nonempty → bdd_below s → t.nonempty → bdd_below t → Sup (image2 l s t) = l (Inf s) (Inf t) :=
@cSup_image2_eq_cSup_cSup αᵒᵈ βᵒᵈ _ _ _ _ _ _ _ _ _ h₁ h₂
lemma cInf_image2_eq_cInf_cInf (h₁ : ∀ b, galois_connection (l₁ b) (swap u b))
(h₂ : ∀ a, galois_connection (l₂ a) (u a)) :
s.nonempty → bdd_below s → t.nonempty → bdd_below t →
Inf (image2 u s t) = u (Inf s) (Inf t) :=
@cSup_image2_eq_cSup_cSup αᵒᵈ βᵒᵈ γᵒᵈ _ _ _ _ _ _ l₁ l₂ (λ _, (h₁ _).dual) (λ _, (h₂ _).dual)
lemma cInf_image2_eq_cInf_cSup (h₁ : ∀ b, galois_connection (l₁ b) (swap u b))
(h₂ : ∀ a, galois_connection (to_dual ∘ l₂ a) (u a ∘ of_dual)) :
s.nonempty → bdd_below s → t.nonempty → bdd_above t → Inf (image2 u s t) = u (Inf s) (Sup t) :=
@cInf_image2_eq_cInf_cInf _ βᵒᵈ _ _ _ _ _ _ _ _ _ h₁ h₂
lemma cInf_image2_eq_cSup_cInf (h₁ : ∀ b, galois_connection (to_dual ∘ l₁ b) (swap u b ∘ of_dual))
(h₂ : ∀ a, galois_connection (l₂ a) (u a)) :
s.nonempty → bdd_above s → t.nonempty → bdd_below t → Inf (image2 u s t) = u (Sup s) (Inf t) :=
@cInf_image2_eq_cInf_cInf αᵒᵈ _ _ _ _ _ _ _ _ _ _ h₁ h₂
lemma cInf_image2_eq_cSup_cSup (h₁ : ∀ b, galois_connection (to_dual ∘ l₁ b) (swap u b ∘ of_dual))
(h₂ : ∀ a, galois_connection (to_dual ∘ l₂ a) (u a ∘ of_dual)) :
s.nonempty → bdd_above s → t.nonempty → bdd_above t → Inf (image2 u s t) = u (Sup s) (Sup t) :=
@cInf_image2_eq_cInf_cInf αᵒᵈ βᵒᵈ _ _ _ _ _ _ _ _ _ h₁ h₂
end
/-!
### Relation between `Sup` / `Inf` and `finset.sup'` / `finset.inf'`
Like the `Sup` of a `conditionally_complete_lattice`, `finset.sup'` also requires the set to be
non-empty. As a result, we can translate between the two.
-/
namespace finset
lemma sup'_eq_cSup_image [conditionally_complete_lattice β] (s : finset α) (H) (f : α → β) :
s.sup' H f = Sup (f '' s) :=
begin
apply le_antisymm,
{ refine (finset.sup'_le _ _ $ λ a ha, _),
refine le_cSup ⟨s.sup' H f, _⟩ ⟨a, ha, rfl⟩,
rintros i ⟨j, hj, rfl⟩,
exact finset.le_sup' _ hj },
{ apply cSup_le ((coe_nonempty.mpr H).image _),
rintros _ ⟨a, ha, rfl⟩,
exact finset.le_sup' _ ha, }
end
lemma inf'_eq_cInf_image [conditionally_complete_lattice β] (s : finset α) (H) (f : α → β) :
s.inf' H f = Inf (f '' s) :=
@sup'_eq_cSup_image _ βᵒᵈ _ _ H _
lemma sup'_id_eq_cSup [conditionally_complete_lattice α] (s : finset α) (H) :
s.sup' H id = Sup s :=
by rw [sup'_eq_cSup_image s H, set.image_id]
lemma inf'_id_eq_cInf [conditionally_complete_lattice α] (s : finset α) (H) :
s.inf' H id = Inf s :=
@sup'_id_eq_cSup αᵒᵈ _ _ H
end finset
section with_top_bot
/-!
### Complete lattice structure on `with_top (with_bot α)`
If `α` is a `conditionally_complete_lattice`, then we show that `with_top α` and `with_bot α`
also inherit the structure of conditionally complete lattices. Furthermore, we show
that `with_top (with_bot α)` naturally inherits the structure of a complete lattice. Note that
for α a conditionally complete lattice, `Sup` and `Inf` both return junk values
for sets which are empty or unbounded. The extension of `Sup` to `with_top α` fixes
the unboundedness problem and the extension to `with_bot α` fixes the problem with
the empty set.
This result can be used to show that the extended reals [-∞, ∞] are a complete lattice.
-/
open_locale classical
/-- Adding a top element to a conditionally complete lattice
gives a conditionally complete lattice -/
noncomputable instance with_top.conditionally_complete_lattice
{α : Type*} [conditionally_complete_lattice α] :
conditionally_complete_lattice (with_top α) :=
{ le_cSup := λ S a hS haS, (with_top.is_lub_Sup' ⟨a, haS⟩).1 haS,
cSup_le := λ S a hS haS, (with_top.is_lub_Sup' hS).2 haS,
cInf_le := λ S a hS haS, (with_top.is_glb_Inf' hS).1 haS,
le_cInf := λ S a hS haS, (with_top.is_glb_Inf' ⟨a, haS⟩).2 haS,
..with_top.lattice,
..with_top.has_Sup,
..with_top.has_Inf }
/-- Adding a bottom element to a conditionally complete lattice
gives a conditionally complete lattice -/
noncomputable instance with_bot.conditionally_complete_lattice
{α : Type*} [conditionally_complete_lattice α] :
conditionally_complete_lattice (with_bot α) :=
{ le_cSup := (@with_top.conditionally_complete_lattice αᵒᵈ _).cInf_le,
cSup_le := (@with_top.conditionally_complete_lattice αᵒᵈ _).le_cInf,
cInf_le := (@with_top.conditionally_complete_lattice αᵒᵈ _).le_cSup,
le_cInf := (@with_top.conditionally_complete_lattice αᵒᵈ _).cSup_le,
..with_bot.lattice,
..with_bot.has_Sup,
..with_bot.has_Inf }
noncomputable instance with_top.with_bot.complete_lattice {α : Type*}
[conditionally_complete_lattice α] : complete_lattice (with_top (with_bot α)) :=
{ le_Sup := λ S a haS, (with_top.is_lub_Sup' ⟨a, haS⟩).1 haS,
Sup_le := λ S a ha,
begin
cases S.eq_empty_or_nonempty with h,
{ show ite _ _ _ ≤ a,
split_ifs,
{ rw h at h_1, cases h_1 },
{ convert bot_le, convert with_bot.cSup_empty, rw h, refl },
{ exfalso, apply h_2, use ⊥, rw h, rintro b ⟨⟩ } },
{ refine (with_top.is_lub_Sup' h).2 ha }
end,
Inf_le := λ S a haS,
show ite _ _ _ ≤ a,
begin
split_ifs,
{ cases a with a, exact le_rfl,
cases (h haS); tauto },
{ cases a,
{ exact le_top },
{ apply with_top.some_le_some.2, refine cInf_le _ haS, use ⊥, intros b hb, exact bot_le } }
end,
le_Inf := λ S a haS, (with_top.is_glb_Inf' ⟨a, haS⟩).2 haS,
..with_top.has_Inf,
..with_top.has_Sup,
..with_top.bounded_order,
..with_top.lattice }
noncomputable instance with_top.with_bot.complete_linear_order {α : Type*}
[conditionally_complete_linear_order α] : complete_linear_order (with_top (with_bot α)) :=
{ .. with_top.with_bot.complete_lattice,
.. with_top.linear_order }
lemma with_top.supr_coe_eq_top {ι : Sort*} {α : Type*} [conditionally_complete_linear_order_bot α]
(f : ι → α) : (⨆ x, (f x : with_top α)) = ⊤ ↔ ¬ bdd_above (set.range f) :=
begin
refine ⟨_, λ hf, _⟩,
{ rw [supr_eq_top, not_bdd_above_iff],
intros hf r,
rcases hf r (with_top.coe_lt_top r) with ⟨i, hi⟩,
exact ⟨f i, ⟨i, rfl⟩, with_top.coe_lt_coe.mp hi⟩ },
{ refine (supr_eq_top _).mpr (λ a ha, _),
rcases not_bdd_above_iff.mp hf (a.untop ha.ne) with ⟨-, ⟨i, rfl⟩, hi⟩,
exact ⟨i, by simpa only [with_top.coe_untop _ ha.ne] using with_top.coe_lt_coe.mpr hi⟩ },
end
lemma with_top.supr_coe_lt_top {ι : Sort*} {α : Type*} [conditionally_complete_linear_order_bot α]
(f : ι → α) : (⨆ x, (f x : with_top α)) < ⊤ ↔ bdd_above (set.range f) :=
by simpa only [not_not, lt_top_iff_ne_top] using not_iff_not.mpr (with_top.supr_coe_eq_top f)
end with_top_bot
section group
variables {ι' : Sort*} [nonempty ι] [nonempty ι'] [conditionally_complete_lattice α] [group α]
@[to_additive]
lemma le_mul_cinfi [covariant_class α α (*) (≤)] {a : α} {g : α} {h : ι → α}
(H : ∀ j, a ≤ g * h j) : a ≤ g * infi h :=
inv_mul_le_iff_le_mul.mp $ le_cinfi $ λ hi, inv_mul_le_iff_le_mul.mpr $ H _
@[to_additive]
lemma mul_csupr_le [covariant_class α α (*) (≤)] {a : α} {g : α} {h : ι → α}
(H : ∀ j, g * h j ≤ a) : g * supr h ≤ a :=
@le_mul_cinfi αᵒᵈ _ _ _ _ _ _ _ _ H
@[to_additive]
lemma le_cinfi_mul [covariant_class α α (function.swap (*)) (≤)] {a : α} {g : ι → α} {h : α}
(H : ∀ i, a ≤ g i * h) : a ≤ infi g * h :=
mul_inv_le_iff_le_mul.mp $ le_cinfi $ λ gi, mul_inv_le_iff_le_mul.mpr $ H _
@[to_additive]
lemma csupr_mul_le [covariant_class α α (function.swap (*)) (≤)] {a : α} {g : ι → α} {h : α}
(H : ∀ i, g i * h ≤ a) : supr g * h ≤ a :=
@le_cinfi_mul αᵒᵈ _ _ _ _ _ _ _ _ H
@[to_additive]
lemma le_cinfi_mul_cinfi [covariant_class α α (*) (≤)] [covariant_class α α (function.swap (*)) (≤)]
{a : α} {g : ι → α} {h : ι' → α} (H : ∀ i j, a ≤ g i * h j) : a ≤ infi g * infi h :=
le_cinfi_mul $ λ i, le_mul_cinfi $ H _
@[to_additive]
lemma csupr_mul_csupr_le [covariant_class α α (*) (≤)] [covariant_class α α (function.swap (*)) (≤)]
{a : α} {g : ι → α} {h : ι' → α} (H : ∀ i j, g i * h j ≤ a) : supr g * supr h ≤ a :=
csupr_mul_le $ λ i, mul_csupr_le $ H _
end group
|
cd5fc9b621bf40d26345c9844aff9b2c0722a622 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/order/filter/bases.lean | 3c9787d1975274fb470293e9ce073499d364fbe7 | [] | 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 | 34,933 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Yury Kudryashov, Johannes Hölzl, Mario Carneiro, Patrick Massot
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.order.filter.basic
import Mathlib.data.set.countable
import Mathlib.PostPort
universes u_6 l u_1 u_4 u_5 u_2 u_3
namespace Mathlib
/-!
# Filter bases
A filter basis `B : filter_basis α` on a type `α` is a nonempty collection of sets of `α`
such that the intersection of two elements of this collection contains some element of
the collection. Compared to filters, filter bases do not require that any set containing
an element of `B` belongs to `B`.
A filter basis `B` can be used to construct `B.filter : filter α` such that a set belongs
to `B.filter` if and only if it contains an element of `B`.
Given an indexing type `ι`, a predicate `p : ι → Prop`, and a map `s : ι → set α`,
the proposition `h : filter.is_basis p s` makes sure the range of `s` bounded by `p`
(ie. `s '' set_of p`) defines a filter basis `h.filter_basis`.
If one already has a filter `l` on `α`, `filter.has_basis l p s` (where `p : ι → Prop`
and `s : ι → set α` as above) means that a set belongs to `l` if and
only if it contains some `s i` with `p i`. It implies `h : filter.is_basis p s`, and
`l = h.filter_basis.filter`. The point of this definition is that checking statements
involving elements of `l` often reduces to checking them on the basis elements.
We define a function `has_basis.index (h : filter.has_basis l p s) (t) (ht : t ∈ l)` that returns
some index `i` such that `p i` and `s i ⊆ t`. This function can be useful to avoid manual
destruction of `h.mem_iff.mpr ht` using `cases` or `let`.
This file also introduces more restricted classes of bases, involving monotonicity or
countability. In particular, for `l : filter α`, `l.is_countably_generated` means
there is a countable set of sets which generates `s`. This is reformulated in term of bases,
and consequences are derived.
## Main statements
* `has_basis.mem_iff`, `has_basis.mem_of_superset`, `has_basis.mem_of_mem` : restate `t ∈ f` in terms
of a basis;
* `basis_sets` : all sets of a filter form a basis;
* `has_basis.inf`, `has_basis.inf_principal`, `has_basis.prod`, `has_basis.prod_self`,
`has_basis.map`, `has_basis.comap` : combinators to construct filters of `l ⊓ l'`,
`l ⊓ 𝓟 t`, `l ×ᶠ l'`, `l ×ᶠ l`, `l.map f`, `l.comap f` respectively;
* `has_basis.le_iff`, `has_basis.ge_iff`, has_basis.le_basis_iff` : restate `l ≤ l'` in terms
of bases.
* `has_basis.tendsto_right_iff`, `has_basis.tendsto_left_iff`, `has_basis.tendsto_iff` : restate
`tendsto f l l'` in terms of bases.
* `is_countably_generated_iff_exists_antimono_basis` : proves a filter is
countably generated if and only if it admis a basis parametrized by a
decreasing sequence of sets indexed by `ℕ`.
* `tendsto_iff_seq_tendsto ` : an abstract version of "sequentially continuous implies continuous".
## Implementation notes
As with `Union`/`bUnion`/`sUnion`, there are three different approaches to filter bases:
* `has_basis l s`, `s : set (set α)`;
* `has_basis l s`, `s : ι → set α`;
* `has_basis l p s`, `p : ι → Prop`, `s : ι → set α`.
We use the latter one because, e.g., `𝓝 x` in an `emetric_space` or in a `metric_space` has a basis
of this form. The other two can be emulated using `s = id` or `p = λ _, true`.
With this approach sometimes one needs to `simp` the statement provided by the `has_basis`
machinery, e.g., `simp only [exists_prop, true_and]` or `simp only [forall_const]` can help
with the case `p = λ _, true`.
-/
/-- A filter basis `B` on a type `α` is a nonempty collection of sets of `α`
such that the intersection of two elements of this collection contains some element
of the collection. -/
structure filter_basis (α : Type u_6)
where
sets : set (set α)
nonempty : set.nonempty sets
inter_sets : ∀ {x y : set α}, x ∈ sets → y ∈ sets → ∃ (z : set α), ∃ (H : z ∈ sets), z ⊆ x ∩ y
protected instance filter_basis.nonempty_sets {α : Type u_1} (B : filter_basis α) : Nonempty ↥(filter_basis.sets B) :=
set.nonempty.to_subtype (filter_basis.nonempty B)
/-- If `B` is a filter basis on `α`, and `U` a subset of `α` then we can write `U ∈ B` as on paper. -/
protected instance filter_basis.has_mem {α : Type u_1} : has_mem (set α) (filter_basis α) :=
has_mem.mk fun (U : set α) (B : filter_basis α) => U ∈ filter_basis.sets B
-- For illustration purposes, the filter basis defining (at_top : filter ℕ)
protected instance filter_basis.inhabited : Inhabited (filter_basis ℕ) :=
{ default := filter_basis.mk (set.range set.Ici) sorry sorry }
/-- `is_basis p s` means the image of `s` bounded by `p` is a filter basis. -/
structure filter.is_basis {α : Type u_1} {ι : Type u_4} (p : ι → Prop) (s : ι → set α)
where
nonempty : ∃ (i : ι), p i
inter : ∀ {i j : ι}, p i → p j → ∃ (k : ι), p k ∧ s k ⊆ s i ∩ s j
namespace filter
namespace is_basis
/-- Constructs a filter basis from an indexed family of sets satisfying `is_basis`. -/
protected def filter_basis {α : Type u_1} {ι : Type u_4} {p : ι → Prop} {s : ι → set α} (h : is_basis p s) : filter_basis α :=
filter_basis.mk (s '' set_of p) sorry sorry
theorem mem_filter_basis_iff {α : Type u_1} {ι : Type u_4} {p : ι → Prop} {s : ι → set α} (h : is_basis p s) {U : set α} : U ∈ is_basis.filter_basis h ↔ ∃ (i : ι), p i ∧ s i = U :=
iff.rfl
end is_basis
end filter
namespace filter_basis
/-- The filter associated to a filter basis. -/
protected def filter {α : Type u_1} (B : filter_basis α) : filter α :=
filter.mk (set_of fun (s : set α) => ∃ (t : set α), ∃ (H : t ∈ B), t ⊆ s) sorry sorry sorry
theorem mem_filter_iff {α : Type u_1} (B : filter_basis α) {U : set α} : U ∈ filter_basis.filter B ↔ ∃ (s : set α), ∃ (H : s ∈ B), s ⊆ U :=
iff.rfl
theorem mem_filter_of_mem {α : Type u_1} (B : filter_basis α) {U : set α} : U ∈ B → U ∈ filter_basis.filter B :=
fun (U_in : U ∈ B) => Exists.intro U (Exists.intro U_in (set.subset.refl U))
theorem eq_infi_principal {α : Type u_1} (B : filter_basis α) : filter_basis.filter B = infi fun (s : ↥(sets B)) => filter.principal ↑s := sorry
protected theorem generate {α : Type u_1} (B : filter_basis α) : filter.generate (sets B) = filter_basis.filter B := sorry
end filter_basis
namespace filter
namespace is_basis
/-- Constructs a filter from an indexed family of sets satisfying `is_basis`. -/
protected def filter {α : Type u_1} {ι : Type u_4} {p : ι → Prop} {s : ι → set α} (h : is_basis p s) : filter α :=
filter_basis.filter (is_basis.filter_basis h)
protected theorem mem_filter_iff {α : Type u_1} {ι : Type u_4} {p : ι → Prop} {s : ι → set α} (h : is_basis p s) {U : set α} : U ∈ is_basis.filter h ↔ ∃ (i : ι), p i ∧ s i ⊆ U := sorry
theorem filter_eq_generate {α : Type u_1} {ι : Type u_4} {p : ι → Prop} {s : ι → set α} (h : is_basis p s) : is_basis.filter h = generate (set_of fun (U : set α) => ∃ (i : ι), p i ∧ s i = U) := sorry
end is_basis
/-- We say that a filter `l` has a basis `s : ι → set α` bounded by `p : ι → Prop`,
if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`. -/
structure has_basis {α : Type u_1} {ι : Type u_4} (l : filter α) (p : ι → Prop) (s : ι → set α)
where
mem_iff' : ∀ (t : set α), t ∈ l ↔ ∃ (i : ι), ∃ (hi : p i), s i ⊆ t
theorem has_basis_generate {α : Type u_1} (s : set (set α)) : has_basis (generate s) (fun (t : set (set α)) => set.finite t ∧ t ⊆ s) fun (t : set (set α)) => ⋂₀t := sorry
/-- The smallest filter basis containing a given collection of sets. -/
def filter_basis.of_sets {α : Type u_1} (s : set (set α)) : filter_basis α :=
filter_basis.mk (set.sInter '' set_of fun (t : set (set α)) => set.finite t ∧ t ⊆ s) sorry sorry
/-- Definition of `has_basis` unfolded with implicit set argument. -/
theorem has_basis.mem_iff {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} {t : set α} (hl : has_basis l p s) : t ∈ l ↔ ∃ (i : ι), ∃ (hi : p i), s i ⊆ t :=
has_basis.mem_iff' hl t
theorem has_basis_iff {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} : has_basis l p s ↔ ∀ (t : set α), t ∈ l ↔ ∃ (i : ι), ∃ (hi : p i), s i ⊆ t := sorry
theorem has_basis.ex_mem {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} (h : has_basis l p s) : ∃ (i : ι), p i := sorry
protected theorem is_basis.has_basis {α : Type u_1} {ι : Type u_4} {p : ι → Prop} {s : ι → set α} (h : is_basis p s) : has_basis (is_basis.filter h) p s := sorry
theorem has_basis.mem_of_superset {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} {t : set α} {i : ι} (hl : has_basis l p s) (hi : p i) (ht : s i ⊆ t) : t ∈ l :=
iff.mpr (has_basis.mem_iff hl) (Exists.intro i (Exists.intro hi ht))
theorem has_basis.mem_of_mem {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} {i : ι} (hl : has_basis l p s) (hi : p i) : s i ∈ l :=
has_basis.mem_of_superset hl hi (set.subset.refl (s i))
/-- Index of a basis set such that `s i ⊆ t` as an element of `subtype p`. -/
def has_basis.index {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} (h : has_basis l p s) (t : set α) (ht : t ∈ l) : Subtype fun (i : ι) => p i :=
{ val := Exists.some sorry, property := sorry }
theorem has_basis.property_index {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} {t : set α} (h : has_basis l p s) (ht : t ∈ l) : p ↑(has_basis.index h t ht) :=
subtype.property (has_basis.index h t ht)
theorem has_basis.set_index_mem {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} {t : set α} (h : has_basis l p s) (ht : t ∈ l) : s ↑(has_basis.index h t ht) ∈ l :=
has_basis.mem_of_mem h (has_basis.property_index h ht)
theorem has_basis.set_index_subset {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} {t : set α} (h : has_basis l p s) (ht : t ∈ l) : s ↑(has_basis.index h t ht) ⊆ t :=
Exists.snd (Exists.some_spec (iff.mp (has_basis.mem_iff h) ht))
theorem has_basis.is_basis {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} (h : has_basis l p s) : is_basis p s := sorry
theorem has_basis.filter_eq {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} (h : has_basis l p s) : is_basis.filter (has_basis.is_basis h) = l := sorry
theorem has_basis.eq_generate {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} (h : has_basis l p s) : l = generate (set_of fun (U : set α) => ∃ (i : ι), p i ∧ s i = U) := sorry
theorem generate_eq_generate_inter {α : Type u_1} (s : set (set α)) : generate s = generate (set.sInter '' set_of fun (t : set (set α)) => set.finite t ∧ t ⊆ s) := sorry
theorem of_sets_filter_eq_generate {α : Type u_1} (s : set (set α)) : filter_basis.filter (filter_basis.of_sets s) = generate s := sorry
theorem has_basis.to_has_basis {α : Type u_1} {ι : Type u_4} {ι' : Type u_5} {l : filter α} {p : ι → Prop} {s : ι → set α} {p' : ι' → Prop} {s' : ι' → set α} (hl : has_basis l p s) (h : ∀ (i : ι), p i → ∃ (i' : ι'), p' i' ∧ s' i' ⊆ s i) (h' : ∀ (i' : ι'), p' i' → ∃ (i : ι), p i ∧ s i ⊆ s' i') : has_basis l p' s' := sorry
theorem has_basis.eventually_iff {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} (hl : has_basis l p s) {q : α → Prop} : filter.eventually (fun (x : α) => q x) l ↔ ∃ (i : ι), p i ∧ ∀ {x : α}, x ∈ s i → q x := sorry
theorem has_basis.frequently_iff {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} (hl : has_basis l p s) {q : α → Prop} : filter.frequently (fun (x : α) => q x) l ↔ ∀ (i : ι), p i → ∃ (x : α), ∃ (H : x ∈ s i), q x := sorry
theorem has_basis.exists_iff {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} (hl : has_basis l p s) {P : set α → Prop} (mono : ∀ {s t : set α}, s ⊆ t → P t → P s) : (∃ (s : set α), ∃ (H : s ∈ l), P s) ↔ ∃ (i : ι), ∃ (hi : p i), P (s i) := sorry
theorem has_basis.forall_iff {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} (hl : has_basis l p s) {P : set α → Prop} (mono : ∀ {s t : set α}, s ⊆ t → P s → P t) : (∀ (s : set α), s ∈ l → P s) ↔ ∀ (i : ι), p i → P (s i) := sorry
theorem has_basis.ne_bot_iff {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} (hl : has_basis l p s) : ne_bot l ↔ ∀ {i : ι}, p i → set.nonempty (s i) :=
iff.trans (iff.symm forall_sets_nonempty_iff_ne_bot)
(has_basis.forall_iff hl fun (_x _x_1 : set α) => set.nonempty.mono)
theorem has_basis.eq_bot_iff {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} (hl : has_basis l p s) : l = ⊥ ↔ ∃ (i : ι), p i ∧ s i = ∅ := sorry
theorem basis_sets {α : Type u_1} (l : filter α) : has_basis l (fun (s : set α) => s ∈ l) id :=
has_basis.mk fun (t : set α) => iff.symm exists_sets_subset_iff
theorem has_basis_self {α : Type u_1} {l : filter α} {P : set α → Prop} : has_basis l (fun (s : set α) => s ∈ l ∧ P s) id ↔ ∀ (t : set α), t ∈ l ↔ ∃ (r : set α), ∃ (H : r ∈ l), P r ∧ r ⊆ t := sorry
/-- If `{s i | p i}` is a basis of a filter `l` and each `s i` includes `s j` such that
`p j ∧ q j`, then `{s j | p j ∧ q j}` is a basis of `l`. -/
theorem has_basis.restrict {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} (h : has_basis l p s) {q : ι → Prop} (hq : ∀ (i : ι), p i → ∃ (j : ι), p j ∧ q j ∧ s j ⊆ s i) : has_basis l (fun (i : ι) => p i ∧ q i) s := sorry
/-- If `{s i | p i}` is a basis of a filter `l` and `V ∈ l`, then `{s i | p i ∧ s i ⊆ V}`
is a basis of `l`. -/
theorem has_basis.restrict_subset {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} (h : has_basis l p s) {V : set α} (hV : V ∈ l) : has_basis l (fun (i : ι) => p i ∧ s i ⊆ V) s := sorry
theorem has_basis.has_basis_self_subset {α : Type u_1} {l : filter α} {p : set α → Prop} (h : has_basis l (fun (s : set α) => s ∈ l ∧ p s) id) {V : set α} (hV : V ∈ l) : has_basis l (fun (s : set α) => s ∈ l ∧ p s ∧ s ⊆ V) id := sorry
theorem has_basis.ge_iff {α : Type u_1} {ι' : Type u_5} {l : filter α} {l' : filter α} {p' : ι' → Prop} {s' : ι' → set α} (hl' : has_basis l' p' s') : l ≤ l' ↔ ∀ (i' : ι'), p' i' → s' i' ∈ l := sorry
theorem has_basis.le_iff {α : Type u_1} {ι : Type u_4} {l : filter α} {l' : filter α} {p : ι → Prop} {s : ι → set α} (hl : has_basis l p s) : l ≤ l' ↔ ∀ (t : set α), t ∈ l' → ∃ (i : ι), ∃ (hi : p i), s i ⊆ t := sorry
theorem has_basis.le_basis_iff {α : Type u_1} {ι : Type u_4} {ι' : Type u_5} {l : filter α} {l' : filter α} {p : ι → Prop} {s : ι → set α} {p' : ι' → Prop} {s' : ι' → set α} (hl : has_basis l p s) (hl' : has_basis l' p' s') : l ≤ l' ↔ ∀ (i' : ι'), p' i' → ∃ (i : ι), ∃ (hi : p i), s i ⊆ s' i' := sorry
theorem has_basis.ext {α : Type u_1} {ι : Type u_4} {ι' : Type u_5} {l : filter α} {l' : filter α} {p : ι → Prop} {s : ι → set α} {p' : ι' → Prop} {s' : ι' → set α} (hl : has_basis l p s) (hl' : has_basis l' p' s') (h : ∀ (i : ι), p i → ∃ (i' : ι'), p' i' ∧ s' i' ⊆ s i) (h' : ∀ (i' : ι'), p' i' → ∃ (i : ι), p i ∧ s i ⊆ s' i') : l = l' := sorry
theorem has_basis.inf {α : Type u_1} {ι : Type u_4} {ι' : Type u_5} {l : filter α} {l' : filter α} {p : ι → Prop} {s : ι → set α} {p' : ι' → Prop} {s' : ι' → set α} (hl : has_basis l p s) (hl' : has_basis l' p' s') : has_basis (l ⊓ l') (fun (i : ι × ι') => p (prod.fst i) ∧ p' (prod.snd i))
fun (i : ι × ι') => s (prod.fst i) ∩ s' (prod.snd i) := sorry
theorem has_basis_principal {α : Type u_1} (t : set α) : has_basis (principal t) (fun (i : Unit) => True) fun (i : Unit) => t := sorry
theorem has_basis.sup {α : Type u_1} {ι : Type u_4} {ι' : Type u_5} {l : filter α} {l' : filter α} {p : ι → Prop} {s : ι → set α} {p' : ι' → Prop} {s' : ι' → set α} (hl : has_basis l p s) (hl' : has_basis l' p' s') : has_basis (l ⊔ l') (fun (i : ι × ι') => p (prod.fst i) ∧ p' (prod.snd i))
fun (i : ι × ι') => s (prod.fst i) ∪ s' (prod.snd i) := sorry
theorem has_basis.inf_principal {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} (hl : has_basis l p s) (s' : set α) : has_basis (l ⊓ principal s') p fun (i : ι) => s i ∩ s' := sorry
theorem has_basis.inf_basis_ne_bot_iff {α : Type u_1} {ι : Type u_4} {ι' : Type u_5} {l : filter α} {l' : filter α} {p : ι → Prop} {s : ι → set α} {p' : ι' → Prop} {s' : ι' → set α} (hl : has_basis l p s) (hl' : has_basis l' p' s') : ne_bot (l ⊓ l') ↔ ∀ {i : ι}, p i → ∀ {i' : ι'}, p' i' → set.nonempty (s i ∩ s' i') := sorry
theorem has_basis.inf_ne_bot_iff {α : Type u_1} {ι : Type u_4} {l : filter α} {l' : filter α} {p : ι → Prop} {s : ι → set α} (hl : has_basis l p s) : ne_bot (l ⊓ l') ↔ ∀ {i : ι}, p i → ∀ {s' : set α}, s' ∈ l' → set.nonempty (s i ∩ s') :=
has_basis.inf_basis_ne_bot_iff hl (basis_sets l')
theorem has_basis.inf_principal_ne_bot_iff {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} (hl : has_basis l p s) {t : set α} : ne_bot (l ⊓ principal t) ↔ ∀ {i : ι}, p i → set.nonempty (s i ∩ t) :=
has_basis.ne_bot_iff (has_basis.inf_principal hl t)
theorem inf_ne_bot_iff {α : Type u_1} {l : filter α} {l' : filter α} : ne_bot (l ⊓ l') ↔ ∀ {s : set α}, s ∈ l → ∀ {s' : set α}, s' ∈ l' → set.nonempty (s ∩ s') :=
has_basis.inf_ne_bot_iff (basis_sets l)
theorem inf_principal_ne_bot_iff {α : Type u_1} {l : filter α} {s : set α} : ne_bot (l ⊓ principal s) ↔ ∀ (U : set α), U ∈ l → set.nonempty (U ∩ s) :=
has_basis.inf_principal_ne_bot_iff (basis_sets l)
theorem inf_eq_bot_iff {α : Type u_1} {f : filter α} {g : filter α} : f ⊓ g = ⊥ ↔ ∃ (U : set α), ∃ (H : U ∈ f), ∃ (V : set α), ∃ (H : V ∈ g), U ∩ V = ∅ := sorry
protected theorem disjoint_iff {α : Type u_1} {f : filter α} {g : filter α} : disjoint f g ↔ ∃ (U : set α), ∃ (H : U ∈ f), ∃ (V : set α), ∃ (H : V ∈ g), U ∩ V = ∅ :=
iff.trans disjoint_iff inf_eq_bot_iff
theorem mem_iff_inf_principal_compl {α : Type u_1} {f : filter α} {s : set α} : s ∈ f ↔ f ⊓ principal (sᶜ) = ⊥ := sorry
theorem mem_iff_disjoint_principal_compl {α : Type u_1} {f : filter α} {s : set α} : s ∈ f ↔ disjoint f (principal (sᶜ)) :=
iff.trans mem_iff_inf_principal_compl (iff.symm disjoint_iff)
theorem le_iff_forall_disjoint_principal_compl {α : Type u_1} {f : filter α} {g : filter α} : f ≤ g ↔ ∀ (V : set α), V ∈ g → disjoint f (principal (Vᶜ)) :=
forall_congr fun (_x : set α) => forall_congr fun (_x_1 : _x ∈ g) => mem_iff_disjoint_principal_compl
theorem le_iff_forall_inf_principal_compl {α : Type u_1} {f : filter α} {g : filter α} : f ≤ g ↔ ∀ (V : set α), V ∈ g → f ⊓ principal (Vᶜ) = ⊥ :=
forall_congr fun (_x : set α) => forall_congr fun (_x_1 : _x ∈ g) => mem_iff_inf_principal_compl
theorem inf_ne_bot_iff_frequently_left {α : Type u_1} {f : filter α} {g : filter α} : ne_bot (f ⊓ g) ↔ ∀ {p : α → Prop}, filter.eventually (fun (x : α) => p x) f → filter.frequently (fun (x : α) => p x) g := sorry
theorem inf_ne_bot_iff_frequently_right {α : Type u_1} {f : filter α} {g : filter α} : ne_bot (f ⊓ g) ↔ ∀ {p : α → Prop}, filter.eventually (fun (x : α) => p x) g → filter.frequently (fun (x : α) => p x) f := sorry
theorem has_basis.eq_binfi {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} (h : has_basis l p s) : l = infi fun (i : ι) => infi fun (_x : p i) => principal (s i) := sorry
theorem has_basis.eq_infi {α : Type u_1} {ι : Type u_4} {l : filter α} {s : ι → set α} (h : has_basis l (fun (_x : ι) => True) s) : l = infi fun (i : ι) => principal (s i) := sorry
theorem has_basis_infi_principal {α : Type u_1} {ι : Type u_4} {s : ι → set α} (h : directed ge s) [Nonempty ι] : has_basis (infi fun (i : ι) => principal (s i)) (fun (_x : ι) => True) s := sorry
/-- If `s : ι → set α` is an indexed family of sets, then finite intersections of `s i` form a basis
of `⨅ i, 𝓟 (s i)`. -/
theorem has_basis_infi_principal_finite {α : Type u_1} {ι : Type u_4} (s : ι → set α) : has_basis (infi fun (i : ι) => principal (s i)) (fun (t : set ι) => set.finite t)
fun (t : set ι) => set.Inter fun (i : ι) => set.Inter fun (H : i ∈ t) => s i := sorry
theorem has_basis_binfi_principal {α : Type u_1} {β : Type u_2} {s : β → set α} {S : set β} (h : directed_on (s ⁻¹'o ge) S) (ne : set.nonempty S) : has_basis (infi fun (i : β) => infi fun (H : i ∈ S) => principal (s i)) (fun (i : β) => i ∈ S) s := sorry
theorem has_basis_binfi_principal' {α : Type u_1} {ι : Type u_4} {p : ι → Prop} {s : ι → set α} (h : ∀ (i : ι), p i → ∀ (j : ι), p j → ∃ (k : ι), ∃ (h : p k), s k ⊆ s i ∧ s k ⊆ s j) (ne : ∃ (i : ι), p i) : has_basis (infi fun (i : ι) => infi fun (h : p i) => principal (s i)) p s :=
has_basis_binfi_principal h ne
theorem has_basis.map {α : Type u_1} {β : Type u_2} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} (f : α → β) (hl : has_basis l p s) : has_basis (map f l) p fun (i : ι) => f '' s i := sorry
theorem has_basis.comap {α : Type u_1} {β : Type u_2} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} (f : β → α) (hl : has_basis l p s) : has_basis (comap f l) p fun (i : ι) => f ⁻¹' s i := sorry
theorem comap_has_basis {α : Type u_1} {β : Type u_2} (f : α → β) (l : filter β) : has_basis (comap f l) (fun (s : set β) => s ∈ l) fun (s : set β) => f ⁻¹' s :=
has_basis.mk fun (t : set α) => mem_comap_sets
theorem has_basis.prod_self {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} (hl : has_basis l p s) : has_basis (filter.prod l l) p fun (i : ι) => set.prod (s i) (s i) := sorry
theorem mem_prod_self_iff {α : Type u_1} {l : filter α} {s : set (α × α)} : s ∈ filter.prod l l ↔ ∃ (t : set α), ∃ (H : t ∈ l), set.prod t t ⊆ s :=
has_basis.mem_iff (has_basis.prod_self (basis_sets l))
theorem has_basis.sInter_sets {α : Type u_1} {ι : Type u_4} {l : filter α} {p : ι → Prop} {s : ι → set α} (h : has_basis l p s) : ⋂₀sets l = set.Inter fun (i : ι) => set.Inter fun (H : i ∈ set_of p) => s i := sorry
/-- `is_antimono_basis p s` means the image of `s` bounded by `p` is a filter basis
such that `s` is decreasing and `p` is increasing, ie `i ≤ j → p i → p j`. -/
structure is_antimono_basis {α : Type u_1} {ι : Type u_4} (p : ι → Prop) (s : ι → set α) [preorder ι]
extends is_basis p s
where
decreasing : ∀ {i j : ι}, p i → p j → i ≤ j → s j ⊆ s i
mono : monotone p
/-- We say that a filter `l` has a antimono basis `s : ι → set α` bounded by `p : ι → Prop`,
if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`,
and `s` is decreasing and `p` is increasing, ie `i ≤ j → p i → p j`. -/
structure has_antimono_basis {α : Type u_1} {ι : Type u_4} [preorder ι] [preorder ι] (l : filter α) (p : ι → Prop) (s : ι → set α)
extends has_basis l p s
where
decreasing : ∀ {i j : ι}, p i → p j → i ≤ j → s j ⊆ s i
mono : monotone p
theorem has_basis.tendsto_left_iff {α : Type u_1} {β : Type u_2} {ι : Type u_4} {la : filter α} {pa : ι → Prop} {sa : ι → set α} {lb : filter β} {f : α → β} (hla : has_basis la pa sa) : tendsto f la lb ↔ ∀ (t : set β), t ∈ lb → ∃ (i : ι), ∃ (hi : pa i), ∀ (x : α), x ∈ sa i → f x ∈ t := sorry
theorem has_basis.tendsto_right_iff {α : Type u_1} {β : Type u_2} {ι' : Type u_5} {la : filter α} {lb : filter β} {pb : ι' → Prop} {sb : ι' → set β} {f : α → β} (hlb : has_basis lb pb sb) : tendsto f la lb ↔ ∀ (i : ι'), pb i → filter.eventually (fun (x : α) => f x ∈ sb i) la := sorry
theorem has_basis.tendsto_iff {α : Type u_1} {β : Type u_2} {ι : Type u_4} {ι' : Type u_5} {la : filter α} {pa : ι → Prop} {sa : ι → set α} {lb : filter β} {pb : ι' → Prop} {sb : ι' → set β} {f : α → β} (hla : has_basis la pa sa) (hlb : has_basis lb pb sb) : tendsto f la lb ↔ ∀ (ib : ι'), pb ib → ∃ (ia : ι), ∃ (hia : pa ia), ∀ (x : α), x ∈ sa ia → f x ∈ sb ib := sorry
theorem tendsto.basis_left {α : Type u_1} {β : Type u_2} {ι : Type u_4} {la : filter α} {pa : ι → Prop} {sa : ι → set α} {lb : filter β} {f : α → β} (H : tendsto f la lb) (hla : has_basis la pa sa) (t : set β) : t ∈ lb → ∃ (i : ι), ∃ (hi : pa i), ∀ (x : α), x ∈ sa i → f x ∈ t :=
iff.mp (has_basis.tendsto_left_iff hla) H
theorem tendsto.basis_right {α : Type u_1} {β : Type u_2} {ι' : Type u_5} {la : filter α} {lb : filter β} {pb : ι' → Prop} {sb : ι' → set β} {f : α → β} (H : tendsto f la lb) (hlb : has_basis lb pb sb) (i : ι') (hi : pb i) : filter.eventually (fun (x : α) => f x ∈ sb i) la :=
iff.mp (has_basis.tendsto_right_iff hlb) H
theorem tendsto.basis_both {α : Type u_1} {β : Type u_2} {ι : Type u_4} {ι' : Type u_5} {la : filter α} {pa : ι → Prop} {sa : ι → set α} {lb : filter β} {pb : ι' → Prop} {sb : ι' → set β} {f : α → β} (H : tendsto f la lb) (hla : has_basis la pa sa) (hlb : has_basis lb pb sb) (ib : ι') (hib : pb ib) : ∃ (ia : ι), ∃ (hia : pa ia), ∀ (x : α), x ∈ sa ia → f x ∈ sb ib :=
iff.mp (has_basis.tendsto_iff hla hlb) H
theorem has_basis.prod {α : Type u_1} {β : Type u_2} {ι : Type u_4} {ι' : Type u_5} {la : filter α} {pa : ι → Prop} {sa : ι → set α} {lb : filter β} {pb : ι' → Prop} {sb : ι' → set β} (hla : has_basis la pa sa) (hlb : has_basis lb pb sb) : has_basis (filter.prod la lb) (fun (i : ι × ι') => pa (prod.fst i) ∧ pb (prod.snd i))
fun (i : ι × ι') => set.prod (sa (prod.fst i)) (sb (prod.snd i)) :=
has_basis.inf (has_basis.comap prod.fst hla) (has_basis.comap prod.snd hlb)
theorem has_basis.prod' {α : Type u_1} {β : Type u_2} {la : filter α} {lb : filter β} {ι : Type u_3} {p : ι → Prop} {sa : ι → set α} {sb : ι → set β} (hla : has_basis la p sa) (hlb : has_basis lb p sb) (h_dir : ∀ {i j : ι}, p i → p j → ∃ (k : ι), p k ∧ sa k ⊆ sa i ∧ sb k ⊆ sb j) : has_basis (filter.prod la lb) p fun (i : ι) => set.prod (sa i) (sb i) := sorry
/-- `is_countably_generated f` means `f = generate s` for some countable `s`. -/
def is_countably_generated {α : Type u_1} (f : filter α) :=
∃ (s : set (set α)), set.countable s ∧ f = generate s
/-- `is_countable_basis p s` means the image of `s` bounded by `p` is a countable filter basis. -/
structure is_countable_basis {α : Type u_1} {ι : Type u_4} (p : ι → Prop) (s : ι → set α)
extends is_basis p s
where
countable : set.countable (set_of p)
/-- We say that a filter `l` has a countable basis `s : ι → set α` bounded by `p : ι → Prop`,
if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`, and the set
defined by `p` is countable. -/
structure has_countable_basis {α : Type u_1} {ι : Type u_4} (l : filter α) (p : ι → Prop) (s : ι → set α)
extends has_basis l p s
where
countable : set.countable (set_of p)
/-- A countable filter basis `B` on a type `α` is a nonempty countable collection of sets of `α`
such that the intersection of two elements of this collection contains some element
of the collection. -/
structure countable_filter_basis (α : Type u_6)
extends filter_basis α
where
countable : set.countable (filter_basis.sets _to_filter_basis)
-- For illustration purposes, the countable filter basis defining (at_top : filter ℕ)
protected instance nat.inhabited_countable_filter_basis : Inhabited (countable_filter_basis ℕ) :=
{ default := countable_filter_basis.mk (filter_basis.mk (filter_basis.sets Inhabited.default) sorry sorry) sorry }
theorem antimono_seq_of_seq {α : Type u_1} (s : ℕ → set α) : ∃ (t : ℕ → set α),
(∀ (i j : ℕ), i ≤ j → t j ⊆ t i) ∧ (infi fun (i : ℕ) => principal (s i)) = infi fun (i : ℕ) => principal (t i) := sorry
theorem countable_binfi_eq_infi_seq {α : Type u_1} {ι : Type u_4} [complete_lattice α] {B : set ι} (Bcbl : set.countable B) (Bne : set.nonempty B) (f : ι → α) : ∃ (x : ℕ → ι), (infi fun (t : ι) => infi fun (H : t ∈ B) => f t) = infi fun (i : ℕ) => f (x i) := sorry
theorem countable_binfi_eq_infi_seq' {α : Type u_1} {ι : Type u_4} [complete_lattice α] {B : set ι} (Bcbl : set.countable B) (f : ι → α) {i₀ : ι} (h : f i₀ = ⊤) : ∃ (x : ℕ → ι), (infi fun (t : ι) => infi fun (H : t ∈ B) => f t) = infi fun (i : ℕ) => f (x i) := sorry
theorem countable_binfi_principal_eq_seq_infi {α : Type u_1} {B : set (set α)} (Bcbl : set.countable B) : ∃ (x : ℕ → set α), (infi fun (t : set α) => infi fun (H : t ∈ B) => principal t) = infi fun (i : ℕ) => principal (x i) :=
countable_binfi_eq_infi_seq' Bcbl principal principal_univ
namespace is_countably_generated
/-- A set generating a countably generated filter. -/
def generating_set {α : Type u_1} {f : filter α} (h : is_countably_generated f) : set (set α) :=
classical.some h
theorem countable_generating_set {α : Type u_1} {f : filter α} (h : is_countably_generated f) : set.countable (generating_set h) :=
and.left (classical.some_spec h)
theorem eq_generate {α : Type u_1} {f : filter α} (h : is_countably_generated f) : f = generate (generating_set h) :=
and.right (classical.some_spec h)
/-- A countable filter basis for a countably generated filter. -/
def countable_filter_basis {α : Type u_1} {l : filter α} (h : is_countably_generated l) : countable_filter_basis α :=
countable_filter_basis.mk (filter_basis.mk (filter_basis.sets (filter_basis.of_sets (generating_set h))) sorry sorry)
sorry
theorem filter_basis_filter {α : Type u_1} {l : filter α} (h : is_countably_generated l) : filter_basis.filter (countable_filter_basis.to_filter_basis (countable_filter_basis h)) = l := sorry
theorem has_countable_basis {α : Type u_1} {l : filter α} (h : is_countably_generated l) : has_countable_basis l (fun (t : set (set α)) => set.finite t ∧ t ⊆ generating_set h) fun (t : set (set α)) => ⋂₀t := sorry
theorem exists_countable_infi_principal {α : Type u_1} {f : filter α} (h : is_countably_generated f) : ∃ (s : set (set α)), set.countable s ∧ f = infi fun (t : set α) => infi fun (H : t ∈ s) => principal t := sorry
theorem exists_seq {α : Type u_1} {f : filter α} (cblb : is_countably_generated f) : ∃ (x : ℕ → set α), f = infi fun (i : ℕ) => principal (x i) := sorry
/-- If `f` is countably generated and `f.has_basis p s`, then `f` admits a decreasing basis
enumerated by natural numbers such that all sets have the form `s i`. More precisely, there is a
sequence `i n` such that `p (i n)` for all `n` and `s (i n)` is a decreasing sequence of sets which
forms a basis of `f`-/
theorem exists_antimono_subbasis {α : Type u_1} {ι : Type u_4} {f : filter α} (cblb : is_countably_generated f) {p : ι → Prop} {s : ι → set α} (hs : has_basis f p s) : ∃ (x : ℕ → ι), (∀ (i : ℕ), p (x i)) ∧ has_antimono_basis f (fun (_x : ℕ) => True) fun (i : ℕ) => s (x i) := sorry
/-- A countably generated filter admits a basis formed by a monotonically decreasing sequence of
sets. -/
theorem exists_antimono_basis {α : Type u_1} {f : filter α} (cblb : is_countably_generated f) : ∃ (x : ℕ → set α), has_antimono_basis f (fun (_x : ℕ) => True) x := sorry
end is_countably_generated
theorem has_countable_basis.is_countably_generated {α : Type u_1} {ι : Type u_4} {f : filter α} {p : ι → Prop} {s : ι → set α} (h : has_countable_basis f p s) : is_countably_generated f :=
Exists.intro (set_of fun (t : set α) => ∃ (i : ι), p i ∧ s i = t)
{ left := set.countable.image (has_countable_basis.countable h) s,
right := has_basis.eq_generate (has_countable_basis.to_has_basis h) }
theorem is_countably_generated_seq {α : Type u_1} (x : ℕ → set α) : is_countably_generated (infi fun (i : ℕ) => principal (x i)) := sorry
theorem is_countably_generated_of_seq {α : Type u_1} {f : filter α} (h : ∃ (x : ℕ → set α), f = infi fun (i : ℕ) => principal (x i)) : is_countably_generated f := sorry
theorem is_countably_generated_binfi_principal {α : Type u_1} {B : set (set α)} (h : set.countable B) : is_countably_generated (infi fun (s : set α) => infi fun (H : s ∈ B) => principal s) :=
is_countably_generated_of_seq (countable_binfi_principal_eq_seq_infi h)
theorem is_countably_generated_iff_exists_antimono_basis {α : Type u_1} {f : filter α} : is_countably_generated f ↔ ∃ (x : ℕ → set α), has_antimono_basis f (fun (_x : ℕ) => True) x := sorry
theorem is_countably_generated_principal {α : Type u_1} (s : set α) : is_countably_generated (principal s) := sorry
namespace is_countably_generated
theorem inf {α : Type u_1} {f : filter α} {g : filter α} (hf : is_countably_generated f) (hg : is_countably_generated g) : is_countably_generated (f ⊓ g) := sorry
theorem inf_principal {α : Type u_1} {f : filter α} (h : is_countably_generated f) (s : set α) : is_countably_generated (f ⊓ principal s) :=
inf h (is_countably_generated_principal s)
theorem exists_antimono_seq' {α : Type u_1} {f : filter α} (cblb : is_countably_generated f) : ∃ (x : ℕ → set α), (∀ (i j : ℕ), i ≤ j → x j ⊆ x i) ∧ ∀ {s : set α}, s ∈ f ↔ ∃ (i : ℕ), x i ⊆ s := sorry
protected theorem comap {α : Type u_1} {β : Type u_2} {l : filter β} (h : is_countably_generated l) (f : α → β) : is_countably_generated (comap f l) := sorry
|
b1690bccc46bd39a500d2eb3f301cde5e7bc34cc | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/category_theory/preadditive/opposite.lean | fec4539a5f879b6378bcc2dd76d34b92c3ed71f8 | [
"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 | 1,539 | lean | /-
Copyright (c) 2021 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Adam Topaz
-/
import category_theory.preadditive
import category_theory.preadditive.additive_functor
import data.equiv.transfer_instance
/-!
# If `C` is preadditive, `Cᵒᵖ` has a natural preadditive structure.
-/
open opposite
namespace category_theory
variables (C : Type*) [category C] [preadditive C]
instance : preadditive Cᵒᵖ :=
{ hom_group := λ X Y, equiv.add_comm_group (op_equiv X Y),
add_comp' := λ X Y Z f f' g,
congr_arg quiver.hom.op (preadditive.comp_add _ _ _ g.unop f.unop f'.unop),
comp_add' := λ X Y Z f g g',
congr_arg quiver.hom.op (preadditive.add_comp _ _ _ g.unop g'.unop f.unop), }
@[simp] lemma unop_zero (X Y : Cᵒᵖ) : (0 : X ⟶ Y).unop = 0 := rfl
@[simp] lemma unop_add {X Y : Cᵒᵖ} (f g : X ⟶ Y) : (f + g).unop = f.unop + g.unop := rfl
@[simp] lemma op_zero (X Y : C) : (0 : X ⟶ Y).op = 0 := rfl
@[simp] lemma op_add {X Y : C} (f g : X ⟶ Y) : (f + g).op = f.op + g.op := rfl
variables {C} {D : Type*} [category D] [preadditive D]
instance functor.op_additive (F : C ⥤ D) [F.additive] : F.op.additive := {}
instance functor.right_op_additive (F : Cᵒᵖ ⥤ D) [F.additive] : F.right_op.additive := {}
instance functor.left_op_additive (F : C ⥤ Dᵒᵖ) [F.additive] : F.left_op.additive := {}
instance functor.unop_additive (F : Cᵒᵖ ⥤ Dᵒᵖ) [F.additive] : F.unop.additive := {}
end category_theory
|
e0a54c10846809ea3fab8c45123f0ca2922d3788 | 4727251e0cd73359b15b664c3170e5d754078599 | /archive/miu_language/decision_suf.lean | 6ead3de8bc3ff838ffd16e49f6bafbf6c423b1f1 | [
"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 | 14,344 | lean | /-
Copyright (c) 2020 Gihan Marasingha. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gihan Marasingha
-/
import .decision_nec
import tactic.linarith
/-!
# Decision procedure - sufficient condition and decidability
We give a sufficient condition for a string to be derivable in the MIU language. Together with the
necessary condition, we use this to prove that `derivable` is an instance of `decidable_pred`.
Let `count I st` and `count U st` denote the number of `I`s (respectively `U`s) in `st : miustr`.
We'll show that `st` is derivable if it has the form `M::x` where `x` is a string of `I`s and `U`s
for which `count I x` is congruent to 1 or 2 modulo 3.
To prove this, it suffices to show `derivable M::y` where `y` is any `miustr` consisting only of
`I`s such that the number of `I`s in `y` is `a+3b`, where `a = count I x` and `b = count U x`.
This suffices because Rule 3 permits us to change any string of three consecutive `I`s into a `U`.
As `count I y = (count I x) + 3*(count U x) ≡ (count I x) [MOD 3]`, it suffices to show
`derivable M::z` where `z` is an `miustr` of `I`s such that `count I z` is congruent to
1 or 2 modulo 3.
Let `z` be such an `miustr` and let `c` denote `count I z`, so `c ≡ 1 or 2 [MOD 3]`.
To derive such an `miustr`, it suffices to derive an `miustr` `M::w`, where again w is an
`miustr` of only `I`s with the additional conditions that `count I w` is a power of 2, that
`count I w ≥ c` and that `count I w ≡ c [MOD 3]`.
To see that this suffices, note that we can remove triples of `I`s from the end of `M::w`,
creating `U`s as we go along. Once the number of `I`s equals `m`, we remove `U`s two at a time
until we have no `U`s. The only issue is that we may begin the removal process with an odd number
of `U`s.
Writing `d = count I w`, we see that this happens if and only if `(d-c)/3` is odd.
In this case, we must apply Rule 1 to `z`, prior to removing triples of `I`s. We thereby
introduce an additional `U` and ensure that the final number of `U`s will be even.
## Tags
miu, decision procedure, decidability, decidable_pred, decidable
-/
namespace miu
open miu_atom list nat
/--
We start by showing that an `miustr` `M::w` can be derived, where `w` consists only of `I`s and
where `count I w` is a power of 2.
-/
private lemma der_cons_repeat (n : ℕ) : derivable (M::(repeat I (2^n))) :=
begin
induction n with k hk,
{ constructor, }, -- base case
{ rw [succ_eq_add_one, pow_add, pow_one 2, mul_two,repeat_add], -- inductive step
exact derivable.r2 hk, },
end
/-!
## Converting `I`s to `U`s
For any given natural number `c ≡ 1 or 2 [MOD 3]`, we need to show that can derive an `miustr`
`M::w` where `w` consists only of `I`s, where `d = count I w` is a power of 2, where `d ≥ c` and
where `d ≡ c [MOD 3]`.
Given the above lemmas, the desired result reduces to an arithmetic result, given in the file
`arithmetic.lean`.
We'll use this result to show we can derive an `miustr` of the form `M::z` where `z` is an string
consisting only of `I`s such that `count I z ≡ 1 or 2 [MOD 3]`.
As an intermediate step, we show that derive `z` from `zt`, where `t` is aN `miustr` consisting of
an even number of `U`s and `z` is any `miustr`.
-/
/--
Any number of successive occurrences of `"UU"` can be removed from the end of a `derivable` `miustr`
to produce another `derivable` `miustr`.
-/
lemma der_of_der_append_repeat_U_even {z : miustr} {m : ℕ} (h : derivable (z ++ repeat U (m*2)))
: derivable z :=
begin
induction m with k hk,
{ revert h,
simp only [list.repeat, zero_mul, append_nil, imp_self], },
{ apply hk,
simp only [succ_mul, repeat_add] at h,
change repeat U 2 with [U,U] at h,
rw ←(append_nil (z ++ repeat U (k*2) )),
apply derivable.r4,
simp only [append_nil, append_assoc,h], },
end
/-!
In fine-tuning my application of `simp`, I issued the following commend to determine which lemmas
`simp` uses.
`set_option trace.simplify.rewrite true`
-/
/--
We may replace several consecutive occurrences of `"III"` with the same number of `"U"`s.
In application of the following lemma, `xs` will either be `[]` or `[U]`.
-/
lemma der_cons_repeat_I_repeat_U_append_of_der_cons_repeat_I_append (c k : ℕ)
(hc : c % 3 = 1 ∨ c % 3 = 2) (xs : miustr) (hder : derivable (M ::(repeat I (c+3*k)) ++ xs)) :
derivable (M::(repeat I c ++ repeat U k) ++ xs) :=
begin
revert xs,
induction k with a ha,
{ simp only [list.repeat, mul_zero, add_zero, append_nil, forall_true_iff, imp_self],},
{ intro xs,
specialize ha (U::xs),
intro h₂,
simp only [succ_eq_add_one, repeat_add], -- We massage the goal
rw [←append_assoc, ←cons_append], -- into a form amenable
change repeat U 1 with [U], -- to the application of
rw [append_assoc, singleton_append], -- ha.
apply ha,
apply derivable.r3,
change [I,I,I] with repeat I 3,
simp only [cons_append, ←repeat_add],
convert h₂, },
end
/-!
### Arithmetic
We collect purely arithmetic lemmas: `add_mod2` is used to ensure we have an even number of `U`s
while `le_pow2_and_pow2_eq_mod3` treats the congruence condition modulo 3.
-/
section arithmetic
/--
For every `a`, the number `a + a % 2` is even.
-/
lemma add_mod2 (a : ℕ) : ∃ t, a + a % 2 = t*2 :=
begin
simp only [mul_comm _ 2], -- write `t*2` as `2*t`
apply dvd_of_mod_eq_zero, -- it suffices to prove `(a + a % 2) % 2 = 0`
rw [add_mod, mod_mod, ←two_mul, mul_mod_right],
end
private lemma le_pow2_and_pow2_eq_mod3' (c : ℕ) (x : ℕ) (h : c = 1 ∨ c = 2) :
∃ m : ℕ, c + 3*x ≤ 2^m ∧ 2^m % 3 = c % 3 :=
begin
induction x with k hk,
{ use (c+1),
cases h with hc hc;
{ rw hc, norm_num }, },
rcases hk with ⟨g, hkg, hgmod⟩,
by_cases hp : (c + 3*(k+1) ≤ 2 ^g),
{ use g, exact ⟨hp, hgmod⟩ },
refine ⟨g + 2, _, _⟩,
{ rw [mul_succ, ←add_assoc, pow_add],
change 2^2 with (1+3), rw [mul_add (2^g) 1 3, mul_one],
linarith [hkg, one_le_two_pow g], },
{ rw [pow_add, ←mul_one c],
exact modeq.mul hgmod rfl }
end
/--
If `a` is 1 or 2 modulo 3, then exists `k` a power of 2 for which `a ≤ k` and `a ≡ k [MOD 3]`.
-/
lemma le_pow2_and_pow2_eq_mod3 (a : ℕ) (h : a % 3 = 1 ∨ a % 3 = 2) :
∃ m : ℕ, a ≤ 2^m ∧ 2^m % 3 = a % 3:=
begin
cases le_pow2_and_pow2_eq_mod3' (a%3) (a/3) h with m hm,
use m,
split,
{ convert hm.1, exact (mod_add_div a 3).symm, },
{ rw [hm.2, mod_mod _ 3], },
end
end arithmetic
lemma repeat_pow_minus_append {m : ℕ} : M :: repeat I (2^m - 1) ++ [I] = M::(repeat I (2^m)) :=
begin
change [I] with repeat I 1,
rw [cons_append, ←repeat_add, tsub_add_cancel_of_le (one_le_pow' m 1)],
end
/--
`der_repeat_I_of_mod3` states that `M::y` is `derivable` if `y` is any `miustr` consisiting just of
`I`s, where `count I y` is 1 or 2 modulo 3.
-/
lemma der_repeat_I_of_mod3 (c : ℕ) (h : c % 3 = 1 ∨ c % 3 = 2):
derivable (M::(repeat I c)) :=
begin
-- From `der_cons_repeat`, we can derive the `miustr` `M::w` described in the introduction.
cases (le_pow2_and_pow2_eq_mod3 c h) with m hm, -- `2^m` will be the number of `I`s in `M::w`
have hw₂ : derivable (M::(repeat I (2^m)) ++ repeat U ((2^m -c)/3 % 2)),
{ cases mod_two_eq_zero_or_one ((2^m -c)/3) with h_zero h_one,
{ simp only [der_cons_repeat m, append_nil,list.repeat, h_zero], }, -- `(2^m - c)/3 ≡ 0 [MOD 2]`
{ rw [h_one, ←repeat_pow_minus_append, append_assoc], -- case `(2^m - c)/3 ≡ 1 [MOD 2]`
apply derivable.r1,
rw repeat_pow_minus_append,
exact (der_cons_repeat m), }, },
have hw₃ : derivable (M::(repeat I c) ++ repeat U ((2^m-c)/3) ++ repeat U ((2^m-c)/3 % 2)),
{ apply der_cons_repeat_I_repeat_U_append_of_der_cons_repeat_I_append c ((2^m-c)/3) h,
convert hw₂, -- now we must show `c + 3 * ((2 ^ m - c) / 3) = 2 ^ m`
rw nat.mul_div_cancel',
{ exact add_tsub_cancel_of_le hm.1 },
{ exact (modeq_iff_dvd' hm.1).mp hm.2.symm } },
rw [append_assoc, ←repeat_add _ _] at hw₃,
cases add_mod2 ((2^m-c)/3) with t ht,
rw ht at hw₃,
exact der_of_der_append_repeat_U_even hw₃,
end
example (c : ℕ) (h : c % 3 = 1 ∨ c % 3 = 2):
derivable (M::(repeat I c)) :=
begin
-- From `der_cons_repeat`, we can derive the `miustr` `M::w` described in the introduction.
cases (le_pow2_and_pow2_eq_mod3 c h) with m hm, -- `2^m` will be the number of `I`s in `M::w`
have hw₂ : derivable (M::(repeat I (2^m)) ++ repeat U ((2^m -c)/3 % 2)),
{ cases mod_two_eq_zero_or_one ((2^m -c)/3) with h_zero h_one,
{ simp only [der_cons_repeat m, append_nil, list.repeat,h_zero], }, -- `(2^m - c)/3 ≡ 0 [MOD 2]`
{ rw [h_one, ←repeat_pow_minus_append, append_assoc], -- case `(2^m - c)/3 ≡ 1 [MOD 2]`
apply derivable.r1,
rw repeat_pow_minus_append,
exact (der_cons_repeat m), }, },
have hw₃ : derivable (M::(repeat I c) ++ repeat U ((2^m-c)/3) ++ repeat U ((2^m-c)/3 % 2)),
{ apply der_cons_repeat_I_repeat_U_append_of_der_cons_repeat_I_append c ((2^m-c)/3) h,
convert hw₂, -- now we must show `c + 3 * ((2 ^ m - c) / 3) = 2 ^ m`
rw nat.mul_div_cancel',
{ exact add_tsub_cancel_of_le hm.1 },
{ exact (modeq_iff_dvd' hm.1).mp hm.2.symm } },
rw [append_assoc, ←repeat_add _ _] at hw₃,
cases add_mod2 ((2^m-c)/3) with t ht,
rw ht at hw₃,
exact der_of_der_append_repeat_U_even hw₃,
end
/-!
### `decstr` is a sufficient condition
The remainder of this file sets up the proof that `dectstr en` is sufficent to ensure
`derivable en`. Decidability of `derivable en` is an easy consequence.
The proof proceeds by induction on the `count U` of `en`.
We tackle first the base case of the induction. This requires auxiliary results giving
conditions under which `count I ys = length ys`.
-/
/--
If an `miustr` has a zero `count U` and contains no `M`, then its `count I` is its length.
-/
lemma count_I_eq_length_of_count_U_zero_and_neg_mem {ys : miustr} (hu : count U ys = 0)
(hm : M ∉ ys) : count I ys = length ys :=
begin
induction ys with x xs hxs,
{ refl, },
{ cases x,
{ exfalso, exact hm (mem_cons_self M xs), }, -- case `x = M` gives a contradiction.
{ rw [count_cons, if_pos (rfl), length, succ_eq_add_one, succ_inj'], -- case `x = I`
apply hxs,
{ simpa only [count], },
{ simp only [mem_cons_iff,false_or] at hm, exact hm, }, },
{ exfalso, simp only [count, countp_cons_of_pos] at hu, -- case `x = U` gives a contradiction.
exact succ_ne_zero _ hu, }, },
end
/--
`base_case_suf` is the base case of the sufficiency result.
-/
lemma base_case_suf (en : miustr) (h : decstr en) (hu : count U en = 0) : derivable en :=
begin
rcases h with ⟨⟨mhead, nmtail⟩, hi ⟩,
have : en ≠ nil,
{ intro k, simp only [k, count, countp, if_false, zero_mod, zero_ne_one, false_or] at hi,
contradiction, },
rcases (exists_cons_of_ne_nil this) with ⟨y,ys,rfl⟩,
rw head at mhead,
rw mhead at *,
suffices : ∃ c, repeat I c = ys ∧ (c % 3 = 1 ∨ c % 3 = 2),
{ rcases this with ⟨c, hysr, hc⟩,
rw ←hysr,
exact der_repeat_I_of_mod3 c hc, },
{ simp only [count] at *,
use (count I ys),
refine and.intro _ hi,
apply repeat_count_eq_of_count_eq_length,
exact count_I_eq_length_of_count_U_zero_and_neg_mem hu nmtail, },
end
/-!
Before continuing to the proof of the induction step, we need other auxiliary results that
relate to `count U`.
-/
lemma mem_of_count_U_eq_succ {xs : miustr} {k : ℕ} (h : count U xs = succ k) : U ∈ xs :=
begin
induction xs with z zs hzs,
{ exfalso, rw count at h, contradiction, },
{ simp only [mem_cons_iff],
cases z,
repeat -- cases `z = M` and `z=I`
{ right, apply hzs, simp only [count, countp, if_false] at h, rw ←h, refl, },
{ left, refl, }, }, -- case `z = U`
end
lemma eq_append_cons_U_of_count_U_pos {k : ℕ} {zs : miustr} (h : count U zs = succ k) :
∃ (as bs : miustr), (zs = as ++ U :: bs) :=
mem_split (mem_of_count_U_eq_succ h)
/--
`ind_hyp_suf` is the inductive step of the sufficiency result.
-/
lemma ind_hyp_suf (k : ℕ) (ys : miustr) (hu : count U ys = succ k) (hdec : decstr ys) :
∃ (as bs : miustr), (ys = M::as ++ U:: bs) ∧ (count U (M::as ++ [I,I,I] ++ bs) = k) ∧
decstr (M::as ++ [I,I,I] ++ bs) :=
begin
rcases hdec with ⟨⟨mhead,nmtail⟩, hic⟩,
have : ys ≠ nil,
{ intro k, simp only [k ,count, countp, zero_mod, false_or, zero_ne_one] at hic, contradiction, },
rcases (exists_cons_of_ne_nil this) with ⟨z,zs,rfl⟩,
rw head at mhead,
rw mhead at *,
simp only [count, countp, cons_append, if_false, countp_append] at *,
rcases (eq_append_cons_U_of_count_U_pos hu) with ⟨as,bs,hab⟩,
rw hab at *,
simp only [countp, cons_append, if_pos, if_false, countp_append] at *,
use [as,bs],
apply and.intro rfl (and.intro (succ.inj hu) _),
split,
{ apply and.intro rfl,
simp only [tail, mem_append, mem_cons_iff, false_or, not_mem_nil, or_false] at *,
exact nmtail, },
{ simp only [count, countp, cons_append, if_false, countp_append, if_pos],
rw [add_right_comm, add_mod_right], exact hic, },
end
/--
`der_of_decstr` states that `derivable en` follows from `decstr en`.
-/
theorem der_of_decstr {en : miustr} (h : decstr en) : derivable en :=
begin
/- The next three lines have the effect of introducing `count U en` as a variable that can be used
for induction -/
have hu : ∃ n, count U en = n := exists_eq',
cases hu with n hu,
revert en, /- Crucially, we need the induction hypothesis to quantify over `en` -/
induction n with k hk,
{ exact base_case_suf, },
{ intros ys hdec hus,
rcases ind_hyp_suf k ys hus hdec with ⟨as, bs, hyab, habuc, hdecab⟩,
have h₂ : derivable (M::as ++ [I,I,I] ++ bs) := hk hdecab habuc,
rw hyab,
exact derivable.r3 h₂, },
end
/-!
### Decidability of `derivable`
-/
/--
Finally, we have the main result, namely that `derivable` is a decidable predicate.
-/
instance : decidable_pred derivable :=
λ en, decidable_of_iff _ ⟨der_of_decstr, decstr_of_der⟩
/-!
By decidability, we can automatically determine whether any given `miustr` is `derivable`.
-/
example : ¬(derivable "MU") :=
dec_trivial
example : derivable "MUIUIUIIIIIUUUIUII" :=
dec_trivial
end miu
|
349fd37b442da107f122950336a0ddc0f8c80c92 | 82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7 | /tests/compiler/array_test.lean | 1eaa97b82b9df884b7a18505de6dfd513fc5cd60 | [
"Apache-2.0"
] | permissive | banksonian/lean4 | 3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc | 78da6b3aa2840693eea354a41e89fc5b212a5011 | refs/heads/master | 1,673,703,624,165 | 1,605,123,551,000 | 1,605,123,551,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,235 | lean |
def foo (a : Array Nat) : Array Nat :=
let a := a.push 0
let a := a.push 1
let a := a.push 2
let a := a.push 3
a
def main : IO UInt32 := do
let a : Array Nat := Array.empty
IO.println (toString a)
IO.println (toString a.sz)
let a := foo a
IO.println (toString a)
let a := a.map (fun a => a + 10)
IO.println (toString a)
IO.println (toString a.sz)
let a1 := a.pop
let a2 := a.push 100
IO.println (toString a1)
IO.println (toString a2)
let a2 := a.pop
IO.println a2
IO.println $ (([1, 2, 3, 4].toArray).map (fun a => a + 2)).map toString
IO.println $ ([1, 2, 3, 4].toArray.extract 1 3)
IO.println $ ([1, 2, 3, 4].toArray.extract 0 100)
IO.println $ ([1, 2, 3, 4].toArray.extract 1 1)
IO.println $ ([1, 2, 3, 4].toArray.extract 2 4)
IO.println [1,2,3,4].toArray.reverse
IO.println ([] : List Nat).toArray.reverse
IO.println [1,2,3].toArray.reverse
IO.println $ [1,2,3,4].toArray.filter (fun a => a % 2 == 0)
IO.println $ [1,2,3,4,5].toArray.filter (fun a => a % 2 == 0)
IO.println $ [1,2,3,4,5].toArray.filter (fun a => a % 2 == 1)
IO.println $ [1,2,3,4].toArray.filter (fun a => a > 2)
IO.println $ [1,2,3,4].toArray.filter (fun a => a > 10)
IO.println $ [1,2,3,4].toArray.filter (fun a => a > 0)
pure 0
|
286830c7753638f4dc884c5ef6f028712a6dcfa7 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/ring_theory/local_properties.lean | 70f52e77a63c566c580f589c4e31dfc3cdf8e031 | [
"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 | 29,175 | lean | /-
Copyright (c) 2021 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import group_theory.submonoid.pointwise
import logic.equiv.transfer_instance
import ring_theory.finiteness
import ring_theory.localization.at_prime
import ring_theory.localization.away
import ring_theory.localization.integer
import ring_theory.localization.submodule
import ring_theory.nilpotent
import ring_theory.ring_hom_properties
/-!
# Local properties of commutative rings
In this file, we provide the proofs of various local properties.
## Naming Conventions
* `localization_P` : `P` holds for `S⁻¹R` if `P` holds for `R`.
* `P_of_localization_maximal` : `P` holds for `R` if `P` holds for `Rₘ` for all maximal `m`.
* `P_of_localization_prime` : `P` holds for `R` if `P` holds for `Rₘ` for all prime `m`.
* `P_of_localization_span` : `P` holds for `R` if given a spanning set `{fᵢ}`, `P` holds for all
`R_{fᵢ}`.
## Main results
The following properties are covered:
* The triviality of an ideal or an element:
`ideal_eq_zero_of_localization`, `eq_zero_of_localization`
* `is_reduced` : `localization_is_reduced`, `is_reduced_of_localization_maximal`.
* `finite`: `localization_finite`, `finite_of_localization_span`
* `finite_type`: `localization_finite_type`, `finite_type_of_localization_span`
-/
open_locale pointwise classical big_operators
universe u
variables {R S : Type u} [comm_ring R] [comm_ring S] (M : submonoid R)
variables (N : submonoid S) (R' S' : Type u) [comm_ring R'] [comm_ring S'] (f : R →+* S)
variables [algebra R R'] [algebra S S']
section properties
section comm_ring
variable (P : ∀ (R : Type u) [comm_ring R], Prop)
include P
/-- A property `P` of comm rings is said to be preserved by localization
if `P` holds for `M⁻¹R` whenever `P` holds for `R`. -/
def localization_preserves : Prop :=
∀ {R : Type u} [hR : comm_ring R] (M : by exactI submonoid R) (S : Type u) [hS : comm_ring S]
[by exactI algebra R S] [by exactI is_localization M S], @P R hR → @P S hS
/-- A property `P` of comm rings satisfies `of_localization_maximal` if
if `P` holds for `R` whenever `P` holds for `Rₘ` for all maximal ideal `m`. -/
def of_localization_maximal : Prop :=
∀ (R : Type u) [comm_ring R],
by exactI (∀ (J : ideal R) (hJ : J.is_maximal), by exactI P (localization.at_prime J)) → P R
end comm_ring
section ring_hom
variable (P : ∀ {R S : Type u} [comm_ring R] [comm_ring S] (f : by exactI R →+* S), Prop)
include P
/-- A property `P` of ring homs is said to be preserved by localization
if `P` holds for `M⁻¹R →+* M⁻¹S` whenever `P` holds for `R →+* S`. -/
def ring_hom.localization_preserves :=
∀ ⦃R S : Type u⦄ [comm_ring R] [comm_ring S] (f : by exactI R →+* S) (M : by exactI submonoid R)
(R' S' : Type u) [comm_ring R'] [comm_ring S'] [by exactI algebra R R']
[by exactI algebra S S'] [by exactI is_localization M R']
[by exactI is_localization (M.map f) S'],
by exactI (P f → P (is_localization.map S' f (submonoid.le_comap_map M) : R' →+* S'))
/-- A property `P` of ring homs satisfies `ring_hom.of_localization_finite_span`
if `P` holds for `R →+* S` whenever there exists a finite set `{ r }` that spans `R` such that
`P` holds for `Rᵣ →+* Sᵣ`.
Note that this is equivalent to `ring_hom.of_localization_span` via
`ring_hom.of_localization_span_iff_finite`, but this is easier to prove. -/
def ring_hom.of_localization_finite_span :=
∀ ⦃R S : Type u⦄ [comm_ring R] [comm_ring S] (f : by exactI R →+* S)
(s : finset R) (hs : by exactI ideal.span (s : set R) = ⊤)
(H : by exactI (∀ (r : s), P (localization.away_map f r))), by exactI P f
/-- A property `P` of ring homs satisfies `ring_hom.of_localization_finite_span`
if `P` holds for `R →+* S` whenever there exists a set `{ r }` that spans `R` such that
`P` holds for `Rᵣ →+* Sᵣ`.
Note that this is equivalent to `ring_hom.of_localization_finite_span` via
`ring_hom.of_localization_span_iff_finite`, but this has less restrictions when applying. -/
def ring_hom.of_localization_span :=
∀ ⦃R S : Type u⦄ [comm_ring R] [comm_ring S] (f : by exactI R →+* S)
(s : set R) (hs : by exactI ideal.span s = ⊤)
(H : by exactI (∀ (r : s), P (localization.away_map f r))), by exactI P f
/-- A property `P` of ring homs satisfies `ring_hom.holds_for_localization_away`
if `P` holds for each localization map `R →+* Rᵣ`. -/
def ring_hom.holds_for_localization_away : Prop :=
∀ ⦃R : Type u⦄ (S : Type u) [comm_ring R] [comm_ring S] [by exactI algebra R S] (r : R)
[by exactI is_localization.away r S], by exactI P (algebra_map R S)
/-- A property `P` of ring homs satisfies `ring_hom.of_localization_finite_span_target`
if `P` holds for `R →+* S` whenever there exists a finite set `{ r }` that spans `S` such that
`P` holds for `R →+* Sᵣ`.
Note that this is equivalent to `ring_hom.of_localization_span_target` via
`ring_hom.of_localization_span_target_iff_finite`, but this is easier to prove. -/
def ring_hom.of_localization_finite_span_target : Prop :=
∀ ⦃R S : Type u⦄ [comm_ring R] [comm_ring S] (f : by exactI R →+* S)
(s : finset S) (hs : by exactI ideal.span (s : set S) = ⊤)
(H : by exactI (∀ (r : s), P ((algebra_map S (localization.away (r : S))).comp f))),
by exactI P f
/-- A property `P` of ring homs satisfies `ring_hom.of_localization_span_target`
if `P` holds for `R →+* S` whenever there exists a set `{ r }` that spans `S` such that
`P` holds for `R →+* Sᵣ`.
Note that this is equivalent to `ring_hom.of_localization_finite_span_target` via
`ring_hom.of_localization_span_target_iff_finite`, but this has less restrictions when applying. -/
def ring_hom.of_localization_span_target : Prop :=
∀ ⦃R S : Type u⦄ [comm_ring R] [comm_ring S] (f : by exactI R →+* S)
(s : set S) (hs : by exactI ideal.span s = ⊤)
(H : by exactI (∀ (r : s), P ((algebra_map S (localization.away (r : S))).comp f))),
by exactI P f
/-- A property `P` of ring homs satisfies `of_localization_prime` if
if `P` holds for `R` whenever `P` holds for `Rₘ` for all prime ideals `p`. -/
def ring_hom.of_localization_prime : Prop :=
∀ ⦃R S : Type u⦄ [comm_ring R] [comm_ring S] (f : by exactI R →+* S),
by exactI (∀ (J : ideal S) (hJ : J.is_prime),
by exactI P (localization.local_ring_hom _ J f rfl)) → P f
/-- A property of ring homs is local if it is preserved by localizations and compositions, and for
each `{ r }` that spans `S`, we have `P (R →+* S) ↔ ∀ r, P (R →+* Sᵣ)`. -/
structure ring_hom.property_is_local : Prop :=
(localization_preserves : ring_hom.localization_preserves @P)
(of_localization_span_target : ring_hom.of_localization_span_target @P)
(stable_under_composition : ring_hom.stable_under_composition @P)
(holds_for_localization_away : ring_hom.holds_for_localization_away @P)
lemma ring_hom.of_localization_span_iff_finite :
ring_hom.of_localization_span @P ↔ ring_hom.of_localization_finite_span @P :=
begin
delta ring_hom.of_localization_span ring_hom.of_localization_finite_span,
apply forall₅_congr, -- TODO: Using `refine` here breaks `resetI`.
introsI,
split,
{ intros h s, exact h s },
{ intros h s hs hs',
obtain ⟨s', h₁, h₂⟩ := (ideal.span_eq_top_iff_finite s).mp hs,
exact h s' h₂ (λ x, hs' ⟨_, h₁ x.prop⟩) }
end
lemma ring_hom.of_localization_span_target_iff_finite :
ring_hom.of_localization_span_target @P ↔ ring_hom.of_localization_finite_span_target @P :=
begin
delta ring_hom.of_localization_span_target ring_hom.of_localization_finite_span_target,
apply forall₅_congr, -- TODO: Using `refine` here breaks `resetI`.
introsI,
split,
{ intros h s, exact h s },
{ intros h s hs hs',
obtain ⟨s', h₁, h₂⟩ := (ideal.span_eq_top_iff_finite s).mp hs,
exact h s' h₂ (λ x, hs' ⟨_, h₁ x.prop⟩) }
end
variables {P f R' S'}
lemma _root_.ring_hom.property_is_local.respects_iso (hP : ring_hom.property_is_local @P) :
ring_hom.respects_iso @P :=
begin
apply hP.stable_under_composition.respects_iso,
introv,
resetI,
letI := e.to_ring_hom.to_algebra,
apply_with hP.holds_for_localization_away { instances := ff },
apply is_localization.away_of_is_unit_of_bijective _ is_unit_one,
exact e.bijective
end
-- Almost all arguments are implicit since this is not intended to use mid-proof.
lemma ring_hom.localization_preserves.away
(H : ring_hom.localization_preserves @P) (r : R) [is_localization.away r R']
[is_localization.away (f r) S'] (hf : P f) :
P (by exactI is_localization.away.map R' S' f r) :=
begin
resetI,
haveI : is_localization ((submonoid.powers r).map f) S',
{ rw submonoid.map_powers, assumption },
exact H f (submonoid.powers r) R' S' hf,
end
lemma ring_hom.property_is_local.of_localization_span (hP : ring_hom.property_is_local @P) :
ring_hom.of_localization_span @P :=
begin
introv R hs hs',
resetI,
apply_fun (ideal.map f) at hs,
rw [ideal.map_span, ideal.map_top] at hs,
apply hP.of_localization_span_target _ _ hs,
rintro ⟨_, r, hr, rfl⟩,
have := hs' ⟨r, hr⟩,
convert hP.stable_under_composition _ _ (hP.holds_for_localization_away (localization.away r) r)
(hs' ⟨r, hr⟩) using 1,
exact (is_localization.map_comp _).symm
end
end ring_hom
end properties
section ideal
-- This proof should work for all modules, but we do not know how to localize a module yet.
/-- An ideal is trivial if its localization at every maximal ideal is trivial. -/
lemma ideal_eq_zero_of_localization (I : ideal R)
(h : ∀ (J : ideal R) (hJ : J.is_maximal),
by exactI is_localization.coe_submodule (localization.at_prime J) I = 0) : I = 0 :=
begin
by_contradiction hI, change I ≠ ⊥ at hI,
obtain ⟨x, hx, hx'⟩ := set_like.exists_of_lt hI.bot_lt,
rw [submodule.mem_bot] at hx',
have H : (ideal.span ({x} : set R)).annihilator ≠ ⊤,
{ rw [ne.def, submodule.annihilator_eq_top_iff],
by_contra,
apply hx',
rw [← set.mem_singleton_iff, ← @submodule.bot_coe R, ← h],
exact ideal.subset_span (set.mem_singleton x) },
obtain ⟨p, hp₁, hp₂⟩ := ideal.exists_le_maximal _ H,
resetI,
specialize h p hp₁,
have : algebra_map R (localization.at_prime p) x = 0,
{ rw ← set.mem_singleton_iff,
change algebra_map R (localization.at_prime p) x ∈ (0 : submodule R (localization.at_prime p)),
rw ← h,
exact submodule.mem_map_of_mem hx },
rw is_localization.map_eq_zero_iff p.prime_compl at this,
obtain ⟨m, hm⟩ := this,
apply m.prop,
refine hp₂ _,
erw submodule.mem_annihilator_span_singleton,
rwa mul_comm at hm,
end
lemma eq_zero_of_localization (r : R)
(h : ∀ (J : ideal R) (hJ : J.is_maximal),
by exactI algebra_map R (localization.at_prime J) r = 0) : r = 0 :=
begin
rw ← ideal.span_singleton_eq_bot,
apply ideal_eq_zero_of_localization,
intros J hJ,
delta is_localization.coe_submodule,
erw [submodule.map_span, submodule.span_eq_bot],
rintro _ ⟨_, h', rfl⟩,
cases set.mem_singleton_iff.mpr h',
exact h J hJ,
end
end ideal
section reduced
lemma localization_is_reduced : localization_preserves (λ R hR, by exactI is_reduced R) :=
begin
introv R _ _,
resetI,
constructor,
rintro x ⟨(_|n), e⟩,
{ simpa using congr_arg (*x) e },
obtain ⟨⟨y, m⟩, hx⟩ := is_localization.surj M x,
dsimp only at hx,
let hx' := congr_arg (^ n.succ) hx,
simp only [mul_pow, e, zero_mul, ← ring_hom.map_pow] at hx',
rw [← (algebra_map R S).map_zero] at hx',
obtain ⟨m', hm'⟩ := (is_localization.eq_iff_exists M S).mp hx',
apply_fun (*m'^n) at hm',
simp only [mul_assoc, zero_mul] at hm',
rw [mul_comm, ← pow_succ, ← mul_pow] at hm',
replace hm' := is_nilpotent.eq_zero ⟨_, hm'.symm⟩,
rw [← (is_localization.map_units S m).mul_left_inj, hx, zero_mul,
is_localization.map_eq_zero_iff M],
exact ⟨m', by rw [← hm', mul_comm]⟩
end
instance [is_reduced R] : is_reduced (localization M) := localization_is_reduced M _ infer_instance
lemma is_reduced_of_localization_maximal :
of_localization_maximal (λ R hR, by exactI is_reduced R) :=
begin
introv R h,
constructor,
intros x hx,
apply eq_zero_of_localization,
intros J hJ,
specialize h J hJ,
resetI,
exact (hx.map $ algebra_map R $ localization.at_prime J).eq_zero,
end
end reduced
section surjective
lemma localization_preserves_surjective :
ring_hom.localization_preserves (λ R S _ _ f, function.surjective f) :=
begin
introv R H x,
resetI,
obtain ⟨x, ⟨_, s, hs, rfl⟩, rfl⟩ := is_localization.mk'_surjective (M.map f) x,
obtain ⟨y, rfl⟩ := H x,
use is_localization.mk' R' y ⟨s, hs⟩,
rw is_localization.map_mk',
refl,
end
lemma surjective_of_localization_span :
ring_hom.of_localization_span (λ R S _ _ f, function.surjective f) :=
begin
introv R e H,
rw [← set.range_iff_surjective, set.eq_univ_iff_forall],
resetI,
letI := f.to_algebra,
intro x,
apply submodule.mem_of_span_eq_top_of_smul_pow_mem (algebra.of_id R S).to_linear_map.range s e,
intro r,
obtain ⟨a, e'⟩ := H r (algebra_map _ _ x),
obtain ⟨b, ⟨_, n, rfl⟩, rfl⟩ := is_localization.mk'_surjective (submonoid.powers (r : R)) a,
erw is_localization.map_mk' at e',
rw [eq_comm, is_localization.eq_mk'_iff_mul_eq, subtype.coe_mk, subtype.coe_mk, ← map_mul] at e',
obtain ⟨⟨_, n', rfl⟩, e''⟩ := (is_localization.eq_iff_exists (submonoid.powers (f r)) _).mp e',
rw [subtype.coe_mk, mul_assoc, ← map_pow, ← map_mul, ← map_mul, ← pow_add, mul_comm] at e'',
exact ⟨n + n', _, e''.symm⟩
end
end surjective
section finite
/-- If `S` is a finite `R`-algebra, then `S' = M⁻¹S` is a finite `R' = M⁻¹R`-algebra. -/
lemma localization_finite : ring_hom.localization_preserves @ring_hom.finite :=
begin
introv R hf,
-- Setting up the `algebra` and `is_scalar_tower` instances needed
resetI,
letI := f.to_algebra,
letI := ((algebra_map S S').comp f).to_algebra,
let f' : R' →+* S' := is_localization.map S' f (submonoid.le_comap_map M),
letI := f'.to_algebra,
haveI : is_scalar_tower R R' S' :=
is_scalar_tower.of_algebra_map_eq' (is_localization.map_comp _).symm,
let fₐ : S →ₐ[R] S' := alg_hom.mk' (algebra_map S S') (λ c x, ring_hom.map_mul _ _ _),
-- We claim that if `S` is generated by `T` as an `R`-module,
-- then `S'` is generated by `T` as an `R'`-module.
unfreezingI { obtain ⟨T, hT⟩ := hf },
use T.image (algebra_map S S'),
rw eq_top_iff,
rintro x -,
-- By the hypotheses, for each `x : S'`, we have `x = y / (f r)` for some `y : S` and `r : M`.
-- Since `S` is generated by `T`, the image of `y` should fall in the span of the image of `T`.
obtain ⟨y, ⟨_, ⟨r, hr, rfl⟩⟩, rfl⟩ := is_localization.mk'_surjective (M.map f) x,
rw [is_localization.mk'_eq_mul_mk'_one, mul_comm, finset.coe_image],
have hy : y ∈ submodule.span R ↑T, by { rw hT, trivial },
replace hy : algebra_map S S' y ∈ submodule.map fₐ.to_linear_map (submodule.span R T) :=
submodule.mem_map_of_mem hy,
rw submodule.map_span fₐ.to_linear_map T at hy,
have H : submodule.span R ((algebra_map S S') '' T) ≤
(submodule.span R' ((algebra_map S S') '' T)).restrict_scalars R,
{ rw submodule.span_le, exact submodule.subset_span },
-- Now, since `y ∈ span T`, and `(f r)⁻¹ ∈ R'`, `x / (f r)` is in `span T` as well.
convert (submodule.span R' ((algebra_map S S') '' T)).smul_mem
(is_localization.mk' R' (1 : R) ⟨r, hr⟩) (H hy) using 1,
rw algebra.smul_def,
erw is_localization.map_mk',
rw map_one,
refl,
end
lemma localization_away_map_finite (r : R) [is_localization.away r R']
[is_localization.away (f r) S'] (hf : f.finite) :
(is_localization.away.map R' S' f r).finite :=
localization_finite.away r hf
/--
Let `S` be an `R`-algebra, `M` an submonoid of `R`, and `S' = M⁻¹S`.
If the image of some `x : S` falls in the span of some finite `s ⊆ S'` over `R`,
then there exists some `m : M` such that `m • x` falls in the
span of `finset_integer_multiple _ s` over `R`.
-/
lemma is_localization.smul_mem_finset_integer_multiple_span [algebra R S]
[algebra R S'] [is_scalar_tower R S S']
[is_localization (M.map (algebra_map R S : R →* S)) S'] (x : S)
(s : finset S') (hx : algebra_map S S' x ∈ submodule.span R (s : set S')) :
∃ m : M, m • x ∈ submodule.span R
(is_localization.finset_integer_multiple (M.map (algebra_map R S : R →* S)) s : set S) :=
begin
let g : S →ₐ[R] S' := alg_hom.mk' (algebra_map S S')
(λ c x, by simp [algebra.algebra_map_eq_smul_one]),
-- We first obtain the `y' ∈ M` such that `s' = y' • s` is falls in the image of `S` in `S'`.
let y := is_localization.common_denom_of_finset (M.map (algebra_map R S : R →* S)) s,
have hx₁ : (y : S) • ↑s = g '' _ := (is_localization.finset_integer_multiple_image _ s).symm,
obtain ⟨y', hy', e : algebra_map R S y' = y⟩ := y.prop,
have : algebra_map R S y' • (s : set S') = y' • s :=
by simp_rw [algebra.algebra_map_eq_smul_one, smul_assoc, one_smul],
rw [← e, this] at hx₁,
replace hx₁ := congr_arg (submodule.span R) hx₁,
rw submodule.span_smul_eq at hx₁,
replace hx : _ ∈ y' • submodule.span R (s : set S') := set.smul_mem_smul_set hx,
rw hx₁ at hx,
erw [← g.map_smul, ← submodule.map_span (g : S →ₗ[R] S')] at hx,
-- Since `x` falls in the span of `s` in `S'`, `y' • x : S` falls in the span of `s'` in `S'`.
-- That is, there exists some `x' : S` in the span of `s'` in `S` and `x' = y' • x` in `S'`.
-- Thus `a • (y' • x) = a • x' ∈ span s'` in `S` for some `a ∈ M`.
obtain ⟨x', hx', hx'' : algebra_map _ _ _ = _⟩ := hx,
obtain ⟨⟨_, a, ha₁, rfl⟩, ha₂⟩ := (is_localization.eq_iff_exists
(M.map (algebra_map R S : R →* S)) S').mp hx'',
use (⟨a, ha₁⟩ : M) * (⟨y', hy'⟩ : M),
convert (submodule.span R (is_localization.finset_integer_multiple
(submonoid.map (algebra_map R S : R →* S) M) s : set S)).smul_mem a hx' using 1,
convert ha₂.symm,
{ rw [mul_comm (y' • x), subtype.coe_mk, submonoid.smul_def, submonoid.coe_mul, ← smul_smul],
exact algebra.smul_def _ _ },
{ rw mul_comm, exact algebra.smul_def _ _ }
end
/-- If `S` is an `R' = M⁻¹R` algebra, and `x ∈ span R' s`,
then `t • x ∈ span R s` for some `t : M`.-/
lemma multiple_mem_span_of_mem_localization_span [algebra R' S] [algebra R S]
[is_scalar_tower R R' S] [is_localization M R']
(s : set S) (x : S) (hx : x ∈ submodule.span R' s) :
∃ t : M, t • x ∈ submodule.span R s :=
begin
classical,
obtain ⟨s', hss', hs'⟩ := submodule.mem_span_finite_of_mem_span hx,
suffices : ∃ t : M, t • x ∈ submodule.span R (s' : set S),
{ obtain ⟨t, ht⟩ := this,
exact ⟨t, submodule.span_mono hss' ht⟩ },
clear hx hss' s,
revert x,
apply s'.induction_on,
{ intros x hx, use 1, simpa using hx },
rintros a s ha hs x hx,
simp only [finset.coe_insert, finset.image_insert, finset.coe_image, subtype.coe_mk,
submodule.mem_span_insert] at hx ⊢,
rcases hx with ⟨y, z, hz, rfl⟩,
rcases is_localization.surj M y with ⟨⟨y', s'⟩, e⟩,
replace e : _ * a = _ * a := (congr_arg (λ x, algebra_map R' S x * a) e : _),
simp_rw [ring_hom.map_mul, ← is_scalar_tower.algebra_map_apply, mul_comm (algebra_map R' S y),
mul_assoc, ← algebra.smul_def] at e,
rcases hs _ hz with ⟨t, ht⟩,
refine ⟨t*s', t*y', _, (submodule.span R (s : set S)).smul_mem s' ht, _⟩,
rw [smul_add, ← smul_smul, mul_comm, ← smul_smul, ← smul_smul, ← e],
refl,
end
/-- If `S` is an `R' = M⁻¹R` algebra, and `x ∈ adjoin R' s`,
then `t • x ∈ adjoin R s` for some `t : M`.-/
lemma multiple_mem_adjoin_of_mem_localization_adjoin [algebra R' S] [algebra R S]
[is_scalar_tower R R' S] [is_localization M R']
(s : set S) (x : S) (hx : x ∈ algebra.adjoin R' s) :
∃ t : M, t • x ∈ algebra.adjoin R s :=
begin
change ∃ (t : M), t • x ∈ (algebra.adjoin R s).to_submodule,
change x ∈ (algebra.adjoin R' s).to_submodule at hx,
simp_rw [algebra.adjoin_eq_span] at hx ⊢,
exact multiple_mem_span_of_mem_localization_span M R' _ _ hx
end
lemma finite_of_localization_span : ring_hom.of_localization_span @ring_hom.finite :=
begin
rw ring_hom.of_localization_span_iff_finite,
introv R hs H,
-- We first setup the instances
resetI,
letI := f.to_algebra,
letI := λ (r : s), (localization.away_map f r).to_algebra,
haveI : ∀ r : s, is_localization ((submonoid.powers (r : R)).map (algebra_map R S : R →* S))
(localization.away (f r)),
{ intro r, rw submonoid.map_powers, exact localization.is_localization },
haveI : ∀ r : s, is_scalar_tower R (localization.away (r : R)) (localization.away (f r)) :=
λ r, is_scalar_tower.of_algebra_map_eq' (is_localization.map_comp _).symm,
-- By the hypothesis, we may find a finite generating set for each `Sᵣ`. This set can then be
-- lifted into `R` by multiplying a sufficiently large power of `r`. I claim that the union of
-- these generates `S`.
constructor,
replace H := λ r, (H r).1,
choose s₁ s₂ using H,
let sf := λ (x : s), is_localization.finset_integer_multiple (submonoid.powers (f x)) (s₁ x),
use s.attach.bUnion sf,
rw [submodule.span_attach_bUnion, eq_top_iff],
-- It suffices to show that `r ^ n • x ∈ span T` for each `r : s`, since `{ r ^ n }` spans `R`.
-- This then follows from the fact that each `x : R` is a linear combination of the generating set
-- of `Sᵣ`. By multiplying a sufficiently large power of `r`, we can cancel out the `r`s in the
-- denominators of both the generating set and the coefficients.
rintro x -,
apply submodule.mem_of_span_eq_top_of_smul_pow_mem _ (s : set R) hs _ _,
intro r,
obtain ⟨⟨_, n₁, rfl⟩, hn₁⟩ := multiple_mem_span_of_mem_localization_span
(submonoid.powers (r : R)) (localization.away (r : R)) (s₁ r : set (localization.away (f r)))
(algebra_map S _ x) (by { rw s₂ r, trivial }),
rw [submonoid.smul_def, algebra.smul_def, is_scalar_tower.algebra_map_apply R S,
subtype.coe_mk, ← map_mul] at hn₁,
obtain ⟨⟨_, n₂, rfl⟩, hn₂⟩ := is_localization.smul_mem_finset_integer_multiple_span
(submonoid.powers (r : R)) (localization.away (f r)) _ (s₁ r) hn₁,
rw [submonoid.smul_def, ← algebra.smul_def, smul_smul, subtype.coe_mk, ← pow_add] at hn₂,
use n₂ + n₁,
refine le_supr (λ (x : s), submodule.span R (sf x : set S)) r _,
change _ ∈ submodule.span R
((is_localization.finset_integer_multiple _ (s₁ r) : finset S) : set S),
convert hn₂,
rw submonoid.map_powers, refl,
end
end finite
section finite_type
lemma localization_finite_type : ring_hom.localization_preserves @ring_hom.finite_type :=
begin
introv R hf,
-- mirrors the proof of `localization_map_finite`
resetI,
letI := f.to_algebra,
letI := ((algebra_map S S').comp f).to_algebra,
let f' : R' →+* S' := is_localization.map S' f (submonoid.le_comap_map M),
letI := f'.to_algebra,
haveI : is_scalar_tower R R' S' :=
is_scalar_tower.of_algebra_map_eq' (is_localization.map_comp _).symm,
let fₐ : S →ₐ[R] S' := alg_hom.mk' (algebra_map S S') (λ c x, ring_hom.map_mul _ _ _),
obtain ⟨T, hT⟩ := id hf,
use T.image (algebra_map S S'),
rw eq_top_iff,
rintro x -,
obtain ⟨y, ⟨_, ⟨r, hr, rfl⟩⟩, rfl⟩ := is_localization.mk'_surjective (M.map f) x,
rw [is_localization.mk'_eq_mul_mk'_one, mul_comm, finset.coe_image],
have hy : y ∈ algebra.adjoin R (T : set S), by { rw hT, trivial },
replace hy : algebra_map S S' y ∈ (algebra.adjoin R (T : set S)).map fₐ :=
subalgebra.mem_map.mpr ⟨_, hy, rfl⟩,
rw fₐ.map_adjoin T at hy,
have H : algebra.adjoin R ((algebra_map S S') '' T) ≤
(algebra.adjoin R' ((algebra_map S S') '' T)).restrict_scalars R,
{ rw algebra.adjoin_le_iff, exact algebra.subset_adjoin },
convert (algebra.adjoin R' ((algebra_map S S') '' T)).smul_mem (H hy)
(is_localization.mk' R' (1 : R) ⟨r, hr⟩) using 1,
rw algebra.smul_def,
erw is_localization.map_mk',
rw map_one,
refl,
end
lemma localization_away_map_finite_type (r : R) [is_localization.away r R']
[is_localization.away (f r) S'] (hf : f.finite_type) :
(is_localization.away.map R' S' f r).finite_type :=
localization_finite_type.away r hf
variable {S'}
/--
Let `S` be an `R`-algebra, `M` a submonoid of `S`, `S' = M⁻¹S`.
Suppose the image of some `x : S` falls in the adjoin of some finite `s ⊆ S'` over `R`,
and `A` is an `R`-subalgebra of `S` containing both `M` and the numerators of `s`.
Then, there exists some `m : M` such that `m • x` falls in `A`.
-/
lemma is_localization.exists_smul_mem_of_mem_adjoin [algebra R S]
[algebra R S'] [is_scalar_tower R S S'] (M : submonoid S)
[is_localization M S'] (x : S) (s : finset S') (A : subalgebra R S)
(hA₁ : (is_localization.finset_integer_multiple M s : set S) ⊆ A)
(hA₂ : M ≤ A.to_submonoid)
(hx : algebra_map S S' x ∈ algebra.adjoin R (s : set S')) :
∃ m : M, m • x ∈ A :=
begin
let g : S →ₐ[R] S' := is_scalar_tower.to_alg_hom R S S',
let y := is_localization.common_denom_of_finset M s,
have hx₁ : (y : S) • ↑s = g '' _ := (is_localization.finset_integer_multiple_image _ s).symm,
obtain ⟨n, hn⟩ := algebra.pow_smul_mem_of_smul_subset_of_mem_adjoin (y : S) (s : set S')
(A.map g) (by { rw hx₁, exact set.image_subset _ hA₁ }) hx (set.mem_image_of_mem _ (hA₂ y.2)),
obtain ⟨x', hx', hx''⟩ := hn n (le_of_eq rfl),
rw [algebra.smul_def, ← _root_.map_mul] at hx'',
obtain ⟨a, ha₂⟩ := (is_localization.eq_iff_exists M S').mp hx'',
use a * y ^ n,
convert A.mul_mem hx' (hA₂ a.2),
convert ha₂.symm,
simp only [submonoid.smul_def, submonoid.coe_pow, smul_eq_mul, submonoid.coe_mul],
ring,
end
/--
Let `S` be an `R`-algebra, `M` an submonoid of `R`, and `S' = M⁻¹S`.
If the image of some `x : S` falls in the adjoin of some finite `s ⊆ S'` over `R`,
then there exists some `m : M` such that `m • x` falls in the
adjoin of `finset_integer_multiple _ s` over `R`.
-/
lemma is_localization.lift_mem_adjoin_finset_integer_multiple [algebra R S]
[algebra R S'] [is_scalar_tower R S S']
[is_localization (M.map (algebra_map R S : R →* S)) S'] (x : S)
(s : finset S') (hx : algebra_map S S' x ∈ algebra.adjoin R (s : set S')) :
∃ m : M, m • x ∈ algebra.adjoin R
(is_localization.finset_integer_multiple (M.map (algebra_map R S : R →* S)) s : set S) :=
begin
obtain ⟨⟨_, a, ha, rfl⟩, e⟩ := is_localization.exists_smul_mem_of_mem_adjoin
(M.map (algebra_map R S : R →* S)) x s (algebra.adjoin R _) algebra.subset_adjoin _ hx,
{ exact ⟨⟨a, ha⟩, by simpa [submonoid.smul_def] using e⟩ },
{ rintros _ ⟨a, ha, rfl⟩, exact subalgebra.algebra_map_mem _ a }
end
lemma finite_type_of_localization_span : ring_hom.of_localization_span @ring_hom.finite_type :=
begin
rw ring_hom.of_localization_span_iff_finite,
introv R hs H,
-- mirrors the proof of `finite_of_localization_span`
resetI,
letI := f.to_algebra,
letI := λ (r : s), (localization.away_map f r).to_algebra,
haveI : ∀ r : s, is_localization ((submonoid.powers (r : R)).map (algebra_map R S : R →* S))
(localization.away (f r)),
{ intro r, rw submonoid.map_powers, exact localization.is_localization },
haveI : ∀ r : s, is_scalar_tower R (localization.away (r : R)) (localization.away (f r)) :=
λ r, is_scalar_tower.of_algebra_map_eq' (is_localization.map_comp _).symm,
constructor,
replace H := λ r, (H r).1,
choose s₁ s₂ using H,
let sf := λ (x : s), is_localization.finset_integer_multiple (submonoid.powers (f x)) (s₁ x),
use s.attach.bUnion sf,
convert (algebra.adjoin_attach_bUnion sf).trans _,
rw eq_top_iff,
rintro x -,
apply (⨆ (x : s), algebra.adjoin R (sf x : set S)).to_submodule
.mem_of_span_eq_top_of_smul_pow_mem _ hs _ _,
intro r,
obtain ⟨⟨_, n₁, rfl⟩, hn₁⟩ := multiple_mem_adjoin_of_mem_localization_adjoin
(submonoid.powers (r : R)) (localization.away (r : R)) (s₁ r : set (localization.away (f r)))
(algebra_map S (localization.away (f r)) x) (by { rw s₂ r, trivial }),
rw [submonoid.smul_def, algebra.smul_def, is_scalar_tower.algebra_map_apply R S,
subtype.coe_mk, ← map_mul] at hn₁,
obtain ⟨⟨_, n₂, rfl⟩, hn₂⟩ := is_localization.lift_mem_adjoin_finset_integer_multiple
(submonoid.powers (r : R)) _ (s₁ r) hn₁,
rw [submonoid.smul_def, ← algebra.smul_def, smul_smul, subtype.coe_mk, ← pow_add] at hn₂,
use n₂ + n₁,
refine le_supr (λ (x : s), algebra.adjoin R (sf x : set S)) r _,
change _ ∈ algebra.adjoin R
((is_localization.finset_integer_multiple _ (s₁ r) : finset S) : set S),
convert hn₂,
rw submonoid.map_powers,
refl,
end
end finite_type
|
2a716a80341c758b3e5d08bfa9ac4565f3f4f97d | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/coe6.lean | b7eaf854a485e9ad035f7ff4eebf89b27e8ec23f | [
"Apache-2.0"
] | permissive | soonhokong/lean-osx | 4a954262c780e404c1369d6c06516161d07fcb40 | 3670278342d2f4faa49d95b46d86642d7875b47c | refs/heads/master | 1,611,410,334,552 | 1,474,425,686,000 | 1,474,425,686,000 | 12,043,103 | 5 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 296 | lean | structure Group :=
(carrier : Type*) (mul : carrier → carrier → carrier) (one : carrier)
attribute [instance]
definition Group_to_Type : has_coe_to_sort Group :=
has_coe_to_sort.mk Type Group.carrier
constant g : Group.{1}
set_option pp.binder_types true
check λ a b : g, Group.mul g a b
|
e564da05c9eb82fe9de6d8c4d3719a8bb802c7f2 | eb586f8ae80b7045ba4ff08f1c7ba69403d61081 | /src/e_trans_helpers2.lean | 2923adc1af095868fd97f403ef8ea8ca2d2fd1cc | [] | no_license | bryangingechen/transcendental | 926584f58c47d766b304d39d1aa6814284535394 | 3692ac5ebe85e49c5f65bc7f2ea4f873a973bac2 | refs/heads/master | 1,668,733,660,442 | 1,594,269,161,000 | 1,594,269,161,000 | 278,266,099 | 0 | 0 | null | 1,594,270,314,000 | 1,594,270,313,000 | null | UTF-8 | Lean | false | false | 40,100 | lean | import ring_theory.algebraic
import algebra.big_operators
import measure_theory.set_integral
import analysis.special_functions.exp_log
import small_things
noncomputable theory
open_locale classical
open small_things
open_locale big_operators
/-- # Definition and some theorems about differentiating multiple times
-/
/-Definition
For any integer polynomial $f$ and $n\in\mathbb N$ we define `deriv_n f n` to be the $n$-th derivative of polynomial $f$. $h^{[n]}$ means $h\circ h\circ h\cdots\circ h$ $n$-times.
-/
def deriv_n (f : polynomial ℤ) (n : ℕ) : polynomial ℤ := polynomial.derivative ^[n] f
/-Lemma
the zeroth derivative of polynomial $f$ is $f$ itself.
-/
lemma zeroth_deriv (f : polynomial ℤ) : deriv_n f 0 = f :=
begin
-- This is purely definition of `deriv_n f n`
-- We also used $f^{[n]}=\mathrm{id}$ and $\mathrm{id} x = x$.
rw deriv_n, simp only [id.def, function.iterate_zero],
end
/-Lemma
the derivative of $f^{(n)}$ is $f^{(n+1)}$
-/
lemma deriv_succ (f : polynomial ℤ) (n : ℕ) : (deriv_n f n).derivative = (deriv_n f (n+1)) :=
begin
-- By definition and $h^{[n+1]}=h\circ h^{[n]}$
rw [deriv_n, deriv_n, function.iterate_succ'],
end
/-Lemma
the $n$-th derivative of zero polynomial is $0$
-/
lemma deriv_zero_p (n : ℕ) : deriv_n 0 n = 0 :=
begin
-- We prove by induction. Base case and inductive case can all be done with `simp`
induction n with n hn; simp only [deriv_n, id.def, function.iterate_zero], rw <-deriv_n, assumption,
end
/-Lemma
If the $n$-th coefficient of $f$ is $a_n$, then the $n$-th coefficient in $f^{(k)}$ is $\left(\prod_{i=0}^{k-1} (n+k-i)\right)a_{n+k}$
-/
lemma deriv_n_coeff (f : polynomial ℤ) (k : ℕ) : ∀ n : ℕ, (deriv_n f k).coeff n = (∏ i in finset.range k, (n+k-i)) * (f.coeff (n+k)) :=
begin
-- So we use induction on $k$
induction k with k ih,
-- For the zeroth derivative, $f^{(0)}=f$. This case is true by `simp`.
simp only [add_zero, nat.nat_zero_eq_zero, one_mul, finset.range_zero, finset.prod_empty], rw deriv_n, simp only [forall_const, id.def, eq_self_iff_true, function.iterate_zero],
-- Let us assume our claim is true for $k$ and consider the $m$-th coefficient.
intro m,
-- We know that $f^{(k+1)}=\left(f^{(k)}\right)'$ and for any polynomial $g$, the $m$-th coefficient of $g'$ is $(m+1)\times (m+1)$-th coefficient of $g$. Then we can use induction hypothesis with $m+1$.
rw [deriv_n, function.iterate_succ'], simp only [function.comp_app, int.coe_nat_succ], rw <-deriv_n,
rw polynomial.coeff_derivative, rw ih (m+1),
rw finset.prod_range_succ, simp only [int.coe_nat_succ, int.nat_cast_eq_coe_nat],
-- The rest of the proves are trivial to a pair of human eyes. But we need to give computers some hint to solve this triviality.
have triv : (∏ (x : ℕ) in finset.range k, ((m:ℤ) + 1 + ↑k - ↑x)) = ∏ (x : ℕ) in finset.range k, (↑m + (↑k + 1) - ↑x),
{
apply congr_arg, ext, simp only [sub_left_inj], ring,
}, rw triv,
replace triv : (m + 1 : ℤ) = (m + (k+1) - k:ℤ),
{
rw add_sub_assoc, simp only [add_sub_cancel'],
}, rw triv,
replace triv : f.coeff (m + 1 + k) = f.coeff (m + k.succ),
{
rw nat.succ_eq_add_one, ring,
},
rw triv, ring,
end
/-Lemma
Like first derivative, higher derivatives still respect addition
-/
lemma deriv_n_add (p q :polynomial ℤ) (n : ℕ) : (deriv_n (p+q) n) = (deriv_n p n) + (deriv_n q n) :=
begin
induction n with n ih, rw [deriv_n, deriv_n, deriv_n], simp only [id.def, function.iterate_zero],
rw [deriv_n, deriv_n, deriv_n, function.iterate_succ'], simp only [function.comp_app], rw [<-deriv_n,<-deriv_n,<-deriv_n, ih], simp only [polynomial.derivative_add],
end
/-Lemma
For any polynomial $f$ with degree $d$, the $d+1$-th derivative is zero.
-/
theorem deriv_too_much (f : polynomial ℤ): (deriv_n f (f.nat_degree + 1)) = 0 :=
begin
-- We prove that all coefficient of $f^{(d+1)}$ is zero.
ext,
-- We use lemma `deriv_n_coeff` and all coefficient of zero polynomial is $0$.
rw deriv_n_coeff, simp only [int.coe_nat_succ, polynomial.coeff_zero, mul_eq_zero], right,
-- Then the problem reduces to prove that $d+1$-th coeffcient of $f$ is zero. But $f$ has degree $d$. So we just need $d<d+1$. This is proved by `linarith`.
apply polynomial.coeff_eq_zero_of_nat_degree_lt, linarith,
end
/-Lemma
if $i+1\le n$ then $n-(i+1)+1=n-i$
-/
private lemma nat_sub_eq (n i : ℕ) (h : i + 1 ≤ n) : (n - (i + 1) + 1) = n - i :=
begin
have triv : n - (i+1) = n - i - 1, exact rfl,
rw triv, apply nat.sub_add_cancel, exact nat.le_sub_left_of_add_le h,
end
/-Lemma
We have the pascal triangle
\[{n\choose k+1}+{n\choose k} = {n+1\choose k+1}\]
-/
private lemma pascal_triangle (n k : ℕ) : (n.choose (k+1)) + (n.choose k) = (n+1).choose (k+1) :=
begin
-- This is actually how `mathlib` defined binomial coefficient.
exact add_comm (nat.choose n (k + 1)) (nat.choose n k),
end
/-Theorem
We also have that for $p,q\in\mathbb Z[x]$,
\[
(p\times q)^{(n)} = \sum_{i=0}^n\left({n\choose i}p^{(i)}q^{(n-i)}\right)
\]
-/
theorem deriv_n_poly_prod (p q : polynomial ℤ) (n : ℕ) : deriv_n (p * q) n = ∑ k in finset.range n.succ, (polynomial.C (n.choose k:ℤ)) * (deriv_n p (n-k)) * (deriv_n q k) :=
begin
-- We prove by induction on $n$.
induction n with n IH,
-- For $n=0$, we are using `zeroth_deriv`.
simp only [zeroth_deriv, nat.choose_self, int.cast_coe_nat, ring_hom.eq_int_cast, one_mul, nat.cast_one, finset.sum_singleton, finset.range_one],
{
-- For inductive case
-- We use $(pq)^{(n+1)}=d(pq)^{(n)}$, inductive hypothesis and that derivative is linear.
rw deriv_n, rw function.iterate_succ', dsimp, rw <-deriv_n,
rw IH, simp only [polynomial.derivative_sum, polynomial.derivative_mul, zero_mul, polynomial.derivative_C, zero_add, polynomial.derivative_sum, polynomial.derivative_mul, zero_mul, polynomial.derivative_C, zero_add],
-- The rest of the proves is essentially openning and closing brackets and renaming summing indeces.
rw finset.sum_add_distrib,
conv_lhs {rw finset.sum_range_succ', rw finset.sum_range_succ, simp only [zeroth_deriv, nat.choose_self, one_mul, nat.choose_zero_right, int.coe_nat_zero, nat.sub_self, polynomial.C_1, int.coe_nat_succ, nat.sub_zero, zero_add]},
have eq :
∑ (i : ℕ) in finset.range n,
polynomial.C (n.choose (i + 1):ℤ) * (deriv_n p (n - (i + 1))).derivative * deriv_n q (i + 1) +
(deriv_n p n).derivative * q +
(p * (deriv_n q n).derivative +
∑ (x : ℕ) in finset.range n, polynomial.C (n.choose x:ℤ) * deriv_n p (n - x) * (deriv_n q x).derivative) =
(∑ (i : ℕ) in finset.range n,
polynomial.C (n.choose (i + 1):ℤ) * (deriv_n p (n - (i + 1))).derivative * deriv_n q (i + 1)) +
(∑ (x : ℕ) in finset.range n, polynomial.C (n.choose x:ℤ) * deriv_n p (n - x) * (deriv_n q x).derivative) +
((deriv_n p n).derivative * q + (p * (deriv_n q n).derivative)) := by ring,
rw [eq, <-finset.sum_add_distrib],
replace eq :
(∑ (x : ℕ) in finset.range n,
(polynomial.C (n.choose (x + 1):ℤ) * (deriv_n p (n - (x + 1))).derivative * deriv_n q (x + 1) +
polynomial.C (n.choose x:ℤ) * deriv_n p (n - x) * (deriv_n q x).derivative)) =
(∑ (x : ℕ) in finset.range n,
(polynomial.C (n.choose (x + 1):ℤ) * (deriv_n p (n - x)) * deriv_n q (x + 1) +
polynomial.C (n.choose x:ℤ) * deriv_n p (n - x) * (deriv_n q (x+1)))),
{
apply finset.sum_congr, exact rfl, intros i hi, simp only [deriv_succ, int.cast_coe_nat, ring_hom.eq_int_cast, add_left_inj], simp only [finset.mem_range] at hi,
replace hi : i + 1 ≤ n := hi,
rw nat_sub_eq _ _ hi,
}, rw eq,
replace eq :
(∑ (x : ℕ) in finset.range n,
(polynomial.C (n.choose (x + 1):ℤ) * (deriv_n p (n - x)) * deriv_n q (x + 1) +
polynomial.C (n.choose x:ℤ) * deriv_n p (n - x) * (deriv_n q (x+1)))) =
(∑ (x : ℕ) in finset.range n,
((polynomial.C (n.choose (x + 1):ℤ) + polynomial.C (n.choose x:ℤ)) * (deriv_n p (n - x)) * deriv_n q (x + 1))),
{
apply congr_arg, rw function.funext_iff, intro i, ring,
}, rw eq,
replace eq :
(∑ (x : ℕ) in finset.range n,
((polynomial.C (n.choose (x + 1):ℤ) + polynomial.C (n.choose x:ℤ)) * (deriv_n p (n - x)) * deriv_n q (x + 1))) =
(∑ (x : ℕ) in finset.range n,
((polynomial.C (n.choose (x + 1) + (n.choose x):ℤ)) * (deriv_n p (n - x)) * deriv_n q (x + 1))),
{
apply congr_arg, rw function.funext_iff, intro i, simp only [int.cast_add, ring_hom.eq_int_cast],
}, rw eq,
replace eq :
(∑ (x : ℕ) in finset.range n,
((polynomial.C (n.choose (x + 1) + (n.choose x):ℤ)) * (deriv_n p (n - x)) * deriv_n q (x + 1))) =
(∑ (x : ℕ) in finset.range n,
((polynomial.C ((n+1).choose (x + 1):ℤ)) * (deriv_n p (n - x)) * deriv_n q (x + 1))),
{
apply congr_arg, rw function.funext_iff, intro i, rw <-pascal_triangle, simp only [int.coe_nat_add],
}, rw eq,
conv_rhs {rw finset.sum_range_succ', rw finset.sum_range_succ}, simp only [deriv_succ, zeroth_deriv, nat.succ_eq_add_one, nat.choose_self, int.cast_coe_nat, ring_hom.eq_int_cast, one_mul, nat.succ_sub_succ_eq_sub, nat.choose_zero_right, int.coe_nat_zero, nat.sub_self, int.cast_one, int.coe_nat_succ, nat.sub_zero, zero_add], ring,
}
end
/-Theorem
For a polynomial $f$ then if $n>0$, we have $f^{(n)}=f^{(n-1)\times f'}$
-/
theorem poly_pow_deriv (f : polynomial ℤ) (n : ℕ) (hn : n > 0) : (f ^ n).derivative = (polynomial.C (n:ℤ)) * (f ^ (n-1)) * f.derivative :=
begin
induction n with n IH,
exfalso, linarith,
{
cases n,
simp only [ring_hom.eq_int_cast, one_mul, int.coe_nat_zero, int.cast_one, int.coe_nat_succ, pow_one, zero_add, pow_zero],
replace IH := IH (nat.succ_pos n),
rw nat.succ_eq_add_one, rw pow_add, simp only [int.cast_coe_nat, int.cast_add, ring_hom.eq_int_cast, polynomial.derivative_mul, int.cast_one, nat.succ_add_sub_one,
int.coe_nat_succ, pow_one], rw IH, simp only [nat.succ_sub_succ_eq_sub, polynomial.C_add, polynomial.C_1, int.coe_nat_succ, nat.sub_zero, nat.succ_sub_succ_eq_sub,
int.coe_nat_succ, nat.sub_zero],
have eq1 : (polynomial.C ↑n + 1) * f ^ n * f.derivative * f = (polynomial.C ↑n + 1) * f ^ (n+1) * f.derivative,
{
rw pow_add, simp only [int.cast_coe_nat, ring_hom.eq_int_cast, pow_one], ring,
} ,
rw eq1, rw nat.succ_eq_add_one, repeat {rw add_mul}, simp only [int.cast_coe_nat, ring_hom.eq_int_cast, one_mul],
}
end
/-- # Assumption-/
-- I should assume they are "nice".
axiom ftc (f: ℝ -> ℝ) (a b : ℝ) (h : b ≥ a) : (∫ x in set.Icc a b, (deriv f) x) = f b - f a
axiom integrate_by_part (f g : ℝ -> ℝ) (a b : ℝ) (h : b ≥ a) :
(∫ x in set.Icc a b, (f x)*(deriv g x)) = (f b) * (g b) - (f a) * (g a) - (∫ x in set.Icc a b, (deriv f x) * (g x))
theorem integral_le_integral' (f g : ℝ -> ℝ) {h1 : measurable f ∧ measurable g ∧ measure_theory.integrable f ∧ measure_theory.integrable g} (a b : ℝ) (h : b ≥ a) (hf : ∀ x ∈ set.Icc a b, f x ≤ g x ∧ 0 ≤ f x) : (∫ x in set.Icc a b, f x) ≤ (∫ x in set.Icc a b, g x) :=
begin
-- destruct h1,
apply @measure_theory.integral_le_integral ℝ _ ((set.Icc a b).indicator f) ((set.Icc a b).indicator g),
simp [set.indicator],
apply measurable.if, apply is_measurable_Icc,
dsimp, exact h1.1, exact measurable_zero,
apply measure_theory.integrable.integrable_on, exact h1.2.2.1,
simp [set.indicator],
apply measurable.if, apply is_measurable_Icc, dsimp, exact h1.2.1, exact measurable_zero,
apply measure_theory.integrable.integrable_on, exact h1.2.2.2,
intros c, simp [set.indicator], split_ifs, exact (hf c ⟨h_1.1, h_1.2⟩).1, exact le_refl 0,
end
theorem same_integral {S : set ℝ} (f g : ℝ -> ℝ) : f = g -> (∫ x in S, f x) = ∫ x in S, g x :=
begin
intro h,
simp only [], exact congr_arg measure_theory.integral (congr_arg (set.indicator S) h)
end
theorem same_integral'' {S : set ℝ} (f g : ℝ -> ℝ) : (∀ x ∈ S, f x = g x) -> (∫ x in S, f x) = ∫ x in S, g x :=
begin
intro h,
simp only [], apply congr_arg measure_theory.integral, ext, simp only [set.indicator], split_ifs, exact h x h_1, refl,
end
theorem same_integral' (f g : ℝ -> ℝ) : f = g -> (∫ x, f x) = ∫ x, g x := (λ h, congr_arg measure_theory.integral h)
theorem same_deriv (f g : ℝ -> ℝ) (x : ℝ) : f = g -> deriv f x = deriv g x := λ h, congr_fun (congr_arg deriv h) x
theorem integral_neg' {S : set ℝ} (f : ℝ -> ℝ) : (∫ x in S, -f x) = - ∫ x in S, f x := integral_on_neg S (λ (a : ℝ), f a)
theorem integral_constant (a b : ℝ) (h : b ≥ a) (c : ℝ): (∫ x in set.Icc a b, c) = (b - a) * c :=
begin
have eq1 : (∫ x in set.Icc a b, c) = (∫ x in set.Icc a b, (deriv (λ y, c * y)) x),
{
apply congr_arg, apply congr_arg, ext, simp only [differentiable_at_const, mul_one, deriv_mul, differentiable_at_id', zero_mul, deriv_id'', deriv_const', zero_add],
},
rw eq1,
rw (ftc (λ (y : ℝ), c * y) a b h), simp only [], ring,
end
theorem integrable_const_Icc (a b c : ℝ) (c_nonneg : 0 ≤ c) (hab : a ≤ b) :
measure_theory.integrable ((set.Icc a b).indicator (λ _, c)) :=
begin
set f_simp : measure_theory.simple_func ℝ ennreal :=
{
to_fun := λ a_1, ennreal.of_real (ite (a_1 ∈ set.Icc a b) c 0),
measurable_sn :=
begin
intros x,
by_cases (c=0),
{
rw h, simp only [if_t_t, norm_zero, ennreal.of_real_zero], rw set.preimage_const,
split_ifs, exact is_measurable.univ, exact is_measurable.empty,
},
{
have c_pos : c > 0, exact lt_of_le_of_ne c_nonneg (ne.symm h),
by_cases H : (x=0),
{
rw H,
have set1 : (λ (a_1 : ℝ), ennreal.of_real (ite (a_1 ∈ set.Icc a b) c 0)) ⁻¹' {0} = (set.Icc a b)ᶜ,
{
ext y, split, intros hy, simp only [set.mem_preimage, ennreal.of_real_eq_zero, set.mem_zero, set.singleton_zero, set.mem_Icc] at hy ⊢,
split_ifs at hy, linarith, simp only [not_and, not_le] at h_1,
suffices : y ∉ set.Icc a b, exact set.mem_compl this, simp only [not_and, not_le, set.mem_Icc], intro rid,
replace h_1 := h_1 rid, exact h_1,
intros hy, simp only [set.mem_preimage, not_and, ennreal.of_real_eq_zero, not_le, set.mem_zero, set.singleton_zero, set.mem_compl_eq,
set.mem_Icc] at hy ⊢, split_ifs, replace hy := hy h_1.1, replace h_1 := h_1.2, linarith, exact le_refl 0,
}, rw set1, rw is_measurable.compl_iff, exact is_measurable_Icc,
},
{
by_cases (x=(ennreal.of_real c)),
{
rw h,
have set1 : ((λ (a_1 : ℝ), ennreal.of_real (ite (a_1 ∈ set.Icc a b) c 0)) ⁻¹' {ennreal.of_real c}) = set.Icc a b,
{
ext y, split, intros hy, simp only [set.mem_preimage, set.mem_singleton_iff, set.mem_Icc] at hy ⊢,
split_ifs at hy, assumption, simp only [ennreal.of_real_zero] at hy,
replace hy := ennreal.of_real_eq_zero.1 (eq.symm hy), linarith,
intro hy, simp only [set.mem_preimage, set.mem_singleton_iff, set.mem_Icc], split_ifs,
refl, refl,
}, rw set1, exact is_measurable_Icc,
},
{
have set2 : ((λ (a_1 : ℝ), ennreal.of_real (ite (a_1 ∈ set.Icc a b) c 0)) ⁻¹' {x}) = ∅,
{
ext y, split, intros hy, simp only [set.mem_preimage, set.mem_singleton_iff, set.mem_Icc] at hy,
split_ifs at hy, rw <-hy at h, simp only [eq_self_iff_true, not_true] at h,
exfalso, exact h,
simp only [ennreal.of_real_zero] at hy, exact H (eq.symm hy),
intros hy, exfalso, simp only [set.mem_empty_eq] at hy, exact hy,
}, rw set2, exact is_measurable.empty,
}
},
}
end,
finite :=
begin
have set1 : (set.range (λ (a_1 : ℝ), ennreal.of_real (ite (a_1 ∈ set.Icc a b) c 0))) = {ennreal.of_real c, 0},
{
ext, split, intros hx, simp only [set.mem_insert_iff, set.mem_range, set.mem_zero, set.singleton_zero, set.mem_Icc] at hx ⊢,
choose y hy using hx, split_ifs at hy, left, exact eq.symm hy, right, simp only [ennreal.of_real_zero] at hy,
exact eq.symm hy,
intros hx, simp only [set.mem_insert_iff, set.mem_range, set.mem_zero, set.singleton_zero, set.mem_Icc] at hx ⊢,
cases hx,
use a, split_ifs, exact hx.symm,
simp only [forall_prop_of_true, not_and, not_le] at h, linarith,
use b+1, split_ifs, have rid1 := h.1, have rid2 := h.2, linarith,
simp only [add_le_iff_nonpos_right, not_and, not_le] at h,
rw hx, simp only [ennreal.of_real_zero],
}, rw set1,
apply set.finite.insert, exact set.finite_singleton 0,
end
} with hf_simp,
have f_simp_to_fun : f_simp.to_fun = (λ (a_1 : ℝ), ennreal.of_real (ite (a_1 ∈ set.Icc a b) c 0)), dsimp [f_simp], refl,
have f_simp_range : f_simp.range = {0, ennreal.of_real c},
{
ext y, split, intros hy, simp only [measure_theory.simple_func.mem_range, finset.mem_insert, finset.mem_singleton] at hy ⊢,
choose x hx using hy,
have triv : (f_simp x) =
((λ (a_1 : ℝ), ennreal.of_real (ite (a_1 ∈ set.Icc a b) c 0)) x),
rw [<-f_simp_to_fun], exact rfl,
rw hx at triv, simp only [] at triv, split_ifs at triv, right, exact triv, simp only [ennreal.of_real_zero] at triv, left, exact triv,
intros hy, simp only [finset.mem_insert, finset.mem_singleton] at hy, cases hy,
rw hy, simp only [measure_theory.simple_func.mem_range],
use b+1, have triv : f_simp (b + 1) = f_simp.to_fun (b+1), exact rfl, rw triv, rw f_simp_to_fun, simp only [],
split_ifs, exfalso, simp only [add_le_iff_nonpos_right, set.mem_Icc] at h, have rid1 := h.1, have rid2 := h.2, linarith,
rw ennreal.of_real_zero,
rw hy, simp only [measure_theory.simple_func.mem_range],
use a, have triv : f_simp a = f_simp.to_fun a, exact rfl, rw triv, rw f_simp_to_fun, simp only [], split_ifs, refl,
simp only [set.left_mem_Icc, not_le] at h, linarith,
},
have eq2 : (∫⁻ (a_1 : ℝ), ennreal.of_real (ite (a_1 ∈ set.Icc a b) c 0)) = (∫⁻ (a_1 : ℝ), f_simp a_1),
{
apply measure_theory.lintegral_congr, intro x, simp only [f_simp, if_t_t, forall_prop_of_true, set.mem_empty_eq, set.mem_preimage, add_zero, norm_zero, set.mem_insert_iff,
set.mem_range, not_and, set.mem_singleton_iff, ennreal.of_real_zero, ennreal.of_real_eq_zero, not_le, eq_self_iff_true,
not_true, set.finite_singleton, set.finite.insert, set.mem_zero, zero_add, set.singleton_zero, set.mem_compl_eq,
set.mem_Icc, neg_zero], exact rfl,
},
by_cases c_zero : (c = 0),
simp [c_zero], rw measure_theory.integrable_iff_norm,
simp_rw norm_indicator_eq_indicator_norm,
simp only [set.indicator],
have triv : ∥c∥ = c, rw real.norm_eq_abs, rw abs_of_nonneg, exact c_nonneg,
simp_rw [triv], rw eq2, rw measure_theory.simple_func.lintegral_eq_integral, rw measure_theory.simple_func.integral,
apply ennreal.sum_lt_top,
intros z hz, rw f_simp_range at hz, simp only [finset.mem_insert, finset.mem_singleton] at hz,
cases hz,
{
rw hz, rw zero_mul, exact with_top.zero_lt_top,
},
{
rw hz,
have set1 : (⇑f_simp ⁻¹' {ennreal.of_real c}) = (set.Icc a b),
{
ext y, split, intro hy, simp only [set.mem_preimage, set.mem_singleton_iff, set.mem_Icc] at hy ⊢,
have triv : (f_simp y) = (f_simp.to_fun y), exact rfl, rw triv at hy, rw f_simp_to_fun at hy, simp only [] at hy,
split_ifs at hy, simp only [set.mem_Icc] at h, exact h, simp only [ennreal.of_real_zero] at hy, replace hy := eq.symm hy,
rw ennreal.of_real_eq_zero at hy, exfalso,
replace hy : c < 0, exact lt_of_le_of_ne hy c_zero, linarith,
intros hy, rw set.mem_preimage, simp only [set.mem_singleton_iff] at ⊢,
have triv : (f_simp y) = (f_simp.to_fun y), exact rfl, rw triv, rw f_simp_to_fun, simp only [], split_ifs, refl,
}, rw set1, rw real.volume_Icc, apply ennreal.mul_lt_top, rw lt_top_iff_ne_top, exact ennreal.of_real_ne_top,
rw lt_top_iff_ne_top, exact ennreal.of_real_ne_top,
},
end
theorem integral_le_max_times_length (f : ℝ -> ℝ) {h1 : measurable f ∧ measure_theory.integrable f} (a b : ℝ) (h : b ≥ a) (c : ℝ)
(f_nonneg : ∀ x ∈ set.Icc a b, f x ≥ 0) (c_max : ∀ x ∈ set.Icc a b, f x ≤ c) :
(∫ x in set.Icc a b, f x) ≤ (b - a) * c :=
begin
have ineq1 := integral_le_integral' f ((set.Icc a b).indicator (λ _, c)) a b h _,
have triv1 : (∫ (x : ℝ) in set.Icc a b, (set.Icc a b).indicator (λ (_x : ℝ), c) x) = (∫ (x : ℝ) in set.Icc a b, c),
{
rw same_integral'', intros, simp only [set.indicator, set.mem_Icc], split_ifs, refl, refl,
},
rw triv1 at ineq1, rw integral_constant at ineq1, exact ineq1, exact h,
split, exact h1.1, split, simp only [set.indicator], apply measurable.if, exact is_measurable_Icc, exact measurable_const,
exact measurable_zero, split, exact h1.2,
apply integrable_const_Icc,
{
have ineq1 := f_nonneg a _,
have ineq2 := c_max a _, exact le_trans ineq1 ineq2, simp only [set.left_mem_Icc], exact h,
simp only [set.left_mem_Icc], exact h,
}, exact h,
intros x hx, simp only [set.indicator], split_ifs, split, exact c_max x hx, exact f_nonneg x hx,
end
theorem deriv_exp_t_x (t : ℝ) : deriv (λ x, real.exp (t-x)) = -(λ x, real.exp (t-x)) :=
begin
have triv : (λ x, real.exp (t-x)) = real.exp ∘ (λ x, t - x) := by simp only [],
ext,
rw triv,
rw deriv.scomp, simp only [neg_mul_eq_neg_mul_symm, deriv_exp, differentiable_at_const, mul_one, algebra.id.smul_eq_mul, one_mul, zero_sub, deriv_sub, differentiable_at_id', pi.neg_apply, deriv_id'', deriv_const'],
simp only [differentiable_at_id', differentiable_at.exp],
apply differentiable_at.const_sub,
exact differentiable_at_id,
end
theorem deriv_exp_t_x' (t : ℝ) : (deriv (λ x, - (real.exp (t-x)))) = (λ x, real.exp (t-x)) := by simp only [deriv_exp_t_x, deriv_neg', pi.neg_apply, neg_neg]
/--
# about I
-/
/-Definition
Suppose $f$ is an integer polynomial with degree $n$ and $t\ge0$ then define
\[I(f,t):=\int_0^t \exp(t-x)f(z)\mathrm{d}x\]
We use integration by parts to prove
\[I(f,t)=\exp(t)\left(\times\sum_{i=0}^n f^{(i)}(0)-\sum_{i=0}^n f^{(i)}(t)\right)\]
The two different ways of representing $I(f,t)$ we give us upper bound and lower bound when we are using this on transcendence of $e$.
-/
def I (f : polynomial ℤ) (t : ℝ) (ht : t ≥ 0) : ℝ :=
t.exp * (∑ i in finset.range f.nat_degree.succ, (f_eval_on_ℝ (deriv_n f i) 0)) - (∑ i in finset.range f.nat_degree.succ, (f_eval_on_ℝ (deriv_n f i) t))
def II (f : polynomial ℤ) (t : ℝ) (ht : t ≥ 0) : ℝ := ∫ x in set.Icc 0 t, real.exp(t - x) * (f_eval_on_ℝ f x)
/-Theorem
$\int_0^0$ is 0.
-/
theorem II_0 (t : ℝ) (ht : t ≥ 0) : II 0 t ht = 0 :=
begin
rw II, unfold f_eval_on_ℝ, simp only [set.indicator_zero, measure_theory.integral_zero, mul_zero, polynomial.eval_zero, polynomial.map_zero],
end
/-Theorem
By integration by part we have:
\[I(f, t) = e^tf(0)-f(t)+I(f',t)\]
-/
theorem II_integrate_by_part (f : polynomial ℤ) (t : ℝ) (ht : t ≥ 0) :
(II f t ht) = (real.exp t) * (f_eval_on_ℝ f 0) - (f_eval_on_ℝ f t) + (II f.derivative t ht) :=
begin
rw II,
have eq : (∫ x in set.Icc 0 t, (t - x).exp * f_eval_on_ℝ f x) = (∫ x in set.Icc 0 t, f_eval_on_ℝ f x * (deriv (λ x, - (real.exp (t-x))) x)),
{
apply same_integral, ext, simp only [deriv_exp_t_x'], ring,
},
rw eq,
replace eq := integrate_by_part (f_eval_on_ℝ f) (λ (x : ℝ), -(t - x).exp) 0 t ht,
rw eq, simp only [mul_one, neg_sub_neg, real.exp_zero, sub_zero, mul_neg_eq_neg_mul_symm, sub_self],
replace eq : (∫ x in set.Icc 0 t, -(deriv (f_eval_on_ℝ f) x * (t - x).exp)) = ∫ x in set.Icc 0 t, -((λ x, (deriv (f_eval_on_ℝ f) x * (t - x).exp)) x),
{
apply same_integral, ext, simp only [],
},
rw eq, rw integral_neg', simp only [sub_neg_eq_add], rw II,
replace eq : (∫ (x : ℝ) in set.Icc 0 t, (t - x).exp * f_eval_on_ℝ f.derivative x) = ∫ (x : ℝ) in set.Icc 0 t, deriv (f_eval_on_ℝ f) x * (t - x).exp,
{
apply same_integral, ext, ring, rw f_eval_on_ℝ,
have triv : (polynomial.map ℤembℝ f.derivative) = (polynomial.map ℤembℝ f).derivative,
{
ext, rw polynomial.coeff_derivative, rw polynomial.coeff_map, rw polynomial.coeff_derivative, rw polynomial.coeff_map,
simp only [int.cast_coe_nat, int.cast_add, ring_hom.eq_int_cast, int.cast_mul, int.cast_one, int.nat_cast_eq_coe_nat],
},
rw triv, rw <-polynomial.deriv,replace triv : deriv (λ (x : ℝ), polynomial.eval x (polynomial.map ℤembℝ f)) x = deriv (f_eval_on_ℝ f) x,
{
apply same_deriv, ext, rw f_eval_on_ℝ,
},
rw triv, ring,
}, rw eq, ring,
end
/-Theorem
Combine the theorem above with induction we get for all $m\in\mathbb N$
\[
I(f,t)=e^t\sum_{i=0}^m f^{(i)}(0)-\sum_{i=0}^m f^{(i)}(t)
\]
-/
theorem II_integrate_by_part_m (f : polynomial ℤ) (t : ℝ) (ht : t ≥ 0) (m : ℕ) :
II f t ht = t.exp * (∑ i in finset.range (m+1), (f_eval_on_ℝ (deriv_n f i) 0)) - (∑ i in finset.range (m+1), f_eval_on_ℝ (deriv_n f i) t) + (II (deriv_n f (m+1)) t ht) :=
begin
induction m with m ih,
rw deriv_n, simp only [function.iterate_one, finset.sum_singleton, finset.range_one], rw II_integrate_by_part, rw deriv_n, simp only [id.def, function.iterate_zero],
rw ih,
have triv : m.succ + 1 = (m+1).succ := by ring, rw triv, generalize hM : m + 1 = M,
rw II_integrate_by_part,
replace triv : t.exp * ∑ (i : ℕ) in finset.range M, f_eval_on_ℝ (deriv_n f i) 0 -
∑ (i : ℕ) in finset.range M, f_eval_on_ℝ (deriv_n f i) t +
(t.exp * f_eval_on_ℝ (deriv_n f M) 0 - f_eval_on_ℝ (deriv_n f M) t + II (deriv_n f M).derivative t ht)
= t.exp * ((∑ (i : ℕ) in finset.range M, f_eval_on_ℝ (deriv_n f i) 0) + (f_eval_on_ℝ (deriv_n f M) 0))
- ((∑ (i : ℕ) in finset.range M, f_eval_on_ℝ (deriv_n f i) t) + f_eval_on_ℝ (deriv_n f M) t) + II (deriv_n f M).derivative t ht := by ring,
rw triv,
replace triv : ∑ (i : ℕ) in finset.range M, f_eval_on_ℝ (deriv_n f i) 0 + f_eval_on_ℝ (deriv_n f M) 0 = ∑ (i : ℕ) in finset.range M.succ, f_eval_on_ℝ (deriv_n f i) 0,
rw finset.sum_range_succ, ring,
rw triv,
replace triv : (∑ (i : ℕ) in finset.range M, f_eval_on_ℝ (deriv_n f i) t + f_eval_on_ℝ (deriv_n f M) t) = (∑ (i : ℕ) in finset.range M.succ, f_eval_on_ℝ (deriv_n f i) t),
rw finset.sum_range_succ, ring,
rw triv,
replace triv : (deriv_n f M).derivative= (deriv_n f M.succ),
{
conv_rhs {rw deriv_n}, rw function.iterate_succ',
replace triv : (polynomial.derivative ∘ (polynomial.derivative^[M])) f = (polynomial.derivative (polynomial.derivative^[M] f)) := rfl,
rw triv, rw <-deriv_n,
}, rw triv,
end
/-Theorem
So the using if $f$ has degree $n$, then $f^{(n+1)}$ is zero we have the two definition of $I(f,t)$ agrees.
-/
theorem II_eq_I (f : polynomial ℤ) (t : ℝ) (ht : t ≥ 0) : II f t ht = I f t ht :=
begin
have II_integrate_by_part_m := II_integrate_by_part_m f t ht f.nat_degree,
have triv := deriv_too_much f, rw triv at II_integrate_by_part_m, rw II_0 at II_integrate_by_part_m, simp only [add_zero] at II_integrate_by_part_m,
rw I, assumption,
end
lemma norm_indicator {a b : ℝ} {h : a ≤ b} (f : ℝ -> ℝ) (x : ℝ) : ∥ set.indicator (set.Icc a b) f x ∥ = (set.indicator (set.Icc a b) (λ y, ∥ f y ∥)) x :=
begin
conv_rhs {rw [set.indicator_apply],}, split_ifs,
rw set.indicator_apply, simp only [h_1, if_true],
rw set.indicator_apply, simp only [h_1, norm_zero, if_false],
end
/-Theorem
\[\left|I(f,t)\right|\le \int_0^t \left|e^{t-x}f(x)\right|\mathrm{d}x\]
-/
theorem abs_II_le1 (f : polynomial ℤ) (t : ℝ) (ht : t ≥ 0) : abs (II f t ht) ≤ ∫ x in set.Icc 0 t, abs ((t-x).exp * (f_eval_on_ℝ f x)) :=
begin
have triv : (∫ x in set.Icc 0 t, abs ((t-x).exp * (f_eval_on_ℝ f x))) = ∫ x in set.Icc 0 t, ∥(t-x).exp * (f_eval_on_ℝ f x)∥,
{
apply same_integral, ext, exact rfl,
}, rw triv,
replace triv : abs (II f t ht) = ∥ (∫ (x : ℝ) in set.Icc 0 t, (t - x).exp * f_eval_on_ℝ f x) ∥,
{
exact rfl,
}, rw triv,
have ineq := @measure_theory.norm_integral_le_integral_norm ℝ _ ℝ _ _ _ _ _ _ (set.indicator (set.Icc 0 t) (λ x, (t - x).exp * f_eval_on_ℝ f x)),
simp only [] at ineq,
replace triv : (∫ (a : ℝ), ∥(set.Icc 0 t).indicator (λ (x : ℝ), (t - x).exp * f_eval_on_ℝ f x) a∥) =
∫ (a : ℝ), (set.Icc 0 t).indicator (λ (x : ℝ), ∥ (t - x).exp * f_eval_on_ℝ f x ∥) a,
{
apply same_integral', ext, rw norm_indicator, exact ht,
}, rw triv at ineq, exact ineq,
end
/-- # $\bar{f}$
- Say $f(T)=a_0+a_1T+a_2T^2+\cdots+a_nT^n$. Then $\bar{f}=|a_0|+|a_1|T+|a_2|T^2+\cdots+|a_n|T^n$
- We proved some theorems about $\bar{f}$
-/
def f_bar (f : polynomial ℤ) : polynomial ℤ :=
{ support := f.support,
to_fun := λ n, abs (f.coeff n),
mem_support_to_fun := λ n, ⟨begin
intro hn, simp only [abs_eq_zero, ne.def], have h := (f.3 n).1 hn, simp only [ne.def] at h, assumption
end, begin
intro hn, simp only [abs_eq_zero, ne.def] at hn, apply (f.3 n).2, simpa only [],
end⟩}
theorem bar_coeff (f : polynomial ℤ) (n : ℕ) : (f_bar f).coeff n = abs (f.coeff n) :=
begin
dsimp [f_bar], refl,
end
theorem bar_supp (f : polynomial ℤ) : (f_bar f).1 = f.1 :=
begin
dsimp [f_bar], refl,
end
theorem bar_same_deg (f : polynomial ℤ) : (f_bar f).nat_degree = f.nat_degree :=
begin
apply polynomial.nat_degree_eq_of_degree_eq,
rw polynomial.degree, rw polynomial.degree, rw bar_supp,
end
theorem f_bar_0 : f_bar 0 = 0 :=
begin
ext, rw bar_coeff, simp only [abs_zero, polynomial.coeff_zero],
end
theorem f_bar_eq_0 (f : polynomial ℤ) : f_bar f = 0 -> f = 0 :=
begin
intro h, rw polynomial.ext_iff at h, ext,
have hn := h n, simp only [polynomial.coeff_zero] at hn, rw bar_coeff at hn, simp only [abs_eq_zero, polynomial.coeff_zero] at hn ⊢, assumption,
end
private lemma coeff_sum (f : ℕ -> polynomial ℤ) (m : ℕ) (s : finset ℕ) : (∑ i in s, (f i).coeff m) = (∑ i in s, f i).coeff m :=
begin
apply finset.induction_on s, simp only [finset.sum_empty, polynomial.coeff_zero],
intros a s ha, simp only [forall_prop_of_true, polynomial.finset_sum_coeff],
end
theorem f_bar_eq (f : polynomial ℤ) : f_bar f = ∑ i in finset.range f.nat_degree.succ, polynomial.C (abs (f.coeff i)) * polynomial.X^i :=
begin
ext, rw bar_coeff, rw <-coeff_sum, simp_rw [polynomial.coeff_C_mul_X], simp only [finset.mem_range, finset.sum_ite_eq], split_ifs, refl, simp only [not_lt] at h,
rw polynomial.coeff_eq_zero_of_nat_degree_lt h, exact rfl,
end
theorem coeff_f_bar_mul (f g : polynomial ℤ) (n : ℕ) : (f_bar (f*g)).coeff n = abs(∑ p in finset.nat.antidiagonal n, (f.coeff p.1)*(g.coeff p.2)) :=
begin
rw bar_coeff (f*g) n, rw polynomial.coeff_mul,
end
theorem f_bar_ineq (f : polynomial ℤ) (t : ℝ) (ht : t ≥ 0) : ∀ x ∈ set.Icc 0 t, abs (f_eval_on_ℝ f x) ≤ f_eval_on_ℝ (f_bar f) t :=
begin
intros x hx,
have lhs : f_eval_on_ℝ f x = ∑ i in f.support, (f.coeff i : ℝ) * x ^ i,
{
rw [f_eval_on_ℝ, polynomial.eval_map, polynomial.eval₂, finsupp.sum],
apply congr_arg, ext, norm_cast,
},
rw lhs,
have ineq1 : abs (∑ (i : ℕ) in f.support, (f.coeff i:ℝ) * x ^ i) ≤ ∑ i in f.support, (abs (f.coeff i:ℝ) * (x ^ i)),
{
have ineq1' := @finset.abs_sum_le_sum_abs ℝ ℕ _ (λ i, (f.coeff i:ℝ) * (x ^ i)) f.support, simp only [] at ineq1',
have eq1 : ∑ (x_1 : ℕ) in f.support, abs (↑(f.coeff x_1) * x ^ x_1) = ∑ (x_1 : ℕ) in f.support, abs (↑(f.coeff x_1)) * x ^ x_1,
{
apply congr_arg, ext, rw abs_mul,
rw @abs_of_nonneg ℝ _ (x^x_1) _, apply pow_nonneg, exact (set.mem_Icc.1 hx).1,
},
rw eq1 at ineq1', exact ineq1',
},
have rhs : f_eval_on_ℝ (f_bar f) t = ∑ i in (f_bar f).support, abs (f.coeff i:ℝ) * t ^ i,
{
rw [f_eval_on_ℝ, polynomial.eval_map, polynomial.eval₂, finsupp.sum],
apply congr_arg, ext, norm_cast,
},
rw rhs,
have ineq2 : ∑ (i : ℕ) in f.support, abs ↑(f.coeff i) * x ^ i ≤ ∑ i in (f_bar f).support, abs (f.coeff i:ℝ) * t ^ i,
{
rw bar_supp, apply finset.sum_le_sum, intros n hn,
suffices : x ^ n ≤ t ^ n,
{
apply mul_le_mul, exact le_refl (abs ↑(polynomial.coeff f n)), exact this, apply pow_nonneg, exact (set.mem_Icc.1 hx).1, exact abs_nonneg ↑(polynomial.coeff f n),
},
apply pow_le_pow_of_le_left, exact (set.mem_Icc.1 hx).1, exact (set.mem_Icc.1 hx).2,
},
exact le_trans ineq1 ineq2,
end
private lemma II_le2' (f : polynomial ℤ) (t : ℝ) (ht : t ≥ 0) : (∫ x in set.Icc 0 t, abs ((t-x).exp * (f_eval_on_ℝ f x))) ≤ t * t.exp * (f_eval_on_ℝ (f_bar f) t) :=
begin
have ineq1 := integral_le_max_times_length ((set.Icc 0 t).indicator (λ x, abs ((t - x).exp * f_eval_on_ℝ f x))) 0 t ht (t.exp * f_eval_on_ℝ (f_bar f) t) _ _,
simp only [sub_zero] at ineq1,
have triv0 : measure_theory.integral ((set.Icc 0 t).indicator ((set.Icc 0 t).indicator (λ (x : ℝ), abs (real.exp (t - x) * f_eval_on_ℝ f x)))) =
measure_theory.integral ((set.Icc 0 t).indicator (λ (x : ℝ), abs (real.exp (t - x) * f_eval_on_ℝ f x))),
{
apply same_integral', ext y, split_ifs, simp [set.indicator, h],
}, rw <-triv0,
have triv : t * (t.exp * f_eval_on_ℝ (f_bar f) t) = t * t.exp * f_eval_on_ℝ (f_bar f) t := by ring,
rw triv at ineq1, exact ineq1,
{
split,
apply measurable.measurable_on, exact is_measurable_Icc,
apply continuous.measurable,
have eq1 : (λ (x : ℝ), abs (real.exp (t - x) * f_eval_on_ℝ f x)) = abs ∘ (λ (x : ℝ), (real.exp (t - x) * f_eval_on_ℝ f x)),
simp only [eq_self_iff_true], rw eq1,
have cont1 := real.continuous_abs,
have cont2 : continuous (λ (x : ℝ), real.exp (t - x) * f_eval_on_ℝ f x),
{
have eq2 : (λ x : ℝ, real.exp (t-x)) = real.exp ∘ (λ x : ℝ, t - x), simp only [],
have cont21 : continuous (λ x : ℝ, real.exp (t-x)), rw eq2,
have cont20 := real.continuous_exp,
have cont201 : continuous (λ (x : ℝ), t - x),
have eq3 : (λ (x : ℝ), t - x) = (λ (x : ℝ), (λ _, t) x - id x), ext, simp only [id], rw eq3,
have cont3 : continuous (λ _ :ℝ, t), exact continuous_const,
have cont3' : continuous (@id ℝ), exact continuous_id,
have cont33 := continuous.sub cont3 cont3', assumption,
exact continuous.comp cont20 cont201,
have cont4 : continuous (λ x , f_eval_on_ℝ f x),
unfold f_eval_on_ℝ, exact polynomial.continuous (polynomial.map ℤembℝ f),
exact continuous.mul cont21 cont4,
},
exact continuous.comp cont1 cont2,
have hmax := @compact.exists_forall_ge _ _ _ _ _ _ (set.Icc 0 t) (compact_Icc) _ (λ (x : ℝ), abs (real.exp (t - x) * f_eval_on_ℝ f x)) _,
choose max hmax using hmax,
generalize hM : abs (real.exp (t - max) * f_eval_on_ℝ f max) = M,
set bound : ℝ -> ℝ := (set.Icc 0 t).indicator (λ _, M) with hbound,
apply @measure_theory.integrable_of_integrable_bound _ _ _ _ ((set.Icc 0 t).indicator (λ (x : ℝ), abs (real.exp (t - x) * f_eval_on_ℝ f x))) bound,
simp [hbound], apply integrable_const_Icc,
rw <-hM, exact abs_nonneg (real.exp (t - max) * f_eval_on_ℝ f max), exact ht,
suffices : ∀ (a : ℝ), ∥(set.Icc 0 t).indicator (λ (x : ℝ), abs (real.exp (t - x) * f_eval_on_ℝ f x)) a∥ ≤ bound a,
exact measure_theory.ae_of_all measure_theory.measure_space.volume this,
intros y, simp only [hbound, set.indicator, set.mem_Icc], rw real.norm_eq_abs, split_ifs, rw abs_abs,
rw <-hM, exact hmax.2 y h, simp only [abs_zero],
use 0, simp only [set.left_mem_Icc], exact ht,
have eq1 : (λ (x : ℝ), abs (real.exp (t - x) * f_eval_on_ℝ f x)) = abs ∘ (λ (x : ℝ), (real.exp (t - x) * f_eval_on_ℝ f x)),
simp only [eq_self_iff_true], rw eq1,
have cont1 := real.continuous_abs,
have cont2 : continuous (λ (x : ℝ), real.exp (t - x) * f_eval_on_ℝ f x),
{
have eq2 : (λ x : ℝ, real.exp (t-x)) = real.exp ∘ (λ x : ℝ, t - x), simp only [],
have cont21 : continuous (λ x : ℝ, real.exp (t-x)), rw eq2,
have cont20 := real.continuous_exp,
have cont201 : continuous (λ (x : ℝ), t - x),
have eq3 : (λ (x : ℝ), t - x) = (λ (x : ℝ), (λ _, t) x - id x), ext, simp only [id], rw eq3,
have cont3 : continuous (λ _ :ℝ, t), exact continuous_const,
have cont3' : continuous (@id ℝ), exact continuous_id,
have cont33 := continuous.sub cont3 cont3', assumption,
exact continuous.comp cont20 cont201,
have cont4 : continuous (λ x , f_eval_on_ℝ f x),
unfold f_eval_on_ℝ, exact polynomial.continuous (polynomial.map ℤembℝ f),
exact continuous.mul cont21 cont4,
},
have cont3 := continuous.comp cont1 cont2,
exact continuous.continuous_on cont3,
},
{
intros x hx, simp only [ge_iff_le], simp only [set.indicator, set.mem_Icc], split_ifs, exact abs_nonneg (real.exp (t - x) * f_eval_on_ℝ f x),
exact abs_nonneg (real.exp (t - x) * f_eval_on_ℝ f x),
},
{
intros x hx, simp only [set.indicator, set.mem_Icc], split_ifs,
rw abs_mul,
have triv : abs (t - x).exp = (t-x).exp, {
apply abs_of_pos, exact (t - x).exp_pos,
},
rw triv,
have ineq1 := f_bar_ineq f t ht x hx,
have ineq2 : (t - x).exp ≤ t.exp,
{
rw real.exp_le_exp, rw sub_le, simp only [sub_self], exact hx.1,
},
have ineq3 : (t - x).exp * abs (f_eval_on_ℝ f x) ≤ t.exp * abs (f_eval_on_ℝ f x),
{
apply mul_le_mul, assumption, exact le_refl (abs (f_eval_on_ℝ f x)), exact abs_nonneg (f_eval_on_ℝ f x),
exact le_of_lt (real.exp_pos t),
},
have ineq4 : t.exp * abs (f_eval_on_ℝ f x) ≤ t.exp * f_eval_on_ℝ (f_bar f) t,
{
apply mul_le_mul, exact le_refl (real.exp t), assumption, exact abs_nonneg (f_eval_on_ℝ f x), exact le_of_lt (real.exp_pos t),
},
exact le_trans ineq3 ineq4, simp only [not_and, not_le] at h,
have rid1 := h hx.1, have rid2 := hx.2, linarith,
},
end
theorem abs_II_le2 (f : polynomial ℤ) (t : ℝ) (ht : t ≥ 0) : abs (II f t ht) ≤ t * t.exp * (f_eval_on_ℝ (f_bar f) t) :=
begin
exact le_trans (abs_II_le1 f t ht) (II_le2' f t ht),
end
|
801ac7e5307bdf607c38e92af47ce6bb77307e6e | 4e3bf8e2b29061457a887ac8889e88fa5aa0e34c | /lean/love09_hoare_logic_exercise_sheet.lean | b62193c84cefcb9c4b1c52ee24e74d3487991a44 | [] | no_license | mukeshtiwari/logical_verification_2019 | 9f964c067a71f65eb8884743273fbeef99e6503d | 16f62717f55ed5b7b87e03ae0134791a9bef9b9a | refs/heads/master | 1,619,158,844,208 | 1,585,139,500,000 | 1,585,139,500,000 | 249,906,380 | 0 | 0 | null | 1,585,118,728,000 | 1,585,118,727,000 | null | UTF-8 | Lean | false | false | 3,980 | lean | /- LoVe Exercise 9: Hoare Logic -/
import .love09_hoare_logic_demo
namespace LoVe
/- Question 1: Program Verification -/
section GAUSS
/- The following WHILE program is intended to compute the Gaussian sum up to
`n`, leaving the result in `r`. -/
def GAUSS : program :=
assign "r" (λs, 0) ;;
while (λs, s "n" ≠ 0)
(assign "r" (λs, s "r" + s "n") ;;
assign "n" (λs, s "n" - 1))
/- The summation function: -/
def sum_upto : ℕ → ℕ
| 0 := 0
| (n + 1) := n + 1 + sum_upto n
/- 1.1. Prove the correctness of `GAUSS`, using `vcg`. The main challenge is to
figure out which invariant to use for the while loop. The invariant should
capture both the work that has been done already (the intermediate result) and
the work that remains to be done. -/
lemma GAUSS_correct (n : ℕ) :
{* λs, s "n" = n *} GAUSS {* λs, s "r" = sum_upto n *} :=
sorry
end GAUSS
section MUL
/- The following WHILE program is intended to compute the product of `n` and
`m`, leaving the result in `r`. -/
def MUL : program :=
assign "r" (λs, 0) ;;
while (λs, s "n" ≠ 0)
(assign "r" (λs, s "r" + s "m") ;;
assign "n" (λs, s "n" - 1))
/- 1.2 Prove the correctness of `MUL`, using `vcg`.
Hint: If a variable `x` does not change in a program, it might be useful to
record this in the invariant, by adding a conjunct `s "x" = x`. -/
lemma MUL_correct (n m : ℕ) :
{* λs, s "n" = n ∧ s "m" = m *} MUL {* λs, s "r" = n * m *} :=
sorry
end MUL
/- Question 2: Hoare Triples for Total Correctness -/
def total_hoare (P : state → Prop) (p : program) (Q : state → Prop) : Prop :=
∀s, P s → ∃t, (p, s) ⟹ t ∧ Q t
notation `[* ` P : 1 ` *] ` p : 1 ` [* ` Q : 1 ` *]` := total_hoare P p Q
namespace total_hoare
variables {P P' P₁ P₂ P₃ Q Q' : state → Prop} {x : string}
variables {S S₀ S₁ S₂ : program}
variables {b : state → Prop} {a : state → ℕ} {s s₀ s₁ s₂ t u : state}
/- 2.1. Prove the consequence rule. -/
lemma consequence (h : [* P *] S [* Q *]) (hp : ∀s, P' s → P s)
(hq : ∀s, Q s → Q' s) :
[* P' *] S [* Q' *] :=
sorry
/- 2.2. Prove the rule for `skip`. -/
lemma skip_intro :
[* P *] skip [* P *] :=
sorry
/- 2.3. Prove the rule for `assign`. -/
lemma assign_intro (P : state → Prop) :
[* λs, P (s{x ↦ a s}) *] assign x a [* P *] :=
sorry
/- 2.4. Prove the rule for `seq`. -/
lemma seq_intro (h₁ : [* P₁ *] S₁ [* P₂ *])
(h₂ : [* P₂ *] S₂ [* P₃ *]) :
[* P₁ *] S₁ ;; S₂ [* P₃ *] :=
sorry
/- 2.5 **optional**. Prove the rule for `ite`. This requires `b s ∨ ¬ b s`.
`classical.em (b s)` provides a proof, even when `b` is not decidable. -/
lemma ite_intro (h₁ : [* λs, P s ∧ b s *] S₁ [* Q *])
(h₂ : [* λs, P s ∧ ¬ b s *] S₂ [* Q *]) :
[* P *] ite b S₁ S₂ [* Q *] :=
sorry
/- 2.6 **optional**. Try to prove the rule for `while`.
Before we prove our final goal, we introduce an auxiliary proof. This proof
requires well-founded induction. When using `while_intro.aux` as induction
hypothesis we recommend to do it directly after proving that the argument is
less than `n`:
have ih : ∃u, (while c p, t) ⟹ u ∧ I u ∧ ¬ c u :=
have M < n := …,
-- necessary for Lean to figure out the well-founded induction
while_intro.aux M …,
Similar to `ite`, this requires `c s ∨ ¬ c s`. `classical.em (c s)` provides a
proof. -/
lemma while_intro.aux
(I : state → Prop)
(V : state → ℕ)
(h_inv : ∀n, [* λs, I s ∧ b s ∧ V s = n *] S [* λs, I s ∧ V s < n *]) :
∀n s, V s = n → I s → ∃t, (while b S, s) ⟹ t ∧ I t ∧ ¬ b t
| n s V_eq hs :=
sorry
lemma while_intro
(I : state → Prop) -- invariant in the loop
(V : state → ℕ) -- variant in the loop body (a.k.a. termination measure)
(h_inv : ∀n, [* λs, I s ∧ b s ∧ V s = n *] S [* λs, I s ∧ V s < n *]) :
[* I *] while b S [* λs, I s ∧ ¬ b s *] :=
sorry
end total_hoare
end LoVe
|
497bba72618f7f517e02e559da345fcef992361d | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/topology/metric_space/basic.lean | c219fc00273a78cb59daa9e9ac7472cf65e8d575 | [
"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 | 140,849 | lean | /-
Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel
-/
import tactic.positivity
import topology.algebra.order.compact
import topology.metric_space.emetric_space
import topology.bornology.constructions
/-!
# Metric spaces
This file defines metric spaces. Many definitions and theorems expected
on metric spaces are already introduced on uniform spaces and topological spaces.
For example: open and closed sets, compactness, completeness, continuity and uniform continuity
## Main definitions
* `has_dist α`: Endows a space `α` with a function `dist a b`.
* `pseudo_metric_space α`: A space endowed with a distance function, which can
be zero even if the two elements are non-equal.
* `metric.ball x ε`: The set of all points `y` with `dist y x < ε`.
* `metric.bounded s`: Whether a subset of a `pseudo_metric_space` is bounded.
* `metric_space α`: A `pseudo_metric_space` with the guarantee `dist x y = 0 → x = y`.
Additional useful definitions:
* `nndist a b`: `dist` as a function to the non-negative reals.
* `metric.closed_ball x ε`: The set of all points `y` with `dist y x ≤ ε`.
* `metric.sphere x ε`: The set of all points `y` with `dist y x = ε`.
* `proper_space α`: A `pseudo_metric_space` where all closed balls are compact.
* `metric.diam s` : The `supr` of the distances of members of `s`.
Defined in terms of `emetric.diam`, for better handling of the case when it should be infinite.
TODO (anyone): Add "Main results" section.
## Implementation notes
Since a lot of elementary properties don't require `eq_of_dist_eq_zero` we start setting up the
theory of `pseudo_metric_space`, where we don't require `dist x y = 0 → x = y` and we specialize
to `metric_space` at the end.
## Tags
metric, pseudo_metric, dist
-/
open set filter topological_space bornology
open_locale uniformity topological_space big_operators filter nnreal ennreal
universes u v w
variables {α : Type u} {β : Type v} {X ι : Type*}
/-- Construct a uniform structure core from a distance function and metric space axioms.
This is a technical construction that can be immediately used to construct a uniform structure
from a distance function and metric space axioms but is also useful when discussing
metrizable topologies, see `pseudo_metric_space.of_metrizable`. -/
def uniform_space.core_of_dist {α : Type*} (dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space.core α :=
{ uniformity := (⨅ ε>0, 𝓟 {p:α×α | dist p.1 p.2 < ε}),
refl := le_infi $ assume ε, le_infi $
by simp [set.subset_def, id_rel, dist_self, (>)] {contextual := tt},
comp := le_infi $ assume ε, le_infi $ assume h, lift'_le
(mem_infi_of_mem (ε / 2) $ mem_infi_of_mem (div_pos h zero_lt_two) (subset.refl _)) $
have ∀ (a b c : α), dist a c < ε / 2 → dist c b < ε / 2 → dist a b < ε,
from assume a b c hac hcb,
calc dist a b ≤ dist a c + dist c b : dist_triangle _ _ _
... < ε / 2 + ε / 2 : add_lt_add hac hcb
... = ε : by rw [div_add_div_same, add_self_div_two],
by simpa [comp_rel],
symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h,
tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [dist_comm] }
/-- Construct a uniform structure from a distance function and metric space axioms -/
def uniform_space_of_dist
(dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space α :=
uniform_space.of_core (uniform_space.core_of_dist dist dist_self dist_comm dist_triangle)
/-- This is an internal lemma used to construct a bornology from a metric in `bornology.of_dist`. -/
private lemma bounded_iff_aux {α : Type*} (dist : α → α → ℝ)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z)
(s : set α) (a : α) :
(∃ c, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ c) ↔ (∃ r, ∀ ⦃x⦄, x ∈ s → dist x a ≤ r) :=
begin
split; rintro ⟨C, hC⟩,
{ rcases s.eq_empty_or_nonempty with rfl | ⟨x, hx⟩,
{ exact ⟨0, by simp⟩ },
{ exact ⟨C + dist x a, λ y hy,
(dist_triangle y x a).trans (add_le_add_right (hC hy hx) _)⟩ } },
{ exact ⟨C + C, λ x hx y hy,
(dist_triangle x a y).trans (add_le_add (hC hx) (by {rw dist_comm, exact hC hy}))⟩ }
end
/-- Construct a bornology from a distance function and metric space axioms. -/
def bornology.of_dist {α : Type*} (dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) :
bornology α :=
bornology.of_bounded
{ s : set α | ∃ C, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ C }
⟨0, λ x hx y, hx.elim⟩
(λ s ⟨c, hc⟩ t h, ⟨c, λ x hx y hy, hc (h hx) (h hy)⟩)
(λ s hs t ht,
begin
rcases s.eq_empty_or_nonempty with rfl | ⟨z, hz⟩,
{ exact (empty_union t).symm ▸ ht },
{ simp only [λ u, bounded_iff_aux dist dist_comm dist_triangle u z] at hs ht ⊢,
rcases ⟨hs, ht⟩ with ⟨⟨r₁, hr₁⟩, ⟨r₂, hr₂⟩⟩,
exact ⟨max r₁ r₂, λ x hx, or.elim hx
(λ hx', (hr₁ hx').trans (le_max_left _ _))
(λ hx', (hr₂ hx').trans (le_max_right _ _))⟩ }
end)
(λ z, ⟨0, λ x hx y hy,
by { rw [eq_of_mem_singleton hx, eq_of_mem_singleton hy], exact (dist_self z).le }⟩)
/-- The distance function (given an ambient metric space on `α`), which returns
a nonnegative real number `dist x y` given `x y : α`. -/
@[ext] class has_dist (α : Type*) := (dist : α → α → ℝ)
export has_dist (dist)
-- the uniform structure and the emetric space structure are embedded in the metric space structure
-- to avoid instance diamond issues. See Note [forgetful inheritance].
/-- This is an internal lemma used inside the default of `pseudo_metric_space.edist`. -/
private theorem pseudo_metric_space.dist_nonneg' {α} {x y : α} (dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z): 0 ≤ dist x y :=
have 2 * dist x y ≥ 0,
from calc 2 * dist x y = dist x y + dist y x : by rw [dist_comm x y, two_mul]
... ≥ 0 : by rw ← dist_self x; apply dist_triangle,
nonneg_of_mul_nonneg_right this zero_lt_two
/-- This tactic is used to populate `pseudo_metric_space.edist_dist` when the default `edist` is
used. -/
protected meta def pseudo_metric_space.edist_dist_tac : tactic unit :=
tactic.intros >> `[exact (ennreal.of_real_eq_coe_nnreal _).symm <|> control_laws_tac]
/-- Pseudo metric and Metric spaces
A pseudo metric space is endowed with a distance for which the requirement `d(x,y)=0 → x = y` might
not hold. A metric space is a pseudo metric space such that `d(x,y)=0 → x = y`.
Each pseudo metric space induces a canonical `uniform_space` and hence a canonical
`topological_space` This is enforced in the type class definition, by extending the `uniform_space`
structure. When instantiating a `pseudo_metric_space` structure, the uniformity fields are not
necessary, they will be filled in by default. In the same way, each (pseudo) metric space induces a
(pseudo) emetric space structure. It is included in the structure, but filled in by default.
-/
class pseudo_metric_space (α : Type u) extends has_dist α : Type u :=
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z)
(edist : α → α → ℝ≥0∞ := λ x y,
@coe (ℝ≥0) _ _ ⟨dist x y, pseudo_metric_space.dist_nonneg' _ ‹_› ‹_› ‹_›⟩)
(edist_dist : ∀ x y : α,
edist x y = ennreal.of_real (dist x y) . pseudo_metric_space.edist_dist_tac)
(to_uniform_space : uniform_space α := uniform_space_of_dist dist dist_self dist_comm dist_triangle)
(uniformity_dist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | dist p.1 p.2 < ε} . control_laws_tac)
(to_bornology : bornology α := bornology.of_dist dist dist_self dist_comm dist_triangle)
(cobounded_sets : (bornology.cobounded α).sets =
{ s | ∃ C, ∀ ⦃x⦄, x ∈ sᶜ → ∀ ⦃y⦄, y ∈ sᶜ → dist x y ≤ C } . control_laws_tac)
/-- Two pseudo metric space structures with the same distance function coincide. -/
@[ext] lemma pseudo_metric_space.ext {α : Type*} {m m' : pseudo_metric_space α}
(h : m.to_has_dist = m'.to_has_dist) : m = m' :=
begin
unfreezingI { rcases m, rcases m' },
dsimp at h,
unfreezingI { subst h },
congr,
{ ext x y : 2,
dsimp at m_edist_dist m'_edist_dist,
simp [m_edist_dist, m'_edist_dist] },
{ dsimp at m_uniformity_dist m'_uniformity_dist,
rw ← m'_uniformity_dist at m_uniformity_dist,
exact uniform_space_eq m_uniformity_dist },
{ ext1,
dsimp at m_cobounded_sets m'_cobounded_sets,
rw ← m'_cobounded_sets at m_cobounded_sets,
exact filter_eq m_cobounded_sets }
end
variables [pseudo_metric_space α]
attribute [priority 100, instance] pseudo_metric_space.to_uniform_space
attribute [priority 100, instance] pseudo_metric_space.to_bornology
@[priority 200] -- see Note [lower instance priority]
instance pseudo_metric_space.to_has_edist : has_edist α := ⟨pseudo_metric_space.edist⟩
/-- Construct a pseudo-metric space structure whose underlying topological space structure
(definitionally) agrees which a pre-existing topology which is compatible with a given distance
function. -/
def pseudo_metric_space.of_metrizable {α : Type*} [topological_space α] (dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z)
(H : ∀ s : set α, is_open s ↔ ∀ x ∈ s, ∃ ε > 0, ∀ y, dist x y < ε → y ∈ s) :
pseudo_metric_space α :=
{ dist := dist,
dist_self := dist_self,
dist_comm := dist_comm,
dist_triangle := dist_triangle,
to_uniform_space := { is_open_uniformity := begin
dsimp only [uniform_space.core_of_dist],
intros s,
change is_open s ↔ _,
rw H s,
refine forall₂_congr (λ x x_in, _),
erw (has_basis_binfi_principal _ nonempty_Ioi).mem_iff,
{ refine exists₂_congr (λ ε ε_pos, _),
simp only [prod.forall, set_of_subset_set_of],
split,
{ rintros h _ y H rfl,
exact h y H },
{ intros h y hxy,
exact h _ _ hxy rfl } },
{ exact λ r (hr : 0 < r) p (hp : 0 < p), ⟨min r p, lt_min hr hp,
λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_left r p),
λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_right r p)⟩ },
{ apply_instance }
end,
..uniform_space.core_of_dist dist dist_self dist_comm dist_triangle },
uniformity_dist := rfl,
to_bornology := bornology.of_dist dist dist_self dist_comm dist_triangle,
cobounded_sets := rfl }
@[simp] theorem dist_self (x : α) : dist x x = 0 := pseudo_metric_space.dist_self x
theorem dist_comm (x y : α) : dist x y = dist y x := pseudo_metric_space.dist_comm x y
theorem edist_dist (x y : α) : edist x y = ennreal.of_real (dist x y) :=
pseudo_metric_space.edist_dist x y
theorem dist_triangle (x y z : α) : dist x z ≤ dist x y + dist y z :=
pseudo_metric_space.dist_triangle x y z
theorem dist_triangle_left (x y z : α) : dist x y ≤ dist z x + dist z y :=
by rw dist_comm z; apply dist_triangle
theorem dist_triangle_right (x y z : α) : dist x y ≤ dist x z + dist y z :=
by rw dist_comm y; apply dist_triangle
lemma dist_triangle4 (x y z w : α) :
dist x w ≤ dist x y + dist y z + dist z w :=
calc dist x w ≤ dist x z + dist z w : dist_triangle x z w
... ≤ (dist x y + dist y z) + dist z w : add_le_add_right (dist_triangle x y z) _
lemma dist_triangle4_left (x₁ y₁ x₂ y₂ : α) :
dist x₂ y₂ ≤ dist x₁ y₁ + (dist x₁ x₂ + dist y₁ y₂) :=
by { rw [add_left_comm, dist_comm x₁, ← add_assoc], apply dist_triangle4 }
lemma dist_triangle4_right (x₁ y₁ x₂ y₂ : α) :
dist x₁ y₁ ≤ dist x₁ x₂ + dist y₁ y₂ + dist x₂ y₂ :=
by { rw [add_right_comm, dist_comm y₁], apply dist_triangle4 }
/-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/
lemma dist_le_Ico_sum_dist (f : ℕ → α) {m n} (h : m ≤ n) :
dist (f m) (f n) ≤ ∑ i in finset.Ico m n, dist (f i) (f (i + 1)) :=
begin
revert n,
apply nat.le_induction,
{ simp only [finset.sum_empty, finset.Ico_self, dist_self] },
{ assume n hn hrec,
calc dist (f m) (f (n+1)) ≤ dist (f m) (f n) + dist _ _ : dist_triangle _ _ _
... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add hrec le_rfl
... = ∑ i in finset.Ico m (n+1), _ :
by rw [nat.Ico_succ_right_eq_insert_Ico hn, finset.sum_insert, add_comm]; simp }
end
/-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/
lemma dist_le_range_sum_dist (f : ℕ → α) (n : ℕ) :
dist (f 0) (f n) ≤ ∑ i in finset.range n, dist (f i) (f (i + 1)) :=
nat.Ico_zero_eq_range ▸ dist_le_Ico_sum_dist f (nat.zero_le n)
/-- A version of `dist_le_Ico_sum_dist` with each intermediate distance replaced
with an upper estimate. -/
lemma dist_le_Ico_sum_of_dist_le {f : ℕ → α} {m n} (hmn : m ≤ n)
{d : ℕ → ℝ} (hd : ∀ {k}, m ≤ k → k < n → dist (f k) (f (k + 1)) ≤ d k) :
dist (f m) (f n) ≤ ∑ i in finset.Ico m n, d i :=
le_trans (dist_le_Ico_sum_dist f hmn) $
finset.sum_le_sum $ λ k hk, hd (finset.mem_Ico.1 hk).1 (finset.mem_Ico.1 hk).2
/-- A version of `dist_le_range_sum_dist` with each intermediate distance replaced
with an upper estimate. -/
lemma dist_le_range_sum_of_dist_le {f : ℕ → α} (n : ℕ)
{d : ℕ → ℝ} (hd : ∀ {k}, k < n → dist (f k) (f (k + 1)) ≤ d k) :
dist (f 0) (f n) ≤ ∑ i in finset.range n, d i :=
nat.Ico_zero_eq_range ▸ dist_le_Ico_sum_of_dist_le (zero_le n) (λ _ _, hd)
theorem swap_dist : function.swap (@dist α _) = dist :=
by funext x y; exact dist_comm _ _
theorem abs_dist_sub_le (x y z : α) : |dist x z - dist y z| ≤ dist x y :=
abs_sub_le_iff.2
⟨sub_le_iff_le_add.2 (dist_triangle _ _ _),
sub_le_iff_le_add.2 (dist_triangle_left _ _ _)⟩
theorem dist_nonneg {x y : α} : 0 ≤ dist x y :=
pseudo_metric_space.dist_nonneg' dist dist_self dist_comm dist_triangle
section
open tactic tactic.positivity
/-- Extension for the `positivity` tactic: distances are nonnegative. -/
@[positivity]
meta def _root_.tactic.positivity_dist : expr → tactic strictness
| `(dist %%a %%b) := nonnegative <$> mk_app ``dist_nonneg [a, b]
| _ := failed
end
@[simp] theorem abs_dist {a b : α} : |dist a b| = dist a b :=
abs_of_nonneg dist_nonneg
/-- A version of `has_dist` that takes value in `ℝ≥0`. -/
class has_nndist (α : Type*) := (nndist : α → α → ℝ≥0)
export has_nndist (nndist)
/-- Distance as a nonnegative real number. -/
@[priority 100] -- see Note [lower instance priority]
instance pseudo_metric_space.to_has_nndist : has_nndist α := ⟨λ a b, ⟨dist a b, dist_nonneg⟩⟩
/--Express `nndist` in terms of `edist`-/
lemma nndist_edist (x y : α) : nndist x y = (edist x y).to_nnreal :=
by simp [nndist, edist_dist, real.to_nnreal, max_eq_left dist_nonneg, ennreal.of_real]
/--Express `edist` in terms of `nndist`-/
lemma edist_nndist (x y : α) : edist x y = ↑(nndist x y) :=
by { simpa only [edist_dist, ennreal.of_real_eq_coe_nnreal dist_nonneg] }
@[simp, norm_cast] lemma coe_nnreal_ennreal_nndist (x y : α) : ↑(nndist x y) = edist x y :=
(edist_nndist x y).symm
@[simp, norm_cast] lemma edist_lt_coe {x y : α} {c : ℝ≥0} :
edist x y < c ↔ nndist x y < c :=
by rw [edist_nndist, ennreal.coe_lt_coe]
@[simp, norm_cast] lemma edist_le_coe {x y : α} {c : ℝ≥0} :
edist x y ≤ c ↔ nndist x y ≤ c :=
by rw [edist_nndist, ennreal.coe_le_coe]
/--In a pseudometric space, the extended distance is always finite-/
lemma edist_lt_top {α : Type*} [pseudo_metric_space α] (x y : α) : edist x y < ⊤ :=
(edist_dist x y).symm ▸ ennreal.of_real_lt_top
/--In a pseudometric space, the extended distance is always finite-/
lemma edist_ne_top (x y : α) : edist x y ≠ ⊤ := (edist_lt_top x y).ne
/--`nndist x x` vanishes-/
@[simp] lemma nndist_self (a : α) : nndist a a = 0 := (nnreal.coe_eq_zero _).1 (dist_self a)
/--Express `dist` in terms of `nndist`-/
lemma dist_nndist (x y : α) : dist x y = ↑(nndist x y) := rfl
@[simp, norm_cast] lemma coe_nndist (x y : α) : ↑(nndist x y) = dist x y :=
(dist_nndist x y).symm
@[simp, norm_cast] lemma dist_lt_coe {x y : α} {c : ℝ≥0} :
dist x y < c ↔ nndist x y < c :=
iff.rfl
@[simp, norm_cast] lemma dist_le_coe {x y : α} {c : ℝ≥0} :
dist x y ≤ c ↔ nndist x y ≤ c :=
iff.rfl
@[simp] lemma edist_lt_of_real {x y : α} {r : ℝ} : edist x y < ennreal.of_real r ↔ dist x y < r :=
by rw [edist_dist, ennreal.of_real_lt_of_real_iff_of_nonneg dist_nonneg]
@[simp] lemma edist_le_of_real {x y : α} {r : ℝ} (hr : 0 ≤ r) :
edist x y ≤ ennreal.of_real r ↔ dist x y ≤ r :=
by rw [edist_dist, ennreal.of_real_le_of_real_iff hr]
/--Express `nndist` in terms of `dist`-/
lemma nndist_dist (x y : α) : nndist x y = real.to_nnreal (dist x y) :=
by rw [dist_nndist, real.to_nnreal_coe]
theorem nndist_comm (x y : α) : nndist x y = nndist y x :=
by simpa only [dist_nndist, nnreal.coe_eq] using dist_comm x y
/--Triangle inequality for the nonnegative distance-/
theorem nndist_triangle (x y z : α) : nndist x z ≤ nndist x y + nndist y z :=
dist_triangle _ _ _
theorem nndist_triangle_left (x y z : α) : nndist x y ≤ nndist z x + nndist z y :=
dist_triangle_left _ _ _
theorem nndist_triangle_right (x y z : α) : nndist x y ≤ nndist x z + nndist y z :=
dist_triangle_right _ _ _
/--Express `dist` in terms of `edist`-/
lemma dist_edist (x y : α) : dist x y = (edist x y).to_real :=
by rw [edist_dist, ennreal.to_real_of_real (dist_nonneg)]
namespace metric
/- instantiate pseudometric space as a topology -/
variables {x y z : α} {δ ε ε₁ ε₂ : ℝ} {s : set α}
/-- `ball x ε` is the set of all points `y` with `dist y x < ε` -/
def ball (x : α) (ε : ℝ) : set α := {y | dist y x < ε}
@[simp] theorem mem_ball : y ∈ ball x ε ↔ dist y x < ε := iff.rfl
theorem mem_ball' : y ∈ ball x ε ↔ dist x y < ε := by rw [dist_comm, mem_ball]
theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε :=
dist_nonneg.trans_lt hy
theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε :=
show dist x x < ε, by rw dist_self; assumption
@[simp] lemma nonempty_ball : (ball x ε).nonempty ↔ 0 < ε :=
⟨λ ⟨x, hx⟩, pos_of_mem_ball hx, λ h, ⟨x, mem_ball_self h⟩⟩
@[simp] lemma ball_eq_empty : ball x ε = ∅ ↔ ε ≤ 0 :=
by rw [← not_nonempty_iff_eq_empty, nonempty_ball, not_lt]
@[simp] lemma ball_zero : ball x 0 = ∅ :=
by rw [ball_eq_empty]
/-- If a point belongs to an open ball, then there is a strictly smaller radius whose ball also
contains it.
See also `exists_lt_subset_ball`. -/
lemma exists_lt_mem_ball_of_mem_ball (h : x ∈ ball y ε) : ∃ ε' < ε, x ∈ ball y ε' :=
begin
simp only [mem_ball] at h ⊢,
exact ⟨(ε + dist x y) / 2, by linarith, by linarith⟩,
end
lemma ball_eq_ball (ε : ℝ) (x : α) :
uniform_space.ball x {p | dist p.2 p.1 < ε} = metric.ball x ε := rfl
lemma ball_eq_ball' (ε : ℝ) (x : α) :
uniform_space.ball x {p | dist p.1 p.2 < ε} = metric.ball x ε :=
by { ext, simp [dist_comm, uniform_space.ball] }
@[simp] lemma Union_ball_nat (x : α) : (⋃ n : ℕ, ball x n) = univ :=
Union_eq_univ_iff.2 $ λ y, exists_nat_gt (dist y x)
@[simp] lemma Union_ball_nat_succ (x : α) : (⋃ n : ℕ, ball x (n + 1)) = univ :=
Union_eq_univ_iff.2 $ λ y, (exists_nat_gt (dist y x)).imp $ λ n hn,
hn.trans (lt_add_one _)
/-- `closed_ball x ε` is the set of all points `y` with `dist y x ≤ ε` -/
def closed_ball (x : α) (ε : ℝ) := {y | dist y x ≤ ε}
@[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ dist y x ≤ ε := iff.rfl
theorem mem_closed_ball' : y ∈ closed_ball x ε ↔ dist x y ≤ ε := by rw [dist_comm, mem_closed_ball]
/-- `sphere x ε` is the set of all points `y` with `dist y x = ε` -/
def sphere (x : α) (ε : ℝ) := {y | dist y x = ε}
@[simp] theorem mem_sphere : y ∈ sphere x ε ↔ dist y x = ε := iff.rfl
theorem mem_sphere' : y ∈ sphere x ε ↔ dist x y = ε := by rw [dist_comm, mem_sphere]
theorem ne_of_mem_sphere (h : y ∈ sphere x ε) (hε : ε ≠ 0) : y ≠ x :=
by { contrapose! hε, symmetry, simpa [hε] using h }
theorem sphere_eq_empty_of_subsingleton [subsingleton α] (hε : ε ≠ 0) :
sphere x ε = ∅ :=
set.eq_empty_iff_forall_not_mem.mpr $ λ y hy, ne_of_mem_sphere hy hε (subsingleton.elim _ _)
theorem sphere_is_empty_of_subsingleton [subsingleton α] (hε : ε ≠ 0) :
is_empty (sphere x ε) :=
by simp only [sphere_eq_empty_of_subsingleton hε, set.has_emptyc.emptyc.is_empty α]
theorem mem_closed_ball_self (h : 0 ≤ ε) : x ∈ closed_ball x ε :=
show dist x x ≤ ε, by rw dist_self; assumption
@[simp] lemma nonempty_closed_ball : (closed_ball x ε).nonempty ↔ 0 ≤ ε :=
⟨λ ⟨x, hx⟩, dist_nonneg.trans hx, λ h, ⟨x, mem_closed_ball_self h⟩⟩
@[simp] lemma closed_ball_eq_empty : closed_ball x ε = ∅ ↔ ε < 0 :=
by rw [← not_nonempty_iff_eq_empty, nonempty_closed_ball, not_le]
theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε :=
assume y (hy : _ < _), le_of_lt hy
theorem sphere_subset_closed_ball : sphere x ε ⊆ closed_ball x ε :=
λ y, le_of_eq
lemma closed_ball_disjoint_ball (h : δ + ε ≤ dist x y) : disjoint (closed_ball x δ) (ball y ε) :=
set.disjoint_left.mpr $
λ a ha1 ha2, (h.trans $ dist_triangle_left _ _ _).not_lt $ add_lt_add_of_le_of_lt ha1 ha2
lemma ball_disjoint_closed_ball (h : δ + ε ≤ dist x y) : disjoint (ball x δ) (closed_ball y ε) :=
(closed_ball_disjoint_ball $ by rwa [add_comm, dist_comm]).symm
lemma ball_disjoint_ball (h : δ + ε ≤ dist x y) : disjoint (ball x δ) (ball y ε) :=
(closed_ball_disjoint_ball h).mono_left ball_subset_closed_ball
lemma closed_ball_disjoint_closed_ball (h : δ + ε < dist x y) :
disjoint (closed_ball x δ) (closed_ball y ε) :=
set.disjoint_left.mpr $
λ a ha1 ha2, h.not_le $ (dist_triangle_left _ _ _).trans $ add_le_add ha1 ha2
theorem sphere_disjoint_ball : disjoint (sphere x ε) (ball x ε) :=
set.disjoint_left.mpr $ λ y hy₁ hy₂, absurd hy₁ $ ne_of_lt hy₂
@[simp] theorem ball_union_sphere : ball x ε ∪ sphere x ε = closed_ball x ε :=
set.ext $ λ y, (@le_iff_lt_or_eq ℝ _ _ _).symm
@[simp] theorem sphere_union_ball : sphere x ε ∪ ball x ε = closed_ball x ε :=
by rw [union_comm, ball_union_sphere]
@[simp] theorem closed_ball_diff_sphere : closed_ball x ε \ sphere x ε = ball x ε :=
by rw [← ball_union_sphere, set.union_diff_cancel_right sphere_disjoint_ball.symm.le_bot]
@[simp] theorem closed_ball_diff_ball : closed_ball x ε \ ball x ε = sphere x ε :=
by rw [← ball_union_sphere, set.union_diff_cancel_left sphere_disjoint_ball.symm.le_bot]
theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε :=
by rw [mem_ball', mem_ball]
theorem mem_closed_ball_comm : x ∈ closed_ball y ε ↔ y ∈ closed_ball x ε :=
by rw [mem_closed_ball', mem_closed_ball]
theorem mem_sphere_comm : x ∈ sphere y ε ↔ y ∈ sphere x ε :=
by rw [mem_sphere', mem_sphere]
theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ :=
λ y (yx : _ < ε₁), lt_of_lt_of_le yx h
lemma closed_ball_eq_bInter_ball : closed_ball x ε = ⋂ δ > ε, ball x δ :=
by ext y; rw [mem_closed_ball, ← forall_lt_iff_le', mem_Inter₂]; refl
lemma ball_subset_ball' (h : ε₁ + dist x y ≤ ε₂) : ball x ε₁ ⊆ ball y ε₂ :=
λ z hz, calc
dist z y ≤ dist z x + dist x y : dist_triangle _ _ _
... < ε₁ + dist x y : add_lt_add_right hz _
... ≤ ε₂ : h
theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) :
closed_ball x ε₁ ⊆ closed_ball x ε₂ :=
λ y (yx : _ ≤ ε₁), le_trans yx h
lemma closed_ball_subset_closed_ball' (h : ε₁ + dist x y ≤ ε₂) :
closed_ball x ε₁ ⊆ closed_ball y ε₂ :=
λ z hz, calc
dist z y ≤ dist z x + dist x y : dist_triangle _ _ _
... ≤ ε₁ + dist x y : add_le_add_right hz _
... ≤ ε₂ : h
theorem closed_ball_subset_ball (h : ε₁ < ε₂) :
closed_ball x ε₁ ⊆ ball x ε₂ :=
λ y (yh : dist y x ≤ ε₁), lt_of_le_of_lt yh h
lemma closed_ball_subset_ball' (h : ε₁ + dist x y < ε₂) :
closed_ball x ε₁ ⊆ ball y ε₂ :=
λ z hz, calc
dist z y ≤ dist z x + dist x y : dist_triangle _ _ _
... ≤ ε₁ + dist x y : add_le_add_right hz _
... < ε₂ : h
lemma dist_le_add_of_nonempty_closed_ball_inter_closed_ball
(h : (closed_ball x ε₁ ∩ closed_ball y ε₂).nonempty) :
dist x y ≤ ε₁ + ε₂ :=
let ⟨z, hz⟩ := h in calc
dist x y ≤ dist z x + dist z y : dist_triangle_left _ _ _
... ≤ ε₁ + ε₂ : add_le_add hz.1 hz.2
lemma dist_lt_add_of_nonempty_closed_ball_inter_ball (h : (closed_ball x ε₁ ∩ ball y ε₂).nonempty) :
dist x y < ε₁ + ε₂ :=
let ⟨z, hz⟩ := h in calc
dist x y ≤ dist z x + dist z y : dist_triangle_left _ _ _
... < ε₁ + ε₂ : add_lt_add_of_le_of_lt hz.1 hz.2
lemma dist_lt_add_of_nonempty_ball_inter_closed_ball (h : (ball x ε₁ ∩ closed_ball y ε₂).nonempty) :
dist x y < ε₁ + ε₂ :=
begin
rw inter_comm at h,
rw [add_comm, dist_comm],
exact dist_lt_add_of_nonempty_closed_ball_inter_ball h
end
lemma dist_lt_add_of_nonempty_ball_inter_ball (h : (ball x ε₁ ∩ ball y ε₂).nonempty) :
dist x y < ε₁ + ε₂ :=
dist_lt_add_of_nonempty_closed_ball_inter_ball $
h.mono (inter_subset_inter ball_subset_closed_ball subset.rfl)
@[simp] lemma Union_closed_ball_nat (x : α) : (⋃ n : ℕ, closed_ball x n) = univ :=
Union_eq_univ_iff.2 $ λ y, exists_nat_ge (dist y x)
lemma Union_inter_closed_ball_nat (s : set α) (x : α) :
(⋃ (n : ℕ), s ∩ closed_ball x n) = s :=
by rw [← inter_Union, Union_closed_ball_nat, inter_univ]
theorem ball_subset (h : dist x y ≤ ε₂ - ε₁) : ball x ε₁ ⊆ ball y ε₂ :=
λ z zx, by rw ← add_sub_cancel'_right ε₁ ε₂; exact
lt_of_le_of_lt (dist_triangle z x y) (add_lt_add_of_lt_of_le zx h)
theorem ball_half_subset (y) (h : y ∈ ball x (ε / 2)) : ball y (ε / 2) ⊆ ball x ε :=
ball_subset $ by rw sub_self_div_two; exact le_of_lt h
theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε :=
⟨_, sub_pos.2 h, ball_subset $ by rw sub_sub_self⟩
/-- If a property holds for all points in closed balls of arbitrarily large radii, then it holds for
all points. -/
lemma forall_of_forall_mem_closed_ball (p : α → Prop) (x : α)
(H : ∃ᶠ (R : ℝ) in at_top, ∀ y ∈ closed_ball x R, p y) (y : α) :
p y :=
begin
obtain ⟨R, hR, h⟩ : ∃ (R : ℝ) (H : dist y x ≤ R), ∀ (z : α), z ∈ closed_ball x R → p z :=
frequently_iff.1 H (Ici_mem_at_top (dist y x)),
exact h _ hR
end
/-- If a property holds for all points in balls of arbitrarily large radii, then it holds for all
points. -/
lemma forall_of_forall_mem_ball (p : α → Prop) (x : α)
(H : ∃ᶠ (R : ℝ) in at_top, ∀ y ∈ ball x R, p y) (y : α) :
p y :=
begin
obtain ⟨R, hR, h⟩ : ∃ (R : ℝ) (H : dist y x < R), ∀ (z : α), z ∈ ball x R → p z :=
frequently_iff.1 H (Ioi_mem_at_top (dist y x)),
exact h _ hR
end
theorem is_bounded_iff {s : set α} :
is_bounded s ↔ ∃ C : ℝ, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ C :=
by rw [is_bounded_def, ← filter.mem_sets, (@pseudo_metric_space.cobounded_sets α _).out,
mem_set_of_eq, compl_compl]
theorem is_bounded_iff_eventually {s : set α} :
is_bounded s ↔ ∀ᶠ C in at_top, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ C :=
is_bounded_iff.trans ⟨λ ⟨C, h⟩, eventually_at_top.2 ⟨C, λ C' hC' x hx y hy, (h hx hy).trans hC'⟩,
eventually.exists⟩
theorem is_bounded_iff_exists_ge {s : set α} (c : ℝ) :
is_bounded s ↔ ∃ C, c ≤ C ∧ ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ C :=
⟨λ h, ((eventually_ge_at_top c).and (is_bounded_iff_eventually.1 h)).exists,
λ h, is_bounded_iff.2 $ h.imp $ λ _, and.right⟩
theorem is_bounded_iff_nndist {s : set α} :
is_bounded s ↔ ∃ C : ℝ≥0, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → nndist x y ≤ C :=
by simp only [is_bounded_iff_exists_ge 0, nnreal.exists, ← nnreal.coe_le_coe, ← dist_nndist,
nnreal.coe_mk, exists_prop]
theorem uniformity_basis_dist :
(𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 < ε}) :=
begin
rw ← pseudo_metric_space.uniformity_dist.symm,
refine has_basis_binfi_principal _ nonempty_Ioi,
exact λ r (hr : 0 < r) p (hp : 0 < p), ⟨min r p, lt_min hr hp,
λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_left r p),
λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_right r p)⟩
end
/-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers
accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`.
For specific bases see `uniformity_basis_dist`, `uniformity_basis_dist_inv_nat_succ`,
and `uniformity_basis_dist_inv_nat_pos`. -/
protected theorem mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ℝ}
(hf₀ : ∀ i, p i → 0 < f i) (hf : ∀ ⦃ε⦄, 0 < ε → ∃ i (hi : p i), f i ≤ ε) :
(𝓤 α).has_basis p (λ i, {p:α×α | dist p.1 p.2 < f i}) :=
begin
refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩,
split,
{ rintros ⟨ε, ε₀, hε⟩,
obtain ⟨i, hi, H⟩ : ∃ i (hi : p i), f i ≤ ε, from hf ε₀,
exact ⟨i, hi, λ x (hx : _ < _), hε $ lt_of_lt_of_le hx H⟩ },
{ exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ }
end
theorem uniformity_basis_dist_inv_nat_succ :
(𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / (↑n+1) }) :=
metric.mk_uniformity_basis (λ n _, div_pos zero_lt_one $ nat.cast_add_one_pos n)
(λ ε ε0, (exists_nat_one_div_lt ε0).imp $ λ n hn, ⟨trivial, le_of_lt hn⟩)
theorem uniformity_basis_dist_inv_nat_pos :
(𝓤 α).has_basis (λ n:ℕ, 0<n) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / ↑n }) :=
metric.mk_uniformity_basis (λ n hn, div_pos zero_lt_one $ nat.cast_pos.2 hn)
(λ ε ε0, let ⟨n, hn⟩ := exists_nat_one_div_lt ε0 in ⟨n+1, nat.succ_pos n,
by exact_mod_cast hn.le⟩)
theorem uniformity_basis_dist_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) :
(𝓤 α).has_basis (λ n:ℕ, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 < r ^ n }) :=
metric.mk_uniformity_basis (λ n hn, pow_pos h0 _)
(λ ε ε0, let ⟨n, hn⟩ := exists_pow_lt_of_lt_one ε0 h1 in ⟨n, trivial, hn.le⟩)
theorem uniformity_basis_dist_lt {R : ℝ} (hR : 0 < R) :
(𝓤 α).has_basis (λ r : ℝ, 0 < r ∧ r < R) (λ r, {p : α × α | dist p.1 p.2 < r}) :=
metric.mk_uniformity_basis (λ r, and.left) $ λ r hr,
⟨min r (R / 2), ⟨lt_min hr (half_pos hR), min_lt_iff.2 $ or.inr (half_lt_self hR)⟩,
min_le_left _ _⟩
/-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers
accumulating to zero, then closed neighborhoods of the diagonal of sizes `{f i | p i}`
form a basis of `𝓤 α`.
Currently we have only one specific basis `uniformity_basis_dist_le` based on this constructor.
More can be easily added if needed in the future. -/
protected theorem mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ℝ}
(hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) :
(𝓤 α).has_basis p (λ x, {p:α×α | dist p.1 p.2 ≤ f x}) :=
begin
refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩,
split,
{ rintros ⟨ε, ε₀, hε⟩,
rcases exists_between ε₀ with ⟨ε', hε'⟩,
rcases hf ε' hε'.1 with ⟨i, hi, H⟩,
exact ⟨i, hi, λ x (hx : _ ≤ _), hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ },
{ exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x (hx : _ < _), H (le_of_lt hx)⟩ }
end
/-- Contant size closed neighborhoods of the diagonal form a basis
of the uniformity filter. -/
theorem uniformity_basis_dist_le :
(𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 ≤ ε}) :=
metric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩)
theorem uniformity_basis_dist_le_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) :
(𝓤 α).has_basis (λ n:ℕ, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 ≤ r ^ n }) :=
metric.mk_uniformity_basis_le (λ n hn, pow_pos h0 _)
(λ ε ε0, let ⟨n, hn⟩ := exists_pow_lt_of_lt_one ε0 h1 in ⟨n, trivial, hn.le⟩)
theorem mem_uniformity_dist {s : set (α×α)} :
s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, dist a b < ε → (a, b) ∈ s) :=
uniformity_basis_dist.mem_uniformity_iff
/-- A constant size neighborhood of the diagonal is an entourage. -/
theorem dist_mem_uniformity {ε:ℝ} (ε0 : 0 < ε) :
{p:α×α | dist p.1 p.2 < ε} ∈ 𝓤 α :=
mem_uniformity_dist.2 ⟨ε, ε0, λ a b, id⟩
theorem uniform_continuous_iff [pseudo_metric_space β] {f : α → β} :
uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0,
∀{a b:α}, dist a b < δ → dist (f a) (f b) < ε :=
uniformity_basis_dist.uniform_continuous_iff uniformity_basis_dist
lemma uniform_continuous_on_iff [pseudo_metric_space β] {f : α → β} {s : set α} :
uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ x y ∈ s, dist x y < δ → dist (f x) (f y) < ε :=
metric.uniformity_basis_dist.uniform_continuous_on_iff metric.uniformity_basis_dist
lemma uniform_continuous_on_iff_le [pseudo_metric_space β] {f : α → β} {s : set α} :
uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ x y ∈ s, dist x y ≤ δ → dist (f x) (f y) ≤ ε :=
metric.uniformity_basis_dist_le.uniform_continuous_on_iff metric.uniformity_basis_dist_le
theorem uniform_embedding_iff [pseudo_metric_space β] {f : α → β} :
uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧
∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ :=
uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl
⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (dist_mem_uniformity δ0),
⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 tu in
⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩,
λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in
⟨_, dist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩
/-- If a map between pseudometric spaces is a uniform embedding then the distance between `f x`
and `f y` is controlled in terms of the distance between `x` and `y`. -/
theorem controlled_of_uniform_embedding [pseudo_metric_space β] {f : α → β} :
uniform_embedding f →
(∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, dist a b < δ → dist (f a) (f b) < ε) ∧
(∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ) :=
begin
assume h,
exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩
end
theorem totally_bounded_iff {s : set α} :
totally_bounded s ↔ ∀ ε > 0, ∃t : set α, t.finite ∧ s ⊆ ⋃y∈t, ball y ε :=
⟨λ H ε ε0, H _ (dist_mem_uniformity ε0),
λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru,
⟨t, ft, h⟩ := H ε ε0 in
⟨t, ft, h.trans $ Union₂_mono $ λ y yt z, hε⟩⟩
/-- A pseudometric space is totally bounded if one can reconstruct up to any ε>0 any element of the
space from finitely many data. -/
lemma totally_bounded_of_finite_discretization {s : set α}
(H : ∀ε > (0 : ℝ), ∃ (β : Type u) (_ : fintype β) (F : s → β),
∀x y, F x = F y → dist (x:α) y < ε) :
totally_bounded s :=
begin
cases s.eq_empty_or_nonempty with hs hs,
{ rw hs, exact totally_bounded_empty },
rcases hs with ⟨x0, hx0⟩,
haveI : inhabited s := ⟨⟨x0, hx0⟩⟩,
refine totally_bounded_iff.2 (λ ε ε0, _),
rcases H ε ε0 with ⟨β, fβ, F, hF⟩,
resetI,
let Finv := function.inv_fun F,
refine ⟨range (subtype.val ∘ Finv), finite_range _, λ x xs, _⟩,
let x' := Finv (F ⟨x, xs⟩),
have : F x' = F ⟨x, xs⟩ := function.inv_fun_eq ⟨⟨x, xs⟩, rfl⟩,
simp only [set.mem_Union, set.mem_range],
exact ⟨_, ⟨F ⟨x, xs⟩, rfl⟩, hF _ _ this.symm⟩
end
theorem finite_approx_of_totally_bounded {s : set α} (hs : totally_bounded s) :
∀ ε > 0, ∃ t ⊆ s, set.finite t ∧ s ⊆ ⋃y∈t, ball y ε :=
begin
intros ε ε_pos,
rw totally_bounded_iff_subset at hs,
exact hs _ (dist_mem_uniformity ε_pos),
end
/-- Expressing uniform convergence using `dist` -/
lemma tendsto_uniformly_on_filter_iff {ι : Type*}
{F : ι → β → α} {f : β → α} {p : filter ι} {p' : filter β} :
tendsto_uniformly_on_filter F f p p' ↔
∀ ε > 0, ∀ᶠ (n : ι × β) in (p ×ᶠ p'), dist (f n.snd) (F n.fst n.snd) < ε :=
begin
refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu, _⟩,
rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩,
refine (H ε εpos).mono (λ n hn, hε hn),
end
/-- Expressing locally uniform convergence on a set using `dist`. -/
lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β]
{F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} :
tendsto_locally_uniformly_on F f p s ↔
∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε :=
begin
refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu x hx, _⟩,
rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩,
rcases H ε εpos x hx with ⟨t, ht, Ht⟩,
exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩
end
/-- Expressing uniform convergence on a set using `dist`. -/
lemma tendsto_uniformly_on_iff {ι : Type*}
{F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} :
tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, dist (f x) (F n x) < ε :=
begin
refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu, _⟩,
rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩,
exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx))
end
/-- Expressing locally uniform convergence using `dist`. -/
lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β]
{F : ι → β → α} {f : β → α} {p : filter ι} :
tendsto_locally_uniformly F f p ↔
∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε :=
by simp only [← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff,
nhds_within_univ, mem_univ, forall_const, exists_prop]
/-- Expressing uniform convergence using `dist`. -/
lemma tendsto_uniformly_iff {ι : Type*}
{F : ι → β → α} {f : β → α} {p : filter ι} :
tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, dist (f x) (F n x) < ε :=
by { rw [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff], simp }
protected lemma cauchy_iff {f : filter α} :
cauchy f ↔ ne_bot f ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, dist x y < ε :=
uniformity_basis_dist.cauchy_iff
theorem nhds_basis_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (ball x) :=
nhds_basis_uniformity uniformity_basis_dist
theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s :=
nhds_basis_ball.mem_iff
theorem eventually_nhds_iff {p : α → Prop} :
(∀ᶠ y in 𝓝 x, p y) ↔ ∃ε>0, ∀ ⦃y⦄, dist y x < ε → p y :=
mem_nhds_iff
lemma eventually_nhds_iff_ball {p : α → Prop} :
(∀ᶠ y in 𝓝 x, p y) ↔ ∃ ε>0, ∀ y ∈ ball x ε, p y :=
mem_nhds_iff
/-- A version of `filter.eventually_prod_iff` where the second filter consists of neighborhoods
in a pseudo-metric space.-/
lemma eventually_prod_nhds_iff {f : filter ι} {x₀ : α} {p : ι × α → Prop}:
(∀ᶠ x in f ×ᶠ 𝓝 x₀, p x) ↔ ∃ (pa : ι → Prop) (ha : ∀ᶠ i in f, pa i) (ε > 0),
∀ {i}, pa i → ∀ {x}, dist x x₀ < ε → p (i, x) :=
begin
simp_rw [eventually_prod_iff, metric.eventually_nhds_iff],
refine exists_congr (λ q, exists_congr $ λ hq, _),
split,
{ rintro ⟨r, ⟨ε, hε, hεr⟩, hp⟩, exact ⟨ε, hε, λ i hi x hx, hp hi $ hεr hx⟩ },
{ rintro ⟨ε, hε, hp⟩, exact ⟨λ x, dist x x₀ < ε, ⟨ε, hε, λ y, id⟩, @hp⟩ }
end
/-- A version of `filter.eventually_prod_iff` where the first filter consists of neighborhoods
in a pseudo-metric space.-/
lemma eventually_nhds_prod_iff {ι α} [pseudo_metric_space α] {f : filter ι} {x₀ : α}
{p : α × ι → Prop}:
(∀ᶠ x in 𝓝 x₀ ×ᶠ f, p x) ↔ ∃ (ε > (0 : ℝ)) (pa : ι → Prop) (ha : ∀ᶠ i in f, pa i) ,
∀ {x}, dist x x₀ < ε → ∀ {i}, pa i → p (x, i) :=
begin
rw [eventually_swap_iff, metric.eventually_prod_nhds_iff],
split; { rintro ⟨a1, a2, a3, a4, a5⟩, refine ⟨a3, a4, a1, a2, λ b1 b2 b3 b4, a5 b4 b2⟩ }
end
theorem nhds_basis_closed_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (closed_ball x) :=
nhds_basis_uniformity uniformity_basis_dist_le
theorem nhds_basis_ball_inv_nat_succ :
(𝓝 x).has_basis (λ _, true) (λ n:ℕ, ball x (1 / (↑n+1))) :=
nhds_basis_uniformity uniformity_basis_dist_inv_nat_succ
theorem nhds_basis_ball_inv_nat_pos :
(𝓝 x).has_basis (λ n, 0<n) (λ n:ℕ, ball x (1 / ↑n)) :=
nhds_basis_uniformity uniformity_basis_dist_inv_nat_pos
theorem nhds_basis_ball_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) :
(𝓝 x).has_basis (λ n, true) (λ n:ℕ, ball x (r ^ n)) :=
nhds_basis_uniformity (uniformity_basis_dist_pow h0 h1)
theorem nhds_basis_closed_ball_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) :
(𝓝 x).has_basis (λ n, true) (λ n:ℕ, closed_ball x (r ^ n)) :=
nhds_basis_uniformity (uniformity_basis_dist_le_pow h0 h1)
theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s :=
by simp only [is_open_iff_mem_nhds, mem_nhds_iff]
theorem is_open_ball : is_open (ball x ε) :=
is_open_iff.2 $ λ y, exists_ball_subset_ball
theorem ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x :=
is_open_ball.mem_nhds (mem_ball_self ε0)
theorem closed_ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : closed_ball x ε ∈ 𝓝 x :=
mem_of_superset (ball_mem_nhds x ε0) ball_subset_closed_ball
theorem closed_ball_mem_nhds_of_mem {x c : α} {ε : ℝ} (h : x ∈ ball c ε) :
closed_ball c ε ∈ 𝓝 x :=
mem_of_superset (is_open_ball.mem_nhds h) ball_subset_closed_ball
theorem nhds_within_basis_ball {s : set α} :
(𝓝[s] x).has_basis (λ ε:ℝ, 0 < ε) (λ ε, ball x ε ∩ s) :=
nhds_within_has_basis nhds_basis_ball s
theorem mem_nhds_within_iff {t : set α} : s ∈ 𝓝[t] x ↔ ∃ε>0, ball x ε ∩ t ⊆ s :=
nhds_within_basis_ball.mem_iff
theorem tendsto_nhds_within_nhds_within [pseudo_metric_space β] {t : set β} {f : α → β} {a b} :
tendsto f (𝓝[s] a) (𝓝[t] b) ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → f x ∈ t ∧ dist (f x) b < ε :=
(nhds_within_basis_ball.tendsto_iff nhds_within_basis_ball).trans $
forall₂_congr $ λ ε hε, exists₂_congr $ λ δ hδ,
forall_congr $ λ x, by simp; itauto
theorem tendsto_nhds_within_nhds [pseudo_metric_space β] {f : α → β} {a b} :
tendsto f (𝓝[s] a) (𝓝 b) ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) b < ε :=
by { rw [← nhds_within_univ b, tendsto_nhds_within_nhds_within],
simp only [mem_univ, true_and] }
theorem tendsto_nhds_nhds [pseudo_metric_space β] {f : α → β} {a b} :
tendsto f (𝓝 a) (𝓝 b) ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) b < ε :=
nhds_basis_ball.tendsto_iff nhds_basis_ball
theorem continuous_at_iff [pseudo_metric_space β] {f : α → β} {a : α} :
continuous_at f a ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) (f a) < ε :=
by rw [continuous_at, tendsto_nhds_nhds]
theorem continuous_within_at_iff [pseudo_metric_space β] {f : α → β} {a : α} {s : set α} :
continuous_within_at f s a ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) (f a) < ε :=
by rw [continuous_within_at, tendsto_nhds_within_nhds]
theorem continuous_on_iff [pseudo_metric_space β] {f : α → β} {s : set α} :
continuous_on f s ↔
∀ (b ∈ s) (ε > 0), ∃ δ > 0, ∀a ∈ s, dist a b < δ → dist (f a) (f b) < ε :=
by simp [continuous_on, continuous_within_at_iff]
theorem continuous_iff [pseudo_metric_space β] {f : α → β} :
continuous f ↔
∀b (ε > 0), ∃ δ > 0, ∀a, dist a b < δ → dist (f a) (f b) < ε :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_nhds
theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} :
tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, dist (u x) a < ε :=
nhds_basis_ball.tendsto_right_iff
theorem continuous_at_iff' [topological_space β] {f : β → α} {b : β} :
continuous_at f b ↔
∀ ε > 0, ∀ᶠ x in 𝓝 b, dist (f x) (f b) < ε :=
by rw [continuous_at, tendsto_nhds]
theorem continuous_within_at_iff' [topological_space β] {f : β → α} {b : β} {s : set β} :
continuous_within_at f s b ↔
∀ ε > 0, ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε :=
by rw [continuous_within_at, tendsto_nhds]
theorem continuous_on_iff' [topological_space β] {f : β → α} {s : set β} :
continuous_on f s ↔
∀ (b ∈ s) (ε > 0), ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε :=
by simp [continuous_on, continuous_within_at_iff']
theorem continuous_iff' [topological_space β] {f : β → α} :
continuous f ↔ ∀a (ε > 0), ∀ᶠ x in 𝓝 a, dist (f x) (f a) < ε :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds
theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} :
tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) a < ε :=
(at_top_basis.tendsto_iff nhds_basis_ball).trans $
by { simp only [exists_prop, true_and], refl }
/--
A variant of `tendsto_at_top` that
uses `∃ N, ∀ n > N, ...` rather than `∃ N, ∀ n ≥ N, ...`
-/
theorem tendsto_at_top' [nonempty β] [semilattice_sup β] [no_max_order β] {u : β → α} {a : α} :
tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n>N, dist (u n) a < ε :=
(at_top_basis_Ioi.tendsto_iff nhds_basis_ball).trans $
by { simp only [exists_prop, true_and], refl }
lemma is_open_singleton_iff {α : Type*} [pseudo_metric_space α] {x : α} :
is_open ({x} : set α) ↔ ∃ ε > 0, ∀ y, dist y x < ε → y = x :=
by simp [is_open_iff, subset_singleton_iff, mem_ball]
/-- Given a point `x` in a discrete subset `s` of a pseudometric space, there is an open ball
centered at `x` and intersecting `s` only at `x`. -/
lemma exists_ball_inter_eq_singleton_of_mem_discrete [discrete_topology s] {x : α} (hx : x ∈ s) :
∃ ε > 0, metric.ball x ε ∩ s = {x} :=
nhds_basis_ball.exists_inter_eq_singleton_of_mem_discrete hx
/-- Given a point `x` in a discrete subset `s` of a pseudometric space, there is a closed ball
of positive radius centered at `x` and intersecting `s` only at `x`. -/
lemma exists_closed_ball_inter_eq_singleton_of_discrete [discrete_topology s] {x : α} (hx : x ∈ s) :
∃ ε > 0, metric.closed_ball x ε ∩ s = {x} :=
nhds_basis_closed_ball.exists_inter_eq_singleton_of_mem_discrete hx
lemma _root_.dense.exists_dist_lt {s : set α} (hs : dense s) (x : α) {ε : ℝ} (hε : 0 < ε) :
∃ y ∈ s, dist x y < ε :=
begin
have : (ball x ε).nonempty, by simp [hε],
simpa only [mem_ball'] using hs.exists_mem_open is_open_ball this
end
lemma _root_.dense_range.exists_dist_lt {β : Type*} {f : β → α} (hf : dense_range f)
(x : α) {ε : ℝ} (hε : 0 < ε) :
∃ y, dist x (f y) < ε :=
exists_range_iff.1 (hf.exists_dist_lt x hε)
end metric
open metric
/-Instantiate a pseudometric space as a pseudoemetric space. Before we can state the instance,
we need to show that the uniform structure coming from the edistance and the
distance coincide. -/
/-- Expressing the uniformity in terms of `edist` -/
protected lemma pseudo_metric.uniformity_basis_edist :
(𝓤 α).has_basis (λ ε:ℝ≥0∞, 0 < ε) (λ ε, {p | edist p.1 p.2 < ε}) :=
⟨begin
intro t,
refine mem_uniformity_dist.trans ⟨_, _⟩; rintro ⟨ε, ε0, Hε⟩,
{ use [ennreal.of_real ε, ennreal.of_real_pos.2 ε0],
rintros ⟨a, b⟩,
simp only [edist_dist, ennreal.of_real_lt_of_real_iff ε0],
exact Hε },
{ rcases ennreal.lt_iff_exists_real_btwn.1 ε0 with ⟨ε', _, ε0', hε⟩,
rw [ennreal.of_real_pos] at ε0',
refine ⟨ε', ε0', λ a b h, Hε (lt_trans _ hε)⟩,
rwa [edist_dist, ennreal.of_real_lt_of_real_iff ε0'] }
end⟩
theorem metric.uniformity_edist : 𝓤 α = (⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε}) :=
pseudo_metric.uniformity_basis_edist.eq_binfi
/-- A pseudometric space induces a pseudoemetric space -/
@[priority 100] -- see Note [lower instance priority]
instance pseudo_metric_space.to_pseudo_emetric_space : pseudo_emetric_space α :=
{ edist := edist,
edist_self := by simp [edist_dist],
edist_comm := by simp only [edist_dist, dist_comm]; simp,
edist_triangle := assume x y z, begin
simp only [edist_dist, ← ennreal.of_real_add, dist_nonneg],
rw ennreal.of_real_le_of_real_iff _,
{ exact dist_triangle _ _ _ },
{ simpa using add_le_add (dist_nonneg : 0 ≤ dist x y) dist_nonneg }
end,
uniformity_edist := metric.uniformity_edist,
..‹pseudo_metric_space α› }
/-- In a pseudometric space, an open ball of infinite radius is the whole space -/
lemma metric.eball_top_eq_univ (x : α) :
emetric.ball x ∞ = set.univ :=
set.eq_univ_iff_forall.mpr (λ y, edist_lt_top y x)
/-- Balls defined using the distance or the edistance coincide -/
@[simp] lemma metric.emetric_ball {x : α} {ε : ℝ} : emetric.ball x (ennreal.of_real ε) = ball x ε :=
begin
ext y,
simp only [emetric.mem_ball, mem_ball, edist_dist],
exact ennreal.of_real_lt_of_real_iff_of_nonneg dist_nonneg
end
/-- Balls defined using the distance or the edistance coincide -/
@[simp] lemma metric.emetric_ball_nnreal {x : α} {ε : ℝ≥0} : emetric.ball x ε = ball x ε :=
by { convert metric.emetric_ball, simp }
/-- Closed balls defined using the distance or the edistance coincide -/
lemma metric.emetric_closed_ball {x : α} {ε : ℝ} (h : 0 ≤ ε) :
emetric.closed_ball x (ennreal.of_real ε) = closed_ball x ε :=
by ext y; simp [edist_dist]; rw ennreal.of_real_le_of_real_iff h
/-- Closed balls defined using the distance or the edistance coincide -/
@[simp] lemma metric.emetric_closed_ball_nnreal {x : α} {ε : ℝ≥0} :
emetric.closed_ball x ε = closed_ball x ε :=
by { convert metric.emetric_closed_ball ε.2, simp }
@[simp] lemma metric.emetric_ball_top (x : α) : emetric.ball x ⊤ = univ :=
eq_univ_of_forall $ λ y, edist_lt_top _ _
lemma metric.inseparable_iff {x y : α} : inseparable x y ↔ dist x y = 0 :=
by rw [emetric.inseparable_iff, edist_nndist, dist_nndist, ennreal.coe_eq_zero,
nnreal.coe_eq_zero]
/-- Build a new pseudometric space from an old one where the bundled uniform structure is provably
(but typically non-definitionaly) equal to some given uniform structure.
See Note [forgetful inheritance].
-/
def pseudo_metric_space.replace_uniformity {α} [U : uniform_space α] (m : pseudo_metric_space α)
(H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) :
pseudo_metric_space α :=
{ dist := @dist _ m.to_has_dist,
dist_self := dist_self,
dist_comm := dist_comm,
dist_triangle := dist_triangle,
edist := edist,
edist_dist := edist_dist,
to_uniform_space := U,
uniformity_dist := H.trans pseudo_metric_space.uniformity_dist }
lemma pseudo_metric_space.replace_uniformity_eq {α} [U : uniform_space α]
(m : pseudo_metric_space α)
(H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) :
m.replace_uniformity H = m :=
by { ext, refl }
/-- Build a new pseudo metric space from an old one where the bundled topological structure is
provably (but typically non-definitionaly) equal to some given topological structure.
See Note [forgetful inheritance].
-/
@[reducible] def pseudo_metric_space.replace_topology {γ} [U : topological_space γ]
(m : pseudo_metric_space γ) (H : U = m.to_uniform_space.to_topological_space) :
pseudo_metric_space γ :=
@pseudo_metric_space.replace_uniformity γ (m.to_uniform_space.replace_topology H) m rfl
lemma pseudo_metric_space.replace_topology_eq {γ} [U : topological_space γ]
(m : pseudo_metric_space γ) (H : U = m.to_uniform_space.to_topological_space) :
m.replace_topology H = m :=
by { ext, refl }
/-- One gets a pseudometric space from an emetric space if the edistance
is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the
uniformity are defeq in the pseudometric space and the pseudoemetric space. In this definition, the
distance is given separately, to be able to prescribe some expression which is not defeq to the
push-forward of the edistance to reals. -/
def pseudo_emetric_space.to_pseudo_metric_space_of_dist {α : Type u} [e : pseudo_emetric_space α]
(dist : α → α → ℝ)
(edist_ne_top : ∀x y: α, edist x y ≠ ⊤)
(h : ∀x y, dist x y = ennreal.to_real (edist x y)) :
pseudo_metric_space α :=
let m : pseudo_metric_space α :=
{ dist := dist,
dist_self := λx, by simp [h],
dist_comm := λx y, by simp [h, pseudo_emetric_space.edist_comm],
dist_triangle := λx y z, begin
simp only [h],
rw [← ennreal.to_real_add (edist_ne_top _ _) (edist_ne_top _ _),
ennreal.to_real_le_to_real (edist_ne_top _ _)],
{ exact edist_triangle _ _ _ },
{ simp [ennreal.add_eq_top, edist_ne_top] }
end,
edist := edist,
edist_dist := λ x y, by simp [h, ennreal.of_real_to_real, edist_ne_top] } in
m.replace_uniformity $ by { rw [uniformity_pseudoedist, metric.uniformity_edist], refl }
/-- One gets a pseudometric space from an emetric space if the edistance
is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the
uniformity are defeq in the pseudometric space and the emetric space. -/
def pseudo_emetric_space.to_pseudo_metric_space {α : Type u} [e : pseudo_emetric_space α]
(h : ∀x y: α, edist x y ≠ ⊤) : pseudo_metric_space α :=
pseudo_emetric_space.to_pseudo_metric_space_of_dist
(λx y, ennreal.to_real (edist x y)) h (λx y, rfl)
/-- Build a new pseudometric space from an old one where the bundled bornology structure is provably
(but typically non-definitionaly) equal to some given bornology structure.
See Note [forgetful inheritance].
-/
def pseudo_metric_space.replace_bornology {α} [B : bornology α] (m : pseudo_metric_space α)
(H : ∀ s, @is_bounded _ B s ↔ @is_bounded _ pseudo_metric_space.to_bornology s) :
pseudo_metric_space α :=
{ to_bornology := B,
cobounded_sets := set.ext $ compl_surjective.forall.2 $ λ s, (H s).trans $
by rw [is_bounded_iff, mem_set_of_eq, compl_compl],
.. m }
lemma pseudo_metric_space.replace_bornology_eq {α} [m : pseudo_metric_space α] [B : bornology α]
(H : ∀ s, @is_bounded _ B s ↔ @is_bounded _ pseudo_metric_space.to_bornology s) :
pseudo_metric_space.replace_bornology _ H = m :=
by { ext, refl }
/-- A very useful criterion to show that a space is complete is to show that all sequences
which satisfy a bound of the form `dist (u n) (u m) < B N` for all `n m ≥ N` are
converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to
`0`, which makes it possible to use arguments of converging series, while this is impossible
to do in general for arbitrary Cauchy sequences. -/
theorem metric.complete_of_convergent_controlled_sequences (B : ℕ → real) (hB : ∀n, 0 < B n)
(H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → dist (u n) (u m) < B N) →
∃x, tendsto u at_top (𝓝 x)) :
complete_space α :=
uniform_space.complete_of_convergent_controlled_sequences
(λ n, {p:α×α | dist p.1 p.2 < B n}) (λ n, dist_mem_uniformity $ hB n) H
theorem metric.complete_of_cauchy_seq_tendsto :
(∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α :=
emetric.complete_of_cauchy_seq_tendsto
section real
/-- Instantiate the reals as a pseudometric space. -/
instance real.pseudo_metric_space : pseudo_metric_space ℝ :=
{ dist := λx y, |x - y|,
dist_self := by simp [abs_zero],
dist_comm := assume x y, abs_sub_comm _ _,
dist_triangle := assume x y z, abs_sub_le _ _ _ }
theorem real.dist_eq (x y : ℝ) : dist x y = |x - y| := rfl
theorem real.nndist_eq (x y : ℝ) : nndist x y = real.nnabs (x - y) := rfl
theorem real.nndist_eq' (x y : ℝ) : nndist x y = real.nnabs (y - x) := nndist_comm _ _
theorem real.dist_0_eq_abs (x : ℝ) : dist x 0 = |x| :=
by simp [real.dist_eq]
theorem real.dist_left_le_of_mem_interval {x y z : ℝ} (h : y ∈ interval x z) :
dist x y ≤ dist x z :=
by simpa only [dist_comm x] using abs_sub_left_of_mem_interval h
theorem real.dist_right_le_of_mem_interval {x y z : ℝ} (h : y ∈ interval x z) :
dist y z ≤ dist x z :=
by simpa only [dist_comm _ z] using abs_sub_right_of_mem_interval h
theorem real.dist_le_of_mem_interval {x y x' y' : ℝ} (hx : x ∈ interval x' y')
(hy : y ∈ interval x' y') : dist x y ≤ dist x' y' :=
abs_sub_le_of_subinterval $ interval_subset_interval (by rwa interval_swap) (by rwa interval_swap)
theorem real.dist_le_of_mem_Icc {x y x' y' : ℝ} (hx : x ∈ Icc x' y') (hy : y ∈ Icc x' y') :
dist x y ≤ y' - x' :=
by simpa only [real.dist_eq, abs_of_nonpos (sub_nonpos.2 $ hx.1.trans hx.2), neg_sub]
using real.dist_le_of_mem_interval (Icc_subset_interval hx) (Icc_subset_interval hy)
theorem real.dist_le_of_mem_Icc_01 {x y : ℝ} (hx : x ∈ Icc (0:ℝ) 1) (hy : y ∈ Icc (0:ℝ) 1) :
dist x y ≤ 1 :=
by simpa only [sub_zero] using real.dist_le_of_mem_Icc hx hy
instance : order_topology ℝ :=
order_topology_of_nhds_abs $ λ x,
by simp only [nhds_basis_ball.eq_binfi, ball, real.dist_eq, abs_sub_comm]
lemma real.ball_eq_Ioo (x r : ℝ) : ball x r = Ioo (x - r) (x + r) :=
set.ext $ λ y, by rw [mem_ball, dist_comm, real.dist_eq,
abs_sub_lt_iff, mem_Ioo, ← sub_lt_iff_lt_add', sub_lt_comm]
lemma real.closed_ball_eq_Icc {x r : ℝ} : closed_ball x r = Icc (x - r) (x + r) :=
by ext y; rw [mem_closed_ball, dist_comm, real.dist_eq,
abs_sub_le_iff, mem_Icc, ← sub_le_iff_le_add', sub_le_comm]
theorem real.Ioo_eq_ball (x y : ℝ) : Ioo x y = ball ((x + y) / 2) ((y - x) / 2) :=
by rw [real.ball_eq_Ioo, ← sub_div, add_comm, ← sub_add,
add_sub_cancel', add_self_div_two, ← add_div,
add_assoc, add_sub_cancel'_right, add_self_div_two]
theorem real.Icc_eq_closed_ball (x y : ℝ) : Icc x y = closed_ball ((x + y) / 2) ((y - x) / 2) :=
by rw [real.closed_ball_eq_Icc, ← sub_div, add_comm, ← sub_add,
add_sub_cancel', add_self_div_two, ← add_div,
add_assoc, add_sub_cancel'_right, add_self_div_two]
section metric_ordered
variables [preorder α] [compact_Icc_space α]
lemma totally_bounded_Icc (a b : α) : totally_bounded (Icc a b) :=
is_compact_Icc.totally_bounded
lemma totally_bounded_Ico (a b : α) : totally_bounded (Ico a b) :=
totally_bounded_subset Ico_subset_Icc_self (totally_bounded_Icc a b)
lemma totally_bounded_Ioc (a b : α) : totally_bounded (Ioc a b) :=
totally_bounded_subset Ioc_subset_Icc_self (totally_bounded_Icc a b)
lemma totally_bounded_Ioo (a b : α) : totally_bounded (Ioo a b) :=
totally_bounded_subset Ioo_subset_Icc_self (totally_bounded_Icc a b)
end metric_ordered
/-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the
general case. -/
lemma squeeze_zero' {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀ᶠ t in t₀, 0 ≤ f t)
(hft : ∀ᶠ t in t₀, f t ≤ g t) (g0 : tendsto g t₀ (nhds 0)) : tendsto f t₀ (𝓝 0) :=
tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds g0 hf hft
/-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le`
and `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the general case. -/
lemma squeeze_zero {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀t, 0 ≤ f t) (hft : ∀t, f t ≤ g t)
(g0 : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) :=
squeeze_zero' (eventually_of_forall hf) (eventually_of_forall hft) g0
theorem metric.uniformity_eq_comap_nhds_zero :
𝓤 α = comap (λp:α×α, dist p.1 p.2) (𝓝 (0 : ℝ)) :=
by { ext s,
simp [mem_uniformity_dist, (nhds_basis_ball.comap _).mem_iff, subset_def, real.dist_0_eq_abs] }
lemma cauchy_seq_iff_tendsto_dist_at_top_0 [nonempty β] [semilattice_sup β] {u : β → α} :
cauchy_seq u ↔ tendsto (λ (n : β × β), dist (u n.1) (u n.2)) at_top (𝓝 0) :=
by rw [cauchy_seq_iff_tendsto, metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff,
prod.map_def]
lemma tendsto_uniformity_iff_dist_tendsto_zero {ι : Type*} {f : ι → α × α} {p : filter ι} :
tendsto f p (𝓤 α) ↔ tendsto (λ x, dist (f x).1 (f x).2) p (𝓝 0) :=
by rw [metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff]
lemma filter.tendsto.congr_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α}
(h₁ : tendsto f₁ p (𝓝 a)) (h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) :
tendsto f₂ p (𝓝 a) :=
h₁.congr_uniformity $ tendsto_uniformity_iff_dist_tendsto_zero.2 h
alias filter.tendsto.congr_dist ← tendsto_of_tendsto_of_dist
lemma tendsto_iff_of_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α}
(h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) :
tendsto f₁ p (𝓝 a) ↔ tendsto f₂ p (𝓝 a) :=
uniform.tendsto_congr $ tendsto_uniformity_iff_dist_tendsto_zero.2 h
/-- If `u` is a neighborhood of `x`, then for small enough `r`, the closed ball
`closed_ball x r` is contained in `u`. -/
lemma eventually_closed_ball_subset {x : α} {u : set α} (hu : u ∈ 𝓝 x) :
∀ᶠ r in 𝓝 (0 : ℝ), closed_ball x r ⊆ u :=
begin
obtain ⟨ε, εpos, hε⟩ : ∃ ε (hε : 0 < ε), closed_ball x ε ⊆ u :=
nhds_basis_closed_ball.mem_iff.1 hu,
have : Iic ε ∈ 𝓝 (0 : ℝ) := Iic_mem_nhds εpos,
filter_upwards [this] with _ hr using subset.trans (closed_ball_subset_closed_ball hr) hε,
end
end real
section cauchy_seq
variables [nonempty β] [semilattice_sup β]
/-- In a pseudometric space, Cauchy sequences are characterized by the fact that, eventually,
the distance between its elements is arbitrarily small -/
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem metric.cauchy_seq_iff {u : β → α} :
cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, dist (u m) (u n) < ε :=
uniformity_basis_dist.cauchy_seq_iff
/-- A variation around the pseudometric characterization of Cauchy sequences -/
theorem metric.cauchy_seq_iff' {u : β → α} :
cauchy_seq u ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) (u N) < ε :=
uniformity_basis_dist.cauchy_seq_iff'
/-- In a pseudometric space, unifom Cauchy sequences are characterized by the fact that, eventually,
the distance between all its elements is uniformly, arbitrarily small -/
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem metric.uniform_cauchy_seq_on_iff {γ : Type*}
{F : β → γ → α} {s : set γ} :
uniform_cauchy_seq_on F at_top s ↔
∀ ε : ℝ, ε > 0 → ∃ (N : β), ∀ m : β, m ≥ N → ∀ n : β, n ≥ N → ∀ x : γ, x ∈ s →
dist (F m x) (F n x) < ε :=
begin
split,
{ intros h ε hε,
let u := { a : α × α | dist a.fst a.snd < ε },
have hu : u ∈ 𝓤 α := metric.mem_uniformity_dist.mpr ⟨ε, hε, (λ a b, by simp)⟩,
rw ←@filter.eventually_at_top_prod_self' _ _ _
(λ m, ∀ x : γ, x ∈ s → dist (F m.fst x) (F m.snd x) < ε),
specialize h u hu,
rw prod_at_top_at_top_eq at h,
exact h.mono (λ n h x hx, set.mem_set_of_eq.mp (h x hx)), },
{ intros h u hu,
rcases (metric.mem_uniformity_dist.mp hu) with ⟨ε, hε, hab⟩,
rcases h ε hε with ⟨N, hN⟩,
rw [prod_at_top_at_top_eq, eventually_at_top],
use (N, N),
intros b hb x hx,
rcases hb with ⟨hbl, hbr⟩,
exact hab (hN b.fst hbl.ge b.snd hbr.ge x hx), },
end
/-- If the distance between `s n` and `s m`, `n ≤ m` is bounded above by `b n`
and `b` converges to zero, then `s` is a Cauchy sequence. -/
lemma cauchy_seq_of_le_tendsto_0' {s : β → α} (b : β → ℝ)
(h : ∀ n m : β, n ≤ m → dist (s n) (s m) ≤ b n) (h₀ : tendsto b at_top (𝓝 0)) :
cauchy_seq s :=
metric.cauchy_seq_iff'.2 $ λ ε ε0,
(h₀.eventually (gt_mem_nhds ε0)).exists.imp $ λ N hN n hn,
calc dist (s n) (s N) = dist (s N) (s n) : dist_comm _ _
... ≤ b N : h _ _ hn
... < ε : hN
/-- If the distance between `s n` and `s m`, `n, m ≥ N` is bounded above by `b N`
and `b` converges to zero, then `s` is a Cauchy sequence. -/
lemma cauchy_seq_of_le_tendsto_0 {s : β → α} (b : β → ℝ)
(h : ∀ n m N : β, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) (h₀ : tendsto b at_top (𝓝 0)) :
cauchy_seq s :=
cauchy_seq_of_le_tendsto_0' b (λ n m hnm, h _ _ _ le_rfl hnm) h₀
/-- A Cauchy sequence on the natural numbers is bounded. -/
theorem cauchy_seq_bdd {u : ℕ → α} (hu : cauchy_seq u) :
∃ R > 0, ∀ m n, dist (u m) (u n) < R :=
begin
rcases metric.cauchy_seq_iff'.1 hu 1 zero_lt_one with ⟨N, hN⟩,
rsuffices ⟨R, R0, H⟩ : ∃ R > 0, ∀ n, dist (u n) (u N) < R,
{ exact ⟨_, add_pos R0 R0, λ m n,
lt_of_le_of_lt (dist_triangle_right _ _ _) (add_lt_add (H m) (H n))⟩ },
let R := finset.sup (finset.range N) (λ n, nndist (u n) (u N)),
refine ⟨↑R + 1, add_pos_of_nonneg_of_pos R.2 zero_lt_one, λ n, _⟩,
cases le_or_lt N n,
{ exact lt_of_lt_of_le (hN _ h) (le_add_of_nonneg_left R.2) },
{ have : _ ≤ R := finset.le_sup (finset.mem_range.2 h),
exact lt_of_le_of_lt this (lt_add_of_pos_right _ zero_lt_one) }
end
/-- Yet another metric characterization of Cauchy sequences on integers. This one is often the
most efficient. -/
lemma cauchy_seq_iff_le_tendsto_0 {s : ℕ → α} : cauchy_seq s ↔ ∃ b : ℕ → ℝ,
(∀ n, 0 ≤ b n) ∧
(∀ n m N : ℕ, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) ∧
tendsto b at_top (𝓝 0) :=
⟨λ hs, begin
/- `s` is a Cauchy sequence. The sequence `b` will be constructed by taking
the supremum of the distances between `s n` and `s m` for `n m ≥ N`.
First, we prove that all these distances are bounded, as otherwise the Sup
would not make sense. -/
let S := λ N, (λ(p : ℕ × ℕ), dist (s p.1) (s p.2)) '' {p | p.1 ≥ N ∧ p.2 ≥ N},
have hS : ∀ N, ∃ x, ∀ y ∈ S N, y ≤ x,
{ rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩,
refine λ N, ⟨R, _⟩, rintro _ ⟨⟨m, n⟩, _, rfl⟩,
exact le_of_lt (hR m n) },
have bdd : bdd_above (range (λ(p : ℕ × ℕ), dist (s p.1) (s p.2))),
{ rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩,
use R, rintro _ ⟨⟨m, n⟩, rfl⟩, exact le_of_lt (hR m n) },
-- Prove that it bounds the distances of points in the Cauchy sequence
have ub : ∀ m n N, N ≤ m → N ≤ n → dist (s m) (s n) ≤ Sup (S N) :=
λ m n N hm hn, le_cSup (hS N) ⟨⟨_, _⟩, ⟨hm, hn⟩, rfl⟩,
have S0m : ∀ n, (0:ℝ) ∈ S n := λ n, ⟨⟨n, n⟩, ⟨le_rfl, le_rfl⟩, dist_self _⟩,
have S0 := λ n, le_cSup (hS n) (S0m n),
-- Prove that it tends to `0`, by using the Cauchy property of `s`
refine ⟨λ N, Sup (S N), S0, ub, metric.tendsto_at_top.2 (λ ε ε0, _)⟩,
refine (metric.cauchy_seq_iff.1 hs (ε/2) (half_pos ε0)).imp (λ N hN n hn, _),
rw [real.dist_0_eq_abs, abs_of_nonneg (S0 n)],
refine lt_of_le_of_lt (cSup_le ⟨_, S0m _⟩ _) (half_lt_self ε0),
rintro _ ⟨⟨m', n'⟩, ⟨hm', hn'⟩, rfl⟩,
exact le_of_lt (hN _ (le_trans hn hm') _ (le_trans hn hn'))
end,
λ ⟨b, _, b_bound, b_lim⟩, cauchy_seq_of_le_tendsto_0 b b_bound b_lim⟩
end cauchy_seq
/-- Pseudometric space structure pulled back by a function. -/
def pseudo_metric_space.induced {α β} (f : α → β)
(m : pseudo_metric_space β) : pseudo_metric_space α :=
{ dist := λ x y, dist (f x) (f y),
dist_self := λ x, dist_self _,
dist_comm := λ x y, dist_comm _ _,
dist_triangle := λ x y z, dist_triangle _ _ _,
edist := λ x y, edist (f x) (f y),
edist_dist := λ x y, edist_dist _ _,
to_uniform_space := uniform_space.comap f m.to_uniform_space,
uniformity_dist := begin
apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, dist (f x) (f y)),
refine compl_surjective.forall.2 (λ s, compl_mem_comap.trans $ mem_uniformity_dist.trans _),
simp only [mem_compl_iff, @imp_not_comm _ (_ ∈ _), ← prod.forall', prod.mk.eta, ball_image_iff]
end,
to_bornology := bornology.induced f,
cobounded_sets := set.ext $ compl_surjective.forall.2 $ λ s,
by simp only [compl_mem_comap, filter.mem_sets, ← is_bounded_def, mem_set_of_eq, compl_compl,
is_bounded_iff, ball_image_iff] }
/-- Pull back a pseudometric space structure by an inducing map. This is a version of
`pseudo_metric_space.induced` useful in case if the domain already has a `topological_space`
structure. -/
def inducing.comap_pseudo_metric_space {α β} [topological_space α] [pseudo_metric_space β]
{f : α → β} (hf : inducing f) : pseudo_metric_space α :=
(pseudo_metric_space.induced f ‹_›).replace_topology hf.induced
/-- Pull back a pseudometric space structure by a uniform inducing map. This is a version of
`pseudo_metric_space.induced` useful in case if the domain already has a `uniform_space`
structure. -/
def uniform_inducing.comap_pseudo_metric_space {α β} [uniform_space α] [pseudo_metric_space β]
(f : α → β) (h : uniform_inducing f) : pseudo_metric_space α :=
(pseudo_metric_space.induced f ‹_›).replace_uniformity h.comap_uniformity.symm
instance subtype.pseudo_metric_space {p : α → Prop} : pseudo_metric_space (subtype p) :=
pseudo_metric_space.induced coe ‹_›
theorem subtype.dist_eq {p : α → Prop} (x y : subtype p) : dist x y = dist (x : α) y := rfl
theorem subtype.nndist_eq {p : α → Prop} (x y : subtype p) : nndist x y = nndist (x : α) y := rfl
namespace mul_opposite
@[to_additive]
instance : pseudo_metric_space (αᵐᵒᵖ) := pseudo_metric_space.induced mul_opposite.unop ‹_›
@[simp, to_additive] theorem dist_unop (x y : αᵐᵒᵖ) : dist (unop x) (unop y) = dist x y := rfl
@[simp, to_additive] theorem dist_op (x y : α) : dist (op x) (op y) = dist x y := rfl
@[simp, to_additive] theorem nndist_unop (x y : αᵐᵒᵖ) : nndist (unop x) (unop y) = nndist x y := rfl
@[simp, to_additive] theorem nndist_op (x y : α) : nndist (op x) (op y) = nndist x y := rfl
end mul_opposite
section nnreal
instance : pseudo_metric_space ℝ≥0 := subtype.pseudo_metric_space
lemma nnreal.dist_eq (a b : ℝ≥0) : dist a b = |(a:ℝ) - b| := rfl
lemma nnreal.nndist_eq (a b : ℝ≥0) :
nndist a b = max (a - b) (b - a) :=
begin
/- WLOG, `b ≤ a`. `wlog h : b ≤ a` works too but it is much slower because Lean tries to prove one
case from the other and fails; `tactic.skip` tells Lean not to try. -/
wlog h : b ≤ a := le_total b a using [a b, b a] tactic.skip,
{ rw [← nnreal.coe_eq, ← dist_nndist, nnreal.dist_eq, tsub_eq_zero_iff_le.2 h,
max_eq_left (zero_le $ a - b), ← nnreal.coe_sub h, abs_of_nonneg (a - b).coe_nonneg] },
{ rwa [nndist_comm, max_comm] }
end
@[simp] lemma nnreal.nndist_zero_eq_val (z : ℝ≥0) : nndist 0 z = z :=
by simp only [nnreal.nndist_eq, max_eq_right, tsub_zero, zero_tsub, zero_le']
@[simp] lemma nnreal.nndist_zero_eq_val' (z : ℝ≥0) : nndist z 0 = z :=
by { rw nndist_comm, exact nnreal.nndist_zero_eq_val z, }
lemma nnreal.le_add_nndist (a b : ℝ≥0) : a ≤ b + nndist a b :=
begin
suffices : (a : ℝ) ≤ (b : ℝ) + (dist a b),
{ exact nnreal.coe_le_coe.mp this, },
linarith [le_of_abs_le (by refl : abs (a-b : ℝ) ≤ (dist a b))],
end
end nnreal
section ulift
variables [pseudo_metric_space β]
instance : pseudo_metric_space (ulift β) :=
pseudo_metric_space.induced ulift.down ‹_›
lemma ulift.dist_eq (x y : ulift β) : dist x y = dist x.down y.down := rfl
lemma ulift.nndist_eq (x y : ulift β) : nndist x y = nndist x.down y.down := rfl
@[simp] lemma ulift.dist_up_up (x y : β) : dist (ulift.up x) (ulift.up y) = dist x y := rfl
@[simp] lemma ulift.nndist_up_up (x y : β) : nndist (ulift.up x) (ulift.up y) = nndist x y := rfl
end ulift
section prod
variables [pseudo_metric_space β]
instance prod.pseudo_metric_space_max :
pseudo_metric_space (α × β) :=
(pseudo_emetric_space.to_pseudo_metric_space_of_dist
(λ x y : α × β, dist x.1 y.1 ⊔ dist x.2 y.2)
(λ x y, (max_lt (edist_lt_top _ _) (edist_lt_top _ _)).ne)
(λ x y, by simp only [sup_eq_max, dist_edist,
← ennreal.to_real_max (edist_ne_top _ _) (edist_ne_top _ _), prod.edist_eq]))
.replace_bornology $
λ s, by { simp only [← is_bounded_image_fst_and_snd, is_bounded_iff_eventually, ball_image_iff,
← eventually_and, ← forall_and_distrib, ← max_le_iff], refl }
lemma prod.dist_eq {x y : α × β} :
dist x y = max (dist x.1 y.1) (dist x.2 y.2) := rfl
@[simp]
lemma dist_prod_same_left {x : α} {y₁ y₂ : β} : dist (x, y₁) (x, y₂) = dist y₁ y₂ :=
by simp [prod.dist_eq, dist_nonneg]
@[simp]
lemma dist_prod_same_right {x₁ x₂ : α} {y : β} : dist (x₁, y) (x₂, y) = dist x₁ x₂ :=
by simp [prod.dist_eq, dist_nonneg]
theorem ball_prod_same (x : α) (y : β) (r : ℝ) :
ball x r ×ˢ ball y r = ball (x, y) r :=
ext $ λ z, by simp [prod.dist_eq]
theorem closed_ball_prod_same (x : α) (y : β) (r : ℝ) :
closed_ball x r ×ˢ closed_ball y r = closed_ball (x, y) r :=
ext $ λ z, by simp [prod.dist_eq]
end prod
theorem uniform_continuous_dist : uniform_continuous (λp:α×α, dist p.1 p.2) :=
metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε/2, half_pos ε0,
begin
suffices,
{ intros p q h, cases p with p₁ p₂, cases q with q₁ q₂,
cases max_lt_iff.1 h with h₁ h₂, clear h,
dsimp at h₁ h₂ ⊢,
rw real.dist_eq,
refine abs_sub_lt_iff.2 ⟨_, _⟩,
{ revert p₁ p₂ q₁ q₂ h₁ h₂, exact this },
{ apply this; rwa dist_comm } },
intros p₁ p₂ q₁ q₂ h₁ h₂,
have := add_lt_add
(abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₁ q₁ p₂) h₁)).1
(abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₂ q₂ q₁) h₂)).1,
rwa [add_halves, dist_comm p₂, sub_add_sub_cancel, dist_comm q₂] at this
end⟩)
theorem uniform_continuous.dist [uniform_space β] {f g : β → α}
(hf : uniform_continuous f) (hg : uniform_continuous g) :
uniform_continuous (λb, dist (f b) (g b)) :=
uniform_continuous_dist.comp (hf.prod_mk hg)
@[continuity]
theorem continuous_dist : continuous (λp:α×α, dist p.1 p.2) :=
uniform_continuous_dist.continuous
@[continuity]
theorem continuous.dist [topological_space β] {f g : β → α}
(hf : continuous f) (hg : continuous g) : continuous (λb, dist (f b) (g b)) :=
continuous_dist.comp (hf.prod_mk hg : _)
theorem filter.tendsto.dist {f g : β → α} {x : filter β} {a b : α}
(hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) :
tendsto (λx, dist (f x) (g x)) x (𝓝 (dist a b)) :=
(continuous_dist.tendsto (a, b)).comp (hf.prod_mk_nhds hg)
lemma nhds_comap_dist (a : α) : (𝓝 (0 : ℝ)).comap (λa', dist a' a) = 𝓝 a :=
by simp only [@nhds_eq_comap_uniformity α, metric.uniformity_eq_comap_nhds_zero,
comap_comap, (∘), dist_comm]
lemma tendsto_iff_dist_tendsto_zero {f : β → α} {x : filter β} {a : α} :
(tendsto f x (𝓝 a)) ↔ (tendsto (λb, dist (f b) a) x (𝓝 0)) :=
by rw [← nhds_comap_dist a, tendsto_comap_iff]
lemma continuous_iff_continuous_dist [topological_space β] {f : β → α} :
continuous f ↔ continuous (λ x : β × β, dist (f x.1) (f x.2)) :=
⟨λ h, (h.comp continuous_fst).dist (h.comp continuous_snd), λ h, continuous_iff_continuous_at.2 $
λ x, tendsto_iff_dist_tendsto_zero.2 $
(h.comp (continuous_id.prod_mk continuous_const)).tendsto' _ _ $ dist_self _⟩
lemma uniform_continuous_nndist : uniform_continuous (λp:α×α, nndist p.1 p.2) :=
uniform_continuous_dist.subtype_mk _
lemma uniform_continuous.nndist [uniform_space β] {f g : β → α} (hf : uniform_continuous f)
(hg : uniform_continuous g) :
uniform_continuous (λ b, nndist (f b) (g b)) :=
uniform_continuous_nndist.comp (hf.prod_mk hg)
lemma continuous_nndist : continuous (λp:α×α, nndist p.1 p.2) :=
uniform_continuous_nndist.continuous
lemma continuous.nndist [topological_space β] {f g : β → α}
(hf : continuous f) (hg : continuous g) : continuous (λb, nndist (f b) (g b)) :=
continuous_nndist.comp (hf.prod_mk hg : _)
theorem filter.tendsto.nndist {f g : β → α} {x : filter β} {a b : α}
(hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) :
tendsto (λx, nndist (f x) (g x)) x (𝓝 (nndist a b)) :=
(continuous_nndist.tendsto (a, b)).comp (hf.prod_mk_nhds hg)
namespace metric
variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α}
theorem is_closed_ball : is_closed (closed_ball x ε) :=
is_closed_le (continuous_id.dist continuous_const) continuous_const
lemma is_closed_sphere : is_closed (sphere x ε) :=
is_closed_eq (continuous_id.dist continuous_const) continuous_const
@[simp] theorem closure_closed_ball : closure (closed_ball x ε) = closed_ball x ε :=
is_closed_ball.closure_eq
theorem closure_ball_subset_closed_ball : closure (ball x ε) ⊆ closed_ball x ε :=
closure_minimal ball_subset_closed_ball is_closed_ball
theorem frontier_ball_subset_sphere : frontier (ball x ε) ⊆ sphere x ε :=
frontier_lt_subset_eq (continuous_id.dist continuous_const) continuous_const
theorem frontier_closed_ball_subset_sphere : frontier (closed_ball x ε) ⊆ sphere x ε :=
frontier_le_subset_eq (continuous_id.dist continuous_const) continuous_const
theorem ball_subset_interior_closed_ball : ball x ε ⊆ interior (closed_ball x ε) :=
interior_maximal ball_subset_closed_ball is_open_ball
/-- ε-characterization of the closure in pseudometric spaces-/
theorem mem_closure_iff {s : set α} {a : α} :
a ∈ closure s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε :=
(mem_closure_iff_nhds_basis nhds_basis_ball).trans $
by simp only [mem_ball, dist_comm]
lemma mem_closure_range_iff {e : β → α} {a : α} :
a ∈ closure (range e) ↔ ∀ε>0, ∃ k : β, dist a (e k) < ε :=
by simp only [mem_closure_iff, exists_range_iff]
lemma mem_closure_range_iff_nat {e : β → α} {a : α} :
a ∈ closure (range e) ↔ ∀n : ℕ, ∃ k : β, dist a (e k) < 1 / ((n : ℝ) + 1) :=
(mem_closure_iff_nhds_basis nhds_basis_ball_inv_nat_succ).trans $
by simp only [mem_ball, dist_comm, exists_range_iff, forall_const]
theorem mem_of_closed' {s : set α} (hs : is_closed s) {a : α} :
a ∈ s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε :=
by simpa only [hs.closure_eq] using @mem_closure_iff _ _ s a
lemma closed_ball_zero' (x : α) : closed_ball x 0 = closure {x} :=
subset.antisymm
(λ y hy, mem_closure_iff.2 $ λ ε ε0, ⟨x, mem_singleton x, (mem_closed_ball.1 hy).trans_lt ε0⟩)
(closure_minimal (singleton_subset_iff.2 (dist_self x).le) is_closed_ball)
lemma dense_iff {s : set α} :
dense s ↔ ∀ x, ∀ r > 0, (ball x r ∩ s).nonempty :=
forall_congr $ λ x, by simp only [mem_closure_iff, set.nonempty, exists_prop, mem_inter_iff,
mem_ball', and_comm]
lemma dense_range_iff {f : β → α} :
dense_range f ↔ ∀ x, ∀ r > 0, ∃ y, dist x (f y) < r :=
forall_congr $ λ x, by simp only [mem_closure_iff, exists_range_iff]
/-- If a set `s` is separable, then the corresponding subtype is separable in a metric space.
This is not obvious, as the countable set whose closure covers `s` does not need in general to
be contained in `s`. -/
lemma _root_.topological_space.is_separable.separable_space {s : set α} (hs : is_separable s) :
separable_space s :=
begin
classical,
rcases eq_empty_or_nonempty s with rfl|⟨⟨x₀, x₀s⟩⟩,
{ apply_instance },
rcases hs with ⟨c, hc, h'c⟩,
haveI : encodable c := hc.to_encodable,
obtain ⟨u, -, u_pos, u_lim⟩ : ∃ (u : ℕ → ℝ), strict_anti u ∧ (∀ (n : ℕ), 0 < u n) ∧
tendsto u at_top (𝓝 0) := exists_seq_strict_anti_tendsto (0 : ℝ),
let f : c × ℕ → α := λ p, if h : (metric.ball (p.1 : α) (u p.2) ∩ s).nonempty then h.some else x₀,
have fs : ∀ p, f p ∈ s,
{ rintros ⟨y, n⟩,
by_cases h : (ball (y : α) (u n) ∩ s).nonempty,
{ simpa only [f, h, dif_pos] using h.some_spec.2 },
{ simpa only [f, h, not_false_iff, dif_neg] } },
let g : c × ℕ → s := λ p, ⟨f p, fs p⟩,
apply separable_space_of_dense_range g,
apply metric.dense_range_iff.2,
rintros ⟨x, xs⟩ r (rpos : 0 < r),
obtain ⟨n, hn⟩ : ∃ n, u n < r / 2 := ((tendsto_order.1 u_lim).2 _ (half_pos rpos)).exists,
obtain ⟨z, zc, hz⟩ : ∃ z ∈ c, dist x z < u n :=
metric.mem_closure_iff.1 (h'c xs) _ (u_pos n),
refine ⟨(⟨z, zc⟩, n), _⟩,
change dist x (f (⟨z, zc⟩, n)) < r,
have A : (metric.ball z (u n) ∩ s).nonempty := ⟨x, hz, xs⟩,
dsimp [f],
simp only [A, dif_pos],
calc dist x A.some
≤ dist x z + dist z A.some : dist_triangle _ _ _
... < r/2 + r/2 : add_lt_add (hz.trans hn) ((metric.mem_ball'.1 A.some_spec.1).trans hn)
... = r : add_halves _
end
/-- The preimage of a separable set by an inducing map is separable. -/
protected lemma _root_.inducing.is_separable_preimage {f : β → α} [topological_space β]
(hf : inducing f) {s : set α} (hs : is_separable s) :
is_separable (f ⁻¹' s) :=
begin
haveI : second_countable_topology s,
{ haveI : separable_space s := hs.separable_space,
exact uniform_space.second_countable_of_separable _ },
let g : f ⁻¹' s → s := cod_restrict (f ∘ coe) s (λ x, x.2),
have : inducing g := (hf.comp inducing_coe).cod_restrict _,
haveI : second_countable_topology (f ⁻¹' s) := this.second_countable_topology,
rw show f ⁻¹' s = coe '' (univ : set (f ⁻¹' s)),
by simpa only [image_univ, subtype.range_coe_subtype],
exact (is_separable_of_separable_space _).image continuous_subtype_coe
end
protected lemma _root_.embedding.is_separable_preimage {f : β → α} [topological_space β]
(hf : embedding f) {s : set α} (hs : is_separable s) :
is_separable (f ⁻¹' s) :=
hf.to_inducing.is_separable_preimage hs
/-- If a map is continuous on a separable set `s`, then the image of `s` is also separable. -/
lemma _root_.continuous_on.is_separable_image [topological_space β] {f : α → β} {s : set α}
(hf : continuous_on f s) (hs : is_separable s) :
is_separable (f '' s) :=
begin
rw show f '' s = s.restrict f '' univ, by ext ; simp,
exact (is_separable_univ_iff.2 hs.separable_space).image
(continuous_on_iff_continuous_restrict.1 hf),
end
end metric
section pi
open finset
variables {π : β → Type*} [fintype β] [∀b, pseudo_metric_space (π b)]
/-- A finite product of pseudometric spaces is a pseudometric space, with the sup distance. -/
instance pseudo_metric_space_pi : pseudo_metric_space (Πb, π b) :=
begin
/- we construct the instance from the pseudoemetric space instance to avoid checking again that
the uniformity is the same as the product uniformity, but we register nevertheless a nice formula
for the distance -/
refine (pseudo_emetric_space.to_pseudo_metric_space_of_dist
(λf g : Π b, π b, ((sup univ (λb, nndist (f b) (g b)) : ℝ≥0) : ℝ))
(λ f g, _) (λ f g, _)).replace_bornology (λ s, _),
show edist f g ≠ ⊤,
from ne_of_lt ((finset.sup_lt_iff bot_lt_top).2 $ λ b hb, edist_lt_top _ _),
show ↑(sup univ (λ b, nndist (f b) (g b))) = (sup univ (λ b, edist (f b) (g b))).to_real,
by simp only [edist_nndist, ← ennreal.coe_finset_sup, ennreal.coe_to_real],
show (@is_bounded _ pi.bornology s ↔ @is_bounded _ pseudo_metric_space.to_bornology _),
{ simp only [← is_bounded_def, is_bounded_iff_eventually, ← forall_is_bounded_image_eval_iff,
ball_image_iff, ← eventually_all, function.eval_apply, @dist_nndist (π _)],
refine eventually_congr ((eventually_ge_at_top 0).mono $ λ C hC, _),
lift C to ℝ≥0 using hC,
refine ⟨λ H x hx y hy, nnreal.coe_le_coe.2 $ finset.sup_le $ λ b hb, H b x hx y hy,
λ H b x hx y hy, nnreal.coe_le_coe.2 _⟩,
simpa only using finset.sup_le_iff.1 (nnreal.coe_le_coe.1 $ H hx hy) b (finset.mem_univ b) }
end
lemma nndist_pi_def (f g : Πb, π b) : nndist f g = sup univ (λb, nndist (f b) (g b)) :=
nnreal.eq rfl
lemma dist_pi_def (f g : Πb, π b) :
dist f g = (sup univ (λb, nndist (f b) (g b)) : ℝ≥0) := rfl
lemma nndist_pi_le_iff {f g : Πb, π b} {r : ℝ≥0} :
nndist f g ≤ r ↔ ∀b, nndist (f b) (g b) ≤ r :=
by simp [nndist_pi_def]
lemma dist_pi_lt_iff {f g : Πb, π b} {r : ℝ} (hr : 0 < r) :
dist f g < r ↔ ∀b, dist (f b) (g b) < r :=
begin
lift r to ℝ≥0 using hr.le,
simp [dist_pi_def, finset.sup_lt_iff (show ⊥ < r, from hr)],
end
lemma dist_pi_le_iff {f g : Πb, π b} {r : ℝ} (hr : 0 ≤ r) :
dist f g ≤ r ↔ ∀b, dist (f b) (g b) ≤ r :=
begin
lift r to ℝ≥0 using hr,
exact nndist_pi_le_iff
end
lemma dist_pi_le_iff' [nonempty β] {f g : Π b, π b} {r : ℝ} :
dist f g ≤ r ↔ ∀ b, dist (f b) (g b) ≤ r :=
begin
by_cases hr : 0 ≤ r,
{ exact dist_pi_le_iff hr },
{ exact iff_of_false (λ h, hr $ dist_nonneg.trans h)
(λ h, hr $ dist_nonneg.trans $ h $ classical.arbitrary _) }
end
lemma dist_pi_const_le (a b : α) : dist (λ _ : β, a) (λ _, b) ≤ dist a b :=
(dist_pi_le_iff dist_nonneg).2 $ λ _, le_rfl
lemma nndist_pi_const_le (a b : α) : nndist (λ _ : β, a) (λ _, b) ≤ nndist a b :=
nndist_pi_le_iff.2 $ λ _, le_rfl
@[simp] lemma dist_pi_const [nonempty β] (a b : α) : dist (λ x : β, a) (λ _, b) = dist a b :=
by simpa only [dist_edist] using congr_arg ennreal.to_real (edist_pi_const a b)
@[simp] lemma nndist_pi_const [nonempty β] (a b : α) :
nndist (λ x : β, a) (λ _, b) = nndist a b := nnreal.eq $ dist_pi_const a b
lemma nndist_le_pi_nndist (f g : Πb, π b) (b : β) : nndist (f b) (g b) ≤ nndist f g :=
by { rw [nndist_pi_def], exact finset.le_sup (finset.mem_univ b) }
lemma dist_le_pi_dist (f g : Πb, π b) (b : β) : dist (f b) (g b) ≤ dist f g :=
by simp only [dist_nndist, nnreal.coe_le_coe, nndist_le_pi_nndist f g b]
/-- An open ball in a product space is a product of open balls. See also `metric.ball_pi'`
for a version assuming `nonempty β` instead of `0 < r`. -/
lemma ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 < r) :
ball x r = set.pi univ (λ b, ball (x b) r) :=
by { ext p, simp [dist_pi_lt_iff hr] }
/-- An open ball in a product space is a product of open balls. See also `metric.ball_pi`
for a version assuming `0 < r` instead of `nonempty β`. -/
lemma ball_pi' [nonempty β] (x : Π b, π b) (r : ℝ) :
ball x r = set.pi univ (λ b, ball (x b) r) :=
(lt_or_le 0 r).elim (ball_pi x) $ λ hr, by simp [ball_eq_empty.2 hr]
/-- A closed ball in a product space is a product of closed balls. See also `metric.closed_ball_pi'`
for a version assuming `nonempty β` instead of `0 ≤ r`. -/
lemma closed_ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 ≤ r) :
closed_ball x r = set.pi univ (λ b, closed_ball (x b) r) :=
by { ext p, simp [dist_pi_le_iff hr] }
/-- A closed ball in a product space is a product of closed balls. See also `metric.closed_ball_pi`
for a version assuming `0 ≤ r` instead of `nonempty β`. -/
lemma closed_ball_pi' [nonempty β] (x : Π b, π b) (r : ℝ) :
closed_ball x r = set.pi univ (λ b, closed_ball (x b) r) :=
(le_or_lt 0 r).elim (closed_ball_pi x) $ λ hr, by simp [closed_ball_eq_empty.2 hr]
@[simp] lemma fin.nndist_insert_nth_insert_nth {n : ℕ} {α : fin (n + 1) → Type*}
[Π i, pseudo_metric_space (α i)] (i : fin (n + 1)) (x y : α i) (f g : Π j, α (i.succ_above j)) :
nndist (i.insert_nth x f) (i.insert_nth y g) = max (nndist x y) (nndist f g) :=
eq_of_forall_ge_iff $ λ c, by simp [nndist_pi_le_iff, i.forall_iff_succ_above]
@[simp] lemma fin.dist_insert_nth_insert_nth {n : ℕ} {α : fin (n + 1) → Type*}
[Π i, pseudo_metric_space (α i)] (i : fin (n + 1)) (x y : α i) (f g : Π j, α (i.succ_above j)) :
dist (i.insert_nth x f) (i.insert_nth y g) = max (dist x y) (dist f g) :=
by simp only [dist_nndist, fin.nndist_insert_nth_insert_nth, nnreal.coe_max]
lemma real.dist_le_of_mem_pi_Icc {x y x' y' : β → ℝ} (hx : x ∈ Icc x' y') (hy : y ∈ Icc x' y') :
dist x y ≤ dist x' y' :=
begin
refine (dist_pi_le_iff dist_nonneg).2 (λ b, (real.dist_le_of_mem_interval _ _).trans
(dist_le_pi_dist _ _ b)); refine Icc_subset_interval _,
exacts [⟨hx.1 _, hx.2 _⟩, ⟨hy.1 _, hy.2 _⟩]
end
end pi
section compact
/-- Any compact set in a pseudometric space can be covered by finitely many balls of a given
positive radius -/
lemma finite_cover_balls_of_compact {α : Type u} [pseudo_metric_space α] {s : set α}
(hs : is_compact s) {e : ℝ} (he : 0 < e) :
∃t ⊆ s, set.finite t ∧ s ⊆ ⋃x∈t, ball x e :=
begin
apply hs.elim_finite_subcover_image,
{ simp [is_open_ball] },
{ intros x xs,
simp,
exact ⟨x, ⟨xs, by simpa⟩⟩ }
end
alias finite_cover_balls_of_compact ← is_compact.finite_cover_balls
end compact
section proper_space
open metric
/-- A pseudometric space is proper if all closed balls are compact. -/
class proper_space (α : Type u) [pseudo_metric_space α] : Prop :=
(is_compact_closed_ball : ∀x:α, ∀r, is_compact (closed_ball x r))
export proper_space (is_compact_closed_ball)
/-- In a proper pseudometric space, all spheres are compact. -/
lemma is_compact_sphere {α : Type*} [pseudo_metric_space α] [proper_space α] (x : α) (r : ℝ) :
is_compact (sphere x r) :=
is_compact_of_is_closed_subset (is_compact_closed_ball x r) is_closed_sphere
sphere_subset_closed_ball
/-- In a proper pseudometric space, any sphere is a `compact_space` when considered as a subtype. -/
instance {α : Type*} [pseudo_metric_space α] [proper_space α] (x : α) (r : ℝ) :
compact_space (sphere x r) :=
is_compact_iff_compact_space.mp (is_compact_sphere _ _)
/-- A proper pseudo metric space is sigma compact, and therefore second countable. -/
@[priority 100] -- see Note [lower instance priority]
instance second_countable_of_proper [proper_space α] :
second_countable_topology α :=
begin
-- We already have `sigma_compact_space_of_locally_compact_second_countable`, so we don't
-- add an instance for `sigma_compact_space`.
suffices : sigma_compact_space α, by exactI emetric.second_countable_of_sigma_compact α,
rcases em (nonempty α) with ⟨⟨x⟩⟩|hn,
{ exact ⟨⟨λ n, closed_ball x n, λ n, is_compact_closed_ball _ _, Union_closed_ball_nat _⟩⟩ },
{ exact ⟨⟨λ n, ∅, λ n, is_compact_empty, Union_eq_univ_iff.2 $ λ x, (hn ⟨x⟩).elim⟩⟩ }
end
lemma tendsto_dist_right_cocompact_at_top [proper_space α] (x : α) :
tendsto (λ y, dist y x) (cocompact α) at_top :=
(has_basis_cocompact.tendsto_iff at_top_basis).2 $ λ r hr,
⟨closed_ball x r, is_compact_closed_ball x r, λ y hy, (not_le.1 $ mt mem_closed_ball.2 hy).le⟩
lemma tendsto_dist_left_cocompact_at_top [proper_space α] (x : α) :
tendsto (dist x) (cocompact α) at_top :=
by simpa only [dist_comm] using tendsto_dist_right_cocompact_at_top x
/-- If all closed balls of large enough radius are compact, then the space is proper. Especially
useful when the lower bound for the radius is 0. -/
lemma proper_space_of_compact_closed_ball_of_le
(R : ℝ) (h : ∀x:α, ∀r, R ≤ r → is_compact (closed_ball x r)) :
proper_space α :=
⟨begin
assume x r,
by_cases hr : R ≤ r,
{ exact h x r hr },
{ have : closed_ball x r = closed_ball x R ∩ closed_ball x r,
{ symmetry,
apply inter_eq_self_of_subset_right,
exact closed_ball_subset_closed_ball (le_of_lt (not_le.1 hr)) },
rw this,
exact (h x R le_rfl).inter_right is_closed_ball }
end⟩
/- A compact pseudometric space is proper -/
@[priority 100] -- see Note [lower instance priority]
instance proper_of_compact [compact_space α] : proper_space α :=
⟨assume x r, is_closed_ball.is_compact⟩
/-- A proper space is locally compact -/
@[priority 100] -- see Note [lower instance priority]
instance locally_compact_of_proper [proper_space α] :
locally_compact_space α :=
locally_compact_space_of_has_basis (λ x, nhds_basis_closed_ball) $
λ x ε ε0, is_compact_closed_ball _ _
/-- A proper space is complete -/
@[priority 100] -- see Note [lower instance priority]
instance complete_of_proper [proper_space α] : complete_space α :=
⟨begin
intros f hf,
/- We want to show that the Cauchy filter `f` is converging. It suffices to find a closed
ball (therefore compact by properness) where it is nontrivial. -/
obtain ⟨t, t_fset, ht⟩ : ∃ t ∈ f, ∀ x y ∈ t, dist x y < 1 :=
(metric.cauchy_iff.1 hf).2 1 zero_lt_one,
rcases hf.1.nonempty_of_mem t_fset with ⟨x, xt⟩,
have : closed_ball x 1 ∈ f := mem_of_superset t_fset (λ y yt, (ht y yt x xt).le),
rcases (is_compact_iff_totally_bounded_is_complete.1 (is_compact_closed_ball x 1)).2 f hf
(le_principal_iff.2 this) with ⟨y, -, hy⟩,
exact ⟨y, hy⟩
end⟩
/-- A finite product of proper spaces is proper. -/
instance pi_proper_space {π : β → Type*} [fintype β] [∀b, pseudo_metric_space (π b)]
[h : ∀b, proper_space (π b)] : proper_space (Πb, π b) :=
begin
refine proper_space_of_compact_closed_ball_of_le 0 (λx r hr, _),
rw closed_ball_pi _ hr,
apply is_compact_univ_pi (λb, _),
apply (h b).is_compact_closed_ball
end
variables [proper_space α] {x : α} {r : ℝ} {s : set α}
/-- If a nonempty ball in a proper space includes a closed set `s`, then there exists a nonempty
ball with the same center and a strictly smaller radius that includes `s`. -/
lemma exists_pos_lt_subset_ball (hr : 0 < r) (hs : is_closed s) (h : s ⊆ ball x r) :
∃ r' ∈ Ioo 0 r, s ⊆ ball x r' :=
begin
unfreezingI { rcases eq_empty_or_nonempty s with rfl|hne },
{ exact ⟨r / 2, ⟨half_pos hr, half_lt_self hr⟩, empty_subset _⟩ },
have : is_compact s,
from is_compact_of_is_closed_subset (is_compact_closed_ball x r) hs
(subset.trans h ball_subset_closed_ball),
obtain ⟨y, hys, hy⟩ : ∃ y ∈ s, s ⊆ closed_ball x (dist y x),
from this.exists_forall_ge hne (continuous_id.dist continuous_const).continuous_on,
have hyr : dist y x < r, from h hys,
rcases exists_between hyr with ⟨r', hyr', hrr'⟩,
exact ⟨r', ⟨dist_nonneg.trans_lt hyr', hrr'⟩, subset.trans hy $ closed_ball_subset_ball hyr'⟩
end
/-- If a ball in a proper space includes a closed set `s`, then there exists a ball with the same
center and a strictly smaller radius that includes `s`. -/
lemma exists_lt_subset_ball (hs : is_closed s) (h : s ⊆ ball x r) :
∃ r' < r, s ⊆ ball x r' :=
begin
cases le_or_lt r 0 with hr hr,
{ rw [ball_eq_empty.2 hr, subset_empty_iff] at h, unfreezingI { subst s },
exact (exists_lt r).imp (λ r' hr', ⟨hr', empty_subset _⟩) },
{ exact (exists_pos_lt_subset_ball hr hs h).imp (λ r' hr', ⟨hr'.fst.2, hr'.snd⟩) }
end
end proper_space
lemma is_compact.is_separable {s : set α} (hs : is_compact s) :
is_separable s :=
begin
haveI : compact_space s := is_compact_iff_compact_space.mp hs,
exact is_separable_of_separable_space_subtype s,
end
namespace metric
section second_countable
open topological_space
/-- A pseudometric space is second countable if, for every `ε > 0`, there is a countable set which
is `ε`-dense. -/
lemma second_countable_of_almost_dense_set
(H : ∀ε > (0 : ℝ), ∃ s : set α, s.countable ∧ (∀x, ∃y ∈ s, dist x y ≤ ε)) :
second_countable_topology α :=
begin
refine emetric.second_countable_of_almost_dense_set (λ ε ε0, _),
rcases ennreal.lt_iff_exists_nnreal_btwn.1 ε0 with ⟨ε', ε'0, ε'ε⟩,
choose s hsc y hys hyx using H ε' (by exact_mod_cast ε'0),
refine ⟨s, hsc, Union₂_eq_univ_iff.2 (λ x, ⟨y x, hys _, le_trans _ ε'ε.le⟩)⟩,
exact_mod_cast hyx x
end
end second_countable
end metric
lemma lebesgue_number_lemma_of_metric
{s : set α} {ι} {c : ι → set α} (hs : is_compact s)
(hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) :
∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i :=
let ⟨n, en, hn⟩ := lebesgue_number_lemma hs hc₁ hc₂,
⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 en in
⟨δ, δ0, assume x hx, let ⟨i, hi⟩ := hn x hx in
⟨i, assume y hy, hi (hδ (mem_ball'.mp hy))⟩⟩
lemma lebesgue_number_lemma_of_metric_sUnion
{s : set α} {c : set (set α)} (hs : is_compact s)
(hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) :
∃ δ > 0, ∀ x ∈ s, ∃ t ∈ c, ball x δ ⊆ t :=
by rw sUnion_eq_Union at hc₂;
simpa using lebesgue_number_lemma_of_metric hs (by simpa) hc₂
namespace metric
/-- Boundedness of a subset of a pseudometric space. We formulate the definition to work
even in the empty space. -/
def bounded (s : set α) : Prop :=
∃C, ∀x y ∈ s, dist x y ≤ C
section bounded
variables {x : α} {s t : set α} {r : ℝ}
lemma bounded_iff_is_bounded (s : set α) : bounded s ↔ is_bounded s :=
begin
change bounded s ↔ sᶜ ∈ (cobounded α).sets,
simp [pseudo_metric_space.cobounded_sets, metric.bounded],
end
@[simp] lemma bounded_empty : bounded (∅ : set α) :=
⟨0, by simp⟩
lemma bounded_iff_mem_bounded : bounded s ↔ ∀ x ∈ s, bounded s :=
⟨λ h _ _, h, λ H,
s.eq_empty_or_nonempty.elim
(λ hs, hs.symm ▸ bounded_empty)
(λ ⟨x, hx⟩, H x hx)⟩
/-- Subsets of a bounded set are also bounded -/
lemma bounded.mono (incl : s ⊆ t) : bounded t → bounded s :=
Exists.imp $ λ C hC x hx y hy, hC x (incl hx) y (incl hy)
/-- Closed balls are bounded -/
lemma bounded_closed_ball : bounded (closed_ball x r) :=
⟨r + r, λ y hy z hz, begin
simp only [mem_closed_ball] at *,
calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _
... ≤ r + r : add_le_add hy hz
end⟩
/-- Open balls are bounded -/
lemma bounded_ball : bounded (ball x r) :=
bounded_closed_ball.mono ball_subset_closed_ball
/-- Spheres are bounded -/
lemma bounded_sphere : bounded (sphere x r) :=
bounded_closed_ball.mono sphere_subset_closed_ball
/-- Given a point, a bounded subset is included in some ball around this point -/
lemma bounded_iff_subset_ball (c : α) : bounded s ↔ ∃r, s ⊆ closed_ball c r :=
begin
split; rintro ⟨C, hC⟩,
{ cases s.eq_empty_or_nonempty with h h,
{ subst s, exact ⟨0, by simp⟩ },
{ rcases h with ⟨x, hx⟩,
exact ⟨C + dist x c, λ y hy, calc
dist y c ≤ dist y x + dist x c : dist_triangle _ _ _
... ≤ C + dist x c : add_le_add_right (hC y hy x hx) _⟩ } },
{ exact bounded_closed_ball.mono hC }
end
lemma bounded.subset_ball (h : bounded s) (c : α) : ∃ r, s ⊆ closed_ball c r :=
(bounded_iff_subset_ball c).1 h
lemma bounded.subset_ball_lt (h : bounded s) (a : ℝ) (c : α) : ∃ r, a < r ∧ s ⊆ closed_ball c r :=
begin
rcases h.subset_ball c with ⟨r, hr⟩,
refine ⟨max r (a+1), lt_of_lt_of_le (by linarith) (le_max_right _ _), _⟩,
exact subset.trans hr (closed_ball_subset_closed_ball (le_max_left _ _))
end
lemma bounded_closure_of_bounded (h : bounded s) : bounded (closure s) :=
let ⟨C, h⟩ := h in
⟨C, λ a ha b hb, (is_closed_le' C).closure_subset $ map_mem_closure₂ continuous_dist ha hb h⟩
alias bounded_closure_of_bounded ← bounded.closure
@[simp] lemma bounded_closure_iff : bounded (closure s) ↔ bounded s :=
⟨λ h, h.mono subset_closure, λ h, h.closure⟩
/-- The union of two bounded sets is bounded. -/
lemma bounded.union (hs : bounded s) (ht : bounded t) : bounded (s ∪ t) :=
begin
refine bounded_iff_mem_bounded.2 (λ x _, _),
rw bounded_iff_subset_ball x at hs ht ⊢,
rcases hs with ⟨Cs, hCs⟩, rcases ht with ⟨Ct, hCt⟩,
exact ⟨max Cs Ct, union_subset
(subset.trans hCs $ closed_ball_subset_closed_ball $ le_max_left _ _)
(subset.trans hCt $ closed_ball_subset_closed_ball $ le_max_right _ _)⟩,
end
/-- The union of two sets is bounded iff each of the sets is bounded. -/
@[simp] lemma bounded_union : bounded (s ∪ t) ↔ bounded s ∧ bounded t :=
⟨λ h, ⟨h.mono (by simp), h.mono (by simp)⟩, λ h, h.1.union h.2⟩
/-- A finite union of bounded sets is bounded -/
lemma bounded_bUnion {I : set β} {s : β → set α} (H : I.finite) :
bounded (⋃i∈I, s i) ↔ ∀i ∈ I, bounded (s i) :=
finite.induction_on H (by simp) $ λ x I _ _ IH,
by simp [or_imp_distrib, forall_and_distrib, IH]
protected lemma bounded.prod [pseudo_metric_space β] {s : set α} {t : set β}
(hs : bounded s) (ht : bounded t) : bounded (s ×ˢ t) :=
begin
refine bounded_iff_mem_bounded.mpr (λ x hx, _),
rcases hs.subset_ball x.1 with ⟨rs, hrs⟩,
rcases ht.subset_ball x.2 with ⟨rt, hrt⟩,
suffices : s ×ˢ t ⊆ closed_ball x (max rs rt),
from bounded_closed_ball.mono this,
rw [← @prod.mk.eta _ _ x, ← closed_ball_prod_same],
exact prod_mono (hrs.trans $ closed_ball_subset_closed_ball $ le_max_left _ _)
(hrt.trans $ closed_ball_subset_closed_ball $ le_max_right _ _)
end
/-- A totally bounded set is bounded -/
lemma _root_.totally_bounded.bounded {s : set α} (h : totally_bounded s) : bounded s :=
-- We cover the totally bounded set by finitely many balls of radius 1,
-- and then argue that a finite union of bounded sets is bounded
let ⟨t, fint, subs⟩ := (totally_bounded_iff.mp h) 1 zero_lt_one in
bounded.mono subs $ (bounded_bUnion fint).2 $ λ i hi, bounded_ball
/-- A compact set is bounded -/
lemma _root_.is_compact.bounded {s : set α} (h : is_compact s) : bounded s :=
-- A compact set is totally bounded, thus bounded
h.totally_bounded.bounded
/-- A finite set is bounded -/
lemma bounded_of_finite {s : set α} (h : s.finite) : bounded s :=
h.is_compact.bounded
alias bounded_of_finite ← _root_.set.finite.bounded
/-- A singleton is bounded -/
lemma bounded_singleton {x : α} : bounded ({x} : set α) :=
bounded_of_finite $ finite_singleton _
/-- Characterization of the boundedness of the range of a function -/
lemma bounded_range_iff {f : β → α} : bounded (range f) ↔ ∃C, ∀x y, dist (f x) (f y) ≤ C :=
exists_congr $ λ C, ⟨
λ H x y, H _ ⟨x, rfl⟩ _ ⟨y, rfl⟩,
by rintro H _ ⟨x, rfl⟩ _ ⟨y, rfl⟩; exact H x y⟩
lemma bounded_range_of_tendsto_cofinite_uniformity {f : β → α}
(hf : tendsto (prod.map f f) (cofinite ×ᶠ cofinite) (𝓤 α)) :
bounded (range f) :=
begin
rcases (has_basis_cofinite.prod_self.tendsto_iff uniformity_basis_dist).1 hf 1 zero_lt_one
with ⟨s, hsf, hs1⟩,
rw [← image_univ, ← union_compl_self s, image_union, bounded_union],
use [(hsf.image f).bounded, 1],
rintro _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩,
exact le_of_lt (hs1 (x, y) ⟨hx, hy⟩)
end
lemma bounded_range_of_cauchy_map_cofinite {f : β → α} (hf : cauchy (map f cofinite)) :
bounded (range f) :=
bounded_range_of_tendsto_cofinite_uniformity $ (cauchy_map_iff.1 hf).2
lemma _root_.cauchy_seq.bounded_range {f : ℕ → α} (hf : cauchy_seq f) : bounded (range f) :=
bounded_range_of_cauchy_map_cofinite $ by rwa nat.cofinite_eq_at_top
lemma bounded_range_of_tendsto_cofinite {f : β → α} {a : α} (hf : tendsto f cofinite (𝓝 a)) :
bounded (range f) :=
bounded_range_of_tendsto_cofinite_uniformity $
(hf.prod_map hf).mono_right $ nhds_prod_eq.symm.trans_le (nhds_le_uniformity a)
/-- In a compact space, all sets are bounded -/
lemma bounded_of_compact_space [compact_space α] : bounded s :=
is_compact_univ.bounded.mono (subset_univ _)
lemma bounded_range_of_tendsto (u : ℕ → α) {x : α} (hu : tendsto u at_top (𝓝 x)) :
bounded (range u) :=
hu.cauchy_seq.bounded_range
/-- If a function is continuous within a set `s` at every point of a compact set `k`, then it is
bounded on some open neighborhood of `k` in `s`. -/
lemma exists_is_open_bounded_image_inter_of_is_compact_of_forall_continuous_within_at
[topological_space β] {k s : set β} {f : β → α}
(hk : is_compact k) (hf : ∀ x ∈ k, continuous_within_at f s x) :
∃ t, k ⊆ t ∧ is_open t ∧ bounded (f '' (t ∩ s)) :=
begin
apply hk.induction_on,
{ exact ⟨∅, subset.refl _, is_open_empty,
by simp only [image_empty, bounded_empty, empty_inter]⟩ },
{ rintros s s' hss' ⟨t, s't, t_open, t_bounded⟩,
exact ⟨t, hss'.trans s't, t_open, t_bounded⟩ },
{ rintros s s' ⟨t, st, t_open, t_bounded⟩ ⟨t', s't', t'_open, t'_bounded⟩,
refine ⟨t ∪ t', union_subset_union st s't', t_open.union t'_open, _⟩,
rw [union_inter_distrib_right, image_union],
exact t_bounded.union t'_bounded },
{ assume x hx,
have A : ball (f x) 1 ∈ 𝓝 (f x), from ball_mem_nhds _ zero_lt_one,
have B : f ⁻¹' (ball (f x) 1) ∈ 𝓝[s] x, from hf x hx A,
obtain ⟨u, u_open, xu, uf⟩ : ∃ (u : set β), is_open u ∧ x ∈ u ∧ u ∩ s ⊆ f ⁻¹' ball (f x) 1,
from _root_.mem_nhds_within.1 B,
refine ⟨u, _, u, subset.refl _, u_open, _⟩,
{ apply nhds_within_le_nhds,
exact u_open.mem_nhds xu },
{ apply bounded.mono (image_subset _ uf),
exact bounded_ball.mono (image_preimage_subset _ _) } }
end
/-- If a function is continuous at every point of a compact set `k`, then it is bounded on
some open neighborhood of `k`. -/
lemma exists_is_open_bounded_image_of_is_compact_of_forall_continuous_at
[topological_space β] {k : set β} {f : β → α}
(hk : is_compact k) (hf : ∀ x ∈ k, continuous_at f x) :
∃ t, k ⊆ t ∧ is_open t ∧ bounded (f '' t) :=
begin
simp_rw ← continuous_within_at_univ at hf,
simpa only [inter_univ] using
exists_is_open_bounded_image_inter_of_is_compact_of_forall_continuous_within_at hk hf,
end
/-- If a function is continuous on a set `s` containing a compact set `k`, then it is bounded on
some open neighborhood of `k` in `s`. -/
lemma exists_is_open_bounded_image_inter_of_is_compact_of_continuous_on
[topological_space β] {k s : set β} {f : β → α}
(hk : is_compact k) (hks : k ⊆ s) (hf : continuous_on f s) :
∃ t, k ⊆ t ∧ is_open t ∧ bounded (f '' (t ∩ s)) :=
exists_is_open_bounded_image_inter_of_is_compact_of_forall_continuous_within_at hk
(λ x hx, hf x (hks hx))
/-- If a function is continuous on a neighborhood of a compact set `k`, then it is bounded on
some open neighborhood of `k`. -/
lemma exists_is_open_bounded_image_of_is_compact_of_continuous_on
[topological_space β] {k s : set β} {f : β → α}
(hk : is_compact k) (hs : is_open s) (hks : k ⊆ s) (hf : continuous_on f s) :
∃ t, k ⊆ t ∧ is_open t ∧ bounded (f '' t) :=
exists_is_open_bounded_image_of_is_compact_of_forall_continuous_at hk
(λ x hx, hf.continuous_at (hs.mem_nhds (hks hx)))
/-- The **Heine–Borel theorem**: In a proper space, a closed bounded set is compact. -/
lemma is_compact_of_is_closed_bounded [proper_space α] (hc : is_closed s) (hb : bounded s) :
is_compact s :=
begin
unfreezingI { rcases eq_empty_or_nonempty s with (rfl|⟨x, hx⟩) },
{ exact is_compact_empty },
{ rcases hb.subset_ball x with ⟨r, hr⟩,
exact is_compact_of_is_closed_subset (is_compact_closed_ball x r) hc hr }
end
/-- The **Heine–Borel theorem**: In a proper space, the closure of a bounded set is compact. -/
lemma bounded.is_compact_closure [proper_space α] (h : bounded s) :
is_compact (closure s) :=
is_compact_of_is_closed_bounded is_closed_closure h.closure
/-- The **Heine–Borel theorem**:
In a proper Hausdorff space, a set is compact if and only if it is closed and bounded. -/
lemma is_compact_iff_is_closed_bounded [t2_space α] [proper_space α] :
is_compact s ↔ is_closed s ∧ bounded s :=
⟨λ h, ⟨h.is_closed, h.bounded⟩, λ h, is_compact_of_is_closed_bounded h.1 h.2⟩
lemma compact_space_iff_bounded_univ [proper_space α] : compact_space α ↔ bounded (univ : set α) :=
⟨@bounded_of_compact_space α _ _, λ hb, ⟨is_compact_of_is_closed_bounded is_closed_univ hb⟩⟩
section conditionally_complete_linear_order
variables [preorder α] [compact_Icc_space α]
lemma bounded_Icc (a b : α) : bounded (Icc a b) :=
(totally_bounded_Icc a b).bounded
lemma bounded_Ico (a b : α) : bounded (Ico a b) :=
(totally_bounded_Ico a b).bounded
lemma bounded_Ioc (a b : α) : bounded (Ioc a b) :=
(totally_bounded_Ioc a b).bounded
lemma bounded_Ioo (a b : α) : bounded (Ioo a b) :=
(totally_bounded_Ioo a b).bounded
/-- In a pseudo metric space with a conditionally complete linear order such that the order and the
metric structure give the same topology, any order-bounded set is metric-bounded. -/
lemma bounded_of_bdd_above_of_bdd_below {s : set α} (h₁ : bdd_above s) (h₂ : bdd_below s) :
bounded s :=
let ⟨u, hu⟩ := h₁, ⟨l, hl⟩ := h₂ in
bounded.mono (λ x hx, mem_Icc.mpr ⟨hl hx, hu hx⟩) (bounded_Icc l u)
end conditionally_complete_linear_order
end bounded
section diam
variables {s : set α} {x y z : α}
/-- The diameter of a set in a metric space. To get controllable behavior even when the diameter
should be infinite, we express it in terms of the emetric.diameter -/
noncomputable def diam (s : set α) : ℝ := ennreal.to_real (emetric.diam s)
/-- The diameter of a set is always nonnegative -/
lemma diam_nonneg : 0 ≤ diam s := ennreal.to_real_nonneg
lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 :=
by simp only [diam, emetric.diam_subsingleton hs, ennreal.zero_to_real]
/-- The empty set has zero diameter -/
@[simp] lemma diam_empty : diam (∅ : set α) = 0 :=
diam_subsingleton subsingleton_empty
/-- A singleton has zero diameter -/
@[simp] lemma diam_singleton : diam ({x} : set α) = 0 :=
diam_subsingleton subsingleton_singleton
-- Does not work as a simp-lemma, since {x, y} reduces to (insert y {x})
lemma diam_pair : diam ({x, y} : set α) = dist x y :=
by simp only [diam, emetric.diam_pair, dist_edist]
-- Does not work as a simp-lemma, since {x, y, z} reduces to (insert z (insert y {x}))
lemma diam_triple :
metric.diam ({x, y, z} : set α) = max (max (dist x y) (dist x z)) (dist y z) :=
begin
simp only [metric.diam, emetric.diam_triple, dist_edist],
rw [ennreal.to_real_max, ennreal.to_real_max];
apply_rules [ne_of_lt, edist_lt_top, max_lt]
end
/-- If the distance between any two points in a set is bounded by some constant `C`,
then `ennreal.of_real C` bounds the emetric diameter of this set. -/
lemma ediam_le_of_forall_dist_le {C : ℝ} (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) :
emetric.diam s ≤ ennreal.of_real C :=
emetric.diam_le $
λ x hx y hy, (edist_dist x y).symm ▸ ennreal.of_real_le_of_real (h x hx y hy)
/-- If the distance between any two points in a set is bounded by some non-negative constant,
this constant bounds the diameter. -/
lemma diam_le_of_forall_dist_le {C : ℝ} (h₀ : 0 ≤ C) (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) :
diam s ≤ C :=
ennreal.to_real_le_of_le_of_real h₀ (ediam_le_of_forall_dist_le h)
/-- If the distance between any two points in a nonempty set is bounded by some constant,
this constant bounds the diameter. -/
lemma diam_le_of_forall_dist_le_of_nonempty (hs : s.nonempty) {C : ℝ}
(h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : diam s ≤ C :=
have h₀ : 0 ≤ C, from let ⟨x, hx⟩ := hs in le_trans dist_nonneg (h x hx x hx),
diam_le_of_forall_dist_le h₀ h
/-- The distance between two points in a set is controlled by the diameter of the set. -/
lemma dist_le_diam_of_mem' (h : emetric.diam s ≠ ⊤) (hx : x ∈ s) (hy : y ∈ s) :
dist x y ≤ diam s :=
begin
rw [diam, dist_edist],
rw ennreal.to_real_le_to_real (edist_ne_top _ _) h,
exact emetric.edist_le_diam_of_mem hx hy
end
/-- Characterize the boundedness of a set in terms of the finiteness of its emetric.diameter. -/
lemma bounded_iff_ediam_ne_top : bounded s ↔ emetric.diam s ≠ ⊤ :=
iff.intro
(λ ⟨C, hC⟩, ne_top_of_le_ne_top ennreal.of_real_ne_top $ ediam_le_of_forall_dist_le hC)
(λ h, ⟨diam s, λ x hx y hy, dist_le_diam_of_mem' h hx hy⟩)
lemma bounded.ediam_ne_top (h : bounded s) : emetric.diam s ≠ ⊤ :=
bounded_iff_ediam_ne_top.1 h
lemma ediam_univ_eq_top_iff_noncompact [proper_space α] :
emetric.diam (univ : set α) = ∞ ↔ noncompact_space α :=
by rw [← not_compact_space_iff, compact_space_iff_bounded_univ, bounded_iff_ediam_ne_top, not_not]
@[simp] lemma ediam_univ_of_noncompact [proper_space α] [noncompact_space α] :
emetric.diam (univ : set α) = ∞ :=
ediam_univ_eq_top_iff_noncompact.mpr ‹_›
@[simp] lemma diam_univ_of_noncompact [proper_space α] [noncompact_space α] :
diam (univ : set α) = 0 :=
by simp [diam]
/-- The distance between two points in a set is controlled by the diameter of the set. -/
lemma dist_le_diam_of_mem (h : bounded s) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s :=
dist_le_diam_of_mem' h.ediam_ne_top hx hy
lemma ediam_of_unbounded (h : ¬(bounded s)) : emetric.diam s = ∞ :=
by rwa [bounded_iff_ediam_ne_top, not_not] at h
/-- An unbounded set has zero diameter. If you would prefer to get the value ∞, use `emetric.diam`.
This lemma makes it possible to avoid side conditions in some situations -/
lemma diam_eq_zero_of_unbounded (h : ¬(bounded s)) : diam s = 0 :=
by rw [diam, ediam_of_unbounded h, ennreal.top_to_real]
/-- If `s ⊆ t`, then the diameter of `s` is bounded by that of `t`, provided `t` is bounded. -/
lemma diam_mono {s t : set α} (h : s ⊆ t) (ht : bounded t) : diam s ≤ diam t :=
begin
unfold diam,
rw ennreal.to_real_le_to_real (bounded.mono h ht).ediam_ne_top ht.ediam_ne_top,
exact emetric.diam_mono h
end
/-- The diameter of a union is controlled by the sum of the diameters, and the distance between
any two points in each of the sets. This lemma is true without any side condition, since it is
obviously true if `s ∪ t` is unbounded. -/
lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) :
diam (s ∪ t) ≤ diam s + dist x y + diam t :=
begin
by_cases H : bounded (s ∪ t),
{ have hs : bounded s, from H.mono (subset_union_left _ _),
have ht : bounded t, from H.mono (subset_union_right _ _),
rw [bounded_iff_ediam_ne_top] at H hs ht,
rw [dist_edist, diam, diam, diam, ← ennreal.to_real_add, ← ennreal.to_real_add,
ennreal.to_real_le_to_real];
repeat { apply ennreal.add_ne_top.2; split }; try { assumption };
try { apply edist_ne_top },
exact emetric.diam_union xs yt },
{ rw [diam_eq_zero_of_unbounded H],
apply_rules [add_nonneg, diam_nonneg, dist_nonneg] }
end
/-- If two sets intersect, the diameter of the union is bounded by the sum of the diameters. -/
lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t :=
begin
rcases h with ⟨x, ⟨xs, xt⟩⟩,
simpa using diam_union xs xt
end
lemma diam_le_of_subset_closed_ball {r : ℝ} (hr : 0 ≤ r) (h : s ⊆ closed_ball x r) :
diam s ≤ 2 * r :=
diam_le_of_forall_dist_le (mul_nonneg zero_le_two hr) $ λa ha b hb, calc
dist a b ≤ dist a x + dist b x : dist_triangle_right _ _ _
... ≤ r + r : add_le_add (h ha) (h hb)
... = 2 * r : by simp [mul_two, mul_comm]
/-- The diameter of a closed ball of radius `r` is at most `2 r`. -/
lemma diam_closed_ball {r : ℝ} (h : 0 ≤ r) : diam (closed_ball x r) ≤ 2 * r :=
diam_le_of_subset_closed_ball h subset.rfl
/-- The diameter of a ball of radius `r` is at most `2 r`. -/
lemma diam_ball {r : ℝ} (h : 0 ≤ r) : diam (ball x r) ≤ 2 * r :=
diam_le_of_subset_closed_ball h ball_subset_closed_ball
/-- If a family of complete sets with diameter tending to `0` is such that each finite intersection
is nonempty, then the total intersection is also nonempty. -/
lemma _root_.is_complete.nonempty_Inter_of_nonempty_bInter {s : ℕ → set α} (h0 : is_complete (s 0))
(hs : ∀ n, is_closed (s n)) (h's : ∀ n, bounded (s n)) (h : ∀ N, (⋂ n ≤ N, s n).nonempty)
(h' : tendsto (λ n, diam (s n)) at_top (𝓝 0)) :
(⋂ n, s n).nonempty :=
begin
let u := λ N, (h N).some,
have I : ∀ n N, n ≤ N → u N ∈ s n,
{ assume n N hn,
apply mem_of_subset_of_mem _ ((h N).some_spec),
assume x hx,
simp only [mem_Inter] at hx,
exact hx n hn },
have : ∀ n, u n ∈ s 0 := λ n, I 0 n (zero_le _),
have : cauchy_seq u,
{ apply cauchy_seq_of_le_tendsto_0 _ _ h',
assume m n N hm hn,
exact dist_le_diam_of_mem (h's N) (I _ _ hm) (I _ _ hn) },
obtain ⟨x, hx, xlim⟩ : ∃ (x : α) (H : x ∈ s 0), tendsto (λ (n : ℕ), u n) at_top (𝓝 x) :=
cauchy_seq_tendsto_of_is_complete h0 (λ n, I 0 n (zero_le _)) this,
refine ⟨x, mem_Inter.2 (λ n, _)⟩,
apply (hs n).mem_of_tendsto xlim,
filter_upwards [Ici_mem_at_top n] with p hp,
exact I n p hp,
end
/-- In a complete space, if a family of closed sets with diameter tending to `0` is such that each
finite intersection is nonempty, then the total intersection is also nonempty. -/
lemma nonempty_Inter_of_nonempty_bInter [complete_space α] {s : ℕ → set α}
(hs : ∀ n, is_closed (s n)) (h's : ∀ n, bounded (s n)) (h : ∀ N, (⋂ n ≤ N, s n).nonempty)
(h' : tendsto (λ n, diam (s n)) at_top (𝓝 0)) :
(⋂ n, s n).nonempty :=
(hs 0).is_complete.nonempty_Inter_of_nonempty_bInter hs h's h h'
end diam
lemma exists_local_min_mem_ball [proper_space α] [topological_space β]
[conditionally_complete_linear_order β] [order_topology β]
{f : α → β} {a z : α} {r : ℝ} (hf : continuous_on f (closed_ball a r))
(hz : z ∈ closed_ball a r) (hf1 : ∀ z' ∈ sphere a r, f z < f z') :
∃ z ∈ ball a r, is_local_min f z :=
begin
simp_rw [← closed_ball_diff_ball] at hf1,
exact (is_compact_closed_ball a r).exists_local_min_mem_open ball_subset_closed_ball hf hz hf1
is_open_ball,
end
end metric
namespace tactic
open positivity
/-- Extension for the `positivity` tactic: the diameter of a set is always nonnegative. -/
@[positivity]
meta def positivity_diam : expr → tactic strictness
| `(metric.diam %%s) := nonnegative <$> mk_app ``metric.diam_nonneg [s]
| e := pp e >>= fail ∘ format.bracket "The expression " " is not of the form `metric.diam s`"
end tactic
lemma comap_dist_right_at_top_le_cocompact (x : α) : comap (λ y, dist y x) at_top ≤ cocompact α :=
begin
refine filter.has_basis_cocompact.ge_iff.2 (λ s hs, mem_comap.2 _),
rcases hs.bounded.subset_ball x with ⟨r, hr⟩,
exact ⟨Ioi r, Ioi_mem_at_top r, λ y hy hys, (mem_closed_ball.1 $ hr hys).not_lt hy⟩
end
lemma comap_dist_left_at_top_le_cocompact (x : α) : comap (dist x) at_top ≤ cocompact α :=
by simpa only [dist_comm _ x] using comap_dist_right_at_top_le_cocompact x
lemma comap_dist_right_at_top_eq_cocompact [proper_space α] (x : α) :
comap (λ y, dist y x) at_top = cocompact α :=
(comap_dist_right_at_top_le_cocompact x).antisymm $ (tendsto_dist_right_cocompact_at_top x).le_comap
lemma comap_dist_left_at_top_eq_cocompact [proper_space α] (x : α) :
comap (dist x) at_top = cocompact α :=
(comap_dist_left_at_top_le_cocompact x).antisymm $ (tendsto_dist_left_cocompact_at_top x).le_comap
lemma tendsto_cocompact_of_tendsto_dist_comp_at_top {f : β → α} {l : filter β} (x : α)
(h : tendsto (λ y, dist (f y) x) l at_top) : tendsto f l (cocompact α) :=
by { refine tendsto.mono_right _ (comap_dist_right_at_top_le_cocompact x), rwa tendsto_comap_iff }
/-- We now define `metric_space`, extending `pseudo_metric_space`. -/
class metric_space (α : Type u) extends pseudo_metric_space α : Type u :=
(eq_of_dist_eq_zero : ∀ {x y : α}, dist x y = 0 → x = y)
/-- Two metric space structures with the same distance coincide. -/
@[ext] lemma metric_space.ext {α : Type*} {m m' : metric_space α}
(h : m.to_has_dist = m'.to_has_dist) : m = m' :=
begin
have h' : m.to_pseudo_metric_space = m'.to_pseudo_metric_space := pseudo_metric_space.ext h,
unfreezingI { rcases m, rcases m' },
dsimp at h',
unfreezingI { subst h' },
end
/-- Construct a metric space structure whose underlying topological space structure
(definitionally) agrees which a pre-existing topology which is compatible with a given distance
function. -/
def metric_space.of_metrizable {α : Type*} [topological_space α] (dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z)
(H : ∀ s : set α, is_open s ↔ ∀ x ∈ s, ∃ ε > 0, ∀ y, dist x y < ε → y ∈ s)
(eq_of_dist_eq_zero : ∀ x y : α, dist x y = 0 → x = y) : metric_space α :=
{ eq_of_dist_eq_zero := eq_of_dist_eq_zero,
..pseudo_metric_space.of_metrizable dist dist_self dist_comm dist_triangle H }
variables {γ : Type w} [metric_space γ]
theorem eq_of_dist_eq_zero {x y : γ} : dist x y = 0 → x = y :=
metric_space.eq_of_dist_eq_zero
@[simp] theorem dist_eq_zero {x y : γ} : dist x y = 0 ↔ x = y :=
iff.intro eq_of_dist_eq_zero (assume : x = y, this ▸ dist_self _)
@[simp] theorem zero_eq_dist {x y : γ} : 0 = dist x y ↔ x = y :=
by rw [eq_comm, dist_eq_zero]
theorem dist_ne_zero {x y : γ} : dist x y ≠ 0 ↔ x ≠ y :=
by simpa only [not_iff_not] using dist_eq_zero
@[simp] theorem dist_le_zero {x y : γ} : dist x y ≤ 0 ↔ x = y :=
by simpa [le_antisymm_iff, dist_nonneg] using @dist_eq_zero _ _ x y
@[simp] theorem dist_pos {x y : γ} : 0 < dist x y ↔ x ≠ y :=
by simpa only [not_le] using not_congr dist_le_zero
theorem eq_of_forall_dist_le {x y : γ} (h : ∀ ε > 0, dist x y ≤ ε) : x = y :=
eq_of_dist_eq_zero (eq_of_le_of_forall_le_of_dense dist_nonneg h)
/--Deduce the equality of points with the vanishing of the nonnegative distance-/
theorem eq_of_nndist_eq_zero {x y : γ} : nndist x y = 0 → x = y :=
by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero]
/--Characterize the equality of points with the vanishing of the nonnegative distance-/
@[simp] theorem nndist_eq_zero {x y : γ} : nndist x y = 0 ↔ x = y :=
by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero]
@[simp] theorem zero_eq_nndist {x y : γ} : 0 = nndist x y ↔ x = y :=
by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, zero_eq_dist]
namespace metric
variables {x : γ} {s : set γ}
@[simp] lemma closed_ball_zero : closed_ball x 0 = {x} :=
set.ext $ λ y, dist_le_zero
@[simp] lemma sphere_zero : sphere x 0 = {x} :=
set.ext $ λ y, dist_eq_zero
lemma subsingleton_closed_ball (x : γ) {r : ℝ} (hr : r ≤ 0) : (closed_ball x r).subsingleton :=
begin
rcases hr.lt_or_eq with hr|rfl,
{ rw closed_ball_eq_empty.2 hr, exact subsingleton_empty },
{ rw closed_ball_zero, exact subsingleton_singleton }
end
lemma subsingleton_sphere (x : γ) {r : ℝ} (hr : r ≤ 0) : (sphere x r).subsingleton :=
(subsingleton_closed_ball x hr).anti sphere_subset_closed_ball
/-- A map between metric spaces is a uniform embedding if and only if the distance between `f x`
and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/
theorem uniform_embedding_iff' [metric_space β] {f : γ → β} :
uniform_embedding f ↔
(∀ ε > 0, ∃ δ > 0, ∀ {a b : γ}, dist a b < δ → dist (f a) (f b) < ε) ∧
(∀ δ > 0, ∃ ε > 0, ∀ {a b : γ}, dist (f a) (f b) < ε → dist a b < δ) :=
begin
split,
{ assume h,
exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1,
(uniform_embedding_iff.1 h).2.2⟩ },
{ rintros ⟨h₁, h₂⟩,
refine uniform_embedding_iff.2 ⟨_, uniform_continuous_iff.2 h₁, h₂⟩,
assume x y hxy,
have : dist x y ≤ 0,
{ refine le_of_forall_lt' (λδ δpos, _),
rcases h₂ δ δpos with ⟨ε, εpos, hε⟩,
have : dist (f x) (f y) < ε, by simpa [hxy],
exact hε this },
simpa using this }
end
@[priority 100] -- see Note [lower instance priority]
instance _root_.metric_space.to_separated : separated_space γ :=
separated_def.2 $ λ x y h, eq_of_forall_dist_le $
λ ε ε0, le_of_lt (h _ (dist_mem_uniformity ε0))
/-- If a `pseudo_metric_space` is a T₀ space, then it is a `metric_space`. -/
def of_t0_pseudo_metric_space (α : Type*) [pseudo_metric_space α] [t0_space α] :
metric_space α :=
{ eq_of_dist_eq_zero := λ x y hdist, inseparable.eq $ metric.inseparable_iff.2 hdist,
..‹pseudo_metric_space α› }
/-- A metric space induces an emetric space -/
@[priority 100] -- see Note [lower instance priority]
instance metric_space.to_emetric_space : emetric_space γ :=
emetric.of_t0_pseudo_emetric_space γ
lemma is_closed_of_pairwise_le_dist {s : set γ} {ε : ℝ} (hε : 0 < ε)
(hs : s.pairwise (λ x y, ε ≤ dist x y)) : is_closed s :=
is_closed_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hs
lemma closed_embedding_of_pairwise_le_dist {α : Type*} [topological_space α] [discrete_topology α]
{ε : ℝ} (hε : 0 < ε) {f : α → γ} (hf : pairwise (λ x y, ε ≤ dist (f x) (f y))) :
closed_embedding f :=
closed_embedding_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hf
/-- If `f : β → α` sends any two distinct points to points at distance at least `ε > 0`, then
`f` is a uniform embedding with respect to the discrete uniformity on `β`. -/
lemma uniform_embedding_bot_of_pairwise_le_dist {β : Type*} {ε : ℝ} (hε : 0 < ε) {f : β → α}
(hf : pairwise (λ x y, ε ≤ dist (f x) (f y))) : @uniform_embedding _ _ ⊥ (by apply_instance) f :=
uniform_embedding_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hf
end metric
/-- Build a new metric space from an old one where the bundled uniform structure is provably
(but typically non-definitionaly) equal to some given uniform structure.
See Note [forgetful inheritance].
-/
def metric_space.replace_uniformity {γ} [U : uniform_space γ] (m : metric_space γ)
(H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) :
metric_space γ :=
{ eq_of_dist_eq_zero := @eq_of_dist_eq_zero _ _,
..pseudo_metric_space.replace_uniformity m.to_pseudo_metric_space H, }
lemma metric_space.replace_uniformity_eq {γ} [U : uniform_space γ] (m : metric_space γ)
(H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) :
m.replace_uniformity H = m :=
by { ext, refl }
/-- Build a new metric space from an old one where the bundled topological structure is provably
(but typically non-definitionaly) equal to some given topological structure.
See Note [forgetful inheritance].
-/
@[reducible] def metric_space.replace_topology {γ} [U : topological_space γ] (m : metric_space γ)
(H : U = m.to_pseudo_metric_space.to_uniform_space.to_topological_space) :
metric_space γ :=
@metric_space.replace_uniformity γ (m.to_uniform_space.replace_topology H) m rfl
lemma metric_space.replace_topology_eq {γ} [U : topological_space γ] (m : metric_space γ)
(H : U = m.to_pseudo_metric_space.to_uniform_space.to_topological_space) :
m.replace_topology H = m :=
by { ext, refl }
/-- One gets a metric space from an emetric space if the edistance
is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the
uniformity are defeq in the metric space and the emetric space. In this definition, the distance
is given separately, to be able to prescribe some expression which is not defeq to the push-forward
of the edistance to reals. -/
def emetric_space.to_metric_space_of_dist {α : Type u} [e : emetric_space α]
(dist : α → α → ℝ)
(edist_ne_top : ∀x y: α, edist x y ≠ ⊤)
(h : ∀x y, dist x y = ennreal.to_real (edist x y)) :
metric_space α :=
{ dist := dist,
eq_of_dist_eq_zero := λx y hxy,
by simpa [h, ennreal.to_real_eq_zero_iff, edist_ne_top x y] using hxy,
..pseudo_emetric_space.to_pseudo_metric_space_of_dist dist edist_ne_top h, }
/-- One gets a metric space from an emetric space if the edistance
is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the
uniformity are defeq in the metric space and the emetric space. -/
def emetric_space.to_metric_space {α : Type u} [e : emetric_space α] (h : ∀x y: α, edist x y ≠ ⊤) :
metric_space α :=
emetric_space.to_metric_space_of_dist (λx y, ennreal.to_real (edist x y)) h (λx y, rfl)
/-- Build a new metric space from an old one where the bundled bornology structure is provably
(but typically non-definitionaly) equal to some given bornology structure.
See Note [forgetful inheritance].
-/
def metric_space.replace_bornology {α} [B : bornology α] (m : metric_space α)
(H : ∀ s, @is_bounded _ B s ↔ @is_bounded _ pseudo_metric_space.to_bornology s) :
metric_space α :=
{ to_bornology := B,
.. pseudo_metric_space.replace_bornology _ H,
.. m }
lemma metric_space.replace_bornology_eq {α} [m : metric_space α] [B : bornology α]
(H : ∀ s, @is_bounded _ B s ↔ @is_bounded _ pseudo_metric_space.to_bornology s) :
metric_space.replace_bornology _ H = m :=
by { ext, refl }
/-- Metric space structure pulled back by an injective function. Injectivity is necessary to
ensure that `dist x y = 0` only if `x = y`. -/
def metric_space.induced {γ β} (f : γ → β) (hf : function.injective f)
(m : metric_space β) : metric_space γ :=
{ eq_of_dist_eq_zero := λ x y h, hf (dist_eq_zero.1 h),
..pseudo_metric_space.induced f m.to_pseudo_metric_space }
/-- Pull back a metric space structure by a uniform embedding. This is a version of
`metric_space.induced` useful in case if the domain already has a `uniform_space` structure. -/
@[reducible] def uniform_embedding.comap_metric_space
{α β} [uniform_space α] [metric_space β] (f : α → β) (h : uniform_embedding f) :
metric_space α :=
(metric_space.induced f h.inj ‹_›).replace_uniformity h.comap_uniformity.symm
/-- Pull back a metric space structure by an embedding. This is a version of
`metric_space.induced` useful in case if the domain already has a `topological_space` structure. -/
@[reducible] def embedding.comap_metric_space
{α β} [topological_space α] [metric_space β] (f : α → β) (h : embedding f) :
metric_space α :=
begin
letI : uniform_space α := embedding.comap_uniform_space f h,
exact uniform_embedding.comap_metric_space f (h.to_uniform_embedding f),
end
instance subtype.metric_space {α : Type*} {p : α → Prop} [metric_space α] :
metric_space (subtype p) :=
metric_space.induced coe subtype.coe_injective ‹_›
@[to_additive] instance {α : Type*} [metric_space α] : metric_space (αᵐᵒᵖ) :=
metric_space.induced mul_opposite.unop mul_opposite.unop_injective ‹_›
instance : metric_space empty :=
{ dist := λ _ _, 0,
dist_self := λ _, rfl,
dist_comm := λ _ _, rfl,
eq_of_dist_eq_zero := λ _ _ _, subsingleton.elim _ _,
dist_triangle := λ _ _ _, show (0:ℝ) ≤ 0 + 0, by rw add_zero,
to_uniform_space := empty.uniform_space,
uniformity_dist := subsingleton.elim _ _ }
instance : metric_space punit.{u + 1} :=
{ dist := λ _ _, 0,
dist_self := λ _, rfl,
dist_comm := λ _ _, rfl,
eq_of_dist_eq_zero := λ _ _ _, subsingleton.elim _ _,
dist_triangle := λ _ _ _, show (0:ℝ) ≤ 0 + 0, by rw add_zero,
to_uniform_space := punit.uniform_space,
uniformity_dist :=
begin
simp only,
haveI : ne_bot (⨅ ε > (0 : ℝ), 𝓟 {p : punit.{u + 1} × punit.{u + 1} | 0 < ε}),
{ exact @uniformity.ne_bot _ (uniform_space_of_dist (λ _ _, 0) (λ _, rfl) (λ _ _, rfl)
(λ _ _ _, by rw zero_add)) _ },
refine (eq_top_of_ne_bot _).trans (eq_top_of_ne_bot _).symm,
end}
section real
/-- Instantiate the reals as a metric space. -/
instance real.metric_space : metric_space ℝ :=
{ eq_of_dist_eq_zero := λ x y h, by simpa [dist, sub_eq_zero] using h,
..real.pseudo_metric_space }
end real
section nnreal
instance : metric_space ℝ≥0 := subtype.metric_space
end nnreal
instance [metric_space β] : metric_space (ulift β) :=
metric_space.induced ulift.down ulift.down_injective ‹_›
section prod
instance prod.metric_space_max [metric_space β] : metric_space (γ × β) :=
{ eq_of_dist_eq_zero := λ x y h, begin
cases max_le_iff.1 (le_of_eq h) with h₁ h₂,
exact prod.ext_iff.2 ⟨dist_le_zero.1 h₁, dist_le_zero.1 h₂⟩
end,
..prod.pseudo_metric_space_max, }
end prod
section pi
open finset
variables {π : β → Type*} [fintype β] [∀b, metric_space (π b)]
/-- A finite product of metric spaces is a metric space, with the sup distance. -/
instance metric_space_pi : metric_space (Πb, π b) :=
/- we construct the instance from the emetric space instance to avoid checking again that the
uniformity is the same as the product uniformity, but we register nevertheless a nice formula
for the distance -/
{ eq_of_dist_eq_zero := assume f g eq0,
begin
have eq1 : edist f g = 0 := by simp only [edist_dist, eq0, ennreal.of_real_zero],
have eq2 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq1,
simp only [finset.sup_le_iff] at eq2,
exact (funext $ assume b, edist_le_zero.1 $ eq2 b $ mem_univ b)
end,
..pseudo_metric_space_pi }
end pi
namespace metric
section second_countable
open topological_space
/-- A metric space is second countable if one can reconstruct up to any `ε>0` any element of the
space from countably many data. -/
lemma second_countable_of_countable_discretization {α : Type u} [metric_space α]
(H : ∀ε > (0 : ℝ), ∃ (β : Type*) (_ : encodable β) (F : α → β), ∀x y, F x = F y → dist x y ≤ ε) :
second_countable_topology α :=
begin
cases (univ : set α).eq_empty_or_nonempty with hs hs,
{ haveI : compact_space α := ⟨by rw hs; exact is_compact_empty⟩, by apply_instance },
rcases hs with ⟨x0, hx0⟩,
letI : inhabited α := ⟨x0⟩,
refine second_countable_of_almost_dense_set (λε ε0, _),
rcases H ε ε0 with ⟨β, fβ, F, hF⟩,
resetI,
let Finv := function.inv_fun F,
refine ⟨range Finv, ⟨countable_range _, λx, _⟩⟩,
let x' := Finv (F x),
have : F x' = F x := function.inv_fun_eq ⟨x, rfl⟩,
exact ⟨x', mem_range_self _, hF _ _ this.symm⟩
end
end second_countable
end metric
section eq_rel
/-- The canonical equivalence relation on a pseudometric space. -/
def pseudo_metric.dist_setoid (α : Type u) [pseudo_metric_space α] : setoid α :=
setoid.mk (λx y, dist x y = 0)
begin
unfold equivalence,
repeat { split },
{ exact pseudo_metric_space.dist_self },
{ assume x y h, rwa pseudo_metric_space.dist_comm },
{ assume x y z hxy hyz,
refine le_antisymm _ dist_nonneg,
calc dist x z ≤ dist x y + dist y z : pseudo_metric_space.dist_triangle _ _ _
... = 0 + 0 : by rw [hxy, hyz]
... = 0 : by simp }
end
local attribute [instance] pseudo_metric.dist_setoid
/-- The canonical quotient of a pseudometric space, identifying points at distance `0`. -/
@[reducible] definition pseudo_metric_quot (α : Type u) [pseudo_metric_space α] : Type* :=
quotient (pseudo_metric.dist_setoid α)
instance has_dist_metric_quot {α : Type u} [pseudo_metric_space α] :
has_dist (pseudo_metric_quot α) :=
{ dist := quotient.lift₂ (λp q : α, dist p q)
begin
assume x y x' y' hxx' hyy',
have Hxx' : dist x x' = 0 := hxx',
have Hyy' : dist y y' = 0 := hyy',
have A : dist x y ≤ dist x' y' := calc
dist x y ≤ dist x x' + dist x' y : pseudo_metric_space.dist_triangle _ _ _
... = dist x' y : by simp [Hxx']
... ≤ dist x' y' + dist y' y : pseudo_metric_space.dist_triangle _ _ _
... = dist x' y' : by simp [pseudo_metric_space.dist_comm, Hyy'],
have B : dist x' y' ≤ dist x y := calc
dist x' y' ≤ dist x' x + dist x y' : pseudo_metric_space.dist_triangle _ _ _
... = dist x y' : by simp [pseudo_metric_space.dist_comm, Hxx']
... ≤ dist x y + dist y y' : pseudo_metric_space.dist_triangle _ _ _
... = dist x y : by simp [Hyy'],
exact le_antisymm A B
end }
lemma pseudo_metric_quot_dist_eq {α : Type u} [pseudo_metric_space α] (p q : α) :
dist ⟦p⟧ ⟦q⟧ = dist p q := rfl
instance metric_space_quot {α : Type u} [pseudo_metric_space α] :
metric_space (pseudo_metric_quot α) :=
{ dist_self := begin
refine quotient.ind (λy, _),
exact pseudo_metric_space.dist_self _
end,
eq_of_dist_eq_zero := λxc yc, by exact quotient.induction_on₂ xc yc (λx y H, quotient.sound H),
dist_comm :=
λxc yc, quotient.induction_on₂ xc yc (λx y, pseudo_metric_space.dist_comm _ _),
dist_triangle :=
λxc yc zc, quotient.induction_on₃ xc yc zc (λx y z, pseudo_metric_space.dist_triangle _ _ _) }
end eq_rel
/-!
### `additive`, `multiplicative`
The distance on those type synonyms is inherited without change.
-/
open additive multiplicative
section
variables [has_dist X]
instance : has_dist (additive X) := ‹has_dist X›
instance : has_dist (multiplicative X) := ‹has_dist X›
@[simp] lemma dist_of_mul (a b : X) : dist (of_mul a) (of_mul b) = dist a b := rfl
@[simp] lemma dist_of_add (a b : X) : dist (of_add a) (of_add b) = dist a b := rfl
@[simp] lemma dist_to_mul (a b : additive X) : dist (to_mul a) (to_mul b) = dist a b := rfl
@[simp] lemma dist_to_add (a b : multiplicative X) : dist (to_add a) (to_add b) = dist a b := rfl
end
section
variables [pseudo_metric_space X]
instance : pseudo_metric_space (additive X) := ‹pseudo_metric_space X›
instance : pseudo_metric_space (multiplicative X) := ‹pseudo_metric_space X›
@[simp] lemma nndist_of_mul (a b : X) : nndist (of_mul a) (of_mul b) = nndist a b := rfl
@[simp] lemma nndist_of_add (a b : X) : nndist (of_add a) (of_add b) = nndist a b := rfl
@[simp] lemma nndist_to_mul (a b : additive X) : nndist (to_mul a) (to_mul b) = nndist a b := rfl
@[simp] lemma nndist_to_add (a b : multiplicative X) : nndist (to_add a) (to_add b) = nndist a b :=
rfl
end
instance [metric_space X] : metric_space (additive X) := ‹metric_space X›
instance [metric_space X] : metric_space (multiplicative X) := ‹metric_space X›
instance [pseudo_metric_space X] [proper_space X] : proper_space (additive X) := ‹proper_space X›
instance [pseudo_metric_space X] [proper_space X] : proper_space (multiplicative X) :=
‹proper_space X›
/-!
### Order dual
The distance on this type synonym is inherited without change.
-/
open order_dual
section
variables [has_dist X]
instance : has_dist Xᵒᵈ := ‹has_dist X›
@[simp] lemma dist_to_dual (a b : X) : dist (to_dual a) (to_dual b) = dist a b := rfl
@[simp] lemma dist_of_dual (a b : Xᵒᵈ) : dist (of_dual a) (of_dual b) = dist a b := rfl
end
section
variables [pseudo_metric_space X]
instance : pseudo_metric_space Xᵒᵈ := ‹pseudo_metric_space X›
@[simp] lemma nndist_to_dual (a b : X) : nndist (to_dual a) (to_dual b) = nndist a b := rfl
@[simp] lemma nndist_of_dual (a b : Xᵒᵈ) : nndist (of_dual a) (of_dual b) = nndist a b := rfl
end
instance [metric_space X] : metric_space Xᵒᵈ := ‹metric_space X›
instance [pseudo_metric_space X] [proper_space X] : proper_space Xᵒᵈ := ‹proper_space X›
|
bfdc14cdf07ced2a82b5abf3c8ab3d2c974f5da5 | 5df84495ec6c281df6d26411cc20aac5c941e745 | /src/formal_ml/with_density_compose_eq_multiply.lean | 40ce22f83ce553f0269928e30d580db3b0a8eee2 | [
"Apache-2.0"
] | permissive | eric-wieser/formal-ml | e278df5a8df78aa3947bc8376650419e1b2b0a14 | 630011d19fdd9539c8d6493a69fe70af5d193590 | refs/heads/master | 1,681,491,589,256 | 1,612,642,743,000 | 1,612,642,743,000 | 360,114,136 | 0 | 0 | Apache-2.0 | 1,618,998,189,000 | 1,618,998,188,000 | null | UTF-8 | Lean | false | false | 6,437 | lean | /-
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-/
import measure_theory.measurable_space
import measure_theory.measure_space
import measure_theory.outer_measure
import measure_theory.lebesgue_measure
import measure_theory.integration
import measure_theory.set_integral
import measure_theory.borel_space
import data.set.countable
import formal_ml.nnreal
import formal_ml.sum
import formal_ml.core
import formal_ml.measurable_space
import formal_ml.semiring
import formal_ml.real_measurable_space
import formal_ml.set
import formal_ml.filter_util
import topology.instances.ennreal
import formal_ml.int
import formal_ml.lattice
import formal_ml.rat
--import formal_ml.with_density_compose_eq_multiply_part_one
/-
The simple way to think about a continuous random variable is as a
continuous function (a density function). Formally, this is the Radon-Nikodym derivative.
Using the operation with_density, one can transform this Radon-Nikodym derivative into
a measure using measure_theory.with_density, which is provided in measure_theory.integration
in mathlib. Specifically, one can write:
μ.with_density f
where μ is normally the Lebesgue measure on the real number line, and generate a probability
measure for a continuous density function.
In this file,
measure_theory.with_density.compose_eq_multiply connects the integration (or expectation) of
a function with respect to the probability measure derived from the density function with the
integral using the original base measure. So, if μ is again the base measure, f is the density
function, and g is the function we want to take the expectation of, then:
(μ.with_density f).integral g = μ.integral (f * g)
This is the familiar connection that we use to integrate functions of real random variables on
a regular basis.
-/
------------------------Theorems of ennreal -------------------------------------------
--Unnecessary
lemma le_coe_ne_top {x:nnreal} {y:ennreal}:y≤(x:ennreal) → y≠ ⊤ :=
begin
intro A1,
have A2:(x:ennreal)< ⊤,
{
apply with_top.coe_lt_top,
},
have A3:y < ⊤,
{
apply lt_of_le_of_lt,
apply A1,
apply A2,
},
rw ← lt_top_iff_ne_top,
apply A3,
end
--Unnecessary
lemma upper_bounds_nnreal (s : set ennreal) {x:nnreal} {y:ennreal}:
(x:ennreal) ∈ upper_bounds s → (y∈ s) → y≠ ⊤:=
begin
intros A1 A2,
rw mem_upper_bounds at A1,
have A3 := A1 y A2,
apply le_coe_ne_top A3,
end
--Unnecessary
lemma upper_bounds_nnreal_fn {α:Type*} {f:α → ennreal} {x:nnreal}:
(x:ennreal) ∈ upper_bounds (set.range f) → (∃ g:α → nnreal,
f = (λ a:α, (g a:ennreal))) :=
begin
intro A1,
let g:α → nnreal := λ a:α, ((f a).to_nnreal),
begin
have A2:g = λ a:α, ((f a).to_nnreal) := rfl,
apply exists.intro g,
rw A2,
ext a,
split;intro A3,
{
simp,
simp at A3,
rw A3,
rw ennreal.to_nnreal_coe,
},
{
simp,
simp at A3,
rw ← A3,
symmetry,
apply ennreal.coe_to_nnreal,
apply upper_bounds_nnreal,
apply A1,
simp,
},
end
end
------ Measure theory --------------------------------------------------------------------------
--Used EVERYWHERE.
lemma measure.apply {Ω:Type*} [M:measurable_space Ω] (μ:measure_theory.measure Ω) (S:set Ω):
μ S = μ.to_outer_measure.measure_of S :=
begin
refl
end
--Use in hahn.lean
--TODO: Can this be replaced with measure_theory.lintegral_supr?
--Look more closely: this is using supr_apply, which means it is more
--than just measure_theory.lintegral_supr.
lemma measure_theory.lintegral_supr2 {α : Type*}
[N:measurable_space α]
{μ:measure_theory.measure α}
{f : ℕ → α → ennreal}:
(∀ (n : ℕ), measurable (f n)) →
monotone f →
((∫⁻ a:α, (⨆ (n : ℕ), f n) a ∂ μ) =
⨆ (n : ℕ), (∫⁻ a:α, (f n) a ∂ μ)) :=
begin
intros A1 A2,
have A3:(λ a, (⨆ (n : ℕ), f n a)) = (⨆ (n : ℕ), f n),
{
apply funext,
intro a,
rw supr_apply,
},
rw ← A3,
apply measure_theory.lintegral_supr,
apply A1,
apply A2,
end
--Used in hahn.lean
lemma supr_indicator {Ω:Type*} (g:ℕ → Ω → ennreal) (S:set Ω):
(set.indicator S (supr g)) =
(⨆ (n : ℕ), (set.indicator S (g n))) :=
begin
apply funext,
intro ω,
rw (@supr_apply Ω (λ ω:Ω, ennreal) ℕ _ (λ n:ℕ, set.indicator S (g n)) ),
have A0:(λ (i : ℕ), (λ (n : ℕ), set.indicator S (g n)) i ω) =
(λ (i : ℕ), set.indicator S (g i) ω),
{
apply funext,
intro i,
simp,
},
rw A0,
have A1:ω ∈ S ∨ ω ∉ S ,
{
apply classical.em,
},
cases A1,
{
rw set.indicator_of_mem A1,
have B1A:(λ (i : ℕ), set.indicator S (g i) ω) =
(λ (i : ℕ), g i ω),
{
apply funext,
intro i,
rw set.indicator_of_mem A1,
},
rw B1A,
rw supr_apply,
},
{
rw set.indicator_of_not_mem A1,
have B1A:(λ (i : ℕ), set.indicator S (g i) ω) = (λ (i:ℕ), 0),
{
apply funext,
intro i,
rw set.indicator_of_not_mem A1,
},
rw B1A,
rw @supr_const ennreal ℕ _ _ 0,
},
end
--Used all over.
--Prefer measure_theory.with_density_apply
lemma measure_theory.with_density_apply2' {Ω:Type*} [M:measurable_space Ω] (μ:measure_theory.measure Ω) (f:Ω → ennreal) (S:set Ω):(measurable_set S) →
(μ.with_density f) S = (∫⁻ a:Ω, (set.indicator S f) a ∂ μ) :=
begin
intro A1,
rw measure_theory.with_density_apply f A1,
rw measure_theory.lintegral_indicator,
apply A1,
end
--Move to Radon-Nikodym (?)
lemma with_density.zero {Ω:Type*} [M:measurable_space Ω] (μ:measure_theory.measure Ω):
(μ.with_density 0) = 0 :=
begin
apply measure_theory.measure.ext,
intros S A1,
rw measure_theory.with_density_apply2',
{
simp,
},
{
apply A1,
}
end
|
534542543098d862c4c50344047af2fd1c010e81 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/algebra/group_with_zero_power.lean | 2bc0c6daccd3bf9417776dccd220ef551e4d3f11 | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 7,626 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import algebra.group_power
/-!
# Powers of elements of groups with an adjoined zero element
In this file we define integer power functions for groups with an adjoined zero element.
This generalises the integer power function on a division ring.
-/
@[simp] lemma zero_pow' {M : Type*} [monoid_with_zero M] :
∀ n : ℕ, n ≠ 0 → (0 : M) ^ n = 0
| 0 h := absurd rfl h
| (k+1) h := zero_mul _
section group_with_zero
variables {G₀ : Type*} [group_with_zero G₀]
section nat_pow
@[simp, field_simps] theorem inv_pow' (a : G₀) (n : ℕ) : (a⁻¹) ^ n = (a ^ n)⁻¹ :=
by induction n with n ih; [exact inv_one.symm,
rw [pow_succ', pow_succ, ih, mul_inv_rev']]
theorem pow_eq_zero' {g : G₀} {n : ℕ} (H : g ^ n = 0) : g = 0 :=
begin
induction n with n ih,
{ rw pow_zero at H,
rw [← mul_one g, H, mul_zero] },
exact or.cases_on (mul_eq_zero.1 H) id ih
end
@[field_simps] theorem pow_ne_zero' {g : G₀} (n : ℕ) (h : g ≠ 0) : g ^ n ≠ 0 :=
mt pow_eq_zero' h
theorem pow_sub' (a : G₀) {m n : ℕ} (ha : a ≠ 0) (h : n ≤ m) : a ^ (m - n) = a ^ m * (a ^ n)⁻¹ :=
have h1 : m - n + n = m, from nat.sub_add_cancel h,
have h2 : a ^ (m - n) * a ^ n = a ^ m, by rw [←pow_add, h1],
eq_div_of_mul_eq (pow_ne_zero' _ ha) h2
theorem pow_inv_comm' (a : G₀) (m n : ℕ) : (a⁻¹) ^ m * a ^ n = a ^ n * (a⁻¹) ^ m :=
(commute.refl a).inv_left'.pow_pow m n
end nat_pow
end group_with_zero
section int_pow
open int
variables {G₀ : Type*} [group_with_zero G₀]
/--
The power operation in a group with zero.
This extends `monoid.pow` to negative integers
with the definition `a ^ (-n) = (a ^ n)⁻¹`.
-/
def fpow (a : G₀) : ℤ → G₀
| (of_nat n) := a ^ n
| -[1+n] := (a ^ (nat.succ n))⁻¹
@[priority 10] instance : has_pow G₀ ℤ := ⟨fpow⟩
@[simp] theorem fpow_coe_nat (a : G₀) (n : ℕ) : a ^ (n:ℤ) = a ^ n := rfl
theorem fpow_of_nat (a : G₀) (n : ℕ) : a ^ of_nat n = a ^ n := rfl
@[simp] theorem fpow_neg_succ_of_nat (a : G₀) (n : ℕ) : a ^ -[1+n] = (a ^ n.succ)⁻¹ := rfl
local attribute [ematch] le_of_lt
@[simp] theorem fpow_zero (a : G₀) : a ^ (0:ℤ) = 1 := rfl
@[simp] theorem fpow_one (a : G₀) : a ^ (1:ℤ) = a := mul_one _
@[simp] theorem one_fpow : ∀ (n : ℤ), (1 : G₀) ^ n = 1
| (n : ℕ) := one_pow _
| -[1+ n] := show _⁻¹=(1:G₀), by rw [one_pow, inv_one]
lemma zero_fpow : ∀ z : ℤ, z ≠ 0 → (0 : G₀) ^ z = 0
| (of_nat n) h := zero_pow' _ $ by rintro rfl; exact h rfl
| -[1+n] h := show (0*0 ^ n)⁻¹ = (0 : G₀), by simp
@[simp] theorem fpow_neg (a : G₀) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹
| (n+1:ℕ) := rfl
| 0 := inv_one.symm
| -[1+ n] := (inv_inv' _).symm
theorem fpow_neg_one (x : G₀) : x ^ (-1:ℤ) = x⁻¹ := congr_arg has_inv.inv $ pow_one x
theorem inv_fpow (a : G₀) : ∀n:ℤ, a⁻¹ ^ n = (a ^ n)⁻¹
| (n : ℕ) := inv_pow' a n
| -[1+ n] := congr_arg has_inv.inv $ inv_pow' a (n+1)
lemma fpow_add_one {a : G₀} (ha : a ≠ 0) : ∀ n : ℤ, a ^ (n + 1) = a ^ n * a
| (of_nat n) := by simp [← int.coe_nat_succ, pow_succ']
| -[1+0] := by simp [int.neg_succ_of_nat_eq, ha]
| -[1+(n+1)] := by rw [int.neg_succ_of_nat_eq, fpow_neg, neg_add, neg_add_cancel_right, fpow_neg,
← int.coe_nat_succ, fpow_coe_nat, fpow_coe_nat, pow_succ _ (n + 1), mul_inv_rev', mul_assoc,
inv_mul_cancel ha, mul_one]
lemma fpow_sub_one {a : G₀} (ha : a ≠ 0) (n : ℤ) : a ^ (n - 1) = a ^ n * a⁻¹ :=
calc a ^ (n - 1) = a ^ (n - 1) * a * a⁻¹ : by rw [mul_assoc, mul_inv_cancel ha, mul_one]
... = a^n * a⁻¹ : by rw [← fpow_add_one ha, sub_add_cancel]
lemma fpow_add {a : G₀} (ha : a ≠ 0) (m n : ℤ) : a ^ (m + n) = a ^ m * a ^ n :=
begin
induction n using int.induction_on with n ihn n ihn,
case hz : { simp },
{ simp only [← add_assoc, fpow_add_one ha, ihn, mul_assoc] },
{ rw [fpow_sub_one ha, ← mul_assoc, ← ihn, ← fpow_sub_one ha, add_sub_assoc] }
end
theorem fpow_one_add {a : G₀} (h : a ≠ 0) (i : ℤ) : a ^ (1 + i) = a * a ^ i :=
by rw [fpow_add h, fpow_one]
theorem semiconj_by.fpow_right {a x y : G₀} (h : semiconj_by a x y) :
∀ m : ℤ, semiconj_by a (x^m) (y^m)
| (n : ℕ) := h.pow_right n
| -[1+n] := (h.pow_right (n + 1)).inv_right'
theorem commute.fpow_right {a b : G₀} (h : commute a b) : ∀ m : ℤ, commute a (b^m) :=
h.fpow_right
theorem commute.fpow_left {a b : G₀} (h : commute a b) (m : ℤ) : commute (a^m) b :=
(h.symm.fpow_right m).symm
theorem commute.fpow_fpow {a b : G₀} (h : commute a b) (m n : ℤ) : commute (a^m) (b^n) :=
(h.fpow_left m).fpow_right n
theorem commute.fpow_self (a : G₀) (n : ℤ) : commute (a^n) a := (commute.refl a).fpow_left n
theorem commute.self_fpow (a : G₀) (n : ℤ) : commute a (a^n) := (commute.refl a).fpow_right n
theorem commute.fpow_fpow_self (a : G₀) (m n : ℤ) : commute (a^m) (a^n) := (commute.refl a).fpow_fpow m n
theorem fpow_mul (a : G₀) : ∀ m n : ℤ, a ^ (m * n) = (a ^ m) ^ n
| (m : ℕ) (n : ℕ) := pow_mul _ _ _
| (m : ℕ) -[1+ n] := (fpow_neg _ (m * n.succ)).trans $
show (a ^ (m * n.succ))⁻¹ = _, by rw pow_mul; refl
| -[1+ m] (n : ℕ) := (fpow_neg _ (m.succ * n)).trans $
show (a ^ (m.succ * n))⁻¹ = _, by rw [pow_mul, ← inv_pow']; refl
| -[1+ m] -[1+ n] := (pow_mul a m.succ n.succ).trans $
show _ = (_⁻¹ ^ _)⁻¹, by rw [inv_pow', inv_inv']
theorem fpow_mul' (a : G₀) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m :=
by rw [mul_comm, fpow_mul]
@[simp, norm_cast] lemma units.coe_gpow' (u : units G₀) :
∀ (n : ℤ), ((u ^ n : units G₀) : G₀) = u ^ n
| (n : ℕ) := u.coe_pow n
| -[1+k] := by rw [gpow_neg_succ_of_nat, fpow_neg_succ_of_nat, units.coe_inv', u.coe_pow]
lemma fpow_ne_zero_of_ne_zero {a : G₀} (ha : a ≠ 0) : ∀ (z : ℤ), a ^ z ≠ 0
| (of_nat n) := pow_ne_zero' _ ha
| -[1+n] := inv_ne_zero $ pow_ne_zero' _ ha
lemma fpow_sub {a : G₀} (ha : a ≠ 0) (z1 z2 : ℤ) : a ^ (z1 - z2) = a ^ z1 / a ^ z2 :=
by rw [sub_eq_add_neg, fpow_add ha, fpow_neg]; refl
lemma commute.mul_fpow {a b : G₀} (h : commute a b) :
∀ (i : ℤ), (a * b) ^ i = (a ^ i) * (b ^ i)
| (n : ℕ) := h.mul_pow n
| -[1+n] := by simp [h.mul_pow, (h.pow_pow _ _).eq, mul_inv_rev']
lemma mul_fpow {G₀ : Type*} [comm_group_with_zero G₀] (a b : G₀) (m : ℤ):
(a * b) ^ m = (a ^ m) * (b ^ m) :=
(commute.all a b).mul_fpow m
lemma fpow_eq_zero {x : G₀} {n : ℤ} (h : x ^ n = 0) : x = 0 :=
classical.by_contradiction $ λ hx, fpow_ne_zero_of_ne_zero hx n h
lemma fpow_ne_zero {x : G₀} (n : ℤ) : x ≠ 0 → x ^ n ≠ 0 :=
mt fpow_eq_zero
theorem fpow_neg_mul_fpow_self (n : ℤ) {x : G₀} (h : x ≠ 0) :
x ^ (-n) * x ^ n = 1 :=
begin
rw [fpow_neg],
exact inv_mul_cancel (fpow_ne_zero n h)
end
theorem one_div_pow {a : G₀} (n : ℕ) :
(1 / a) ^ n = 1 / a ^ n :=
by simp only [one_div, inv_pow']
theorem one_div_fpow {a : G₀} (n : ℤ) :
(1 / a) ^ n = 1 / a ^ n :=
by simp only [one_div, inv_fpow]
end int_pow
section
variables {G₀ : Type*} [comm_group_with_zero G₀]
@[simp] theorem div_pow (a b : G₀) (n : ℕ) :
(a / b) ^ n = a ^ n / b ^ n :=
by simp only [div_eq_mul_inv, mul_pow, inv_pow']
@[simp] theorem div_fpow (a : G₀) {b : G₀} (n : ℤ) :
(a / b) ^ n = a ^ n / b ^ n :=
by simp only [div_eq_mul_inv, mul_fpow, inv_fpow]
lemma div_sq_cancel {a : G₀} (ha : a ≠ 0) (b : G₀) : a ^ 2 * b / a = a * b :=
by rw [pow_two, mul_assoc, mul_div_cancel_left _ ha]
end
|
b14c90ae8ff84e72213106bc540eded18d73960b | 3b880d8d9f5be25fbdaadb8860a1e6beac8e52a5 | /20170116_POPL/assoc/ac_by_simp.lean | 1fb1f20548cc4677fbfd1711803ce99b4607b9da | [
"Apache-2.0"
] | permissive | gebner/presentations | 29ea49abd3feb88e0a36d24ace38fbf5a3b939ad | 3b2149d19d6429c193965454d919e1b4eb1a44d8 | refs/heads/master | 1,609,598,807,163 | 1,484,466,986,000 | 1,484,466,986,000 | 78,720,148 | 0 | 0 | null | 1,484,206,190,000 | 1,484,206,190,000 | null | UTF-8 | Lean | false | false | 4,351 | lean | import data.set
/-
The Lean simplifer can be also use to "flat" nested application of associative operators,
and "sort" associative/commutative ones.
The Lean simplifier can be viewed as a ordered rewriting system.
It can be customized with user provided lemmas.
It is well-known that we can use ordered rewriting to "sort" nested applications
of associative-commutative (AC) operators.
Let's assume we have an AC operator op.
-/
constant α : Type
constant op : α → α → α
axiom h_comm : ∀ x y, op x y = op y x
axiom h_assoc : ∀ x y z, op (op x y) z = op x (op y z)
/-
To "sort" the nested op-applications, we also need
the following lemma that follows from h_comm and h_assoc.
-/
lemma h_left_comm : ∀ x y z, op x (op y z) = op y (op x z) :=
left_comm _ h_comm h_assoc
/- Now, we declare notation for (op a b) -/
infix `∙`:65 := op
example (a b c d : α) : a ∙ b ∙ c ∙ d = (c ∙ b) ∙ (a ∙ d) :=
by simp [h_comm, h_assoc, h_left_comm]
/- We can add h_comm, h_assoc and h_left_comm
to the main simp_lemmas (set of simplification rules) -/
attribute [simp] h_comm h_assoc h_left_comm
/- Now, these lemmas are automatically used. -/
example (a b c d : α) : a ∙ b ∙ c ∙ d = (c ∙ b) ∙ (a ∙ d) :=
by simp
/- We can also locally remove lemmas from the [simp] -/
local attribute [-simp] h_comm h_assoc h_left_comm
example (a b c d : α) : a ∙ b ∙ c ∙ d = (c ∙ b) ∙ (a ∙ d) :=
/- Now, the following will fail since h_comm, h_assoc and h_left_comm
have been removed from the simp set [simp] -/
by simp
/- We can declare our own simp sets.
The command mk_simp_attr is implemented in Lean
using the attribute manager API.
We discuss the attribute manager later. -/
run_command mk_simp_attr `sort_op
attribute [sort_op] h_comm h_assoc h_left_comm
example (a b c d : α) : a ∙ b ∙ c ∙ d = (c ∙ b) ∙ (a ∙ d) :=
/- The modifier 'with' instructs simp to use the given simp set -/
by simp with sort_op
open tactic
/-
Note that (left_comm op h_comm h_assoc) is not recognized as the rewrite rule
we expect
-/
check left_comm op h_comm h_assoc -- : left_commutative f
/- So, we define an auxiliary lemma with the "right" type. -/
lemma {u} left_comm_rw {α : Type u} (f : α → α → α) (h_comm : commutative f) (h_assoc : associative f) :
∀ x y z, f x (f y z) = f y (f x z) :=
left_comm f h_comm h_assoc
/- The simp sets are first-class citizens in Lean, we
can write functions that create them.
Given proof terms h_comm and h_assoc, the tactic
(mk_sort_simp_set h_comm h_assoc) returns
a simp set containing h_comm, h_assoc and the
associated left_comm lemma implied by h_comm and h_assoc. -/
meta def mk_sort_simp_set (op : expr) (h_comm : expr) (h_assoc : expr) : tactic simp_lemmas :=
do
S ← return simp_lemmas.mk,
S ← S^.add h_comm,
S ← S^.add h_assoc,
h_left_comm ← to_expr `(left_comm_rw %%op %%h_comm %%h_assoc) >>= whnf,
S^.add h_left_comm
declare_trace sort_ac
meta def sort_ac_core (op : expr) (h_comm : expr) (h_assoc : expr) : tactic unit :=
do S ← mk_sort_simp_set op h_comm h_assoc,
/- When tracing sort_ac, we pretty print the generated simp_set. -/
when_tracing `sort_ac (S^.pp >>= trace),
simplify_goal S,
try reflexivity
open expr
meta def is_bin_app : expr → tactic (expr × expr × expr)
| (app (app fn a1) a2) := return (fn, a1, a2)
| _ := failed
/- Now, we use type class resolution to retrieve the comm and assoc lemmas. -/
meta def sort_ac : tactic unit :=
do (lhs, rhs) ← target >>= match_eq,
(op, _, _) ← is_bin_app lhs,
h_assoc ← to_expr `(is_associative.assoc %%op),
h_comm ← to_expr `(is_commutative.comm %%op),
sort_ac_core op h_comm h_assoc
/- We still did not declare the instances is_associative and is_commutative
for op.
We have to mark them as noncomputable because we did not define them.
-/
noncomputable instance : is_associative _ op :=
⟨h_assoc⟩
noncomputable instance : is_commutative _ op :=
⟨h_comm⟩
example (a b c d : α) : a ∙ b ∙ c ∙ d = (c ∙ b) ∙ (a ∙ d) :=
by sort_ac
example (s₁ s₂ s₃ : set nat) : s₁ ∪ s₂ ∪ s₃ = s₃ ∪ s₁ ∪ s₂ :=
by sort_ac
set_option trace.sort_ac true
example (a b c : nat) : a + b + c = c + b + a :=
by sort_ac
|
6d606dba8f12965eff0d53fef792eb7fe50dad58 | 6f4750ff03c8be1d6c0b1b809ff6ac541b9d5a22 | /While.lean | 9159bf75710b6b54a15a5df576511104b7ff0a76 | [] | no_license | benating/Lean_Test | 1809b5e15df9edcdf4a3388f53d2205f29c89ac2 | c07099804a86347b4ec836f54530f62e22534bdb | refs/heads/master | 1,628,468,905,337 | 1,510,426,597,000 | 1,510,426,597,000 | 108,762,297 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,145 | lean | import .WhileSyntax
open whileSyntax
open whileSyntax.configExpr
open whileSyntax.wExpr
open whileSyntax.wComm
open whileSyntax.wBool
namespace semantics
def a := num 1
def b := num 2
def c := num 3
def d := ident("x")
def f : string → ℕ
| "x" := 4
| _ := 0
def exampleConfig := (configE(a + b + (c * d), f))
def oneSmallStepExpr : configExpr → configExpr
| (configE (num a, state)) := configE (num a, state)
| (configE (ident x, state)) := configE (num (state x), state)
| (configE (num a + num b, state)) := configE (num (a + b), state)
| (configE (num a * num b, state)) := configE (num (a * b), state)
| (configE (num a + exp2, state)) := let (configE (exp2', state')) := oneSmallStepExpr (configE (exp2, state)) in
configE (num a + exp2', state')
| (configE (num a * exp2, state)) := let (configE (exp2', state')) := oneSmallStepExpr (configE (exp2, state)) in
configE (num a * exp2', state')
| (configE (exp1 + exp2, state)) := let (configE (exp1', state')) := oneSmallStepExpr (configE (exp1, state)) in
configE (exp1' + exp2, state')
| (configE (exp1 * exp2, state)) := let (configE (exp1', state')) := oneSmallStepExpr (configE (exp1, state)) in
configE (exp1' * exp2, state')
def smallStepExpr : configExpr → configExpr
| (configE (num a, state)) := configE (num a, state)
| a := have sizeof (oneSmallStepExpr a) < sizeof a, from sorry,
smallStepExpr $ oneSmallStepExpr a
def bigStepExpr : configExpr → configExpr
| (configE (num a, state)) := configE (num a, state)
| (configE (ident x, state)) := configE (num (state x), state)
| (configE (num a + num b, state)) := configE (num (a + b), state)
| (configE (num a * num b, state)) := configE (num (a * b), state)
| (configE (exp1 + exp2, state)) := let (configE (exp1', state')) := bigStepExpr (configE (exp1, state)),
(configE (exp2', state'')) := bigStepExpr (configE (exp2, state')) in
have sizeof exp2' + sizeof exp1' < sizeof exp2 + sizeof exp1, from sorry,
bigStepExpr $ configE (exp1' + exp2', state'')
| (configE (exp1 * exp2, state)) := let (configE (exp1', state')) := bigStepExpr (configE (exp1, state)),
(configE (exp2', state'')) := bigStepExpr (configE (exp2, state')) in
have sizeof exp2' * sizeof exp1' < sizeof exp2 * sizeof exp1, from sorry,
bigStepExpr $ configE (exp1' * exp2', state'')
theorem normal_forms (e : configExpr) : (∃ n : ℕ, ∃ f : string → ℕ, smallStepExpr e = configE (num n, f) ) :=
begin
admit
end
def g := let (configE (a, _)) := smallStepExpr (configE (num 7 + num 6, f)) in a
def h := let (configE (a, _)) := bigStepExpr (configE (num 7 + ident "x", f)) in a
def i := let (configE (a, _)) := bigStepExpr exampleConfig in a
def j := let (configE (a, _)) := smallStepExpr exampleConfig in a
#eval i
#eval j
end semantics |
600caf2c45548be1233e8ded39a36ae76b65290f | bb31430994044506fa42fd667e2d556327e18dfe | /src/algebra/algebra/hom.lean | e0bc7c2029b1d46f34f9f56050f238b1500006ed | [
"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 | 14,001 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Yury Kudryashov
-/
import algebra.algebra.basic
/-!
# Homomorphisms of `R`-algebras
This file defines bundled homomorphisms of `R`-algebras.
## Main definitions
* `alg_hom R A B`: the type of `R`-algebra morphisms from `A` to `B`.
* `algebra.of_id R A : R →ₐ[R] A`: the canonical map from `R` to `A`, as an `alg_hom`.
## Notations
* `A →ₐ[R] B` : `R`-algebra homomorphism from `A` to `B`.
-/
open_locale big_operators
universes u v w u₁ v₁
set_option old_structure_cmd true
/-- Defining the homomorphism in the category R-Alg. -/
@[nolint has_nonempty_instance]
structure alg_hom (R : Type u) (A : Type v) (B : Type w)
[comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends ring_hom A B :=
(commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r)
run_cmd tactic.add_doc_string `alg_hom.to_ring_hom "Reinterpret an `alg_hom` as a `ring_hom`"
infixr ` →ₐ `:25 := alg_hom _
notation A ` →ₐ[`:25 R `] ` B := alg_hom R A B
/-- `alg_hom_class F R A B` asserts `F` is a type of bundled algebra homomorphisms
from `A` to `B`. -/
class alg_hom_class (F : Type*) (R : out_param Type*) (A : out_param Type*) (B : out_param Type*)
[comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B]
extends ring_hom_class F A B :=
(commutes : ∀ (f : F) (r : R), f (algebra_map R A r) = algebra_map R B r)
-- `R` becomes a metavariable but that's fine because it's an `out_param`
attribute [nolint dangerous_instance] alg_hom_class.to_ring_hom_class
attribute [simp] alg_hom_class.commutes
namespace alg_hom_class
variables {R : Type*} {A : Type*} {B : Type*} [comm_semiring R] [semiring A] [semiring B]
[algebra R A] [algebra R B]
@[priority 100] -- see Note [lower instance priority]
instance {F : Type*} [alg_hom_class F R A B] : linear_map_class F R A B :=
{ map_smulₛₗ := λ f r x, by simp only [algebra.smul_def, map_mul, commutes, ring_hom.id_apply],
..‹alg_hom_class F R A B› }
instance {F : Type*} [alg_hom_class F R A B] : has_coe_t F (A →ₐ[R] B) :=
{ coe := λ f,
{ to_fun := f,
commutes' := alg_hom_class.commutes f,
.. (f : A →+* B) } }
end alg_hom_class
namespace alg_hom
variables {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} {D : Type v₁}
section semiring
variables [comm_semiring R] [semiring A] [semiring B] [semiring C] [semiring D]
variables [algebra R A] [algebra R B] [algebra R C] [algebra R D]
instance : has_coe_to_fun (A →ₐ[R] B) (λ _, A → B) := ⟨alg_hom.to_fun⟩
initialize_simps_projections alg_hom (to_fun → apply)
@[simp, protected] lemma coe_coe {F : Type*} [alg_hom_class F R A B] (f : F) :
⇑(f : A →ₐ[R] B) = f := rfl
@[simp] lemma to_fun_eq_coe (f : A →ₐ[R] B) : f.to_fun = f := rfl
instance : alg_hom_class (A →ₐ[R] B) R A B :=
{ coe := to_fun,
coe_injective' := λ f g h, by { cases f, cases g, congr' },
map_add := map_add',
map_zero := map_zero',
map_mul := map_mul',
map_one := map_one',
commutes := λ f, f.commutes' }
instance coe_ring_hom : has_coe (A →ₐ[R] B) (A →+* B) := ⟨alg_hom.to_ring_hom⟩
instance coe_monoid_hom : has_coe (A →ₐ[R] B) (A →* B) := ⟨λ f, ↑(f : A →+* B)⟩
instance coe_add_monoid_hom : has_coe (A →ₐ[R] B) (A →+ B) := ⟨λ f, ↑(f : A →+* B)⟩
@[simp, norm_cast] lemma coe_mk {f : A → B} (h₁ h₂ h₃ h₄ h₅) :
⇑(⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →ₐ[R] B) = f := rfl
-- make the coercion the simp-normal form
@[simp] lemma to_ring_hom_eq_coe (f : A →ₐ[R] B) : f.to_ring_hom = f := rfl
@[simp, norm_cast] lemma coe_to_ring_hom (f : A →ₐ[R] B) : ⇑(f : A →+* B) = f := rfl
@[simp, norm_cast] lemma coe_to_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →* B) = f := rfl
@[simp, norm_cast] lemma coe_to_add_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →+ B) = f := rfl
variables (φ : A →ₐ[R] B)
theorem coe_fn_injective : @function.injective (A →ₐ[R] B) (A → B) coe_fn := fun_like.coe_injective
theorem coe_fn_inj {φ₁ φ₂ : A →ₐ[R] B} : (φ₁ : A → B) = φ₂ ↔ φ₁ = φ₂ := fun_like.coe_fn_eq
theorem coe_ring_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+* B)) :=
λ φ₁ φ₂ H, coe_fn_injective $ show ((φ₁ : (A →+* B)) : A → B) = ((φ₂ : (A →+* B)) : A → B),
from congr_arg _ H
theorem coe_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →* B)) :=
ring_hom.coe_monoid_hom_injective.comp coe_ring_hom_injective
theorem coe_add_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+ B)) :=
ring_hom.coe_add_monoid_hom_injective.comp coe_ring_hom_injective
protected lemma congr_fun {φ₁ φ₂ : A →ₐ[R] B} (H : φ₁ = φ₂) (x : A) : φ₁ x = φ₂ x :=
fun_like.congr_fun H x
protected lemma congr_arg (φ : A →ₐ[R] B) {x y : A} (h : x = y) : φ x = φ y :=
fun_like.congr_arg φ h
@[ext]
theorem ext {φ₁ φ₂ : A →ₐ[R] B} (H : ∀ x, φ₁ x = φ₂ x) : φ₁ = φ₂ := fun_like.ext _ _ H
theorem ext_iff {φ₁ φ₂ : A →ₐ[R] B} : φ₁ = φ₂ ↔ ∀ x, φ₁ x = φ₂ x := fun_like.ext_iff
@[simp] theorem mk_coe {f : A →ₐ[R] B} (h₁ h₂ h₃ h₄ h₅) :
(⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →ₐ[R] B) = f := ext $ λ _, rfl
@[simp]
theorem commutes (r : R) : φ (algebra_map R A r) = algebra_map R B r := φ.commutes' r
theorem comp_algebra_map : (φ : A →+* B).comp (algebra_map R A) = algebra_map R B :=
ring_hom.ext $ φ.commutes
protected lemma map_add (r s : A) : φ (r + s) = φ r + φ s := map_add _ _ _
protected lemma map_zero : φ 0 = 0 := map_zero _
protected lemma map_mul (x y) : φ (x * y) = φ x * φ y := map_mul _ _ _
protected lemma map_one : φ 1 = 1 := map_one _
protected lemma map_pow (x : A) (n : ℕ) : φ (x ^ n) = (φ x) ^ n := map_pow _ _ _
@[simp] protected lemma map_smul (r : R) (x : A) : φ (r • x) = r • φ x := map_smul _ _ _
protected lemma map_sum {ι : Type*} (f : ι → A) (s : finset ι) :
φ (∑ x in s, f x) = ∑ x in s, φ (f x) := map_sum _ _ _
protected lemma map_finsupp_sum {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A) :
φ (f.sum g) = f.sum (λ i a, φ (g i a)) := map_finsupp_sum _ _ _
protected lemma map_bit0 (x) : φ (bit0 x) = bit0 (φ x) := map_bit0 _ _
protected lemma map_bit1 (x) : φ (bit1 x) = bit1 (φ x) := map_bit1 _ _
/-- If a `ring_hom` is `R`-linear, then it is an `alg_hom`. -/
def mk' (f : A →+* B) (h : ∀ (c : R) x, f (c • x) = c • f x) : A →ₐ[R] B :=
{ to_fun := f,
commutes' := λ c, by simp only [algebra.algebra_map_eq_smul_one, h, f.map_one],
.. f }
@[simp] lemma coe_mk' (f : A →+* B) (h : ∀ (c : R) x, f (c • x) = c • f x) : ⇑(mk' f h) = f := rfl
section
variables (R A)
/-- Identity map as an `alg_hom`. -/
protected def id : A →ₐ[R] A :=
{ commutes' := λ _, rfl,
..ring_hom.id A }
@[simp] lemma coe_id : ⇑(alg_hom.id R A) = id := rfl
@[simp] lemma id_to_ring_hom : (alg_hom.id R A : A →+* A) = ring_hom.id _ := rfl
end
lemma id_apply (p : A) : alg_hom.id R A p = p := rfl
/-- Composition of algebra homeomorphisms. -/
def comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : A →ₐ[R] C :=
{ commutes' := λ r : R, by rw [← φ₁.commutes, ← φ₂.commutes]; refl,
.. φ₁.to_ring_hom.comp ↑φ₂ }
@[simp] lemma coe_comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : ⇑(φ₁.comp φ₂) = φ₁ ∘ φ₂ := rfl
lemma comp_apply (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) (p : A) : φ₁.comp φ₂ p = φ₁ (φ₂ p) := rfl
lemma comp_to_ring_hom (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) :
(φ₁.comp φ₂ : A →+* C) = (φ₁ : B →+* C).comp ↑φ₂ := rfl
@[simp] theorem comp_id : φ.comp (alg_hom.id R A) = φ :=
ext $ λ x, rfl
@[simp] theorem id_comp : (alg_hom.id R B).comp φ = φ :=
ext $ λ x, rfl
theorem comp_assoc (φ₁ : C →ₐ[R] D) (φ₂ : B →ₐ[R] C) (φ₃ : A →ₐ[R] B) :
(φ₁.comp φ₂).comp φ₃ = φ₁.comp (φ₂.comp φ₃) :=
ext $ λ x, rfl
/-- R-Alg ⥤ R-Mod -/
def to_linear_map : A →ₗ[R] B :=
{ to_fun := φ,
map_add' := map_add _,
map_smul' := map_smul _ }
@[simp] lemma to_linear_map_apply (p : A) : φ.to_linear_map p = φ p := rfl
theorem to_linear_map_injective : function.injective (to_linear_map : _ → (A →ₗ[R] B)) :=
λ φ₁ φ₂ h, ext $ linear_map.congr_fun h
@[simp] lemma comp_to_linear_map (f : A →ₐ[R] B) (g : B →ₐ[R] C) :
(g.comp f).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl
@[simp] lemma to_linear_map_id : to_linear_map (alg_hom.id R A) = linear_map.id :=
linear_map.ext $ λ _, rfl
/-- Promote a `linear_map` to an `alg_hom` by supplying proofs about the behavior on `1` and `*`. -/
@[simps]
def of_linear_map (f : A →ₗ[R] B) (map_one : f 1 = 1) (map_mul : ∀ x y, f (x * y) = f x * f y) :
A →ₐ[R] B :=
{ to_fun := f,
map_one' := map_one,
map_mul' := map_mul,
commutes' := λ c, by simp only [algebra.algebra_map_eq_smul_one, f.map_smul, map_one],
.. f.to_add_monoid_hom }
@[simp] lemma of_linear_map_to_linear_map (map_one) (map_mul) :
of_linear_map φ.to_linear_map map_one map_mul = φ :=
by { ext, refl }
@[simp] lemma to_linear_map_of_linear_map (f : A →ₗ[R] B) (map_one) (map_mul) :
to_linear_map (of_linear_map f map_one map_mul) = f :=
by { ext, refl }
@[simp] lemma of_linear_map_id (map_one) (map_mul) :
of_linear_map linear_map.id map_one map_mul = alg_hom.id R A :=
ext $ λ _, rfl
lemma map_smul_of_tower {R'} [has_smul R' A] [has_smul R' B]
[linear_map.compatible_smul A B R' R] (r : R') (x : A) : φ (r • x) = r • φ x :=
φ.to_linear_map.map_smul_of_tower r x
lemma map_list_prod (s : list A) :
φ s.prod = (s.map φ).prod :=
φ.to_ring_hom.map_list_prod s
@[simps mul one {attrs := []}] instance End : monoid (A →ₐ[R] A) :=
{ mul := comp,
mul_assoc := λ ϕ ψ χ, rfl,
one := alg_hom.id R A,
one_mul := λ ϕ, ext $ λ x, rfl,
mul_one := λ ϕ, ext $ λ x, rfl }
@[simp] lemma one_apply (x : A) : (1 : A →ₐ[R] A) x = x := rfl
@[simp] lemma mul_apply (φ ψ : A →ₐ[R] A) (x : A) : (φ * ψ) x = φ (ψ x) := rfl
lemma algebra_map_eq_apply (f : A →ₐ[R] B) {y : R} {x : A} (h : algebra_map R A y = x) :
algebra_map R B y = f x :=
h ▸ (f.commutes _).symm
end semiring
section comm_semiring
variables [comm_semiring R] [comm_semiring A] [comm_semiring B]
variables [algebra R A] [algebra R B] (φ : A →ₐ[R] B)
protected lemma map_multiset_prod (s : multiset A) :
φ s.prod = (s.map φ).prod := map_multiset_prod _ _
protected lemma map_prod {ι : Type*} (f : ι → A) (s : finset ι) :
φ (∏ x in s, f x) = ∏ x in s, φ (f x) := map_prod _ _ _
protected lemma map_finsupp_prod {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A) :
φ (f.prod g) = f.prod (λ i a, φ (g i a)) := map_finsupp_prod _ _ _
end comm_semiring
section ring
variables [comm_semiring R] [ring A] [ring B]
variables [algebra R A] [algebra R B] (φ : A →ₐ[R] B)
protected lemma map_neg (x) : φ (-x) = -φ x := map_neg _ _
protected lemma map_sub (x y) : φ (x - y) = φ x - φ y := map_sub _ _ _
end ring
end alg_hom
namespace ring_hom
variables {R S : Type*}
/-- Reinterpret a `ring_hom` as an `ℕ`-algebra homomorphism. -/
def to_nat_alg_hom [semiring R] [semiring S] (f : R →+* S) :
R →ₐ[ℕ] S :=
{ to_fun := f, commutes' := λ n, by simp, .. f }
/-- Reinterpret a `ring_hom` as a `ℤ`-algebra homomorphism. -/
def to_int_alg_hom [ring R] [ring S] [algebra ℤ R] [algebra ℤ S] (f : R →+* S) :
R →ₐ[ℤ] S :=
{ commutes' := λ n, by simp, .. f }
/-- Reinterpret a `ring_hom` as a `ℚ`-algebra homomorphism. This actually yields an equivalence,
see `ring_hom.equiv_rat_alg_hom`. -/
def to_rat_alg_hom [ring R] [ring S] [algebra ℚ R] [algebra ℚ S] (f : R →+* S) :
R →ₐ[ℚ] S :=
{ commutes' := f.map_rat_algebra_map, .. f }
@[simp]
lemma to_rat_alg_hom_to_ring_hom [ring R] [ring S] [algebra ℚ R] [algebra ℚ S]
(f : R →+* S) : ↑f.to_rat_alg_hom = f :=
ring_hom.ext $ λ x, rfl
end ring_hom
section
variables {R S : Type*}
@[simp]
lemma alg_hom.to_ring_hom_to_rat_alg_hom [ring R] [ring S] [algebra ℚ R] [algebra ℚ S]
(f : R →ₐ[ℚ] S) : (f : R →+* S).to_rat_alg_hom = f :=
alg_hom.ext $ λ x, rfl
/-- The equivalence between `ring_hom` and `ℚ`-algebra homomorphisms. -/
@[simps]
def ring_hom.equiv_rat_alg_hom [ring R] [ring S] [algebra ℚ R] [algebra ℚ S] :
(R →+* S) ≃ (R →ₐ[ℚ] S) :=
{ to_fun := ring_hom.to_rat_alg_hom,
inv_fun := alg_hom.to_ring_hom,
left_inv := ring_hom.to_rat_alg_hom_to_ring_hom,
right_inv := alg_hom.to_ring_hom_to_rat_alg_hom, }
end
namespace algebra
variables (R : Type u) (A : Type v)
variables [comm_semiring R] [semiring A] [algebra R A]
/-- `algebra_map` as an `alg_hom`. -/
def of_id : R →ₐ[R] A :=
{ commutes' := λ _, rfl, .. algebra_map R A }
variables {R}
theorem of_id_apply (r) : of_id R A r = algebra_map R A r := rfl
end algebra
namespace mul_semiring_action
variables {M G : Type*} (R A : Type*) [comm_semiring R] [semiring A] [algebra R A]
variables [monoid M] [mul_semiring_action M A] [smul_comm_class M R A]
/-- Each element of the monoid defines a algebra homomorphism.
This is a stronger version of `mul_semiring_action.to_ring_hom` and
`distrib_mul_action.to_linear_map`. -/
@[simps]
def to_alg_hom (m : M) : A →ₐ[R] A :=
{ to_fun := λ a, m • a,
commutes' := smul_algebra_map _,
..mul_semiring_action.to_ring_hom _ _ m }
theorem to_alg_hom_injective [has_faithful_smul M A] :
function.injective (mul_semiring_action.to_alg_hom R A : M → A →ₐ[R] A) :=
λ m₁ m₂ h, eq_of_smul_eq_smul $ λ r, alg_hom.ext_iff.1 h r
end mul_semiring_action
|
144bd58105dc1592d5e0d1255705bbf4332be0ca | 5a6ff5f8d173cbfe51967eb4c96837e3a791fe3d | /mm0-lean/mm0/mm0b.lean | dd3f39cd7e883d02e47e76ec63515eff0cf515f5 | [
"CC0-1.0"
] | permissive | digama0/mm0 | 491ac09146708aa1bb775007bf3dbe339ffc0096 | 98496badaf6464e56ed7b4204e7d54b85667cb01 | refs/heads/master | 1,692,321,030,902 | 1,686,254,458,000 | 1,686,254,458,000 | 172,456,790 | 273 | 38 | CC0-1.0 | 1,689,939,563,000 | 1,551,080,059,000 | Rust | UTF-8 | Lean | false | false | 5,587 | lean | namespace mm0
namespace mm0b
def sortid := ℕ
def termid := ℕ
def thmid := ℕ
def heapid := ℕ
def ptr := ℕ
structure sort_data := (pure strict provable free : bool := ff)
inductive proof_cmd : Type
| save : proof_cmd
| term : termid → proof_cmd
| ref : heapid → proof_cmd
| dummy : sortid → proof_cmd
| thm : thmid → proof_cmd
| hyp : proof_cmd
| conv : proof_cmd
| refl : proof_cmd
| symm : proof_cmd
| cong : proof_cmd
| unfold : proof_cmd
| conv_cut : proof_cmd
| conv_ref : heapid → proof_cmd
inductive type : Type
| bound : sortid → type
| reg : sortid → list bool → type
inductive sexpr : Type
| var : type → heapid → sexpr
| app : type → termid → list ptr → sexpr
inductive stackel
| expr : ptr → stackel
| proof : ptr → stackel
| conv : ptr → ptr → stackel
| co_conv : ptr → ptr → stackel
| hyp : ptr → stackel
def type.sort : type → sortid
| (type.bound s) := s
| (type.reg s _) := s
inductive unify_cmd
| save : unify_cmd
| term : termid → unify_cmd
| ref : heapid → unify_cmd
| dummy : sortid → unify_cmd
| hyp : unify_cmd
structure termel :=
(bis : list type)
(ret : type)
(defn : option (list unify_cmd))
structure thmel :=
(bis : list type)
(unify : list unify_cmd)
structure env :=
(sorts : list sort_data)
(terms : list termel)
(thms : list thmel)
inductive get_term_args : ℕ → list stackel → list ptr → list stackel → Prop
| zero (S) : get_term_args 0 S [] S
| succ (n S₁ p ps S₂) :
get_term_args n S₁ ps S₂ →
get_term_args (n+1) (stackel.expr p :: S₁) (ps ++ [p]) S₂
structure state :=
(stack : list stackel)
(heap : list stackel)
(store : list sexpr)
inductive unify : list sexpr → list ptr × list unify_cmd → list ptr → list stackel → list stackel → Prop
| save (σ H us e K S S') :
unify σ (H ++ [e], us) (e :: K) S S' →
unify σ (H, unify_cmd.save :: us) (e :: K) S S'
| term (σ : list sexpr) (H us e t τ es K S S') :
σ.nth e = some (sexpr.app τ t es) →
unify σ (H, us) (es ++ K) S S' →
unify σ (H, unify_cmd.term t :: us) (e :: K) S S'
| ref (σ) (H : list ptr) (us e v K S S') :
H.nth v = some e →
unify σ (H, us) K S S' →
unify σ (H, unify_cmd.ref v :: us) (e :: K) S S'
| dummy (σ : list sexpr) (H us e s v K S S') :
σ.nth e = some (sexpr.var (type.bound s) v) →
unify σ (H ++ [e], us) K S S' →
unify σ (H, unify_cmd.dummy s :: us) (e :: K) S S'
| hyp (σ H us e K S S') :
unify σ (H, us) (e :: K) S S' →
unify σ (H, unify_cmd.hyp :: us) K (stackel.proof e :: S) S'
| nil (σ H S) : unify σ (H, []) [] S S
inductive step_proof (env : env) : proof_cmd → state → state → Prop
| save (e S H σ) : step_proof proof_cmd.save ⟨e :: S, H, σ⟩ ⟨e :: S, H ++ [e], σ⟩
| term (t el S args S' H σ) :
env.terms.nth t = some el →
get_term_args el.bis.length S args S' →
step_proof (proof_cmd.term t) ⟨S, H, σ⟩
⟨stackel.expr σ.length :: S', H, σ ++ [sexpr.app el.ret t args]⟩
| ref (v S) (H : list stackel) (el σ) :
H.nth v = some el →
step_proof (proof_cmd.ref v) ⟨S, H, σ⟩ ⟨el :: S, H, σ⟩
| dummy (s S H σ) :
step_proof (proof_cmd.dummy s) ⟨S, H, σ⟩
⟨stackel.expr σ.length :: S,
H ++ [stackel.expr σ.length],
σ ++ [sexpr.var (type.bound s) H.length]⟩
| thm (t e el S args S₁ S₂ H σ) :
env.thms.nth t = some el →
get_term_args el.bis.length S args S₁ →
unify σ (args, el.unify) [e] S₁ S₂ →
step_proof (proof_cmd.thm t) ⟨stackel.expr e :: S, H, σ⟩ ⟨S₂, H, σ⟩
| hyp (e S H σ) :
step_proof proof_cmd.hyp
⟨stackel.expr e :: S, H, σ⟩
⟨stackel.hyp e :: S, H ++ [stackel.proof e], σ⟩
| conv (e1 e2 S H σ) :
step_proof proof_cmd.conv
⟨stackel.proof e2 :: stackel.expr e1 :: S, H, σ⟩
⟨stackel.co_conv e1 e2 :: stackel.proof e1 :: S, H, σ⟩
| refl (e S H σ) :
step_proof proof_cmd.refl
⟨stackel.co_conv e e :: S, H, σ⟩ ⟨S, H, σ⟩
| symm (e1 e2 S H σ) :
step_proof proof_cmd.symm
⟨stackel.co_conv e1 e2 :: S, H, σ⟩
⟨stackel.co_conv e2 e1 :: S, H, σ⟩
| cong (e1 e2 t τ1 τ2 es1 es2 S H) (σ : list sexpr) :
σ.nth e1 = sexpr.app τ1 t es1 →
σ.nth e2 = sexpr.app τ2 t es2 →
step_proof proof_cmd.cong
⟨stackel.co_conv e1 e2 :: S, H, σ⟩
⟨list.zip_with stackel.co_conv es1 es2 ++ S, H, σ⟩
| unfold (e e' τ t el us e2 args S H S') (σ : list sexpr) :
σ.nth e = sexpr.app τ t args →
env.terms.nth t = some el → el.defn = some us →
unify σ (args, us) [e2] S (stackel.co_conv e e' :: S') →
step_proof proof_cmd.cong
⟨stackel.expr e2 :: stackel.expr e :: S, H, σ⟩
⟨stackel.co_conv e2 e' :: S', H, σ⟩
| conv_cut (e1 e2 S H) (σ : list sexpr) :
step_proof proof_cmd.conv_cut
⟨stackel.expr e2 :: stackel.expr e1 :: S, H, σ⟩
⟨stackel.co_conv e1 e2 :: stackel.conv e1 e2 :: S, H, σ⟩
| conv_ref (v e1 e2 S) (H : list stackel) (σ) :
H.nth v = some (stackel.conv e1 e2) →
step_proof (proof_cmd.conv_ref v)
⟨stackel.co_conv e1 e2 :: S, H, σ⟩ ⟨S, H, σ⟩
inductive initial_state (env : env) : list type → state → Prop
inductive proof (env : env) (args : list ptr) (us : list unify_cmd)
(thm : bool) : list proof_cmd → state → Prop
| cons (p ps st st') :
step_proof env p st st' →
proof ps st' → proof (p :: ps) st
| nil (S H σ e) :
unify σ (args, us) [e] (stackel.proof <$> S) [] →
proof [] ⟨(if thm then stackel.proof e else stackel.expr e) ::
(stackel.hyp <$> S), H, σ⟩
end mm0b
end mm0
|
933b23eb0117946785d31dfc8be3a90a0d6402b8 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/data/real/nnreal.lean | 36c852b58a048a5d1a4553cd0cf08e6f8a57feae | [
"Apache-2.0"
] | permissive | waynemunro/mathlib | e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552 | 065a70810b5480d584033f7bbf8e0409480c2118 | refs/heads/master | 1,693,417,182,397 | 1,634,644,781,000 | 1,634,644,781,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 27,866 | lean | /-
Copyright (c) 2018 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import algebra.big_operators.ring
import data.real.basic
import algebra.indicator_function
import algebra.algebra.basic
import algebra.order.nonneg
/-!
# Nonnegative real numbers
In this file we define `nnreal` (notation: `ℝ≥0`) to be the type of non-negative real numbers,
a.k.a. the interval `[0, ∞)`. We also define the following operations and structures on `ℝ≥0`:
* the order on `ℝ≥0` is the restriction of the order on `ℝ`; these relations define a conditionally
complete linear order with a bottom element, `conditionally_complete_linear_order_bot`;
* `a + b` and `a * b` are the restrictions of addition and multiplication of real numbers to `ℝ≥0`;
these operations together with `0 = ⟨0, _⟩` and `1 = ⟨1, _⟩` turn `ℝ≥0` into a linear ordered
archimedean commutative semifield; we have no typeclass for this in `mathlib` yet, so we define
the following instances instead:
- `linear_ordered_semiring ℝ≥0`;
- `ordered_comm_semiring ℝ≥0`;
- `canonically_ordered_comm_semiring ℝ≥0`;
- `linear_ordered_comm_group_with_zero ℝ≥0`;
- `canonically_linear_ordered_add_monoid ℝ≥0`
- `archimedean ℝ≥0`.
These instances are derived from corresponding instances about the type `{x : α // 0 ≤ x}` in an
appropriate ordered field/ring/group/monoid `α`. See `algebra/order/nonneg`.
* `real.to_nnreal x` is defined as `⟨max x 0, _⟩`, i.e. `↑(real.to_nnreal x) = x` when `0 ≤ x` and
`↑(real.to_nnreal x) = 0` otherwise.
We also define an instance `can_lift ℝ ℝ≥0`. This instance can be used by the `lift` tactic to
replace `x : ℝ` and `hx : 0 ≤ x` in the proof context with `x : ℝ≥0` while replacing all occurences
of `x` with `↑x`. This tactic also works for a function `f : α → ℝ` with a hypothesis
`hf : ∀ x, 0 ≤ f x`.
## Notations
This file defines `ℝ≥0` as a localized notation for `nnreal`.
-/
noncomputable theory
open_locale classical big_operators
/-- Nonnegative real numbers. -/
@[derive [semilattice_inf_bot, densely_ordered,
canonically_linear_ordered_add_monoid, linear_ordered_comm_group_with_zero, archimedean,
linear_ordered_semiring, ordered_comm_semiring, canonically_ordered_comm_semiring,
has_sub, has_ordered_sub, has_div, inhabited]]
def nnreal := {r : ℝ // 0 ≤ r}
localized "notation ` ℝ≥0 ` := nnreal" in nnreal
namespace nnreal
instance : has_coe ℝ≥0 ℝ := ⟨subtype.val⟩
/- Simp lemma to put back `n.val` into the normal form given by the coercion. -/
@[simp] lemma val_eq_coe (n : ℝ≥0) : n.val = n := rfl
instance : can_lift ℝ ℝ≥0 :=
{ coe := coe,
cond := λ r, 0 ≤ r,
prf := λ x hx, ⟨⟨x, hx⟩, rfl⟩ }
protected lemma eq {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) → n = m := subtype.eq
protected lemma eq_iff {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) ↔ n = m :=
iff.intro nnreal.eq (congr_arg coe)
lemma ne_iff {x y : ℝ≥0} : (x : ℝ) ≠ (y : ℝ) ↔ x ≠ y :=
not_iff_not_of_iff $ nnreal.eq_iff
/-- Reinterpret a real number `r` as a non-negative real number. Returns `0` if `r < 0`. -/
def _root_.real.to_nnreal (r : ℝ) : ℝ≥0 := ⟨max r 0, le_max_right _ _⟩
lemma _root_.real.coe_to_nnreal (r : ℝ) (hr : 0 ≤ r) : (real.to_nnreal r : ℝ) = r :=
max_eq_left hr
lemma _root_.real.le_coe_to_nnreal (r : ℝ) : r ≤ real.to_nnreal r :=
le_max_left r 0
lemma coe_nonneg (r : ℝ≥0) : (0 : ℝ) ≤ r := r.2
@[norm_cast]
theorem coe_mk (a : ℝ) (ha) : ((⟨a, ha⟩ : ℝ≥0) : ℝ) = a := rfl
example : has_zero ℝ≥0 := by apply_instance
example : has_one ℝ≥0 := by apply_instance
example : has_add ℝ≥0 := by apply_instance
example : has_sub ℝ≥0 := by apply_instance
example : has_mul ℝ≥0 := by apply_instance
example : has_inv ℝ≥0 := by apply_instance
example : has_div ℝ≥0 := by apply_instance
example : has_le ℝ≥0 := by apply_instance
example : has_bot ℝ≥0 := by apply_instance
example : inhabited ℝ≥0 := by apply_instance
example : nontrivial ℝ≥0 := by apply_instance
protected lemma coe_injective : function.injective (coe : ℝ≥0 → ℝ) := subtype.coe_injective
@[simp, norm_cast] protected lemma coe_eq {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) = r₂ ↔ r₁ = r₂ :=
nnreal.coe_injective.eq_iff
protected lemma coe_zero : ((0 : ℝ≥0) : ℝ) = 0 := rfl
protected lemma coe_one : ((1 : ℝ≥0) : ℝ) = 1 := rfl
protected lemma coe_add (r₁ r₂ : ℝ≥0) : ((r₁ + r₂ : ℝ≥0) : ℝ) = r₁ + r₂ := rfl
protected lemma coe_mul (r₁ r₂ : ℝ≥0) : ((r₁ * r₂ : ℝ≥0) : ℝ) = r₁ * r₂ := rfl
protected lemma coe_inv (r : ℝ≥0) : ((r⁻¹ : ℝ≥0) : ℝ) = r⁻¹ := rfl
protected lemma coe_div (r₁ r₂ : ℝ≥0) : ((r₁ / r₂ : ℝ≥0) : ℝ) = r₁ / r₂ := rfl
@[simp, norm_cast] protected lemma coe_bit0 (r : ℝ≥0) : ((bit0 r : ℝ≥0) : ℝ) = bit0 r := rfl
@[simp, norm_cast] protected lemma coe_bit1 (r : ℝ≥0) : ((bit1 r : ℝ≥0) : ℝ) = bit1 r := rfl
@[simp, norm_cast] protected lemma coe_sub {r₁ r₂ : ℝ≥0} (h : r₂ ≤ r₁) :
((r₁ - r₂ : ℝ≥0) : ℝ) = r₁ - r₂ :=
max_eq_left $ le_sub.2 $ by simp [show (r₂ : ℝ) ≤ r₁, from h]
-- TODO: setup semifield!
@[simp, norm_cast] protected lemma coe_eq_zero (r : ℝ≥0) : ↑r = (0 : ℝ) ↔ r = 0 :=
by rw [← nnreal.coe_zero, nnreal.coe_eq]
@[simp, norm_cast] protected lemma coe_eq_one (r : ℝ≥0) : ↑r = (1 : ℝ) ↔ r = 1 :=
by rw [← nnreal.coe_one, nnreal.coe_eq]
lemma coe_ne_zero {r : ℝ≥0} : (r : ℝ) ≠ 0 ↔ r ≠ 0 := by norm_cast
example : comm_semiring ℝ≥0 := by apply_instance
/-- Coercion `ℝ≥0 → ℝ` as a `ring_hom`. -/
def to_real_hom : ℝ≥0 →+* ℝ :=
⟨coe, nnreal.coe_one, nnreal.coe_mul, nnreal.coe_zero, nnreal.coe_add⟩
@[simp] lemma coe_to_real_hom : ⇑to_real_hom = coe := rfl
section actions
/-- A `mul_action` over `ℝ` restricts to a `mul_action` over `ℝ≥0`. -/
instance {M : Type*} [mul_action ℝ M] : mul_action ℝ≥0 M :=
mul_action.comp_hom M to_real_hom.to_monoid_hom
lemma smul_def {M : Type*} [mul_action ℝ M] (c : ℝ≥0) (x : M) :
c • x = (c : ℝ) • x := rfl
instance {M N : Type*} [mul_action ℝ M] [mul_action ℝ N] [has_scalar M N]
[is_scalar_tower ℝ M N] : is_scalar_tower ℝ≥0 M N :=
{ smul_assoc := λ r, (smul_assoc (r : ℝ) : _)}
instance smul_comm_class_left {M N : Type*} [mul_action ℝ N] [has_scalar M N]
[smul_comm_class ℝ M N] : smul_comm_class ℝ≥0 M N :=
{ smul_comm := λ r, (smul_comm (r : ℝ) : _)}
instance smul_comm_class_right {M N : Type*} [mul_action ℝ N] [has_scalar M N]
[smul_comm_class M ℝ N] : smul_comm_class M ℝ≥0 N :=
{ smul_comm := λ m r, (smul_comm m (r : ℝ) : _)}
/-- A `distrib_mul_action` over `ℝ` restricts to a `distrib_mul_action` over `ℝ≥0`. -/
instance {M : Type*} [add_monoid M] [distrib_mul_action ℝ M] : distrib_mul_action ℝ≥0 M :=
distrib_mul_action.comp_hom M to_real_hom.to_monoid_hom
/-- A `module` over `ℝ` restricts to a `module` over `ℝ≥0`. -/
instance {M : Type*} [add_comm_monoid M] [module ℝ M] : module ℝ≥0 M :=
module.comp_hom M to_real_hom
/-- An `algebra` over `ℝ` restricts to an `algebra` over `ℝ≥0`. -/
instance {A : Type*} [semiring A] [algebra ℝ A] : algebra ℝ≥0 A :=
{ smul := (•),
commutes' := λ r x, by simp [algebra.commutes],
smul_def' := λ r x, by simp [←algebra.smul_def (r : ℝ) x, smul_def],
to_ring_hom := ((algebra_map ℝ A).comp (to_real_hom : ℝ≥0 →+* ℝ)) }
-- verify that the above produces instances we might care about
example : algebra ℝ≥0 ℝ := by apply_instance
example : distrib_mul_action (units ℝ≥0) ℝ := by apply_instance
end actions
example : comm_group_with_zero ℝ≥0 := by apply_instance
@[simp, norm_cast] lemma coe_indicator {α} (s : set α) (f : α → ℝ≥0) (a : α) :
((s.indicator f a : ℝ≥0) : ℝ) = s.indicator (λ x, f x) a :=
(to_real_hom : ℝ≥0 →+ ℝ).map_indicator _ _ _
@[simp, norm_cast] lemma coe_pow (r : ℝ≥0) (n : ℕ) : ((r^n : ℝ≥0) : ℝ) = r^n :=
to_real_hom.map_pow r n
@[norm_cast] lemma coe_list_sum (l : list ℝ≥0) :
((l.sum : ℝ≥0) : ℝ) = (l.map coe).sum :=
to_real_hom.map_list_sum l
@[norm_cast] lemma coe_list_prod (l : list ℝ≥0) :
((l.prod : ℝ≥0) : ℝ) = (l.map coe).prod :=
to_real_hom.map_list_prod l
@[norm_cast] lemma coe_multiset_sum (s : multiset ℝ≥0) :
((s.sum : ℝ≥0) : ℝ) = (s.map coe).sum :=
to_real_hom.map_multiset_sum s
@[norm_cast] lemma coe_multiset_prod (s : multiset ℝ≥0) :
((s.prod : ℝ≥0) : ℝ) = (s.map coe).prod :=
to_real_hom.map_multiset_prod s
@[norm_cast] lemma coe_sum {α} {s : finset α} {f : α → ℝ≥0} :
↑(∑ a in s, f a) = ∑ a in s, (f a : ℝ) :=
to_real_hom.map_sum _ _
lemma _root_.real.to_nnreal_sum_of_nonneg {α} {s : finset α} {f : α → ℝ}
(hf : ∀ a, a ∈ s → 0 ≤ f a) :
real.to_nnreal (∑ a in s, f a) = ∑ a in s, real.to_nnreal (f a) :=
begin
rw [←nnreal.coe_eq, nnreal.coe_sum, real.coe_to_nnreal _ (finset.sum_nonneg hf)],
exact finset.sum_congr rfl (λ x hxs, by rw real.coe_to_nnreal _ (hf x hxs)),
end
@[norm_cast] lemma coe_prod {α} {s : finset α} {f : α → ℝ≥0} :
↑(∏ a in s, f a) = ∏ a in s, (f a : ℝ) :=
to_real_hom.map_prod _ _
lemma _root_.real.to_nnreal_prod_of_nonneg {α} {s : finset α} {f : α → ℝ}
(hf : ∀ a, a ∈ s → 0 ≤ f a) :
real.to_nnreal (∏ a in s, f a) = ∏ a in s, real.to_nnreal (f a) :=
begin
rw [←nnreal.coe_eq, nnreal.coe_prod, real.coe_to_nnreal _ (finset.prod_nonneg hf)],
exact finset.prod_congr rfl (λ x hxs, by rw real.coe_to_nnreal _ (hf x hxs)),
end
lemma nsmul_coe (r : ℝ≥0) (n : ℕ) : ↑(n • r) = n • (r:ℝ) :=
by norm_cast
@[simp, norm_cast] protected lemma coe_nat_cast (n : ℕ) : (↑(↑n : ℝ≥0) : ℝ) = n :=
to_real_hom.map_nat_cast n
example : linear_order ℝ≥0 := by apply_instance
@[simp, norm_cast] protected lemma coe_le_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) ≤ r₂ ↔ r₁ ≤ r₂ := iff.rfl
@[simp, norm_cast] protected lemma coe_lt_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) < r₂ ↔ r₁ < r₂ := iff.rfl
@[simp, norm_cast] protected lemma coe_pos {r : ℝ≥0} : (0 : ℝ) < r ↔ 0 < r := iff.rfl
protected lemma coe_mono : monotone (coe : ℝ≥0 → ℝ) := λ _ _, nnreal.coe_le_coe.2
protected lemma _root_.real.to_nnreal_mono : monotone real.to_nnreal :=
λ x y h, max_le_max h (le_refl 0)
@[simp] lemma _root_.real.to_nnreal_coe {r : ℝ≥0} : real.to_nnreal r = r :=
nnreal.eq $ max_eq_left r.2
@[simp] lemma mk_coe_nat (n : ℕ) : @eq ℝ≥0 (⟨(n : ℝ), n.cast_nonneg⟩ : ℝ≥0) n :=
nnreal.eq (nnreal.coe_nat_cast n).symm
@[simp] lemma to_nnreal_coe_nat (n : ℕ) : real.to_nnreal n = n :=
nnreal.eq $ by simp [real.coe_to_nnreal]
/-- `real.to_nnreal` and `coe : ℝ≥0 → ℝ` form a Galois insertion. -/
protected def gi : galois_insertion real.to_nnreal coe :=
galois_insertion.monotone_intro nnreal.coe_mono real.to_nnreal_mono
real.le_coe_to_nnreal (λ _, real.to_nnreal_coe)
example : order_bot ℝ≥0 := by apply_instance
example : canonically_linear_ordered_add_monoid ℝ≥0 := by apply_instance
example : linear_ordered_add_comm_monoid ℝ≥0 := by apply_instance
example : distrib_lattice ℝ≥0 := by apply_instance
example : semilattice_inf_bot ℝ≥0 := by apply_instance
example : semilattice_sup_bot ℝ≥0 := by apply_instance
example : linear_ordered_semiring ℝ≥0 := by apply_instance
example : ordered_comm_semiring ℝ≥0 := by apply_instance
example : linear_ordered_comm_monoid ℝ≥0 := by apply_instance
example : linear_ordered_comm_monoid_with_zero ℝ≥0 := by apply_instance
example : linear_ordered_comm_group_with_zero ℝ≥0 := by apply_instance
example : canonically_ordered_comm_semiring ℝ≥0 := by apply_instance
example : densely_ordered ℝ≥0 := by apply_instance
example : no_top_order ℝ≥0 := by apply_instance
lemma bdd_above_coe {s : set ℝ≥0} : bdd_above ((coe : ℝ≥0 → ℝ) '' s) ↔ bdd_above s :=
iff.intro
(assume ⟨b, hb⟩, ⟨real.to_nnreal b, assume ⟨y, hy⟩ hys, show y ≤ max b 0, from
le_max_of_le_left $ hb $ set.mem_image_of_mem _ hys⟩)
(assume ⟨b, hb⟩, ⟨b, assume y ⟨x, hx, eq⟩, eq ▸ hb hx⟩)
lemma bdd_below_coe (s : set ℝ≥0) : bdd_below ((coe : ℝ≥0 → ℝ) '' s) :=
⟨0, assume r ⟨q, _, eq⟩, eq ▸ q.2⟩
instance : conditionally_complete_linear_order_bot ℝ≥0 :=
{ cSup_empty := (function.funext_iff.1
(@subset_Sup_def ℝ (set.Ici (0 : ℝ)) _ ⟨(0 : ℝ≥0)⟩) ∅).trans $ nnreal.eq $ by simp,
.. (by apply_instance : order_bot ℝ≥0),
.. @ord_connected_subset_conditionally_complete_linear_order ℝ (set.Ici (0 : ℝ)) _ ⟨(0 : ℝ≥0)⟩ _ }
lemma coe_Sup (s : set ℝ≥0) : (↑(Sup s) : ℝ) = Sup ((coe : ℝ≥0 → ℝ) '' s) :=
eq.symm $ @subset_Sup_of_within ℝ (set.Ici 0) _ ⟨(0 : ℝ≥0)⟩ s $
real.Sup_nonneg _ $ λ y ⟨x, _, hy⟩, hy ▸ x.2
lemma coe_Inf (s : set ℝ≥0) : (↑(Inf s) : ℝ) = Inf ((coe : ℝ≥0 → ℝ) '' s) :=
eq.symm $ @subset_Inf_of_within ℝ (set.Ici 0) _ ⟨(0 : ℝ≥0)⟩ s $
real.Inf_nonneg _ $ λ y ⟨x, _, hy⟩, hy ▸ x.2
example : archimedean ℝ≥0 := by apply_instance
lemma le_of_forall_pos_le_add {a b : ℝ≥0} (h : ∀ε, 0 < ε → a ≤ b + ε) : a ≤ b :=
le_of_forall_le_of_dense $ assume x hxb,
begin
rcases le_iff_exists_add.1 (le_of_lt hxb) with ⟨ε, rfl⟩,
exact h _ ((lt_add_iff_pos_right b).1 hxb)
end
-- TODO: generalize to some ordered add_monoids, based on #6145
lemma le_of_add_le_left {a b c : ℝ≥0} (h : a + b ≤ c) : a ≤ c :=
by { refine le_trans _ h, simp }
lemma le_of_add_le_right {a b c : ℝ≥0} (h : a + b ≤ c) : b ≤ c :=
by { refine le_trans _ h, simp }
lemma lt_iff_exists_rat_btwn (a b : ℝ≥0) :
a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < real.to_nnreal q ∧ real.to_nnreal q < b) :=
iff.intro
(assume (h : (↑a:ℝ) < (↑b:ℝ)),
let ⟨q, haq, hqb⟩ := exists_rat_btwn h in
have 0 ≤ (q : ℝ), from le_trans a.2 $ le_of_lt haq,
⟨q, rat.cast_nonneg.1 this,
by simp [real.coe_to_nnreal _ this, nnreal.coe_lt_coe.symm, haq, hqb]⟩)
(assume ⟨q, _, haq, hqb⟩, lt_trans haq hqb)
lemma bot_eq_zero : (⊥ : ℝ≥0) = 0 := rfl
lemma mul_sup (a b c : ℝ≥0) : a * (b ⊔ c) = (a * b) ⊔ (a * c) :=
begin
cases le_total b c with h h,
{ simp [sup_eq_max, max_eq_right h, max_eq_right (mul_le_mul_of_nonneg_left h (zero_le a))] },
{ simp [sup_eq_max, max_eq_left h, max_eq_left (mul_le_mul_of_nonneg_left h (zero_le a))] },
end
lemma mul_finset_sup {α} {f : α → ℝ≥0} {s : finset α} (r : ℝ≥0) :
r * s.sup f = s.sup (λa, r * f a) :=
begin
refine s.induction_on _ _,
{ simp [bot_eq_zero] },
{ assume a s has ih, simp [has, ih, mul_sup], }
end
lemma finset_sup_div {α} {f : α → ℝ≥0} {s : finset α} (r : ℝ≥0) :
s.sup f / r = s.sup (λ a, f a / r) :=
by simp only [div_eq_inv_mul, mul_finset_sup]
@[simp, norm_cast] lemma coe_max (x y : ℝ≥0) :
((max x y : ℝ≥0) : ℝ) = max (x : ℝ) (y : ℝ) :=
nnreal.coe_mono.map_max
@[simp, norm_cast] lemma coe_min (x y : ℝ≥0) :
((min x y : ℝ≥0) : ℝ) = min (x : ℝ) (y : ℝ) :=
nnreal.coe_mono.map_min
@[simp] lemma zero_le_coe {q : ℝ≥0} : 0 ≤ (q : ℝ) := q.2
end nnreal
namespace real
section to_nnreal
@[simp] lemma to_nnreal_zero : real.to_nnreal 0 = 0 :=
by simp [real.to_nnreal]; refl
@[simp] lemma to_nnreal_one : real.to_nnreal 1 = 1 :=
by simp [real.to_nnreal, max_eq_left (zero_le_one : (0 :ℝ) ≤ 1)]; refl
@[simp] lemma to_nnreal_pos {r : ℝ} : 0 < real.to_nnreal r ↔ 0 < r :=
by simp [real.to_nnreal, nnreal.coe_lt_coe.symm, lt_irrefl]
@[simp] lemma to_nnreal_eq_zero {r : ℝ} : real.to_nnreal r = 0 ↔ r ≤ 0 :=
by simpa [-to_nnreal_pos] using (not_iff_not.2 (@to_nnreal_pos r))
lemma to_nnreal_of_nonpos {r : ℝ} : r ≤ 0 → real.to_nnreal r = 0 :=
to_nnreal_eq_zero.2
@[simp] lemma coe_to_nnreal' (r : ℝ) : (real.to_nnreal r : ℝ) = max r 0 := rfl
@[simp] lemma to_nnreal_le_to_nnreal_iff {r p : ℝ} (hp : 0 ≤ p) :
real.to_nnreal r ≤ real.to_nnreal p ↔ r ≤ p :=
by simp [nnreal.coe_le_coe.symm, real.to_nnreal, hp]
@[simp] lemma to_nnreal_lt_to_nnreal_iff' {r p : ℝ} :
real.to_nnreal r < real.to_nnreal p ↔ r < p ∧ 0 < p :=
by simp [nnreal.coe_lt_coe.symm, real.to_nnreal, lt_irrefl]
lemma to_nnreal_lt_to_nnreal_iff {r p : ℝ} (h : 0 < p) :
real.to_nnreal r < real.to_nnreal p ↔ r < p :=
to_nnreal_lt_to_nnreal_iff'.trans (and_iff_left h)
lemma to_nnreal_lt_to_nnreal_iff_of_nonneg {r p : ℝ} (hr : 0 ≤ r) :
real.to_nnreal r < real.to_nnreal p ↔ r < p :=
to_nnreal_lt_to_nnreal_iff'.trans ⟨and.left, λ h, ⟨h, lt_of_le_of_lt hr h⟩⟩
@[simp] lemma to_nnreal_add {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) :
real.to_nnreal (r + p) = real.to_nnreal r + real.to_nnreal p :=
nnreal.eq $ by simp [real.to_nnreal, hr, hp, add_nonneg]
lemma to_nnreal_add_to_nnreal {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) :
real.to_nnreal r + real.to_nnreal p = real.to_nnreal (r + p) :=
(real.to_nnreal_add hr hp).symm
lemma to_nnreal_le_to_nnreal {r p : ℝ} (h : r ≤ p) :
real.to_nnreal r ≤ real.to_nnreal p :=
real.to_nnreal_mono h
lemma to_nnreal_add_le {r p : ℝ} :
real.to_nnreal (r + p) ≤ real.to_nnreal r + real.to_nnreal p :=
nnreal.coe_le_coe.1 $ max_le (add_le_add (le_max_left _ _) (le_max_left _ _)) nnreal.zero_le_coe
lemma to_nnreal_le_iff_le_coe {r : ℝ} {p : ℝ≥0} : real.to_nnreal r ≤ p ↔ r ≤ ↑p :=
nnreal.gi.gc r p
lemma le_to_nnreal_iff_coe_le {r : ℝ≥0} {p : ℝ} (hp : 0 ≤ p) : r ≤ real.to_nnreal p ↔ ↑r ≤ p :=
by rw [← nnreal.coe_le_coe, real.coe_to_nnreal p hp]
lemma le_to_nnreal_iff_coe_le' {r : ℝ≥0} {p : ℝ} (hr : 0 < r) : r ≤ real.to_nnreal p ↔ ↑r ≤ p :=
(le_or_lt 0 p).elim le_to_nnreal_iff_coe_le $ λ hp,
by simp only [(hp.trans_le r.coe_nonneg).not_le, to_nnreal_eq_zero.2 hp.le, hr.not_le]
lemma to_nnreal_lt_iff_lt_coe {r : ℝ} {p : ℝ≥0} (ha : 0 ≤ r) : real.to_nnreal r < p ↔ r < ↑p :=
by rw [← nnreal.coe_lt_coe, real.coe_to_nnreal r ha]
lemma lt_to_nnreal_iff_coe_lt {r : ℝ≥0} {p : ℝ} : r < real.to_nnreal p ↔ ↑r < p :=
begin
cases le_total 0 p,
{ rw [← nnreal.coe_lt_coe, real.coe_to_nnreal p h] },
{ rw [to_nnreal_eq_zero.2 h], split,
{ intro, have := not_lt_of_le (zero_le r), contradiction },
{ intro rp, have : ¬(p ≤ 0) := not_le_of_lt (lt_of_le_of_lt (nnreal.coe_nonneg _) rp),
contradiction } }
end
@[simp] lemma to_nnreal_bit0 {r : ℝ} (hr : 0 ≤ r) :
real.to_nnreal (bit0 r) = bit0 (real.to_nnreal r) :=
real.to_nnreal_add hr hr
@[simp] lemma to_nnreal_bit1 {r : ℝ} (hr : 0 ≤ r) :
real.to_nnreal (bit1 r) = bit1 (real.to_nnreal r) :=
(real.to_nnreal_add (by simp [hr]) zero_le_one).trans (by simp [to_nnreal_one, bit1, hr])
end to_nnreal
end real
open real
namespace nnreal
section mul
lemma mul_eq_mul_left {a b c : ℝ≥0} (h : a ≠ 0) : (a * b = a * c ↔ b = c) :=
begin
rw [← nnreal.eq_iff, ← nnreal.eq_iff, nnreal.coe_mul, nnreal.coe_mul], split,
{ exact mul_left_cancel₀ (mt (@nnreal.eq_iff a 0).1 h) },
{ assume h, rw [h] }
end
lemma _root_.real.to_nnreal_mul {p q : ℝ} (hp : 0 ≤ p) :
real.to_nnreal (p * q) = real.to_nnreal p * real.to_nnreal q :=
begin
cases le_total 0 q with hq hq,
{ apply nnreal.eq,
simp [real.to_nnreal, hp, hq, max_eq_left, mul_nonneg] },
{ have hpq := mul_nonpos_of_nonneg_of_nonpos hp hq,
rw [to_nnreal_eq_zero.2 hq, to_nnreal_eq_zero.2 hpq, mul_zero] }
end
end mul
section pow
lemma pow_antitone_exp {a : ℝ≥0} (m n : ℕ) (mn : m ≤ n) (a1 : a ≤ 1) :
a ^ n ≤ a ^ m :=
begin
rcases le_iff_exists_add.mp mn with ⟨k, rfl⟩,
rw [← mul_one (a ^ m), pow_add],
refine mul_le_mul rfl.le (pow_le_one _ (zero_le a) a1) _ _;
exact pow_nonneg (zero_le _) _,
end
end pow
section sub
/-!
### Lemmas about subtraction
In this section we provide a few lemmas about subtraction that do not fit well into any other
typeclass. For lemmas about subtraction and addition see lemmas
about `has_ordered_sub` in the file `algebra.order.sub`. See also `mul_sub'` and `sub_mul'`. -/
lemma sub_def {r p : ℝ≥0} : r - p = real.to_nnreal (r - p) := rfl
lemma coe_sub_def {r p : ℝ≥0} : ↑(r - p) = max (r - p : ℝ) 0 := rfl
example : has_ordered_sub ℝ≥0 := by apply_instance
lemma sub_div (a b c : ℝ≥0) : (a - b) / c = a / c - b / c :=
by simp only [div_eq_mul_inv, sub_mul']
end sub
section inv
lemma sum_div {ι} (s : finset ι) (f : ι → ℝ≥0) (b : ℝ≥0) :
(∑ i in s, f i) / b = ∑ i in s, (f i / b) :=
by simp only [div_eq_mul_inv, finset.sum_mul]
@[simp] lemma inv_pos {r : ℝ≥0} : 0 < r⁻¹ ↔ 0 < r :=
by simp [pos_iff_ne_zero]
lemma div_pos {r p : ℝ≥0} (hr : 0 < r) (hp : 0 < p) : 0 < r / p :=
by simpa only [div_eq_mul_inv] using mul_pos hr (inv_pos.2 hp)
protected lemma mul_inv {r p : ℝ≥0} : (r * p)⁻¹ = p⁻¹ * r⁻¹ := nnreal.eq $ mul_inv_rev₀ _ _
lemma div_self_le (r : ℝ≥0) : r / r ≤ 1 :=
if h : r = 0 then by simp [h] else by rw [div_self h]
@[simp] lemma inv_le {r p : ℝ≥0} (h : r ≠ 0) : r⁻¹ ≤ p ↔ 1 ≤ r * p :=
by rw [← mul_le_mul_left (pos_iff_ne_zero.2 h), mul_inv_cancel h]
lemma inv_le_of_le_mul {r p : ℝ≥0} (h : 1 ≤ r * p) : r⁻¹ ≤ p :=
by by_cases r = 0; simp [*, inv_le]
@[simp] lemma le_inv_iff_mul_le {r p : ℝ≥0} (h : p ≠ 0) : (r ≤ p⁻¹ ↔ r * p ≤ 1) :=
by rw [← mul_le_mul_left (pos_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm]
@[simp] lemma lt_inv_iff_mul_lt {r p : ℝ≥0} (h : p ≠ 0) : (r < p⁻¹ ↔ r * p < 1) :=
by rw [← mul_lt_mul_left (pos_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm]
lemma mul_le_iff_le_inv {a b r : ℝ≥0} (hr : r ≠ 0) : r * a ≤ b ↔ a ≤ r⁻¹ * b :=
have 0 < r, from lt_of_le_of_ne (zero_le r) hr.symm,
by rw [← @mul_le_mul_left _ _ a _ r this, ← mul_assoc, mul_inv_cancel hr, one_mul]
lemma le_div_iff_mul_le {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ a * r ≤ b :=
by rw [div_eq_inv_mul, ← mul_le_iff_le_inv hr, mul_comm]
lemma div_le_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a / r ≤ b ↔ a ≤ b * r :=
@div_le_iff ℝ _ a r b $ pos_iff_ne_zero.2 hr
lemma div_le_iff' {a b r : ℝ≥0} (hr : r ≠ 0) : a / r ≤ b ↔ a ≤ r * b :=
@div_le_iff' ℝ _ a r b $ pos_iff_ne_zero.2 hr
lemma div_le_of_le_mul {a b c : ℝ≥0} (h : a ≤ b * c) : a / c ≤ b :=
if h0 : c = 0 then by simp [h0] else (div_le_iff h0).2 h
lemma div_le_of_le_mul' {a b c : ℝ≥0} (h : a ≤ b * c) : a / b ≤ c :=
div_le_of_le_mul $ mul_comm b c ▸ h
lemma le_div_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ a * r ≤ b :=
@le_div_iff ℝ _ a b r $ pos_iff_ne_zero.2 hr
lemma le_div_iff' {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ r * a ≤ b :=
@le_div_iff' ℝ _ a b r $ pos_iff_ne_zero.2 hr
lemma div_lt_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a / r < b ↔ a < b * r :=
lt_iff_lt_of_le_iff_le (le_div_iff hr)
lemma div_lt_iff' {a b r : ℝ≥0} (hr : r ≠ 0) : a / r < b ↔ a < r * b :=
lt_iff_lt_of_le_iff_le (le_div_iff' hr)
lemma lt_div_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a < b / r ↔ a * r < b :=
lt_iff_lt_of_le_iff_le (div_le_iff hr)
lemma lt_div_iff' {a b r : ℝ≥0} (hr : r ≠ 0) : a < b / r ↔ r * a < b :=
lt_iff_lt_of_le_iff_le (div_le_iff' hr)
lemma mul_lt_of_lt_div {a b r : ℝ≥0} (h : a < b / r) : a * r < b :=
begin
refine (lt_div_iff $ λ hr, false.elim _).1 h,
subst r,
simpa using h
end
lemma div_le_div_left_of_le {a b c : ℝ≥0} (b0 : 0 < b) (c0 : 0 < c) (cb : c ≤ b) :
a / b ≤ a / c :=
begin
by_cases a0 : a = 0,
{ rw [a0, zero_div, zero_div] },
{ cases a with a ha,
replace a0 : 0 < a := lt_of_le_of_ne ha (ne_of_lt (zero_lt_iff.mpr a0)),
exact (div_le_div_left a0 b0 c0).mpr cb }
end
lemma div_le_div_left {a b c : ℝ≥0} (a0 : 0 < a) (b0 : 0 < b) (c0 : 0 < c) :
a / b ≤ a / c ↔ c ≤ b :=
by rw [nnreal.div_le_iff b0.ne.symm, div_mul_eq_mul_div, nnreal.le_div_iff_mul_le c0.ne.symm,
mul_le_mul_left a0]
lemma le_of_forall_lt_one_mul_le {x y : ℝ≥0} (h : ∀a<1, a * x ≤ y) : x ≤ y :=
le_of_forall_ge_of_dense $ assume a ha,
have hx : x ≠ 0 := pos_iff_ne_zero.1 (lt_of_le_of_lt (zero_le _) ha),
have hx' : x⁻¹ ≠ 0, by rwa [(≠), inv_eq_zero],
have a * x⁻¹ < 1, by rwa [← lt_inv_iff_mul_lt hx', inv_inv₀],
have (a * x⁻¹) * x ≤ y, from h _ this,
by rwa [mul_assoc, inv_mul_cancel hx, mul_one] at this
lemma div_add_div_same (a b c : ℝ≥0) : a / c + b / c = (a + b) / c :=
eq.symm $ right_distrib a b (c⁻¹)
lemma half_pos {a : ℝ≥0} (h : 0 < a) : 0 < a / 2 := div_pos h zero_lt_two
lemma add_halves (a : ℝ≥0) : a / 2 + a / 2 = a := nnreal.eq (add_halves a)
lemma half_lt_self {a : ℝ≥0} (h : a ≠ 0) : a / 2 < a :=
by rw [← nnreal.coe_lt_coe, nnreal.coe_div]; exact
half_lt_self (bot_lt_iff_ne_bot.2 h)
lemma two_inv_lt_one : (2⁻¹:ℝ≥0) < 1 :=
by simpa using half_lt_self zero_ne_one.symm
lemma div_lt_one_of_lt {a b : ℝ≥0} (h : a < b) : a / b < 1 :=
begin
rwa [div_lt_iff, one_mul],
exact ne_of_gt (lt_of_le_of_lt (zero_le _) h)
end
@[field_simps] lemma div_add_div (a : ℝ≥0) {b : ℝ≥0} (c : ℝ≥0) {d : ℝ≥0}
(hb : b ≠ 0) (hd : d ≠ 0) : a / b + c / d = (a * d + b * c) / (b * d) :=
begin
rw ← nnreal.eq_iff,
simp only [nnreal.coe_add, nnreal.coe_div, nnreal.coe_mul],
exact div_add_div _ _ (coe_ne_zero.2 hb) (coe_ne_zero.2 hd)
end
@[field_simps] lemma add_div' (a b c : ℝ≥0) (hc : c ≠ 0) :
b + a / c = (b * c + a) / c :=
by simpa using div_add_div b a one_ne_zero hc
@[field_simps] lemma div_add' (a b c : ℝ≥0) (hc : c ≠ 0) :
a / c + b = (a + b * c) / c :=
by rwa [add_comm, add_div', add_comm]
lemma _root_.real.to_nnreal_inv {x : ℝ} :
real.to_nnreal x⁻¹ = (real.to_nnreal x)⁻¹ :=
begin
by_cases hx : 0 ≤ x,
{ nth_rewrite 0 ← real.coe_to_nnreal x hx,
rw [←nnreal.coe_inv, real.to_nnreal_coe], },
{ have hx' := le_of_not_ge hx,
rw [to_nnreal_eq_zero.mpr hx', inv_zero, to_nnreal_eq_zero.mpr (inv_nonpos.mpr hx')], },
end
lemma _root_.real.to_nnreal_div {x y : ℝ} (hx : 0 ≤ x) :
real.to_nnreal (x / y) = real.to_nnreal x / real.to_nnreal y :=
by rw [div_eq_mul_inv, div_eq_mul_inv, ← real.to_nnreal_inv, ← real.to_nnreal_mul hx]
lemma _root_.real.to_nnreal_div' {x y : ℝ} (hy : 0 ≤ y) :
real.to_nnreal (x / y) = real.to_nnreal x / real.to_nnreal y :=
by rw [div_eq_inv_mul, div_eq_inv_mul, real.to_nnreal_mul (inv_nonneg.2 hy), real.to_nnreal_inv]
end inv
@[simp] lemma abs_eq (x : ℝ≥0) : |(x : ℝ)| = x :=
abs_of_nonneg x.property
end nnreal
namespace real
/-- The absolute value on `ℝ` as a map to `ℝ≥0`. -/
@[pp_nodot] def nnabs : monoid_with_zero_hom ℝ ℝ≥0 :=
{ to_fun := λ x, ⟨|x|, abs_nonneg x⟩,
map_zero' := by { ext, simp },
map_one' := by { ext, simp },
map_mul' := λ x y, by { ext, simp [abs_mul] } }
@[norm_cast, simp] lemma coe_nnabs (x : ℝ) : (nnabs x : ℝ) = |x| :=
by simp [nnabs]
@[simp] lemma nnabs_of_nonneg {x : ℝ} (h : 0 ≤ x) : nnabs x = to_nnreal x :=
by { ext, simp [coe_to_nnreal x h, abs_of_nonneg h] }
lemma coe_to_nnreal_le (x : ℝ) : (to_nnreal x : ℝ) ≤ |x| :=
max_le (le_abs_self _) (abs_nonneg _)
lemma cast_nat_abs_eq_nnabs_cast (n : ℤ) :
(n.nat_abs : ℝ≥0) = nnabs n :=
by { ext, rw [nnreal.coe_nat_cast, int.cast_nat_abs, real.coe_nnabs] }
end real
|
c35fd5e1d6f289ce6895686a1bbb2ff31550e615 | 4767244035cdd124e1ce3d0c81128f8929df6163 | /ring_theory/noetherian.lean | 0f23ae604eb6b763ad47101a4655d5bb29a43ba8 | [
"Apache-2.0"
] | permissive | 5HT/mathlib | b941fecacd31a9c5dd0abad58770084b8a1e56b1 | 40fa9ade2f5649569639608db5e621e5fad0cc02 | refs/heads/master | 1,586,978,681,358 | 1,546,681,764,000 | 1,546,681,764,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,670 | lean | /-
Copyright (c) 2018 Mario Carneiro and Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Kevin Buzzard
-/
import data.equiv.algebra
import data.polynomial
import linear_algebra.lc
import ring_theory.ideal_operations
open set lattice
namespace submodule
variables {α : Type*} {β : Type*} [ring α] [add_comm_group β] [module α β]
def fg (s : submodule α β) : Prop := ∃ t : finset β, submodule.span ↑t = s
theorem fg_def {s : submodule α β} :
s.fg ↔ ∃ t : set β, finite t ∧ span t = s :=
⟨λ ⟨t, h⟩, ⟨_, finset.finite_to_set t, h⟩, begin
rintro ⟨t', h, rfl⟩,
rcases finite.exists_finset_coe h with ⟨t, rfl⟩,
exact ⟨t, rfl⟩
end⟩
theorem fg_bot : (⊥ : submodule α β).fg :=
⟨∅, by rw [finset.coe_empty, span_empty]⟩
theorem fg_sup {s₁ s₂ : submodule α β}
(hs₁ : s₁.fg) (hs₂ : s₂.fg) : (s₁ ⊔ s₂).fg :=
let ⟨t₁, ht₁⟩ := fg_def.1 hs₁, ⟨t₂, ht₂⟩ := fg_def.1 hs₂ in
fg_def.2 ⟨t₁ ∪ t₂, finite_union ht₁.1 ht₂.1, by rw [span_union, ht₁.2, ht₂.2]⟩
variables {γ : Type*} [add_comm_group γ] [module α γ]
variables {f : β →ₗ γ}
theorem fg_map {s : submodule α β} (hs : s.fg) : (s.map f).fg :=
let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, finite_image _ ht.1, by rw [span_image, ht.2]⟩
theorem fg_prod {sb : submodule α β} {sc : submodule α γ}
(hsb : sb.fg) (hsc : sc.fg) : (sb.prod sc).fg :=
let ⟨tb, htb⟩ := fg_def.1 hsb, ⟨tc, htc⟩ := fg_def.1 hsc in
fg_def.2 ⟨prod.inl '' tb ∪ prod.inr '' tc,
finite_union (finite_image _ htb.1) (finite_image _ htc.1),
by rw [linear_map.span_inl_union_inr, htb.2, htc.2]⟩
variable (f)
/-- If 0 → M' → M → M'' → 0 is exact and M' and M'' are
finitely generated then so is M. -/
theorem fg_of_fg_map_of_fg_inf_ker {s : submodule α β}
(hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg :=
begin
haveI := classical.dec_eq β, haveI := classical.dec_eq γ,
cases hs1 with t1 ht1, cases hs2 with t2 ht2,
have : ∀ y ∈ t1, ∃ x ∈ s, f x = y,
{ intros y hy,
have : y ∈ map f s, { rw ← ht1, exact subset_span hy },
rcases mem_map.1 this with ⟨x, hx1, hx2⟩,
exact ⟨x, hx1, hx2⟩ },
have : ∃ g : γ → β, ∀ y ∈ t1, g y ∈ s ∧ f (g y) = y,
{ choose g hg1 hg2,
existsi λ y, if H : y ∈ t1 then g y H else 0,
intros y H, split,
{ simp only [dif_pos H], apply hg1 },
{ simp only [dif_pos H], apply hg2 } },
cases this with g hg, clear this,
existsi t1.image g ∪ t2,
rw [finset.coe_union, span_union, finset.coe_image],
apply le_antisymm,
{ refine sup_le (span_le.2 $ image_subset_iff.2 _) (span_le.2 _),
{ intros y hy, exact (hg y hy).1 },
{ intros x hx, have := subset_span hx,
rw ht2 at this,
exact this.1 } },
intros x hx,
have : f x ∈ map f s, { rw mem_map, exact ⟨x, hx, rfl⟩ },
rw [← ht1, mem_span_iff_lc] at this,
rcases this with ⟨l, hl1, hl2⟩,
refine mem_sup.2 ⟨lc.total β ((lc.map g : lc α γ → lc α β) l), _,
x - lc.total β ((lc.map g : lc α γ → lc α β) l), _, add_sub_cancel'_right _ _⟩,
{ rw mem_span_iff_lc, refine ⟨_, _, rfl⟩,
rw [← lc.map_supported g, mem_map],
exact ⟨_, hl1, rfl⟩ },
rw [ht2, mem_inf], split,
{ apply s.sub_mem hx,
rw [lc.total_apply, lc.map_apply, finsupp.sum_map_domain_index],
refine s.sum_mem _,
{ intros y hy, exact s.smul_mem _ (hg y (hl1 hy)).1 },
{ exact zero_smul }, { exact λ _ _ _, add_smul _ _ _ } },
{ rw [linear_map.mem_ker, f.map_sub, ← hl2],
rw [lc.total_apply, lc.total_apply, lc.map_apply],
rw [finsupp.sum_map_domain_index, finsupp.sum, finsupp.sum, f.map_sum],
rw sub_eq_zero,
refine finset.sum_congr rfl (λ y hy, _),
rw [f.map_smul, (hg y (hl1 hy)).2],
{ exact zero_smul }, { exact λ _ _ _, add_smul _ _ _ } }
end
end submodule
def is_noetherian (α β) [ring α] [add_comm_group β] [module α β] : Prop :=
∀ (s : submodule α β), s.fg
section
variables {α : Type*} {β : Type*} {γ : Type*}
variables [ring α] [add_comm_group β] [add_comm_group γ]
variables [module α β] [module α γ]
include α
theorem is_noetherian_submodule {N : submodule α β} :
is_noetherian α N ↔ ∀ s : submodule α β, s ≤ N → s.fg :=
⟨λ hn s hs, have s ≤ N.subtype.range, from (N.range_subtype).symm ▸ hs,
linear_map.map_comap_eq_self this ▸ submodule.fg_map (hn _),
λ h s, submodule.fg_of_fg_map_of_fg_inf_ker N.subtype (h _ $ submodule.map_subtype_le _ _) $
by rw [submodule.ker_subtype, inf_bot_eq]; exact submodule.fg_bot⟩
theorem is_noetherian_submodule_left {N : submodule α β} :
is_noetherian α N ↔ ∀ s : submodule α β, (N ⊓ s).fg :=
is_noetherian_submodule.trans
⟨λ H s, H _ inf_le_left, λ H s hs, (inf_of_le_right hs) ▸ H _⟩
theorem is_noetherian_submodule_right {N : submodule α β} :
is_noetherian α N ↔ ∀ s : submodule α β, (s ⊓ N).fg :=
is_noetherian_submodule.trans
⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩
variable (β)
theorem is_noetherian_of_surjective (f : β →ₗ γ) (hf : f.range = ⊤)
(hb : is_noetherian α β) : is_noetherian α γ :=
λ s, have (s.comap f).map f = s, from linear_map.map_comap_eq_self $ hf.symm ▸ le_top,
this ▸ submodule.fg_map $ hb _
variable {β}
theorem is_noetherian_of_linear_equiv (f : β ≃ₗ γ)
(hb : is_noetherian α β) : is_noetherian α γ :=
is_noetherian_of_surjective _ f.to_linear_map f.range hb
theorem is_noetherian_prod (hb : is_noetherian α β)
(hc : is_noetherian α γ) : is_noetherian α (β × γ) :=
λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd β γ) (hc _) $
have s ⊓ linear_map.ker (linear_map.snd β γ) ≤ linear_map.range (linear_map.inl β γ),
from λ x ⟨hx1, hx2⟩, ⟨x.1, trivial, prod.ext rfl $ eq.symm $ linear_map.mem_ker.1 hx2⟩,
linear_map.map_comap_eq_self this ▸ submodule.fg_map (hb _)
theorem is_noetherian_pi {α ι : Type*} {β : ι → Type*} [ring α]
[Π i, add_comm_group (β i)] [Π i, module α (β i)] [fintype ι]
(hb : ∀ i, is_noetherian α (β i)) : is_noetherian α (Π i, β i) :=
begin
haveI := classical.dec_eq ι,
suffices : ∀ s : finset ι, is_noetherian α (Π i : (↑s : set ι), β i),
{ refine is_noetherian_of_linear_equiv ⟨_, _, _, _, _, _⟩ (this finset.univ),
{ exact λ f i, f ⟨i, finset.mem_univ _⟩ },
{ intros, ext, refl },
{ intros, ext, refl },
{ exact λ f i, f i.1 },
{ intro, ext i, cases i, refl },
{ intro, ext i, refl } },
intro s,
induction s using finset.induction with a s has ih,
{ intro s, convert submodule.fg_bot, apply eq_bot_iff.2,
intros x hx, refine submodule.mem_bot.2 _, ext i, cases i.2 },
refine is_noetherian_of_linear_equiv ⟨_, _, _, _, _, _⟩ (is_noetherian_prod (hb a) ih),
{ exact λ f i, or.by_cases (finset.mem_insert.1 i.2)
(λ h : i.1 = a, show β i.1, from (eq.rec_on h.symm f.1))
(λ h : i.1 ∈ s, show β i.1, from f.2 ⟨i.1, h⟩) },
{ intros f g, ext i, unfold or.by_cases, cases i with i hi,
rcases finset.mem_insert.1 hi with rfl | h,
{ change _ = _ + _, simp only [dif_pos], refl },
{ change _ = _ + _, have : ¬i = a, { rintro rfl, exact has h },
simp only [dif_neg this, dif_pos h], refl } },
{ intros c f, ext i, unfold or.by_cases, cases i with i hi,
rcases finset.mem_insert.1 hi with rfl | h,
{ change _ = c • _, simp only [dif_pos], refl },
{ change _ = c • _, have : ¬i = a, { rintro rfl, exact has h },
simp only [dif_neg this, dif_pos h], refl } },
{ exact λ f, (f ⟨a, finset.mem_insert_self _ _⟩, λ i, f ⟨i.1, finset.mem_insert_of_mem i.2⟩) },
{ intro f, apply prod.ext,
{ simp only [or.by_cases, dif_pos] },
{ ext i, cases i with i his,
have : ¬i = a, { rintro rfl, exact has his },
dsimp only [or.by_cases], change i ∈ s at his,
rw [dif_neg this, dif_pos his] } },
{ intro f, ext i, cases i with i hi,
rcases finset.mem_insert.1 hi with rfl | h,
{ simp only [or.by_cases, dif_pos], refl },
{ have : ¬i = a, { rintro rfl, exact has h },
simp only [or.by_cases, dif_neg this, dif_pos h], refl } }
end
end
theorem is_noetherian_iff_well_founded
{α β} [ring α] [add_comm_group β] [module α β] :
is_noetherian α β ↔ well_founded ((>) : submodule α β → submodule α β → Prop) :=
⟨λ h, begin
apply order_embedding.well_founded_iff_no_descending_seq.2,
swap, { apply is_strict_order.swap },
rintro ⟨⟨N, hN⟩⟩,
let M := ⨆ n, N n,
rcases submodule.fg_def.1 (h M) with ⟨t, h₁, h₂⟩,
have hN' : ∀ {a b}, a ≤ b → N a ≤ N b :=
λ a b, (le_iff_le_of_strict_mono N (λ _ _, hN.1)).2,
have : t ⊆ ⋃ i, (N i : set β),
{ rw [← submodule.Union_coe_of_directed _ N _],
{ show t ⊆ M, rw ← h₂,
apply submodule.subset_span },
{ apply_instance },
{ exact λ i j, ⟨max i j,
hN' (le_max_left _ _),
hN' (le_max_right _ _)⟩ } },
simp [subset_def] at this,
choose f hf using show ∀ x : t, ∃ (i : ℕ), x.1 ∈ N i, { simpa },
cases h₁ with h₁,
let A := finset.sup (@finset.univ t h₁) f,
have : M ≤ N A,
{ rw ← h₂, apply submodule.span_le.2,
exact λ x h, hN' (finset.le_sup (@finset.mem_univ t h₁ _))
(hf ⟨x, h⟩) },
exact not_le_of_lt (hN.1 (nat.lt_succ_self A))
(le_trans (le_supr _ _) this)
end,
begin
assume h N,
suffices : ∀ M ≤ N, ∃ s, finite s ∧ M ⊔ submodule.span s = N,
{ rcases this ⊥ bot_le with ⟨s, hs, e⟩,
exact submodule.fg_def.2 ⟨s, hs, by simpa using e⟩ },
refine λ M, h.induction M _, intros M IH MN,
letI := classical.dec,
by_cases h : ∀ x, x ∈ N → x ∈ M,
{ cases le_antisymm MN h, exact ⟨∅, by simp⟩ },
{ simp [not_forall] at h,
rcases h with ⟨x, h, h₂⟩,
have : ¬M ⊔ submodule.span {x} ≤ M,
{ intro hn, apply h₂,
have := le_trans le_sup_right hn,
exact submodule.span_le.1 this (mem_singleton x) },
rcases IH (M ⊔ submodule.span {x})
⟨@le_sup_left _ _ M _, this⟩
(sup_le MN (submodule.span_le.2 (by simpa))) with ⟨s, hs, hs₂⟩,
refine ⟨insert x s, finite_insert _ hs, _⟩,
rw [← hs₂, sup_assoc, ← submodule.span_union], simp }
end⟩
def is_noetherian_ring (α) [ring α] : Prop := is_noetherian α α
theorem ring.is_noetherian_of_fintype (R M) [ring R] [add_comm_group M] [module R M] [fintype M] : is_noetherian R M :=
by letI := classical.dec; exact
assume s, ⟨to_finset s, by rw [finset.coe_to_finset', submodule.span_eq]⟩
theorem ring.is_noetherian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_noetherian_ring R :=
by haveI := subsingleton_of_zero_eq_one R h01;
haveI := fintype.of_subsingleton (0:R);
exact ring.is_noetherian_of_fintype R R
theorem is_noetherian_of_submodule_of_noetherian (R M) [ring R] [add_comm_group M] [module R M] (N : submodule R M)
(h : is_noetherian R M) : is_noetherian R N :=
begin
rw is_noetherian_iff_well_founded at h ⊢,
convert order_embedding.well_founded (order_embedding.rsymm (submodule.map_subtype.lt_order_embedding N)) h
end
theorem is_noetherian_of_quotient_of_noetherian (R) [ring R] (M) [add_comm_group M] [module R M] (N : submodule R M)
(h : is_noetherian R M) : is_noetherian R N.quotient :=
begin
rw is_noetherian_iff_well_founded at h ⊢,
convert order_embedding.well_founded (order_embedding.rsymm (submodule.comap_mkq.lt_order_embedding N)) h
end
theorem is_noetherian_of_fg_of_noetherian {R M} [ring R] [add_comm_group M] [module R M] (N : submodule R M)
(h : is_noetherian_ring R) (hN : N.fg) : is_noetherian R N :=
let ⟨s, hs⟩ := hN in
begin
haveI := classical.dec_eq M,
have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx,
refine @@is_noetherian_of_surjective ((↑s : set M) → R) _ _ _ (pi.module _)
_ _ _ (is_noetherian_pi $ λ _, h),
{ fapply linear_map.mk,
{ exact λ f, ⟨s.attach.sum (λ i, f i • i.1), N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ },
{ intros f g, apply subtype.eq,
change s.attach.sum (λ i, (f i + g i) • _) = _,
simp only [add_smul, finset.sum_add_distrib], refl },
{ intros c f, apply subtype.eq,
change s.attach.sum (λ i, (c • f i) • _) = _,
simp only [smul_eq_mul, mul_smul],
exact finset.sum_hom _ } },
rw linear_map.range_eq_top,
rintro ⟨n, hn⟩, change n ∈ N at hn,
rw [← hs, mem_span_iff_lc] at hn,
rcases hn with ⟨l, hl1, hl2⟩,
refine ⟨λ x, l x.1, subtype.eq _⟩,
change s.attach.sum (λ i, l i.1 • i.1) = n,
rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2,
lc.total_apply, finsupp.sum, eq_comm],
refine finset.sum_subset hl1 (λ x _ hx, _),
rw [finsupp.not_mem_support_iff.1 hx, zero_smul]
end
theorem is_noetherian_ring_of_surjective (R) [comm_ring R] (S) [comm_ring S]
(f : R → S) (hf : is_ring_hom f) (hf : function.surjective f)
(H : is_noetherian_ring R) : is_noetherian_ring S :=
begin
unfold is_noetherian_ring at H ⊢,
rw is_noetherian_iff_well_founded at H ⊢,
convert order_embedding.well_founded (order_embedding.rsymm (ideal.lt_order_embedding_of_surjective f hf)) H
end
theorem is_noetherian_ring_of_ring_equiv (R) [comm_ring R] {S} [comm_ring S]
(f : R ≃r S) (H : is_noetherian_ring R) : is_noetherian_ring S :=
is_noetherian_ring_of_surjective R S f.1 f.2 f.1.bijective.2 H
|
f3b22fc824586abec384dea1ba606a9e36401578 | dd4e652c749fea9ac77e404005cb3470e5f75469 | /src/eigenvectors/smul_id.lean | bd57bd9825eac5d7bd382c76adf7b45bdd9d2913 | [] | no_license | skbaek/cvx | e32822ad5943541539966a37dee162b0a5495f55 | c50c790c9116f9fac8dfe742903a62bdd7292c15 | refs/heads/master | 1,623,803,010,339 | 1,618,058,958,000 | 1,618,058,958,000 | 176,293,135 | 3 | 2 | null | null | null | null | UTF-8 | Lean | false | false | 1,348 | lean | import linear_algebra.basic
import ring_theory.algebra
import deprecated.ring
universes v w
section smul_id
variables {α : Type v} {β : Type w}
variables [comm_ring α] [add_comm_group β] [module α β] (a : α)
def smul_id : β →ₗ[α] β := a • linear_map.id
lemma smul_id_apply (x : β) : ((smul_id a : β →ₗ[α] β) : β → β) x = a • x := rfl
instance smul_id.is_semiring_hom :
is_semiring_hom (smul_id : α → β →ₗ[α] β) := {
map_zero := begin unfold smul_id, ext, simp end,
map_one := begin unfold smul_id, ext, simp end,
map_add := begin unfold smul_id, simp [add_smul] end,
map_mul := begin unfold smul_id, intros, ext, simp [mul_smul] end
}
instance smul_id.is_ring_hom :
is_ring_hom (smul_id : α → β →ₗ[α] β) := {
map_one := smul_id.is_semiring_hom.map_one,
map_add := smul_id.is_semiring_hom.map_add,
map_mul := smul_id.is_semiring_hom.map_mul
}
def smul_id_ring_hom : α →+* (β →ₗ[α] β) := ring_hom.of (smul_id : α → β →ₗ[α] β)
-- TODO: merge with this?
#check module.endomorphism_algebra
#check algebra_map
instance : algebra α (β →ₗ[α] β) :=
(smul_id_ring_hom : α →+* (β →ₗ[α] β)).to_algebra'
begin
intros a f,
simp only [smul_id_ring_hom, ring_hom.coe_of],
dunfold smul_id,
ext,
simp,
end
end smul_id |
1927a14e782f7552c45c040e3fb064cb87a95aca | 22e97a5d648fc451e25a06c668dc03ac7ed7bc25 | /src/data/real/nnreal.lean | eee1c44f557f44c5db7e461934a8ff939314945d | [
"Apache-2.0"
] | permissive | keeferrowan/mathlib | f2818da875dbc7780830d09bd4c526b0764a4e50 | aad2dfc40e8e6a7e258287a7c1580318e865817e | refs/heads/master | 1,661,736,426,952 | 1,590,438,032,000 | 1,590,438,032,000 | 266,892,663 | 0 | 0 | Apache-2.0 | 1,590,445,835,000 | 1,590,445,835,000 | null | UTF-8 | Lean | false | false | 25,127 | lean | /-
Copyright (c) 2018 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
Nonnegative real numbers.
-/
import data.real.basic
noncomputable theory
open_locale classical
/-- Nonnegative real numbers. -/
def nnreal := {r : ℝ // 0 ≤ r}
localized "notation ` ℝ≥0 ` := nnreal" in nnreal
namespace nnreal
instance : has_coe ℝ≥0 ℝ := ⟨subtype.val⟩
/- Simp lemma to put back `n.val` into the normal form given by the coercion. -/
@[simp] lemma val_eq_coe (n : nnreal) : n.val = n := rfl
instance : can_lift ℝ nnreal :=
{ coe := coe,
cond := λ r, r ≥ 0,
prf := λ x hx, ⟨⟨x, hx⟩, rfl⟩ }
protected lemma eq {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) → n = m := subtype.eq
protected lemma eq_iff {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) ↔ n = m :=
iff.intro nnreal.eq (congr_arg coe)
lemma ne_iff {x y : ℝ≥0} : (x : ℝ) ≠ (y : ℝ) ↔ x ≠ y :=
not_iff_not_of_iff $ nnreal.eq_iff
protected def of_real (r : ℝ) : ℝ≥0 := ⟨max r 0, le_max_right _ _⟩
lemma coe_of_real (r : ℝ) (hr : 0 ≤ r) : (nnreal.of_real r : ℝ) = r :=
max_eq_left hr
lemma le_coe_of_real (r : ℝ) : r ≤ nnreal.of_real r :=
le_max_left r 0
lemma coe_nonneg (r : nnreal) : (0 : ℝ) ≤ r := r.2
@[norm_cast]
theorem coe_mk (a : ℝ) (ha) : ((⟨a, ha⟩ : ℝ≥0) : ℝ) = a := rfl
instance : has_zero ℝ≥0 := ⟨⟨0, le_refl 0⟩⟩
instance : has_one ℝ≥0 := ⟨⟨1, zero_le_one⟩⟩
instance : has_add ℝ≥0 := ⟨λa b, ⟨a + b, add_nonneg a.2 b.2⟩⟩
instance : has_sub ℝ≥0 := ⟨λa b, nnreal.of_real (a - b)⟩
instance : has_mul ℝ≥0 := ⟨λa b, ⟨a * b, mul_nonneg a.2 b.2⟩⟩
instance : has_inv ℝ≥0 := ⟨λa, ⟨(a.1)⁻¹, inv_nonneg.2 a.2⟩⟩
instance : has_div ℝ≥0 := ⟨λa b, ⟨a.1 / b.1, div_nonneg' a.2 b.2⟩⟩
instance : has_le ℝ≥0 := ⟨λ r s, (r:ℝ) ≤ s⟩
instance : has_bot ℝ≥0 := ⟨0⟩
instance : inhabited ℝ≥0 := ⟨0⟩
@[simp, norm_cast] protected lemma coe_eq {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) = r₂ ↔ r₁ = r₂ :=
subtype.ext.symm
@[simp, norm_cast] protected lemma coe_zero : ((0 : ℝ≥0) : ℝ) = 0 := rfl
@[simp, norm_cast] protected lemma coe_one : ((1 : ℝ≥0) : ℝ) = 1 := rfl
@[simp, norm_cast] protected lemma coe_add (r₁ r₂ : ℝ≥0) : ((r₁ + r₂ : ℝ≥0) : ℝ) = r₁ + r₂ := rfl
@[simp, norm_cast] protected lemma coe_mul (r₁ r₂ : ℝ≥0) : ((r₁ * r₂ : ℝ≥0) : ℝ) = r₁ * r₂ := rfl
@[simp, norm_cast] protected lemma coe_div (r₁ r₂ : ℝ≥0) : ((r₁ / r₂ : ℝ≥0) : ℝ) = r₁ / r₂ := rfl
@[simp, norm_cast] protected lemma coe_inv (r : ℝ≥0) : ((r⁻¹ : ℝ≥0) : ℝ) = r⁻¹ := rfl
@[simp, norm_cast] protected lemma coe_bit0 (r : ℝ≥0) : ((bit0 r : ℝ≥0) : ℝ) = bit0 r := rfl
@[simp, norm_cast] protected lemma coe_bit1 (r : ℝ≥0) : ((bit1 r : ℝ≥0) : ℝ) = bit1 r := rfl
@[simp, norm_cast] protected lemma coe_sub {r₁ r₂ : ℝ≥0} (h : r₂ ≤ r₁) :
((r₁ - r₂ : ℝ≥0) : ℝ) = r₁ - r₂ :=
max_eq_left $ le_sub.2 $ by simp [show (r₂ : ℝ) ≤ r₁, from h]
-- TODO: setup semifield!
@[simp] protected lemma zero_div (r : ℝ≥0) : 0 / r = 0 := nnreal.eq (zero_div _)
@[simp] protected lemma coe_eq_zero (r : ℝ≥0) : ↑r = (0 : ℝ) ↔ r = 0 := by norm_cast
lemma coe_ne_zero {r : ℝ≥0} : (r : ℝ) ≠ 0 ↔ r ≠ 0 := by norm_cast
instance : comm_semiring ℝ≥0 :=
begin
refine { zero := 0, add := (+), one := 1, mul := (*), ..};
{ intros;
apply nnreal.eq;
simp [mul_comm, mul_assoc, add_comm_monoid.add, left_distrib, right_distrib,
add_comm_monoid.zero, add_comm, add_left_comm] }
end
/-- Coercion `ℝ≥0 → ℝ` as a `ring_hom`. -/
def to_real_hom : ℝ≥0 →+* ℝ :=
⟨coe, nnreal.coe_one, nnreal.coe_mul, nnreal.coe_zero, nnreal.coe_add⟩
@[simp] lemma coe_to_real_hom : ⇑to_real_hom = coe := rfl
instance : comm_group_with_zero ℝ≥0 :=
{ zero_ne_one := assume h, zero_ne_one $ nnreal.eq_iff.2 h,
inv_zero := nnreal.eq $ inv_zero,
mul_inv_cancel := assume x h, nnreal.eq $ mul_inv_cancel $ ne_iff.2 h,
.. (by apply_instance : has_inv ℝ≥0),
.. (_ : comm_semiring ℝ≥0),
.. (_ : semiring ℝ≥0) }
@[norm_cast] lemma coe_pow (r : ℝ≥0) (n : ℕ) : ((r^n : ℝ≥0) : ℝ) = r^n :=
to_real_hom.map_pow r n
@[norm_cast] lemma coe_list_sum (l : list ℝ≥0) :
((l.sum : ℝ≥0) : ℝ) = (l.map coe).sum :=
to_real_hom.map_list_sum l
@[norm_cast] lemma coe_list_prod (l : list ℝ≥0) :
((l.prod : ℝ≥0) : ℝ) = (l.map coe).prod :=
to_real_hom.map_list_prod l
@[norm_cast] lemma coe_multiset_sum (s : multiset ℝ≥0) :
((s.sum : ℝ≥0) : ℝ) = (s.map coe).sum :=
to_real_hom.map_multiset_sum s
@[norm_cast] lemma coe_multiset_prod (s : multiset ℝ≥0) :
((s.prod : ℝ≥0) : ℝ) = (s.map coe).prod :=
to_real_hom.map_multiset_prod s
@[norm_cast] lemma coe_sum {α} {s : finset α} {f : α → ℝ≥0} :
↑(s.sum f) = s.sum (λa, (f a : ℝ)) :=
to_real_hom.map_sum _ _
@[norm_cast] lemma coe_prod {α} {s : finset α} {f : α → ℝ≥0} :
↑(s.prod f) = s.prod (λa, (f a : ℝ)) :=
to_real_hom.map_prod _ _
@[norm_cast] lemma smul_coe (r : ℝ≥0) (n : ℕ) : ↑(add_monoid.smul n r) = add_monoid.smul n (r:ℝ) :=
to_real_hom.to_add_monoid_hom.map_smul _ _
@[simp, norm_cast] protected lemma coe_nat_cast (n : ℕ) : (↑(↑n : ℝ≥0) : ℝ) = n :=
to_real_hom.map_nat_cast n
instance : decidable_linear_order ℝ≥0 :=
decidable_linear_order.lift (coe : ℝ≥0 → ℝ) subtype.val_injective (by apply_instance)
@[norm_cast] protected lemma coe_le_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) ≤ r₂ ↔ r₁ ≤ r₂ := iff.rfl
@[norm_cast] protected lemma coe_lt_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) < r₂ ↔ r₁ < r₂ := iff.rfl
protected lemma coe_pos {r : ℝ≥0} : (0 : ℝ) < r ↔ 0 < r := iff.rfl
protected lemma coe_mono : monotone (coe : ℝ≥0 → ℝ) := λ _ _, nnreal.coe_le_coe.2
protected lemma of_real_mono : monotone nnreal.of_real :=
λ x y h, max_le_max h (le_refl 0)
@[simp] lemma of_real_coe {r : ℝ≥0} : nnreal.of_real r = r :=
nnreal.eq $ max_eq_left r.2
/-- `nnreal.of_real` and `coe : ℝ≥0 → ℝ` form a Galois insertion. -/
protected def gi : galois_insertion nnreal.of_real coe :=
galois_insertion.monotone_intro nnreal.coe_mono nnreal.of_real_mono
le_coe_of_real (λ _, of_real_coe)
instance : order_bot ℝ≥0 :=
{ bot := ⊥, bot_le := assume ⟨a, h⟩, h, .. nnreal.decidable_linear_order }
instance : canonically_ordered_add_monoid ℝ≥0 :=
{ add_le_add_left := assume a b h c, @add_le_add_left ℝ _ a b h c,
lt_of_add_lt_add_left := assume a b c, @lt_of_add_lt_add_left ℝ _ a b c,
le_iff_exists_add := assume ⟨a, ha⟩ ⟨b, hb⟩,
iff.intro
(assume h : a ≤ b,
⟨⟨b - a, le_sub_iff_add_le.2 $ by simp [h]⟩,
nnreal.eq $ show b = a + (b - a), by rw [add_sub_cancel'_right]⟩)
(assume ⟨⟨c, hc⟩, eq⟩, eq.symm ▸ show a ≤ a + c, from (le_add_iff_nonneg_right a).2 hc),
..nnreal.comm_semiring,
..nnreal.order_bot,
..nnreal.decidable_linear_order }
instance : distrib_lattice ℝ≥0 := by apply_instance
instance : semilattice_inf_bot ℝ≥0 :=
{ .. nnreal.order_bot, .. nnreal.distrib_lattice }
instance : semilattice_sup_bot ℝ≥0 :=
{ .. nnreal.order_bot, .. nnreal.distrib_lattice }
instance : linear_ordered_semiring ℝ≥0 :=
{ add_left_cancel := assume a b c h, nnreal.eq $ @add_left_cancel ℝ _ a b c (nnreal.eq_iff.2 h),
add_right_cancel := assume a b c h, nnreal.eq $ @add_right_cancel ℝ _ a b c (nnreal.eq_iff.2 h),
le_of_add_le_add_left := assume a b c, @le_of_add_le_add_left ℝ _ a b c,
mul_lt_mul_of_pos_left := assume a b c, @mul_lt_mul_of_pos_left ℝ _ a b c,
mul_lt_mul_of_pos_right := assume a b c, @mul_lt_mul_of_pos_right ℝ _ a b c,
zero_lt_one := @zero_lt_one ℝ _,
.. nnreal.decidable_linear_order,
.. nnreal.canonically_ordered_add_monoid,
.. nnreal.comm_semiring }
instance : canonically_ordered_comm_semiring ℝ≥0 :=
{ zero_ne_one := assume h, @zero_ne_one ℝ _ $ congr_arg subtype.val $ h,
mul_eq_zero_iff := assume a b, nnreal.eq_iff.symm.trans $ mul_eq_zero.trans $ by simp,
.. nnreal.linear_ordered_semiring,
.. nnreal.canonically_ordered_add_monoid,
.. nnreal.comm_semiring }
instance : densely_ordered ℝ≥0 :=
⟨assume a b (h : (a : ℝ) < b), let ⟨c, hac, hcb⟩ := dense h in
⟨⟨c, le_trans a.property $ le_of_lt $ hac⟩, hac, hcb⟩⟩
instance : no_top_order ℝ≥0 :=
⟨assume a, let ⟨b, hb⟩ := no_top (a:ℝ) in ⟨⟨b, le_trans a.property $ le_of_lt $ hb⟩, hb⟩⟩
lemma bdd_above_coe {s : set ℝ≥0} : bdd_above ((coe : nnreal → ℝ) '' s) ↔ bdd_above s :=
iff.intro
(assume ⟨b, hb⟩, ⟨nnreal.of_real b, assume ⟨y, hy⟩ hys, show y ≤ max b 0, from
le_max_left_of_le $ hb $ set.mem_image_of_mem _ hys⟩)
(assume ⟨b, hb⟩, ⟨b, assume y ⟨x, hx, eq⟩, eq ▸ hb hx⟩)
lemma bdd_below_coe (s : set ℝ≥0) : bdd_below ((coe : nnreal → ℝ) '' s) :=
⟨0, assume r ⟨q, _, eq⟩, eq ▸ q.2⟩
instance : has_Sup ℝ≥0 :=
⟨λs, ⟨Sup ((coe : nnreal → ℝ) '' s),
begin
cases s.eq_empty_or_nonempty with h h,
{ simp [h, set.image_empty, real.Sup_empty] },
rcases h with ⟨⟨b, hb⟩, hbs⟩,
by_cases h' : bdd_above s,
{ exact le_cSup_of_le (bdd_above_coe.2 h') (set.mem_image_of_mem _ hbs) hb },
{ rw [real.Sup_of_not_bdd_above], rwa [bdd_above_coe] }
end⟩⟩
instance : has_Inf ℝ≥0 :=
⟨λs, ⟨Inf ((coe : nnreal → ℝ) '' s),
begin
cases s.eq_empty_or_nonempty with h h,
{ simp [h, set.image_empty, real.Inf_empty] },
exact le_cInf (h.image _) (assume r ⟨q, _, eq⟩, eq ▸ q.2)
end⟩⟩
lemma coe_Sup (s : set nnreal) : (↑(Sup s) : ℝ) = Sup ((coe : nnreal → ℝ) '' s) := rfl
lemma coe_Inf (s : set nnreal) : (↑(Inf s) : ℝ) = Inf ((coe : nnreal → ℝ) '' s) := rfl
instance : conditionally_complete_linear_order_bot ℝ≥0 :=
{ Sup := Sup,
Inf := Inf,
le_cSup := assume s a hs ha, le_cSup (bdd_above_coe.2 hs) (set.mem_image_of_mem _ ha),
cSup_le := assume s a hs h,show Sup ((coe : nnreal → ℝ) '' s) ≤ a, from
cSup_le (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq ▸ h hb,
cInf_le := assume s a _ has, cInf_le (bdd_below_coe s) (set.mem_image_of_mem _ has),
le_cInf := assume s a hs h, show (↑a : ℝ) ≤ Inf ((coe : nnreal → ℝ) '' s), from
le_cInf (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq ▸ h hb,
cSup_empty := nnreal.eq $ by simp [coe_Sup, real.Sup_empty]; refl,
decidable_le := begin assume x y, apply classical.dec end,
.. nnreal.linear_ordered_semiring, .. lattice_of_decidable_linear_order,
.. nnreal.order_bot }
instance : archimedean nnreal :=
⟨ assume x y pos_y,
let ⟨n, hr⟩ := archimedean.arch (x:ℝ) (pos_y : (0 : ℝ) < y) in
⟨n, show (x:ℝ) ≤ (add_monoid.smul n y : nnreal), by simp [*, smul_coe]⟩ ⟩
lemma le_of_forall_epsilon_le {a b : nnreal} (h : ∀ε, ε > 0 → a ≤ b + ε) : a ≤ b :=
le_of_forall_le_of_dense $ assume x hxb,
begin
rcases le_iff_exists_add.1 (le_of_lt hxb) with ⟨ε, rfl⟩,
exact h _ ((lt_add_iff_pos_right b).1 hxb)
end
lemma lt_iff_exists_rat_btwn (a b : nnreal) :
a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < nnreal.of_real q ∧ nnreal.of_real q < b) :=
iff.intro
(assume (h : (↑a:ℝ) < (↑b:ℝ)),
let ⟨q, haq, hqb⟩ := exists_rat_btwn h in
have 0 ≤ (q : ℝ), from le_trans a.2 $ le_of_lt haq,
⟨q, rat.cast_nonneg.1 this, by simp [coe_of_real _ this, nnreal.coe_lt_coe.symm, haq, hqb]⟩)
(assume ⟨q, _, haq, hqb⟩, lt_trans haq hqb)
lemma bot_eq_zero : (⊥ : nnreal) = 0 := rfl
lemma mul_sup (a b c : ℝ≥0) : a * (b ⊔ c) = (a * b) ⊔ (a * c) :=
begin
cases le_total b c with h h,
{ simp [sup_eq_max, max_eq_right h, max_eq_right (mul_le_mul_of_nonneg_left h (zero_le a))] },
{ simp [sup_eq_max, max_eq_left h, max_eq_left (mul_le_mul_of_nonneg_left h (zero_le a))] },
end
lemma mul_finset_sup {α} {f : α → ℝ≥0} {s : finset α} (r : ℝ≥0) :
r * s.sup f = s.sup (λa, r * f a) :=
begin
refine s.induction_on _ _,
{ simp [bot_eq_zero] },
{ assume a s has ih, simp [has, ih, mul_sup], }
end
@[simp, norm_cast] lemma coe_max (x y : nnreal) :
((max x y : nnreal) : ℝ) = max (x : ℝ) (y : ℝ) :=
by { delta max, split_ifs; refl }
@[simp, norm_cast] lemma coe_min (x y : nnreal) :
((min x y : nnreal) : ℝ) = min (x : ℝ) (y : ℝ) :=
by { delta min, split_ifs; refl }
section of_real
@[simp] lemma zero_le_coe {q : nnreal} : 0 ≤ (q : ℝ) := q.2
@[simp] lemma of_real_zero : nnreal.of_real 0 = 0 :=
by simp [nnreal.of_real]; refl
@[simp] lemma of_real_one : nnreal.of_real 1 = 1 :=
by simp [nnreal.of_real, max_eq_left (zero_le_one : (0 :ℝ) ≤ 1)]; refl
@[simp] lemma of_real_pos {r : ℝ} : 0 < nnreal.of_real r ↔ 0 < r :=
by simp [nnreal.of_real, nnreal.coe_lt_coe.symm, lt_irrefl]
@[simp] lemma of_real_eq_zero {r : ℝ} : nnreal.of_real r = 0 ↔ r ≤ 0 :=
by simpa [-of_real_pos] using (not_iff_not.2 (@of_real_pos r))
lemma of_real_of_nonpos {r : ℝ} : r ≤ 0 → nnreal.of_real r = 0 :=
of_real_eq_zero.2
@[simp] lemma of_real_le_of_real_iff {r p : ℝ} (hp : 0 ≤ p) :
nnreal.of_real r ≤ nnreal.of_real p ↔ r ≤ p :=
by simp [nnreal.coe_le_coe.symm, nnreal.of_real, hp]
@[simp] lemma of_real_lt_of_real_iff' {r p : ℝ} :
nnreal.of_real r < nnreal.of_real p ↔ r < p ∧ 0 < p :=
by simp [nnreal.coe_lt_coe.symm, nnreal.of_real, lt_irrefl]
lemma of_real_lt_of_real_iff {r p : ℝ} (h : 0 < p) :
nnreal.of_real r < nnreal.of_real p ↔ r < p :=
of_real_lt_of_real_iff'.trans (and_iff_left h)
lemma of_real_lt_of_real_iff_of_nonneg {r p : ℝ} (hr : 0 ≤ r) :
nnreal.of_real r < nnreal.of_real p ↔ r < p :=
of_real_lt_of_real_iff'.trans ⟨and.left, λ h, ⟨h, lt_of_le_of_lt hr h⟩⟩
@[simp] lemma of_real_add {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) :
nnreal.of_real (r + p) = nnreal.of_real r + nnreal.of_real p :=
nnreal.eq $ by simp [nnreal.of_real, hr, hp, add_nonneg]
lemma of_real_add_of_real {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) :
nnreal.of_real r + nnreal.of_real p = nnreal.of_real (r + p) :=
(of_real_add hr hp).symm
lemma of_real_le_of_real {r p : ℝ} (h : r ≤ p) : nnreal.of_real r ≤ nnreal.of_real p :=
nnreal.of_real_mono h
lemma of_real_add_le {r p : ℝ} : nnreal.of_real (r + p) ≤ nnreal.of_real r + nnreal.of_real p :=
nnreal.coe_le_coe.1 $ max_le (add_le_add (le_max_left _ _) (le_max_left _ _)) nnreal.zero_le_coe
lemma of_real_le_iff_le_coe {r : ℝ} {p : nnreal} : nnreal.of_real r ≤ p ↔ r ≤ ↑p :=
nnreal.gi.gc r p
lemma le_of_real_iff_coe_le {r : nnreal} {p : ℝ} (hp : p ≥ 0) : r ≤ nnreal.of_real p ↔ ↑r ≤ p :=
by rw [← nnreal.coe_le_coe, nnreal.coe_of_real p hp]
lemma of_real_lt_iff_lt_coe {r : ℝ} {p : nnreal} (ha : r ≥ 0) : nnreal.of_real r < p ↔ r < ↑p :=
by rw [← nnreal.coe_lt_coe, nnreal.coe_of_real r ha]
lemma lt_of_real_iff_coe_lt {r : nnreal} {p : ℝ} : r < nnreal.of_real p ↔ ↑r < p :=
begin
cases le_total 0 p,
{ rw [← nnreal.coe_lt_coe, nnreal.coe_of_real p h] },
{ rw [of_real_eq_zero.2 h], split,
intro, have := not_lt_of_le (zero_le r), contradiction,
intro rp, have : ¬(p ≤ 0) := not_le_of_lt (lt_of_le_of_lt (coe_nonneg _) rp), contradiction }
end
end of_real
section mul
lemma mul_eq_mul_left {a b c : nnreal} (h : a ≠ 0) : (a * b = a * c ↔ b = c) :=
begin
rw [← nnreal.eq_iff, ← nnreal.eq_iff, nnreal.coe_mul, nnreal.coe_mul], split,
{ exact eq_of_mul_eq_mul_left (mt (@nnreal.eq_iff a 0).1 h) },
{ assume h, rw [h] }
end
lemma of_real_mul {p q : ℝ} (hp : 0 ≤ p) :
nnreal.of_real (p * q) = nnreal.of_real p * nnreal.of_real q :=
begin
cases le_total 0 q with hq hq,
{ apply nnreal.eq,
have := max_eq_left (mul_nonneg hp hq),
simpa [nnreal.of_real, hp, hq, max_eq_left] },
{ have hpq := mul_nonpos_of_nonneg_of_nonpos hp hq,
rw [of_real_eq_zero.2 hq, of_real_eq_zero.2 hpq, mul_zero] }
end
@[field_simps] theorem mul_ne_zero' {a b : nnreal} (h₁ : a ≠ 0) (h₂ : b ≠ 0) : a * b ≠ 0 :=
mul_ne_zero'' h₁ h₂
end mul
section sub
lemma sub_def {r p : ℝ≥0} : r - p = nnreal.of_real (r - p) := rfl
lemma sub_eq_zero {r p : ℝ≥0} (h : r ≤ p) : r - p = 0 :=
nnreal.eq $ max_eq_right $ sub_le_iff_le_add.2 $ by simpa [nnreal.coe_le_coe] using h
@[simp] lemma sub_self {r : ℝ≥0} : r - r = 0 := sub_eq_zero $ le_refl r
@[simp] lemma sub_zero {r : ℝ≥0} : r - 0 = r :=
by rw [sub_def, nnreal.coe_zero, sub_zero, nnreal.of_real_coe]
lemma sub_pos {r p : ℝ≥0} : 0 < r - p ↔ p < r :=
of_real_pos.trans $ sub_pos.trans $ nnreal.coe_lt_coe
protected lemma sub_lt_self {r p : nnreal} : 0 < r → 0 < p → r - p < r :=
assume hr hp,
begin
cases le_total r p,
{ rwa [sub_eq_zero h] },
{ rw [← nnreal.coe_lt_coe, nnreal.coe_sub h], exact sub_lt_self _ hp }
end
@[simp] lemma sub_le_iff_le_add {r p q : nnreal} : r - p ≤ q ↔ r ≤ q + p :=
match le_total p r with
| or.inl h :=
by rw [← nnreal.coe_le_coe, ← nnreal.coe_le_coe, nnreal.coe_sub h, nnreal.coe_add, sub_le_iff_le_add]
| or.inr h :=
have r ≤ p + q, from le_add_right h,
by simpa [nnreal.coe_le_coe, nnreal.coe_le_coe, sub_eq_zero h, add_comm]
end
@[simp] lemma sub_le_self {r p : ℝ≥0} : r - p ≤ r :=
sub_le_iff_le_add.2 $ le_add_right $ le_refl r
lemma add_sub_cancel {r p : nnreal} : (p + r) - r = p :=
nnreal.eq $ by rw [nnreal.coe_sub, nnreal.coe_add, add_sub_cancel]; exact le_add_left (le_refl _)
lemma add_sub_cancel' {r p : nnreal} : (r + p) - r = p :=
by rw [add_comm, add_sub_cancel]
@[simp] lemma sub_add_cancel_of_le {a b : nnreal} (h : b ≤ a) : (a - b) + b = a :=
nnreal.eq $ by rw [nnreal.coe_add, nnreal.coe_sub h, sub_add_cancel]
lemma sub_sub_cancel_of_le {r p : ℝ≥0} (h : r ≤ p) : p - (p - r) = r :=
by rw [nnreal.sub_def, nnreal.sub_def, nnreal.coe_of_real _ $ sub_nonneg.2 h,
sub_sub_cancel, nnreal.of_real_coe]
lemma lt_sub_iff_add_lt {p q r : nnreal} : p < q - r ↔ p + r < q :=
begin
split,
{ assume H,
have : (((q - r) : nnreal) : ℝ) = (q : ℝ) - (r : ℝ) :=
nnreal.coe_sub (le_of_lt (sub_pos.1 (lt_of_le_of_lt (zero_le _) H))),
rwa [← nnreal.coe_lt_coe, this, lt_sub_iff_add_lt, ← nnreal.coe_add] at H },
{ assume H,
have : r ≤ q := le_trans (le_add_left (le_refl _)) (le_of_lt H),
rwa [← nnreal.coe_lt_coe, nnreal.coe_sub this, lt_sub_iff_add_lt, ← nnreal.coe_add] }
end
end sub
section inv
lemma div_def {r p : nnreal} : r / p = r * p⁻¹ := rfl
@[simp] lemma inv_zero : (0 : nnreal)⁻¹ = 0 := nnreal.eq inv_zero
@[simp] lemma inv_eq_zero {r : nnreal} : (r : nnreal)⁻¹ = 0 ↔ r = 0 :=
inv_eq_zero
@[simp] lemma inv_pos {r : nnreal} : 0 < r⁻¹ ↔ 0 < r :=
by simp [zero_lt_iff_ne_zero]
lemma div_pos {r p : ℝ≥0} (hr : 0 < r) (hp : 0 < p) : 0 < r / p :=
mul_pos hr (inv_pos.2 hp)
@[simp] lemma inv_one : (1:ℝ≥0)⁻¹ = 1 := nnreal.eq $ inv_one
@[simp] lemma div_one {r : ℝ≥0} : r / 1 = r := by rw [div_def, inv_one, mul_one]
protected lemma mul_inv {r p : ℝ≥0} : (r * p)⁻¹ = p⁻¹ * r⁻¹ := nnreal.eq $ mul_inv' _ _
protected lemma inv_pow {r : ℝ≥0} {n : ℕ} : (r^n)⁻¹ = (r⁻¹)^n :=
nnreal.eq $ by { push_cast, exact (inv_pow' _ _).symm }
@[simp] lemma inv_mul_cancel {r : ℝ≥0} (h : r ≠ 0) : r⁻¹ * r = 1 :=
nnreal.eq $ inv_mul_cancel $ mt (@nnreal.eq_iff r 0).1 h
@[simp] lemma mul_inv_cancel {r : ℝ≥0} (h : r ≠ 0) : r * r⁻¹ = 1 :=
by rw [mul_comm, inv_mul_cancel h]
@[simp] lemma div_self {r : ℝ≥0} (h : r ≠ 0) : r / r = 1 :=
mul_inv_cancel h
@[simp] lemma div_mul_cancel {r p : ℝ≥0} (h : p ≠ 0) : r / p * p = r :=
by rw [div_def, mul_assoc, inv_mul_cancel h, mul_one]
@[simp] lemma mul_div_cancel {r p : ℝ≥0} (h : p ≠ 0) : r * p / p = r :=
by rw [div_def, mul_assoc, mul_inv_cancel h, mul_one]
@[simp] lemma mul_div_cancel' {r p : ℝ≥0} (h : r ≠ 0) : r * (p / r) = p :=
by rw [mul_comm, div_mul_cancel h]
@[simp] lemma inv_inv {r : ℝ≥0} : r⁻¹⁻¹ = r := nnreal.eq (inv_inv' _)
@[simp] lemma inv_le {r p : ℝ≥0} (h : r ≠ 0) : r⁻¹ ≤ p ↔ 1 ≤ r * p :=
by rw [← mul_le_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h]
lemma inv_le_of_le_mul {r p : ℝ≥0} (h : 1 ≤ r * p) : r⁻¹ ≤ p :=
by by_cases r = 0; simp [*, inv_le]
@[simp] lemma le_inv_iff_mul_le {r p : ℝ≥0} (h : p ≠ 0) : (r ≤ p⁻¹ ↔ r * p ≤ 1) :=
by rw [← mul_le_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm]
@[simp] lemma lt_inv_iff_mul_lt {r p : ℝ≥0} (h : p ≠ 0) : (r < p⁻¹ ↔ r * p < 1) :=
by rw [← mul_lt_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm]
lemma mul_le_iff_le_inv {a b r : ℝ≥0} (hr : r ≠ 0) : r * a ≤ b ↔ a ≤ r⁻¹ * b :=
have 0 < r, from lt_of_le_of_ne (zero_le r) hr.symm,
by rw [← @mul_le_mul_left _ _ a _ r this, ← mul_assoc, mul_inv_cancel hr, one_mul]
lemma le_div_iff_mul_le {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ a * r ≤ b :=
by rw [div_def, mul_comm, ← mul_le_iff_le_inv hr, mul_comm]
lemma le_of_forall_lt_one_mul_lt {x y : ℝ≥0} (h : ∀a<1, a * x ≤ y) : x ≤ y :=
le_of_forall_ge_of_dense $ assume a ha,
have hx : x ≠ 0 := zero_lt_iff_ne_zero.1 (lt_of_le_of_lt (zero_le _) ha),
have hx' : x⁻¹ ≠ 0, by rwa [(≠), inv_eq_zero],
have a * x⁻¹ < 1, by rwa [← lt_inv_iff_mul_lt hx', inv_inv],
have (a * x⁻¹) * x ≤ y, from h _ this,
by rwa [mul_assoc, inv_mul_cancel hx, mul_one] at this
lemma div_add_div_same (a b c : ℝ≥0) : a / c + b / c = (a + b) / c :=
eq.symm $ right_distrib a b (c⁻¹)
lemma half_pos {a : ℝ≥0} (h : 0 < a) : 0 < a / 2 := div_pos h zero_lt_two
lemma add_halves (a : ℝ≥0) : a / 2 + a / 2 = a := nnreal.eq (add_halves a)
lemma half_lt_self {a : ℝ≥0} (h : a ≠ 0) : a / 2 < a :=
by rw [← nnreal.coe_lt_coe, nnreal.coe_div]; exact
half_lt_self (bot_lt_iff_ne_bot.2 h)
lemma two_inv_lt_one : (2⁻¹:ℝ≥0) < 1 :=
by simpa [div_def] using half_lt_self zero_ne_one.symm
lemma div_lt_iff {a b c : ℝ≥0} (hc : c ≠ 0) : b / c < a ↔ b < a * c :=
begin
rw [← nnreal.coe_lt_coe, ← nnreal.coe_lt_coe, nnreal.coe_div, nnreal.coe_mul],
exact div_lt_iff (zero_lt_iff_ne_zero.mpr hc)
end
lemma div_lt_one_of_lt {a b : ℝ≥0} (h : a < b) : a / b < 1 :=
begin
rwa [div_lt_iff, one_mul],
exact ne_of_gt (lt_of_le_of_lt (zero_le _) h)
end
@[field_simps] theorem div_pow {a b : ℝ≥0} (n : ℕ) : (a / b) ^ n = a ^ n / b ^ n :=
div_pow _ _ _
@[field_simps] lemma mul_div_assoc' (a b c : ℝ≥0) : a * (b / c) = (a * b) / c :=
by rw [div_def, div_def, mul_assoc]
@[field_simps] lemma div_add_div (a : ℝ≥0) {b : ℝ≥0} (c : ℝ≥0) {d : ℝ≥0}
(hb : b ≠ 0) (hd : d ≠ 0) : a / b + c / d = (a * d + b * c) / (b * d) :=
begin
rw ← nnreal.eq_iff,
simp only [nnreal.coe_add, nnreal.coe_div, nnreal.coe_mul],
exact div_add_div _ _ (coe_ne_zero.2 hb) (coe_ne_zero.2 hd)
end
@[field_simps] lemma inv_eq_one_div (a : ℝ≥0) : a⁻¹ = 1/a :=
by rw [div_def, one_mul]
@[field_simps] lemma div_mul_eq_mul_div (a b c : ℝ≥0) : (a / b) * c = (a * c) / b :=
by { rw [div_def, div_def], ac_refl }
@[field_simps] lemma add_div' (a b c : ℝ≥0) (hc : c ≠ 0) :
b + a / c = (b * c + a) / c :=
by simpa using div_add_div b a one_ne_zero hc
@[field_simps] lemma div_add' (a b c : ℝ≥0) (hc : c ≠ 0) :
a / c + b = (a + b * c) / c :=
by rwa [add_comm, add_div', add_comm]
lemma one_div_eq_inv (a : ℝ≥0) : 1 / a = a⁻¹ :=
one_mul a⁻¹
lemma one_div_div (a b : ℝ≥0) : 1 / (a / b) = b / a :=
by { rw ← nnreal.eq_iff, simp [one_div_div] }
lemma div_eq_mul_one_div (a b : ℝ≥0) : a / b = a * (1 / b) :=
by rw [div_def, div_def, one_mul]
@[field_simps] lemma div_div_eq_mul_div (a b c : ℝ≥0) : a / (b / c) = (a * c) / b :=
by { rw ← nnreal.eq_iff, simp [div_div_eq_mul_div] }
@[field_simps] lemma div_div_eq_div_mul (a b c : ℝ≥0) : (a / b) / c = a / (b * c) :=
by { rw ← nnreal.eq_iff, simp [div_div_eq_div_mul] }
@[field_simps] lemma div_eq_div_iff {a b c d : ℝ≥0} (hb : b ≠ 0) (hd : d ≠ 0) :
a / b = c / d ↔ a * d = c * b :=
div_eq_div_iff hb hd
@[field_simps] lemma div_eq_iff {a b c : ℝ≥0} (hb : b ≠ 0) : a / b = c ↔ a = c * b :=
by simpa using @div_eq_div_iff a b c 1 hb one_ne_zero
@[field_simps] lemma eq_div_iff {a b c : ℝ≥0} (hb : b ≠ 0) : c = a / b ↔ c * b = a :=
by simpa using @div_eq_div_iff c 1 a b one_ne_zero hb
end inv
section pow
theorem pow_eq_zero {a : ℝ≥0} {n : ℕ} (h : a^n = 0) : a = 0 :=
begin
rw ← nnreal.eq_iff,
rw [← nnreal.eq_iff, coe_pow] at h,
exact pow_eq_zero h
end
@[field_simps] theorem pow_ne_zero {a : ℝ≥0} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 :=
mt pow_eq_zero h
end pow
end nnreal
|
212208b1a6cc2821e0cc5535846f4ed22a414177 | 46125763b4dbf50619e8846a1371029346f4c3db | /src/tactic/explode.lean | d8ef1cac861ecc8c0c47e1b5c3a151832c1dde0a | [
"Apache-2.0"
] | permissive | thjread/mathlib | a9d97612cedc2c3101060737233df15abcdb9eb1 | 7cffe2520a5518bba19227a107078d83fa725ddc | refs/heads/master | 1,615,637,696,376 | 1,583,953,063,000 | 1,583,953,063,000 | 246,680,271 | 0 | 0 | Apache-2.0 | 1,583,960,875,000 | 1,583,960,875,000 | null | UTF-8 | Lean | false | false | 5,196 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Displays a proof term in a line by line format somewhat akin to a Fitch style
proof or the Metamath proof style.
-/
import tactic.core
open expr tactic
namespace tactic
namespace explode
-- TODO(Mario): move back to list.basic
@[simp] def head' {α} : list α → option α
| [] := none
| (a :: l) := some a
@[derive inhabited]
inductive status | reg | intro | lam | sintro
meta structure entry :=
(expr : expr)
(line : nat)
(depth : nat)
(status : status)
(thm : string)
(deps : list nat)
meta def pad_right (l : list string) : list string :=
let n := l.foldl (λ r (s:string), max r s.length) 0 in
l.map $ λ s, nat.iterate (λ s, s.push ' ') (n - s.length) s
@[derive inhabited]
meta structure entries := mk' ::
(s : expr_map entry)
(l : list entry)
meta def entries.find (es : entries) (e : expr) := es.s.find e
meta def entries.size (es : entries) := es.s.size
meta def entries.add : entries → entry → entries
| es@⟨s, l⟩ e := if s.contains e.expr then es else ⟨s.insert e.expr e, e :: l⟩
meta def entries.head (es : entries) : option entry := head' es.l
meta def format_aux : list string → list string → list string → list entry → tactic format
| (line :: lines) (dep :: deps) (thm :: thms) (en :: es) := do
fmt ← do {
let margin := string.join (list.repeat " │" en.depth),
let margin := match en.status with
| status.sintro := " ├" ++ margin
| status.intro := " │" ++ margin ++ " ┌"
| status.reg := " │" ++ margin ++ ""
| status.lam := " │" ++ margin ++ ""
end,
p ← infer_type en.expr >>= pp,
let lhs := line ++ "│" ++ dep ++ "│ " ++ thm ++ margin ++ " ",
return $ format.of_string lhs ++ to_string p ++ format.line },
(++ fmt) <$> format_aux lines deps thms es
| _ _ _ _ := return format.nil
meta instance : has_to_tactic_format entries :=
⟨λ es : entries,
let lines := pad_right $ es.l.map (λ en, to_string en.line),
deps := pad_right $ es.l.map (λ en, string.intercalate "," (en.deps.map to_string)),
thms := pad_right $ es.l.map entry.thm in
format_aux lines deps thms es.l⟩
meta def append_dep (filter : expr → tactic unit)
(es : entries) (e : expr) (deps : list nat) : tactic (list nat) :=
do { ei ← es.find e,
filter ei.expr,
return (ei.line :: deps) }
<|> return deps
meta def may_be_proof (e : expr) : tactic bool :=
do expr.sort u ← infer_type e >>= infer_type,
return $ bnot u.nonzero
end explode
open explode
meta mutual def explode.core, explode.args (filter : expr → tactic unit)
with explode.core : expr → bool → nat → entries → tactic entries
| e@(lam n bi d b) si depth es := do
m ← mk_fresh_name,
let l := local_const m n bi d,
let b' := instantiate_var b l,
if si then
let en : entry := ⟨l, es.size, depth, status.sintro, to_string n, []⟩ in do
es' ← explode.core b' si depth (es.add en),
return $ es'.add ⟨e, es'.size, depth, status.lam, "∀I", [es.size, es'.size - 1]⟩
else do
let en : entry := ⟨l, es.size, depth, status.intro, to_string n, []⟩,
es' ← explode.core b' si (depth + 1) (es.add en),
deps' ← explode.append_dep filter es' b' [],
deps' ← explode.append_dep filter es' l deps',
return $ es'.add ⟨e, es'.size, depth, status.lam, "∀I", deps'⟩
| e@(macro _ l) si depth es := explode.core l.head si depth es
| e si depth es := filter e >>
match get_app_fn_args e with
| (const n _, args) :=
explode.args e args depth es (to_string n) []
| (fn, []) := do
p ← pp fn,
let en : entry := ⟨fn, es.size, depth, status.reg, to_string p, []⟩,
return (es.add en)
| (fn, args) := do
es' ← explode.core fn ff depth es,
deps ← explode.append_dep filter es' fn [],
explode.args e args depth es' "∀E" deps
end
with explode.args : expr → list expr → nat → entries → string → list nat → tactic entries
| e (arg :: args) depth es thm deps := do
es' ← explode.core arg ff depth es <|> return es,
deps' ← explode.append_dep filter es' arg deps,
explode.args e args depth es' thm deps'
| e [] depth es thm deps :=
return (es.add ⟨e, es.size, depth, status.reg, thm, deps.reverse⟩)
meta def explode_expr (e : expr) (hide_non_prop := tt) : tactic entries :=
let filter := if hide_non_prop then λ e, may_be_proof e >>= guardb else λ _, skip in
tactic.explode.core filter e tt 0 (default _)
meta def explode (n : name) : tactic unit :=
do const n _ ← resolve_name n | fail "cannot resolve name",
d ← get_decl n,
v ← match d with
| (declaration.defn _ _ _ v _ _) := return v
| (declaration.thm _ _ _ v) := return v.get
| _ := fail "not a definition"
end,
t ← pp d.type,
explode_expr v <* trace (to_fmt n ++ " : " ++ t) >>= trace
open interactive lean lean.parser interaction_monad.result
@[user_command]
meta def explode_cmd (_ : parse $ tk "#explode") : parser unit :=
do n ← ident,
explode n
.
-- #explode iff_true_intro
-- #explode nat.strong_rec_on
end tactic
|
29e8d6254c637db0706a5eaf75655ce8ffb78c4c | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/algebra/category/Group/abelian.lean | 40470fdc1f025c09081291a48ea880f49721fc58 | [
"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 | 1,505 | lean | /-
Copyright (c) 2020 Markus Himmel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel
-/
import algebra.category.Group.Z_Module_equivalence
import algebra.category.Group.limits
import algebra.category.Group.colimits
import algebra.category.Module.abelian
import category_theory.abelian.basic
/-!
# The category of abelian groups is abelian
-/
open category_theory
open category_theory.limits
universe u
noncomputable theory
namespace AddCommGroup
section
variables {X Y : AddCommGroup.{u}} (f : X ⟶ Y)
/-- In the category of abelian groups, every monomorphism is normal. -/
def normal_mono (hf : mono f) : normal_mono f :=
equivalence_reflects_normal_mono (forget₂ (Module.{u} ℤ) AddCommGroup.{u}).inv $
Module.normal_mono _ $ right_adjoint_preserves_mono (functor.adjunction _) hf
/-- In the category of abelian groups, every epimorphism is normal. -/
def normal_epi (hf : epi f) : normal_epi f :=
equivalence_reflects_normal_epi (forget₂ (Module.{u} ℤ) AddCommGroup.{u}).inv $
Module.normal_epi _ $ left_adjoint_preserves_epi (functor.adjunction _) hf
end
/-- The category of abelian groups is abelian. -/
instance : abelian AddCommGroup.{u} :=
{ has_finite_products := ⟨by apply_instance⟩,
normal_mono := λ X Y, normal_mono,
normal_epi := λ X Y, normal_epi,
add_comp' := by { intros, simp only [preadditive.add_comp] },
comp_add' := by { intros, simp only [preadditive.comp_add] } }
end AddCommGroup
|
a50eb57357d81e670d158bce3bc52e0777b4384e | 432d948a4d3d242fdfb44b81c9e1b1baacd58617 | /src/tactic/aesop/tracing.lean | 801ccb579a2deb23a98048cd1a134fa41d5e0336 | [
"Apache-2.0"
] | permissive | JLimperg/aesop3 | 306cc6570c556568897ed2e508c8869667252e8a | a4a116f650cc7403428e72bd2e2c4cda300fe03f | refs/heads/master | 1,682,884,916,368 | 1,620,320,033,000 | 1,620,320,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,201 | lean | /-
Copyright (c) 2021 Jannis Limperg. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jannis Limperg
-/
import tactic.aesop.tree
declare_trace aesop.steps
declare_trace aesop.tree
declare_trace aesop.rule_set
variables {α β : Type} [has_to_tactic_format α] [has_to_tactic_format β]
namespace tactic
meta def trace_tagged (n : name) (tag : string) (msg : α) : tactic unit :=
when_tracing n $ trace! "[{tag}] {msg}"
meta def trace_nested (n : name) (tag : string) (header : α) (body : β) :
tactic unit :=
when_tracing n $ trace! "[{tag}] {header}{format.nested 2 <$> pp body}"
namespace aesop
meta def trace : α → tactic unit :=
trace_tagged `aesop.steps "aesop"
meta def trace_nested : α → β → tactic unit :=
tactic.trace_nested `aesop.steps "aesop"
meta def trace_separator : tactic unit :=
trace "================================================================================"
meta def trace_tree (t : tree) : tactic unit :=
tactic.trace_nested `aesop.tree "aesop" "search tree" t
meta def trace_rule_set (rs : rule_set) : tactic unit :=
tactic.trace_nested `aesop.rule_set "aesop" "rule set" rs
end aesop
end tactic
|
8d22e671310cebdf99943268d80e2633cb5dc46c | fe25de614feb5587799621c41487aaee0d083b08 | /stage0/src/Lean/Elab/Tactic/Induction.lean | 9556f4f9edc56b948df9926a442c764b268f2d86 | [
"Apache-2.0"
] | permissive | pollend/lean4 | e8469c2f5fb8779b773618c3267883cf21fb9fac | c913886938c4b3b83238a3f99673c6c5a9cec270 | refs/heads/master | 1,687,973,251,481 | 1,628,039,739,000 | 1,628,039,739,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 19,380 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
import Lean.Util.CollectFVars
import Lean.Parser.Term
import Lean.Meta.RecursorInfo
import Lean.Meta.CollectMVars
import Lean.Meta.Tactic.ElimInfo
import Lean.Meta.Tactic.Induction
import Lean.Meta.Tactic.Cases
import Lean.Meta.GeneralizeVars
import Lean.Elab.App
import Lean.Elab.Tactic.ElabTerm
import Lean.Elab.Tactic.Generalize
namespace Lean.Elab.Tactic
open Meta
/-
Given an `inductionAlt` of the form
```
nodeWithAntiquot "inductionAlt" `Lean.Parser.Tactic.inductionAlt $ ident' >> many ident' >> darrow >> termParser
```
-/
private def getAltName (alt : Syntax) : Name :=
-- alt[1] is of the form (("@"? ident) <|> "_")
if alt[1].hasArgs then alt[1][1].getId.eraseMacroScopes else `_
private def altHasExplicitModifier (alt : Syntax) : Bool :=
alt[1].hasArgs && !alt[1][0].isNone
private def getAltVarNames (alt : Syntax) : Array Name :=
alt[2].getArgs.map getNameOfIdent'
private def getAltRHS (alt : Syntax) : Syntax :=
alt[4]
private def getAltDArrow (alt : Syntax) : Syntax :=
alt[3]
-- Return true if `stx` is a term occurring in the RHS of the induction/cases tactic
def isHoleRHS (rhs : Syntax) : Bool :=
rhs.isOfKind ``Parser.Term.syntheticHole || rhs.isOfKind ``Parser.Term.hole
def evalAlt (mvarId : MVarId) (alt : Syntax) (remainingGoals : Array MVarId) : TacticM (Array MVarId) :=
let rhs := getAltRHS alt
withCaseRef (getAltDArrow alt) rhs do
if isHoleRHS rhs then
let gs' ← withMVarContext mvarId $ withRef rhs do
let mvarDecl ← getMVarDecl mvarId
let val ← elabTermEnsuringType rhs mvarDecl.type
assignExprMVar mvarId val
let gs' ← getMVarsNoDelayed val
tagUntaggedGoals mvarDecl.userName `induction gs'.toList
pure gs'
return remainingGoals ++ gs'
else
setGoals [mvarId]
closeUsingOrAdmit (withTacticInfoContext alt (evalTactic rhs))
return remainingGoals
/-
Helper method for creating an user-defined eliminator/recursor application.
-/
namespace ElimApp
structure Context where
elimInfo : ElimInfo
targets : Array Expr -- targets provided by the user
structure State where
argPos : Nat := 0 -- current argument position
targetPos : Nat := 0 -- current target at targetsStx
f : Expr
fType : Expr
alts : Array (Name × MVarId) := #[]
insts : Array MVarId := #[]
abbrev M := ReaderT Context $ StateRefT State TermElabM
private def addNewArg (arg : Expr) : M Unit :=
modify fun s => { s with argPos := s.argPos+1, f := mkApp s.f arg, fType := s.fType.bindingBody!.instantiate1 arg }
/- Return the binder name at `fType`. This method assumes `fType` is a function type. -/
private def getBindingName : M Name := return (← get).fType.bindingName!
/- Return the next argument expected type. This method assumes `fType` is a function type. -/
private def getArgExpectedType : M Expr := return (← get).fType.bindingDomain!
private def getFType : M Expr := do
let fType ← whnfForall (← get).fType
modify fun s => { s with fType := fType }
pure fType
structure Result where
elimApp : Expr
alts : Array (Name × MVarId) := #[]
others : Array MVarId := #[]
/--
Construct the an eliminator/recursor application. `targets` contains the explicit and implicit targets for
the eliminator. For example, the indices of builtin recursors are considered implicit targets.
Remark: the method `addImplicitTargets` may be used to compute the sequence of implicit and explicit targets
from the explicit ones.
-/
partial def mkElimApp (elimName : Name) (elimInfo : ElimInfo) (targets : Array Expr) (tag : Name) : TermElabM Result := do
let rec loop : M Unit := do
match (← getFType) with
| Expr.forallE binderName _ _ c =>
let ctx ← read
let argPos := (← get).argPos
if ctx.elimInfo.motivePos == argPos then
let motive ← mkFreshExprMVar (← getArgExpectedType) MetavarKind.syntheticOpaque
addNewArg motive
else if ctx.elimInfo.targetsPos.contains argPos then
let s ← get
let ctx ← read
unless s.targetPos < ctx.targets.size do
throwError "insufficient number of targets for '{elimName}'"
let target := ctx.targets[s.targetPos]
let expectedType ← getArgExpectedType
let target ← Term.ensureHasType expectedType target
modify fun s => { s with targetPos := s.targetPos + 1 }
addNewArg target
else match c.binderInfo with
| BinderInfo.implicit =>
let arg ← mkFreshExprMVar (← getArgExpectedType)
addNewArg arg
| BinderInfo.instImplicit =>
let arg ← mkFreshExprMVar (← getArgExpectedType) (kind := MetavarKind.synthetic) (userName := appendTag tag binderName)
modify fun s => { s with insts := s.insts.push arg.mvarId! }
addNewArg arg
| _ =>
let arg ← mkFreshExprSyntheticOpaqueMVar (← getArgExpectedType) (tag := appendTag tag binderName)
let x ← getBindingName
modify fun s => { s with alts := s.alts.push (x, arg.mvarId!) }
addNewArg arg
loop
| _ =>
pure ()
let f ← Term.mkConst elimName
let fType ← inferType f
let (_, s) ← loop.run { elimInfo := elimInfo, targets := targets } |>.run { f := f, fType := fType }
let mut others := #[]
for mvarId in s.insts do
try
unless (← Term.synthesizeInstMVarCore mvarId) do
setMVarKind mvarId MetavarKind.syntheticOpaque
others := others.push mvarId
catch _ =>
setMVarKind mvarId MetavarKind.syntheticOpaque
others := others.push mvarId
return { elimApp := (← instantiateMVars s.f), alts := s.alts, others := others }
/- Given a goal `... targets ... |- C[targets]` associated with `mvarId`, assign
`motiveArg := fun targets => C[targets]` -/
def setMotiveArg (mvarId : MVarId) (motiveArg : MVarId) (targets : Array FVarId) : MetaM Unit := do
let type ← inferType (mkMVar mvarId)
let motive ← mkLambdaFVars (targets.map mkFVar) type
let motiverInferredType ← inferType motive
let motiveType ← inferType (mkMVar motiveArg)
unless (← isDefEqGuarded motiverInferredType motiveType) do
throwError "type mismatch when assigning motive{indentExpr motive}\n{← mkHasTypeButIsExpectedMsg motiverInferredType motiveType}"
assignExprMVar motiveArg motive
private def getAltNumFields (elimInfo : ElimInfo) (altName : Name) : TermElabM Nat := do
for altInfo in elimInfo.altsInfo do
if altInfo.name == altName then
return altInfo.numFields
throwError "unknown alternative name '{altName}'"
private def checkAltNames (alts : Array (Name × MVarId)) (altsSyntax : Array Syntax) : TacticM Unit :=
for altStx in altsSyntax do
let altName := getAltName altStx
if altName != `_ then
unless alts.any fun (n, _) => n == altName do
throwErrorAt altStx "invalid alternative name '{altName}'"
def evalAlts (elimInfo : ElimInfo) (alts : Array (Name × MVarId)) (optPreTac : Syntax) (altsSyntax : Array Syntax)
(initialInfo : Info)
(numEqs : Nat := 0) (numGeneralized : Nat := 0) (toClear : Array FVarId := #[]) : TacticM Unit := do
checkAltNames alts altsSyntax
let hasAlts := altsSyntax.size > 0
if hasAlts then
-- default to initial state outside of alts
withInfoContext go initialInfo
else go
where
go := do
let hasAlts := altsSyntax.size > 0
let mut usedWildcard := false
let mut subgoals := #[] -- when alternatives are not provided, we accumulate subgoals here
let mut altsSyntax := altsSyntax
for (altName, altMVarId) in alts do
let numFields ← getAltNumFields elimInfo altName
let mut isWildcard := false
let altStx? ←
match altsSyntax.findIdx? (fun alt => getAltName alt == altName) with
| some idx =>
let altStx := altsSyntax[idx]
altsSyntax := altsSyntax.eraseIdx idx
pure (some altStx)
| none => match altsSyntax.findIdx? (fun alt => getAltName alt == `_) with
| some idx =>
isWildcard := true
pure (some altsSyntax[idx])
| none =>
pure none
match altStx? with
| none =>
let mut (_, altMVarId) ← introN altMVarId numFields
match (← Cases.unifyEqs numEqs altMVarId {}) with
| none => pure () -- alternative is not reachable
| some (altMVarId', _) =>
(_, altMVarId) ← introNP altMVarId' numGeneralized
for fvarId in toClear do
altMVarId ← tryClear altMVarId fvarId
let altMVarIds ← applyPreTac altMVarId
if !hasAlts then
-- User did not provide alternatives using `|`
subgoals := subgoals ++ altMVarIds.toArray
else if altMVarIds.isEmpty then
pure ()
else
logError m!"alternative '{altName}' has not been provided"
altMVarIds.forM fun mvarId => admitGoal mvarId
| some altStx =>
(subgoals, usedWildcard) ← withRef altStx do
let unusedAlt :=
if isWildcard then
pure (#[], usedWildcard)
else
throwError "alternative '{altName}' is not needed"
let altVarNames := getAltVarNames altStx
if altVarNames.size > numFields then
logError m!"too many variable names provided at alternative '{altName}', #{altVarNames.size} provided, but #{numFields} expected"
let mut (_, altMVarId) ← introN altMVarId numFields altVarNames.toList (useNamesForExplicitOnly := !altHasExplicitModifier altStx)
match (← Cases.unifyEqs numEqs altMVarId {}) with
| none => unusedAlt
| some (altMVarId', _) =>
(_, altMVarId) ← introNP altMVarId' numGeneralized
for fvarId in toClear do
altMVarId ← tryClear altMVarId fvarId
let altMVarIds ← applyPreTac altMVarId
if altMVarIds.isEmpty then
unusedAlt
else
let mut subgoals := subgoals
for altMVarId' in altMVarIds do
subgoals ← evalAlt altMVarId' altStx subgoals
pure (subgoals, usedWildcard || isWildcard)
if usedWildcard then
altsSyntax := altsSyntax.filter fun alt => getAltName alt != `_
unless altsSyntax.isEmpty do
logErrorAt altsSyntax[0] "unused alternative"
setGoals subgoals.toList
applyPreTac (mvarId : MVarId) : TacticM (List MVarId) :=
if optPreTac.isNone then
return [mvarId]
else
evalTacticAt optPreTac[0] mvarId
end ElimApp
/-
Recall that
```
generalizingVars := optional (" generalizing " >> many1 ident)
«induction» := leading_parser nonReservedSymbol "induction " >> majorPremise >> usingRec >> generalizingVars >> optional inductionAlts
```
`stx` is syntax for `induction`. -/
private def getUserGeneralizingFVarIds (stx : Syntax) : TacticM (Array FVarId) :=
withRef stx do
let generalizingStx := stx[3]
if generalizingStx.isNone then
pure #[]
else
trace[Elab.induction] "{generalizingStx}"
let vars := generalizingStx[1].getArgs
getFVarIds vars
-- process `generalizingVars` subterm of induction Syntax `stx`.
private def generalizeVars (mvarId : MVarId) (stx : Syntax) (targets : Array Expr) : TacticM (Nat × MVarId) :=
withMVarContext mvarId do
let userFVarIds ← getUserGeneralizingFVarIds stx
let forbidden ← mkGeneralizationForbiddenSet targets
let mut s ← getFVarSetToGeneralize targets forbidden
for userFVarId in userFVarIds do
if forbidden.contains userFVarId then
throwError "variable cannot be generalized because target depends on it{indentExpr (mkFVar userFVarId)}"
if s.contains userFVarId then
throwError "unnecessary 'generalizing' argument, variable '{mkFVar userFVarId}' is generalized automatically"
s := s.insert userFVarId
let fvarIds ← sortFVars s
let (fvarIds, mvarId') ← Meta.revert mvarId fvarIds
return (fvarIds.size, mvarId')
-- syntax inductionAlts := "with " (tactic)? withPosition( (colGe inductionAlt)+)
private def getAltsOfInductionAlts (inductionAlts : Syntax) : Array Syntax :=
inductionAlts[2].getArgs
private def getAltsOfOptInductionAlts (optInductionAlts : Syntax) : Array Syntax :=
if optInductionAlts.isNone then #[] else getAltsOfInductionAlts optInductionAlts[0]
private def getOptPreTacOfOptInductionAlts (optInductionAlts : Syntax) : Syntax :=
if optInductionAlts.isNone then mkNullNode else optInductionAlts[0][1]
/-
We may have at most one `| _ => ...` (wildcard alternative), and it must not set variable names.
The idea is to make sure users do not write unstructured tactics. -/
private def checkAltsOfOptInductionAlts (optInductionAlts : Syntax) : TacticM Unit :=
unless optInductionAlts.isNone do
let mut found := false
for alt in getAltsOfInductionAlts optInductionAlts[0] do
let n := getAltName alt
if n == `_ then
unless (getAltVarNames alt).isEmpty do
throwErrorAt alt "wildcard alternative must not specify variable names"
if found then
throwErrorAt alt "more than one wildcard alternative '| _ => ...' used"
found := true
def getInductiveValFromMajor (major : Expr) : TacticM InductiveVal :=
liftMetaMAtMain fun mvarId => do
let majorType ← inferType major
let majorType ← whnf majorType
matchConstInduct majorType.getAppFn
(fun _ => Meta.throwTacticEx `induction mvarId m!"major premise type is not an inductive type {indentExpr majorType}")
(fun val _ => pure val)
private def generalizeTerm (term : Expr) : TacticM Expr := do
match term with
| Expr.fvar .. => pure term
| _ =>
liftMetaTacticAux fun mvarId => do
let mvarId ← Meta.generalize mvarId term `x false
let (fvarId, mvarId) ← Meta.intro1 mvarId
pure (mkFVar fvarId, [mvarId])
-- `optElimId` is of the form `("using" ident)?`
private def getElimNameInfo (optElimId : Syntax) (targets : Array Expr) (induction : Bool): TacticM (Name × ElimInfo) := do
if optElimId.isNone then
unless targets.size == 1 do
throwError "eliminator must be provided when multiple targets are used (use 'using <eliminator-name>')"
let indVal ← getInductiveValFromMajor targets[0]
let elimName := if induction then mkRecName indVal.name else mkCasesOnName indVal.name
pure (elimName, ← getElimInfo elimName)
else
let elimId := optElimId[1]
let elimName ← withRef elimId do resolveGlobalConstNoOverloadWithInfo elimId
pure (elimName, ← withRef elimId do getElimInfo elimName)
@[builtinTactic Lean.Parser.Tactic.induction] def evalInduction : Tactic := fun stx => focus do
let targets ← stx[1].getSepArgs.mapM fun target => do
let target ← withMainContext <| elabTerm target none
generalizeTerm target
let (elimName, elimInfo) ← getElimNameInfo stx[2] targets (induction := true)
let mvarId ← getMainGoal
-- save initial info before main goal is reassigned
let initInfo ← mkTacticInfo (← getMCtx) (← getUnsolvedGoals) (← getRef)
let tag ← getMVarTag mvarId
withMVarContext mvarId do
let targets ← addImplicitTargets elimInfo targets
checkTargets targets
let targetFVarIds := targets.map (·.fvarId!)
let (n, mvarId) ← generalizeVars mvarId stx targets
withMVarContext mvarId do
let result ← withRef stx[1] do -- use target position as reference
ElimApp.mkElimApp elimName elimInfo targets tag
let elimArgs := result.elimApp.getAppArgs
let motiveType ← inferType elimArgs[elimInfo.motivePos]
ElimApp.setMotiveArg mvarId elimArgs[elimInfo.motivePos].mvarId! targetFVarIds
let optInductionAlts := stx[4]
let optPreTac := getOptPreTacOfOptInductionAlts optInductionAlts
let alts := getAltsOfOptInductionAlts optInductionAlts
assignExprMVar mvarId result.elimApp
ElimApp.evalAlts elimInfo result.alts optPreTac alts initInfo (numGeneralized := n) (toClear := targetFVarIds)
appendGoals result.others.toList
where
checkTargets (targets : Array Expr) : MetaM Unit := do
let mut foundFVars : NameSet := {}
for target in targets do
unless target.isFVar do
throwError "index in target's type is not a variable (consider using the `cases` tactic instead){indentExpr target}"
if foundFVars.contains target.fvarId! then
throwError "target (or one of its indices) occurs more than once{indentExpr target}"
-- Recall that
-- majorPremise := leading_parser optional (try (ident >> " : ")) >> termParser
private def getTargetHypothesisName? (target : Syntax) : Option Name :=
if target[0].isNone then
none
else
some target[0][0].getId
private def getTargetTerm (target : Syntax) : Syntax :=
target[1]
private def elabTaggedTerm (h? : Option Name) (termStx : Syntax) : TacticM Expr :=
withMainContext <| withRef termStx do
let term ← elabTerm termStx none
match h? with
| none => pure term
| some h =>
let lctx ← getLCtx
let x ← mkFreshUserName `x
evalGeneralizeAux h? term x
withMainContext do
let lctx ← getLCtx
match lctx.findFromUserName? x with
| some decl => pure decl.toExpr
| none => throwError "failed to generalize"
def elabTargets (targets : Array Syntax) : TacticM (Array Expr) :=
targets.mapM fun target => do
let h? := getTargetHypothesisName? target
let term ← elabTaggedTerm h? (getTargetTerm target)
generalizeTerm term
builtin_initialize registerTraceClass `Elab.cases
@[builtinTactic Lean.Parser.Tactic.cases] def evalCases : Tactic := fun stx => focus do
-- leading_parser nonReservedSymbol "cases " >> sepBy1 (group majorPremise) ", " >> usingRec >> optInductionAlts
let targets ← elabTargets stx[1].getSepArgs
let optInductionAlts := stx[3]
let optPreTac := getOptPreTacOfOptInductionAlts optInductionAlts
let alts := getAltsOfOptInductionAlts optInductionAlts
let targetRef := stx[1]
let (elimName, elimInfo) ← getElimNameInfo stx[2] targets (induction := false)
let mvarId ← getMainGoal
-- save initial info before main goal is reassigned
let initInfo ← mkTacticInfo (← getMCtx) (← getUnsolvedGoals) (← getRef)
let tag ← getMVarTag mvarId
withMVarContext mvarId do
let targets ← addImplicitTargets elimInfo targets
let result ← withRef targetRef <| ElimApp.mkElimApp elimName elimInfo targets tag
let elimArgs := result.elimApp.getAppArgs
let targets ← elimInfo.targetsPos.mapM fun i => instantiateMVars elimArgs[i]
let motiveType ← inferType elimArgs[elimInfo.motivePos]
let mvarId ← generalizeTargets mvarId motiveType targets
let (targetsNew, mvarId) ← introN mvarId targets.size
withMVarContext mvarId do
ElimApp.setMotiveArg mvarId elimArgs[elimInfo.motivePos].mvarId! targetsNew
assignExprMVar mvarId result.elimApp
ElimApp.evalAlts elimInfo result.alts optPreTac alts initInfo (numEqs := targets.size) (toClear := targetsNew)
end Lean.Elab.Tactic
|
3e53792dbdad6ebbc8a89414db09afed634e2eba | a047a4718edfa935d17231e9e6ecec8c7b701e05 | /src/analysis/normed_space/dual.lean | e19688909eedf31e7fa7e76ebf0c67b4659e5ed3 | [
"Apache-2.0"
] | permissive | utensil-contrib/mathlib | bae0c9fafe5e2bdb516efc89d6f8c1502ecc9767 | b91909e77e219098a2f8cc031f89d595fe274bd2 | refs/heads/master | 1,668,048,976,965 | 1,592,442,701,000 | 1,592,442,701,000 | 273,197,855 | 0 | 0 | null | 1,592,472,812,000 | 1,592,472,811,000 | null | UTF-8 | Lean | false | false | 2,909 | lean | /-
Copyright (c) 2020 Heather Macbeth. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Heather Macbeth
-/
import analysis.normed_space.hahn_banach
/-!
# The topological dual of a normed space
In this file we define the topological dual of a normed space, and the bounded linear map from
a normed space into its double dual.
We also prove that, for base field the real numbers, this map is an isometry. (TODO: the same for
the complex numbers.)
-/
noncomputable theory
namespace normed_space
section general
variables (𝕜 : Type*) [nondiscrete_normed_field 𝕜]
variables (E : Type*) [normed_group E] [normed_space 𝕜 E]
/-- The topological dual of a normed space `E`. -/
@[derive [has_coe_to_fun, normed_group, normed_space 𝕜]] def dual := E →L[𝕜] 𝕜
instance : inhabited (dual 𝕜 E) := ⟨0⟩
/-- The inclusion of a normed space in its double (topological) dual. -/
def inclusion_in_double_dual' (x : E) : (dual 𝕜 (dual 𝕜 E)) :=
linear_map.mk_continuous
{ to_fun := λ f, f x,
map_add' := by simp,
map_smul' := by simp }
∥x∥
(λ f, by { rw mul_comm, exact f.le_op_norm x } )
@[simp] lemma dual_def (x : E) (f : dual 𝕜 E) :
((inclusion_in_double_dual' 𝕜 E) x) f = f x := rfl
lemma double_dual_bound (x : E) : ∥(inclusion_in_double_dual' 𝕜 E) x∥ ≤ ∥x∥ :=
begin
apply continuous_linear_map.op_norm_le_bound,
{ simp },
{ intros f, rw mul_comm, exact f.le_op_norm x, }
end
/-- The inclusion of a normed space in its double (topological) dual, considered
as a bounded linear map. -/
def inclusion_in_double_dual : E →L[𝕜] (dual 𝕜 (dual 𝕜 E)) :=
linear_map.mk_continuous
{ to_fun := λ (x : E), (inclusion_in_double_dual' 𝕜 E) x,
map_add' := λ x y, by { ext, simp },
map_smul' := λ (c : 𝕜) x, by { ext, simp } }
1
(λ x, by { convert double_dual_bound _ _ _, simp } )
end general
section real
variables (E : Type*) [normed_group E] [normed_space ℝ E]
/-- The inclusion of a real normed space in its double dual is an isometry onto its image.-/
lemma inclusion_in_double_dual_isometry (x : E) : ∥inclusion_in_double_dual ℝ E x∥ = ∥x∥ :=
begin
by_cases h : vector_space.dim ℝ E = 0,
{ rw dim_zero_iff_forall_zero.mp h x, simp },
{ have h' : 0 < vector_space.dim ℝ E := zero_lt_iff_ne_zero.mpr h,
refine le_antisymm_iff.mpr ⟨double_dual_bound ℝ E x, _⟩,
rw continuous_linear_map.norm_def,
apply real.lb_le_Inf _ continuous_linear_map.bounds_nonempty,
intros c, simp only [and_imp, set.mem_set_of_eq], intros h₁ h₂,
cases exists_dual_vector' h' x with f hf,
calc ∥x∥ = f x : hf.2.symm
... ≤ ∥f x∥ : le_max_left (f x) (-f x)
... ≤ c * ∥f∥ : h₂ f
... = c : by rw [ hf.1, mul_one ] }
end
-- TODO: This is also true over ℂ.
end real
end normed_space
|
284aa8c56e49508c56bf4a554653c0f3ae7f1607 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/linear_algebra/affine_space/basic.lean | 9df96f95457ad77423a4b24f0c600920efb2e67c | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 1,610 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers
-/
import algebra.add_torsor
/-!
# Affine space
In this file we introduce the following notation:
* `affine_space V P` is an alternative notation for `add_torsor V P` introduced at the end of this
file.
We tried to use an `abbreviation` instead of a `notation` but this led to hard-to-debug elaboration
errors. So, we introduce a localized notation instead. When this notation is enabled with
`open_locale affine`, Lean will use `affine_space` instead of `add_torsor` both in input and in the
proof state.
Here is an incomplete list of notions related to affine spaces, all of them are defined in other
files:
* `affine_map`: a map between affine spaces that preserves the affine structure;
* `affine_equiv`: an equivalence between affine spaces that preserves the affine structure;
* `affine_subspace`: a subset of an affine space closed w.r.t. affine combinations of points;
* `affine_combination`: an affine combination of points;
* `affine_independent`: affine independent set of points;
* `affine_basis.coord`: the barycentric coordinate of a point.
## TODO
Some key definitions are not yet present.
* Affine frames. An affine frame might perhaps be represented as an `affine_equiv` to a `finsupp`
(in the general case) or function type (in the finite-dimensional case) that gives the
coordinates, with appropriate proofs of existence when `k` is a field.
-/
localized "notation (name := add_torsor) `affine_space` := add_torsor" in affine
|
ee13d72b2184ad4bd4ec75d05febd836365ef7ee | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/playground/split.lean | a1639253d34924a9f80100d898fd0fa5851d7314 | [
"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 | 773 | lean | def mkBig : Nat → String → String
| 0 s := s
| (k+1) s := mkBig k (s ++ "this is a big string\n")
def main : IO Unit :=
let s := mkBig 500000 "" in
let ss := s.split "\n" in
IO.println ss.length *>
IO.println (repr $ "aaa bbb ccc ddd".split) *>
IO.println (repr $ "aaa, bbb, ccc, ddd".split ", ") *>
IO.println (repr $ "aaa, bbb, ccc, ddd".split ",") *>
IO.println (repr $ "aaa,,,bbb,ccc,,ddd".split ",") *>
IO.println (repr $ "aaa#bbb#ccc#ddd".split "#") *>
IO.println (repr $ "aaa#bbb#ccc#ddd".split "") *>
IO.println (repr $ "aaa##bbb".split "##") *>
IO.println (repr $ "aaa##".split "##") *>
IO.println (repr $ "aaa#".split "#") *>
IO.println (repr $ "aaa".split "#") *>
IO.println (repr $ "aaa##bbb##".split "##") *>
IO.println (repr $ "aaa##bbb".split "##")
|
d7dee11d9e212b7ba7a718953b1124c23f3f5c93 | e38e95b38a38a99ecfa1255822e78e4b26f65bb0 | /src/certigrad/optim.lean | 2395a5501df6fad5bb126405cad1e580421f6441 | [
"Apache-2.0"
] | permissive | ColaDrill/certigrad | fefb1be3670adccd3bed2f3faf57507f156fd501 | fe288251f623ac7152e5ce555f1cd9d3a20203c2 | refs/heads/master | 1,593,297,324,250 | 1,499,903,753,000 | 1,499,903,753,000 | 97,075,797 | 1 | 0 | null | 1,499,916,210,000 | 1,499,916,210,000 | null | UTF-8 | Lean | false | false | 1,914 | lean | /-
Copyright (c) 2017 Daniel Selsam. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Daniel Selsam
Algorithms for optimization.
-/
import .tensor .tvec .dvec
namespace certigrad
namespace optim
namespace adam
structure params : Type := (α β₁ β₂ ε : ℝ)
structure state (shapes : list S) : Type := (m₀ v₀ : dvec T shapes) (t : ℕ)
def init_state {shapes : list S} : state shapes := ⟨0, 0, 0⟩
def default_params : params := ⟨1/1000, 9/10, 999/1000, T.pow 10 (- 8)⟩
def step_core_slow {shapes : list S} (θ grads : dvec T shapes) : Π (ps : params) (st : state shapes), dvec T shapes × state shapes
| (params.mk α β₁ β₂ ε : params) (state.mk m_old v_old t_old : state shapes) :=
let t := t_old + 1,
m := β₁ ⬝ m_old + (1 - β₁) ⬝ grads,
v := β₂ ⬝ v_old + (1 - β₂) ⬝ (grads * grads),
m' := m / ((1 - T.pow β₁ (T.of_nat t)) ⬝ 1),
v' := v / ((1 - T.pow β₂ (T.of_nat t)) ⬝ 1)
in
(θ - α ⬝ (m' / (tvec.sqrt v' + ε ⬝ 1)), state.mk m v t)
def step_core {shapes : list S} (θ grads : dvec T shapes) : Π (ps : params) (st : state shapes), dvec T shapes × state shapes
| (params.mk α β₁ β₂ ε : params) (state.mk m_old v_old t_old : state shapes) :=
let t := t_old + 1,
m := β₁ ⬝ m_old + (1 - β₁) ⬝ grads,
v := β₂ ⬝ v_old + (1 - β₂) ⬝ (grads * grads),
γ := α * T.sqrt (1 - T.pow β₂ (T.of_nat t)) / (1 - T.pow β₁ (T.of_nat t))
in
(θ - γ ⬝ (m / (tvec.sqrt v + ε ⬝ 1)), state.mk m v t)
-- Exercise for the reader: state and prove that `step_core` is correct, i.e. that it computes the same function as `step_core_slow`.
def step {shapes : list S} (θ grads : dvec T shapes) : Π (st : state shapes), dvec T shapes × state shapes :=
step_core θ grads default_params
end adam
end optim
end certigrad
|
00addf2a96fbc40781e3457eccf57dd2fb7f541d | 471bedbd023d35c9d078c2f936dd577ace7f5813 | /library/init/data/int/basic.lean | 09a1012c4886d5f8e85d2bdffce75466928c3d56 | [
"Apache-2.0"
] | permissive | lambdaxymox/lean | e06f0fa503666df827edd9867d7f49ca017aae64 | fc13c8c72a15dab71a2c2b31410c2cadc3526bd7 | refs/heads/master | 1,666,785,407,985 | 1,666,153,673,000 | 1,666,153,673,000 | 310,165,986 | 0 | 0 | Apache-2.0 | 1,604,542,096,000 | 1,604,542,095,000 | null | UTF-8 | Lean | false | false | 23,247 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
The integers, with addition, multiplication, and subtraction.
-/
prelude
import init.data.nat.lemmas init.data.nat.gcd
open nat
/- the type, coercions, and notation -/
@[derive decidable_eq]
inductive int : Type
| of_nat : nat → int
| neg_succ_of_nat : nat → int
notation `ℤ` := int
instance : has_coe nat int := ⟨int.of_nat⟩
notation `-[1+ ` n `]` := int.neg_succ_of_nat n
protected def int.repr : int → string
| (int.of_nat n) := repr n
| (int.neg_succ_of_nat n) := "-" ++ repr (succ n)
instance : has_repr int :=
⟨int.repr⟩
instance : has_to_string int :=
⟨int.repr⟩
namespace int
protected lemma coe_nat_eq (n : ℕ) : ↑n = int.of_nat n := rfl
protected def zero : ℤ := of_nat 0
protected def one : ℤ := of_nat 1
instance : has_zero ℤ := ⟨int.zero⟩
instance : has_one ℤ := ⟨int.one⟩
lemma of_nat_zero : of_nat (0 : nat) = (0 : int) := rfl
lemma of_nat_one : of_nat (1 : nat) = (1 : int) := rfl
/- definitions of basic functions -/
def neg_of_nat : ℕ → ℤ
| 0 := 0
| (succ m) := -[1+ m]
def sub_nat_nat (m n : ℕ) : ℤ :=
match (n - m : nat) with
| 0 := of_nat (m - n) -- m ≥ n
| (succ k) := -[1+ k] -- m < n, and n - m = succ k
end
lemma sub_nat_nat_of_sub_eq_zero {m n : ℕ} (h : n - m = 0) :
sub_nat_nat m n = of_nat (m - n) :=
begin unfold sub_nat_nat, rw h, unfold sub_nat_nat._match_1 end
lemma sub_nat_nat_of_sub_eq_succ {m n k : ℕ} (h : n - m = succ k) :
sub_nat_nat m n = -[1+ k] :=
begin unfold sub_nat_nat, rw h, unfold sub_nat_nat._match_1 end
protected def neg : ℤ → ℤ
| (of_nat n) := neg_of_nat n
| -[1+ n] := succ n
protected def add : ℤ → ℤ → ℤ
| (of_nat m) (of_nat n) := of_nat (m + n)
| (of_nat m) -[1+ n] := sub_nat_nat m (succ n)
| -[1+ m] (of_nat n) := sub_nat_nat n (succ m)
| -[1+ m] -[1+ n] := -[1+ succ (m + n)]
protected def mul : ℤ → ℤ → ℤ
| (of_nat m) (of_nat n) := of_nat (m * n)
| (of_nat m) -[1+ n] := neg_of_nat (m * succ n)
| -[1+ m] (of_nat n) := neg_of_nat (succ m * n)
| -[1+ m] -[1+ n] := of_nat (succ m * succ n)
instance : has_neg ℤ := ⟨int.neg⟩
instance : has_add ℤ := ⟨int.add⟩
instance : has_mul ℤ := ⟨int.mul⟩
-- defeq to algebra.sub which gives subtraction for arbitrary `add_group`s
protected def sub : ℤ → ℤ → ℤ :=
λ m n, m + -n
instance : has_sub ℤ := ⟨int.sub⟩
protected lemma neg_zero : -(0:ℤ) = 0 := rfl
lemma of_nat_add (n m : ℕ) : of_nat (n + m) = of_nat n + of_nat m := rfl
lemma of_nat_mul (n m : ℕ) : of_nat (n * m) = of_nat n * of_nat m := rfl
lemma of_nat_succ (n : ℕ) : of_nat (succ n) = of_nat n + 1 := rfl
lemma neg_of_nat_zero : -(of_nat 0) = 0 := rfl
lemma neg_of_nat_of_succ (n : ℕ) : -(of_nat (succ n)) = -[1+ n] := rfl
lemma neg_neg_of_nat_succ (n : ℕ) : -(-[1+ n]) = of_nat (succ n) := rfl
lemma of_nat_eq_coe (n : ℕ) : of_nat n = ↑n := rfl
lemma neg_succ_of_nat_coe (n : ℕ) : -[1+ n] = -↑(n + 1) := rfl
protected lemma coe_nat_add (m n : ℕ) : (↑(m + n) : ℤ) = ↑m + ↑n := rfl
protected lemma coe_nat_mul (m n : ℕ) : (↑(m * n) : ℤ) = ↑m * ↑n := rfl
protected lemma coe_nat_zero : ↑(0 : ℕ) = (0 : ℤ) := rfl
protected lemma coe_nat_one : ↑(1 : ℕ) = (1 : ℤ) := rfl
protected lemma coe_nat_succ (n : ℕ) : (↑(succ n) : ℤ) = ↑n + 1 := rfl
protected lemma coe_nat_add_out (m n : ℕ) : ↑m + ↑n = (m + n : ℤ) := rfl
protected lemma coe_nat_mul_out (m n : ℕ) : ↑m * ↑n = (↑(m * n) : ℤ) := rfl
protected lemma coe_nat_add_one_out (n : ℕ) : ↑n + (1 : ℤ) = ↑(succ n) := rfl
/- these are only for internal use -/
lemma of_nat_add_of_nat (m n : nat) : of_nat m + of_nat n = of_nat (m + n) := rfl
lemma of_nat_add_neg_succ_of_nat (m n : nat) :
of_nat m + -[1+ n] = sub_nat_nat m (succ n) := rfl
lemma neg_succ_of_nat_add_of_nat (m n : nat) :
-[1+ m] + of_nat n = sub_nat_nat n (succ m) := rfl
lemma neg_succ_of_nat_add_neg_succ_of_nat (m n : nat) :
-[1+ m] + -[1+ n] = -[1+ succ (m + n)] := rfl
lemma of_nat_mul_of_nat (m n : nat) : of_nat m * of_nat n = of_nat (m * n) := rfl
lemma of_nat_mul_neg_succ_of_nat (m n : nat) :
of_nat m * -[1+ n] = neg_of_nat (m * succ n) := rfl
lemma neg_succ_of_nat_of_nat (m n : nat) :
-[1+ m] * of_nat n = neg_of_nat (succ m * n) := rfl
lemma mul_neg_succ_of_nat_neg_succ_of_nat (m n : nat) :
-[1+ m] * -[1+ n] = of_nat (succ m * succ n) := rfl
local attribute [simp] of_nat_add_of_nat of_nat_mul_of_nat neg_of_nat_zero neg_of_nat_of_succ
neg_neg_of_nat_succ of_nat_add_neg_succ_of_nat neg_succ_of_nat_add_of_nat
neg_succ_of_nat_add_neg_succ_of_nat of_nat_mul_neg_succ_of_nat neg_succ_of_nat_of_nat
mul_neg_succ_of_nat_neg_succ_of_nat
/- some basic functions and properties -/
protected lemma coe_nat_inj {m n : ℕ} (h : (↑m : ℤ) = ↑n) : m = n :=
int.of_nat.inj h
lemma of_nat_eq_of_nat_iff (m n : ℕ) : of_nat m = of_nat n ↔ m = n :=
iff.intro int.of_nat.inj (congr_arg _)
protected lemma coe_nat_eq_coe_nat_iff (m n : ℕ) : (↑m : ℤ) = ↑n ↔ m = n :=
of_nat_eq_of_nat_iff m n
lemma neg_succ_of_nat_inj_iff {m n : ℕ} : neg_succ_of_nat m = neg_succ_of_nat n ↔ m = n :=
⟨neg_succ_of_nat.inj, assume H, by simp [H]⟩
lemma neg_succ_of_nat_eq (n : ℕ) : -[1+ n] = -(n + 1) := rfl
/- neg -/
protected lemma neg_neg : ∀ a : ℤ, -(-a) = a
| (of_nat 0) := rfl
| (of_nat (n+1)) := rfl
| -[1+ n] := rfl
protected lemma neg_inj {a b : ℤ} (h : -a = -b) : a = b :=
by rw [← int.neg_neg a, ← int.neg_neg b, h]
protected lemma sub_eq_add_neg {a b : ℤ} : a - b = a + -b := rfl
/- basic properties of sub_nat_nat -/
lemma sub_nat_nat_elim (m n : ℕ) (P : ℕ → ℕ → ℤ → Prop)
(hp : ∀i n, P (n + i) n (of_nat i))
(hn : ∀i m, P m (m + i + 1) (-[1+ i])) :
P m n (sub_nat_nat m n) :=
begin
have H : ∀k, n - m = k → P m n (nat.cases_on k (of_nat (m - n)) (λa, -[1+ a])),
{ intro k, cases k,
{ intro e,
cases (nat.le.dest (nat.le_of_sub_eq_zero e)) with k h,
rw [h.symm, nat.add_sub_cancel_left],
apply hp },
{ intro heq,
have h : m ≤ n,
{ exact nat.le_of_lt (nat.lt_of_sub_eq_succ heq) },
rw [nat.sub_eq_iff_eq_add h] at heq,
rw [heq, nat.add_comm],
apply hn } },
delta sub_nat_nat,
exact H _ rfl
end
lemma sub_nat_nat_add_left {m n : ℕ} :
sub_nat_nat (m + n) m = of_nat n :=
begin
dunfold sub_nat_nat,
rw [nat.sub_eq_zero_of_le],
dunfold sub_nat_nat._match_1,
rw [nat.add_sub_cancel_left],
apply nat.le_add_right
end
lemma sub_nat_nat_add_right {m n : ℕ} :
sub_nat_nat m (m + n + 1) = neg_succ_of_nat n :=
calc sub_nat_nat._match_1 m (m + n + 1) (m + n + 1 - m) =
sub_nat_nat._match_1 m (m + n + 1) (m + (n + 1) - m) : by rw [nat.add_assoc]
... = sub_nat_nat._match_1 m (m + n + 1) (n + 1) : by rw [nat.add_sub_cancel_left]
... = neg_succ_of_nat n : rfl
lemma sub_nat_nat_add_add (m n k : ℕ) : sub_nat_nat (m + k) (n + k) = sub_nat_nat m n :=
sub_nat_nat_elim m n (λm n i, sub_nat_nat (m + k) (n + k) = i)
(assume i n, have n + i + k = (n + k) + i, by simp [nat.add_comm, nat.add_left_comm],
begin rw [this], exact sub_nat_nat_add_left end)
(assume i m, have m + i + 1 + k = (m + k) + i + 1, by simp [nat.add_comm, nat.add_left_comm],
begin rw [this], exact sub_nat_nat_add_right end)
lemma sub_nat_nat_of_le {m n : ℕ} (h : n ≤ m) : sub_nat_nat m n = of_nat (m - n) :=
sub_nat_nat_of_sub_eq_zero (nat.sub_eq_zero_of_le h)
lemma sub_nat_nat_of_lt {m n : ℕ} (h : m < n) : sub_nat_nat m n = -[1+ pred (n - m)] :=
have n - m = succ (pred (n - m)), from eq.symm (succ_pred_eq_of_pos (nat.sub_pos_of_lt h)),
by rewrite sub_nat_nat_of_sub_eq_succ this
/- nat_abs -/
@[simp] def nat_abs : ℤ → ℕ
| (of_nat m) := m
| -[1+ m] := succ m
lemma nat_abs_of_nat (n : ℕ) : nat_abs ↑n = n := rfl
lemma eq_zero_of_nat_abs_eq_zero : Π {a : ℤ}, nat_abs a = 0 → a = 0
| (of_nat m) H := congr_arg of_nat H
| -[1+ m'] H := absurd H (succ_ne_zero _)
lemma nat_abs_pos_of_ne_zero {a : ℤ} (h : a ≠ 0) : 0 < nat_abs a :=
(nat.eq_zero_or_pos _).resolve_left $ mt eq_zero_of_nat_abs_eq_zero h
lemma nat_abs_zero : nat_abs (0 : int) = (0 : nat) := rfl
lemma nat_abs_one : nat_abs (1 : int) = (1 : nat) := rfl
lemma nat_abs_mul_self : Π {a : ℤ}, ↑(nat_abs a * nat_abs a) = a * a
| (of_nat m) := rfl
| -[1+ m'] := rfl
@[simp] lemma nat_abs_neg (a : ℤ) : nat_abs (-a) = nat_abs a :=
by {cases a with n n, cases n; refl, refl}
lemma nat_abs_eq : Π (a : ℤ), a = nat_abs a ∨ a = -(nat_abs a)
| (of_nat m) := or.inl rfl
| -[1+ m'] := or.inr rfl
lemma eq_coe_or_neg (a : ℤ) : ∃n : ℕ, a = n ∨ a = -n := ⟨_, nat_abs_eq a⟩
/- sign -/
def sign : ℤ → ℤ
| (n+1:ℕ) := 1
| 0 := 0
| -[1+ n] := -1
@[simp] theorem sign_zero : sign 0 = 0 := rfl
@[simp] theorem sign_one : sign 1 = 1 := rfl
@[simp] theorem sign_neg_one : sign (-1) = -1 := rfl
/- Quotient and remainder -/
-- There are three main conventions for integer division,
-- referred here as the E, F, T rounding conventions.
-- All three pairs satisfy the identity x % y + (x / y) * y = x
-- unconditionally.
-- E-rounding: This pair satisfies 0 ≤ mod x y < nat_abs y for y ≠ 0
protected def div : ℤ → ℤ → ℤ
| (m : ℕ) (n : ℕ) := of_nat (m / n)
| (m : ℕ) -[1+ n] := -of_nat (m / succ n)
| -[1+ m] 0 := 0
| -[1+ m] (n+1:ℕ) := -[1+ m / succ n]
| -[1+ m] -[1+ n] := of_nat (succ (m / succ n))
protected def mod : ℤ → ℤ → ℤ
| (m : ℕ) n := (m % nat_abs n : ℕ)
| -[1+ m] n := sub_nat_nat (nat_abs n) (succ (m % nat_abs n))
-- F-rounding: This pair satisfies fdiv x y = floor (x / y)
def fdiv : ℤ → ℤ → ℤ
| 0 _ := 0
| (m : ℕ) (n : ℕ) := of_nat (m / n)
| (m+1:ℕ) -[1+ n] := -[1+ m / succ n]
| -[1+ m] 0 := 0
| -[1+ m] (n+1:ℕ) := -[1+ m / succ n]
| -[1+ m] -[1+ n] := of_nat (succ m / succ n)
def fmod : ℤ → ℤ → ℤ
| 0 _ := 0
| (m : ℕ) (n : ℕ) := of_nat (m % n)
| (m+1:ℕ) -[1+ n] := sub_nat_nat (m % succ n) n
| -[1+ m] (n : ℕ) := sub_nat_nat n (succ (m % n))
| -[1+ m] -[1+ n] := -of_nat (succ m % succ n)
-- T-rounding: This pair satisfies quot x y = round_to_zero (x / y)
def quot : ℤ → ℤ → ℤ
| (of_nat m) (of_nat n) := of_nat (m / n)
| (of_nat m) -[1+ n] := -of_nat (m / succ n)
| -[1+ m] (of_nat n) := -of_nat (succ m / n)
| -[1+ m] -[1+ n] := of_nat (succ m / succ n)
def rem : ℤ → ℤ → ℤ
| (of_nat m) (of_nat n) := of_nat (m % n)
| (of_nat m) -[1+ n] := of_nat (m % succ n)
| -[1+ m] (of_nat n) := -of_nat (succ m % n)
| -[1+ m] -[1+ n] := -of_nat (succ m % succ n)
instance : has_div ℤ := ⟨int.div⟩
instance : has_mod ℤ := ⟨int.mod⟩
/- gcd -/
def gcd (m n : ℤ) : ℕ := gcd (nat_abs m) (nat_abs n)
/-
int is a ring
-/
/- addition -/
protected lemma add_comm : ∀ a b : ℤ, a + b = b + a
| (of_nat n) (of_nat m) := by simp [nat.add_comm]
| (of_nat n) -[1+ m] := rfl
| -[1+ n] (of_nat m) := rfl
| -[1+ n] -[1+m] := by simp [nat.add_comm]
protected lemma add_zero : ∀ a : ℤ, a + 0 = a
| (of_nat n) := rfl
| -[1+ n] := rfl
protected lemma zero_add (a : ℤ) : 0 + a = a :=
int.add_comm a 0 ▸ int.add_zero a
lemma sub_nat_nat_sub {m n : ℕ} (h : n ≤ m) (k : ℕ) :
sub_nat_nat (m - n) k = sub_nat_nat m (k + n) :=
calc
sub_nat_nat (m - n) k = sub_nat_nat (m - n + n) (k + n) : by rewrite [sub_nat_nat_add_add]
... = sub_nat_nat m (k + n) : by rewrite [nat.sub_add_cancel h]
lemma sub_nat_nat_add (m n k : ℕ) : sub_nat_nat (m + n) k = of_nat m + sub_nat_nat n k :=
begin
have h := le_or_lt k n,
cases h with h' h',
{ rw [sub_nat_nat_of_le h'],
have h₂ : k ≤ m + n, exact (le_trans h' (nat.le_add_left _ _)),
rw [sub_nat_nat_of_le h₂], simp,
rw nat.add_sub_assoc h' },
rw [sub_nat_nat_of_lt h'], simp, rw [succ_pred_eq_of_pos (nat.sub_pos_of_lt h')],
transitivity, rw [← nat.sub_add_cancel (le_of_lt h')],
apply sub_nat_nat_add_add
end
lemma sub_nat_nat_add_neg_succ_of_nat (m n k : ℕ) :
sub_nat_nat m n + -[1+ k] = sub_nat_nat m (n + succ k) :=
begin
have h := le_or_lt n m,
cases h with h' h',
{ rw [sub_nat_nat_of_le h'], simp, rw [sub_nat_nat_sub h', nat.add_comm] },
have h₂ : m < n + succ k, exact nat.lt_of_lt_of_le h' (nat.le_add_right _ _),
have h₃ : m ≤ n + k, exact le_of_succ_le_succ h₂,
rw [sub_nat_nat_of_lt h', sub_nat_nat_of_lt h₂], simp [nat.add_comm],
rw [← add_succ, succ_pred_eq_of_pos (nat.sub_pos_of_lt h'), add_succ, succ_sub h₃, pred_succ],
rw [nat.add_comm n, nat.add_sub_assoc (le_of_lt h')]
end
lemma add_assoc_aux1 (m n : ℕ) :
∀ c : ℤ, of_nat m + of_nat n + c = of_nat m + (of_nat n + c)
| (of_nat k) := by simp [nat.add_assoc]
| -[1+ k] := by simp [sub_nat_nat_add]
lemma add_assoc_aux2 (m n k : ℕ) :
-[1+ m] + -[1+ n] + of_nat k = -[1+ m] + (-[1+ n] + of_nat k) :=
begin
simp [add_succ], rw [int.add_comm, sub_nat_nat_add_neg_succ_of_nat], simp [add_succ, succ_add, nat.add_comm]
end
protected lemma add_assoc : ∀ a b c : ℤ, a + b + c = a + (b + c)
| (of_nat m) (of_nat n) c := add_assoc_aux1 _ _ _
| (of_nat m) b (of_nat k) := by rw [int.add_comm, ← add_assoc_aux1, int.add_comm (of_nat k),
add_assoc_aux1, int.add_comm b]
| a (of_nat n) (of_nat k) := by rw [int.add_comm, int.add_comm a, ← add_assoc_aux1,
int.add_comm a, int.add_comm (of_nat k)]
| -[1+ m] -[1+ n] (of_nat k) := add_assoc_aux2 _ _ _
| -[1+ m] (of_nat n) -[1+ k] := by rw [int.add_comm, ← add_assoc_aux2, int.add_comm (of_nat n),
← add_assoc_aux2, int.add_comm -[1+ m] ]
| (of_nat m) -[1+ n] -[1+ k] := by rw [int.add_comm, int.add_comm (of_nat m),
int.add_comm (of_nat m), ← add_assoc_aux2,
int.add_comm -[1+ k] ]
| -[1+ m] -[1+ n] -[1+ k] := by simp [add_succ, nat.add_comm, nat.add_left_comm, neg_of_nat_of_succ]
/- negation -/
lemma sub_nat_self : ∀ n, sub_nat_nat n n = 0
| 0 := rfl
| (succ m) := begin rw [sub_nat_nat_of_sub_eq_zero, nat.sub_self, of_nat_zero], rw nat.sub_self end
local attribute [simp] sub_nat_self
protected lemma add_left_neg : ∀ a : ℤ, -a + a = 0
| (of_nat 0) := rfl
| (of_nat (succ m)) := by simp
| -[1+ m] := by simp
protected lemma add_right_neg (a : ℤ) : a + -a = 0 :=
by rw [int.add_comm, int.add_left_neg]
/- multiplication -/
protected lemma mul_comm : ∀ a b : ℤ, a * b = b * a
| (of_nat m) (of_nat n) := by simp [nat.mul_comm]
| (of_nat m) -[1+ n] := by simp [nat.mul_comm]
| -[1+ m] (of_nat n) := by simp [nat.mul_comm]
| -[1+ m] -[1+ n] := by simp [nat.mul_comm]
lemma of_nat_mul_neg_of_nat (m : ℕ) :
∀ n, of_nat m * neg_of_nat n = neg_of_nat (m * n)
| 0 := rfl
| (succ n) := begin unfold neg_of_nat, simp end
lemma neg_of_nat_mul_of_nat (m n : ℕ) :
neg_of_nat m * of_nat n = neg_of_nat (m * n) :=
begin rw int.mul_comm, simp [of_nat_mul_neg_of_nat, nat.mul_comm] end
lemma neg_succ_of_nat_mul_neg_of_nat (m : ℕ) :
∀ n, -[1+ m] * neg_of_nat n = of_nat (succ m * n)
| 0 := rfl
| (succ n) := begin unfold neg_of_nat, simp end
lemma neg_of_nat_mul_neg_succ_of_nat (m n : ℕ) :
neg_of_nat n * -[1+ m] = of_nat (n * succ m) :=
begin rw int.mul_comm, simp [neg_succ_of_nat_mul_neg_of_nat, nat.mul_comm] end
local attribute [simp] of_nat_mul_neg_of_nat neg_of_nat_mul_of_nat
neg_succ_of_nat_mul_neg_of_nat neg_of_nat_mul_neg_succ_of_nat
protected lemma mul_assoc : ∀ a b c : ℤ, a * b * c = a * (b * c)
| (of_nat m) (of_nat n) (of_nat k) := by simp [nat.mul_assoc]
| (of_nat m) (of_nat n) -[1+ k] := by simp [nat.mul_assoc]
| (of_nat m) -[1+ n] (of_nat k) := by simp [nat.mul_assoc]
| (of_nat m) -[1+ n] -[1+ k] := by simp [nat.mul_assoc]
| -[1+ m] (of_nat n) (of_nat k) := by simp [nat.mul_assoc]
| -[1+ m] (of_nat n) -[1+ k] := by simp [nat.mul_assoc]
| -[1+ m] -[1+ n] (of_nat k) := by simp [nat.mul_assoc]
| -[1+ m] -[1+ n] -[1+ k] := by simp [nat.mul_assoc]
protected lemma mul_zero : ∀ (a : ℤ), a * 0 = 0
| (of_nat m) := rfl
| -[1+ m] := rfl
protected lemma zero_mul (a : ℤ) : 0 * a = 0 :=
int.mul_comm a 0 ▸ int.mul_zero a
lemma neg_of_nat_eq_sub_nat_nat_zero : ∀ n, neg_of_nat n = sub_nat_nat 0 n
| 0 := rfl
| (succ n) := rfl
lemma of_nat_mul_sub_nat_nat (m n k : ℕ) :
of_nat m * sub_nat_nat n k = sub_nat_nat (m * n) (m * k) :=
begin
have h₀ : m > 0 ∨ 0 = m,
exact decidable.lt_or_eq_of_le m.zero_le,
cases h₀ with h₀ h₀,
{ have h := nat.lt_or_ge n k,
cases h with h h,
{ have h' : m * n < m * k,
exact nat.mul_lt_mul_of_pos_left h h₀,
rw [sub_nat_nat_of_lt h, sub_nat_nat_of_lt h'],
simp, rw [succ_pred_eq_of_pos (nat.sub_pos_of_lt h)],
rw [← neg_of_nat_of_succ, nat.mul_sub_left_distrib],
rw [← succ_pred_eq_of_pos (nat.sub_pos_of_lt h')], reflexivity },
have h' : m * k ≤ m * n,
exact nat.mul_le_mul_left _ h,
rw [sub_nat_nat_of_le h, sub_nat_nat_of_le h'], simp,
rw [nat.mul_sub_left_distrib]
},
have h₂ : of_nat 0 = 0, exact rfl,
subst h₀, simp [h₂, int.zero_mul, nat.zero_mul]
end
lemma neg_of_nat_add (m n : ℕ) :
neg_of_nat m + neg_of_nat n = neg_of_nat (m + n) :=
begin
cases m,
{ cases n,
{ simp, reflexivity },
simp [nat.zero_add], reflexivity },
cases n,
{ simp, reflexivity },
simp [nat.succ_add], reflexivity
end
lemma neg_succ_of_nat_mul_sub_nat_nat (m n k : ℕ) :
-[1+ m] * sub_nat_nat n k = sub_nat_nat (succ m * k) (succ m * n) :=
begin
have h := nat.lt_or_ge n k,
cases h with h h,
{ have h' : succ m * n < succ m * k,
exact nat.mul_lt_mul_of_pos_left h (nat.succ_pos m),
rw [sub_nat_nat_of_lt h, sub_nat_nat_of_le (le_of_lt h')],
simp [succ_pred_eq_of_pos (nat.sub_pos_of_lt h), nat.mul_sub_left_distrib]},
have h' : n > k ∨ k = n,
exact decidable.lt_or_eq_of_le h,
cases h' with h' h',
{ have h₁ : succ m * n > succ m * k,
exact nat.mul_lt_mul_of_pos_left h' (nat.succ_pos m),
rw [sub_nat_nat_of_le h, sub_nat_nat_of_lt h₁], simp [nat.mul_sub_left_distrib, nat.mul_comm],
rw [nat.mul_comm k, nat.mul_comm n, ← succ_pred_eq_of_pos (nat.sub_pos_of_lt h₁),
← neg_of_nat_of_succ],
reflexivity },
subst h', simp, reflexivity
end
local attribute [simp] of_nat_mul_sub_nat_nat neg_of_nat_add neg_succ_of_nat_mul_sub_nat_nat
protected lemma distrib_left : ∀ a b c : ℤ, a * (b + c) = a * b + a * c
| (of_nat m) (of_nat n) (of_nat k) := by simp [nat.left_distrib]
| (of_nat m) (of_nat n) -[1+ k] := begin simp [neg_of_nat_eq_sub_nat_nat_zero],
rw ← sub_nat_nat_add, reflexivity end
| (of_nat m) -[1+ n] (of_nat k) := begin simp [neg_of_nat_eq_sub_nat_nat_zero],
rw [int.add_comm, ← sub_nat_nat_add], reflexivity end
| (of_nat m) -[1+ n] -[1+ k] := begin simp, rw [← nat.left_distrib, add_succ, succ_add] end
| -[1+ m] (of_nat n) (of_nat k) := begin simp [nat.mul_comm], rw [← nat.right_distrib, nat.mul_comm] end
| -[1+ m] (of_nat n) -[1+ k] := begin simp [neg_of_nat_eq_sub_nat_nat_zero],
rw [int.add_comm, ← sub_nat_nat_add], reflexivity end
| -[1+ m] -[1+ n] (of_nat k) := begin simp [neg_of_nat_eq_sub_nat_nat_zero],
rw [← sub_nat_nat_add], reflexivity end
| -[1+ m] -[1+ n] -[1+ k] := begin simp, rw [← nat.left_distrib, add_succ, succ_add] end
protected lemma distrib_right (a b c : ℤ) : (a + b) * c = a * c + b * c :=
begin rw [int.mul_comm, int.distrib_left], simp [int.mul_comm] end
protected lemma zero_ne_one : (0 : int) ≠ 1 :=
assume h : 0 = 1, succ_ne_zero _ (int.of_nat.inj h).symm
lemma of_nat_sub {n m : ℕ} (h : m ≤ n) : of_nat (n - m) = of_nat n - of_nat m :=
show of_nat (n - m) = of_nat n + neg_of_nat m, from match m, h with
| 0, h := rfl
| succ m, h := show of_nat (n - succ m) = sub_nat_nat n (succ m),
by delta sub_nat_nat; rw nat.sub_eq_zero_of_le h; refl
end
protected lemma add_left_comm (a b c : ℤ) : a + (b + c) = b + (a + c) :=
by rw [← int.add_assoc, int.add_comm a, int.add_assoc]
protected lemma add_left_cancel {a b c : ℤ} (h : a + b = a + c) : b = c :=
have -a + (a + b) = -a + (a + c), by rw h,
by rwa [← int.add_assoc, ← int.add_assoc, int.add_left_neg, int.zero_add, int.zero_add] at this
protected lemma neg_add {a b : ℤ} : - (a + b) = -a + -b :=
calc - (a + b) = -(a + b) + (a + b) + -a + -b :
begin
rw [int.add_assoc, int.add_comm (-a), int.add_assoc, int.add_assoc, ← int.add_assoc b],
rw [int.add_right_neg, int.zero_add, int.add_right_neg, int.add_zero],
end
... = -a + -b : by { rw [int.add_left_neg, int.zero_add] }
lemma neg_succ_of_nat_coe' (n : ℕ) : -[1+ n] = -↑n - 1 :=
by rw [int.sub_eq_add_neg, ← int.neg_add]; refl
protected lemma coe_nat_sub {n m : ℕ} : n ≤ m → (↑(m - n) : ℤ) = ↑m - ↑n := of_nat_sub
local attribute [simp] int.sub_eq_add_neg
protected lemma sub_nat_nat_eq_coe {m n : ℕ} : sub_nat_nat m n = ↑m - ↑n :=
sub_nat_nat_elim m n (λm n i, i = ↑m - ↑n)
(λi n, by { simp [int.coe_nat_add, int.add_left_comm, int.add_assoc, int.add_right_neg], refl })
(λi n, by { rw [int.coe_nat_add, int.coe_nat_add, int.coe_nat_one, int.neg_succ_of_nat_eq,
int.sub_eq_add_neg, int.neg_add, int.neg_add, int.neg_add, ← int.add_assoc,
← int.add_assoc, int.add_right_neg, int.zero_add] })
def to_nat : ℤ → ℕ
| (n : ℕ) := n
| -[1+ n] := 0
theorem to_nat_sub (m n : ℕ) : to_nat (m - n) = m - n :=
by rw [← int.sub_nat_nat_eq_coe]; exact sub_nat_nat_elim m n
(λm n i, to_nat i = m - n)
(λi n, by rw [nat.add_sub_cancel_left]; refl)
(λi n, by rw [nat.add_assoc, nat.sub_eq_zero_of_le (nat.le_add_right _ _)]; refl)
-- Since mod x y is always nonnegative when y ≠ 0, we can make a nat version of it
def nat_mod (m n : ℤ) : ℕ := (m % n).to_nat
protected lemma one_mul : ∀ (a : ℤ), (1 : ℤ) * a = a
| (of_nat n) := show of_nat (1 * n) = of_nat n, by rw nat.one_mul
| -[1+ n] := show -[1+ (1 * n)] = -[1+ n], by rw nat.one_mul
protected lemma mul_one (a : ℤ) : a * 1 = a :=
by rw [int.mul_comm, int.one_mul]
protected lemma neg_eq_neg_one_mul : ∀ a : ℤ, -a = -1 * a
| (of_nat 0) := rfl
| (of_nat (n+1)) := show _ = -[1+ (1*n)+0], by { rw nat.one_mul, refl }
| -[1+ n] := show _ = of_nat _, by { rw nat.one_mul, refl }
theorem sign_mul_nat_abs : ∀ (a : ℤ), sign a * nat_abs a = a
| (n+1:ℕ) := int.one_mul _
| 0 := rfl
| -[1+ n] := (int.neg_eq_neg_one_mul _).symm
end int
|
fd5df271875f2807ad02201c1a5cb599d3fb832a | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/category_theory/natural_transformation.lean | 2867688150fd622926dedafdfed2bf384ca45cf7 | [
"Apache-2.0"
] | permissive | rmitta/mathlib | 8d90aee30b4db2b013e01f62c33f297d7e64a43d | 883d974b608845bad30ae19e27e33c285200bf84 | refs/heads/master | 1,585,776,832,544 | 1,576,874,096,000 | 1,576,874,096,000 | 153,663,165 | 0 | 2 | Apache-2.0 | 1,544,806,490,000 | 1,539,884,365,000 | Lean | UTF-8 | Lean | false | false | 2,546 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn
Defines natural transformations between functors.
Introduces notations
`τ.app X` for the components of natural transformations,
`F ⟶ G` for the type of natural transformations between functors `F` and `G`,
`σ ≫ τ` for vertical compositions, and
`σ ◫ τ` for horizontal compositions.
-/
import category_theory.functor
namespace category_theory
universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ -- declare the `v`'s first; see `category_theory.category` for an explanation
variables {C : Type u₁} [𝒞 : category.{v₁} C] {D : Type u₂} [𝒟 : category.{v₂} D]
include 𝒞 𝒟
/--
`nat_trans F G` represents a natural transformation between functors `F` and `G`.
The field `app` provides the components of the natural transformation.
Naturality is expressed by `α.naturality_lemma`.
-/
structure nat_trans (F G : C ⥤ D) : Type (max u₁ v₂) :=
(app : Π X : C, (F.obj X) ⟶ (G.obj X))
(naturality' : ∀ {{X Y : C}} (f : X ⟶ Y), (F.map f) ≫ (app Y) = (app X) ≫ (G.map f) . obviously)
restate_axiom nat_trans.naturality'
attribute [simp] nat_trans.naturality
namespace nat_trans
/-- `nat_trans.id F` is the identity natural transformation on a functor `F`. -/
protected def id (F : C ⥤ D) : nat_trans F F :=
{ app := λ X, 𝟙 (F.obj X) }
@[simp] lemma id_app' (F : C ⥤ D) (X : C) : (nat_trans.id F).app X = 𝟙 (F.obj X) := rfl
open category
open category_theory.functor
section
variables {F G H I : C ⥤ D}
/-- `vcomp α β` is the vertical compositions of natural transformations. -/
def vcomp (α : nat_trans F G) (β : nat_trans G H) : nat_trans F H :=
{ app := λ X, (α.app X) ≫ (β.app X),
naturality' :=
begin
/- `obviously'` says: -/
intros, simp, rw [←assoc, naturality, assoc, ←naturality],
end }
-- We'll want to be able to prove that two natural transformations are equal if they are componentwise equal.
@[ext] lemma ext {α β : nat_trans F G} (w : ∀ X : C, α.app X = β.app X) : α = β :=
begin
induction α with α_components α_naturality,
induction β with β_components β_naturality,
have hc : α_components = β_components := funext w,
subst hc
end
@[simp] lemma vcomp_app (α : nat_trans F G) (β : nat_trans G H) (X : C) :
(vcomp α β).app X = (α.app X) ≫ (β.app X) := rfl
end
end nat_trans
end category_theory
|
1db1ba325a438ef572f5d13847ba08dfbb204d10 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/topology/metric_space/metric_separated.lean | 0fbbc4afab2c803e18f2c11abc67da173f3ce5c2 | [
"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,548 | 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 topology.metric_space.emetric_space
/-!
# Metric separated pairs of sets
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we define the predicate `is_metric_separated`. We say that two sets in an (extended)
metric space are *metric separated* if the (extended) distance between `x ∈ s` and `y ∈ t` is
bounded from below by a positive constant.
This notion is useful, e.g., to define metric outer measures.
-/
open emetric set
noncomputable theory
/-- Two sets in an (extended) metric space are called *metric separated* if the (extended) distance
between `x ∈ s` and `y ∈ t` is bounded from below by a positive constant. -/
def is_metric_separated {X : Type*} [emetric_space X] (s t : set X) :=
∃ r ≠ 0, ∀ (x ∈ s) (y ∈ t), r ≤ edist x y
namespace is_metric_separated
variables {X : Type*} [emetric_space X] {s t : set X} {x y : X}
@[symm] lemma symm (h : is_metric_separated s t) : is_metric_separated t s :=
let ⟨r, r0, hr⟩ := h in ⟨r, r0, λ y hy x hx, edist_comm x y ▸ hr x hx y hy⟩
lemma comm : is_metric_separated s t ↔ is_metric_separated t s := ⟨symm, symm⟩
@[simp] lemma empty_left (s : set X) : is_metric_separated ∅ s :=
⟨1, one_ne_zero, λ x, false.elim⟩
@[simp] lemma empty_right (s : set X) : is_metric_separated s ∅ :=
(empty_left s).symm
protected lemma disjoint (h : is_metric_separated s t) : disjoint s t :=
let ⟨r, r0, hr⟩ := h in
set.disjoint_left.mpr $ λ x hx1 hx2, r0 $ by simpa using hr x hx1 x hx2
lemma subset_compl_right (h : is_metric_separated s t) : s ⊆ tᶜ :=
λ x hs ht, h.disjoint.le_bot ⟨hs, ht⟩
@[mono] lemma mono {s' t'} (hs : s ⊆ s') (ht : t ⊆ t') :
is_metric_separated s' t' → is_metric_separated s t :=
λ ⟨r, r0, hr⟩, ⟨r, r0, λ x hx y hy, hr x (hs hx) y (ht hy)⟩
lemma mono_left {s'} (h' : is_metric_separated s' t) (hs : s ⊆ s') :
is_metric_separated s t :=
h'.mono hs subset.rfl
lemma mono_right {t'} (h' : is_metric_separated s t') (ht : t ⊆ t') :
is_metric_separated s t :=
h'.mono subset.rfl ht
lemma union_left {s'} (h : is_metric_separated s t) (h' : is_metric_separated s' t) :
is_metric_separated (s ∪ s') t :=
begin
rcases ⟨h, h'⟩ with ⟨⟨r, r0, hr⟩, ⟨r', r0', hr'⟩⟩,
refine ⟨min r r', _, λ x hx y hy, hx.elim _ _⟩,
{ rw [← pos_iff_ne_zero] at r0 r0' ⊢,
exact lt_min r0 r0' },
{ exact λ hx, (min_le_left _ _).trans (hr _ hx _ hy) },
{ exact λ hx, (min_le_right _ _).trans (hr' _ hx _ hy) }
end
@[simp] lemma union_left_iff {s'} :
is_metric_separated (s ∪ s') t ↔ is_metric_separated s t ∧ is_metric_separated s' t :=
⟨λ h, ⟨h.mono_left (subset_union_left _ _), h.mono_left (subset_union_right _ _)⟩,
λ h, h.1.union_left h.2⟩
lemma union_right {t'} (h : is_metric_separated s t) (h' : is_metric_separated s t') :
is_metric_separated s (t ∪ t') :=
(h.symm.union_left h'.symm).symm
@[simp] lemma union_right_iff {t'} :
is_metric_separated s (t ∪ t') ↔ is_metric_separated s t ∧ is_metric_separated s t' :=
comm.trans $ union_left_iff.trans $ and_congr comm comm
lemma finite_Union_left_iff {ι : Type*} {I : set ι} (hI : I.finite) {s : ι → set X} {t : set X} :
is_metric_separated (⋃ i ∈ I, s i) t ↔ ∀ i ∈ I, is_metric_separated (s i) t :=
begin
refine finite.induction_on hI (by simp) (λ i I hi _ hI, _),
rw [bUnion_insert, ball_insert_iff, union_left_iff, hI]
end
alias finite_Union_left_iff ↔ _ finite_Union_left
lemma finite_Union_right_iff {ι : Type*} {I : set ι} (hI : I.finite) {s : set X} {t : ι → set X} :
is_metric_separated s (⋃ i ∈ I, t i) ↔ ∀ i ∈ I, is_metric_separated s (t i) :=
by simpa only [@comm _ _ s] using finite_Union_left_iff hI
@[simp] lemma finset_Union_left_iff {ι : Type*} {I : finset ι} {s : ι → set X} {t : set X} :
is_metric_separated (⋃ i ∈ I, s i) t ↔ ∀ i ∈ I, is_metric_separated (s i) t :=
finite_Union_left_iff I.finite_to_set
alias finset_Union_left_iff ↔ _ finset_Union_left
@[simp] lemma finset_Union_right_iff {ι : Type*} {I : finset ι} {s : set X} {t : ι → set X} :
is_metric_separated s (⋃ i ∈ I, t i) ↔ ∀ i ∈ I, is_metric_separated s (t i) :=
finite_Union_right_iff I.finite_to_set
alias finset_Union_right_iff ↔ _ finset_Union_right
end is_metric_separated
|
ec3c83dd14d989ef6da84a46297d756c7046efd3 | e07b1aca72e83a272dd59d24c6e0fa246034d774 | /src/real_analysis/01_convergent_sequences.lean | 0cec8170de4fa5318271f95626e294bd4d3ef2a3 | [] | no_license | pedrominicz/learn | 637a343bd4f8669d76819ac660a2d2d3e0958710 | b79b802a9846c86c21d4b6f3e17af36e7382f0ef | refs/heads/master | 1,671,746,990,402 | 1,670,778,113,000 | 1,670,778,113,000 | 265,735,177 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,022 | lean | import algebra.pi_instances
import data.real.basic
local attribute [instance] classical.prop_decidable
class metric_space (α : Type*) :=
(dist : α → α → ℝ)
(dist_self : ∀ x, dist x x = 0)
(eq_of_dist_eq_zero : ∀ {x y : α}, dist x y = 0 → x = y)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z)
open metric_space
section
variables {α : Type*} [metric_space α]
variables {u v : ℕ → α} {l l₁ l₂ : α}
def limit (u : ℕ → α) (l : α) : Prop :=
∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, dist (u n) l ≤ ε
theorem dist_nonneg {x y : α}: 0 ≤ dist x y :=
begin
have : dist x x ≤ dist x y + dist y x, from dist_triangle _ _ _,
rw dist_comm y x at this,
rw dist_self at this,
linarith
end
theorem dist_pos {x y : α} : 0 < dist x y ↔ x ≠ y :=
begin
split; contrapose!,
{ rintro rfl,
have : dist x x = 0, from dist_self _,
linarith },
{ intro h,
apply eq_of_dist_eq_zero,
have : 0 ≤ dist x y, from dist_nonneg,
linarith }
end
lemma limit_unique (h₁ : limit u l₁) (h₂ : limit u l₂) : l₁ = l₂ :=
begin
by_contra h,
let ε := dist l₁ l₂,
have : ε > 0, from dist_pos.mpr h,
cases h₁ (ε/3) (by linarith) with N₁ hN₁,
cases h₂ (ε/3) (by linarith) with N₂ hN₂,
let n := max N₁ N₂,
specialize hN₁ n (le_max_left _ _),
specialize hN₂ n (le_max_right _ _),
have : dist (u n) l₁ + dist (u n) l₂ < ε, by linarith,
have : ε ≤ dist l₁ (u n) + dist (u n) l₂, from dist_triangle _ _ _,
linarith [dist_comm l₁ (u n)]
end
end
notation `|`x`|` := abs x
noncomputable instance : metric_space ℝ :=
{ dist := λ x y, |x - y|,
-- This proof term is hideous and beautiful simultaneously.
dist_self := λ x, eq.symm (sub_self x) ▸ abs_zero,
eq_of_dist_eq_zero := λ x y, eq_of_abs_sub_eq_zero,
dist_comm := abs_sub,
dist_triangle := abs_sub_le }
variables {u v : ℕ → ℝ} {c l l₁ l₂ : ℝ}
@[simp] def const (l : ℝ) : ℕ → ℝ := function.const _ l
lemma neg_const : -const l = const (-l) := by funext; simp
theorem const_limit : limit (const c) c :=
begin
intros ε ε_pos,
use 0,
intros n hn,
unfold dist,
simp,
linarith
end
theorem limit_add_limit (h₁ : limit u l₁) (h₂ : limit v l₂) :
limit (u + v) (l₁ + l₂) :=
begin
intros ε ε_pos,
cases h₁ (ε/2) (by linarith) with N₁ hN₁,
cases h₂ (ε/2) (by linarith) with N₂ hN₂,
use max N₁ N₂,
intros n hn,
specialize hN₁ n (le_of_max_le_left hn),
specialize hN₂ n (le_of_max_le_right hn),
unfold dist at *,
calc
|(u + v) n - (l₁ + l₂)| = |(u n + v n) - (l₁ + l₂)| : rfl
... = |(u n - l₁) + (v n - l₂)| : by congr; ring
... ≤ |u n - l₁| + |v n - l₂| : by apply abs_add
... ≤ ε : by linarith
end
lemma limit_add_const (h : limit u l) : limit (u + const c) (l + c) :=
limit_add_limit h const_limit
lemma limit_sub_self (h : limit u l) : limit (u - const l) 0 :=
begin
rw [←sub_self l, sub_eq_add_neg, sub_eq_add_neg, neg_const],
exact limit_add_const h
end
example (α : Type*) [linear_ordered_field α] (a b c : α) (h : a ≤ b / c) (H : c > 0) : a*c ≤ b := by refine (le_div_iff H).mp h
lemma limit_mul_const (h : limit u l) : limit (u * const c) (l * c) :=
begin
intros ε ε_pos,
by_cases hc : c = 0,
{ use 0,
intros n hn,
rw hc,
simp,
rw dist_self,
exact le_of_lt ε_pos },
{ change c ≠ 0 at hc,
have : ε / |c| > 0, from div_pos_of_pos_of_pos ε_pos (by rwa abs_pos_iff),
cases h _ this with N hN,
use N,
intros n hn,
specialize hN n hn,
unfold dist at *,
suffices : |(u n - l) * c| ≤ ε,
{ calc
|(u * const c) n - l * c| = |(u n * c) - l * c| : rfl
... = |(u n - l) * c| : by congr; ring
... ≤ ε : this },
rwa [abs_mul, ←le_div_iff],
rwa abs_pos_iff }
end
theorem limit_zero_mul_limit_zero (h₁ : limit u 0) (h₂ : limit v 0) :
limit (u * v) 0 :=
begin
intros ε ε_pos,
have : ε.sqrt > 0, from real.sqrt_pos.mpr ε_pos,
cases h₁ (ε.sqrt) this with N₁ hN₁,
cases h₂ (ε.sqrt) this with N₂ hN₂,
use max N₁ N₂,
intros n hn,
specialize hN₁ n (le_of_max_le_left hn),
specialize hN₂ n (le_of_max_le_right hn),
unfold dist at *,
calc
|(u * v) n - 0| = |(u n * v n) - 0| : rfl
... = |(u n - 0) * (v n - 0)| : by ring
... = |u n - 0| * |v n - 0| : by apply abs_mul
... ≤ ε.sqrt * ε.sqrt : mul_le_mul hN₁ hN₂ (abs_nonneg _) (le_of_lt this)
... = ε.sqrt ^ 2 : by ring
... = ε : real.sqr_sqrt (le_of_lt ε_pos)
end
lemma limit_neg_iff : limit (-u) (-l) ↔ limit u l :=
begin
split;
{ intros h ε ε_pos,
cases h ε ε_pos with N hN,
use N,
intros n hn,
specialize hN n hn,
unfold dist at *,
simp at *,
rwa abs_sub at hN }
end
notation u `+` v := limit_add_limit u v
theorem limit_mul_limit (h₁ : limit u l₁) (h₂ : limit v l₂) :
limit (u * v) (l₁ * l₂) :=
begin
let c₁ := const l₁,
let c₂ := const l₂,
have w₁ : limit ((u - c₁) * (v - c₂)) 0,
from limit_zero_mul_limit_zero (limit_sub_self h₁) (limit_sub_self h₂),
rw (show (u - c₁) * (v - c₂) = u * v - u * c₂ - v * c₁ + c₁ * c₂, by ring) at w₁,
have w₂ : limit (-c₁ * c₂) (-l₁ * l₂),
{ simp,
rw limit_neg_iff,
exact limit_mul_const const_limit },
have w₃ : limit (u * c₂) (l₁ * l₂), from limit_mul_const h₁,
have w₄ : limit (v * c₁) (l₁ * l₂), by { rw mul_comm l₁, exact limit_mul_const h₂ },
have w := w₁ + w₂ + w₃ + w₄,
-- The most satisfying two lines.
simp at w,
ring at w,
rwa [mul_comm u, mul_comm l₁]
end |
3de16df6e9cf7cff6e5ea3ad99c9c355c61b68d4 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/ring_theory/nullstellensatz.lean | bce357fd533ede5df1c773e094f530028779d471 | [
"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 | 8,183 | lean | /-
Copyright (c) 2021 Devon Tuma. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Devon Tuma
-/
import ring_theory.jacobson
import field_theory.is_alg_closed.basic
import field_theory.mv_polynomial
import algebraic_geometry.prime_spectrum.basic
/-!
# Nullstellensatz
This file establishes a version of Hilbert's classical Nullstellensatz for `mv_polynomial`s.
The main statement of the theorem is `vanishing_ideal_zero_locus_eq_radical`.
The statement is in terms of new definitions `vanishing_ideal` and `zero_locus`.
Mathlib already has versions of these in terms of the prime spectrum of a ring,
but those are not well-suited for expressing this result.
Suggestions for better ways to state this theorem or organize things are welcome.
The machinery around `vanishing_ideal` and `zero_locus` is also minimal, I only added lemmas
directly needed in this proof, since I'm not sure if they are the right approach.
-/
open ideal
noncomputable theory
namespace mv_polynomial
open mv_polynomial
variables {k : Type*} [field k]
variables {σ : Type*}
/-- Set of points that are zeroes of all polynomials in an ideal -/
def zero_locus (I : ideal (mv_polynomial σ k)) : set (σ → k) :=
{x : σ → k | ∀ p ∈ I, eval x p = 0}
@[simp] lemma mem_zero_locus_iff {I : ideal (mv_polynomial σ k)} {x : σ → k} :
x ∈ zero_locus I ↔ ∀ p ∈ I, eval x p = 0 := iff.rfl
lemma zero_locus_anti_mono {I J : ideal (mv_polynomial σ k)} (h : I ≤ J) :
zero_locus J ≤ zero_locus I :=
λ x hx p hp, hx p $ h hp
lemma zero_locus_bot : zero_locus (⊥ : ideal (mv_polynomial σ k)) = ⊤ :=
eq_top_iff.2 (λ x hx p hp, trans (congr_arg (eval x) (mem_bot.1 hp)) (eval x).map_zero)
lemma zero_locus_top : zero_locus (⊤ : ideal (mv_polynomial σ k)) = ⊥ :=
eq_bot_iff.2 $ λ x hx, one_ne_zero ((eval x).map_one ▸ (hx 1 submodule.mem_top) : (1 : k) = 0)
/-- Ideal of polynomials with common zeroes at all elements of a set -/
def vanishing_ideal (V : set (σ → k)) : ideal (mv_polynomial σ k) :=
{ carrier := {p | ∀ x ∈ V, eval x p = 0},
zero_mem' := λ x hx, ring_hom.map_zero _,
add_mem' := λ p q hp hq x hx, by simp only [hq x hx, hp x hx, add_zero, ring_hom.map_add],
smul_mem' := λ p q hq x hx,
by simp only [hq x hx, algebra.id.smul_eq_mul, mul_zero, ring_hom.map_mul] }
@[simp] lemma mem_vanishing_ideal_iff {V : set (σ → k)} {p : mv_polynomial σ k} :
p ∈ vanishing_ideal V ↔ ∀ x ∈ V, eval x p = 0 := iff.rfl
lemma vanishing_ideal_anti_mono {A B : set (σ → k)} (h : A ≤ B) :
vanishing_ideal B ≤ vanishing_ideal A :=
λ p hp x hx, hp x $ h hx
lemma vanishing_ideal_empty : vanishing_ideal (∅ : set (σ → k)) = ⊤ :=
le_antisymm le_top (λ p hp x hx, absurd hx (set.not_mem_empty x))
lemma le_vanishing_ideal_zero_locus (I : ideal (mv_polynomial σ k)) :
I ≤ vanishing_ideal (zero_locus I) :=
λ p hp x hx, hx p hp
lemma zero_locus_vanishing_ideal_le (V : set (σ → k)) :
V ≤ zero_locus (vanishing_ideal V) :=
λ V hV p hp, hp V hV
theorem zero_locus_vanishing_ideal_galois_connection :
@galois_connection (ideal (mv_polynomial σ k)) (order_dual (set (σ → k))) _ _
zero_locus vanishing_ideal :=
λ I V, ⟨λ h, le_trans (le_vanishing_ideal_zero_locus I) (vanishing_ideal_anti_mono h),
λ h, le_trans (zero_locus_anti_mono h) (zero_locus_vanishing_ideal_le V)⟩
lemma mem_vanishing_ideal_singleton_iff (x : σ → k) (p : mv_polynomial σ k) :
p ∈ (vanishing_ideal {x} : ideal (mv_polynomial σ k)) ↔ (eval x p = 0) :=
⟨λ h, h x rfl, λ hpx y hy, hy.symm ▸ hpx⟩
instance vanishing_ideal_singleton_is_maximal {x : σ → k} :
(vanishing_ideal {x} : ideal (mv_polynomial σ k)).is_maximal :=
begin
have : (vanishing_ideal {x} : ideal (mv_polynomial σ k)).quotient ≃+* k := ring_equiv.of_bijective
(ideal.quotient.lift _ (eval x) (λ p h, (mem_vanishing_ideal_singleton_iff x p).mp h))
begin
refine ⟨(ring_hom.injective_iff _).mpr (λ p hp, _), λ z,
⟨(ideal.quotient.mk (vanishing_ideal {x} : ideal (mv_polynomial σ k))) (C z), by simp⟩⟩,
obtain ⟨q, rfl⟩ := quotient.mk_surjective p,
rwa [ideal.quotient.lift_mk, ← mem_vanishing_ideal_singleton_iff,
← quotient.eq_zero_iff_mem] at hp,
end,
rw [← bot_quotient_is_maximal_iff, ring_equiv.bot_maximal_iff this],
exact bot_is_maximal,
end
lemma radical_le_vanishing_ideal_zero_locus (I : ideal (mv_polynomial σ k)) :
I.radical ≤ vanishing_ideal (zero_locus I) :=
begin
intros p hp x hx,
rw ← mem_vanishing_ideal_singleton_iff,
rw radical_eq_Inf at hp,
refine (mem_Inf.mp hp) ⟨le_trans (le_vanishing_ideal_zero_locus I)
(vanishing_ideal_anti_mono (λ y hy, hy.symm ▸ hx)), is_maximal.is_prime' _⟩,
end
/-- The point in the prime spectrum assosiated to a given point -/
def point_to_point (x : σ → k) : prime_spectrum (mv_polynomial σ k) :=
⟨(vanishing_ideal {x} : ideal (mv_polynomial σ k)), by apply_instance⟩
@[simp] lemma vanishing_ideal_point_to_point (V : set (σ → k)) :
prime_spectrum.vanishing_ideal (point_to_point '' V) = mv_polynomial.vanishing_ideal V :=
le_antisymm
(λ p hp x hx, (((prime_spectrum.mem_vanishing_ideal _ _).1 hp)
⟨vanishing_ideal {x}, by apply_instance⟩ ⟨x, ⟨hx, rfl⟩⟩) x rfl)
(λ p hp, (prime_spectrum.mem_vanishing_ideal _ _).2
(λ I hI, let ⟨x, hx⟩ := hI in hx.2 ▸ λ x' hx', (set.mem_singleton_iff.1 hx').symm ▸ hp x hx.1))
lemma point_to_point_zero_locus_le (I : ideal (mv_polynomial σ k)) :
point_to_point '' (mv_polynomial.zero_locus I) ≤ prime_spectrum.zero_locus ↑I :=
λ J hJ, let ⟨x, hx⟩ := hJ in (le_trans (le_vanishing_ideal_zero_locus I)
(hx.2 ▸ vanishing_ideal_anti_mono (set.singleton_subset_iff.2 hx.1)) : I ≤ J.as_ideal)
variables [is_alg_closed k] [fintype σ]
lemma is_maximal_iff_eq_vanishing_ideal_singleton (I : ideal (mv_polynomial σ k)) :
I.is_maximal ↔ ∃ (x : σ → k), I = vanishing_ideal {x} :=
begin
refine ⟨λ hI, _, λ h, let ⟨x, hx⟩ := h in
hx.symm ▸ (mv_polynomial.vanishing_ideal_singleton_is_maximal)⟩,
letI : I.is_maximal := hI,
letI : field I.quotient := quotient.field I,
let ϕ : k →+* I.quotient := (ideal.quotient.mk I).comp C,
have hϕ : function.bijective ϕ := ⟨quotient_mk_comp_C_injective _ _ I hI.ne_top,
is_alg_closed.algebra_map_surjective_of_is_integral' ϕ
(mv_polynomial.comp_C_integral_of_surjective_of_jacobson _ quotient.mk_surjective)⟩,
obtain ⟨φ, hφ⟩ := function.surjective.has_right_inverse hϕ.2,
let x : σ → k := λ s, φ ((ideal.quotient.mk I) (X s)),
have hx : ∀ s : σ, ϕ (x s) = (ideal.quotient.mk I) (X s) := λ s, hφ ((ideal.quotient.mk I) (X s)),
refine ⟨x, (is_maximal.eq_of_le (by apply_instance) hI.ne_top _).symm⟩,
intros p hp,
rw [← quotient.eq_zero_iff_mem, map_mv_polynomial_eq_eval₂ (ideal.quotient.mk I) p, eval₂_eq'],
rw [mem_vanishing_ideal_singleton_iff, eval_eq'] at hp,
convert (trans (congr_arg ϕ hp) ϕ.map_zero),
simp only [ϕ.map_sum, ϕ.map_mul, ϕ.map_prod, ϕ.map_pow, hx],
end
/-- Main statement of the Nullstellensatz -/
@[simp] theorem vanishing_ideal_zero_locus_eq_radical (I : ideal (mv_polynomial σ k)) :
vanishing_ideal (zero_locus I) = I.radical :=
begin
rw I.radical_eq_jacobson,
refine le_antisymm (le_Inf _) (λ p hp x hx, _),
{ rintros J ⟨hJI, hJ⟩,
obtain ⟨x, hx⟩ := (is_maximal_iff_eq_vanishing_ideal_singleton J).1 hJ,
refine hx.symm ▸ vanishing_ideal_anti_mono (λ y hy p hp, _),
rw [← mem_vanishing_ideal_singleton_iff, set.mem_singleton_iff.1 hy, ← hx],
refine hJI hp },
{ rw ← mem_vanishing_ideal_singleton_iff x p,
refine (mem_Inf.mp hp) ⟨le_trans (le_vanishing_ideal_zero_locus I)
(vanishing_ideal_anti_mono (λ y hy, hy.symm ▸ hx)),
mv_polynomial.vanishing_ideal_singleton_is_maximal⟩ },
end
@[simp] lemma is_prime.vanishing_ideal_zero_locus (P : ideal (mv_polynomial σ k)) [h : P.is_prime] :
vanishing_ideal (zero_locus P) = P :=
trans (vanishing_ideal_zero_locus_eq_radical P) h.radical
end mv_polynomial
|
119cce9dc92ee37590308ef51f3e605238de5e53 | 22e97a5d648fc451e25a06c668dc03ac7ed7bc25 | /src/tactic/core.lean | 7a451f6ebcd6751b78905e5691affd122913878f | [
"Apache-2.0"
] | permissive | keeferrowan/mathlib | f2818da875dbc7780830d09bd4c526b0764a4e50 | aad2dfc40e8e6a7e258287a7c1580318e865817e | refs/heads/master | 1,661,736,426,952 | 1,590,438,032,000 | 1,590,438,032,000 | 266,892,663 | 0 | 0 | Apache-2.0 | 1,590,445,835,000 | 1,590,445,835,000 | null | UTF-8 | Lean | false | false | 83,653 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek
-/
import data.dlist.basic
import control.basic
import meta.expr
import meta.rb_map
import data.bool
import tactic.lean_core_docs
universe variable u
instance : has_lt pos :=
{ lt := λ x y, (x.line, x.column) < (y.line, y.column) }
namespace expr
open tactic
/-- Given an expr `α` representing a type with numeral structure,
`of_nat α n` creates the `α`-valued numeral expression corresponding to `n`. -/
protected meta def of_nat (α : expr) : ℕ → tactic expr :=
nat.binary_rec
(tactic.mk_mapp ``has_zero.zero [some α, none])
(λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else
do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e])
/-- Given an expr `α` representing a type with numeral structure,
`of_int α n` creates the `α`-valued numeral expression corresponding to `n`.
The output is either a numeral or the negation of a numeral. -/
protected meta def of_int (α : expr) : ℤ → tactic expr
| (n : ℕ) := expr.of_nat α n
| -[1+ n] := do
e ← expr.of_nat α (n+1),
tactic.mk_app ``has_neg.neg [e]
/-- Generates an expression of the form `∃(args), inner`. `args` is assumed to be a list of local
constants. When possible, `p ∧ q` is used instead of `∃(_ : p), q`. -/
meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr :=
args.mfoldr (λarg i:expr, do
t ← infer_type arg,
sort l ← infer_type t,
return $ if arg.occurs i ∨ l ≠ level.zero
then (const `Exists [l] : expr) t (i.lambdas [arg])
else (const `and [] : expr) t i)
inner
/-- `traverse f e` applies the monadic function `f` to the direct descendants of `e`. -/
meta def traverse {m : Type → Type u} [applicative m]
{elab elab' : bool} (f : expr elab → m (expr elab')) :
expr elab → m (expr elab')
| (var v) := pure $ var v
| (sort l) := pure $ sort l
| (const n ls) := pure $ const n ls
| (mvar n n' e) := mvar n n' <$> f e
| (local_const n n' bi e) := local_const n n' bi <$> f e
| (app e₀ e₁) := app <$> f e₀ <*> f e₁
| (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁
| (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁
| (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂
| (macro mac es) := macro mac <$> list.traverse f es
/-- `mfoldl f a e` folds the monadic function `f` over the subterms of the expression `e`,
with initial value `a`. -/
meta def mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α
| x e := prod.snd <$> (state_t.run (e.traverse $ λ e',
(get >>= monad_lift ∘ flip f e' >>= put) $> e') x : m _)
end expr
namespace interaction_monad
open result
variables {σ : Type} {α : Type u}
/-- `get_state` returns the underlying state inside an interaction monad, from within that monad. -/
-- Note that this is a generalization of `tactic.read` in core.
meta def get_state : interaction_monad σ σ :=
λ state, success state state
/-- `set_state` sets the underlying state inside an interaction monad, from within that monad. -/
-- Note that this is a generalization of `tactic.write` in core.
meta def set_state (state : σ) : interaction_monad σ unit :=
λ _, success () state
/--
`run_with_state state tac` applies `tac` to the given state `state` and returns the result,
subsequently restoring the original state.
If `tac` fails, then `run_with_state` does too.
-/
meta def run_with_state (state : σ) (tac : interaction_monad σ α) : interaction_monad σ α :=
λ s, match tac state with
| success val _ := success val s
| exception fn pos _ := exception fn pos s
end
end interaction_monad
namespace format
/-- `join' [a,b,c]` produces the format object `abc`.
It differs from `format.join` by using `format.nil` instead of `""` for the empty list. -/
meta def join' (xs : list format) : format :=
xs.foldl compose nil
/-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`,
where `.` represents `format.join`. -/
meta def intercalate (x : format) : list format → format :=
join' ∘ list.intersperse x
/-- `soft_break` is similar to `line`. Whereas in `group (x ++ line ++ y ++ line ++ z)`
the result either fits on one line or in three, `x ++ soft_break ++ y ++ soft_break ++ z`
each line break is decided independently -/
meta def soft_break : format :=
group line
end format
section format
open format
/-- format a `list` by separating elements with `soft_break` instead of `line` -/
meta def list.to_line_wrap_format {α : Type u} [has_to_format α] : list α → format
| [] := to_fmt "[]"
| xs := to_fmt "[" ++ group (nest 1 $ intercalate ("," ++ soft_break) $ xs.map to_fmt) ++ to_fmt "]"
end format
namespace tactic
open function
/-- Private work function for `add_local_consts_as_local_hyps`: given
`mappings : list (expr × expr)` corresponding to pairs `(var, hyp)` of variables and the local
hypothesis created as a result and `(var :: rest) : list expr` of more local variables we
examine `var` to see if it contains any other variables in `rest`. If it does, we put it to the
back of the queue and recurse. If it does not, then we perform replacements inside the type of
`var` using the `mappings`, create a new associate local hypothesis, add this to the list of
mappings, and recurse. We are done once all local hypotheses have been processed.
If the list of passed local constants have types which depend on one another (which can only
happen by hand-crafting the `expr`s manually), this function will loop forever. -/
private meta def add_local_consts_as_local_hyps_aux
: list (expr × expr) → list expr → tactic (list (expr × expr))
| mappings [] := return mappings
| mappings (var :: rest) := do
/- Determine if `var` contains any local variables in the lift `rest`. -/
let is_dependent := var.local_type.fold ff $ λ e n b,
if b then b else e ∈ rest,
/- If so, then skip it---add it to the end of the variable queue. -/
if is_dependent then
add_local_consts_as_local_hyps_aux mappings (rest ++ [var])
else do
/- Otherwise, replace all of the local constants referenced by the type of `var` with the
respective new corresponding local hypotheses as recorded in the list `mappings`. -/
let new_type := var.local_type.replace_subexprs mappings,
/- Introduce a new local new local hypothesis `hyp` for `var`, with the correct type. -/
hyp ← assertv var.local_pp_name new_type (var.local_const_set_type new_type),
/- Process the next variable in the queue, with the mapping list updated to include the local
hypothesis which we just created. -/
add_local_consts_as_local_hyps_aux ((var, hyp) :: mappings) rest
/-- `add_local_consts_as_local_hyps vars` add the given list `vars` of `expr.local_const`s to the
tactic state. This is harder than it sounds, since the list of local constants which we have
been passed can have dependencies between their types.
For example, suppose we have two local constants `n : ℕ` and `h : n = 3`. Then we cannot blindly
add `h` as a local hypothesis, since we need the `n` to which it refers to be the `n` created as
a new local hypothesis, not the old local constant `n` with the same name. Of course, these
dependencies can be nested arbitrarily deep.
If the list of passed local constants have types which depend on one another (which can only
happen by hand-crafting the `expr`s manually), this function will loop forever. -/
meta def add_local_consts_as_local_hyps (vars : list expr) : tactic (list (expr × expr)) :=
/- The `list.reverse` below is a performance optimisation since the list of available variables
reported by the system is often mostly the reverse of the order in which they are dependent. -/
add_local_consts_as_local_hyps_aux [] vars.reverse.erase_dup
/-- `mk_local_pisn e n` instantiates the first `n` variables of a pi expression `e`,
and returns the new local constants along with the instantiated expression. Fails if `e` does
not begin with at least `n` pi binders. -/
meta def mk_local_pisn : expr → nat → tactic (list expr × expr)
| (expr.pi n bi d b) (c + 1) := do
p ← mk_local' n bi d,
(ps, r) ← mk_local_pisn (b.instantiate_var p) c,
return ((p :: ps), r)
| e 0 := return ([], e)
| _ _ := failed
-- TODO: move to `declaration` namespace in `meta/expr.lean`
/-- `mk_theorem n ls t e` creates a theorem declaration with name `n`, universe parameters named
`ls`, type `t`, and body `e`. -/
meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration :=
declaration.thm n ls t (task.pure e)
/-- `add_theorem_by n ls type tac` uses `tac` to synthesize a term with type `type`, and adds this
to the environment as a theorem with name `n` and universe parameters `ls`. -/
meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) :
tactic expr :=
do ((), body) ← solve_aux type tac,
body ← instantiate_mvars body,
add_decl $ mk_theorem n ls type body,
return $ expr.const n $ ls.map level.param
/-- `eval_expr' α e` attempts to evaluate the expression `e` in the type `α`.
This is a variant of `eval_expr` in core. Due to unexplained behavior in the VM, in rare
situations the latter will fail but the former will succeed. -/
meta def eval_expr' (α : Type*) [_inst_1 : reflected α] (e : expr) : tactic α :=
mk_app ``id [e] >>= eval_expr α
/-- `mk_fresh_name` returns identifiers starting with underscores,
which are not legal when emitted by tactic programs. `mk_user_fresh_name`
turns the useful source of random names provided by `mk_fresh_name` into
names which are usable by tactic programs.
The returned name has four components which are all strings. -/
meta def mk_user_fresh_name : tactic name :=
do nm ← mk_fresh_name,
return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__
/-- `has_attribute' attr_name decl_name` checks whether `decl_name` has attribute `attr_name`. -/
meta def has_attribute' (attr_name decl_name : name) : tactic bool :=
succeeds (has_attribute attr_name decl_name)
/-- Checks whether the name is a simp lemma -/
meta def is_simp_lemma : name → tactic bool :=
has_attribute' `simp
/-- Checks whether the name is an instance. -/
meta def is_instance : name → tactic bool :=
has_attribute' `instance
/-- `local_decls` returns a dictionary mapping names to their corresponding declarations.
Covers all declarations from the current file. -/
meta def local_decls : tactic (name_map declaration) :=
do e ← tactic.get_env,
let xs := e.fold native.mk_rb_map
(λ d s, if environment.in_current_file' e d.to_name
then s.insert d.to_name d else s),
pure xs
/-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/
meta def get_unused_decl_name_aux (e : environment) (nm : name) : ℕ → tactic name | n :=
let nm' := nm.append_suffix ("_" ++ to_string n) in
if e.contains nm' then get_unused_decl_name_aux (n+1) else return nm'
/-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it
returns that, otherwise it tries `nm_2`, `nm_3`, ... -/
meta def get_unused_decl_name (nm : name) : tactic name :=
get_env >>= λ e, if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm
/--
Returns a pair `(e, t)`, where `e ← mk_const d.to_name`, and `t = d.type`
but with universe params updated to match the fresh universe metavariables in `e`.
This should have the same effect as just
```lean
do e ← mk_const d.to_name,
t ← infer_type e,
return (e, t)
```
but is hopefully faster.
-/
meta def decl_mk_const (d : declaration) : tactic (expr × expr) :=
do subst ← d.univ_params.mmap $ λ u, prod.mk u <$> mk_meta_univ,
let e : expr := expr.const d.to_name (prod.snd <$> subst),
return (e, d.type.instantiate_univ_params subst)
/--
Replace every universe metavariable in an expression with a universe parameter.
(This is useful when making new declarations.)
-/
meta def replace_univ_metas_with_univ_params (e : expr) : tactic expr :=
do
e.list_univ_meta_vars.enum.mmap (λ n, do
let n' := (`u).append_suffix ("_" ++ to_string (n.1+1)),
unify (expr.sort (level.mvar n.2)) (expr.sort (level.param n'))),
instantiate_mvars e
/-- `mk_local n` creates a dummy local variable with name `n`.
The type of this local constant is a constant with name `n`, so it is very unlikely to be
a meaningful expression. -/
meta def mk_local (n : name) : expr :=
expr.local_const n n binder_info.default (expr.const n [])
/-- `pis loc_consts f` is used to create a pi expression whose body is `f`.
`loc_consts` should be a list of local constants. The function will abstract these local
constants from `f` and bind them with pi binders.
For example, if `a, b` are local constants with types `Ta, Tb`,
``pis [a, b] `(f a b)`` will return the expression
`Π (a : Ta) (b : Tb), f a b`. -/
meta def pis : list expr → expr → tactic expr
| (e@(expr.local_const uniq pp info _) :: es) f := do
t ← infer_type e,
f' ← pis es f,
pure $ expr.pi pp info t (expr.abstract_local f' uniq)
| _ f := pure f
/-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`.
`loc_consts` should be a list of local constants. The function will abstract these local
constants from `f` and bind them with lambda binders.
For example, if `a, b` are local constants with types `Ta, Tb`,
``lambdas [a, b] `(f a b)`` will return the expression
`λ (a : Ta) (b : Tb), f a b`. -/
meta def lambdas : list expr → expr → tactic expr
| (e@(expr.local_const uniq pp info _) :: es) f := do
t ← infer_type e,
f' ← lambdas es f,
pure $ expr.lam pp info t (expr.abstract_local f' uniq)
| _ f := pure f
/-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`,
`y : ty x` and `z : tz x y`, creates an expression of sigma type:
`⟨x,y,z⟩ : Σ' (x : tx) (y : ty x), tz x y`.
-/
meta def mk_psigma : list expr → tactic expr
| [] := mk_const ``punit
| [x@(expr.local_const _ _ _ _)] := pure x
| (x@(expr.local_const _ _ _ _) :: xs) :=
do y ← mk_psigma xs,
α ← infer_type x,
β ← infer_type y,
t ← lambdas [x] β >>= instantiate_mvars,
r ← mk_mapp ``psigma.mk [α,t],
pure $ r x y
| _ := fail "mk_psigma expects a list of local constants"
/-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n`
times and uses `ns` to name the resulting variables. Returns a triple: list of new variables,
remaining term and unused variable names.
-/
meta def elim_gen_prod : nat → expr → list expr → list name → tactic (list expr × expr × list name)
| 0 e hs ns := return (hs.reverse, e, ns)
| (n + 1) e hs ns := do
t ← infer_type e,
if t.is_app_of `eq then return (hs.reverse, e, ns)
else do
[(_, [h, h'], _)] ← cases_core e (ns.take 1),
elim_gen_prod n h' (h :: hs) (ns.drop 1)
private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr)
| 0 e hs := return (hs, e)
| (n + 1) e hs := do
[(_, [h], _), (_, [h'], _)] ← induction e [],
swap,
elim_gen_sum_aux n h' (h::hs)
/-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose
type is a (nested) sum `⊕`. Returns the list of local constants representing the components of `e`.
-/
meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do
(hs, h') ← elim_gen_sum_aux n e [],
gs ← get_goals,
set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1),
return $ hs.reverse ++ [h']
/-- Given `elab_def`, a tactic to solve the current goal,
`extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it
to close the goal. If `trusted` is false, it will be a meta definition. -/
meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit :=
do cxt ← list.map expr.to_implicit_local_const <$> local_context,
t ← target,
(eqns,d) ← solve_aux t elab_def,
d ← instantiate_mvars d,
t' ← pis cxt t,
d' ← lambdas cxt d,
let univ := t'.collect_univ_params,
add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted,
applyc n
/-- Attempts to close the goal with `dec_trivial`. -/
meta def exact_dec_trivial : tactic unit := `[exact dec_trivial]
/-- Runs a tactic for a result, reverting the state after completion. -/
meta def retrieve {α} (tac : tactic α) : tactic α :=
λ s, result.cases_on (tac s)
(λ a s', result.success a s)
result.exception
/-- Repeat a tactic at least once, calling it recursively on all subgoals,
until it fails. This tactic fails if the first invocation fails. -/
meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t
/-- `iterate_range m n t`: Repeat the given tactic at least `m` times and
at most `n` times or until `t` fails. Fails if `t` does not run at least `m` times. -/
meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit
| 0 0 t := skip
| 0 (n+1) t := try (t >> iterate_range 0 n t)
| (m+1) n t := t >> iterate_range m (n-1) t
/--
Given a tactic `tac` that takes an expression
and returns a new expression and a proof of equality,
use that tactic to change the type of the hypotheses listed in `hs`,
as well as the goal if `tgt = tt`.
Returns `tt` if any types were successfully changed.
-/
meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) :
tactic bool :=
do to_remove ← hs.mfilter $ λ h, do {
h_type ← infer_type h,
succeeds $ do
(new_h_type, pr) ← tac h_type,
assert h.local_pp_name new_h_type,
mk_eq_mp pr h >>= tactic.exact },
goal_simplified ← succeeds $ do {
guard tgt,
(new_t, pr) ← target >>= tac,
replace_target new_t pr },
to_remove.mmap' (λ h, try (clear h)),
return (¬ to_remove.empty ∨ goal_simplified)
/-- `revert_after e` reverts all local constants after local constant `e`. -/
meta def revert_after (e : expr) : tactic ℕ := do
l ← local_context,
[pos] ← return $ l.indexes_of e | pp e >>= λ s, fail format!"No such local constant {s}",
let l := l.drop pos.succ, -- all local hypotheses after `e`
revert_lst l
/-- `generalize' e n` generalizes the target with respect to `e`. It creates a new local constant
with name `n` of the same type as `e` and replaces all occurrences of `e` by `n`.
`generalize'` is similar to `generalize` but also succeeds when `e` does not occur in the
goal, in which case it just calls `assert`.
In contrast to `generalize` it already introduces the generalized variable. -/
meta def generalize' (e : expr) (n : name) : tactic expr :=
(generalize e n >> intro1) <|> note n none e
/-!
### Various tactics related to local definitions (local constants of the form `x : α := t`)
We call `t` the value of `x`.
-/
/-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined
locally using a `let` expression. Otherwise it fails. -/
meta def local_def_value (e : expr) : tactic expr :=
pp e >>= λ s, -- running `pp` here, because we cannot access it in the `type_context` monad.
tactic.unsafe.type_context.run $ do
lctx <- tactic.unsafe.type_context.get_local_context,
some ldecl <- return $ lctx.get_local_decl e.local_uniq_name |
tactic.unsafe.type_context.fail format!"No such hypothesis {s}.",
some let_val <- return ldecl.value |
tactic.unsafe.type_context.fail format!"Variable {e} is not a local definition.",
return let_val
/-- `revert_deps e` reverts all the hypotheses that depend on one of the local
constants `e`, including the local definitions that have `e` in their definition.
This fixes a bug in `revert_kdeps` that does not revert local definitions for which `e` only
appears in the definition. -/
/- We cannot implement it as `revert e >> intro1`, because that would change the local constant in
the context. -/
meta def revert_deps (e : expr) : tactic ℕ := do
n ← revert_kdeps e,
l ← local_context,
[pos] ← return $ l.indexes_of e,
let l := l.drop pos.succ, -- local hypotheses after `e`
ls ← l.mfilter $ λ e', try_core (local_def_value e') >>= λ o, return $ o.elim ff $ λ e'',
e''.has_local_constant e,
n' ← revert_lst ls,
return $ n + n'
/-- `is_local_def e` succeeds when `e` is a local definition (a local constant of the form
`e : α := t`) and otherwise fails. -/
meta def is_local_def (e : expr) : tactic unit :=
retrieve $ do revert e, expr.elet _ _ _ _ ← target, skip
/-- `clear_value e` clears the body of the local definition `e`, changing it into a regular
hypothesis. A hypothesis `e : α := t` is changed to `e : α`.
This tactic is called `clearbody` in Coq. -/
meta def clear_value (e : expr) : tactic unit := do
n ← revert_after e,
is_local_def e <|>
pp e >>= λ s, fail format!"Cannot clear the body of {s}. It is not a local definition.",
let nm := e.local_pp_name,
(generalize' e nm >> clear e) <|>
fail format!"Cannot clear the body of {nm}. The resulting goal is not type correct.",
intron n
/-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions,
`simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting
expression and a proof of equality. -/
meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) :
tactic (expr × expr) :=
prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg
/-- Caches unary type classes on a type `α : Type.{univ}`. -/
meta structure instance_cache :=
(α : expr)
(univ : level)
(inst : name_map expr)
/-- Creates an `instance_cache` for the type `α`. -/
meta def mk_instance_cache (α : expr) : tactic instance_cache :=
do u ← mk_meta_univ,
infer_type α >>= unify (expr.sort (level.succ u)),
u ← get_univ_assignment u,
return ⟨α, u, mk_name_map⟩
namespace instance_cache
/-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of
`n c.α` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance
via type class resolution, and updates the cache. -/
meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) :=
match c.inst.find n with
| some i := return (c, i)
| none := do e ← mk_app n [c.α] >>= mk_instance,
return (⟨c.α, c.univ, c.inst.insert n e⟩, e)
end
open expr
/-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`,
`append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/
meta def append_typeclasses : expr → instance_cache → list expr →
tactic (instance_cache × list expr)
| (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l :=
do (c, p) ← c.get n, return (c, p :: l)
| _ c l := return (c, l)
/-- Creates the application `n c.α p l`, where `p` is a type class instance found in the cache `c`.
-/
meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) :=
do d ← get_decl n,
(c, l) ← append_typeclasses d.type.binding_body c l,
return (c, (expr.const n [c.univ]).mk_app (c.α :: l))
/-- `c.of_nat n` creates the `c.α`-valued numeral expression corresponding to `n`. -/
protected meta def of_nat (c : instance_cache) (n : ℕ) : tactic (instance_cache × expr) :=
if n = 0 then c.mk_app ``has_zero.zero [] else do
(c, ai) ← c.get ``has_add,
(c, oi) ← c.get ``has_one,
(c, one) ← c.mk_app ``has_one.one [],
return (c, n.binary_rec one $ λ b n e,
if n = 0 then one else
cond b
((expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e])
((expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e]))
/-- `c.of_int n` creates the `c.α`-valued numeral expression corresponding to `n`.
The output is either a numeral or the negation of a numeral. -/
protected meta def of_int (c : instance_cache) : ℤ → tactic (instance_cache × expr)
| (n : ℕ) := c.of_nat n
| -[1+ n] := do
(c, e) ← c.of_nat (n+1),
c.mk_app ``has_neg.neg [e]
end instance_cache
private meta def get_expl_pi_arity_aux : expr → tactic nat
| (expr.pi n bi d b) :=
do m ← mk_fresh_name,
let l := expr.local_const m n bi d,
new_b ← whnf (expr.instantiate_var b l),
r ← get_expl_pi_arity_aux new_b,
if bi = binder_info.default then
return (r + 1)
else
return r
| e := return 0
/-- Compute the arity of explicit arguments of the given (Pi-)type. -/
meta def get_expl_pi_arity (type : expr) : tactic nat :=
whnf type >>= get_expl_pi_arity_aux
/-- Compute the arity of explicit arguments of the given function. -/
meta def get_expl_arity (fn : expr) : tactic nat :=
infer_type fn >>= get_expl_pi_arity
/-- Auxilliary defintion for `get_pi_binders`. -/
meta def get_pi_binders_aux : list binder → expr → tactic (list binder × expr)
| es (expr.pi n bi d b) :=
do m ← mk_fresh_name,
let l := expr.local_const m n bi d,
let new_b := expr.instantiate_var b l,
get_pi_binders_aux (⟨n, bi, d⟩::es) new_b
| es e := return (es, e)
/-- Get the binders and target of a pi-type. Instantiates bound variables by
local constants. Cf. `pi_binders` in `meta.expr` (which produces open terms).
See also `mk_local_pis` in `init.core.tactic` which does almost the same. -/
meta def get_pi_binders : expr → tactic (list binder × expr) | e :=
do (es, e) ← get_pi_binders_aux [] e, return (es.reverse, e)
/-- Auxilliary definition for `get_pi_binders_dep`. -/
meta def get_pi_binders_dep_aux : ℕ → expr → tactic (list (ℕ × binder) × expr)
| n (expr.pi nm bi d b) :=
do l ← mk_local' nm bi d,
(ls, r) ← get_pi_binders_dep_aux (n+1) (expr.instantiate_var b l),
return (if b.has_var then ls else (n, ⟨nm, bi, d⟩)::ls, r)
| n e := return ([], e)
/-- A variant of `get_pi_binders` that only returns the binders that do not occur in later
arguments or in the target. Also returns the argument position of each returned binder. -/
meta def get_pi_binders_dep : expr → tactic (list (ℕ × binder) × expr) :=
get_pi_binders_dep_aux 0
/-- A variation on `assert` where a (possibly incomplete)
proof of the assertion is provided as a parameter.
``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and
use `tac` to (partially) construct a proof for it. `gs` is the
list of remaining goals in the proof of `h`.
The benefits over assert are:
- unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`;
- when `tac` does not complete the proof of `h`, returning the list
of goals allows one to write a tactic using `h` and with the confidence
that a proof will not boil over to goals left over from the proof of `h`,
unlike what would be the case when using `tactic.swap`.
-/
meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) :
tactic (expr × list expr) :=
focus1 $
do h' ← assert h p,
[g₀,g₁] ← get_goals,
set_goals [g₀], tac₀,
gs ← get_goals,
set_goals [g₁],
return (h', gs)
/-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/
meta def var_names : expr → list name
| (expr.pi n _ _ b) := n :: var_names b
| _ := []
/-- When `struct_n` is the name of a structure type,
`subobject_names struct_n` returns two lists of names `(instances, fields)`.
The names in `instances` are the projections from `struct_n` to the structures that it extends
(assuming it was defined with `old_structure_cmd false`).
The names in `fields` are the standard fields of `struct_n`. -/
meta def subobject_names (struct_n : name) : tactic (list name × list name) :=
do env ← get_env,
[c] ← pure $ env.constructors_of struct_n | fail "too many constructors",
vs ← var_names <$> (mk_const c >>= infer_type),
fields ← env.structure_fields struct_n,
return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs)
private meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n :=
do (so,fs) ← subobject_names struct_n,
ts ← so.mmap (λ n, do
(_, e) ← mk_const (n.update_prefix struct_n) >>= infer_type >>= mk_local_pis,
expanded_field_list' $ e.get_app_fn.const_name),
return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n)
open functor function
/-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure
named `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name
of the projection is `prefix.name`. -/
meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) :=
dlist.to_list <$> expanded_field_list' struct_n
/--
Return a list of all type classes which can be instantiated
for the given expression.
-/
meta def get_classes (e : expr) : tactic (list name) :=
attribute.get_instances `class >>= list.mfilter (λ n,
succeeds $ mk_app n [e] >>= mk_instance)
open nat
/-- Create a list of `n` fresh metavariables. -/
meta def mk_mvar_list : ℕ → tactic (list expr)
| 0 := pure []
| (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n
/-- Returns the only goal, or fails if there isn't just one goal. -/
meta def get_goal : tactic expr :=
do gs ← get_goals,
match gs with
| [a] := return a
| [] := fail "there are no goals"
| _ := fail "there are too many goals"
end
/-- `iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals,
or until it fails. Always succeeds. -/
meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit
| 0 tac := trace "maximal iterations reached"
| (succ n) tac := tactic.all_goals' $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip
/-- `iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first
goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on
current goal. -/
meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit
| 0 tac := trace "maximal iterations reached"
| (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac)
/-- `apply_list l`: try to apply the tactics in the list `l` on the first goal, and
fail if none succeeds -/
meta def apply_list_expr : list expr → tactic unit
| [] := fail "no matching rule"
| (h::t) := do interactive.concat_tags (apply h) <|> apply_list_expr t
/-- constructs a list of expressions given a list of p-expressions, as follows:
- if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it
- if the p-expression is a user attribute, add all the theorems with this attribute
to the list.-/
meta def build_list_expr_for_apply : list pexpr → tactic (list expr)
| [] := return []
| (h::t) := do
tail ← build_list_expr_for_apply t,
a ← i_to_expr_for_apply h,
(do l ← attribute.get_instances (expr.const_name a),
m ← list.mmap mk_const l,
return (m.append tail))
<|> return (a::tail)
/--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the
first goal and the resulting subgoals, iteratively, at most `n` times.
Unlike `solve_by_elim`, `apply_rules` does not do any backtracking, and just greedily applies
a lemma from the list until it can't.
-/
meta def apply_rules (hs : list pexpr) (n : nat) : tactic unit :=
do l ← build_list_expr_for_apply hs,
iterate_at_most_on_subgoals n (assumption <|> apply_list_expr l)
/-- `replace h p` elaborates the pexpr `p`, clears the existing hypothesis named `h` from the local
context, and adds a new hypothesis named `h`. The type of this hypothesis is the type of `p`.
Fails if there is nothing named `h` in the local context. -/
meta def replace (h : name) (p : pexpr) : tactic unit :=
do h' ← get_local h,
p ← to_expr p,
note h none p,
clear h'
/-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp``
or `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an
`iff`, returns an expression with the `iff` converted to either the forwards or backwards
implication, as requested. -/
meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → option expr
| (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n))
| `(%%a ↔ %%b) f := some $ @expr.const tt iffmp [] a b (f 0)
| _ f := none
/-- `iff_mp_core e ty` assumes that `ty` is the type of `e`.
If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., A → B`. -/
meta def iff_mp_core (e ty: expr) : option expr :=
mk_iff_mp_app `iff.mp ty (λ_, e)
/-- `iff_mpr_core e ty` assumes that `ty` is the type of `e`.
If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., B → A`. -/
meta def iff_mpr_core (e ty: expr) : option expr :=
mk_iff_mp_app `iff.mpr ty (λ_, e)
/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,
create the expression which is the forward implication. -/
meta def iff_mp (e : expr) : tactic expr :=
do t ← infer_type e,
iff_mp_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`"
/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,
create the expression which is the reverse implication. -/
meta def iff_mpr (e : expr) : tactic expr :=
do t ← infer_type e,
iff_mpr_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`"
/--
Attempts to apply `e`, and if that fails, if `e` is an `iff`,
try applying both directions separately.
-/
meta def apply_iff (e : expr) : tactic (list (name × expr)) :=
let ap e := tactic.apply e {new_goals := new_goals.non_dep_only} in
ap e <|> (iff_mp e >>= ap) <|> (iff_mpr e >>= ap)
/--
Configuration options for `apply_any`:
* `use_symmetry`: if `apply_any` fails to apply any lemma, call `symmetry` and try again.
* `use_exfalso`: if `apply_any` fails to apply any lemma, call `exfalso` and try again.
* `apply`: specify an alternative to `tactic.apply`; usually `apply := tactic.eapply`.
-/
meta structure apply_any_opt :=
(use_symmetry : bool := tt)
(use_exfalso : bool := tt)
(apply : expr → tactic (list (name × expr)) := tactic.apply)
/--
This is a version of `apply_any` that takes a list of `tactic expr`s instead of `expr`s,
and evaluates these as thunks before trying to apply them.
We need to do this to avoid metavariables getting stuck during subsequent rounds of `apply`.
-/
meta def apply_any_thunk
(lemmas : list (tactic expr))
(opt : apply_any_opt := {})
(tac : tactic unit := skip) : tactic unit :=
do
let modes := [skip]
++ (if opt.use_symmetry then [symmetry] else [])
++ (if opt.use_exfalso then [exfalso] else []),
modes.any_of (λ m, do m,
lemmas.any_of (λ H, H >>= opt.apply >> tac)) <|>
fail "apply_any tactic failed; no lemma could be applied"
/--
`apply_any lemmas` tries to apply one of the list `lemmas` to the current goal.
`apply_any lemmas opt` allows control over how lemmas are applied.
`opt` has fields:
* `use_symmetry`: if no lemma applies, call `symmetry` and try again. (Defaults to `tt`.)
* `use_exfalso`: if no lemma applies, call `exfalso` and try again. (Defaults to `tt`.)
* `apply`: use a tactic other than `tactic.apply` (e.g. `tactic.fapply` or `tactic.eapply`).
`apply_any lemmas tac` calls the tactic `tac` after a successful application.
Defaults to `skip`. This is used, for example, by `solve_by_elim` to arrange
recursive invocations of `apply_any`.
-/
meta def apply_any
(lemmas : list expr)
(opt : apply_any_opt := {})
(tac : tactic unit := skip) : tactic unit :=
apply_any_thunk (lemmas.map pure) opt tac
/-- Try to apply a hypothesis from the local context to the goal. -/
meta def apply_assumption : tactic unit :=
local_context >>= apply_any
/-- `change_core e none` is equivalent to `change e`. It tries to change the goal to `e` and fails
if this is not a definitional equality.
`change_core e (some h)` assumes `h` is a local constant, and tries to change the type of `h` to `e`
by reverting `h`, changing the goal, and reintroducing hypotheses. -/
meta def change_core (e : expr) : option expr → tactic unit
| none := tactic.change e
| (some h) :=
do num_reverted : ℕ ← revert h,
expr.pi n bi d b ← target,
tactic.change $ expr.pi n bi e b,
intron num_reverted
/--
`change_with_at olde newe hyp` replaces occurences of `olde` with `newe` at hypothesis `hyp`,
assuming `olde` and `newe` are defeq when elaborated.
-/
meta def change_with_at (olde newe : pexpr) (hyp : name) : tactic unit :=
do h ← get_local hyp,
tp ← infer_type h,
olde ← to_expr olde, newe ← to_expr newe,
let repl_tp := tp.replace (λ a n, if a = olde then some newe else none),
change_core repl_tp (some h)
/-- Returns a list of all metavariables in the current partial proof. This can differ from
the list of goals, since the goals can be manually edited. -/
meta def metavariables : tactic (list expr) :=
expr.list_meta_vars <$> result
/-- Fail if the target contains a metavariable. -/
meta def no_mvars_in_target : tactic unit :=
expr.has_meta_var <$> target >>= guardb ∘ bnot
/-- Succeeds only if the current goal is a proposition. -/
meta def propositional_goal : tactic unit :=
do g :: _ ← get_goals,
is_proof g >>= guardb
/-- Succeeds only if we can construct an instance showing the
current goal is a subsingleton type. -/
meta def subsingleton_goal : tactic unit :=
do g :: _ ← get_goals,
ty ← infer_type g >>= instantiate_mvars,
to_expr ``(subsingleton %%ty) >>= mk_instance >> skip
/--
Succeeds only if the current goal is "terminal",
in the sense that no other goals depend on it
(except possibly through shared metavariables; see `independent_goal`).
-/
meta def terminal_goal : tactic unit :=
propositional_goal <|> subsingleton_goal <|>
do g₀ :: _ ← get_goals,
mvars ← (λ L, list.erase L g₀) <$> metavariables,
mvars.mmap' $ λ g, do
t ← infer_type g >>= instantiate_mvars,
d ← kdepends_on t g₀,
monad.whenb d $
pp t >>= λ s, fail ("The current goal is not terminal: " ++ s.to_string ++ " depends on it.")
/--
Succeeds only if the current goal is "independent", in the sense
that no other goals depend on it, even through shared meta-variables.
-/
meta def independent_goal : tactic unit :=
no_mvars_in_target >> terminal_goal
/-- `triv'` tries to close the first goal with the proof `trivial : true`. Unlike `triv`,
it only unfolds reducible definitions, so it sometimes fails faster. -/
meta def triv' : tactic unit := do c ← mk_const `trivial, exact c reducible
variable {α : Type}
/-- Apply a tactic as many times as possible, collecting the results in a list.
Fail if the tactic does not succeed at least once. -/
meta def iterate1 (t : tactic α) : tactic (list α) :=
do r ← decorate_ex "iterate1 failed: tactic did not succeed" t,
L ← iterate t,
return (r :: L)
/-- Introduces one or more variables and returns the new local constants.
Fails if `intro` cannot be applied. -/
meta def intros1 : tactic (list expr) :=
iterate1 intro1
/-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/
meta def under_binders {α : Type} (t : tactic α) : tactic α :=
do
v ← intros,
r ← t,
revert_lst v,
return r
namespace interactive
/-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/
meta def under_binders (i : itactic) : itactic := tactic.under_binders i
end interactive
/-- `successes` invokes each tactic in turn, returning the list of successful results. -/
meta def successes (tactics : list (tactic α)) : tactic (list α) :=
list.filter_map id <$> monad.sequence (tactics.map (λ t, try_core t))
/--
Try all the tactics in a list, each time starting at the original `tactic_state`,
returning the list of successful results,
and reverting to the original `tactic_state`.
-/
-- Note this is not the same as `successes`, which keeps track of the evolving `tactic_state`.
meta def try_all {α : Type} (tactics : list (tactic α)) : tactic (list α) :=
λ s, result.success
(tactics.map $
λ t : tactic α,
match t s with
| result.success a s' := [a]
| _ := []
end).join s
/--
Try all the tactics in a list, each time starting at the original `tactic_state`,
returning the list of successful results sorted by
the value produced by a subsequent execution of the `sort_by` tactic,
and reverting to the original `tactic_state`.
-/
meta def try_all_sorted {α : Type} (tactics : list (tactic α)) (sort_by : tactic ℕ := num_goals) :
tactic (list (α × ℕ)) :=
λ s, result.success
((tactics.map $
λ t : tactic α,
match (do a ← t, n ← sort_by, return (a, n)) s with
| result.success a s' := [a]
| _ := []
end).join.qsort (λ p q : α × ℕ, p.2 < q.2)) s
/-- Return target after instantiating metavars and whnf. -/
private meta def target' : tactic expr :=
target >>= instantiate_mvars >>= whnf
/--
Just like `split`, `fsplit` applies the constructor when the type of the target is
an inductive data type with one constructor.
However it does not reorder goals or invoke `auto_param` tactics.
-/
-- FIXME check if we can remove `auto_param := ff`
meta def fsplit : tactic unit :=
do [c] ← target' >>= get_constructors_for |
fail "fsplit tactic failed, target is not an inductive datatype with only one constructor",
mk_const c >>= λ e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip
run_cmd add_interactive [`fsplit]
add_tactic_doc
{ name := "fsplit",
category := doc_category.tactic,
decl_names := [`tactic.interactive.fsplit],
tags := ["logic", "goal management"] }
/-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection`
succeeds, clears the old hypothesis. -/
meta def injections_and_clear : tactic unit :=
do l ← local_context,
results ← successes $ l.map $ λ e, injection e >> clear e,
when (results.empty) (fail "could not use `injection` then `clear` on any hypothesis")
run_cmd add_interactive [`injections_and_clear]
add_tactic_doc
{ name := "injections_and_clear",
category := doc_category.tactic,
decl_names := [`tactic.interactive.injections_and_clear],
tags := ["context management"] }
/-- Calls `cases` on every local hypothesis, succeeding if
it succeeds on at least one hypothesis. -/
meta def case_bash : tactic unit :=
do l ← local_context,
r ← successes (l.reverse.map (λ h, cases h >> skip)),
when (r.empty) failed
/--
`note_anon t v`, given a proof `v : t`,
adds `h : t` to the current context, where the name `h` is fresh.
`note_anon none v` will infer the type `t` from `v`.
-/
-- While `note` provides a default value for `t`, it doesn't seem this could ever be used.
meta def note_anon (t : option expr) (v : expr) : tactic expr :=
do h ← get_unused_name `h none,
note h t v
/-- `find_local t` returns a local constant with type t, or fails if none exists. -/
meta def find_local (t : pexpr) : tactic expr :=
do t' ← to_expr t,
(prod.snd <$> solve_aux t' assumption >>= instantiate_mvars) <|>
fail format!"No hypothesis found of the form: {t'}"
/-- `dependent_pose_core l`: introduce dependent hypotheses, where the proofs depend on the values
of the previous local constants. `l` is a list of local constants and their values. -/
meta def dependent_pose_core (l : list (expr × expr)) : tactic unit := do
let lc := l.map prod.fst,
let lm := l.map (λ⟨l, v⟩, (l.local_uniq_name, v)),
t ← target,
new_goal ← mk_meta_var (t.pis lc),
old::other_goals ← get_goals,
set_goals (old :: new_goal :: other_goals),
exact ((new_goal.mk_app lc).instantiate_locals lm),
return ()
/-- Like `mk_local_pis` but translating into weak head normal form before checking if it is a `Π`.
-/
meta def mk_local_pis_whnf : expr → tactic (list expr × expr) | e := do
(expr.pi n bi d b) ← whnf e | return ([], e),
p ← mk_local' n bi d,
(ps, r) ← mk_local_pis (expr.instantiate_var b p),
return ((p :: ps), r)
/-- Changes `(h : ∀xs, ∃a:α, p a) ⊢ g` to `(d : ∀xs, a) (s : ∀xs, p (d xs) ⊢ g`. -/
meta def choose1 (h : expr) (data : name) (spec : name) : tactic expr := do
t ← infer_type h,
(ctxt, t) ← mk_local_pis_whnf t,
`(@Exists %%α %%p) ← whnf t transparency.all |
fail "expected a term of the shape ∀xs, ∃a, p xs a",
α_t ← infer_type α,
expr.sort u ← whnf α_t transparency.all,
value ← mk_local_def data (α.pis ctxt),
t' ← head_beta (p.app (value.mk_app ctxt)),
spec ← mk_local_def spec (t'.pis ctxt),
dependent_pose_core [
(value, ((((expr.const `classical.some [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt),
(spec, ((((expr.const `classical.some_spec [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt)],
try (tactic.clear h),
intro1,
intro1
/-- Changes `(h : ∀xs, ∃as, p as) ⊢ g` to a list of functions `as`,
and a final hypothesis on `p as`. -/
meta def choose : expr → list name → tactic unit
| h [] := fail "expect list of variables"
| h [n] := do
cnt ← revert h,
intro n,
intron (cnt - 1),
return ()
| h (n::ns) := do
v ← get_unused_name >>= choose1 h n,
choose v ns
/--
Instantiates metavariables that appear in the current goal.
-/
meta def instantiate_mvars_in_target : tactic unit :=
target >>= instantiate_mvars >>= change
/--
Instantiates metavariables in all goals.
-/
meta def instantiate_mvars_in_goals : tactic unit :=
all_goals' $ instantiate_mvars_in_target
/-- This makes sure that the execution of the tactic does not change the tactic state.
This can be helpful while using rewrite, apply, or expr munging.
Remember to instantiate your metavariables before you're done! -/
meta def lock_tactic_state {α} (t : tactic α) : tactic α
| s := match t s with
| result.success a s' := result.success a s
| result.exception msg pos s' := result.exception msg pos s
end
/-- Similar to `mk_local_pis` but make meta variables instead of
local constants. -/
meta def mk_meta_pis : expr → tactic (list expr × expr)
| (expr.pi n bi d b) := do
p ← mk_meta_var d,
(ps, r) ← mk_meta_pis (expr.instantiate_var b p),
return ((p :: ps), r)
| e := return ([], e)
end tactic
namespace lean.parser
open tactic interaction_monad
/-- `emit_command_here str` behaves as if the string `str` were placed as a user command at the
current line. -/
meta def emit_command_here (str : string) : lean.parser string :=
do (_, left) ← with_input command_like str,
return left
/-- `emit_code_here str` behaves as if the string `str` were placed at the current location in
source code. -/
meta def emit_code_here : string → lean.parser unit
| str := do left ← emit_command_here str,
if left.length = 0 then return ()
else emit_code_here left
/-- `get_current_namespace` returns the current namespace (it could be `name.anonymous`).
This function deserves a C++ implementation in core lean, and will fail if it is not called from
the body of a command (i.e. anywhere else that the `lean.parser` monad can be invoked). -/
meta def get_current_namespace : lean.parser name :=
do n ← tactic.mk_user_fresh_name,
emit_code_here $ sformat!"def {n} := ()",
nfull ← tactic.resolve_constant n,
return $ nfull.get_nth_prefix n.components.length
/-- `get_variables` returns a list of existing variable names, along with their types and binder
info. -/
meta def get_variables : lean.parser (list (name × binder_info × expr)) :=
list.map expr.get_local_const_kind <$> list_available_include_vars
/-- `get_included_variables` returns those variables `v` returned by `get_variables` which have been
"included" by an `include v` statement and are not (yet) `omit`ed. -/
meta def get_included_variables : lean.parser (list (name × binder_info × expr)) :=
do ns ← list_include_var_names,
list.filter (λ v, v.1 ∈ ns) <$> get_variables
/-- From the `lean.parser` monad, synthesize a `tactic_state` which includes all of the local
variables referenced in `es : list pexpr`, and those variables which have been `include`ed in the
local context---precisely those variables which would be ambiently accessible if we were in a
tactic-mode block where the goals had types `es.mmap to_expr`, for example.
Returns a new `ts : tactic_state` with these local variables added, and
`mappings : list (expr × expr)`, for which pairs `(var, hyp)` correspond to an existing variable
`var` and the local hypothesis `hyp` which was added to the tactic state `ts` as a result. -/
meta def synthesize_tactic_state_with_variables_as_hyps (es : list pexpr)
: lean.parser (tactic_state × list (expr × expr)) :=
do /- First, in order to get `to_expr e` to resolve declared `variables`, we add all of the
declared variables to a fake `tactic_state`, and perform the resolution. At the end,
`to_expr e` has done the work of determining which variables were actually referenced, which
we then obtain from `fe` via `expr.list_local_consts` (which, importantly, is not defined for
`pexpr`s). -/
vars ← list_available_include_vars,
fake_es ← lean.parser.of_tactic $ lock_tactic_state $ do {
/- Note that `add_local_consts_as_local_hyps` returns the mappings it generated, but we discard
them on this first pass. (We return the mappings generated by our second invocation of this
function below.) -/
add_local_consts_as_local_hyps vars,
es.mmap to_expr
},
/- Now calculate lists of a) the explicitly `include`ed variables and b) the variables which were
referenced in `e` when it was resolved to `fake_e`.
It is important that we include variables of the kind a) because we want `simp` to have access
to declared local instances, and it is important that we only restrict to variables of kind a)
and b) together since we do not to recognise a hypothesis which is posited as a `variable`
in the environment but not referenced in the `pexpr` we were passed.
One use case for this behaviour is running `simp` on the passed `pexpr`, since we do not want
simp to use arbitrary hypotheses which were declared as `variables` in the local environment
but not referenced in the expression to simplify (as one would be expect generally in tactic
mode). -/
included_vars ← list_include_var_names,
let referenced_vars := list.join $ fake_es.map $ λ e, e.list_local_consts.map expr.local_pp_name,
/- Look up the explicit `included_vars` and the `referenced_vars` (which have appeared in the
`pexpr` list which we were passed.) -/
let directly_included_vars := vars.filter $ λ var,
(var.local_pp_name ∈ included_vars) ∨ (var.local_pp_name ∈ referenced_vars),
/- Inflate the list `directly_included_vars` to include those variables which are "implicitly
included" by virtue of reference to one or multiple others. For example, given
`variables (n : ℕ) [prime n] [ih : even n]`, a reference to `n` implies that the typeclass
instance `prime n` should be included, but `ih : even n` should not. -/
let all_implicitly_included_vars :=
expr.all_implicitly_included_variables vars directly_included_vars,
/- Capture a tactic state where both of these kinds of variables have been added as local
hypotheses, and resolve `e` against this state with `to_expr`, this time for real. -/
lean.parser.of_tactic $ do {
mappings ← add_local_consts_as_local_hyps all_implicitly_included_vars,
ts ← get_state,
return (ts, mappings)
}
end lean.parser
namespace tactic
variables {α : Type}
/--
Hole command used to fill in a structure's field when specifying an instance.
In the following:
```lean
instance : monad id :=
{! !}
```
invoking the hole command "Instance Stub" ("Generate a skeleton for the structure under
construction.") produces:
```lean
instance : monad id :=
{ map := _,
map_const := _,
pure := _,
seq := _,
seq_left := _,
seq_right := _,
bind := _ }
```
-/
@[hole_command] meta def instance_stub : hole_command :=
{ name := "Instance Stub",
descr := "Generate a skeleton for the structure under construction.",
action := λ _,
do tgt ← target >>= whnf,
let cl := tgt.get_app_fn.const_name,
env ← get_env,
fs ← expanded_field_list cl,
let fs := fs.map prod.snd,
let fs := format.intercalate (",\n " : format) $ fs.map (λ fn, format!"{fn} := _"),
let out := format.to_string format!"{{ {fs} }",
return [(out,"")] }
add_tactic_doc
{ name := "instance_stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.instance_stub],
tags := ["instances"] }
/-- Like `resolve_name` except when the list of goals is
empty. In that situation `resolve_name` fails whereas
`resolve_name'` simply proceeds on a dummy goal -/
meta def resolve_name' (n : name) : tactic pexpr :=
do [] ← get_goals | resolve_name n,
g ← mk_mvar,
set_goals [g],
resolve_name n <* set_goals []
private meta def strip_prefix' (n : name) : list string → name → tactic name
| s name.anonymous := pure $ s.foldl (flip name.mk_string) name.anonymous
| s (name.mk_string a p) :=
do let n' := s.foldl (flip name.mk_string) name.anonymous,
do { n'' ← tactic.resolve_constant n',
if n'' = n
then pure n'
else strip_prefix' (a :: s) p }
<|> strip_prefix' (a :: s) p
| s n@(name.mk_numeral a p) := pure $ s.foldl (flip name.mk_string) n
/-- Strips unnecessary prefixes from a name, e.g. if a namespace is open. -/
meta def strip_prefix : name → tactic name
| n@(name.mk_string a a_1) :=
if (`_private).is_prefix_of n
then let n' := n.update_prefix name.anonymous in
n' <$ resolve_name' n' <|> pure n
else strip_prefix' n [a] a_1
| n := pure n
/-- Used to format return strings for the hole commands `match_stub` and `eqn_stub`. -/
meta def mk_patterns (t : expr) : tactic (list format) :=
do let cl := t.get_app_fn.const_name,
env ← get_env,
let fs := env.constructors_of cl,
fs.mmap $ λ f,
do { (vs,_) ← mk_const f >>= infer_type >>= mk_local_pis,
let vs := vs.filter (λ v, v.is_default_local),
vs ← vs.mmap (λ v,
do v' ← get_unused_name v.local_pp_name,
pose v' none `(()),
pure v' ),
vs.mmap' $ λ v, get_local v >>= clear,
let args := list.intersperse (" " : format) $ vs.map to_fmt,
f ← strip_prefix f,
if args.empty
then pure $ format!"| {f} := _\n"
else pure format!"| ({f} {format.join args}) := _\n" }
/--
Hole command used to generate a `match` expression.
In the following:
```lean
meta def foo (e : expr) : tactic unit :=
{! e !}
```
invoking hole command "Match Stub" ("Generate a list of equations for a `match` expression")
produces:
```lean
meta def foo (e : expr) : tactic unit :=
match e with
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
end
```
-/
@[hole_command] meta def match_stub : hole_command :=
{ name := "Match Stub",
descr := "Generate a list of equations for a `match` expression.",
action := λ es,
do [e] ← pure es | fail "expecting one expression",
e ← to_expr e,
t ← infer_type e >>= whnf,
fs ← mk_patterns t,
e ← pp e,
let out := format.to_string format!"match {e} with\n{format.join fs}end\n",
return [(out,"")] }
add_tactic_doc
{ name := "Match Stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.match_stub],
tags := ["pattern matching"] }
/--
Invoking hole command "Equations Stub" ("Generate a list of equations for a recursive definition")
in the following:
```lean
meta def foo : {! expr → tactic unit !} -- `:=` is omitted
```
produces:
```lean
meta def foo : expr → tactic unit
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
```
A similar result can be obtained by invoking "Equations Stub" on the following:
```lean
meta def foo : expr → tactic unit := -- do not forget to write `:=`!!
{! !}
```
```lean
meta def foo : expr → tactic unit := -- don't forget to erase `:=`!!
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
```
-/
@[hole_command] meta def eqn_stub : hole_command :=
{ name := "Equations Stub",
descr := "Generate a list of equations for a recursive definition.",
action := λ es,
do t ← match es with
| [t] := to_expr t
| [] := target
| _ := fail "expecting one type"
end,
e ← whnf t,
(v :: _,_) ← mk_local_pis e | fail "expecting a Pi-type",
t' ← infer_type v,
fs ← mk_patterns t',
t ← pp t,
let out :=
if es.empty then
format.to_string format!"-- do not forget to erase `:=`!!\n{format.join fs}"
else format.to_string format!"{t}\n{format.join fs}",
return [(out,"")] }
add_tactic_doc
{ name := "Equations Stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.eqn_stub],
tags := ["pattern matching"] }
/--
This command lists the constructors that can be used to satisfy the expected type.
Invoking "List Constructors" ("Show the list of constructors of the expected type")
in the following hole:
```lean
def foo : ℤ ⊕ ℕ :=
{! !}
```
produces:
```lean
def foo : ℤ ⊕ ℕ :=
{! sum.inl, sum.inr !}
```
and will display:
```lean
sum.inl : ℤ → ℤ ⊕ ℕ
sum.inr : ℕ → ℤ ⊕ ℕ
```
-/
@[hole_command] meta def list_constructors_hole : hole_command :=
{ name := "List Constructors",
descr := "Show the list of constructors of the expected type.",
action := λ es,
do t ← target >>= whnf,
(_,t) ← mk_local_pis t,
let cl := t.get_app_fn.const_name,
let args := t.get_app_args,
env ← get_env,
let cs := env.constructors_of cl,
ts ← cs.mmap $ λ c,
do { e ← mk_const c,
t ← infer_type (e.mk_app args) >>= pp,
c ← strip_prefix c,
pure format!"\n{c} : {t}\n" },
fs ← format.intercalate ", " <$> cs.mmap (strip_prefix >=> pure ∘ to_fmt),
let out := format.to_string format!"{{! {fs} !}",
trace (format.join ts).to_string,
return [(out,"")] }
add_tactic_doc
{ name := "List Constructors",
category := doc_category.hole_cmd,
decl_names := [`tactic.list_constructors_hole],
tags := ["goal information"] }
/-- Makes the declaration `classical.prop_decidable` available to type class inference.
This asserts that all propositions are decidable, but does not have computational content. -/
meta def classical : tactic unit :=
do h ← get_unused_name `_inst,
mk_const `classical.prop_decidable >>= note h none,
reset_instance_cache
open expr
/-- `mk_comp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so,
returns the expression `f ∘ g ∘ h`. -/
meta def mk_comp (v : expr) : expr → tactic expr
| (app f e) :=
if e = v then pure f
else do
guard (¬ v.occurs f) <|> fail "bad guard",
e' ← mk_comp e >>= instantiate_mvars,
f ← instantiate_mvars f,
mk_mapp ``function.comp [none,none,none,f,e']
| e :=
do guard (e = v),
t ← infer_type e,
mk_mapp ``id [t]
/--
From a lemma of the shape `∀ x, f (g x) = h x`
derive an auxiliary lemma of the form `f ∘ g = h`
for reasoning about higher-order functions.
-/
meta def mk_higher_order_type : expr → tactic expr
| (pi n bi d b@(pi _ _ _ _)) :=
do v ← mk_local_def n d,
let b' := (b.instantiate_var v),
(pi n bi d ∘ flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b'
| (pi n bi d b) :=
do v ← mk_local_def n d,
let b' := (b.instantiate_var v),
(l,r) ← match_eq b' <|> fail format!"not an equality {b'}",
l' ← mk_comp v l,
r' ← mk_comp v r,
mk_app ``eq [l',r']
| e := failed
open lean.parser interactive.types
/-- A user attribute that applies to lemmas of the shape `∀ x, f (g x) = h x`.
It derives an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions.
-/
@[user_attribute]
meta def higher_order_attr : user_attribute unit (option name) :=
{ name := `higher_order,
parser := optional ident,
descr :=
"From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the
form `f ∘ g = h` for reasoning about higher-order functions.",
after_set := some $ λ lmm _ _,
do env ← get_env,
decl ← env.get lmm,
let num := decl.univ_params.length,
let lvls := (list.iota num).map (`l).append_after,
let l : expr := expr.const lmm $ lvls.map level.param,
t ← infer_type l >>= instantiate_mvars,
t' ← mk_higher_order_type t,
(_,pr) ← solve_aux t' $ do {
intros, applyc ``_root_.funext, intro1, applyc lmm; assumption },
pr ← instantiate_mvars pr,
lmm' ← higher_order_attr.get_param lmm,
lmm' ← (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure lmm.add_prime,
add_decl $ declaration.thm lmm' lvls t' (pure pr),
copy_attribute `simp lmm lmm',
copy_attribute `functor_norm lmm lmm' }
add_tactic_doc
{ name := "higher_order",
category := doc_category.attr,
decl_names := [`tactic.higher_order_attr],
tags := ["lemma derivation"] }
attribute [higher_order map_comp_pure] map_pure
/--
Use `refine` to partially discharge the goal,
or call `fconstructor` and try again.
-/
private meta def use_aux (h : pexpr) : tactic unit :=
(focus1 (refine h >> done)) <|> (fconstructor >> use_aux)
/-- Similar to `existsi`, `use l` will use entries in `l` to instantiate existential obligations
at the beginning of a target. Unlike `existsi`, the pexprs in `l` are elaborated with respect to
the expected type.
```lean
example : ∃ x : ℤ, x = x :=
by tactic.use ``(42)
```
See the doc string for `tactic.interactive.use` for more information.
-/
protected meta def use (l : list pexpr) : tactic unit :=
focus1 $ seq' (l.mmap' $ λ h, use_aux h <|> fail format!"failed to instantiate goal with {h}")
instantiate_mvars_in_target
/-- `clear_aux_decl_aux l` clears all expressions in `l` that represent aux decls from the
local context. -/
meta def clear_aux_decl_aux : list expr → tactic unit
| [] := skip
| (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l
/-- `clear_aux_decl` clears all expressions from the local context that represent aux decls. -/
meta def clear_aux_decl : tactic unit :=
local_context >>= clear_aux_decl_aux
/-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`)
finds a list of expressions `vs` and returns `(e.mk_args (vs ++ [h]), vs)`. -/
meta def apply_at_aux (arg t : expr) : list expr → expr → expr → tactic (expr × list expr)
| vs e (pi n bi d b) :=
do { v ← mk_meta_var d,
apply_at_aux (v :: vs) (e v) (b.instantiate_var v) } <|>
(e arg, vs) <$ unify d t
| vs e _ := failed
/-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result. -/
meta def apply_at (e h : expr) : tactic unit :=
do ht ← infer_type h,
et ← infer_type e,
(h', gs') ← apply_at_aux h ht [] e et,
note h.local_pp_name none h',
clear h,
gs' ← gs'.mfilter is_assigned,
(g :: gs) ← get_goals,
set_goals (g :: gs' ++ gs)
/-- `symmetry_hyp h` applies `symmetry` on hypothesis `h`. -/
meta def symmetry_hyp (h : expr) (md := semireducible) : tactic unit :=
do tgt ← infer_type h,
env ← get_env,
let r := get_app_fn tgt,
match env.symm_for (const_name r) with
| (some symm) := do s ← mk_const symm,
apply_at s h
| none := fail "symmetry tactic failed, target is not a relation application with the expected property."
end
precedence `setup_tactic_parser`:0
/-- `setup_tactic_parser` is a user command that opens the namespaces used in writing
interactive tactics, and declares the local postfix notation `?` for `optional` and `*` for `many`.
It does *not* use the `namespace` command, so it will typically be used after
`namespace tactic.interactive`.
-/
@[user_command]
meta def setup_tactic_parser_cmd (_ : interactive.parse $ tk "setup_tactic_parser") :
lean.parser unit :=
emit_code_here "
open lean
open lean.parser
open interactive interactive.types
local postfix `?`:9001 := optional
local postfix *:9001 := many .
"
/-- `finally tac finalizer` runs `tac` first, then runs `finalizer` even if
`tac` fails. `finally tac finalizer` fails if either `tac` or `finalizer` fails. -/
meta def finally {β} (tac : tactic α) (finalizer : tactic β) : tactic α :=
λ s, match tac s with
| (result.success r s') := (finalizer >> pure r) s'
| (result.exception msg p s') := (finalizer >> result.exception msg p) s'
end
/--
`on_exception handler tac` runs `tac` first, and then runs `handler` only if `tac` failed.
-/
meta def on_exception {β} (handler : tactic β) (tac : tactic α) : tactic α | s :=
match tac s with
| result.exception msg p s' := (handler *> result.exception msg p) s'
| ok := ok
end
/-- `decorate_error add_msg tac` prepends `add_msg` to an exception produced by `tac` -/
meta def decorate_error (add_msg : string) (tac : tactic α) : tactic α | s :=
match tac s with
| result.exception msg p s :=
let msg (_ : unit) : format := match msg with
| some msg := add_msg ++ format.line ++ msg ()
| none := add_msg
end in
result.exception msg p s
| ok := ok
end
/-- Applies tactic `t`. If it succeeds, revert the state, and return the value. If it fails,
returns the error message. -/
meta def retrieve_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) :=
λ s, match t s with
| (interaction_monad.result.success a s') := result.success (sum.inl a) s
| (interaction_monad.result.exception msg' _ s') :=
result.success (sum.inr (msg'.iget ()).to_string) s
end
/-- This tactic succeeds if `t` succeeds or fails with message `msg` such that `p msg` is `tt`.
-/
meta def succeeds_or_fails_with_msg {α : Type} (t : tactic α) (p : string → bool) : tactic unit :=
do x ← retrieve_or_report_error t,
match x with
| (sum.inl _) := skip
| (sum.inr msg) := if p msg then skip else fail msg
end
add_tactic_doc
{ name := "setup_tactic_parser",
category := doc_category.cmd,
decl_names := [`tactic.setup_tactic_parser_cmd],
tags := ["parsing", "notation"] }
/-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message
of `t`. -/
meta def trace_error (msg : string) (t : tactic α) : tactic α
| s := match t s with
| (result.success r s') := result.success r s'
| (result.exception (some msg') p s') := (trace msg >> trace (msg' ()) >> result.exception (some msg') p) s'
| (result.exception none p s') := result.exception none p s'
end
/--
``trace_if_enabled `n msg`` traces the message `msg`
only if tracing is enabled for the name `n`.
Create new names registered for tracing with `declare_trace n`.
Then use `set_option trace.n true/false` to enable or disable tracing for `n`.
-/
meta def trace_if_enabled
(n : name) {α : Type u} [has_to_tactic_format α] (msg : α) : tactic unit :=
when_tracing n (trace msg)
/--
``trace_state_if_enabled `n msg`` prints the tactic state,
preceded by the optional string `msg`,
only if tracing is enabled for the name `n`.
-/
meta def trace_state_if_enabled
(n : name) (msg : string := "") : tactic unit :=
when_tracing n ((if msg = "" then skip else trace msg) >> trace_state)
/--
This combinator is for testing purposes. It succeeds if `t` fails with message `msg`,
and fails otherwise.
-/
meta def success_if_fail_with_msg {α : Type u} (t : tactic α) (msg : string) : tactic unit :=
λ s, match t s with
| (interaction_monad.result.exception msg' _ s') :=
let expected_msg := (msg'.iget ()).to_string in
if msg = expected_msg then result.success () s
else mk_exception format!"failure messages didn't match. Expected:\n{expected_msg}" none s
| (interaction_monad.result.success a s) :=
mk_exception "success_if_fail_with_msg combinator failed, given tactic succeeded" none s
end
/-- `with_local_goals gs tac` runs `tac` on the goals `gs` and then restores the
initial goals and returns the goals `tac` ended on. -/
meta def with_local_goals {α} (gs : list expr) (tac : tactic α) : tactic (α × list expr) :=
do gs' ← get_goals,
set_goals gs,
finally (prod.mk <$> tac <*> get_goals) (set_goals gs')
/-- like `with_local_goals` but discards the resulting goals -/
meta def with_local_goals' {α} (gs : list expr) (tac : tactic α) : tactic α :=
prod.fst <$> with_local_goals gs tac
/-- Representation of a proof goal that lends itself to comparison. The
following goal:
```lean
l₀ : T,
l₁ : T
⊢ ∀ v : T, foo
```
is represented as
```
(2, ∀ l₀ l₁ v : T, foo)
```
The number 2 indicates that first the two bound variables of the
`∀` are actually local constant. Comparing two such goals with `=`
rather than `=ₐ` or `is_def_eq` tells us that proof script should
not see the difference between the two.
-/
meta def packaged_goal := ℕ × expr
/-- proof state made of multiple `goal` meant for comparing
the result of running different tactics -/
meta def proof_state := list packaged_goal
meta instance goal.inhabited : inhabited packaged_goal := ⟨(0,var 0)⟩
meta instance proof_state.inhabited : inhabited proof_state :=
(infer_instance : inhabited (list packaged_goal))
/-- create a `packaged_goal` corresponding to the current goal -/
meta def get_packaged_goal : tactic packaged_goal := do
ls ← local_context,
tgt ← target >>= instantiate_mvars,
tgt ← pis ls tgt,
pure (ls.length, tgt)
/-- `goal_of_mvar g`, with `g` a meta variable, creates a
`packaged_goal` corresponding to `g` interpretted as a proof goal -/
meta def goal_of_mvar (g : expr) : tactic packaged_goal :=
with_local_goals' [g] get_packaged_goal
/-- `get_proof_state` lists the user visible goal for each goal
of the current state and for each goal, abstracts all of the
meta variables of the other gaols.
This produces a list of goals in the form of `ℕ × expr` where
the `expr` encodes the following proof state:
```lean
2 goals
l₁ : t₁,
l₂ : t₂,
l₃ : t₃
⊢ tgt₁
⊢ tgt₂
```
as
```lean
[ (3, ∀ (mv : tgt₁) (mv : tgt₂) (l₁ : t₁) (l₂ : t₂) (l₃ : t₃), tgt₁),
(0, ∀ (mv : tgt₁) (mv : tgt₂), tgt₂) ]
```
with 2 goals, the first 2 bound variables encode the meta variable
of all the goals, the next 3 (in the first goal) and 0 (in the second goal)
are the local constants.
This representation allows us to compare goals and proof states while
ignoring information like the unique name of local constants and
the equality or difference of meta variables that encode the same goal.
-/
meta def get_proof_state : tactic proof_state :=
do gs ← get_goals,
gs.mmap $ λ g, do
⟨n,g⟩ ← goal_of_mvar g,
g ← gs.mfoldl (λ g v, do
g ← kabstract g v reducible ff,
pure $ pi `goal binder_info.default `(true) g ) g,
pure (n,g)
/--
Run `tac` in a disposable proof state and return the state.
See `proof_state`, `goal` and `get_proof_state`.
-/
meta def get_proof_state_after (tac : tactic unit) : tactic (option proof_state) :=
try_core $ retrieve $ tac >> get_proof_state
open lean interactive
/-- A type alias for `tactic format`, standing for "pretty print format". -/
meta def pformat := tactic format
/-- `mk` lifts `fmt : format` to the tactic monad (`pformat`). -/
meta def pformat.mk (fmt : format) : pformat := pure fmt
/-- an alias for `pp`. -/
meta def to_pfmt {α} [has_to_tactic_format α] (x : α) : pformat :=
pp x
meta instance pformat.has_to_tactic_format : has_to_tactic_format pformat :=
⟨ id ⟩
meta instance : has_append pformat :=
⟨ λ x y, (++) <$> x <*> y ⟩
meta instance tactic.has_to_tactic_format [has_to_tactic_format α] :
has_to_tactic_format (tactic α) :=
⟨ λ x, x >>= to_pfmt ⟩
private meta def parse_pformat : string → list char → parser pexpr
| acc [] := pure ``(to_pfmt %%(reflect acc))
| acc ('\n'::s) :=
do f ← parse_pformat "" s,
pure ``(to_pfmt %%(reflect acc) ++ pformat.mk format.line ++ %%f)
| acc ('{'::'{'::s) := parse_pformat (acc ++ "{") s
| acc ('{'::s) :=
do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string,
'}'::s ← return s.to_list | fail "'}' expected",
f ← parse_pformat "" s,
pure ``(to_pfmt %%(reflect acc) ++ to_pfmt %%e ++ %%f)
| acc (c::s) := parse_pformat (acc.str c) s
reserve prefix `pformat! `:100
/-- See `format!` in `init/meta/interactive_base.lean`.
The main differences are that `pp` is called instead of `to_fmt` and that we can use
arguments of type `tactic α` in the quotations.
Now, consider the following:
```lean
e ← to_expr ``(3 + 7),
trace format!"{e}" -- outputs `has_add.add.{0} nat nat.has_add (bit1.{0} nat nat.has_one nat.has_add (has_one.one.{0} nat nat.has_one)) ...`
trace pformat!"{e}" -- outputs `3 + 7`
```
The difference is significant. And now, the following is expressible:
```lean
e ← to_expr ``(3 + 7),
trace pformat!"{e} : {infer_type e}" -- outputs `3 + 7 : ℕ`
```
See also: `trace!` and `fail!`
-/
@[user_notation]
meta def pformat_macro (_ : parse $ tk "pformat!") (s : string) : parser pexpr :=
do e ← parse_pformat "" s.to_list,
return ``(%%e : pformat)
reserve prefix `fail! `:100
/--
The combination of `pformat` and `fail`.
-/
@[user_notation]
meta def fail_macro (_ : parse $ tk "fail!") (s : string) : parser pexpr :=
do e ← pformat_macro () s,
pure ``((%%e : pformat) >>= fail)
reserve prefix `trace! `:100
/--
The combination of `pformat` and `fail`.
-/
@[user_notation]
meta def trace_macro (_ : parse $ tk "trace!") (s : string) : parser pexpr :=
do e ← pformat_macro () s,
pure ``((%%e : pformat) >>= trace)
/-- A hackish way to get the `src` directory of mathlib. -/
meta def get_mathlib_dir : tactic string :=
do e ← get_env,
s ← e.decl_olean `tactic.reset_instance_cache,
return $ s.popn_back 17
/-- Checks whether a declaration with the given name is declared in mathlib.
If you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead,
since it is expensive to execute `get_mathlib_dir` many times. -/
meta def is_in_mathlib (n : name) : tactic bool :=
do ml ← get_mathlib_dir, e ← get_env, return $ e.is_prefix_of_file ml n
/--
Runs a tactic by name.
If it is a `tactic string`, return whatever string it returns.
If it is a `tactic unit`, return the name.
(This is mostly used in invoking "self-reporting tactics", e.g. by `tidy` and `hint`.)
-/
meta def name_to_tactic (n : name) : tactic string :=
do d ← get_decl n,
e ← mk_const n,
let t := d.type,
if (t =ₐ `(tactic unit)) then
(eval_expr (tactic unit) e) >>= (λ t, t >> (name.to_string <$> strip_prefix n))
else if (t =ₐ `(tactic string)) then
(eval_expr (tactic string) e) >>= (λ t, t)
else fail!"name_to_tactic cannot take `{n} as input: its type must be `tactic string` or `tactic unit`"
/-- auxiliary function for `apply_under_n_pis` -/
private meta def apply_under_n_pis_aux (func arg : pexpr) : ℕ → ℕ → expr → pexpr
| n 0 _ :=
let vars := ((list.range n).reverse.map (@expr.var ff)),
bd := vars.foldl expr.app arg.mk_explicit in
func bd
| n (k+1) (expr.pi nm bi tp bd) := expr.pi nm bi (pexpr.of_expr tp) (apply_under_n_pis_aux (n+1) k bd)
| n (k+1) t := apply_under_n_pis_aux n 0 t
/--
Assumes `pi_expr` is of the form `Π x1 ... xn xn+1..., _`.
Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`.
All arguments (implicit and explicit) to `arg` should be supplied. -/
meta def apply_under_n_pis (func arg : pexpr) (pi_expr : expr) (n : ℕ) : pexpr :=
apply_under_n_pis_aux func arg 0 n pi_expr
/--
Assumes `pi_expr` is of the form `Π x1 ... xn, _`.
Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`.
All arguments (implicit and explicit) to `arg` should be supplied. -/
meta def apply_under_pis (func arg : pexpr) (pi_expr : expr) : pexpr :=
apply_under_n_pis func arg pi_expr pi_expr.pi_arity
/--
If `func` is a `pexpr` representing a function that takes an argument `a`,
`get_pexpr_arg_arity_with_tgt func tgt` returns the arity of `a`.
When `tgt` is a `pi` expr, `func` is elaborated in a context
with the domain of `tgt`.
Examples:
* ```get_pexpr_arg_arity ``(ring) `(true)``` returns 0, since `ring` takes one non-function argument.
* ```get_pexpr_arg_arity_with_tgt ``(monad) `(true)``` returns 1, since `monad` takes one argument of type `α → α`.
* ```get_pexpr_arg_arity_with_tgt ``(module R) `(Π (R : Type), comm_ring R → true)``` returns 0
-/
private meta def get_pexpr_arg_arity_with_tgt (func : pexpr) (tgt : expr) : tactic ℕ :=
lock_tactic_state $ do
mv ← mk_mvar,
solve_aux tgt $ intros >> to_expr ``(%%func %%mv),
expr.pi_arity <$> (instantiate_mvars mv >>= infer_type)
/--
Tries to derive instances by unfolding the newly introduced type and applying type class resolution.
For example,
```lean
@[derive ring] def new_int : Type := ℤ
```
adds an instance `ring new_int`, defined to be the instance of `ring ℤ` found by `apply_instance`.
Multiple instances can be added with `@[derive [ring, module ℝ]]`.
This derive handler applies only to declarations made using `def`, and will fail on such a
declaration if it is unable to derive an instance. It is run with higher priority than the built-in
handlers, which will fail on `def`s.
-/
@[derive_handler, priority 2000] meta def delta_instance : derive_handler :=
λ cls new_decl_name,
do env ← get_env,
if env.is_inductive new_decl_name then return ff else
do new_decl ← get_decl new_decl_name,
new_decl_pexpr ← resolve_name new_decl_name,
arity ← get_pexpr_arg_arity_with_tgt cls new_decl.type,
tgt ← to_expr $ apply_under_n_pis cls new_decl_pexpr new_decl.type (new_decl.type.pi_arity - arity),
(_, inst) ← solve_aux tgt
(intros >> reset_instance_cache >> delta_target [new_decl_name] >> apply_instance >> done),
inst ← instantiate_mvars inst,
inst ← replace_univ_metas_with_univ_params inst,
tgt ← instantiate_mvars tgt,
nm ← get_unused_decl_name $ new_decl_name <.>
match cls with
| (expr.const nm _) := nm.last
| _ := "inst"
end,
add_protected_decl $ declaration.defn nm inst.collect_univ_params tgt inst new_decl.reducibility_hints new_decl.is_trusted,
set_basic_attribute `instance nm tt,
return tt
/-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files.
`find_private_decl n (some m)` finds a private declaration named `n` in the same file where a
declaration named `m` can be found. -/
meta def find_private_decl (n : name) (fr : option name) : tactic name :=
do env ← get_env,
fn ← option_t.run (do
fr ← option_t.mk (return fr),
d ← monad_lift $ get_decl fr,
option_t.mk (return $ env.decl_olean d.to_name) ),
let p : string → bool :=
match fn with
| (some fn) := λ x, fn = x
| none := λ _, tt
end,
let xs := env.decl_filter_map (λ d,
do fn ← env.decl_olean d.to_name,
guard ((`_private).is_prefix_of d.to_name ∧ p fn ∧ d.to_name.update_prefix name.anonymous = n),
pure d.to_name),
match xs with
| [n] := pure n
| [] := fail "no such private found"
| _ := fail "many matches found"
end
open lean.parser interactive
/-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar`
and creates a local notation to refer to it.
`import_private foo` looks for `foo` in all imported files.
When possible, make `foo` non-private rather than using this feature.
-/
@[user_command]
meta def import_private_cmd (_ : parse $ tk "import_private") : lean.parser unit :=
do n ← ident,
fr ← optional (tk "from" *> ident),
n ← find_private_decl n fr,
c ← resolve_constant n,
d ← get_decl n,
let c := @expr.const tt c d.univ_levels,
new_n ← new_aux_decl_name,
add_decl $ declaration.defn new_n d.univ_params d.type c reducibility_hints.abbrev d.is_trusted,
let new_not := sformat!"local notation `{n.update_prefix name.anonymous}` := {new_n}",
emit_command_here $ new_not,
skip .
add_tactic_doc
{ name := "import_private",
category := doc_category.cmd,
decl_names := [`tactic.import_private_cmd],
tags := ["renaming"] }
/--
The command `mk_simp_attribute simp_name "description"` creates a simp set with name `simp_name`.
Lemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called.
`mk_simp_attribute simp_name none` will use a default description.
Appending the command with `with attr1 attr2 ...` will include all declarations tagged with
`attr1`, `attr2`, ... in the new simp set.
This command is preferred to using ``run_cmd mk_simp_attr `simp_name`` since it adds a doc string
to the attribute that is defined. If you need to create a simp set in a file where this command is
not available, you should use
```lean
run_cmd mk_simp_attr `simp_name
run_cmd add_doc_string `simp_attr.simp_name "Description of the simp set here"
```
-/
@[user_command]
meta def mk_simp_attribute_cmd (_ : parse $ tk "mk_simp_attribute") : lean.parser unit :=
do n ← ident,
d ← parser.pexpr,
d ← to_expr ``(%%d : option string),
descr ← eval_expr (option string) d,
with_list ← types.with_ident_list <|> return [],
mk_simp_attr n with_list,
add_doc_string (name.append `simp_attr n) $ descr.get_or_else $ "simp set for " ++ to_string n
add_tactic_doc
{ name := "mk_simp_attribute",
category := doc_category.cmd,
decl_names := [`tactic.mk_simp_attribute_cmd],
tags := ["simplification"] }
end tactic
|
234ea780534d98c74684092b60f291defb23cf37 | 3dd1b66af77106badae6edb1c4dea91a146ead30 | /tests/lean/run/tactic9.lean | 3cc5dea3132265c82c9fd31fb19920f663420ad8 | [
"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 | 180 | lean | import standard
using tactic
theorem tst {A B : Prop} (H1 : A) (H2 : B) : ((fun x : Prop, x) A) ∧ B ∧ A
:= by apply and_intro; beta; assumption; apply and_intro; !assumption
|
8b336ee7e7c80f048235410f818611d35c447855 | 82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7 | /stage0/src/Lean/PrettyPrinter/Formatter.lean | 468269ff96def792f177738a75baba2ba2fc8ae2 | [
"Apache-2.0"
] | permissive | banksonian/lean4 | 3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc | 78da6b3aa2840693eea354a41e89fc5b212a5011 | refs/heads/master | 1,673,703,624,165 | 1,605,123,551,000 | 1,605,123,551,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 20,980 | lean | /-
Copyright (c) 2020 Sebastian Ullrich. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
-/
/-!
The formatter turns a `Syntax` tree into a `Format` object, inserting both mandatory whitespace (to separate adjacent
tokens) as well as "pretty" optional whitespace.
The basic approach works much like the parenthesizer: A right-to-left traversal over the syntax tree, driven by
parser-specific handlers registered via attributes. The traversal is right-to-left so that when emitting a token, we
already know the text following it and can decide whether or not whitespace between the two is necessary.
-/
import Lean.CoreM
import Lean.Parser.Extension
import Lean.KeyedDeclsAttribute
import Lean.ParserCompiler.Attribute
import Lean.PrettyPrinter.Basic
namespace Lean
namespace PrettyPrinter
namespace Formatter
structure Context :=
(options : Options)
(table : Parser.TokenTable)
structure State :=
(stxTrav : Syntax.Traverser)
-- Textual content of `stack` up to the first whitespace (not enclosed in an escaped ident). We assume that the textual
-- content of `stack` is modified only by `pushText` and `pushLine`, so `leadWord` is adjusted there accordingly.
(leadWord : String := "")
-- Stack of generated Format objects, analogous to the Syntax stack in the parser.
-- Note, however, that the stack is reversed because of the right-to-left traversal.
(stack : Array Format := #[])
end Formatter
abbrev FormatterM := ReaderT Formatter.Context $ StateRefT Formatter.State CoreM
@[inline] def FormatterM.orelse {α} (p₁ p₂ : FormatterM α) : FormatterM α := do
let s ← get
catchInternalId backtrackExceptionId
p₁
(fun _ => do set s; p₂)
instance {α} : OrElse (FormatterM α) := ⟨FormatterM.orelse⟩
abbrev Formatter := FormatterM Unit
unsafe def mkFormatterAttribute : IO (KeyedDeclsAttribute Formatter) :=
KeyedDeclsAttribute.init {
builtinName := `builtinFormatter,
name := `formatter,
descr := "Register a formatter for a parser.
[formatter k] registers a declaration of type `Lean.PrettyPrinter.Formatter` for the `SyntaxNodeKind` `k`.",
valueTypeName := `Lean.PrettyPrinter.Formatter,
evalKey := fun builtin args => do
let env ← getEnv
match attrParamSyntaxToIdentifier args with
| some id =>
-- `isValidSyntaxNodeKind` is updated only in the next stage for new `[builtin*Parser]`s, but we try to
-- synthesize a formatter for it immediately, so we just check for a declaration in this case
if (builtin && (env.find? id).isSome) || Parser.isValidSyntaxNodeKind env id then pure id
else throwError ("invalid [formatter] argument, unknown syntax kind '" ++ toString id ++ "'")
| none => throwError "invalid [formatter] argument, expected identifier"
} `Lean.PrettyPrinter.formatterAttribute
@[builtinInit mkFormatterAttribute] constant formatterAttribute : KeyedDeclsAttribute Formatter := arbitrary _
unsafe def mkCombinatorFormatterAttribute : IO ParserCompiler.CombinatorAttribute :=
ParserCompiler.registerCombinatorAttribute
`combinatorFormatter
"Register a formatter for a parser combinator.
[combinatorFormatter c] registers a declaration of type `Lean.PrettyPrinter.Formatter` for the `Parser` declaration `c`.
Note that, unlike with [formatter], this is not a node kind since combinators usually do not introduce their own node kinds.
The tagged declaration may optionally accept parameters corresponding to (a prefix of) those of `c`, where `Parser` is replaced
with `Formatter` in the parameter types."
@[builtinInit mkCombinatorFormatterAttribute] constant combinatorFormatterAttribute : ParserCompiler.CombinatorAttribute := arbitrary _
namespace Formatter
open Lean.Core
open Lean.Parser
def throwBacktrack {α} : FormatterM α :=
throw $ Exception.internal backtrackExceptionId
instance : Syntax.MonadTraverser FormatterM := ⟨{
get := State.stxTrav <$> get,
set := fun t => modify (fun st => { st with stxTrav := t }),
modifyGet := fun f => modifyGet (fun st => let (a, t) := f st.stxTrav; (a, { st with stxTrav := t }))
}⟩
open Syntax.MonadTraverser
def getStack : FormatterM (Array Format) := do
let st ← get
pure st.stack
def getStackSize : FormatterM Nat := do
let stack ← getStack;
pure stack.size
def setStack (stack : Array Format) : FormatterM Unit :=
modify fun st => { st with stack := stack }
def push (f : Format) : FormatterM Unit :=
modify fun st => { st with stack := st.stack.push f }
def pushLine : FormatterM Unit := do
push Format.line;
modify fun st => { st with leadWord := "" }
/-- Execute `x` at the right-most child of the current node, if any, then advance to the left. -/
def visitArgs (x : FormatterM Unit) : FormatterM Unit := do
let stx ← getCur
if stx.getArgs.size > 0 then
goDown (stx.getArgs.size - 1) *> x <* goUp
goLeft
/-- Execute `x`, pass array of generated Format objects to `fn`, and push result. -/
def fold (fn : Array Format → Format) (x : FormatterM Unit) : FormatterM Unit := do
let sp ← getStackSize
x
let stack ← getStack
let f := fn $ stack.extract sp stack.size
setStack $ (stack.shrink sp).push f
/-- Execute `x` and concatenate generated Format objects. -/
def concat (x : FormatterM Unit) : FormatterM Unit := do
fold (Array.foldl (fun acc f => if acc.isNil then f else f ++ acc) Format.nil) x
def indent (x : Formatter) (indent : Option Int := none) : Formatter := do
concat x
let ctx ← read
let indent := indent.getD $ Format.getIndent ctx.options
modify fun st => { st with stack := st.stack.pop.push (Format.nest indent st.stack.back) }
def group (x : Formatter) : Formatter := do
concat x
modify fun st => { st with stack := st.stack.pop.push (Format.fill st.stack.back) }
@[combinatorFormatter Lean.Parser.orelse] def orelse.formatter (p1 p2 : Formatter) : Formatter :=
-- HACK: We have no (immediate) information on which side of the orelse could have produced the current node, so try
-- them in turn. Uses the syntax traverser non-linearly!
p1 <|> p2
-- `mkAntiquot` is quite complex, so we'd rather have its formatter synthesized below the actual parser definition.
-- Note that there is a mutual recursion
-- `categoryParser -> mkAntiquot -> termParser -> categoryParser`, so we need to introduce an indirection somewhere
-- anyway.
@[extern "lean_mk_antiquot_formatter"]
constant mkAntiquot.formatter' (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Formatter
-- break up big mutual recursion
@[extern "lean_pretty_printer_formatter_interpret_parser_descr"]
constant interpretParserDescr' : ParserDescr → CoreM Formatter := arbitrary _
unsafe def formatterForKindUnsafe (k : SyntaxNodeKind) : Formatter := do
(← liftM $ runForNodeKind formatterAttribute k interpretParserDescr')
@[implementedBy formatterForKindUnsafe]
constant formatterForKind (k : SyntaxNodeKind) : Formatter := arbitrary _
@[combinatorFormatter Lean.Parser.withAntiquot]
def withAntiquot.formatter (antiP p : Formatter) : Formatter :=
-- TODO: could be optimized using `isAntiquot` (which would have to be moved), but I'd rather
-- fix the backtracking hack outright.
orelse.formatter antiP p
@[combinatorFormatter Lean.Parser.categoryParser]
def categoryParser.formatter (cat : Name) : Formatter := group $ indent do
let stx ← getCur
if stx.getKind == `choice then
visitArgs do
let stx ← getCur;
let sp ← getStackSize
stx.getArgs.forM fun stx => formatterForKind stx.getKind
let stack ← getStack
if stack.size > sp && stack[sp:stack.size].any fun f => f.pretty != (stack.get! sp).pretty then
panic! "Formatter.visit: inequal choice children";
-- discard all but one child format
setStack $ stack.extract 0 (sp+1)
else
withAntiquot.formatter (mkAntiquot.formatter' cat.toString none) (formatterForKind stx.getKind)
@[combinatorFormatter Lean.Parser.categoryParserOfStack]
def categoryParserOfStack.formatter (offset : Nat) : Formatter := do
let st ← get
let stx := st.stxTrav.parents.back.getArg (st.stxTrav.idxs.back - offset)
categoryParser.formatter stx.getId
@[combinatorFormatter Lean.Parser.error]
def error.formatter (msg : String) : Formatter := pure ()
@[combinatorFormatter Lean.Parser.errorAtSavedPos]
def errorAtSavedPos.formatter (msg : String) (delta : Bool) : Formatter := pure ()
@[combinatorFormatter Lean.Parser.try]
def try.formatter (p : Formatter) : Formatter := p
@[combinatorFormatter Lean.Parser.lookahead]
def lookahead.formatter (p : Formatter) : Formatter := pure ()
@[combinatorFormatter Lean.Parser.notFollowedBy]
def notFollowedBy.formatter (p : Formatter) : Formatter := pure ()
@[combinatorFormatter Lean.Parser.andthen]
def andthen.formatter (p1 p2 : Formatter) : Formatter := p2 *> p1
def checkKind (k : SyntaxNodeKind) : FormatterM Unit := do
let stx ← getCur
if k != stx.getKind then
trace[PrettyPrinter.format.backtrack]! "unexpected node kind '{stx.getKind}', expected '{k}'"
throwBacktrack
@[combinatorFormatter Lean.Parser.node]
def node.formatter (k : SyntaxNodeKind) (p : Formatter) : Formatter := do
checkKind k;
visitArgs p
@[combinatorFormatter Lean.Parser.trailingNode]
def trailingNode.formatter (k : SyntaxNodeKind) (_ : Nat) (p : Formatter) : Formatter := do
checkKind k
visitArgs do
p;
-- leading term, not actually produced by `p`
categoryParser.formatter `foo
def parseToken (s : String) : FormatterM ParserState := do
let ctx ← read
let env ← getEnv
pure $ Parser.tokenFn { input := s, fileName := "", fileMap := FileMap.ofString "", prec := 0, env := env, tokens := ctx.table } (Parser.mkParserState s)
def pushTokenCore (tk : String) : FormatterM Unit := do
if tk.toSubstring.dropRightWhile (fun s => s == ' ') == tk.toSubstring then
push tk
else
pushLine
push tk.trimRight
def pushToken (tk : String) : FormatterM Unit := do
let st ← get
-- If there is no space between `tk` and the next word, see if we would parse more than `tk` as a single token
if st.leadWord != "" && tk.trimRight == tk then
let tk' := tk.trimLeft
let t ← parseToken $ tk' ++ st.leadWord
if t.pos <= tk'.bsize then
-- stopped within `tk` => use it as is, extend `leadWord` if not prefixed by whitespace
pushTokenCore tk
modify fun st => { st with leadWord := if tk.trimLeft == tk then tk ++ st.leadWord else "" }
else
-- stopped after `tk` => add space
pushTokenCore $ tk ++ " "
modify fun st => { st with leadWord := if tk.trimLeft == tk then tk else "" }
else
-- already separated => use `tk` as is
pushTokenCore tk
modify fun st => { st with leadWord := if tk.trimLeft == tk then tk else "" }
@[combinatorFormatter Lean.Parser.symbol]
def symbol.formatter (sym : String) : Formatter := do
let stx ← getCur
if stx.isToken sym then do
pushToken sym;
goLeft
else do
trace[PrettyPrinter.format.backtrack]! "unexpected syntax '{stx}', expected symbol '{sym}'"
throwBacktrack
@[combinatorFormatter Lean.Parser.nonReservedSymbol] def nonReservedSymbol.formatter := symbol.formatter
@[combinatorFormatter Lean.Parser.unicodeSymbol]
def unicodeSymbol.formatter (sym asciiSym : String) : Formatter := do
let stx ← getCur
let Syntax.atom _ val ← pure stx
| throwError $ "not an atom: " ++ toString stx
if val == sym.trim then
pushToken sym
else
pushToken asciiSym;
goLeft
@[combinatorFormatter Lean.Parser.identNoAntiquot]
def identNoAntiquot.formatter : Formatter := do
checkKind identKind;
let stx ← getCur
let id := stx.getId
let id := id.simpMacroScopes
let s := id.toString;
if id.isAnonymous then
pushToken "[anonymous]"
else if isInaccessibleUserName id || id.components.any Name.isNum ||
-- loose bvar
"#".isPrefixOf s then
-- not parsable anyway, output as-is
pushToken s
else
-- try to parse `s` as-is; if it fails, escape
let pst ← parseToken s
if pst.stxStack == #[stx] then
pushToken s
else
let n := stx.getId
-- TODO: do something better than escaping all parts
let n := (n.components.map fun c => "«" ++ toString c ++ "»").foldl Name.mkStr Name.anonymous
pushToken n.toString
goLeft
@[combinatorFormatter Lean.Parser.rawIdent] def rawIdent.formatter : Formatter := do
checkKind identKind
let stx ← getCur
pushToken stx.getId.toString;
goLeft
@[combinatorFormatter Lean.Parser.identEq] def identEq.formatter (id : Name) := rawIdent.formatter
def visitAtom (k : SyntaxNodeKind) : Formatter := do
let stx ← getCur
if k != Name.anonymous then
checkKind k
let Syntax.atom _ val ← pure $ stx.ifNode (fun n => n.getArg 0) (fun _ => stx)
| throwError $ "not an atom: " ++ toString stx
pushToken val
goLeft
@[combinatorFormatter Lean.Parser.charLitNoAntiquot] def charLitNoAntiquot.formatter := visitAtom charLitKind
@[combinatorFormatter Lean.Parser.strLitNoAntiquot] def strLitNoAntiquot.formatter := visitAtom strLitKind
@[combinatorFormatter Lean.Parser.nameLitNoAntiquot] def nameLitNoAntiquot.formatter := visitAtom nameLitKind
@[combinatorFormatter Lean.Parser.numLitNoAntiquot] def numLitNoAntiquot.formatter := visitAtom numLitKind
@[combinatorFormatter Lean.Parser.fieldIdx] def fieldIdx.formatter := visitAtom fieldIdxKind
@[combinatorFormatter Lean.Parser.many]
def many.formatter (p : Formatter) : Formatter := do
let stx ← getCur
visitArgs $ stx.getArgs.size.forM fun _ => p
@[combinatorFormatter Lean.Parser.many1] def many1.formatter (p : Formatter) : Formatter := many.formatter p
@[combinatorFormatter Lean.Parser.optional]
def optional.formatter (p : Formatter) : Formatter := visitArgs p
@[combinatorFormatter Lean.Parser.many1Unbox]
def many1Unbox.formatter (p : Formatter) : Formatter := do
let stx ← getCur
if stx.getKind == nullKind then do
many.formatter p
else
p
@[combinatorFormatter Lean.Parser.sepBy]
def sepBy.formatter (p pSep : Formatter) : Formatter := do
let stx ← getCur
visitArgs $ (List.range stx.getArgs.size).reverse.forM $ fun i => if i % 2 == 0 then p else pSep
@[combinatorFormatter Lean.Parser.sepBy1] def sepBy1.formatter := sepBy.formatter
@[combinatorFormatter Lean.Parser.withPosition] def withPosition.formatter (p : Formatter) : Formatter := p
@[combinatorFormatter Lean.Parser.withoutPosition] def withoutPosition.formatter (p : Formatter) : Formatter := p
@[combinatorFormatter Lean.Parser.withForbidden] def withForbidden.formatter (tk : Token) (p : Formatter) : Formatter := p
@[combinatorFormatter Lean.Parser.withoutForbidden] def withoutForbidden.formatter (p : Formatter) : Formatter := p
@[combinatorFormatter Lean.Parser.setExpected]
def setExpected.formatter (expected : List String) (p : Formatter) : Formatter := p
@[combinatorFormatter Lean.Parser.toggleInsideQuot] def toggleInsideQuot.formatter (p : Formatter) : Formatter := p
@[combinatorFormatter Lean.Parser.suppressInsideQuot] def suppressInsideQuot.formatter (p : Formatter) : Formatter := p
@[combinatorFormatter Lean.Parser.checkWsBefore] def checkWsBefore.formatter : Formatter := do
let st ← get
if st.leadWord != "" then
pushLine
@[combinatorFormatter Lean.Parser.checkPrec] def checkPrec.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.checkStackTop] def checkStackTop.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.checkNoWsBefore] def checkNoWsBefore.formatter : Formatter :=
-- prevent automatic whitespace insertion
modify fun st => { st with leadWord := "" }
@[combinatorFormatter Lean.Parser.checkTailWs] def checkTailWs.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.checkColGe] def checkColGe.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.checkColGt] def checkColGt.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.checkLineEq] def checkLineEq.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.eoi] def eoi.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.notFollowedByCategoryToken] def notFollowedByCategoryToken.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.checkNoImmediateColon] def checkNoImmediateColon.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.checkInsideQuot] def checkInsideQuot.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.checkOutsideQuot] def checkOutsideQuot.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.skip] def skip.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.pushNone] def pushNone.formatter : Formatter := goLeft
@[combinatorFormatter Lean.Parser.interpolatedStr]
def interpolatedStr.formatter (p : Formatter) : Formatter := do
visitArgs $ (← getCur).getArgs.reverse.forM fun chunk =>
match chunk.isLit? interpolatedStrLitKind with
| some str => push str *> goLeft
| none => p
@[combinatorFormatter ite, macroInline] def ite {α : Type} (c : Prop) [h : Decidable c] (t e : Formatter) : Formatter :=
if c then t else e
@[export lean_pretty_printer_formatter_interpret_parser_descr]
unsafe def interpretParserDescr : ParserDescr → CoreM Formatter
| ParserDescr.andthen d₁ d₂ => andthen.formatter <$> interpretParserDescr d₁ <*> interpretParserDescr d₂
| ParserDescr.orelse d₁ d₂ => orelse.formatter <$> interpretParserDescr d₁ <*> interpretParserDescr d₂
| ParserDescr.optional d => optional.formatter <$> interpretParserDescr d
| ParserDescr.lookahead d => lookahead.formatter <$> interpretParserDescr d
| ParserDescr.try d => try.formatter <$> interpretParserDescr d
| ParserDescr.notFollowedBy d => notFollowedBy.formatter <$> interpretParserDescr d
| ParserDescr.many d => many.formatter <$> interpretParserDescr d
| ParserDescr.many1 d => many1.formatter <$> interpretParserDescr d
| ParserDescr.sepBy d₁ d₂ _ => sepBy.formatter <$> interpretParserDescr d₁ <*> interpretParserDescr d₂
| ParserDescr.sepBy1 d₁ d₂ _ => sepBy1.formatter <$> interpretParserDescr d₁ <*> interpretParserDescr d₂
| ParserDescr.node k prec d => node.formatter k <$> interpretParserDescr d
| ParserDescr.trailingNode k prec d => trailingNode.formatter k prec <$> interpretParserDescr d
| ParserDescr.symbol tk => pure $ symbol.formatter tk
| ParserDescr.numLit => pure $ withAntiquot.formatter (mkAntiquot.formatter' "numLit" `numLit) numLitNoAntiquot.formatter
| ParserDescr.strLit => pure $ withAntiquot.formatter (mkAntiquot.formatter' "strLit" `strLit) strLitNoAntiquot.formatter
| ParserDescr.charLit => pure $ withAntiquot.formatter (mkAntiquot.formatter' "charLit" `charLit) charLitNoAntiquot.formatter
| ParserDescr.nameLit => pure $ withAntiquot.formatter (mkAntiquot.formatter' "nameLit" `nameLit) nameLitNoAntiquot.formatter
| ParserDescr.ident => pure $ withAntiquot.formatter (mkAntiquot.formatter' "ident" `ident) identNoAntiquot.formatter
| ParserDescr.interpolatedStr d => interpolatedStr.formatter <$> interpretParserDescr d
| ParserDescr.nonReservedSymbol tk includeIdent => pure $ nonReservedSymbol.formatter tk
| ParserDescr.noWs => pure $ checkNoWsBefore.formatter
| ParserDescr.withPosition d => withPosition.formatter <$> interpretParserDescr d
| ParserDescr.checkCol strict => pure $ if strict then checkColGt.formatter else checkColGe.formatter
| ParserDescr.parser constName => combinatorFormatterAttribute.runDeclFor constName
| ParserDescr.cat catName prec => pure $ categoryParser.formatter catName
end Formatter
open Formatter
def format (formatter : Formatter) (stx : Syntax) : CoreM Format := do
let options ← getOptions
let table ← Parser.builtinTokenTable.get
catchInternalId backtrackExceptionId
(do
let (_, st) ← (concat formatter { table := table, options := options }).run { stxTrav := Syntax.Traverser.fromSyntax stx };
pure $ Format.fill $ st.stack.get! 0)
(fun _ => throwError "format: uncaught backtrack exception")
def formatTerm := format $ categoryParser.formatter `term
def formatCommand := format $ categoryParser.formatter `command
builtin_initialize registerTraceClass `PrettyPrinter.format;
end PrettyPrinter
end Lean
|
8cad8eff5cf9b55ef875d27f33e73eae22210dc7 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/category/Group/basic.lean | a03a9c64f8360d58bc05b2bd7438e8a59c2a4b98 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 10,246 | lean | /-
Copyright (c) 2018 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import algebra.category.Mon.basic
import category_theory.endomorphism
/-!
# Category instances for group, add_group, comm_group, and add_comm_group.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We introduce the bundled categories:
* `Group`
* `AddGroup`
* `CommGroup`
* `AddCommGroup`
along with the relevant forgetful functors between them, and to the bundled monoid categories.
-/
universes u v
open category_theory
/-- The category of groups and group morphisms. -/
@[to_additive AddGroup]
def Group : Type (u+1) := bundled group
/-- The category of additive groups and group morphisms -/
add_decl_doc AddGroup
namespace Group
@[to_additive]
instance : bundled_hom.parent_projection group.to_monoid := ⟨⟩
attribute [derive [large_category, concrete_category]] Group
attribute [to_additive] Group.large_category Group.concrete_category
@[to_additive] instance : has_coe_to_sort Group Type* := bundled.has_coe_to_sort
/-- Construct a bundled `Group` from the underlying type and typeclass. -/
@[to_additive] def of (X : Type u) [group X] : Group := bundled.of X
/-- Construct a bundled `AddGroup` from the underlying type and typeclass. -/
add_decl_doc AddGroup.of
/-- Typecheck a `monoid_hom` as a morphism in `Group`. -/
@[to_additive] def of_hom {X Y : Type u} [group X] [group Y] (f : X →* Y) : of X ⟶ of Y := f
/-- Typecheck a `add_monoid_hom` as a morphism in `AddGroup`. -/
add_decl_doc AddGroup.of_hom
@[simp, to_additive] lemma of_hom_apply {X Y : Type*} [group X] [group Y] (f : X →* Y) (x : X) :
of_hom f x = f x := rfl
@[to_additive]
instance (G : Group) : group G := G.str
@[simp, to_additive] lemma coe_of (R : Type u) [group R] : (Group.of R : Type u) = R := rfl
@[to_additive]
instance : inhabited Group := ⟨Group.of punit⟩
@[to_additive]
instance of_unique (G : Type*) [group G] [i : unique G] : unique (Group.of G) := i
@[simp, to_additive]
lemma one_apply (G H : Group) (g : G) : (1 : G ⟶ H) g = 1 := rfl
@[ext, to_additive]
lemma ext (G H : Group) (f₁ f₂ : G ⟶ H) (w : ∀ x, f₁ x = f₂ x) : f₁ = f₂ :=
by { ext1, apply w }
@[to_additive has_forget_to_AddMon]
instance has_forget_to_Mon : has_forget₂ Group Mon := bundled_hom.forget₂ _ _
@[to_additive] instance : has_coe Group.{u} Mon.{u} :=
{ coe := (forget₂ Group Mon).obj, }
end Group
/-- The category of commutative groups and group morphisms. -/
@[to_additive AddCommGroup]
def CommGroup : Type (u+1) := bundled comm_group
/-- The category of additive commutative groups and group morphisms. -/
add_decl_doc AddCommGroup
/-- `Ab` is an abbreviation for `AddCommGroup`, for the sake of mathematicians' sanity. -/
abbreviation Ab := AddCommGroup
namespace CommGroup
@[to_additive]
instance : bundled_hom.parent_projection comm_group.to_group := ⟨⟩
attribute [derive [large_category, concrete_category]] CommGroup
attribute [to_additive] CommGroup.large_category CommGroup.concrete_category
@[to_additive] instance : has_coe_to_sort CommGroup Type* := bundled.has_coe_to_sort
/-- Construct a bundled `CommGroup` from the underlying type and typeclass. -/
@[to_additive] def of (G : Type u) [comm_group G] : CommGroup := bundled.of G
/-- Construct a bundled `AddCommGroup` from the underlying type and typeclass. -/
add_decl_doc AddCommGroup.of
/-- Typecheck a `monoid_hom` as a morphism in `CommGroup`. -/
@[to_additive] def of_hom {X Y : Type u} [comm_group X] [comm_group Y] (f : X →* Y) :
of X ⟶ of Y := f
/-- Typecheck a `add_monoid_hom` as a morphism in `AddCommGroup`. -/
add_decl_doc AddCommGroup.of_hom
@[simp, to_additive] lemma of_hom_apply {X Y : Type*} [comm_group X] [comm_group Y] (f : X →* Y)
(x : X) : of_hom f x = f x := rfl
@[to_additive]
instance comm_group_instance (G : CommGroup) : comm_group G := G.str
@[simp, to_additive] lemma coe_of (R : Type u) [comm_group R] : (CommGroup.of R : Type u) = R := rfl
@[to_additive]
instance : inhabited CommGroup := ⟨CommGroup.of punit⟩
@[to_additive]
instance of_unique (G : Type*) [comm_group G] [i : unique G] : unique (CommGroup.of G) := i
@[simp, to_additive]
lemma one_apply (G H : CommGroup) (g : G) : (1 : G ⟶ H) g = 1 := rfl
@[ext, to_additive]
lemma ext (G H : CommGroup) (f₁ f₂ : G ⟶ H) (w : ∀ x, f₁ x = f₂ x) : f₁ = f₂ :=
by { ext1, apply w }
@[to_additive has_forget_to_AddGroup]
instance has_forget_to_Group : has_forget₂ CommGroup Group := bundled_hom.forget₂ _ _
@[to_additive] instance : has_coe CommGroup.{u} Group.{u} :=
{ coe := (forget₂ CommGroup Group).obj, }
@[to_additive has_forget_to_AddCommMon]
instance has_forget_to_CommMon : has_forget₂ CommGroup CommMon :=
induced_category.has_forget₂ (λ G : CommGroup, CommMon.of G)
@[to_additive] instance : has_coe CommGroup.{u} CommMon.{u} :=
{ coe := (forget₂ CommGroup CommMon).obj, }
end CommGroup
-- This example verifies an improvement possible in Lean 3.8.
-- Before that, to have `monoid_hom.map_map` usable by `simp` here,
-- we had to mark all the concrete category `has_coe_to_sort` instances reducible.
-- Now, it just works.
@[to_additive]
example {R S : CommGroup} (i : R ⟶ S) (r : R) (h : r = 1) : i r = 1 :=
by simp [h]
namespace AddCommGroup
/-- Any element of an abelian group gives a unique morphism from `ℤ` sending
`1` to that element. -/
-- Note that because `ℤ : Type 0`, this forces `G : AddCommGroup.{0}`,
-- so we write this explicitly to be clear.
-- TODO generalize this, requiring a `ulift_instances.lean` file
def as_hom {G : AddCommGroup.{0}} (g : G) : (AddCommGroup.of ℤ) ⟶ G :=
zmultiples_hom G g
@[simp]
lemma as_hom_apply {G : AddCommGroup.{0}} (g : G) (i : ℤ) : (as_hom g) i = i • g := rfl
lemma as_hom_injective {G : AddCommGroup.{0}} : function.injective (@as_hom G) :=
λ h k w, by convert congr_arg (λ k : (AddCommGroup.of ℤ) ⟶ G, (k : ℤ → G) (1 : ℤ)) w; simp
@[ext]
lemma int_hom_ext
{G : AddCommGroup.{0}} (f g : (AddCommGroup.of ℤ) ⟶ G) (w : f (1 : ℤ) = g (1 : ℤ)) : f = g :=
add_monoid_hom.ext_int w
-- TODO: this argument should be generalised to the situation where
-- the forgetful functor is representable.
lemma injective_of_mono {G H : AddCommGroup.{0}} (f : G ⟶ H) [mono f] : function.injective f :=
λ g₁ g₂ h,
begin
have t0 : as_hom g₁ ≫ f = as_hom g₂ ≫ f :=
begin
ext,
simpa [as_hom_apply] using h,
end,
have t1 : as_hom g₁ = as_hom g₂ := (cancel_mono _).1 t0,
apply as_hom_injective t1,
end
end AddCommGroup
/-- Build an isomorphism in the category `Group` from a `mul_equiv` between `group`s. -/
@[to_additive add_equiv.to_AddGroup_iso, simps]
def mul_equiv.to_Group_iso {X Y : Group} (e : X ≃* Y) : X ≅ Y :=
{ hom := e.to_monoid_hom,
inv := e.symm.to_monoid_hom }
/-- Build an isomorphism in the category `AddGroup` from an `add_equiv` between `add_group`s. -/
add_decl_doc add_equiv.to_AddGroup_iso
/-- Build an isomorphism in the category `CommGroup` from a `mul_equiv` between `comm_group`s. -/
@[to_additive add_equiv.to_AddCommGroup_iso, simps]
def mul_equiv.to_CommGroup_iso {X Y : CommGroup} (e : X ≃* Y) : X ≅ Y :=
{ hom := e.to_monoid_hom,
inv := e.symm.to_monoid_hom }
/-- Build an isomorphism in the category `AddCommGroup` from a `add_equiv` between
`add_comm_group`s. -/
add_decl_doc add_equiv.to_AddCommGroup_iso
namespace category_theory.iso
/-- Build a `mul_equiv` from an isomorphism in the category `Group`. -/
@[to_additive AddGroup_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category
`AddGroup`.", simps]
def Group_iso_to_mul_equiv {X Y : Group} (i : X ≅ Y) : X ≃* Y :=
i.hom.to_mul_equiv i.inv i.hom_inv_id i.inv_hom_id
/-- Build a `mul_equiv` from an isomorphism in the category `CommGroup`. -/
@[to_additive AddCommGroup_iso_to_add_equiv "Build an `add_equiv` from an isomorphism
in the category `AddCommGroup`.", simps]
def CommGroup_iso_to_mul_equiv {X Y : CommGroup} (i : X ≅ Y) : X ≃* Y :=
i.hom.to_mul_equiv i.inv i.hom_inv_id i.inv_hom_id
end category_theory.iso
/-- multiplicative equivalences between `group`s are the same as (isomorphic to) isomorphisms
in `Group` -/
@[to_additive add_equiv_iso_AddGroup_iso "additive equivalences between `add_group`s are the same
as (isomorphic to) isomorphisms in `AddGroup`"]
def mul_equiv_iso_Group_iso {X Y : Group.{u}} : (X ≃* Y) ≅ (X ≅ Y) :=
{ hom := λ e, e.to_Group_iso,
inv := λ i, i.Group_iso_to_mul_equiv, }
/-- multiplicative equivalences between `comm_group`s are the same as (isomorphic to) isomorphisms
in `CommGroup` -/
@[to_additive add_equiv_iso_AddCommGroup_iso "additive equivalences between `add_comm_group`s are
the same as (isomorphic to) isomorphisms in `AddCommGroup`"]
def mul_equiv_iso_CommGroup_iso {X Y : CommGroup.{u}} : X ≃* Y ≅ (X ≅ Y) :=
{ hom := λ e, e.to_CommGroup_iso,
inv := λ i, i.CommGroup_iso_to_mul_equiv, }
namespace category_theory.Aut
/-- The (bundled) group of automorphisms of a type is isomorphic to the (bundled) group
of permutations. -/
def iso_perm {α : Type u} : Group.of (Aut α) ≅ Group.of (equiv.perm α) :=
{ hom := ⟨λ g, g.to_equiv, (by tidy), (by tidy)⟩,
inv := ⟨λ g, g.to_iso, (by tidy), (by tidy)⟩ }
/-- The (unbundled) group of automorphisms of a type is `mul_equiv` to the (unbundled) group
of permutations. -/
def mul_equiv_perm {α : Type u} : Aut α ≃* equiv.perm α :=
iso_perm.Group_iso_to_mul_equiv
end category_theory.Aut
@[to_additive]
instance Group.forget_reflects_isos : reflects_isomorphisms (forget Group.{u}) :=
{ reflects := λ X Y f _,
begin
resetI,
let i := as_iso ((forget Group).map f),
let e : X ≃* Y := { ..f, ..i.to_equiv },
exact ⟨(is_iso.of_iso e.to_Group_iso).1⟩,
end }
@[to_additive]
instance CommGroup.forget_reflects_isos : reflects_isomorphisms (forget CommGroup.{u}) :=
{ reflects := λ X Y f _,
begin
resetI,
let i := as_iso ((forget CommGroup).map f),
let e : X ≃* Y := { ..f, ..i.to_equiv },
exact ⟨(is_iso.of_iso e.to_CommGroup_iso).1⟩,
end }
|
613f92c472e0f3a0a4a6ec392d7f02e9dfa7b0f3 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/algebra/order/archimedean.lean | 5ca66b88e7cd63c0177e0267e28a9d64b2f31b5a | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 15,032 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import algebra.field_power
import data.int.least_greatest
import data.rat.floor
/-!
# Archimedean groups and fields.
This file defines the archimedean property for ordered groups and proves several results connected
to this notion. Being archimedean means that for all elements `x` and `y>0` there exists a natural
number `n` such that `x ≤ n • y`.
## Main definitions
* `archimedean` is a typeclass for an ordered additive commutative monoid to have the archimedean
property.
* `archimedean.floor_ring` defines a floor function on an archimedean linearly ordered ring making
it into a `floor_ring`.
* `round` defines a function rounding to the nearest integer for a linearly ordered field which is
also a floor ring.
## Main statements
* `ℕ`, `ℤ`, and `ℚ` are archimedean.
-/
open int set
variables {α : Type*}
/-- An ordered additive commutative monoid is called `archimedean` if for any two elements `x`, `y`
such that `0 < y` there exists a natural number `n` such that `x ≤ n • y`. -/
class archimedean (α) [ordered_add_comm_monoid α] : Prop :=
(arch : ∀ (x : α) {y}, 0 < y → ∃ n : ℕ, x ≤ n • y)
instance order_dual.archimedean [ordered_add_comm_group α] [archimedean α] :
archimedean (order_dual α) :=
⟨λ x y hy, let ⟨n, hn⟩ := archimedean.arch (-x : α) (neg_pos.2 hy) in
⟨n, by rwa [neg_nsmul, neg_le_neg_iff] at hn⟩⟩
section linear_ordered_add_comm_group
variables [linear_ordered_add_comm_group α] [archimedean α]
/-- An archimedean decidable linearly ordered `add_comm_group` has a version of the floor: for
`a > 0`, any `g` in the group lies between some two consecutive multiples of `a`. -/
lemma exists_unique_zsmul_near_of_pos {a : α} (ha : 0 < a) (g : α) :
∃! k : ℤ, k • a ≤ g ∧ g < (k + 1) • a :=
begin
let s : set ℤ := {n : ℤ | n • a ≤ g},
obtain ⟨k, hk : -g ≤ k • a⟩ := archimedean.arch (-g) ha,
have h_ne : s.nonempty := ⟨-k, by simpa using neg_le_neg hk⟩,
obtain ⟨k, hk⟩ := archimedean.arch g ha,
have h_bdd : ∀ n ∈ s, n ≤ (k : ℤ),
{ assume n hn,
apply (zsmul_le_zsmul_iff ha).mp,
rw ← coe_nat_zsmul at hk,
exact le_trans hn hk },
obtain ⟨m, hm, hm'⟩ := int.exists_greatest_of_bdd ⟨k, h_bdd⟩ h_ne,
have hm'' : g < (m + 1) • a,
{ contrapose! hm', exact ⟨m + 1, hm', lt_add_one _⟩, },
refine ⟨m, ⟨hm, hm''⟩, λ n hn, (hm' n hn.1).antisymm $ int.le_of_lt_add_one _⟩,
rw ← zsmul_lt_zsmul_iff ha,
exact lt_of_le_of_lt hm hn.2
end
lemma exists_unique_zsmul_near_of_pos' {a : α} (ha : 0 < a) (g : α) :
∃! k : ℤ, 0 ≤ g - k • a ∧ g - k • a < a :=
by simpa only [sub_nonneg, add_zsmul, one_zsmul, sub_lt_iff_lt_add']
using exists_unique_zsmul_near_of_pos ha g
lemma exists_unique_add_zsmul_mem_Ico {a : α} (ha : 0 < a) (b c : α) :
∃! m : ℤ, b + m • a ∈ set.Ico c (c + a) :=
(equiv.neg ℤ).bijective.exists_unique_iff.2 $
by simpa only [equiv.neg_apply, mem_Ico, neg_zsmul, ← sub_eq_add_neg, le_sub_iff_add_le, zero_add,
add_comm c, sub_lt_iff_lt_add', add_assoc] using exists_unique_zsmul_near_of_pos' ha (b - c)
lemma exists_unique_add_zsmul_mem_Ioc {a : α} (ha : 0 < a) (b c : α) :
∃! m : ℤ, b + m • a ∈ set.Ioc c (c + a) :=
(equiv.add_right (1 : ℤ)).bijective.exists_unique_iff.2 $
by simpa only [add_zsmul, sub_lt_iff_lt_add', le_sub_iff_add_le', ← add_assoc, and.comm, mem_Ioc,
equiv.coe_add_right, one_zsmul, add_le_add_iff_right]
using exists_unique_zsmul_near_of_pos ha (c - b)
end linear_ordered_add_comm_group
theorem exists_nat_gt [ordered_semiring α] [nontrivial α] [archimedean α]
(x : α) : ∃ n : ℕ, x < n :=
let ⟨n, h⟩ := archimedean.arch x zero_lt_one in
⟨n+1, lt_of_le_of_lt (by rwa ← nsmul_one)
(nat.cast_lt.2 (nat.lt_succ_self _))⟩
theorem exists_nat_ge [ordered_semiring α] [archimedean α] (x : α) :
∃ n : ℕ, x ≤ n :=
begin
nontriviality α,
exact (exists_nat_gt x).imp (λ n, le_of_lt)
end
lemma add_one_pow_unbounded_of_pos [ordered_semiring α] [nontrivial α] [archimedean α]
(x : α) {y : α} (hy : 0 < y) :
∃ n : ℕ, x < (y + 1) ^ n :=
have 0 ≤ 1 + y, from add_nonneg zero_le_one hy.le,
let ⟨n, h⟩ := archimedean.arch x hy in
⟨n, calc x ≤ n • y : h
... = n * y : nsmul_eq_mul _ _
... < 1 + n * y : lt_one_add _
... ≤ (1 + y) ^ n : one_add_mul_le_pow' (mul_nonneg hy.le hy.le) (mul_nonneg this this)
(add_nonneg zero_le_two hy.le) _
... = (y + 1) ^ n : by rw [add_comm]⟩
section linear_ordered_ring
variables [linear_ordered_ring α] [archimedean α]
lemma pow_unbounded_of_one_lt (x : α) {y : α} (hy1 : 1 < y) :
∃ n : ℕ, x < y ^ n :=
sub_add_cancel y 1 ▸ add_one_pow_unbounded_of_pos _ (sub_pos.2 hy1)
/-- Every x greater than or equal to 1 is between two successive
natural-number powers of every y greater than one. -/
lemma exists_nat_pow_near {x : α} {y : α} (hx : 1 ≤ x) (hy : 1 < y) :
∃ n : ℕ, y ^ n ≤ x ∧ x < y ^ (n + 1) :=
have h : ∃ n : ℕ, x < y ^ n, from pow_unbounded_of_one_lt _ hy,
by classical; exact let n := nat.find h in
have hn : x < y ^ n, from nat.find_spec h,
have hnp : 0 < n, from pos_iff_ne_zero.2 (λ hn0,
by rw [hn0, pow_zero] at hn; exact (not_le_of_gt hn hx)),
have hnsp : nat.pred n + 1 = n, from nat.succ_pred_eq_of_pos hnp,
have hltn : nat.pred n < n, from nat.pred_lt (ne_of_gt hnp),
⟨nat.pred n, le_of_not_lt (nat.find_min h hltn), by rwa hnsp⟩
theorem exists_int_gt (x : α) : ∃ n : ℤ, x < n :=
let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa ← coe_coe⟩
theorem exists_int_lt (x : α) : ∃ n : ℤ, (n : α) < x :=
let ⟨n, h⟩ := exists_int_gt (-x) in ⟨-n, by rw int.cast_neg; exact neg_lt.1 h⟩
theorem exists_floor (x : α) :
∃ (fl : ℤ), ∀ (z : ℤ), z ≤ fl ↔ (z : α) ≤ x :=
begin
haveI := classical.prop_decidable,
have : ∃ (ub : ℤ), (ub:α) ≤ x ∧ ∀ (z : ℤ), (z:α) ≤ x → z ≤ ub :=
int.exists_greatest_of_bdd
(let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h',
int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩)
(let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩),
refine this.imp (λ fl h z, _),
cases h with h₁ h₂,
exact ⟨λ h, le_trans (int.cast_le.2 h) h₁, h₂ z⟩,
end
end linear_ordered_ring
section linear_ordered_field
variables [linear_ordered_field α]
/-- Every positive `x` is between two successive integer powers of
another `y` greater than one. This is the same as `exists_mem_Ioc_zpow`,
but with ≤ and < the other way around. -/
lemma exists_mem_Ico_zpow [archimedean α]
{x : α} {y : α} (hx : 0 < x) (hy : 1 < y) :
∃ n : ℤ, x ∈ set.Ico (y ^ n) (y ^ (n + 1)) :=
by classical; exact
let ⟨N, hN⟩ := pow_unbounded_of_one_lt x⁻¹ hy in
have he: ∃ m : ℤ, y ^ m ≤ x, from
⟨-N, le_of_lt (by { rw [zpow_neg₀ y (↑N), zpow_coe_nat],
exact (inv_lt hx (lt_trans (inv_pos.2 hx) hN)).1 hN })⟩,
let ⟨M, hM⟩ := pow_unbounded_of_one_lt x hy in
have hb: ∃ b : ℤ, ∀ m, y ^ m ≤ x → m ≤ b, from
⟨M, λ m hm, le_of_not_lt (λ hlt, not_lt_of_ge
(zpow_le_of_le hy.le hlt.le)
(lt_of_le_of_lt hm (by rwa ← zpow_coe_nat at hM)))⟩,
let ⟨n, hn₁, hn₂⟩ := int.exists_greatest_of_bdd hb he in
⟨n, hn₁, lt_of_not_ge (λ hge, not_le_of_gt (int.lt_succ _) (hn₂ _ hge))⟩
/-- Every positive `x` is between two successive integer powers of
another `y` greater than one. This is the same as `exists_mem_Ico_zpow`,
but with ≤ and < the other way around. -/
lemma exists_mem_Ioc_zpow [archimedean α]
{x : α} {y : α} (hx : 0 < x) (hy : 1 < y) :
∃ n : ℤ, x ∈ set.Ioc (y ^ n) (y ^ (n + 1)) :=
let ⟨m, hle, hlt⟩ := exists_mem_Ico_zpow (inv_pos.2 hx) hy in
have hyp : 0 < y, from lt_trans zero_lt_one hy,
⟨-(m+1),
by rwa [zpow_neg₀, inv_lt (zpow_pos_of_pos hyp _) hx],
by rwa [neg_add, neg_add_cancel_right, zpow_neg₀,
le_inv hx (zpow_pos_of_pos hyp _)]⟩
/-- For any `y < 1` and any positive `x`, there exists `n : ℕ` with `y ^ n < x`. -/
lemma exists_pow_lt_of_lt_one [archimedean α] {x y : α} (hx : 0 < x) (hy : y < 1) :
∃ n : ℕ, y ^ n < x :=
begin
by_cases y_pos : y ≤ 0,
{ use 1, simp only [pow_one], linarith, },
rw [not_le] at y_pos,
rcases pow_unbounded_of_one_lt (x⁻¹) (one_lt_inv y_pos hy) with ⟨q, hq⟩,
exact ⟨q, by rwa [inv_pow₀, inv_lt_inv hx (pow_pos y_pos _)] at hq⟩
end
/-- Given `x` and `y` between `0` and `1`, `x` is between two successive powers of `y`.
This is the same as `exists_nat_pow_near`, but for elements between `0` and `1` -/
lemma exists_nat_pow_near_of_lt_one [archimedean α]
{x : α} {y : α} (xpos : 0 < x) (hx : x ≤ 1) (ypos : 0 < y) (hy : y < 1) :
∃ n : ℕ, y ^ (n + 1) < x ∧ x ≤ y ^ n :=
begin
rcases exists_nat_pow_near (one_le_inv_iff.2 ⟨xpos, hx⟩) (one_lt_inv_iff.2 ⟨ypos, hy⟩)
with ⟨n, hn, h'n⟩,
refine ⟨n, _, _⟩,
{ rwa [inv_pow₀, inv_lt_inv xpos (pow_pos ypos _)] at h'n },
{ rwa [inv_pow₀, inv_le_inv (pow_pos ypos _) xpos] at hn }
end
variables [floor_ring α]
lemma sub_floor_div_mul_nonneg (x : α) {y : α} (hy : 0 < y) :
0 ≤ x - ⌊x / y⌋ * y :=
begin
conv in x {rw ← div_mul_cancel x (ne_of_lt hy).symm},
rw ← sub_mul,
exact mul_nonneg (sub_nonneg.2 (floor_le _)) (le_of_lt hy)
end
lemma sub_floor_div_mul_lt (x : α) {y : α} (hy : 0 < y) :
x - ⌊x / y⌋ * y < y :=
sub_lt_iff_lt_add.2 begin
conv in y {rw ← one_mul y},
conv in x {rw ← div_mul_cancel x (ne_of_lt hy).symm},
rw ← add_mul,
exact (mul_lt_mul_right hy).2 (by rw add_comm; exact lt_floor_add_one _),
end
end linear_ordered_field
instance : archimedean ℕ :=
⟨λ n m m0, ⟨n, by simpa only [mul_one, nat.nsmul_eq_mul] using nat.mul_le_mul_left n m0⟩⟩
instance : archimedean ℤ :=
⟨λ n m m0, ⟨n.to_nat, le_trans (int.le_to_nat _) $
by simpa only [nsmul_eq_mul, int.nat_cast_eq_coe_nat, zero_add, mul_one]
using mul_le_mul_of_nonneg_left (int.add_one_le_iff.2 m0) (int.coe_zero_le n.to_nat)⟩⟩
/-- A linear ordered archimedean ring is a floor ring. This is not an `instance` because in some
cases we have a computable `floor` function. -/
noncomputable def archimedean.floor_ring (α)
[linear_ordered_ring α] [archimedean α] : floor_ring α :=
floor_ring.of_floor α (λ a, classical.some (exists_floor a))
(λ z a, (classical.some_spec (exists_floor a) z).symm)
section linear_ordered_field
variables [linear_ordered_field α]
theorem archimedean_iff_nat_lt :
archimedean α ↔ ∀ x : α, ∃ n : ℕ, x < n :=
⟨@exists_nat_gt α _ _, λ H, ⟨λ x y y0,
(H (x / y)).imp $ λ n h, le_of_lt $
by rwa [div_lt_iff y0, ← nsmul_eq_mul] at h⟩⟩
theorem archimedean_iff_nat_le :
archimedean α ↔ ∀ x : α, ∃ n : ℕ, x ≤ n :=
archimedean_iff_nat_lt.trans
⟨λ H x, (H x).imp $ λ _, le_of_lt,
λ H x, let ⟨n, h⟩ := H x in ⟨n+1,
lt_of_le_of_lt h (nat.cast_lt.2 (lt_add_one _))⟩⟩
theorem exists_rat_gt [archimedean α] (x : α) : ∃ q : ℚ, x < q :=
let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa rat.cast_coe_nat⟩
theorem archimedean_iff_rat_lt :
archimedean α ↔ ∀ x : α, ∃ q : ℚ, x < q :=
⟨@exists_rat_gt α _,
λ H, archimedean_iff_nat_lt.2 $ λ x,
let ⟨q, h⟩ := H x in
⟨⌈q⌉₊, lt_of_lt_of_le h $
by simpa only [rat.cast_coe_nat] using (@rat.cast_le α _ _ _).2 (nat.le_ceil _)⟩⟩
theorem archimedean_iff_rat_le :
archimedean α ↔ ∀ x : α, ∃ q : ℚ, x ≤ q :=
archimedean_iff_rat_lt.trans
⟨λ H x, (H x).imp $ λ _, le_of_lt,
λ H x, let ⟨n, h⟩ := H x in ⟨n+1,
lt_of_le_of_lt h (rat.cast_lt.2 (lt_add_one _))⟩⟩
variable [archimedean α]
theorem exists_rat_lt (x : α) : ∃ q : ℚ, (q : α) < x :=
let ⟨n, h⟩ := exists_int_lt x in ⟨n, by rwa rat.cast_coe_int⟩
theorem exists_rat_btwn {x y : α} (h : x < y) : ∃ q : ℚ, x < q ∧ (q:α) < y :=
begin
cases exists_nat_gt (y - x)⁻¹ with n nh,
cases exists_floor (x * n) with z zh,
refine ⟨(z + 1 : ℤ) / n, _⟩,
have n0' := (inv_pos.2 (sub_pos.2 h)).trans nh,
have n0 := nat.cast_pos.1 n0',
rw [rat.cast_div_of_ne_zero, rat.cast_coe_nat, rat.cast_coe_int, div_lt_iff n0'],
refine ⟨(lt_div_iff n0').2 $
(lt_iff_lt_of_le_iff_le (zh _)).1 (lt_add_one _), _⟩,
rw [int.cast_add, int.cast_one],
refine lt_of_le_of_lt (add_le_add_right ((zh _).1 le_rfl) _) _,
rwa [← lt_sub_iff_add_lt', ← sub_mul,
← div_lt_iff' (sub_pos.2 h), one_div],
{ rw [rat.coe_int_denom, nat.cast_one], exact one_ne_zero },
{ intro H, rw [rat.coe_nat_num, ← coe_coe, nat.cast_eq_zero] at H, subst H, cases n0 },
{ rw [rat.coe_nat_denom, nat.cast_one], exact one_ne_zero }
end
theorem exists_nat_one_div_lt {ε : α} (hε : 0 < ε) : ∃ n : ℕ, 1 / (n + 1: α) < ε :=
begin
cases exists_nat_gt (1/ε) with n hn,
use n,
rw [div_lt_iff, ← div_lt_iff' hε],
{ apply hn.trans,
simp [zero_lt_one] },
{ exact n.cast_add_one_pos }
end
theorem exists_pos_rat_lt {x : α} (x0 : 0 < x) : ∃ q : ℚ, 0 < q ∧ (q : α) < x :=
by simpa only [rat.cast_pos] using exists_rat_btwn x0
end linear_ordered_field
section
variables [linear_ordered_field α] [floor_ring α]
/-- `round` rounds a number to the nearest integer. `round (1 / 2) = 1` -/
def round (x : α) : ℤ := ⌊x + 1 / 2⌋
@[simp] lemma round_zero : round (0 : α) = 0 := floor_eq_iff.2 (by norm_num)
@[simp] lemma round_one : round (1 : α) = 1 := floor_eq_iff.2 (by norm_num)
lemma abs_sub_round (x : α) : |x - round x| ≤ 1 / 2 :=
begin
rw [round, abs_sub_le_iff],
have := floor_le (x + 1 / 2),
have := lt_floor_add_one (x + 1 / 2),
split; linarith
end
@[simp, norm_cast] theorem rat.floor_cast (x : ℚ) : ⌊(x:α)⌋ = ⌊x⌋ :=
floor_eq_iff.2 (by exact_mod_cast floor_eq_iff.1 (eq.refl ⌊x⌋))
@[simp, norm_cast] theorem rat.ceil_cast (x : ℚ) : ⌈(x:α)⌉ = ⌈x⌉ :=
by rw [←neg_inj, ←floor_neg, ←floor_neg, ← rat.cast_neg, rat.floor_cast]
@[simp, norm_cast] theorem rat.round_cast (x : ℚ) : round (x:α) = round x :=
have ((x + 1 / 2 : ℚ) : α) = x + 1 / 2, by simp,
by rw [round, round, ← this, rat.floor_cast]
@[simp, norm_cast] theorem rat.cast_fract (x : ℚ) : (↑(fract x) : α) = fract x :=
by { simp only [fract, rat.cast_sub], simp }
end
section
variables [linear_ordered_field α] [archimedean α]
theorem exists_rat_near (x : α) {ε : α} (ε0 : 0 < ε) :
∃ q : ℚ, |x - q| < ε :=
let ⟨q, h₁, h₂⟩ := exists_rat_btwn $
lt_trans ((sub_lt_self_iff x).2 ε0) ((lt_add_iff_pos_left x).2 ε0) in
⟨q, abs_sub_lt_iff.2 ⟨sub_lt.1 h₁, sub_lt_iff_lt_add.2 h₂⟩⟩
instance : archimedean ℚ :=
archimedean_iff_rat_le.2 $ λ q, ⟨q, by rw rat.cast_id⟩
end
|
620435f5e9b901c45ccefea1ea5fca83d8e6a1a0 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/order/filter/lift.lean | 7b87d6c233765d59c07f4d27ee33360c85f487a3 | [
"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 | 21,957 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import order.filter.bases
/-!
# Lift filters along filter and set functions
-/
open set
open_locale classical filter
namespace filter
variables {α : Type*} {β : Type*} {γ : Type*} {ι : Sort*}
section lift
/-- A variant on `bind` using a function `g` taking a set instead of a member of `α`.
This is essentially a push-forward along a function mapping each set to a filter. -/
protected def lift (f : filter α) (g : set α → filter β) :=
⨅s ∈ f, g s
variables {f f₁ f₂ : filter α} {g g₁ g₂ : set α → filter β}
@[simp] lemma lift_top (g : set α → filter β) : (⊤ : filter α).lift g = g univ :=
by simp [filter.lift]
/-- If `(p : ι → Prop, s : ι → set α)` is a basis of a filter `f`, `g` is a monotone function
`set α → filter γ`, and for each `i`, `(pg : β i → Prop, sg : β i → set α)` is a basis
of the filter `g (s i)`, then `(λ (i : ι) (x : β i), p i ∧ pg i x, λ (i : ι) (x : β i), sg i x)`
is a basis of the filter `f.lift g`.
This basis is parametrized by `i : ι` and `x : β i`, so in order to formulate this fact using
`has_basis` one has to use `Σ i, β i` as the index type, see `filter.has_basis.lift`.
This lemma states the corresponding `mem_iff` statement without using a sigma type. -/
lemma has_basis.mem_lift_iff {ι} {p : ι → Prop} {s : ι → set α} {f : filter α}
(hf : f.has_basis p s) {β : ι → Type*} {pg : Π i, β i → Prop} {sg : Π i, β i → set γ}
{g : set α → filter γ} (hg : ∀ i, (g $ s i).has_basis (pg i) (sg i)) (gm : monotone g)
{s : set γ} :
s ∈ f.lift g ↔ ∃ (i : ι) (hi : p i) (x : β i) (hx : pg i x), sg i x ⊆ s :=
begin
refine (mem_binfi_of_directed _ ⟨univ, univ_sets _⟩).trans _,
{ intros t₁ ht₁ t₂ ht₂,
exact ⟨t₁ ∩ t₂, inter_mem ht₁ ht₂, gm $ inter_subset_left _ _,
gm $ inter_subset_right _ _⟩ },
{ simp only [← (hg _).mem_iff],
exact hf.exists_iff (λ t₁ t₂ ht H, gm ht H) }
end
/-- If `(p : ι → Prop, s : ι → set α)` is a basis of a filter `f`, `g` is a monotone function
`set α → filter γ`, and for each `i`, `(pg : β i → Prop, sg : β i → set α)` is a basis
of the filter `g (s i)`, then `(λ (i : ι) (x : β i), p i ∧ pg i x, λ (i : ι) (x : β i), sg i x)`
is a basis of the filter `f.lift g`.
This basis is parametrized by `i : ι` and `x : β i`, so in order to formulate this fact using
`has_basis` one has to use `Σ i, β i` as the index type. See also `filter.has_basis.mem_lift_iff`
for the corresponding `mem_iff` statement formulated without using a sigma type. -/
lemma has_basis.lift {ι} {p : ι → Prop} {s : ι → set α} {f : filter α} (hf : f.has_basis p s)
{β : ι → Type*} {pg : Π i, β i → Prop} {sg : Π i, β i → set γ} {g : set α → filter γ}
(hg : ∀ i, (g $ s i).has_basis (pg i) (sg i)) (gm : monotone g) :
(f.lift g).has_basis (λ i : Σ i, β i, p i.1 ∧ pg i.1 i.2) (λ i : Σ i, β i, sg i.1 i.2) :=
begin
refine ⟨λ t, (hf.mem_lift_iff hg gm).trans _⟩,
simp [sigma.exists, and_assoc, exists_and_distrib_left]
end
lemma mem_lift_sets (hg : monotone g) {s : set β} :
s ∈ f.lift g ↔ ∃t∈f, s ∈ g t :=
(f.basis_sets.mem_lift_iff (λ s, (g s).basis_sets) hg).trans $
by simp only [id, ← exists_mem_subset_iff]
lemma mem_lift {s : set β} {t : set α} (ht : t ∈ f) (hs : s ∈ g t) :
s ∈ f.lift g :=
le_principal_iff.mp $ show f.lift g ≤ 𝓟 s,
from infi_le_of_le t $ infi_le_of_le ht $ le_principal_iff.mpr hs
lemma lift_le {f : filter α} {g : set α → filter β} {h : filter β} {s : set α}
(hs : s ∈ f) (hg : g s ≤ h) : f.lift g ≤ h :=
infi_le_of_le s $ infi_le_of_le hs $ hg
lemma le_lift {f : filter α} {g : set α → filter β} {h : filter β}
(hh : ∀s∈f, h ≤ g s) : h ≤ f.lift g :=
le_infi $ assume s, le_infi $ assume hs, hh s hs
lemma lift_mono (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.lift g₁ ≤ f₂.lift g₂ :=
infi_le_infi $ assume s, infi_le_infi2 $ assume hs, ⟨hf hs, hg s⟩
lemma lift_mono' (hg : ∀s∈f, g₁ s ≤ g₂ s) : f.lift g₁ ≤ f.lift g₂ :=
infi_le_infi $ assume s, infi_le_infi $ assume hs, hg s hs
lemma tendsto_lift {m : γ → β} {l : filter γ} :
tendsto m l (f.lift g) ↔ ∀ s ∈ f, tendsto m l (g s) :=
by simp only [filter.lift, tendsto_infi]
lemma map_lift_eq {m : β → γ} (hg : monotone g) : map m (f.lift g) = f.lift (map m ∘ g) :=
have monotone (map m ∘ g),
from map_mono.comp hg,
filter.ext $ λ s,
by simp only [mem_lift_sets hg, mem_lift_sets this, exists_prop, mem_map, function.comp_app]
lemma comap_lift_eq {m : γ → β} (hg : monotone g) : comap m (f.lift g) = f.lift (comap m ∘ g) :=
have monotone (comap m ∘ g),
from comap_mono.comp hg,
begin
ext,
simp only [mem_lift_sets hg, mem_lift_sets this, mem_comap, exists_prop, mem_lift_sets],
exact ⟨λ ⟨b, ⟨a, ha, hb⟩, hs⟩, ⟨a, ha, b, hb, hs⟩, λ ⟨a, ha, b, hb, hs⟩, ⟨b, ⟨a, ha, hb⟩, hs⟩⟩
end
theorem comap_lift_eq2 {m : β → α} {g : set β → filter γ} (hg : monotone g) :
(comap m f).lift g = f.lift (g ∘ preimage m) :=
le_antisymm
(le_infi $ assume s, le_infi $ assume hs,
infi_le_of_le (preimage m s) $ infi_le _ ⟨s, hs, subset.refl _⟩)
(le_infi $ assume s, le_infi $ assume ⟨s', hs', (h_sub : preimage m s' ⊆ s)⟩,
infi_le_of_le s' $ infi_le_of_le hs' $ hg h_sub)
lemma map_lift_eq2 {g : set β → filter γ} {m : α → β} (hg : monotone g) :
(map m f).lift g = f.lift (g ∘ image m) :=
le_antisymm
(infi_le_infi2 $ assume s, ⟨image m s,
infi_le_infi2 $ assume hs, ⟨
f.sets_of_superset hs $ assume a h, mem_image_of_mem _ h,
le_refl _⟩⟩)
(infi_le_infi2 $ assume t, ⟨preimage m t,
infi_le_infi2 $ assume ht, ⟨ht,
hg $ assume x, assume h : x ∈ m '' preimage m t,
let ⟨y, hy, h_eq⟩ := h in
show x ∈ t, from h_eq ▸ hy⟩⟩)
lemma lift_comm {g : filter β} {h : set α → set β → filter γ} :
f.lift (λs, g.lift (h s)) = g.lift (λt, f.lift (λs, h s t)) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume hi, le_infi $ assume j, le_infi $ assume hj,
infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi)
(le_infi $ assume i, le_infi $ assume hi, le_infi $ assume j, le_infi $ assume hj,
infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi)
lemma lift_assoc {h : set β → filter γ} (hg : monotone g) :
(f.lift g).lift h = f.lift (λs, (g s).lift h) :=
le_antisymm
(le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht,
infi_le_of_le t $ infi_le _ $ (mem_lift_sets hg).mpr ⟨_, hs, ht⟩)
(le_infi $ assume t, le_infi $ assume ht,
let ⟨s, hs, h'⟩ := (mem_lift_sets hg).mp ht in
infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le t $ infi_le _ h')
lemma lift_lift_same_le_lift {g : set α → set α → filter β} :
f.lift (λs, f.lift (g s)) ≤ f.lift (λs, g s s) :=
le_infi $ assume s, le_infi $ assume hs, infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $
infi_le _ hs
lemma lift_lift_same_eq_lift {g : set α → set α → filter β}
(hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)) :
f.lift (λs, f.lift (g s)) = f.lift (λs, g s s) :=
le_antisymm
lift_lift_same_le_lift
(le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht,
infi_le_of_le (s ∩ t) $
infi_le_of_le (inter_mem hs ht) $
calc g (s ∩ t) (s ∩ t) ≤ g s (s ∩ t) : hg₂ (s ∩ t) (inter_subset_left _ _)
... ≤ g s t : hg₁ s (inter_subset_right _ _))
lemma lift_principal {s : set α} (hg : monotone g) :
(𝓟 s).lift g = g s :=
le_antisymm
(infi_le_of_le s $ infi_le _ $ subset.refl _)
(le_infi $ assume t, le_infi $ assume hi, hg hi)
theorem monotone_lift [preorder γ] {f : γ → filter α} {g : γ → set α → filter β}
(hf : monotone f) (hg : monotone g) : monotone (λc, (f c).lift (g c)) :=
assume a b h, lift_mono (hf h) (hg h)
lemma lift_ne_bot_iff (hm : monotone g) : (ne_bot $ f.lift g) ↔ (∀s∈f, ne_bot (g s)) :=
begin
rw [filter.lift, infi_subtype', infi_ne_bot_iff_of_directed', subtype.forall'],
{ rintros ⟨s, hs⟩ ⟨t, ht⟩,
exact ⟨⟨s ∩ t, inter_mem hs ht⟩, hm (inter_subset_left s t), hm (inter_subset_right s t)⟩ }
end
@[simp] lemma lift_const {f : filter α} {g : filter β} : f.lift (λx, g) = g :=
le_antisymm (lift_le univ_mem $ le_refl g) (le_lift $ assume s hs, le_refl g)
@[simp] lemma lift_inf {f : filter α} {g h : set α → filter β} :
f.lift (λx, g x ⊓ h x) = f.lift g ⊓ f.lift h :=
by simp only [filter.lift, infi_inf_eq, eq_self_iff_true]
@[simp] lemma lift_principal2 {f : filter α} : f.lift 𝓟 = f :=
le_antisymm
(assume s hs, mem_lift hs (mem_principal_self s))
(le_infi $ assume s, le_infi $ assume hs, by simp only [hs, le_principal_iff])
lemma lift_infi {f : ι → filter α} {g : set α → filter β}
[hι : nonempty ι] (hg : ∀{s t}, g s ⊓ g t = g (s ∩ t)) : (infi f).lift g = (⨅i, (f i).lift g) :=
le_antisymm
(le_infi $ assume i, lift_mono (infi_le _ _) (le_refl _))
(assume s,
have g_mono : monotone g,
from assume s t h, le_of_inf_eq $ eq.trans hg $ congr_arg g $ inter_eq_self_of_subset_left h,
have ∀t∈(infi f), (⨅ (i : ι), filter.lift (f i) g) ≤ g t,
from assume t ht, infi_sets_induct ht
(let ⟨i⟩ := hι in infi_le_of_le i $ infi_le_of_le univ $ infi_le _ univ_mem)
(assume i s₁ s₂ hs₁ hs₂,
@hg s₁ s₂ ▸ le_inf (infi_le_of_le i $ infi_le_of_le s₁ $ infi_le _ hs₁) hs₂),
begin
simp only [mem_lift_sets g_mono, exists_imp_distrib],
exact assume t ht hs, this t ht hs
end)
end lift
section lift'
/-- Specialize `lift` to functions `set α → set β`. This can be viewed as a generalization of `map`.
This is essentially a push-forward along a function mapping each set to a set. -/
protected def lift' (f : filter α) (h : set α → set β) :=
f.lift (𝓟 ∘ h)
variables {f f₁ f₂ : filter α} {h h₁ h₂ : set α → set β}
@[simp] lemma lift'_top (h : set α → set β) : (⊤ : filter α).lift' h = 𝓟 (h univ) :=
lift_top _
lemma mem_lift' {t : set α} (ht : t ∈ f) : h t ∈ (f.lift' h) :=
le_principal_iff.mp $ show f.lift' h ≤ 𝓟 (h t),
from infi_le_of_le t $ infi_le_of_le ht $ le_refl _
lemma tendsto_lift' {m : γ → β} {l : filter γ} :
tendsto m l (f.lift' h) ↔ ∀ s ∈ f, ∀ᶠ a in l, m a ∈ h s :=
by simp only [filter.lift', tendsto_lift, tendsto_principal]
lemma has_basis.lift' {ι} {p : ι → Prop} {s} (hf : f.has_basis p s) (hh : monotone h) :
(f.lift' h).has_basis p (h ∘ s) :=
begin
refine ⟨λ t, (hf.mem_lift_iff _ (monotone_principal.comp hh)).trans _⟩,
show ∀ i, (𝓟 (h (s i))).has_basis (λ j : unit, true) (λ (j : unit), h (s i)),
from λ i, has_basis_principal _,
simp only [exists_const]
end
lemma mem_lift'_sets (hh : monotone h) {s : set β} : s ∈ (f.lift' h) ↔ (∃t∈f, h t ⊆ s) :=
mem_lift_sets $ monotone_principal.comp hh
lemma eventually_lift'_iff (hh : monotone h) {p : β → Prop} :
(∀ᶠ y in f.lift' h, p y) ↔ (∃ t ∈ f, ∀ y ∈ h t, p y) :=
mem_lift'_sets hh
lemma lift'_le {f : filter α} {g : set α → set β} {h : filter β} {s : set α}
(hs : s ∈ f) (hg : 𝓟 (g s) ≤ h) : f.lift' g ≤ h :=
lift_le hs hg
lemma lift'_mono (hf : f₁ ≤ f₂) (hh : h₁ ≤ h₂) : f₁.lift' h₁ ≤ f₂.lift' h₂ :=
lift_mono hf $ assume s, principal_mono.mpr $ hh s
lemma lift'_mono' (hh : ∀s∈f, h₁ s ⊆ h₂ s) : f.lift' h₁ ≤ f.lift' h₂ :=
infi_le_infi $ assume s, infi_le_infi $ assume hs, principal_mono.mpr $ hh s hs
lemma lift'_cong (hh : ∀s∈f, h₁ s = h₂ s) : f.lift' h₁ = f.lift' h₂ :=
le_antisymm (lift'_mono' $ assume s hs, le_of_eq $ hh s hs)
(lift'_mono' $ assume s hs, le_of_eq $ (hh s hs).symm)
lemma map_lift'_eq {m : β → γ} (hh : monotone h) : map m (f.lift' h) = f.lift' (image m ∘ h) :=
calc map m (f.lift' h) = f.lift (map m ∘ 𝓟 ∘ h) :
map_lift_eq $ monotone_principal.comp hh
... = f.lift' (image m ∘ h) : by simp only [(∘), filter.lift', map_principal, eq_self_iff_true]
lemma map_lift'_eq2 {g : set β → set γ} {m : α → β} (hg : monotone g) :
(map m f).lift' g = f.lift' (g ∘ image m) :=
map_lift_eq2 $ monotone_principal.comp hg
theorem comap_lift'_eq {m : γ → β} (hh : monotone h) :
comap m (f.lift' h) = f.lift' (preimage m ∘ h) :=
calc comap m (f.lift' h) = f.lift (comap m ∘ 𝓟 ∘ h) :
comap_lift_eq $ monotone_principal.comp hh
... = f.lift' (preimage m ∘ h) :
by simp only [(∘), filter.lift', comap_principal, eq_self_iff_true]
theorem comap_lift'_eq2 {m : β → α} {g : set β → set γ} (hg : monotone g) :
(comap m f).lift' g = f.lift' (g ∘ preimage m) :=
comap_lift_eq2 $ monotone_principal.comp hg
lemma lift'_principal {s : set α} (hh : monotone h) :
(𝓟 s).lift' h = 𝓟 (h s) :=
lift_principal $ monotone_principal.comp hh
lemma lift'_pure {a : α} (hh : monotone h) :
(pure a : filter α).lift' h = 𝓟 (h {a}) :=
by rw [← principal_singleton, lift'_principal hh]
lemma lift'_bot (hh : monotone h) : (⊥ : filter α).lift' h = 𝓟 (h ∅) :=
by rw [← principal_empty, lift'_principal hh]
lemma principal_le_lift' {t : set β} (hh : ∀s∈f, t ⊆ h s) :
𝓟 t ≤ f.lift' h :=
le_infi $ assume s, le_infi $ assume hs, principal_mono.mpr (hh s hs)
theorem monotone_lift' [preorder γ] {f : γ → filter α} {g : γ → set α → set β}
(hf : monotone f) (hg : monotone g) : monotone (λc, (f c).lift' (g c)) :=
assume a b h, lift'_mono (hf h) (hg h)
lemma lift_lift'_assoc {g : set α → set β} {h : set β → filter γ}
(hg : monotone g) (hh : monotone h) :
(f.lift' g).lift h = f.lift (λs, h (g s)) :=
calc (f.lift' g).lift h = f.lift (λs, (𝓟 (g s)).lift h) :
lift_assoc (monotone_principal.comp hg)
... = f.lift (λs, h (g s)) : by simp only [lift_principal, hh, eq_self_iff_true]
lemma lift'_lift'_assoc {g : set α → set β} {h : set β → set γ}
(hg : monotone g) (hh : monotone h) :
(f.lift' g).lift' h = f.lift' (λs, h (g s)) :=
lift_lift'_assoc hg (monotone_principal.comp hh)
lemma lift'_lift_assoc {g : set α → filter β} {h : set β → set γ}
(hg : monotone g) : (f.lift g).lift' h = f.lift (λs, (g s).lift' h) :=
lift_assoc hg
lemma lift_lift'_same_le_lift' {g : set α → set α → set β} :
f.lift (λs, f.lift' (g s)) ≤ f.lift' (λs, g s s) :=
lift_lift_same_le_lift
lemma lift_lift'_same_eq_lift' {g : set α → set α → set β}
(hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)) :
f.lift (λs, f.lift' (g s)) = f.lift' (λs, g s s) :=
lift_lift_same_eq_lift
(assume s, monotone_principal.comp (hg₁ s))
(assume t, monotone_principal.comp (hg₂ t))
lemma lift'_inf_principal_eq {h : set α → set β} {s : set β} :
f.lift' h ⊓ 𝓟 s = f.lift' (λt, h t ∩ s) :=
by simp only [filter.lift', filter.lift, (∘), ← inf_principal, infi_subtype', ← infi_inf]
lemma lift'_ne_bot_iff (hh : monotone h) : (ne_bot (f.lift' h)) ↔ (∀s∈f, (h s).nonempty) :=
calc (ne_bot (f.lift' h)) ↔ (∀s∈f, ne_bot (𝓟 (h s))) :
lift_ne_bot_iff (monotone_principal.comp hh)
... ↔ (∀s∈f, (h s).nonempty) : by simp only [principal_ne_bot_iff]
@[simp] lemma lift'_id {f : filter α} : f.lift' id = f :=
lift_principal2
lemma le_lift' {f : filter α} {h : set α → set β} {g : filter β}
(h_le : ∀s∈f, h s ∈ g) : g ≤ f.lift' h :=
le_infi $ assume s, le_infi $ assume hs,
by simpa only [h_le, le_principal_iff, function.comp_app] using h_le s hs
lemma lift_infi' {f : ι → filter α} {g : set α → filter β}
[nonempty ι] (hf : directed (≥) f) (hg : monotone g) : (infi f).lift g = (⨅i, (f i).lift g) :=
le_antisymm
(le_infi $ assume i, lift_mono (infi_le _ _) (le_refl _))
(assume s,
begin
rw mem_lift_sets hg,
simp only [exists_imp_distrib, mem_infi_of_directed hf],
exact assume t i ht hs, mem_infi_of_mem i $ mem_lift ht hs
end)
lemma lift'_infi {f : ι → filter α} {g : set α → set β}
[nonempty ι] (hg : ∀{s t}, g s ∩ g t = g (s ∩ t)) : (infi f).lift' g = (⨅i, (f i).lift' g) :=
lift_infi $ λ s t, by simp only [principal_eq_iff_eq, inf_principal, (∘), hg]
lemma lift'_inf (f g : filter α) {s : set α → set β} (hs : ∀ {t₁ t₂}, s t₁ ∩ s t₂ = s (t₁ ∩ t₂)) :
(f ⊓ g).lift' s = f.lift' s ⊓ g.lift' s :=
have (⨅ b : bool, cond b f g).lift' s = ⨅ b : bool, (cond b f g).lift' s :=
lift'_infi @hs,
by simpa only [infi_bool_eq]
theorem comap_eq_lift' {f : filter β} {m : α → β} :
comap m f = f.lift' (preimage m) :=
filter.ext $ λ s, (mem_lift'_sets monotone_preimage).symm
lemma lift'_infi_powerset {f : ι → filter α} :
(infi f).lift' powerset = (⨅i, (f i).lift' powerset) :=
begin
casesI is_empty_or_nonempty ι,
{ rw [infi_of_empty f, infi_of_empty, lift'_top, powerset_univ, principal_univ] },
{ exact (lift'_infi $ λ _ _, (powerset_inter _ _).symm) },
end
lemma lift'_inf_powerset (f g : filter α) :
(f ⊓ g).lift' powerset = f.lift' powerset ⊓ g.lift' powerset :=
lift'_inf f g $ λ _ _, (powerset_inter _ _).symm
lemma eventually_lift'_powerset {f : filter α} {p : set α → Prop} :
(∀ᶠ s in f.lift' powerset, p s) ↔ ∃ s ∈ f, ∀ t ⊆ s, p t :=
eventually_lift'_iff monotone_powerset
lemma eventually_lift'_powerset' {f : filter α} {p : set α → Prop}
(hp : ∀ ⦃s t⦄, s ⊆ t → p t → p s) :
(∀ᶠ s in f.lift' powerset, p s) ↔ ∃ s ∈ f, p s :=
eventually_lift'_powerset.trans $ exists_congr $ λ s, exists_congr $
λ hsf, ⟨λ H, H s (subset.refl s), λ hs t ht, hp ht hs⟩
instance lift'_powerset_ne_bot (f : filter α) : ne_bot (f.lift' powerset) :=
(lift'_ne_bot_iff monotone_powerset).2 $ λ _ _, powerset_nonempty
lemma tendsto_lift'_powerset_mono {la : filter α} {lb : filter β} {s t : α → set β}
(ht : tendsto t la (lb.lift' powerset)) (hst : ∀ᶠ x in la, s x ⊆ t x) :
tendsto s la (lb.lift' powerset) :=
begin
simp only [filter.lift', filter.lift, (∘), tendsto_infi, tendsto_principal] at ht ⊢,
exact λ u hu, (ht u hu).mp (hst.mono $ λ a hst ht, subset.trans hst ht)
end
@[simp] lemma eventually_lift'_powerset_forall {f : filter α} {p : α → Prop} :
(∀ᶠ s in f.lift' powerset, ∀ x ∈ s, p x) ↔ ∀ᶠ x in f, p x :=
iff.trans (eventually_lift'_powerset' $ λ s t hst ht x hx, ht x (hst hx))
exists_mem_subset_iff
alias eventually_lift'_powerset_forall ↔
filter.eventually.of_lift'_powerset filter.eventually.lift'_powerset
@[simp] lemma eventually_lift'_powerset_eventually {f g : filter α} {p : α → Prop} :
(∀ᶠ s in f.lift' powerset, ∀ᶠ x in g, x ∈ s → p x) ↔ ∀ᶠ x in f ⊓ g, p x :=
calc _ ↔ ∃ s ∈ f, ∀ᶠ x in g, x ∈ s → p x :
eventually_lift'_powerset' $ λ s t hst ht, ht.mono $ λ x hx hs, hx (hst hs)
... ↔ ∃ (s ∈ f) (t ∈ g), ∀ x, x ∈ t → x ∈ s → p x :
by simp only [eventually_iff_exists_mem]
... ↔ ∀ᶠ x in f ⊓ g, p x : by { rw eventually_inf, finish }
end lift'
section prod
variables {f : filter α}
lemma prod_def {f : filter α} {g : filter β} : f ×ᶠ g = (f.lift $ λs, g.lift' $ set.prod s) :=
have ∀(s:set α) (t : set β),
𝓟 (set.prod s t) = (𝓟 s).comap prod.fst ⊓ (𝓟 t).comap prod.snd,
by simp only [principal_eq_iff_eq, comap_principal, inf_principal]; intros; refl,
begin
simp only [filter.lift', function.comp, this, lift_inf, lift_const, lift_inf],
rw [← comap_lift_eq monotone_principal, ← comap_lift_eq monotone_principal],
simp only [filter.prod, lift_principal2, eq_self_iff_true]
end
lemma prod_same_eq : f ×ᶠ f = f.lift' (λt, set.prod t t) :=
by rw [prod_def];
from lift_lift'_same_eq_lift'
(assume s, set.monotone_prod monotone_const monotone_id)
(assume t, set.monotone_prod monotone_id monotone_const)
lemma mem_prod_same_iff {s : set (α×α)} :
s ∈ f ×ᶠ f ↔ (∃t∈f, set.prod t t ⊆ s) :=
by rw [prod_same_eq, mem_lift'_sets]; exact set.monotone_prod monotone_id monotone_id
lemma tendsto_prod_self_iff {f : α × α → β} {x : filter α} {y : filter β} :
filter.tendsto f (x ×ᶠ x) y ↔
∀ W ∈ y, ∃ U ∈ x, ∀ (x x' : α), x ∈ U → x' ∈ U → f (x, x') ∈ W :=
by simp only [tendsto_def, mem_prod_same_iff, prod_sub_preimage_iff, exists_prop, iff_self]
variables {α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*}
lemma prod_lift_lift
{f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → filter β₁} {g₂ : set α₂ → filter β₂}
(hg₁ : monotone g₁) (hg₂ : monotone g₂) :
(f₁.lift g₁) ×ᶠ (f₂.lift g₂) = f₁.lift (λs, f₂.lift (λt, g₁ s ×ᶠ g₂ t)) :=
begin
simp only [prod_def],
rw [lift_assoc],
apply congr_arg, funext x,
rw [lift_comm],
apply congr_arg, funext y,
rw [lift'_lift_assoc],
exact hg₂,
exact hg₁
end
lemma prod_lift'_lift'
{f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → set β₁} {g₂ : set α₂ → set β₂}
(hg₁ : monotone g₁) (hg₂ : monotone g₂) :
f₁.lift' g₁ ×ᶠ f₂.lift' g₂ = f₁.lift (λs, f₂.lift' (λt, (g₁ s).prod (g₂ t))) :=
begin
rw [prod_def, lift_lift'_assoc],
apply congr_arg, funext x,
rw [lift'_lift'_assoc],
exact hg₂,
exact set.monotone_prod monotone_const monotone_id,
exact hg₁,
exact (monotone_lift' monotone_const $ monotone_lam $
assume x, set.monotone_prod monotone_id monotone_const)
end
end prod
end filter
|
290195dffd0fcbe71c3a76675b68dbe0b82b9233 | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/ring_theory/polynomial/pochhammer.lean | 983751cabb6a75fb82f85228d68b0b84a4245d44 | [
"Apache-2.0"
] | permissive | abentkamp/mathlib | d9a75d291ec09f4637b0f30cc3880ffb07549ee5 | 5360e476391508e092b5a1e5210bd0ed22dc0755 | refs/heads/master | 1,682,382,954,948 | 1,622,106,077,000 | 1,622,106,077,000 | 149,285,665 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,346 | 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 tactic.abel
import data.polynomial.eval
/-!
# The Pochhammer polynomials
We define and prove some basic relations about
`pochhammer S n : polynomial S = X * (X+1) * ... * (X + n - 1)`
which is also known as the rising factorial. A version of this definition
that is focused on `nat` can be found in `data.nat.factorial` as `desc_fac`.
## Implementation
As with many other families of polynomials, even though the coefficients are always in `ℕ`,
we define the polynomial with coefficients in any `[semiring S]`.
## TODO
There is lots more in this direction:
* q-factorials, q-binomials, q-Pochhammer.
* Defining Bernstein polynomials (e.g. as one way to prove Weierstrass' theorem).
-/
universes u v
open polynomial
section
variables (S : Type u) [semiring S]
/--
`pochhammer S n` is the polynomial `X * (X+1) * ... * (X + n - 1)`,
with coefficients in the semiring `S`.
-/
noncomputable def pochhammer : ℕ → polynomial S
| 0 := 1
| (n+1) := X * (pochhammer n).comp (X + 1)
@[simp] lemma pochhammer_zero : pochhammer S 0 = 1 := rfl
@[simp] lemma pochhammer_one : pochhammer S 1 = X := by simp [pochhammer]
lemma pochhammer_succ_left (n : ℕ) : pochhammer S (n+1) = X * (pochhammer S n).comp (X+1) :=
by rw pochhammer
section
variables {S} {T : Type v} [semiring T]
@[simp] lemma pochhammer_map (f : S →+* T) (n : ℕ) : (pochhammer S n).map f = pochhammer T n :=
begin
induction n with n ih,
{ simp, },
{ simp [ih, pochhammer_succ_left, map_comp], },
end
end
@[simp, norm_cast] lemma pochhammer_eval_cast (n k : ℕ) :
((pochhammer ℕ n).eval k : S) = (pochhammer S n).eval k :=
begin
rw [←pochhammer_map (algebra_map ℕ S), eval_map, ←(algebra_map ℕ S).eq_nat_cast,
eval₂_at_nat_cast, nat.cast_id, ring_hom.eq_nat_cast],
end
lemma pochhammer_eval_zero {n : ℕ} : (pochhammer S n).eval 0 = if n = 0 then 1 else 0 :=
begin
cases n,
{ simp, },
{ simp [X_mul, nat.succ_ne_zero, pochhammer_succ_left], }
end
lemma pochhammer_zero_eval_zero : (pochhammer S 0).eval 0 = 1 :=
by simp
@[simp] lemma pochhammer_ne_zero_eval_zero {n : ℕ} (h : n ≠ 0) : (pochhammer S n).eval 0 = 0 :=
by simp [pochhammer_eval_zero, h]
lemma pochhammer_succ_right (n : ℕ) : pochhammer S (n+1) = pochhammer S n * (X + n) :=
begin
suffices h : pochhammer ℕ (n+1) = pochhammer ℕ n * (X + n),
{ apply_fun polynomial.map (algebra_map ℕ S) at h,
simpa only [pochhammer_map, map_mul, map_add, map_X, map_nat_cast] using h, },
induction n with n ih,
{ simp, },
{ conv_lhs {
rw [pochhammer_succ_left, ih, mul_comp, ←mul_assoc, ←pochhammer_succ_left, add_comp, X_comp,
nat_cast_comp, add_assoc, add_comm (1 : polynomial ℕ)], },
refl, },
end
lemma polynomial.mul_X_add_nat_cast_comp {p q : polynomial S} {n : ℕ} :
(p * (X + n)).comp q = (p.comp q) * (q + n) :=
by rw [mul_add, add_comp, mul_X_comp, ←nat.cast_comm, nat_cast_mul_comp, nat.cast_comm, mul_add]
lemma pochhammer_mul (n m : ℕ) :
pochhammer S n * (pochhammer S m).comp (X + n) = pochhammer S (n + m) :=
begin
induction m with m ih,
{ simp, },
{ rw [pochhammer_succ_right, polynomial.mul_X_add_nat_cast_comp, ←mul_assoc, ih,
nat.succ_eq_add_one, ←add_assoc, pochhammer_succ_right, nat.cast_add, add_assoc], }
end
lemma pochhammer_nat_eq_desc_fac (n : ℕ) : ∀ k, (pochhammer ℕ k).eval (n + 1) = nat.desc_fac n k
| 0 := by erw [eval_one]; refl
| (t + 1) := begin
rw [pochhammer_succ_right, eval_mul, pochhammer_nat_eq_desc_fac t],
suffices : n.desc_fac t * (n + 1 + t) = n.desc_fac (t + 1), by simpa,
rw [nat.desc_fac_succ, add_right_comm, mul_comm]
end
end
section
variables {S : Type*} [ordered_semiring S] [nontrivial S]
lemma pochhammer_pos (n : ℕ) (s : S) (h : 0 < s) : 0 < (pochhammer S n).eval s :=
begin
induction n with n ih,
{ simp only [nat.nat_zero_eq_zero, pochhammer_zero, eval_one], exact zero_lt_one, },
{ rw [pochhammer_succ_right, mul_add, eval_add, ←nat.cast_comm, eval_nat_cast_mul, eval_mul_X,
nat.cast_comm, ←mul_add],
exact mul_pos ih
(lt_of_lt_of_le h ((le_add_iff_nonneg_right _).mpr (nat.cast_nonneg n))), }
end
end
section factorial
open_locale nat
variables (S : Type*) [semiring S] (r n : ℕ)
@[simp]
lemma pochhammer_eval_one (S : Type*) [semiring S] (n : ℕ) :
(pochhammer S n).eval (1 : S) = (n! : S) :=
by rw_mod_cast [pochhammer_nat_eq_desc_fac, nat.zero_desc_fac]
lemma factorial_mul_pochhammer (S : Type*) [semiring S] (r n : ℕ) :
(r! : S) * (pochhammer S n).eval (r + 1) = (r + n)! :=
by rw_mod_cast [pochhammer_nat_eq_desc_fac, nat.factorial_mul_desc_fac]
lemma pochhammer_nat_eval_succ (r : ℕ) :
∀ n : ℕ, n * (pochhammer ℕ r).eval (n + 1) = (n + r) * (pochhammer ℕ r).eval n
| 0 := begin
by_cases h : r = 0,
{ simp only [h, zero_mul, zero_add], },
{ simp only [pochhammer_eval_zero, zero_mul, if_neg h, mul_zero], }
end
| (k + 1) := by simp only [pochhammer_nat_eq_desc_fac, nat.succ_desc_fac, add_right_comm]
lemma pochhammer_eval_succ (r n : ℕ) :
(n : S) * (pochhammer S r).eval (n + 1 : S) = (n + r) * (pochhammer S r).eval n :=
by exact_mod_cast congr_arg nat.cast (pochhammer_nat_eval_succ r n)
end factorial
|
8f5177123f8440260544ff568c7df7b7b19bc8d7 | 8b9f17008684d796c8022dab552e42f0cb6fb347 | /library/data/nat/div.lean | 14922c74d3e788080a51038690570917b7756a4c | [
"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 | 37,247 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: data.nat.div
Authors: Jeremy Avigad, Leonardo de Moura
Definitions and properties of div, mod, gcd, lcm, coprime. Much of the development follows
Isabelle's library.
-/
import data.nat.sub tools.fake_simplifier
open eq.ops well_founded decidable fake_simplifier prod
namespace nat
/- div and mod -/
-- auxiliary lemma used to justify div
private definition div_rec_lemma {x y : nat} (H : 0 < y ∧ y ≤ x) : x - y < x :=
and.rec_on H (λ ypos ylex, sub_lt (lt_of_lt_of_le ypos ylex) ypos)
private definition div.F (x : nat) (f : Π x₁, x₁ < x → nat → nat) (y : nat) : nat :=
if H : 0 < y ∧ y ≤ x then f (x - y) (div_rec_lemma H) y + 1 else zero
definition divide (x y : nat) := fix div.F x y
theorem divide_def (x y : nat) : divide x y = if 0 < y ∧ y ≤ x then divide (x - y) y + 1 else 0 :=
congr_fun (fix_eq div.F x) y
notation a div b := divide a b
theorem div_zero (a : ℕ) : a div 0 = 0 :=
divide_def a 0 ⬝ if_neg (!not_and_of_not_left (lt.irrefl 0))
theorem div_eq_zero_of_lt {a b : ℕ} (h : a < b) : a div b = 0 :=
divide_def a b ⬝ if_neg (!not_and_of_not_right (not_le_of_lt h))
theorem zero_div (b : ℕ) : 0 div b = 0 :=
divide_def 0 b ⬝ if_neg (λ h, and.rec_on h (λ l r, absurd (lt_of_lt_of_le l r) (lt.irrefl 0)))
theorem div_eq_succ_sub_div {a b : ℕ} (h₁ : b > 0) (h₂ : a ≥ b) : a div b = succ ((a - b) div b) :=
divide_def a b ⬝ if_pos (and.intro h₁ h₂)
theorem add_div_self (x : ℕ) {z : ℕ} (H : z > 0) : (x + z) div z = succ (x div z) :=
calc
(x + z) div z = if 0 < z ∧ z ≤ x + z then (x + z - z) div z + 1 else 0 : !divide_def
... = (x + z - z) div z + 1 : if_pos (and.intro H (le_add_left z x))
... = succ (x div z) : {!add_sub_cancel}
theorem add_div_self_left {x : ℕ} (z : ℕ) (H : x > 0) : (x + z) div x = succ (z div x) :=
!add.comm ▸ !add_div_self H
theorem add_mul_div_self {x y z : ℕ} (H : z > 0) : (x + y * z) div z = x div z + y :=
nat.induction_on y
(calc (x + zero * z) div z = (x + zero) div z : zero_mul
... = x div z : add_zero
... = x div z + zero : add_zero)
(take y,
assume IH : (x + y * z) div z = x div z + y, calc
(x + succ y * z) div z = (x + y * z + z) div z : by simp
... = succ ((x + y * z) div z) : !add_div_self H
... = x div z + succ y : by simp)
theorem add_mul_div_self_left (x z : ℕ) {y : ℕ} (H : y > 0) : (x + y * z) div y = x div y + z :=
!mul.comm ▸ add_mul_div_self H
theorem mul_div_cancel (m : ℕ) {n : ℕ} (H : n > 0) : m * n div n = m :=
calc
m * n div n = (0 + m * n) div n : zero_add
... = 0 div n + m : add_mul_div_self H
... = 0 + m : zero_div
... = m : zero_add
theorem mul_div_cancel_left {m : ℕ} (n : ℕ) (H : m > 0) : m * n div m = n :=
!mul.comm ▸ !mul_div_cancel H
theorem mul_cancel_right_of_ne_zero {a b c : nat} : c ≠ 0 → a * c = b * c → a = b :=
assume h₁ h₂, by rewrite [-mul_div_cancel a (pos_of_ne_zero h₁), h₂, mul_div_cancel b (pos_of_ne_zero h₁)]
theorem mul_cancel_left_of_ne_zero {a b c : nat} : a ≠ 0 → a * b = a * c → b = c :=
assume h₁ h₂, mul_cancel_right_of_ne_zero h₁ (mul.comm a b ▸ mul.comm a c ▸ h₂)
private definition mod.F (x : nat) (f : Π x₁, x₁ < x → nat → nat) (y : nat) : nat :=
if H : 0 < y ∧ y ≤ x then f (x - y) (div_rec_lemma H) y else x
definition modulo (x y : nat) := fix mod.F x y
notation a mod b := modulo a b
theorem modulo_def (x y : nat) : modulo x y = if 0 < y ∧ y ≤ x then modulo (x - y) y else x :=
congr_fun (fix_eq mod.F x) y
theorem mod_zero (a : ℕ) : a mod 0 = a :=
modulo_def a 0 ⬝ if_neg (!not_and_of_not_left (lt.irrefl 0))
theorem mod_eq_of_lt {a b : ℕ} (h : a < b) : a mod b = a :=
modulo_def a b ⬝ if_neg (!not_and_of_not_right (not_le_of_lt h))
theorem zero_mod (b : ℕ) : 0 mod b = 0 :=
modulo_def 0 b ⬝ if_neg (λ h, and.rec_on h (λ l r, absurd (lt_of_lt_of_le l r) (lt.irrefl 0)))
theorem mod_eq_sub_mod {a b : ℕ} (h₁ : b > 0) (h₂ : a ≥ b) : a mod b = (a - b) mod b :=
modulo_def a b ⬝ if_pos (and.intro h₁ h₂)
theorem add_mod_self {x z : ℕ} (H : z > 0) : (x + z) mod z = x mod z :=
calc
(x + z) mod z = if 0 < z ∧ z ≤ x + z then (x + z - z) mod z else _ : modulo_def
... = (x + z - z) mod z : if_pos (and.intro H (le_add_left z x))
... = x mod z : add_sub_cancel
theorem add_mod_self_left {x z : ℕ} (H : x > 0) : (x + z) mod x = z mod x :=
!add.comm ▸ add_mod_self H
theorem add_mul_mod_self {x y z : ℕ} (H : z > 0) : (x + y * z) mod z = x mod z :=
nat.induction_on y
(calc (x + zero * z) mod z = (x + zero) mod z : zero_mul
... = x mod z : add_zero)
(take y,
assume IH : (x + y * z) mod z = x mod z,
calc
(x + succ y * z) mod z = (x + (y * z + z)) mod z : succ_mul
... = (x + y * z + z) mod z : add.assoc
... = (x + y * z) mod z : add_mod_self H
... = x mod z : IH)
theorem add_mul_mod_self_left {x y z : ℕ} (H : y > 0) : (x + y * z) mod y = x mod y :=
!mul.comm ▸ add_mul_mod_self H
theorem mul_mod_left {m n : ℕ} : (m * n) mod n = 0 :=
by_cases_zero_pos n (by simp)
(take n,
assume npos : n > 0,
(by simp) ▸ (@add_mul_mod_self 0 m _ npos))
theorem mul_mod_right {m n : ℕ} : (m * n) mod m = 0 :=
!mul.comm ▸ !mul_mod_left
theorem mod_lt {x y : ℕ} (H : y > 0) : x mod y < y :=
nat.case_strong_induction_on x
(show 0 mod y < y, from !zero_mod⁻¹ ▸ H)
(take x,
assume IH : ∀x', x' ≤ x → x' mod y < y,
show succ x mod y < y, from
by_cases -- (succ x < y)
(assume H1 : succ x < y,
have H2 : succ x mod y = succ x, from mod_eq_of_lt H1,
show succ x mod y < y, from H2⁻¹ ▸ H1)
(assume H1 : ¬ succ x < y,
have H2 : y ≤ succ x, from le_of_not_lt H1,
have H3 : succ x mod y = (succ x - y) mod y, from mod_eq_sub_mod H H2,
have H4 : succ x - y < succ x, from sub_lt !succ_pos H,
have H5 : succ x - y ≤ x, from le_of_lt_succ H4,
show succ x mod y < y, from H3⁻¹ ▸ IH _ H5))
/- properties of div and mod together -/
-- the quotient / remainder theorem
theorem eq_div_mul_add_mod {x y : ℕ} : x = x div y * y + x mod y :=
by_cases_zero_pos y
(show x = x div 0 * 0 + x mod 0, from
(calc
x div 0 * 0 + x mod 0 = 0 + x mod 0 : mul_zero
... = x mod 0 : zero_add
... = x : mod_zero)⁻¹)
(take y,
assume H : y > 0,
show x = x div y * y + x mod y, from
nat.case_strong_induction_on x
(show 0 = (0 div y) * y + 0 mod y, by simp)
(take x,
assume IH : ∀x', x' ≤ x → x' = x' div y * y + x' mod y,
show succ x = succ x div y * y + succ x mod y, from
by_cases -- (succ x < y)
(assume H1 : succ x < y,
have H2 : succ x div y = 0, from div_eq_zero_of_lt H1,
have H3 : succ x mod y = succ x, from mod_eq_of_lt H1,
by simp)
(assume H1 : ¬ succ x < y,
have H2 : y ≤ succ x, from le_of_not_lt H1,
have H3 : succ x div y = succ ((succ x - y) div y), from div_eq_succ_sub_div H H2,
have H4 : succ x mod y = (succ x - y) mod y, from mod_eq_sub_mod H H2,
have H5 : succ x - y < succ x, from sub_lt !succ_pos H,
have H6 : succ x - y ≤ x, from le_of_lt_succ H5,
(calc
succ x div y * y + succ x mod y =
succ ((succ x - y) div y) * y + succ x mod y : H3
... = ((succ x - y) div y) * y + y + succ x mod y : succ_mul
... = ((succ x - y) div y) * y + y + (succ x - y) mod y : H4
... = ((succ x - y) div y) * y + (succ x - y) mod y + y : add.right_comm
... = succ x - y + y : {!(IH _ H6)⁻¹}
... = succ x : sub_add_cancel H2)⁻¹)))
theorem mod_le {x y : ℕ} : x mod y ≤ x :=
eq_div_mul_add_mod⁻¹ ▸ !le_add_left
theorem eq_remainder {y : ℕ} (H : y > 0) {q1 r1 q2 r2 : ℕ} (H1 : r1 < y) (H2 : r2 < y)
(H3 : q1 * y + r1 = q2 * y + r2) : r1 = r2 :=
calc
r1 = r1 mod y : by simp
... = (r1 + q1 * y) mod y : (add_mul_mod_self H)⁻¹
... = (q1 * y + r1) mod y : add.comm
... = (r2 + q2 * y) mod y : by simp
... = r2 mod y : add_mul_mod_self H
... = r2 : by simp
theorem eq_quotient {y : ℕ} (H : y > 0) {q1 r1 q2 r2 : ℕ} (H1 : r1 < y) (H2 : r2 < y)
(H3 : q1 * y + r1 = q2 * y + r2) : q1 = q2 :=
have H4 : q1 * y + r2 = q2 * y + r2, from (eq_remainder H H1 H2 H3) ▸ H3,
have H5 : q1 * y = q2 * y, from add.cancel_right H4,
have H6 : y > 0, from lt_of_le_of_lt !zero_le H1,
show q1 = q2, from eq_of_mul_eq_mul_right H6 H5
theorem mul_div_mul_left {z : ℕ} (x y : ℕ) (zpos : z > 0) : (z * x) div (z * y) = x div y :=
by_cases -- (y = 0)
(assume H : y = 0, by simp)
(assume H : y ≠ 0,
have ypos : y > 0, from pos_of_ne_zero H,
have zypos : z * y > 0, from mul_pos zpos ypos,
have H1 : (z * x) mod (z * y) < z * y, from mod_lt zypos,
have H2 : z * (x mod y) < z * y, from mul_lt_mul_of_pos_left (mod_lt ypos) zpos,
eq_quotient zypos H1 H2
(calc
((z * x) div (z * y)) * (z * y) + (z * x) mod (z * y) = z * x : eq_div_mul_add_mod
... = z * (x div y * y + x mod y) : eq_div_mul_add_mod
... = z * (x div y * y) + z * (x mod y) : mul.left_distrib
... = (x div y) * (z * y) + z * (x mod y) : mul.left_comm))
theorem mul_div_mul_right {x z y : ℕ} (zpos : z > 0) : (x * z) div (y * z) = x div y :=
!mul.comm ▸ !mul.comm ▸ !mul_div_mul_left zpos
theorem mul_mod_mul_left (z x y : ℕ) : (z * x) mod (z * y) = z * (x mod y) :=
or.elim (eq_zero_or_pos z)
(assume H : z = 0,
calc
(z * x) mod (z * y) = (0 * x) mod (z * y) : H
... = 0 mod (z * y) : zero_mul
... = 0 : zero_mod
... = 0 * (x mod y) : zero_mul
... = z * (x mod y) : H)
(assume zpos : z > 0,
or.elim (eq_zero_or_pos y)
(assume H : y = 0, by simp)
(assume ypos : y > 0,
have zypos : z * y > 0, from mul_pos zpos ypos,
have H1 : (z * x) mod (z * y) < z * y, from mod_lt zypos,
have H2 : z * (x mod y) < z * y, from mul_lt_mul_of_pos_left (mod_lt ypos) zpos,
eq_remainder zypos H1 H2
(calc
((z * x) div (z * y)) * (z * y) + (z * x) mod (z * y) = z * x : eq_div_mul_add_mod
... = z * (x div y * y + x mod y) : eq_div_mul_add_mod
... = z * (x div y * y) + z * (x mod y) : mul.left_distrib
... = (x div y) * (z * y) + z * (x mod y) : mul.left_comm)))
theorem mul_mod_mul_right (x z y : ℕ) : (x * z) mod (y * z) = (x mod y) * z :=
mul.comm z x ▸ mul.comm z y ▸ !mul.comm ▸ !mul_mod_mul_left
theorem mod_one (n : ℕ) : n mod 1 = 0 :=
have H1 : n mod 1 < 1, from mod_lt !succ_pos,
eq_zero_of_le_zero (le_of_lt_succ H1)
theorem mod_self (n : ℕ) : n mod n = 0 :=
nat.cases_on n (by simp)
(take n,
have H : (succ n * 1) mod (succ n * 1) = succ n * (1 mod 1),
from !mul_mod_mul_left,
(by simp) ▸ H)
theorem div_one (n : ℕ) : n div 1 = n :=
have H : n div 1 * 1 + n mod 1 = n, from eq_div_mul_add_mod⁻¹,
(by simp) ▸ H
theorem div_self {n : ℕ} (H : n > 0) : n div n = 1 :=
have H1 : (n * 1) div (n * 1) = 1 div 1, from !mul_div_mul_left H,
(by simp) ▸ H1
theorem div_mul_cancel_of_mod_eq_zero {m n : ℕ} (H : m mod n = 0) : m div n * n = m :=
(calc
m = m div n * n + m mod n : eq_div_mul_add_mod
... = m div n * n + 0 : H
... = m div n * n : !add_zero)⁻¹
theorem mul_div_cancel_of_mod_eq_zero {m n : ℕ} (H : m mod n = 0) : n * (m div n) = m :=
!mul.comm ▸ div_mul_cancel_of_mod_eq_zero H
theorem div_lt_of_lt_mul {m n k : ℕ} (H : m < k * n) : m div k < n :=
lt_of_mul_lt_mul_right (calc
m div k * k ≤ m div k * k + m mod k : le_add_right
... = m : eq_div_mul_add_mod
... < k * n : H
... = n * k : nat.mul.comm)
theorem div_le_of_le_mul {m n k : ℕ} (H : m ≤ k * n) : m div k ≤ n :=
or.elim (eq_zero_or_pos k)
(assume H1 : k = 0,
calc
m div k = m div 0 : H1
... = 0 : div_zero
... ≤ n : zero_le)
(assume H1 : k > 0,
le_of_mul_le_mul_right (calc
m div k * k ≤ m div k * k + m mod k : le_add_right
... = m : eq_div_mul_add_mod
... ≤ k * n : H
... = n * k : nat.mul.comm) H1)
theorem div_le (m n : ℕ) : m div n ≤ m :=
nat.cases_on n (!div_zero⁻¹ ▸ !zero_le)
take n,
have H : m ≤ succ n * m, from calc
m = 1 * m : one_mul
... ≤ succ n * m : mul_le_mul_right (succ_le_succ !zero_le),
div_le_of_le_mul H
theorem mul_sub_div_of_lt {m n k : ℕ} (H : k < m * n) :
(m * n - (k + 1)) div m = n - k div m - 1 :=
have H1 : k div m < n, from div_lt_of_lt_mul H,
have H2 : n - k div m ≥ 1, from
le_sub_of_add_le (calc
1 + k div m = succ (k div m) : add.comm
... ≤ n : succ_le_of_lt H1),
assert H3 : n - k div m = n - k div m - 1 + 1, from (sub_add_cancel H2)⁻¹,
assert H4 : m > 0, from pos_of_ne_zero (assume H': m = 0, not_lt_zero _ (!zero_mul ▸ H' ▸ H)),
have H5 : k mod m + 1 ≤ m, from succ_le_of_lt (mod_lt H4),
assert H6 : m - (k mod m + 1) < m, from sub_lt_self H4 !succ_pos,
calc
(m * n - (k + 1)) div m = (m * n - (k div m * m + k mod m + 1)) div m : eq_div_mul_add_mod
... = (m * n - k div m * m - (k mod m + 1)) div m : by rewrite [*sub_sub]
... = ((n - k div m) * m - (k mod m + 1)) div m :
by rewrite [mul.comm m, mul_sub_right_distrib]
... = ((n - k div m - 1) * m + m - (k mod m + 1)) div m :
by rewrite [H3 at {1}, mul.right_distrib, nat.one_mul]
... = ((n - k div m - 1) * m + (m - (k mod m + 1))) div m : {add_sub_assoc H5 _}
... = (m - (k mod m + 1)) div m + (n - k div m - 1) :
by rewrite [add.comm, (add_mul_div_self H4)]
... = n - k div m - 1 :
by rewrite [div_eq_zero_of_lt H6, zero_add]
/- divides -/
theorem dvd_of_mod_eq_zero {m n : ℕ} (H : n mod m = 0) : m ∣ n :=
dvd.intro (!mul.comm ▸ div_mul_cancel_of_mod_eq_zero H)
theorem mod_eq_zero_of_dvd {m n : ℕ} (H : m ∣ n) : n mod m = 0 :=
dvd.elim H
(take z,
assume H1 : n = m * z,
H1⁻¹ ▸ !mul_mod_right)
theorem dvd_iff_mod_eq_zero (m n : ℕ) : m ∣ n ↔ n mod m = 0 :=
iff.intro mod_eq_zero_of_dvd dvd_of_mod_eq_zero
definition dvd.decidable_rel [instance] : decidable_rel dvd :=
take m n, decidable_of_decidable_of_iff _ (iff.symm !dvd_iff_mod_eq_zero)
theorem div_mul_cancel {m n : ℕ} (H : n ∣ m) : m div n * n = m :=
div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H)
theorem mul_div_cancel' {m n : ℕ} (H : n ∣ m) : n * (m div n) = m :=
!mul.comm ▸ div_mul_cancel H
theorem eq_mul_of_div_eq {m n k : ℕ} (H1 : m ∣ n) (H2 : n div m = k) : n = m * k :=
eq.symm (calc
m * k = m * (n div m) : H2
... = n : mul_div_cancel' H1)
theorem eq_div_of_mul_eq {m n k : ℕ} (H1 : k > 0) (H2 : n * k = m) : n = m div k :=
calc
n = n * k div k : mul_div_cancel _ H1
... = m div k : H2
theorem dvd_of_dvd_add_left {m n₁ n₂ : ℕ} (H₁ : m ∣ n₁ + n₂) (H₂ : m ∣ n₁) : m ∣ n₂ :=
obtain (c₁ : nat) (Hc₁ : n₁ + n₂ = m * c₁), from H₁,
obtain (c₂ : nat) (Hc₂ : n₁ = m * c₂), from H₂,
have aux : m * (c₁ - c₂) = n₂, from calc
m * (c₁ - c₂) = m * c₁ - m * c₂ : mul_sub_left_distrib
... = n₁ + n₂ - m * c₂ : Hc₁
... = n₁ + n₂ - n₁ : Hc₂
... = n₂ : add_sub_cancel_left,
dvd.intro aux
theorem dvd_of_dvd_add_right {m n1 n2 : ℕ} (H : m ∣ (n1 + n2)) : m ∣ n2 → m ∣ n1 :=
dvd_of_dvd_add_left (!add.comm ▸ H)
theorem dvd_sub {m n1 n2 : ℕ} (H1 : m ∣ n1) (H2 : m ∣ n2) : m ∣ n1 - n2 :=
by_cases
(assume H3 : n1 ≥ n2,
have H4 : n1 = n1 - n2 + n2, from (sub_add_cancel H3)⁻¹,
show m ∣ n1 - n2, from dvd_of_dvd_add_right (H4 ▸ H1) H2)
(assume H3 : ¬ (n1 ≥ n2),
have H4 : n1 - n2 = 0, from sub_eq_zero_of_le (le_of_lt (lt_of_not_le H3)),
show m ∣ n1 - n2, from H4⁻¹ ▸ dvd_zero _)
theorem dvd.antisymm {m n : ℕ} : m ∣ n → n ∣ m → m = n :=
by_cases_zero_pos n
(assume H1, assume H2 : 0 ∣ m, eq_zero_of_zero_dvd H2)
(take n,
assume Hpos : n > 0,
assume H1 : m ∣ n,
assume H2 : n ∣ m,
obtain k (Hk : n = m * k), from exists_eq_mul_right_of_dvd H1,
obtain l (Hl : m = n * l), from exists_eq_mul_right_of_dvd H2,
have H3 : n * (l * k) = n, from !mul.assoc ▸ Hl ▸ Hk⁻¹,
have H4 : l * k = 1, from eq_one_of_mul_eq_self_right Hpos H3,
have H5 : k = 1, from eq_one_of_mul_eq_one_left H4,
show m = n, from (mul_one m)⁻¹ ⬝ (H5 ▸ Hk⁻¹))
theorem mul_div_assoc (m : ℕ) {n k : ℕ} (H : k ∣ n) : m * n div k = m * (n div k) :=
or.elim (eq_zero_or_pos k)
(assume H1 : k = 0,
calc
m * n div k = m * n div 0 : H1
... = 0 : div_zero
... = m * 0 : mul_zero m
... = m * (n div 0) : div_zero
... = m * (n div k) : H1)
(assume H1 : k > 0,
have H2 : n = n div k * k, from (div_mul_cancel H)⁻¹,
calc
m * n div k = m * (n div k * k) div k : H2
... = m * (n div k) * k div k : mul.assoc
... = m * (n div k) : mul_div_cancel _ H1)
theorem dvd_of_mul_dvd_mul_left {m n k : ℕ} (kpos : k > 0) (H : k * m ∣ k * n) : m ∣ n :=
dvd.elim H
(take l,
assume H1 : k * n = k * m * l,
have H2 : n = m * l, from eq_of_mul_eq_mul_left kpos (H1 ⬝ !mul.assoc),
dvd.intro H2⁻¹)
theorem dvd_of_mul_dvd_mul_right {m n k : ℕ} (kpos : k > 0) (H : m * k ∣ n * k) : m ∣ n :=
dvd_of_mul_dvd_mul_left kpos (!mul.comm ▸ !mul.comm ▸ H)
theorem div_dvd_div {k m n : ℕ} (H1 : k ∣ m) (H2 : m ∣ n) : m div k ∣ n div k :=
have H3 : m = m div k * k, from (div_mul_cancel H1)⁻¹,
have H4 : n = n div k * k, from (div_mul_cancel (dvd.trans H1 H2))⁻¹,
or.elim (eq_zero_or_pos k)
(assume H5 : k = 0,
have H6: n div k = 0, from (congr_arg _ H5 ⬝ !div_zero),
H6⁻¹ ▸ !dvd_zero)
(assume H5 : k > 0,
dvd_of_mul_dvd_mul_right H5 (H3 ▸ H4 ▸ H2))
/- gcd -/
private definition pair_nat.lt : nat × nat → nat × nat → Prop := measure pr₂
private definition pair_nat.lt.wf : well_founded pair_nat.lt :=
intro_k (measure.wf pr₂) 20 -- we use intro_k to be able to execute gcd efficiently in the kernel
local attribute pair_nat.lt.wf [instance] -- instance will not be saved in .olean
local infixl `≺`:50 := pair_nat.lt
private definition gcd.lt.dec (x y₁ : nat) : (succ y₁, x mod succ y₁) ≺ (x, succ y₁) :=
mod_lt (succ_pos y₁)
definition gcd.F (p₁ : nat × nat) : (Π p₂ : nat × nat, p₂ ≺ p₁ → nat) → nat :=
prod.cases_on p₁ (λx y, nat.cases_on y
(λ f, x)
(λ y₁ (f : Πp₂, p₂ ≺ (x, succ y₁) → nat), f (succ y₁, x mod succ y₁) !gcd.lt.dec))
definition gcd (x y : nat) := fix gcd.F (pair x y)
theorem gcd_zero_right (x : nat) : gcd x 0 = x :=
well_founded.fix_eq gcd.F (x, 0)
theorem gcd_succ (x y : nat) : gcd x (succ y) = gcd (succ y) (x mod succ y) :=
well_founded.fix_eq gcd.F (x, succ y)
theorem gcd_one_right (n : ℕ) : gcd n 1 = 1 :=
calc gcd n 1 = gcd 1 (n mod 1) : gcd_succ n zero
... = gcd 1 0 : mod_one
... = 1 : gcd_zero_right
theorem gcd_def (x y : ℕ) : gcd x y = if y = 0 then x else gcd y (x mod y) :=
nat.cases_on y
(calc gcd x 0 = x : gcd_zero_right x
... = if 0 = 0 then x else gcd zero (x mod zero) : (if_pos rfl)⁻¹)
(λy₁, calc
gcd x (succ y₁) = gcd (succ y₁) (x mod succ y₁) : gcd_succ x y₁
... = if succ y₁ = 0 then x else gcd (succ y₁) (x mod succ y₁) : (if_neg (succ_ne_zero y₁))⁻¹)
theorem gcd_self (n : ℕ) : gcd n n = n :=
nat.cases_on n
rfl
(λn₁, calc
gcd (succ n₁) (succ n₁) = gcd (succ n₁) (succ n₁ mod succ n₁) : gcd_succ (succ n₁) n₁
... = gcd (succ n₁) 0 : mod_self (succ n₁)
... = succ n₁ : gcd_zero_right)
theorem gcd_zero_left (n : nat) : gcd 0 n = n :=
nat.cases_on n
rfl
(λ n₁, calc
gcd 0 (succ n₁) = gcd (succ n₁) (0 mod succ n₁) : gcd_succ
... = gcd (succ n₁) 0 : zero_mod
... = (succ n₁) : gcd_zero_right)
theorem gcd_rec_of_pos (m : ℕ) {n : ℕ} (H : n > 0) : gcd m n = gcd n (m mod n) :=
gcd_def m n ⬝ if_neg (ne_zero_of_pos H)
theorem gcd_rec (m n : ℕ) : gcd m n = gcd n (m mod n) :=
by_cases_zero_pos n
(calc
gcd m 0 = m : gcd_zero_right
... = gcd 0 m : gcd_zero_left
... = gcd 0 (m mod 0) : mod_zero)
(take n, assume H : 0 < n, gcd_rec_of_pos m H)
theorem gcd.induction {P : ℕ → ℕ → Prop}
(m n : ℕ)
(H0 : ∀m, P m 0)
(H1 : ∀m n, 0 < n → P n (m mod n) → P m n) :
P m n :=
let Q : nat × nat → Prop := λ p : nat × nat, P (pr₁ p) (pr₂ p) in
have aux : Q (m, n), from
well_founded.induction (m, n) (λp, prod.cases_on p
(λm n, nat.cases_on n
(λ ih, show P (pr₁ (m, 0)) (pr₂ (m, 0)), from H0 m)
(λ n₁ (ih : ∀p₂, p₂ ≺ (m, succ n₁) → P (pr₁ p₂) (pr₂ p₂)),
have hlt₁ : 0 < succ n₁, from succ_pos n₁,
have hlt₂ : (succ n₁, m mod succ n₁) ≺ (m, succ n₁), from gcd.lt.dec _ _,
have hp : P (succ n₁) (m mod succ n₁), from ih _ hlt₂,
show P m (succ n₁), from
H1 m (succ n₁) hlt₁ hp))),
aux
theorem gcd_dvd (m n : ℕ) : (gcd m n ∣ m) ∧ (gcd m n ∣ n) :=
gcd.induction m n
(take m,
show (gcd m 0 ∣ m) ∧ (gcd m 0 ∣ 0), by simp)
(take m n,
assume npos : 0 < n,
assume IH : (gcd n (m mod n) ∣ n) ∧ (gcd n (m mod n) ∣ (m mod n)),
have H : (gcd n (m mod n) ∣ (m div n * n + m mod n)), from
dvd_add (dvd.trans (and.elim_left IH) !dvd_mul_left) (and.elim_right IH),
have H1 : (gcd n (m mod n) ∣ m), from eq_div_mul_add_mod⁻¹ ▸ H,
have gcd_eq : gcd n (m mod n) = gcd m n, from !gcd_rec⁻¹,
show (gcd m n ∣ m) ∧ (gcd m n ∣ n), from gcd_eq ▸ (and.intro H1 (and.elim_left IH)))
theorem gcd_dvd_left (m n : ℕ) : gcd m n ∣ m := and.elim_left !gcd_dvd
theorem gcd_dvd_right (m n : ℕ) : gcd m n ∣ n := and.elim_right !gcd_dvd
theorem dvd_gcd {m n k : ℕ} : k ∣ m → k ∣ n → k ∣ gcd m n :=
gcd.induction m n
(take m, assume (h₁ : k ∣ m) (h₂ : k ∣ 0),
show k ∣ gcd m 0, from !gcd_zero_right⁻¹ ▸ h₁)
(take m n,
assume npos : n > 0,
assume IH : k ∣ n → k ∣ m mod n → k ∣ gcd n (m mod n),
assume H1 : k ∣ m,
assume H2 : k ∣ n,
have H3 : k ∣ m div n * n + m mod n, from eq_div_mul_add_mod ▸ H1,
have H4 : k ∣ m mod n, from nat.dvd_of_dvd_add_left H3 (dvd.trans H2 (by simp)),
have gcd_eq : gcd n (m mod n) = gcd m n, from !gcd_rec⁻¹,
show k ∣ gcd m n, from gcd_eq ▸ IH H2 H4)
theorem gcd.comm (m n : ℕ) : gcd m n = gcd n m :=
dvd.antisymm
(dvd_gcd !gcd_dvd_right !gcd_dvd_left)
(dvd_gcd !gcd_dvd_right !gcd_dvd_left)
theorem gcd.assoc (m n k : ℕ) : gcd (gcd m n) k = gcd m (gcd n k) :=
dvd.antisymm
(dvd_gcd
(dvd.trans !gcd_dvd_left !gcd_dvd_left)
(dvd_gcd (dvd.trans !gcd_dvd_left !gcd_dvd_right) !gcd_dvd_right))
(dvd_gcd
(dvd_gcd !gcd_dvd_left (dvd.trans !gcd_dvd_right !gcd_dvd_left))
(dvd.trans !gcd_dvd_right !gcd_dvd_right))
theorem gcd_one_left (m : ℕ) : gcd 1 m = 1 :=
!gcd.comm ⬝ !gcd_one_right
theorem gcd_mul_left (m n k : ℕ) : gcd (m * n) (m * k) = m * gcd n k :=
gcd.induction n k
(take n,
calc
gcd (m * n) (m * 0) = gcd (m * n) 0 : mul_zero
... = m * n : gcd_zero_right
... = m * gcd n 0 : gcd_zero_right)
(take n k,
assume H : 0 < k,
assume IH : gcd (m * k) (m * (n mod k)) = m * gcd k (n mod k),
calc
gcd (m * n) (m * k) = gcd (m * k) (m * n mod (m * k)) : !gcd_rec
... = gcd (m * k) (m * (n mod k)) : mul_mod_mul_left
... = m * gcd k (n mod k) : IH
... = m * gcd n k : !gcd_rec)
theorem gcd_mul_right (m n k : ℕ) : gcd (m * n) (k * n) = gcd m k * n :=
calc
gcd (m * n) (k * n) = gcd (n * m) (k * n) : mul.comm
... = gcd (n * m) (n * k) : mul.comm
... = n * gcd m k : gcd_mul_left
... = gcd m k * n : mul.comm
theorem gcd_pos_of_pos_left {m : ℕ} (n : ℕ) (mpos : m > 0) : gcd m n > 0 :=
pos_of_dvd_of_pos !gcd_dvd_left mpos
theorem gcd_pos_of_pos_right (m : ℕ) {n : ℕ} (npos : n > 0) : gcd m n > 0 :=
pos_of_dvd_of_pos !gcd_dvd_right npos
theorem eq_zero_of_gcd_eq_zero_left {m n : ℕ} (H : gcd m n = 0) : m = 0 :=
or.elim (eq_zero_or_pos m)
(assume H1, H1)
(assume H1 : m > 0, absurd H⁻¹ (ne_of_lt (!gcd_pos_of_pos_left H1)))
theorem eq_zero_of_gcd_eq_zero_right {m n : ℕ} (H : gcd m n = 0) : n = 0 :=
eq_zero_of_gcd_eq_zero_left (!gcd.comm ▸ H)
theorem gcd_div {m n k : ℕ} (H1 : (k ∣ m)) (H2 : (k ∣ n)) : gcd (m div k) (n div k) = gcd m n div k :=
or.elim (eq_zero_or_pos k)
(assume H3 : k = 0,
calc
gcd (m div k) (n div k) = gcd (m div 0) (n div k) : H3
... = gcd 0 (n div k) : div_zero
... = n div k : gcd_zero_left
... = n div 0 : H3
... = 0 : div_zero
... = gcd m n div 0 : div_zero
... = gcd m n div k : H3)
(assume H3 : k > 0,
eq_div_of_mul_eq H3
(calc
gcd (m div k) (n div k) * k = gcd (m div k * k) (n div k * k) : gcd_mul_right
... = gcd m (n div k * k) : div_mul_cancel H1
... = gcd m n : div_mul_cancel H2))
theorem gcd_dvd_gcd_mul_left (m n k : ℕ) : gcd m n ∣ gcd (k * m) n :=
dvd_gcd (dvd.trans !gcd_dvd_left !dvd_mul_left) !gcd_dvd_right
theorem gcd_dvd_gcd_mul_right (m n k : ℕ) : gcd m n ∣ gcd (m * k) n :=
!mul.comm ▸ !gcd_dvd_gcd_mul_left
theorem gcd_dvd_gcd_mul_left_right (m n k : ℕ) : gcd m n ∣ gcd m (k * n) :=
dvd_gcd !gcd_dvd_left (dvd.trans !gcd_dvd_right !dvd_mul_left)
theorem gcd_dvd_gcd_mul_right_right (m n k : ℕ) : gcd m n ∣ gcd m (n * k) :=
!mul.comm ▸ !gcd_dvd_gcd_mul_left_right
/- lcm -/
definition lcm (m n : ℕ) : ℕ := m * n div (gcd m n)
theorem lcm.comm (m n : ℕ) : lcm m n = lcm n m :=
calc
lcm m n = m * n div gcd m n : rfl
... = n * m div gcd m n : mul.comm
... = n * m div gcd n m : gcd.comm
... = lcm n m : rfl
theorem lcm_zero_left (m : ℕ) : lcm 0 m = 0 :=
calc
lcm 0 m = 0 * m div gcd 0 m : rfl
... = 0 div gcd 0 m : zero_mul
... = 0 : zero_div
theorem lcm_zero_right (m : ℕ) : lcm m 0 = 0 := !lcm.comm ▸ !lcm_zero_left
theorem lcm_one_left (m : ℕ) : lcm 1 m = m :=
calc
lcm 1 m = 1 * m div gcd 1 m : rfl
... = m div gcd 1 m : one_mul
... = m div 1 : gcd_one_left
... = m : div_one
theorem lcm_one_right (m : ℕ) : lcm m 1 = m := !lcm.comm ▸ !lcm_one_left
theorem lcm_self (m : ℕ) : lcm m m = m :=
have H : m * m div m = m, from
by_cases_zero_pos m !div_zero (take m, assume H1 : m > 0, !mul_div_cancel H1),
calc
lcm m m = m * m div gcd m m : rfl
... = m * m div m : gcd_self
... = m : H
theorem dvd_lcm_left (m n : ℕ) : m ∣ lcm m n :=
have H : lcm m n = m * (n div gcd m n), from mul_div_assoc _ !gcd_dvd_right,
dvd.intro H⁻¹
theorem dvd_lcm_right (m n : ℕ) : n ∣ lcm m n :=
!lcm.comm ▸ !dvd_lcm_left
theorem gcd_mul_lcm (m n : ℕ) : gcd m n * lcm m n = m * n :=
eq.symm (eq_mul_of_div_eq (dvd.trans !gcd_dvd_left !dvd_mul_right) rfl)
theorem lcm_dvd {m n k : ℕ} (H1 : m ∣ k) (H2 : n ∣ k) : lcm m n ∣ k :=
or.elim (eq_zero_or_pos k)
(assume kzero : k = 0, !kzero⁻¹ ▸ !dvd_zero)
(assume kpos : k > 0,
have mpos : m > 0, from pos_of_dvd_of_pos H1 kpos,
have npos : n > 0, from pos_of_dvd_of_pos H2 kpos,
have gcd_pos : gcd m n > 0, from !gcd_pos_of_pos_left mpos,
obtain p (km : k = m * p), from exists_eq_mul_right_of_dvd H1,
obtain q (kn : k = n * q), from exists_eq_mul_right_of_dvd H2,
have ppos : p > 0, from pos_of_mul_pos_left (km ▸ kpos),
have qpos : q > 0, from pos_of_mul_pos_left (kn ▸ kpos),
have H3 : p * q * (m * n * gcd p q) = p * q * (gcd m n * k), from
calc
p * q * (m * n * gcd p q) = p * (q * (m * n * gcd p q)) : mul.assoc
... = p * (q * (m * (n * gcd p q))) : mul.assoc
... = p * (m * (q * (n * gcd p q))) : mul.left_comm
... = p * m * (q * (n * gcd p q)) : mul.assoc
... = p * m * (q * n * gcd p q) : mul.assoc
... = m * p * (q * n * gcd p q) : mul.comm
... = k * (q * n * gcd p q) : km
... = k * (n * q * gcd p q) : mul.comm
... = k * (k * gcd p q) : kn
... = k * gcd (k * p) (k * q) : gcd_mul_left
... = k * gcd (n * q * p) (k * q) : kn
... = k * gcd (n * q * p) (m * p * q) : km
... = k * gcd (n * (q * p)) (m * p * q) : mul.assoc
... = k * gcd (n * (q * p)) (m * (p * q)) : mul.assoc
... = k * gcd (n * (p * q)) (m * (p * q)) : mul.comm
... = k * (gcd n m * (p * q)) : gcd_mul_right
... = gcd n m * (p * q) * k : mul.comm
... = p * q * gcd n m * k : mul.comm
... = p * q * (gcd n m * k) : mul.assoc
... = p * q * (gcd m n * k) : gcd.comm,
have H4 : m * n * gcd p q = gcd m n * k,
from !eq_of_mul_eq_mul_left (mul_pos ppos qpos) H3,
have H5 : gcd m n * (lcm m n * gcd p q) = gcd m n * k,
from !mul.assoc ▸ !gcd_mul_lcm⁻¹ ▸ H4,
have H6 : lcm m n * gcd p q = k,
from !eq_of_mul_eq_mul_left gcd_pos H5,
dvd.intro H6)
theorem lcm_assoc (m n k : ℕ) : lcm (lcm m n) k = lcm m (lcm n k) :=
dvd.antisymm
(lcm_dvd
(lcm_dvd !dvd_lcm_left (dvd.trans !dvd_lcm_left !dvd_lcm_right))
(dvd.trans !dvd_lcm_right !dvd_lcm_right))
(lcm_dvd
(dvd.trans !dvd_lcm_left !dvd_lcm_left)
(lcm_dvd (dvd.trans !dvd_lcm_right !dvd_lcm_left) !dvd_lcm_right))
/- coprime -/
definition coprime [reducible] (m n : ℕ) : Prop := gcd m n = 1
theorem coprime_swap {m n : ℕ} (H : coprime n m) : coprime m n :=
!gcd.comm ▸ H
theorem dvd_of_coprime_of_dvd_mul_right {m n k : ℕ} (H1 : coprime k n) (H2 : k ∣ m * n) : k ∣ m :=
have H3 : gcd (m * k) (m * n) = m, from
calc
gcd (m * k) (m * n) = m * gcd k n : gcd_mul_left
... = m * 1 : H1
... = m : mul_one,
have H4 : (k ∣ gcd (m * k) (m * n)), from dvd_gcd !dvd_mul_left H2,
H3 ▸ H4
theorem dvd_of_coprime_of_dvd_mul_left {m n k : ℕ} (H1 : coprime k m) (H2 : k ∣ m * n) : k ∣ n :=
dvd_of_coprime_of_dvd_mul_right H1 (!mul.comm ▸ H2)
theorem gcd_mul_left_cancel_of_coprime {k : ℕ} (m : ℕ) {n : ℕ} (H : coprime k n) :
gcd (k * m) n = gcd m n :=
have H1 : coprime (gcd (k * m) n) k, from
calc
gcd (gcd (k * m) n) k = gcd k (gcd (k * m) n) : gcd.comm
... = gcd (gcd k (k * m)) n : gcd.assoc
... = gcd (gcd (k * 1) (k * m)) n : mul_one
... = gcd (k * gcd 1 m) n : gcd_mul_left
... = gcd (k * 1) n : gcd_one_left
... = gcd k n : mul_one
... = 1 : H,
dvd.antisymm
(dvd_gcd (dvd_of_coprime_of_dvd_mul_left H1 !gcd_dvd_left) !gcd_dvd_right)
(dvd_gcd (dvd.trans !gcd_dvd_left !dvd_mul_left) !gcd_dvd_right)
theorem gcd_mul_right_cancel_of_coprime (m : ℕ) {k n : ℕ} (H : coprime k n) :
gcd (m * k) n = gcd m n :=
!mul.comm ▸ !gcd_mul_left_cancel_of_coprime H
theorem gcd_mul_left_cancel_of_coprime_right {k m : ℕ} (n : ℕ) (H : coprime k m) :
gcd m (k * n) = gcd m n :=
!gcd.comm ▸ !gcd.comm ▸ !gcd_mul_left_cancel_of_coprime H
theorem gcd_mul_right_cancel_of_coprime_right {k m : ℕ} (n : ℕ) (H : coprime k m) :
gcd m (n * k) = gcd m n :=
!gcd.comm ▸ !gcd.comm ▸ !gcd_mul_right_cancel_of_coprime H
theorem coprime_div_gcd_div_gcd {m n : ℕ} (H : gcd m n > 0) :
coprime (m div gcd m n) (n div gcd m n) :=
calc
gcd (m div gcd m n) (n div gcd m n) = gcd m n div gcd m n : gcd_div !gcd_dvd_left !gcd_dvd_right
... = 1 : div_self H
theorem exists_coprime {m n : ℕ} (H : gcd m n > 0) :
exists m' n', coprime m' n' ∧ m = m' * gcd m n ∧ n = n' * gcd m n :=
have H1 : m = (m div gcd m n) * gcd m n, from (div_mul_cancel !gcd_dvd_left)⁻¹,
have H2 : n = (n div gcd m n) * gcd m n, from (div_mul_cancel !gcd_dvd_right)⁻¹,
exists.intro _ (exists.intro _ (and.intro (coprime_div_gcd_div_gcd H) (and.intro H1 H2)))
theorem coprime_mul {m n k : ℕ} (H1 : coprime m k) (H2 : coprime n k) : coprime (m * n) k :=
calc
gcd (m * n) k = gcd n k : !gcd_mul_left_cancel_of_coprime H1
... = 1 : H2
theorem coprime_mul_right {k m n : ℕ} (H1 : coprime k m) (H2 : coprime k n) : coprime k (m * n) :=
coprime_swap (coprime_mul (coprime_swap H1) (coprime_swap H2))
theorem coprime_of_coprime_mul_left {k m n : ℕ} (H : coprime (k * m) n) : coprime m n :=
have H1 : (gcd m n ∣ gcd (k * m) n), from !gcd_dvd_gcd_mul_left,
eq_one_of_dvd_one (H ▸ H1)
theorem coprime_of_coprime_mul_right {k m n : ℕ} (H : coprime (m * k) n) : coprime m n :=
coprime_of_coprime_mul_left (!mul.comm ▸ H)
theorem coprime_of_coprime_mul_left_right {k m n : ℕ} (H : coprime m (k * n)) : coprime m n :=
coprime_swap (coprime_of_coprime_mul_left (coprime_swap H))
theorem coprime_of_coprime_mul_right_right {k m n : ℕ} (H : coprime m (n * k)) : coprime m n :=
coprime_of_coprime_mul_left_right (!mul.comm ▸ H)
theorem exists_eq_prod_and_dvd_and_dvd {m n k} (H : k ∣ m * n) :
∃ m' n', k = m' * n' ∧ m' ∣ m ∧ n' ∣ n :=
or.elim (eq_zero_or_pos (gcd k m))
(assume H1 : gcd k m = 0,
have H2 : k = 0, from eq_zero_of_gcd_eq_zero_left H1,
have H3 : m = 0, from eq_zero_of_gcd_eq_zero_right H1,
have H4 : k = 0 * n, from H2 ⬝ !zero_mul⁻¹,
have H5 : 0 ∣ m, from H3⁻¹ ▸ !dvd.refl,
have H6 : n ∣ n, from !dvd.refl,
exists.intro _ (exists.intro _ (and.intro H4 (and.intro H5 H6))))
(assume H1 : gcd k m > 0,
have H2 : gcd k m ∣ k, from !gcd_dvd_left,
have H3 : k div gcd k m ∣ (m * n) div gcd k m, from div_dvd_div H2 H,
have H4 : (m * n) div gcd k m = (m div gcd k m) * n, from
calc
m * n div gcd k m = n * m div gcd k m : mul.comm
... = n * (m div gcd k m) : !mul_div_assoc !gcd_dvd_right
... = m div gcd k m * n : mul.comm,
have H5 : k div gcd k m ∣ (m div gcd k m) * n, from H4 ▸ H3,
have H6 : coprime (k div gcd k m) (m div gcd k m), from coprime_div_gcd_div_gcd H1,
have H7 : k div gcd k m ∣ n, from dvd_of_coprime_of_dvd_mul_left H6 H5,
have H8 : k = gcd k m * (k div gcd k m), from (mul_div_cancel' H2)⁻¹,
exists.intro _ (exists.intro _ (and.intro H8 (and.intro !gcd_dvd_right H7))))
end nat
|
a52ffdc0c5e7030e50f9c63c94452bb206a71c7b | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/linear_algebra/contraction.lean | 4cd0bf74772b0431144ca9736462fde3fabd2b2d | [
"Apache-2.0"
] | permissive | gebner/mathlib | eab0150cc4f79ec45d2016a8c21750244a2e7ff0 | cc6a6edc397c55118df62831e23bfbd6e6c6b4ab | refs/heads/master | 1,625,574,853,976 | 1,586,712,827,000 | 1,586,712,827,000 | 99,101,412 | 1 | 0 | Apache-2.0 | 1,586,716,389,000 | 1,501,667,958,000 | Lean | UTF-8 | Lean | false | false | 1,883 | 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 linear_algebra.tensor_product
import linear_algebra.dual
/-!
# Contractions
Given modules $M, N$ over a commutative ring $R$, this file defines the natural linear maps:
$M^* \otimes M \to R$, $M \otimes M^* \to R$, and $M^* \otimes N → Hom(M, N)$, as well as proving
some basic properties of these maps.
## Tags
contraction, dual module, tensor product
-/
universes u v
set_option class.instance_max_depth 50
section contraction
open tensor_product
open_locale tensor_product
variables (R : Type u) (M N : Type v)
variables [comm_ring R] [add_comm_group M] [add_comm_group N] [module R M] [module R N]
/-- The natural left-handed pairing between a module and its dual. -/
def contract_left : (module.dual R M) ⊗ M →ₗ[R] R := (uncurry _ _ _ _).to_fun linear_map.id
/-- The natural right-handed pairing between a module and its dual. -/
def contract_right : M ⊗ (module.dual R M) →ₗ[R] R := (uncurry _ _ _ _).to_fun linear_map.id.flip
/-- The natural map associating a linear map to the tensor product of two modules. -/
def dual_tensor_hom : (module.dual R M) ⊗ N →ₗ M →ₗ N :=
let M' := module.dual R M in
(uncurry R M' N (M →ₗ[R] N) : _ → M' ⊗ N →ₗ M →ₗ N) linear_map.smul_rightₗ
variables {R M N}
@[simp] lemma contract_left_apply (f : module.dual R M) (m : M) :
contract_left R M (f ⊗ₜ m) = f m := by apply uncurry_apply
@[simp] lemma contract_right_apply (f : module.dual R M) (m : M) :
contract_right R M (m ⊗ₜ f) = f m := by apply uncurry_apply
@[simp] lemma dual_tensor_hom_apply (f : module.dual R M) (m : M) (n : N) :
dual_tensor_hom R M N (f ⊗ₜ n) m = (f m) • n :=
by { dunfold dual_tensor_hom, rw uncurry_apply, refl, }
end contraction
|
6f89150f590ff3a90090dd010ad92e8e39a88c94 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/sum.lean | e9763567250cdd32f370ba72e2337b58e7616fdb | [] | 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 | 11,244 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Yury G. Kudryashov
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.logic.function.basic
import Mathlib.PostPort
universes u_1 u_2 u v w x u_3 u_4
namespace Mathlib
/-!
# More theorems about the sum type
-/
/-- Check if a sum is `inl` and if so, retrieve its contents. -/
@[simp] def sum.get_left {α : Type u_1} {β : Type u_2} : α ⊕ β → Option α :=
sorry
/-- Check if a sum is `inr` and if so, retrieve its contents. -/
@[simp] def sum.get_right {α : Type u_1} {β : Type u_2} : α ⊕ β → Option β :=
sorry
/-- Check if a sum is `inl`. -/
@[simp] def sum.is_left {α : Type u_1} {β : Type u_2} : α ⊕ β → Bool :=
sorry
/-- Check if a sum is `inr`. -/
@[simp] def sum.is_right {α : Type u_1} {β : Type u_2} : α ⊕ β → Bool :=
sorry
protected instance sum.decidable_eq (α : Type u) [a : DecidableEq α] (β : Type v) : [a : DecidableEq β] → DecidableEq (α ⊕ β) := sorry
@[simp] theorem sum.forall {α : Type u} {β : Type v} {p : α ⊕ β → Prop} : (∀ (x : α ⊕ β), p x) ↔ (∀ (a : α), p (sum.inl a)) ∧ ∀ (b : β), p (sum.inr b) := sorry
@[simp] theorem sum.exists {α : Type u} {β : Type v} {p : α ⊕ β → Prop} : (∃ (x : α ⊕ β), p x) ↔ (∃ (a : α), p (sum.inl a)) ∨ ∃ (b : β), p (sum.inr b) := sorry
namespace sum
theorem injective_inl {α : Type u} {β : Type v} : function.injective inl :=
fun (x y : α) => inl.inj
theorem injective_inr {α : Type u} {β : Type v} : function.injective inr :=
fun (x y : β) => inr.inj
/-- Map `α ⊕ β` to `α' ⊕ β'` sending `α` to `α'` and `β` to `β'`. -/
protected def map {α : Type u} {α' : Type w} {β : Type v} {β' : Type x} (f : α → α') (g : β → β') : α ⊕ β → α' ⊕ β' :=
sorry
@[simp] theorem map_inl {α : Type u} {α' : Type w} {β : Type v} {β' : Type x} (f : α → α') (g : β → β') (x : α) : sum.map f g (inl x) = inl (f x) :=
rfl
@[simp] theorem map_inr {α : Type u} {α' : Type w} {β : Type v} {β' : Type x} (f : α → α') (g : β → β') (x : β) : sum.map f g (inr x) = inr (g x) :=
rfl
@[simp] theorem map_map {α : Type u} {α' : Type w} {β : Type v} {β' : Type x} {α'' : Type u_1} {β'' : Type u_2} (f' : α' → α'') (g' : β' → β'') (f : α → α') (g : β → β') (x : α ⊕ β) : sum.map f' g' (sum.map f g x) = sum.map (f' ∘ f) (g' ∘ g) x :=
sum.cases_on x (fun (x : α) => idRhs (sum.map f' g' (sum.map f g (inl x)) = sum.map f' g' (sum.map f g (inl x))) rfl)
fun (x : β) => idRhs (sum.map f' g' (sum.map f g (inr x)) = sum.map f' g' (sum.map f g (inr x))) rfl
@[simp] theorem map_comp_map {α : Type u} {α' : Type w} {β : Type v} {β' : Type x} {α'' : Type u_1} {β'' : Type u_2} (f' : α' → α'') (g' : β' → β'') (f : α → α') (g : β → β') : sum.map f' g' ∘ sum.map f g = sum.map (f' ∘ f) (g' ∘ g) :=
funext (map_map f' g' f g)
@[simp] theorem map_id_id (α : Type u_1) (β : Type u_2) : sum.map id id = id :=
funext fun (x : α ⊕ β) => sum.rec_on x (fun (_x : α) => rfl) fun (_x : β) => rfl
theorem inl.inj_iff {α : Type u} {β : Type v} {a : α} {b : α} : inl a = inl b ↔ a = b :=
{ mp := inl.inj, mpr := congr_arg fun {a : α} => inl a }
theorem inr.inj_iff {α : Type u} {β : Type v} {a : β} {b : β} : inr a = inr b ↔ a = b :=
{ mp := inr.inj, mpr := congr_arg fun {a : β} => inr a }
theorem inl_ne_inr {α : Type u} {β : Type v} {a : α} {b : β} : inl a ≠ inr b :=
fun (ᾰ : inl a = inr b) =>
eq.dcases_on ᾰ (fun (H_1 : inr b = inl a) => sum.no_confusion H_1) (Eq.refl (inr b)) (HEq.refl ᾰ)
theorem inr_ne_inl {α : Type u} {β : Type v} {a : α} {b : β} : inr b ≠ inl a :=
fun (ᾰ : inr b = inl a) =>
eq.dcases_on ᾰ (fun (H_1 : inl a = inr b) => sum.no_confusion H_1) (Eq.refl (inl a)) (HEq.refl ᾰ)
/-- Define a function on `α ⊕ β` by giving separate definitions on `α` and `β`. -/
protected def elim {α : Type u_1} {β : Type u_2} {γ : Sort u_3} (f : α → γ) (g : β → γ) : α ⊕ β → γ :=
fun (x : α ⊕ β) => sum.rec_on x f g
@[simp] theorem elim_inl {α : Type u_1} {β : Type u_2} {γ : Sort u_3} (f : α → γ) (g : β → γ) (x : α) : sum.elim f g (inl x) = f x :=
rfl
@[simp] theorem elim_inr {α : Type u_1} {β : Type u_2} {γ : Sort u_3} (f : α → γ) (g : β → γ) (x : β) : sum.elim f g (inr x) = g x :=
rfl
@[simp] theorem elim_comp_inl {α : Type u_1} {β : Type u_2} {γ : Sort u_3} (f : α → γ) (g : β → γ) : sum.elim f g ∘ inl = f :=
rfl
@[simp] theorem elim_comp_inr {α : Type u_1} {β : Type u_2} {γ : Sort u_3} (f : α → γ) (g : β → γ) : sum.elim f g ∘ inr = g :=
rfl
@[simp] theorem elim_inl_inr {α : Type u_1} {β : Type u_2} : sum.elim inl inr = id :=
funext fun (x : α ⊕ β) => sum.cases_on x (fun (_x : α) => rfl) fun (_x : β) => rfl
theorem comp_elim {α : Type u_1} {β : Type u_2} {γ : Sort u_3} {δ : Sort u_4} (f : γ → δ) (g : α → γ) (h : β → γ) : f ∘ sum.elim g h = sum.elim (f ∘ g) (f ∘ h) :=
funext fun (x : α ⊕ β) => sum.cases_on x (fun (_x : α) => rfl) fun (_x : β) => rfl
@[simp] theorem elim_comp_inl_inr {α : Type u_1} {β : Type u_2} {γ : Sort u_3} (f : α ⊕ β → γ) : sum.elim (f ∘ inl) (f ∘ inr) = f :=
funext fun (x : α ⊕ β) => sum.cases_on x (fun (_x : α) => rfl) fun (_x : β) => rfl
@[simp] theorem update_elim_inl {α : Type u_1} {β : Type u_2} {γ : Sort u_3} [DecidableEq α] [DecidableEq (α ⊕ β)] {f : α → γ} {g : β → γ} {i : α} {x : γ} : function.update (sum.elim f g) (inl i) x = sum.elim (function.update f i x) g := sorry
@[simp] theorem update_elim_inr {α : Type u_1} {β : Type u_2} {γ : Sort u_3} [DecidableEq β] [DecidableEq (α ⊕ β)] {f : α → γ} {g : β → γ} {i : β} {x : γ} : function.update (sum.elim f g) (inr i) x = sum.elim f (function.update g i x) := sorry
@[simp] theorem update_inl_comp_inl {α : Type u_1} {β : Type u_2} {γ : Sort u_3} [DecidableEq α] [DecidableEq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {x : γ} : function.update f (inl i) x ∘ inl = function.update (f ∘ inl) i x :=
function.update_comp_eq_of_injective f injective_inl i x
@[simp] theorem update_inl_apply_inl {α : Type u_1} {β : Type u_2} {γ : Sort u_3} [DecidableEq α] [DecidableEq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {j : α} {x : γ} : function.update f (inl i) x (inl j) = function.update (f ∘ inl) i x j := sorry
@[simp] theorem update_inl_comp_inr {α : Type u_1} {β : Type u_2} {γ : Sort u_3} [DecidableEq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {x : γ} : function.update f (inl i) x ∘ inr = f ∘ inr :=
function.update_comp_eq_of_forall_ne f x fun (_x : β) => inr_ne_inl
@[simp] theorem update_inl_apply_inr {α : Type u_1} {β : Type u_2} {γ : Sort u_3} [DecidableEq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {j : β} {x : γ} : function.update f (inl i) x (inr j) = f (inr j) :=
function.update_noteq inr_ne_inl x f
@[simp] theorem update_inr_comp_inl {α : Type u_1} {β : Type u_2} {γ : Sort u_3} [DecidableEq (α ⊕ β)] {f : α ⊕ β → γ} {i : β} {x : γ} : function.update f (inr i) x ∘ inl = f ∘ inl :=
function.update_comp_eq_of_forall_ne f x fun (_x : α) => inl_ne_inr
@[simp] theorem update_inr_apply_inl {α : Type u_1} {β : Type u_2} {γ : Sort u_3} [DecidableEq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {j : β} {x : γ} : function.update f (inr j) x (inl i) = f (inl i) :=
function.update_noteq inl_ne_inr x f
@[simp] theorem update_inr_comp_inr {α : Type u_1} {β : Type u_2} {γ : Sort u_3} [DecidableEq β] [DecidableEq (α ⊕ β)] {f : α ⊕ β → γ} {i : β} {x : γ} : function.update f (inr i) x ∘ inr = function.update (f ∘ inr) i x :=
function.update_comp_eq_of_injective f injective_inr i x
@[simp] theorem update_inr_apply_inr {α : Type u_1} {β : Type u_2} {γ : Sort u_3} [DecidableEq β] [DecidableEq (α ⊕ β)] {f : α ⊕ β → γ} {i : β} {j : β} {x : γ} : function.update f (inr i) x (inr j) = function.update (f ∘ inr) i x j := sorry
inductive lex {α : Type u} {β : Type v} (ra : α → α → Prop) (rb : β → β → Prop) : α ⊕ β → α ⊕ β → Prop
where
| inl : ∀ {a₁ a₂ : α}, ra a₁ a₂ → lex ra rb (inl a₁) (inl a₂)
| inr : ∀ {b₁ b₂ : β}, rb b₁ b₂ → lex ra rb (inr b₁) (inr b₂)
| sep : ∀ (a : α) (b : β), lex ra rb (inl a) (inr b)
@[simp] theorem lex_inl_inl {α : Type u} {β : Type v} {ra : α → α → Prop} {rb : β → β → Prop} {a₁ : α} {a₂ : α} : lex ra rb (inl a₁) (inl a₂) ↔ ra a₁ a₂ := sorry
@[simp] theorem lex_inr_inr {α : Type u} {β : Type v} {ra : α → α → Prop} {rb : β → β → Prop} {b₁ : β} {b₂ : β} : lex ra rb (inr b₁) (inr b₂) ↔ rb b₁ b₂ := sorry
@[simp] theorem lex_inr_inl {α : Type u} {β : Type v} {ra : α → α → Prop} {rb : β → β → Prop} {b : β} {a : α} : ¬lex ra rb (inr b) (inl a) := sorry
theorem lex_acc_inl {α : Type u} {β : Type v} {ra : α → α → Prop} {rb : β → β → Prop} {a : α} (aca : acc ra a) : acc (lex ra rb) (inl a) := sorry
theorem lex_acc_inr {α : Type u} {β : Type v} {ra : α → α → Prop} {rb : β → β → Prop} (aca : ∀ (a : α), acc (lex ra rb) (inl a)) {b : β} (acb : acc rb b) : acc (lex ra rb) (inr b) := sorry
theorem lex_wf {α : Type u} {β : Type v} {ra : α → α → Prop} {rb : β → β → Prop} (ha : well_founded ra) (hb : well_founded rb) : well_founded (lex ra rb) :=
(fun (aca : ∀ (a : α), acc (lex ra rb) (inl a)) =>
well_founded.intro fun (x : α ⊕ β) => sum.rec_on x aca fun (b : β) => lex_acc_inr aca (well_founded.apply hb b))
fun (a : α) => lex_acc_inl (well_founded.apply ha a)
/-- Swap the factors of a sum type -/
@[simp] def swap {α : Type u} {β : Type v} : α ⊕ β → β ⊕ α :=
sorry
@[simp] theorem swap_swap {α : Type u} {β : Type v} (x : α ⊕ β) : swap (swap x) = x :=
sum.cases_on x (fun (x : α) => Eq.refl (swap (swap (inl x)))) fun (x : β) => Eq.refl (swap (swap (inr x)))
@[simp] theorem swap_swap_eq {α : Type u} {β : Type v} : swap ∘ swap = id :=
funext swap_swap
@[simp] theorem swap_left_inverse {α : Type u} {β : Type v} : function.left_inverse swap swap :=
swap_swap
@[simp] theorem swap_right_inverse {α : Type u} {β : Type v} : function.right_inverse swap swap :=
swap_swap
end sum
namespace function
theorem injective.sum_elim {α : Type u} {β : Type v} {γ : Sort u_1} {f : α → γ} {g : β → γ} (hf : injective f) (hg : injective g) (hfg : ∀ (a : α) (b : β), f a ≠ g b) : injective (sum.elim f g) := sorry
theorem injective.sum_map {α : Type u} {α' : Type w} {β : Type v} {β' : Type x} {f : α → β} {g : α' → β'} (hf : injective f) (hg : injective g) : injective (sum.map f g) := sorry
theorem surjective.sum_map {α : Type u} {α' : Type w} {β : Type v} {β' : Type x} {f : α → β} {g : α' → β'} (hf : surjective f) (hg : surjective g) : surjective (sum.map f g) := sorry
|
8033394d6935b211b917a39d003ace5e3e7541cd | 5ee26964f602030578ef0159d46145dd2e357ba5 | /src/for_mathlib/opens.lean | e59c088f14a61a8fa471f8947e34df46cf3abfb5 | [
"Apache-2.0"
] | permissive | fpvandoorn/lean-perfectoid-spaces | 569b4006fdfe491ca8b58dd817bb56138ada761f | 06cec51438b168837fc6e9268945735037fd1db6 | refs/heads/master | 1,590,154,571,918 | 1,557,685,392,000 | 1,557,685,392,000 | 186,363,547 | 0 | 0 | Apache-2.0 | 1,557,730,933,000 | 1,557,730,933,000 | null | UTF-8 | Lean | false | false | 1,055 | lean | import topology.opens
import category_theory.functor
variables {α : Type*} {β : Type*} [topological_space α] [topological_space β]
{f : α → β}
open topological_space
def topological_space.is_open_map_map (h : is_open_map f) : opens α → opens β :=
λ U, ⟨f '' U.1, h U.1 U.2⟩
def functor.is_open_map.map (h : is_open_map f) : opens α ⥤ opens β :=
{ obj := topological_space.is_open_map_map h,
map := λ X Y hXY, ⟨⟨set.mono_image hXY.1.1⟩⟩,
map_id' := λ _, rfl,
map_comp' := λ _ _ _ _ _, rfl }
def continuous.comap {X : Type*} [topological_space X] {Y : Type*} [topological_space Y]
{f : X → Y} (hf : continuous f) (V : opens Y) : opens X := ⟨f ⁻¹' V.1, hf V.1 V.2⟩
def continuous.comap_id {X : Type*} [topological_space X] (U : opens X) :
continuous.comap (continuous_id) U = U := by ext; refl
def continuous.comap_mono {X : Type*} [topological_space X] {Y : Type*} [topological_space Y]
{f : X → Y} (hf : continuous f) {V W : opens Y} (hVW : V ⊆ W) : hf.comap V ⊆ hf.comap W :=
λ _ h, hVW h
|
642abf6c8c4147775f7b505f01827829729a2a58 | 95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990 | /src/category_theory/products.lean | 13494accd19869eea3a3a798ddaf9a965a6848f2 | [
"Apache-2.0"
] | permissive | uniformity1/mathlib | 829341bad9dfa6d6be9adaacb8086a8a492e85a4 | dd0e9bd8f2e5ec267f68e72336f6973311909105 | refs/heads/master | 1,588,592,015,670 | 1,554,219,842,000 | 1,554,219,842,000 | 179,110,702 | 0 | 0 | Apache-2.0 | 1,554,220,076,000 | 1,554,220,076,000 | null | UTF-8 | Lean | false | false | 5,811 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Stephen Morgan, Scott Morrison
import category_theory.functor_category
import category_theory.isomorphism
import tactic.interactive
namespace category_theory
universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ -- declare the `v`'s first; see `category_theory.category` for an explanation
-- Am awkward note on universes:
-- we need to make sure we're in `Type`, not `Sort`
-- for both objects and morphisms when taking products.
section
variables (C : Type u₁) [𝒞 : category.{v₁+1} C] (D : Type u₂) [𝒟 : category.{v₂+1} D]
include 𝒞 𝒟
/--
`prod C D` gives the cartesian product of two categories.
-/
instance prod : category.{max (v₁+1) (v₂+1)} (C × D) :=
{ hom := λ X Y, ((X.1) ⟶ (Y.1)) × ((X.2) ⟶ (Y.2)),
id := λ X, ⟨ 𝟙 (X.1), 𝟙 (X.2) ⟩,
comp := λ _ _ _ f g, (f.1 ≫ g.1, f.2 ≫ g.2) }
-- rfl lemmas for category.prod
@[simp] lemma prod_id (X : C) (Y : D) : 𝟙 (X, Y) = (𝟙 X, 𝟙 Y) := rfl
@[simp] lemma prod_comp {P Q R : C} {S T U : D} (f : (P, S) ⟶ (Q, T)) (g : (Q, T) ⟶ (R, U)) :
f ≫ g = (f.1 ≫ g.1, f.2 ≫ g.2) := rfl
@[simp] lemma prod_id_fst (X : prod C D) : _root_.prod.fst (𝟙 X) = 𝟙 X.fst := rfl
@[simp] lemma prod_id_snd (X : prod C D) : _root_.prod.snd (𝟙 X) = 𝟙 X.snd := rfl
@[simp] lemma prod_comp_fst {X Y Z : prod C D} (f : X ⟶ Y) (g : Y ⟶ Z) :
(f ≫ g).1 = f.1 ≫ g.1 := rfl
@[simp] lemma prod_comp_snd {X Y Z : prod C D} (f : X ⟶ Y) (g : Y ⟶ Z) :
(f ≫ g).2 = f.2 ≫ g.2 := rfl
end
section
variables (C : Type u₁) [𝒞 : category.{v₁+1} C] (D : Type u₁) [𝒟 : category.{v₁+1} D]
include 𝒞 𝒟
/--
`prod.category.uniform C D` is an additional instance specialised so both factors have the same universe levels. This helps typeclass resolution.
-/
instance uniform_prod : category (C × D) := category_theory.prod C D
end
-- Next we define the natural functors into and out of product categories. For now this doesn't address the universal properties.
namespace prod
variables (C : Type u₁) [𝒞 : category.{v₁+1} C] (D : Type u₂) [𝒟 : category.{v₂+1} D]
include 𝒞 𝒟
/-- `inl C Z` is the functor `X ↦ (X, Z)`. -/
def inl (Z : D) : C ⥤ C × D :=
{ obj := λ X, (X, Z),
map := λ X Y f, (f, 𝟙 Z) }
/-- `inr D Z` is the functor `X ↦ (Z, X)`. -/
def inr (Z : C) : D ⥤ C × D :=
{ obj := λ X, (Z, X),
map := λ X Y f, (𝟙 Z, f) }
/-- `fst` is the functor `(X, Y) ↦ X`. -/
def fst : C × D ⥤ C :=
{ obj := λ X, X.1,
map := λ X Y f, f.1 }
/-- `snd` is the functor `(X, Y) ↦ Y`. -/
def snd : C × D ⥤ D :=
{ obj := λ X, X.2,
map := λ X Y f, f.2 }
def swap : C × D ⥤ D × C :=
{ obj := λ X, (X.2, X.1),
map := λ _ _ f, (f.2, f.1) }
def symmetry : swap C D ⋙ swap D C ≅ functor.id (C × D) :=
{ hom :=
{ app := λ X, 𝟙 X,
naturality' := begin intros, erw [category.comp_id (C × D), category.id_comp (C × D)], dsimp [swap], simp, end },
inv :=
{ app := λ X, 𝟙 X,
naturality' := begin intros, erw [category.comp_id (C × D), category.id_comp (C × D)], dsimp [swap], simp, end } }
end prod
section
variables (C : Sort u₁) [𝒞 : category.{v₁} C] (D : Sort u₂) [𝒟 : category.{v₂} D]
include 𝒞 𝒟
@[simp] def evaluation : C ⥤ (C ⥤ D) ⥤ D :=
{ obj := λ X,
{ obj := λ F, F.obj X,
map := λ F G α, α.app X, },
map := λ X Y f,
{ app := λ F, F.map f,
naturality' := λ F G α, eq.symm (α.naturality f) },
map_comp' := λ X Y Z f g,
begin
ext, dsimp, rw functor.map_comp,
end }
end
section
variables (C : Type u₁) [𝒞 : category.{v₁+1} C] (D : Type u₂) [𝒟 : category.{v₂+1} D]
include 𝒞 𝒟
@[simp] def evaluation_uncurried : C × (C ⥤ D) ⥤ D :=
{ obj := λ p, p.2.obj p.1,
map := λ x y f, (x.2.map f.1) ≫ (f.2.app y.1),
map_comp' := begin
intros X Y Z f g, cases g, cases f, cases Z, cases Y, cases X, dsimp at *, simp at *,
erw [←nat_trans.vcomp_app, nat_trans.naturality, category.assoc, nat_trans.naturality]
end }
end
variables {A : Type u₁} [𝒜 : category.{v₁+1} A]
{B : Type u₂} [ℬ : category.{v₂+1} B]
{C : Type u₃} [𝒞 : category.{v₃+1} C]
{D : Type u₄} [𝒟 : category.{v₄+1} D]
include 𝒜 ℬ 𝒞 𝒟
namespace functor
/-- The cartesian product of two functors. -/
def prod (F : A ⥤ B) (G : C ⥤ D) : A × C ⥤ B × D :=
{ obj := λ X, (F.obj X.1, G.obj X.2),
map := λ _ _ f, (F.map f.1, G.map f.2) }
/- Because of limitations in Lean 3's handling of notations, we do not setup a notation `F × G`.
You can use `F.prod G` as a "poor man's infix", or just write `functor.prod F G`. -/
@[simp] lemma prod_obj (F : A ⥤ B) (G : C ⥤ D) (a : A) (c : C) : (F.prod G).obj (a, c) = (F.obj a, G.obj c) := rfl
@[simp] lemma prod_map (F : A ⥤ B) (G : C ⥤ D) {a a' : A} {c c' : C} (f : (a, c) ⟶ (a', c')) : (F.prod G).map f = (F.map f.1, G.map f.2) := rfl
end functor
namespace nat_trans
/-- The cartesian product of two natural transformations. -/
def prod {F G : A ⥤ B} {H I : C ⥤ D} (α : F ⟹ G) (β : H ⟹ I) : F.prod H ⟹ G.prod I :=
{ app := λ X, (α.app X.1, β.app X.2),
naturality' := begin /- `obviously'` says: -/ intros, cases f, cases Y, cases X, dsimp at *, simp, split, rw naturality, rw naturality end }
/- Again, it is inadvisable in Lean 3 to setup a notation `α × β`; use instead `α.prod β` or `nat_trans.prod α β`. -/
@[simp] lemma prod_app {F G : A ⥤ B} {H I : C ⥤ D} (α : F ⟹ G) (β : H ⟹ I) (a : A) (c : C) :
(nat_trans.prod α β).app (a, c) = (α.app a, β.app c) := rfl
end nat_trans
end category_theory
|
b788fb4ecb7c1f8c54edde64c54b1e11784caa71 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/analysis/normed_space/riesz_lemma_auto.lean | d8df17d6064540f0b0c36d57bbeeb7443e66b52d | [] | 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,161 | lean | /-
Copyright (c) 2019 Jean Lo. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jean Lo
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.topology.metric_space.hausdorff_distance
import Mathlib.PostPort
universes u_1 u_2
namespace Mathlib
/-!
# Riesz's lemma
Riesz's lemma, stated for a normed space over a normed field: for any
closed proper subspace F of E, there is a nonzero x such that ∥x - F∥
is at least r * ∥x∥ for any r < 1.
-/
/-- Riesz's lemma, which usually states that it is possible to find a
vector with norm 1 whose distance to a closed proper subspace is
arbitrarily close to 1. The statement here is in terms of multiples of
norms, since in general the existence of an element of norm exactly 1
is not guaranteed. -/
theorem riesz_lemma {𝕜 : Type u_1} [normed_field 𝕜] {E : Type u_2} [normed_group E]
[normed_space 𝕜 E] {F : subspace 𝕜 E} (hFc : is_closed ↑F) (hF : ∃ (x : E), ¬x ∈ F) {r : ℝ}
(hr : r < 1) : ∃ (x₀ : E), ¬x₀ ∈ F ∧ ∀ (y : E), y ∈ F → r * norm x₀ ≤ norm (x₀ - y) :=
sorry
end Mathlib |
78a9e3d95b5caf35633cf5cb30518080cd7c7ea2 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/1118.lean | 98880c5f2f24e5c70aead18cfccc652f526fee2d | [
"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 | 686 | lean | theorem CongrGood {x y: Nat}: x + y = y + x := by
conv =>
congr
. rw [Nat.add_comm]
. rfl
theorem CongrBad {x y: Nat}: x + y = y + x := by
have I: True := True.intro;
conv =>
congr
. rw [Nat.add_comm]
. rfl
theorem CongrBad' {x y: Nat}: x + y = y + x := by
let I: True := True.intro;
conv =>
congr
. rw [Nat.add_comm]
. rfl
theorem CongrBad'' {x y: Nat}: x + y = y + x := by
let I: True := True.intro;
try rfl;
conv =>
congr
. rw [Nat.add_comm]
. rfl
theorem CongrGood' {x y: Nat}: x + y = y + x := by
cases x;
have I: True := True.intro;
rw [Nat.add_comm]
conv =>
congr
. rw [Nat.add_comm]
. rfl
|
3e8d69565d4dfc5839fb23d615c1466b57903c04 | 42610cc2e5db9c90269470365e6056df0122eaa0 | /hott/types/fin.hlean | 6f2a9905c83db214f46db3f44992ea29d4bcb259 | [
"Apache-2.0"
] | permissive | tomsib2001/lean | 2ab59bfaebd24a62109f800dcf4a7139ebd73858 | eb639a7d53fb40175bea5c8da86b51d14bb91f76 | refs/heads/master | 1,586,128,387,740 | 1,468,968,950,000 | 1,468,968,950,000 | 61,027,234 | 0 | 0 | null | 1,465,813,585,000 | 1,465,813,585,000 | null | UTF-8 | Lean | false | false | 23,019 | hlean | /-
Copyright (c) 2015 Haitao Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Haitao Zhang, Leonardo de Moura, Jakob von Raumer, Floris van Doorn
Finite ordinal types.
-/
import types.list algebra.group function logic types.prod types.sum types.nat.div
open eq nat function list equiv is_trunc algebra sigma sum
structure fin (n : nat) := (val : nat) (is_lt : val < n)
definition less_than [reducible] := fin
namespace fin
attribute fin.val [coercion]
section def_equal
variable {n : nat}
definition sigma_char : fin n ≃ Σ (val : nat), val < n :=
begin
fapply equiv.MK,
intro i, cases i with i ilt, apply dpair i ilt,
intro s, cases s with i ilt, apply fin.mk i ilt,
intro s, cases s with i ilt, reflexivity,
intro i, cases i with i ilt, reflexivity
end
definition is_set_fin [instance] : is_set (fin n) :=
begin
apply is_trunc_equiv_closed, apply equiv.symm, apply sigma_char,
end
definition eq_of_veq : Π {i j : fin n}, (val i) = j → i = j :=
begin
intro i j, cases i with i ilt, cases j with j jlt, esimp,
intro p, induction p, apply ap (mk i), apply !is_prop.elim
end
definition eq_of_veq_refl (i : fin n) : eq_of_veq (refl (val i)) = idp :=
!is_prop.elim
definition veq_of_eq : Π {i j : fin n}, i = j → (val i) = j :=
by intro i j P; apply ap val; exact P
definition eq_iff_veq {i j : fin n} : (val i) = j ↔ i = j :=
pair eq_of_veq veq_of_eq
definition val_inj := @eq_of_veq n
end def_equal
section decidable
open decidable
protected definition has_decidable_eq [instance] (n : nat) :
Π (i j : fin n), decidable (i = j) :=
begin
intros i j, apply decidable_of_decidable_of_iff,
apply nat.has_decidable_eq i j, apply eq_iff_veq,
end
end decidable
/-lemma dinj_lt (n : nat) : dinj (λ i, i < n) fin.mk :=
take a1 a2 Pa1 Pa2 Pmkeq, fin.no_confusion Pmkeq (λ Pe Pqe, Pe)
lemma val_mk (n i : nat) (Plt : i < n) : fin.val (fin.mk i Plt) = i := rfl
definition upto [reducible] (n : nat) : list (fin n) :=
dmap (λ i, i < n) fin.mk (list.upto n)
lemma nodup_upto (n : nat) : nodup (upto n) :=
dmap_nodup_of_dinj (dinj_lt n) (list.nodup_upto n)
lemma mem_upto (n : nat) : Π (i : fin n), i ∈ upto n :=
take i, fin.destruct i
(take ival Piltn,
have ival ∈ list.upto n, from mem_upto_of_lt Piltn,
mem_dmap Piltn this)
lemma upto_zero : upto 0 = [] :=
by rewrite [↑upto, list.upto_nil, dmap_nil]
lemma map_val_upto (n : nat) : map fin.val (upto n) = list.upto n :=
map_dmap_of_inv_of_pos (val_mk n) (@lt_of_mem_upto n)
lemma length_upto (n : nat) : length (upto n) = n :=
calc
length (upto n) = length (list.upto n) : (map_val_upto n ▸ length_map fin.val (upto n))⁻¹
... = n : list.length_upto n
definition is_fintype [instance] (n : nat) : fintype (fin n) :=
fintype.mk (upto n) (nodup_upto n) (mem_upto n)
section pigeonhole
open fintype
lemma card_fin (n : nat) : card (fin n) = n := length_upto n
theorem pigeonhole {n m : nat} (Pmltn : m < n) : ¬Σ f : fin n → fin m, injective f :=
assume Pex, absurd Pmltn (not_lt_of_ge
(calc
n = card (fin n) : card_fin
... ≤ card (fin m) : card_le_of_inj (fin n) (fin m) Pex
... = m : card_fin))
end pigeonhole-/
protected definition zero [constructor] (n : nat) : fin (succ n) :=
mk 0 !zero_lt_succ
definition fin_has_zero [instance] (n : nat) : has_zero (fin (succ n)) :=
has_zero.mk (fin.zero n)
definition val_zero (n : nat) : val (0 : fin (succ n)) = 0 := rfl
definition mk_mod [reducible] (n i : nat) : fin (succ n) :=
mk (i % (succ n)) (mod_lt _ !zero_lt_succ)
theorem mk_mod_zero_eq (n : nat) : mk_mod n 0 = 0 :=
apd011 fin.mk rfl !is_prop.elim
variable {n : nat}
theorem val_lt : Π i : fin n, val i < n
| (mk v h) := h
lemma max_lt (i j : fin n) : max i j < n :=
max_lt (is_lt i) (is_lt j)
definition lift [constructor] : fin n → Π m : nat, fin (n + m)
| (mk v h) m := mk v (lt_add_of_lt_right h m)
definition lift_succ [constructor] (i : fin n) : fin (nat.succ n) :=
have r : fin (n+1), from lift i 1,
r
definition maxi [reducible] : fin (succ n) :=
mk n !lt_succ_self
definition val_lift : Π (i : fin n) (m : nat), val i = val (lift i m)
| (mk v h) m := rfl
lemma mk_succ_ne_zero {i : nat} : Π {P}, mk (succ i) P ≠ (0 : fin (succ n)) :=
assume P Pe, absurd (veq_of_eq Pe) !succ_ne_zero
lemma mk_mod_eq {i : fin (succ n)} : i = mk_mod n i :=
eq_of_veq begin rewrite [↑mk_mod, mod_eq_of_lt !is_lt] end
lemma mk_mod_of_lt {i : nat} (Plt : i < succ n) : mk_mod n i = mk i Plt :=
begin esimp [mk_mod], congruence, exact mod_eq_of_lt Plt end
section lift_lower
lemma lift_zero : lift_succ (0 : fin (succ n)) = (0 : fin (succ (succ n))) :=
by apply eq_of_veq; reflexivity
lemma ne_max_of_lt_max {i : fin (succ n)} : i < n → i ≠ maxi :=
begin
intro hlt he,
have he' : maxi = i, by apply he⁻¹,
induction he', apply nat.lt_irrefl n hlt,
end
lemma lt_max_of_ne_max {i : fin (succ n)} : i ≠ maxi → i < n :=
assume hne : i ≠ maxi,
have vne : val i ≠ n, from
assume he,
have val (@maxi n) = n, from rfl,
have val i = val (@maxi n), from he ⬝ this⁻¹,
absurd (eq_of_veq this) hne,
have val i < nat.succ n, from val_lt i,
lt_of_le_of_ne (le_of_lt_succ this) vne
lemma lift_succ_ne_max {i : fin n} : lift_succ i ≠ maxi :=
begin
cases i with v hlt, esimp [lift_succ, lift, max], intro he,
injection he, substvars,
exact absurd hlt (lt.irrefl v)
end
lemma lift_succ_inj [instance] : is_embedding (@lift_succ n) :=
begin
apply is_embedding_of_is_injective, intro i j,
induction i with iv ilt, induction j with jv jlt, intro Pmkeq,
apply eq_of_veq, apply veq_of_eq Pmkeq
end
definition lt_of_inj_of_max (f : fin (succ n) → fin (succ n)) :
is_embedding f → (f maxi = maxi) → Π i : fin (succ n), i < n → f i < n :=
assume Pinj Peq, take i, assume Pilt,
have P1 : f i = f maxi → i = maxi, from assume Peq, is_injective_of_is_embedding Peq,
have f i ≠ maxi, from
begin rewrite -Peq, intro P2, apply absurd (P1 P2) (ne_max_of_lt_max Pilt) end,
lt_max_of_ne_max this
definition lift_fun : (fin n → fin n) → (fin (succ n) → fin (succ n)) :=
λ f i, dite (i = maxi) (λ Pe, maxi) (λ Pne, lift_succ (f (mk i (lt_max_of_ne_max Pne))))
definition lower_inj (f : fin (succ n) → fin (succ n)) (inj : is_embedding f) :
f maxi = maxi → fin n → fin n :=
assume Peq, take i, mk (f (lift_succ i)) (lt_of_inj_of_max f inj Peq (lift_succ i) (lt_max_of_ne_max lift_succ_ne_max))
lemma lift_fun_max {f : fin n → fin n} : lift_fun f maxi = maxi :=
begin rewrite [↑lift_fun, dif_pos rfl] end
lemma lift_fun_of_ne_max {f : fin n → fin n} {i} (Pne : i ≠ maxi) :
lift_fun f i = lift_succ (f (mk i (lt_max_of_ne_max Pne))) :=
begin rewrite [↑lift_fun, dif_neg Pne] end
lemma lift_fun_eq {f : fin n → fin n} {i : fin n} :
lift_fun f (lift_succ i) = lift_succ (f i) :=
begin
rewrite [lift_fun_of_ne_max lift_succ_ne_max], do 2 congruence,
apply eq_of_veq, esimp, rewrite -val_lift,
end
lemma lift_fun_of_inj {f : fin n → fin n} : is_embedding f → is_embedding (lift_fun f) :=
begin
intro Pemb, apply is_embedding_of_is_injective, intro i j,
have Pdi : decidable (i = maxi), by apply _,
have Pdj : decidable (j = maxi), by apply _,
cases Pdi with Pimax Pinmax,
cases Pdj with Pjmax Pjnmax,
substvars, intros, reflexivity,
substvars, rewrite [lift_fun_max, lift_fun_of_ne_max Pjnmax],
intro Plmax, apply absurd Plmax⁻¹ lift_succ_ne_max,
cases Pdj with Pjmax Pjnmax,
substvars, rewrite [lift_fun_max, lift_fun_of_ne_max Pinmax],
intro Plmax, apply absurd Plmax lift_succ_ne_max,
rewrite [lift_fun_of_ne_max Pinmax, lift_fun_of_ne_max Pjnmax],
intro Peq, apply eq_of_veq,
cases i with i ilt, cases j with j jlt, esimp at *,
fapply veq_of_eq, apply is_injective_of_is_embedding,
apply @is_injective_of_is_embedding _ _ lift_succ _ _ _ Peq,
end
lemma lift_fun_inj : is_embedding (@lift_fun n) :=
begin
apply is_embedding_of_is_injective, intro f f' Peq, apply eq_of_homotopy, intro i,
have H : lift_fun f (lift_succ i) = lift_fun f' (lift_succ i), by apply congr_fun Peq _,
revert H, rewrite [*lift_fun_eq], apply is_injective_of_is_embedding,
end
lemma lower_inj_apply {f Pinj Pmax} (i : fin n) :
val (lower_inj f Pinj Pmax i) = val (f (lift_succ i)) :=
by rewrite [↑lower_inj]
end lift_lower
section madd
definition madd (i j : fin (succ n)) : fin (succ n) :=
mk ((i + j) % (succ n)) (mod_lt _ !zero_lt_succ)
definition minv : Π i : fin (succ n), fin (succ n)
| (mk iv ilt) := mk ((succ n - iv) % succ n) (mod_lt _ !zero_lt_succ)
lemma val_madd : Π i j : fin (succ n), val (madd i j) = (i + j) % (succ n)
| (mk iv ilt) (mk jv jlt) := by esimp
lemma madd_inj : Π {i : fin (succ n)}, is_embedding (madd i)
| (mk iv ilt) := is_embedding_of_is_injective
(take j₁ j₂, fin.destruct j₁ (fin.destruct j₂ (λ jv₁ jlt₁ jv₂ jlt₂, begin
rewrite [↑madd],
intro Peq', note Peq := ap val Peq', congruence,
rewrite [-(mod_eq_of_lt jlt₁), -(mod_eq_of_lt jlt₂)],
apply mod_eq_mod_of_add_mod_eq_add_mod_left Peq
end)))
lemma madd_mk_mod {i j : nat} : madd (mk_mod n i) (mk_mod n j) = mk_mod n (i+j) :=
eq_of_veq begin esimp [madd, mk_mod], rewrite [ mod_add_mod, add_mod_mod ] end
lemma val_mod : Π i : fin (succ n), (val i) % (succ n) = val i
| (mk iv ilt) := by esimp; rewrite [(mod_eq_of_lt ilt)]
lemma madd_comm (i j : fin (succ n)) : madd i j = madd j i :=
by apply eq_of_veq; rewrite [*val_madd, add.comm (val i)]
lemma zero_madd (i : fin (succ n)) : madd 0 i = i :=
have H : madd (fin.zero n) i = i,
by apply eq_of_veq; rewrite [val_madd, ↑fin.zero, nat.zero_add, mod_eq_of_lt (is_lt i)],
H
lemma madd_zero (i : fin (succ n)) : madd i (fin.zero n) = i :=
!madd_comm ▸ zero_madd i
lemma madd_assoc (i j k : fin (succ n)) : madd (madd i j) k = madd i (madd j k) :=
by apply eq_of_veq; rewrite [*val_madd, mod_add_mod, add_mod_mod, add.assoc (val i)]
lemma madd_left_inv : Π i : fin (succ n), madd (minv i) i = fin.zero n
| (mk iv ilt) := eq_of_veq (by
rewrite [val_madd, ↑minv, mod_add_mod, nat.sub_add_cancel (le_of_lt ilt), mod_self])
definition madd_is_comm_group [instance] : add_comm_group (fin (succ n)) :=
add_comm_group.mk madd _ madd_assoc (fin.zero n) zero_madd madd_zero minv madd_left_inv madd_comm
end madd
definition pred [constructor] : fin n → fin n
| (mk v h) := mk (nat.pred v) (pre_lt_of_lt h)
lemma val_pred : Π (i : fin n), val (pred i) = nat.pred (val i)
| (mk v h) := rfl
lemma pred_zero : pred (fin.zero n) = fin.zero n :=
begin
induction n, reflexivity, apply eq_of_veq, reflexivity,
end
definition mk_pred (i : nat) (h : succ i < succ n) : fin n :=
mk i (lt_of_succ_lt_succ h)
definition succ : fin n → fin (succ n)
| (mk v h) := mk (nat.succ v) (succ_lt_succ h)
lemma val_succ : Π (i : fin n), val (succ i) = nat.succ (val i)
| (mk v h) := rfl
lemma succ_max : fin.succ maxi = (@maxi (nat.succ n)) := rfl
lemma lift_succ.comm : lift_succ ∘ (@succ n) = succ ∘ lift_succ :=
eq_of_homotopy take i,
eq_of_veq (begin rewrite [↑lift_succ, -val_lift, *val_succ, -val_lift] end)
definition elim0 {C : fin 0 → Type} : Π i : fin 0, C i
| (mk v h) := absurd h !not_lt_zero
definition zero_succ_cases {C : fin (nat.succ n) → Type} :
C (fin.zero n) → (Π j : fin n, C (succ j)) → (Π k : fin (nat.succ n), C k) :=
begin
intros CO CS k,
induction k with [vk, pk],
induction (nat.decidable_lt 0 vk) with [HT, HF],
{ show C (mk vk pk), from
let vj := nat.pred vk in
have vk = nat.succ vj, from
inverse (succ_pred_of_pos HT),
have vj < n, from
lt_of_succ_lt_succ (eq.subst `vk = nat.succ vj` pk),
have succ (mk vj `vj < n`) = mk vk pk, by apply val_inj; apply (succ_pred_of_pos HT),
eq.rec_on this (CS (mk vj `vj < n`)) },
{ show C (mk vk pk), from
have vk = 0, from
eq_zero_of_le_zero (le_of_not_gt HF),
have fin.zero n = mk vk pk, from
val_inj (inverse this),
eq.rec_on this CO }
end
definition succ_maxi_cases {C : fin (nat.succ n) → Type} :
(Π j : fin n, C (lift_succ j)) → C maxi → (Π k : fin (nat.succ n), C k) :=
begin
intros CL CM k,
induction k with [vk, pk],
induction (nat.decidable_lt vk n) with [HT, HF],
{ show C (mk vk pk), from
have HL : lift_succ (mk vk HT) = mk vk pk, from
val_inj rfl,
eq.rec_on HL (CL (mk vk HT)) },
{ show C (mk vk pk), from
have HMv : vk = n, from
le.antisymm (le_of_lt_succ pk) (le_of_not_gt HF),
have HM : maxi = mk vk pk, from
val_inj (inverse HMv),
eq.rec_on HM CM }
end
open decidable
-- TODO there has to be a less painful way to do this
definition elim_succ_maxi_cases_lift_succ {C : fin (nat.succ n) → Type}
{Cls : Π j : fin n, C (lift_succ j)} {Cm : C maxi} (i : fin n) :
succ_maxi_cases Cls Cm (lift_succ i) = Cls i :=
begin
esimp[succ_maxi_cases], cases i with i ilt, esimp,
apply decidable.rec,
{ intro ilt', esimp[val_inj], apply concat,
apply ap (λ x, eq.rec_on x _), esimp[eq_of_veq, rfl], reflexivity,
have H : ilt = ilt', by apply is_prop.elim, cases H,
have H' : is_prop.elim (lt_add_of_lt_right ilt 1) (lt_add_of_lt_right ilt 1) = idp,
by apply is_prop.elim,
krewrite H' },
{ intro a, exact absurd ilt a },
end
definition elim_succ_maxi_cases_maxi {C : fin (nat.succ n) → Type}
{Cls : Π j : fin n, C (lift_succ j)} {Cm : C maxi} :
succ_maxi_cases Cls Cm maxi = Cm :=
begin
esimp[succ_maxi_cases, maxi],
apply decidable.rec,
{ intro a, apply absurd a !nat.lt_irrefl },
{ intro a, esimp[val_inj], apply concat,
have H : (le.antisymm (le_of_lt_succ (lt_succ_self n)) (le_of_not_gt a))⁻¹ = idp,
by apply is_prop.elim,
apply ap _ H, krewrite eq_of_veq_refl },
end
definition foldr {A B : Type} (m : A → B → B) (b : B) : Π {n : nat}, (fin n → A) → B :=
nat.rec (λ f, b) (λ n IH f, m (f (fin.zero n)) (IH (λ i : fin n, f (succ i))))
definition foldl {A B : Type} (m : B → A → B) (b : B) : Π {n : nat}, (fin n → A) → B :=
nat.rec (λ f, b) (λ n IH f, m (IH (λ i : fin n, f (lift_succ i))) (f maxi))
theorem choice {C : fin n → Type} :
(Π i : fin n, nonempty (C i)) → nonempty (Π i : fin n, C i) :=
begin
revert C,
induction n with [n, IH],
{ intros C H,
apply nonempty.intro,
exact elim0 },
{ intros C H,
fapply nonempty.elim (H (fin.zero n)),
intro CO,
fapply nonempty.elim (IH (λ i, C (succ i)) (λ i, H (succ i))),
intro CS,
apply nonempty.intro,
exact zero_succ_cases CO CS }
end
/-section
open list
local postfix `+1`:100 := nat.succ
lemma dmap_map_lift {n : nat} : Π l : list nat, (Π i, i ∈ l → i < n) → dmap (λ i, i < n +1) mk l = map lift_succ (dmap (λ i, i < n) mk l)
| [] := assume Plt, rfl
| (i::l) := assume Plt, begin
rewrite [@dmap_cons_of_pos _ _ (λ i, i < n +1) _ _ _ (lt_succ_of_lt (Plt i !mem_cons)), @dmap_cons_of_pos _ _ (λ i, i < n) _ _ _ (Plt i !mem_cons), map_cons],
congruence,
apply dmap_map_lift,
intro j Pjinl, apply Plt, apply mem_cons_of_mem, assumption end
lemma upto_succ (n : nat) : upto (n +1) = maxi :: map lift_succ (upto n) :=
begin
rewrite [↑fin.upto, list.upto_succ, @dmap_cons_of_pos _ _ (λ i, i < n +1) _ _ _ (nat.self_lt_succ n)],
congruence,
apply dmap_map_lift, apply @list.lt_of_mem_upto
end
definition upto_step : Π {n : nat}, fin.upto (n +1) = (map succ (upto n))++[0]
| 0 := rfl
| (i +1) := begin rewrite [upto_succ i, map_cons, append_cons, succ_max, upto_succ, -lift_zero],
congruence, rewrite [map_map, -lift_succ.comm, -map_map, -(map_singleton _ 0), -map_append, -upto_step] end
end-/
open sum equiv decidable
definition fin_zero_equiv_empty : fin 0 ≃ empty :=
begin
fapply equiv.MK, rotate 1, do 2 (intro x; contradiction),
rotate 1, do 2 (intro x; apply elim0 x)
end
definition is_contr_fin_one [instance] : is_contr (fin 1) :=
begin
fapply is_contr.mk, exact 0,
intro x, induction x with v vlt,
apply eq_of_veq, rewrite val_zero,
apply inverse, apply eq_zero_of_le_zero, apply le_of_succ_le_succ, exact vlt,
end
definition fin_sum_equiv (n m : nat) : (fin n + fin m) ≃ fin (n+m) :=
begin
fapply equiv.MK,
{ intro s, induction s with l r,
induction l with v vlt, apply mk v, apply lt_add_of_lt_right, exact vlt,
induction r with v vlt, apply mk (v + n), rewrite {n + m}add.comm,
apply add_lt_add_of_lt_of_le vlt, apply nat.le_refl },
{ intro f, induction f with v vlt,
exact if h : v < n
then sum.inl (mk v h)
else sum.inr (mk (v-n) (nat.sub_lt_of_lt_add vlt (le_of_not_gt h))) },
{ intro f, cases f with v vlt, esimp, apply @by_cases (v < n),
intro vltn, rewrite [dif_pos vltn], apply eq_of_veq, reflexivity,
intro nvltn, rewrite [dif_neg nvltn], apply eq_of_veq, esimp,
apply nat.sub_add_cancel, apply le_of_not_gt, apply nvltn },
{ intro s, cases s with f g,
cases f with v vlt, rewrite [dif_pos vlt],
cases g with v vlt, esimp, have ¬ v + n < n, from
suppose v + n < n,
have v < n - n, from nat.lt_sub_of_add_lt this !le.refl,
have v < 0, by rewrite [nat.sub_self at this]; exact this,
absurd this !not_lt_zero,
apply concat, apply dif_neg this, apply ap inr, apply eq_of_veq, esimp,
apply nat.add_sub_cancel },
end
definition fin_succ_equiv (n : nat) : fin (n + 1) ≃ fin n + unit :=
begin
fapply equiv.MK,
{ apply succ_maxi_cases, esimp, apply inl, apply inr unit.star },
{ intro d, cases d, apply lift_succ a, apply maxi },
{ intro d, cases d,
cases a with a alt, esimp, apply elim_succ_maxi_cases_lift_succ,
cases a, apply elim_succ_maxi_cases_maxi },
{ intro a, apply succ_maxi_cases, esimp,
intro j, krewrite elim_succ_maxi_cases_lift_succ,
krewrite elim_succ_maxi_cases_maxi },
end
open prod
definition fin_prod_equiv (n m : nat) : (fin n × fin m) ≃ fin (n*m) :=
begin
induction n,
{ krewrite nat.zero_mul,
calc fin 0 × fin m ≃ empty × fin m : fin_zero_equiv_empty
... ≃ fin m × empty : prod_comm_equiv
... ≃ empty : prod_empty_equiv
... ≃ fin 0 : fin_zero_equiv_empty },
{ have H : (a + 1) * m = a * m + m, by rewrite [nat.right_distrib, one_mul],
calc fin (a + 1) × fin m
≃ (fin a + unit) × fin m : prod.prod_equiv_prod_right !fin_succ_equiv
... ≃ (fin a × fin m) + (unit × fin m) : sum_prod_right_distrib
... ≃ (fin a × fin m) + (fin m × unit) : prod_comm_equiv
... ≃ fin (a * m) + (fin m × unit) : v_0
... ≃ fin (a * m) + fin m : prod_unit_equiv
... ≃ fin (a * m + m) : fin_sum_equiv
... ≃ fin ((a + 1) * m) : equiv_of_eq (ap fin H⁻¹) },
end
definition fin_two_equiv_bool : fin 2 ≃ bool :=
let H := equiv_unit_of_is_contr (fin 1) in
calc
fin 2 ≃ fin (1 + 1) : equiv.refl
... ≃ fin 1 + fin 1 : fin_sum_equiv
... ≃ unit + unit : H
... ≃ bool : bool_equiv_unit_sum_unit
definition fin_sum_unit_equiv (n : nat) : fin n + unit ≃ fin (nat.succ n) :=
let H := equiv_unit_of_is_contr (fin 1) in
calc
fin n + unit ≃ fin n + fin 1 : H
... ≃ fin (nat.succ n) : fin_sum_equiv
definition fin_sum_equiv_cancel {n : nat} {A B : Type} (H : (fin n) + A ≃ (fin n) + B) :
A ≃ B :=
begin
induction n with n IH,
{ calc A ≃ A + empty : sum_empty_equiv
... ≃ empty + A : sum_comm_equiv
... ≃ fin 0 + A : fin_zero_equiv_empty
... ≃ fin 0 + B : H
... ≃ empty + B : fin_zero_equiv_empty
... ≃ B + empty : sum_comm_equiv
... ≃ B : sum_empty_equiv },
{ apply IH, apply unit_sum_equiv_cancel,
calc unit + (fin n + A) ≃ (unit + fin n) + A : sum_assoc_equiv
... ≃ (fin n + unit) + A : sum_comm_equiv
... ≃ fin (nat.succ n) + A : fin_sum_unit_equiv
... ≃ fin (nat.succ n) + B : H
... ≃ (fin n + unit) + B : fin_sum_unit_equiv
... ≃ (unit + fin n) + B : sum_comm_equiv
... ≃ unit + (fin n + B) : sum_assoc_equiv },
end
definition eq_of_fin_equiv {m n : nat} (H :fin m ≃ fin n) : m = n :=
begin
revert n H, induction m with m IH IH,
{ intro n H, cases n, reflexivity, exfalso,
apply to_fun fin_zero_equiv_empty, apply to_inv H, apply fin.zero },
{ intro n H, cases n with n, exfalso,
apply to_fun fin_zero_equiv_empty, apply to_fun H, apply fin.zero,
have unit + fin m ≃ unit + fin n, from
calc unit + fin m ≃ fin m + unit : sum_comm_equiv
... ≃ fin (nat.succ m) : fin_succ_equiv
... ≃ fin (nat.succ n) : H
... ≃ fin n + unit : fin_succ_equiv
... ≃ unit + fin n : sum_comm_equiv,
have fin m ≃ fin n, from unit_sum_equiv_cancel this,
apply ap nat.succ, apply IH _ this },
end
definition cyclic_succ {n : ℕ} (x : fin n) : fin n :=
begin
cases n with n,
{ exfalso, apply not_lt_zero _ (is_lt x)},
{ exact
if H : val x = n
then fin.mk 0 !zero_lt_succ
else fin.mk (nat.succ (val x))
(succ_lt_succ (lt_of_le_of_ne (le_of_lt_succ (is_lt x)) H))}
end
/-
We want to say that fin (succ n) always has a 0 and 1. However, we want a bit more, because
sometimes we want a zero of (fin a) where a is either
- equal to a successor, but not definitionally a successor (e.g. (0 : fin (3 + n)))
- definitionally equal to a successor, but not in a way that type class inference can infer.
(e.g. (0 : fin 4). Note that 4 is bit0 (bit0 one), but (bit0 x) (defined as x + x),
is not always a successor)
To solve this we use an auxillary class `is_succ` which can solve whether a number is a
successor.
-/
inductive is_succ [class] : ℕ → Type :=
| mk : Π(n : ℕ), is_succ (nat.succ n)
attribute is_succ.mk [instance]
definition is_succ_add_right [instance] (n m : ℕ) [H : is_succ m] : is_succ (n+m) :=
by induction H with m; constructor
definition is_succ_add_left [instance] (n m : ℕ) [H : is_succ n] : is_succ (n+m) :=
by induction H with n; cases m with m: constructor
definition is_succ_bit0 [instance] (n : ℕ) [H : is_succ n] : is_succ (bit0 n) :=
by induction H with n; constructor
/- this is a version of `madd` which might compute better -/
protected definition add {n : ℕ} (x y : fin n) : fin n :=
iterate cyclic_succ (val y) x
definition has_zero_fin [instance] (n : ℕ) [H : is_succ n] : has_zero (fin n) :=
by induction H with n; exact has_zero.mk (fin.zero n)
definition has_one_fin [instance] (n : ℕ) [H : is_succ n] : has_one (fin n) :=
by induction H with n; exact has_one.mk (cyclic_succ (fin.zero n))
definition has_add_fin [instance] (n : ℕ) : has_add (fin n) :=
has_add.mk fin.add
end fin
|
f66983f0c906946f3683111d3b30b42f022365cd | f5f7e6fae601a5fe3cac7cc3ed353ed781d62419 | /src/order/basic.lean | 86720979d8bbeabd15683c0e7427c2d8378e5175 | [
"Apache-2.0"
] | permissive | EdAyers/mathlib | 9ecfb2f14bd6caad748b64c9c131befbff0fb4e0 | ca5d4c1f16f9c451cf7170b10105d0051db79e1b | refs/heads/master | 1,626,189,395,845 | 1,555,284,396,000 | 1,555,284,396,000 | 144,004,030 | 0 | 0 | Apache-2.0 | 1,533,727,664,000 | 1,533,727,663,000 | null | UTF-8 | Lean | false | false | 22,550 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Mario Carneiro
-/
import tactic.interactive logic.basic data.sum data.set.basic algebra.order
open function
/- TODO: automatic construction of dual definitions / theorems -/
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w} {r : α → α → Prop}
theorem ge_of_eq [preorder α] {a b : α} : a = b → a ≥ b :=
λ h, h ▸ le_refl a
theorem is_refl.swap (r) [is_refl α r] : is_refl α (swap r) := ⟨refl_of r⟩
theorem is_irrefl.swap (r) [is_irrefl α r] : is_irrefl α (swap r) := ⟨irrefl_of r⟩
theorem is_trans.swap (r) [is_trans α r] : is_trans α (swap r) :=
⟨λ a b c h₁ h₂, trans_of r h₂ h₁⟩
theorem is_antisymm.swap (r) [is_antisymm α r] : is_antisymm α (swap r) :=
⟨λ a b h₁ h₂, antisymm h₂ h₁⟩
theorem is_asymm.swap (r) [is_asymm α r] : is_asymm α (swap r) :=
⟨λ a b h₁ h₂, asymm_of r h₂ h₁⟩
theorem is_total.swap (r) [is_total α r] : is_total α (swap r) :=
⟨λ a b, (total_of r a b).swap⟩
theorem is_trichotomous.swap (r) [is_trichotomous α r] : is_trichotomous α (swap r) :=
⟨λ a b, by simpa [swap, or.comm, or.left_comm] using trichotomous_of r a b⟩
theorem is_preorder.swap (r) [is_preorder α r] : is_preorder α (swap r) :=
{..@is_refl.swap α r _, ..@is_trans.swap α r _}
theorem is_strict_order.swap (r) [is_strict_order α r] : is_strict_order α (swap r) :=
{..@is_irrefl.swap α r _, ..@is_trans.swap α r _}
theorem is_partial_order.swap (r) [is_partial_order α r] : is_partial_order α (swap r) :=
{..@is_preorder.swap α r _, ..@is_antisymm.swap α r _}
theorem is_total_preorder.swap (r) [is_total_preorder α r] : is_total_preorder α (swap r) :=
{..@is_preorder.swap α r _, ..@is_total.swap α r _}
theorem is_linear_order.swap (r) [is_linear_order α r] : is_linear_order α (swap r) :=
{..@is_partial_order.swap α r _, ..@is_total.swap α r _}
def antisymm_of_asymm (r) [is_asymm α r] : is_antisymm α r :=
⟨λ x y h₁ h₂, (asymm h₁ h₂).elim⟩
/- Convert algebraic structure style to explicit relation style typeclasses -/
instance [preorder α] : is_refl α (≤) := ⟨le_refl⟩
instance [preorder α] : is_refl α (≥) := is_refl.swap _
instance [preorder α] : is_trans α (≤) := ⟨@le_trans _ _⟩
instance [preorder α] : is_trans α (≥) := is_trans.swap _
instance [preorder α] : is_preorder α (≤) := {}
instance [preorder α] : is_preorder α (≥) := {}
instance [preorder α] : is_irrefl α (<) := ⟨lt_irrefl⟩
instance [preorder α] : is_irrefl α (>) := is_irrefl.swap _
instance [preorder α] : is_trans α (<) := ⟨@lt_trans _ _⟩
instance [preorder α] : is_trans α (>) := is_trans.swap _
instance [preorder α] : is_asymm α (<) := ⟨@lt_asymm _ _⟩
instance [preorder α] : is_asymm α (>) := is_asymm.swap _
instance [preorder α] : is_antisymm α (<) := antisymm_of_asymm _
instance [preorder α] : is_antisymm α (>) := antisymm_of_asymm _
instance [preorder α] : is_strict_order α (<) := {}
instance [preorder α] : is_strict_order α (>) := {}
instance preorder.is_total_preorder [preorder α] [is_total α (≤)] : is_total_preorder α (≤) := {}
instance [partial_order α] : is_antisymm α (≤) := ⟨@le_antisymm _ _⟩
instance [partial_order α] : is_antisymm α (≥) := is_antisymm.swap _
instance [partial_order α] : is_partial_order α (≤) := {}
instance [partial_order α] : is_partial_order α (≥) := {}
instance [linear_order α] : is_total α (≤) := ⟨le_total⟩
instance [linear_order α] : is_total α (≥) := is_total.swap _
instance linear_order.is_total_preorder [linear_order α] : is_total_preorder α (≤) := by apply_instance
instance [linear_order α] : is_total_preorder α (≥) := {}
instance [linear_order α] : is_linear_order α (≤) := {}
instance [linear_order α] : is_linear_order α (≥) := {}
instance [linear_order α] : is_trichotomous α (<) := ⟨lt_trichotomy⟩
instance [linear_order α] : is_trichotomous α (>) := is_trichotomous.swap _
theorem preorder.ext {α} {A B : preorder α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
resetI, cases A, cases B, congr,
{ funext x y, exact propext (H x y) },
{ funext x y,
dsimp [(≤)] at A_lt_iff_le_not_le B_lt_iff_le_not_le H,
simp [A_lt_iff_le_not_le, B_lt_iff_le_not_le, H] },
end
theorem partial_order.ext {α} {A B : partial_order α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
by haveI this := preorder.ext H;
cases A; cases B; injection this; congr'
theorem linear_order.ext {α} {A B : linear_order α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
by haveI this := partial_order.ext H;
cases A; cases B; injection this; congr'
/-- Given an order `R` on `β` and a function `f : α → β`,
the preimage order on `α` is defined by `x ≤ y ↔ f x ≤ f y`.
It is the unique order on `α` making `f` an order embedding
(assuming `f` is injective). -/
@[simp] def order.preimage {α β} (f : α → β) (s : β → β → Prop) (x y : α) := s (f x) (f y)
infix ` ⁻¹'o `:80 := order.preimage
section monotone
variables [preorder α] [preorder β] [preorder γ]
/-- A function between preorders is monotone if
`a ≤ b` implies `f a ≤ f b`. -/
def monotone (f : α → β) := ∀⦃a b⦄, a ≤ b → f a ≤ f b
theorem monotone_id : @monotone α α _ _ id := assume x y h, h
theorem monotone_const {b : β} : monotone (λ(a:α), b) := assume x y h, le_refl b
theorem monotone_comp {f : α → β} {g : β → γ} (m_f : monotone f) (m_g : monotone g) :
monotone (g ∘ f) :=
assume a b h, m_g (m_f h)
lemma monotone_of_monotone_nat {f : ℕ → α} (hf : ∀n, f n ≤ f (n + 1)) :
monotone f | n m h :=
begin
induction h,
{ refl },
{ transitivity, assumption, exact hf _ }
end
end monotone
def order_dual (α : Type*) := α
namespace order_dual
instance (α : Type*) [has_le α] : has_le (order_dual α) := ⟨λx y:α, y ≤ x⟩
instance (α : Type*) [has_lt α] : has_lt (order_dual α) := ⟨λx y:α, y < x⟩
instance (α : Type*) [preorder α] : preorder (order_dual α) :=
{ le_refl := le_refl,
le_trans := assume a b c hab hbc, le_trans hbc hab,
lt_iff_le_not_le := λ _ _, lt_iff_le_not_le,
.. order_dual.has_le α,
.. order_dual.has_lt α }
instance (α : Type*) [partial_order α] : partial_order (order_dual α) :=
{ le_antisymm := assume a b hab hba, @le_antisymm α _ a b hba hab, .. order_dual.preorder α }
instance (α : Type*) [linear_order α] : linear_order (order_dual α) :=
{ le_total := assume a b:α, le_total b a, .. order_dual.partial_order α }
instance (α : Type*) [decidable_linear_order α] : decidable_linear_order (order_dual α) :=
{ decidable_le := show decidable_rel (λa b:α, b ≤ a), by apply_instance,
decidable_lt := show decidable_rel (λa b:α, b < a), by apply_instance,
.. order_dual.linear_order α }
end order_dual
/- order instances on the function space -/
instance pi.preorder {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] : preorder (Πi, α i) :=
{ le := λx y, ∀i, x i ≤ y i,
le_refl := assume a i, le_refl (a i),
le_trans := assume a b c h₁ h₂ i, le_trans (h₁ i) (h₂ i) }
instance pi.partial_order {ι : Type u} {α : ι → Type v} [∀i, partial_order (α i)] : partial_order (Πi, α i) :=
{ le_antisymm := λf g h1 h2, funext (λb, le_antisymm (h1 b) (h2 b)),
..pi.preorder }
theorem comp_le_comp_left_of_monotone [preorder α] [preorder β] [preorder γ]
{f : β → α} {g h : γ → β} (m_f : monotone f) (le_gh : g ≤ h) : has_le.le.{max w u} (f ∘ g) (f ∘ h) :=
assume x, m_f (le_gh x)
section monotone
variables [preorder α] [preorder γ]
theorem monotone_lam {f : α → β → γ} (m : ∀b, monotone (λa, f a b)) : monotone f :=
assume a a' h b, m b h
theorem monotone_app (f : β → α → γ) (b : β) (m : monotone (λa b, f b a)) : monotone (f b) :=
assume a a' h, m h b
end monotone
def preorder.lift {α β} [preorder β] (f : α → β) : preorder α :=
{ le := λx y, f x ≤ f y,
le_refl := λ a, le_refl _,
le_trans := λ a b c, le_trans,
lt := λx y, f x < f y,
lt_iff_le_not_le := λ a b, lt_iff_le_not_le }
def partial_order.lift {α β} [partial_order β]
(f : α → β) (inj : injective f) : partial_order α :=
{ le_antisymm := λ a b h₁ h₂, inj (le_antisymm h₁ h₂), .. preorder.lift f }
def linear_order.lift {α β} [linear_order β]
(f : α → β) (inj : injective f) : linear_order α :=
{ le_total := λx y, le_total (f x) (f y), .. partial_order.lift f inj }
def decidable_linear_order.lift {α β} [decidable_linear_order β]
(f : α → β) (inj : injective f) : decidable_linear_order α :=
{ decidable_le := λ x y, show decidable (f x ≤ f y), by apply_instance,
decidable_lt := λ x y, show decidable (f x < f y), by apply_instance,
decidable_eq := λ x y, decidable_of_iff _ ⟨@inj x y, congr_arg f⟩,
.. linear_order.lift f inj }
instance subtype.preorder {α} [preorder α] (p : α → Prop) : preorder (subtype p) :=
preorder.lift subtype.val
instance subtype.partial_order {α} [partial_order α] (p : α → Prop) : partial_order (subtype p) :=
partial_order.lift subtype.val $ λ x y, subtype.eq'
instance subtype.linear_order {α} [linear_order α] (p : α → Prop) : linear_order (subtype p) :=
linear_order.lift subtype.val $ λ x y, subtype.eq'
instance subtype.decidable_linear_order {α} [decidable_linear_order α] (p : α → Prop) :
decidable_linear_order (subtype p) :=
decidable_linear_order.lift subtype.val $ λ x y, subtype.eq'
instance prod.has_le (α : Type u) (β : Type v) [has_le α] [has_le β] : has_le (α × β) :=
⟨λp q, p.1 ≤ q.1 ∧ p.2 ≤ q.2⟩
instance prod.preorder (α : Type u) (β : Type v) [preorder α] [preorder β] : preorder (α × β) :=
{ le_refl := assume ⟨a, b⟩, ⟨le_refl a, le_refl b⟩,
le_trans := assume ⟨a, b⟩ ⟨c, d⟩ ⟨e, f⟩ ⟨hac, hbd⟩ ⟨hce, hdf⟩,
⟨le_trans hac hce, le_trans hbd hdf⟩,
.. prod.has_le α β }
/-- The pointwise partial order on a product.
(The lexicographic ordering is defined in order/lexicographic.lean, and the instances are
available via the type synonym `lex α β = α × β`.) -/
instance prod.partial_order (α : Type u) (β : Type v) [partial_order α] [partial_order β] :
partial_order (α × β) :=
{ le_antisymm := assume ⟨a, b⟩ ⟨c, d⟩ ⟨hac, hbd⟩ ⟨hca, hdb⟩,
prod.ext (le_antisymm hac hca) (le_antisymm hbd hdb),
.. prod.preorder α β }
/- additional order classes -/
/-- order without a top element; somtimes called cofinal -/
class no_top_order (α : Type u) [preorder α] : Prop :=
(no_top : ∀a:α, ∃a', a < a')
lemma no_top [preorder α] [no_top_order α] : ∀a:α, ∃a', a < a' :=
no_top_order.no_top
/-- order without a bottom element; somtimes called coinitial or dense -/
class no_bot_order (α : Type u) [preorder α] : Prop :=
(no_bot : ∀a:α, ∃a', a' < a)
lemma no_bot [preorder α] [no_bot_order α] : ∀a:α, ∃a', a' < a :=
no_bot_order.no_bot
/-- An order is dense if there is an element between any pair of distinct elements. -/
class densely_ordered (α : Type u) [preorder α] : Prop :=
(dense : ∀a₁ a₂:α, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂)
lemma dense [preorder α] [densely_ordered α] : ∀{a₁ a₂:α}, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂ :=
densely_ordered.dense
lemma le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀a₃>a₂, a₁ ≤ a₃) :
a₁ ≤ a₂ :=
le_of_not_gt $ assume ha,
let ⟨a, ha₁, ha₂⟩ := dense ha in
lt_irrefl a $ lt_of_lt_of_le ‹a < a₁› (h _ ‹a₂ < a›)
lemma eq_of_le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}
(h₁ : a₂ ≤ a₁) (h₂ : ∀a₃>a₂, a₁ ≤ a₃) : a₁ = a₂ :=
le_antisymm (le_of_forall_le_of_dense h₂) h₁
lemma le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}(h : ∀a₃<a₁, a₂ ≥ a₃) :
a₁ ≤ a₂ :=
le_of_not_gt $ assume ha,
let ⟨a, ha₁, ha₂⟩ := dense ha in
lt_irrefl a $ lt_of_le_of_lt (h _ ‹a < a₁›) ‹a₂ < a›
lemma eq_of_le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}
(h₁ : a₂ ≤ a₁) (h₂ : ∀a₃<a₁, a₂ ≥ a₃) : a₁ = a₂ :=
le_antisymm (le_of_forall_ge_of_dense h₂) h₁
lemma dense_or_discrete [linear_order α] {a₁ a₂ : α} (h : a₁ < a₂) :
(∃a, a₁ < a ∧ a < a₂) ∨ ((∀a>a₁, a ≥ a₂) ∧ (∀a<a₂, a ≤ a₁)) :=
classical.or_iff_not_imp_left.2 $ assume h,
⟨assume a ha₁, le_of_not_gt $ assume ha₂, h ⟨a, ha₁, ha₂⟩,
assume a ha₂, le_of_not_gt $ assume ha₁, h ⟨a, ha₁, ha₂⟩⟩
section
variables {s : β → β → Prop} {t : γ → γ → Prop}
theorem is_irrefl_of_is_asymm [is_asymm α r] : is_irrefl α r :=
⟨λ a h, asymm h h⟩
/-- Construct a partial order from a `is_strict_order` relation -/
def partial_order_of_SO (r) [is_strict_order α r] : partial_order α :=
{ le := λ x y, x = y ∨ r x y,
lt := r,
le_refl := λ x, or.inl rfl,
le_trans := λ x y z h₁ h₂,
match y, z, h₁, h₂ with
| _, _, or.inl rfl, h₂ := h₂
| _, _, h₁, or.inl rfl := h₁
| _, _, or.inr h₁, or.inr h₂ := or.inr (trans h₁ h₂)
end,
le_antisymm := λ x y h₁ h₂,
match y, h₁, h₂ with
| _, or.inl rfl, h₂ := rfl
| _, h₁, or.inl rfl := rfl
| _, or.inr h₁, or.inr h₂ := (asymm h₁ h₂).elim
end,
lt_iff_le_not_le := λ x y,
⟨λ h, ⟨or.inr h, not_or
(λ e, by rw e at h; exact irrefl _ h)
(asymm h)⟩,
λ ⟨h₁, h₂⟩, h₁.resolve_left (λ e, h₂ $ e ▸ or.inl rfl)⟩ }
/-- This is basically the same as `is_strict_total_order`, but that definition is
in Type (probably by mistake) and also has redundant assumptions. -/
@[algebra] class is_strict_total_order' (α : Type u) (lt : α → α → Prop) extends is_trichotomous α lt, is_strict_order α lt : Prop.
/-- Construct a linear order from a `is_strict_total_order'` relation -/
def linear_order_of_STO' (r) [is_strict_total_order' α r] : linear_order α :=
{ le_total := λ x y,
match y, trichotomous_of r x y with
| y, or.inl h := or.inl (or.inr h)
| _, or.inr (or.inl rfl) := or.inl (or.inl rfl)
| _, or.inr (or.inr h) := or.inr (or.inr h)
end,
..partial_order_of_SO r }
/-- Construct a decidable linear order from a `is_strict_total_order'` relation -/
def decidable_linear_order_of_STO' (r) [is_strict_total_order' α r] [decidable_rel r] : decidable_linear_order α :=
by letI LO := linear_order_of_STO' r; exact
{ decidable_le := λ x y, decidable_of_iff (¬ r y x) (@not_lt _ _ y x),
..LO }
noncomputable def classical.DLO (α) [LO : linear_order α] : decidable_linear_order α :=
{ decidable_le := classical.dec_rel _, ..LO }
theorem is_strict_total_order'.swap (r) [is_strict_total_order' α r] : is_strict_total_order' α (swap r) :=
{..is_trichotomous.swap r, ..is_strict_order.swap r}
instance [linear_order α] : is_strict_total_order' α (<) := {}
/-- A connected order is one satisfying the condition `a < c → a < b ∨ b < c`.
This is recognizable as an intuitionistic substitute for `a ≤ b ∨ b ≤ a` on
the constructive reals, and is also known as negative transitivity,
since the contrapositive asserts transitivity of the relation `¬ a < b`. -/
@[algebra] class is_order_connected (α : Type u) (lt : α → α → Prop) : Prop :=
(conn : ∀ a b c, lt a c → lt a b ∨ lt b c)
theorem is_order_connected.neg_trans {r : α → α → Prop} [is_order_connected α r]
{a b c} (h₁ : ¬ r a b) (h₂ : ¬ r b c) : ¬ r a c :=
mt (is_order_connected.conn a b c) $ by simp [h₁, h₂]
theorem is_strict_weak_order_of_is_order_connected [is_asymm α r]
[is_order_connected α r] : is_strict_weak_order α r :=
{ trans := λ a b c h₁ h₂, (is_order_connected.conn _ c _ h₁).resolve_right (asymm h₂),
incomp_trans := λ a b c ⟨h₁, h₂⟩ ⟨h₃, h₄⟩,
⟨is_order_connected.neg_trans h₁ h₃, is_order_connected.neg_trans h₄ h₂⟩,
..@is_irrefl_of_is_asymm α r _ }
instance is_order_connected_of_is_strict_total_order'
[is_strict_total_order' α r] : is_order_connected α r :=
⟨λ a b c h, (trichotomous _ _).imp_right (λ o,
o.elim (λ e, e ▸ h) (λ h', trans h' h))⟩
instance is_strict_total_order_of_is_strict_total_order'
[is_strict_total_order' α r] : is_strict_total_order α r :=
{..is_strict_weak_order_of_is_order_connected}
instance [linear_order α] : is_strict_total_order α (<) := by apply_instance
instance [linear_order α] : is_order_connected α (<) := by apply_instance
instance [linear_order α] : is_incomp_trans α (<) := by apply_instance
instance [linear_order α] : is_strict_weak_order α (<) := by apply_instance
/-- An extensional relation is one in which an element is determined by its set
of predecessors. It is named for the `x ∈ y` relation in set theory, whose
extensionality is one of the first axioms of ZFC. -/
@[algebra] class is_extensional (α : Type u) (r : α → α → Prop) : Prop :=
(ext : ∀ a b, (∀ x, r x a ↔ r x b) → a = b)
instance is_extensional_of_is_strict_total_order'
[is_strict_total_order' α r] : is_extensional α r :=
⟨λ a b H, ((@trichotomous _ r _ a b)
.resolve_left $ mt (H _).2 (irrefl a))
.resolve_right $ mt (H _).1 (irrefl b)⟩
/-- A well order is a well-founded linear order. -/
@[algebra] class is_well_order (α : Type u) (r : α → α → Prop) extends is_strict_total_order' α r : Prop :=
(wf : well_founded r)
instance is_well_order.is_strict_total_order {α} (r : α → α → Prop) [is_well_order α r] : is_strict_total_order α r := by apply_instance
instance is_well_order.is_extensional {α} (r : α → α → Prop) [is_well_order α r] : is_extensional α r := by apply_instance
instance is_well_order.is_trichotomous {α} (r : α → α → Prop) [is_well_order α r] : is_trichotomous α r := by apply_instance
instance is_well_order.is_trans {α} (r : α → α → Prop) [is_well_order α r] : is_trans α r := by apply_instance
instance is_well_order.is_irrefl {α} (r : α → α → Prop) [is_well_order α r] : is_irrefl α r := by apply_instance
instance is_well_order.is_asymm {α} (r : α → α → Prop) [is_well_order α r] : is_asymm α r := by apply_instance
instance empty_relation.is_well_order [subsingleton α] : is_well_order α empty_relation :=
{ trichotomous := λ a b, or.inr $ or.inl $ subsingleton.elim _ _,
irrefl := λ a, id,
trans := λ a b c, false.elim,
wf := ⟨λ a, ⟨_, λ y, false.elim⟩⟩ }
instance nat.lt.is_well_order : is_well_order ℕ (<) := ⟨nat.lt_wf⟩
instance sum.lex.is_well_order [is_well_order α r] [is_well_order β s] : is_well_order (α ⊕ β) (sum.lex r s) :=
{ trichotomous := λ a b, by cases a; cases b; simp; apply trichotomous,
irrefl := λ a, by cases a; simp; apply irrefl,
trans := λ a b c, by cases a; cases b; simp; cases c; simp; apply trans,
wf := sum.lex_wf (is_well_order.wf r) (is_well_order.wf s) }
instance prod.lex.is_well_order [is_well_order α r] [is_well_order β s] : is_well_order (α × β) (prod.lex r s) :=
{ trichotomous := λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩,
match @trichotomous _ r _ a₁ b₁ with
| or.inl h₁ := or.inl $ prod.lex.left _ _ _ h₁
| or.inr (or.inr h₁) := or.inr $ or.inr $ prod.lex.left _ _ _ h₁
| or.inr (or.inl e) := e ▸ match @trichotomous _ s _ a₂ b₂ with
| or.inl h := or.inl $ prod.lex.right _ _ h
| or.inr (or.inr h) := or.inr $ or.inr $ prod.lex.right _ _ h
| or.inr (or.inl e) := e ▸ or.inr $ or.inl rfl
end
end,
irrefl := λ ⟨a₁, a₂⟩ h, by cases h with _ _ _ _ h _ _ _ h;
[exact irrefl _ h, exact irrefl _ h],
trans := λ a b c h₁ h₂, begin
cases h₁ with a₁ a₂ b₁ b₂ ab a₁ b₁ b₂ ab;
cases h₂ with _ _ c₁ c₂ bc _ _ c₂ bc,
{ exact prod.lex.left _ _ _ (trans ab bc) },
{ exact prod.lex.left _ _ _ ab },
{ exact prod.lex.left _ _ _ bc },
{ exact prod.lex.right _ _ (trans ab bc) }
end,
wf := prod.lex_wf (is_well_order.wf r) (is_well_order.wf s) }
theorem well_founded.has_min {α} {r : α → α → Prop} (H : well_founded r)
(p : set α) : p ≠ ∅ → ∃ a ∈ p, ∀ x ∈ p, ¬ r x a :=
by haveI := classical.prop_decidable; exact
not_imp_comm.1 (λ he, set.eq_empty_iff_forall_not_mem.2 $ λ a,
acc.rec_on (H.apply a) $ λ a H IH h,
he ⟨_, h, λ y, imp_not_comm.1 (IH y)⟩)
/-- The minimum element of a nonempty set in a well-founded order -/
noncomputable def well_founded.min {α} {r : α → α → Prop} (H : well_founded r)
(p : set α) (h : p ≠ ∅) : α :=
classical.some (H.has_min p h)
theorem well_founded.min_mem {α} {r : α → α → Prop} (H : well_founded r)
(p : set α) (h : p ≠ ∅) : H.min p h ∈ p :=
let ⟨h, _⟩ := classical.some_spec (H.has_min p h) in h
theorem well_founded.not_lt_min {α} {r : α → α → Prop} (H : well_founded r)
(p : set α) (h : p ≠ ∅) {x} (xp : x ∈ p) : ¬ r x (H.min p h) :=
let ⟨_, h'⟩ := classical.some_spec (H.has_min p h) in h' _ xp
variable (r)
local infix `≼` : 50 := r
/-- A family of elements of α is directed (with respect to a relation `≼` on α)
if there is a member of the family `≼`-above any pair in the family. -/
def directed {ι : Sort v} (f : ι → α) := ∀x y, ∃z, f x ≼ f z ∧ f y ≼ f z
/-- A subset of α is directed if there is an element of the set `≼`-above any
pair of elements in the set. -/
def directed_on (s : set α) := ∀ (x ∈ s) (y ∈ s), ∃z ∈ s, x ≼ z ∧ y ≼ z
theorem directed_on_iff_directed {s} : @directed_on α r s ↔ directed r (coe : s → α) :=
by simp [directed, directed_on]; refine ball_congr (λ x hx, by simp; refl)
theorem directed_comp {ι} (f : ι → β) (g : β → α) :
directed r (g ∘ f) ↔ directed (g ⁻¹'o r) f := iff.rfl
theorem directed_mono {s : α → α → Prop} {ι} (f : ι → α)
(H : ∀ a b, r a b → s a b) (h : directed r f) : directed s f :=
λ a b, let ⟨c, h₁, h₂⟩ := h a b in ⟨c, H _ _ h₁, H _ _ h₂⟩
end
|
65db46eb8ad6b369f15a57707d6d11c112914339 | 4f065978c49388d188224610d9984673079f7d91 | /abelianization.lean | 1677fc29ab54ce656a790e5a7c6acbb0ddda5357 | [] | no_license | kckennylau/Lean | b323103f52706304907adcfaee6f5cb8095d4a33 | 907d0a4d2bd8f23785abd6142ad53d308c54fdcb | refs/heads/master | 1,624,623,720,653 | 1,563,901,820,000 | 1,563,901,820,000 | 109,506,702 | 3 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 4,200 | lean | import data.set.basic algebra.group
universes u v
namespace group
variables {α : Type u} [group α] (S : set α)
inductive generate : set α
| basic : ∀ x ∈ S, generate x
| one : generate 1
| inv : ∀ x, generate x → generate x⁻¹
| mul : ∀ x y, generate x → generate y → generate (x * y)
namespace generate
def group : group (generate S) :=
by refine
{ mul := λ x y, ⟨x * y, mul x y x.2 y.2⟩,
one := ⟨1, one S⟩,
inv := λ x, ⟨x⁻¹, inv x x.2⟩,
.. };
{ intros, apply subtype.eq,
{ apply mul_assoc <|> apply mul_one <|>
apply one_mul <|> apply mul_left_inv } }
end generate
end group
variables (G : Type u) [group G]
namespace abelianization
def ambient : Type (max u (v+1)) := Π (H : Type v) [comm_group H] (f : G → H) (Hf : @is_group_hom G H _ (@comm_group.to_group H _inst_2) f), H
instance ambient.comm_group : comm_group (ambient.{u v} G) :=
by refine
{ mul := λ x y H HH f Hf, @has_mul.mul _ (@semigroup.to_has_mul _ (@monoid.to_semigroup _ (@group.to_monoid H (@comm_group.to_group H HH)))) (@x H HH f Hf) (@y H HH f Hf),
one := λ H HH f Hf, @has_one.one _ (@monoid.to_has_one _ (@group.to_monoid H (@comm_group.to_group H HH))),
inv := λ x H HH f Hf, @has_inv.inv _ (@group.to_has_inv H (@comm_group.to_group H HH)) (@x H HH f Hf),
.. };
{ intros, funext, dsimp, letI := HH,
{ apply mul_assoc <|> apply mul_one <|>
apply one_mul <|> apply mul_left_inv <|> apply mul_comm } }
def ambient.of_G : G → ambient G :=
λ x H HH f Hf, f x
end abelianization
def abelianization : Type (max u (v+1)) :=
group.generate (abelianization.ambient.of_G G '' set.univ)
namespace abelianization
def of_G : G → abelianization G :=
λ x, ⟨ambient.of_G G x, group.generate.basic _ ⟨x, trivial, rfl⟩⟩
instance : comm_group (abelianization G) :=
{ mul_comm := λ x y, subtype.eq $ by funext; apply HH.mul_comm,
.. group.generate.group _ }
def of_G.is_group_hom : is_group_hom (of_G G) :=
λ x y, subtype.eq $ by funext; apply Hf
variables (H : Type v) [comm_group H] (f : G → H) (Hf : is_group_hom f)
def to_comm_group : abelianization G → H :=
λ x, x.1 H f Hf
def to_comm_group.is_group_hom : is_group_hom (to_comm_group G H f Hf) :=
λ x y, rfl
def to_comm_group.commute (x : G) : to_comm_group G H f Hf (of_G G x) = f x :=
rfl
variables (g : abelianization.{u v} G → H)
variables (Hg1 : is_group_hom g)
variables (Hg2 : ∀ x, g (of_G G x) = f x)
include Hg1 Hg2
def to_comm_group.unique : g = to_comm_group G H f Hf :=
begin
funext x,
cases x with x hx,
induction hx with x1 h x1 h ih x1 x2 h1 h2 ih1 ih2,
case group.generate.basic
{ rcases h with ⟨x2, h1, h2⟩,
specialize Hg2 x2,
dsimp [of_G] at Hg2,
have H1 : (⟨ambient.of_G G x2, of_G._proof_1 G x2⟩ : abelianization G) =
⟨x1, group.generate.basic x1 (Exists.intro x2 ⟨h1, h2⟩)⟩,
{ congr, exact h2 },
rw H1 at Hg2,
rw Hg2,
dsimp [to_comm_group],
have h3 := congr_arg (λ z : ambient G, z H f) h2,
dsimp at h3,
rw ← h3,
refl },
case group.generate.one
{ exact Hg1.one },
case group.generate.inv
{ have H1 : (⟨x1⁻¹, group.generate.inv x1 h⟩ : abelianization G) =
@has_inv.inv _ (@group.to_has_inv _ (@comm_group.to_group _ (abelianization.comm_group G))) ⟨x1, h⟩ := rfl,
rw [H1, ← Hg1.inv, ih],
refl },
case group.generate.mul
{ have H1 : (⟨x1 * x2, group.generate.mul x1 x2 h1 h2⟩ : abelianization G) =
@has_mul.mul _ (@semigroup.to_has_mul _ (@monoid.to_semigroup _ (@group.to_monoid _ (group.generate.group _)))) ⟨x1, h1⟩ ⟨x2, h2⟩ := rfl,
rw [H1, Hg1, ih1, ih2],
refl }
end
end abelianization
namespace commutator
def commutators : set G :=
abelianization.of_G G ⁻¹' {1}
variables (x y : G)
theorem commutator : x * y * x⁻¹ * y⁻¹ ∈ commutators G :=
by dsimp [commutators]; simp;
rw [abelianization.of_G.is_group_hom G];
rw [abelianization.of_G.is_group_hom G];
rw [abelianization.of_G.is_group_hom G];
rw [← is_group_hom.inv (abelianization.of_G.is_group_hom G)];
rw [← is_group_hom.inv (abelianization.of_G.is_group_hom G)];
rw [mul_comm (abelianization.of_G G x)];
simp
end commutator
|
4c2954eb3cd2250057ab723d9fc3852fb2973d4c | 4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d | /stage0/src/Lean/Elab/Deriving/DecEq.lean | 688c90b9e02c0a9035588421c83b95ee4dc140b7 | [
"Apache-2.0"
] | permissive | subfish-zhou/leanprover-zh_CN.github.io | 30b9fba9bd790720bd95764e61ae796697d2f603 | 8b2985d4a3d458ceda9361ac454c28168d920d3f | refs/heads/master | 1,689,709,967,820 | 1,632,503,056,000 | 1,632,503,056,000 | 409,962,097 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,892 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Transform
import Lean.Meta.Inductive
import Lean.Elab.Deriving.Basic
import Lean.Elab.Deriving.Util
namespace Lean.Elab.Deriving.DecEq
open Lean.Parser.Term
open Meta
def mkDecEqHeader (ctx : Context) (indVal : InductiveVal) : TermElabM Header := do
mkHeader ctx `DecidableEq 2 indVal
def mkMatch (ctx : Context) (header : Header) (indVal : InductiveVal) (auxFunName : Name) (argNames : Array Name) : TermElabM Syntax := do
let discrs ← mkDiscrs header indVal
let alts ← mkAlts
`(match $[$discrs],* with $alts:matchAlt*)
where
mkSameCtorRhs : List (Syntax × Syntax × Bool) → TermElabM Syntax
| [] => ``(isTrue rfl)
| (a, b, recField) :: todo => withFreshMacroScope do
let rhs ←
`(if h : $a = $b then
by subst h; exact $(← mkSameCtorRhs todo):term
else
isFalse (by intro n; injection n; apply h _; assumption))
if recField then
-- add local instance for `a = b` using the function being defined `auxFunName`
`(let inst := $(mkIdent auxFunName) $a $b; $rhs)
else
return rhs
mkAlts : TermElabM (Array Syntax) := do
let mut alts := #[]
for ctorName₁ in indVal.ctors do
let ctorInfo ← getConstInfoCtor ctorName₁
for ctorName₂ in indVal.ctors do
let mut patterns := #[]
-- add `_` pattern for indices
for i in [:indVal.numIndices] do
patterns := patterns.push (← `(_))
if ctorName₁ == ctorName₂ then
let alt ← forallTelescopeReducing ctorInfo.type fun xs type => do
let type ← Core.betaReduce type -- we 'beta-reduce' to eliminate "artificial" dependencies
let mut patterns := patterns
let mut ctorArgs1 := #[]
let mut ctorArgs2 := #[]
-- add `_` for inductive parameters, they are inaccessible
for i in [:indVal.numParams] do
ctorArgs1 := ctorArgs1.push (← `(_))
ctorArgs2 := ctorArgs2.push (← `(_))
let mut todo := #[]
for i in [:ctorInfo.numFields] do
let x := xs[indVal.numParams + i]
if type.containsFVar x.fvarId! then
-- If resulting type depends on this field, we don't need to compare
ctorArgs1 := ctorArgs1.push (← `(_))
ctorArgs2 := ctorArgs2.push (← `(_))
else
let a := mkIdent (← mkFreshUserName `a)
let b := mkIdent (← mkFreshUserName `b)
ctorArgs1 := ctorArgs1.push a
ctorArgs2 := ctorArgs2.push b
let recField := (← inferType x).isAppOf indVal.name
todo := todo.push (a, b, recField)
patterns := patterns.push (← `(@$(mkIdent ctorName₁):ident $ctorArgs1:term*))
patterns := patterns.push (← `(@$(mkIdent ctorName₁):ident $ctorArgs2:term*))
let rhs ← mkSameCtorRhs todo.toList
`(matchAltExpr| | $[$patterns:term],* => $rhs:term)
alts := alts.push alt
else if (← compatibleCtors ctorName₁ ctorName₂) then
patterns := patterns ++ #[(← `($(mkIdent ctorName₁) ..)), (← `($(mkIdent ctorName₂) ..))]
let rhs ← `(isFalse (by intro h; injection h))
alts ← alts.push (← `(matchAltExpr| | $[$patterns:term],* => $rhs:term))
return alts
def mkAuxFunction (ctx : Context) : TermElabM Syntax := do
let auxFunName ← ctx.auxFunNames[0]
let indVal ← ctx.typeInfos[0]
let header ← mkDecEqHeader ctx indVal
let mut body ← mkMatch ctx header indVal auxFunName header.argNames
let binders := header.binders
let type ← `(Decidable ($(mkIdent header.targetNames[0]) = $(mkIdent header.targetNames[1])))
`(private def $(mkIdent auxFunName):ident $binders:explicitBinder* : $type:term := $body:term)
def mkDecEqCmds (indVal : InductiveVal) : TermElabM (Array Syntax) := do
let ctx ← mkContext "decEq" indVal.name
let cmds := #[← mkAuxFunction ctx] ++ (← mkInstanceCmds ctx `DecidableEq #[indVal.name] (useAnonCtor := false))
trace[Elab.Deriving.decEq] "\n{cmds}"
return cmds
open Command
def mkDecEq (declName : Name) : CommandElabM Bool := do
let indVal ← getConstInfoInduct declName
if indVal.isNested then
return false -- nested inductive types are not supported yet
else
let cmds ← liftTermElabM none <| mkDecEqCmds indVal
cmds.forM elabCommand
return true
partial def mkEnumOfNat (declName : Name) : MetaM Unit := do
let indVal ← getConstInfoInduct declName
let enumType := mkConst declName
let ctors := indVal.ctors.toArray
withLocalDeclD `n (mkConst ``Nat) fun n => do
let cond := mkConst ``cond [levelZero]
let rec mkDecTree (low high : Nat) : Expr :=
if low + 1 == high then
mkConst ctors[low]
else if low + 2 == high then
mkApp4 cond enumType (mkApp2 (mkConst ``Nat.beq) n (mkRawNatLit low)) (mkConst ctors[low]) (mkConst ctors[low+1])
else
let mid := (low + high)/2
let lowBranch := mkDecTree low mid
let highBranch := mkDecTree mid high
mkApp4 cond enumType (mkApp2 (mkConst ``Nat.ble) (mkRawNatLit mid) n) highBranch lowBranch
let value ← mkLambdaFVars #[n] (mkDecTree 0 ctors.size)
let type ← mkArrow (mkConst ``Nat) enumType
addAndCompile <| Declaration.defnDecl {
name := Name.mkStr declName "ofNat"
levelParams := []
safety := DefinitionSafety.safe
hints := ReducibilityHints.abbrev
value, type
}
def mkEnumOfNatThm (declName : Name) : MetaM Unit := do
let indVal ← getConstInfoInduct declName
let toCtorIdx := mkConst (Name.mkStr declName "toCtorIdx")
let ofNat := mkConst (Name.mkStr declName "ofNat")
let enumType := mkConst declName
let eqEnum := mkApp (mkConst ``Eq [levelOne]) enumType
let rflEnum := mkApp (mkConst ``Eq.refl [levelOne]) enumType
let ctors := indVal.ctors
withLocalDeclD `x enumType fun x => do
let resultType := mkApp2 eqEnum (mkApp ofNat (mkApp toCtorIdx x)) x
let motive ← mkLambdaFVars #[x] resultType
let casesOn := mkConst (mkCasesOnName declName) [levelZero]
let mut value := mkApp2 casesOn motive x
for ctor in ctors do
value := mkApp value (mkApp rflEnum (mkConst ctor))
value ← mkLambdaFVars #[x] value
let type ← mkForallFVars #[x] resultType
addAndCompile <| Declaration.thmDecl {
name := Name.mkStr declName "ofNat_toCtorIdx"
levelParams := []
value, type
}
def mkDecEqEnum (declName : Name) : CommandElabM Unit := do
liftTermElabM none <| mkEnumOfNat declName
liftTermElabM none <| mkEnumOfNatThm declName
let ofNatIdent := mkIdent (Name.mkStr declName "ofNat")
let auxThmIdent := mkIdent (Name.mkStr declName "ofNat_toCtorIdx")
let indVal ← getConstInfoInduct declName
let cmd ← `(
instance : DecidableEq $(mkIdent declName) :=
fun x y =>
if h : x.toCtorIdx = y.toCtorIdx then
isTrue (by have aux := congrArg $ofNatIdent h; rw [$auxThmIdent:ident, $auxThmIdent:ident] at aux; assumption)
else
isFalse fun h => by subst h; contradiction
)
elabCommand cmd
def mkDecEqInstanceHandler (declNames : Array Name) : CommandElabM Bool := do
if declNames.size != 1 then
return false -- mutually inductive types are not supported yet
else if (← isEnumType declNames[0]) then
mkDecEqEnum declNames[0]
return true
else
mkDecEq declNames[0]
builtin_initialize
registerBuiltinDerivingHandler `DecidableEq mkDecEqInstanceHandler
registerTraceClass `Elab.Deriving.decEq
end Lean.Elab.Deriving.DecEq
|
94a71847f86fb9acc657ed47f575643e3f1c55d2 | 8b9f17008684d796c8022dab552e42f0cb6fb347 | /library/data/set/function.lean | 06e117121d1471cfa1a5aa0a1254ea734a9b32de | [
"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 | 7,787 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: data.set.function
Author: Jeremy Avigad, Andrew Zipperer
Functions between subsets of finite types.
-/
import .basic
import algebra.function
open function eq.ops
namespace set
variables {X Y Z : Type}
abbreviation eq_on (f1 f2 : X → Y) (a : set X) : Prop :=
∀₀ x ∈ a, f1 x = f2 x
/- image -/
definition image (f : X → Y) (a : set X) : set Y := {y : Y | ∃x, x ∈ a ∧ f x = y}
notation f `'[`:max a `]` := image f a
theorem image_eq_image_of_eq_on {f1 f2 : X → Y} {a : set X} (H1 : eq_on f1 f2 a) :
f1 '[a] = f2 '[a] :=
setext (take y, iff.intro
(assume H2,
obtain x (H3 : x ∈ a ∧ f1 x = y), from H2,
have H4 : x ∈ a, from and.left H3,
have H5 : f2 x = y, from (H1 H4)⁻¹ ⬝ and.right H3,
exists.intro x (and.intro H4 H5))
(assume H2,
obtain x (H3 : x ∈ a ∧ f2 x = y), from H2,
have H4 : x ∈ a, from and.left H3,
have H5 : f1 x = y, from (H1 H4) ⬝ and.right H3,
exists.intro x (and.intro H4 H5)))
/- maps to -/
definition maps_to [reducible] (f : X → Y) (a : set X) (b : set Y) : Prop := ∀⦃x⦄, x ∈ a → f x ∈ b
theorem maps_to_of_eq_on {f1 f2 : X → Y} {a : set X} {b : set Y} (eq_on_a : eq_on f1 f2 a)
(maps_to_f1 : maps_to f1 a b) :
maps_to f2 a b :=
take x,
assume xa : x ∈ a,
have H : f1 x ∈ b, from maps_to_f1 xa,
show f2 x ∈ b, from eq_on_a xa ▸ H
theorem maps_to_compose {g : Y → Z} {f : X → Y} {a : set X} {b : set Y} {c : set Z}
(H1 : maps_to g b c) (H2 : maps_to f a b) : maps_to (g ∘ f) a c :=
take x, assume H : x ∈ a, H1 (H2 H)
/- injectivity -/
definition inj_on [reducible] (f : X → Y) (a : set X) : Prop :=
∀⦃x1 x2 : X⦄, x1 ∈ a → x2 ∈ a → f x1 = f x2 → x1 = x2
theorem inj_on_of_eq_on {f1 f2 : X → Y} {a : set X} (eq_f1_f2 : eq_on f1 f2 a)
(inj_f1 : inj_on f1 a) :
inj_on f2 a :=
take x1 x2 : X,
assume ax1 : x1 ∈ a,
assume ax2 : x2 ∈ a,
assume H : f2 x1 = f2 x2,
have H' : f1 x1 = f1 x2, from eq_f1_f2 ax1 ⬝ H ⬝ (eq_f1_f2 ax2)⁻¹,
show x1 = x2, from inj_f1 ax1 ax2 H'
theorem inj_on_compose {g : Y → Z} {f : X → Y} {a : set X} {b : set Y}
(fab : maps_to f a b) (Hg : inj_on g b) (Hf: inj_on f a) :
inj_on (g ∘ f) a :=
take x1 x2 : X,
assume x1a : x1 ∈ a,
assume x2a : x2 ∈ a,
have fx1b : f x1 ∈ b, from fab x1a,
have fx2b : f x2 ∈ b, from fab x2a,
assume H1 : g (f x1) = g (f x2),
have H2 : f x1 = f x2, from Hg fx1b fx2b H1,
show x1 = x2, from Hf x1a x2a H2
/- surjectivity -/
definition surj_on [reducible] (f : X → Y) (a : set X) (b : set Y) : Prop := b ⊆ f '[a]
theorem surj_on_of_eq_on {f1 f2 : X → Y} {a : set X} {b : set Y} (eq_f1_f2 : eq_on f1 f2 a)
(surj_f1 : surj_on f1 a b) :
surj_on f2 a b :=
take y, assume H : y ∈ b,
obtain x (H1 : x ∈ a ∧ f1 x = y), from surj_f1 H,
have H2 : x ∈ a, from and.left H1,
have H3 : f2 x = y, from (eq_f1_f2 H2)⁻¹ ⬝ and.right H1,
exists.intro x (and.intro H2 H3)
theorem surj_on_compose {g : Y → Z} {f : X → Y} {a : set X} {b : set Y} {c : set Z}
(Hg : surj_on g b c) (Hf: surj_on f a b) :
surj_on (g ∘ f) a c :=
take z,
assume zc : z ∈ c,
obtain y (H1 : y ∈ b ∧ g y = z), from Hg zc,
obtain x (H2 : x ∈ a ∧ f x = y), from Hf (and.left H1),
show ∃x, x ∈ a ∧ g (f x) = z, from
exists.intro x
(and.intro
(and.left H2)
(calc
g (f x) = g y : {and.right H2}
... = z : and.right H1))
/- bijectivity -/
definition bij_on [reducible] (f : X → Y) (a : set X) (b : set Y) : Prop :=
maps_to f a b ∧ inj_on f a ∧ surj_on f a b
theorem bij_on_of_eq_on {f1 f2 : X → Y} {a : set X} {b : set Y} (eqf : eq_on f1 f2 a)
(H : bij_on f1 a b) : bij_on f2 a b :=
match H with and.intro Hmap (and.intro Hinj Hsurj) :=
and.intro
(maps_to_of_eq_on eqf Hmap)
(and.intro
(inj_on_of_eq_on eqf Hinj)
(surj_on_of_eq_on eqf Hsurj))
end
theorem bij_on_compose {g : Y → Z} {f : X → Y} {a : set X} {b : set Y} {c : set Z}
(Hg : bij_on g b c) (Hf: bij_on f a b) :
bij_on (g ∘ f) a c :=
match Hg with and.intro Hgmap (and.intro Hginj Hgsurj) :=
match Hf with and.intro Hfmap (and.intro Hfinj Hfsurj) :=
and.intro
(maps_to_compose Hgmap Hfmap)
(and.intro
(inj_on_compose Hfmap Hginj Hfinj)
(surj_on_compose Hgsurj Hfsurj))
end
end
/- left inverse -/
-- g is a left inverse to f on a
definition left_inv_on [reducible] (g : Y → X) (f : X → Y) (a : set X) : Prop :=
∀₀ x ∈ a, g (f x) = x
theorem left_inv_on_of_eq_on_left {g1 g2 : Y → X} {f : X → Y} {a : set X} {b : set Y}
(fab : maps_to f a b) (eqg : eq_on g1 g2 b) (H : left_inv_on g1 f a) : left_inv_on g2 f a :=
take x,
assume xa : x ∈ a,
calc
g2 (f x) = g1 (f x) : (eqg (fab xa))⁻¹
... = x : H xa
theorem left_inv_on_of_eq_on_right {g : Y → X} {f1 f2 : X → Y} {a : set X}
(eqf : eq_on f1 f2 a) (H : left_inv_on g f1 a) : left_inv_on g f2 a :=
take x,
assume xa : x ∈ a,
calc
g (f2 x) = g (f1 x) : {(eqf xa)⁻¹}
... = x : H xa
theorem inj_on_of_left_inv_on {g : Y → X} {f : X → Y} {a : set X} (H : left_inv_on g f a) :
inj_on f a :=
take x1 x2,
assume x1a : x1 ∈ a,
assume x2a : x2 ∈ a,
assume H1 : f x1 = f x2,
calc
x1 = g (f x1) : H x1a
... = g (f x2) : H1
... = x2 : H x2a
theorem left_inv_on_compose {f' : Y → X} {g' : Z → Y} {g : Y → Z} {f : X → Y}
{a : set X} {b : set Y} (fab : maps_to f a b)
(Hf : left_inv_on f' f a) (Hg : left_inv_on g' g b) : left_inv_on (f' ∘ g') (g ∘ f) a :=
take x : X,
assume xa : x ∈ a,
have fxb : f x ∈ b, from fab xa,
calc
f' (g' (g (f x))) = f' (f x) : Hg fxb
... = x : Hf xa
/- right inverse -/
-- g is a right inverse to f on a
definition right_inv_on [reducible] (g : Y → X) (f : X → Y) (b : set Y) : Prop :=
left_inv_on f g b
theorem right_inv_on_of_eq_on_left {g1 g2 : Y → X} {f : X → Y} {a : set X} {b : set Y}
(eqg : eq_on g1 g2 b) (H : right_inv_on g1 f b) : right_inv_on g2 f b :=
left_inv_on_of_eq_on_right eqg H
theorem right_inv_on_of_eq_on_right {g : Y → X} {f1 f2 : X → Y} {a : set X} {b : set Y}
(gba : maps_to g b a) (eqf : eq_on f1 f2 a) (H : right_inv_on g f1 b) : right_inv_on g f2 b :=
left_inv_on_of_eq_on_left gba eqf H
theorem surj_on_of_right_inv_on {g : Y → X} {f : X → Y} {a : set X} {b : set Y}
(gba : maps_to g b a) (H : right_inv_on g f b) :
surj_on f a b :=
take y,
assume yb : y ∈ b,
have gya : g y ∈ a, from gba yb,
have H1 : f (g y) = y, from H yb,
exists.intro (g y) (and.intro gya H1)
theorem right_inv_on_compose {f' : Y → X} {g' : Z → Y} {g : Y → Z} {f : X → Y}
{c : set Z} {b : set Y} (g'cb : maps_to g' c b)
(Hf : right_inv_on f' f b) (Hg : right_inv_on g' g c) : right_inv_on (f' ∘ g') (g ∘ f) c :=
left_inv_on_compose g'cb Hg Hf
theorem eq_on_of_left_inv_of_right_inv {g1 g2 : Y → X} {f : X → Y} {a : set X} {b : set Y}
(g2ba : maps_to g2 b a) (Hg1 : left_inv_on g1 f a) (Hg2 : right_inv_on g2 f b) : eq_on g1 g2 b :=
take y,
assume yb : y ∈ b,
calc
g1 y = g1 (f (g2 y)) : {(Hg2 yb)⁻¹}
... = g2 y : Hg1 (g2ba yb)
/- inverses -/
-- g is an inverse to f viewed as a map from a to b
definition inv_on [reducible] (g : Y → X) (f : X → Y) (a : set X) (b : set Y) : Prop :=
left_inv_on g f a ∧ right_inv_on g f b
theorem bij_on_of_inv_on {g : Y → X} {f : X → Y} {a : set X} {b : set Y} (fab : maps_to f a b)
(gba : maps_to g b a) (H : inv_on g f a b) : bij_on f a b :=
and.intro fab
(and.intro
(inj_on_of_left_inv_on (and.left H))
(surj_on_of_right_inv_on gba (and.right H)))
end set
|
7992d12f07afac4456e969f98fd0291884becae0 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/topology/algebra/group_with_zero.lean | b8f1d991045956702a592844356d5e5e8b6f7fbe | [
"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 | 11,421 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
-/
import topology.algebra.monoid
import algebra.group.pi
import topology.homeomorph
/-!
# Topological group with zero
In this file we define `has_continuous_inv₀` to be a mixin typeclass a type with `has_inv` and
`has_zero` (e.g., a `group_with_zero`) such that `λ x, x⁻¹` is continuous at all nonzero points. Any
normed (semi)field has this property. Currently the only example of `has_continuous_inv₀` in
`mathlib` which is not a normed field is the type `nnnreal` (a.k.a. `ℝ≥0`) of nonnegative real
numbers.
Then we prove lemmas about continuity of `x ↦ x⁻¹` and `f / g` providing dot-style `*.inv'` and
`*.div` operations on `filter.tendsto`, `continuous_at`, `continuous_within_at`, `continuous_on`,
and `continuous`. As a special case, we provide `*.div_const` operations that require only
`group_with_zero` and `has_continuous_mul` instances.
All lemmas about `(⁻¹)` use `inv'` in their names because lemmas without `'` are used for
`topological_group`s. We also use `'` in the typeclass name `has_continuous_inv₀` for the sake of
consistency of notation.
On a `group_with_zero` with continuous multiplication, we also define left and right multiplication
as homeomorphisms.
-/
open_locale topological_space filter
open filter function
/-!
### A group with zero with continuous multiplication
If `G₀` is a group with zero with continuous `(*)`, then `(/y)` is continuous for any `y`. In this
section we prove lemmas that immediately follow from this fact providing `*.div_const` dot-style
operations on `filter.tendsto`, `continuous_at`, `continuous_within_at`, `continuous_on`, and
`continuous`.
-/
variables {α β G₀ : Type*}
section div_const
variables [group_with_zero G₀] [topological_space G₀] [has_continuous_mul G₀]
{f : α → G₀} {s : set α} {l : filter α}
lemma filter.tendsto.div_const {x y : G₀} (hf : tendsto f l (𝓝 x)) :
tendsto (λa, f a / y) l (𝓝 (x / y)) :=
by simpa only [div_eq_mul_inv] using hf.mul tendsto_const_nhds
variables [topological_space α]
lemma continuous_at.div_const {a : α} (hf : continuous_at f a) {y : G₀} :
continuous_at (λ x, f x / y) a :=
by simpa only [div_eq_mul_inv] using hf.mul continuous_at_const
lemma continuous_within_at.div_const {a} (hf : continuous_within_at f s a) {y : G₀} :
continuous_within_at (λ x, f x / y) s a :=
hf.div_const
lemma continuous_on.div_const (hf : continuous_on f s) {y : G₀} : continuous_on (λ x, f x / y) s :=
by simpa only [div_eq_mul_inv] using hf.mul continuous_on_const
@[continuity] lemma continuous.div_const (hf : continuous f) {y : G₀} :
continuous (λ x, f x / y) :=
by simpa only [div_eq_mul_inv] using hf.mul continuous_const
end div_const
/-- A type with `0` and `has_inv` such that `λ x, x⁻¹` is continuous at all nonzero points. Any
normed (semi)field has this property. -/
class has_continuous_inv₀ (G₀ : Type*) [has_zero G₀] [has_inv G₀] [topological_space G₀] : Prop :=
(continuous_at_inv₀ : ∀ ⦃x : G₀⦄, x ≠ 0 → continuous_at has_inv.inv x)
export has_continuous_inv₀ (continuous_at_inv₀)
section inv₀
variables [has_zero G₀] [has_inv G₀] [topological_space G₀] [has_continuous_inv₀ G₀]
{l : filter α} {f : α → G₀} {s : set α} {a : α}
/-!
### Continuity of `λ x, x⁻¹` at a non-zero point
We define `topological_group_with_zero` to be a `group_with_zero` such that the operation `x ↦ x⁻¹`
is continuous at all nonzero points. In this section we prove dot-style `*.inv'` lemmas for
`filter.tendsto`, `continuous_at`, `continuous_within_at`, `continuous_on`, and `continuous`.
-/
lemma tendsto_inv₀ {x : G₀} (hx : x ≠ 0) : tendsto has_inv.inv (𝓝 x) (𝓝 x⁻¹) :=
continuous_at_inv₀ hx
lemma continuous_on_inv₀ : continuous_on (has_inv.inv : G₀ → G₀) {0}ᶜ :=
λ x hx, (continuous_at_inv₀ hx).continuous_within_at
/-- If a function converges to a nonzero value, its inverse converges to the inverse of this value.
We use the name `tendsto.inv₀` as `tendsto.inv` is already used in multiplicative topological
groups. -/
lemma filter.tendsto.inv₀ {a : G₀} (hf : tendsto f l (𝓝 a))
(ha : a ≠ 0) :
tendsto (λ x, (f x)⁻¹) l (𝓝 a⁻¹) :=
(tendsto_inv₀ ha).comp hf
variables [topological_space α]
lemma continuous_within_at.inv₀ (hf : continuous_within_at f s a) (ha : f a ≠ 0) :
continuous_within_at (λ x, (f x)⁻¹) s a :=
hf.inv₀ ha
lemma continuous_at.inv₀ (hf : continuous_at f a) (ha : f a ≠ 0) :
continuous_at (λ x, (f x)⁻¹) a :=
hf.inv₀ ha
@[continuity] lemma continuous.inv₀ (hf : continuous f) (h0 : ∀ x, f x ≠ 0) :
continuous (λ x, (f x)⁻¹) :=
continuous_iff_continuous_at.2 $ λ x, (hf.tendsto x).inv₀ (h0 x)
lemma continuous_on.inv₀ (hf : continuous_on f s) (h0 : ∀ x ∈ s, f x ≠ 0) :
continuous_on (λ x, (f x)⁻¹) s :=
λ x hx, (hf x hx).inv₀ (h0 x hx)
end inv₀
/-!
### Continuity of division
If `G₀` is a `group_with_zero` with `x ↦ x⁻¹` continuous at all nonzero points and `(*)`, then
division `(/)` is continuous at any point where the denominator is continuous.
-/
section div
variables [group_with_zero G₀] [topological_space G₀] [has_continuous_inv₀ G₀]
[has_continuous_mul G₀] {f g : α → G₀}
lemma filter.tendsto.div {l : filter α} {a b : G₀} (hf : tendsto f l (𝓝 a))
(hg : tendsto g l (𝓝 b)) (hy : b ≠ 0) :
tendsto (f / g) l (𝓝 (a / b)) :=
by simpa only [div_eq_mul_inv] using hf.mul (hg.inv₀ hy)
variables [topological_space α] [topological_space β] {s : set α} {a : α}
lemma continuous_within_at.div (hf : continuous_within_at f s a) (hg : continuous_within_at g s a)
(h₀ : g a ≠ 0) :
continuous_within_at (f / g) s a :=
hf.div hg h₀
lemma continuous_on.div (hf : continuous_on f s) (hg : continuous_on g s) (h₀ : ∀ x ∈ s, g x ≠ 0) :
continuous_on (f / g) s :=
λ x hx, (hf x hx).div (hg x hx) (h₀ x hx)
/-- Continuity at a point of the result of dividing two functions continuous at that point, where
the denominator is nonzero. -/
lemma continuous_at.div (hf : continuous_at f a) (hg : continuous_at g a) (h₀ : g a ≠ 0) :
continuous_at (f / g) a :=
hf.div hg h₀
@[continuity] lemma continuous.div (hf : continuous f) (hg : continuous g) (h₀ : ∀ x, g x ≠ 0) :
continuous (f / g) :=
by simpa only [div_eq_mul_inv] using hf.mul (hg.inv₀ h₀)
lemma continuous_on_div : continuous_on (λ p : G₀ × G₀, p.1 / p.2) {p | p.2 ≠ 0} :=
continuous_on_fst.div continuous_on_snd $ λ _, id
/-- The function `f x / g x` is discontinuous when `g x = 0`.
However, under appropriate conditions, `h x (f x / g x)` is still continuous.
The condition is that if `g a = 0` then `h x y` must tend to `h a 0` when `x` tends to `a`,
with no information about `y`. This is represented by the `⊤` filter.
Note: `filter.tendsto_prod_top_iff` characterizes this convergence in uniform spaces.
See also `filter.prod_top` and `filter.mem_prod_top`. -/
lemma continuous_at.comp_div_cases {f g : α → G₀} (h : α → G₀ → β)
(hf : continuous_at f a) (hg : continuous_at g a)
(hh : g a ≠ 0 → continuous_at ↿h (a, f a / g a))
(h2h : g a = 0 → tendsto ↿h (𝓝 a ×ᶠ ⊤) (𝓝 (h a 0))) :
continuous_at (λ x, h x (f x / g x)) a :=
begin
show continuous_at (↿h ∘ (λ x, (x, f x / g x))) a,
by_cases hga : g a = 0,
{ rw [continuous_at], simp_rw [comp_app, hga, div_zero],
exact (h2h hga).comp (continuous_at_id.prod_mk tendsto_top) },
{ exact continuous_at.comp (hh hga) (continuous_at_id.prod (hf.div hg hga)) }
end
/-- `h x (f x / g x)` is continuous under certain conditions, even if the denominator is sometimes
`0`. See docstring of `continuous_at.comp_div_cases`. -/
lemma continuous.comp_div_cases {f g : α → G₀} (h : α → G₀ → β)
(hf : continuous f) (hg : continuous g)
(hh : ∀ a, g a ≠ 0 → continuous_at ↿h (a, f a / g a))
(h2h : ∀ a, g a = 0 → tendsto ↿h (𝓝 a ×ᶠ ⊤) (𝓝 (h a 0))) :
continuous (λ x, h x (f x / g x)) :=
continuous_iff_continuous_at.mpr $
λ a, hf.continuous_at.comp_div_cases _ hg.continuous_at (hh a) (h2h a)
end div
/-! ### Left and right multiplication as homeomorphisms -/
namespace homeomorph
variables [topological_space α] [group_with_zero α] [has_continuous_mul α]
/-- Left multiplication by a nonzero element in a `group_with_zero` with continuous multiplication
is a homeomorphism of the underlying type. -/
protected def mul_left₀ (c : α) (hc : c ≠ 0) : α ≃ₜ α :=
{ continuous_to_fun := continuous_mul_left _,
continuous_inv_fun := continuous_mul_left _,
.. equiv.mul_left₀ c hc }
/-- Right multiplication by a nonzero element in a `group_with_zero` with continuous multiplication
is a homeomorphism of the underlying type. -/
protected def mul_right₀ (c : α) (hc : c ≠ 0) : α ≃ₜ α :=
{ continuous_to_fun := continuous_mul_right _,
continuous_inv_fun := continuous_mul_right _,
.. equiv.mul_right₀ c hc }
@[simp] lemma coe_mul_left₀ (c : α) (hc : c ≠ 0) : ⇑(homeomorph.mul_left₀ c hc) = (*) c := rfl
@[simp] lemma mul_left₀_symm_apply (c : α) (hc : c ≠ 0) :
((homeomorph.mul_left₀ c hc).symm : α → α) = (*) c⁻¹ := rfl
@[simp] lemma coe_mul_right₀ (c : α) (hc : c ≠ 0) :
⇑(homeomorph.mul_right₀ c hc) = λ x, x * c := rfl
@[simp] lemma mul_right₀_symm_apply (c : α) (hc : c ≠ 0) :
((homeomorph.mul_right₀ c hc).symm : α → α) = λ x, x * c⁻¹ := rfl
end homeomorph
section zpow
variables [group_with_zero G₀] [topological_space G₀] [has_continuous_inv₀ G₀]
[has_continuous_mul G₀]
lemma continuous_at_zpow₀ (x : G₀) (m : ℤ) (h : x ≠ 0 ∨ 0 ≤ m) : continuous_at (λ x, x ^ m) x :=
begin
cases m,
{ simpa only [zpow_of_nat] using continuous_at_pow x m },
{ simp only [zpow_neg_succ_of_nat],
have hx : x ≠ 0, from h.resolve_right (int.neg_succ_of_nat_lt_zero m).not_le,
exact (continuous_at_pow x (m + 1)).inv₀ (pow_ne_zero _ hx) }
end
lemma continuous_on_zpow₀ (m : ℤ) : continuous_on (λ x : G₀, x ^ m) {0}ᶜ :=
λ x hx, (continuous_at_zpow₀ _ _ (or.inl hx)).continuous_within_at
lemma filter.tendsto.zpow₀ {f : α → G₀} {l : filter α} {a : G₀} (hf : tendsto f l (𝓝 a)) (m : ℤ)
(h : a ≠ 0 ∨ 0 ≤ m) :
tendsto (λ x, (f x) ^ m) l (𝓝 (a ^ m)) :=
(continuous_at_zpow₀ _ m h).tendsto.comp hf
variables {X : Type*} [topological_space X] {a : X} {s : set X} {f : X → G₀}
lemma continuous_at.zpow₀ (hf : continuous_at f a) (m : ℤ) (h : f a ≠ 0 ∨ 0 ≤ m) :
continuous_at (λ x, (f x) ^ m) a :=
hf.zpow₀ m h
lemma continuous_within_at.zpow₀ (hf : continuous_within_at f s a) (m : ℤ) (h : f a ≠ 0 ∨ 0 ≤ m) :
continuous_within_at (λ x, f x ^ m) s a :=
hf.zpow₀ m h
lemma continuous_on.zpow₀ (hf : continuous_on f s) (m : ℤ) (h : ∀ a ∈ s, f a ≠ 0 ∨ 0 ≤ m) :
continuous_on (λ x, f x ^ m) s :=
λ a ha, (hf a ha).zpow₀ m (h a ha)
@[continuity] lemma continuous.zpow₀ (hf : continuous f) (m : ℤ) (h0 : ∀ a, f a ≠ 0 ∨ 0 ≤ m) :
continuous (λ x, (f x) ^ m) :=
continuous_iff_continuous_at.2 $ λ x, (hf.tendsto x).zpow₀ m (h0 x)
end zpow
|
69d27bd6d87818027a99391b84927df401663718 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/data/rat/denumerable.lean | 8206b36ee0828cf6747420c9fe6085504d0ba80e | [
"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 | 1,227 | lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import data.rat
import set_theory.cardinal
/-!
# Denumerability of ℚ
This file proves that ℚ is infinite, denumerable, and deduces that it has cardinality `omega`.
-/
namespace rat
open denumerable
instance : infinite ℚ :=
infinite.of_injective (coe : ℕ → ℚ) nat.cast_injective
private def denumerable_aux : ℚ ≃ { x : ℤ × ℕ // 0 < x.2 ∧ x.1.nat_abs.coprime x.2 } :=
{ to_fun := λ x, ⟨⟨x.1, x.2⟩, x.3, x.4⟩,
inv_fun := λ x, ⟨x.1.1, x.1.2, x.2.1, x.2.2⟩,
left_inv := λ ⟨_, _, _, _⟩, rfl,
right_inv := λ ⟨⟨_, _⟩, _, _⟩, rfl }
/-- **Denumerability of the Rational Numbers** -/
instance : denumerable ℚ :=
begin
let T := { x : ℤ × ℕ // 0 < x.2 ∧ x.1.nat_abs.coprime x.2 },
letI : infinite T := infinite.of_injective _ denumerable_aux.injective,
letI : encodable T := encodable.subtype,
letI : denumerable T := of_encodable_of_infinite T,
exact denumerable.of_equiv T denumerable_aux
end
end rat
namespace cardinal
open_locale cardinal
lemma mk_rat : #ℚ = ω := mk_denumerable ℚ
end cardinal
|
955022224887ad8521bc99f7348ae336beb44bd8 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/algebra/ring/ulift.lean | ef4f598050dadfa847cce6535d0a0a538620bca9 | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 3,178 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import algebra.group.ulift
import data.equiv.ring
/-!
# `ulift` instances for ring
This file defines instances for ring, semiring and related structures on `ulift` types.
(Recall `ulift α` is just a "copy" of a type `α` in a higher universe.)
We also provide `ulift.ring_equiv : ulift R ≃+* R`.
-/
universes u v
variables {α : Type u} {x y : ulift.{v} α}
namespace ulift
instance mul_zero_class [mul_zero_class α] : mul_zero_class (ulift α) :=
by refine_struct { zero := (0 : ulift α), mul := (*), .. }; tactic.pi_instance_derive_field
instance distrib [distrib α] : distrib (ulift α) :=
by refine_struct { add := (+), mul := (*), .. }; tactic.pi_instance_derive_field
instance non_unital_non_assoc_semiring [non_unital_non_assoc_semiring α] :
non_unital_non_assoc_semiring (ulift α) :=
by refine_struct { zero := (0 : ulift α), add := (+), mul := (*),
nsmul := add_monoid.nsmul, };
tactic.pi_instance_derive_field
instance non_assoc_semiring [non_assoc_semiring α] : non_assoc_semiring (ulift α) :=
by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*),
nsmul := add_monoid.nsmul };
tactic.pi_instance_derive_field
instance non_unital_semiring [non_unital_semiring α] : non_unital_semiring (ulift α) :=
by refine_struct { zero := (0 : ulift α), add := (+), mul := (*),
nsmul := add_monoid.nsmul, };
tactic.pi_instance_derive_field
instance semiring [semiring α] : semiring (ulift α) :=
by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*),
nsmul := add_monoid.nsmul, npow := monoid.npow };
tactic.pi_instance_derive_field
/--
The ring equivalence between `ulift α` and `α`.
-/
def ring_equiv [non_unital_non_assoc_semiring α] : ulift α ≃+* α :=
{ to_fun := ulift.down,
inv_fun := ulift.up,
map_mul' := λ x y, rfl,
map_add' := λ x y, rfl,
left_inv := by tidy,
right_inv := by tidy, }
instance comm_semiring [comm_semiring α] : comm_semiring (ulift α) :=
by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*),
nsmul := add_monoid.nsmul, npow := monoid.npow };
tactic.pi_instance_derive_field
instance non_unital_non_assoc_ring [non_unital_non_assoc_ring α] :
non_unital_non_assoc_ring (ulift α) :=
by refine_struct { zero := (0 : ulift α), add := (+), mul := (*), sub := has_sub.sub,
neg := has_neg.neg, nsmul := add_monoid.nsmul, zsmul := sub_neg_monoid.zsmul };
tactic.pi_instance_derive_field
instance ring [ring α] : ring (ulift α) :=
by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), sub := has_sub.sub,
neg := has_neg.neg, nsmul := add_monoid.nsmul, npow := monoid.npow,
zsmul := sub_neg_monoid.zsmul };
tactic.pi_instance_derive_field
instance comm_ring [comm_ring α] : comm_ring (ulift α) :=
by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), sub := has_sub.sub,
neg := has_neg.neg, nsmul := add_monoid.nsmul, npow := monoid.npow,
zsmul := sub_neg_monoid.zsmul };
tactic.pi_instance_derive_field
end ulift
|
5d935b5d4eaa08aa1cd741b36fc472a4fdeeb3be | 874a8d2247ab9a4516052498f80da2e32d0e3a48 | /fermat.lean | f320514cf5bc085b030a360314090c288bd03957 | [] | no_license | AlexKontorovich/Spring2020Math492 | 378b36c643ee029f5ab91c1677889baa591f5e85 | 659108c5d864ff5c75b9b3b13b847aa5cff4348a | refs/heads/master | 1,610,780,595,457 | 1,588,174,859,000 | 1,588,174,859,000 | 243,017,788 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 28,745 | lean | -- Presentation aimed for March 4, 2020
-- (prime p = 4k+1 is sum of two squares)
-- Must arrive at 10:00, MIT Lab on that day.
-- https://github.com/leanprover-community/mathlib/blob/master/docs/install/windows.md
import tactic
import algebra.group_power
import data.int.basic
--import data.zmod.quadratic_reciprocity
universe u
local attribute [instance] classical.prop_decidable
def ex1 (x y z : ℕ) : ℕ := x + y * z
def even (n : ℕ) : Prop := ∃ k, n = 2*k
def odd (n : ℕ) : Prop := ∃ k, n = 2*k+1
lemma even_or_odd (n : ℕ) : or (even n) (odd n) :=
begin
induction n with d hd,
left,
rw even,
use 0,
simp,
cases hd with p q,
rw even at p,
cases p with k p,
right,
rw odd,
use k,
rw p,
rw odd at q,
cases q with k q,
left,
rw even,
use k+1,
rw mul_add,
rw q,
refl,
end
lemma not_both_even_odd (n : ℕ) : ¬((even n) ∧ (odd n)) :=
begin
by_cases h : (even n) ∧ (odd n),
exfalso,
cases h with h1 h2,
rw even at h1,
cases h1 with k h1k,
rw odd at h2,
cases h2 with k' h2k,
rw h1k at h2k,
have hk := nat.mul_mod_right 2 k,
rw h2k at hk,
rw add_comm at hk,
have hk1 := nat.add_mul_mod_self_left 1 2 k',
have one_lt_two : 1 < 2 := by {exact nat.lt_succ_self 1},
have one_mod_two_is_one := nat.mod_eq_of_lt one_lt_two,
rw one_mod_two_is_one at hk1,
rw hk at hk1,
have zero_lt_one : 0 < 1 := by exact nat.lt_succ_self 0,
rw hk1 at zero_lt_one,
exact lt_irrefl 1 zero_lt_one,
exact h,
end
lemma even_plus_even_is_even (n m : ℕ) (h : and (even n) (even m)) : even (n+m) :=
begin
cases h with p q,
rw even at p,
cases p with k p,
rw even at q,
cases q with l q,
rw even,
use k+l,
rw mul_add,
rw p,
rw q,
end
lemma even_plus_odd_is_odd (n m : ℕ) (h : and (even n) (odd m)) : odd (n+m) :=
begin
cases h with p q,
rw even at p,
cases p with k p,
rw odd at q,
cases q with l q,
rw odd,
use k+l,
rw mul_add,
rw p,
rw q,
ring,
end
lemma odd_plus_even_is_odd (n m : ℕ) (h : and (odd n) (even m)) : odd (n+m) :=
begin
rw and_comm at h,
rw add_comm,
apply even_plus_odd_is_odd,
exact h,
end
lemma odd_plus_odd_is_even (n m : ℕ) (h : and (odd n) (odd m)) : even (n+m) :=
begin
cases h with p q,
rw odd at p,
cases p with k p,
rw odd at q,
cases q with l q,
rw even,
use k+l+1,
rw p,
rw q,
rw mul_add,
rw mul_add,
ring,
end
lemma even_minus_even_is_even (n m : ℕ) (h : (even n) ∧ (even m) ∧ (m ≤ n))
: even (n - m) :=
begin
cases h with h1 h2,
cases h2 with h3 h4,
have deo := even_or_odd (n-m),
cases deo with deven dodd,
exact deven,
exfalso,
have sum := odd_plus_even_is_odd (n-m) m ⟨dodd, h3⟩,
have claim : n - m + m = n,
have summ := nat.le.dest h4,
cases summ with smd summ',
rw add_comm at summ',
rw (eq.symm summ'),
rw nat.add_sub_cancel,
rw claim at sum,
exact not_both_even_odd n ⟨h1, sum⟩,
end
lemma odd_minus_odd_is_even (n m : ℕ) (h : (odd n) ∧ (odd m) ∧ (m ≤ n))
: even (n - m) :=
begin
cases h with h1 h2,
cases h2 with h3 h4,
have deo := even_or_odd (n-m),
cases deo with deven dodd,
exact deven,
exfalso,
have sum := odd_plus_odd_is_even (n-m) m ⟨dodd, h3⟩,
have claim : n - m + m = n,
have summ := nat.le.dest h4,
cases summ with smd summ',
rw add_comm at summ',
rw (eq.symm summ'),
rw nat.add_sub_cancel,
rw claim at sum,
exact not_both_even_odd n ⟨sum, h1⟩,
end
lemma even_times_nat_is_even (n m : ℕ) (h : even n) : even (n*m) :=
begin
rw even,
rw even at h,
cases h with p kp,
use m*p,
rw kp,
ring,
end
lemma nat_times_even_is_even (n m : ℕ) (h : even m) : even (n*m) :=
begin
rw mul_comm,
apply even_times_nat_is_even,
exact h,
end
lemma odd_times_odd_is_odd (n m : ℕ) (h : and (odd n) (odd m)) : odd (n*m) :=
begin
rw odd,
cases h with h1 h2,
rw odd at h1,
cases h1 with p kp,
rw odd at h2,
cases h2 with q kq,
use 2*p*q + p + q,
rw kp,
rw kq,
ring,
end
lemma even_square_is_even (n : ℕ) (h : even n) : even (n^2) :=
begin
rw nat.pow_two,
exact nat_times_even_is_even n n h,
end
lemma odd_square_is_odd (n : ℕ) (h : odd n) : odd (n^2) :=
begin
rw nat.pow_two,
exact odd_times_odd_is_odd n n ⟨h, h⟩,
end
lemma not_and_eq_or_not (p q : Prop) : ¬(p ∧ q) ↔ ¬p ∨ ¬q :=
begin
split,
intro f,
by_cases hp : p,
{ by_cases hq : q,
{ exact (f ⟨hp, hq⟩).elim, },
exact or.inr hq, },
{ exact or.inl hp, },
intro g,
cases g with g1 g2,
by_cases h : p ∧ q,
exfalso,
cases h with h1 h2,
exact g1(h1),
exact h,
by_cases h : p ∧ q,
exfalso,
cases h with h1 h2,
exact g2(h2),
exact h,
end
lemma not_or_eq_and_not (p q : Prop) : ¬(p ∨ q) ↔ ¬p ∧ ¬q :=
begin
split,
intro f,
by_cases hp : p,
have i := or.intro_left q hp,
exfalso,
exact f(i),
by_cases hq : q,
have i := or.intro_right p hq,
exfalso,
exact f(i),
exact ⟨hp, hq⟩,
intro f,
cases f with f1 f2,
by_cases h : p ∨ q,
cases h with h1 h2,
exfalso,
exact f1(h1),
exfalso,
exact f2(h2),
exact h,
end
lemma pos_or_zero (n : ℕ) : 0 < n ∨ n = 0 :=
begin
have tri := lt_trichotomy 0 n,
cases tri with tri1 tri2,
left,
exact tri1,
cases tri2 with tri3 tri4,
right,
exact (eq.symm tri3),
exfalso,
have nng := zero_le n,
have lt1 := lt_of_le_of_lt nng tri4,
exact lt_irrefl 0 lt1,
end
lemma mul_cancel (a b c : ℕ) (h : a*b = a*c) (p : 0 < a) : b = c :=
begin
have ltr := lt_trichotomy b c,
cases ltr with ltr' ltr1,
exfalso,
have thing := mul_lt_mul_of_pos_left ltr' p,
rw h at thing,
exact lt_irrefl (a*c) thing,
cases ltr1 with ltr2 ltr3,
exact ltr2,
exfalso,
have thing := mul_lt_mul_of_pos_left ltr3 p,
rw h at thing,
exact lt_irrefl (a*c) thing,
end
lemma int_mul_cancel (a b c : ℤ) (h : a*b = a*c) (p : 0 < a) : b = c :=
begin
have ltr := lt_trichotomy b c,
cases ltr with ltr' ltr1,
exfalso,
have thing := mul_lt_mul_of_pos_left ltr' p,
rw h at thing,
exact lt_irrefl (a*c) thing,
cases ltr1 with ltr2 ltr3,
exact ltr2,
exfalso,
have thing := mul_lt_mul_of_pos_left ltr3 p,
rw h at thing,
exact lt_irrefl (a*c) thing,
end
lemma int_mul_cancel_lt (a b c : ℤ) (h : a*b < a*c) (p : 0 < a) : b < c :=
begin
have ltr := lt_trichotomy b c,
cases ltr with ltr' ltr1,
exact ltr',
exfalso,
cases ltr1 with ltr2 ltr3,
rw ltr2 at h,
exact lt_irrefl (a*c) h,
have th := mul_lt_mul_of_pos_left ltr3 p,
exact lt_irrefl (a*b) (lt_trans h th),
end
-- I imagine that those will be important. Now for the real deal.
def divides (n m : ℕ) : Prop := ∃ k, n*k = m
def prime' (p : ℕ) : Prop := 1 < p ∧ (∀ k, (divides k p → (k = 1 ∨ k = p)))
lemma square_eq_times_itself (a : ℤ) : a^2 = a*a :=
begin
rw pow_succ,
rw pow_succ,
rw pow_zero,
rw mul_one,
end
lemma square_eq_sq_of_nat (a : ℤ) : ∃(n:ℕ),(a^2=(n:ℤ)^2) :=
begin
have ltr := lt_trichotomy 0 a,
cases ltr with ltr1 ltr',
have thing := int.eq_coe_of_zero_le (le_of_lt ltr1),
cases thing with n th',
use n,
rw th',
cases ltr' with ltr2 ltr3,
use 0,
rw (eq.symm ltr2),
ring,
have th := int.add_lt_add_left ltr3 (-a),
rw add_zero at th,
have fill_in_hole : -a+a=0 := by ring,
rw fill_in_hole at th,
have thing := int.eq_coe_of_zero_le (le_of_lt th),
cases thing with n th',
use n,
rw (eq.symm th'),
ring,
end
lemma nonzero_square_pos (a : ℤ) (h : 0 ≠ a) : 0 < a^2 :=
begin
by_cases p : 0 < a,
rw square_eq_times_itself,
rw [←( int.mul_zero a)],
exact mul_lt_mul_of_pos_left p p,
have q := lt_trichotomy 0 a,
cases q,
exfalso,
apply p,
exact q,
cases q,
exfalso,
apply h,
exact q,
rw square_eq_times_itself,
rw [←( int.mul_zero a)],
exact mul_lt_mul_of_neg_left q q,
end
lemma square_nonneg (a : ℤ) : 0 <= a^2 :=
begin
by_cases p : a = 0,
rw p,
refl,
apply le_of_lt,
apply nonzero_square_pos,
by_cases q : 0 = a,
have r := eq.symm q,
exfalso,
apply p,
exact r,
exact q,
end
lemma LCex (a p : ℕ) (hp : 0 < p) :
∃(d:ℕ), 0 < d ∧ (∃(x:ℤ), (∃(y:ℤ), (x*a + y*p = d))) :=
begin
use (a*↑a+p*↑p),
split,
have q := square_nonneg(↑a),
rw square_eq_times_itself at q,
have s := nonzero_square_pos(↑p),
norm_cast,
rw square_eq_times_itself at s,
norm_cast at s,
norm_cast at q,
by_cases pz : 0 = p,
rw pz at hp,
have ir := gt_irrefl p,
exfalso,
apply ir,
exact hp,
have r1 := s(pz),
have ala := add_lt_add_left r1 (a*a),
rw add_zero at ala,
exact lt_of_le_of_lt q ala,
norm_cast,
use a,
use p,
norm_cast,
end
lemma div_alg (a b : ℕ) (hp : 0 < b) : ∃(r q : ℕ), (a = b*q+r ∧ r < b) :=
begin
induction a with d hd,
use 0,
use 0,
split,
ring,
exact hp,
cases hd with r rh,
cases rh with q qh,
cases qh with qh1 qh2,
by_cases p : nat.succ r = b,
use 0,
use q+1,
rw qh1,
split,
have p1 := eq.symm p,
rw p1,
ring,
exact hp,
have qh3 := nat.succ_le_of_lt qh2,
have tri := lt_trichotomy (nat.succ r) b,
cases tri with tri1 tri2,
use nat.succ r,
use q,rw qh1,
rw nat.add_succ,
split,
refl,
exact tri1,
cases tri2 with tri3 tri4,
exfalso,
apply p,
exact tri3,
exfalso,
have i := nat.lt_of_le_of_lt qh3 tri4,
have ir := lt_irrefl (nat.succ r),
apply ir,
exact i,
end
lemma div_alg_near_zero (a b : ℕ) (b_pos : 0 < b) (ho : odd b) :
∃(q:ℤ), ∃(r:ℤ), ((a:ℤ) = b*q+r ∧ 2*r < b ∧ -2*r < b) :=
begin
have div := div_alg a b b_pos,
cases div with r divr,
cases divr with q divq,
have tri := lt_trichotomy (2*r) b,
cases tri with tri1 tri2,
use q,
use r,
cases divq with divq1 divq2,
split,
norm_cast,
exact divq1,
split,
norm_cast,
exact tri1,
have claim : (-2:ℤ)*r ≤ 0,
have thing := zero_le (2*r),
have thing2 : (0 ≤ 2 * (r : ℤ)) :=
by { norm_cast, exact thing },
have st := add_le_add_left thing2 ((-2:ℤ)*r),
rw add_zero at st,
have claim1 : (-2:ℤ) * ↑r + 2 * ↑r = 0 := by ring,
rw claim1 at st,
exact st,
have b_pos_int : (0 < (b:ℤ)) := by {norm_cast, exact b_pos},
exact lt_of_le_of_lt claim b_pos_int,
cases tri2 with tri3 tri4,
exfalso,
have claim : even b := by {rw even, use r, exact (eq.symm tri3)},
have not_both := not_both_even_odd b,
exact not_both ⟨claim, ho⟩,
use q+1,
use r-b,
cases divq with divq1 divq2,
split,
rw divq1,
push_cast,
ring,
split,
have claim : 0 < (b:ℤ) := by {norm_cast, exact b_pos},
have claim2 : (r:ℤ) < (b:ℤ) := by {norm_cast, exact divq2},
have st := add_lt_add_left claim2 (-b:ℤ),
have claim3 : -(b:ℤ) + (r:ℤ) = (r:ℤ) - (b:ℤ) := by {ring},
rw claim3 at st,
have fillinhole : -(b:ℤ) + (b:ℤ) = 0 := by {ring},
rw fillinhole at st,
have st' := mul_lt_mul_of_pos_left st (lt_trans zero_lt_one one_lt_two),
rw mul_zero at st',
exact (lt_trans st' claim),
have claim : (b:ℤ) < 2*(r:ℤ) := by {norm_cast, exact tri4},
have st := add_lt_add_left claim (b - 2*(r:ℤ)),
have claim2 : (b:ℤ) - 2*(r:ℤ) + b = (-(2:ℤ))*(r-(b:ℤ)) := by {ring},
rw claim2 at st,
have claim3 : (b:ℤ) - 2*(r:ℤ) + 2*r = b := by {ring},
rw claim3 at st,
exact st,
end
lemma abs_thing (a b : ℤ) (h1 : a < b) (h2 : -a < b) : a^2 < b^2 :=
begin
have h1' := add_lt_add_right h1 (-a),
have f1 : a + (-a) = 0 := by ring,
rw f1 at h1',
have h2' := add_lt_add_right h2 a,
have f2 : (-a) + a = 0 := by ring,
rw f2 at h2',
have thing : 0 < (b+a)*(b+(-a)) := by {exact mul_pos' h2' h1'},
have soandso : (b+a)*(b+(-a)) = b^2-a^2 := by ring,
rw soandso at thing,
have res := add_lt_add_right thing (a^2),
rw zero_add at res,
have th' : b^2-a^2+a^2 = b^2 := by ring,
rw th' at res,
exact res,
end
def isLC (a p d : ℕ) : Prop := 0 < d ∧ (∃(x:ℤ), (∃(y:ℤ), (x*a + y*p = d)))
-- The following lemmas show that the *smallest* positive integer linear
-- combination of a and b is a common divisor of a and b.
lemma bezout (a b d : ℕ) (h_pos : 0 < d)
(h1 : ∃(x:ℤ), (∃(y:ℤ), (x*a + y*b = d)))
(h2 : ∀(d':ℕ), (0 < d' ∧ ∃(x:ℤ), (∃(y:ℤ), (x*a + y*b = d'))) → d ≤ d') :
divides d a :=
begin
have r1 := div_alg a d h_pos,
cases r1 with r hr,
cases hr with q hq,
cases hq with hq1 hq2,
have htr := pos_or_zero r,
cases htr with htr1 htr2,
exfalso,
have claim1 : (a:ℤ)-d*q = r,
rw hq1,
push_cast,
ring,
cases h1 with x_ex hx,
cases hx with y_ex hy,
have claim2 : (1-x_ex*q)*a + (-y_ex*q)*b = r,
rw (eq.symm claim1),
rw (eq.symm hy),
ring,
have thing := h2(r),
have EG : ∃ (x y : ℤ), x * ↑a + y * ↑b = ↑r,
use (1 - x_ex * q),
use (-y_ex * q),
exact claim2,
have concl := thing(⟨htr1, EG⟩),
have ir1 := lt_of_le_of_lt concl hq2,
have ir2 := lt_irrefl d,
exact ir2(ir1),
rw htr2 at hq1,
rw add_zero at hq1,
rw divides,
use q,
rw hq1,
end
-- The above shows that d divides a.
-- Now we apply it to show d divides both of them, without
-- rewriting the entire argument.
lemma bezout_doub (a b d : ℕ) (h_pos : 0 < d)
(h1 : ∃(x:ℤ), (∃(y:ℤ), (x*a + y*b = d)))
(h2 : ∀(d':ℕ), (0 < d' ∧ ∃(x:ℤ), (∃(y:ℤ), (x*a + y*b = d'))) → d ≤ d') :
divides d a ∧ divides d b :=
begin
split,
exact bezout a b d h_pos h1 h2,
have h1_swap : ∃ (x y : ℤ), x * b + y * a = d,
cases h1 with xex h1a,
cases h1a with yex h1b,
use yex,
use xex,
rw (eq.symm h1b),
rw add_comm,
have h2_swap : ∀ (d' : ℕ), (0 < d' ∧ ∃ (x y : ℤ), x * b + y * a = d') → d ≤ d',
intro d',
intro f,
cases f with f1 f2,
have f2_swap : ∃ (x y : ℤ), x * a + y * b = d',
cases f2 with xex f2a,
cases f2a with yex f2b,
use yex,
use xex,
rw (eq.symm f2b),
rw add_comm,
have thing := h2(d'),
exact thing(⟨f1, f2_swap⟩),
exact bezout b a d h_pos h1_swap h2_swap,
end
lemma bezout1 (a p : ℕ) (hp : prime' p) (ha : ¬(divides p a)) :
∃(x:ℤ), (∃(y:ℤ), (x*a + y*p = 1)) :=
begin
rw prime' at hp,
cases hp with hp1 hp2,
have zero_lt_one := nat.lt_succ_self 0,
have p_pos := lt_trans zero_lt_one hp1,
have dh : ∃ (d : ℕ), 0 < d ∧ ∃ (x y : ℤ), x * ↑a + y * ↑p = ↑d := LCex a p p_pos,
let d := nat.find(dh),
have dx : 0 < d ∧ ∃ (x y : ℤ), x * ↑a + y * ↑p = ↑d := nat.find_spec dh,
have dm : ∀ d', (0 < d' ∧ ∃ (x y : ℤ), x * ↑a + y * ↑p = ↑d') → d ≤ d' := λ d', nat.find_min' dh,
cases dx with d_pos dx2,
have dividing := bezout_doub a p d d_pos dx2 dm,
cases dividing with div1 div2,
have concl := hp2(d)(div2),
cases concl with c1 c2,
cases dx2 with xex dx3,
cases dx3 with yex dx4,
use xex,
use yex,
rw c1 at dx4,
norm_cast at dx4,
exact dx4,
exfalso,
rw c2 at div1,
exact ha(div1),
end
lemma neg_one_is_square (p : ℕ) (hp : prime' p) (hm : divides 4 (p-1)) :
∃ x, (0 < x ∧ x < p ∧ divides p (x^2+1)) :=
begin
sorry -- when I tried to import quadratic_reciprocity, memory was overloaded
end
lemma nat_square_sep (a b : ℕ) (a_pos : 0 < a) (bound : a < b) : a^2 + 1 < b^2 :=
begin
have b_pos := lt_trans a_pos bound,
have st1 := nat.mul_lt_mul_of_pos_right bound b_pos,
have st2 := nat.mul_lt_mul_of_pos_left bound a_pos,
have st2' := nat.succ_le_of_lt st2,
have res := lt_of_le_of_lt st2' st1,
rw nat.pow_two,
rw nat.pow_two,
exact res,
end
theorem mult_sum_of_two_squares (p : ℕ) (hp : prime' p) (hm : divides 4 (p-1)) :
∃ m, (0 < m ∧ m < p ∧ ∃ x, ∃ y, m*p = x^2+y^2) :=
begin
have q := neg_one_is_square p hp hm,
cases q with a ka,
rw divides at ka,
cases ka with a_pos ka1,
cases ka1 with a_bound ka2,
cases ka2 with n kb,
use n,
split,
have zero_lt_one := nat.lt_succ_self 0,
have posmul := nat.mul_lt_mul_of_pos_left a_pos a_pos,
rw mul_zero at posmul,
have summing := add_lt_add_right posmul 1,
rw zero_add at summing,
have res := lt_trans zero_lt_one summing,
rw nat.pow_two at kb,
rw (eq.symm kb) at res,
have n_pos_zero := pos_or_zero n,
cases n_pos_zero with n_pos n_zero,
exact n_pos,
exfalso,
rw n_zero at res,
rw mul_zero at res,
exact lt_irrefl 0 res,
split,
have st := nat_square_sep a p a_pos a_bound,
rw (eq.symm kb) at st,
rw nat.pow_two at st,
have tri := lt_trichotomy p n,
cases tri with tri1 tri2,
exfalso,
have tri1a := nat.mul_lt_mul_of_pos_left tri1 (lt.trans a_pos a_bound),
have tri1b := lt.trans st tri1a,
exact lt_irrefl (p*n) tri1b,
cases tri2 with tri3 tri4,
exfalso,
rw tri3 at st,
exact lt_irrefl (n*n) st,
exact tri4,
use a,
use 1,
rw mul_comm,
rw kb,
ring,
end
lemma prelim (x y : ℕ) (h : x < y) :
2 * (x ^ 2 + y ^ 2) = (y + x) ^ 2 + (y - x) ^ 2 :=
begin
apply int.coe_nat_inj,
push_cast,
rw int.coe_nat_sub (le_of_lt h),
ring,
simp,
end
lemma halving_first (n x y : ℕ) (h : x < y) (h1 : 2*n = x^2 + y^2) :
∃a:ℕ, ∃b:ℕ, n = a^2 + b^2 :=
begin
have zero_lt_two := lt_trans (nat.lt_succ_self 0) (nat.lt_succ_self 1),
have xeo := even_or_odd x,
have yeo := even_or_odd y,
cases xeo with x_even x_odd,
cases yeo with y_even y_odd,
have sum_even := even_plus_even_is_even y x ⟨y_even, x_even⟩,
have diff_even := even_minus_even_is_even y x ⟨y_even, x_even, le_of_lt h⟩,
rw even at sum_even,
cases sum_even with sum' sum_ev,
rw even at diff_even,
cases diff_even with diff' diff_ev,
use sum',
use diff',
have claim : 2*n = 2*(sum'^2 + diff'^2),
rw h1,
have claim' : 2*(x^2+y^2) = 4*(sum'^2+diff'^2),
have thing : 4*(sum'^2+diff'^2) = (2*sum')^2+(2*diff')^2 := by ring,
rw thing,
rw (eq.symm sum_ev),
rw (eq.symm diff_ev),
exact prelim x y h,
have thing : 4*(sum'^2+diff'^2) = 2*(2*(sum'^2+diff'^2)) := by ring,
rw thing at claim',
exact mul_cancel 2 (x^2+y^2) (2*(sum'^2+diff'^2)) claim' zero_lt_two,
exact mul_cancel 2 n (sum'^2+diff'^2) claim zero_lt_two,
exfalso,
have xsq_even := even_times_nat_is_even x x x_even,
have ysq_odd := odd_times_odd_is_odd y y ⟨y_odd, y_odd⟩,
have sum_odd := even_plus_odd_is_odd (x*x) (y*y) ⟨xsq_even, ysq_odd⟩,
rw nat.pow_two at h1,
rw nat.pow_two at h1,
have claim : even (x*x+y*y) := by {rw even, use n, rw h1},
exact not_both_even_odd (x*x+y*y) ⟨claim, sum_odd⟩,
cases yeo with y_even y_odd,
exfalso,
have xsq_odd := odd_times_odd_is_odd x x ⟨x_odd, x_odd⟩,
have ysq_even := even_times_nat_is_even y y y_even,
have sum_odd := odd_plus_even_is_odd (x*x) (y*y) ⟨xsq_odd, ysq_even⟩,
rw nat.pow_two at h1,
rw nat.pow_two at h1,
have claim : even (x*x+y*y) := by {rw even, use n, rw h1},
exact not_both_even_odd (x*x+y*y) ⟨claim, sum_odd⟩,
have sum_even := odd_plus_odd_is_even y x ⟨y_odd, x_odd⟩,
have diff_even := odd_minus_odd_is_even y x ⟨y_odd, x_odd, le_of_lt h⟩,
rw even at sum_even,
cases sum_even with sum' sum_ev,
rw even at diff_even,
cases diff_even with diff' diff_ev,
use sum',
use diff',
have claim : 2*n = 2*(sum'^2 + diff'^2),
rw h1,
have claim' : 2*(x^2+y^2) = 4*(sum'^2+diff'^2),
have thing : 4*(sum'^2+diff'^2) = (2*sum')^2+(2*diff')^2 := by ring,
rw thing,
rw (eq.symm sum_ev),
rw (eq.symm diff_ev),
exact prelim x y h,
have thing : 4*(sum'^2+diff'^2) = 2*(2*(sum'^2+diff'^2)) := by ring,
rw thing at claim',
exact mul_cancel 2 (x^2+y^2) (2*(sum'^2+diff'^2)) claim' zero_lt_two,
exact mul_cancel 2 n (sum'^2+diff'^2) claim zero_lt_two,
end
-- halving just applies halving_first several times to rid the assumption
-- of the comparison on x and y.
lemma halving (n x y : ℕ) (h1 : 2*n = x^2 + y^2) :
∃a:ℕ, ∃b:ℕ, n = a^2 + b^2 :=
begin
have ltr := lt_trichotomy x y,
cases ltr with ltr' ltr1,
exact halving_first n x y ltr' h1,
cases ltr1 with ltr2 ltr3,
use x,
use 0,
rw (eq.symm ltr2) at h1,
have claim : x^2 + x^2 = 2*(x^2) := by ring,
rw claim at h1,
have zero_lt_two := lt_trans (nat.lt_succ_self 0) (nat.lt_succ_self 1),
have thing := mul_cancel 2 n (x^2) h1 zero_lt_two,
rw thing,
ring,
rw add_comm at h1,
exact halving_first n y x ltr3 h1,
end
lemma ineq's (n k : ℕ) (h1 : 0 < 2*n) (h2 : 2*n < k) :
0 < n ∧ n < k :=
begin
split,
have pz := pos_or_zero n,
cases pz with pz1 pz2,
exact pz1,
exfalso,
rw pz2 at h1,
rw mul_zero at h1,
exact lt_irrefl 0 h1,
have ltr := lt_trichotomy n k,
cases ltr with ltr' ltr1,
exact ltr',
exfalso,
cases ltr1 with ltr2 ltr3,
rw ltr2 at h2,
have claim : k ≤ 2*k,
have thing := add_le_add_left (zero_le k) k,
rw add_zero at thing,
have thing' : k + k = 2*k := by ring,
rw thing' at thing,
exact thing,
have thing := lt_of_le_of_lt claim h2,
exact lt_irrefl k thing,
have zero_lt_two : 0 < 2 := by {
exact lt_trans (nat.lt_succ_self 0) (nat.lt_succ_self 1)
},
have thing := mul_lt_mul_of_pos_left ltr3 zero_lt_two,
have h2' := lt_trans thing h2,
have claim : k ≤ 2*k,
have thing := add_le_add_left (zero_le k) k,
rw add_zero at thing,
have thing' : k + k = 2*k := by ring,
rw thing' at thing,
exact thing,
have thing := lt_of_le_of_lt claim h2',
exact lt_irrefl k thing,
end
theorem sum_of_two_squares (p : ℕ) (hp : prime' p) (hm : divides 4 (p-1)) :
∃ x, ∃ y, p = x^2+y^2 :=
begin
let m := nat.find(mult_sum_of_two_squares p hp hm),
have mx : 0 < m ∧ m < p ∧ ∃ x, ∃ y, m*p = x^2+y^2 := nat.find_spec(mult_sum_of_two_squares p hp hm),
have mm : ∀ m', (0 < m' ∧ m' < p ∧ ∃ x, ∃ y, m'*p = x^2+y^2) → m ≤ m' := λ d', nat.find_min'(mult_sum_of_two_squares p hp hm),
have meo := even_or_odd m,
cases mx with mx1 mx1',
cases mx1' with mx2 mx3,
cases meo with m_even m_odd,
exfalso,
rw even at m_even,
cases m_even with m' m_ev,
cases mx3 with xex mx3',
cases mx3' with yex mx4,
rw m_ev at mx4,
rw mul_assoc at mx4,
have half := halving (m'*p) xex yex mx4,
rw m_ev at mx1,
rw m_ev at mx2,
have ineqs := ineq's m' p mx1 mx2,
cases ineqs with ineq1 ineq2,
have fact := mm m' ⟨ineq1, ineq2, half⟩,
rw m_ev at fact,
have fact2 := add_lt_add_left ineq1 m',
rw add_zero at fact2,
have ir := lt_of_le_of_lt fact fact2,
have claim : m' + m' = 2 * m' := by ring,
rw claim at ir,
exact lt_irrefl (2*m') ir,
-- Now for the case that m is odd.
by_cases is_m_one : m = 1,
rw is_m_one at mx3,
cases mx3 with xex mx3',
cases mx3' with yex mx3'',
rw one_mul at mx3'',
use xex,
use yex,
exact mx3'',
-- Now for the case that m is odd and > 1.
cases mx3 with xex mx3',
cases mx3' with yex mx4,
have xd := div_alg_near_zero xex m mx1 m_odd,
cases xd with qx xd'',
cases xd'' with x1 xd',
have yd := div_alg_near_zero yex m mx1 m_odd,
cases yd with qy yd'',
cases yd'' with y1 yd',
cases xd' with xd1 xd1',
cases xd1' with xd2 xd3,
cases yd' with yd1 yd1',
cases yd1' with yd2 yd3,
have claim : ∃(n:ℤ), (m:ℤ)*n = x1^2+y1^2,
use (p:ℤ) - (xex+x1)*qx - (yex+y1)*qy,
have thing0 : ↑m * (↑p - (↑xex + x1) * qx - (↑yex + y1) * qy)
= (↑m * ↑p) - ↑m * (↑xex + x1) * qx - ↑m * (↑yex + y1) * qy := by ring,
rw thing0,
have thing0' : (m:ℤ)*p = (xex:ℤ)^2+yex^2 := by {norm_cast, exact mx4},
have thing1 : x1 = (xex:ℤ) - (m:ℤ)*qx := by {rw xd1, ring},
have thing2 : y1 = (yex:ℤ) - (m:ℤ)*qy := by {rw yd1, ring},
rw thing1,
rw thing2,
rw thing0',
ring,
cases claim with n cn,
have n_pos : 0 < n,
have ltr := lt_trichotomy 0 n,
cases ltr with ltr1 ltr1',
exact ltr1,
exfalso,
cases ltr1' with ltr2 ltr3,
rw (eq.symm ltr2) at cn,
rw mul_zero at cn,
have x1sq_nn := square_nonneg x1,
have y1sq_nn := square_nonneg y1,
have clema := add_le_add_right x1sq_nn (y1^2),
rw zero_add at clema,
rw (eq.symm cn) at clema,
have y1sq_zero := le_antisymm clema y1sq_nn,
have y1_zero : 0 = y1 := by {
by_cases contr : 0 = y1,
exact contr,
exfalso,
have thing := nonzero_square_pos y1 contr,
rw y1sq_zero at thing,
exact lt_irrefl 0 thing
},
have clema' := add_le_add_left y1sq_nn (x1^2),
rw add_zero at clema',
rw (eq.symm cn) at clema',
have x1sq_zero := le_antisymm clema' x1sq_nn,
have x1_zero : 0 = x1 := by {
by_cases contr : 0 = x1,
exact contr,
exfalso,
have thing := nonzero_square_pos x1 contr,
rw x1sq_zero at thing,
exact lt_irrefl 0 thing
},
rw (eq.symm x1_zero) at xd1,
rw add_zero at xd1,
rw (eq.symm y1_zero) at yd1,
rw add_zero at yd1,
have mx4' : (m:ℤ)*p = (xex:ℤ)^2 + yex^2 := by {norm_cast, exact mx4},
rw xd1 at mx4',
rw yd1 at mx4',
have mx4'' : (m:ℤ)*p = (m:ℤ)*(m*(qx^2+qy^2)) := by {rw mx4', ring},
have int_m_pos : (0:ℤ) < (m:ℤ) := by {norm_cast, exact mx1},
have thing := int_mul_cancel m p (m*(qx^2+qy^2)) mx4'' int_m_pos,
have qx_nat := square_eq_sq_of_nat qx,
cases qx_nat with qxn qx_nat',
have qy_nat := square_eq_sq_of_nat qy,
cases qy_nat with qyn qy_nat',
rw qx_nat' at thing,
rw qy_nat' at thing,
have thing' := int.coe_nat_inj thing,
have oth : divides m p := by {
rw divides, use qxn * (qxn * 1) + qyn * (qyn * 1), exact eq.symm thing'},
rw prime' at hp,
cases hp with hp1 hp2,
have conc := hp2 m oth,
cases conc with conc1 conc2,
exact is_m_one conc1,
rw conc2 at mx2,
exact lt_irrefl p mx2,
-- FINALLY confirmed n can't be zero.
have x1sq_nn := square_nonneg x1,
have y1sq_nn := square_nonneg y1,
have clema := add_le_add_right x1sq_nn (y1^2),
rw zero_add at clema,
rw (eq.symm cn) at clema,
have clema' := le_trans y1sq_nn clema,
have mx1' : (m:ℤ) > 0 := by {norm_cast, exact mx1},
have thing := linarith.mul_neg ltr3 mx1',
exact lt_irrefl 0 (lt_of_le_of_lt clema' thing),
have n_lt_m : n < m,
have two_squared_is_four : (2:ℤ)^2 = (4:ℤ) := by ring,
have negstx : (-2)*x1=-(2*x1) := by ring,
rw negstx at xd3,
have squarerelx := abs_thing (2*x1) (m:ℤ) xd2 xd3,
rw mul_pow at squarerelx,
rw two_squared_is_four at squarerelx,
have negsty : (-2)*y1=-(2*y1) := by ring,
rw negsty at yd3,
have squarerely := abs_thing (2*y1) (m:ℤ) yd2 yd3,
rw mul_pow at squarerely,
rw two_squared_is_four at squarerely,
have cn'4 : 4*((m:ℤ)*n) = 4*(x1^2+y1^2) := by {rw cn},
rw mul_add at cn'4,
have compare := add_lt_add squarerelx squarerely,
rw (eq.symm cn'4) at compare,
have th'1 : 4*((m:ℤ)*n)=(2*(m:ℤ))*(2*n) := by ring,
rw th'1 at compare,
have th'2 : (m:ℤ)^2+m^2 = (2*(m:ℤ))*m := by ring,
rw th'2 at compare,
have thong : 0 < 2*(m:ℤ) := by {
norm_cast,
have mx1' := add_lt_add_left mx1 m,
rw add_zero at mx1',
have th : 2*m=m+m := by ring,
rw th,
exact (lt_trans mx1 mx1')
},
have res := int_mul_cancel_lt (2*(m:ℤ)) (2*n) (m:ℤ) compare thong,
have final : n < 2*n := by {
have fin := add_lt_add_left n_pos n,
rw add_zero at fin,
have th : 2*n=n+n := by ring,
rw th, exact fin
},
exact lt_trans final res,
-- Now we can finally carry on with the rest.
-- We just need to show n*p is a sum of two squares.
have first_divis_lemma : ∃(a:ℤ),(m:ℤ)*a=xex*x1+yex*y1,
use p - xex*qx - yex*qy,
have claim : (m:ℤ)*(p-xex*qx-yex*qy) = (m:ℤ)*p - (m:ℤ)*(xex*qx+yex*qy) := by ring,
rw claim,
have mx4' : ((m:ℤ)*p = (xex:ℤ)^2+yex^2) := by {norm_cast, exact mx4},
rw mx4',
have xd1' : x1 = (xex:ℤ)-((m:ℤ)*qx) := by {rw xd1, ring},
rw xd1',
have yd1' : y1 = (yex:ℤ)-((m:ℤ)*qy) := by {rw yd1, ring},
rw yd1',
ring,
have second_divis_lemma : ∃(b:ℤ),(m:ℤ)*b=xex*y1-yex*x1,
use (yex:ℤ)*qx - (xex:ℤ)*qy,
have xd1' : x1 = (xex:ℤ)-((m:ℤ)*qx) := by {rw xd1, ring},
rw xd1',
have yd1' : y1 = (yex:ℤ)-((m:ℤ)*qy) := by {rw yd1, ring},
rw yd1',
ring,
cases first_divis_lemma with a fdl,
cases second_divis_lemma with b sdl,
have claim1 : ((m:ℤ)^2)*(n*p) = (xex*x1+yex*y1)^2 + (xex*y1-yex*x1)^2 := by {
have thong : ((m:ℤ)^2)*(n*p) = ((m:ℤ)*n)*((m:ℤ)*p) := by ring,
rw thong,
have mx4' : ((m:ℤ)*p = (xex:ℤ)^2+yex^2) := by {norm_cast, exact mx4},
rw cn,
rw mx4',
ring
},
rw (eq.symm fdl) at claim1,
rw (eq.symm sdl) at claim1,
have dist : ((m:ℤ)*a)^2 + ((m:ℤ)*b)^2 = (m:ℤ)^2*(a^2+b^2) := by ring,
rw dist at claim1,
have mx1' : 0 < (m:ℤ) := by {norm_cast, exact mx1},
by_cases could_it_be : (0:ℤ) = (m:ℤ),
exfalso,
rw could_it_be at mx1',
exact lt_irrefl (m:ℤ) mx1',
have sq_pos := nonzero_square_pos (m:ℤ) could_it_be,
have res := int_mul_cancel ((m:ℤ)^2) (n*(p:ℤ)) (a^2+b^2) claim1 sq_pos,
have n_can_be_coed := int.eq_coe_of_zero_le (le_of_lt n_pos),
cases n_can_be_coed with n' nc,
have ext_claim : ∃ (x y : ℕ), n'*p = x^2+y^2 := by {
have a_nat := square_eq_sq_of_nat a,
cases a_nat with aex a_n,
have b_nat := square_eq_sq_of_nat b,
cases b_nat with bex b_n,
use aex, use bex,
apply int.coe_nat_inj,
push_cast,
rw (eq.symm a_n),
rw (eq.symm b_n),
rw (eq.symm nc), exact res
},
rw nc at n_pos,
have n_pos' := int.coe_nat_lt.mp n_pos,
rw nc at n_lt_m,
have n_lt_m' := int.coe_nat_lt.mp n_lt_m,
have n_lt_p := lt_trans n_lt_m' mx2,
have final_thing := mm n' ⟨n_pos', n_lt_p, ext_claim⟩,
exfalso,
exact lt_irrefl m (lt_of_le_of_lt final_thing n_lt_m'),
end |
892b98a99c7917307c5fa2c39b8db7b7655a0972 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/explicitMotive.lean | a5ca056fb24c430272433b68bc5055b1dee1bc8e | [
"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 | 318 | lean |
def f1 (ex : Empty) {α : Type} : α :=
Empty.rec (motive := fun _ => α) ex
def f2 (a b : Nat) (h₁ : b = a) (h₂ : a + b = b) : a + a = b :=
Eq.rec (motive := fun x _ => a + x = b) h₂ h₁
def f3 (a b : Nat) (h₁ : b = a) (h₂ : a + b = b) : a + a = b :=
Eq.recOn (motive := fun x _ => a + x = b) h₁ h₂
|
becdc08307abc2393edb6292ce1fd67a382e3133 | abd85493667895c57a7507870867b28124b3998f | /src/representation_theory/maschke.lean | 53df1b424ad32cb0be907a5e8d027708b3eb94c8 | [
"Apache-2.0"
] | permissive | pechersky/mathlib | d56eef16bddb0bfc8bc552b05b7270aff5944393 | f1df14c2214ee114c9738e733efd5de174deb95d | refs/heads/master | 1,666,714,392,571 | 1,591,747,567,000 | 1,591,747,567,000 | 270,557,274 | 0 | 0 | Apache-2.0 | 1,591,597,975,000 | 1,591,597,974,000 | null | UTF-8 | Lean | false | false | 5,918 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Scott Morrison
-/
import data.monoid_algebra
import ring_theory.algebra
import algebra.invertible
import algebra.char_p
import linear_algebra.basis
/-!
# Maschke's theorem
We prove Maschke's theorem for finite groups,
in the formulation that every submodule of a `k[G]` module has a complement,
when `k` is a field with `¬(ring_char k ∣ fintype.card G)`.
We do the core computation in greater generality.
For any `[comm_ring k]` in which `[invertible (fintype.card G : k)]`,
and a `k[G]`-linear map `i : V → W` which admits a `k`-linear retraction `π`,
we produce a `k[G]`-linear retraction by
taking the average over `G` of the conjugates of `π`.
## Future work
It's not so far to give the usual statement, that every finite dimensional representation
of a finite group is semisimple (i.e. a direct sum of irreducibles).
-/
universes u
noncomputable theory
open module
open monoid_algebra
section
-- At first we work with any `[comm_ring k]`, and add the assumption that
-- `[invertible (fintype.card G : k)]` when it is required.
variables {k : Type u} [comm_ring k] {G : Type u} [group G]
variables {V : Type u} [add_comm_group V] [module (monoid_algebra k G) V]
variables {W : Type u} [add_comm_group W] [module (monoid_algebra k G) W]
/-!
We now do the key calculation in Maschke's theorem.
Given `V → W`, an inclusion of `k[G]` modules,,
assume we have some retraction `π` (i.e. `∀ v, π (i v) = v`),
just as a `k`-linear map.
(When `k` is a field, this will be available cheaply, by choosing a basis.)
We now construct a retraction of the inclusion as a `k[G]`-linear map,
by the formula
$$ \frac{1}{|G|} \sum_{g \mem G} g⁻¹ • π(g • -). $$
-/
variables (π : (restrict_scalars k (monoid_algebra k G) W) →ₗ[k]
(restrict_scalars k (monoid_algebra k G) V))
include π
/--
We define the conjugate of `π` by `g`, as a `k`-linear map.
-/
def conjugate (g : G) :
(restrict_scalars k (monoid_algebra k G) W) →ₗ[k] (restrict_scalars k (monoid_algebra k G) V) :=
((group_smul.linear_map k V g⁻¹).comp π).comp (group_smul.linear_map k W g)
variables (i : V →ₗ[monoid_algebra k G] W) (h : ∀ v : V, π (i v) = v)
section
include h
lemma conjugate_i (g : G) (v : V) : (conjugate π g) (i v) = v :=
begin
dsimp [conjugate],
simp only [←i.map_smul, h, ←mul_smul, single_mul_single, mul_one, mul_left_inv],
change (1 : monoid_algebra k G) • v = v,
simp,
end
end
variables [fintype G]
/--
The sum of the conjugates of `π` by each element `g : G`, as a `k`-linear map.
(We postpone dividing by the size of the group as long as possible.)
-/
def sum_of_conjugates :
(restrict_scalars k (monoid_algebra k G) W) →ₗ[k] (restrict_scalars k (monoid_algebra k G) V) :=
(finset.univ : finset G).sum (λ g, conjugate π g)
/--
In fact, the sum over `g : G` of the conjugate of `π` by `g` is a `k[G]`-linear map.
-/
def sum_of_conjugates_equivariant :
W →ₗ[monoid_algebra k G] V :=
monoid_algebra.equivariant_of_linear_of_comm (sum_of_conjugates π) (λ g v,
begin
dsimp [sum_of_conjugates],
simp only [linear_map.sum_apply, finset.smul_sum],
dsimp [conjugate],
conv_lhs {
rw [←finset.univ_map_embedding (mul_right_embedding g⁻¹)],
simp only [mul_right_embedding],
},
simp only [←mul_smul, single_mul_single, mul_inv_rev, mul_one, function.embedding.coe_fn_mk,
finset.sum_map, inv_inv, inv_mul_cancel_right],
end)
section
variables [inv : invertible (fintype.card G : k)]
include inv
section
local attribute [instance] linear_map_algebra_module
/--
We construct our `k[G]`-linear retraction of `i` as
$$ \frac{1}{|G|} \sum_{g \mem G} g⁻¹ • π(g • -). $$
-/
def equivariant_projection :
W →ₗ[monoid_algebra k G] V :=
⅟(fintype.card G : k) • (sum_of_conjugates_equivariant π)
end
include h
lemma equivariant_projection_condition (v : V) : (equivariant_projection π) (i v) = v :=
begin
rw [equivariant_projection, linear_map_algebra_module.smul_apply, sum_of_conjugates_equivariant,
equivariant_of_linear_of_comm_apply, sum_of_conjugates],
rw [linear_map.sum_apply],
simp only [conjugate_i π i h],
rw [finset.sum_const, finset.card_univ,
@semimodule.nsmul_eq_smul k _
(restrict_scalars k (monoid_algebra k G) V) _ _ (fintype.card G) v,
←mul_smul, invertible.inv_of_mul_self, one_smul],
end
end
end
-- Now we work over a `[field k]`, and replace the assumption `[invertible (fintype.card G : k)]`
-- with `¬(ring_char k ∣ fintype.card G)`.
variables {k : Type u} [field k] {G : Type u} [fintype G] [group G]
variables {V : Type u} [add_comm_group V] [module (monoid_algebra k G) V]
variables {W : Type u} [add_comm_group W] [module (monoid_algebra k G) W]
lemma monoid_algebra.exists_left_inverse_of_injective
(not_dvd : ¬(ring_char k ∣ fintype.card G))
(f : V →ₗ[monoid_algebra k G] W) (hf_inj : f.ker = ⊥) :
∃ (g : W →ₗ[monoid_algebra k G] V), g.comp f = linear_map.id :=
begin
let E := linear_map.exists_left_inverse_of_injective
(by convert f.restrict_scalars k) (by simp [hf_inj]),
fsplit,
haveI : invertible (fintype.card G : k) :=
invertible_of_ring_char_not_dvd not_dvd,
exact equivariant_projection (classical.some E),
{ ext v,
apply equivariant_projection_condition,
intro v,
have := classical.some_spec E,
have := congr_arg linear_map.to_fun this,
exact congr_fun this v, }
end
lemma monoid_algebra.submodule.exists_is_compl
(not_dvd : ¬(ring_char k ∣ fintype.card G)) (p : submodule (monoid_algebra k G) V) :
∃ q : submodule (monoid_algebra k G) V, is_compl p q :=
let ⟨f, hf⟩ := monoid_algebra.exists_left_inverse_of_injective not_dvd p.subtype p.ker_subtype in
⟨f.ker, linear_map.is_compl_of_proj $ linear_map.ext_iff.1 hf⟩
|
8119ecb353ccc1f5b551c3d2021ce69036bda3c0 | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /library/init/meta/converter.lean | 79cfd15b6e934434e9fa6c22b89c029b3472dcca | [
"Apache-2.0"
] | permissive | bre7k30/lean | de893411bcfa7b3c5572e61b9e1c52951b310aa4 | 5a924699d076dab1bd5af23a8f910b433e598d7a | refs/heads/master | 1,610,900,145,817 | 1,488,006,845,000 | 1,488,006,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,921 | 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
Converter monad for building simplifiers.
-/
prelude
import init.meta.tactic init.meta.simp_tactic
import init.meta.congr_lemma init.meta.match_tactic
open tactic
meta structure conv_result (α : Type) :=
(val : α) (rhs : expr) (proof : option expr)
meta def conv (α : Type) : Type :=
name → expr → tactic (conv_result α)
namespace conv
meta def lhs : conv expr :=
λ r e, return ⟨e, e, none⟩
meta def change (new_p : pexpr) : conv unit :=
λ r e, do
new_e ← to_expr new_p,
unify e new_e,
return ⟨(), new_e, none⟩
protected meta def pure {α : Type} : α → conv α :=
λ a r e, return ⟨a, e, none⟩
private meta def join_proofs (r : name) (o₁ o₂ : option expr) : tactic (option expr) :=
match o₁, o₂ with
| none, _ := return o₂
| _, none := return o₁
| some p₁, some p₂ := do
env ← get_env,
match env^.trans_for r with
| some trans := do pr ← mk_app trans [p₁, p₂], return $ some pr
| none := fail $ "converter failed, relation '" ++ r^.to_string ++ "' is not transitive"
end
end
protected meta def seq {α β : Type} (c₁ : conv (α → β)) (c₂ : conv α) : conv β :=
λ r e, do
⟨fn, e₁, pr₁⟩ ← c₁ r e,
⟨a, e₂, pr₂⟩ ← c₂ r e₁,
pr ← join_proofs r pr₁ pr₂,
return ⟨fn a, e₂, pr⟩
protected meta def fail {α : Type} : conv α :=
λ r e, failed
protected meta def orelse {α : Type} (c₁ : conv α) (c₂ : conv α) : conv α :=
λ r e, c₁ r e <|> c₂ r e
protected meta def map {α β : Type} (f : α → β) (c : conv α) : conv β :=
λ r e, do
⟨a, e₁, pr⟩ ← c r e,
return ⟨f a, e₁, pr⟩
protected meta def bind {α β : Type} (c₁ : conv α) (c₂ : α → conv β) : conv β :=
λ r e, do
⟨a, e₁, pr₁⟩ ← c₁ r e,
⟨b, e₂, pr₂⟩ ← c₂ a r e₁,
pr ← join_proofs r pr₁ pr₂,
return ⟨b, e₂, pr⟩
meta instance : monad conv :=
{ map := @conv.map,
ret := @conv.pure,
bind := @conv.bind }
meta instance : alternative conv :=
{ map := @conv.map,
pure := @conv.pure,
seq := @conv.seq,
failure := @conv.fail,
orelse := @conv.orelse }
meta def whnf (md : transparency := reducible) : conv unit :=
λ r e, do n ← tactic.whnf e md, return ⟨(), n, none⟩
meta def dsimp : conv unit :=
λ r e, do s ← simp_lemmas.mk_default, n ← s^.dsimplify e, return ⟨(), n, none⟩
meta def try (c : conv unit) : conv unit :=
c <|> return ()
meta def tryb (c : conv unit) : conv bool :=
(c >> return tt) <|> return ff
meta def trace {α : Type} [has_to_tactic_format α] (a : α) : conv unit :=
λ r e, tactic.trace a >> return ⟨(), e, none⟩
meta def trace_lhs : conv unit :=
lhs >>= trace
meta def apply_lemmas_core (s : simp_lemmas) (prove : tactic unit) : conv unit :=
λ r e, do
(new_e, pr) ← s^.rewrite prove r e,
return ⟨(), new_e, some pr⟩
meta def apply_lemmas (s : simp_lemmas) : conv unit :=
apply_lemmas_core s failed
/- αdapter for using iff-lemmas as eq-lemmas -/
meta def apply_propext_lemmas_core (s : simp_lemmas) (prove : tactic unit) : conv unit :=
λ r e, do
guard (r = `eq),
(new_e, pr) ← s^.rewrite prove `iff e,
new_pr ← mk_app `propext [pr],
return ⟨(), new_e, some new_pr⟩
meta def apply_propext_lemmas (s : simp_lemmas) : conv unit :=
apply_propext_lemmas_core s failed
private meta def mk_refl_proof (r : name) (e : expr) : tactic expr :=
do env ← get_env,
match (environment.refl_for env r) with
| (some refl) := do pr ← mk_app refl [e], return pr
| none := fail $ "converter failed, relation '" ++ r^.to_string ++ "' is not reflexive"
end
meta def to_tactic (c : conv unit) : name → expr → tactic (expr × expr) :=
λ r e, do
⟨u, e₁, o⟩ ← c r e,
match o with
| none := do p ← mk_refl_proof r e, return (e₁, p)
| some p := return (e₁, p)
end
meta def lift_tactic {α : Type} (t : tactic α) : conv α :=
λ r e, do a ← t, return ⟨a, e, none⟩
meta def apply_simp_set (attr_name : name) : conv unit :=
lift_tactic (get_user_simp_lemmas attr_name) >>= apply_lemmas
meta def apply_propext_simp_set (attr_name : name) : conv unit :=
lift_tactic (get_user_simp_lemmas attr_name) >>= apply_propext_lemmas
meta def skip : conv unit :=
return ()
meta def repeat : conv unit → conv unit
| c r lhs :=
(do
⟨_, rhs₁, pr₁⟩ ← c r lhs,
guard (¬ lhs =ₐ rhs₁),
⟨_, rhs₂, pr₂⟩ ← repeat c r rhs₁,
pr ← join_proofs r pr₁ pr₂,
return ⟨(), rhs₂, pr⟩)
<|> return ⟨(), lhs, none⟩
meta def first {α : Type} : list (conv α) → conv α
| [] := conv.fail
| (c::cs) := c <|> first cs
meta def match_pattern (p : pattern) : conv unit :=
λ r e, tactic.match_pattern p e >> return ⟨(), e, none⟩
meta def mk_match_expr (p : pexpr) : tactic (conv unit) :=
do new_p ← pexpr_to_pattern p,
return (λ r e, tactic.match_pattern new_p e >> return ⟨(), e, none⟩)
meta def match_expr (p : pexpr) : conv unit :=
λ r e, do
new_p ← pexpr_to_pattern p,
tactic.match_pattern new_p e >> return ⟨(), e, none⟩
meta def funext (c : conv unit) : conv unit :=
λ r lhs, do
guard (r = `eq),
(expr.lam n bi d b) ← return lhs,
let aux_type := expr.pi n bi d (expr.const `true []),
(result, _) ← solve_aux aux_type $ do {
x ← intro1,
c_result ← c r (b^.instantiate_var x),
let rhs := expr.lam n bi d (c_result^.rhs^.abstract x),
match c_result^.proof : _ → tactic (conv_result unit) with
| some pr := do
let aux_pr := expr.lam n bi d (pr^.abstract x),
new_pr ← mk_app `funext [lhs, rhs, aux_pr],
return ⟨(), rhs, some new_pr⟩
| none := return ⟨(), rhs, none⟩
end },
return result
meta def congr_core (c_f c_a : conv unit) : conv unit :=
λ r lhs, do
guard (r = `eq),
(expr.app f a) ← return lhs,
f_type ← infer_type f >>= tactic.whnf,
guard (f_type^.is_arrow),
⟨(), new_f, of⟩ ← try c_f r f,
⟨(), new_a, oa⟩ ← try c_a r a,
rhs ← return $ new_f new_a,
match of, oa with
| none, none :=
return ⟨(), rhs, none⟩
| none, some pr_a := do
pr ← mk_app `congr_arg [a, new_a, f, pr_a],
return ⟨(), new_f new_a, some pr⟩
| some pr_f, none := do
pr ← mk_app `congr_fun [f, new_f, pr_f, a],
return ⟨(), rhs, some pr⟩
| some pr_f, some pr_a := do
pr ← mk_app `congr [f, new_f, a, new_a, pr_f, pr_a],
return ⟨(), rhs, some pr⟩
end
meta def congr (c : conv unit) : conv unit :=
congr_core c c
meta def bottom_up (c : conv unit) : conv unit :=
λ r e, do
s ← simp_lemmas.mk_default,
(a, new_e, pr) ←
ext_simplify_core () {} s
(λ u, return u)
(λ a s r p e, failed)
(λ a s r p e, do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, tt))
r e,
return ⟨(), new_e, some pr⟩
meta def top_down (c : conv unit) : conv unit :=
λ r e, do
s ← simp_lemmas.mk_default,
(a, new_e, pr) ←
ext_simplify_core () {} s
(λ u, return u)
(λ a s r p e, do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, tt))
(λ a s r p e, failed)
r e,
return ⟨(), new_e, some pr⟩
meta def find (c : conv unit) : conv unit :=
λ r e, do
s ← simp_lemmas.mk_default,
(a, new_e, pr) ←
ext_simplify_core () {} s
(λ u, return u)
(λ a s r p e,
(do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, ff))
<|>
return ((), e, none, tt))
(λ a s r p e, failed)
r e,
return ⟨(), new_e, some pr⟩
meta def find_pattern (pat : pattern) (c : conv unit) : conv unit :=
λ r e, do
s ← simp_lemmas.mk_default,
(a, new_e, pr) ←
ext_simplify_core () {} s
(λ u, return u)
(λ a s r p e, do
matched ← (tactic.match_pattern pat e >> return tt) <|> return ff,
if matched
then do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, ff)
else return ((), e, none, tt))
(λ a s r p e, failed)
r e,
return ⟨(), new_e, some pr⟩
meta def findp : pexpr → conv unit → conv unit :=
λ p c r e, do
pat ← pexpr_to_pattern p,
find_pattern pat c r e
meta def conversion (c : conv unit) : tactic unit :=
do (r, lhs, rhs) ← (target_lhs_rhs <|> fail "conversion failed, target is not of the form 'lhs R rhs'"),
(new_lhs, pr) ← to_tactic c r lhs,
(unify new_lhs rhs <|>
do new_lhs_fmt ← pp new_lhs,
rhs_fmt ← pp rhs,
fail (to_fmt "conversion failed, expected" ++
rhs_fmt^.indent 4 ++ format.line ++ "provided" ++
new_lhs_fmt^.indent 4)),
exact pr
end conv
|
dff000388ae0bbd94dee171b57558a65633aaeb2 | 98beff2e97d91a54bdcee52f922c4e1866a6c9b9 | /src/category/sparse_skeleton.lean | 349d05bffa541dca000476b764ebb6d34b38cecf | [] | no_license | b-mehta/topos | c3fc43fb04ba16bae1965ce5c26c6461172e5bc6 | c9032b11789e36038bc841a1e2b486972421b983 | refs/heads/master | 1,629,609,492,867 | 1,609,907,263,000 | 1,609,907,263,000 | 240,943,034 | 43 | 3 | null | 1,598,210,062,000 | 1,581,877,668,000 | Lean | UTF-8 | Lean | false | false | 5,067 | 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.opposites
import category_theory.thin
import category_theory.full_subcategory
import category_theory.currying
import tactic
universes v v₂ v₃ u u₂ u₃
namespace category_theory
open category_theory category_theory.category
variables {C : Type u} [category.{v} C]
variables {D : Type u₂} [category.{v₂} D]
variables {E : Type u₃} [category.{v₃} E]
def are_iso (X Y : C) : Prop := nonempty (X ≅ Y)
variables (C)
def skeletal : Prop := ∀ (X Y : C), (X ≅ Y) → X = Y
instance up_to_iso : setoid C :=
{ r := are_iso,
iseqv :=
begin
refine ⟨λ X, ⟨iso.refl _⟩, λ X Y, _, λ X Y Z, _⟩,
rintro ⟨i⟩,
refine ⟨i.symm⟩,
rintro ⟨i⟩ ⟨j⟩,
refine ⟨i.trans j⟩,
end }
def skel := quotient (category_theory.up_to_iso C)
instance skel_preorder : preorder (skel C) :=
{ le :=
begin
refine quotient.lift₂ (λ X Y, nonempty (X ⟶ Y)) _,
rintros _ _ _ _ ⟨i₁⟩ ⟨i₂⟩,
apply propext,
split,
rintro ⟨f⟩,
refine ⟨i₁.inv ≫ f ≫ i₂.hom⟩,
rintro ⟨g⟩,
refine ⟨i₁.hom ≫ g ≫ i₂.inv⟩,
end,
le_refl :=
begin
refine quotient.ind (λ a, _),
exact ⟨𝟙 _⟩,
end,
le_trans :=
begin
intros _ _ _,
apply quotient.induction_on₃ a b c,
rintros _ _ _ ⟨f⟩ ⟨g⟩,
refine ⟨f ≫ g⟩,
end }
instance skel_subsingleton {X Y : skel C} : subsingleton (X ⟶ Y) :=
⟨by { rintros ⟨⟨f₁⟩⟩ ⟨⟨f₂⟩⟩, refl }⟩
instance skel_iso_subsingleton {X Y : skel C} : subsingleton (X ≅ Y) :=
⟨by { rintros i₁ i₂, ext1, apply subsingleton.elim }⟩
def skel_quotient : C ⥤ skel C :=
{ obj := quotient.mk,
map := λ X Y f, ⟨⟨⟨f⟩⟩⟩ }
variables {C}
@[simps]
def skel_map (F : C ⥤ D) : skel C ⥤ skel D :=
{ obj :=
begin
refine quotient.lift _ _,
intro x,
apply quotient.mk (F.obj x),
rintros x y ⟨k⟩,
apply quotient.sound,
refine ⟨_⟩,
apply F.map_iso k,
end,
map :=
begin
refine quotient.rec _ _,
{ intro x,
refine quotient.rec _ _,
{ intros y k,
refine ⟨⟨_⟩⟩,
rcases k with ⟨⟨⟨k⟩⟩⟩,
refine ⟨F.map k⟩ },
{ intros y z h,
apply subsingleton.elim } },
{ intros x y h,
apply subsingleton.elim }
end }
lemma skel_quotient_map (F : C ⥤ D) : skel_quotient C ⋙ skel_map F = F ⋙ skel_quotient D :=
rfl
def skel_map_comp (F : C ⥤ D) (G : D ⥤ E) : skel_map (F ⋙ G) ≅ skel_map F ⋙ skel_map G :=
nat_iso.of_components (λ X, quotient.rec_on_subsingleton X (λ x, iso.refl _)) (by tidy)
def skel_map_id : skel_map (𝟭 C) ≅ 𝟭 _ :=
nat_iso.of_components (λ X, quotient.rec_on_subsingleton X (λ x, iso.refl _)) (by tidy)
def skel_map_func {F₁ F₂ : C ⥤ D} (k : F₁ ⟶ F₂) : skel_map F₁ ⟶ skel_map F₂ :=
{ app := λ X, quotient.rec_on_subsingleton X (λ x, ⟨⟨⟨k.app x⟩⟩⟩) }
def skel_map_iso {F₁ F₂ : C ⥤ D} (h : F₁ ≅ F₂) : skel_map F₁ ≅ skel_map F₂ :=
{ hom := skel_map_func h.hom, inv := skel_map_func h.inv }
variables [∀ X Y : C, subsingleton (X ⟶ Y)]
-- def iso_of_both_ways {X Y : C} (f : X ⟶ Y) (g : Y ⟶ X) : X ≅ Y :=
-- { hom := f, inv := g }
lemma equiv_of_both_ways {X Y : C} (f : X ⟶ Y) (g : Y ⟶ X) : X ≈ Y :=
⟨iso_of_both_ways f g⟩
instance : partial_order (skel C) :=
{ le_antisymm :=
begin
refine quotient.ind₂ _,
rintros _ _ ⟨f⟩ ⟨g⟩,
apply quotient.sound,
apply equiv_of_both_ways f g,
end,
..category_theory.skel_preorder C }
lemma skel_is_skel : skeletal (skel C) :=
begin
intros X Y,
apply quotient.induction_on₂ X Y,
rintros _ _ ⟨⟨⟨⟨f⟩⟩⟩, ⟨⟨⟨g⟩⟩⟩, _, _⟩,
apply quotient.sound,
apply equiv_of_both_ways f g,
end
def skel_map₂ (F : C ⥤ D ⥤ E) : skel C ⥤ skel D ⥤ skel E :=
category_theory.curry_obj
{ obj :=
begin
rintro ⟨x₁, x₂⟩,
refine quotient.map₂ _ _ x₁ x₂,
intros c d, apply (F.obj c).obj d,
rintros c₁ c₂ ⟨hc⟩ d₁ d₂ ⟨hd⟩,
refine ⟨(F.map_iso hc).app d₁ ≪≫ (F.obj c₂).map_iso hd⟩,
end,
map :=
begin
rintros ⟨X₁,Y₁⟩,
rintros ⟨X₂,Y₂⟩,
refine quotient.rec_on_subsingleton X₁ _,
refine quotient.rec_on_subsingleton Y₁ _,
refine quotient.rec_on_subsingleton X₂ _,
refine quotient.rec_on_subsingleton Y₂ _,
rintros y₂ x₂ y₁ x₁ ⟨⟨⟨hx⟩⟩, ⟨⟨hy⟩⟩⟩,
dsimp at hx hy,
refine ⟨⟨_⟩⟩,
cases hx, cases hy,
exact ⟨(F.map hx).app y₁ ≫ (F.obj x₂).map hy⟩,
end }
def skel_map_eq {F₁ F₂ : C ⥤ D} (h : F₁ ≅ F₂) : skel_map F₁ = skel_map F₂ :=
begin
apply functor.ext (quotient.ind _) _,
{ intro x,
apply quotient.sound,
refine ⟨h.app x⟩ },
{ tidy },
end
end category_theory |
4fa33dc3a7587f61f7b0927da2f8285ae04e13ef | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/group_theory/subsemigroup/center.lean | 0f393774d6893e0b365583643e01fb9a79f148de | [
"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,052 | lean | /-
Copyright (c) 2021 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser, Jireh Loreaux
-/
import algebra.ring.defs
import group_theory.subsemigroup.operations
/-!
# Centers of magmas and semigroups
## Main definitions
* `set.center`: the center of a magma
* `subsemigroup.center`: the center of a semigroup
* `set.add_center`: the center of an additive magma
* `add_subsemigroup.center`: the center of an additive semigroup
We provide `submonoid.center`, `add_submonoid.center`, `subgroup.center`, `add_subgroup.center`,
`subsemiring.center`, and `subring.center` in other files.
-/
variables {M : Type*}
namespace set
variables (M)
/-- The center of a magma. -/
@[to_additive add_center /-" The center of an additive magma. "-/]
def center [has_mul M] : set M := {z | ∀ m, m * z = z * m}
@[to_additive mem_add_center]
lemma mem_center_iff [has_mul M] {z : M} : z ∈ center M ↔ ∀ g, g * z = z * g := iff.rfl
instance decidable_mem_center [has_mul M] [∀ a : M, decidable $ ∀ b : M, b * a = a * b] :
decidable_pred (∈ center M) :=
λ _, decidable_of_iff' _ (mem_center_iff M)
@[simp, to_additive zero_mem_add_center]
lemma one_mem_center [mul_one_class M] : (1 : M) ∈ set.center M := by simp [mem_center_iff]
@[simp]
lemma zero_mem_center [mul_zero_class M] : (0 : M) ∈ set.center M := by simp [mem_center_iff]
variables {M}
@[simp, to_additive add_mem_add_center]
lemma mul_mem_center [semigroup M] {a b : M}
(ha : a ∈ set.center M) (hb : b ∈ set.center M) : a * b ∈ set.center M :=
λ g, by rw [mul_assoc, ←hb g, ← mul_assoc, ha g, mul_assoc]
@[simp, to_additive neg_mem_add_center]
lemma inv_mem_center [group M] {a : M} (ha : a ∈ set.center M) : a⁻¹ ∈ set.center M :=
λ g, by rw [← inv_inj, mul_inv_rev, inv_inv, ← ha, mul_inv_rev, inv_inv]
@[simp]
lemma add_mem_center [distrib M] {a b : M}
(ha : a ∈ set.center M) (hb : b ∈ set.center M) : a + b ∈ set.center M :=
λ c, by rw [add_mul, mul_add, ha c, hb c]
@[simp]
lemma neg_mem_center [ring M] {a : M} (ha : a ∈ set.center M) : -a ∈ set.center M :=
λ c, by rw [←neg_mul_comm, ha (-c), neg_mul_comm]
@[to_additive subset_add_center_add_units]
lemma subset_center_units [monoid M] :
(coe : Mˣ → M) ⁻¹' center M ⊆ set.center Mˣ :=
λ a ha b, units.ext $ ha _
lemma center_units_subset [group_with_zero M] :
set.center Mˣ ⊆ (coe : Mˣ → M) ⁻¹' center M :=
λ a ha b, begin
obtain rfl | hb := eq_or_ne b 0,
{ rw [zero_mul, mul_zero], },
{ exact units.ext_iff.mp (ha (units.mk0 _ hb)) }
end
/-- In a group with zero, the center of the units is the preimage of the center. -/
lemma center_units_eq [group_with_zero M] :
set.center Mˣ = (coe : Mˣ → M) ⁻¹' center M :=
subset.antisymm center_units_subset subset_center_units
@[simp]
lemma inv_mem_center₀ [group_with_zero M] {a : M} (ha : a ∈ set.center M) : a⁻¹ ∈ set.center M :=
begin
obtain rfl | ha0 := eq_or_ne a 0,
{ rw inv_zero, exact zero_mem_center M },
rcases is_unit.mk0 _ ha0 with ⟨a, rfl⟩,
rw ←units.coe_inv,
exact center_units_subset (inv_mem_center (subset_center_units ha)),
end
@[simp, to_additive sub_mem_add_center]
lemma div_mem_center [group M] {a b : M} (ha : a ∈ set.center M) (hb : b ∈ set.center M) :
a / b ∈ set.center M :=
begin
rw [div_eq_mul_inv],
exact mul_mem_center ha (inv_mem_center hb),
end
@[simp]
lemma div_mem_center₀ [group_with_zero M] {a b : M} (ha : a ∈ set.center M)
(hb : b ∈ set.center M) : a / b ∈ set.center M :=
begin
rw div_eq_mul_inv,
exact mul_mem_center ha (inv_mem_center₀ hb),
end
variables (M)
@[simp, to_additive add_center_eq_univ]
lemma center_eq_univ [comm_semigroup M] : center M = set.univ :=
subset.antisymm (subset_univ _) $ λ x _ y, mul_comm y x
end set
namespace subsemigroup
section
variables (M) [semigroup M]
/-- The center of a semigroup `M` is the set of elements that commute with everything in `M` -/
@[to_additive "The center of a semigroup `M` is the set of elements that commute with everything in
`M`"]
def center : subsemigroup M :=
{ carrier := set.center M,
mul_mem' := λ a b, set.mul_mem_center }
@[to_additive] lemma coe_center : ↑(center M) = set.center M := rfl
variables {M}
@[to_additive] lemma mem_center_iff {z : M} : z ∈ center M ↔ ∀ g, g * z = z * g := iff.rfl
@[to_additive]
instance decidable_mem_center (a) [decidable $ ∀ b : M, b * a = a * b] :
decidable (a ∈ center M) :=
decidable_of_iff' _ mem_center_iff
/-- The center of a semigroup is commutative. -/
@[to_additive "The center of an additive semigroup is commutative."]
instance : comm_semigroup (center M) :=
{ mul_comm := λ a b, subtype.ext $ b.prop _,
.. mul_mem_class.to_semigroup (center M) }
end
section
variables (M) [comm_semigroup M]
@[to_additive, simp] lemma center_eq_top : center M = ⊤ :=
set_like.coe_injective (set.center_eq_univ M)
end
end subsemigroup
-- Guard against import creep
assert_not_exists finset
|
e72d4228d9fa486836f54b611bd3f8142091d1cf | bb31430994044506fa42fd667e2d556327e18dfe | /src/data/set/intervals/ord_connected_component.lean | eff4c832d07d6dc623eb33a125b97cf24d9cdcc6 | [
"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 | 9,253 | lean | /-
Copyright (c) 2022 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import data.set.intervals.ord_connected
import tactic.wlog
/-!
# Order connected components of a set
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we define `set.ord_connected_component s x` to be the set of `y` such that
`set.uIcc x y ⊆ s` and prove some basic facts about this definition. At the moment of writing,
this construction is used only to prove that any linear order with order topology is a T₅ space,
so we only add API needed for this lemma.
-/
open function order_dual
open_locale interval
namespace set
variables {α : Type*} [linear_order α] {s t : set α} {x y z : α}
/-- Order-connected component of a point `x` in a set `s`. It is defined as the set of `y` such that
`set.uIcc x y ⊆ s`. Note that it is empty if and only if `x ∉ s`. -/
def ord_connected_component (s : set α) (x : α) : set α := {y | [x, y] ⊆ s}
lemma mem_ord_connected_component : y ∈ ord_connected_component s x ↔ [x, y] ⊆ s := iff.rfl
lemma dual_ord_connected_component :
ord_connected_component (of_dual ⁻¹' s) (to_dual x) = of_dual ⁻¹' (ord_connected_component s x) :=
ext $ to_dual.surjective.forall.2 $ λ x,
by { rw [mem_ord_connected_component, dual_uIcc], refl }
lemma ord_connected_component_subset : ord_connected_component s x ⊆ s := λ y hy, hy right_mem_uIcc
lemma subset_ord_connected_component {t} [h : ord_connected s] (hs : x ∈ s) (ht : s ⊆ t) :
s ⊆ ord_connected_component t x :=
λ y hy, (h.uIcc_subset hs hy).trans ht
@[simp] lemma self_mem_ord_connected_component : x ∈ ord_connected_component s x ↔ x ∈ s :=
by rw [mem_ord_connected_component, uIcc_self, singleton_subset_iff]
@[simp] lemma nonempty_ord_connected_component : (ord_connected_component s x).nonempty ↔ x ∈ s :=
⟨λ ⟨y, hy⟩, hy $ left_mem_uIcc, λ h, ⟨x, self_mem_ord_connected_component.2 h⟩⟩
@[simp] lemma ord_connected_component_eq_empty : ord_connected_component s x = ∅ ↔ x ∉ s :=
by rw [← not_nonempty_iff_eq_empty, nonempty_ord_connected_component]
@[simp] lemma ord_connected_component_empty : ord_connected_component ∅ x = ∅ :=
ord_connected_component_eq_empty.2 (not_mem_empty x)
@[simp] lemma ord_connected_component_univ : ord_connected_component univ x = univ :=
by simp [ord_connected_component]
lemma ord_connected_component_inter (s t : set α) (x : α) :
ord_connected_component (s ∩ t) x = ord_connected_component s x ∩ ord_connected_component t x :=
by simp [ord_connected_component, set_of_and]
lemma mem_ord_connected_component_comm :
y ∈ ord_connected_component s x ↔ x ∈ ord_connected_component s y :=
by rw [mem_ord_connected_component, mem_ord_connected_component, uIcc_comm]
lemma mem_ord_connected_component_trans (hxy : y ∈ ord_connected_component s x)
(hyz : z ∈ ord_connected_component s y) : z ∈ ord_connected_component s x :=
calc [x, z] ⊆ [x, y] ∪ [y, z] : uIcc_subset_uIcc_union_uIcc
... ⊆ s : union_subset hxy hyz
lemma ord_connected_component_eq (h : [x, y] ⊆ s) :
ord_connected_component s x = ord_connected_component s y :=
ext $ λ z, ⟨mem_ord_connected_component_trans (mem_ord_connected_component_comm.2 h),
mem_ord_connected_component_trans h⟩
instance : ord_connected (ord_connected_component s x) :=
ord_connected_of_uIcc_subset_left $ λ y hy z hz, (uIcc_subset_uIcc_left hz).trans hy
/-- Projection from `s : set α` to `α` sending each order connected component of `s` to a single
point of this component. -/
noncomputable def ord_connected_proj (s : set α) : s → α :=
λ x : s, (nonempty_ord_connected_component.2 x.prop).some
lemma ord_connected_proj_mem_ord_connected_component (s : set α) (x : s) :
ord_connected_proj s x ∈ ord_connected_component s x :=
nonempty.some_mem _
lemma mem_ord_connected_component_ord_connected_proj (s : set α) (x : s) :
↑x ∈ ord_connected_component s (ord_connected_proj s x) :=
mem_ord_connected_component_comm.2 $ ord_connected_proj_mem_ord_connected_component s x
@[simp] lemma ord_connected_component_ord_connected_proj (s : set α) (x : s) :
ord_connected_component s (ord_connected_proj s x) = ord_connected_component s x :=
ord_connected_component_eq $ mem_ord_connected_component_ord_connected_proj _ _
@[simp] lemma ord_connected_proj_eq {x y : s} :
ord_connected_proj s x = ord_connected_proj s y ↔ [(x : α), y] ⊆ s :=
begin
split; intro h,
{ rw [← mem_ord_connected_component, ← ord_connected_component_ord_connected_proj, h,
ord_connected_component_ord_connected_proj, self_mem_ord_connected_component],
exact y.2 },
{ simp only [ord_connected_proj],
congr' 1,
exact ord_connected_component_eq h }
end
/-- A set that intersects each order connected component of a set by a single point. Defined as the
range of `set.ord_connected_proj s`. -/
def ord_connected_section (s : set α) : set α := range $ ord_connected_proj s
lemma dual_ord_connected_section (s : set α) :
ord_connected_section (of_dual ⁻¹' s) = of_dual ⁻¹' (ord_connected_section s) :=
begin
simp only [ord_connected_section, ord_connected_proj],
congr' 1 with x, simp only, congr' 1,
exact dual_ord_connected_component
end
lemma ord_connected_section_subset : ord_connected_section s ⊆ s :=
range_subset_iff.2 $ λ x, ord_connected_component_subset $ nonempty.some_mem _
lemma eq_of_mem_ord_connected_section_of_uIcc_subset (hx : x ∈ ord_connected_section s)
(hy : y ∈ ord_connected_section s) (h : [x, y] ⊆ s) : x = y :=
begin
rcases hx with ⟨x, rfl⟩, rcases hy with ⟨y, rfl⟩,
exact ord_connected_proj_eq.2 (mem_ord_connected_component_trans
(mem_ord_connected_component_trans (ord_connected_proj_mem_ord_connected_component _ _) h)
(mem_ord_connected_component_ord_connected_proj _ _))
end
/-- Given two sets `s t : set α`, the set `set.order_separating_set s t` is the set of points that
belong both to some `set.ord_connected_component tᶜ x`, `x ∈ s`, and to some
`set.ord_connected_component sᶜ x`, `x ∈ t`. In the case of two disjoint closed sets, this is the
union of all open intervals $(a, b)$ such that their endpoints belong to different sets. -/
def ord_separating_set (s t : set α) : set α :=
(⋃ x ∈ s, ord_connected_component tᶜ x) ∩ (⋃ x ∈ t, ord_connected_component sᶜ x)
lemma ord_separating_set_comm (s t : set α) :
ord_separating_set s t = ord_separating_set t s :=
inter_comm _ _
lemma disjoint_left_ord_separating_set : disjoint s (ord_separating_set s t) :=
disjoint.inter_right' _ $ disjoint_Union₂_right.2 $ λ x hx, disjoint_compl_right.mono_right $
ord_connected_component_subset
lemma disjoint_right_ord_separating_set : disjoint t (ord_separating_set s t) :=
ord_separating_set_comm t s ▸ disjoint_left_ord_separating_set
lemma dual_ord_separating_set :
ord_separating_set (of_dual ⁻¹' s) (of_dual ⁻¹' t) = of_dual ⁻¹' (ord_separating_set s t) :=
by simp only [ord_separating_set, mem_preimage, ← to_dual.surjective.Union_comp, of_dual_to_dual,
dual_ord_connected_component, ← preimage_compl, preimage_inter, preimage_Union]
/-- An auxiliary neighborhood that will be used in the proof of `order_topology.t5_space`. -/
def ord_t5_nhd (s t : set α) : set α :=
⋃ x ∈ s, ord_connected_component (tᶜ ∩ (ord_connected_section $ ord_separating_set s t)ᶜ) x
lemma disjoint_ord_t5_nhd : disjoint (ord_t5_nhd s t) (ord_t5_nhd t s) :=
begin
rw disjoint_iff_inf_le,
rintro x ⟨hx₁, hx₂⟩,
rcases mem_Union₂.1 hx₁ with ⟨a, has, ha⟩, clear hx₁,
rcases mem_Union₂.1 hx₂ with ⟨b, hbt, hb⟩, clear hx₂,
rw [mem_ord_connected_component, subset_inter_iff] at ha hb,
wlog hab : a ≤ b := le_total a b using [a b s t, b a t s] tactic.skip,
rotate, from λ h₁ h₂ h₃ h₄, this h₂ h₁ h₄ h₃,
cases ha with ha ha', cases hb with hb hb',
have hsub : [a, b] ⊆ (ord_separating_set s t).ord_connected_sectionᶜ,
{ rw [ord_separating_set_comm, uIcc_comm] at hb',
calc [a, b] ⊆ [a, x] ∪ [x, b] : uIcc_subset_uIcc_union_uIcc
... ⊆ (ord_separating_set s t).ord_connected_sectionᶜ : union_subset ha' hb' },
clear ha' hb',
cases le_total x a with hxa hax,
{ exact hb (Icc_subset_uIcc' ⟨hxa, hab⟩) has },
cases le_total b x with hbx hxb,
{ exact ha (Icc_subset_uIcc ⟨hab, hbx⟩) hbt },
have : x ∈ ord_separating_set s t,
{ exact ⟨mem_Union₂.2 ⟨a, has, ha⟩, mem_Union₂.2 ⟨b, hbt, hb⟩⟩ },
lift x to ord_separating_set s t using this,
suffices : ord_connected_component (ord_separating_set s t) x ⊆ [a, b],
from hsub (this $ ord_connected_proj_mem_ord_connected_component _ _) (mem_range_self _),
rintros y (hy : [↑x, y] ⊆ ord_separating_set s t),
rw [uIcc_of_le hab, mem_Icc, ← not_lt, ← not_lt],
exact ⟨λ hya, disjoint_left.1 disjoint_left_ord_separating_set has
(hy $ Icc_subset_uIcc' ⟨hya.le, hax⟩),
λ hyb, disjoint_left.1 disjoint_right_ord_separating_set hbt
(hy $ Icc_subset_uIcc ⟨hxb, hyb.le⟩)⟩
end
end set
|
35c525846fc6a553b729808a7ae2ee1f6befa49d | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/282.lean | 5379b17f7c9872d731a42b841e38c3e4949f82b4 | [
"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 | 341 | lean | open Classical
inductive S where
| B
| I
open S
inductive Expr : S → Type where
| lit : Int → Expr I
| eq {s : S} : Expr s → Expr s → Expr B
def Val : S → Type
| B => Bool
| I => Int
noncomputable def Expr.eval : {s : S} → Expr s → Val s
| _, lit n => n
| _, eq e₁ e₂ => decide (e₁.eval = e₂.eval)
|
26c3f86e43caacac66c2547b8477fb9d3e943723 | f4bff2062c030df03d65e8b69c88f79b63a359d8 | /src/game/sets/sqrtOfTwo.lean | ec09feb09739409dee1d6abddaa45c2dd9ee0139 | [
"Apache-2.0"
] | permissive | adastra7470/real-number-game | 776606961f52db0eb824555ed2f8e16f92216ea3 | f9dcb7d9255a79b57e62038228a23346c2dc301b | refs/heads/master | 1,669,221,575,893 | 1,594,669,800,000 | 1,594,669,800,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,899 | lean | import data.nat.prime
open nat
theorem sqrt_two_irrational_V1 {a b : ℕ} (co : gcd a b = 1) : a^2 ≠ 2 * b^2 :=
assume h : a^2 = 2 * b^2,
have 2 ∣ a^2,
by simp [h],
have ha : 2 ∣ a,
from prime.dvd_of_dvd_pow prime_two this,
-- usually after exists.elim the rest of the proof should be inside
-- parantheses
exists.elim ha (assume c : ℕ, assume aeq : a = 2 * c,
have 2 * (2 * c^2) = 2 * b^2,
by simp [eq.symm h, aeq];
simp [nat.pow_succ, mul_comm, mul_assoc, mul_left_comm],
have 2 * c^2 = b^2,
from eq_of_mul_eq_mul_left dec_trivial this,
have 2 ∣ b^2,
by simp [eq.symm this],
have hb : 2 ∣ b,
from prime.dvd_of_dvd_pow prime_two this,
have 2 ∣ gcd a b,
from dvd_gcd ha hb,
have habs : 2 ∣ (1:ℕ),
by simp * at *,
-- therefore the ) below!!!!
show false, from absurd habs dec_trivial )
--#check sqrt_two_irrational_V1
-- tactics mode
theorem sqrt_two_irrational_V2 {a b : ℕ} (co : gcd a b = 1) : a^2 ≠ 2 * b^2 :=
begin
intro h,
have h1 : 2 ∣ a^2, by simp [h],
have h2 : 2 ∣ a, from prime.dvd_of_dvd_pow prime_two h1,
cases h2 with c aeq,
have h3 : 2 * (2 * c^2) = 2 * b^2,
by simp [eq.symm h, aeq];
simp [nat.pow_succ, mul_comm, mul_assoc, mul_left_comm],
have h4 : 2 * c^2 = b^2,
from eq_of_mul_eq_mul_left dec_trivial h3,
have h5 : 2 ∣ b^2,
by simp [eq.symm h4],
have hb : 2 ∣ b,
from prime.dvd_of_dvd_pow prime_two h5,
have h6 : 2 ∣ gcd a b, from dvd_gcd (exists.intro c aeq) hb,
have habs : 2 ∣ (1:ℕ), by simp * at *,
exact absurd habs dec_trivial, done
end
-- using let (it may introduce a bug due to _let_match hypothesis)
theorem sqrt_two_irrational_V3 {a b : ℕ} (co : gcd a b = 1) : a^2 ≠ 2 * b^2 :=
assume h : a^2 = 2 * b^2,
have 2 ∣ a^2,
by simp [h],
have ha : 2 ∣ a,
from prime.dvd_of_dvd_pow prime_two this,
let ⟨c, aeq⟩ := ha in
have 2 * (2 * c^2) = 2 * b^2,
by simp [eq.symm h, aeq];
simp [nat.pow_succ, mul_comm, mul_assoc, mul_left_comm],
have 2 * c^2 = b^2,
from eq_of_mul_eq_mul_left dec_trivial this,
have 2 ∣ b^2,
by simp [eq.symm this],
have hb : 2 ∣ b,
from prime.dvd_of_dvd_pow prime_two this,
have 2 ∣ gcd a b,
from dvd_gcd ha hb,
have habs : 2 ∣ (1:ℕ),
by clear_aux_decl; simp * at *, -- replaces simp * at *,
show false, from absurd habs dec_trivial
-- variant with match, needs end to finish
theorem sqrt_two_irrational_V4 {a b : ℕ} (co : gcd a b = 1) : a^2 ≠ 2 * b^2 :=
assume h : a^2 = 2 * b^2,
have 2 ∣ a^2,
by simp [h],
have ha : 2 ∣ a,
from prime.dvd_of_dvd_pow prime_two this,
match ha with | ⟨c, aeq⟩ :=
have 2 * (2 * c^2) = 2 * b^2,
by simp [eq.symm h, aeq];
simp [nat.pow_succ, mul_comm, mul_assoc, mul_left_comm],
have 2 * c^2 = b^2,
from eq_of_mul_eq_mul_left dec_trivial this,
have 2 ∣ b^2,
by simp [eq.symm this],
have hb : 2 ∣ b,
from prime.dvd_of_dvd_pow prime_two this,
have 2 ∣ gcd a b,
from dvd_gcd ha hb,
have habs : 2 ∣ (1:ℕ),
by clear_aux_decl; simp * at *, -- replaces simp * at *,
show false, from absurd habs dec_trivial
end
theorem sqrt_two_irrational {a b : ℕ} (co : gcd a b = 1) :
a^2 ≠ 2 * b^2 :=
assume h : a^2 = 2 * b^2,
have 2 ∣ a^2,
by simp [h],
have 2 ∣ a,
from prime.dvd_of_dvd_pow prime_two this,
exists.elim this $
assume (c : nat) (aeq : a = 2 * c),
have 2 * (2 * c^2) = 2 * b^2,
by simp [eq.symm h, aeq];
simp [nat.pow_succ, mul_comm, mul_assoc, mul_left_comm],
have 2 * c^2 = b^2,
from eq_of_mul_eq_mul_left dec_trivial this,
have 2 ∣ b^2,
by simp [eq.symm this],
have 2 ∣ b,
from prime.dvd_of_dvd_pow prime_two this,
have 2 ∣ gcd a b,
from dvd_gcd ‹2 ∣ a› ‹2 ∣ b›,
have 2 ∣ (1 : ℕ),
by simp * at *,
show false, from absurd ‹2 ∣ 1› dec_trivial
--#check sqrt_two_irrational
|
817cb3c0c01a91998b302b8f3a966d50f70d847b | 94e33a31faa76775069b071adea97e86e218a8ee | /src/order/hom/basic.lean | 3a6b5fd94291f1efb7142c689e53787f4ef6c760 | [
"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 | 39,532 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import logic.equiv.option
import order.rel_iso
import tactic.monotonicity.basic
/-!
# Order homomorphisms
This file defines order homomorphisms, which are bundled monotone functions. A preorder
homomorphism `f : α →o β` is a function `α → β` along with a proof that `∀ x y, x ≤ y → f x ≤ f y`.
## Main definitions
In this file we define the following bundled monotone maps:
* `order_hom α β` a.k.a. `α →o β`: Preorder homomorphism.
An `order_hom α β` is a function `f : α → β` such that `a₁ ≤ a₂ → f a₁ ≤ f a₂`
* `order_embedding α β` a.k.a. `α ↪o β`: Relation embedding.
An `order_embedding α β` is an embedding `f : α ↪ β` such that `a ≤ b ↔ f a ≤ f b`.
Defined as an abbreviation of `@rel_embedding α β (≤) (≤)`.
* `order_iso`: Relation isomorphism.
An `order_iso α β` is an equivalence `f : α ≃ β` such that `a ≤ b ↔ f a ≤ f b`.
Defined as an abbreviation of `@rel_iso α β (≤) (≤)`.
We also define many `order_hom`s. In some cases we define two versions, one with `ₘ` suffix and
one without it (e.g., `order_hom.compₘ` and `order_hom.comp`). This means that the former
function is a "more bundled" version of the latter. We can't just drop the "less bundled" version
because the more bundled version usually does not work with dot notation.
* `order_hom.id`: identity map as `α →o α`;
* `order_hom.curry`: an order isomorphism between `α × β →o γ` and `α →o β →o γ`;
* `order_hom.comp`: composition of two bundled monotone maps;
* `order_hom.compₘ`: composition of bundled monotone maps as a bundled monotone map;
* `order_hom.const`: constant function as a bundled monotone map;
* `order_hom.prod`: combine `α →o β` and `α →o γ` into `α →o β × γ`;
* `order_hom.prodₘ`: a more bundled version of `order_hom.prod`;
* `order_hom.prod_iso`: order isomorphism between `α →o β × γ` and `(α →o β) × (α →o γ)`;
* `order_hom.diag`: diagonal embedding of `α` into `α × α` as a bundled monotone map;
* `order_hom.on_diag`: restrict a monotone map `α →o α →o β` to the diagonal;
* `order_hom.fst`: projection `prod.fst : α × β → α` as a bundled monotone map;
* `order_hom.snd`: projection `prod.snd : α × β → β` as a bundled monotone map;
* `order_hom.prod_map`: `prod.map f g` as a bundled monotone map;
* `pi.eval_order_hom`: evaluation of a function at a point `function.eval i` as a bundled
monotone map;
* `order_hom.coe_fn_hom`: coercion to function as a bundled monotone map;
* `order_hom.apply`: application of a `order_hom` at a point as a bundled monotone map;
* `order_hom.pi`: combine a family of monotone maps `f i : α →o π i` into a monotone map
`α →o Π i, π i`;
* `order_hom.pi_iso`: order isomorphism between `α →o Π i, π i` and `Π i, α →o π i`;
* `order_hom.subtyle.val`: embedding `subtype.val : subtype p → α` as a bundled monotone map;
* `order_hom.dual`: reinterpret a monotone map `α →o β` as a monotone map `αᵒᵈ →o βᵒᵈ`;
* `order_hom.dual_iso`: order isomorphism between `α →o β` and `(αᵒᵈ →o βᵒᵈ)ᵒᵈ`;
* `order_iso.compl`: order isomorphism `α ≃o αᵒᵈ` given by taking complements in a
boolean algebra;
We also define two functions to convert other bundled maps to `α →o β`:
* `order_embedding.to_order_hom`: convert `α ↪o β` to `α →o β`;
* `rel_hom.to_order_hom`: convert a `rel_hom` between strict orders to a `order_hom`.
## Tags
monotone map, bundled morphism
-/
open order_dual
variables {F α β γ δ : Type*}
/-- Bundled monotone (aka, increasing) function -/
structure order_hom (α β : Type*) [preorder α] [preorder β] :=
(to_fun : α → β)
(monotone' : monotone to_fun)
infixr ` →o `:25 := order_hom
/-- An order embedding is an embedding `f : α ↪ β` such that `a ≤ b ↔ (f a) ≤ (f b)`.
This definition is an abbreviation of `rel_embedding (≤) (≤)`. -/
abbreviation order_embedding (α β : Type*) [has_le α] [has_le β] :=
@rel_embedding α β (≤) (≤)
infix ` ↪o `:25 := order_embedding
/-- An order isomorphism is an equivalence such that `a ≤ b ↔ (f a) ≤ (f b)`.
This definition is an abbreviation of `rel_iso (≤) (≤)`. -/
abbreviation order_iso (α β : Type*) [has_le α] [has_le β] := @rel_iso α β (≤) (≤)
infix ` ≃o `:25 := order_iso
/-- `order_hom_class F α b` asserts that `F` is a type of `≤`-preserving morphisms. -/
abbreviation order_hom_class (F : Type*) (α β : out_param Type*) [has_le α] [has_le β] :=
rel_hom_class F ((≤) : α → α → Prop) ((≤) : β → β → Prop)
/-- `order_iso_class F α β` states that `F` is a type of order isomorphisms.
You should extend this class when you extend `order_iso`. -/
class order_iso_class (F : Type*) (α β : out_param Type*) [has_le α] [has_le β]
extends equiv_like F α β :=
(map_le_map_iff (f : F) {a b : α} : f a ≤ f b ↔ a ≤ b)
export order_iso_class (map_le_map_iff)
attribute [simp] map_le_map_iff
instance [has_le α] [has_le β] [order_iso_class F α β] : has_coe_t F (α ≃o β) :=
⟨λ f, ⟨f, λ _ _, map_le_map_iff f⟩⟩
@[priority 100] -- See note [lower instance priority]
instance order_iso_class.to_order_hom_class [has_le α] [has_le β] [order_iso_class F α β] :
order_hom_class F α β :=
{ map_rel := λ f a b, (map_le_map_iff f).2, ..equiv_like.to_embedding_like }
namespace order_hom_class
variables [preorder α] [preorder β] [order_hom_class F α β]
protected lemma monotone (f : F) : monotone (f : α → β) := λ _ _, map_rel f
protected lemma mono (f : F) : monotone (f : α → β) := λ _ _, map_rel f
instance : has_coe_t F (α →o β) := ⟨λ f, { to_fun := f, monotone' := order_hom_class.mono _ }⟩
end order_hom_class
section order_iso_class
section has_le
variables [has_le α] [has_le β] [order_iso_class F α β]
@[simp] lemma map_inv_le_iff (f : F) {a : α} {b : β} : equiv_like.inv f b ≤ a ↔ b ≤ f a :=
by { convert (map_le_map_iff _).symm, exact (equiv_like.right_inv _ _).symm }
@[simp] lemma le_map_inv_iff (f : F) {a : α} {b : β} : a ≤ equiv_like.inv f b ↔ f a ≤ b :=
by { convert (map_le_map_iff _).symm, exact (equiv_like.right_inv _ _).symm }
end has_le
variables [preorder α] [preorder β] [order_iso_class F α β]
include β
lemma map_lt_map_iff (f : F) {a b : α} : f a < f b ↔ a < b :=
lt_iff_lt_of_le_iff_le' (map_le_map_iff f) (map_le_map_iff f)
@[simp] lemma map_inv_lt_iff (f : F) {a : α} {b : β} : equiv_like.inv f b < a ↔ b < f a :=
by { convert (map_lt_map_iff _).symm, exact (equiv_like.right_inv _ _).symm }
@[simp] lemma lt_map_inv_iff (f : F) {a : α} {b : β} : a < equiv_like.inv f b ↔ f a < b :=
by { convert (map_lt_map_iff _).symm, exact (equiv_like.right_inv _ _).symm }
end order_iso_class
namespace order_hom
variables [preorder α] [preorder β] [preorder γ] [preorder δ]
/-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun`
directly. -/
instance : has_coe_to_fun (α →o β) (λ _, α → β) := ⟨order_hom.to_fun⟩
initialize_simps_projections order_hom (to_fun → coe)
protected lemma monotone (f : α →o β) : monotone f := f.monotone'
protected lemma mono (f : α →o β) : monotone f := f.monotone
instance : order_hom_class (α →o β) α β :=
{ coe := to_fun,
coe_injective' := λ f g h, by { cases f, cases g, congr' },
map_rel := λ f, f.monotone }
@[simp] lemma to_fun_eq_coe {f : α →o β} : f.to_fun = f := rfl
@[simp] lemma coe_fun_mk {f : α → β} (hf : _root_.monotone f) : (mk f hf : α → β) = f := rfl
@[ext] -- See library note [partially-applied ext lemmas]
lemma ext (f g : α →o β) (h : (f : α → β) = g) : f = g := fun_like.coe_injective h
lemma coe_eq (f : α →o β) : coe f = f := by ext ; refl
/-- One can lift an unbundled monotone function to a bundled one. -/
instance : can_lift (α → β) (α →o β) :=
{ coe := coe_fn,
cond := monotone,
prf := λ f h, ⟨⟨f, h⟩, rfl⟩ }
/-- Copy of an `order_hom` with a new `to_fun` equal to the old one. Useful to fix definitional
equalities. -/
protected def copy (f : α →o β) (f' : α → β) (h : f' = f) : α →o β := ⟨f', h.symm.subst f.monotone'⟩
/-- The identity function as bundled monotone function. -/
@[simps {fully_applied := ff}]
def id : α →o α := ⟨id, monotone_id⟩
instance : inhabited (α →o α) := ⟨id⟩
/-- The preorder structure of `α →o β` is pointwise inequality: `f ≤ g ↔ ∀ a, f a ≤ g a`. -/
instance : preorder (α →o β) :=
@preorder.lift (α →o β) (α → β) _ coe_fn
instance {β : Type*} [partial_order β] : partial_order (α →o β) :=
@partial_order.lift (α →o β) (α → β) _ coe_fn ext
lemma le_def {f g : α →o β} : f ≤ g ↔ ∀ x, f x ≤ g x := iff.rfl
@[simp, norm_cast] lemma coe_le_coe {f g : α →o β} : (f : α → β) ≤ g ↔ f ≤ g := iff.rfl
@[simp] lemma mk_le_mk {f g : α → β} {hf hg} : mk f hf ≤ mk g hg ↔ f ≤ g := iff.rfl
@[mono] lemma apply_mono {f g : α →o β} {x y : α} (h₁ : f ≤ g) (h₂ : x ≤ y) :
f x ≤ g y :=
(h₁ x).trans $ g.mono h₂
/-- Curry/uncurry as an order isomorphism between `α × β →o γ` and `α →o β →o γ`. -/
def curry : (α × β →o γ) ≃o (α →o β →o γ) :=
{ to_fun := λ f, ⟨λ x, ⟨function.curry f x, λ y₁ y₂ h, f.mono ⟨le_rfl, h⟩⟩,
λ x₁ x₂ h y, f.mono ⟨h, le_rfl⟩⟩,
inv_fun := λ f, ⟨function.uncurry (λ x, f x), λ x y h, (f.mono h.1 x.2).trans $ (f y.1).mono h.2⟩,
left_inv := λ f, by { ext ⟨x, y⟩, refl },
right_inv := λ f, by { ext x y, refl },
map_rel_iff' := λ f g, by simp [le_def] }
@[simp] lemma curry_apply (f : α × β →o γ) (x : α) (y : β) : curry f x y = f (x, y) := rfl
@[simp] lemma curry_symm_apply (f : α →o β →o γ) (x : α × β) : curry.symm f x = f x.1 x.2 := rfl
/-- The composition of two bundled monotone functions. -/
@[simps {fully_applied := ff}]
def comp (g : β →o γ) (f : α →o β) : α →o γ := ⟨g ∘ f, g.mono.comp f.mono⟩
@[mono] lemma comp_mono ⦃g₁ g₂ : β →o γ⦄ (hg : g₁ ≤ g₂) ⦃f₁ f₂ : α →o β⦄ (hf : f₁ ≤ f₂) :
g₁.comp f₁ ≤ g₂.comp f₂ :=
λ x, (hg _).trans (g₂.mono $ hf _)
/-- The composition of two bundled monotone functions, a fully bundled version. -/
@[simps {fully_applied := ff}]
def compₘ : (β →o γ) →o (α →o β) →o α →o γ :=
curry ⟨λ f : (β →o γ) × (α →o β), f.1.comp f.2, λ f₁ f₂ h, comp_mono h.1 h.2⟩
@[simp] lemma comp_id (f : α →o β) : comp f id = f :=
by { ext, refl }
@[simp] lemma id_comp (f : α →o β) : comp id f = f :=
by { ext, refl }
/-- Constant function bundled as a `order_hom`. -/
@[simps {fully_applied := ff}]
def const (α : Type*) [preorder α] {β : Type*} [preorder β] : β →o α →o β :=
{ to_fun := λ b, ⟨function.const α b, λ _ _ _, le_rfl⟩,
monotone' := λ b₁ b₂ h x, h }
@[simp] lemma const_comp (f : α →o β) (c : γ) : (const β c).comp f = const α c := rfl
@[simp] lemma comp_const (γ : Type*) [preorder γ] (f : α →o β) (c : α) :
f.comp (const γ c) = const γ (f c) := rfl
/-- Given two bundled monotone maps `f`, `g`, `f.prod g` is the map `x ↦ (f x, g x)` bundled as a
`order_hom`. -/
@[simps] protected def prod (f : α →o β) (g : α →o γ) : α →o (β × γ) :=
⟨λ x, (f x, g x), λ x y h, ⟨f.mono h, g.mono h⟩⟩
@[mono] lemma prod_mono {f₁ f₂ : α →o β} (hf : f₁ ≤ f₂) {g₁ g₂ : α →o γ} (hg : g₁ ≤ g₂) :
f₁.prod g₁ ≤ f₂.prod g₂ :=
λ x, prod.le_def.2 ⟨hf _, hg _⟩
lemma comp_prod_comp_same (f₁ f₂ : β →o γ) (g : α →o β) :
(f₁.comp g).prod (f₂.comp g) = (f₁.prod f₂).comp g :=
rfl
/-- Given two bundled monotone maps `f`, `g`, `f.prod g` is the map `x ↦ (f x, g x)` bundled as a
`order_hom`. This is a fully bundled version. -/
@[simps] def prodₘ : (α →o β) →o (α →o γ) →o α →o β × γ :=
curry ⟨λ f : (α →o β) × (α →o γ), f.1.prod f.2, λ f₁ f₂ h, prod_mono h.1 h.2⟩
/-- Diagonal embedding of `α` into `α × α` as a `order_hom`. -/
@[simps] def diag : α →o α × α := id.prod id
/-- Restriction of `f : α →o α →o β` to the diagonal. -/
@[simps {simp_rhs := tt}] def on_diag (f : α →o α →o β) : α →o β := (curry.symm f).comp diag
/-- `prod.fst` as a `order_hom`. -/
@[simps] def fst : α × β →o α := ⟨prod.fst, λ x y h, h.1⟩
/-- `prod.snd` as a `order_hom`. -/
@[simps] def snd : α × β →o β := ⟨prod.snd, λ x y h, h.2⟩
@[simp] lemma fst_prod_snd : (fst : α × β →o α).prod snd = id :=
by { ext ⟨x, y⟩ : 2, refl }
@[simp] lemma fst_comp_prod (f : α →o β) (g : α →o γ) : fst.comp (f.prod g) = f := ext _ _ rfl
@[simp] lemma snd_comp_prod (f : α →o β) (g : α →o γ) : snd.comp (f.prod g) = g := ext _ _ rfl
/-- Order isomorphism between the space of monotone maps to `β × γ` and the product of the spaces
of monotone maps to `β` and `γ`. -/
@[simps] def prod_iso : (α →o β × γ) ≃o (α →o β) × (α →o γ) :=
{ to_fun := λ f, (fst.comp f, snd.comp f),
inv_fun := λ f, f.1.prod f.2,
left_inv := λ f, by ext; refl,
right_inv := λ f, by ext; refl,
map_rel_iff' := λ f g, forall_and_distrib.symm }
/-- `prod.map` of two `order_hom`s as a `order_hom`. -/
@[simps] def prod_map (f : α →o β) (g : γ →o δ) : α × γ →o β × δ :=
⟨prod.map f g, λ x y h, ⟨f.mono h.1, g.mono h.2⟩⟩
variables {ι : Type*} {π : ι → Type*} [Π i, preorder (π i)]
/-- Evaluation of an unbundled function at a point (`function.eval`) as a `order_hom`. -/
@[simps {fully_applied := ff}]
def _root_.pi.eval_order_hom (i : ι) : (Π j, π j) →o π i :=
⟨function.eval i, function.monotone_eval i⟩
/-- The "forgetful functor" from `α →o β` to `α → β` that takes the underlying function,
is monotone. -/
@[simps {fully_applied := ff}] def coe_fn_hom : (α →o β) →o (α → β) :=
{ to_fun := λ f, f,
monotone' := λ x y h, h }
/-- Function application `λ f, f a` (for fixed `a`) is a monotone function from the
monotone function space `α →o β` to `β`. See also `pi.eval_order_hom`. -/
@[simps {fully_applied := ff}] def apply (x : α) : (α →o β) →o β :=
(pi.eval_order_hom x).comp coe_fn_hom
/-- Construct a bundled monotone map `α →o Π i, π i` from a family of monotone maps
`f i : α →o π i`. -/
@[simps] def pi (f : Π i, α →o π i) : α →o (Π i, π i) :=
⟨λ x i, f i x, λ x y h i, (f i).mono h⟩
/-- Order isomorphism between bundled monotone maps `α →o Π i, π i` and families of bundled monotone
maps `Π i, α →o π i`. -/
@[simps] def pi_iso : (α →o Π i, π i) ≃o Π i, α →o π i :=
{ to_fun := λ f i, (pi.eval_order_hom i).comp f,
inv_fun := pi,
left_inv := λ f, by { ext x i, refl },
right_inv := λ f, by { ext x i, refl },
map_rel_iff' := λ f g, forall_swap }
/-- `subtype.val` as a bundled monotone function. -/
@[simps {fully_applied := ff}]
def subtype.val (p : α → Prop) : subtype p →o α :=
⟨subtype.val, λ x y h, h⟩
-- TODO[gh-6025]: make this a global instance once safe to do so
/-- There is a unique monotone map from a subsingleton to itself. -/
local attribute [instance]
def unique [subsingleton α] : unique (α →o α) :=
{ default := order_hom.id, uniq := λ a, ext _ _ (subsingleton.elim _ _) }
lemma order_hom_eq_id [subsingleton α] (g : α →o α) : g = order_hom.id :=
subsingleton.elim _ _
/-- Reinterpret a bundled monotone function as a monotone function between dual orders. -/
@[simps] protected def dual : (α →o β) ≃ (αᵒᵈ →o βᵒᵈ) :=
{ to_fun := λ f, ⟨order_dual.to_dual ∘ f ∘ order_dual.of_dual, f.mono.dual⟩,
inv_fun := λ f, ⟨order_dual.of_dual ∘ f ∘ order_dual.to_dual, f.mono.dual⟩,
left_inv := λ f, ext _ _ rfl,
right_inv := λ f, ext _ _ rfl }
@[simp] lemma dual_id : (order_hom.id : α →o α).dual = order_hom.id := rfl
@[simp] lemma dual_comp (g : β →o γ) (f : α →o β) : (g.comp f).dual = g.dual.comp f.dual := rfl
@[simp] lemma symm_dual_id : order_hom.dual.symm order_hom.id = (order_hom.id : α →o α) := rfl
@[simp] lemma symm_dual_comp (g : βᵒᵈ →o γᵒᵈ) (f : αᵒᵈ →o βᵒᵈ) :
order_hom.dual.symm (g.comp f) = (order_hom.dual.symm g).comp (order_hom.dual.symm f) := rfl
/-- `order_hom.dual` as an order isomorphism. -/
def dual_iso (α β : Type*) [preorder α] [preorder β] : (α →o β) ≃o (αᵒᵈ →o βᵒᵈ)ᵒᵈ :=
{ to_equiv := order_hom.dual.trans order_dual.to_dual,
map_rel_iff' := λ f g, iff.rfl }
/-- Lift an order homomorphism `f : α →o β` to an order homomorphism `with_bot α →o with_bot β`. -/
@[simps { fully_applied := ff }]
protected def with_bot_map (f : α →o β) : with_bot α →o with_bot β :=
⟨with_bot.map f, f.mono.with_bot_map⟩
/-- Lift an order homomorphism `f : α →o β` to an order homomorphism `with_top α →o with_top β`. -/
@[simps { fully_applied := ff }]
protected def with_top_map (f : α →o β) : with_top α →o with_top β :=
⟨with_top.map f, f.mono.with_top_map⟩
end order_hom
/-- Embeddings of partial orders that preserve `<` also preserve `≤`. -/
def rel_embedding.order_embedding_of_lt_embedding [partial_order α] [partial_order β]
(f : ((<) : α → α → Prop) ↪r ((<) : β → β → Prop)) :
α ↪o β :=
{ map_rel_iff' := by { intros, simp [le_iff_lt_or_eq,f.map_rel_iff, f.injective.eq_iff] }, .. f }
@[simp]
lemma rel_embedding.order_embedding_of_lt_embedding_apply [partial_order α] [partial_order β]
{f : ((<) : α → α → Prop) ↪r ((<) : β → β → Prop)} {x : α} :
rel_embedding.order_embedding_of_lt_embedding f x = f x := rfl
namespace order_embedding
variables [preorder α] [preorder β] (f : α ↪o β)
/-- `<` is preserved by order embeddings of preorders. -/
def lt_embedding : ((<) : α → α → Prop) ↪r ((<) : β → β → Prop) :=
{ map_rel_iff' := by intros; simp [lt_iff_le_not_le, f.map_rel_iff], .. f }
@[simp] lemma lt_embedding_apply (x : α) : f.lt_embedding x = f x := rfl
@[simp] theorem le_iff_le {a b} : (f a) ≤ (f b) ↔ a ≤ b := f.map_rel_iff
@[simp] theorem lt_iff_lt {a b} : f a < f b ↔ a < b :=
f.lt_embedding.map_rel_iff
@[simp] lemma eq_iff_eq {a b} : f a = f b ↔ a = b := f.injective.eq_iff
protected theorem monotone : monotone f := order_hom_class.monotone f
protected theorem strict_mono : strict_mono f := λ x y, f.lt_iff_lt.2
protected theorem acc (a : α) : acc (<) (f a) → acc (<) a :=
f.lt_embedding.acc a
protected theorem well_founded :
well_founded ((<) : β → β → Prop) → well_founded ((<) : α → α → Prop) :=
f.lt_embedding.well_founded
protected theorem is_well_order [is_well_order β (<)] : is_well_order α (<) :=
f.lt_embedding.is_well_order
/-- An order embedding is also an order embedding between dual orders. -/
protected def dual : αᵒᵈ ↪o βᵒᵈ :=
⟨f.to_embedding, λ a b, f.map_rel_iff⟩
/-- A version of `with_bot.map` for order embeddings. -/
@[simps { fully_applied := ff }]
protected def with_bot_map (f : α ↪o β) : with_bot α ↪o with_bot β :=
{ to_fun := with_bot.map f,
map_rel_iff' := with_bot.map_le_iff f (λ a b, f.map_rel_iff),
.. f.to_embedding.option_map }
/-- A version of `with_top.map` for order embeddings. -/
@[simps { fully_applied := ff }]
protected def with_top_map (f : α ↪o β) : with_top α ↪o with_top β :=
{ to_fun := with_top.map f,
.. f.dual.with_bot_map.dual }
/--
To define an order embedding from a partial order to a preorder it suffices to give a function
together with a proof that it satisfies `f a ≤ f b ↔ a ≤ b`.
-/
def of_map_le_iff {α β} [partial_order α] [preorder β] (f : α → β)
(hf : ∀ a b, f a ≤ f b ↔ a ≤ b) : α ↪o β :=
rel_embedding.of_map_rel_iff f hf
@[simp] lemma coe_of_map_le_iff {α β} [partial_order α] [preorder β] {f : α → β} (h) :
⇑(of_map_le_iff f h) = f := rfl
/-- A strictly monotone map from a linear order is an order embedding. --/
def of_strict_mono {α β} [linear_order α] [preorder β] (f : α → β)
(h : strict_mono f) : α ↪o β :=
of_map_le_iff f (λ _ _, h.le_iff_le)
@[simp] lemma coe_of_strict_mono {α β} [linear_order α] [preorder β] {f : α → β}
(h : strict_mono f) : ⇑(of_strict_mono f h) = f := rfl
/-- Embedding of a subtype into the ambient type as an `order_embedding`. -/
@[simps {fully_applied := ff}] def subtype (p : α → Prop) : subtype p ↪o α :=
⟨function.embedding.subtype p, λ x y, iff.rfl⟩
/-- Convert an `order_embedding` to a `order_hom`. -/
@[simps {fully_applied := ff}]
def to_order_hom {X Y : Type*} [preorder X] [preorder Y] (f : X ↪o Y) : X →o Y :=
{ to_fun := f,
monotone' := f.monotone }
end order_embedding
section rel_hom
variables [partial_order α] [preorder β]
namespace rel_hom
variables (f : ((<) : α → α → Prop) →r ((<) : β → β → Prop))
/-- A bundled expression of the fact that a map between partial orders that is strictly monotone
is weakly monotone. -/
@[simps {fully_applied := ff}]
def to_order_hom : α →o β :=
{ to_fun := f,
monotone' := strict_mono.monotone (λ x y, f.map_rel), }
end rel_hom
lemma rel_embedding.to_order_hom_injective (f : ((<) : α → α → Prop) ↪r ((<) : β → β → Prop)) :
function.injective (f : ((<) : α → α → Prop) →r ((<) : β → β → Prop)).to_order_hom :=
λ _ _ h, f.injective h
end rel_hom
namespace order_iso
section has_le
variables [has_le α] [has_le β] [has_le γ]
instance : order_iso_class (α ≃o β) α β :=
{ coe := λ f, f.to_fun,
inv := λ f, f.inv_fun,
left_inv := λ f, f.left_inv,
right_inv := λ f, f.right_inv,
coe_injective' := λ f g h₁ h₂, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' },
map_le_map_iff := λ f, f.map_rel_iff' }
@[simp] lemma to_fun_eq_coe {f : α ≃o β} : f.to_fun = f := rfl
@[ext] -- See note [partially-applied ext lemmas]
lemma ext {f g : α ≃o β} (h : (f : α → β) = g) : f = g := fun_like.coe_injective h
/-- Reinterpret an order isomorphism as an order embedding. -/
def to_order_embedding (e : α ≃o β) : α ↪o β :=
e.to_rel_embedding
@[simp] lemma coe_to_order_embedding (e : α ≃o β) :
⇑(e.to_order_embedding) = e := rfl
protected lemma bijective (e : α ≃o β) : function.bijective e := e.to_equiv.bijective
protected lemma injective (e : α ≃o β) : function.injective e := e.to_equiv.injective
protected lemma surjective (e : α ≃o β) : function.surjective e := e.to_equiv.surjective
@[simp] lemma range_eq (e : α ≃o β) : set.range e = set.univ := e.surjective.range_eq
@[simp] lemma apply_eq_iff_eq (e : α ≃o β) {x y : α} : e x = e y ↔ x = y :=
e.to_equiv.apply_eq_iff_eq
/-- Identity order isomorphism. -/
def refl (α : Type*) [has_le α] : α ≃o α := rel_iso.refl (≤)
@[simp] lemma coe_refl : ⇑(refl α) = id := rfl
@[simp] lemma refl_apply (x : α) : refl α x = x := rfl
@[simp] lemma refl_to_equiv : (refl α).to_equiv = equiv.refl α := rfl
/-- Inverse of an order isomorphism. -/
def symm (e : α ≃o β) : β ≃o α := e.symm
@[simp] lemma apply_symm_apply (e : α ≃o β) (x : β) : e (e.symm x) = x :=
e.to_equiv.apply_symm_apply x
@[simp] lemma symm_apply_apply (e : α ≃o β) (x : α) : e.symm (e x) = x :=
e.to_equiv.symm_apply_apply x
@[simp] lemma symm_refl (α : Type*) [has_le α] : (refl α).symm = refl α := rfl
lemma apply_eq_iff_eq_symm_apply (e : α ≃o β) (x : α) (y : β) : e x = y ↔ x = e.symm y :=
e.to_equiv.apply_eq_iff_eq_symm_apply
theorem symm_apply_eq (e : α ≃o β) {x : α} {y : β} : e.symm y = x ↔ y = e x :=
e.to_equiv.symm_apply_eq
@[simp] lemma symm_symm (e : α ≃o β) : e.symm.symm = e := by { ext, refl }
lemma symm_injective : function.injective (symm : (α ≃o β) → (β ≃o α)) :=
λ e e' h, by rw [← e.symm_symm, h, e'.symm_symm]
@[simp] lemma to_equiv_symm (e : α ≃o β) : e.to_equiv.symm = e.symm.to_equiv := rfl
@[simp] lemma symm_image_image (e : α ≃o β) (s : set α) : e.symm '' (e '' s) = s :=
e.to_equiv.symm_image_image s
@[simp] lemma image_symm_image (e : α ≃o β) (s : set β) : e '' (e.symm '' s) = s :=
e.to_equiv.image_symm_image s
lemma image_eq_preimage (e : α ≃o β) (s : set α) : e '' s = e.symm ⁻¹' s :=
e.to_equiv.image_eq_preimage s
@[simp] lemma preimage_symm_preimage (e : α ≃o β) (s : set α) : e ⁻¹' (e.symm ⁻¹' s) = s :=
e.to_equiv.preimage_symm_preimage s
@[simp] lemma symm_preimage_preimage (e : α ≃o β) (s : set β) : e.symm ⁻¹' (e ⁻¹' s) = s :=
e.to_equiv.symm_preimage_preimage s
@[simp] lemma image_preimage (e : α ≃o β) (s : set β) : e '' (e ⁻¹' s) = s :=
e.to_equiv.image_preimage s
@[simp] lemma preimage_image (e : α ≃o β) (s : set α) : e ⁻¹' (e '' s) = s :=
e.to_equiv.preimage_image s
/-- Composition of two order isomorphisms is an order isomorphism. -/
@[trans] def trans (e : α ≃o β) (e' : β ≃o γ) : α ≃o γ := e.trans e'
@[simp] lemma coe_trans (e : α ≃o β) (e' : β ≃o γ) : ⇑(e.trans e') = e' ∘ e := rfl
@[simp] lemma trans_apply (e : α ≃o β) (e' : β ≃o γ) (x : α) : e.trans e' x = e' (e x) := rfl
@[simp] lemma refl_trans (e : α ≃o β) : (refl α).trans e = e := by { ext x, refl }
@[simp] lemma trans_refl (e : α ≃o β) : e.trans (refl β) = e := by { ext x, refl }
/-- `prod.swap` as an `order_iso`. -/
def prod_comm : (α × β) ≃o (β × α) :=
{ to_equiv := equiv.prod_comm α β,
map_rel_iff' := λ a b, prod.swap_le_swap }
@[simp] lemma coe_prod_comm : ⇑(prod_comm : (α × β) ≃o (β × α)) = prod.swap := rfl
@[simp] lemma prod_comm_symm : (prod_comm : (α × β) ≃o (β × α)).symm = prod_comm := rfl
variables (α)
/-- The order isomorphism between a type and its double dual. -/
def dual_dual : α ≃o αᵒᵈᵒᵈ := refl α
@[simp] lemma coe_dual_dual : ⇑(dual_dual α) = to_dual ∘ to_dual := rfl
@[simp] lemma coe_dual_dual_symm : ⇑(dual_dual α).symm = of_dual ∘ of_dual := rfl
variables {α}
@[simp] lemma dual_dual_apply (a : α) : dual_dual α a = to_dual (to_dual a) := rfl
@[simp] lemma dual_dual_symm_apply (a : αᵒᵈᵒᵈ) : (dual_dual α).symm a = of_dual (of_dual a) := rfl
end has_le
open set
section le
variables [has_le α] [has_le β] [has_le γ]
@[simp] lemma le_iff_le (e : α ≃o β) {x y : α} : e x ≤ e y ↔ x ≤ y := e.map_rel_iff
lemma le_symm_apply (e : α ≃o β) {x : α} {y : β} : x ≤ e.symm y ↔ e x ≤ y :=
e.rel_symm_apply
lemma symm_apply_le (e : α ≃o β) {x : α} {y : β} : e.symm y ≤ x ↔ y ≤ e x :=
e.symm_apply_rel
end le
variables [preorder α] [preorder β] [preorder γ]
protected lemma monotone (e : α ≃o β) : monotone e := e.to_order_embedding.monotone
protected lemma strict_mono (e : α ≃o β) : strict_mono e := e.to_order_embedding.strict_mono
@[simp] lemma lt_iff_lt (e : α ≃o β) {x y : α} : e x < e y ↔ x < y :=
e.to_order_embedding.lt_iff_lt
/-- Converts an `order_iso` into a `rel_iso (<) (<)`. -/
def to_rel_iso_lt (e : α ≃o β): ((<) : α → α → Prop) ≃r ((<) : β → β → Prop) :=
⟨e.to_equiv, λ _ _, lt_iff_lt e⟩
/-- To show that `f : α → β`, `g : β → α` make up an order isomorphism of linear orders,
it suffices to prove `cmp a (g b) = cmp (f a) b`. --/
def of_cmp_eq_cmp {α β} [linear_order α] [linear_order β] (f : α → β) (g : β → α)
(h : ∀ (a : α) (b : β), cmp a (g b) = cmp (f a) b) : α ≃o β :=
have gf : ∀ (a : α), a = g (f a) := by { intro, rw [←cmp_eq_eq_iff, h, cmp_self_eq_eq] },
{ to_fun := f,
inv_fun := g,
left_inv := λ a, (gf a).symm,
right_inv := by { intro, rw [←cmp_eq_eq_iff, ←h, cmp_self_eq_eq] },
map_rel_iff' := by { intros, apply le_iff_le_of_cmp_eq_cmp, convert (h _ _).symm, apply gf } }
/-- To show that `f : α →o β` and `g : β →o α` make up an order isomorphism it is enough to show
that `g` is the inverse of `f`-/
def of_hom_inv {F G : Type*} [order_hom_class F α β] [order_hom_class G β α]
(f : F) (g : G) (h₁ : (f : α →o β).comp (g : β →o α) = order_hom.id)
(h₂ : (g : β →o α).comp (f : α →o β) = order_hom.id) : α ≃o β :=
{ to_fun := f,
inv_fun := g,
left_inv := fun_like.congr_fun h₂,
right_inv := fun_like.congr_fun h₁,
map_rel_iff' := λ a b, ⟨λ h, by { replace h := map_rel g h, rwa [equiv.coe_fn_mk,
(show g (f a) = (g : β →o α).comp (f : α →o β) a, from rfl),
(show g (f b) = (g : β →o α).comp (f : α →o β) b, from rfl), h₂] at h },
λ h, (f : α →o β).monotone h⟩ }
/-- Order isomorphism between two equal sets. -/
def set_congr (s t : set α) (h : s = t) : s ≃o t :=
{ to_equiv := equiv.set_congr h,
map_rel_iff' := λ x y, iff.rfl }
/-- Order isomorphism between `univ : set α` and `α`. -/
def set.univ : (set.univ : set α) ≃o α :=
{ to_equiv := equiv.set.univ α,
map_rel_iff' := λ x y, iff.rfl }
/-- Order isomorphism between `α → β` and `β`, where `α` has a unique element. -/
@[simps to_equiv apply] def fun_unique (α β : Type*) [unique α] [preorder β] :
(α → β) ≃o β :=
{ to_equiv := equiv.fun_unique α β,
map_rel_iff' := λ f g, by simp [pi.le_def, unique.forall_iff] }
@[simp] lemma fun_unique_symm_apply {α β : Type*} [unique α] [preorder β] :
((fun_unique α β).symm : β → α → β) = function.const α := rfl
end order_iso
namespace equiv
variables [preorder α] [preorder β]
/-- If `e` is an equivalence with monotone forward and inverse maps, then `e` is an
order isomorphism. -/
def to_order_iso (e : α ≃ β) (h₁ : monotone e) (h₂ : monotone e.symm) :
α ≃o β :=
⟨e, λ x y, ⟨λ h, by simpa only [e.symm_apply_apply] using h₂ h, λ h, h₁ h⟩⟩
@[simp] lemma coe_to_order_iso (e : α ≃ β) (h₁ : monotone e) (h₂ : monotone e.symm) :
⇑(e.to_order_iso h₁ h₂) = e := rfl
@[simp] lemma to_order_iso_to_equiv (e : α ≃ β) (h₁ : monotone e) (h₂ : monotone e.symm) :
(e.to_order_iso h₁ h₂).to_equiv = e := rfl
end equiv
/-- If a function `f` is strictly monotone on a set `s`, then it defines an order isomorphism
between `s` and its image. -/
protected noncomputable def strict_mono_on.order_iso {α β} [linear_order α] [preorder β]
(f : α → β) (s : set α) (hf : strict_mono_on f s) :
s ≃o f '' s :=
{ to_equiv := hf.inj_on.bij_on_image.equiv _,
map_rel_iff' := λ x y, hf.le_iff_le x.2 y.2 }
namespace strict_mono
variables {α β} [linear_order α] [preorder β]
variables (f : α → β) (h_mono : strict_mono f) (h_surj : function.surjective f)
/-- A strictly monotone function from a linear order is an order isomorphism between its domain and
its range. -/
@[simps apply] protected noncomputable def order_iso : α ≃o set.range f :=
{ to_equiv := equiv.of_injective f h_mono.injective,
map_rel_iff' := λ a b, h_mono.le_iff_le }
/-- A strictly monotone surjective function from a linear order is an order isomorphism. -/
noncomputable def order_iso_of_surjective : α ≃o β :=
(h_mono.order_iso f).trans $ (order_iso.set_congr _ _ h_surj.range_eq).trans order_iso.set.univ
@[simp] lemma coe_order_iso_of_surjective :
(order_iso_of_surjective f h_mono h_surj : α → β) = f :=
rfl
@[simp] lemma order_iso_of_surjective_symm_apply_self (a : α) :
(order_iso_of_surjective f h_mono h_surj).symm (f a) = a :=
(order_iso_of_surjective f h_mono h_surj).symm_apply_apply _
lemma order_iso_of_surjective_self_symm_apply (b : β) :
f ((order_iso_of_surjective f h_mono h_surj).symm b) = b :=
(order_iso_of_surjective f h_mono h_surj).apply_symm_apply _
/-- A strictly monotone function with a right inverse is an order isomorphism. -/
@[simps {fully_applied := false}] def order_iso_of_right_inverse
(g : β → α) (hg : function.right_inverse g f) : α ≃o β :=
{ to_fun := f,
inv_fun := g,
left_inv := λ x, h_mono.injective $ hg _,
right_inv := hg,
.. order_embedding.of_strict_mono f h_mono }
end strict_mono
/-- An order isomorphism is also an order isomorphism between dual orders. -/
protected def order_iso.dual [has_le α] [has_le β] (f : α ≃o β) : αᵒᵈ ≃o βᵒᵈ :=
⟨f.to_equiv, λ _ _, f.map_rel_iff⟩
section lattice_isos
lemma order_iso.map_bot' [has_le α] [partial_order β] (f : α ≃o β) {x : α} {y : β}
(hx : ∀ x', x ≤ x') (hy : ∀ y', y ≤ y') : f x = y :=
by { refine le_antisymm _ (hy _), rw [← f.apply_symm_apply y, f.map_rel_iff], apply hx }
lemma order_iso.map_bot [has_le α] [partial_order β] [order_bot α] [order_bot β] (f : α ≃o β) :
f ⊥ = ⊥ :=
f.map_bot' (λ _, bot_le) (λ _, bot_le)
lemma order_iso.map_top' [has_le α] [partial_order β] (f : α ≃o β) {x : α} {y : β}
(hx : ∀ x', x' ≤ x) (hy : ∀ y', y' ≤ y) : f x = y :=
f.dual.map_bot' hx hy
lemma order_iso.map_top [has_le α] [partial_order β] [order_top α] [order_top β] (f : α ≃o β) :
f ⊤ = ⊤ :=
f.dual.map_bot
lemma order_embedding.map_inf_le [semilattice_inf α] [semilattice_inf β] (f : α ↪o β) (x y : α) :
f (x ⊓ y) ≤ f x ⊓ f y :=
f.monotone.map_inf_le x y
lemma order_embedding.le_map_sup [semilattice_sup α] [semilattice_sup β] (f : α ↪o β) (x y : α) :
f x ⊔ f y ≤ f (x ⊔ y) :=
f.monotone.le_map_sup x y
lemma order_iso.map_inf [semilattice_inf α] [semilattice_inf β] (f : α ≃o β) (x y : α) :
f (x ⊓ y) = f x ⊓ f y :=
begin
refine (f.to_order_embedding.map_inf_le x y).antisymm _,
simpa [← f.symm.le_iff_le] using f.symm.to_order_embedding.map_inf_le (f x) (f y)
end
lemma order_iso.map_sup [semilattice_sup α] [semilattice_sup β] (f : α ≃o β) (x y : α) :
f (x ⊔ y) = f x ⊔ f y :=
f.dual.map_inf x y
/-- Note that this goal could also be stated `(disjoint on f) a b` -/
lemma disjoint.map_order_iso [semilattice_inf α] [order_bot α] [semilattice_inf β] [order_bot β]
{a b : α} (f : α ≃o β) (ha : disjoint a b) : disjoint (f a) (f b) :=
by { rw [disjoint, ←f.map_inf, ←f.map_bot], exact f.monotone ha }
/-- Note that this goal could also be stated `(codisjoint on f) a b` -/
lemma codisjoint.map_order_iso [semilattice_sup α] [order_top α] [semilattice_sup β] [order_top β]
{a b : α} (f : α ≃o β) (ha : codisjoint a b) : codisjoint (f a) (f b) :=
by { rw [codisjoint, ←f.map_sup, ←f.map_top], exact f.monotone ha }
@[simp] lemma disjoint_map_order_iso_iff [semilattice_inf α] [order_bot α] [semilattice_inf β]
[order_bot β] {a b : α} (f : α ≃o β) : disjoint (f a) (f b) ↔ disjoint a b :=
⟨λ h, f.symm_apply_apply a ▸ f.symm_apply_apply b ▸ h.map_order_iso f.symm, λ h, h.map_order_iso f⟩
@[simp] lemma codisjoint_map_order_iso_iff [semilattice_sup α] [order_top α] [semilattice_sup β]
[order_top β] {a b : α} (f : α ≃o β) : codisjoint (f a) (f b) ↔ codisjoint a b :=
⟨λ h, f.symm_apply_apply a ▸ f.symm_apply_apply b ▸ h.map_order_iso f.symm, λ h, h.map_order_iso f⟩
namespace with_bot
/-- Taking the dual then adding `⊥` is the same as adding `⊤` then taking the dual. -/
protected def to_dual_top [has_le α] : with_bot αᵒᵈ ≃o (with_top α)ᵒᵈ := order_iso.refl _
@[simp] lemma to_dual_top_coe [has_le α] (a : α) :
with_bot.to_dual_top ↑(to_dual a) = to_dual (a : with_top α) := rfl
@[simp] lemma to_dual_top_symm_coe [has_le α] (a : α) :
with_bot.to_dual_top.symm (to_dual (a : with_top α)) = ↑(to_dual a) := rfl
end with_bot
namespace with_top
/-- Taking the dual then adding `⊤` is the same as adding `⊥` then taking the dual. -/
protected def to_dual_bot [has_le α] : with_top αᵒᵈ ≃o (with_bot α)ᵒᵈ := order_iso.refl _
@[simp] lemma to_dual_bot_coe [has_le α] (a : α) :
with_top.to_dual_bot ↑(to_dual a) = to_dual (a : with_bot α) := rfl
@[simp] lemma to_dual_bot_symm_coe [has_le α] (a : α) :
with_top.to_dual_bot.symm (to_dual (a : with_bot α)) = ↑(to_dual a) := rfl
end with_top
namespace order_iso
variables [partial_order α] [partial_order β] [partial_order γ]
/-- A version of `equiv.option_congr` for `with_top`. -/
@[simps apply]
def with_top_congr (e : α ≃o β) : with_top α ≃o with_top β :=
{ to_equiv := e.to_equiv.option_congr,
.. e.to_order_embedding.with_top_map }
@[simp] lemma with_top_congr_refl : (order_iso.refl α).with_top_congr = order_iso.refl _ :=
rel_iso.to_equiv_injective equiv.option_congr_refl
@[simp] lemma with_top_congr_symm (e : α ≃o β) : e.with_top_congr.symm = e.symm.with_top_congr :=
rel_iso.to_equiv_injective e.to_equiv.option_congr_symm
@[simp] lemma with_top_congr_trans (e₁ : α ≃o β) (e₂ : β ≃o γ) :
e₁.with_top_congr.trans e₂.with_top_congr = (e₁.trans e₂).with_top_congr :=
rel_iso.to_equiv_injective $ e₁.to_equiv.option_congr_trans e₂.to_equiv
/-- A version of `equiv.option_congr` for `with_bot`. -/
@[simps apply]
def with_bot_congr (e : α ≃o β) :
with_bot α ≃o with_bot β :=
{ to_equiv := e.to_equiv.option_congr,
.. e.to_order_embedding.with_bot_map }
@[simp] lemma with_bot_congr_refl : (order_iso.refl α).with_bot_congr = order_iso.refl _ :=
rel_iso.to_equiv_injective equiv.option_congr_refl
@[simp] lemma with_bot_congr_symm (e : α ≃o β) : e.with_bot_congr.symm = e.symm.with_bot_congr :=
rel_iso.to_equiv_injective e.to_equiv.option_congr_symm
@[simp] lemma with_bot_congr_trans (e₁ : α ≃o β) (e₂ : β ≃o γ) :
e₁.with_bot_congr.trans e₂.with_bot_congr = (e₁.trans e₂).with_bot_congr :=
rel_iso.to_equiv_injective $ e₁.to_equiv.option_congr_trans e₂.to_equiv
end order_iso
section bounded_order
variables [lattice α] [lattice β] [bounded_order α] [bounded_order β] (f : α ≃o β)
include f
lemma order_iso.is_compl {x y : α} (h : is_compl x y) : is_compl (f x) (f y) :=
⟨h.1.map_order_iso _, h.2.map_order_iso _⟩
theorem order_iso.is_compl_iff {x y : α} :
is_compl x y ↔ is_compl (f x) (f y) :=
⟨f.is_compl, λ h, f.symm_apply_apply x ▸ f.symm_apply_apply y ▸ f.symm.is_compl h⟩
lemma order_iso.is_complemented
[is_complemented α] : is_complemented β :=
⟨λ x, begin
obtain ⟨y, hy⟩ := exists_is_compl (f.symm x),
rw ← f.symm_apply_apply y at hy,
refine ⟨f y, f.symm.is_compl_iff.2 hy⟩,
end⟩
theorem order_iso.is_complemented_iff :
is_complemented α ↔ is_complemented β :=
⟨by { introI, exact f.is_complemented }, by { introI, exact f.symm.is_complemented }⟩
end bounded_order
end lattice_isos
section boolean_algebra
variables (α) [boolean_algebra α]
/-- Taking complements as an order isomorphism to the order dual. -/
@[simps]
def order_iso.compl : α ≃o αᵒᵈ :=
{ to_fun := order_dual.to_dual ∘ compl,
inv_fun := compl ∘ order_dual.of_dual,
left_inv := compl_compl,
right_inv := compl_compl,
map_rel_iff' := λ x y, compl_le_compl_iff_le }
theorem compl_strict_anti : strict_anti (compl : α → α) :=
(order_iso.compl α).strict_mono
theorem compl_antitone : antitone (compl : α → α) :=
(order_iso.compl α).monotone
end boolean_algebra
|
17e7a3d73c846f0bee09fa8facf4d385629dce71 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/order/field/canonical/basic.lean | d37ac79c840bc4ca6da3d32fff9f4b79457ea1f2 | [
"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 | 598 | lean | /-
Copyright (c) 2014 Robert Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Lewis, Leonardo de Moura, Mario Carneiro, Floris van Doorn
-/
import algebra.order.field.canonical.defs
/-!
# Lemmas about canonically ordered semifields.
-/
variables {α : Type*}
section canonically_linear_ordered_semifield
variables [canonically_linear_ordered_semifield α] [has_sub α] [has_ordered_sub α]
lemma tsub_div (a b c : α) : (a - b) / c = a / c - b / c := by simp_rw [div_eq_mul_inv, tsub_mul]
end canonically_linear_ordered_semifield
|
5f275f1f1b12d552744540536ba9a663e12fc015 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/algebraic_geometry/prime_spectrum/basic.lean | 9170666db2a7b3f34000cfcf31e9e7045569e701 | [
"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 | 31,001 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import algebra.punit_instances
import linear_algebra.finsupp
import ring_theory.nilpotent
import ring_theory.localization.away
import ring_theory.ideal.prod
import ring_theory.ideal.over
import topology.sets.opens
import topology.sober
/-!
# Prime spectrum of a commutative ring
The prime spectrum of a commutative ring is the type of all prime ideals.
It is naturally endowed with a topology: the Zariski topology.
(It is also naturally endowed with a sheaf of rings,
which is constructed in `algebraic_geometry.structure_sheaf`.)
## Main definitions
* `prime_spectrum R`: The prime spectrum of a commutative ring `R`,
i.e., the set of all prime ideals of `R`.
* `zero_locus s`: The zero locus of a subset `s` of `R`
is the subset of `prime_spectrum R` consisting of all prime ideals that contain `s`.
* `vanishing_ideal t`: The vanishing ideal of a subset `t` of `prime_spectrum R`
is the intersection of points in `t` (viewed as prime ideals).
## Conventions
We denote subsets of rings with `s`, `s'`, etc...
whereas we denote subsets of prime spectra with `t`, `t'`, etc...
## Inspiration/contributors
The contents of this file draw inspiration from
<https://github.com/ramonfmir/lean-scheme>
which has contributions from Ramon Fernandez Mir, Kevin Buzzard, Kenny Lau,
and Chris Hughes (on an earlier repository).
-/
noncomputable theory
open_locale classical
universes u v
variables (R : Type u) [comm_ring R]
/-- The prime spectrum of a commutative ring `R`
is the type of all prime ideals of `R`.
It is naturally endowed with a topology (the Zariski topology),
and a sheaf of commutative rings (see `algebraic_geometry.structure_sheaf`).
It is a fundamental building block in algebraic geometry. -/
@[nolint has_inhabited_instance]
def prime_spectrum := {I : ideal R // I.is_prime}
variable {R}
namespace prime_spectrum
/-- A method to view a point in the prime spectrum of a commutative ring
as an ideal of that ring. -/
abbreviation as_ideal (x : prime_spectrum R) : ideal R := x.val
instance is_prime (x : prime_spectrum R) :
x.as_ideal.is_prime := x.2
/--
The prime spectrum of the zero ring is empty.
-/
lemma punit (x : prime_spectrum punit) : false :=
x.1.ne_top_iff_one.1 x.2.1 $ subsingleton.elim (0 : punit) 1 ▸ x.1.zero_mem
section
variables (R) (S : Type v) [comm_ring S]
/-- The prime spectrum of `R × S` is in bijection with the disjoint unions of the prime spectrum of
`R` and the prime spectrum of `S`. -/
noncomputable def prime_spectrum_prod :
prime_spectrum (R × S) ≃ prime_spectrum R ⊕ prime_spectrum S :=
ideal.prime_ideals_equiv R S
variables {R S}
@[simp] lemma prime_spectrum_prod_symm_inl_as_ideal (x : prime_spectrum R) :
((prime_spectrum_prod R S).symm (sum.inl x)).as_ideal = ideal.prod x.as_ideal ⊤ :=
by { cases x, refl }
@[simp] lemma prime_spectrum_prod_symm_inr_as_ideal (x : prime_spectrum S) :
((prime_spectrum_prod R S).symm (sum.inr x)).as_ideal = ideal.prod ⊤ x.as_ideal :=
by { cases x, refl }
end
@[ext] lemma ext {x y : prime_spectrum R} :
x = y ↔ x.as_ideal = y.as_ideal :=
subtype.ext_iff_val
/-- The zero locus of a set `s` of elements of a commutative ring `R`
is the set of all prime ideals of the ring that contain the set `s`.
An element `f` of `R` can be thought of as a dependent function
on the prime spectrum of `R`.
At a point `x` (a prime ideal)
the function (i.e., element) `f` takes values in the quotient ring `R` modulo the prime ideal `x`.
In this manner, `zero_locus s` is exactly the subset of `prime_spectrum R`
where all "functions" in `s` vanish simultaneously.
-/
def zero_locus (s : set R) : set (prime_spectrum R) :=
{x | s ⊆ x.as_ideal}
@[simp] lemma mem_zero_locus (x : prime_spectrum R) (s : set R) :
x ∈ zero_locus s ↔ s ⊆ x.as_ideal := iff.rfl
@[simp] lemma zero_locus_span (s : set R) :
zero_locus (ideal.span s : set R) = zero_locus s :=
by { ext x, exact (submodule.gi R R).gc s x.as_ideal }
/-- The vanishing ideal of a set `t` of points
of the prime spectrum of a commutative ring `R`
is the intersection of all the prime ideals in the set `t`.
An element `f` of `R` can be thought of as a dependent function
on the prime spectrum of `R`.
At a point `x` (a prime ideal)
the function (i.e., element) `f` takes values in the quotient ring `R` modulo the prime ideal `x`.
In this manner, `vanishing_ideal t` is exactly the ideal of `R`
consisting of all "functions" that vanish on all of `t`.
-/
def vanishing_ideal (t : set (prime_spectrum R)) : ideal R :=
⨅ (x : prime_spectrum R) (h : x ∈ t), x.as_ideal
lemma coe_vanishing_ideal (t : set (prime_spectrum R)) :
(vanishing_ideal t : set R) = {f : R | ∀ x : prime_spectrum R, x ∈ t → f ∈ x.as_ideal} :=
begin
ext f,
rw [vanishing_ideal, set_like.mem_coe, submodule.mem_infi],
apply forall_congr, intro x,
rw [submodule.mem_infi],
end
lemma mem_vanishing_ideal (t : set (prime_spectrum R)) (f : R) :
f ∈ vanishing_ideal t ↔ ∀ x : prime_spectrum R, x ∈ t → f ∈ x.as_ideal :=
by rw [← set_like.mem_coe, coe_vanishing_ideal, set.mem_set_of_eq]
@[simp] lemma vanishing_ideal_singleton (x : prime_spectrum R) :
vanishing_ideal ({x} : set (prime_spectrum R)) = x.as_ideal :=
by simp [vanishing_ideal]
lemma subset_zero_locus_iff_le_vanishing_ideal (t : set (prime_spectrum R)) (I : ideal R) :
t ⊆ zero_locus I ↔ I ≤ vanishing_ideal t :=
⟨λ h f k, (mem_vanishing_ideal _ _).mpr (λ x j, (mem_zero_locus _ _).mpr (h j) k), λ h,
λ x j, (mem_zero_locus _ _).mpr (le_trans h (λ f h, ((mem_vanishing_ideal _ _).mp h) x j))⟩
section gc
variable (R)
/-- `zero_locus` and `vanishing_ideal` form a galois connection. -/
lemma gc : @galois_connection (ideal R) (set (prime_spectrum R))ᵒᵈ _ _
(λ I, zero_locus I) (λ t, vanishing_ideal t) :=
λ I t, subset_zero_locus_iff_le_vanishing_ideal t I
/-- `zero_locus` and `vanishing_ideal` form a galois connection. -/
lemma gc_set : @galois_connection (set R) (set (prime_spectrum R))ᵒᵈ _ _
(λ s, zero_locus s) (λ t, vanishing_ideal t) :=
have ideal_gc : galois_connection (ideal.span) coe := (submodule.gi R R).gc,
by simpa [zero_locus_span, function.comp] using ideal_gc.compose (gc R)
lemma subset_zero_locus_iff_subset_vanishing_ideal (t : set (prime_spectrum R)) (s : set R) :
t ⊆ zero_locus s ↔ s ⊆ vanishing_ideal t :=
(gc_set R) s t
end gc
lemma subset_vanishing_ideal_zero_locus (s : set R) :
s ⊆ vanishing_ideal (zero_locus s) :=
(gc_set R).le_u_l s
lemma le_vanishing_ideal_zero_locus (I : ideal R) :
I ≤ vanishing_ideal (zero_locus I) :=
(gc R).le_u_l I
@[simp] lemma vanishing_ideal_zero_locus_eq_radical (I : ideal R) :
vanishing_ideal (zero_locus (I : set R)) = I.radical := ideal.ext $ λ f,
begin
rw [mem_vanishing_ideal, ideal.radical_eq_Inf, submodule.mem_Inf],
exact ⟨(λ h x hx, h ⟨x, hx.2⟩ hx.1), (λ h x hx, h x.1 ⟨hx, x.2⟩)⟩
end
@[simp] lemma zero_locus_radical (I : ideal R) : zero_locus (I.radical : set R) = zero_locus I :=
vanishing_ideal_zero_locus_eq_radical I ▸ (gc R).l_u_l_eq_l I
lemma subset_zero_locus_vanishing_ideal (t : set (prime_spectrum R)) :
t ⊆ zero_locus (vanishing_ideal t) :=
(gc R).l_u_le t
lemma zero_locus_anti_mono {s t : set R} (h : s ⊆ t) : zero_locus t ⊆ zero_locus s :=
(gc_set R).monotone_l h
lemma zero_locus_anti_mono_ideal {s t : ideal R} (h : s ≤ t) :
zero_locus (t : set R) ⊆ zero_locus (s : set R) :=
(gc R).monotone_l h
lemma vanishing_ideal_anti_mono {s t : set (prime_spectrum R)} (h : s ⊆ t) :
vanishing_ideal t ≤ vanishing_ideal s :=
(gc R).monotone_u h
lemma zero_locus_subset_zero_locus_iff (I J : ideal R) :
zero_locus (I : set R) ⊆ zero_locus (J : set R) ↔ J ≤ I.radical :=
⟨λ h, ideal.radical_le_radical_iff.mp (vanishing_ideal_zero_locus_eq_radical I ▸
vanishing_ideal_zero_locus_eq_radical J ▸ vanishing_ideal_anti_mono h),
λ h, zero_locus_radical I ▸ zero_locus_anti_mono_ideal h⟩
lemma zero_locus_subset_zero_locus_singleton_iff (f g : R) :
zero_locus ({f} : set R) ⊆ zero_locus {g} ↔ g ∈ (ideal.span ({f} : set R)).radical :=
by rw [← zero_locus_span {f}, ← zero_locus_span {g}, zero_locus_subset_zero_locus_iff,
ideal.span_le, set.singleton_subset_iff, set_like.mem_coe]
lemma zero_locus_bot :
zero_locus ((⊥ : ideal R) : set R) = set.univ :=
(gc R).l_bot
@[simp] lemma zero_locus_singleton_zero :
zero_locus ({0} : set R) = set.univ :=
zero_locus_bot
@[simp] lemma zero_locus_empty :
zero_locus (∅ : set R) = set.univ :=
(gc_set R).l_bot
@[simp] lemma vanishing_ideal_univ :
vanishing_ideal (∅ : set (prime_spectrum R)) = ⊤ :=
by simpa using (gc R).u_top
lemma zero_locus_empty_of_one_mem {s : set R} (h : (1:R) ∈ s) :
zero_locus s = ∅ :=
begin
rw set.eq_empty_iff_forall_not_mem,
intros x hx,
rw mem_zero_locus at hx,
have x_prime : x.as_ideal.is_prime := by apply_instance,
have eq_top : x.as_ideal = ⊤, { rw ideal.eq_top_iff_one, exact hx h },
apply x_prime.ne_top eq_top,
end
@[simp] lemma zero_locus_singleton_one :
zero_locus ({1} : set R) = ∅ :=
zero_locus_empty_of_one_mem (set.mem_singleton (1 : R))
lemma zero_locus_empty_iff_eq_top {I : ideal R} :
zero_locus (I : set R) = ∅ ↔ I = ⊤ :=
begin
split,
{ contrapose!,
intro h,
apply set.ne_empty_iff_nonempty.mpr,
rcases ideal.exists_le_maximal I h with ⟨M, hM, hIM⟩,
exact ⟨⟨M, hM.is_prime⟩, hIM⟩ },
{ rintro rfl, apply zero_locus_empty_of_one_mem, trivial }
end
@[simp] lemma zero_locus_univ :
zero_locus (set.univ : set R) = ∅ :=
zero_locus_empty_of_one_mem (set.mem_univ 1)
lemma zero_locus_sup (I J : ideal R) :
zero_locus ((I ⊔ J : ideal R) : set R) = zero_locus I ∩ zero_locus J :=
(gc R).l_sup
lemma zero_locus_union (s s' : set R) :
zero_locus (s ∪ s') = zero_locus s ∩ zero_locus s' :=
(gc_set R).l_sup
lemma vanishing_ideal_union (t t' : set (prime_spectrum R)) :
vanishing_ideal (t ∪ t') = vanishing_ideal t ⊓ vanishing_ideal t' :=
(gc R).u_inf
lemma zero_locus_supr {ι : Sort*} (I : ι → ideal R) :
zero_locus ((⨆ i, I i : ideal R) : set R) = (⋂ i, zero_locus (I i)) :=
(gc R).l_supr
lemma zero_locus_Union {ι : Sort*} (s : ι → set R) :
zero_locus (⋃ i, s i) = (⋂ i, zero_locus (s i)) :=
(gc_set R).l_supr
lemma zero_locus_bUnion (s : set (set R)) :
zero_locus (⋃ s' ∈ s, s' : set R) = ⋂ s' ∈ s, zero_locus s' :=
by simp only [zero_locus_Union]
lemma vanishing_ideal_Union {ι : Sort*} (t : ι → set (prime_spectrum R)) :
vanishing_ideal (⋃ i, t i) = (⨅ i, vanishing_ideal (t i)) :=
(gc R).u_infi
lemma zero_locus_inf (I J : ideal R) :
zero_locus ((I ⊓ J : ideal R) : set R) = zero_locus I ∪ zero_locus J :=
set.ext $ λ x, by simpa using x.2.inf_le
lemma union_zero_locus (s s' : set R) :
zero_locus s ∪ zero_locus s' = zero_locus ((ideal.span s) ⊓ (ideal.span s') : ideal R) :=
by { rw zero_locus_inf, simp }
lemma zero_locus_mul (I J : ideal R) :
zero_locus ((I * J : ideal R) : set R) = zero_locus I ∪ zero_locus J :=
set.ext $ λ x, by simpa using x.2.mul_le
lemma zero_locus_singleton_mul (f g : R) :
zero_locus ({f * g} : set R) = zero_locus {f} ∪ zero_locus {g} :=
set.ext $ λ x, by simpa using x.2.mul_mem_iff_mem_or_mem
@[simp] lemma zero_locus_pow (I : ideal R) {n : ℕ} (hn : 0 < n) :
zero_locus ((I ^ n : ideal R) : set R) = zero_locus I :=
zero_locus_radical (I ^ n) ▸ (I.radical_pow n hn).symm ▸ zero_locus_radical I
@[simp] lemma zero_locus_singleton_pow (f : R) (n : ℕ) (hn : 0 < n) :
zero_locus ({f ^ n} : set R) = zero_locus {f} :=
set.ext $ λ x, by simpa using x.2.pow_mem_iff_mem n hn
lemma sup_vanishing_ideal_le (t t' : set (prime_spectrum R)) :
vanishing_ideal t ⊔ vanishing_ideal t' ≤ vanishing_ideal (t ∩ t') :=
begin
intros r,
rw [submodule.mem_sup, mem_vanishing_ideal],
rintro ⟨f, hf, g, hg, rfl⟩ x ⟨hxt, hxt'⟩,
rw mem_vanishing_ideal at hf hg,
apply submodule.add_mem; solve_by_elim
end
lemma mem_compl_zero_locus_iff_not_mem {f : R} {I : prime_spectrum R} :
I ∈ (zero_locus {f} : set (prime_spectrum R))ᶜ ↔ f ∉ I.as_ideal :=
by rw [set.mem_compl_eq, mem_zero_locus, set.singleton_subset_iff]; refl
/-- The Zariski topology on the prime spectrum of a commutative ring
is defined via the closed sets of the topology:
they are exactly those sets that are the zero locus of a subset of the ring. -/
instance zariski_topology : topological_space (prime_spectrum R) :=
topological_space.of_closed (set.range prime_spectrum.zero_locus)
(⟨set.univ, by simp⟩)
begin
intros Zs h,
rw set.sInter_eq_Inter,
let f : Zs → set R := λ i, classical.some (h i.2),
have hf : ∀ i : Zs, ↑i = zero_locus (f i) := λ i, (classical.some_spec (h i.2)).symm,
simp only [hf],
exact ⟨_, zero_locus_Union _⟩
end
(by { rintro _ ⟨s, rfl⟩ _ ⟨t, rfl⟩, exact ⟨_, (union_zero_locus s t).symm⟩ })
lemma is_open_iff (U : set (prime_spectrum R)) :
is_open U ↔ ∃ s, Uᶜ = zero_locus s :=
by simp only [@eq_comm _ Uᶜ]; refl
lemma is_closed_iff_zero_locus (Z : set (prime_spectrum R)) :
is_closed Z ↔ ∃ s, Z = zero_locus s :=
by rw [← is_open_compl_iff, is_open_iff, compl_compl]
lemma is_closed_iff_zero_locus_ideal (Z : set (prime_spectrum R)) :
is_closed Z ↔ ∃ (s : ideal R), Z = zero_locus s :=
(is_closed_iff_zero_locus _).trans
⟨λ x, ⟨_, x.some_spec.trans (zero_locus_span _).symm⟩, λ x, ⟨_, x.some_spec⟩⟩
lemma is_closed_iff_zero_locus_radical_ideal (Z : set (prime_spectrum R)) :
is_closed Z ↔ ∃ (s : ideal R), s.radical = s ∧ Z = zero_locus s :=
(is_closed_iff_zero_locus_ideal _).trans
⟨λ x, ⟨_, ideal.radical_idem _, x.some_spec.trans (zero_locus_radical _).symm⟩,
λ x, ⟨_, x.some_spec.2⟩⟩
lemma is_closed_zero_locus (s : set R) :
is_closed (zero_locus s) :=
by { rw [is_closed_iff_zero_locus], exact ⟨s, rfl⟩ }
lemma is_closed_singleton_iff_is_maximal (x : prime_spectrum R) :
is_closed ({x} : set (prime_spectrum R)) ↔ x.as_ideal.is_maximal :=
begin
refine (is_closed_iff_zero_locus _).trans ⟨λ h, _, λ h, _⟩,
{ obtain ⟨s, hs⟩ := h,
rw [eq_comm, set.eq_singleton_iff_unique_mem] at hs,
refine ⟨⟨x.2.1, λ I hI, not_not.1 (mt (ideal.exists_le_maximal I) $
not_exists.2 (λ J, not_and.2 $ λ hJ hIJ,_))⟩⟩,
exact ne_of_lt (lt_of_lt_of_le hI hIJ) (symm $ congr_arg prime_spectrum.as_ideal
(hs.2 ⟨J, hJ.is_prime⟩ (λ r hr, hIJ (le_of_lt hI $ hs.1 hr)))) },
{ refine ⟨x.as_ideal.1, _⟩,
rw [eq_comm, set.eq_singleton_iff_unique_mem],
refine ⟨λ _ h, h, λ y hy, prime_spectrum.ext.2 (h.eq_of_le y.2.ne_top hy).symm⟩ }
end
lemma zero_locus_vanishing_ideal_eq_closure (t : set (prime_spectrum R)) :
zero_locus (vanishing_ideal t : set R) = closure t :=
begin
apply set.subset.antisymm,
{ rintro x hx t' ⟨ht', ht⟩,
obtain ⟨fs, rfl⟩ : ∃ s, t' = zero_locus s,
by rwa [is_closed_iff_zero_locus] at ht',
rw [subset_zero_locus_iff_subset_vanishing_ideal] at ht,
exact set.subset.trans ht hx },
{ rw (is_closed_zero_locus _).closure_subset_iff,
exact subset_zero_locus_vanishing_ideal t }
end
lemma vanishing_ideal_closure (t : set (prime_spectrum R)) :
vanishing_ideal (closure t) = vanishing_ideal t :=
zero_locus_vanishing_ideal_eq_closure t ▸ (gc R).u_l_u_eq_u t
lemma t1_space_iff_is_field [is_domain R] :
t1_space (prime_spectrum R) ↔ is_field R :=
begin
refine ⟨_, λ h, _⟩,
{ introI h,
have hbot : ideal.is_prime (⊥ : ideal R) := ideal.bot_prime,
exact not_not.1 (mt (ring.ne_bot_of_is_maximal_of_not_is_field $
(is_closed_singleton_iff_is_maximal _).1 (t1_space.t1 ⟨⊥, hbot⟩)) (not_not.2 rfl)) },
{ refine ⟨λ x, (is_closed_singleton_iff_is_maximal x).2 _⟩,
by_cases hx : x.as_ideal = ⊥,
{ exact hx.symm ▸ @ideal.bot_is_maximal R (@field.to_division_ring _ h.to_field) },
{ exact absurd h (ring.not_is_field_iff_exists_prime.2 ⟨x.as_ideal, ⟨hx, x.2⟩⟩) } }
end
local notation `Z(` a `)` := zero_locus (a : set R)
lemma is_irreducible_zero_locus_iff_of_radical (I : ideal R) (hI : I.radical = I) :
is_irreducible (zero_locus (I : set R)) ↔ I.is_prime :=
begin
rw [ideal.is_prime_iff, is_irreducible],
apply and_congr,
{ rw [← set.ne_empty_iff_nonempty, ne.def, zero_locus_empty_iff_eq_top] },
{ transitivity ∀ (x y : ideal R), Z(I) ⊆ Z(x) ∪ Z(y) → Z(I) ⊆ Z(x) ∨ Z(I) ⊆ Z(y),
{ simp_rw [is_preirreducible_iff_closed_union_closed, is_closed_iff_zero_locus_ideal],
split,
{ rintros h x y, exact h _ _ ⟨x, rfl⟩ ⟨y, rfl⟩ },
{ rintros h _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, exact h x y } },
{ simp_rw [← zero_locus_inf, subset_zero_locus_iff_le_vanishing_ideal,
vanishing_ideal_zero_locus_eq_radical, hI],
split,
{ intros h x y h',
simp_rw [← set_like.mem_coe, ← set.singleton_subset_iff, ← ideal.span_le],
apply h,
rw [← hI, ← ideal.radical_le_radical_iff, ideal.radical_inf, ← ideal.radical_mul,
ideal.radical_le_radical_iff, hI, ideal.span_mul_span],
simpa [ideal.span_le] using h' },
{ simp_rw [or_iff_not_imp_left, set_like.not_le_iff_exists],
rintros h s t h' ⟨x, hx, hx'⟩ y hy,
exact h (h' ⟨ideal.mul_mem_right _ _ hx, ideal.mul_mem_left _ _ hy⟩) hx' } } }
end
lemma is_irreducible_zero_locus_iff (I : ideal R) :
is_irreducible (zero_locus (I : set R)) ↔ I.radical.is_prime :=
(zero_locus_radical I) ▸ is_irreducible_zero_locus_iff_of_radical _ I.radical_idem
instance [is_domain R] : irreducible_space (prime_spectrum R) :=
begin
rw [irreducible_space_def, set.top_eq_univ, ← zero_locus_bot, is_irreducible_zero_locus_iff],
simpa using ideal.bot_prime
end
instance : quasi_sober (prime_spectrum R) :=
begin
constructor,
intros S h₁ h₂,
rw [← h₂.closure_eq, ← zero_locus_vanishing_ideal_eq_closure,
is_irreducible_zero_locus_iff] at h₁,
use ⟨_, h₁⟩,
obtain ⟨s, hs, rfl⟩ := (is_closed_iff_zero_locus_radical_ideal _).mp h₂,
rw is_generic_point_iff_forall_closed h₂,
intros Z hZ hxZ,
obtain ⟨t, rfl⟩ := (is_closed_iff_zero_locus_ideal _).mp hZ,
exact zero_locus_anti_mono (by simpa [hs] using hxZ),
simp [hs]
end
section comap
variables {S : Type v} [comm_ring S] {S' : Type*} [comm_ring S']
lemma preimage_comap_zero_locus_aux (f : R →+* S) (s : set R) :
(λ y, ⟨ideal.comap f y.as_ideal, infer_instance⟩ :
prime_spectrum S → prime_spectrum R) ⁻¹' (zero_locus s) = zero_locus (f '' s) :=
begin
ext x,
simp only [mem_zero_locus, set.image_subset_iff],
refl
end
/-- The function between prime spectra of commutative rings induced by a ring homomorphism.
This function is continuous. -/
def comap (f : R →+* S) : C(prime_spectrum S, prime_spectrum R) :=
{ to_fun := λ y, ⟨ideal.comap f y.as_ideal, infer_instance⟩,
continuous_to_fun :=
begin
simp only [continuous_iff_is_closed, is_closed_iff_zero_locus],
rintro _ ⟨s, rfl⟩,
exact ⟨_, preimage_comap_zero_locus_aux f s⟩
end }
variables (f : R →+* S)
@[simp] lemma comap_as_ideal (y : prime_spectrum S) :
(comap f y).as_ideal = ideal.comap f y.as_ideal :=
rfl
@[simp] lemma comap_id : comap (ring_hom.id R) = continuous_map.id _ := by { ext, refl }
@[simp] lemma comap_comp (f : R →+* S) (g : S →+* S') :
comap (g.comp f) = (comap f).comp (comap g) :=
rfl
lemma comap_comp_apply (f : R →+* S) (g : S →+* S') (x : prime_spectrum S') :
prime_spectrum.comap (g.comp f) x = (prime_spectrum.comap f) (prime_spectrum.comap g x) :=
rfl
@[simp] lemma preimage_comap_zero_locus (s : set R) :
(comap f) ⁻¹' (zero_locus s) = zero_locus (f '' s) :=
preimage_comap_zero_locus_aux f s
lemma comap_injective_of_surjective (f : R →+* S) (hf : function.surjective f) :
function.injective (comap f) :=
λ x y h, prime_spectrum.ext.2 (ideal.comap_injective_of_surjective f hf
(congr_arg prime_spectrum.as_ideal h : (comap f x).as_ideal = (comap f y).as_ideal))
lemma comap_singleton_is_closed_of_surjective (f : R →+* S) (hf : function.surjective f)
(x : prime_spectrum S) (hx : is_closed ({x} : set (prime_spectrum S))) :
is_closed ({comap f x} : set (prime_spectrum R)) :=
begin
haveI : x.as_ideal.is_maximal := (is_closed_singleton_iff_is_maximal x).1 hx,
exact (is_closed_singleton_iff_is_maximal _).2 (ideal.comap_is_maximal_of_surjective f hf)
end
lemma comap_singleton_is_closed_of_is_integral (f : R →+* S) (hf : f.is_integral)
(x : prime_spectrum S) (hx : is_closed ({x} : set (prime_spectrum S))) :
is_closed ({comap f x} : set (prime_spectrum R)) :=
(is_closed_singleton_iff_is_maximal _).2 (ideal.is_maximal_comap_of_is_integral_of_is_maximal'
f hf x.as_ideal $ (is_closed_singleton_iff_is_maximal x).1 hx)
variable S
lemma localization_comap_inducing [algebra R S] (M : submonoid R)
[is_localization M S] : inducing (comap (algebra_map R S)) :=
begin
constructor,
rw topological_space_eq_iff,
intro U,
simp_rw ← is_closed_compl_iff,
generalize : Uᶜ = Z,
simp_rw [is_closed_induced_iff, is_closed_iff_zero_locus],
split,
{ rintro ⟨s, rfl⟩,
refine ⟨_,⟨(algebra_map R S) ⁻¹' (ideal.span s),rfl⟩,_⟩,
rw [preimage_comap_zero_locus, ← zero_locus_span, ← zero_locus_span s],
congr' 1,
exact congr_arg submodule.carrier (is_localization.map_comap M S (ideal.span s)) },
{ rintro ⟨_, ⟨t, rfl⟩, rfl⟩, simp }
end
lemma localization_comap_injective [algebra R S] (M : submonoid R)
[is_localization M S] : function.injective (comap (algebra_map R S)) :=
begin
intros p q h,
replace h := congr_arg (λ (x : prime_spectrum R), ideal.map (algebra_map R S) x.as_ideal) h,
dsimp only at h,
erw [is_localization.map_comap M S, is_localization.map_comap M S] at h,
ext1,
exact h
end
lemma localization_comap_embedding [algebra R S] (M : submonoid R)
[is_localization M S] : embedding (comap (algebra_map R S)) :=
⟨localization_comap_inducing S M, localization_comap_injective S M⟩
lemma localization_comap_range [algebra R S] (M : submonoid R)
[is_localization M S] :
set.range (comap (algebra_map R S)) = { p | disjoint (M : set R) p.as_ideal } :=
begin
ext x,
split,
{ rintro ⟨p, rfl⟩ x ⟨hx₁, hx₂⟩,
exact (p.2.1 : ¬ _)
(p.as_ideal.eq_top_of_is_unit_mem hx₂ (is_localization.map_units S ⟨x, hx₁⟩)) },
{ intro h,
use ⟨x.as_ideal.map (algebra_map R S),
is_localization.is_prime_of_is_prime_disjoint M S _ x.2 h⟩,
ext1,
exact is_localization.comap_map_of_is_prime_disjoint M S _ x.2 h }
end
end comap
section basic_open
/-- `basic_open r` is the open subset containing all prime ideals not containing `r`. -/
def basic_open (r : R) : topological_space.opens (prime_spectrum R) :=
{ val := { x | r ∉ x.as_ideal },
property := ⟨{r}, set.ext $ λ x, set.singleton_subset_iff.trans $ not_not.symm⟩ }
@[simp] lemma mem_basic_open (f : R) (x : prime_spectrum R) :
x ∈ basic_open f ↔ f ∉ x.as_ideal := iff.rfl
lemma is_open_basic_open {a : R} : is_open ((basic_open a) : set (prime_spectrum R)) :=
(basic_open a).property
@[simp] lemma basic_open_eq_zero_locus_compl (r : R) :
(basic_open r : set (prime_spectrum R)) = (zero_locus {r})ᶜ :=
set.ext $ λ x, by simpa only [set.mem_compl_eq, mem_zero_locus, set.singleton_subset_iff]
@[simp] lemma basic_open_one : basic_open (1 : R) = ⊤ :=
topological_space.opens.ext $ by simp
@[simp] lemma basic_open_zero : basic_open (0 : R) = ⊥ :=
topological_space.opens.ext $ by simp
lemma basic_open_le_basic_open_iff (f g : R) :
basic_open f ≤ basic_open g ↔ f ∈ (ideal.span ({g} : set R)).radical :=
by rw [topological_space.opens.le_def, basic_open_eq_zero_locus_compl,
basic_open_eq_zero_locus_compl, set.le_eq_subset, set.compl_subset_compl,
zero_locus_subset_zero_locus_singleton_iff]
lemma basic_open_mul (f g : R) : basic_open (f * g) = basic_open f ⊓ basic_open g :=
topological_space.opens.ext $ by {simp [zero_locus_singleton_mul]}
lemma basic_open_mul_le_left (f g : R) : basic_open (f * g) ≤ basic_open f :=
by { rw basic_open_mul f g, exact inf_le_left }
lemma basic_open_mul_le_right (f g : R) : basic_open (f * g) ≤ basic_open g :=
by { rw basic_open_mul f g, exact inf_le_right }
@[simp] lemma basic_open_pow (f : R) (n : ℕ) (hn : 0 < n) : basic_open (f ^ n) = basic_open f :=
topological_space.opens.ext $ by simpa using zero_locus_singleton_pow f n hn
lemma is_topological_basis_basic_opens : topological_space.is_topological_basis
(set.range (λ (r : R), (basic_open r : set (prime_spectrum R)))) :=
begin
apply topological_space.is_topological_basis_of_open_of_nhds,
{ rintros _ ⟨r, rfl⟩,
exact is_open_basic_open },
{ rintros p U hp ⟨s, hs⟩,
rw [← compl_compl U, set.mem_compl_eq, ← hs, mem_zero_locus, set.not_subset] at hp,
obtain ⟨f, hfs, hfp⟩ := hp,
refine ⟨basic_open f, ⟨f, rfl⟩, hfp, _⟩,
rw [← set.compl_subset_compl, ← hs, basic_open_eq_zero_locus_compl, compl_compl],
exact zero_locus_anti_mono (set.singleton_subset_iff.mpr hfs) }
end
lemma is_basis_basic_opens :
topological_space.opens.is_basis (set.range (@basic_open R _)) :=
begin
unfold topological_space.opens.is_basis,
convert is_topological_basis_basic_opens,
rw ← set.range_comp,
end
lemma is_compact_basic_open (f : R) : is_compact (basic_open f : set (prime_spectrum R)) :=
is_compact_of_finite_subfamily_closed $ λ ι Z hZc hZ,
begin
let I : ι → ideal R := λ i, vanishing_ideal (Z i),
have hI : ∀ i, Z i = zero_locus (I i) := λ i,
by simpa only [zero_locus_vanishing_ideal_eq_closure] using (hZc i).closure_eq.symm,
rw [basic_open_eq_zero_locus_compl f, set.inter_comm, ← set.diff_eq,
set.diff_eq_empty, funext hI, ← zero_locus_supr] at hZ,
obtain ⟨n, hn⟩ : f ∈ (⨆ (i : ι), I i).radical,
{ rw ← vanishing_ideal_zero_locus_eq_radical,
apply vanishing_ideal_anti_mono hZ,
exact (subset_vanishing_ideal_zero_locus {f} (set.mem_singleton f)) },
rcases submodule.exists_finset_of_mem_supr I hn with ⟨s, hs⟩,
use s,
-- Using simp_rw here, because `hI` and `zero_locus_supr` need to be applied underneath binders
simp_rw [basic_open_eq_zero_locus_compl f, set.inter_comm, ← set.diff_eq,
set.diff_eq_empty, hI, ← zero_locus_supr],
rw ← zero_locus_radical, -- this one can't be in `simp_rw` because it would loop
apply zero_locus_anti_mono,
rw set.singleton_subset_iff,
exact ⟨n, hs⟩
end
@[simp]
lemma basic_open_eq_bot_iff (f : R) :
basic_open f = ⊥ ↔ is_nilpotent f :=
begin
rw [← subtype.coe_injective.eq_iff, basic_open_eq_zero_locus_compl],
simp only [set.eq_univ_iff_forall, topological_space.opens.empty_eq, set.singleton_subset_iff,
topological_space.opens.coe_bot, nilpotent_iff_mem_prime, set.compl_empty_iff, mem_zero_locus,
set_like.mem_coe],
exact subtype.forall,
end
lemma localization_away_comap_range (S : Type v) [comm_ring S] [algebra R S] (r : R)
[is_localization.away r S] : set.range (comap (algebra_map R S)) = basic_open r :=
begin
rw localization_comap_range S (submonoid.powers r),
ext,
simp only [mem_zero_locus, basic_open_eq_zero_locus_compl, set_like.mem_coe, set.mem_set_of_eq,
set.singleton_subset_iff, set.mem_compl_eq],
split,
{ intros h₁ h₂,
exact h₁ ⟨submonoid.mem_powers r, h₂⟩ },
{ rintros h₁ _ ⟨⟨n, rfl⟩, h₃⟩,
exact h₁ (x.2.mem_of_pow_mem _ h₃) },
end
lemma localization_away_open_embedding (S : Type v) [comm_ring S] [algebra R S] (r : R)
[is_localization.away r S] : open_embedding (comap (algebra_map R S)) :=
{ to_embedding := localization_comap_embedding S (submonoid.powers r),
open_range := by { rw localization_away_comap_range S r, exact is_open_basic_open } }
end basic_open
/-- The prime spectrum of a commutative ring is a compact topological space. -/
instance : compact_space (prime_spectrum R) :=
{ compact_univ := by { convert is_compact_basic_open (1 : R), rw basic_open_one, refl } }
section order
/-!
## The specialization order
We endow `prime_spectrum R` with a partial order,
where `x ≤ y` if and only if `y ∈ closure {x}`.
-/
instance : partial_order (prime_spectrum R) :=
subtype.partial_order _
@[simp] lemma as_ideal_le_as_ideal (x y : prime_spectrum R) :
x.as_ideal ≤ y.as_ideal ↔ x ≤ y :=
subtype.coe_le_coe
@[simp] lemma as_ideal_lt_as_ideal (x y : prime_spectrum R) :
x.as_ideal < y.as_ideal ↔ x < y :=
subtype.coe_lt_coe
lemma le_iff_mem_closure (x y : prime_spectrum R) :
x ≤ y ↔ y ∈ closure ({x} : set (prime_spectrum R)) :=
by rw [← as_ideal_le_as_ideal, ← zero_locus_vanishing_ideal_eq_closure,
mem_zero_locus, vanishing_ideal_singleton, set_like.coe_subset_coe]
lemma le_iff_specializes (x y : prime_spectrum R) :
x ≤ y ↔ x ⤳ y :=
(le_iff_mem_closure x y).trans specializes_iff_mem_closure.symm
/-- `nhds` as an order embedding. -/
@[simps { fully_applied := tt }]
def nhds_order_embedding : prime_spectrum R ↪o filter (prime_spectrum R) :=
order_embedding.of_map_le_iff nhds $ λ a b, (le_iff_specializes a b).symm
instance : t0_space (prime_spectrum R) := ⟨nhds_order_embedding.injective⟩
end order
/-- If `x` specializes to `y`, then there is a natural map from the localization of `y` to
the localization of `x`. -/
def localization_map_of_specializes {x y : prime_spectrum R} (h : x ⤳ y) :
localization.at_prime y.as_ideal →+* localization.at_prime x.as_ideal :=
@is_localization.lift _ _ _ _ _ _ _ _
localization.is_localization (algebra_map R (localization.at_prime x.as_ideal))
begin
rintro ⟨a, ha⟩,
rw [← prime_spectrum.le_iff_specializes, ← as_ideal_le_as_ideal, ← set_like.coe_subset_coe,
← set.compl_subset_compl] at h,
exact (is_localization.map_units _ ⟨a, (show a ∈ x.as_ideal.prime_compl, from h ha)⟩ : _)
end
end prime_spectrum
namespace local_ring
variables (R) [local_ring R]
/--
The closed point in the prime spectrum of a local ring.
-/
def closed_point : prime_spectrum R :=
⟨maximal_ideal R, (maximal_ideal.is_maximal R).is_prime⟩
variable {R}
lemma is_local_ring_hom_iff_comap_closed_point {S : Type v} [comm_ring S] [local_ring S]
(f : R →+* S) : is_local_ring_hom f ↔ prime_spectrum.comap f (closed_point S) = closed_point R :=
by { rw [(local_hom_tfae f).out 0 4, subtype.ext_iff], refl }
@[simp] lemma comap_closed_point {S : Type v} [comm_ring S] [local_ring S] (f : R →+* S)
[is_local_ring_hom f] : prime_spectrum.comap f (closed_point S) = closed_point R :=
(is_local_ring_hom_iff_comap_closed_point f).mp infer_instance
end local_ring
|
a6be750778402943c42ed031785c90ea8fa1bab2 | 8b9f17008684d796c8022dab552e42f0cb6fb347 | /library/data/unit.lean | dfeb3f253a10b5fb3a3d132cc1f22cdb33cc330f | [
"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 | 723 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: data.unit
Author: Leonardo de Moura
-/
import logic.eq
namespace unit
notation `⋆` := star
protected theorem equal (a b : unit) : a = b :=
unit.rec_on a (unit.rec_on b rfl)
theorem eq_star (a : unit) : a = star :=
unit.equal a star
protected theorem subsingleton [instance] : subsingleton unit :=
subsingleton.intro (λ a b, equal a b)
protected definition is_inhabited [instance] : inhabited unit :=
inhabited.mk unit.star
protected definition has_decidable_eq [instance] : decidable_eq unit :=
take (a b : unit), decidable.inl (equal a b)
end unit
|
48ce11eeea3c53c8d8d6af2e0fb2a0ac2fefd6ac | 037dba89703a79cd4a4aec5e959818147f97635d | /src/2020/integers/int_def_solns.lean | 7351bb4923aa79a50f93b9cd956e9b44afe4529b | [] | 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 | 10,713 | lean | import tactic
/-- The equivalence relation on ℕ² such that equivalence classes are ℤ -/
def nat2.R (a b : ℕ × ℕ) : Prop :=
a.1 + b.2 = b.1 + a.2
-- here a and b are pairs, so a = (a.1, a.2) etc.
-- introduce ≈ (type with `\~~`) notation for this relation
instance : has_equiv (ℕ × ℕ) := ⟨nat2.R⟩
-- let's prove some lemmas about this binary relation
namespace nat2.R
#check quotient.lift_on
-- The following lemma is true by definition, but it's useful to
-- have it around so you can rewrite with it
@[simp] lemma equiv_def {i j k l : ℕ} : (i, j) ≈ (k, l) ↔ i + l = k + j :=
begin
refl
end
-- try rewriting `equiv_def`
lemma practice : (3, 5) ≈ (4, 6) :=
begin
change 3 + 6 = 4 + 5,
refl,
end
-- Now let's prove that this binary relation is an equivalence relation
lemma reflexive : ∀ x : ℕ × ℕ, x ≈ x :=
begin
rintro ⟨i, j⟩,
rw equiv_def,
end
lemma symmetric : ∀ x y : ℕ × ℕ, (x ≈ y) → (y ≈ x) :=
begin
-- here are a couple of tricks
rintro ⟨i, j⟩ ⟨k, l⟩ h,
-- type `⊢` with `\|-`
rw equiv_def at h ⊢,
rw h,
end
lemma transitive : ∀ x y z : ℕ × ℕ, (x ≈ y) → (y ≈ z) → (x ≈ z) :=
begin
-- this is a little trickier
-- recall `add_right_inj` says `a + b = c + b → a = c`
rintro ⟨i, j⟩ ⟨k, l⟩ ⟨m, n⟩ hxy hyz,
rw equiv_def at hxy hyz ⊢,
rw ← add_left_inj (k+l),
calc (i+n)+(k+l)=(i+l)+(k+n) : by ring
... = (k+j)+(m+l) : by rw [hxy, hyz]
... = (m+j)+(k+l) : by ring
end
-- This line tells Lean that the binary relation is an equivalence
-- relation and hence we can take the "quotient", i.e. the
-- type of equivalence classes
instance setoid : setoid (ℕ × ℕ) :=
{ r := nat2.R,
iseqv := ⟨reflexive, symmetric, transitive⟩ }
-- end of lemmas about the binary relation
end nat2.R
-- ...but we're still going to be using them
open nat2.R
/-- The integers are the equivalence classes of the equivalence relation
we just defined on ℕ² -/
def myint := quotient nat2.R.setoid
-- let's make some definitions, and prove some theorems, about integers
namespace myint
-- The first goal is to get a good interface for addition.
-- To do this we need to define a+b, and -a, and 0. Let's do
-- them in reverse order.
/-! ## zero -/
def zero := ⟦(0,0)⟧
instance : has_zero myint := ⟨myint.zero⟩
lemma zero_def : (0 : myint) = ⟦(0, 0)⟧ :=
begin
refl
end
/-! ## negation (additive inverse) -/
-- First we define an "auxiliary" map from ℕ² to ℤ
-- sending (a,b) to the equivalence class of (b,a).
def neg_aux (x : ℕ × ℕ) : myint := ⟦(x.2, x.1)⟧
-- true by definition
lemma neg_aux_def (i j : ℕ) : neg_aux (i, j) = ⟦(j, i)⟧ := rfl
/-! ### Well-definedness
OK now here's the concrete problem. We would like to define
a negation map `ℤ → ℤ` sending `z` to `-z`. We want to do this in
the following way: Say `z ∈ ℤ`. Choose `a=(i,j) ∈ ℕ²` representing `z`
(i.e. such that `cl(i,j) = ⟦(i,j)⟧ = z`)
Now apply `neg_aux` to `a`, and define `-z` to be the result.
The problem with this is that what if `b` is a different
element of the equivalence class? Then we also want `-z` to be `neg_aux b`.
Indeed, in Lean this construction is called `quotient.lift`, and
if you uncomment the below code
-/
--def neg : myint → myint :=
--quotient.lift neg_aux _
/-
you'll see an error, and if you put your cursor on the error you'll
see that Lean wants a proof that if two elements `a` and `b` are in the
same equivalence class, then `neg_aux a = neg_aux b`. So let's prove this now.
-/
-- negation on the integers, defined via neg_aux, is well-defined.
lemma neg_aux_lemma : ∀ x y : ℕ × ℕ, x ≈ y → neg_aux x = neg_aux y :=
begin
rintro ⟨i,j⟩ ⟨k,l⟩ h,
rw [neg_aux_def, neg_aux_def],
-- ⊢ ⟦(j, i)⟧ = ⟦(l, k)⟧
-- next step: if ⟦a⟧=⟦b⟧ then a ≈ b
apply quotient.sound,
-- ⊢ (j, i) ≈ (l, k)
rw equiv_def at h ⊢,
rw add_comm,
rw ← h,
apply add_comm,
end
/-- Negation on on the integers. The function sending `z` to `-z`. -/
def neg : myint → myint :=
quotient.lift neg_aux neg_aux_lemma
-- notation for negation
instance : has_neg myint := ⟨neg⟩
-- this is true by definition
lemma neg_def (i j : ℕ) : (-⟦(i, j)⟧ : myint) = ⟦(j, i)⟧ :=
begin
refl
end
/-! ## addition
Our final construction: we want to define addition on `myint`.
Here we have the same problem. Say z₁ and z₂ are integers.
Choose elements a₁=(i,j) and a₂=(k,l) in ℕ². We want to define
z₁ + z₂ to be ⟦(i+k,j+l)⟧, the equivalence class of a₁ + a₂.
Let's make this definition now.
-/
/-- An auxiliary function taking two elements of ℕ² and returning
the equivalence class of their sum. -/
def add_aux (x y : ℕ × ℕ) : myint := ⟦(x.1 + y.1, x.2 + y.2)⟧
-- true by definition, but useful for rewriting
lemma add_aux_def (i j k l : ℕ) : add_aux (i, j) (k, l) = ⟦(i + k, j + l)⟧ :=
begin
refl
end
/-
We want the definition of addition to look like the below.
Uncomment it to see the problem.
-/
--def add : myint → myint → myint :=
--quotient.lift₂ add_aux _
/-
We had better check that choosing different elements in the same
equivalence class gives the same definition.
-/
lemma add_aux_lemma : ∀ x₁ x₂ y₁ y₂ : ℕ × ℕ,
(x₁ ≈ y₁) → (x₂ ≈ y₂) → add_aux x₁ x₂ = add_aux y₁ y₂ :=
begin
rintro ⟨a, b⟩ ⟨c, d⟩ ⟨e, f⟩ ⟨g, h⟩ h1 h2,
rw add_aux_def,
rw add_aux_def,
apply quotient.sound,
rw equiv_def at *,
rw (show (a+c)+(f+h) = (a+f)+(c+h), by ring),
rw [h1, h2],
ring,
end
-- Now this is checked, we can define addition.
/-- Addition on the integers -/
def add : myint → myint → myint :=
quotient.lift₂ add_aux add_aux_lemma
-- notation for addition
instance : has_add myint := ⟨add⟩
-- true by definition
lemma add_def (i j k l : ℕ) :
(⟦(i, j)⟧ + ⟦(k, l)⟧ : myint) = ⟦(i + k, j + l)⟧ :=
begin
refl
end
/-
The four fundamental facts about addition on the integes are:
1) associativity
2) commutativity
3) zero is an additive identity
4) negation is an additive inverse.
Let's prove these now.
-/
lemma zero_add (x : myint) : 0 + x = x :=
begin
apply quotient.induction_on x,
rintro ⟨a, b⟩,
rw zero_def,
rw add_def,
apply quotient.sound,
rw equiv_def,
ring,
end
lemma add_zero (x : myint) : x + 0 = x :=
begin
apply quotient.induction_on x,
rintro ⟨a, b⟩,
rw zero_def,
rw add_def,
apply quotient.sound,
rw equiv_def,
ring,
end
lemma add_left_neg (x : myint) : -x + x = 0 :=
begin
apply quotient.induction_on x,
rintro ⟨a, b⟩,
rw zero_def,
rw neg_def,
rw add_def,
apply quotient.sound,
rw equiv_def,
ring,
end
lemma add_comm (x y : myint) : x + y = y + x :=
begin
apply quotient.induction_on₂ x y,
rintro ⟨a, b⟩ ⟨c, d⟩,
rw [add_def, add_def],
apply quotient.sound,
rw equiv_def,
ring,
end
lemma add_assoc (x y z : myint) : (x + y) + z = x + (y + z) :=
begin
apply quotient.induction_on₃ x y z,
rintro ⟨a, b⟩ ⟨c, d⟩ ⟨e, f⟩,
simp [add_def],
ring,
end
-- We just proved that the integers are a commutative group under addition!
instance : add_comm_group myint :=
{ add := (+),
add_assoc := add_assoc,
zero := 0,
zero_add := zero_add,
add_zero := add_zero,
neg := has_neg.neg,
add_left_neg := add_left_neg,
add_comm := add_comm }
-- woohoo!
/-! ## multiplication
What's left to define is 1 and multiplication (note that we don't need multiplicative
inverses -- if a is a non-zero integer then a⁻¹ is typially not an integer)
-/
def mul_aux (x y : ℕ × ℕ) : myint := ⟦(x.1*y.1+x.2*y.2, x.1*y.2+x.2*y.1)⟧
lemma mul_aux_def (i j k l : ℕ) : mul_aux (i, j) (k, l) = ⟦(i*k+j*l, i*l+j*k)⟧ :=
begin
refl
end
-- Boss level.
-- Dr. Lawn: "We leave the similar verification for multiplication as an exercise."
-- This is what we need to check for multiplication to "descend" (or "lift" as Lean
-- calls it) to a well-defined function on the quotient.
lemma mul_aux_lemma : ∀ x₁ x₂ y₁ y₂ : ℕ × ℕ,
(x₁ ≈ y₁) → (x₂ ≈ y₂) → mul_aux x₁ x₂ = mul_aux y₁ y₂ :=
begin
rintro ⟨a, b⟩ ⟨c, d⟩ ⟨e, f⟩ ⟨g, h⟩ h1 h2,
simp only [mul_aux_def],
apply quotient.sound,
rw equiv_def at *,
-- a calc proof would be nicer. Can I get away with rewriting h1 and h2
-- fewer times?
rw ← add_left_inj (a * h),
have h3 : a * c + b * d + (e * h + f * g) + a * h = a * (c + h) + b*d+e*h+f*g,
ring,
rw h3,
rw h2,
have h4 : a * (g + d) + b * d + e * h + f * g = (a+f)*g+a*d+b*d+e*h,
ring,
rw h4,
rw h1,
clear h3, clear h4,
rw (show (e + b) * g + a * d + b * d + e * h = e*g+a*d+b*(g+d)+e*h, by ring),
rw ← h2,
rw (show e * g + a * d + b * (c + h) + e * h = e * g + a * d + b * c + (e+b) * h, by ring),
rw ← h1,
ring,
end
-- definition of multiplication
def mul : myint → myint → myint :=
quotient.lift₂ mul_aux mul_aux_lemma
instance : has_mul myint := ⟨mul⟩
lemma mul_def (i j k l : ℕ) : (⟦(i, j)⟧ * ⟦(k, l)⟧ : myint) = ⟦(i*k+j*l, i*l+j*k)⟧ :=
begin
refl
end
lemma mul_assoc (x y z : myint) : (x * y) * z = x * (y * z) :=
begin
apply quotient.induction_on₃ x y z,
rintro ⟨a, b⟩ ⟨c, d⟩ ⟨e, f⟩,
simp [mul_def],
ring,
end
def one : myint := ⟦(37, 36)⟧
instance : has_one myint := ⟨myint.one⟩
-- true by definition
lemma one_def : (1 : myint) = ⟦(37, 36)⟧ :=
begin
refl
end
lemma one_mul (x : myint) : 1 * x = x :=
begin
apply quotient.induction_on x,
rintro ⟨i, j⟩,
simp [one_def, mul_def],
ring,
end
lemma mul_one (x : myint) : x * 1 = x :=
begin
apply quotient.induction_on x,
rintro ⟨i, j⟩,
simp [one_def, mul_def],
ring,
end
lemma mul_comm (x y : myint) : x * y = y * x :=
begin
apply quotient.induction_on₂ x y,
rintro ⟨i, j⟩ ⟨k, l⟩,
simp [mul_def],
ring,
end
lemma mul_add (x y z : myint) : x * (y + z) = x * y + x * z :=
begin
apply quotient.induction_on₃ x y z,
rintro ⟨i, j⟩ ⟨k, l⟩ ⟨m, n⟩,
simp [add_def, mul_def],
ring,
end
lemma add_mul (x y z : myint) : (x + y) * z = x * z + y * z :=
begin
apply quotient.induction_on₃ x y z,
rintro ⟨i, j⟩ ⟨k, l⟩ ⟨m, n⟩,
simp [add_def, mul_def],
ring,
end
-- The integers are a commutative ring
-- (that is, they satisfy the axioms we just proved)
instance : comm_ring myint :=
{ mul := (*),
mul_assoc := mul_assoc,
one := 1,
one_mul := one_mul,
mul_one := mul_one,
left_distrib := mul_add,
right_distrib := add_mul,
mul_comm := mul_comm,
..myint.add_comm_group }
end myint
|
5dffd7399d89fac6a2525962ba4dafbe6b6112d5 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/cdotTests.lean | f75301a2112d214469a961a308f441d9f03e1118 | [
"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 | 579 | lean |
class Inc (α : Type) :=
(inc : α → α)
export Inc (inc)
instance {α} [Inc α] : Inc (List α) :=
{ inc := (·.map inc) }
instance : Inc Nat :=
{ inc := Nat.succ }
#eval inc 10
#eval inc [1, 2, 3]
theorem ex1 : [(1, "hello"), (2, "world")].map (·.1) = [1, 2] :=
rfl
theorem ex2 : [(1, "hello"), (2, "world")].map (·.snd) = ["hello", "world"] :=
rfl
def sum (xs : List Nat) : Nat :=
(·.2) $ Id.run $ StateT.run (s:=0) do
xs.forM fun x => modify (· + x)
#eval sum [1, 2, 3, 4]
theorem ex3 : sum [1, 2, 3] = 6 :=
rfl
theorem ex4 : sum [1, 2, 3, 4] = 10 :=
rfl
|
6426cf86e9f7eb6a5b3a88715a62df0357e8484d | 432d948a4d3d242fdfb44b81c9e1b1baacd58617 | /src/category_theory/category/Quiv.lean | 73648f15d50016fc9714a2bd7474651b8d9731d9 | [
"Apache-2.0"
] | permissive | JLimperg/aesop3 | 306cc6570c556568897ed2e508c8869667252e8a | a4a116f650cc7403428e72bd2e2c4cda300fe03f | refs/heads/master | 1,682,884,916,368 | 1,620,320,033,000 | 1,620,320,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,897 | lean | /-
Copyright (c) 2021 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.path_category
import category_theory.category.Cat
/-!
# The category of quivers
The category of (bundled) quivers, and the free/forgetful adjunction between `Cat` and `Quiv`.
-/
universes v u
namespace category_theory
/-- Category of quivers. -/
def Quiv := bundled quiver.{(v+1) u}
namespace Quiv
instance : has_coe_to_sort Quiv :=
{ S := Type u,
coe := bundled.α }
instance str (C : Quiv.{v u}) : quiver.{(v+1) u} C := C.str
/-- Construct a bundled `Quiv` from the underlying type and the typeclass. -/
def of (C : Type u) [quiver.{v+1} C] : Quiv.{v u} := bundled.of C
instance : inhabited Quiv := ⟨Quiv.of (quiver.empty pempty)⟩
/-- Category structure on `Quiv` -/
instance category : large_category.{max v u} Quiv.{v u} :=
{ hom := λ C D, prefunctor C D,
id := λ C, prefunctor.id C,
comp := λ C D E F G, prefunctor.comp F G,
id_comp' := λ C D F, by cases F; refl,
comp_id' := λ C D F, by cases F; refl,
assoc' := by intros; refl }
/-- The forgetful functor from categories to quivers. -/
@[simps]
def forget : Cat.{v u} ⥤ Quiv.{v u} :=
{ obj := λ C, Quiv.of C,
map := λ C D F, F.to_prefunctor, }
end Quiv
namespace Cat
local attribute [ext] functor.ext
/-- The functor sending each quiver to its path category. -/
@[simps]
def free : Quiv.{v u} ⥤ Cat.{(max u v) u} :=
{ obj := λ V, Cat.of (paths V),
map := λ V W F,
{ obj := λ X, F.obj X,
map := λ X Y f, F.map_path f,
map_comp' := λ X Y Z f g, F.map_path_comp f g, },
map_id' := λ V, begin
ext; dsimp,
{ induction f with b c p e ih,
{ refl, },
{ dsimp,
erw [ih, functor.id_map, functor.id_map, prefunctor.id_map],
simp, }, },
{ intros X, erw [functor.id_obj, prefunctor.id_obj], refl, },
end,
map_comp' := λ U V W F G,
begin
ext; dsimp,
{ induction f with b c p e ih,
{ refl, },
{ dsimp,
erw [ih, functor.id_map, functor.id_map, prefunctor.id_map],
simp, }, },
{ intros X, erw [functor.id_obj, prefunctor.id_obj], refl, },
end }
end Cat
namespace Quiv
local attribute [ext] functor.ext
/-- Any prefunctor into a category lifts to a functor from the path category. -/
@[simps]
def lift {V : Type u} [quiver.{v+1} V] {C : Type u} [category.{v} C]
(F : prefunctor V C) : paths V ⥤ C :=
{ obj := λ X, F.obj X,
map := λ X Y f, compose_path (F.map_path f), }
-- We might construct `of_lift_iso_self : paths.of ⋙ lift F ≅ F`
-- (and then show that `lift F` is initial amongst such functors)
-- but it would require lifting quite a bit of machinery to quivers!
/--
The adjunction between forming the free category on a quiver, and forgetting a category to a quiver.
-/
def adj : Cat.free ⊣ Quiv.forget :=
adjunction.mk_of_hom_equiv
{ hom_equiv := λ V C,
{ to_fun := λ F,
-- This would be better as a composition `V ⥤ paths V ⥤ C ⥤ forget.obj C`
{ obj := λ X, F.obj X,
map := λ X Y f, F.map f.to_path, },
inv_fun := λ F, lift F,
left_inv := λ F, begin
ext,
{ dsimp, simp,
induction f with Y' Z' f g ih,
{ exact (F.map_id X).symm, },
{ dsimp, simp only [ih],
exact (F.map_comp _ _).symm, }, },
{ dsimp, simp, },
end,
right_inv := begin
rintro ⟨obj,map⟩,
dsimp,
congr,
ext X Y f,
exact category.id_comp _,
end, },
hom_equiv_naturality_left_symm' := λ V W C f g,
begin
ext X Y h,
{ dsimp,
erw [functor.comp_map],
simp only [category.comp_id, category.id_comp, Cat.free_map_map, Quiv.lift_map],
induction h with Y' Z h e ih,
{ refl, },
{ simp [ih], refl, }, },
{ intro X, refl, },
end, }
end Quiv
end category_theory
|
702cb6aebe6da594d6bfd84d1b9677c455cf4960 | e953c38599905267210b87fb5d82dcc3e52a4214 | /hott/init/trunc.hlean | 31c4fcdf8c3ab96babc3748b9a33b356b0aca552 | [
"Apache-2.0"
] | permissive | c-cube/lean | 563c1020bff98441c4f8ba60111fef6f6b46e31b | 0fb52a9a139f720be418dafac35104468e293b66 | refs/heads/master | 1,610,753,294,113 | 1,440,451,356,000 | 1,440,499,588,000 | 41,748,334 | 0 | 0 | null | 1,441,122,656,000 | 1,441,122,656,000 | null | UTF-8 | Lean | false | false | 11,190 | hlean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Floris van Doorn
Definition of is_trunc (n-truncatedness)
Ported from Coq HoTT.
-/
--TODO: can we replace some definitions with a hprop as codomain by theorems?
prelude
import .logic .equiv .types .pathover
open eq nat sigma unit
namespace is_trunc
/- Truncation levels -/
inductive trunc_index : Type₀ :=
| minus_two : trunc_index
| succ : trunc_index → trunc_index
/-
notation for trunc_index is -2, -1, 0, 1, ...
from 0 and up this comes from a coercion from num to trunc_index (via nat)
-/
postfix `.+1`:(max+1) := trunc_index.succ
postfix `.+2`:(max+1) := λn, (n .+1 .+1)
notation `-2` := trunc_index.minus_two
notation `-1` := -2.+1 -- ISSUE: -1 gets printed as -2.+1
export [coercions] nat
namespace trunc_index
definition add (n m : trunc_index) : trunc_index :=
trunc_index.rec_on m n (λ k l, l .+1)
definition leq (n m : trunc_index) : Type₀ :=
trunc_index.rec_on n (λm, unit) (λ n p m, trunc_index.rec_on m (λ p, empty) (λ m q p, p m) p) m
infix <= := trunc_index.leq
infix ≤ := trunc_index.leq
end trunc_index
infix `+2+`:65 := trunc_index.add
namespace trunc_index
definition succ_le_succ {n m : trunc_index} (H : n ≤ m) : n.+1 ≤ m.+1 := H
definition le_of_succ_le_succ {n m : trunc_index} (H : n.+1 ≤ m.+1) : n ≤ m := H
definition minus_two_le (n : trunc_index) : -2 ≤ n := star
definition empty_of_succ_le_minus_two {n : trunc_index} (H : n .+1 ≤ -2) : empty := H
end trunc_index
definition trunc_index.of_nat [coercion] [reducible] (n : nat) : trunc_index :=
(nat.rec_on n -2 (λ n k, k.+1)).+2
definition sub_two [reducible] (n : nat) : trunc_index :=
nat.rec_on n -2 (λ n k, k.+1)
postfix `.-2`:(max+1) := sub_two
/- truncated types -/
/-
Just as in Coq HoTT we define an internal version of contractibility and is_trunc, but we only
use `is_trunc` and `is_contr`
-/
structure contr_internal (A : Type) :=
(center : A)
(center_eq : Π(a : A), center = a)
definition is_trunc_internal (n : trunc_index) : Type → Type :=
trunc_index.rec_on n
(λA, contr_internal A)
(λn trunc_n A, (Π(x y : A), trunc_n (x = y)))
end is_trunc open is_trunc
structure is_trunc [class] (n : trunc_index) (A : Type) :=
(to_internal : is_trunc_internal n A)
open nat num is_trunc.trunc_index
namespace is_trunc
abbreviation is_contr := is_trunc -2
abbreviation is_hprop := is_trunc -1
abbreviation is_hset := is_trunc 0
variables {A B : Type}
definition is_trunc_succ_intro (A : Type) (n : trunc_index) [H : ∀x y : A, is_trunc n (x = y)]
: is_trunc n.+1 A :=
is_trunc.mk (λ x y, !is_trunc.to_internal)
definition is_trunc_eq [instance] [priority 1200]
(n : trunc_index) [H : is_trunc (n.+1) A] (x y : A) : is_trunc n (x = y) :=
is_trunc.mk (is_trunc.to_internal (n.+1) A x y)
/- contractibility -/
definition is_contr.mk (center : A) (center_eq : Π(a : A), center = a) : is_contr A :=
is_trunc.mk (contr_internal.mk center center_eq)
definition center (A : Type) [H : is_contr A] : A :=
contr_internal.center (is_trunc.to_internal -2 A)
definition center_eq [H : is_contr A] (a : A) : !center = a :=
contr_internal.center_eq (is_trunc.to_internal -2 A) a
definition eq_of_is_contr [H : is_contr A] (x y : A) : x = y :=
(center_eq x)⁻¹ ⬝ (center_eq y)
definition hprop_eq_of_is_contr {A : Type} [H : is_contr A] {x y : A} (p q : x = y) : p = q :=
have K : ∀ (r : x = y), eq_of_is_contr x y = r, from (λ r, eq.rec_on r !con.left_inv),
(K p)⁻¹ ⬝ K q
theorem is_contr_eq {A : Type} [H : is_contr A] (x y : A) : is_contr (x = y) :=
is_contr.mk !eq_of_is_contr (λ p, !hprop_eq_of_is_contr)
local attribute is_contr_eq [instance]
/- truncation is upward close -/
-- n-types are also (n+1)-types
theorem is_trunc_succ [instance] [priority 900] (A : Type) (n : trunc_index)
[H : is_trunc n A] : is_trunc (n.+1) A :=
trunc_index.rec_on n
(λ A (H : is_contr A), !is_trunc_succ_intro)
(λ n IH A (H : is_trunc (n.+1) A), @is_trunc_succ_intro _ _ (λ x y, IH _ _))
A H
--in the proof the type of H is given explicitly to make it available for class inference
theorem is_trunc_of_leq.{l} (A : Type.{l}) {n m : trunc_index} (Hnm : n ≤ m)
[Hn : is_trunc n A] : is_trunc m A :=
have base : ∀k A, k ≤ -2 → is_trunc k A → (is_trunc -2 A), from
λ k A, trunc_index.cases_on k
(λh1 h2, h2)
(λk h1 h2, empty.elim (trunc_index.empty_of_succ_le_minus_two h1)),
have step : Π (m : trunc_index)
(IHm : Π (n : trunc_index) (A : Type), n ≤ m → is_trunc n A → is_trunc m A)
(n : trunc_index) (A : Type)
(Hnm : n ≤ m .+1) (Hn : is_trunc n A), is_trunc m .+1 A, from
λm IHm n, trunc_index.rec_on n
(λA Hnm Hn, @is_trunc_succ A m (IHm -2 A star Hn))
(λn IHn A Hnm (Hn : is_trunc n.+1 A),
@is_trunc_succ_intro A m (λx y, IHm n (x = y) (trunc_index.le_of_succ_le_succ Hnm) _)),
trunc_index.rec_on m base step n A Hnm Hn
-- the following cannot be instances in their current form, because they are looping
theorem is_trunc_of_is_contr (A : Type) (n : trunc_index) [H : is_contr A] : is_trunc n A :=
trunc_index.rec_on n H _
theorem is_trunc_succ_of_is_hprop (A : Type) (n : trunc_index) [H : is_hprop A]
: is_trunc (n.+1) A :=
is_trunc_of_leq A (show -1 ≤ n.+1, from star)
theorem is_trunc_succ_succ_of_is_hset (A : Type) (n : trunc_index) [H : is_hset A]
: is_trunc (n.+2) A :=
is_trunc_of_leq A (show 0 ≤ n.+2, from star)
/- hprops -/
definition is_hprop.elim [H : is_hprop A] (x y : A) : x = y :=
!center
definition is_contr_of_inhabited_hprop {A : Type} [H : is_hprop A] (x : A) : is_contr A :=
is_contr.mk x (λy, !is_hprop.elim)
theorem is_hprop_of_imp_is_contr {A : Type} (H : A → is_contr A) : is_hprop A :=
@is_trunc_succ_intro A -2
(λx y,
have H2 [visible] : is_contr A, from H x,
!is_contr_eq)
theorem is_hprop.mk {A : Type} (H : ∀x y : A, x = y) : is_hprop A :=
is_hprop_of_imp_is_contr (λ x, is_contr.mk x (H x))
theorem is_hprop_elim_self {A : Type} {H : is_hprop A} (x : A) : is_hprop.elim x x = idp :=
!is_hprop.elim
/- hsets -/
theorem is_hset.mk (A : Type) (H : ∀(x y : A) (p q : x = y), p = q) : is_hset A :=
@is_trunc_succ_intro _ _ (λ x y, is_hprop.mk (H x y))
definition is_hset.elim [H : is_hset A] ⦃x y : A⦄ (p q : x = y) : p = q :=
!is_hprop.elim
/- instances -/
definition is_contr_sigma_eq [instance] [priority 800] {A : Type} (a : A)
: is_contr (Σ(x : A), a = x) :=
is_contr.mk (sigma.mk a idp) (λp, sigma.rec_on p (λ b q, eq.rec_on q idp))
definition is_contr_unit : is_contr unit :=
is_contr.mk star (λp, unit.rec_on p idp)
definition is_hprop_empty : is_hprop empty :=
is_hprop.mk (λx, !empty.elim x)
local attribute is_contr_unit is_hprop_empty [instance]
definition is_trunc_unit [instance] (n : trunc_index) : is_trunc n unit :=
!is_trunc_of_is_contr
definition is_trunc_empty [instance] (n : trunc_index) : is_trunc (n.+1) empty :=
!is_trunc_succ_of_is_hprop
/- truncated universe -/
-- TODO: move to root namespace?
structure trunctype (n : trunc_index) :=
(carrier : Type) (struct : is_trunc n carrier)
attribute trunctype.carrier [coercion]
attribute trunctype.struct [instance]
notation n `-Type` := trunctype n
abbreviation hprop := -1-Type
abbreviation hset := 0-Type
protected abbreviation hprop.mk := @trunctype.mk -1
protected abbreviation hset.mk := @trunctype.mk (-1.+1)
protected abbreviation trunctype.mk' [parsing-only] (n : trunc_index) (A : Type)
[H : is_trunc n A] : n-Type :=
trunctype.mk A H
/- interaction with equivalences -/
section
open is_equiv equiv
--should we remove the following two theorems as they are special cases of
--"is_trunc_is_equiv_closed"
definition is_contr_is_equiv_closed (f : A → B) [Hf : is_equiv f] [HA: is_contr A]
: (is_contr B) :=
is_contr.mk (f (center A)) (λp, eq_of_eq_inv !center_eq)
definition is_contr_equiv_closed (H : A ≃ B) [HA: is_contr A] : is_contr B :=
is_contr_is_equiv_closed (to_fun H)
definition equiv_of_is_contr_of_is_contr [HA : is_contr A] [HB : is_contr B] : A ≃ B :=
equiv.mk
(λa, center B)
(is_equiv.adjointify (λa, center B) (λb, center A) center_eq center_eq)
theorem is_trunc_is_equiv_closed (n : trunc_index) (f : A → B) [H : is_equiv f]
[HA : is_trunc n A] : is_trunc n B :=
trunc_index.rec_on n
(λA (HA : is_contr A) B f (H : is_equiv f), is_contr_is_equiv_closed f)
(λn IH A (HA : is_trunc n.+1 A) B f (H : is_equiv f), @is_trunc_succ_intro _ _ (λ x y : B,
IH (f⁻¹ x = f⁻¹ y) _ (x = y) (ap f⁻¹)⁻¹ !is_equiv_inv))
A HA B f H
definition is_trunc_is_equiv_closed_rev (n : trunc_index) (f : A → B) [H : is_equiv f]
[HA : is_trunc n B] : is_trunc n A :=
is_trunc_is_equiv_closed n f⁻¹
definition is_trunc_equiv_closed (n : trunc_index) (f : A ≃ B) [HA : is_trunc n A]
: is_trunc n B :=
is_trunc_is_equiv_closed n (to_fun f)
definition is_trunc_equiv_closed_rev (n : trunc_index) (f : A ≃ B) [HA : is_trunc n B]
: is_trunc n A :=
is_trunc_is_equiv_closed n (to_inv f)
definition is_equiv_of_is_hprop [constructor] [HA : is_hprop A] [HB : is_hprop B]
(f : A → B) (g : B → A) : is_equiv f :=
is_equiv.mk f g (λb, !is_hprop.elim) (λa, !is_hprop.elim) (λa, !is_hset.elim)
definition equiv_of_is_hprop [constructor] [HA : is_hprop A] [HB : is_hprop B]
(f : A → B) (g : B → A) : A ≃ B :=
equiv.mk f (is_equiv_of_is_hprop f g)
definition equiv_of_iff_of_is_hprop [unfold 5] [HA : is_hprop A] [HB : is_hprop B] (H : A ↔ B) : A ≃ B :=
equiv_of_is_hprop (iff.elim_left H) (iff.elim_right H)
end
/- interaction with the Unit type -/
open equiv
-- A contractible type is equivalent to [Unit]. *)
definition equiv_unit_of_is_contr [H : is_contr A] : A ≃ unit :=
equiv.MK (λ (x : A), ⋆)
(λ (u : unit), center A)
(λ (u : unit), unit.rec_on u idp)
(λ (x : A), center_eq x)
/- interaction with pathovers -/
variables {C : A → Type}
{a a₂ : A} (p : a = a₂)
(c : C a) (c₂ : C a₂)
definition is_hprop.elimo [H : is_hprop (C a)] : c =[p] c₂ :=
pathover_of_eq_tr !is_hprop.elim
definition is_trunc_pathover [instance]
(n : trunc_index) [H : is_trunc (n.+1) (C a)] : is_trunc n (c =[p] c₂) :=
is_trunc_equiv_closed_rev n !pathover_equiv_eq_tr
variables {p c c₂}
theorem is_hset.elimo (q q' : c =[p] c₂) [H : is_hset (C a)] : q = q' :=
!is_hprop.elim
/- truncatedness of lift -/
definition is_trunc_lift [instance] (A : Type) (n : trunc_index) [H : is_trunc n A]
: is_trunc n (lift A) :=
is_trunc_equiv_closed _ !equiv_lift
-- TODO: port "Truncated morphisms"
end is_trunc
|
e6398638073ecc12f26f674a3b17e79354d1860c | f3a5af2927397cf346ec0e24312bfff077f00425 | /src/game/world1/level2.lean | 8b283f770e7a64e82dc21cbe498fd3af322367b3 | [
"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 | 4,681 | lean | import mynat.mul -- hide
namespace mynat -- hide
/-
# Tutorial world
## level 2: The rewrite (`rw`) tactic.
The rewrite tactic is the way to "substitute in" the value
of a variable. In general, if you have a hypothesis of the form `A = B`, and your
goal mentions the left hand side `A` somewhere, then
the `rewrite` tactic will replace the `A` in your goal with a `B`.
Below is a theorem which cannot be
proved using `refl` -- you need a rewrite first.
Delete the sorry and take a look in the top right box at what we have.
The variables $x$ and $y$ are natural numbers, and we have
a proof `h` that $y = x + 7$. Our goal
is to prove that $2y=2(x+7)$. This goal is obvious -- we just
substitute in $y = x+7$ and we're done. In Lean, we do
this substitution using the `rw` tactic. So start your proof with
`rw h,`
and then hit enter. **Don't forget the comma.**
Did you see what happened to the goal? The goal doesn't close,
but it *changes* from `⊢ 2 * y = 2 * (x + 7)` to `⊢ 2 * (x + 7) = 2 * (x + 7)`.
We can just close this goal with
`refl,`
by writing it on the line after `rw h,`. Don't forget the comma, hit
enter, and enjoy seeing the "Proof complete!" message in the
top right window. The other reason you'll know you're
done is that the bottom right window (the error window)
becomes empty. When you've finished reading the comments below
the proof, click "Next Level" in the top right to proceed to the next
level in this world.
-/
/- Lemma : no-side-bar
If $x$ and $y$ are natural numbers,
and $y=x+7$, then $2y=2(x+7)$.
-/
lemma example2 (x y : mynat) (h : y = x + 7) : 2 * y = 2 * (x + 7) :=
begin [nat_num_game]
rw h,
refl
end
/- Tactic : rw
## Summary
If `h` is a proof of `X = Y`, then `rw h,` will change
all `X`s in the goal to `Y`s. Variants: `rw ← h` (changes
`Y` to `X`) and
`rw h at h2` (changes `X` to `Y` in hypothesis `h2` instead
of the goal).
## Details
The `rw` tactic is a way to do "substituting in". There
are two distinct situations where use this tactics.
1) If `h : A = B` is a hypothesis (i.e., a proof of `A = B`)
in your local context (the box in the top right)
and if your goal contains one or more `A`s, then `rw h`
will change them all to `B`'s.
2) The `rw` tactic will also work with proofs of theorems
which are equalities (look for them in the drop down
menu on the left, within Theorem Statements).
For example, in world 1 level 4
we learn about `add_zero x : x + 0 = x`, and `rw add_zero`
will change `x + 0` into `x` in your goal (or fail with
an error if Lean cannot find `x + 0` in the goal).
Important note: if `h` is not a proof of the form `A = B`
or `A ↔ B` (for example if `h` is a function, an implication,
or perhaps even a proposition itself rather than its proof),
then `rw` is not the tactic you want to use. For example,
`rw (P = Q)` is never correct: `P = Q` is the true-false
statement itself, not the proof.
If `h : P = Q` is its proof, then `rw h` will work.
Pro tip 1: If `h : A = B` and you want to change
`B`s to `A`s instead, try `rw ←h` (get the arrow with `\l` and
note that this is a small letter L, not a number 1).
### Example:
If it looks like this in the top right hand box:
```
x y : mynat
h : x = y + y
⊢ succ (x + 0) = succ (y + y)
```
then
`rw add_zero,`
will change the goal into `⊢ succ x = succ (y + y)`, and then
`rw h,`
will change the goal into `⊢ succ (y + y) = succ (y + y)`, which
can be solved with `refl,`.
### Example:
You can use `rw` to change a hypothesis as well.
For example, if your local context looks like this:
```
x y : mynat
h1 : x = y + 3
h2 : 2 * y = x
⊢ y = 3
```
then `rw h1 at h2` will turn `h2` into `h2 : 2 * y = y + 3`.
-/
/-
## Exploring your proof.
Click on `refl,` and then use the arrow keys to move
your cursor around the proof. Go up and down and note that
the goal changes -- indeed you can inspect Lean's "state" at each
line of the proof (the hypotheses, and the goal).
Try to figure out the exact place where the goal changes.
The comma tells Lean "I've finished writing this tactic now,
please process it." Lean ignores newlines, but pays great
attention to commas.
## The tactic index
The documentation for `rw` just appeared in the list of tactics
in the box on the left. Play around with the menus on the left
and see what is there currently. More information will appear as you progress.
## Bewildered?
Doesn't work? Weird error that won't go away? You can check out
the
<a href="https://github.com/ImperialCollegeLondon/natural_number_game/blob/master/SOLUTIONS.md"
target="blank">solutions</a> (github.com, opens in new window).
Solutions to every level are here.
-/
end mynat -- hide |
ecae7f55cd495f79e11b8573ce789f944dc4b0a0 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/analysis/normed_space/add_torsor.lean | 001c01845a245e7a6c9669f70da91f3a4a545cd0 | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 7,384 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers, Yury Kudryashov
-/
import analysis.normed_space.basic
import analysis.normed.group.add_torsor
import linear_algebra.affine_space.midpoint_zero
import linear_algebra.affine_space.affine_subspace
import topology.instances.real_vector_space
/-!
# Torsors of normed space actions.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file contains lemmas about normed additive torsors over normed spaces.
-/
noncomputable theory
open_locale nnreal topology
open filter
variables {α V P W Q : Type*} [seminormed_add_comm_group V] [pseudo_metric_space P]
[normed_add_torsor V P] [normed_add_comm_group W] [metric_space Q] [normed_add_torsor W Q]
section normed_space
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 V] [normed_space 𝕜 W]
open affine_map
lemma affine_subspace.is_closed_direction_iff (s : affine_subspace 𝕜 Q) :
is_closed (s.direction : set W) ↔ is_closed (s : set Q) :=
begin
rcases s.eq_bot_or_nonempty with rfl|⟨x, hx⟩, { simp [is_closed_singleton] },
rw [← (isometry_equiv.vadd_const x).to_homeomorph.symm.is_closed_image,
affine_subspace.coe_direction_eq_vsub_set_right hx],
refl
end
include V
@[simp] lemma dist_center_homothety (p₁ p₂ : P) (c : 𝕜) :
dist p₁ (homothety p₁ c p₂) = ‖c‖ * dist p₁ p₂ :=
by simp [homothety_def, norm_smul, ← dist_eq_norm_vsub, dist_comm]
@[simp] lemma dist_homothety_center (p₁ p₂ : P) (c : 𝕜) :
dist (homothety p₁ c p₂) p₁ = ‖c‖ * dist p₁ p₂ :=
by rw [dist_comm, dist_center_homothety]
@[simp] lemma dist_line_map_line_map (p₁ p₂ : P) (c₁ c₂ : 𝕜) :
dist (line_map p₁ p₂ c₁) (line_map p₁ p₂ c₂) = dist c₁ c₂ * dist p₁ p₂ :=
begin
rw dist_comm p₁ p₂,
simp only [line_map_apply, dist_eq_norm_vsub, vadd_vsub_vadd_cancel_right, ← sub_smul, norm_smul,
vsub_eq_sub],
end
lemma lipschitz_with_line_map (p₁ p₂ : P) :
lipschitz_with (nndist p₁ p₂) (line_map p₁ p₂ : 𝕜 → P) :=
lipschitz_with.of_dist_le_mul $ λ c₁ c₂,
((dist_line_map_line_map p₁ p₂ c₁ c₂).trans (mul_comm _ _)).le
@[simp] lemma dist_line_map_left (p₁ p₂ : P) (c : 𝕜) :
dist (line_map p₁ p₂ c) p₁ = ‖c‖ * dist p₁ p₂ :=
by simpa only [line_map_apply_zero, dist_zero_right] using dist_line_map_line_map p₁ p₂ c 0
@[simp] lemma dist_left_line_map (p₁ p₂ : P) (c : 𝕜) :
dist p₁ (line_map p₁ p₂ c) = ‖c‖ * dist p₁ p₂ :=
(dist_comm _ _).trans (dist_line_map_left _ _ _)
@[simp] lemma dist_line_map_right (p₁ p₂ : P) (c : 𝕜) :
dist (line_map p₁ p₂ c) p₂ = ‖1 - c‖ * dist p₁ p₂ :=
by simpa only [line_map_apply_one, dist_eq_norm'] using dist_line_map_line_map p₁ p₂ c 1
@[simp] lemma dist_right_line_map (p₁ p₂ : P) (c : 𝕜) :
dist p₂ (line_map p₁ p₂ c) = ‖1 - c‖ * dist p₁ p₂ :=
(dist_comm _ _).trans (dist_line_map_right _ _ _)
@[simp] lemma dist_homothety_self (p₁ p₂ : P) (c : 𝕜) :
dist (homothety p₁ c p₂) p₂ = ‖1 - c‖ * dist p₁ p₂ :=
by rw [homothety_eq_line_map, dist_line_map_right]
@[simp] lemma dist_self_homothety (p₁ p₂ : P) (c : 𝕜) :
dist p₂ (homothety p₁ c p₂) = ‖1 - c‖ * dist p₁ p₂ :=
by rw [dist_comm, dist_homothety_self]
section invertible_two
variables [invertible (2:𝕜)]
@[simp] lemma dist_left_midpoint (p₁ p₂ : P) :
dist p₁ (midpoint 𝕜 p₁ p₂) = ‖(2:𝕜)‖⁻¹ * dist p₁ p₂ :=
by rw [midpoint, dist_comm, dist_line_map_left, inv_of_eq_inv, ← norm_inv]
@[simp] lemma dist_midpoint_left (p₁ p₂ : P) :
dist (midpoint 𝕜 p₁ p₂) p₁ = ‖(2:𝕜)‖⁻¹ * dist p₁ p₂ :=
by rw [dist_comm, dist_left_midpoint]
@[simp] lemma dist_midpoint_right (p₁ p₂ : P) :
dist (midpoint 𝕜 p₁ p₂) p₂ = ‖(2:𝕜)‖⁻¹ * dist p₁ p₂ :=
by rw [midpoint_comm, dist_midpoint_left, dist_comm]
@[simp] lemma dist_right_midpoint (p₁ p₂ : P) :
dist p₂ (midpoint 𝕜 p₁ p₂) = ‖(2:𝕜)‖⁻¹ * dist p₁ p₂ :=
by rw [dist_comm, dist_midpoint_right]
lemma dist_midpoint_midpoint_le' (p₁ p₂ p₃ p₄ : P) :
dist (midpoint 𝕜 p₁ p₂) (midpoint 𝕜 p₃ p₄) ≤ (dist p₁ p₃ + dist p₂ p₄) / ‖(2 : 𝕜)‖ :=
begin
rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, midpoint_vsub_midpoint];
try { apply_instance },
rw [midpoint_eq_smul_add, norm_smul, inv_of_eq_inv, norm_inv, ← div_eq_inv_mul],
exact div_le_div_of_le_of_nonneg (norm_add_le _ _) (norm_nonneg _),
end
end invertible_two
omit V
include W
lemma antilipschitz_with_line_map {p₁ p₂ : Q} (h : p₁ ≠ p₂) :
antilipschitz_with (nndist p₁ p₂)⁻¹ (line_map p₁ p₂ : 𝕜 → Q) :=
antilipschitz_with.of_le_mul_dist $ λ c₁ c₂, by rw [dist_line_map_line_map, nnreal.coe_inv,
← dist_nndist, mul_left_comm, inv_mul_cancel (dist_ne_zero.2 h), mul_one]
variables (𝕜)
lemma eventually_homothety_mem_of_mem_interior (x : Q) {s : set Q} {y : Q} (hy : y ∈ interior s) :
∀ᶠ δ in 𝓝 (1 : 𝕜), homothety x δ y ∈ s :=
begin
rw (normed_add_comm_group.nhds_basis_norm_lt (1 : 𝕜)).eventually_iff,
cases eq_or_ne y x with h h, { use 1, simp [h.symm, interior_subset hy], },
have hxy : 0 < ‖y -ᵥ x‖, { rwa [norm_pos_iff, vsub_ne_zero], },
obtain ⟨u, hu₁, hu₂, hu₃⟩ := mem_interior.mp hy,
obtain ⟨ε, hε, hyε⟩ := metric.is_open_iff.mp hu₂ y hu₃,
refine ⟨ε / ‖y -ᵥ x‖, div_pos hε hxy, λ δ (hδ : ‖δ - 1‖ < ε / ‖y -ᵥ x‖), hu₁ (hyε _)⟩,
rw [lt_div_iff hxy, ← norm_smul, sub_smul, one_smul] at hδ,
rwa [homothety_apply, metric.mem_ball, dist_eq_norm_vsub W, vadd_vsub_eq_sub_vsub],
end
lemma eventually_homothety_image_subset_of_finite_subset_interior
(x : Q) {s : set Q} {t : set Q} (ht : t.finite) (h : t ⊆ interior s) :
∀ᶠ δ in 𝓝 (1 : 𝕜), homothety x δ '' t ⊆ s :=
begin
suffices : ∀ y ∈ t, ∀ᶠ δ in 𝓝 (1 : 𝕜), homothety x δ y ∈ s,
{ simp_rw set.image_subset_iff,
exact (filter.eventually_all_finite ht).mpr this, },
intros y hy,
exact eventually_homothety_mem_of_mem_interior 𝕜 x (h hy),
end
end normed_space
variables [normed_space ℝ V] [normed_space ℝ W]
lemma dist_midpoint_midpoint_le (p₁ p₂ p₃ p₄ : V) :
dist (midpoint ℝ p₁ p₂) (midpoint ℝ p₃ p₄) ≤ (dist p₁ p₃ + dist p₂ p₄) / 2 :=
by simpa using dist_midpoint_midpoint_le' p₁ p₂ p₃ p₄
include V W
/-- A continuous map between two normed affine spaces is an affine map provided that
it sends midpoints to midpoints. -/
def affine_map.of_map_midpoint (f : P → Q)
(h : ∀ x y, f (midpoint ℝ x y) = midpoint ℝ (f x) (f y))
(hfc : continuous f) :
P →ᵃ[ℝ] Q :=
affine_map.mk' f
↑((add_monoid_hom.of_map_midpoint ℝ ℝ
((affine_equiv.vadd_const ℝ (f $ classical.arbitrary P)).symm ∘ f ∘
(affine_equiv.vadd_const ℝ (classical.arbitrary P))) (by simp)
(λ x y, by simp [h])).to_real_linear_map $ by apply_rules [continuous.vadd, continuous.vsub,
continuous_const, hfc.comp, continuous_id])
(classical.arbitrary P)
(λ p, by simp)
|
0e08821ea6927b1088281628b094f76795c352b8 | 64874bd1010548c7f5a6e3e8902efa63baaff785 | /hott/init/relation.hlean | ef673bcd5ecae80d79e3c1b54dac300e3110aece | [
"Apache-2.0"
] | permissive | tjiaqi/lean | 4634d729795c164664d10d093f3545287c76628f | d0ce4cf62f4246b0600c07e074d86e51f2195e30 | refs/heads/master | 1,622,323,796,480 | 1,422,643,069,000 | 1,422,643,069,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,439 | hlean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.logic
-- TODO(Leo): remove duplication between this file and algebra/relation.lean
-- We need some of the following definitions asap when "initializing" Lean.
variables {A B : Type} (R : B → B → Type)
local infix `≺`:50 := R
definition reflexive := ∀x, x ≺ x
definition symmetric := ∀⦃x y⦄, x ≺ y → y ≺ x
definition transitive := ∀⦃x y z⦄, x ≺ y → y ≺ z → x ≺ z
definition irreflexive := ∀x, ¬ x ≺ x
definition anti_symmetric := ∀⦃x y⦄, x ≺ y → y ≺ x → x = y
definition empty_relation := λa₁ a₂ : A, empty
definition subrelation (Q R : B → B → Type) := ∀⦃x y⦄, Q x y → R x y
definition inv_image (f : A → B) : A → A → Type :=
λa₁ a₂, f a₁ ≺ f a₂
definition inv_image.trans (f : A → B) (H : transitive R) : transitive (inv_image R f) :=
λ (a₁ a₂ a₃ : A) (H₁ : inv_image R f a₁ a₂) (H₂ : inv_image R f a₂ a₃), H H₁ H₂
definition inv_image.irreflexive (f : A → B) (H : irreflexive R) : irreflexive (inv_image R f) :=
λ (a : A) (H₁ : inv_image R f a a), H (f a) H₁
inductive tc {A : Type} (R : A → A → Type) : A → A → Type :=
base : ∀a b, R a b → tc R a b,
trans : ∀a b c, tc R a b → tc R b c → tc R a c
|
33b2698d91342eec4d448fd25ef66adc261dd1d3 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /stage0/src/Lean/Meta/DiscrTree.lean | 0bb11590eb141d5041f93ac083e26449bfd37ac8 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | EdAyers/lean4 | 57ac632d6b0789cb91fab2170e8c9e40441221bd | 37ba0df5841bde51dbc2329da81ac23d4f6a4de4 | refs/heads/master | 1,676,463,245,298 | 1,660,619,433,000 | 1,660,619,433,000 | 183,433,437 | 1 | 0 | Apache-2.0 | 1,657,612,672,000 | 1,556,196,574,000 | Lean | UTF-8 | Lean | false | false | 22,936 | 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
import Lean.Meta.WHNF
import Lean.Meta.Match.MatcherInfo
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
| Key.proj .. => 6
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₁.name n₂.name || (n₁ == n₂ && a₁ < a₂)
| Key.const n₁ a₁, Key.const n₂ a₂ => Name.quickLt n₁ n₂ || (n₁ == n₂ && a₁ < a₂)
| Key.proj s₁ i₁, Key.proj s₂ i₂ => Name.quickLt s₁ s₂ || (s₁ == s₂ && i₁ < i₂)
| 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) => Std.format v
| Key.lit (Literal.strVal v) => repr v
| Key.const k _ => Std.format k
| Key.proj s i => Std.format s ++ "." ++ Std.format i
| Key.fvar k _ => Std.format k.name
| Key.arrow => "→"
instance : ToFormat Key := ⟨Key.format⟩
def Key.arity : Key → Nat
| Key.const _ a => a
| Key.fvar _ a => a
| Key.arrow => 2
| Key.proj .. => 1
| _ => 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 " " ++ Std.format vs)
++ Format.join (cs.toList.map fun ⟨k, c⟩ => Format.line ++ Format.paren (Std.format 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 (Std.format k ++ " => " ++ Std.format 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 := { name := `_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 theorems 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 theorem 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.isInstImplicit then
return true
else if info.isImplicit || info.isStrictImplicit 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
/--
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
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 `fn` is a "bad" key. That is, `pushArgs` would add `Key.other` or `Key.star`.
We use this function when processing "root terms, and will avoid unfolding terms.
Note that without this trick the pattern `List.map f ∘ List.map g` would be mapped into the key `Key.other`
since the function composition `∘` would be unfolded and we would get `fun x => List.map g (List.map f x)`
-/
private def isBadKey (fn : Expr) : Bool :=
match fn with
| Expr.lit .. => false
| Expr.const .. => false
| Expr.fvar .. => false
| Expr.proj .. => false
| Expr.forallE _ _ b _ => b.hasLooseBVars
| _ => true
/--
Reduce `e` until we get an irreducible term (modulo current reducibility setting) or the resulting term
is a bad key (see comment at `isBadKey`).
We use this method instead of `whnfEta` for root terms at `pushArgs`. -/
private partial def whnfUntilBadKey (e : Expr) : MetaM Expr := do
let e ← step e
match e.etaExpandedStrict? with
| some e => whnfUntilBadKey e
| none => return e
where
step (e : Expr) := do
let e ← whnfCore e
match (← unfoldDefinition? e) with
| some e' => if isBadKey e'.getAppFn then return e else step e'
| none => return e
/-- whnf for the discrimination tree module -/
def whnfDT (e : Expr) (root : Bool) : MetaM Expr :=
if root then whnfUntilBadKey e else whnfEta e
/- 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 ← whnfDT e root
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.proj s i a .. =>
return (Key.proj s i, todo.push a)
| 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 (← mvarId.isReadOnlyOrSyntheticOpaque) 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, default)
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 root : Bool) : MetaM (Key × Array Expr) := do
let e ← whnfDT e root
match e.getAppFn with
| Expr.lit v => return (Key.lit v, #[])
| Expr.const c _ =>
if (← getConfig).isDefEqStuckEx && e.hasExprMVar then
if (← isReducible c) then
/- `e` is a term `c ...` s.t. `c` is reducible and `e` has metavariables, but it was not unfolded.
This can happen if the metavariables in `e` are "blocking" smart unfolding.
If `isDefEqStuckEx` is enabled, then we must throw the `isDefEqStuck` exception to postpone TC resolution.
Here is an example. Suppose we have
```
inductive Ty where
| bool | fn (a ty : Ty)
@[reducible] def Ty.interp : Ty → Type
| bool => Bool
| fn a b => a.interp → b.interp
```
and we are trying to synthesize `BEq (Ty.interp ?m)`
-/
Meta.throwIsDefEqStuck
else if let some matcherInfo := isMatcherAppCore? (← getEnv) e then
-- A matcher application is stuck is one of the discriminants has a metavariable
let args := e.getAppArgs
for arg in args[matcherInfo.getFirstDiscrPos: matcherInfo.getFirstDiscrPos + matcherInfo.numDiscrs] do
if arg.hasExprMVar then
Meta.throwIsDefEqStuck
else if (← isRec c) then
/- Similar to the previous case, but for `match` and recursor applications. It may be stuck (i.e., did not reduce)
because of metavariables. -/
Meta.throwIsDefEqStuck
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 (← mvarId.isReadOnlyOrSyntheticOpaque) then
return (Key.other, #[])
else
return (Key.star, #[])
| Expr.proj s i a .. =>
return (Key.proj s i, #[a])
| 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) (root : Bool) : MetaM (Key × Array Expr) :=
getKeyArgs e (isMatch := true) (root := root)
private abbrev getUnifyKeyArgs (e : Expr) (root : Bool) : MetaM (Key × Array Expr) :=
getKeyArgs e (isMatch := false) (root := root)
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, default) (fun a b => a.1 < b.1)
private partial def getMatchLoop (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 (root := false)
/- 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
getMatchLoop todo first.2 result
else
return result
let visitNonStar (k : Key) (args : Array Expr) (result : Array α) : MetaM (Array α) :=
match findKey cs k with
| none => return result
| some c => getMatchLoop (todo ++ args) c.2 result
let result ← visitStar result
match k with
| Key.star => return 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
private def getMatchRoot (d : DiscrTree α) (k : Key) (args : Array Expr) (result : Array α) : MetaM (Array α) :=
match d.root.find? k with
| none => return result
| some c => getMatchLoop args c result
private def getMatchCore (d : DiscrTree α) (e : Expr) : MetaM (Key × Array α) :=
withReducible do
let result := getStarResult d
let (k, args) ← getMatchKeyArgs e (root := true)
match k with
| Key.star => return (k, result)
| _ => return (k, ← getMatchRoot d k args result)
/--
Find values that match `e` in `d`.
-/
def getMatch (d : DiscrTree α) (e : Expr) : MetaM (Array α) :=
return (← getMatchCore d e).2
/--
Similar to `getMatch`, but returns solutions that are prefixes of `e`.
We store the number of ignored arguments in the result.-/
partial def getMatchWithExtra (d : DiscrTree α) (e : Expr) : MetaM (Array (α × Nat)) := do
let (k, result) ← getMatchCore d e
let result := result.map (·, 0)
if !e.isApp then
return result
else if !(← mayMatchPrefix k) then
return result
else
go e.appFn! 1 result
where
mayMatchPrefix (k : Key) : MetaM Bool :=
let cont (k : Key) : MetaM Bool :=
if d.root.find? k |>.isSome then
return true
else
mayMatchPrefix k
match k with
| Key.const f (n+1) => cont (Key.const f n)
| Key.fvar f (n+1) => cont (Key.fvar f n)
| _ => return false
go (e : Expr) (numExtra : Nat) (result : Array (α × Nat)) : MetaM (Array (α × Nat)) := do
let result := result ++ (← getMatch d e).map (., numExtra)
if e.isApp then
go e.appFn! (numExtra + 1) result
else
return result
partial def getUnify (d : DiscrTree α) (e : Expr) : MetaM (Array α) :=
withReducible do
let (k, args) ← getUnifyKeyArgs e (root := true)
match k with
| .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 _ 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 (root := false)
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 => return result
| some c => process 0 (todo ++ args) c.2 result
match k with
| .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
| .arrow => visitNonStar Key.other #[] (← visitNonStar k args (← visitStar result))
| _ => visitNonStar k args (← visitStar result)
end Lean.Meta.DiscrTree
|
194885c06bf8cdae40680b9a74d215cfcc2d979a | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/measure_theory/function/ae_eq_fun.lean | 0493fef543775867222c84cd2e4555b69b9c4e11 | [
"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 | 20,398 | lean | /-
Copyright (c) 2019 Johannes Hölzl, Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Zhouhang Zhou
-/
import measure_theory.integral.lebesgue
import order.filter.germ
import topology.continuous_function.algebra
/-!
# Almost everywhere equal functions
Two measurable functions are treated as identical if they are almost everywhere equal. We form the
set of equivalence classes under the relation of being almost everywhere equal, which is sometimes
known as the `L⁰` space.
See `l1_space.lean` for `L¹` space.
## Notation
* `α →ₘ[μ] β` is the type of `L⁰` space, where `α` and `β` are measurable spaces and `μ`
is a measure on `α`. `f : α →ₘ β` is a "function" in `L⁰`. In comments, `[f]` is also used
to denote an `L⁰` function.
`ₘ` can be typed as `\_m`. Sometimes it is shown as a box if font is missing.
## Main statements
* The linear structure of `L⁰` :
Addition and scalar multiplication are defined on `L⁰` in the natural way, i.e.,
`[f] + [g] := [f + g]`, `c • [f] := [c • f]`. So defined, `α →ₘ β` inherits the linear structure
of `β`. For example, if `β` is a module, then `α →ₘ β` is a module over the same ring.
See `mk_add_mk`, `neg_mk`, `mk_sub_mk`, `smul_mk`,
`add_to_fun`, `neg_to_fun`, `sub_to_fun`, `smul_to_fun`
* The order structure of `L⁰` :
`≤` can be defined in a similar way: `[f] ≤ [g]` if `f a ≤ g a` for almost all `a` in domain.
And `α →ₘ β` inherits the preorder and partial order of `β`.
TODO: Define `sup` and `inf` on `L⁰` so that it forms a lattice. It seems that `β` must be a
linear order, since otherwise `f ⊔ g` may not be a measurable function.
## Implementation notes
* `f.to_fun` : To find a representative of `f : α →ₘ β`, use `f.to_fun`.
For each operation `op` in `L⁰`, there is a lemma called `op_to_fun`,
characterizing, say, `(f op g).to_fun`.
* `ae_eq_fun.mk` : To constructs an `L⁰` function `α →ₘ β` from a measurable function `f : α → β`,
use `ae_eq_fun.mk`
* `comp` : Use `comp g f` to get `[g ∘ f]` from `g : β → γ` and `[f] : α →ₘ γ`
* `comp₂` : Use `comp₂ g f₁ f₂ to get `[λa, g (f₁ a) (f₂ a)]`.
For example, `[f + g]` is `comp₂ (+)`
## Tags
function space, almost everywhere equal, `L⁰`, ae_eq_fun
-/
noncomputable theory
open_locale classical ennreal
open set filter topological_space ennreal emetric measure_theory function
variables {α β γ δ : Type*} [measurable_space α] {μ ν : measure α}
namespace measure_theory
section measurable_space
variables [measurable_space β]
variable (β)
/-- The equivalence relation of being almost everywhere equal -/
def measure.ae_eq_setoid (μ : measure α) : setoid { f : α → β // ae_measurable f μ } :=
⟨λf g, (f : α → β) =ᵐ[μ] g, λ f, ae_eq_refl f, λ f g, ae_eq_symm, λ f g h, ae_eq_trans⟩
variable (α)
/-- The space of equivalence classes of measurable functions, where two measurable functions are
equivalent if they agree almost everywhere, i.e., they differ on a set of measure `0`. -/
def ae_eq_fun (μ : measure α) : Type* := quotient (μ.ae_eq_setoid β)
variables {α β}
notation α ` →ₘ[`:25 μ `] ` β := ae_eq_fun α β μ
end measurable_space
namespace ae_eq_fun
variables [measurable_space β] [measurable_space γ] [measurable_space δ]
/-- Construct the equivalence class `[f]` of an almost everywhere measurable function `f`, based
on the equivalence relation of being almost everywhere equal. -/
def mk (f : α → β) (hf : ae_measurable f μ) : α →ₘ[μ] β := quotient.mk' ⟨f, hf⟩
/-- A measurable representative of an `ae_eq_fun` [f] -/
instance : has_coe_to_fun (α →ₘ[μ] β) (λ _, α → β) :=
⟨λf, ae_measurable.mk _ (quotient.out' f : {f : α → β // ae_measurable f μ}).2⟩
protected lemma measurable (f : α →ₘ[μ] β) : measurable f :=
ae_measurable.measurable_mk _
protected lemma ae_measurable (f : α →ₘ[μ] β) : ae_measurable f μ :=
f.measurable.ae_measurable
@[simp] lemma quot_mk_eq_mk (f : α → β) (hf) :
(quot.mk (@setoid.r _ $ μ.ae_eq_setoid β) ⟨f, hf⟩ : α →ₘ[μ] β) = mk f hf :=
rfl
@[simp] lemma mk_eq_mk {f g : α → β} {hf hg} :
(mk f hf : α →ₘ[μ] β) = mk g hg ↔ f =ᵐ[μ] g :=
quotient.eq'
@[simp] lemma mk_coe_fn (f : α →ₘ[μ] β) : mk f f.ae_measurable = f :=
begin
conv_rhs { rw ← quotient.out_eq' f },
set g : {f : α → β // ae_measurable f μ} := quotient.out' f with hg,
have : g = ⟨g.1, g.2⟩ := subtype.eq rfl,
rw [this, ← mk, mk_eq_mk],
exact (ae_measurable.ae_eq_mk _).symm,
end
@[ext] lemma ext {f g : α →ₘ[μ] β} (h : f =ᵐ[μ] g) : f = g :=
by rwa [← f.mk_coe_fn, ← g.mk_coe_fn, mk_eq_mk]
lemma ext_iff {f g : α →ₘ[μ] β} : f = g ↔ f =ᵐ[μ] g :=
⟨λ h, by rw h, λ h, ext h⟩
lemma coe_fn_mk (f : α → β) (hf) : (mk f hf : α →ₘ[μ] β) =ᵐ[μ] f :=
begin
apply (ae_measurable.ae_eq_mk _).symm.trans,
exact @quotient.mk_out' _ (μ.ae_eq_setoid β) (⟨f, hf⟩ : {f // ae_measurable f μ})
end
@[elab_as_eliminator]
lemma induction_on (f : α →ₘ[μ] β) {p : (α →ₘ[μ] β) → Prop} (H : ∀ f hf, p (mk f hf)) : p f :=
quotient.induction_on' f $ subtype.forall.2 H
@[elab_as_eliminator]
lemma induction_on₂ {α' β' : Type*} [measurable_space α'] [measurable_space β'] {μ' : measure α'}
(f : α →ₘ[μ] β) (f' : α' →ₘ[μ'] β') {p : (α →ₘ[μ] β) → (α' →ₘ[μ'] β') → Prop}
(H : ∀ f hf f' hf', p (mk f hf) (mk f' hf')) :
p f f' :=
induction_on f $ λ f hf, induction_on f' $ H f hf
@[elab_as_eliminator]
lemma induction_on₃ {α' β' : Type*} [measurable_space α'] [measurable_space β'] {μ' : measure α'}
{α'' β'' : Type*} [measurable_space α''] [measurable_space β''] {μ'' : measure α''}
(f : α →ₘ[μ] β) (f' : α' →ₘ[μ'] β') (f'' : α'' →ₘ[μ''] β'')
{p : (α →ₘ[μ] β) → (α' →ₘ[μ'] β') → (α'' →ₘ[μ''] β'') → Prop}
(H : ∀ f hf f' hf' f'' hf'', p (mk f hf) (mk f' hf') (mk f'' hf'')) :
p f f' f'' :=
induction_on f $ λ f hf, induction_on₂ f' f'' $ H f hf
/-- Given a measurable function `g : β → γ`, and an almost everywhere equal function `[f] : α →ₘ β`,
return the equivalence class of `g ∘ f`, i.e., the almost everywhere equal function
`[g ∘ f] : α →ₘ γ`. -/
def comp (g : β → γ) (hg : measurable g) (f : α →ₘ[μ] β) : α →ₘ[μ] γ :=
quotient.lift_on' f (λ f, mk (g ∘ (f : α → β)) (hg.comp_ae_measurable f.2)) $
λ f f' H, mk_eq_mk.2 $ H.fun_comp g
@[simp] lemma comp_mk (g : β → γ) (hg : measurable g)
(f : α → β) (hf) :
comp g hg (mk f hf : α →ₘ[μ] β) = mk (g ∘ f) (hg.comp_ae_measurable hf) :=
rfl
lemma comp_eq_mk (g : β → γ) (hg : measurable g) (f : α →ₘ[μ] β) :
comp g hg f = mk (g ∘ f) (hg.comp_ae_measurable f.ae_measurable) :=
by rw [← comp_mk g hg f f.ae_measurable, mk_coe_fn]
lemma coe_fn_comp (g : β → γ) (hg : measurable g) (f : α →ₘ[μ] β) :
comp g hg f =ᵐ[μ] g ∘ f :=
by { rw [comp_eq_mk], apply coe_fn_mk }
/-- The class of `x ↦ (f x, g x)`. -/
def pair (f : α →ₘ[μ] β) (g : α →ₘ[μ] γ) : α →ₘ[μ] β × γ :=
quotient.lift_on₂' f g (λ f g, mk (λ x, (f.1 x, g.1 x)) (f.2.prod_mk g.2)) $
λ f g f' g' Hf Hg, mk_eq_mk.2 $ Hf.prod_mk Hg
@[simp] lemma pair_mk_mk (f : α → β) (hf) (g : α → γ) (hg) :
(mk f hf : α →ₘ[μ] β).pair (mk g hg) = mk (λ x, (f x, g x)) (hf.prod_mk hg) :=
rfl
lemma pair_eq_mk (f : α →ₘ[μ] β) (g : α →ₘ[μ] γ) :
f.pair g = mk (λ x, (f x, g x)) (f.ae_measurable.prod_mk g.ae_measurable) :=
by simp only [← pair_mk_mk, mk_coe_fn]
lemma coe_fn_pair (f : α →ₘ[μ] β) (g : α →ₘ[μ] γ) :
f.pair g =ᵐ[μ] (λ x, (f x, g x)) :=
by { rw pair_eq_mk, apply coe_fn_mk }
/-- Given a measurable function `g : β → γ → δ`, and almost everywhere equal functions
`[f₁] : α →ₘ β` and `[f₂] : α →ₘ γ`, return the equivalence class of the function
`λa, g (f₁ a) (f₂ a)`, i.e., the almost everywhere equal function
`[λa, g (f₁ a) (f₂ a)] : α →ₘ γ` -/
def comp₂ {γ δ : Type*} [measurable_space γ] [measurable_space δ] (g : β → γ → δ)
(hg : measurable (uncurry g)) (f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) : α →ₘ[μ] δ :=
comp _ hg (f₁.pair f₂)
@[simp] lemma comp₂_mk_mk {γ δ : Type*} [measurable_space γ] [measurable_space δ]
(g : β → γ → δ) (hg : measurable (uncurry g)) (f₁ : α → β) (f₂ : α → γ) (hf₁ hf₂) :
comp₂ g hg (mk f₁ hf₁ : α →ₘ[μ] β) (mk f₂ hf₂) =
mk (λa, g (f₁ a) (f₂ a)) (hg.comp_ae_measurable (hf₁.prod_mk hf₂)) :=
rfl
lemma comp₂_eq_pair {γ δ : Type*} [measurable_space γ] [measurable_space δ]
(g : β → γ → δ) (hg : measurable (uncurry g)) (f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) :
comp₂ g hg f₁ f₂ = comp _ hg (f₁.pair f₂) :=
rfl
lemma comp₂_eq_mk {γ δ : Type*} [measurable_space γ] [measurable_space δ]
(g : β → γ → δ) (hg : measurable (uncurry g)) (f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) :
comp₂ g hg f₁ f₂ = mk (λ a, g (f₁ a) (f₂ a))
(hg.comp_ae_measurable (f₁.ae_measurable.prod_mk f₂.ae_measurable)) :=
by rw [comp₂_eq_pair, pair_eq_mk, comp_mk]; refl
lemma coe_fn_comp₂ {γ δ : Type*} [measurable_space γ] [measurable_space δ]
(g : β → γ → δ) (hg : measurable (uncurry g)) (f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) :
comp₂ g hg f₁ f₂ =ᵐ[μ] λ a, g (f₁ a) (f₂ a) :=
by { rw comp₂_eq_mk, apply coe_fn_mk }
/-- Interpret `f : α →ₘ[μ] β` as a germ at `μ.ae` forgetting that `f` is almost everywhere
measurable. -/
def to_germ (f : α →ₘ[μ] β) : germ μ.ae β :=
quotient.lift_on' f (λ f, ((f : α → β) : germ μ.ae β)) $ λ f g H, germ.coe_eq.2 H
@[simp] lemma mk_to_germ (f : α → β) (hf) : (mk f hf : α →ₘ[μ] β).to_germ = f := rfl
lemma to_germ_eq (f : α →ₘ[μ] β) : f.to_germ = (f : α → β) :=
by rw [← mk_to_germ, mk_coe_fn]
lemma to_germ_injective : injective (to_germ : (α →ₘ[μ] β) → germ μ.ae β) :=
λ f g H, ext $ germ.coe_eq.1 $ by rwa [← to_germ_eq, ← to_germ_eq]
lemma comp_to_germ (g : β → γ) (hg : measurable g) (f : α →ₘ[μ] β) :
(comp g hg f).to_germ = f.to_germ.map g :=
induction_on f $ λ f hf, by simp
lemma comp₂_to_germ (g : β → γ → δ) (hg : measurable (uncurry g))
(f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) :
(comp₂ g hg f₁ f₂).to_germ = f₁.to_germ.map₂ g f₂.to_germ :=
induction_on₂ f₁ f₂ $ λ f₁ hf₁ f₂ hf₂, by simp
/-- Given a predicate `p` and an equivalence class `[f]`, return true if `p` holds of `f a`
for almost all `a` -/
def lift_pred (p : β → Prop) (f : α →ₘ[μ] β) : Prop := f.to_germ.lift_pred p
/-- Given a relation `r` and equivalence class `[f]` and `[g]`, return true if `r` holds of
`(f a, g a)` for almost all `a` -/
def lift_rel (r : β → γ → Prop) (f : α →ₘ[μ] β) (g : α →ₘ[μ] γ) : Prop :=
f.to_germ.lift_rel r g.to_germ
lemma lift_rel_mk_mk {r : β → γ → Prop} {f : α → β} {g : α → γ} {hf hg} :
lift_rel r (mk f hf : α →ₘ[μ] β) (mk g hg) ↔ ∀ᵐ a ∂μ, r (f a) (g a) :=
iff.rfl
lemma lift_rel_iff_coe_fn {r : β → γ → Prop} {f : α →ₘ[μ] β} {g : α →ₘ[μ] γ} :
lift_rel r f g ↔ ∀ᵐ a ∂μ, r (f a) (g a) :=
by rw [← lift_rel_mk_mk, mk_coe_fn, mk_coe_fn]
section order
instance [preorder β] : preorder (α →ₘ[μ] β) := preorder.lift to_germ
@[simp] lemma mk_le_mk [preorder β] {f g : α → β} (hf hg) :
(mk f hf : α →ₘ[μ] β) ≤ mk g hg ↔ f ≤ᵐ[μ] g :=
iff.rfl
@[simp, norm_cast] lemma coe_fn_le [preorder β] {f g : α →ₘ[μ] β} :
(f : α → β) ≤ᵐ[μ] g ↔ f ≤ g :=
lift_rel_iff_coe_fn.symm
instance [partial_order β] : partial_order (α →ₘ[μ] β) :=
partial_order.lift to_germ to_germ_injective
/- TODO: Prove `L⁰` space is a lattice if β is linear order.
What if β is only a lattice? -/
-- instance [linear_order β] : semilattice_sup (α →ₘ β) :=
-- { sup := comp₂ (⊔) (_),
-- .. ae_eq_fun.partial_order }
end order
variable (α)
/-- The equivalence class of a constant function: `[λa:α, b]`, based on the equivalence relation of
being almost everywhere equal -/
def const (b : β) : α →ₘ[μ] β := mk (λa:α, b) ae_measurable_const
lemma coe_fn_const (b : β) : (const α b : α →ₘ[μ] β) =ᵐ[μ] function.const α b :=
coe_fn_mk _ _
variable {α}
instance [inhabited β] : inhabited (α →ₘ[μ] β) := ⟨const α (default β)⟩
@[to_additive] instance [has_one β] : has_one (α →ₘ[μ] β) := ⟨const α 1⟩
@[to_additive] lemma one_def [has_one β] :
(1 : α →ₘ[μ] β) = mk (λa:α, 1) ae_measurable_const := rfl
@[to_additive] lemma coe_fn_one [has_one β] : ⇑(1 : α →ₘ[μ] β) =ᵐ[μ] 1 := coe_fn_const _ _
@[simp, to_additive] lemma one_to_germ [has_one β] : (1 : α →ₘ[μ] β).to_germ = 1 := rfl
section monoid
variables
[topological_space γ] [second_countable_topology γ] [borel_space γ]
[monoid γ] [has_continuous_mul γ]
@[to_additive]
instance : has_mul (α →ₘ[μ] γ) := ⟨comp₂ (*) measurable_mul⟩
@[simp, to_additive] lemma mk_mul_mk (f g : α → γ) (hf hg) :
(mk f hf : α →ₘ[μ] γ) * (mk g hg) = mk (f * g) (hf.mul hg) :=
rfl
@[to_additive] lemma coe_fn_mul (f g : α →ₘ[μ] γ) : ⇑(f * g) =ᵐ[μ] f * g := coe_fn_comp₂ _ _ _ _
@[simp, to_additive] lemma mul_to_germ (f g : α →ₘ[μ] γ) :
(f * g).to_germ = f.to_germ * g.to_germ :=
comp₂_to_germ _ _ _ _
@[to_additive]
instance : monoid (α →ₘ[μ] γ) :=
to_germ_injective.monoid to_germ one_to_germ mul_to_germ
end monoid
@[to_additive]
instance comm_monoid [topological_space γ] [second_countable_topology γ] [borel_space γ]
[comm_monoid γ] [has_continuous_mul γ] : comm_monoid (α →ₘ[μ] γ) :=
to_germ_injective.comm_monoid to_germ one_to_germ mul_to_germ
section group
variables [topological_space γ] [borel_space γ] [group γ] [topological_group γ]
@[to_additive] instance : has_inv (α →ₘ[μ] γ) := ⟨comp has_inv.inv measurable_inv⟩
@[simp, to_additive] lemma inv_mk (f : α → γ) (hf) : (mk f hf : α →ₘ[μ] γ)⁻¹ = mk f⁻¹ hf.inv := rfl
@[to_additive] lemma coe_fn_inv (f : α →ₘ[μ] γ) : ⇑(f⁻¹) =ᵐ[μ] f⁻¹ := coe_fn_comp _ _ _
@[to_additive] lemma inv_to_germ (f : α →ₘ[μ] γ) : (f⁻¹).to_germ = f.to_germ⁻¹ := comp_to_germ _ _ _
variables [second_countable_topology γ]
@[to_additive] instance : has_div (α →ₘ[μ] γ) := ⟨comp₂ has_div.div measurable_div⟩
@[simp, to_additive] lemma mk_div (f g : α → γ) (hf hg) :
mk (f / g) (ae_measurable.div hf hg) = (mk f hf : α →ₘ[μ] γ) / (mk g hg) :=
rfl
@[to_additive] lemma coe_fn_div (f g : α →ₘ[μ] γ) : ⇑(f / g) =ᵐ[μ] f / g := coe_fn_comp₂ _ _ _ _
@[to_additive] lemma div_to_germ (f g : α →ₘ[μ] γ) : (f / g).to_germ = f.to_germ / g.to_germ :=
comp₂_to_germ _ _ _ _
@[to_additive]
instance : group (α →ₘ[μ] γ) :=
to_germ_injective.group _ one_to_germ mul_to_germ inv_to_germ div_to_germ
end group
@[to_additive]
instance [topological_space γ] [borel_space γ] [comm_group γ] [topological_group γ]
[second_countable_topology γ] : comm_group (α →ₘ[μ] γ) :=
{ .. ae_eq_fun.group, .. ae_eq_fun.comm_monoid }
section module
variables {𝕜 : Type*} [semiring 𝕜] [topological_space 𝕜] [measurable_space 𝕜]
[opens_measurable_space 𝕜]
variables [topological_space γ] [borel_space γ] [add_comm_monoid γ] [module 𝕜 γ]
[has_continuous_smul 𝕜 γ]
instance : has_scalar 𝕜 (α →ₘ[μ] γ) :=
⟨λ c f, comp ((•) c) (measurable_id.const_smul c) f⟩
@[simp] lemma smul_mk (c : 𝕜) (f : α → γ) (hf) :
c • (mk f hf : α →ₘ[μ] γ) = mk (c • f) (hf.const_smul _) :=
rfl
lemma coe_fn_smul (c : 𝕜) (f : α →ₘ[μ] γ) : ⇑(c • f) =ᵐ[μ] c • f := coe_fn_comp _ _ _
lemma smul_to_germ (c : 𝕜) (f : α →ₘ[μ] γ) : (c • f).to_germ = c • f.to_germ :=
comp_to_germ _ _ _
variables [second_countable_topology γ] [has_continuous_add γ]
instance : module 𝕜 (α →ₘ[μ] γ) :=
to_germ_injective.module 𝕜 ⟨@to_germ α γ _ μ _, zero_to_germ, add_to_germ⟩ smul_to_germ
end module
open ennreal
/-- For `f : α → ℝ≥0∞`, define `∫ [f]` to be `∫ f` -/
def lintegral (f : α →ₘ[μ] ℝ≥0∞) : ℝ≥0∞ :=
quotient.lift_on' f (λf, ∫⁻ a, (f : α → ℝ≥0∞) a ∂μ) (assume f g, lintegral_congr_ae)
@[simp] lemma lintegral_mk (f : α → ℝ≥0∞) (hf) :
(mk f hf : α →ₘ[μ] ℝ≥0∞).lintegral = ∫⁻ a, f a ∂μ := rfl
lemma lintegral_coe_fn (f : α →ₘ[μ] ℝ≥0∞) : ∫⁻ a, f a ∂μ = f.lintegral :=
by rw [← lintegral_mk, mk_coe_fn]
@[simp] lemma lintegral_zero : lintegral (0 : α →ₘ[μ] ℝ≥0∞) = 0 := lintegral_zero
@[simp] lemma lintegral_eq_zero_iff {f : α →ₘ[μ] ℝ≥0∞} : lintegral f = 0 ↔ f = 0 :=
induction_on f $ λ f hf, (lintegral_eq_zero_iff' hf).trans mk_eq_mk.symm
lemma lintegral_add (f g : α →ₘ[μ] ℝ≥0∞) : lintegral (f + g) = lintegral f + lintegral g :=
induction_on₂ f g $ λ f hf g hg, by simp [lintegral_add' hf hg]
lemma lintegral_mono {f g : α →ₘ[μ] ℝ≥0∞} : f ≤ g → lintegral f ≤ lintegral g :=
induction_on₂ f g $ λ f hf g hg hfg, lintegral_mono_ae hfg
section pos_part
variables [topological_space γ] [linear_order γ] [order_closed_topology γ]
[second_countable_topology γ] [has_zero γ] [opens_measurable_space γ]
/-- Positive part of an `ae_eq_fun`. -/
def pos_part (f : α →ₘ[μ] γ) : α →ₘ[μ] γ :=
comp (λ x, max x 0) (measurable_id.max measurable_const) f
@[simp] lemma pos_part_mk (f : α → γ) (hf) :
pos_part (mk f hf : α →ₘ[μ] γ) = mk (λ x, max (f x) 0) (hf.max ae_measurable_const) :=
rfl
lemma coe_fn_pos_part (f : α →ₘ[μ] γ) : ⇑(pos_part f) =ᵐ[μ] (λ a, max (f a) 0) :=
coe_fn_comp _ _ _
end pos_part
end ae_eq_fun
end measure_theory
namespace continuous_map
open measure_theory
variables [topological_space α] [borel_space α] (μ)
variables [topological_space β] [measurable_space β] [borel_space β]
/-- The equivalence class of `μ`-almost-everywhere measurable functions associated to a continuous
map. -/
def to_ae_eq_fun (f : C(α, β)) : α →ₘ[μ] β :=
ae_eq_fun.mk f f.continuous.measurable.ae_measurable
lemma coe_fn_to_ae_eq_fun (f : C(α, β)) : f.to_ae_eq_fun μ =ᵐ[μ] f :=
ae_eq_fun.coe_fn_mk f _
variables [group β] [topological_group β] [second_countable_topology β]
/-- The `mul_hom` from the group of continuous maps from `α` to `β` to the group of equivalence
classes of `μ`-almost-everywhere measurable functions. -/
@[to_additive "The `add_hom` from the group of continuous maps from `α` to `β` to the group of
equivalence classes of `μ`-almost-everywhere measurable functions."]
def to_ae_eq_fun_mul_hom : C(α, β) →* α →ₘ[μ] β :=
{ to_fun := continuous_map.to_ae_eq_fun μ,
map_one' := rfl,
map_mul' := λ f g, ae_eq_fun.mk_mul_mk f g f.continuous.measurable.ae_measurable
g.continuous.measurable.ae_measurable }
variables {𝕜 : Type*} [semiring 𝕜] [topological_space 𝕜] [measurable_space 𝕜]
[opens_measurable_space 𝕜]
variables [topological_space γ] [measurable_space γ] [borel_space γ] [add_comm_group γ]
[module 𝕜 γ] [topological_add_group γ] [has_continuous_smul 𝕜 γ]
[second_countable_topology γ]
/-- The linear map from the group of continuous maps from `α` to `β` to the group of equivalence
classes of `μ`-almost-everywhere measurable functions. -/
def to_ae_eq_fun_linear_map : C(α, γ) →ₗ[𝕜] α →ₘ[μ] γ :=
{ map_smul' := λ c f, ae_eq_fun.smul_mk c f f.continuous.measurable.ae_measurable,
.. to_ae_eq_fun_add_hom μ }
end continuous_map
|
5f7f11d6d394f4f42b20bfb1d20922ba613fb5bc | 92b1c7f0343a6a5cd36bc0f623a7490da3f1e0f3 | /src/lib/attributed/probability_theory.lean | 4410474b27a9476df2d8b3b2b6f9b8c1427db3ac | [
"Apache-2.0"
] | permissive | jtristan/stump-learnable | 717453eb590af16e60c7d3806cc9e66492fab091 | aa3c089f41602efa08d31ef6b41e549456186d57 | refs/heads/master | 1,625,630,634,360 | 1,607,552,106,000 | 1,607,552,106,000 | 218,629,406 | 15 | 2 | null | null | null | null | UTF-8 | Lean | false | false | 18,004 | lean | /-
Probability theory generalities.
Some parts of this file are originally from
https://github.com/johoelzl/mathlib/blob/c9507242274ac18defbceb917f30d6afb8b839a5/src/probability_theory/basic.lean
Authors: Johannes Holzl, Koundinya Vajjha
-/
import measure_theory.measure_space tactic.tidy measure_theory.giry_monad
local attribute [instance] classical.prop_decidable
noncomputable theory
open measure_theory ennreal lattice measure_theory measure_theory.measure set
universe u
section
variables (α : Type*) [measurable_space α]
structure probability_measure extends measure_theory.measure α :=
(measure_univ : to_measure univ = 1)
instance : measurable_space (probability_measure α) :=
measure.measurable_space.comap probability_measure.to_measure
lemma measurable_to_measure :
measurable (@probability_measure.to_measure α _) :=
measurable_space.le_map_comap
instance prob_measure_coe : has_coe (probability_measure α) (measure α) :=
⟨probability_measure.to_measure⟩
instance : has_coe_to_fun (probability_measure α) :=
⟨λ_, set α → nnreal, λp s, ennreal.to_nnreal (p.to_measure s)⟩
end
namespace probability_measure
section
parameters {α : Type*} [measurable_space α] (p : probability_measure α)
lemma to_measure_lt_top (s : set α) : p.to_measure s < ⊤ :=
lt_of_le_of_lt (measure_mono $ subset_univ s) $ p.measure_univ.symm ▸ coe_lt_top
lemma to_measure_ne_top (s : set α) : p.to_measure s ≠ ⊤ :=
lt_top_iff_ne_top.1 (to_measure_lt_top s)
lemma coe_eq_to_measure (s : set α) : (p s : ennreal) = p.to_measure s :=
coe_to_nnreal (to_measure_ne_top s)
@[simp] lemma prob_apply {α : Type u} [measurable_space α] {s : set α}(hs : is_measurable s) (p : probability_measure α) :
(p : probability_measure α) s = ennreal.to_nnreal (p.to_measure s)
:= rfl
@[extensionality] lemma prob.ext {α} [measurable_space α] :
∀ {μ₁ μ₂ : probability_measure α}, (∀s, is_measurable s → μ₁ s = μ₂ s) → μ₁ = μ₂
| ⟨m₁, u₁⟩ ⟨m₂, u₂⟩ H := begin
congr, refine measure.ext (λ s hs, _),
have : (ennreal.to_nnreal (m₁ s) : ennreal) = ennreal.to_nnreal (m₂ s) :=
congr_arg coe (H s hs),
rwa [coe_to_nnreal, coe_to_nnreal] at this,
apply lt_top_iff_ne_top.1 (lt_of_le_of_lt (measure_mono $ subset_univ s) $ by rw u₂ ; exact ennreal.lt_top_iff_ne_top.2 one_ne_top),
apply lt_top_iff_ne_top.1 (lt_of_le_of_lt (measure_mono $ subset_univ s) $ by rw u₁ ; exact ennreal.lt_top_iff_ne_top.2 one_ne_top)
end
@[simp] lemma prob_empty : p ∅ = 0 :=
by rw [← coe_eq_coe, coe_eq_to_measure, measure_empty, coe_zero]
@[simp] lemma prob_univ : p univ = 1 :=
by rw [← coe_eq_coe, coe_eq_to_measure]; exact p.measure_univ
@[simp] lemma prob_mono {s t} (h : s ⊆ t) : p s ≤ p t :=
by rw [← coe_le_coe, coe_eq_to_measure, coe_eq_to_measure]; exact measure_mono h
lemma prob_le_1 (a : set α):
p a ≤ (1:nnreal) :=
begin
intros,
rewrite ← prob_univ p,
apply prob_mono,
apply subset_univ,
end
lemma prob_mono_null {s t} (h : t ⊆ s) (h₂ : p s = 0) : p t = 0 :=
by rw [← le_zero_iff_eq, ← h₂]; exact prob_mono p h
lemma prob_Union_null {β} [encodable β] {s : β → set α} (h : ∀ i, p (s i) = 0) : p (⋃i, s i) = 0 :=
begin
rw [← coe_eq_coe, coe_eq_to_measure, measure_Union_null, coe_zero],
assume i, specialize h i, rwa [← coe_eq_coe, coe_eq_to_measure] at h
end
theorem prob_union_le (s₁ s₂ : set α) : p (s₁ ∪ s₂) ≤ p s₁ + p s₂ :=
by simp only [coe_le_coe.symm, coe_add, coe_eq_to_measure]; exact measure_union_le _ _
lemma prob_union {s₁ s₂ : set α}
(hd : disjoint s₁ s₂) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) :
p (s₁ ∪ s₂) = p s₁ + p s₂ :=
by simp only [coe_eq_coe.symm, coe_add, coe_eq_to_measure]; exact measure_union hd h₁ h₂
lemma prob_diff {s₁ s₂ : set α} (h : s₂ ⊆ s₁) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) :
p (s₁ \ s₂) = p s₁ - p s₂ :=
by simp only [coe_eq_coe.symm, coe_sub, coe_eq_to_measure];
exact measure_diff h h₁ h₂ (to_measure_lt_top _ _)
lemma prob_diff_inter
{a b : set α} (h₁ : is_measurable a) (h₂ : is_measurable b) :
p(b ∩ -a) + p(b ∩ a) = p(b) :=
begin
have h :p(b) = p(b ∩ univ),
by rewrite inter_univ b,
rewrite [h,← compl_union_self a,set.inter_distrib_left,prob_union],
have g : (b ∩ -a) ∩ (b ∩ a) = ∅, by rw [inter_left_comm,set.inter_assoc, compl_inter_self,inter_empty,inter_empty],
apply disjoint_iff.2 g,
{
rewrite ← diff_eq,
apply is_measurable.diff h₂ h₁,
},
apply is_measurable.inter h₂ h₁,
end
lemma prob_union_inter
(a b : set α) (g₁ : is_measurable a) (g₂ : is_measurable b) :
p(a ∪ b) + p(a ∩ b) = p(a) + p(b) :=
begin
have h₁ : a ∪ b = a ∪ (b ∩ -a),by
rw [set.union_distrib_left, union_compl_self a,inter_univ],
have h₂ : is_measurable(b ∩ -a), by exact is_measurable.diff g₂ g₁,
have h₃ : a ∩ (b ∩ -a) = ∅, by tidy,
rw h₁,
rw [prob_union p (disjoint_iff.2 h₃) g₁ h₂],
rw [←prob_diff_inter p g₁ g₂],
simp,
rw [inter_comm],
end
lemma prob_comp (a : set α) (h: is_measurable a) : p(-a) + p(a) = 1 :=
begin
intros, rw ← prob_univ p, rw [←prob_union], simp,
exact disjoint_iff.2 (@compl_inter_self _ a),
apply is_measurable.compl h,
assumption,
end
/-- The Bonnferroni inequality. -/
lemma prob_add_le_inter_add_one
(a b : set α) (h_1 : is_measurable a) (h_2 : is_measurable b) :
p(a) + p(b) ≤ p(a ∩ b) + 1 :=
begin
rw [← prob_union_inter p a b h_1 h_2, ← add_comm],
exact add_le_add_left' (prob_le_1 p (a ∪ b)),
end
protected lemma nonempty : nonempty α :=
classical.by_contradiction $ assume h,
have 0 = p univ, by rw [univ_eq_empty_iff.2 h]; exact p.prob_empty.symm,
@zero_ne_one nnreal _ $ by rwa [p.prob_univ] at this
@[simp] lemma integral_const (r : ennreal) : integral p.to_measure (λa, r) = r :=
suffices integral p.to_measure (λa, ⨆ (h : a ∈ (univ : set α)), r) =
r * p.to_measure univ, by rw [← coe_eq_to_measure] at this; simpa,
@lintegral_supr_const α { μ := p.to_measure } r _ is_measurable.univ
lemma integral_univ : integral p.to_measure (λ a, 1) = 1 := by simp
-- somehow we need δ ≤ 1 o/w coercion hell.
lemma neq_prob_set {α : Type} [measurable_space α] (f : α → nnreal) (μ : probability_measure α) (ε δ : nnreal) (hd : δ ≤ 1) (hS : is_measurable ({x : α | f x > ε})) : μ({x : α | f x > ε}) ≤ δ ↔ μ ({x : α | f x ≤ ε}) ≥ 1 - δ :=
begin
rw nnreal.coe_le,
have h₀ : {x : α | f x > ε} = - {x : α | f x ≤ ε},by tidy,
have h₁ : - {x : α | f x > ε} = {x : α | f x ≤ ε}, by tidy,
have h₃ : (μ ({x : α | f x > ε}) : ℝ) + μ{x : α | f x ≤ ε} = 1, {
rw ←nnreal.coe_add, rw h₀, rw prob_comp, simp, rw ←h₁,
apply is_measurable.compl hS,
},
have h₅ : (μ ({x : α | f x > ε}) : ℝ) = 1 - μ ({x : α | f x ≤ ε}),
{
rw ←h₃, symmetry, rw add_sub_cancel,
},
rw h₅, rw sub_le_iff_le_add',
rw add_comm, rw ←sub_le_iff_le_add', rw ←nnreal.coe_one,
rw ←nnreal.coe_sub _ _ hd, rw ←nnreal.coe_le,
end
lemma neq_prob_set' {α : Type} [measurable_space α] (f : α → nnreal) (μ : probability_measure α) (ε δ : nnreal) (hd : δ ≤ 1) (hS : is_measurable ({x : α | f x > ε})) : μ({x : α | f x > ε}) ≤ δ ↔ μ ({x : α | f x ≤ ε}) + δ ≥ 1 :=
begin
have h₀ : {x : α | f x > ε} = - {x : α | f x ≤ ε},by tidy,
have h₁ : - {x : α | f x > ε} = {x : α | f x ≤ ε}, by tidy,
have h₃ : (μ ({x : α | f x > ε})) + μ{x : α | f x ≤ ε} = 1, {
rw h₀, rw prob_comp, rw ←h₁, apply is_measurable.compl hS,
},
symmetry, rw ← h₃, rw add_comm,
rw ←add_le_add_iff_right,
end
lemma prob_trivial {α: Type} [measurable_space α]:
∀ P: α → Prop, ∀ μ: probability_measure α,
(∀ x, P x) → μ {x: α | P x} = 1 :=
begin
intros,
have UNIV : {x: α | P x} = univ,
{
apply eq_univ_of_forall,
intro,
rw mem_set_of_eq,
apply a,
},
rw UNIV,
apply prob_univ,
end
end
end probability_measure
section giry_monad
variables {α : Type*} {β : Type*} {γ : Type*}
variables [measurable_space α] [measurable_space β] [measurable_space γ]
def pure (a : α) : probability_measure α :=
⟨measure.dirac a, by rw [measure_theory.measure.dirac_apply a is_measurable.univ]; simp⟩
def map (f : α → β) (p : probability_measure α) : probability_measure β :=
if h : measurable f then
⟨measure.map f p, by rw [measure_theory.measure.map_apply h is_measurable.univ, preimage_univ]; exact p.measure_univ⟩
else
pure (f $ classical.choice p.nonempty)
def join (m : probability_measure (probability_measure α)) : probability_measure α :=
⟨measure_theory.measure.bind m.to_measure probability_measure.to_measure,
by rw [measure_theory.measure.bind_apply is_measurable.univ (measurable_to_measure α)];
simp [probability_measure.measure_univ]⟩
def bind (m : probability_measure α) (f : α → probability_measure β) : probability_measure β :=
join (map f m)
def dirac (a : α) : probability_measure α :=
⟨ measure.dirac a , by rw [dirac_apply _ is_measurable.univ]; simp ⟩
@[simp] theorem map_apply {f : α → β} (μ : probability_measure α) (hf : measurable f)
{s : set β} (hs : is_measurable s) :
(map f μ : probability_measure β) s = μ (f ⁻¹' s) :=
begin
rw _root_.map, rw dif_pos hf, unfold_coes, congr, simp, apply measure_theory.measure.map_apply hf hs,
end
@[simp] lemma join_apply {m : probability_measure (probability_measure α)} :
∀{s : set α}, is_measurable s → (join m : probability_measure α) s = (integral m.to_measure (λμ, μ s)).to_nnreal :=
begin
intros s hs,
rw _root_.join,
transitivity,
unfold_coes, congr, simp, transitivity,
refine measure_theory.measure.bind_apply hs (measurable_to_measure _),
congr, funext, symmetry, transitivity,
apply coe_to_nnreal, apply probability_measure.to_measure_ne_top, refl,
end
lemma prob.measurable_coe {s : set α} (hs : is_measurable s) : measurable (λμ : probability_measure α, μ s) :=
begin
have h : (λ (μ : probability_measure α), μ s) =
(λ μ:measure α, (μ s).to_nnreal) ∘ (λ μ:probability_measure α, μ.to_measure),by refl,
rw h,
refine measurable.comp _ (measurable_to_measure _),
refine measurable.comp _ (measurable_coe hs),
refine measurable_of_measurable_nnreal _, simp,
exact measurable_id,
end
-- TODO(Kody) : Get rid of the tidy part at the end. (Makes it slow!)
lemma prob.measurable_coe_iff_measurable_to_measure (f : β → probability_measure α) :
measurable f ↔ measurable ((λ μ:probability_measure α, μ.to_measure) ∘ f ) :=
begin
fsplit,
{intro hf, exact measurable.comp (measurable_to_measure _) hf},
{intros hf s hs,
refine measurable_space.comap_le_iff_le_map.1 _ _ _,
exact measure.measurable_space.comap probability_measure.to_measure
,
simp, tidy,}
end
lemma prob.measurable_measure_kernel [measurable_space α] [measurable_space β] {f : α → probability_measure β} {A : set β} (hf : measurable f) (hA : is_measurable A) : measurable (λ a, f a A) :=
measurable.comp (prob.measurable_coe hA) hf
-- Rethink and rename these.
instance (β : Type u): measurable_space (set β) := ⊤
lemma prob_super [measurable_space α] [measurable_space β] {f: α → set β} (hf : measurable f) (μ : probability_measure β) :
measurable (λ x, μ (f x)) :=
begin
refine measurable.comp _ hf,
intros i a, fsplit,
end
lemma measurable_to_nnreal : measurable (ennreal.to_nnreal) := measurable_of_measurable_nnreal measurable_id
lemma measurable_to_nnreal_comp_of_measurable (f: α → ennreal) : (measurable f) → measurable (λ x, ennreal.to_nnreal (f x)) :=
assume h, measurable.comp measurable_to_nnreal h
lemma measurable_of_ne_top (f : α → ennreal) (h : ∀ x, (f x) ≠ ⊤) (hf : measurable(λ x, ennreal.to_nnreal (f x))): measurable (λ x, f x) :=
begin
have h₀ : ∀ x, ↑((f x).to_nnreal) = f x, assume x, rw coe_to_nnreal (h x),
conv{congr,funext, rw ←h₀,},
apply measurable.comp measurable_coe hf,
end
lemma prob.measurable_of_measurable_coe (f : β → probability_measure α)
(h : ∀(s : set α) (hs : is_measurable s), measurable (λb, f b s)) :
measurable f :=
begin
rw prob.measurable_coe_iff_measurable_to_measure,
apply measurable_of_measurable_coe,
intros s hs,
conv{congr,funext,rw function.comp_apply,},
refine measurable_of_ne_top _ _ _,
intro x, refine probability_measure.to_measure_ne_top _ _,
exact h _ hs,
end
@[simp] lemma bind_apply {m : probability_measure α} {f : α → probability_measure β} {s : set β}
(hs : is_measurable s) (hf : measurable f) : (bind m f : probability_measure β) s = (integral m.to_measure (λa, f a s)).to_nnreal :=
begin
rw _root_.bind, rw _root_.join_apply hs, congr,
have h : (_root_.map f m).to_measure = map f m.to_measure,{
apply measure.ext, intros s hs, rw measure_theory.measure.map_apply hf hs,
rw _root_.map, rw dif_pos hf,unfold_coes, simp, apply measure_theory.measure.map_apply hf hs,
},
rw h, rw integral_map _ hf,
refine measurable.comp measurable_coe _,
exact prob.measurable_coe hs,
end
attribute [irreducible] pure map join bind
infixl ` >>=ₚ `:55 := _root_.bind
infixl ` <$>ₚ `:55 := _root_.map
notation `doₚ` binders ` ←ₚ ` m ` ; ` t:(scoped p, m >>=ₚ p) := t
notation `retₚ` := _root_.dirac
lemma ret_to_measure {γ : Type u} [measurable_space γ] : ∀ (x:γ), (retₚ x).to_measure = measure.dirac x := assume x, rfl
def prod.prob_measure [measurable_space α][measurable_space β] (μ : probability_measure α) (ν : probability_measure β) : probability_measure (α × β) :=
doₚ x ←ₚ μ ;
doₚ y ←ₚ ν ;
retₚ (x, y)
infixl ` ⊗ₚ `:55 := prod.prob_measure
/- TODO(Kody) :
1) shorten these proofs by using the ones proven for measures.
2) Make a simp lemma to get rid of the conv block.
-/
lemma prob_inl_measurable_dirac [measurable_space α][measurable_space β] : ∀ y : β, measurable (λ (x : α), retₚ (x, y)) := assume y,
begin
rw prob.measurable_coe_iff_measurable_to_measure,
apply measurable_of_measurable_coe, intros s hs,
conv{congr,funext,rw function.comp_apply, rw _root_.dirac,},
simp [hs,mem_prod_eq,lattice.supr_eq_if],
apply measurable_const.if _ measurable_const,
apply measurable.preimage _ hs,
apply measurable.prod, dsimp, exact measurable_id,
dsimp, exact measurable_const,
end
lemma prob_inr_measurable_dirac [measurable_space β][measurable_space α] : ∀ x : α, measurable (λ (y : β), retₚ (x, y)) := assume x, begin
rw prob.measurable_coe_iff_measurable_to_measure,
apply measurable_of_measurable_coe, intros s hs,
conv{congr,funext,rw function.comp_apply, rw _root_.dirac,},
simp [hs,mem_prod_eq,lattice.supr_eq_if],
apply measurable_const.if _ measurable_const,
apply measurable.preimage _ hs,
apply measurable.prod, dsimp, exact measurable_const,
dsimp, exact measurable_id,
end
/- TODO(Kody): Duplication of proofs.
Why do I need to manually `change` the goal?
-/
@[simp] lemma prob.dirac_apply {A : set α} {B : set β} (hA : is_measurable A) (hB : is_measurable B) (a : α) (b : β) :
(retₚ (a,b) : measure (α × β)) (A.prod B) = ((retₚ a : measure α) A) * ((retₚ b : measure β) B) :=
begin
rw _root_.dirac, rw _root_.dirac,rw _root_.dirac,
unfold_coes, simp,
change ((( measure.dirac (a,b) : measure (α × β)) (A.prod B)) = (measure.dirac a : measure α) A * (measure.dirac b : measure β) B),
rw [dirac_apply, dirac_apply, dirac_apply, mem_prod_eq],
dsimp,
by_cases Ha: (a ∈ A); by_cases Hb: (b ∈ B),
repeat {simp [Ha, Hb]},
repeat {assumption},
exact is_measurable_set_prod hA hB,
end
@[simp] lemma prob.dirac_apply' {A : set α} {B : set β} (hA : is_measurable A) (hB : is_measurable B) (a : α) (b : β) :
((retₚ(a,b)).to_measure : measure (α × β)) (A.prod B) = (((retₚ a).to_measure : measure α) A) * (((retₚ b).to_measure : measure β) B)
:=
begin
rw _root_.dirac,rw _root_.dirac,rw _root_.dirac,
unfold_coes, simp,
change ((( measure.dirac (a,b) : measure (α × β)) (A.prod B)) = (measure.dirac a : measure α) A * (measure.dirac b : measure β) B),
rw [dirac_apply, dirac_apply, dirac_apply, mem_prod_eq],
dsimp,
by_cases Ha: (a ∈ A); by_cases Hb: (b ∈ B),
repeat {simp [Ha, Hb]},
repeat {assumption},
exact is_measurable_set_prod hA hB,
end
end giry_monad
section cond_prob
noncomputable def cond_prob {α : Type*} [measurable_space α] (p : probability_measure α) (a b : set α) := p(a ∩ b)/p(b)
notation `ℙ^`:95 p `[[`:95 a ` | `:95 b `]]`:0 := cond_prob p a b
parameters {α : Type*} [measurable_space α] (p : probability_measure α)
lemma cond_prob_rw
(a b : set α) (h₁ : p(b) ≠ 0):
p(a ∩ b) = ℙ^p [[ a | b ]] * p(b) :=
begin
unfold cond_prob,
rw [nnreal.div_def,mul_assoc],
have g₁ : (1 : ennreal) < ⊤,
{
rw lattice.lt_top_iff_ne_top,
apply ennreal.one_ne_top,
},
have g₂ : ∀ a, (p(a) ≠ 0) → (p(a))⁻¹ * p(a) = 1,
{
intros a k,
rw mul_comm,
apply nnreal.mul_inv_cancel, exact k,
},
rw g₂ b h₁, simp,
end
/-- Bayes theorem for two sets. -/
theorem cond_prob_swap
{a b : set α} (h₁ : p a ≠ 0) (h₂ : p b ≠ 0) :
ℙ^p [[ b | a ]] * p(a) = ℙ^p [[ a | b ]] * p(b) :=
begin
unfold cond_prob,
rw [nnreal.div_def,mul_assoc],
have g₁ : (1 : ennreal) < ⊤,
{
rw lattice.lt_top_iff_ne_top,
apply ennreal.one_ne_top,
},
have g₂ : ∀ a, (p(a) ≠ 0) → (p(a))⁻¹ * p(a) = 1,
{
intros a k,
rw mul_comm,
apply nnreal.mul_inv_cancel, exact k,
},
rw [g₂ a,nnreal.div_def,mul_assoc,g₂ b, mul_one],
symmetry, rw [mul_one,set.inter_comm],
assumption, assumption,
end
end cond_prob
section giry_prod
end giry_prod |
3688ddae895657f90d1aba0f042abdacb5628022 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/algebra/order/absolute_value.lean | e35a9ba25f8b6038af723f530b50c481437e46d0 | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 8,983 | lean | /-
Copyright (c) 2021 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Anne Baanen
-/
import algebra.order.field
/-!
# Absolute values
This file defines a bundled type of absolute values `absolute_value R S`.
## Main definitions
* `absolute_value R S` is the type of absolute values on `R` mapping to `S`.
* `absolute_value.abs` is the "standard" absolute value on `S`, mapping negative `x` to `-x`.
* `absolute_value.to_monoid_with_zero_hom`: absolute values mapping to a
linear ordered field preserve `0`, `*` and `1`
* `is_absolute_value`: a type class stating that `f : β → α` satisfies the axioms of an abs val
-/
/-- `absolute_value R S` is the type of absolute values on `R` mapping to `S`:
the maps that preserve `*`, are nonnegative, positive definite and satisfy the triangle equality. -/
structure absolute_value (R S : Type*) [semiring R] [ordered_semiring S]
extends mul_hom R S :=
(nonneg' : ∀ x, 0 ≤ to_fun x)
(eq_zero' : ∀ x, to_fun x = 0 ↔ x = 0)
(add_le' : ∀ x y, to_fun (x + y) ≤ to_fun x + to_fun y)
namespace absolute_value
attribute [nolint doc_blame] absolute_value.to_mul_hom
initialize_simps_projections absolute_value (to_mul_hom_to_fun → apply)
section ordered_semiring
variables {R S : Type*} [semiring R] [ordered_semiring S] (abv : absolute_value R S)
instance : has_coe_to_fun (absolute_value R S) (λ f, R → S) := ⟨λ f, f.to_fun⟩
@[simp] lemma coe_to_mul_hom : ⇑abv.to_mul_hom = abv := rfl
protected theorem nonneg (x : R) : 0 ≤ abv x := abv.nonneg' x
@[simp] protected theorem eq_zero {x : R} : abv x = 0 ↔ x = 0 := abv.eq_zero' x
protected theorem add_le (x y : R) : abv (x + y) ≤ abv x + abv y := abv.add_le' x y
@[simp] protected theorem map_mul (x y : R) : abv (x * y) = abv x * abv y := abv.map_mul' x y
protected theorem pos {x : R} (hx : x ≠ 0) : 0 < abv x :=
lt_of_le_of_ne (abv.nonneg x) (ne.symm $ mt abv.eq_zero.mp hx)
@[simp] protected theorem pos_iff {x : R} : 0 < abv x ↔ x ≠ 0 :=
⟨λ h₁, mt abv.eq_zero.mpr h₁.ne', abv.pos⟩
protected theorem ne_zero {x : R} (hx : x ≠ 0) : abv x ≠ 0 := (abv.pos hx).ne'
@[simp] protected theorem map_zero : abv 0 = 0 := abv.eq_zero.2 rfl
end ordered_semiring
section ordered_ring
variables {R S : Type*} [ring R] [ordered_ring S] (abv : absolute_value R S)
protected lemma sub_le (a b c : R) : abv (a - c) ≤ abv (a - b) + abv (b - c) :=
by simpa [sub_eq_add_neg, add_assoc] using abv.add_le (a - b) (b - c)
protected lemma le_sub (a b : R) : abv a - abv b ≤ abv (a - b) :=
sub_le_iff_le_add.2 $ by simpa using abv.add_le (a - b) b
@[simp] lemma map_sub_eq_zero_iff (a b : R) : abv (a - b) = 0 ↔ a = b :=
abv.eq_zero.trans sub_eq_zero
end ordered_ring
section linear_ordered_ring
variables {R S : Type*} [semiring R] [linear_ordered_ring S] (abv : absolute_value R S)
/-- `absolute_value.abs` is `abs` as a bundled `absolute_value`. -/
@[simps]
protected def abs : absolute_value S S :=
{ to_fun := abs,
nonneg' := abs_nonneg,
eq_zero' := λ _, abs_eq_zero,
add_le' := abs_add,
map_mul' := abs_mul }
instance : inhabited (absolute_value S S) := ⟨absolute_value.abs⟩
variables [nontrivial R]
@[simp] protected theorem map_one : abv 1 = 1 :=
(mul_right_inj' $ abv.ne_zero one_ne_zero).1 $
by rw [← abv.map_mul, mul_one, mul_one]
/-- Absolute values from a nontrivial `R` to a linear ordered ring preserve `*`, `0` and `1`. -/
def to_monoid_with_zero_hom : R →*₀ S :=
{ to_fun := abv,
map_zero' := abv.map_zero,
map_one' := abv.map_one,
.. abv }
@[simp] lemma coe_to_monoid_with_zero_hom : ⇑abv.to_monoid_with_zero_hom = abv := rfl
/-- Absolute values from a nontrivial `R` to a linear ordered ring preserve `*` and `1`. -/
def to_monoid_hom : monoid_hom R S :=
{ to_fun := abv,
map_one' := abv.map_one,
.. abv }
@[simp] lemma coe_to_monoid_hom : ⇑abv.to_monoid_hom = abv := rfl
@[simp] protected lemma map_pow (a : R) (n : ℕ) : abv (a ^ n) = abv a ^ n :=
abv.to_monoid_hom.map_pow a n
end linear_ordered_ring
section linear_ordered_comm_ring
section ring
variables {R S : Type*} [ring R] [linear_ordered_comm_ring S] (abv : absolute_value R S)
@[simp] protected theorem map_neg (a : R) : abv (-a) = abv a :=
begin
by_cases ha : a = 0, { simp [ha] },
refine (mul_self_eq_mul_self_iff.mp
(by rw [← abv.map_mul, neg_mul_neg, abv.map_mul])).resolve_right _,
exact ((neg_lt_zero.mpr (abv.pos ha)).trans (abv.pos (neg_ne_zero.mpr ha))).ne'
end
protected theorem map_sub (a b : R) : abv (a - b) = abv (b - a) :=
by rw [← neg_sub, abv.map_neg]
lemma abs_abv_sub_le_abv_sub (a b : R) :
abs (abv a - abv b) ≤ abv (a - b) :=
abs_sub_le_iff.2 ⟨abv.le_sub _ _, by rw abv.map_sub; apply abv.le_sub⟩
end ring
end linear_ordered_comm_ring
section linear_ordered_field
section field
variables {R S : Type*} [division_ring R] [linear_ordered_field S] (abv : absolute_value R S)
@[simp] protected theorem map_inv (a : R) : abv a⁻¹ = (abv a)⁻¹ :=
abv.to_monoid_with_zero_hom.map_inv a
@[simp] protected theorem map_div (a b : R) : abv (a / b) = abv a / abv b :=
abv.to_monoid_with_zero_hom.map_div a b
end field
end linear_ordered_field
end absolute_value
section is_absolute_value
/-- A function `f` is an absolute value if it is nonnegative, zero only at 0, additive, and
multiplicative.
See also the type `absolute_value` which represents a bundled version of absolute values.
-/
class is_absolute_value {S} [ordered_semiring S]
{R} [semiring R] (f : R → S) : Prop :=
(abv_nonneg [] : ∀ x, 0 ≤ f x)
(abv_eq_zero [] : ∀ {x}, f x = 0 ↔ x = 0)
(abv_add [] : ∀ x y, f (x + y) ≤ f x + f y)
(abv_mul [] : ∀ x y, f (x * y) = f x * f y)
namespace is_absolute_value
section ordered_semiring
variables {S : Type*} [ordered_semiring S]
variables {R : Type*} [semiring R] (abv : R → S) [is_absolute_value abv]
/-- A bundled absolute value is an absolute value. -/
instance absolute_value.is_absolute_value
(abv : absolute_value R S) : is_absolute_value abv :=
{ abv_nonneg := abv.nonneg,
abv_eq_zero := λ _, abv.eq_zero,
abv_add := abv.add_le,
abv_mul := abv.map_mul }
/-- Convert an unbundled `is_absolute_value` to a bundled `absolute_value`. -/
@[simps]
def to_absolute_value : absolute_value R S :=
{ to_fun := abv,
add_le' := abv_add abv,
eq_zero' := λ _, abv_eq_zero abv,
nonneg' := abv_nonneg abv,
map_mul' := abv_mul abv }
theorem abv_zero : abv 0 = 0 := (abv_eq_zero abv).2 rfl
theorem abv_pos {a : R} : 0 < abv a ↔ a ≠ 0 :=
by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [abv_eq_zero abv, abv_nonneg abv]
end ordered_semiring
section linear_ordered_ring
variables {S : Type*} [linear_ordered_ring S]
variables {R : Type*} [semiring R] (abv : R → S) [is_absolute_value abv]
instance abs_is_absolute_value {S} [linear_ordered_ring S] :
is_absolute_value (abs : S → S) :=
{ abv_nonneg := abs_nonneg,
abv_eq_zero := λ _, abs_eq_zero,
abv_add := abs_add,
abv_mul := abs_mul }
end linear_ordered_ring
section linear_ordered_comm_ring
variables {S : Type*} [linear_ordered_comm_ring S]
section semiring
variables {R : Type*} [semiring R] (abv : R → S) [is_absolute_value abv]
theorem abv_one [nontrivial R] : abv 1 = 1 :=
(mul_right_inj' $ mt (abv_eq_zero abv).1 one_ne_zero).1 $
by rw [← abv_mul abv, mul_one, mul_one]
/-- `abv` as a `monoid_with_zero_hom`. -/
def abv_hom [nontrivial R] : R →*₀ S := ⟨abv, abv_zero abv, abv_one abv, abv_mul abv⟩
lemma abv_pow [nontrivial R] (abv : R → S) [is_absolute_value abv]
(a : R) (n : ℕ) : abv (a ^ n) = abv a ^ n :=
(abv_hom abv).to_monoid_hom.map_pow a n
end semiring
end linear_ordered_comm_ring
section linear_ordered_field
variables {S : Type*} [linear_ordered_field S]
section ring
variables {R : Type*} [ring R] (abv : R → S) [is_absolute_value abv]
theorem abv_neg (a : R) : abv (-a) = abv a :=
by rw [← mul_self_inj_of_nonneg (abv_nonneg abv _) (abv_nonneg abv _),
← abv_mul abv, ← abv_mul abv]; simp
theorem abv_sub (a b : R) : abv (a - b) = abv (b - a) :=
by rw [← neg_sub, abv_neg abv]
lemma abv_sub_le (a b c : R) : abv (a - c) ≤ abv (a - b) + abv (b - c) :=
by simpa [sub_eq_add_neg, add_assoc] using abv_add abv (a - b) (b - c)
lemma sub_abv_le_abv_sub (a b : R) : abv a - abv b ≤ abv (a - b) :=
sub_le_iff_le_add.2 $ by simpa using abv_add abv (a - b) b
lemma abs_abv_sub_le_abv_sub (a b : R) :
abs (abv a - abv b) ≤ abv (a - b) :=
abs_sub_le_iff.2 ⟨sub_abv_le_abv_sub abv _ _,
by rw abv_sub abv; apply sub_abv_le_abv_sub abv⟩
end ring
section field
variables {R : Type*} [division_ring R] (abv : R → S) [is_absolute_value abv]
theorem abv_inv (a : R) : abv a⁻¹ = (abv a)⁻¹ :=
(abv_hom abv).map_inv a
theorem abv_div (a b : R) : abv (a / b) = abv a / abv b :=
(abv_hom abv).map_div a b
end field
end linear_ordered_field
end is_absolute_value
end is_absolute_value
|
b256956409363585b018c747e10799e55c30e74a | 3446e92e64a5de7ed1f2109cfb024f83cd904c34 | /src/game/world3/level10.lean | 6eaa1dd7509ca8c799a24a606e65bb1bea843089 | [] | 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 | 645 | lean | import game.world3.level9 -- hide
import game.world2.level7 -- succ ne zero -- hide
import game.world2.level13 -- add_left_eq_zero -- hide
namespace mynat -- hide
/-
# Multiplication World
## Level 10: `eq_zero_or_eq_zero_of_mul_eq_zero`
A variant on the previous level.
-/
/- Theorem
If $a * b = 0$, then at least one of $a$ or $b$ is equal to zero.
-/
theorem eq_zero_or_eq_zero_of_mul_eq_zero ⦃a b : mynat⦄ (h : a * b = 0) : a = 0 ∨ b = 0 :=
begin [less_leaky]
cases a with d,
left, refl,
cases b with e he,
right, refl,
exfalso,
rw mul_succ at h,
rw add_succ at h,
exact succ_ne_zero h,
end
end mynat -- hide
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.